From be3ec5302d956ad69c22c83fd5a16d265bdf0cb7 Mon Sep 17 00:00:00 2001 From: Darknode-Official Date: Wed, 25 Nov 2026 16:45:33 -0800 Subject: [PATCH] feat(deadlines): certificate, CRA Article 14 and BOD 22-01 deadline clocks One deadline model, stored per workspace in the monitor Durable Object (dl:, cra:, dlSettings), with the pure rules in public/js/core/deadlines.js shared by the Worker and the Deck. - cert-expiry: from the cert monitor (Free watch included), due when the certificate expires; closes itself when the monitor no longer sees it. The monitor's first alert is its created alert and the 7-day re-alert is replaced by one reminder when a quarter of the time is left. - cra-exploited: only with the CRA opt-in, from Article 14(2) applying (11 Sept 2026), for a CISA KEV match in an asset marked as shipped in a product: early warning 24h and notification 72h after becoming aware (starts at the alert, user can correct it), final report 14 days after the fix is marked available. - kev-due: only with the BOD 22-01 opt-in; the KEV dueDate, end of day UTC. Alerts go to the source monitor's channels when a clock starts and when a quarter of its time is left. CRA alert emails have their own 20 a day limit instead of the 5 a day; certificate and BOD reminders share the 5. The opt-ins need Pro on the server (402 below it). Deck: Deadlines page (steps, sources, mark done or dismiss with a reason, case editor, Copy early-warning facts) and an Overview block. Docs FAQ, changelog, Privacy and Terms updated within TOS 2026-11-25. --- public/js/auth.js | 1 + public/js/core/deadlines.js | 485 ++++++++++++++++++++++++++++++++ public/js/core/entitlements.js | 5 +- public/js/deck-ui.js | 16 +- public/js/deck/deadlines.js | 347 +++++++++++++++++++++++ public/js/deck/routes.js | 2 +- public/js/docs.js | 6 +- public/js/landing.js | 1 + public/js/legal.js | 2 + public/js/ui/explain.js | 2 + test/worker/deadlines.test.mjs | 400 ++++++++++++++++++++++++++ test/worker/monitor-do.test.mjs | 10 +- worker/alert-email.js | 48 +++- worker/checks.js | 2 +- worker/monitor.js | 223 +++++++++++++-- 15 files changed, 1513 insertions(+), 37 deletions(-) create mode 100644 public/js/core/deadlines.js create mode 100644 public/js/deck/deadlines.js create mode 100644 test/worker/deadlines.test.mjs diff --git a/public/js/auth.js b/public/js/auth.js index a7348bd4..053b36ab 100644 --- a/public/js/auth.js +++ b/public/js/auth.js @@ -3013,6 +3013,7 @@ onAuthStateChanged(auth, async (user) => { What changed (November 25, 2026)
  • 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).
  • +
  • Deadlines: Darknode can track certificate expiry and, if you opt in, Cyber Resilience Act and CISA BOD 22-01 clocks. They are reminders only: Darknode does not decide whether a rule applies to you and does not submit anything for you (Sections 3 and 14).
` : ""}
${TOS_HTML} diff --git a/public/js/core/deadlines.js b/public/js/core/deadlines.js new file mode 100644 index 00000000..605ee437 --- /dev/null +++ b/public/js/core/deadlines.js @@ -0,0 +1,485 @@ +// Copyright (c) 2026 Darknode-Official. All rights reserved. See LICENSE. +// +// Deadlines: one model for the clocks a security finding can start. PURE: no DOM, no network, +// no storage. The MonitorDO (worker/monitor.js) creates, stores and alerts them per workspace; +// the Deck (js/deck/deadlines.js) shows them. Both import this file, so the clock maths the +// server alerts on is the same the Deck counts down with. +// +// A deadline: { id, kind, clock, group, title, subject:{type,value,assets}, startedAt, dueAt, +// status: open|done|dismissed, reason, closedAt, closedBy, monitorId, createdAt, +// alerts:{created, quarter, holdUntil} } +// dueAt null = a clock that has not started yet (the CRA final report, until the fix is out). +// Steps and the source link come from the kind (stepsOf, sourceOf), so a stored record stays small. +// +// Kinds: +// cra-exploited Cyber Resilience Act Article 14(2): a known-exploited CVE (CISA KEV) in an asset +// the workspace marked as shipped in a product. Three linked clocks: early warning +// 24 h and vulnerability notification 72 h after becoming aware, final report 14 +// days after a fix or mitigation is available. Only with the workspace's CRA +// opt-in, and not before Article 14 applies (11 September 2026). +// cert-expiry a watched certificate's expiry date (the cert-expiry monitor, the Free watch too). +// kev-due CISA BOD 22-01: the KEV catalogue's due date for a matched CVE. Only with the +// workspace's BOD 22-01 opt-in. +// Darknode tracks the clocks and prepares facts. It does not decide whether a law applies and +// does not submit anything. + +export const HOUR = 3600000; +export const DAY = 24 * HOUR; +export const KINDS = ["cra-exploited", "cert-expiry", "kev-due"]; +export const MAX_SHIPPED = 200; +export const CLOSED = ["done", "dismissed"]; + +export const CRA = { + appliesFrom: Date.UTC(2026, 8, 11), // Article 71(2): Article 14 applies from 11 September 2026 + earlyMs: 24 * HOUR, + notifyMs: 72 * HOUR, + finalMs: 14 * DAY, + source: { label: "Regulation (EU) 2024/2847 (Cyber Resilience Act), Article 14(2)", url: "https://eur-lex.europa.eu/eli/reg/2024/2847/oj/eng" }, + applies: "Article 14 applies from 11 September 2026 (Article 71(2)).", + where: "Notifications go to the CSIRT designated as coordinator and to ENISA at the same time, through ENISA's single reporting platform (Article 14(1) and (7)).", + quote: { + early: "an early warning notification of an actively exploited vulnerability, without undue delay and in any event within 24 hours of the manufacturer becoming aware of it, indicating, where applicable, the Member States on the territory of which the manufacturer is aware that their product with digital elements has been made available", + notify: "a vulnerability notification, without undue delay and in any event within 72 hours of the manufacturer becoming aware of the actively exploited vulnerability", + final: "a final report, no later than 14 days after a corrective or mitigating measure is available", + }, +}; +export const BOD2201 = { + source: { label: "CISA Binding Operational Directive 22-01", url: "https://www.cisa.gov/news-events/directives/bod-22-01-reducing-significant-risk-known-exploited-vulnerabilities" }, +}; +export const KEV_URL = "https://www.cisa.gov/known-exploited-vulnerabilities-catalog"; +export const kevLink = (cve) => KEV_URL + "?search_api_fulltext=" + encodeURIComponent(cve); +export const nvdLink = (cve) => "https://nvd.nist.gov/vuln/detail/" + encodeURIComponent(cve); +export const DISCLAIMER = "Darknode does not decide whether the Cyber Resilience Act or BOD 22-01 applies to you, and it does not submit anything. It tracks the clocks and prepares the facts; you decide and file."; + +// The 27 EU Member States (EU country codes: Greece is EL; GR is accepted too). +export const EU_STATES = { AT: "Austria", BE: "Belgium", BG: "Bulgaria", HR: "Croatia", CY: "Cyprus", CZ: "Czechia", DK: "Denmark", EE: "Estonia", FI: "Finland", FR: "France", DE: "Germany", EL: "Greece", HU: "Hungary", IE: "Ireland", IT: "Italy", LV: "Latvia", LT: "Lithuania", LU: "Luxembourg", MT: "Malta", NL: "Netherlands", PL: "Poland", PT: "Portugal", RO: "Romania", SK: "Slovakia", SI: "Slovenia", ES: "Spain", SE: "Sweden" }; + +const own = (o, k) => Object.prototype.hasOwnProperty.call(o, k); +const str = (v) => (v == null ? "" : String(v)); +const clip = (v, n) => str(v).replace(/\s+/g, " ").trim().slice(0, n); +const fin = (n) => typeof n === "number" && Number.isFinite(n); +const CVE_RE = /CVE-\d{4}-\d{4,7}/gi; +const isCve = (s) => /^CVE-\d{4}-\d{4,7}$/.test(s); + +// "2026-11-25 14:05 UTC" +export const utc = (ms) => (fin(ms) ? new Date(ms).toISOString().slice(0, 16).replace("T", " ") + " UTC" : ""); + +// ---- clock maths ------------------------------------------------------------------------------ + +// The three CRA clocks of a case { awareAt, fixAt }. +export function craClocks(c = {}) { + const aware = fin(c.awareAt) ? c.awareAt : null, fix = fin(c.fixAt) ? c.fixAt : null; + return { + early: aware == null ? null : aware + CRA.earlyMs, + notify: aware == null ? null : aware + CRA.notifyMs, + final: fix == null ? null : fix + CRA.finalMs, + }; +} + +// A KEV due date ("2026-12-01") ends at the end of that day, UTC. +export function kevDueAt(dueDate) { + const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(str(dueDate).trim()); + if (!m) return null; + const t = Date.UTC(+m[1], +m[2] - 1, +m[3], 23, 59, 59); + return Number.isFinite(t) ? t : null; +} + +export const timeLeft = (d, now) => (d && fin(d.dueAt) ? d.dueAt - now : null); + +// When 25% of the deadline's time is left. null for a clock that has not started, or one +// that was already due when it started. +export function quarterAt(d) { + if (!d || !fin(d.dueAt) || !fin(d.startedAt) || d.dueAt <= d.startedAt) return null; + return d.startedAt + Math.round((d.dueAt - d.startedAt) * 0.75); +} + +// open + no dueAt = waiting; open past dueAt = overdue. +export function stateOf(d, now) { + if (!d) return ""; + if (d.status === "done" || d.status === "dismissed") return d.status; + if (!fin(d.dueAt)) return "waiting"; + return now >= d.dueAt ? "overdue" : "open"; +} + +// "2d 4h left", "5h 12m left", "40m left", "overdue by 3h 5m" +export function fmtLeft(ms) { + if (!fin(ms)) return ""; + const a = Math.abs(ms), d = Math.floor(a / DAY), h = Math.floor((a % DAY) / HOUR), m = Math.floor((a % HOUR) / 60000); + const s = d ? d + "d " + h + "h" : h ? h + "h " + m + "m" : Math.max(m, ms < 0 ? 1 : 0) + "m"; + return ms < 0 ? "overdue by " + s : s + " left"; +} + +// Open deadlines first, soonest due first; waiting clocks after them; closed ones last, newest first. +export function sortDeadlines(list, now) { + const rank = (d) => { const s = stateOf(d, now); return s === "overdue" || s === "open" ? 0 : s === "waiting" ? 1 : 2; }; + return [...(list || [])].sort((a, b) => rank(a) - rank(b) + || (rank(a) === 0 ? a.dueAt - b.dueAt : rank(a) === 2 ? (b.closedAt || 0) - (a.closedAt || 0) : (a.createdAt || 0) - (b.createdAt || 0)) + || str(a.id).localeCompare(str(b.id))); +} + +// ---- opt-ins -------------------------------------------------------------------------------- + +// The workspace's deadline settings. Nothing is assumed: both opt-ins default to off. +// shipped: the assets marked "shipped in a product" [{ id, type, name }]. +export function normSettings(s) { + const x = s && typeof s === "object" ? s : {}; + const shipped = [], seen = new Set(); + for (const a of Array.isArray(x.shipped) ? x.shipped : []) { + if (!a || typeof a !== "object") continue; + const name = clip(a.name, 120), id = clip(a.id, 128), type = clip(a.type, 32).toUpperCase(); + if (!name) continue; + const k = id || type + "|" + name.toLowerCase(); + if (seen.has(k)) continue; + seen.add(k); + shipped.push({ id, type, name }); + if (shipped.length >= MAX_SHIPPED) break; + } + return { cra: x.cra === true, bod2201: x.bod2201 === true, shipped }; +} + +// A settings write. `free`: the caller's plan is below Pro, so neither opt-in can be turned on +// (CRA and BOD clocks come from the known-exploited CVE monitor, which is a Pro monitor). +// -> { settings } | { error, plan? } +export function checkSettings(input, { free = false } = {}) { + if (!input || typeof input !== "object") return { error: "settings required" }; + if (input.shipped != null && !Array.isArray(input.shipped)) return { error: "shipped must be a list" }; + if (Array.isArray(input.shipped) && input.shipped.length > MAX_SHIPPED) return { error: "At most " + MAX_SHIPPED + " assets can be marked as shipped in a product." }; + const settings = normSettings(input); + if (free && (settings.cra || settings.bod2201)) return { error: "Cyber Resilience Act and BOD 22-01 clocks come from the known-exploited CVE monitor, which is part of the Pro plan. Request an upgrade under Plans.", plan: true }; + return { settings }; +} + +// CRA clocks start only with the opt-in, and not before Article 14 applies. +export const craApplies = (settings, at) => !!(settings && settings.cra === true) && fin(at) && at >= CRA.appliesFrom; +export const bodApplies = (settings) => !!(settings && settings.bod2201 === true); + +// "DE, fr, Greece" -> { codes: ["DE","FR","EL"], bad: [] } +export function parseMemberStates(v) { + const parts = Array.isArray(v) ? v : str(v).split(/[,;\n]+/); + const byName = new Map(Object.entries(EU_STATES).map(([c, n]) => [n.toLowerCase(), c])); + const codes = [], bad = []; + for (const p of parts) { + const t = clip(p, 40); + if (!t) continue; + const up = t.toUpperCase(), c = up === "GR" ? "EL" : own(EU_STATES, up) ? up : byName.get(t.toLowerCase()) || ""; + if (!c) { bad.push(t); continue; } + if (!codes.includes(c)) codes.push(c); + } + return { codes, bad }; +} +export const stateNames = (codes) => (codes || []).filter((c) => own(EU_STATES, c)).map((c) => EU_STATES[c] + " (" + c + ")"); + +// ---- which assets a CVE touches ---------------------------------------------------------------- + +function cvesOf(e) { + const out = new Set(), d = (e && e.data) || {}; + const add = (v) => { const m = str(v).match(CVE_RE); if (m) for (const c of m) out.add(c.toUpperCase()); }; + add(e && e.name); add(d.cve); + if (Array.isArray(d.cves)) for (const c of d.cves) add(c); + add(d.evidence); + return out; +} + +// The shipped assets a CVE is in. inventory: the workspace graph { entities, relationships } +// (the monitor's own writes already removed). An asset counts when it is the entity that names +// the CVE, is linked to one by a relationship, or is listed in a finding's affected assets. +// A shipped entry matches by graph id, or by name (and type, when both sides have one). +// -> [{ id, type, name }] +export function shippedMatches(cve, inventory, shipped) { + const want = str(cve).toUpperCase().trim(); + const list = Array.isArray(shipped) ? shipped : []; + if (!isCve(want) || !list.length) return []; + const ents = (inventory && Array.isArray(inventory.entities)) ? inventory.entities.filter((e) => e && typeof e === "object") : []; + const rels = (inventory && Array.isArray(inventory.relationships)) ? inventory.relationships : []; + const byId = new Map(ents.map((e) => [e.id, e])); + const ids = new Set(), names = []; + const add = (e) => { if (!e) return; if (e.id) ids.add(e.id); if (e.name) names.push({ type: str(e.type).toUpperCase(), name: str(e.name).trim().toLowerCase() }); }; + const hits = ents.filter((e) => cvesOf(e).has(want)); + const hitIds = new Set(hits.map((e) => e.id).filter(Boolean)); + for (const e of hits) { + add(e); + for (const n of Array.isArray(e.data && e.data.assets) ? e.data.assets : []) if (str(n).trim()) names.push({ type: "", name: str(n).trim().toLowerCase() }); + } + for (const r of rels) { + if (!r) continue; + if (hitIds.has(r.fromId)) add(byId.get(r.toId)); + if (hitIds.has(r.toId)) add(byId.get(r.fromId)); + } + const out = []; + for (const s of list) { + const nm = str(s.name).trim().toLowerCase(), ty = str(s.type).toUpperCase(); + const hit = (s.id && ids.has(s.id)) || (nm && names.some((n) => n.name === nm && (!n.type || !ty || n.type === ty))); + if (hit && !out.includes(s)) out.push(s); + } + return out; +} + +// ---- building deadlines --------------------------------------------------------------------- + +const STEPS = { + early: [ + "Check that the vulnerable component is in the product you ship.", + "Note the Member States where the product is made available.", + "Submit the early warning on ENISA's single reporting platform. It reaches your coordinating CSIRT and ENISA.", + "Mark this clock done here, with the submission reference as the reason.", + ], + notify: [ + "Describe the product, the general nature of the exploit and of the vulnerability.", + "List the corrective or mitigating measures taken, and the ones users can take.", + "Say how sensitive you consider the information.", + "Submit the vulnerability notification on the same platform, unless the early warning already gave all of this.", + ], + final: [ + "Mark the fix or mitigation available here: the 14-day clock starts then.", + "Describe the vulnerability, its severity and impact.", + "Add what is known about any malicious actor exploiting it.", + "Give the details of the security update or other corrective measures.", + "Submit the final report on the same platform.", + ], +}; +const CRA_TITLE = { early: "CRA early warning", notify: "CRA vulnerability notification", final: "CRA final report" }; + +function base(o) { + return { id: o.id, kind: o.kind, clock: o.clock || "", group: o.group || "", title: o.title, subject: o.subject, startedAt: o.startedAt, dueAt: fin(o.dueAt) ? o.dueAt : null, status: "open", reason: "", closedAt: 0, closedBy: "", monitorId: o.monitorId || "", createdAt: o.at, alerts: o.alerts || {} }; +} + +// What to do for a deadline, in order. +export function stepsOf(d) { + const v = (d && d.subject && d.subject.value) || ""; + if (!d) return []; + if (d.kind === "cra-exploited") return STEPS[d.clock] || []; + if (d.kind === "cert-expiry") return ["Renew the certificate for " + v + ".", "Install it on every server, load balancer and CDN that serves " + v + ".", "Run the watch again: this closes by itself when the monitor sees the new certificate."]; + if (d.kind === "kev-due") return ["Remediate " + v + " on every affected system by the KEV due date, following the required action in the catalogue.", "Mark it done here once it is remediated, with the change or ticket reference."]; + return []; +} +// The rule a deadline comes from: { label, url, quote? }. +export function sourceOf(d) { + if (!d) return null; + if (d.kind === "cra-exploited") return { ...CRA.source, quote: CRA.quote[d.clock] || "" }; + if (d.kind === "kev-due") return { ...BOD2201.source, quote: "remediate each vulnerability according to the timelines set forth in the CISA-managed vulnerability catalog" }; + if (d.kind === "cert-expiry") return { label: "Certificate Transparency logs", url: "https://crt.sh/?q=" + encodeURIComponent((d.subject && d.subject.value) || "") }; + return null; +} + +// A new CRA case and its three clocks. `alertedAt`: when Darknode alerted; it is also the +// "became aware" time until the user corrects it. +export function craCase({ cve, assets, kevDateAdded, alertedAt, monitorId }) { + return { cve, assets: assets.map((a) => a.name), kevDateAdded: str(kevDateAdded), alertedAt, awareAt: alertedAt, fixAt: null, measures: "", memberStates: [], monitorId: monitorId || "" }; +} +export function craDeadlines(c, at) { + const k = craClocks(c), what = c.cve + " in " + (c.assets.slice(0, 3).join(", ") + (c.assets.length > 3 ? " and " + (c.assets.length - 3) + " more" : "")); + const subject = { type: "cve", value: c.cve, assets: c.assets.slice() }; + return ["early", "notify", "final"].map((clock) => base({ + id: "cra:" + c.cve + ":" + clock, kind: "cra-exploited", clock, group: "cra:" + c.cve, + title: CRA_TITLE[clock] + ": " + what, subject, startedAt: clock === "final" ? (fin(c.fixAt) ? c.fixAt : null) : c.awareAt, + dueAt: k[clock], monitorId: c.monitorId, at, + })); +} + +// Deadlines from one kev-epss run. events: the run's events (kind "kev" = a new or worsened +// match); findings: the run's findings (a KEV one carries cve, dueDate, dateAdded, kev:true). +// existing: deadlines by id; cases: CRA cases by CVE. Creates a CRA case only with the CRA +// opt-in, after Article 14 applies, for a CVE in an asset marked as shipped; a kev-due deadline +// only with the BOD 22-01 opt-in. Never re-creates one that exists, whatever its status. +// -> { add: deadline[], cases: case[] } +export function kevDeadlines({ events = [], findings = [], settings, inventory, existing = {}, cases = {}, monitorId = "", at }) { + const s = normSettings(settings), add = [], newCases = []; + const byKey = new Map((findings || []).map((f) => [f && f.key, f])); + const done = new Set(); + for (const ev of events || []) { + if (!ev || ev.kind !== "kev") continue; + const f = byKey.get(ev.key); + if (!f || f.kev !== true) continue; // an EPSS-only match is not known-exploited + const cve = str(f.cve).toUpperCase(); + if (!isCve(cve) || done.has(cve)) continue; + done.add(cve); + if (bodApplies(s) && !own(existing, "kev-due:" + cve)) { + const due = kevDueAt(f.dueDate); + if (due != null) add.push(base({ + id: "kev-due:" + cve, kind: "kev-due", title: "BOD 22-01: remediate " + cve, subject: { type: "cve", value: cve, assets: [] }, + startedAt: at, dueAt: due, monitorId, at, + })); + } + if (craApplies(s, at) && !own(cases, cve)) { + const assets = shippedMatches(cve, inventory, s.shipped); + if (!assets.length) continue; // not in anything marked as shipped + const c = craCase({ cve, assets, kevDateAdded: f.dateAdded, alertedAt: at, monitorId }); + newCases.push(c); + for (const d of craDeadlines(c, at)) if (!own(existing, d.id)) add.push(d); + } + } + return { add, cases: newCases }; +} + +// Deadlines from one cert-expiry run. findings: the run's findings (key "cert:", domain, +// notAfter). firstSeen: finding key -> when the monitor first saw it; alerted: the keys this run +// alerted. A certificate's deadline is due when it expires. The monitor's own alert is the +// deadline's "created" alert (never a second email). An open deadline of this monitor closes as +// done when the monitor no longer sees that certificate expiring. +// -> { add: deadline[], close: [{ id, status, reason }] } +export function certDeadlines({ findings = [], existing = {}, monitorId = "", firstSeen = {}, alerted = new Set(), watched = null, at }) { + const add = [], close = [], live = new Set(); + for (const f of findings || []) { + if (!f || !str(f.key).startsWith("cert:") || !f.domain) continue; + const due = Date.parse(f.notAfter); + if (!Number.isFinite(due)) continue; + const id = "cert:" + f.domain + ":" + new Date(due).toISOString().slice(0, 10); + live.add(id); + if (own(existing, id) || add.some((d) => d.id === id)) continue; + add.push(base({ + id, kind: "cert-expiry", title: "Certificate for " + f.domain + " expires", subject: { type: "domain", value: f.domain, assets: [] }, + startedAt: fin(firstSeen[f.key]) ? Math.min(firstSeen[f.key], at) : at, dueAt: due, monitorId, at, + alerts: { created: { at, via: "monitor", sent: alerted.has(f.key) } }, + })); + } + for (const d of Object.values(existing)) { + if (!d || d.kind !== "cert-expiry" || d.status !== "open" || d.monitorId !== monitorId || live.has(d.id)) continue; + const dom = d.subject && d.subject.value; + const gone = watched && dom && !watched.has(dom); + close.push({ id: d.id, status: "done", reason: gone ? "The domain is no longer in this watch." : "The monitor no longer sees this certificate expiring: it was renewed or replaced." }); + } + return { add, close }; +} + +// ---- edits ------------------------------------------------------------------------------------ + +// Close a deadline as done or dismissed. A reason is required (it is the record). +// -> { deadline } | { error } +export function closeDeadline(d, { status, reason, by = "", at }) { + if (!d) return { error: "not found" }; + if (!CLOSED.includes(status)) return { error: "status must be done or dismissed" }; + const why = clip(reason, 500); + if (!why) return { error: status === "done" ? "Say what was done (for example the submission reference)." : "Say why you are dismissing it." }; + return { deadline: { ...d, status, reason: why, closedAt: at, closedBy: str(by).slice(0, 128) } }; +} +export function reopenDeadline(d) { + if (!d) return { error: "not found" }; + return { deadline: { ...d, status: "open", reason: "", closedAt: 0, closedBy: "" } }; +} + +// Edit a CRA case: when you became aware, when a fix or mitigation became available (null = +// not yet), the measures known and the Member States. -> { case } | { error } +export function updateCase(c, patch = {}, now) { + if (!c) return { error: "not found" }; + const next = { ...c }; + const earliest = (fin(c.alertedAt) ? c.alertedAt : now) - 365 * DAY; + if (patch.awareAt !== undefined) { + const t = Number(patch.awareAt); + if (!Number.isFinite(t)) return { error: "Enter when you became aware as a date and time." }; + if (t > now + 60000) return { error: "When you became aware cannot be in the future." }; + if (t < earliest) return { error: "When you became aware must be within a year before Darknode's alert." }; + next.awareAt = t; + } + if (patch.fixAt !== undefined) { + if (patch.fixAt === null) next.fixAt = null; + else { + const t = Number(patch.fixAt); + if (!Number.isFinite(t)) return { error: "Enter when the fix or mitigation became available as a date and time." }; + if (t > now + 60000) return { error: "A fix cannot be marked available in the future." }; + if (t < earliest) return { error: "When the fix became available must be within a year before Darknode's alert." }; + next.fixAt = t; + } + } + if (patch.measures !== undefined) { + const m = str(patch.measures).trim(); + if (m.length > 2000) return { error: "Keep the measures under 2,000 characters." }; + next.measures = m; + } + if (patch.memberStates !== undefined) { + const p = parseMemberStates(patch.memberStates); + if (p.bad.length) return { error: "Not an EU Member State: " + p.bad.slice(0, 5).join(", ") + ". Use the country name or its two-letter code, such as DE or FR." }; + next.memberStates = p.codes; + } + return { case: next }; +} + +// Bring a case's three clocks in line with it. A clock's alerts already sent stay sent; the final +// clock's are reset when the fix is cleared, so marking it again announces the new clock. +// -> the changed deadlines +export function syncCaseClocks(c, existing = {}) { + const k = craClocks(c), out = []; + for (const clock of ["early", "notify", "final"]) { + const d = existing["cra:" + c.cve + ":" + clock]; + if (!d) continue; + const startedAt = clock === "final" ? (fin(c.fixAt) ? c.fixAt : null) : c.awareAt; + if (d.startedAt === startedAt && d.dueAt === k[clock]) continue; + out.push({ ...d, startedAt, dueAt: k[clock], alerts: clock === "final" && k.final == null ? {} : d.alerts || {} }); + } + return out; +} + +// ---- alert schedule --------------------------------------------------------------------------- + +// What to send now: a "created" alert once a clock starts (a cert deadline's is the monitor's own +// alert, recorded at creation), and a "quarter" alert when 25% of the time is left. A quarter +// alert that falls due together with the created one is folded into it; one whose deadline +// already passed is skipped (the Deck shows it overdue). -> [{ id, stage: created|quarter|skip }] +export function dueAlerts(list, now) { + const out = []; + for (const d of list || []) { + if (!d || d.status !== "open" || !fin(d.dueAt)) continue; + const a = d.alerts || {}, q = quarterAt(d); + if (fin(a.holdUntil) && now < a.holdUntil) continue; // held until the monitor's quiet hours end + if (!a.created) { out.push({ id: d.id, stage: "created" }); continue; } + if (a.quarter) continue; + if (q == null || now >= d.dueAt) { out.push({ id: d.id, stage: "skip" }); continue; } + if (now >= q) out.push({ id: d.id, stage: "quarter" }); + } + return out; +} + +// The next time dueAlerts has something to do (null = nothing scheduled). +export function nextAlertAt(list, now) { + let next = null; + const take = (t) => { if (next == null || t < next) next = t; }; + for (const d of list || []) { + if (!d || d.status !== "open" || !fin(d.dueAt)) continue; + const a = d.alerts || {}; + if (a.created && a.quarter) continue; + if (fin(a.holdUntil) && now < a.holdUntil) { take(a.holdUntil); continue; } + if (!a.created) { take(now); continue; } + const q = quarterAt(d); + if (q == null || now >= d.dueAt) take(now); else take(Math.max(q, now)); + } + return next; +} + +// One alert line for a deadline at a stage, for email, Slack, Teams and webhooks. +export function alertLine(d, stage, now) { + const left = fmtLeft(timeLeft(d, now)), due = utc(d.dueAt); + if (d.kind === "cra-exploited") { + const q = CRA.quote[d.clock] ? " Article 14(2): \"" + CRA.quote[d.clock] + "\"." : ""; + return { title: d.title, detail: (stage === "quarter" ? "A quarter of the time is left: due " : "Due ") + due + " (" + left + ")." + q }; + } + if (d.kind === "cert-expiry") return { title: d.title + " on " + utc(d.dueAt).slice(0, 10), detail: (stage === "quarter" ? "A quarter of the time is left (" + left + "). " : "") + "Renew it and install it everywhere it is served." }; + return { title: d.title, detail: (stage === "quarter" ? "A quarter of the time is left: " : "") + "KEV due date " + utc(d.dueAt).slice(0, 10) + " (" + left + ")." }; +} + +// ---- the facts for a CRA early warning --------------------------------------------------------- + +// Plain facts to paste into the early warning. Nothing is guessed: what is not known says so. +// -> { rows: [[label, value]], text } +export function craFacts(c, deadlines = {}, now = Date.now()) { + if (!c) return { rows: [], text: "" }; + const k = craClocks(c); + const aware = utc(c.awareAt) + (fin(c.alertedAt) && c.awareAt !== c.alertedAt ? " (Darknode alerted " + utc(c.alertedAt) + ")" : " (when Darknode alerted)"); + const states = stateNames(c.memberStates); + const rows = [ + ["Vulnerability", c.cve], + ["Product or asset", (c.assets || []).join(", ") || "Not recorded"], + ["Exploitation confirmed", c.kevDateAdded ? "Added to the CISA Known Exploited Vulnerabilities catalogue on " + c.kevDateAdded : "In the CISA Known Exploited Vulnerabilities catalogue (date added not recorded)"], + ["Became aware", aware], + ["Member States where the product is made available", states.length ? states.join(", ") : "Not entered yet"], + ["Corrective or mitigating measures known", c.measures || "None entered yet"], + ["Fix or mitigation available", fin(c.fixAt) ? utc(c.fixAt) : "Not marked yet"], + ["Early warning due", utc(k.early)], + ["Vulnerability notification due", utc(k.notify)], + ["Final report due", k.final != null ? utc(k.final) : "14 days after a fix or mitigation is available"], + ["CISA KEV catalogue", kevLink(c.cve)], + ["NVD", nvdLink(c.cve)], + ["Legal basis", CRA.source.label + ", " + CRA.source.url], + ]; + const text = ["Cyber Resilience Act early-warning facts: " + c.cve, "Prepared " + utc(now) + " by Darknode from the CISA KEV catalogue and your entries.", ""] + .concat(rows.map(([l, v]) => l + ": " + v), ["", CRA.where, DISCLAIMER]).join("\n"); + return { rows, text }; +} diff --git a/public/js/core/entitlements.js b/public/js/core/entitlements.js index ea0849f1..736bd4bd 100644 --- a/public/js/core/entitlements.js +++ b/public/js/core/entitlements.js @@ -92,8 +92,9 @@ export const PLAN_GROUP = { exposure: "pro", code: "pro", identity: "team", dete 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", - // Free: the one-domain watch (Pro adds more monitors; the server enforces both) - monitors: "free" }; + // Free: the one-domain watch (Pro adds more monitors; the server enforces both). Deadlines are + // free to see (a watched certificate's expiry); the CRA and BOD clocks need Pro on the server. + monitors: "free", deadlines: "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 4f9f1365..0519f19f 100644 --- a/public/js/deck-ui.js +++ b/public/js/deck-ui.js @@ -46,6 +46,7 @@ const fqMod = lazyMod("/js/deck/findings-queue.js?v=20261027c"); const invMod = lazyMod("/js/deck/inventory.js?v=20261027c"); const corrMod = lazyMod("/js/deck/correlations.js?v=20261029c"); const monMod = lazyMod("/js/deck/monitors.js?v=20261029d"); +const dlMod = lazyMod("/js/deck/deadlines.js?v=1"); const keysMod = lazyMod("/js/deck/apikeys.js?v=20261030d"); const auditMod = lazyMod("/js/deck/audit.js?v=20261028a"); const deviceMod = lazyMod("/js/deck/device.js?v=20261101a"); @@ -259,6 +260,7 @@ const IC = { pulse: SVG(''), spark: SVG(''), bell: SVG(''), + clock: SVG(''), plus: SVG(''), chevd: SVG(''), gear: SVG(''), @@ -1815,7 +1817,7 @@ export function renderDeck(host, opts) { { id: "exposure", g: "Exposure", items: [["scene", "surface", "Attack Surface", IC.radar], ["scene", "cloud", "Cloud Posture", IC.cloud], ["scene", "threat", "Vulnerabilities", IC.alert], ["tool", "posture", "Scorecard", IC.gauge], ["tool", "tlsfleet", "Certificates", IC.cert], ["tool", "fwaudit", "Firewall Audit", IC.shield], ["tool", "vulnimport", "Scan Imports", IC.alert], ["tool", "fleetcomply", "Devices", IC.gauge], ["tool", "dmarcreports", "DMARC Reports", IC.link], ["tool", "domainguard", "Domains", IC.radar], ["tool", "netexposure", "Network Scans", IC.nodes]] }, { id: "identity", g: "Identity", items: [["tool", "signins", "Sign-ins", IC.search], ["tool", "accessreview", "Access Review", IC.check], ["tool", "caaudit", "Conditional Access", IC.shield], ["tool", "privaudit", "Privileged Access", IC.key], ["tool", "nhi", "Service Accounts", IC.gear], ["tool", "jml", "Joiners & Leavers", IC.check], ["tool", "oauthgov", "OAuth Apps", IC.plug], ["tool", "vpnaudit", "VPN & Remote Access", IC.lock]] }, { id: "code", g: "Application Security", items: [["tool", "codescan", "Code Scanner", IC.code], ["tool", "supplychain", "Dependencies", IC.branch], ["tool", "threatforest", "Attack Trees", IC.tree], ["tool", "iacscan", "Infrastructure as Code", IC.code], ["tool", "k8saudit", "Kubernetes", IC.nodes], ["tool", "licenseaudit", "Licenses", IC.scale], ["tool", "apispec", "API Definitions", IC.plug]] }, - { id: "detect", g: "Security Operations", items: [["scene", "findings", "Findings", IC.alert], ["scene", "inventory", "Asset Inventory", IC.grid], ["scene", "correlations", "Correlations", IC.nodes], ["scene", "invest", "Investigations", IC.search], ["tool", "secgraph", "Security Graph", IC.nodes], ["tool", "incidents", "Incidents", IC.shield], ["tool", "investigation", "Case Files", IC.brief], ["tool", "phishtriage", "Phishing", IC.hook], ["tool", "loghunt", "Log Search", IC.term], ["scene", "monitors", "Monitors", IC.bell], ["scene", "apikeys", "API & Ingest", IC.key], ["scene", "audit", "Audit Log", IC.lock], ["scene", "reports", "Reports", IC.note], ["scene", "activity", "Activity", IC.pulse], ["tool", "cloudtrail", "Cloud Audit Logs", IC.cloud], ["tool", "dnshunt", "DNS Logs", IC.search], ["tool", "proxyhunt", "Proxy Logs", IC.eye], ["tool", "pentestreg", "Pentest Findings", IC.wrench]] }, + { id: "detect", g: "Security Operations", items: [["scene", "findings", "Findings", IC.alert], ["scene", "inventory", "Asset Inventory", IC.grid], ["scene", "correlations", "Correlations", IC.nodes], ["scene", "invest", "Investigations", IC.search], ["tool", "secgraph", "Security Graph", IC.nodes], ["tool", "incidents", "Incidents", IC.shield], ["tool", "investigation", "Case Files", IC.brief], ["tool", "phishtriage", "Phishing", IC.hook], ["tool", "loghunt", "Log Search", IC.term], ["scene", "monitors", "Monitors", IC.bell], ["scene", "deadlines", "Deadlines", IC.clock], ["scene", "apikeys", "API & Ingest", IC.key], ["scene", "audit", "Audit Log", IC.lock], ["scene", "reports", "Reports", IC.note], ["scene", "activity", "Activity", IC.pulse], ["tool", "cloudtrail", "Cloud Audit Logs", IC.cloud], ["tool", "dnshunt", "DNS Logs", IC.search], ["tool", "proxyhunt", "Proxy Logs", IC.eye], ["tool", "pentestreg", "Pentest Findings", IC.wrench]] }, { id: "finsec", g: "Fraud & Abuse", items: [["tool", "strongroom", "Payment Fraud", IC.coins], ["tool", "payees", "Payee Changes", IC.shield], ["tool", "cloudspend", "Cloud Spend", IC.gauge]] }, { id: "risk", g: "Risk & Resilience", items: [["tool", "breachclock", "Breach Deadlines", IC.bell], ["tool", "riskreg", "Risk Register", IC.scale], ["tool", "vendorrisk", "Vendors", IC.nodes], ["tool", "backupready", "Backups", IC.folder]] }, { id: "compliance", g: "Compliance", items: [["scene", "compliance", "Frameworks", IC.check], ["tool", "crosswalk", "AI Risk Mapping", IC.map], ["tool", "dlp", "Sensitive Data", IC.eye], ["tool", "leakprobe", "Exposed Keys", IC.key], ["tool", "evidence", "Audit Evidence", IC.book], ["tool", "dataflow", "Data Inventory", IC.folder], ["tool", "awareness", "Security Training", IC.pulse]] }, @@ -2026,6 +2028,7 @@ export function renderDeck(host, opts) { + @@ -2175,6 +2178,7 @@ export function renderDeck(host, opts) { else if (scene === "inventory") renderInventory(); else if (scene === "correlations") renderCorrelations(); else if (scene === "monitors") renderMonitors(); + else if (scene === "deadlines") renderDeadlines(); else if (scene === "apikeys") renderApiKeys(); else if (scene === "audit") renderAudit(); else if (scene === "section") renderSection(); @@ -2730,6 +2734,7 @@ export function renderDeck(host, opts) { { type: "action", label: "Go to Asset Inventory", group: "Navigate", icon: IC.tree, run: () => go("inventory"), k: "scene:inventory" }, { type: "action", label: "Go to Correlations", group: "Navigate", icon: IC.nodes, run: () => go("correlations"), k: "scene:correlations" }, { type: "action", label: "Go to Monitors", group: "Navigate", icon: IC.bell, run: () => go("monitors"), k: "scene:monitors", kw: "watch alert schedule certificate expiry email dns spf dmarc mx caa drift" }, + { type: "action", label: "Go to Deadlines", group: "Navigate", icon: IC.clock, run: () => go("deadlines"), k: "scene:deadlines", kw: "deadline due clock cyber resilience act cra article 14 enisa early warning bod 22-01 kev certificate expiry" }, { type: "action", label: "Go to API & Ingest", group: "Navigate", icon: IC.key, run: () => go("apikeys"), k: "scene:apikeys" }, { type: "action", label: "Go to Audit Log", group: "Navigate", icon: IC.lock, run: () => go("audit"), k: "scene:audit" }, { type: "action", label: "Go to Investigations", group: "Navigate", icon: IC.search, run: () => go("invest"), k: "scene:invest" }, @@ -3246,6 +3251,7 @@ export function renderDeck(host, opts) {
+

${IC.bolt} Needs attention All findings

Ranking what needs attention…
@@ -3289,6 +3295,9 @@ export function renderDeck(host, opts) { if (frMod) mountFr(frMod); else import("/js/check/first-run.js?v=1").then(mountFr).catch(() => frSlot.remove()); } + // Deadlines: the soonest open ones, or nothing at all when none are open + const dlSlot = el.querySelector("#dkDeadlines0"); + if (dlSlot && !isLocked("scene:deadlines")) dlMod().then((m) => m.mountDeadlineBlock(dlSlot, { tier: planTier, go }), () => {}); // quick AI ask bar -> prefill + open the assistant const askForm = el.querySelector("#dkAsk"), askIn = el.querySelector("#dkAskIn"); if (askForm) askForm.onsubmit = (e) => { e.preventDefault(); askAI(askIn.value); }; @@ -4103,6 +4112,7 @@ export function renderDeck(host, opts) { 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, tier: planTier, go })); } + function renderDeadlines(){ lazyScene(sceneEls.deadlines, dlMod, (m) => m.mountDeadlines(sceneEls.deadlines, { 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 })); } @@ -4213,7 +4223,7 @@ export function renderDeck(host, opts) { 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", "Monitors for more domains and known-exploited CVEs, with Slack, Teams and webhook alerts", "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", "Cyber Resilience Act and BOD 22-01 deadline clocks for known-exploited CVEs, if you opt in", "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.", @@ -5014,7 +5024,7 @@ export function renderDeck(host, opts) { // ---------- keyboard & shortcuts ---------- // Vim-style navigation: press "g" then a scene key. "?" opens the cheatsheet. const GOTO = { o: "overview", e: "surface", i: "threat", l: "cloud", m: "compliance", n: "invest", c: "con", t: "tools", k: "toolkit", a: "activity", s: "assistant", f: "findings", r: "reports", w: "team", p: "plans", ",": "settings", v: "inventory", x: "correlations", b: "monitors", y: "apikeys", u: "audit" }; - const SCENE_TITLE = { overview: "Overview", surface: "Attack Surface", threat: "Vulnerabilities", cloud: "Cloud Posture", compliance: "Frameworks", invest: "Investigations", findings: "Findings", section: "Section overview", con: "Integrations", tools: "Tool Library", toolkit: "Toolkit", activity: "Activity", assistant: "Assistant", reports: "Reports", team: "Team", plans: "Plans & billing", settings: "Settings", inventory: "Asset Inventory", correlations: "Correlations", monitors: "Monitors", apikeys: "API & Ingest", device: "This Computer", audit: "Audit Log" }; + const SCENE_TITLE = { overview: "Overview", surface: "Attack Surface", threat: "Vulnerabilities", cloud: "Cloud Posture", compliance: "Frameworks", invest: "Investigations", findings: "Findings", section: "Section overview", con: "Integrations", tools: "Tool Library", toolkit: "Toolkit", activity: "Activity", assistant: "Assistant", reports: "Reports", team: "Team", plans: "Plans & billing", settings: "Settings", inventory: "Asset Inventory", correlations: "Correlations", monitors: "Monitors", deadlines: "Deadlines", apikeys: "API & Ingest", device: "This Computer", audit: "Audit Log" }; const keysEl = $("#dkKeys"); function buildKeysOverlay(){ const nav = Object.entries(GOTO).filter(([, sc]) => !isLocked("scene:" + sc)).map(([k, sc]) => `
Go to ${esc(SCENE_TITLE[sc] || sc)}g${esc(k)}
`).join(""); diff --git a/public/js/deck/deadlines.js b/public/js/deck/deadlines.js new file mode 100644 index 00000000..f896d3d1 --- /dev/null +++ b/public/js/deck/deadlines.js @@ -0,0 +1,347 @@ +// Copyright (c) 2026 Darknode-Official. All rights reserved. See LICENSE. +// +// Deadlines scene and the Overview's Deadlines block. The clocks are created and alerted on the +// server, per workspace, by the MonitorDO (worker/monitor.js): certificate expiry from the +// certificate monitors (the Free watch too), and, only with the workspace's opt-ins, the Cyber +// Resilience Act Article 14 reporting clocks and CISA BOD 22-01 due dates from the known-exploited +// CVE monitor. The clock maths and the early-warning facts come from core/deadlines.js, the same +// file the server uses. Darknode tracks the clocks and prepares facts; it does not decide whether +// a law applies and does not submit anything. +import { monitorApi as api, monitoringAvailable } from "./monitor-client.js"; +import { CRA, BOD2201, DISCLAIMER, MAX_SHIPPED, stateOf, fmtLeft, utc, stepsOf, sourceOf, craFacts, stateNames, sortDeadlines } from "../core/deadlines.js?v=1"; + +const S = { ctx: null, el: null, data: null, mons: null, seq: 0, open: new Set(), facts: "", pick: "", showClosed: false, graph: null }; +const B = { data: null, at: 0, seq: 0 }; // the Overview block's cache: the Overview re-renders often +const E = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); +const toast = (m, t) => { try { S.ctx && S.ctx.toast && S.ctx.toast(m, t); } catch (_) {} }; +const isFree = (ctx) => !!(ctx && ctx.tier === "free"); +// the Free watch lives in the caller's own workspace, so on Free every request goes there +const call = (body, ctx = S.ctx) => api(body, { personal: isFree(ctx) }); +const KIND = { "cra-exploited": "Cyber Resilience Act", "cert-expiry": "Certificate", "kev-due": "BOD 22-01" }; +const STATE = { overdue: "Overdue", open: "Open", waiting: "Not started", done: "Done", dismissed: "Dismissed" }; +const local = (ms) => (ms ? new Date(ms).toLocaleString([], { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" }) : ""); + +function injectStyle() { + if (document.getElementById("ddl-css")) return; + const st = document.createElement("style"); st.id = "ddl-css"; + st.textContent = ` +.ddl-sub{color:#5a6680;font-size:12.5px;margin:-2px 0 14px;line-height:1.5} +.ddl-card{border:1px solid rgba(23,33,56,.12);border-radius:10px;margin:0 0 10px;background:#fff} +.ddl-card.over{border-color:rgba(198,40,40,.45)} +.ddl-case{padding:12px 14px 4px;border-bottom:1px solid rgba(23,33,56,.08)} +.ddl-case h3{margin:0;font-size:13.5px;font-weight:650;color:#141c2e} +.ddl-case p{margin:3px 0 8px;font-size:12px;color:#5a6680;line-height:1.5} +.ddl-row{display:flex;align-items:center;gap:8px 12px;flex-wrap:wrap;padding:10px 14px} +.ddl-row+.ddl-row{border-top:1px dashed rgba(23,33,56,.1)} +.ddl-row>.ddl-pill{min-width:80px;text-align:center;box-sizing:border-box} +.ddl-pill{font-size:10.5px;font-weight:700;border-radius:20px;padding:1px 8px;background:rgba(23,33,56,.07);color:#45506a;white-space:nowrap} +.ddl-pill.over{background:rgba(198,40,40,.1);color:#c62828} +.ddl-pill.done{background:rgba(18,168,95,.1);color:#0e7a46} +.ddl-t{flex:1 1 300px;min-width:0} +.ddl-t b{display:block;font-size:13px;font-weight:650;color:#141c2e;overflow-wrap:anywhere} +.ddl-t span{font-size:12px;color:#5a6680} +.ddl-left{font-size:13px;font-weight:700;color:#141c2e;font-variant-numeric:tabular-nums;white-space:nowrap} +.ddl-left.over{color:#c62828} +.ddl-acts{display:flex;gap:6px;flex-wrap:wrap} +.ddl-btn{appearance:none;border:1px solid rgba(23,33,56,.16);background:#fff;border-radius:7px;font:inherit;font-size:12px;font-weight:600;color:#2a3450;padding:4px 10px;cursor:pointer} +.ddl-btn:hover{border-color:var(--dk-acc,#2552c6);color:var(--dk-acc,#2552c6)} +.ddl-btn.pri{background:var(--dk-acc,#2552c6);border-color:var(--dk-acc,#2552c6);color:#fff} +.ddl-btn:disabled{opacity:.55;cursor:default} +.ddl-more{padding:0 14px 12px;font-size:12.5px;color:#45506a;line-height:1.55} +.ddl-more ol{margin:4px 0 8px;padding-left:20px} +.ddl-more blockquote{margin:6px 0;padding:6px 10px;border-left:3px solid rgba(23,33,56,.18);color:#45506a;font-size:12px} +.ddl-more a,.ddl-note a{color:var(--dk-acc,#2552c6)} +.ddl-edit{display:grid;grid-template-columns:repeat(auto-fit,minmax(230px,1fr));gap:10px 14px;padding:10px 14px 12px;border-top:1px solid rgba(23,33,56,.08);background:rgba(23,33,56,.02)} +.ddl-f label{display:block;font-size:12px;font-weight:600;color:#2a3450;margin:0 0 3px} +.ddl-f input,.ddl-f textarea{width:100%;font:inherit;font-size:13px;border:1px solid rgba(23,33,56,.18);border-radius:7px;padding:6px 9px;box-sizing:border-box;background:#fff} +.ddl-f textarea{min-height:54px;resize:vertical} +.ddl-f .now{font-size:12px;color:#141c2e;margin:0 0 4px} +.ddl-f .hint{font-size:11.5px;color:#5a6680;margin:3px 0 0;line-height:1.45} +.ddl-f .rowb{display:flex;gap:6px;margin-top:6px;flex-wrap:wrap} +.ddl-facts{margin:0 14px 12px;border:1px solid rgba(37,82,198,.25);border-radius:8px;background:rgba(37,82,198,.03);padding:10px 12px} +.ddl-facts table{width:100%;border-collapse:collapse;font-size:12.5px} +.ddl-facts td{vertical-align:top;overflow-wrap:anywhere} +.ddl-facts td:first-child{width:38%;color:#5a6680;font-weight:600} +.ddl-facts .hd{display:flex;align-items:center;gap:8px;margin:0 0 6px;font-size:12.5px;font-weight:650;color:#141c2e} +.ddl-facts .hd .ddl-btn{margin-left:auto} +.ddl-panel{margin:18px 0 0;border:1px solid rgba(23,33,56,.12);border-radius:10px;padding:12px 14px} +.ddl-panel h2{font-size:14px;margin:0 0 6px} +.ddl-check{display:flex;gap:9px;align-items:flex-start;font-size:13px;color:#141c2e;margin:8px 0;line-height:1.45} +.ddl-check input{margin-top:3px} +.ddl-check small{display:block;color:#5a6680;font-size:12px} +.ddl-note{font-size:12px;color:#45506a;line-height:1.55;margin:8px 0 0} +.ddl-warn{font-size:12.5px;color:#7a4a00;background:rgba(245,146,11,.1);border-radius:8px;padding:9px 12px;line-height:1.5;margin:8px 0 0} +.ddl-picklist{max-height:230px;overflow:auto;border:1px solid rgba(23,33,56,.12);border-radius:8px;margin:6px 0 0} +.ddl-picklist label{display:flex;gap:8px;align-items:center;padding:6px 10px;font-size:12.5px;border-top:1px dashed rgba(23,33,56,.08);overflow-wrap:anywhere} +.ddl-picklist label:first-child{border-top:0} +.ddl-picklist small{color:#5a6680;margin-left:auto;white-space:nowrap} +.ddl-pickbar{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-top:8px} +.ddl-pickbar input{flex:1 1 200px;font:inherit;font-size:13px;border:1px solid rgba(23,33,56,.18);border-radius:7px;padding:6px 9px} +.ddl-off{font-size:12.5px;color:#7a4a00;background:rgba(245,146,11,.1);border-radius:8px;padding:11px 13px;line-height:1.5} +.ddl-ov .ddl-row{padding:8px 0} +.ddl-ov .ddl-row+.ddl-row{border-top:1px dashed rgba(23,33,56,.1)} +@media (max-width:640px){.ddl-row{gap:6px 10px}.ddl-row>.ddl-pill{min-width:0}.ddl-acts{width:100%}.ddl-facts td{display:block;width:auto}.ddl-facts table td:first-child{width:auto;padding-bottom:0!important;border-bottom:0!important}.ddl-facts table td+td{padding-top:2px!important}} +`; + document.head.appendChild(st); +} + +// keep every visible countdown current (one timer for the scene and the Overview block) +let timer = 0; +function tick() { + const t = Date.now(); + document.querySelectorAll("[data-dl-due]").forEach((x) => { + const due = Number(x.dataset.dlDue); if (!due) return; + x.textContent = fmtLeft(due - t); x.classList.toggle("over", due <= t); + }); +} +const startTick = () => { if (!timer) timer = setInterval(tick, 30000); }; +const leftHtml = (d, now) => d.dueAt && (d.status === "open") ? `${E(fmtLeft(d.dueAt - now))}` : ""; +const pill = (st) => `${E(STATE[st] || st)}`; + +// ---- the scene ---------------------------------------------------------------------------------- + +export function mountDeadlines(el, ctx) { + injectStyle(); startTick(); + S.ctx = ctx || S.ctx; S.el = el; S.facts = ""; + el.innerHTML = ` +

Deadlines

The clocks your findings start, soonest first: certificate expiry, and with your opt-ins the Cyber Resilience Act's reporting clocks and CISA BOD 22-01 due dates. Each one lists its steps; you are alerted when it starts and when a quarter of its time is left.

+
Loading deadlines…
`; + load(); +} + +async function load() { + const box = S.el && S.el.querySelector("#dlBody"); if (!box) return; + const my = ++S.seq; + if (!monitoringAvailable()) { box.innerHTML = `
Deadlines need the cloud proxy, which this build has not configured.
`; return; } + try { + const [data, mons] = await Promise.all([call({ op: "deadlines" }), call({ op: "list" }).catch(() => null)]); + if (my !== S.seq) return; + S.data = data; S.mons = mons && mons.monitors; B.at = 0; // the Overview block reloads next time + paint(); + } catch (e) { + if (my !== S.seq) return; + box.innerHTML = `
${E(e.message || String(e))}
`; + } +} + +function rowHtml(d, now) { + const st = stateOf(d, now), open = S.open.has(d.id), src = sourceOf(d); + const sub = d.kind === "cra-exploited" ? (d.dueAt ? "Due " + utc(d.dueAt) + " (" + local(d.dueAt) + " your time)" : "Starts when you mark the fix or mitigation available") + : d.kind === "cert-expiry" ? "Expires " + utc(d.dueAt) + " · watched since " + utc(d.startedAt) + : "KEV due date " + utc(d.dueAt).slice(0, 10) + " (end of day, UTC)"; + const closed = d.status !== "open"; + return `
+ ${pill(st)} +
${E(d.kind === "cra-exploited" ? ({ early: "Early warning (24 hours)", notify: "Vulnerability notification (72 hours)", final: "Final report (14 days after the fix)" }[d.clock] || d.title) : d.title)}${E(KIND[d.kind] || d.kind)} · ${E(sub)}${closed && d.reason ? " · " + E(STATE[d.status]) + ": " + E(d.reason) : ""}
+ ${leftHtml(d, now)} + + + ${closed ? `` : ``} + +
+ ${open ? `
    ${stepsOf(d).map((s) => `
  1. ${E(s)}
  2. `).join("")}
${src ? `${src.quote ? `
"${E(src.quote)}"
` : ""}Source: ${E(src.label)}` : ""}
` : ""}`; +} + +function caseHtml(c, list, now) { + const over = list.some((d) => stateOf(d, now) === "overdue"); + const aware = utc(c.awareAt) + (c.awareAt !== c.alertedAt ? " (you corrected it; Darknode alerted " + utc(c.alertedAt) + ")" : " (when Darknode alerted)"); + const states = stateNames(c.memberStates); + const factsOpen = S.facts === c.cve; + const f = factsOpen ? craFacts(c, {}, now) : null; + return `
+

${E(c.cve)} in ${E((c.assets || []).join(", "))}

+

Known exploited: added to the CISA KEV catalogue${c.kevDateAdded ? " on " + E(c.kevDateAdded) : ""}. Became aware ${E(aware)}. Article 14(2): early warning within 24 hours and vulnerability notification within 72 hours of becoming aware, final report within 14 days after a fix or mitigation is available.

+
+
+ ${f ? `
Early-warning facts
${f.rows.map(([l, v]) => ``).join("")}
${E(l)}${/^https:\/\//.test(v) ? `${E(v)}` : E(v)}

${E(CRA.where)} ${E(DISCLAIMER)}

` : ""} + ${S.open.has("edit:" + c.cve) ? `
+
${E(utc(c.awareAt))}

Correct it if you knew earlier or later. Your local time.

+
${c.fixAt ? E(utc(c.fixAt)) : "Not marked yet"}

Leave empty to use now. This starts the 14-day final report clock.

${c.fixAt ? '' : ""}
+
${states.length ? E(states.join(", ")) : "Not entered yet"}

Where the product is made available: EU country names or two-letter codes, separated by commas.

+
${c.measures ? "Entered" : "Not entered yet"}

Corrective or mitigating measures: what has been done and what users can do.

+
+
` : ""} + ${list.map((d) => rowHtml(d, now)).join("")} +
`; +} + +function paint() { + const box = S.el && S.el.querySelector("#dlBody"); if (!box || !S.data) return; + const now = Date.now(), free = isFree(S.ctx); + const all = sortDeadlines(S.data.deadlines || [], now); + const cases = new Map((S.data.cases || []).map((c) => [c.cve, c])); + const live = all.filter((d) => d.status === "open"), closed = all.filter((d) => d.status !== "open"); + // a CRA case is one card with its three clocks, placed where its soonest open clock sorts + const blocks = [], seen = new Set(); + for (const d of live) { + if (d.kind === "cra-exploited" && d.group) { + if (seen.has(d.group)) continue; + seen.add(d.group); + const c = cases.get(d.subject && d.subject.value); + const list = all.filter((x) => x.group === d.group); + if (c) { blocks.push(caseHtml(c, list, now)); continue; } + } + blocks.push(`
${rowHtml(d, now)}
`); + } + const overdue = live.filter((d) => stateOf(d, now) === "overdue").length, waiting = live.filter((d) => stateOf(d, now) === "waiting").length; + const running = live.length - waiting; + box.innerHTML = ` +

${live.length ? `${running} open${overdue ? `, ${overdue} overdue` : ""}${waiting ? `, ${waiting} not started yet` : ""}.` : "No open deadlines."} Times are in UTC, as the clocks run on the server.

+ ${blocks.join("") || `
Nothing is due. A certificate your monitors see expiring shows up here${free ? "" : ", and so do the reporting clocks you opt in to below"}.
`} + ${closed.length ? `

Closed

${S.showClosed ? closed.map((d) => `
${rowHtml(d, now)}
`).join("") : ""}
` : ""} + ${settingsHtml(free)}`; + wire(box); +} + +// ---- opt-ins and the assets shipped in a product ---------------------------------------------------- + +function settingsHtml(free) { + const s = (S.data && S.data.settings) || { cra: false, bod2201: false, shipped: [] }; + const kev = (S.mons || []).some((m) => m.type === "kev-epss" && !m.paused); + const dis = free ? " disabled" : ""; + const shipped = s.shipped || []; + const ents = S.graph ? S.graph.filter((e) => !S.pick || e.name.toLowerCase().includes(S.pick.toLowerCase())).slice(0, 300) : null; + const isOn = (e) => shipped.some((x) => (x.id && x.id === e.id) || (x.name.toLowerCase() === e.name.toLowerCase() && (!x.type || x.type === e.type))); + return `
+

Opt-ins

+

Nothing is assumed. Darknode starts these clocks only when you say they apply to you.

+ + + ${free ? `
Both clocks come from the known-exploited CVE monitor, which is part of Pro. Certificate deadlines from your Free watch are tracked here already.
` + : (s.cra || s.bod2201) && !kev ? `
Add a KEV/EPSS watch under Monitors: the clocks start from its new matches.
` : ""} +

Shipped in a product

+

Mark the assets and components that go into a product you sell. They come from your Security Graph, including components imported from an SBOM (CycloneDX) or a scanner under API & Ingest. ${shipped.length ? shipped.length + " marked." : "None marked yet."}

+ ${ents === null ? `
` + : `
+
${ents.length ? ents.map((e) => ``).join("") : ``}
`} +

${E(DISCLAIMER)} Source: ${E(CRA.source.label)}.

+
`; +} + +async function loadGraph() { + try { + const g = await import("/js/security-graph.js"); // singleton: never version + const P = await import("/js/core/posture.js"); // the same module instance deck-ui.js loads + S.graph = g.listEntities({ type: ["ASSET", "SOFTWARE"] }).filter((e) => e && e.name && !P.isSimulated(e) && !String(e.source || "").startsWith("monitor:")) + .map((e) => ({ id: e.id, type: e.type, name: String(e.name) })).sort((a, b) => a.name.localeCompare(b.name)); + } catch (_) { S.graph = []; } + paint(); +} + +async function saveSettings(patch) { + const cur = (S.data && S.data.settings) || {}; + try { + const r = await call({ op: "dlSettings", settings: { cra: !!cur.cra, bod2201: !!cur.bod2201, shipped: cur.shipped || [], ...patch } }); + S.data.settings = r.settings; B.at = 0; + toast("Saved", "success"); + } catch (e) { toast(e.message || "Could not save", "error"); } + paint(); +} + +// ---- actions -------------------------------------------------------------------------------------- + +function wire(box) { + const $ = (s) => box.querySelector(s); + box.querySelectorAll(".ddl-row").forEach((row) => row.querySelector(".ddl-acts").onclick = (e) => { + const b = e.target.closest("[data-act]"); if (!b) return; + const id = row.dataset.id, act = b.dataset.act; + if (act === "steps") { S.open.has(id) ? S.open.delete(id) : S.open.add(id); paint(); } + else if (act === "done" || act === "dismiss") closeOne(id, act === "done" ? "done" : "dismissed"); + else if (act === "reopen") change({ op: "dlReopen", id }, "Reopened"); + }); + box.querySelectorAll("[data-case]").forEach((card) => card.querySelectorAll(".ddl-case [data-act], .ddl-facts [data-act], .ddl-edit [data-act]").forEach((b) => b.onclick = () => caseAct(card, card.dataset.case, b.dataset.act))); + const ct = $("#dlClosedT"); if (ct) ct.onclick = () => { S.showClosed = !S.showClosed; paint(); }; + const cra = $("#dlCra"), bod = $("#dlBod"); + if (cra) cra.onchange = () => saveSettings({ cra: cra.checked }); + if (bod) bod.onchange = () => saveSettings({ bod2201: bod.checked }); + const plans = $("#dlPlans"); if (plans) plans.onclick = () => S.ctx && S.ctx.go && S.ctx.go("plans"); + const mon = $("#dlMon"); if (mon) mon.onclick = () => S.ctx && S.ctx.go && S.ctx.go("monitors"); + const pl = $("#dlPickLoad"); if (pl) pl.onclick = loadGraph; + const q = $("#dlPickQ"); + if (q) q.oninput = () => { S.pick = q.value; const pos = q.selectionStart; paintPick(); const n = S.el.querySelector("#dlPickQ"); if (n) { n.focus(); try { n.setSelectionRange(pos, pos); } catch (_) {} } }; + const ps = $("#dlPickSave"); + if (ps) ps.onclick = () => { + const cur = ((S.data && S.data.settings) || {}).shipped || []; + const shown = new Map((S.graph || []).map((e) => [e.id, e])); + const boxes = [...box.querySelectorAll("#dlPickList [data-pid]")]; + const visible = new Set(boxes.map((x) => x.dataset.pid)); + // entries not shown under the current filter are kept as they were + const keep = cur.filter((x) => !(x.id && visible.has(x.id)) && ![...visible].some((id) => shown.get(id) && shown.get(id).name.toLowerCase() === x.name.toLowerCase())); + const add = boxes.filter((x) => x.checked).map((x) => shown.get(x.dataset.pid)).filter(Boolean).map((e) => ({ id: e.id, type: e.type, name: e.name })); + const next = [...keep, ...add]; + if (next.length > MAX_SHIPPED) { toast("At most " + MAX_SHIPPED + " assets can be marked as shipped.", "error"); return; } + saveSettings({ shipped: next }); + }; +} +function paintPick() { paint(); } + +async function change(body, ok) { + try { await call(body); B.at = 0; if (ok) toast(ok, "success"); await load(); } + catch (e) { toast(e.message || "Could not save", "error"); } +} + +async function closeOne(id, status) { + if (!window.dnPrompt) { toast("This needs the in-app dialog, which did not load. Reload the page.", "error"); return; } + const reason = await window.dnPrompt(status === "done" ? "Mark done" : "Dismiss deadline", { + desc: status === "done" ? "Say what was done, for example the submission reference. It is kept with the deadline." : "Say why it does not apply. It is kept with the deadline.", + placeholder: status === "done" ? "Reference or note" : "Reason", textarea: true, submitText: status === "done" ? "Mark done" : "Dismiss", + }); + if (reason == null) return; + if (!String(reason).trim()) { toast("A reason is needed.", "error"); return; } + change({ op: "dlClose", id, status, reason }, status === "done" ? "Marked done" : "Dismissed"); +} + +const fromLocal = (v) => { const t = v ? new Date(v).getTime() : NaN; return Number.isFinite(t) ? t : null; }; + +async function caseAct(card, cve, act) { + const c = ((S.data && S.data.cases) || []).find((x) => x.cve === cve); if (!c) return; + if (act === "facts") { S.facts = S.facts === cve ? "" : cve; paint(); return; } + if (act === "edit") { const k = "edit:" + cve; S.open.has(k) ? S.open.delete(k) : S.open.add(k); paint(); return; } + if (act === "copy") { + const text = craFacts(c, {}, Date.now()).text; + try { await navigator.clipboard.writeText(text); toast("Facts copied", "success"); } + catch (_) { toast("Copy was blocked by the browser. Select the table and copy it instead.", "error"); } + return; + } + const f = (n) => card.querySelector(`[data-f="${n}"]`); + if (act === "fix") { const v = f("fix") && f("fix").value; const t = v ? fromLocal(v) : Date.now(); if (t == null) { toast("Enter a valid date and time.", "error"); return; } return change({ op: "dlCase", cve, patch: { fixAt: t } }, "Fix marked available: the 14-day clock started"); } + if (act === "unfix") return change({ op: "dlCase", cve, patch: { fixAt: null } }, "Cleared"); + if (act === "save") { + const patch = { memberStates: f("states") ? f("states").value : "", measures: f("measures") ? f("measures").value : "" }; + const aw = f("aware") && f("aware").value; + if (aw) { const t = fromLocal(aw); if (t == null) { toast("Enter a valid date and time.", "error"); return; } patch.awareAt = t; } + return change({ op: "dlCase", cve, patch }, "Case saved"); + } +} + +// ---- the Overview block ----------------------------------------------------------------------------- + +// Fills `el` (a .dk-ovp panel) with the soonest open deadlines, or hides it when there are none. +export async function mountDeadlineBlock(el, ctx) { + if (!el) return; + injectStyle(); startTick(); + const draw = (data) => { + const now = Date.now(); + const open = sortDeadlines((data && data.deadlines) || [], now).filter((d) => d.status === "open" && d.dueAt); + if (!open.length || !el.isConnected) { el.hidden = true; return; } + el.hidden = false; + el.classList.add("ddl-ov"); + const over = open.filter((d) => d.dueAt <= now).length; + el.innerHTML = `

Deadlines${over ? ` ${over} overdue` : ""} All deadlines

+ ${open.slice(0, 5).map((d) => `
${pill(stateOf(d, now))}
${E(d.title)}${E(KIND[d.kind] || d.kind)} · due ${E(utc(d.dueAt))}
${leftHtml(d, now)}
`).join("")} + ${open.length > 5 ? `
${open.length - 5} more under Deadlines.
` : ""}`; + const go = el.querySelector("[data-dl-go]"); + if (go) { const nav = () => ctx && ctx.go && ctx.go("deadlines"); go.onclick = nav; go.onkeydown = (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); nav(); } }; } + }; + if (!monitoringAvailable()) { el.hidden = true; return; } + let wid = "me"; + if (!isFree(ctx)) try { wid = (await import("/js/security-graph.js")).activeWorkspaceId() || "me"; } catch (_) {} // singleton: never version + if (B.data && B.wid === wid && Date.now() - B.at < 60000) { draw(B.data); return; } + const my = ++B.seq; + try { + const data = await call({ op: "deadlines" }, ctx); + if (my !== B.seq) return; + B.data = data; B.at = Date.now(); B.wid = wid; + draw(data); + } catch (_) { el.hidden = true; } +} diff --git a/public/js/deck/routes.js b/public/js/deck/routes.js index 2dfab2cd..08e4a871 100644 --- a/public/js/deck/routes.js +++ b/public/js/deck/routes.js @@ -5,7 +5,7 @@ // Pure data and logic, no imports, so the landing can load it without the Deck. // scene id -> its element in the Deck -export const SCENES = { overview: "#dkOverview", surface: "#dkSurface", threat: "#dkThreat", cloud: "#dkCloud", compliance: "#dkCompliance", invest: "#dkInvest", findings: "#dkFindings", inventory: "#dkInventory", correlations: "#dkCorrelations", monitors: "#dkMonitors", apikeys: "#dkApiKeys", device: "#dkDevice", audit: "#dkAudit", section: "#dkSection", con: "#dkCon", tools: "#dkTools", toolkit: "#dkToolkit", activity: "#dkActivity", assistant: "#dkAssistant", plans: "#dkPlans", settings: "#dkSettings", reports: "#dkReports", team: "#dkTeam", personal: "#dkPersonal", enterprise: "#dkEnterprise" }; +export const SCENES = { overview: "#dkOverview", surface: "#dkSurface", threat: "#dkThreat", cloud: "#dkCloud", compliance: "#dkCompliance", invest: "#dkInvest", findings: "#dkFindings", inventory: "#dkInventory", correlations: "#dkCorrelations", monitors: "#dkMonitors", deadlines: "#dkDeadlines", apikeys: "#dkApiKeys", device: "#dkDevice", audit: "#dkAudit", section: "#dkSection", con: "#dkCon", tools: "#dkTools", toolkit: "#dkToolkit", activity: "#dkActivity", assistant: "#dkAssistant", plans: "#dkPlans", settings: "#dkSettings", reports: "#dkReports", team: "#dkTeam", personal: "#dkPersonal", enterprise: "#dkEnterprise" }; // Every Deck page has a darknode.ai link: a page is / (the overview is /, a section is // /area/, a Personal/Organization tab is /personal/). compliance and tools are also // tool ids, so those pages take another name. diff --git a/public/js/docs.js b/public/js/docs.js index 13ad5574..f93689e0 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. 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.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. 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.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,8 @@ 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?

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.

+
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 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.

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.

@@ -157,6 +158,7 @@ node darknode.js nexus init # optional: scaffold .nexus/ project
  • 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.
  • +
  • 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.
  • 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.
  • diff --git a/public/js/landing.js b/public/js/landing.js index dc875a43..37ac846d 100644 --- a/public/js/landing.js +++ b/public/js/landing.js @@ -746,6 +746,7 @@ export function renderLanding(view, actions) {
  • 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)
  • +
  • Known-exploited CVE monitors, with Cyber Resilience Act and BOD 22-01 deadline clocks
  • Cloud sync across devices
  • Email support
  • diff --git a/public/js/legal.js b/public/js/legal.js index 60b14ed7..18f002f0 100644 --- a/public/js/legal.js +++ b/public/js/legal.js @@ -17,6 +17,7 @@ export const TOS_HTML = `

    3. No Professional Advice

    Nothing Darknode provides — including scan results, findings, scores, compliance mappings, reports, or recommendations — constitutes legal, accounting, tax, financial, audit, regulatory, or other professional advice, or a certification of compliance. You are responsible for obtaining independent professional advice before relying on any output.

    +

    Deadlines, including Cyber Resilience Act and CISA BOD 22-01 clocks, are reminders worked out from what you tell us and from public catalogues. Darknode does not decide whether a law or directive applies to you and does not submit any notification or report for you. A deadline it shows, or does not show, does not change your own obligations or their timing.

    4. Disclaimer of Warranties

    The Platform is provided "as is" and "as available" without warranties of any kind, express, implied, or statutory, including but not limited to merchantability, fitness for a particular purpose, title, non-infringement, accuracy, completeness, reliability, security, or availability. Darknode does not warrant that the Platform will be uninterrupted or error-free, that defects will be corrected, or that results will be accurate or complete.

    @@ -78,6 +79,7 @@ export const TOS_HTML = `
  • 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.
  • +
  • Deadlines (optional): the deadlines your monitors find, the opt-ins you set, the assets you mark as shipped in a product, and for a Cyber Resilience Act case the times, Member States and measures you enter. Nothing is sent to a CSIRT, ENISA or anyone else.
  • 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 78f4a6ba..79253209 100644 --- a/public/js/ui/explain.js +++ b/public/js/ui/explain.js @@ -43,6 +43,7 @@ export const EXPLAIN = { "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.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." }, "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." }, "scene.reports": { title: "Reports", body: "Generate branded security reports from your own graph data: executive summary, findings register and attack-surface summary. Built in your browser; sample data is excluded and nothing is uploaded." }, @@ -131,6 +132,7 @@ export const EXPLAIN = { "panel.threat": { title: "New CVEs by severity", body: "How many of the 40 most recent CVEs are critical or high, split by severity. CVEs NVD has not scored yet are shown as Unscored, not counted as low.", src: "NVD, fetched live." }, "panel.notes": { title: "Notes", body: "A scratchpad for IPs, hypotheses and to-dos. Saved in this browser only." }, + "panel.deadlines": { title: "Deadlines", body: "Your soonest open deadlines with the time left. Overdue ones are red. Open Deadlines for each one's steps, and to mark it done or dismiss it with a reason." }, "panel.actions": { title: "Top actions", body: "The most important things to do next, ranked: open critical findings, known-exploited CVEs published this week, open high findings, critical CVEs, then gaps in your connected sources.", src: "Your security graph (sample data excluded), NVD and CISA KEV, fetched live." }, // ---- Findings ---- diff --git a/test/worker/deadlines.test.mjs b/test/worker/deadlines.test.mjs new file mode 100644 index 00000000..ab067bb0 --- /dev/null +++ b/test/worker/deadlines.test.mjs @@ -0,0 +1,400 @@ +// Deadlines (public/js/core/deadlines.js) and their place in the MonitorDO: the clock maths, the +// opt-ins, which KEV matches start a Cyber Resilience Act clock, the alert schedule and its email +// allowance, and the early-warning facts. In-memory storage, a fake network, no real sleeps; +// nothing here reaches Resend, Firebase or CISA. +import { test, group, assert } from "../harness.mjs"; +import { + CRA, HOUR, DAY, craClocks, kevDueAt, quarterAt, stateOf, fmtLeft, sortDeadlines, normSettings, checkSettings, + craApplies, parseMemberStates, shippedMatches, kevDeadlines, certDeadlines, closeDeadline, reopenDeadline, + updateCase, syncCaseClocks, craCase, craDeadlines, dueAlerts, nextAlertAt, craFacts, stepsOf, sourceOf, alertLine, +} from "../../public/js/core/deadlines.js"; +import { MonitorDO, handleMonitor } from "../../worker/monitor.js"; +import { buildDeadlineEmail, CRA_EMAILS_PER_DAY, ALERT_EMAILS_PER_DAY } from "../../worker/alert-email.js"; +import { attachPrincipal } from "../../worker/auth.js"; +import { _resetPlanCache } from "../../worker/plan.js"; + +const NOW = Date.UTC(2026, 10, 25, 9, 30); +const ME = "test@darknode.ai"; +const LOG4J = "CVE-2021-44228", CITRIX = "CVE-2023-4966"; + +// a workspace graph: a CycloneDX finding for log4j-core (shipped) and a scanner finding on a web host (not shipped) +const INVENTORY = { + entities: [ + { id: "f1", type: "FINDING", name: LOG4J + " — Remote code execution in log4j-core", source: "ingest:cyclonedx", data: { assets: ["log4j-core@2.14.1"] } }, + { id: "a1", type: "ASSET", name: "log4j-core@2.14.1", source: "ingest:cyclonedx", data: {} }, + { id: "f2", type: "FINDING", name: CITRIX + " — Information disclosure", source: "ingest:nessus", data: {} }, + { id: "a2", type: "ASSET", name: "web-01.test.darknode.ai", source: "ingest:nessus", data: {} }, + ], + relationships: [{ id: "r1", fromId: "f1", toId: "a1", type: "affects" }, { id: "r2", fromId: "f2", toId: "a2", type: "affects" }], +}; +const SHIPPED = [{ id: "a1", type: "ASSET", name: "log4j-core@2.14.1" }]; +const kevFinding = (cve, extra = {}) => ({ key: "kev:" + cve, severity: "critical", status: "open", cve, kev: true, dueDate: "2021-12-24", dateAdded: "2021-12-10", ...extra }); +const kevEvent = (cve) => ({ kind: "kev", key: "kev:" + cve, severity: "critical" }); + +group("deadlines/clock maths", () => { + test("CRA clocks: 24 h and 72 h from becoming aware, 14 days from the fix", () => { + const k = craClocks({ awareAt: NOW, fixAt: null }); + assert.equal(k.early, NOW + 24 * HOUR); + assert.equal(k.notify, NOW + 72 * HOUR); + assert.equal(k.final, null, "the final report clock waits for the fix"); + assert.equal(craClocks({ awareAt: NOW, fixAt: NOW + 5 * DAY }).final, NOW + 19 * DAY); + assert.equal(CRA.appliesFrom, Date.UTC(2026, 8, 11), "Article 14 applies from 11 September 2026"); + }); + test("a KEV due date ends at the end of that day, UTC", () => { + assert.equal(kevDueAt("2026-12-01"), Date.UTC(2026, 11, 1, 23, 59, 59)); + assert.equal(kevDueAt(""), null); assert.equal(kevDueAt("12/01/2026"), null); + }); + test("the quarter-left point, states and time left", () => { + const d = { status: "open", startedAt: NOW, dueAt: NOW + 24 * HOUR }; + assert.equal(quarterAt(d), NOW + 18 * HOUR); + assert.equal(quarterAt({ startedAt: NOW, dueAt: NOW - 1 }), null, "already due when it started: no quarter point"); + assert.equal(quarterAt({ startedAt: null, dueAt: null }), null); + assert.equal(stateOf(d, NOW), "open"); assert.equal(stateOf(d, NOW + 25 * HOUR), "overdue"); + assert.equal(stateOf({ status: "open", dueAt: null }, NOW), "waiting"); + assert.equal(stateOf({ ...d, status: "dismissed" }, NOW), "dismissed"); + assert.equal(fmtLeft(2 * DAY + 4 * HOUR + 59000), "2d 4h left"); + assert.equal(fmtLeft(5 * HOUR + 12 * 60000), "5h 12m left"); + assert.equal(fmtLeft(-(3 * HOUR + 5 * 60000)), "overdue by 3h 5m"); + assert.equal(fmtLeft(-1000), "overdue by 1m", "a second overdue is never shown as 0m"); + }); + test("soonest first, overdue included; waiting clocks next; closed last", () => { + const L = [ + { id: "closed", status: "done", dueAt: NOW + HOUR, closedAt: NOW }, + { id: "later", status: "open", dueAt: NOW + 3 * DAY }, + { id: "waiting", status: "open", dueAt: null, createdAt: NOW }, + { id: "overdue", status: "open", dueAt: NOW - HOUR }, + { id: "soon", status: "open", dueAt: NOW + HOUR }, + ]; + assert.deepEqual(sortDeadlines(L, NOW).map((d) => d.id), ["overdue", "soon", "later", "waiting", "closed"]); + }); +}); + +group("deadlines/opt-ins", () => { + test("nothing is assumed: both opt-ins are off by default", () => { + assert.deepEqual(normSettings(undefined), { cra: false, bod2201: false, shipped: [] }); + assert.deepEqual(normSettings({ cra: "yes", bod2201: 1 }), { cra: false, bod2201: false, shipped: [] }, "only a real true turns one on"); + }); + test("below Pro an opt-in cannot be turned on, but can be turned off", () => { + const r = checkSettings({ cra: true }, { free: true }); + assert.ok(r.error && r.plan); + assert.ok(checkSettings({ bod2201: true }, { free: true }).plan); + assert.deepEqual(checkSettings({ cra: false, shipped: SHIPPED }, { free: true }).settings.shipped, SHIPPED); + assert.equal(checkSettings({ cra: true }, { free: false }).settings.cra, true); + assert.ok(checkSettings({ shipped: "a1" }).error); + }); + test("CRA clocks start only with the opt-in and after Article 14 applies", () => { + assert.equal(craApplies({ cra: true }, NOW), true); + assert.equal(craApplies({ cra: false }, NOW), false); + assert.equal(craApplies({ cra: true }, Date.UTC(2026, 8, 10, 23)), false, "10 September 2026: not yet"); + }); + test("Member States: names or EU codes, Greece as EL or GR, anything else refused", () => { + assert.deepEqual(parseMemberStates("DE, fr, Greece, GR"), { codes: ["DE", "FR", "EL"], bad: [] }); + assert.deepEqual(parseMemberStates("NL; Norway").bad, ["Norway"]); + }); +}); + +group("deadlines/created from a KEV event, only for shipped assets", () => { + const run = (over = {}) => kevDeadlines({ events: [kevEvent(LOG4J), kevEvent(CITRIX)], findings: [kevFinding(LOG4J), kevFinding(CITRIX)], settings: { cra: true, shipped: SHIPPED }, inventory: INVENTORY, at: NOW, monitorId: "m1", ...over }); + test("the shipped component's CVE gets a case and three clocks; the unshipped host's does not", () => { + const r = run(); + assert.equal(r.cases.length, 1); + assert.equal(r.cases[0].cve, LOG4J); + assert.deepEqual(r.cases[0].assets, ["log4j-core@2.14.1"]); + assert.equal(r.cases[0].kevDateAdded, "2021-12-10"); + assert.equal(r.cases[0].awareAt, NOW, "became aware = when Darknode alerted, until corrected"); + assert.deepEqual(r.add.map((d) => d.id), ["cra:" + LOG4J + ":early", "cra:" + LOG4J + ":notify", "cra:" + LOG4J + ":final"]); + const [early, notify, fin] = r.add; + assert.equal(early.dueAt, NOW + 24 * HOUR); assert.equal(notify.dueAt, NOW + 72 * HOUR); assert.equal(fin.dueAt, null); + assert.ok(r.add.every((d) => d.kind === "cra-exploited" && d.status === "open" && d.monitorId === "m1")); + }); + test("no opt-in, no clocks; before 11 September 2026, no clocks", () => { + assert.deepEqual(run({ settings: { cra: false, shipped: SHIPPED } }), { add: [], cases: [] }); + assert.deepEqual(run({ at: Date.UTC(2026, 7, 1) }), { add: [], cases: [] }); + }); + test("nothing marked as shipped, no clocks; a match by name works without the graph id", () => { + assert.equal(run({ settings: { cra: true, shipped: [] } }).add.length, 0); + assert.equal(run({ settings: { cra: true, shipped: [{ name: "LOG4J-CORE@2.14.1" }] } }).cases.length, 1); + assert.equal(run({ settings: { cra: true, shipped: [{ type: "SOFTWARE", name: "log4j-core@2.14.1" }] } }).cases.length, 1, "the finding's affected-asset list has no type, so the name decides"); + }); + test("only a kev event starts it: a finding without an event, or an EPSS-only match, does not", () => { + assert.equal(run({ events: [] }).add.length, 0); + const epss = { key: "epss:" + LOG4J, cve: LOG4J, kev: false, epss: 0.97 }; + assert.equal(run({ events: [{ kind: "kev", key: epss.key }], findings: [epss] }).add.length, 0); + assert.equal(run({ events: [{ kind: "new", key: "kev:" + LOG4J }] }).add.length, 0, "only the kev kind"); + }); + test("an existing case is never re-created, whatever its status", () => { + assert.equal(run({ cases: { [LOG4J]: { cve: LOG4J } } }).add.length, 0); + }); + test("BOD 22-01 opt-in: a kev-due deadline for every matched KEV CVE, due on the catalogue date", () => { + const r = run({ settings: { bod2201: true } }); + assert.deepEqual(r.add.map((d) => d.id), ["kev-due:" + LOG4J, "kev-due:" + CITRIX]); + assert.equal(r.add[0].dueAt, Date.UTC(2021, 11, 24, 23, 59, 59)); + assert.equal(r.cases.length, 0, "BOD alone starts no CRA clock"); + assert.equal(run({ settings: { bod2201: true }, existing: { ["kev-due:" + LOG4J]: {} } }).add.length, 1); + }); + test("shippedMatches follows relationships both ways and a finding's affected assets", () => { + assert.deepEqual(shippedMatches(LOG4J, INVENTORY, SHIPPED), SHIPPED); + assert.deepEqual(shippedMatches(CITRIX, INVENTORY, SHIPPED), []); + const reverse = { entities: INVENTORY.entities, relationships: [{ fromId: "a1", toId: "f1", type: "related_to" }] }; + assert.deepEqual(shippedMatches(LOG4J, { ...reverse, entities: reverse.entities.map((e) => (e.id === "f1" ? { ...e, data: {} } : e)) }, SHIPPED), SHIPPED); + assert.deepEqual(shippedMatches("not a cve", INVENTORY, SHIPPED), []); + }); +}); + +group("deadlines/certificates", () => { + const f = (domain, notAfter) => ({ key: "cert:" + domain, domain, notAfter, daysToExpiry: 10 }); + test("due when the certificate expires; started when the monitor first saw it; the monitor's alert is the created alert", () => { + const na = new Date(NOW + 10 * DAY).toISOString(); + const r = certDeadlines({ findings: [f("example.com", na)], monitorId: "m1", firstSeen: { "cert:example.com": NOW - DAY }, alerted: new Set(["cert:example.com"]), at: NOW }); + assert.equal(r.add.length, 1); + const d = r.add[0]; + assert.equal(d.id, "cert:example.com:" + na.slice(0, 10)); + assert.equal(d.dueAt, Date.parse(na)); assert.equal(d.startedAt, NOW - DAY); + assert.deepEqual(d.alerts.created, { at: NOW, via: "monitor", sent: true }); + assert.deepEqual(dueAlerts([d], NOW), [], "no second created alert"); + }); + test("closes as done when the monitor no longer sees it, or when the domain leaves the watch", () => { + const d = { id: "cert:example.com:2026-12-05", kind: "cert-expiry", status: "open", monitorId: "m1", subject: { value: "example.com" } }; + assert.equal(certDeadlines({ findings: [], existing: { [d.id]: d }, monitorId: "m1", watched: new Set(["example.com"]), at: NOW }).close[0].status, "done"); + assert.ok(/no longer in this watch/.test(certDeadlines({ findings: [], existing: { [d.id]: d }, monitorId: "m1", watched: new Set(), at: NOW }).close[0].reason)); + assert.equal(certDeadlines({ findings: [], existing: { [d.id]: d }, monitorId: "other", at: NOW }).close.length, 0, "another monitor's run leaves it alone"); + }); +}); + +group("deadlines/alert schedule", () => { + const d0 = (over = {}) => ({ id: "x", status: "open", startedAt: NOW, dueAt: NOW + 24 * HOUR, alerts: {}, ...over }); + test("created once the clock starts, then once when a quarter of the time is left", () => { + assert.deepEqual(dueAlerts([d0()], NOW), [{ id: "x", stage: "created" }]); + const sent = d0({ alerts: { created: { at: NOW } } }); + assert.deepEqual(dueAlerts([sent], NOW + 17 * HOUR), []); + assert.deepEqual(dueAlerts([sent], NOW + 18 * HOUR), [{ id: "x", stage: "quarter" }]); + assert.deepEqual(dueAlerts([d0({ alerts: { created: { at: NOW }, quarter: { at: NOW } } })], NOW + 20 * HOUR), []); + assert.equal(nextAlertAt([sent], NOW), NOW + 18 * HOUR); + }); + test("a quarter point already past its deadline is skipped; closed and waiting clocks are silent", () => { + assert.deepEqual(dueAlerts([d0({ alerts: { created: { at: NOW } } })], NOW + 25 * HOUR), [{ id: "x", stage: "skip" }]); + assert.deepEqual(dueAlerts([d0({ status: "done" }), d0({ dueAt: null })], NOW), []); + assert.equal(nextAlertAt([d0({ status: "dismissed" })], NOW), null); + }); + test("an alert held by quiet hours waits until they end", () => { + const held = d0({ alerts: { holdUntil: NOW + 3 * HOUR } }); + assert.deepEqual(dueAlerts([held], NOW), []); + assert.equal(nextAlertAt([held], NOW), NOW + 3 * HOUR); + assert.deepEqual(dueAlerts([held], NOW + 3 * HOUR), [{ id: "x", stage: "created" }]); + }); + test("alert lines quote Article 14(2) for CRA clocks and say how long is left", () => { + const [early] = craDeadlines(craCase({ cve: LOG4J, assets: SHIPPED, kevDateAdded: "2021-12-10", alertedAt: NOW, monitorId: "m1" }), NOW); + const l = alertLine(early, "quarter", NOW + 18 * HOUR); + assert.ok(l.title.startsWith("CRA early warning: " + LOG4J)); + assert.ok(l.detail.includes("6h 0m left") && l.detail.includes("within 24 hours")); + assert.ok(stepsOf(early).some((s) => /ENISA/.test(s))); + assert.equal(sourceOf(early).url, "https://eur-lex.europa.eu/eli/reg/2024/2847/oj/eng"); + }); +}); + +group("deadlines/edits and facts", () => { + const c0 = () => craCase({ cve: LOG4J, assets: SHIPPED, kevDateAdded: "2021-12-10", alertedAt: NOW, monitorId: "m1" }); + test("correcting the became-aware time moves the 24 h and 72 h clocks; marking the fix starts the final one", () => { + const c = c0(), existing = Object.fromEntries(craDeadlines(c, NOW).map((d) => [d.id, d])); + const r = updateCase(c, { awareAt: NOW - 6 * HOUR }, NOW); + const moved = syncCaseClocks(r.case, existing); + assert.deepEqual(moved.map((d) => [d.clock, d.dueAt]), [["early", NOW + 18 * HOUR], ["notify", NOW + 66 * HOUR]]); + const fix = syncCaseClocks(updateCase(r.case, { fixAt: NOW }, NOW).case, existing); + assert.deepEqual(fix.map((d) => d.clock), ["early", "notify", "final"]); + assert.equal(fix[2].startedAt, NOW); assert.equal(fix[2].dueAt, NOW + 14 * DAY); + }); + test("case edits are checked: no future times, a known Member State, a bounded text", () => { + assert.ok(updateCase(c0(), { awareAt: NOW + HOUR }, NOW).error); + assert.ok(updateCase(c0(), { awareAt: NOW - 400 * DAY }, NOW).error); + assert.ok(updateCase(c0(), { fixAt: NOW + DAY }, NOW).error); + assert.ok(updateCase(c0(), { memberStates: "DE, Atlantis" }, NOW).error.includes("Atlantis")); + assert.ok(updateCase(c0(), { measures: "x".repeat(2001) }, NOW).error); + assert.equal(updateCase(c0(), { fixAt: null }, NOW).case.fixAt, null); + }); + test("done or dismissed needs a reason; reopening clears it", () => { + const d = { id: "x", status: "open" }; + assert.ok(closeDeadline(d, { status: "done", reason: " ", at: NOW }).error); + assert.ok(closeDeadline(d, { status: "closed", reason: "x", at: NOW }).error); + const r = closeDeadline(d, { status: "dismissed", reason: "Not in the EU build", by: "u1", at: NOW }); + assert.deepEqual([r.deadline.status, r.deadline.reason, r.deadline.closedBy], ["dismissed", "Not in the EU build", "u1"]); + assert.equal(reopenDeadline(r.deadline).deadline.status, "open"); + }); + test("the early-warning facts list what is known and say what is not", () => { + const c = { ...c0(), awareAt: NOW - 2 * HOUR, memberStates: ["DE", "FR"], measures: "Upgrade log4j-core to 2.17.1." }; + const f = craFacts(c, {}, NOW); + const row = (l) => (f.rows.find((r) => r[0] === l) || [])[1]; + assert.equal(row("Vulnerability"), LOG4J); + assert.equal(row("Product or asset"), "log4j-core@2.14.1"); + assert.ok(row("Exploitation confirmed").includes("2021-12-10")); + assert.ok(row("Became aware").startsWith("2026-11-25 07:30 UTC") && row("Became aware").includes("Darknode alerted 2026-11-25 09:30 UTC")); + assert.equal(row("Member States where the product is made available"), "Germany (DE), France (FR)"); + assert.equal(row("Corrective or mitigating measures known"), "Upgrade log4j-core to 2.17.1."); + assert.equal(row("Early warning due"), "2026-11-26 07:30 UTC"); + assert.ok(row("CISA KEV catalogue").startsWith("https://www.cisa.gov/known-exploited-vulnerabilities-catalog")); + assert.equal(row("NVD"), "https://nvd.nist.gov/vuln/detail/" + LOG4J); + assert.ok(f.text.includes("does not submit anything")); + const empty = craFacts(c0(), {}, NOW); + assert.equal(empty.rows.find((r) => r[0] === "Member States where the product is made available")[1], "Not entered yet"); + assert.equal(empty.rows.find((r) => r[0] === "Fix or mitigation available")[1], "Not marked yet"); + assert.notOk(/[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}]/u.test(f.text), "no emojis"); + }); +}); + +// ---- in the MonitorDO --------------------------------------------------------------------------- + +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 list({ prefix = "" } = {}) { return new Map([...map].filter(([k]) => k.startsWith(prefix))); }, + async setAlarm(ts) { alarm = ts; }, + async getAlarm() { return alarm; }, + }; + return { storage, blockConcurrencyWhile: async (fn) => fn(), _map: map, alarm: () => alarm }; +} +const graphEnv = (extra = {}) => ({ RESEND_KEY: "re_test_only", DIGEST_SECRET: "unit-test-secret", ...extra, GRAPH: { idFromName: (n) => n, get: () => ({ fetch: async () => ({ ok: true, status: 200, json: async () => INVENTORY }) }) } }); +async function post(mon, body, { free = false, role = "owner" } = {}) { + const headers = { "content-type": "application/json", "x-mon-uid": "u1", "x-mon-role": role, "x-mon-wid": "u1", "x-mon-email": encodeURIComponent(ME) }; + if (free) headers["x-mon-plan"] = "free"; + const res = await mon.fetch(new Request("https://monitor/", { method: "POST", body: JSON.stringify(body), headers })); + return { status: res.status, json: await res.json() }; +} +function kevNet() { + const hooks = [], emails = []; + const fetch = async (url, opts = {}) => { + url = String(url); + if (url.includes("cisa-kev-index")) return { ok: true, status: 200, json: async () => ({ data: [{ cve: LOG4J, dueDate: "2021-12-24", dateAdded: "2021-12-10" }, { cve: CITRIX, dueDate: "2023-11-08", dateAdded: "2023-10-18" }] }) }; + if (url.includes("epss-top")) return { ok: true, status: 200, json: async () => ({ data: [] }) }; + if (url.includes("crt.sh")) return { ok: true, status: 200, json: async () => [{ issuer_name: "C=US, O=Example CA", not_after: new Date(NOW + 10 * DAY).toISOString(), not_before: new Date(NOW - 80 * DAY).toISOString(), name_value: "example.com" }] }; + if (url.includes("certspotter")) return { ok: false, status: 404, json: async () => null }; + if (url === "https://api.resend.com/emails") { emails.push(JSON.parse(opts.body)); return { ok: true, status: 200, json: async () => ({ id: "e" + emails.length }) }; } + hooks.push({ url, body: opts.body }); return { ok: true, status: 200 }; + }; + return { fetch, hooks, emails }; +} +const quick = (n, extra = {}) => ({ force: true, fetch: n.fetch, sleep: async () => {}, now: NOW, ...extra }); +const kevMonitor = (channels) => ({ op: "upsert", monitor: { name: "KEV", type: "kev-epss", config: {}, channels } }); + +group("deadlines/MonitorDO", () => { + test("a KEV run with the CRA opt-in stores the case and three clocks, and alerts the case once", async () => { + const st = memState(), mon = new MonitorDO(st, graphEnv()); + assert.equal((await post(mon, { op: "dlSettings", settings: { cra: true, shipped: SHIPPED } })).status, 200); + await post(mon, kevMonitor([{ type: "webhook", url: "https://hook.test/x" }])); + const n = kevNet(); + const r = await mon.runDue(quick(n)); + assert.equal(r.ran[0].found, 2); + const list = (await post(mon, { op: "deadlines" })).json; + assert.deepEqual(list.deadlines.map((d) => d.id), ["cra:" + LOG4J + ":early", "cra:" + LOG4J + ":notify", "cra:" + LOG4J + ":final"]); + assert.equal(list.cases.length, 1); assert.equal(list.cases[0].kevDateAdded, "2021-12-10"); + assert.equal(n.hooks.length, 2, "the monitor's KEV alert and one CRA alert for the case"); + const cra = JSON.parse(n.hooks[1].body).alert; + assert.equal(cra.severity, "critical"); + assert.equal(cra.deadline.items.length, 2, "early warning and notification in one alert; the final clock has not started"); + assert.ok(/single reporting platform/.test(cra.text) && /does not submit anything/.test(cra.text)); + await mon.runDue(quick(n, { now: NOW + HOUR })); + assert.equal(n.hooks.length, 2, "nothing new an hour later"); + await mon.runDue(quick(n, { now: NOW + 18 * HOUR })); + assert.equal(n.hooks.length, 3, "18 h in: a quarter of the early warning's 24 h is left"); + assert.ok(/early warning/i.test(n.hooks[2].body)); + assert.ok(st.alarm() != null, "the next reminder is scheduled"); + }); + test("without the opt-in a KEV run starts no clock", async () => { + const st = memState(), mon = new MonitorDO(st, graphEnv()); + await post(mon, { op: "dlSettings", settings: { cra: false, shipped: SHIPPED } }); + await post(mon, kevMonitor([{ type: "webhook", url: "https://hook.test/x" }])); + const n = kevNet(); + await mon.runDue(quick(n)); + assert.equal((await post(mon, { op: "deadlines" })).json.deadlines.length, 0); + assert.equal(n.hooks.length, 1, "the monitor's own alert only"); + }); + test("settings: below Pro the opt-ins cannot be turned on (402); viewers cannot change them", async () => { + const st = memState(), mon = new MonitorDO(st, graphEnv()); + const r = await post(mon, { op: "dlSettings", settings: { cra: true } }, { free: true }); + assert.equal(r.status, 402); assert.equal(r.json.plan, true); + assert.equal((await post(mon, { op: "dlSettings", settings: { cra: false, shipped: SHIPPED } }, { free: true })).status, 200); + assert.equal((await post(mon, { op: "dlSettings", settings: { cra: true } }, { role: "viewer" })).status, 403); + assert.equal((await post(mon, { op: "deadlines" }, { role: "viewer" })).status, 200, "viewers can see deadlines"); + }); + test("case edits move the clocks; done and dismiss need a reason", async () => { + const st = memState(), mon = new MonitorDO(st, graphEnv()); + await post(mon, { op: "dlSettings", settings: { cra: true, shipped: SHIPPED } }); + await post(mon, kevMonitor([])); + await mon.runDue(quick(kevNet())); + const fixAt = Date.now() - HOUR; + const r = await post(mon, { op: "dlCase", cve: LOG4J, patch: { fixAt, memberStates: "DE, FR", measures: "Upgrade to 2.17.1" } }); + assert.equal(r.status, 200); + const fin = (await post(mon, { op: "deadlines" })).json.deadlines.find((d) => d.clock === "final"); + assert.equal(fin.dueAt, fixAt + 14 * DAY); + assert.equal((await post(mon, { op: "dlCase", cve: LOG4J, patch: { memberStates: "Atlantis" } })).status, 400); + assert.equal((await post(mon, { op: "dlCase", cve: "CVE-2000-0001", patch: {} })).status, 404); + const id = "cra:" + LOG4J + ":early"; + assert.equal((await post(mon, { op: "dlClose", id, status: "done", reason: "" })).status, 400); + const done = await post(mon, { op: "dlClose", id, status: "done", reason: "Submitted, reference ENISA-123" }); + assert.equal(done.json.deadline.status, "done"); assert.equal(done.json.deadline.closedBy, "u1"); + assert.equal((await post(mon, { op: "dlReopen", id })).json.deadline.status, "open"); + }); + test("cap: CRA alerts use their own allowance, so a used-up monitor allowance does not hold them back", async () => { + const st = memState(), mon = new MonitorDO(st, graphEnv()); + await post(mon, { op: "dlSettings", settings: { cra: true, shipped: SHIPPED } }); + await post(mon, kevMonitor([{ type: "email" }])); + const n = kevNet(), keys = []; + const emailQuota = async (key, limit) => { keys.push([key, limit]); return key.startsWith("alert-email:") ? { ok: false, used: limit, limit } : { ok: true, used: 1, limit }; }; + await mon.runDue(quick(n, { emailQuota })); + assert.deepEqual(keys, [["alert-email:u1", ALERT_EMAILS_PER_DAY], ["deadline-email:u1", CRA_EMAILS_PER_DAY]]); + assert.equal(n.emails.length, 1, "the CRA email went out while the monitor's own alert was capped"); + assert.ok(n.emails[0].subject.includes("CRA early warning")); + assert.ok(n.emails[0].text.includes("single reporting platform") && n.emails[0].text.includes("does not submit anything")); + const log = st._map.get("deliveries"); + assert.ok(log.some((d) => !d.ok && /Daily alert email limit/.test(d.error)), "the capped monitor alert is in the delivery log"); + }); + test("cap: a certificate reminder shares the monitor allowance and is logged when it is used up", async () => { + const st = memState(), mon = new MonitorDO(st, graphEnv()); + await post(mon, { op: "upsert", monitor: { name: "Watch example.com", type: "cert-expiry", config: { domains: ["example.com"], warnDays: 21 }, channels: [{ type: "email" }] } }); + const n = kevNet(); + await mon.runDue(quick(n, { emailQuota: async (k, l) => ({ ok: true, used: 1, limit: l }) })); + assert.equal(n.emails.length, 1, "the monitor's alert is the deadline's created alert: one email"); + const keys = []; + await mon.runDue(quick(n, { now: NOW + 7.6 * DAY, emailQuota: async (k, l) => { keys.push(k); return { ok: false, used: l, limit: l }; } })); + assert.deepEqual(keys, ["alert-email:u1"]); + assert.equal(n.emails.length, 1); + const dl = (await post(mon, { op: "deadlines" })).json.deadlines[0]; + assert.equal(dl.alerts.quarter.sent, false, "tried once, not retried every alarm"); + }); + test("deleting a monitor dismisses its open certificate deadlines", async () => { + const st = memState(), mon = new MonitorDO(st, graphEnv()); + const m = (await post(mon, { op: "upsert", monitor: { name: "C", type: "cert-expiry", config: { domains: ["example.com"] }, channels: [] } })).json.monitor; + await mon.runDue(quick(kevNet())); + assert.equal((await post(mon, { op: "deadlines" })).json.deadlines[0].status, "open"); + await post(mon, { op: "delete", id: m.id }); + const d = (await post(mon, { op: "deadlines" })).json.deadlines[0]; + assert.equal(d.status, "dismissed"); assert.ok(/monitor was deleted/.test(d.reason)); + }); +}); + +group("deadlines/route and email", () => { + test("deadline settings below Pro go on marked free (the DO refuses only turning an opt-in on)", async () => { + const calls = []; + const MONITOR = { idFromName: (x) => x, get: () => ({ fetch: async (u, init) => { calls.push(init); return new Response("{}", { status: 200 }); } }) }; + const real = globalThis.fetch; globalThis.fetch = async () => ({ ok: false, status: 404, json: async () => ({}) }); + try { + for (const claims of [{ email_verified: true }, { email_verified: true, plan: "pro" }]) { + _resetPlanCache(); + const req = new Request("https://w.test/x", { method: "POST", body: JSON.stringify({ op: "dlSettings", settings: { cra: true } }) }); + attachPrincipal(req, { kind: "user", uid: "u1", email: ME, token: "tok", claims }); + await handleMonitor(req, { FIREBASE_PROJECT_ID: "p1", MONITOR }, "u1", (b, status = 200) => ({ status, body: b })); + } + } finally { globalThis.fetch = real; } + assert.equal(calls[0].headers["x-mon-plan"], "free"); + assert.equal(calls[1].headers["x-mon-plan"], undefined); + }); + test("the deadline email: what is due, where to file, the disclaimer, no emojis", () => { + const [early] = craDeadlines(craCase({ cve: LOG4J, assets: SHIPPED, kevDateAdded: "2021-12-10", alertedAt: NOW, monitorId: "m1" }), NOW); + const m = buildDeadlineEmail({ items: [{ ...alertLine(early, "created", NOW), kind: early.kind, stage: "created" }], cra: true, monitor: { name: "KEV" }, notes: [CRA.where], sent: 1, limit: CRA_EMAILS_PER_DAY, now: NOW }); + assert.ok(m.subject.startsWith("New deadline: CRA early warning: " + LOG4J)); + assert.ok(m.text.includes("Due 2026-11-26 09:30 UTC (1d 0h left)")); + assert.ok(m.text.includes("https://darknode.ai/deadlines") && m.html.includes("Open Deadlines in the Deck")); + assert.notOk(/[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}]/u.test(m.subject + m.text + m.html), "no emojis"); + }); +}); diff --git a/test/worker/monitor-do.test.mjs b/test/worker/monitor-do.test.mjs index 2f589f09..b3e10e36 100644 --- a/test/worker/monitor-do.test.mjs +++ b/test/worker/monitor-do.test.mjs @@ -12,6 +12,7 @@ function memState() { async delete(k) { map.delete(k); }, async setAlarm(ts) { alarm = ts; }, async getAlarm() { return alarm; }, + async list({ prefix = "" } = {}) { return new Map([...map].filter(([k]) => k.startsWith(prefix)).sort(([a], [b]) => a.localeCompare(b))); }, _alarm: () => alarm, }; return { storage, blockConcurrencyWhile: async (fn) => fn(), _map: map }; @@ -89,7 +90,7 @@ group("monitor DO/run + alert", () => { assert.equal(net.deliveries.length, 1, "no duplicate alert on an unchanged cert"); }); - test("a day later the same expiring cert does not alert again; crossing into the last week does", async () => { + test("a day later the same expiring cert does not alert again; the deadline reminds once when a quarter of the time is left", async () => { const st = memState(); const mon = new MonitorDO(st); await post(mon, { op: "upsert", monitor: { name: "Certs", type: "cert-expiry", config: { domains: ["a.test.darknode.ai"], warnDays: 21 }, channels: [{ type: "webhook", url: "https://hook.test/x" }] } }); const base = Date.now(), D = 86400000; @@ -98,7 +99,12 @@ group("monitor DO/run + alert", () => { await mon.runDue({ force: true, fetch: net.fetch, sleep: async () => {}, now: base + D }); assert.equal(net.deliveries.length, 1, "expires in 10 days -> 9 days is only a title change"); await mon.runDue({ force: true, fetch: net.fetch, sleep: async () => {}, now: base + 4 * D }); - assert.equal(net.deliveries.length, 2, "high -> critical at 6 days alerts"); + assert.equal(net.deliveries.length, 1, "high -> critical at 6 days is folded into the deadline: no second alert"); + await mon.runDue({ force: true, fetch: net.fetch, sleep: async () => {}, now: base + 7.6 * D }); + assert.equal(net.deliveries.length, 2, "2.4 days left of 10: the quarter-left reminder"); + assert.ok(/quarter of the time is left/i.test(net.deliveries[1].body), "the reminder says why it came"); + await mon.runDue({ force: true, fetch: net.fetch, sleep: async () => {}, now: base + 8 * D }); + assert.equal(net.deliveries.length, 2, "the reminder is sent once"); }); test("a run where the certificate logs do not answer keeps the finding open, and it does not re-alert when they are back", async () => { diff --git a/worker/alert-email.js b/worker/alert-email.js index 12d2ee02..9a526861 100644 --- a/worker/alert-email.js +++ b/worker/alert-email.js @@ -114,7 +114,7 @@ const pill = (txt, warn) => `${esc(title)}
    ${esc(preheader)}
    @@ -124,7 +124,7 @@ function shell({ title, preheader, date, body, footer }) { ${body} - +
    Open Monitors in the Deck
    ${esc(cta.label)}
    ${footer} `; @@ -194,6 +194,50 @@ export function buildTestEmail({ stopUrl = "", sent = 0, limit = ALERT_EMAILS_PE return { subject, text, html: shell({ title: subject, preheader: lines[0], date: new Date(now).toISOString().slice(0, 10), body, footer }) }; } +// ---- deadline alerts (public/js/core/deadlines.js) -------------------------------------------- +// A deadline alert goes out when a deadline is created and when a quarter of its time is left. +// Cyber Resilience Act alerts do not count against ALERT_EMAILS_PER_DAY: a busy day of monitor +// alerts must not hold back a 24-hour legal clock. They have their own daily limit instead, so a +// fault still cannot flood anyone. +export const CRA_EMAILS_PER_DAY = 20; +export const DECK_DEADLINES = SITE + "/deadlines"; + +/** + * items: [{ title, detail, kind, stage }] (alertLine output plus the deadline's kind and stage); + * cra: true for Cyber Resilience Act clocks (adds where to file and the disclaimer); + * monitor: the monitor that found it; sent / limit: this email's number today and its cap. + * -> { subject, text, html } + */ +export function buildDeadlineEmail({ items = [], cra = false, monitor = {}, stopUrl = "", sent = 0, limit = ALERT_EMAILS_PER_DAY, now = Date.now(), notes = [] } = {}) { + const one = items.length === 1 ? items[0] : null; + const allNew = items.length > 0 && items.every((it) => it.stage !== "quarter"); + const subject = one ? (one.stage === "quarter" ? "A quarter of the time is left: " : "New deadline: ") + one.title + : items.length ? (allNew ? "New deadlines: " : "Deadlines need attention: ") + items[0].title + " and " + (items.length - 1) + " more" : "Deadlines need attention"; + const heading = one ? (one.stage === "quarter" ? "A quarter of the time is left" : "A new deadline started") : allNew ? items.length + " new deadlines started" : items.length + " deadlines need attention"; + const name = clip(monitor.name || monitor.type || "Monitor", 80); + const reason = `You get this because the monitor "${name}" emails your account address, and Darknode keeps the deadlines it finds under Deadlines in the Deck.`; + const capped = sent >= limit; + const capLine = `This is deadline email ${sent} of ${limit} today, the daily limit. Further deadline alerts today are listed in the Deck under Deadlines and are not emailed.`; + const t = [heading, ""]; + items.forEach((it, i) => { t.push((items.length > 1 ? i + 1 + ". " : "") + it.title); if (it.detail) t.push(it.detail); t.push(""); }); + for (const n of notes) t.push(n); + if (notes.length) t.push(""); + t.push("Open Deadlines in the Deck: " + DECK_DEADLINES, "", "--", reason); + if (capped) t.push(capLine); + if (stopUrl) t.push("Stop these alerts: " + stopUrl); + t.push("To stop them in the Deck: Monitors, then Pause on \"" + name + "\"."); + const rows = items.map((it, i) => ` +
    ${esc(it.title)}
    +${it.detail ? `
    ${esc(it.detail)}
    ` : ""}`).join(""); + const noteRows = notes.map((n) => `${esc(n)}`).join(""); + const body = `${esc(heading)}${rows}${noteRows}`; + const footer = esc(reason) + (capped ? "
    " + esc(capLine) : "") + "
    " + + (stopUrl ? `Stop these alerts · ` : "") + + `Deadlines · darknode.ai`; + const html = shell({ title: subject, preheader: one ? one.detail || heading : heading, date: new Date(now).toISOString().slice(0, 10), body, footer, cta: { label: "Open Deadlines in the Deck", url: DECK_DEADLINES } }); + return { subject: cra && !/Cyber Resilience Act|CRA/.test(subject) ? "CRA: " + subject : subject, text: t.join("\n"), html }; +} + // ---- the stop link ---------------------------------------------------------------------------- const enc = new TextEncoder(); diff --git a/worker/checks.js b/worker/checks.js index 6d16e322..a022f131 100644 --- a/worker/checks.js +++ b/worker/checks.js @@ -138,7 +138,7 @@ export function matchKevEpss(cves, ctx = {}) { const score = epss.get(cve); if (kev.has(cve)) { const info = kev.get(cve) || {}; - out.push({ key: "kev:" + cve, severity: "critical", status: "open", title: `Known-exploited vulnerability in your inventory: ${cve}`, cve, kev: true, dueDate: info.dueDate || "", epss: typeof score === "number" ? score : null, category: "vulnerability", tool: "monitor:kev-epss" }); + out.push({ key: "kev:" + cve, severity: "critical", status: "open", title: `Known-exploited vulnerability in your inventory: ${cve}`, cve, kev: true, dueDate: info.dueDate || "", dateAdded: info.dateAdded || "", epss: typeof score === "number" ? score : null, category: "vulnerability", tool: "monitor:kev-epss" }); } else if (typeof score === "number" && score >= floor) { out.push({ key: "epss:" + cve, severity: score >= 0.9 ? "high" : "medium", status: "open", title: `High exploit-likelihood vulnerability in your inventory: ${cve} (EPSS ${Math.round(score * 100)}%)`, cve, kev: false, epss: score, category: "vulnerability", tool: "monitor:kev-epss" }); } diff --git a/worker/monitor.js b/worker/monitor.js index 42490827..d95ba026 100644 --- a/worker/monitor.js +++ b/worker/monitor.js @@ -5,9 +5,12 @@ // Discord / signed webhooks / the account's own email with retry. On the Free plan it runs // the one-domain watch (worker/free-watch.js). State and scheduling are the DO's; the grading // is the SAME pure engine the browser tools use (worker/checks.js), and the alert brain -// is worker/monitor-core.js — both unit-tested without a deploy. +// is worker/monitor-core.js — both unit-tested without a deploy. The deadlines a run finds +// (certificate expiry, and with the workspace's opt-ins Cyber Resilience Act and BOD 22-01 +// 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 { diffFindings, diffToEvents, shouldAlert, defaultAlertRules } from "./monitor-core.js"; +import { diffFindings, diffToEvents, shouldAlert, defaultAlertRules, inQuietHours } from "./monitor-core.js"; import { buildGraphWrite } from "./monitor-graph.js"; import { deliver, RETRY_BACKOFF_MS } from "./notify.js"; import { requireUser } from "./auth.js"; @@ -16,8 +19,9 @@ import { featureDenied } from "./plan.js"; import { workspaceTier, liveTier } from "./plan-share.js"; import { readCapped } from "./body-cap.js"; import { FREE_WATCH, FREE_TEAM_MSG, freeWatchDenied, freeAllowed } from "./free-watch.js"; -import { ALERT_EMAILS_PER_DAY, buildAlertEmail, buildTestEmail, maskEmail, recipient, sendEmail, stopToken, stopUrl, STOP_PATH } from "./alert-email.js"; +import { ALERT_EMAILS_PER_DAY, CRA_EMAILS_PER_DAY, DECK_DEADLINES, buildAlertEmail, buildDeadlineEmail, buildTestEmail, maskEmail, recipient, sendEmail, stopToken, stopUrl, STOP_PATH } from "./alert-email.js"; import { unsubSecret } from "./digest.js"; +import { normSettings, checkSettings, kevDeadlines, certDeadlines, closeDeadline, reopenDeadline, updateCase, syncCaseClocks, dueAlerts, nextAlertAt, quarterAt, alertLine, sortDeadlines, CRA, DAY as DL_DAY } from "../public/js/core/deadlines.js"; import { takeDaily } from "./quota.js"; const WID = /^[A-Za-z0-9_-]{1,128}$/; @@ -25,6 +29,9 @@ const HISTORY_CAP = 200, DELIVERY_CAP = 200; const MIN_INTERVAL = 15 * 60 * 1000; // never run a monitor more than every 15 min const now = () => Date.now(); const uid = () => "m_" + Math.random().toString(36).slice(2, 10) + now().toString(36); +const CLOSED_KEEP_MS = 180 * DL_DAY; // a closed certificate or BOD deadline is dropped after 180 days (CRA records stay) +// the first top of an hour outside the monitor's quiet hours (a deadline alert held by them waits until then) +const quietEnd = (t, rules) => { let x = Math.ceil((t + 1) / 3600000) * 3600000; for (let i = 0; i < 25 && inQuietHours(x, rules); i++) x += 3600000; return x; }; // Redact channel secrets before anything leaves the DO. // A Slack/Discord/Teams webhook URL is itself the credential: viewers see only its host. @@ -81,10 +88,14 @@ export class MonitorDO { // per workspace, and it reads the SAME workspace's graph (the GET pull is not uid-scoped — // the per-workspace DO is itself the access boundary, reachable only by server code). Used // only by the kev-epss check. Returns [] if the graph binding or the stored wid is missing. - async _graphCves() { + async _graphCves() { const inv = await this._graphInventory(); return inv && cvesFromEntities(inv.entities); } + // The workspace graph's entities and relationships, without the monitor's own writes: + // { entities, relationships } | null (could not read it). The relationships tell the deadline + // code which assets a CVE is in (public/js/core/deadlines.js shippedMatches). + async _graphInventory() { try { const wid = await this.storage.get("wid"); - if (!wid || !this.env || !this.env.GRAPH) return []; + if (!wid || !this.env || !this.env.GRAPH) return { entities: [], relationships: [] }; const stub = this.env.GRAPH.get(this.env.GRAPH.idFromName(wid)); const res = await stub.fetch("https://graph/?since=0", { headers: { "x-graph-uid": wid } }); if (!res.ok) return null; // could not read the inventory: not the same as an empty one @@ -95,10 +106,108 @@ export class MonitorDO { // inventory would be a feedback loop — a patched CVE would never clear because the // monitor keeps seeing the node it authored last run. Only genuine tool/ingest sources // count as the workspace's real CVE inventory. - const inventory = ((data && data.entities) || []).filter((e) => !String((e && e.source) || "").startsWith("monitor:")); - return cvesFromEntities(inventory); + const entities = ((data && data.entities) || []).filter((e) => !String((e && e.source) || "").startsWith("monitor:")); + const ids = new Set(entities.map((e) => e && e.id)); + const relationships = ((data && data.relationships) || []).filter((r) => r && ids.has(r.fromId) && ids.has(r.toId)); + return { entities, relationships }; } catch (_) { return null; } } + + // ---- deadlines: one key per record, so no single value nears the storage size limit ---- + async _list(prefix) { + const out = Object.create(null); + if (typeof this.storage.list !== "function") return out; + for (const [k, v] of await this.storage.list({ prefix })) out[k.slice(prefix.length)] = v; + return out; + } + _deadlines() { return this._list("dl:"); } + _cases() { return this._list("cra:"); } + async _dlSettings() { return normSettings(await this.storage.get("dlSettings")); } + async _putDeadlines(list) { for (const d of list) await this.storage.put("dl:" + d.id, d); } + + // The deadlines one run found: certificate expiry from a cert-expiry run; CRA and BOD 22-01 + // clocks from a kev-epss run, only with the workspace's opt-ins. Never throws. + async _deadlinesFromRun(m, { findings, events, alerted, inventory, at }) { + try { + if (m.type === "cert-expiry") { + const existing = await this._deadlines(); + const firstSeen = {}; for (const [k, v] of Object.entries(m.graphMeta || {})) if (v && v.firstSeen) firstSeen[k] = v.firstSeen; + const watched = new Set(((m.config && m.config.domains) || []).map(hostOnly).filter(Boolean)); + const r = certDeadlines({ findings, existing, monitorId: m.id, firstSeen, alerted: new Set(alerted.map((e) => e.key)), watched, at }); + const closed = r.close.map((c) => ({ ...existing[c.id], status: c.status, reason: c.reason, closedAt: at, closedBy: "monitor" })); + await this._putDeadlines([...r.add, ...closed]); + return r.add.length; + } + if (m.type === "kev-epss" && inventory) { + const settings = await this._dlSettings(); + if (!settings.cra && !settings.bod2201) return 0; // nothing assumed: no opt-in, no clocks + const r = kevDeadlines({ events, findings, settings, inventory, existing: await this._deadlines(), cases: await this._cases(), monitorId: m.id, at }); + for (const c of r.cases) await this.storage.put("cra:" + c.cve, c); + await this._putDeadlines(r.add); + return r.add.length; + } + } catch (_) {} + return 0; + } + + // Send the deadline alerts that are due: a "created" alert once a clock starts and a "quarter" + // alert when 25% of its time is left (dueAlerts). They go to the channels of the monitor that + // found the deadline; a deadline whose monitor is gone, paused or held for the plan stays in + // the Deck and is not sent. CRA alerts ignore digest mode and quiet hours (a 24-hour clock does + // not wait for the morning) and have their own email allowance (CRA_EMAILS_PER_DAY); the rest + // follow the monitor's rules and share its ALERT_EMAILS_PER_DAY. + async _deadlinePass(deps = {}, monsIn) { + const t0 = Number.isFinite(deps.now) ? deps.now : now(); + let sent = 0; + try { + const dls = await this._deadlines(); + // closed certificate and BOD records older than CLOSED_KEEP_MS are dropped (CRA records stay) + for (const d of Object.values(dls)) if (d.kind !== "cra-exploited" && d.status !== "open" && d.closedAt && d.closedAt < t0 - CLOSED_KEEP_MS) { await this.storage.delete("dl:" + d.id); delete dls[d.id]; } + const todo = dueAlerts(Object.values(dls), t0); + if (!todo.length) return 0; + const mons = monsIn || await this._monitors(); + const changed = new Map(), groups = new Map(); + const mark = (d, stage, v) => { d.alerts = { ...(d.alerts || {}), [stage]: v }; changed.set(d.id, d); }; + for (const { id, stage } of todo) { + const d = dls[id]; + if (stage === "skip") { mark(d, "quarter", { at: t0, sent: false, why: "already due" }); continue; } + const m = mons[d.monitorId]; + const why = !m ? "its monitor was deleted" : m.paused ? "its monitor is paused" : m.planHeld ? "its monitor is held for the plan" : !(m.channels || []).length ? "its monitor has no alert channel" : ""; + const cra = d.kind === "cra-exploited"; + if (!why && !cra) { + const rules = { ...defaultAlertRules(), ...(m.rules || {}) }; + if (rules.digest) { mark(d, stage, { at: t0, sent: false, why: "digest mode" }); continue; } + if (inQuietHours(t0, rules)) { d.alerts = { ...(d.alerts || {}), holdUntil: quietEnd(t0, rules) }; changed.set(d.id, d); continue; } + } + if (why) { mark(d, stage, { at: t0, sent: false, why }); continue; } + const key = d.monitorId + "|" + (cra ? "cra" : "std"); + if (!groups.has(key)) groups.set(key, { m, cra, items: [] }); + groups.get(key).items.push({ d, stage }); + } + for (const g of groups.values()) { + const lines = g.items.map(({ d, stage }) => ({ ...alertLine(d, stage, t0), kind: d.kind, stage, severity: g.cra ? "critical" : "high" })); + const alert = { + title: lines.length === 1 ? (lines[0].stage === "quarter" ? "A quarter of the time is left: " : "New deadline: ") + lines[0].title : lines.length + " deadlines need attention", + severity: g.cra ? "critical" : "high", + text: g.cra ? CRA.where + " Darknode tracks these clocks and prepares the facts under Deadlines; it does not decide whether the Cyber Resilience Act applies and does not submit anything." : "From your monitor \"" + (g.m.name || g.m.type) + "\".", + url: DECK_DEADLINES, + events: lines.map((l) => ({ kind: "deadline", severity: l.severity, title: l.title, detail: l.detail })), + deadline: { cra: g.cra, items: lines }, + }; + let ok = 0; + for (const ch of g.m.channels) ok += (await this._deliverWithRetry(ch, alert, { ...deps, now: t0 }, g.m)) ? 1 : 0; + sent += ok; + for (const { d, stage } of g.items) { + mark(d, stage, { at: t0, sent: ok > 0 }); + const q = quarterAt(d); + if (stage === "created" && !(d.alerts || {}).quarter && q != null && t0 >= q) mark(d, "quarter", { at: t0, sent: ok > 0, via: "created" }); // due together: one alert + if (d.alerts && d.alerts.holdUntil) { const { holdUntil, ...rest } = d.alerts; d.alerts = rest; } + } + } + await this._putDeadlines([...changed.values()]); + } catch (_) {} + return sent; + } // Push a monitor's findings into THIS workspace's GraphDO (same wid as the MonitorDO). // Returns { synced, error }; never throws. The per-workspace DO is itself the access // boundary (reachable only by server code), so the uid header is provenance, not authz. @@ -127,8 +236,8 @@ export class MonitorDO { await this.storage.put(key, list); } - // Soonest next-due time across active monitors; sets the DO alarm to it. - async _reschedule() { + // Soonest next-due time across active monitors and deadline alerts; sets the DO alarm to it. + async _reschedule(at) { const mons = await this._monitors(); let soonest = null; for (const m of Object.values(mons)) { @@ -136,6 +245,9 @@ export class MonitorDO { const due = dueAt(m); if (soonest == null || due < soonest) soonest = due; } + const t = Number.isFinite(at) ? at : now(); + const dl = nextAlertAt(Object.values(await this._deadlines()), t); + if (dl != null && (soonest == null || dl < soonest)) soonest = dl; if (soonest != null) await this.storage.setAlarm(Math.max(soonest, now() + 1000)); } @@ -146,8 +258,10 @@ export class MonitorDO { // production deps.now is never set, so this is the real wall clock. const t0 = Number.isFinite(deps.now) ? deps.now : now(); let findings = []; - // The kev-epss check grades the workspace's own CVE inventory, read from its graph. - const extra = m.type === "kev-epss" ? { cves: await this._graphCves(), feedBase: deps.feedBase } : {}; + // The kev-epss check grades the workspace's own CVE inventory, read from its graph (the + // relationships also say which assets a CVE is in, for the CRA deadline). + const inventory = m.type === "kev-epss" ? await this._graphInventory() : null; + const extra = m.type === "kev-epss" ? { cves: inventory && cvesFromEntities(inventory.entities), feedBase: deps.feedBase } : {}; // A lookup that got no answer is not a clean result: diffing it would resolve every open // finding (closing them in the graph) and alert them all as new once the source is back. try { @@ -170,7 +284,11 @@ export class MonitorDO { if (m.type === "cert-expiry" && m.config && Number(m.config.warnDays) > 0 && !(m.rules && m.rules.certExpiryDays != null)) rules.certExpiryDays = Number(m.config.warnDays); const alerted = []; const held = []; + let folded = 0; for (const ev of events) { + // A certificate crossing into its last week (high -> critical) no longer re-alerts: the cert + // is a deadline now, and its reminder goes out when a quarter of the time to expiry is left. + if (m.type === "cert-expiry" && ev.kind === "worsened") { folded++; continue; } // carry cert window into the rule check for cert monitors // Only new and worsened events take the cert/KEV path. A "changed" event here is just the // title moving (expires in 10 days -> 9, EPSS 61% -> 62%) and re-alerted every run. @@ -198,6 +316,10 @@ export class MonitorDO { for (const ch of m.channels) delivered += (await this._deliverWithRetry(ch, alert, { ...deps, now: t0 }, m)) ? 1 : 0; } + // ---- deadlines this run found (public/js/core/deadlines.js). graphMeta first-seen clocks are + // read before this run adds new ones, so a certificate already open keeps its older start. ---- + const deadlines = await this._deadlinesFromRun(m, { findings, events, alerted, inventory, at: t0 }); + // ---- feed findings into the workspace Security Graph (Trident Phase 2) ---- // Monitor findings become ownable, SLA-tracked, correlatable FINDING entities, the // same shape a browser tool produces. Best-effort: a graph write failure never breaks @@ -244,7 +366,7 @@ export class MonitorDO { } } catch (e) { graphError = String(e.message || e); } - await this._log("history", HISTORY_CAP, { id: m.id, at: t0, found: findings.length, added: diff.added.length, changed: diff.changed.length, removed: diff.removed.length, alerted: alerted.length, held: held.length, ...(skipped ? { skipped } : {}), delivered, graphSynced, graphError, ms: now() - t0 }); + await this._log("history", HISTORY_CAP, { id: m.id, at: t0, found: findings.length, added: diff.added.length, changed: diff.changed.length, removed: diff.removed.length, alerted: alerted.length, held: held.length, ...(skipped ? { skipped } : {}), ...(folded ? { folded } : {}), ...(deadlines ? { deadlines } : {}), delivered, graphSynced, graphError, ms: now() - t0 }); return { id: m.id, found: findings.length, alerted: alerted.length, delivered, graphSynced }; } @@ -275,22 +397,26 @@ export class MonitorDO { }; const who = await recipient(env, channel, deps); if (who.error) { await log({ ok: false, status: 0, error: who.error }, 1); return false; } - const key = "alert-email:" + channel.uid; - const q = await quota(key, ALERT_EMAILS_PER_DAY, t0, false); - if (!q.ok) { await log({ ok: false, status: 429, error: "Daily alert email limit reached (" + ALERT_EMAILS_PER_DAY + " a day). This change is listed in the Deck under Monitors; email alerts resume tomorrow (UTC)." }, 1); return false; } + // CRA deadline alerts count against their own allowance, never the monitor alerts' one + const cra = !!(alert.deadline && alert.deadline.cra), cap = cra ? CRA_EMAILS_PER_DAY : ALERT_EMAILS_PER_DAY; + const key = (cra ? "deadline-email:" : "alert-email:") + channel.uid; + const q = await quota(key, cap, t0, false); + if (!q.ok) { await log({ ok: false, status: 429, error: (cra ? "Daily CRA deadline email limit reached (" : "Daily alert email limit reached (") + cap + " a day). " + (alert.deadline ? "It is listed in the Deck under Deadlines" : "This change is listed in the Deck under Monitors") + "; email alerts resume tomorrow (UTC)." }, 1); return false; } const wid = (await this.storage.get("wid")) || ""; const stop = wid ? await stopUrl(env, wid, channel.uid) : ""; const mail = alert.test - ? buildTestEmail({ stopUrl: stop, sent: q.used, limit: q.limit || ALERT_EMAILS_PER_DAY, now: t0 }) - : buildAlertEmail({ monitor: monitor || {}, events: alert.events || [], stopUrl: stop, sent: q.used, limit: q.limit || ALERT_EMAILS_PER_DAY, now: t0 }); - const idempotencyKey = "dn-" + ((monitor && monitor.id) || "test") + "-" + t0 + "-" + channel.uid; + ? buildTestEmail({ stopUrl: stop, sent: q.used, limit: q.limit || cap, now: t0 }) + : alert.deadline + ? buildDeadlineEmail({ items: alert.deadline.items || [], cra, monitor: monitor || {}, stopUrl: stop, sent: q.used, limit: q.limit || cap, now: t0, notes: cra ? [CRA.where, "Darknode does not decide whether the Cyber Resilience Act applies to you and does not submit anything: it tracks the clocks and prepares the facts (Deadlines, then Copy early-warning facts).", "Source: " + CRA.source.label + ", " + CRA.source.url] : [] }) + : buildAlertEmail({ monitor: monitor || {}, events: alert.events || [], stopUrl: stop, sent: q.used, limit: q.limit || cap, now: t0 }); + const idempotencyKey = "dn-" + (alert.deadline ? "dl-" : "") + ((monitor && monitor.id) || "test") + "-" + t0 + "-" + channel.uid; for (let i = 0; i < RETRY_BACKOFF_MS.length; i++) { if (RETRY_BACKOFF_MS[i]) await sleep(RETRY_BACKOFF_MS[i]); const res = await (deps.sendEmail || sendEmail)(env, { to: who.to, ...mail, stop, idempotencyKey }, deps.fetch || fetch); await log(res, i + 1); if (res.ok) return true; } - try { await quota(key, ALERT_EMAILS_PER_DAY, t0, true); } catch (_) {} // nothing was delivered: it does not count + try { await quota(key, cap, t0, true); } catch (_) {} // nothing was delivered: it does not count return false; } @@ -314,8 +440,9 @@ export class MonitorDO { ran.push(await this._runOne(m, deps, mons)); } await this._put(mons); - await this._reschedule(); - return { ran }; + const deadlineAlerts = await this._deadlinePass(deps, mons); + await this._reschedule(deps.now); + return { ran, ...(deadlineAlerts ? { deadlineAlerts } : {}) }; } async alarm() { @@ -352,6 +479,11 @@ export class MonitorDO { const deliveries = (await this.storage.get("deliveries")) || []; return reply({ monitors: Object.values(mons).map((x) => safeMonitor(x, canWrite, caller)), history: (await this.storage.get("history")) || [], deliveries: canWrite ? deliveries : deliveries.map((d) => ({ ...d, url: hideUrl(d.url) })) }); } + // Deadlines (read): every member can see them, the CRA cases behind them and the opt-ins. + if (op === "deadlines") { + const t = now(); + return reply({ deadlines: sortDeadlines(Object.values(await this._deadlines()), t), cases: Object.values(await this._cases()), settings: await this._dlSettings(), now: t, craAppliesFrom: CRA.appliesFrom }); + } // The stop link in an alert email (handleWatchStop, never reachable through handleMonitor): // pause every monitor here that emails that account. if (op === "stopEmail" && request.headers.get("x-mon-stop") === "1") { @@ -403,9 +535,49 @@ export class MonitorDO { return reply({ monitor: safeMonitor(m, true, caller) }); } if (op === "delete") { - const mons = await this._monitors(); if (mons[body.id]) { delete mons[body.id]; await this._put(mons); await this._reschedule(); } + const mons = await this._monitors(); + if (mons[body.id]) { + delete mons[body.id]; await this._put(mons); + // its open certificate deadlines go with it (nothing checks them any more); CRA and BOD clocks stay + const gone = Object.values(await this._deadlines()).filter((d) => d.kind === "cert-expiry" && d.status === "open" && d.monitorId === body.id); + await this._putDeadlines(gone.map((d) => ({ ...d, status: "dismissed", reason: "Its monitor was deleted.", closedAt: now(), closedBy: caller }))); + await this._reschedule(); + } return reply({ ok: true }); } + // ---- deadlines (write) ---- + // The opt-ins and the assets marked as shipped in a product. Turning an opt-in on needs the + // plan of the known-exploited CVE monitor (Pro); turning them off never does. + if (op === "dlSettings") { + const r = checkSettings(body.settings, { free }); + if (r.error) return r.plan ? planReply(r.error) : reply({ error: r.error }, 400); + await this.storage.put("dlSettings", r.settings); + return reply({ settings: r.settings }); + } + // A CRA case: when you became aware, when a fix or mitigation became available, the measures + // known and the Member States. Its three clocks follow. + if (op === "dlCase") { + const cve = String(body.cve || "").toUpperCase(); + const c = /^CVE-\d{4}-\d{4,7}$/.test(cve) ? await this.storage.get("cra:" + cve) : null; + if (!c) return reply({ error: "not found" }, 404); + const r = updateCase(c, body.patch || {}, now()); + if (r.error) return reply({ error: r.error }, 400); + await this.storage.put("cra:" + cve, r.case); + const moved = syncCaseClocks(r.case, await this._deadlines()); + await this._putDeadlines(moved); + await this._reschedule(); + return reply({ case: r.case, deadlines: moved }); + } + if (op === "dlClose" || op === "dlReopen") { + const id = String(body.id || "").slice(0, 300); + const d = id ? await this.storage.get("dl:" + id) : null; + if (!d) return reply({ error: "not found" }, 404); + const r = op === "dlClose" ? closeDeadline(d, { status: body.status, reason: body.reason, by: caller, at: now() }) : reopenDeadline(d); + if (r.error) return reply({ error: r.error }, 400); + await this._putDeadlines([r.deadline]); + await this._reschedule(); + return reply({ deadline: r.deadline }); + } if (op === "run") { if (!free) return reply(await this.runDue({ force: true, deckUrl: body.deckUrl })); // Free: the watch only, and at most once per 10 minutes (each run reads public CT logs and DNS) @@ -461,12 +633,15 @@ export async function handleMonitor(request, env, wid, json) { // Below Pro, the personal workspace gets the Free plan's one-domain watch: the request goes on // marked x-mon-plan "free" and the MonitorDO enforces the watch's limits (free-watch.js) in the // same step as the write. A team workspace has no Free watch. + // Deadline settings go on marked "free" below Pro, in any workspace: the MonitorDO then refuses + // to turn the CRA or BOD 22-01 opt-in on (those clocks come from the Pro CVE monitor) but still + // lets them be turned off. let op = "", resume = false; try { const b = JSON.parse(bodyText || "{}") || {}; op = String(b.op || ""); resume = op === "pause" && b.paused === false; } catch (_) {} let plan = ""; - if (MON_PAID_OPS.has(op) || resume) { + if (MON_PAID_OPS.has(op) || resume || op === "dlSettings") { const planMsg = featureDenied("monitors", await workspaceTier(env, wid, who)); if (planMsg) { - if (!isPersonalWorkspace(wid, who.uid)) return json({ error: FREE_TEAM_MSG, plan: true }, 402); + if (op !== "dlSettings" && !isPersonalWorkspace(wid, who.uid)) return json({ error: FREE_TEAM_MSG, plan: true }, 402); plan = "free"; } }