From ca40c0126ccbbaee3ca4c9510f625701859759d3 Mon Sep 17 00:00:00 2001 From: Darknode-Official Date: Wed, 25 Nov 2026 09:24:51 -0800 Subject: [PATCH 1/2] feat(check): free domain check in the hero, /check/ links and the Deck first run Landing hero (signed out): a "Check your domain" field runs a live check in the browser and shows an A-F grade with every check, its weight and its points. Email (SPF, DMARC, DKIM, MX) and DNS (DNSSEC via the AD flag, CAA) come from public DoH; HTTPS, the HTTP to HTTPS redirect, the five security headers and security.txt come through the existing /api/fetch proxy (net.js dnFetch). It reuses email-auth.js, the posture engine's header grader, domainguard-engine DNS helpers and security-txt.js. A source that fails is shown as not checked and left out of the grade, never counted as a pass or a zero; under half of the applicable points graded gives N/A. SPF and DMARC fixes name the change for the record that exists instead of telling you to publish a new one. After a result: "Fix in the Deck" (stores dn_first_domain and opens sign-up) and "Copy link". /check/ re-runs the check when opened, with nothing stored; it is an app path, served no-cache with X-Robots-Tag noindex, and is not in the sitemap. Hero copy: the air-gapped and "no data leaving your estate" claims are gone (offline is true of the CLI and desktop app with Ollama), the Built with row is removed, and Star on GitHub becomes See the Deck. Deck: while no scan has run, the overview opens with the same check. A hand-off domain or a /check link runs at once and the key is cleared; the sign-up email's work domain is offered as a chip, never typed in, and never for free mail or a Test Mode / guest session. The result is saved as a Personal run (ticks "Run your first scan") and as findings through the sink kit, and each failing check links the free Deck tool that fixes it. Domain-check findings count as external exposure in coverage and playbooks. Docs: FAQ entry with every check and weight, changelog line, JSON-LD feature. Tests: grading, normalisation, injected-resolver runs and the findings map. --- firebase.json | 14 + public/css/domain-check.css | 116 +++++++ public/index.html | 3 +- public/js/check/check-view.js | 79 +++++ public/js/check/domain-check.js | 519 +++++++++++++++++++++++++++++++ public/js/check/first-run.js | 137 ++++++++ public/js/check/landing-check.js | 147 +++++++++ public/js/core/coverage.js | 2 +- public/js/core/playbooks.js | 2 +- public/js/deck-ui.js | 28 +- public/js/deck/routes.js | 1 + public/js/docs.js | 3 +- public/js/landing.js | 31 +- test/check/domain-check.test.mjs | 293 +++++++++++++++++ test/deck/routes.test.mjs | 4 + 15 files changed, 1355 insertions(+), 24 deletions(-) create mode 100644 public/css/domain-check.css create mode 100644 public/js/check/check-view.js create mode 100644 public/js/check/domain-check.js create mode 100644 public/js/check/first-run.js create mode 100644 public/js/check/landing-check.js create mode 100644 test/check/domain-check.test.mjs diff --git a/firebase.json b/firebase.json index fbbb4838..f6567310 100644 --- a/firebase.json +++ b/firebase.json @@ -45,6 +45,13 @@ { "key": "Cache-Control", "value": "no-cache" } ] }, + { + "source": "/check/**", + "headers": [ + { "key": "Cache-Control", "value": "no-cache" }, + { "key": "X-Robots-Tag", "value": "noindex" } + ] + }, { "source": "/version", "headers": [ @@ -111,6 +118,13 @@ { "key": "Cache-Control", "value": "no-cache" } ] }, + { + "source": "/check/**", + "headers": [ + { "key": "Cache-Control", "value": "no-cache" }, + { "key": "X-Robots-Tag", "value": "noindex" } + ] + }, { "source": "/version", "headers": [ diff --git a/public/css/domain-check.css b/public/css/domain-check.css new file mode 100644 index 00000000..1d8afef9 --- /dev/null +++ b/public/css/domain-check.css @@ -0,0 +1,116 @@ +/* Domain check (js/check/*): the landing hero form, the /check/ page and the Deck's + first-run block. One result card (.dmc-res) themed by custom properties: light by default, + dark inside the landing hero, the Deck's own tokens inside the Deck (so its dark mode, an + invert filter over the light design, works unchanged). Flat: no glows, no gradients. */ + +.dmc-res{--dmc-bg:#fff;--dmc-line:#e2e8f0;--dmc-row:#f1f5f9;--dmc-tx:#0f172a;--dmc-tx2:#334155;--dmc-mut:#64748b;--dmc-acc:#1d4ed8; + --dmc-pass-bg:#ecfdf3;--dmc-pass:#166534;--dmc-pass-bd:#bbf7d0;--dmc-warn-bg:#fffbeb;--dmc-warn:#92400e;--dmc-warn-bd:#fde68a; + --dmc-fail-bg:#fef2f2;--dmc-fail:#b91c1c;--dmc-fail-bd:#fecaca;--dmc-err-bg:#f1f5f9;--dmc-err:#475569;--dmc-err-bd:#cbd5e1; + background:var(--dmc-bg);border:1px solid var(--dmc-line);border-radius:12px;color:var(--dmc-tx);text-align:left;overflow:hidden;font-size:14px;line-height:1.5} +.dmc-head{display:flex;gap:18px;align-items:flex-start;padding:20px 22px;border-bottom:1px solid var(--dmc-line)} +.dmc-grade{flex:none;width:64px;height:64px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:32px;font-weight:800;color:#fff;background:#64748b;letter-spacing:0} +.dmc-grade.g-A{background:#15803d}.dmc-grade.g-B{background:#4d7c0f}.dmc-grade.g-C{background:#b45309}.dmc-grade.g-D{background:#c2410c}.dmc-grade.g-F{background:#b91c1c}.dmc-grade.g-NA{background:#64748b;font-size:20px} +.dmc-grade.g-pending{background:transparent;border:1px solid var(--dmc-line);color:var(--dmc-mut)} +.dmc-spin{width:22px;height:22px;border:2px solid currentColor;border-right-color:transparent;border-radius:50%;animation:dmcspin .8s linear infinite} +@keyframes dmcspin{to{transform:rotate(360deg)}} +@media (prefers-reduced-motion:reduce){.dmc-spin{animation:none;border-right-color:currentColor;opacity:.5}} +.dmc-meta{min-width:0;flex:1} +.dmc-dom{font-size:20px;font-weight:700;color:var(--dmc-tx);overflow-wrap:anywhere;line-height:1.25} +.dmc-res .dmc-dom small{display:block;font-size:12.5px;font-weight:500;color:var(--dmc-mut);margin-top:2px} +.dmc-res .dmc-score{margin-top:4px;font-size:14px;font-weight:600;color:var(--dmc-tx2)} +.dmc-res .dmc-how{margin:6px 0 0;font-size:12.5px;color:var(--dmc-mut);max-width:780px} +.dmc-groups{columns:2 400px;column-gap:0;padding:6px 0} +.dmc-grp{break-inside:avoid;padding:10px 22px 6px} +.dmc-res .dmc-gh{display:flex;align-items:baseline;gap:10px;margin:0 0 4px;font-size:13px;font-weight:700;color:var(--dmc-tx);letter-spacing:0;text-transform:none} +.dmc-res .dmc-gh span{margin-left:auto;font-size:12px;font-weight:600;color:var(--dmc-mut);font-variant-numeric:tabular-nums} +.dmc-grp ul{list-style:none;margin:0;padding:0} +.dmc-row{display:grid;grid-template-columns:104px minmax(0,1fr) auto;gap:4px 12px;align-items:start;padding:10px 0;border-top:1px solid var(--dmc-row)} +.dmc-row:first-child{border-top:0} +.dmc-st{justify-self:start;font-size:11.5px;font-weight:700;line-height:1;padding:5px 8px;border-radius:5px;border:1px solid var(--dmc-err-bd);background:var(--dmc-err-bg);color:var(--dmc-err);white-space:nowrap} +.s-pass .dmc-st{background:var(--dmc-pass-bg);color:var(--dmc-pass);border-color:var(--dmc-pass-bd)} +.s-warn .dmc-st{background:var(--dmc-warn-bg);color:var(--dmc-warn);border-color:var(--dmc-warn-bd)} +.s-fail .dmc-st{background:var(--dmc-fail-bg);color:var(--dmc-fail);border-color:var(--dmc-fail-bd)} +.s-na .dmc-st,.s-pending .dmc-st{background:transparent;color:var(--dmc-mut);border-style:dashed} +.dmc-main{min-width:0} /* not "-body": pro-theme pads every [class$=-body] by 20px */ +.dmc-name{font-size:13.5px;font-weight:600;color:var(--dmc-tx)} +.dmc-res .dmc-w{margin-left:8px;font-size:11.5px;font-weight:500;color:var(--dmc-mut)} +.dmc-res .dmc-det{margin:2px 0 0;font-size:12.5px;color:var(--dmc-tx2);overflow-wrap:anywhere} +.s-pending .dmc-det,.s-na .dmc-det{color:var(--dmc-mut)} +.dmc-res .dmc-fix{margin:4px 0 0;font-size:12.5px;color:var(--dmc-mut);overflow-wrap:anywhere} +.dmc-fix b{color:var(--dmc-tx2);font-weight:600} +.dmc-pts{font-size:12px;font-weight:600;color:var(--dmc-mut);white-space:nowrap;font-variant-numeric:tabular-nums;padding-top:3px} +.dmc-res .dmc-tool{appearance:none;cursor:pointer;margin-top:6px;font:inherit;font-size:12px;font-weight:600;color:var(--dmc-acc);background:transparent;border:1px solid var(--dmc-line);border-radius:6px;padding:3px 10px} +.dmc-tool:hover{border-color:var(--dmc-acc)} +.dmc-next{display:flex;flex-wrap:wrap;align-items:center;gap:14px 24px;padding:16px 22px;border-top:1px solid var(--dmc-line)} +.dmc-next-copy{flex:1 1 320px;min-width:0;display:flex;flex-direction:column;gap:2px} +.dmc-next-copy b{font-size:14.5px;color:var(--dmc-tx)} +.dmc-next-copy span{font-size:13px;color:var(--dmc-mut)} +.dmc-next-btns{display:flex;flex-wrap:wrap;gap:10px;align-items:center} +.dmc-linkbox{flex:1 1 100%;min-width:0;font-size:12.5px} +@media (max-width:560px){ + .dmc-head{padding:16px;gap:14px} + .dmc-grade{width:52px;height:52px;font-size:26px} + .dmc-grp{padding:8px 16px 4px} + .dmc-row{grid-template-columns:minmax(0,1fr) auto;grid-template-areas:"st pts" "body body"} + .dmc-row .dmc-st{grid-area:st}.dmc-row .dmc-pts{grid-area:pts;padding-top:0}.dmc-row .dmc-main{grid-area:body} + .dmc-next{padding:14px 16px} + .dmc-next-btns,.dmc-next-btns .btn{width:100%;justify-content:center} +} + +/* ---- the form (hero and /check page) ---- */ +.dmc-form{width:100%;max-width:600px;margin:26px 0 6px;text-align:left} +.dmc-lbl{display:block;font-size:15px;font-weight:700;margin:0 0 8px;color:#0f172a;letter-spacing:0!important;text-transform:none!important} +.dmc-field{display:flex;gap:10px;flex-wrap:wrap} +html[data-style] body.landing .dmc-form .dmc-field input[type=text]{flex:1 1 220px;min-width:0;height:48px;padding:0 14px!important;font-size:16px;border-radius:6px!important} +html[data-style] body.landing .dmc-form .dmc-field .btn{height:48px;padding:0 22px;font-size:15px;flex:none;justify-content:center} +.dmc-help{margin:10px 0 0;font-size:13px;line-height:1.5;color:#64748b} +.dmc-msg{margin:10px 0 0;font-size:13.5px;font-weight:600;color:#b91c1c} +.dmc-msg[hidden],.dmc-out[hidden]{display:none} +@media (max-width:560px){html[data-style] body.landing .dmc-form .dmc-field .btn{flex:1 1 100%}} + +/* hero: dark surface, same tokens as the live KEV panel */ +html[data-style] body.landing .hero .dmc-lbl{color:#f8fafc} +html[data-style] body.landing .hero .dmc-help{color:#94a3b8} +html[data-style] body.landing .hero .dmc-msg{color:#fca5a5} +html[data-style] body.landing .hero .hero-cta{margin-top:18px} +html[data-style] body.landing .hero .hx-grid>.dmc-out{grid-column:1/-1;min-width:0} +html[data-style] body.landing .hero .dmc-res{--dmc-bg:rgba(15,23,42,.82);--dmc-line:rgba(148,163,184,.25);--dmc-row:rgba(148,163,184,.12);--dmc-tx:#f8fafc;--dmc-tx2:#e2e8f0;--dmc-mut:#94a3b8;--dmc-acc:#93c5fd; + --dmc-pass-bg:rgba(34,197,94,.14);--dmc-pass:#86efac;--dmc-pass-bd:rgba(134,239,172,.35);--dmc-warn-bg:rgba(245,158,11,.14);--dmc-warn:#fcd34d;--dmc-warn-bd:rgba(252,211,77,.35); + --dmc-fail-bg:rgba(239,68,68,.16);--dmc-fail:#fca5a5;--dmc-fail-bd:rgba(252,165,165,.4);--dmc-err-bg:rgba(148,163,184,.14);--dmc-err:#cbd5e1;--dmc-err-bd:rgba(203,213,225,.35)} +html[data-style] body.landing .hero .dmc-next .btn.ghost{background:transparent!important;color:#fff!important;border:1px solid rgba(255,255,255,.35)!important} +html[data-style] body.landing .hero .dmc-next .btn.ghost:hover{background:rgba(255,255,255,.08)!important} +html[data-style] body.landing .hero .dmc-linkbox{background:rgba(255,255,255,.06)!important;color:#e2e8f0!important;border-color:rgba(148,163,184,.35)!important} +@media (max-width:960px){ + html[data-style] body.landing .hero .dmc-form{margin-left:auto;margin-right:auto} + html[data-style] body.landing .hero .dmc-help,html[data-style] body.landing .hero .dmc-lbl{text-align:center} + html[data-style] body.landing .hero .hx-grid>.hx-copy{order:0} + html[data-style] body.landing .hero .hx-grid>.dmc-out{order:1} + html[data-style] body.landing .hero .hx-grid>.hx-live{order:2} +} + +/* ---- /check/ page ---- */ +.dn-checkpage{padding-top:0!important} +.dn-checkpage .dedicated-page-header.dn-pubbar{max-width:none;display:flex;align-items:center;flex-wrap:wrap;gap:10px 16px;padding:24px 0 8px} +.dn-checkpage .dmc-ph{margin:18px 0 6px;font-size:2rem;line-height:1.2;color:#0f172a} +.dn-checkpage .dmc-psub{margin:0 0 20px;color:#475569;font-size:.95rem;max-width:760px} +.dn-checkpage .dmc-form{margin-top:28px} + +/* ---- Deck first run (overview) ---- */ +.dk .dk-fr{background:var(--dk-surf,#fff);border:1px solid var(--dk-line,#e6e4de);border-radius:10px;padding:16px 18px;margin:0 0 16px} +.dk-fr-h b{display:block;font-size:15px;font-weight:600;color:var(--dk-tx,#1d1c1a)} +.dk-fr-h p{margin:2px 0 10px;font-size:13px;line-height:1.5;color:var(--dk-tx2,#56544f)} +.dk-fr .dk-actform input{flex:0 1 280px;width:280px} +.dk .dk-fr-help{margin:8px 0 0;font-size:12px;line-height:1.5;color:var(--dk-mut,#86837c)} +.dk .dk-fr-chips{display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin-top:8px;font-size:12px;color:var(--dk-mut,#86837c)} +.dk-fr-chip{appearance:none;cursor:pointer;font:inherit;font-size:12.5px;font-weight:600;color:var(--dk-acc,#2552c6);background:transparent;border:1px solid var(--dk-line,#e6e4de);border-radius:999px;padding:3px 11px} +.dk-fr-chip:hover{border-color:var(--dk-acc,#2552c6)} +.dk .dk-fr-msg{margin:8px 0 0;font-size:13px;font-weight:600;color:#b3261e} +.dk .dk-fr-msg[hidden],.dk .dk-fr-out[hidden],.dk .dk-fr-saved[hidden]{display:none} +.dk .dk-fr-out{margin-top:14px} +.dk-fr .dmc-res{--dmc-bg:var(--dk-surf,#fff);--dmc-line:var(--dk-line,#e6e4de);--dmc-row:var(--dk-line2,#efeee9);--dmc-tx:var(--dk-tx,#1d1c1a);--dmc-tx2:var(--dk-tx2,#56544f);--dmc-mut:var(--dk-mut,#86837c);--dmc-acc:var(--dk-acc,#2552c6);border-radius:8px} +.dk-fr .dmc-head{padding:16px 18px} +.dk-fr .dmc-grp{padding:8px 18px 4px} +.dk .dk-fr-saved{display:flex;flex-wrap:wrap;align-items:center;gap:8px 14px;margin-top:12px;font-size:13px;color:var(--dk-tx2,#56544f)} +.dk-fr-saved b{color:var(--dk-tx,#1d1c1a);font-weight:600} +.dk-fr-saved .dk-tibtn{height:32px} +@media (max-width:720px){.dk-fr .dk-actform input{flex:1 1 100%;width:auto}} diff --git a/public/index.html b/public/index.html index c0944ecb..987a693c 100644 --- a/public/index.html +++ b/public/index.html @@ -34,7 +34,7 @@ - + @@ -109,6 +109,7 @@ + diff --git a/public/js/check/check-view.js b/public/js/check/check-view.js new file mode 100644 index 00000000..5e253249 --- /dev/null +++ b/public/js/check/check-view.js @@ -0,0 +1,79 @@ +// Copyright (c) 2026 Darknode-Official. All rights reserved. See LICENSE. +// +// HTML for a domain-check result (check/domain-check.js runDomainCheck output), shared by +// the landing hero, the /check/ page and the Deck's first-run block. No DOM work +// and no imports: callers set innerHTML and wire their own buttons. Styles live in +// css/domain-check.css (.dmc-*); the hero adds .dmc-dark. + +const esc = (s) => String(s == null ? "" : s).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); + +const GROUP_ORDER = [ + ["email", "Email authentication"], + ["https", "HTTPS"], + ["headers", "Security headers"], + ["dns", "DNS hardening"], + ["disclosure", "Vulnerability disclosure"], +]; +const STATUS_LABEL = { pass: "Pass", warn: "Warning", fail: "Fail", error: "Not checked", na: "Not applicable", pending: "Checking" }; +const fmt = (n) => (Math.round(n * 10) / 10).toString(); + +function row(c, toolLabel) { + const pts = c.status === "pending" ? "" : c.points == null ? (c.status === "error" ? "not graded" : "n/a") : `${fmt(c.points)} / ${c.weight} pts`; + const tool = toolLabel && (c.status === "fail" || c.status === "warn") ? toolLabel(c.tool) : ""; + return `
  • + ${esc(STATUS_LABEL[c.status] || c.status)} +
    ${esc(c.label)}${c.weight} pts
    +

    ${c.status === "pending" ? "Checking…" : esc(c.detail)}

    + ${c.fix && (c.status === "fail" || c.status === "warn") ? `

    Fix: ${esc(c.fix)}

    ` : ""} + ${tool ? `` : ""} +
    + ${esc(pts)} +
  • `; +} + +/** + * @param {object} res runDomainCheck result (or an onProgress snapshot) + * @param {{ running?: boolean, toolLabel?: (id: string) => string }} [o] + * toolLabel: name of the Deck tool for a failing check, or "" to show no button. + */ +export function renderResult(res, { running = false, toolLabel = null } = {}) { + const checks = res.checks || []; + const n = { pass: 0, warn: 0, fail: 0, error: 0, na: 0, pending: 0 }; + for (const c of checks) n[c.status] = (n[c.status] || 0) + 1; + const graded = !running && n.pending === 0; + const grade = graded ? res.grade : ""; + const parts = [`${n.pass} passed`, `${n.warn} warning${n.warn === 1 ? "" : "s"}`, `${n.fail} failed`]; + if (n.error) parts.push(`${n.error} could not be checked`); + if (n.na) parts.push(`${n.na} not applicable`); + const scoreLine = !graded ? "Reading public DNS records and HTTP responses. Each row fills in as its source answers." + : res.score == null ? "Too few checks could run to grade this domain." + : `${res.score} out of 100 · ${parts.join(" · ")}`; + const how = `Each check is worth the points shown. A pass earns all of them, a warning half, a fail none. Checks that could not run or do not apply are left out${graded && res.possible < 100 ? `, so this grade is based on ${fmt(res.possible)} of 100 points` : ""}.`; + const groups = GROUP_ORDER.map(([id, label]) => { + const rows = checks.filter((c) => c.group === id); + if (!rows.length) return ""; + const got = rows.reduce((s, c) => s + (c.points || 0), 0); + const of = rows.reduce((s, c) => s + (c.points == null ? 0 : c.weight), 0); + // a styled div with the heading role: the site forces every h3 to black, which the hero's dark card cannot use + // and a div, not a section: the site's section rules draw separator lines + return `
    ${esc(label)}${of ? `${fmt(got)} / ${of} pts` : ""}
      ${rows.map((c) => row(c, toolLabel)).join("")}
    `; + }).join(""); + return `
    +
    +
    ${grade ? esc(grade) : ''}
    +
    +
    ${esc(res.domain)}${res.webHost && res.webHost !== res.domain ? `website checked at ${esc(res.webHost)}` : ""}
    +
    ${scoreLine}
    +

    ${how}

    +
    +
    +
    ${groups}
    +
    `; +} + +// The pending shell, before the first DNS answer lands. +export function renderPending(domain) { + return renderResult({ domain, checks: [] }, { running: true }); +} + +export const escapeHtml = esc; diff --git a/public/js/check/domain-check.js b/public/js/check/domain-check.js new file mode 100644 index 00000000..e6bb7b3b --- /dev/null +++ b/public/js/check/domain-check.js @@ -0,0 +1,519 @@ +// Copyright (c) 2026 Darknode-Official. All rights reserved. See LICENSE. +// +// Domain check: a fast, real external check of one domain, run from the browser. The +// landing hero, the shareable /check/ page and the Deck's first-run block all +// run it. It reuses the engines the Deck tools already use: +// email-auth.js SPF, DMARC and DKIM analysis (the Email Security tool) +// posture-engine.js HSTS and security-header grading (the External Posture tool) +// domainguard-engine.js DoH answer parsing, CAA records, registrable domain +// security-txt.js RFC 9116 validation (the security.txt tool) +// DNS goes straight to public DNS-over-HTTPS (Cloudflare, then Google). Web requests go +// through the Darknode fetch proxy (net.js dnFetch), which reads public responses only. +// +// The grade is transparent: every check has a fixed weight (CHECKS, 100 in total) and +// earns all of it on a pass, half on a warn and none on a fail. A check whose source +// could not be read is "error": it is listed and left out of the grade, never counted +// as a pass or a zero. A check that cannot apply (the domain has no website) is "na" +// and is also left out. Below half of the applicable weight graded, the grade is N/A. +// The pure parts (evaluate, gradeChecks, domainCheckFindings) are unit-tested in +// test/check/domain-check.test.mjs with the network injected. + +import { analyzeSPF, analyzeDMARC, analyzeDKIM, DEFAULT_SELECTORS } from "../email-auth.js?v=1"; +import { gradeTransport, gradeHeaders, letterGrade } from "../dataprotect/posture-engine.js?v=1"; +import { dohStatus, rrData, txtStrings, parseCaaData, parseMx, registrableDomain, toAsciiDomain, isDomainName } from "../exposure/domainguard-engine.js?v=1"; +import { validateSecurityTxt } from "../security-txt.js?v=1"; + +export const GROUPS = [ + { id: "email", label: "Email authentication" }, + { id: "https", label: "HTTPS" }, + { id: "headers", label: "Security headers" }, + { id: "dns", label: "DNS hardening" }, + { id: "disclosure", label: "Vulnerability disclosure" }, +]; +const GROUP_LABEL = Object.fromEntries(GROUPS.map((g) => [g.id, g.label])); + +// id -> weight (points out of 100) and the free Deck tool that digs into it. +export const CHECKS = [ + { id: "spf", group: "email", label: "SPF", weight: 10, tool: "emailauth" }, + { id: "dmarc", group: "email", label: "DMARC policy", weight: 12, tool: "emailauth" }, + { id: "dkim", group: "email", label: "DKIM", weight: 6, tool: "emailauth" }, + { id: "mx", group: "email", label: "Mail servers (MX)", weight: 4, tool: "dns" }, + { id: "https", group: "https", label: "HTTPS", weight: 12, tool: "headeranalyzer" }, + { id: "redirect", group: "https", label: "HTTP to HTTPS redirect", weight: 8, tool: "headeranalyzer" }, + { id: "hsts", group: "headers", label: "HSTS", weight: 8, tool: "headeranalyzer" }, + { id: "csp", group: "headers", label: "Content-Security-Policy", weight: 8, tool: "headeranalyzer" }, + { id: "frame", group: "headers", label: "Frame protection", weight: 5, tool: "headeranalyzer" }, + { id: "nosniff", group: "headers", label: "X-Content-Type-Options", weight: 4, tool: "headeranalyzer" }, + { id: "referrer", group: "headers", label: "Referrer-Policy", weight: 3, tool: "headeranalyzer" }, + { id: "dnssec", group: "dns", label: "DNSSEC", weight: 7, tool: "dns" }, + { id: "caa", group: "dns", label: "CAA records", weight: 7, tool: "dns" }, + { id: "securitytxt", group: "disclosure", label: "security.txt", weight: 6, tool: "securitytxt" }, +]; + +// Share of a check's weight each status earns. error / na / pending are not graded. +export const CREDIT = { pass: 1, warn: 0.5, fail: 0 }; + +// ---- input ------------------------------------------------------------------------- + +// What people paste (a URL, you@domain, mailto:, a port, www.) -> a bare ASCII domain, +// or "" when it is not a domain name (an IP address, a single label, junk). +export function normalizeDomain(raw) { + let d = String(raw == null ? "" : raw).trim().toLowerCase(); + d = d.replace(/^mailto:/, "").replace(/^[a-z][a-z0-9+.-]*:\/\//, "").replace(/[/?#].*$/, "").replace(/^.*@/, "") + .replace(/\.+$/, "").replace(/:\d+$/, "").replace(/\.+$/, "").replace(/^www\./, ""); + if (/[^\x00-\x7f]/.test(d)) d = toAsciiDomain(d); + return isDomainName(d) ? d : ""; +} + +// Free and consumer mail providers: their domain is not the user's company, so the Deck +// does not offer it as "your domain". +const FREE_MAIL = new Set(("gmail.com googlemail.com outlook.com hotmail.com live.com msn.com passport.com yahoo.com ymail.com rocketmail.com " + + "aol.com aim.com icloud.com me.com mac.com proton.me protonmail.com protonmail.ch pm.me tuta.io tutanota.com tutanota.de tutamail.com " + + "keemail.me gmx.com gmx.net gmx.de gmx.at gmx.ch web.de mail.com email.com yandex.com yandex.ru ya.ru mail.ru inbox.ru list.ru bk.ru " + + "zoho.com zohomail.com fastmail.com fastmail.fm hey.com duck.com mailbox.org posteo.de posteo.net hushmail.com lycos.com inbox.com " + + "qq.com 163.com 126.com yeah.net sina.com sohu.com aliyun.com naver.com daum.net hanmail.net rediffmail.com libero.it virgilio.it " + + "orange.fr wanadoo.fr free.fr laposte.net sfr.fr t-online.de freenet.de seznam.cz wp.pl o2.pl interia.pl onet.pl btinternet.com " + + "sky.com virginmedia.com talktalk.net comcast.net verizon.net att.net sbcglobal.net bellsouth.net cox.net charter.net earthlink.net " + + "juno.com optonline.net rogers.com shaw.ca sympatico.ca bigpond.com optusnet.com.au xtra.co.nz rambler.ru ukr.net abv.bg").split(" ")); +const FREE_MAIL_FAMILY = /^(yahoo|hotmail|outlook|live|gmx|yandex|aol|msn)\.[a-z]{2,3}(\.[a-z]{2})?$/; +const RESERVED = /(^|\.)(example\.(com|net|org)|test|example|invalid|localhost|local|internal|lan|home\.arpa)$/; + +export function isFreeMail(domain) { + const d = String(domain || "").toLowerCase(); + return FREE_MAIL.has(d) || FREE_MAIL_FAMILY.test(d); +} + +// The sign-up email's domain when it is a company domain worth offering, else "". +export function workDomainFromEmail(email) { + const m = /@([^@\s]+)$/.exec(String(email || "").trim().toLowerCase()); + if (!m) return ""; + const d = normalizeDomain(m[1]); + return d && !isFreeMail(d) && !RESERVED.test(d) ? d : ""; +} + +// ---- transport ----------------------------------------------------------------------- + +const RESOLVERS = [ + (n, t, cd) => "https://cloudflare-dns.com/dns-query?name=" + encodeURIComponent(n) + "&type=" + t + (cd ? "&cd=1" : ""), + (n, t, cd) => "https://dns.google/resolve?name=" + encodeURIComponent(n) + "&type=" + t + (cd ? "&cd=1" : ""), +]; + +async function getDnsJson(url, ms) { + const ctrl = new AbortController(); + const timer = setTimeout(() => ctrl.abort(), ms); + try { + const r = await fetch(url, { headers: { Accept: "application/dns-json" }, signal: ctrl.signal }); + if (!r.ok) throw new Error("HTTP " + r.status); + return await r.json(); + } finally { clearTimeout(timer); } +} + +// One DoH JSON answer ({ Status, AD, Answer }). SERVFAIL / REFUSED are asked of the other +// resolver too; only when neither resolver answers at all does this throw. +export async function dohJSON(name, type, { cd = false } = {}) { + let failed = null, firstErr = null; + for (const url of RESOLVERS) { + try { + const j = await getDnsJson(url(name, type, cd), 8000); + if (j && (j.Status === 2 || j.Status === 5)) { failed = j; continue; } + return j; + } catch (e) { firstErr = firstErr || e; } + } + if (failed) return failed; + throw new Error("neither public DNS resolver answered" + (firstErr && firstErr.message ? " (" + firstErr.message + ")" : "")); +} + +async function defaultFetch(url, opts) { + const { dnFetch } = await import("/js/net.js"); + return dnFetch(url, opts); +} + +const msgOf = (e) => String((e && e.message) || e || "unknown error").replace(/\.+$/, ""); + +// A failure of the proxy itself (or the site refusing the proxy) says nothing about the +// site: that check is "error". Anything else (refused connection, TLS failure, timeout, +// a name that does not resolve) is the site not answering. +const PROXY_ERROR = /darknode proxy|proxy returned|proxy is not configured|proxy size limit|rate limit|origin not allowed|non-public or reserved host|firewall blocked the request|rate-limited the request/i; +export const isProxyError = (e) => PROXY_ERROR.test(msgOf(e)); + +const settle = (p) => Promise.resolve(p).then((value) => ({ value }), (e) => ({ error: msgOf(e) })); +const settleWeb = (p) => Promise.resolve(p).then((value) => ({ value }), (e) => (isProxyError(e) ? { error: msgOf(e) } : { siteError: msgOf(e) })); + +// ---- evaluation (pure) ------------------------------------------------------------------ + +const PENDING = Object.freeze({ status: "pending", detail: "Checking", fix: "" }); +const clip = (s, n) => { s = String(s || ""); return s.length > n ? s.slice(0, n - 1) + "…" : s; }; +const err = (what, why) => ({ status: "error", detail: "Could not read " + what + ": " + why + ".", fix: "" }); +const na = (detail) => ({ status: "na", detail, fix: "" }); + +// a settled DoH lookup -> { j } (an answer, NXDOMAIN included) | { err } | null (still pending) +function dnsRes(r) { + if (!r) return null; + if (r.error) return { err: r.error }; + const st = dohStatus(r.value); + if (st === "ok" || st === "nxdomain") return { j: r.value }; + return { err: "the resolver returned " + st.toUpperCase() }; +} + +const STATUS = { PASS: "pass", WARN: "warn", FAIL: "fail" }; +// The fix for a problem email-auth.js reports in a record that exists, keyed on its wording. +const SPF_FIXES = [ + [/SPF records \(v=spf1\) are published/, "Merge them into a single v=spf1 record."], + [/\+all/, "Replace +all with -all now: +all lets any server on the internet send as this domain."], + [/10 DNS-lookup|stop at 10/, "Bring the record under 10 DNS lookups: drop include: entries for services you no longer use, or flatten them."], + [/~all/, "Once every service that sends your mail is listed, change ~all to -all so mail from unlisted servers is rejected."], + [/\?all/, "Replace ?all with ~all, then -all, so mail from unlisted servers is rejected."], + [/No explicit 'all'/, "End the record with -all (or ~all while you confirm every sender is listed)."], + [/'ptr'/, "Remove the ptr mechanism and list sending hosts with ip4:, ip6: or include: instead."], +]; +const DMARC_FIXES = [ + [/DMARC records are published/, "Keep exactly one DMARC record at _dmarc."], + [/missing or invalid 'p='/, "Add a policy tag to the record: p=quarantine or p=reject."], + [/p=none/, "Read the aggregate (rua) reports, then move to p=quarantine and later p=reject once legitimate mail passes."], + [/p=quarantine/, "Move to p=reject once your DMARC reports show legitimate mail passing."], + [/pct=/, "Remove pct= (or set pct=100) so the policy covers all mail."], + [/No rua= tag/, "Add rua=mailto: to the record to receive daily aggregate reports."], +]; +// An email-auth.js analysis -> a check row: its first problem as the detail and the fix for +// that problem; `missingFix` only when there is no record at all. +function fromAnalysis(a, passDetail, missingFix, fixes) { + const status = STATUS[a.status] || "warn"; + const bad = (a.findings || []).find((f) => f.kind === "bad") || (a.findings || []).find((f) => f.kind === "warn"); + if (status === "pass") return { status, detail: passDetail, fix: "" }; + const known = bad && (fixes || []).find(([re]) => re.test(bad.text)); + const fix = !a.record ? missingFix : known ? known[1] : "Correct the record as described, then run the check again."; + return { status, detail: bad ? bad.text : passDetail, fix }; +} + +// Where the web checks read headers from: the HTTPS answer, else the plain-HTTP one. +function headerSource(o) { + const web = webGate(o); + if (web) return web; + const s = o.https, h = o.http; + if (!s) return PENDING; + if (s.value) return { headers: s.value.headers || {}, code: s.value.status | 0, secure: !/^http:/i.test(s.value.finalUrl || s.value.url || "") }; + if (s.error) return err("the site over HTTPS", s.error); + if (!h) return PENDING; + if (h.value) return { headers: h.value.headers || {}, code: h.value.status | 0, secure: /^https:/i.test(h.value.finalUrl || h.value.url || "") }; + if (h.error) return err("the site over HTTP", h.error); + return na("The site answers neither HTTPS nor HTTP, so there are no headers to read."); +} + +function webGate(o) { + if (!o.web || o.web === "pending") return PENDING; + if (o.web === "none") return na(`No website: ${o.domain} and www.${o.domain} have no A or AAAA record.`); + if (o.web === "error") return err("the address records", o.webErr || "the lookup failed"); + return null; +} + +function fromEngine(src, name, pick) { + if (src.status) return src; // pending / error / na + const c = pick(src).checks.find((x) => x.name === name); + if (!c) return err("the headers", "the grader returned no result"); + const note = src.code >= 400 ? ` Graded from an HTTP ${src.code} response.` : ""; + return { status: c.status, detail: c.detail + note, fix: c.advice || "" }; +} + +const EVAL = { + spf(o) { + const r = dnsRes(o.txt); + if (!r) return PENDING; + if (r.err) return err("the TXT records", r.err); + const a = analyzeSPF(txtStrings(r.j)); + return fromAnalysis(a, "Published: " + clip(a.record, 140), "Publish one TXT record at the domain root, such as v=spf1 include: -all", SPF_FIXES); + }, + dmarc(o) { + if (!o.dmarc) return PENDING; + if (o.dmarc.error) return err("the DMARC record", o.dmarc.error); + const { txts, from } = o.dmarc.value; + const a = analyzeDMARC(txts); + const inherited = from && from !== o.domain ? ` (inherited from ${from})` : ""; + const pol = (/\bp\s*=\s*(\w+)/i.exec(a.record || "") || [])[1]; + const r = fromAnalysis(a, "Enforced: p=" + (pol || "reject") + inherited + ".", `Publish a TXT record at _dmarc.${o.domain}, such as v=DMARC1; p=none; rua=mailto:. Read the reports, then move to p=quarantine and p=reject.`, DMARC_FIXES); + if (r.status !== "pass" && inherited) r.detail = r.detail.replace(/\.?$/, "") + inherited + "."; + return r; + }, + dkim(o) { + if (!o.dkim) return PENDING; + if (o.dkim.error) return err("the DKIM selectors", o.dkim.error); + const list = o.dkim.value || []; + // a domain whose SPF authorises no sender at all sends no mail, so it signs nothing + const t = dnsRes(o.txt); + if (!t) return PENDING; + const spf = t.j ? txtStrings(t.j).find((x) => /^v=spf1(\s|$)/i.test(x.trim())) : ""; + if (spf && /^v=spf1\s+-all$/i.test(spf.trim())) return na("The domain sends no mail (its SPF is v=spf1 -all), so it needs no DKIM key."); + if (list.length && list.every((x) => x.error)) return err("the DKIM selectors", "every selector lookup failed"); + const a = analyzeDKIM(list); + if (a.status === "NOT FOUND") { + return { status: "warn", detail: `No DKIM key at any of the ${list.length} common selectors tried. A custom selector would not show here, so this is a warning, not a fail.`, fix: "Turn on DKIM signing in your mail provider and publish the key it gives you. If signing is already on, look up the s= selector in a signed message's DKIM-Signature header." }; + } + const hit = (a.records || [])[0]; + return fromAnalysis(a, `Key published at selector ${hit ? hit.selector : "?"}${a.records.length > 1 ? ` (+${a.records.length - 1} more)` : ""}.`, "Publish a working DKIM key and remove test mode (t=y) or revoked keys."); + }, + mx(o) { + const r = dnsRes(o.mx); + if (!r) return PENDING; + if (r.err) return err("the MX records", r.err); + const hosts = parseMx(r.j); + if (hosts.length === 1 && !hosts[0].host) return { status: "pass", detail: "Null MX (RFC 7505): the domain declares it accepts no mail.", fix: "" }; + const real = hosts.filter((h) => h.host); + if (real.length) return { status: "pass", detail: `${real.length} mail server${real.length === 1 ? "" : "s"}: ${real.slice(0, 3).map((h) => h.host).join(", ")}${real.length > 3 ? ", …" : ""}.`, fix: "" }; + return { status: "warn", detail: "No MX record. Mail sent to this domain falls back to its address record or bounces.", fix: "Publish MX records for your mail provider, or a null MX (MX 0 .) if the domain takes no mail." }; + }, + https(o) { + const g = webGate(o); + if (g) return g; + const s = o.https; + if (!s) return PENDING; + if (s.error) return err("the site over HTTPS", s.error); + const fix = "Serve the site over TLS with a valid certificate, then redirect HTTP to HTTPS."; + if (s.siteError) return { status: "fail", detail: `No HTTPS answer from ${o.webHost}: ${s.siteError}.`, fix }; + const code = s.value.status | 0, fin = s.value.finalUrl || s.value.url || ""; + if (code === 525 || code === 526) return { status: "fail", detail: `The TLS handshake failed (HTTP ${code}${code === 526 ? ", invalid certificate" : ""}).`, fix }; + if (/^http:/i.test(fin)) return { status: "warn", detail: `HTTPS answers but sends visitors to plain HTTP (${clip(fin, 80)}).`, fix: "Keep visitors on HTTPS: remove the redirect to http://." }; + return { status: "pass", detail: `${o.webHost} answers over HTTPS${code ? " (HTTP " + code + ")" : ""}.`, fix: "" }; + }, + redirect(o) { + const g = webGate(o); + if (g) return g; + const s = o.https, h = o.http; + if (!s || !h) return PENDING; + if (h.error) return err("the site over HTTP", h.error); + if (h.siteError) { + if (s.value) return { status: "pass", detail: "Plain HTTP (port 80) does not answer, so nothing is served unencrypted.", fix: "" }; + if (s.error) return err("the site over HTTPS", s.error); + return na("The site answers neither HTTP nor HTTPS."); + } + const fin = h.value.finalUrl || h.value.url || ""; + if (/^https:/i.test(fin)) return { status: "pass", detail: `http:// redirects to ${clip(fin.replace(/^(https:\/\/[^/]+).*$/i, "$1"), 80)}.`, fix: "" }; + return { status: "fail", detail: `http:// serves the site without moving to HTTPS (HTTP ${h.value.status | 0}).`, fix: "Answer every http:// request with a 301 redirect to the same path on https://." }; + }, + hsts(o) { + const src = headerSource(o); + if (!src.status && !src.secure) return { status: "fail", detail: "The site was only reachable over plain HTTP, and browsers ignore HSTS there.", fix: "Serve the site over HTTPS and send Strict-Transport-Security with max-age of at least 15552000." }; + return fromEngine(src, "HSTS", (x) => gradeTransport({ headers: x.headers, httpsOk: true, httpTested: false })); + }, + csp: (o) => fromEngine(headerSource(o), "Content-Security-Policy", (x) => gradeHeaders({ headers: x.headers })), + frame: (o) => fromEngine(headerSource(o), "Clickjacking protection", (x) => gradeHeaders({ headers: x.headers })), + nosniff: (o) => fromEngine(headerSource(o), "X-Content-Type-Options", (x) => gradeHeaders({ headers: x.headers })), + referrer: (o) => fromEngine(headerSource(o), "Referrer-Policy", (x) => gradeHeaders({ headers: x.headers })), + dnssec(o) { + const a = o.a; + if (!a) return PENDING; + if (a.error) return err("the address record", a.error); + const st = dohStatus(a.value); + if (st === "servfail") { + if (!o.bogus) return PENDING; + if (o.bogus.value && dohStatus(o.bogus.value) === "ok") return { status: "fail", detail: "Validating resolvers refuse to answer, yet the answer comes back with validation off: the DNSSEC signatures are broken.", fix: "Re-sign the zone, or remove the stale DS record at your registrar." }; + return err("the address record", "the resolver returned SERVFAIL"); + } + if (st !== "ok" && st !== "nxdomain") return err("the address record", "the resolver returned " + st.toUpperCase()); + if (a.value.AD === true) return { status: "pass", detail: "Signed and validated: the resolver set the AD (authenticated data) flag.", fix: "" }; + const d = dnsRes(o.ds); + if (!d) return PENDING; + if (d.err) return err(`the DS record at ${o.org}`, d.err); + if (rrData(d.j, "DS").length) return { status: "warn", detail: `${o.org} publishes a DS record, but this answer did not validate.`, fix: "Check that the zone's DNSKEY matches the DS record at your registrar." }; + return { status: "warn", detail: `Not signed: ${o.org} has no DS record, so DNS answers cannot be authenticated.`, fix: "Turn on DNSSEC at your DNS host, then add the DS record it gives you at your registrar." }; + }, + caa(o) { + if (!o.caa) return PENDING; + if (o.caa.error) return err("the CAA records", o.caa.error); + const { at, recs } = o.caa.value; + const fix = 'Publish a CAA record naming the certificate authority you use: 0 issue "".'; + if (!recs.length) return { status: "warn", detail: "No CAA record: any certificate authority may issue certificates for this domain.", fix }; + const issue = recs.filter((r) => r.tag === "issue" || r.tag === "issuewild"); + if (!issue.length) return { status: "warn", detail: `The CAA record at ${at} has no issue tag, so it does not limit which CA may issue.`, fix }; + const cas = [...new Set(issue.map((r) => r.value.split(";")[0].trim() || "none (issuance blocked)"))]; + return { status: "pass", detail: `CAA at ${at} allows: ${clip(cas.join(", "), 120)}.`, fix: "" }; + }, + securitytxt(o) { + const g = webGate(o); + if (g) return g; + const r = o.stxt; + if (!r) return PENDING; + if (r.error) return err("security.txt", r.error); + const fix = "Publish /.well-known/security.txt over HTTPS with Contact: and Expires: fields (RFC 9116)."; + const v = r.value; + if (!v.found) return { status: "warn", detail: "No security.txt at /.well-known/security.txt, so researchers have no published way to report a vulnerability.", fix }; + const res = validateSecurityTxt(v.body); + const bad = res.findings.find((f) => f.level === "error"); + if (!res.ok) return { status: "warn", detail: `Found at ${v.path}, but it is not valid: ${clip(bad ? bad.msg : "it did not parse", 140)}`, fix }; + if (v.path !== "/.well-known/security.txt") return { status: "warn", detail: `Found only at ${v.path}. RFC 9116 places it at /.well-known/security.txt.`, fix: "Serve the same file at /.well-known/security.txt." }; + const contact = res.fields.find((f) => /^contact$/i.test(f.name)); + return { status: "pass", detail: `Valid RFC 9116 file${contact ? ` (Contact: ${clip(contact.value, 60)})` : ""}.`, fix: "" }; + }, +}; + +// All checks for the observations so far: a check whose inputs have not arrived is "pending". +export function evaluate(obs) { + return CHECKS.map((def) => { + let r; + try { r = EVAL[def.id](obs); } catch (e) { r = err("the result", msgOf(e)); } + return { id: def.id, group: def.group, label: def.label, weight: def.weight, tool: def.tool, status: r.status, detail: r.detail, fix: r.fix || "" }; + }); +} + +// Weighted grade. Sets points on each graded check (null when it is not graded). +export function gradeChecks(checks) { + let earned = 0, possible = 0, applicable = 0; + for (const c of checks) { + c.points = null; + if (c.status === "na") continue; + applicable += c.weight; + if (!Object.prototype.hasOwnProperty.call(CREDIT, c.status)) continue; + c.points = c.weight * CREDIT[c.status]; + possible += c.weight; + earned += c.points; + } + const covered = applicable > 0 && possible / applicable >= 0.5; + const score = covered ? Math.round((100 * earned) / possible) : null; + return { score, grade: covered ? letterGrade(score) : "N/A", earned, possible, applicable }; +} + +export function summarize(checks) { + const n = { pass: 0, warn: 0, fail: 0, error: 0, na: 0, pending: 0 }; + for (const c of checks) n[c.status] = (n[c.status] || 0) + 1; + return n; +} + +// ---- collection ---------------------------------------------------------------------------- + +async function lookupDmarc(doh, domain, org) { + const has = (txts) => txts.some((t) => /^v\s*=\s*dmarc1\b/i.test(String(t).trim())); + const read = async (name) => { + const j = await doh("_dmarc." + name, "TXT"); + const st = dohStatus(j); + if (st !== "ok" && st !== "nxdomain") throw new Error("the resolver returned " + st.toUpperCase()); + return txtStrings(j); + }; + const own = await read(domain); + if (has(own) || org === domain) return { txts: own, from: domain }; + const parent = await read(org); // RFC 7489 6.6.3: the organizational domain's policy covers subdomains + return has(parent) ? { txts: parent, from: org } : { txts: own, from: domain }; +} + +async function probeDkim(doh, domain) { + return Promise.all(DEFAULT_SELECTORS.map(async (selector) => { + try { + const j = await doh(selector + "._domainkey." + domain, "TXT"); + const st = dohStatus(j); + if (st !== "ok" && st !== "nxdomain") return { selector, found: false, record: null, error: st }; + const rec = txtStrings(j).find((t) => /(^|;)\s*(v=DKIM1|k=|p=)/i.test(t)); + return { selector, found: !!rec, record: rec || null }; + } catch (e) { return { selector, found: false, record: null, error: msgOf(e) }; } + })); +} + +// CAA applies from the name itself up to the registrable domain (RFC 8659 3): the first +// name that has a CAA set decides. +async function findCaa(doh, domain, org) { + const names = []; + for (let n = domain; n; n = n.slice(n.indexOf(".") + 1)) { names.push(n); if (n === org || n.indexOf(".") < 0) break; } + for (const n of names) { + const j = await doh(n, "CAA"); + const st = dohStatus(j); + if (st !== "ok" && st !== "nxdomain") throw new Error("the resolver returned " + st.toUpperCase()); + const recs = rrData(j, "CAA").map(parseCaaData).filter(Boolean); + if (recs.length) return { at: n, recs }; + } + return { at: null, recs: [] }; +} + +async function fetchSecurityTxt(fetchUrl, host) { + for (const path of ["/.well-known/security.txt", "/security.txt"]) { + let r; + try { r = await fetchUrl("https://" + host + path, { raw: true, max: 32768, timeout: 12000 }); } + catch (e) { if (isProxyError(e)) throw e; return { found: false }; } + const body = String((r && r.body) || ""); + // a site that answers every path with its HTML app is not publishing security.txt + if ((r.status | 0) === 200 && !/^\s* !!(r && r.value && dohStatus(r.value) === "ok" && (rrData(r.value, "A").length || rrData(r.value, "AAAA").length)); +const lookupFailed = (r) => !r || !!r.error || !["ok", "nxdomain"].includes(dohStatus(r.value)); + +/** + * Run the check. onProgress(result) fires as each source lands, with pending checks. + * deps: { doh(name, type, {cd}), fetchUrl(url, opts) } for tests; defaults are live. + * @returns {Promise<{domain, webHost, grade, score, earned, possible, checks, counts, ranAt}>} + */ +export async function runDomainCheck(input, { onProgress, doh = dohJSON, fetchUrl = defaultFetch } = {}) { + const domain = normalizeDomain(input); + if (!domain) throw new Error("Enter a domain name, like example.com."); + const org = registrableDomain(domain); + const obs = { domain, org, webHost: domain, web: "pending" }; + const result = () => { + const checks = evaluate(obs); + const g = gradeChecks(checks); + return { domain, webHost: obs.webHost, grade: g.grade, score: g.score, earned: g.earned, possible: g.possible, checks, counts: summarize(checks), ranAt: Date.now() }; + }; + const emit = () => { if (onProgress) { try { onProgress(result()); } catch (_) {} } }; + + const [a, aaaa] = await Promise.all([settle(doh(domain, "A")), settle(doh(domain, "AAAA"))]); + if (a.value && dohStatus(a.value) === "nxdomain") throw new Error(`${domain} does not exist in public DNS (NXDOMAIN). Check the spelling.`); + if (a.error && aaaa.error) throw new Error("Public DNS could not be reached (" + a.error + "). Check your connection and try again."); + obs.a = a; + + const jobs = []; + const track = (key, p) => jobs.push(p.then((r) => { obs[key] = r; emit(); })); + if (!a.error && dohStatus(a.value) === "servfail") track("bogus", settle(doh(domain, "A", { cd: true }))); + track("txt", settle(doh(domain, "TXT"))); + track("dmarc", settle(lookupDmarc(doh, domain, org))); + track("dkim", settle(probeDkim(doh, domain))); + track("mx", settle(doh(domain, "MX"))); + track("ds", settle(doh(org, "DS"))); + track("caa", settle(findCaa(doh, domain, org))); + + // Web checks: the domain's own address, else www (many sites live only there). + let web = hasAddress(a) || hasAddress(aaaa) ? "yes" : lookupFailed(a) && lookupFailed(aaaa) ? "error" : "none"; + if (web === "none") { + const w = await settle(doh("www." + domain, "A")); + if (hasAddress(w)) { web = "yes"; obs.webHost = "www." + domain; } + } + obs.web = web; + if (web === "error") obs.webErr = a.error || "the resolver returned " + dohStatus(a.value).toUpperCase(); + emit(); + if (web === "yes") { + track("https", settleWeb(fetchUrl("https://" + obs.webHost + "/", { timeout: 15000 }))); + track("http", settleWeb(fetchUrl("http://" + obs.webHost + "/", { timeout: 15000 }))); + track("stxt", settle(fetchSecurityTxt(fetchUrl, obs.webHost))); + } + await Promise.all(jobs); + return result(); +} + +// ---- findings (the Deck sink kit) ----------------------------------------------------------- + +const HIGH_ON_FAIL = new Set(["https", "dmarc", "spf"]); +const fid = (domain, id) => `domaincheck|${domain}|${id}`; + +// Failing and warning checks -> common Finding shape (core/sink-map.js). Ids are stable, +// so a re-run of the same domain merges into the same findings. +export function domainCheckFindings(res) { + const domain = String((res && res.domain) || "").trim().toLowerCase(); + if (!domain) return []; + return (res.checks || []).filter((c) => c.status === "fail" || c.status === "warn").map((c) => ({ + id: fid(domain, c.id), + title: `${c.label} issue on ${domain}`, + severity: c.status === "warn" ? "low" : HIGH_ON_FAIL.has(c.id) ? "high" : "medium", + confidence: c.id === "dkim" && c.status === "warn" ? "review" : "confirmed", + category: GROUP_LABEL[c.group] || c.group, + description: c.detail, + recommendation: c.fix || undefined, + evidence: [{ check: c.label, status: c.status, detail: c.detail }], + assets: [{ type: "DOMAIN", name: domain }], + tags: ["domaincheck", c.status], + })); +} + +// Finding ids this run could not re-check (its source failed): never offered as fixed. +export function domainCheckHeld(res) { + const domain = String((res && res.domain) || "").trim().toLowerCase(); + if (!domain) return []; + return (res.checks || []).filter((c) => c.status === "error" || c.status === "pending").map((c) => fid(domain, c.id)); +} + +// "good" | "warn" | "bad" for the Deck's run history (same rule as the My domain tool). +export const runLevel = (res) => (res.grade === "A" || res.grade === "B" ? "good" : res.grade === "C" || res.score == null ? "warn" : "bad"); diff --git a/public/js/check/first-run.js b/public/js/check/first-run.js new file mode 100644 index 00000000..2903f38a --- /dev/null +++ b/public/js/check/first-run.js @@ -0,0 +1,137 @@ +// Copyright (c) 2026 Darknode-Official. All rights reserved. See LICENSE. +// +// The Deck's first five minutes: the overview's first block while a workspace has run no +// scan yet. It runs the same live domain check as the landing (check/domain-check.js), +// shows the real result before any setup, saves it the way the space tools do (a run in +// the Personal history, which ticks "Run your first scan", and findings through the sink +// kit), and offers the free Deck tool that digs into each failing check. +// +// The domain comes from, in order: a /check/ link, the landing's "Fix in the +// Deck" (localStorage dn_first_domain, cleared once it has run), or the user. The sign-up +// email's domain is only offered as a one-click chip, never typed into the field, and +// never for a free-mail provider or a Test Mode / guest identity. + +import { runDomainCheck, normalizeDomain, workDomainFromEmail, domainCheckFindings, domainCheckHeld, runLevel } from "/js/check/domain-check.js?v=1"; +import { renderResult, renderPending, escapeHtml as esc } from "/js/check/check-view.js?v=1"; +import { recordRun } from "/js/deck/native/ui.js"; // same URL deck-ui and the space tools import + +export const FIRST_DOMAIN_KEY = "dn_first_domain"; + +export function storedFirstDomain() { + try { return localStorage.getItem(FIRST_DOMAIN_KEY) || ""; } catch (_) { return ""; } +} +function clearStored() { try { localStorage.removeItem(FIRST_DOMAIN_KEY); } catch (_) {} } + +// The Deck gets a trimmed user ({uid, displayName, email, photoURL}), so a Test Mode / app +// guest session is told by the shared test address and its random per-session uid prefix. +const isTestIdentity = (u) => !!(u && (u.isAnonymous || u.email === "test@darknode.ai" || /^(test|app-guest)-/.test(u.uid || "") + || (u.providerData || []).some((p) => p && p.providerId === "test"))); + +// Survives overview re-renders for this page load: the block is redrawn into each new slot. +const S = { domain: "", res: null, running: false, saved: null, error: "", seq: 0, slot: null, ctx: null }; + +function toolLabel(id) { + const c = S.ctx; + if (!c || (c.isLocked && c.isLocked("tool:" + id))) return ""; + return (c.toolName && c.toolName(id)) || ""; +} + +function paint() { + const slot = S.slot; + if (!slot || !slot.isConnected) return; + const out = slot.querySelector(".dk-fr-out"), msg = slot.querySelector(".dk-fr-msg"), saved = slot.querySelector(".dk-fr-saved"); + const btn = slot.querySelector(".dk-fr-form button[type=submit]"); + if (btn) { btn.disabled = S.running; btn.textContent = S.running ? "Checking…" : "Check domain"; } + slot.querySelectorAll(".dk-fr-chip").forEach((b) => { b.disabled = S.running; }); + msg.textContent = S.error; msg.hidden = !S.error; + if (S.res) { + out.hidden = false; + out.innerHTML = S.res.checks && S.res.checks.length ? renderResult(S.res, { running: S.running, toolLabel: S.running ? null : toolLabel }) : renderPending(S.res.domain); + } else { out.hidden = true; out.innerHTML = ""; } + saved.hidden = !S.saved; + if (S.saved) saved.innerHTML = savedHtml(S.saved); +} + +function savedHtml(sv) { + const c = S.ctx || {}; + const where = c.isLocked && !c.isLocked("scene:findings") ? { act: "findings", label: "Open findings" } + : c.isLocked && !c.isLocked("tool:secgraph") ? { act: "secgraph", label: "Open the Security Graph" } : null; + const text = !sv.ok ? "The result is shown above, but it could not be saved to this workspace." + : sv.findings ? `Saved to this workspace. ${sv.findings} finding${sv.findings === 1 ? "" : "s"} recorded for ${esc(sv.domain)}, each linked to the tool that fixes it.` + : `Saved to this workspace. No failing or warning checks on ${esc(sv.domain)}.`; + return `${text}${sv.ok && sv.findings && where ? `` : ""}`; +} + +async function save(res, seq) { + const findings = domainCheckFindings(res); + const failing = res.checks.filter((c) => c.status === "fail").length; + // a run in the Personal history: "Run your first scan" reads it, and My domain lists it + try { recordRun("personal", { tool: "domain", target: res.domain, summary: "Grade " + res.grade + " (" + failing + " failing)", level: runLevel(res), score: res.score, grade: res.grade }); } catch (_) {} + let out = null; + try { + const sink = await import("/js/core/sink.js"); + out = await sink.publishFindings("domaincheck", findings, { dataset: "domaincheck " + res.domain, held: domainCheckHeld(res), quiet: true }); + } catch (_) { out = null; } + if (seq !== S.seq) return; + S.saved = { ok: !!out, findings: findings.length, domain: res.domain }; + paint(); + if (S.ctx && S.ctx.onSaved) { try { S.ctx.onSaved(); } catch (_) {} } +} + +async function run(raw) { + const domain = normalizeDomain(raw); + if (!domain) { + S.error = String(raw || "").trim() ? "That is not a domain name. Enter one like example.com." : "Enter a domain, like example.com."; + paint(); + return; + } + const seq = ++S.seq; + Object.assign(S, { domain, res: { domain, checks: [] }, running: true, saved: null, error: "" }); + paint(); + try { + const res = await runDomainCheck(domain, { onProgress: (r) => { if (seq === S.seq) { S.res = r; paint(); } } }); + if (seq !== S.seq) return; + Object.assign(S, { res, running: false }); + paint(); + await save(res, seq); + } catch (e) { + if (seq !== S.seq) return; + Object.assign(S, { res: null, running: false, error: (e && e.message) || "The check failed. Try again." }); + paint(); + } +} + +/** + * Draw the block into `slot` (an empty element at the top of the overview). + * ctx = { user, pending, isLocked(key), toolName(id), openTool(id), go(scene), onSaved() } + */ +export function mountFirstRun(slot, ctx) { + S.slot = slot; S.ctx = ctx; + const chip = isTestIdentity(ctx.user) ? "" : workDomainFromEmail(ctx.user && ctx.user.email); + slot.innerHTML = `
    +
    Start with your domain

    See where you stand before setting anything up: email authentication, HTTPS, security headers, DNS hardening and security.txt, read live from public records.

    +
    + ${chip ? `
    From your sign-up email:
    ` : ""} +

    Use a domain you own or manage. The result is saved to this workspace, with each issue as a finding.

    + + + +
    `; + const form = slot.querySelector(".dk-fr-form"), input = form.querySelector("input"); + form.addEventListener("submit", (e) => { e.preventDefault(); if (!S.running) { run(input.value); input.value = ""; } }); + slot.addEventListener("click", (e) => { + const t = e.target.closest("button"); + if (!t || !slot.contains(t)) return; + if (t.dataset.frDomain && !S.running) run(t.dataset.frDomain); + else if (t.dataset.dmcTool && S.ctx.openTool) S.ctx.openTool(t.dataset.dmcTool); + else if (t.dataset.frGo === "findings" && S.ctx.go) S.ctx.go("findings"); + else if (t.dataset.frGo === "secgraph" && S.ctx.openTool) S.ctx.openTool("secgraph"); + }); + paint(); + // a /check/ link or the landing's hand-off runs at once; the hand-off key is + // cleared as soon as it is used, so it never re-runs on a later visit + const stored = storedFirstDomain(); + const pending = normalizeDomain(ctx.pending || stored); + if (stored) clearStored(); + if (pending && !S.running && pending !== (S.res && S.res.domain)) run(pending); +} diff --git a/public/js/check/landing-check.js b/public/js/check/landing-check.js new file mode 100644 index 00000000..e234dfe2 --- /dev/null +++ b/public/js/check/landing-check.js @@ -0,0 +1,147 @@ +// Copyright (c) 2026 Darknode-Official. All rights reserved. See LICENSE. +// +// Signed-out domain check: the landing hero form and the shareable /check/ page. +// Both run check/domain-check.js live in the visitor's browser. Nothing is stored and no +// account is needed; the only thing kept is the domain in localStorage (dn_first_domain) +// when the visitor chooses to continue in the Deck, so the Deck can run it on first open. + +import { renderResult, renderPending } from "/js/check/check-view.js?v=1"; + +const loadCheck = () => import("/js/check/domain-check.js?v=1"); +const CHECK_PATH = /^\/check\/([^/]+)\/?$/; +export const shareUrl = (domain) => location.origin + "/check/" + encodeURIComponent(domain); + +// The domain in a /check/ path, or null on any other path. +export function checkPathDomain(pathname) { + const m = CHECK_PATH.exec(String(pathname || "")); + if (!m) return null; + try { return decodeURIComponent(m[1]); } catch (_) { return m[1]; } +} + +function setNoindex() { + let robots = document.querySelector('meta[name="robots"]'); + if (!robots) { robots = document.createElement("meta"); robots.name = "robots"; document.head.appendChild(robots); } + robots.content = "noindex"; +} + +async function copyLink(btn, domain) { + const url = shareUrl(domain); + const label = btn.textContent; + try { + await navigator.clipboard.writeText(url); + btn.textContent = "Link copied"; + } catch (_) { + // no clipboard permission: show the link selected so it can be copied by hand + let box = btn.parentElement.querySelector(".dmc-linkbox"); + if (!box) { box = document.createElement("input"); box.className = "dmc-linkbox"; box.readOnly = true; box.setAttribute("aria-label", "Link to this result"); btn.insertAdjacentElement("afterend", box); } + box.value = url; box.focus(); box.select(); + btn.textContent = "Copy the link"; + } + setTimeout(() => { btn.textContent = label; }, 2200); +} + +// The bar under a finished result: share it, and continue in the Deck. The wording never +// promises monitoring (monitors are a Pro feature); it says what the free account does. +function actionsBar(res, actions) { + const bar = document.createElement("div"); + bar.className = "dmc-next"; + const open = res.checks.filter((c) => c.status === "fail" || c.status === "warn").length; + bar.innerHTML = `
    ${open ? "Fix these in the Deck, free account" : "Save this result in the Deck, free account"} + ${open ? "The Deck saves each issue as a finding and opens the tool that fixes it." : "The Deck saves this check to your workspace so you have a baseline."} This domain is checked again when you first open it.
    +
    `; + bar.querySelector(".dmc-cta").addEventListener("click", () => { + try { localStorage.setItem("dn_first_domain", res.domain); } catch (_) {} + if (actions && actions.onGetStarted) actions.onGetStarted(); + }); + bar.querySelector(".dmc-copy").addEventListener("click", (e) => copyLink(e.currentTarget, res.domain)); + return bar; +} + +// Run one check into `out`, rendering progressively. Returns the final result or null. +let runSeq = 0; +async function runInto(out, raw, { actions, msg, button, onStart }) { + const seq = ++runSeq; + const say = (t) => { if (msg) { msg.textContent = t || ""; msg.hidden = !t; } }; + say(""); + const mod = await loadCheck().catch(() => null); + if (seq !== runSeq) return null; + if (!mod) { say("The checker did not load. Check your connection and try again."); return null; } + const domain = mod.normalizeDomain(raw); + if (!domain) { say(String(raw || "").trim() ? "That is not a domain name. Enter one like example.com." : "Enter a domain, like example.com."); return null; } + out.hidden = false; + out.innerHTML = renderPending(domain); + if (onStart) onStart(); + const prevLabel = button ? button.textContent : ""; + if (button) { button.disabled = true; button.textContent = "Checking…"; } + try { + const res = await mod.runDomainCheck(domain, { onProgress: (r) => { if (seq === runSeq) out.innerHTML = renderResult(r, { running: true }); } }); + if (seq !== runSeq) return null; + out.innerHTML = renderResult(res); + out.firstElementChild.appendChild(actionsBar(res, actions)); + return res; + } catch (e) { + if (seq !== runSeq) return null; + out.innerHTML = ""; out.hidden = true; + say((e && e.message) || "The check failed. Try again."); + return null; + } finally { + if (button && seq === runSeq) { button.disabled = false; button.textContent = prevLabel; } + } +} + +function wireForm(form, out, actions, onDone) { + const input = form.querySelector("input"); + const button = form.querySelector("button[type=submit]"); + const msg = form.querySelector(".dmc-msg"); + form.addEventListener("submit", async (e) => { + e.preventDefault(); + // bring the result into view when it starts below the fold (the hero on a phone) + const onStart = () => { const r = out.getBoundingClientRect(); if (r.top > window.innerHeight * 0.6 || r.top < 0) out.scrollIntoView({ behavior: "smooth", block: "start" }); }; + const res = await runInto(out, input.value, { actions, msg, button, onStart }); + if (res && onDone) onDone(res); + }); +} + +// The /check/ page: replaces the landing sections, like the other public pages. +function mountCheckPage(view, actions, raw) { + view.querySelectorAll(".section, .hero, .cta-final").forEach((sec) => { sec.hidden = true; }); + setNoindex(); + const page = document.createElement("section"); + page.className = "section dn-checkpage"; + page.innerHTML = `
    +
    Back to homeFree to use, no account needed.
    +

    Domain check

    +

    Run live in your browser when this page opened, from public DNS records and HTTP responses. Nothing about it is stored, so the link always shows the current state.

    +
    +
    + +
    +

    Reads public DNS records and HTTP headers only. Use a domain you own or are allowed to assess.

    + +
    +
    `; + page.querySelector(".dedicated-back").addEventListener("click", (e) => { e.preventDefault(); window.location.href = "/"; }); + page.querySelector(".dn-pubbar .btn").addEventListener("click", () => actions && actions.onSignIn && actions.onSignIn()); + view.prepend(page); + const out = page.querySelector("#dmcOut"); + const form = page.querySelector("#dmcForm"); + const show = (res) => { + // the address bar always names the domain on screen, so a copied URL shares this result + try { const p = "/check/" + encodeURIComponent(res.domain); if (location.pathname !== p) history.replaceState(history.state, "", p); } catch (_) {} + document.title = "Domain check: " + res.domain + " — Darknode"; + }; + wireForm(form, out, actions, (res) => { show(res); form.querySelector("input").value = ""; }); + document.title = "Domain check — Darknode"; + window.scrollTo(0, 0); + runInto(out, raw, { actions, msg: form.querySelector(".dmc-msg") }).then((res) => { if (res) show(res); }); +} + +/** Wire the hero form, or build the /check/ page when the path is one. */ +export function mountLandingCheck(view, actions) { + const raw = checkPathDomain(location.pathname); + if (raw != null) return mountCheckPage(view, actions, raw); + const form = view.querySelector(".hero #dmcForm"); + const out = view.querySelector(".hero #dmcOut"); + if (form && out) wireForm(form, out, actions); +} + diff --git a/public/js/core/coverage.js b/public/js/core/coverage.js index bd712391..e0510ee5 100644 --- a/public/js/core/coverage.js +++ b/public/js/core/coverage.js @@ -35,7 +35,7 @@ export const ASSET_COV = [ refs: ["CIS v8 11.2", "ISO 27001 A.8.13"], what: "is a managed host with no backup coverage, so it could not be recovered after ransomware or data loss", fix: "Bring the host into a backup policy with a tested restore (Backup Readiness)." }, - { id: "exposure", label: "External exposure", sources: ["domainguard", "posture", "tlsfleet", "netexposure"], + { id: "exposure", label: "External exposure", sources: ["domainguard", "posture", "tlsfleet", "netexposure", "domaincheck"], finding: false }, ]; diff --git a/public/js/core/playbooks.js b/public/js/core/playbooks.js index ee6abced..74897f2a 100644 --- a/public/js/core/playbooks.js +++ b/public/js/core/playbooks.js @@ -15,7 +15,7 @@ const has = (hay, ...needles) => { const s = low(hay); return needles.some((n) = // tool is telling. Kept small and honest — only tools that clearly map to one domain. const TOOL_DOMAIN = { identity: ["caaudit", "signins", "signin-forensics", "privaudit", "jml", "accessreview", "oauthgov", "nhi", "vpnaudit"], - exposure: ["netexposure", "domainguard", "tlsfleet", "posture", "surface"], + exposure: ["netexposure", "domainguard", "tlsfleet", "posture", "surface", "domaincheck"], cloud: ["iacscan", "k8saudit", "cloudtrail", "fleetcomply"], secret: ["codescan", "leakprobe", "dlp", "iacscan"], phishing: ["phishtriage"], diff --git a/public/js/deck-ui.js b/public/js/deck-ui.js index b412905b..6156ee7c 100644 --- a/public/js/deck-ui.js +++ b/public/js/deck-ui.js @@ -1881,6 +1881,11 @@ export function renderDeck(host, opts) { // Onboarding (A3): a short checklist whose steps complete from REAL signals, not a // manual tick. Only the "dismissed" flag persists; completion is always recomputed. let onbState = opts.onboarding || {}; + // First run: the overview opens with a live domain check (js/check/first-run.js) while no + // scan has run, or when a /check/ link or the landing hand-off names a domain. + // Once shown it stays for this page load, so the user keeps their result on screen. + let frPending = "", frShown = false, frMod = null; + const frStored = () => { try { return localStorage.getItem("dn_first_domain") || ""; } catch (_) { return ""; } }; function onbSteps(){ let aiConnected = INTEGRATIONS.some((i) => i.kind === "ai" && conns[i.id] && conns[i.id].connected); if (!aiConnected) { try { const u = window.dnKeys && window.dnKeys.uid(); aiConnected = !!u && Object.keys(localStorage).some((k) => k.indexOf("dnk:" + u + ":dn_key_") === 0); } catch (_) {} } @@ -2128,6 +2133,8 @@ export function renderDeck(host, opts) { const sp = raw.match(/^(personal|enterprise)\/([\w-]+)$/); if (sp) return { scene: sp[1], arg: { tab: sp[2] } }; if (raw === "overview") return { scene: "overview" }; // the weekly digest links /overview + const ck = raw.match(/^check\/([^/\s]+)$/); // a shared domain check runs on the overview + if (ck) { let d = ck[1]; try { d = decodeURIComponent(d); } catch (_) {} return { scene: "overview", arg: { check: d } }; } for (const k in SCENES) if (k !== "section" && (k in SCENE_PATH ? SCENE_PATH[k] : k) === raw) return { scene: k }; return null; } @@ -2155,7 +2162,7 @@ export function renderDeck(host, opts) { setNav(scene === "section" ? "section:" + curSect : "scene:" + scene); for (const k in sceneEls) sceneEls[k].hidden = k !== scene; try { closeDrawer(); } catch (_) {} // an Integrations details panel does not follow you to another page - if (scene === "overview") renderOverview(); + if (scene === "overview") { if (arg && arg.check) frPending = arg.check; renderOverview(); } else if (scene === "surface") renderSurface(); else if (scene === "threat") renderThreat(); else if (scene === "cloud") renderCloud(); @@ -3197,6 +3204,8 @@ export function renderDeck(host, opts) { const steps = onbSteps(); const onbDone = steps.filter((x) => x.done).length; const showOnb = !onbState.dismissed && onbDone < steps.length; + const scanStep = steps.find((x) => x.id === "scan"); + const frOn = frShown || !!frPending || !!frStored() || !!(scanStep && !scanStep.done); const onbCard = showOnb ? `
    Getting started${onbDone} of ${steps.length} done
    @@ -3212,6 +3221,7 @@ export function renderDeck(host, opts) {

    ${esc(greet)}, ${esc(first)}

    Your security posture, with live vulnerability intelligence from NVD, CISA KEV and FIRST EPSS.

    ${now.toLocaleDateString([], { weekday: "long", month: "long", day: "numeric" })}
    + ${frOn ? '
    ' : ""}
    ${IC.spark} @@ -3266,6 +3276,19 @@ export function renderDeck(host, opts) { `; pruneLocked(el); el.querySelectorAll(".dk-qacard[data-tool]").forEach((b) => b.onclick = () => openTool(b.dataset.tool, secLabel[b.dataset.tool] || b.dataset.tool)); + // first run: a live domain check before any setup (drawn at once when already loaded, so a re-render does not flash) + const frSlot = el.querySelector("#dkFirstRun"); + if (frSlot) { + frShown = true; + const mountFr = (m) => { + if (!frSlot.isConnected) return; + frMod = m; + const pending = frPending; frPending = ""; + m.mountFirstRun(frSlot, { user, pending, isLocked, toolName: (id) => secLabel[id] || "", openTool: (id) => openTool(id, secLabel[id] || id), go, onSaved: refreshGraphScene }); + }; + if (frMod) mountFr(frMod); + else import("/js/check/first-run.js?v=1").then(mountFr).catch(() => frSlot.remove()); + } // 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); }; @@ -3377,7 +3400,7 @@ export function renderDeck(host, opts) { sig.hot = real.filter((e) => /^(critical|high)$/i.test(e.severity || "") && !/^(resolved|closed)$/i.test(e.status || "")).length; const hk = el.querySelector('[data-k="hot"] .kn'); if (hk) hk.textContent = real.length ? sig.hot.toLocaleString() : "—"; // Nothing real to score yet: one get-started card replaces the two empty posture tiles. - const st = el.querySelector("#dkStart"); if (st) { st.hidden = !!real.length; el.querySelectorAll('[data-k="exposure"],[data-k="hot"]').forEach((k) => { k.hidden = !real.length; }); } + const st = el.querySelector("#dkStart"); if (st) { st.hidden = !!real.length || !!el.querySelector("#dkFirstRun"); el.querySelectorAll('[data-k="exposure"],[data-k="hot"]').forEach((k) => { k.hidden = !real.length; }); } recomputeExposure(); }).catch(() => { const kn = el.querySelector('[data-k="graph"] .kn'); if (kn) kn.textContent = "0"; sig.real = 0; recomputeExposure(); }); fillSince(el); @@ -5210,6 +5233,7 @@ export function renderDeck(host, opts) { // a page link (/surface, /area/code) opens that page; / restores the last one const route0 = primary ? routeOf(location.pathname) : null; if (route0 && route0.scene !== "overview") initial = route0.scene; + else if (route0 && route0.arg && route0.arg.check) initial = "overview"; // a link to a page or tool above the plan: open Plans and say why, instead of quietly // landing somewhere else (the page itself stays hidden, as in the sidebar) const lockedKey = route0 && route0.scene !== "overview" ? (route0.scene === "section" ? "section:" + route0.arg : "scene:" + route0.scene) diff --git a/public/js/deck/routes.js b/public/js/deck/routes.js index 538659a1..2dfab2cd 100644 --- a/public/js/deck/routes.js +++ b/public/js/deck/routes.js @@ -19,6 +19,7 @@ export function isAppPath(pathname, secs) { if (raw === "console" || raw.startsWith("console/")) raw = raw.slice(7).replace(/^\/+/, ""); if (!raw || raw === "index.html") return true; if (/^(area|personal|enterprise)\/[\w-]+$/.test(raw)) return true; + if (/^check\/[^/\s]+$/.test(raw)) return true; // a shareable domain check: /check/ for (const k in SCENES) if (k !== "section" && (k === raw || SCENE_PATH[k] === raw)) return true; if (raw.includes("/")) return false; const sec = raw.startsWith("tool-") ? raw : raw.replace(/-([a-z])/g, (_, c) => c.toUpperCase()); diff --git a/public/js/docs.js b/public/js/docs.js index 8b6ee27f..7d396d84 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."], + ["3.3.x", "Live integrations: Deck security integrations are connected only after a live key test, through a relay to fixed provider endpoints (VirusTotal, Shodan, AbuseIPDB, GreyNoise, OTX, urlscan, SecurityTrails, ipinfo, Have I Been Pwned, Hunter, Pulsedive, Hybrid Analysis, plus keyless NVD and CIRCL CVE). The Deck Assistant can run lookups on connected integrations, asking first each time unless you choose Always allow. Text boxes no longer refill from saved lists on reload; a Load saved list button brings them back on request. A full bug sweep fixed about 90 issues across the Deck, the business tools, the flagship tools and all 780 quick utilities, among them wrong file hashes for binary files, a strict CSP graded as broken, missed SQL injection and display-name spoofing, the ASN Explorer (moved from the retired BGPView to RIPEstat), and spreadsheet formula injection in CSV exports. Nexus background sessions (nexus bg / attach / sessions); signed-in Nexus and desktop app report version, OS and VM counts every 6 hours (/shareusage off, or Settings > Share app usage). Docs: the Nexus Commands tab lists every Nexus command, and Cost Saving shows /cheap before-and-after costs on each Claude model, measured on real sessions. A free domain check on the home page, with no sign-up, grades email authentication, HTTPS, security headers, DNSSEC, CAA and security.txt and shows what each check is worth; a /check/your-domain link runs it again live, and a new Deck opens on the same check with each issue saved as a finding."], ["3.2.x", "Business security platform: the Darknode Deck with native Personal and Organization spaces (domain posture grading, certificate watch, link and email phishing checks, code-secret scanning, sensitive-data checks with redaction, domain portfolios and fleet views), a Web toolkit tab linking the hands-on web-security tools, plan-based tool availability, team workspaces, and removal of the off-topic financial tools."], ["3.1.x", "Web console line: flagship platforms (PHANTOM packet/network ops, CITADEL SOC console, ORACLE threat-intel engine, SPECTRE cloud posture, CRUCIBLE defensive wargaming, NAVARCH maritime defense), a platform-wide Security Graph that cross-links findings, the Sentinel Eye 3D threat globe, 125 security tools plus 780 quick utilities, the Professional theme, the Darknode assistant (Help button in the top bar), and Nexus AI integration."], ["2.29.x", "Nexus multi-engine agent: /cowork model tiering, /lean /effort /cheap /estimate, local RAG (/index), /race /ensemble /bench, /plan /watch /agents (worktree-isolated), /guard /secrets /scan /redact /offline, git checkpoints (/undo /redo /rewind), MCP + hooks, ~56 commands. NEXUS.md now reaches the Claude engine; plan mode is truly read-only."], @@ -120,6 +120,7 @@ node darknode.js nexus init # optional: scaffold .nexus/ project
    Where did the console go?

    The Darknode Deck is the workspace after you sign in, and every tool opens inside it: use the sidebar or Ctrl K search. The older console view has been retired for users; a link to a tool (darknode.ai/<tool>) opens that tool in the Deck.

    Which tools do I get on my plan?

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

    Do the checks touch my systems?

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

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

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

    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.

    diff --git a/public/js/landing.js b/public/js/landing.js index bedbbb9c..e64be694 100644 --- a/public/js/landing.js +++ b/public/js/landing.js @@ -4,6 +4,7 @@ import { db } from "/js/firebase.js?v=20261021a"; import { collection, addDoc, serverTimestamp } from "https://www.gstatic.com/firebasejs/12.17.0/firebase-firestore.js"; +import { mountLandingCheck } from "/js/check/landing-check.js?v=1"; const GITHUB = "https://github.com/Darknode-Official"; @@ -71,6 +72,7 @@ function loadHeroLive(view) { export function renderLanding(view, actions) { setTimeout(() => loadHeroLive(view), 0); + queueMicrotask(() => mountLandingCheck(view, actions)); // hero domain check, or the /check/ page view.innerHTML = ` @@ -79,26 +81,18 @@ export function renderLanding(view, actions) {
    -
    Runs air-gapped · Deterministic · Your data stays yours
    +
    Deterministic · Explainable · Offline in the CLI and desktop app

    Find the real risks in your
    code

    -

    Darknode scans your code, cloud, dependencies, configs and records for real vulnerabilities and risks — with accurate, explainable, deterministic engines that run on your own infrastructure. No black-box AI deciding severity, no data leaving your estate.

    +

    Darknode checks your domains, code, cloud, dependencies and configs for real vulnerabilities and risks, with deterministic engines that show how they reached each result. No black-box AI deciding severity. The CLI and desktop app run on your own machines and work offline with local Ollama models.

    + + +
    +

    Free, no sign-up, results in seconds. Reads public DNS records and HTTP headers: email authentication, HTTPS, security headers, DNSSEC, CAA and security.txt.

    + +
    - - - - Star on GitHub - -
    -
    - Built with -
    - Node.js - Python - Ollama - Claude - Firebase - Linux -
    + + See the Deck
    +
    diff --git a/test/check/domain-check.test.mjs b/test/check/domain-check.test.mjs new file mode 100644 index 00000000..476435f9 --- /dev/null +++ b/test/check/domain-check.test.mjs @@ -0,0 +1,293 @@ +// Domain check (public/js/check/domain-check.js): input normalisation, the weighted grade, +// each check's verdict from real-shaped DoH / proxy answers, and the findings mapping. +// The network is injected: a fake resolver answers in Cloudflare DoH JSON and a fake +// fetcher answers like the Worker /api/fetch proxy (net.js dnFetch). + +import { test, group, assert } from "../harness.mjs"; +import { + CHECKS, CREDIT, normalizeDomain, isFreeMail, workDomainFromEmail, evaluate, gradeChecks, + runDomainCheck, domainCheckFindings, domainCheckHeld, isProxyError, runLevel, +} from "../../public/js/check/domain-check.js"; + +const T = { A: 1, MX: 15, TXT: 16, AAAA: 28, DS: 43, CAA: 257 }; +const ans = (name, type, datas, extra = {}) => ({ Status: 0, AD: false, Answer: datas.map((data) => ({ name, type: T[type], TTL: 300, data })), ...extra }); +const nodata = (extra = {}) => ({ Status: 0, AD: false, ...extra }); + +// a fake resolver from a "name TYPE" -> answer table; unknown names are NXDOMAIN +function resolver(table) { + const calls = []; + const doh = async (name, type, o = {}) => { + calls.push(name + " " + type + (o.cd ? " cd" : "")); + const k = name + " " + type + (o.cd ? " cd" : ""); + if (k in table) { const v = table[k]; if (v instanceof Error) throw v; return v; } + return { Status: 3 }; + }; + doh.calls = calls; + return doh; +} +const GOOD_HEADERS = { + "strict-transport-security": "max-age=31536000; includeSubDomains", + "content-security-policy": "default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'", + "x-content-type-options": "nosniff", + "x-frame-options": "DENY", + "referrer-policy": "strict-origin-when-cross-origin", +}; +const STXT = "Contact: mailto:security@good.test\nExpires: 2099-01-01T00:00:00.000Z\n"; +function fetcher(map) { + return async (url) => { + const v = map[url]; + if (v instanceof Error) throw v; + if (!v) throw new Error("connect ECONNREFUSED"); + return { url, finalUrl: v.finalUrl || url, status: v.status || 200, headers: v.headers || {}, body: v.body || "" }; + }; +} +const goodDns = (d) => ({ + [`${d} A`]: ans(d, "A", ["192.0.2.10"], { AD: true }), + [`${d} AAAA`]: nodata({ AD: true }), + [`${d} TXT`]: ans(d, "TXT", ['"v=spf1 include:_spf.mail.test -all"']), + [`_dmarc.${d} TXT`]: ans("_dmarc." + d, "TXT", [`"v=DMARC1; p=reject; rua=mailto:dmarc@${d}"`]), + [`selector1._domainkey.${d} TXT`]: ans("selector1._domainkey." + d, "TXT", ['"v=DKIM1; k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC"']), + [`${d} MX`]: ans(d, "MX", ["10 mx1.mail.test."]), + [`${d} DS`]: ans(d, "DS", ["2371 13 2 ABCDEF"]), + [`${d} CAA`]: ans(d, "CAA", ['0 issue "ca.test"']), +}); +const goodWeb = (d) => fetcher({ + [`https://${d}/`]: { status: 200, headers: GOOD_HEADERS }, + [`http://${d}/`]: { status: 200, finalUrl: `https://${d}/`, headers: GOOD_HEADERS }, + [`https://${d}/.well-known/security.txt`]: { status: 200, body: STXT }, +}); +const byId = (res) => Object.fromEntries(res.checks.map((c) => [c.id, c])); + +group("domain check: catalog and grading", () => { + test("weights total 100 and every check names a group and a Deck tool", () => { + assert.equal(CHECKS.reduce((s, c) => s + c.weight, 0), 100); + for (const c of CHECKS) assert.ok(c.group && c.tool && c.weight > 0, c.id); + assert.equal(new Set(CHECKS.map((c) => c.id)).size, CHECKS.length); + }); + test("pass earns all, warn half, fail none", () => { + assert.deepEqual(CREDIT, { pass: 1, warn: 0.5, fail: 0 }); + const g = gradeChecks([{ status: "pass", weight: 10 }, { status: "warn", weight: 10 }, { status: "fail", weight: 20 }]); + assert.equal(g.earned, 15); assert.equal(g.possible, 40); assert.equal(g.score, 38); assert.equal(g.grade, "F"); + }); + test("error and na are left out of the grade, never counted as a pass or a zero", () => { + const checks = [{ status: "pass", weight: 60 }, { status: "error", weight: 30 }, { status: "na", weight: 10 }]; + const g = gradeChecks(checks); + assert.equal(g.score, 100); assert.equal(g.grade, "A"); assert.equal(g.possible, 60); assert.equal(g.applicable, 90); + assert.equal(checks[1].points, null); assert.equal(checks[2].points, null); assert.equal(checks[0].points, 60); + }); + test("under half of the applicable weight graded -> N/A, not a letter", () => { + const g = gradeChecks([{ status: "pass", weight: 40 }, { status: "error", weight: 60 }]); + assert.equal(g.grade, "N/A"); assert.equal(g.score, null); + }); + test("letter bands follow the posture engine (A 90, B 80, C 65, D 50)", () => { + const at = (pct) => gradeChecks([{ status: "pass", weight: pct }, { status: "fail", weight: 100 - pct }]).grade; + assert.equal(at(90), "A"); assert.equal(at(89), "B"); assert.equal(at(80), "B"); assert.equal(at(65), "C"); assert.equal(at(50), "D"); assert.equal(at(49), "F"); + }); + test("a check still waiting for its source is pending and not graded", () => { + const checks = evaluate({ domain: "x.test", org: "x.test", webHost: "x.test", web: "pending" }); + assert.ok(checks.every((c) => c.status === "pending")); + assert.equal(gradeChecks(checks).grade, "N/A"); + }); +}); + +group("domain check: input", () => { + test("pasted URLs, emails and www reduce to the bare domain", () => { + assert.equal(normalizeDomain("https://WWW.Example.com/path?q=1#x"), "example.com"); + assert.equal(normalizeDomain("you@example.org"), "example.org"); + assert.equal(normalizeDomain("mailto:sec@sub.example.net"), "sub.example.net"); + assert.equal(normalizeDomain("example.com:8443."), "example.com"); + assert.equal(normalizeDomain("bücher.example"), "xn--bcher-kva.example"); + }); + test("not a domain -> empty", () => { + for (const v of ["", " ", "localhost", "192.0.2.1", "exa mple.com", "-bad-.com", null]) assert.equal(normalizeDomain(v), "", String(v)); + }); + test("free-mail and reserved domains are never offered as the user's domain", () => { + assert.ok(isFreeMail("gmail.com")); assert.ok(isFreeMail("yahoo.co.uk")); assert.ok(isFreeMail("outlook.de")); + assert.equal(workDomainFromEmail("a@gmail.com"), ""); + assert.equal(workDomainFromEmail("a@example.com"), ""); + assert.equal(workDomainFromEmail("a@corp.test"), ""); + assert.equal(workDomainFromEmail("Jane@Acme-Widgets.io"), "acme-widgets.io"); + assert.equal(workDomainFromEmail("no-at-sign"), ""); + }); +}); + +group("domain check: live run with injected sources", () => { + test("a well-configured domain passes every check (A)", async () => { + const res = await runDomainCheck("good.test", { doh: resolver(goodDns("good.test")), fetchUrl: goodWeb("good.test") }); + const bad = res.checks.filter((c) => c.status !== "pass").map((c) => c.id + ":" + c.status + ":" + c.detail); + assert.deepEqual(bad, []); + assert.equal(res.grade, "A"); assert.equal(res.score, 100); assert.equal(res.possible, 100); + assert.equal(runLevel(res), "good"); + }); + test("progress snapshots arrive with pending checks, and the last one is complete", async () => { + const snaps = []; + const res = await runDomainCheck("good.test", { doh: resolver(goodDns("good.test")), fetchUrl: goodWeb("good.test"), onProgress: (r) => snaps.push(r) }); + assert.ok(snaps.length >= 3); + assert.ok(snaps.some((s) => s.checks.some((c) => c.status === "pending"))); + assert.equal(res.counts.pending, 0); + }); + test("NXDOMAIN stops the check with a plain reason", async () => { + let msg = ""; + try { await runDomainCheck("nope.test", { doh: resolver({}), fetchUrl: goodWeb("nope.test") }); } catch (e) { msg = e.message; } + assert.ok(/does not exist/.test(msg), msg); + }); + test("invalid input is rejected before any lookup", async () => { + const doh = resolver({}); + let msg = ""; + try { await runDomainCheck("not a domain", { doh, fetchUrl: goodWeb("x") }); } catch (e) { msg = e.message; } + assert.ok(/domain name/.test(msg)); assert.equal(doh.calls.length, 0); + }); + test("a failing proxy makes the web checks 'error', not fails, and they leave the grade", async () => { + const proxyDown = async () => { throw new Error("Network error reaching the Darknode proxy: Failed to fetch"); }; + const res = await runDomainCheck("good.test", { doh: resolver(goodDns("good.test")), fetchUrl: proxyDown }); + const c = byId(res); + for (const id of ["https", "redirect", "hsts", "csp", "frame", "nosniff", "referrer", "securitytxt"]) assert.equal(c[id].status, "error", id); + assert.equal(c.spf.status, "pass"); + assert.equal(res.possible, 46); // email 32 + DNS 14 + assert.equal(res.grade, "N/A"); // 46 of 100 applicable points graded is under half + }); + test("a resolver outage on one record is 'error' for that check only", async () => { + const t = goodDns("good.test"); t["good.test CAA"] = { Status: 2 }; + const res = await runDomainCheck("good.test", { doh: resolver(t), fetchUrl: goodWeb("good.test") }); + const c = byId(res); + assert.equal(c.caa.status, "error"); assert.ok(/SERVFAIL/.test(c.caa.detail)); + assert.equal(c.caa.points, null); assert.equal(res.possible, 93); assert.equal(res.score, 100); + }); + test("a weak site: no HTTPS redirect, missing headers, no security.txt", async () => { + const d = "weak.test", t = goodDns(d); + t[`${d} TXT`] = ans(d, "TXT", ['"v=spf1 include:_spf.mail.test ~all"']); + t[`_dmarc.${d} TXT`] = ans("_dmarc." + d, "TXT", ['"v=DMARC1; p=none"']); + t[`${d} A`] = ans(d, "A", ["192.0.2.20"]); t[`${d} AAAA`] = nodata(); delete t[`${d} DS`]; delete t[`${d} CAA`]; + const res = await runDomainCheck(d, { doh: resolver(t), fetchUrl: fetcher({ [`https://${d}/`]: { status: 200 }, [`http://${d}/`]: { status: 200 } }) }); + const c = byId(res); + assert.equal(c.spf.status, "warn"); assert.equal(c.dmarc.status, "warn"); assert.ok(/p=quarantine/.test(c.dmarc.fix), c.dmarc.fix); + assert.equal(c.https.status, "pass"); assert.equal(c.redirect.status, "fail"); + for (const id of ["hsts", "csp", "frame", "nosniff"]) assert.equal(c[id].status, "fail", id); + assert.equal(c.referrer.status, "warn"); + assert.equal(c.dnssec.status, "warn"); assert.ok(/no DS record/.test(c.dnssec.detail)); + assert.equal(c.caa.status, "warn"); assert.equal(c.securitytxt.status, "warn"); + assert.ok(c.redirect.fix.length > 0); + assert.equal(res.grade, "F"); + }); + test("an existing SPF or DMARC record gets the fix for its problem, not 'publish a record'", async () => { + const run = async (spf, dmarc) => { + const d = "mail.test", t = goodDns(d); + if (spf == null) t[`${d} TXT`] = nodata(); else t[`${d} TXT`] = ans(d, "TXT", spf.map((s) => `"${s}"`)); + if (dmarc == null) t[`_dmarc.${d} TXT`] = nodata(); else t[`_dmarc.${d} TXT`] = ans("_dmarc." + d, "TXT", [`"${dmarc}"`]); + return byId(await runDomainCheck(d, { doh: resolver(t), fetchUrl: goodWeb(d) })); + }; + let c = await run(["v=spf1 include:_spf.mail.test ~all"], "v=DMARC1; p=quarantine; rua=mailto:r@mail.test"); + assert.ok(/change ~all to -all/.test(c.spf.fix), c.spf.fix); assert.ok(!/Publish/.test(c.spf.fix)); + assert.ok(/p=reject/.test(c.dmarc.fix) && !/Publish/.test(c.dmarc.fix), c.dmarc.fix); + c = await run(["v=spf1 +all"], "v=DMARC1; p=reject"); + assert.equal(c.spf.status, "fail"); assert.ok(/Replace \+all with -all/.test(c.spf.fix), c.spf.fix); + assert.ok(/rua=mailto:/.test(c.dmarc.fix) && /^Add/.test(c.dmarc.fix), c.dmarc.fix); + c = await run(["v=spf1 -all", "v=spf1 include:_spf.mail.test -all"], "v=DMARC1; p=reject; pct=50; rua=mailto:r@mail.test"); + assert.ok(/Merge/.test(c.spf.fix), c.spf.fix); assert.ok(/pct=100/.test(c.dmarc.fix), c.dmarc.fix); + c = await run(null, null); + assert.equal(c.spf.status, "fail"); assert.ok(/^Publish one TXT record/.test(c.spf.fix), c.spf.fix); + assert.equal(c.dmarc.status, "fail"); assert.ok(/^Publish a TXT record at _dmarc\.mail\.test/.test(c.dmarc.fix), c.dmarc.fix); + }); + test("HTTPS down at the site is a fail; plain-HTTP-only headers fail HSTS", async () => { + const d = "plain.test"; + const res = await runDomainCheck(d, { doh: resolver(goodDns(d)), fetchUrl: fetcher({ [`https://${d}/`]: new Error("TLS handshake failed"), [`http://${d}/`]: { status: 200, headers: GOOD_HEADERS } }) }); + const c = byId(res); + assert.equal(c.https.status, "fail"); assert.ok(/TLS handshake failed/.test(c.https.detail)); + assert.equal(c.redirect.status, "fail"); + assert.equal(c.hsts.status, "fail"); assert.ok(/plain HTTP/.test(c.hsts.detail)); + assert.equal(c.csp.status, "pass"); // graded from the HTTP response + }); + test("closed port 80 with working HTTPS is a pass for the redirect check", async () => { + const d = "tls-only.test"; + const res = await runDomainCheck(d, { doh: resolver(goodDns(d)), fetchUrl: fetcher({ [`https://${d}/`]: { status: 200, headers: GOOD_HEADERS }, [`http://${d}/`]: new Error("connect ECONNREFUSED") }) }); + assert.equal(byId(res).redirect.status, "pass"); + }); + test("no address at the apex: the web checks run against www", async () => { + const d = "apexless.test", t = goodDns(d); + t[`${d} A`] = nodata({ AD: true }); t[`www.${d} A`] = ans("www." + d, "A", ["192.0.2.30"]); + const w = "www." + d; + const res = await runDomainCheck(d, { doh: resolver(t), fetchUrl: goodWeb(w) }); + assert.equal(res.webHost, w); assert.equal(byId(res).https.status, "pass"); + }); + test("no website at all: web checks are not applicable and the grade uses email + DNS", async () => { + const d = "mailonly.test", t = goodDns(d); + t[`${d} A`] = nodata({ AD: true }); + const res = await runDomainCheck(d, { doh: resolver(t), fetchUrl: async () => { throw new Error("must not fetch"); } }); + const c = byId(res); + for (const id of ["https", "redirect", "hsts", "csp", "frame", "nosniff", "referrer", "securitytxt"]) assert.equal(c[id].status, "na", id); + assert.equal(res.possible, 46); assert.equal(res.grade, "A"); + }); + test("a domain that sends no mail needs no DKIM; null MX passes", async () => { + const d = "parked.test", t = goodDns(d); + t[`${d} TXT`] = ans(d, "TXT", ['"v=spf1 -all"']); t[`${d} MX`] = ans(d, "MX", ["0 ."]); + delete t[`selector1._domainkey.${d} TXT`]; + const res = await runDomainCheck(d, { doh: resolver(t), fetchUrl: goodWeb(d) }); + const c = byId(res); + assert.equal(c.dkim.status, "na"); assert.equal(c.mx.status, "pass"); assert.ok(/Null MX/.test(c.mx.detail)); + }); + test("DKIM not found at the common selectors is a warning, not a fail", async () => { + const d = "nodkim.test", t = goodDns(d); delete t[`selector1._domainkey.${d} TXT`]; + const res = await runDomainCheck(d, { doh: resolver(t), fetchUrl: goodWeb(d) }); + assert.equal(byId(res).dkim.status, "warn"); + }); + test("broken DNSSEC (SERVFAIL that answers with checking disabled) fails DNSSEC", async () => { + const d = "bogus.test"; + // validating resolvers SERVFAIL every name in a bogus zone + const t = { [`${d} A`]: { Status: 2 }, [`${d} AAAA`]: { Status: 2 }, [`${d} TXT`]: { Status: 2 }, [`${d} A cd`]: ans(d, "A", ["192.0.2.40"]) }; + const res = await runDomainCheck(d, { doh: resolver(t), fetchUrl: goodWeb(d) }); + const c = byId(res); + assert.equal(c.dnssec.status, "fail"); assert.equal(c.https.status, "error"); assert.equal(c.spf.status, "error"); + }); + test("a subdomain inherits DMARC from its organisational domain and climbs for CAA", async () => { + const t = goodDns("org.test"); + t["app.org.test A"] = ans("app.org.test", "A", ["192.0.2.50"], { AD: true }); t["app.org.test AAAA"] = nodata(); + t["app.org.test TXT"] = ans("app.org.test", "TXT", ['"v=spf1 -all"']); + t["app.org.test MX"] = ans("app.org.test", "MX", ["0 ."]); + const res = await runDomainCheck("app.org.test", { doh: resolver(t), fetchUrl: goodWeb("app.org.test") }); + const c = byId(res); + assert.equal(c.dmarc.status, "pass"); assert.ok(/inherited from org\.test/.test(c.dmarc.detail), c.dmarc.detail); + assert.equal(c.caa.status, "pass"); assert.ok(/CAA at org\.test/.test(c.caa.detail)); + }); + test("an invalid security.txt is a warning that says why", async () => { + const d = "stxt.test"; + const res = await runDomainCheck(d, { doh: resolver(goodDns(d)), fetchUrl: fetcher({ + [`https://${d}/`]: { status: 200, headers: GOOD_HEADERS }, [`http://${d}/`]: { finalUrl: `https://${d}/`, headers: GOOD_HEADERS }, + [`https://${d}/.well-known/security.txt`]: { status: 200, body: "Contact: mailto:a@stxt.test\nExpires: 2000-01-01T00:00:00.000Z\n" } }) }); + const c = byId(res).securitytxt; + assert.equal(c.status, "warn"); assert.ok(/not valid/.test(c.detail), c.detail); + }); + test("an HTML app answering every path is not a security.txt", async () => { + const d = "spa.test"; + const res = await runDomainCheck(d, { doh: resolver(goodDns(d)), fetchUrl: fetcher({ + [`https://${d}/`]: { status: 200, headers: GOOD_HEADERS }, [`http://${d}/`]: { finalUrl: `https://${d}/`, headers: GOOD_HEADERS }, + [`https://${d}/.well-known/security.txt`]: { status: 200, body: "

    Contact: us

    " }, + [`https://${d}/security.txt`]: { status: 200, body: "" } }) }); + assert.equal(byId(res).securitytxt.status, "warn"); + }); +}); + +group("domain check: proxy errors and findings", () => { + test("proxy-side failures are told apart from the site not answering", () => { + for (const m of ["Network error reaching the Darknode proxy: x", "Rate limit exceeded — slow down and retry shortly.", "Origin not allowed", "blocked (non-public or reserved host)", "Live fetch is unavailable — the Darknode proxy is not configured.", "a.test could not be reached: its firewall blocked the request."]) + assert.ok(isProxyError(new Error(m)), m); + for (const m of ["connect ECONNREFUSED", "The operation was aborted", "a.test could not be reached: its name does not resolve to an address (DNS lookup failed)."]) + assert.notOk(isProxyError(new Error(m)), m); + }); + test("only failing and warning checks become findings, with stable ids", () => { + const res = { domain: "Weak.test", checks: [ + { id: "https", group: "https", label: "HTTPS", status: "fail", detail: "d1", fix: "f1" }, + { id: "csp", group: "headers", label: "Content-Security-Policy", status: "fail", detail: "d2", fix: "" }, + { id: "caa", group: "dns", label: "CAA records", status: "warn", detail: "d3", fix: "f3" }, + { id: "dkim", group: "email", label: "DKIM", status: "warn", detail: "d4", fix: "f4" }, + { id: "spf", group: "email", label: "SPF", status: "pass", detail: "ok" }, + { id: "dnssec", group: "dns", label: "DNSSEC", status: "error", detail: "x" }, + ] }; + const f = domainCheckFindings(res); + assert.deepEqual(f.map((x) => x.id), ["domaincheck|weak.test|https", "domaincheck|weak.test|csp", "domaincheck|weak.test|caa", "domaincheck|weak.test|dkim"]); + assert.deepEqual(f.map((x) => x.severity), ["high", "medium", "low", "low"]); + assert.equal(f[3].confidence, "review"); + assert.equal(f[1].recommendation, undefined); + assert.deepEqual(f[0].assets, [{ type: "DOMAIN", name: "weak.test" }]); + assert.deepEqual(domainCheckHeld(res), ["domaincheck|weak.test|dnssec"]); + }); +}); diff --git a/test/deck/routes.test.mjs b/test/deck/routes.test.mjs index aeb5641a..e06313a9 100644 --- a/test/deck/routes.test.mjs +++ b/test/deck/routes.test.mjs @@ -32,6 +32,10 @@ group("deck routes: isAppPath", () => { for (const p of ["/nonexistent-page-xyz", "/get-started", "/tool-zzz-nope", "/emailauth/extra", "/area/a/b", "/console/nope-nope"]) assert.notOk(isAppPath(p, secs), p); }); + test("a shareable domain check is an app path, one segment only", () => { + for (const p of ["/check/example.com", "/check/example.com/", "/check/xn--bcher-kva.example"]) assert.ok(isAppPath(p, secs), p); + for (const p of ["/check", "/check/", "/check/a/b"]) assert.notOk(isAppPath(p, secs), p); + }); test("hyphenated paths map to camelCase section ids", () => { assert.ok(isAppPath("/a-b", new Set(["aB"]))); assert.notOk(isAppPath("/a-b", new Set(["a-b"]))); From d3ccc4352bf4dc8f33ac135038e53811ee30fa85 Mon Sep 17 00:00:00 2001 From: Darknode-Official Date: Wed, 25 Nov 2026 09:30:59 -0800 Subject: [PATCH 2/2] check: record the reviewed XSS false positives on the result renders renderPending/renderResult (check-view.js) escape every interpolated value, including DNS and header text from the checked domain, and the domain is validated by normalizeDomain first. The scanner does not follow the escaping across the module boundary. --- public/js/check/landing-check.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/public/js/check/landing-check.js b/public/js/check/landing-check.js index e234dfe2..2704e4ac 100644 --- a/public/js/check/landing-check.js +++ b/public/js/check/landing-check.js @@ -69,14 +69,14 @@ async function runInto(out, raw, { actions, msg, button, onStart }) { const domain = mod.normalizeDomain(raw); if (!domain) { say(String(raw || "").trim() ? "That is not a domain name. Enter one like example.com." : "Enter a domain, like example.com."); return null; } out.hidden = false; - out.innerHTML = renderPending(domain); + out.innerHTML = renderPending(domain); // darknode-ignore: renderPending escapes every value it interpolates (check-view.js esc); the domain is validated by normalizeDomain first if (onStart) onStart(); const prevLabel = button ? button.textContent : ""; if (button) { button.disabled = true; button.textContent = "Checking…"; } try { const res = await mod.runDomainCheck(domain, { onProgress: (r) => { if (seq === runSeq) out.innerHTML = renderResult(r, { running: true }); } }); if (seq !== runSeq) return null; - out.innerHTML = renderResult(res); + out.innerHTML = renderResult(res); // darknode-ignore: renderResult escapes every value, including DNS and header text from the checked domain (check-view.js esc) out.firstElementChild.appendChild(actionsBar(res, actions)); return res; } catch (e) {