diff --git a/firebase.json b/firebase.json
index 7e35fea6..160ae3bd 100644
--- a/firebase.json
+++ b/firebase.json
@@ -22,7 +22,7 @@
{ "regex": "^/terms/?$", "destination": "/pages/terms.html" },
{ "regex": "^/privacy/?$", "destination": "/pages/privacy.html" },
{ "regex": "^/acceptable-use/?$", "destination": "/pages/acceptable-use.html" },
- { "regex": "^/(?:console(?:/|$))?(?:(?:area|personal|enterprise)/[\\w-]+|check/[^/]+|tool-[a-z0-9-]+|accessreview|activity|addressintel|admin|adversary|adversaryplaybook|aegis|ai|all-tools|api|apifuzzer|apikeys|apispec|apitester|asnexplorer|assistant|attacksim|audit|awareness|backupready|beta|binanalyze|breachclock|breachlookup|caaudit|cheats|citadel|cloud|cloudspend|cloudtrail|coder|codescan|compliance|compliance-center|con|connections|cookieinspect|correlations|corstester|cracklab|credaudit|crosswalk|crucible|cryptotools|cspevaluator|cvesearch|cvetimeline|cvsscalc|cyberbriefing|cyberrange|darknetradar|dataflow|dataviz|deadlines|deception|device|dlguide|dlp|dmarcreports|dns|dnshunt|docs|domainguard|dossier|downloads|education|emailauth|emailheader|embedsdk|encoding|engine|engines|enterprise|evidence|exploitdb|exploitdev|favicon|fedcompliance|findings|firewall|fleetcomply|forensicstoolkit|ftimeline|fwaudit|ghdb|hashsuite|headeranalyzer|home|huntlab|hydra|iacscan|identitymatrix|incidentcost|incidents|inventory|invest|investigation|investigations|iocenrich|jml|k8saudit|leakprobe|learn|learndo|leetspeak|licenseaudit|loganalyze|loghunt|malclass|math|mcpconnect|memforensics|mobilesec|monitors|navarch|netexposure|netmap|networkscanner|networktools|nhi|oauthgov|oracle|osint|overview|packetanalyzer|packetcraft|payees|payloadgen|payloads|payloadstudio|pentestconsole|pentestreg|personal|phantom|phishtriage|plans|posture|privatecloud|privaudit|privesc|prometheus|proxyhunt|reconplanner|refs|regexlab|report|reports|reverseshell|riskreg|secdash|secgraph|secquiz|securitytxt|sentineleye|settings|setup|sigma|signins|snippets|socialeng|spectre|sslinspector|stego|strongroom|subdomains|supplychain|surface|targets|team|techfingerprint|threat|threatforest|threatmodel|tlsfleet|toolbox|toolkit|tools|urldissect|vanguard|veil|vendorrisk|vmlab|vpnaudit|vulndb|vulnimport|wayback|websockettester|wirelesslab|xsslab|yarabuilder|zerotrust)?/?$", "destination": "/index.html" }
+ { "regex": "^/(?:console(?:/|$))?(?:(?:area|personal|enterprise)/[\\w-]+|check/[^/]+|tool-[a-z0-9-]+|accessreview|activity|addressintel|admin|adversary|adversaryplaybook|aegis|ai|all-tools|api|apifuzzer|apikeys|apispec|apitester|asnexplorer|assistant|attacksim|audit|awareness|backupready|beta|binanalyze|breachclock|breachlookup|caaudit|cheats|citadel|cloud|cloudspend|cloudtrail|coder|codescan|compliance|compliance-center|con|connections|cookieinspect|correlations|corstester|cracklab|credaudit|crosswalk|crucible|cryptotools|cspevaluator|cvesearch|cvetimeline|cvsscalc|cyberbriefing|cyberrange|darknetradar|dataflow|dataviz|deadlines|deception|device|dlguide|dlp|dmarcreports|dns|dnshunt|docs|domainguard|dossier|downloads|education|emailauth|emailheader|embedsdk|encoding|engine|engines|enterprise|evidence|exploitdb|exploitdev|favicon|fedcompliance|findings|firewall|fleetcomply|forensicstoolkit|ftimeline|fwaudit|ghdb|hashsuite|headeranalyzer|home|huntlab|hydra|iacscan|identitymatrix|incidentcost|incidents|inventory|invest|investigation|investigations|iocenrich|jml|k8saudit|leakprobe|learn|learndo|leetspeak|licenseaudit|loganalyze|loghunt|malclass|math|mcpconnect|memforensics|mobilesec|monitors|navarch|netexposure|netmap|networkscanner|networktools|nhi|oauthgov|oracle|osint|overview|owner|packetanalyzer|packetcraft|payees|payloadgen|payloads|payloadstudio|pentestconsole|pentestreg|personal|phantom|phishtriage|plans|posture|privatecloud|privaudit|privesc|prometheus|proxyhunt|reconplanner|refs|regexlab|report|reports|reverseshell|riskreg|secdash|secgraph|secquiz|securitytxt|sentineleye|settings|setup|sigma|signins|snippets|socialeng|spectre|sslinspector|stego|strongroom|subdomains|supplychain|surface|targets|team|techfingerprint|threat|threatforest|threatmodel|tlsfleet|toolbox|toolkit|tools|urldissect|vanguard|veil|vendorrisk|vmlab|vpnaudit|vulndb|vulnimport|wayback|websockettester|wirelesslab|xsslab|yarabuilder|zerotrust)?/?$", "destination": "/index.html" }
],
"headers": [
{
@@ -109,7 +109,7 @@
{ "regex": "^/terms/?$", "destination": "/pages/terms.html" },
{ "regex": "^/privacy/?$", "destination": "/pages/privacy.html" },
{ "regex": "^/acceptable-use/?$", "destination": "/pages/acceptable-use.html" },
- { "regex": "^/(?:console(?:/|$))?(?:(?:area|personal|enterprise)/[\\w-]+|check/[^/]+|tool-[a-z0-9-]+|accessreview|activity|addressintel|admin|adversary|adversaryplaybook|aegis|ai|all-tools|api|apifuzzer|apikeys|apispec|apitester|asnexplorer|assistant|attacksim|audit|awareness|backupready|beta|binanalyze|breachclock|breachlookup|caaudit|cheats|citadel|cloud|cloudspend|cloudtrail|coder|codescan|compliance|compliance-center|con|connections|cookieinspect|correlations|corstester|cracklab|credaudit|crosswalk|crucible|cryptotools|cspevaluator|cvesearch|cvetimeline|cvsscalc|cyberbriefing|cyberrange|darknetradar|dataflow|dataviz|deadlines|deception|device|dlguide|dlp|dmarcreports|dns|dnshunt|docs|domainguard|dossier|downloads|education|emailauth|emailheader|embedsdk|encoding|engine|engines|enterprise|evidence|exploitdb|exploitdev|favicon|fedcompliance|findings|firewall|fleetcomply|forensicstoolkit|ftimeline|fwaudit|ghdb|hashsuite|headeranalyzer|home|huntlab|hydra|iacscan|identitymatrix|incidentcost|incidents|inventory|invest|investigation|investigations|iocenrich|jml|k8saudit|leakprobe|learn|learndo|leetspeak|licenseaudit|loganalyze|loghunt|malclass|math|mcpconnect|memforensics|mobilesec|monitors|navarch|netexposure|netmap|networkscanner|networktools|nhi|oauthgov|oracle|osint|overview|packetanalyzer|packetcraft|payees|payloadgen|payloads|payloadstudio|pentestconsole|pentestreg|personal|phantom|phishtriage|plans|posture|privatecloud|privaudit|privesc|prometheus|proxyhunt|reconplanner|refs|regexlab|report|reports|reverseshell|riskreg|secdash|secgraph|secquiz|securitytxt|sentineleye|settings|setup|sigma|signins|snippets|socialeng|spectre|sslinspector|stego|strongroom|subdomains|supplychain|surface|targets|team|techfingerprint|threat|threatforest|threatmodel|tlsfleet|toolbox|toolkit|tools|urldissect|vanguard|veil|vendorrisk|vmlab|vpnaudit|vulndb|vulnimport|wayback|websockettester|wirelesslab|xsslab|yarabuilder|zerotrust)?/?$", "destination": "/index.html" }
+ { "regex": "^/(?:console(?:/|$))?(?:(?:area|personal|enterprise)/[\\w-]+|check/[^/]+|tool-[a-z0-9-]+|accessreview|activity|addressintel|admin|adversary|adversaryplaybook|aegis|ai|all-tools|api|apifuzzer|apikeys|apispec|apitester|asnexplorer|assistant|attacksim|audit|awareness|backupready|beta|binanalyze|breachclock|breachlookup|caaudit|cheats|citadel|cloud|cloudspend|cloudtrail|coder|codescan|compliance|compliance-center|con|connections|cookieinspect|correlations|corstester|cracklab|credaudit|crosswalk|crucible|cryptotools|cspevaluator|cvesearch|cvetimeline|cvsscalc|cyberbriefing|cyberrange|darknetradar|dataflow|dataviz|deadlines|deception|device|dlguide|dlp|dmarcreports|dns|dnshunt|docs|domainguard|dossier|downloads|education|emailauth|emailheader|embedsdk|encoding|engine|engines|enterprise|evidence|exploitdb|exploitdev|favicon|fedcompliance|findings|firewall|fleetcomply|forensicstoolkit|ftimeline|fwaudit|ghdb|hashsuite|headeranalyzer|home|huntlab|hydra|iacscan|identitymatrix|incidentcost|incidents|inventory|invest|investigation|investigations|iocenrich|jml|k8saudit|leakprobe|learn|learndo|leetspeak|licenseaudit|loganalyze|loghunt|malclass|math|mcpconnect|memforensics|mobilesec|monitors|navarch|netexposure|netmap|networkscanner|networktools|nhi|oauthgov|oracle|osint|overview|owner|packetanalyzer|packetcraft|payees|payloadgen|payloads|payloadstudio|pentestconsole|pentestreg|personal|phantom|phishtriage|plans|posture|privatecloud|privaudit|privesc|prometheus|proxyhunt|reconplanner|refs|regexlab|report|reports|reverseshell|riskreg|secdash|secgraph|secquiz|securitytxt|sentineleye|settings|setup|sigma|signins|snippets|socialeng|spectre|sslinspector|stego|strongroom|subdomains|supplychain|surface|targets|team|techfingerprint|threat|threatforest|threatmodel|tlsfleet|toolbox|toolkit|tools|urldissect|vanguard|veil|vendorrisk|vmlab|vpnaudit|vulndb|vulnimport|wayback|websockettester|wirelesslab|xsslab|yarabuilder|zerotrust)?/?$", "destination": "/index.html" }
],
"headers": [
{
diff --git a/public/js/admin.js b/public/js/admin.js
index 80452815..c6496cef 100644
--- a/public/js/admin.js
+++ b/public/js/admin.js
@@ -1,41 +1,14 @@
-// Owner-only admin console: live user management, a ban-list (the site is open
-// to everyone; only banned emails are blocked at sign-in), and site-wide
-// announcements. All backed by Firestore.
+// Owner helpers shared with auth.js. The owner's page itself is the Deck's Owner scene
+// (deck/owner.js, at /owner); the old console Admin page is archived in
+// unused-stuff/owner-console/.
import { db } from "/js/firebase.js?v=20261021a";
+import { doc, getDoc } from "https://www.gstatic.com/firebasejs/12.17.0/firebase-firestore.js";
-// The super-admin is no longer a hardcoded email. The set-admin script stamps the
-// owner's own user doc with `admin: true` (alongside the Firebase custom claim),
-// so this owner-only panel can still badge/exclude that row. The access decision
-// itself is enforced by the ID-token claim + Security Rules, not by this flag.
-const isOwnerRow = (u) => !!u && (u.admin === true || u.role === "owner");
-import {
- collection, getDocs, doc, getDoc, setDoc, deleteDoc, serverTimestamp,
- addDoc, query, orderBy, updateDoc, limit,
-} from "https://www.gstatic.com/firebasejs/12.17.0/firebase-firestore.js";
-
-// Profile timestamps come as Firestore Timestamps, epoch numbers (the worker's Auth-only rows)
-// or the Auth metadata string ensureUserDoc stores ("Wed, 11 Nov 2026 ..."); all count.
-const tsMs = (ts) => ts && ts.toMillis ? ts.toMillis() : ts && ts.toDate ? ts.toDate().getTime()
- : typeof ts === "number" ? (ts < 1e12 ? ts * 1000 : ts) : typeof ts === "string" ? (Date.parse(ts) || 0) : 0;
-// Only the sign-in providers' own avatar hosts load: photoURL is user-writable, and any other
-// URL would send the owner's IP and browser to a server the user picked.
-const AVATAR_HOST = /^(lh\d+\.googleusercontent\.com|avatars\.githubusercontent\.com)$/;
-const safeAvatar = (u) => { try { const x = new URL(u); return x.protocol === "https:" && AVATAR_HOST.test(x.hostname) ? x.href : ""; } catch (_) { return ""; } };
-const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) =>
- ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
-const fmtDate = (ts) => {
- try { const d = ts?.toDate ? ts.toDate() : (ts ? new Date(ts) : null); return d ? d.toLocaleString() : "—"; } catch (_) { return "—"; }
-};
-
-const WL_REF = () => doc(db, "settings", "whitelist");
-const ANN_REF = () => doc(db, "announcements", "current");
-
-// Read the access-control doc (stored at settings/whitelist for history). It now
-// carries a `banned` list; auth.js denies only those emails. Everyone else is
-// allowed. The legacy `emails`/`enforce` allow-list fields are left untouched
-// for back-compat but are no longer enforced.
+// Read the access-control doc (stored at settings/whitelist for history). It carries a
+// `banned` list; auth.js denies only those emails. Everyone else is allowed. The legacy
+// `emails`/`enforce` allow-list fields are left untouched but are no longer enforced.
export async function getWhitelist() {
- try { const s = await getDoc(WL_REF()); return s.exists() ? s.data() : { emails: [], enforce: false, banned: [] }; }
+ try { const s = await getDoc(doc(db, "settings", "whitelist")); return s.exists() ? s.data() : { emails: [], enforce: false, banned: [] }; }
catch (_) { return { emails: [], enforce: false, banned: [] }; }
}
@@ -43,946 +16,7 @@ export async function getWhitelist() {
import { openDeck, closeDeck } from "/js/deck/launch.js?v=20261030d";
export { openDeck, closeDeck };
-// ---- Preview UI: a light, single-surface alternate view of every tool, launched from
-// the admin page like the Deck. Same NAV taxonomy, self-contained module (scoped .pvx). ----
-let _previewOff = null;
-export async function openPreview(user) {
- const nav = await import("/js/console-nav.js?v=20261029d");
- const { renderPreview } = await import("/js/preview-ui.js?v=20261019h");
- if (_previewOff) { try { _previewOff(); } catch (_) {} _previewOff = null; }
- document.querySelectorAll("body > .pvx").forEach((n) => n.remove());
- _previewOff = renderPreview(document.body, {
- groups: (nav.NAV || []).map((g) => ({ id: g.id, name: g.name, color: g.color, items: g.items || [] })),
- onExit: () => { _previewOff = null; },
- });
- return _previewOff;
-}
-export async function renderAdmin(main, user) {
- main.innerHTML = `
-
Admin
-
Owner console — ${esc(user.email)} OWNER
-
-
-
…
users
-
…
new this week
-
…
active today
-
…
banned
-
…
announcement
-
-
-
-
- OWNER ONLY
-
Darknode Command Center
-
The Deck: grouped sidebar, posture overview, attack surface, investigations and every tool in one workspace, with Ctrl K search. Visible only to you.
-
-
-
-
-
-
-
-
-
-
-
-
Users
-
-
-
Loading users…
-
-
-
Nexus, desktop app & VMs
-
-
-
Loading usage…
-
-
-
Recent new-device sign-ins
-
…
-
-
-
Plan upgrade requests
-
-
Requests from the Deck's Plans page. Granting sets the user's plan tier.
-
Loading requests…
-
-
-
Account deletion requests
-
-
Filed before users could delete their own account. Delete runs the same full deletion a user starts in Settings; only accounts that asked are listed.
-
Loading requests…
-
-
-
Feedback & bug reports
-
-
Loading feedback…
-
-
-
Client Error Log
-
-
-
Automatic crash reports from user sessions.
-
Loading errors…
-
-
-
Data & outreach
-
Export the user base or grab every email for an announcement mailout.
-
-
-
-
-
-
-
-
-
Email Users
-
Send an email from contact@darknode.ai to one user or all registered users.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Quick templates:
-
-
-
-
-
-
-
-
-
-
-
-
Banned emails
-
The site is open to everyone. Add an email here to block that account from signing in.
-
-
-
-
-
-
The owner account can never be banned. This list blocks sign-in in the browser only; to cut off an account completely, run node scripts/suspend-user.mjs <email>.
-
-
-
-
Announcement
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Site Analytics
-
-
-
--
Learn Hub topics
-
--
top learner
-
--
avg XP/user
-
--
total completions
-
-
-
-
-
-
-
-
User Activity Log
-
Recent user actions — sign-ins, page views, and tool usage.
-
Loading activity...
-
-
-
-
Maintenance
-
System health and maintenance actions.
-
-
-
-
-
-
-
-
-
-
Feature Flags
-
Toggle site features on/off without redeploying.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Quick Actions
-
-
-
-
-
-
-
-
-
-
System Status
-
-
Firebaseconnected
-
Firestoreconnected
-
Learn Hub--
-
Render deploy--
-
JS bundle--
-
-
-
-
-
Danger Zone
-
-
-
-
-
-
-
-
`;
-
- const $ = (id) => main.querySelector(id);
-
- // ---- Darknode Deck: owner-only command center, launched from here ----
- // Lazy-loaded so the module never ships to the normal console. Uses the live NAV
- // taxonomy as the single source of truth for categories.
- (function wireDeck() {
- const btn = main.querySelector("#deckLaunch");
- if (!btn) return;
- // framed inside the Deck already: opening a second Deck inside its Admin window is no use
- if (document.documentElement.hasAttribute("data-embed")) { btn.remove(); return; }
- async function launchDeck() {
- btn.disabled = true; const label = btn.textContent; btn.textContent = "Loading…";
- try {
- await openDeck(user, { isOwner: true });
- } catch (e) {
- try { window.showToast ? window.showToast("Command center failed to load: " + e.message, "error") : 0; } catch (_) {}
- } finally { btn.disabled = false; btn.textContent = label; }
- }
- btn.addEventListener("click", launchDeck);
- // Returning from an OpenRouter account-link: finish the handshake, then re-open
- // the deck so the user lands back where they started and sees it connected.
- import("/js/openrouter-connect.js?v=20261028c").then(({ shouldReopenDeck }) => {
- if (shouldReopenDeck()) Promise.resolve(window.__orConnect).finally(launchDeck);
- }).catch(() => {});
- })();
-
-
- // ---- Preview UI launcher (sits beside the Deck button) ----
- (function wirePreview() {
- const btn = main.querySelector("#previewLaunch");
- if (!btn) return;
- btn.addEventListener("click", async () => {
- btn.disabled = true; const label = btn.textContent; btn.textContent = "Loading…";
- try { await openPreview(user); }
- catch (e) { try { window.showToast && window.showToast("Preview UI failed to load: " + e.message, "error"); } catch (_) {} }
- finally { btn.disabled = false; btn.textContent = label; }
- });
- })();
-
- let users = [];
- let wl = { emails: [], enforce: false, banned: [] };
-
- // ---- users ----
- async function loadUsers() {
- const host = $("#uList");
- try {
- const snap = await getDocs(collection(db, "users"));
- users = snap.docs.map((d) => ({ uid: d.id, ...d.data() }));
- // Firebase Auth accounts with no users/{uid} doc (an email sign-up that never verified
- // never writes one). Listed by the Worker with its service account; owner only.
- try {
- const { api } = await import("/js/core/api.js");
- const r = await api("/api/admin/users");
- const have = new Map(users.map((u) => [u.uid, u]));
- for (const a of (r && r.users) || []) {
- const u = have.get(a.uid);
- if (u) { u.emailVerified = a.emailVerified; u.disabled = a.disabled; continue; }
- users.push({ uid: a.uid, email: a.email, name: a.name, provider: a.providers.join(", ") || "email", createdAt: a.createdAt, lastLoginAt: a.lastLoginAt, lastSeen: a.lastLoginAt, emailVerified: a.emailVerified, disabled: a.disabled, authOnly: true });
- }
- } catch (_) { /* Worker unreachable: the Firestore list still shows */ }
- $("#stUsers").textContent = users.length;
- const toMs = tsMs;
- const now = Date.now(), day = 864e5, midnight = new Date(); midnight.setHours(0, 0, 0, 0);
- $("#stNew").textContent = users.filter((u) => { const c = toMs(u.created || u.createdAt); return c && now - c < 7 * day; }).length || "—";
- $("#stActive").textContent = users.filter((u) => toMs(u.lastSeen) >= midnight.getTime()).length;
- drawUsers();
- const alerts = [];
- users.forEach((u) => (u.logins || []).forEach((l) => alerts.push({ email: u.email, device: l.device, ts: l.ts })));
- alerts.sort((a, b) => (b.ts || 0) - (a.ts || 0));
- $("#loginList").innerHTML = alerts.length
- ? alerts.slice(0, 20).map((a) => `
${esc(a.device || "device")}
${esc(a.email || "")}
${esc(fmtDate(a.ts))}
`).join("")
- : `
No new-device sign-ins recorded yet.
`;
- } catch (e) {
- host.innerHTML = `
Couldn't load users: ${esc(e.message)}. Make sure Firestore rules are deployed.
';
}
diff --git a/public/js/auth.js b/public/js/auth.js
index 968ee5f5..f1d4137b 100644
--- a/public/js/auth.js
+++ b/public/js/auth.js
@@ -2277,7 +2277,7 @@ function renderApp(user) {
else if (sec === "pentestreg") { import("/js/ops/pentestreg.js?v=20261030c").then(m => live() && m.renderPentestReg(main)); }
else if (sec === "setup") renderSetup(main, more);
else if (sec === "settings") renderSettingsPage(main, user, isOwner, more);
- else if (sec === "admin") { import("/js/admin.js?v=20261030d").then(m => live() && m.renderAdmin(main, user)); }
+ else if (sec === "admin") { import("/js/admin.js?v=20261030d").then(m => live() && m.renderAdmin(main)); }
else if (sec === "contact") renderContact(main);
else if (sec === "education") { main.innerHTML = `
About Darknode Education
Darknode is a cybersecurity education platform designed for students, educators, and security professionals to learn information security through hands-on practice in a safe, controlled environment.
Our Mission: To make cybersecurity education accessible, interactive, and practical. Most tools run in your browser or on your own machine. Some features do send data out: AI chat goes through Darknode's server to the AI provider, some lookup pages query public services (for example NVD, crt.sh and DNS-over-HTTPS resolvers), and saved items and account data are stored in Google Firebase. Each page that contacts an outside service does so only when you run it.
Who Uses Darknode:
Computer science and cybersecurity students
IT professionals studying for certifications (CompTIA Security+, CISSP, CEH, OSCP)
University professors and instructors teaching security courses
Security operations center (SOC) analysts in training
Career changers learning cybersecurity fundamentals
Educational Standards: Our curriculum aligns with NIST NICE Framework, NSA CAE-CD requirements, and CompTIA Security+ objectives. All practice environments are isolated, legal, and designed for authorized educational use only.
Responsible Use: Darknode tools are designed exclusively for educational purposes and authorized security testing. Users must comply with all applicable laws and obtain proper authorization before testing any system they do not own.
Darknode is a product of Darknode-Official. For questions about our educational programs, visit darknode.ai.
`; }
else if (sec === "toolbox") { import("/js/mini-tools.js?v=20261029e").then(m => live() && m.renderToolbox(main, { onOpen: (id) => show("tool-" + id) })); }
diff --git a/public/js/core/active-days.js b/public/js/core/active-days.js
new file mode 100644
index 00000000..ec75f99d
--- /dev/null
+++ b/public/js/core/active-days.js
@@ -0,0 +1,19 @@
+// Copyright (c) 2026 Darknode-Official. All rights reserved. See LICENSE.
+// Which days an account opened the Deck: the dates (UTC, no times) of the last 60 days it
+// was used, kept on users/{uid} as recentDays, plus an all-time activeDays count. It is the
+// only way to tell a person who came back from one who signed up once, since lastSeen is a
+// single timestamp that every visit overwrites. PURE: deck/launch.js does the write.
+
+export const KEEP_DAYS = 60;
+export const dayOf = (ms) => new Date(ms).toISOString().slice(0, 10);
+
+// markDay(recent, now) -> { days, changed }. days: the sorted, de-duplicated dates inside the
+// last KEEP_DAYS, today included; changed: false when today was already recorded (no write).
+export function markDay(recent, now = Date.now()) {
+ const today = dayOf(now), floor = dayOf(now - (KEEP_DAYS - 1) * 864e5);
+ const valid = (Array.isArray(recent) ? recent : []).filter((d) => typeof d === "string" && /^\d{4}-\d{2}-\d{2}$/.test(d) && d >= floor && d <= today);
+ const days = [...new Set(valid)].sort();
+ if (days.includes(today)) return { days, changed: false };
+ days.push(today);
+ return { days, changed: true };
+}
diff --git a/public/js/deck-ui.js b/public/js/deck-ui.js
index 9036b099..5593e080 100644
--- a/public/js/deck-ui.js
+++ b/public/js/deck-ui.js
@@ -47,6 +47,7 @@ const invMod = lazyMod("/js/deck/inventory.js?v=20261027c");
const corrMod = lazyMod("/js/deck/correlations.js?v=20261029c");
const monMod = lazyMod("/js/deck/monitors.js?v=20261029d");
const dlMod = lazyMod("/js/deck/deadlines.js?v=1");
+const ownerMod = lazyMod("/js/deck/owner.js?v=1");
const keysMod = lazyMod("/js/deck/apikeys.js?v=20261030d");
const auditMod = lazyMod("/js/deck/audit.js?v=20261028a");
const deviceMod = lazyMod("/js/deck/device.js?v=20261101a");
@@ -1826,7 +1827,7 @@ export function renderDeck(host, opts) {
{ id: "finsec", g: "Fraud & Abuse", items: [["tool", "strongroom", "Payment Fraud", IC.coins], ["tool", "payees", "Payee Changes", IC.shield], ["tool", "cloudspend", "Cloud Spend", IC.gauge]] },
{ id: "risk", g: "Risk & Resilience", items: [["tool", "breachclock", "Breach Deadlines", IC.bell], ["tool", "riskreg", "Risk Register", IC.scale], ["tool", "vendorrisk", "Vendors", IC.nodes], ["tool", "backupready", "Backups", IC.folder]] },
{ id: "compliance", g: "Compliance", items: [["scene", "compliance", "Frameworks", IC.check], ["tool", "crosswalk", "AI Risk Mapping", IC.map], ["tool", "dlp", "Sensitive Data", IC.eye], ["tool", "leakprobe", "Exposed Keys", IC.key], ["tool", "evidence", "Audit Evidence", IC.book], ["tool", "dataflow", "Data Inventory", IC.folder], ["tool", "awareness", "Security Training", IC.pulse]] },
- { g: "Platform", items: [["scene", "con", "Integrations", IC.plug], ["scene", "tools", "Tool Library", IC.grid], ["scene", "toolkit", "Toolkit", IC.wrench], ["tool", "downloads", "Downloads", IC.dl], ["scene", "assistant", "Assistant", IC.spark], ["scene", "team", "Team", IC.nodes], ["scene", "plans", "Plans", IC.star]].concat(opts.isOwner ? [["tool", "admin", "Admin", IC.key]] : []) },
+ { g: "Platform", items: [["scene", "con", "Integrations", IC.plug], ["scene", "tools", "Tool Library", IC.grid], ["scene", "toolkit", "Toolkit", IC.wrench], ["tool", "downloads", "Downloads", IC.dl], ["scene", "assistant", "Assistant", IC.spark], ["scene", "team", "Team", IC.nodes], ["scene", "plans", "Plans", IC.star]].concat(opts.isOwner ? [["scene", "owner", "Owner", IC.key]] : []) },
];
// Desktop app only: the app's native tools (real shell, sockets, VMs, local files) open
// in their own window. A browser never shows this group.
@@ -1846,7 +1847,7 @@ export function renderDeck(host, opts) {
const needTier = {}, navName = {}, navIcon = {}; // navName keeps the names of entries the plan hides
for (const grp of NAV_DEF) {
if (grp.id) { needTier["section:" + grp.id] = PLAN_GROUP[grp.id] || "free"; navName["section:" + grp.id] = grp.g; }
- for (const [kind, id, label, icon] of grp.items) { navName[kind + ":" + id] = label; navIcon[kind + ":" + id] = icon; if (id !== "admin") needTier[kind + ":" + id] = PLAN_ITEM[id] || PLAN_GROUP[grp.id] || "free"; }
+ for (const [kind, id, label, icon] of grp.items) { navName[kind + ":" + id] = label; navIcon[kind + ":" + id] = icon; if (id !== "owner") needTier[kind + ":" + id] = PLAN_ITEM[id] || PLAN_GROUP[grp.id] || "free"; }
}
const isLocked = (key) => rank(planTier) < rank(needTier[key] || "free");
// Personal cloud sync is a Pro feature; the Worker refuses it below Pro (worker/plan.js).
@@ -1893,21 +1894,69 @@ export function renderDeck(host, opts) {
// 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 ""; } };
+ // Getting started is the loop that brings people back: check a domain, have Darknode watch
+ // it (alert emails when something breaks or expires) and get the Monday summary. Whether a
+ // monitor exists and the digest is on are asked from the server once per load (onbLive).
+ const onbLive = { watch: null, digest: null, asked: false };
+ function askOnbLive(){
+ if (onbLive.asked || noAccount) return;
+ onbLive.asked = true;
+ const done = () => { if (curScene === "overview") paintOnbCard(); };
+ import("/js/deck/monitor-client.js").then((m) => m.monitoringAvailable() ? m.monitorApi({ op: "list" }, { personal: planTier === "free" }) : null)
+ .then((d) => { onbLive.watch = !!(d && (d.monitors || []).length); done(); }, () => {});
+ import("/js/deck/digest-client.js").then((m) => m.getDigest())
+ .then((d) => { onbLive.digest = !!(d && d.on); onbLive.verified = !!(d && d.verified); done(); }, () => {});
+ }
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 (_) {} }
let hasGraph = false;
try { const ents = Object.values((JSON.parse(localStorage.getItem(storeKeyFor(activeWorkspace()))) || {}).entities || {}); hasGraph = ents.some((e) => !isSimulated(e)); } catch (_) {}
// a check run in a space (domain, certificates, links...) is a first scan too: on the Free plan that is where this step sends you
if (!hasGraph) hasGraph = readRuns("personal").length > 0 || readRuns("enterprise").length > 0;
// land ON the thing to do (the field / the first connect button), not just on its page
const focusIn = (sel) => setTimeout(() => { const el = root.querySelector(sel); if (el && el.offsetParent) { el.focus({ preventScroll: true }); el.scrollIntoView({ block: "center" }); } }, 80);
+ const acct = (fn) => () => (noAccount ? toSignup() : fn());
return [
- { id: "ws", label: "Name your workspace", sub: "So reports and the header carry your brand", done: !!wsProfile.name, act: () => { go("settings"); focusIn("#dkSetWsName"); } },
- { id: "ai", label: "Connect an AI model or key", sub: "Power triage, runbooks and explanations", done: aiConnected, act: () => { go("con"); focusIn(".dk-intgrp button, .dk-intgrp [role=button]"); } },
- { id: "scan", label: "Run your first scan", sub: isLocked("scene:surface") ? "Check a domain you own to get a baseline" : "Map an attack surface or scan code to get a baseline", done: hasGraph, act: () => { if (isLocked("scene:surface")) openSpaceTool("personal", "domain"); else { go("surface"); focusIn("#dkSurfIn"); } } },
+ { id: "scan", label: "Check your domain", sub: isLocked("scene:surface") ? "Its certificate, email security and website in one check" : "Map an attack surface or scan code to get a baseline", done: hasGraph, act: () => { if (isLocked("scene:surface")) openSpaceTool("personal", "domain"); else { go("surface"); focusIn("#dkSurfIn"); } } },
+ { id: "watch", label: "Have Darknode watch it", sub: noAccount ? "Needs a free account: it runs on our servers and emails you" : "Checked every day; you get an email when something breaks or is about to expire", done: !!onbLive.watch, go: noAccount ? "Sign up" : "Set up", act: acct(() => go("monitors")) },
+ { id: "digest", label: "Get the Monday summary", sub: noAccount ? "Needs a free account" : "One email a week: newly exploited vulnerabilities and anything about to expire", done: !!onbLive.digest, go: noAccount ? "Sign up" : "Turn on", act: acct(turnOnDigest) },
];
}
+ async function turnOnDigest(){
+ try {
+ const m = await import("/js/deck/digest-client.js");
+ const r = await m.saveDigest(true);
+ onbLive.digest = !!(r && r.on);
+ toast(onbLive.digest ? "Monday summary on. The first one arrives next Monday." : "Verify your email address first, then turn it on.");
+ } catch (e) { toast(String((e && e.message) || "Could not turn on the summary"), "error"); }
+ paintOnbCard();
+ }
+ function onbCardHtml(steps){
+ const n = steps.filter((x) => x.done).length;
+ if (onbState.dismissed || n >= steps.length) return "";
+ return `
+
+
Getting started${n} of ${steps.length} done
+
${steps.map((x) => `
+ `).join("")}
+
`;
+ }
+ function wireOnbCard(el, steps){
+ el.querySelectorAll(".dk-onbd-step[data-onb]").forEach((b) => b.onclick = () => { const st = steps.find((x) => x.id === b.dataset.onb); if (st && !st.done) st.act(); });
+ const onbX = el.querySelector("#dkOnbDismiss");
+ if (onbX) onbX.onclick = () => { dismissOnboarding(); const c = el.querySelector("#dkOnbd"); if (c) c.remove(); };
+ }
+ // the server answered (or a step was done here): redraw just the card, in place
+ function paintOnbCard(){
+ const el = sceneEls.overview, old = el && el.querySelector("#dkOnbd"); if (!old) return;
+ const steps = onbSteps(), html = onbCardHtml(steps);
+ if (!html) { old.remove(); return; }
+ old.insertAdjacentHTML("afterend", html); old.remove();
+ wireOnbCard(el, steps);
+ }
async function dismissOnboarding(){
onbState = Object.assign({}, onbState, { dismissed: true });
if (typeof opts.onOnboarding === "function") { try { await opts.onOnboarding({ dismissed: true }); } catch (_) {} }
@@ -2034,6 +2083,7 @@ export function renderDeck(host, opts) {
+
@@ -2175,7 +2225,7 @@ export function renderDeck(host, opts) {
}
function go(scene, arg){
navSeq++;
- if (!SCENES[scene] || isLocked(scene === "section" ? "section:" + (isSect(arg) ? arg : curSect) : "scene:" + scene)) scene = "overview";
+ if (!SCENES[scene] || (scene === "owner" && !opts.isOwner) || isLocked(scene === "section" ? "section:" + (isSect(arg) ? arg : curSect) : "scene:" + scene)) scene = "overview";
curScene = scene;
if (scene === "section") { if (isSect(arg)) curSect = arg; try { localStorage.setItem("dn_deck_sect", curSect); } catch (_) {} }
syncUrl(scenePath(scene, curSect));
@@ -2199,6 +2249,7 @@ export function renderDeck(host, opts) {
else if (scene === "correlations") renderCorrelations();
else if (scene === "monitors") renderMonitors();
else if (scene === "deadlines") renderDeadlines();
+ else if (scene === "owner") renderOwner();
else if (scene === "apikeys") renderApiKeys();
else if (scene === "audit") renderAudit();
else if (scene === "section") renderSection();
@@ -2662,6 +2713,7 @@ export function renderDeck(host, opts) {
})();
function openTool(sec, label, accent){
if (!sec) return;
+ if (sec === "admin") { go(opts.isOwner ? "owner" : "overview"); return; } // the old Admin page is the Owner scene now
if (isLocked("tool:" + sec)) return;
navSeq++;
label = label || sec; curSec = sec;
@@ -2895,7 +2947,7 @@ export function renderDeck(host, opts) {
- ${primary ? (opts.isOwner ? `` : "") + (typeof opts.onClassic === "function" ? `` : "") : ``}
+ ${primary ? (opts.isOwner ? `` : "") + (typeof opts.onClassic === "function" ? `` : "") : ``}
`;
const su = popAcct.querySelector("#dkMiSignup"); if (su) su.onclick = () => { closeAllMenus(); toSignup(); };
@@ -2909,7 +2961,7 @@ export function renderDeck(host, opts) {
popAcct.querySelector("#dkMiImport").onclick = () => { closeAllMenus(); importDeckState(); };
const miCon = popAcct.querySelector("#dkMiConsole"); if (miCon) miCon.onclick = exitDeck;
const miCls = popAcct.querySelector("#dkMiClassic"); if (miCls) miCls.onclick = () => { closeAllMenus(); opts.onClassic(); };
- const miAdm = popAcct.querySelector("#dkMiAdmin"); if (miAdm) miAdm.onclick = () => { closeAllMenus(); openTool("admin", "Admin"); };
+ const miAdm = popAcct.querySelector("#dkMiAdmin"); if (miAdm) miAdm.onclick = () => { closeAllMenus(); go("owner"); };
popAcct.querySelector("#dkMiExit").onclick = primary ? () => { closeAllMenus(); opts.onSignOut(); } : exitDeck;
}
// ---------- workspace switcher (B2) ----------
@@ -3240,20 +3292,10 @@ export function renderDeck(host, opts) {
const hr = now.getHours();
const greet = hr < 12 ? "Good morning" : hr < 18 ? "Good afternoon" : "Good evening";
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 ? `
-
+ ${kpi(r.total, "People signed up")}
+ ${kpi(r.new7, "New this week")}
+ ${kpi(r.returned, "Came back another day", r.total ? pct(r.returned, r.total) + "%" : "")}
+ ${kpi(r.active7, "Used it this week")}
+ ${kpi(r.active1, "Used it today")}
`;
+ const top = r.funnel[0].n;
+ box("#ownFunnel").innerHTML = `
From sign-up to habit
+
How far people get. A person came back when they used Darknode on two or more different days.
Most recently seen first. Select a person for their details. "Came once" is everyone who has not been back on a second day yet: the people a reminder is for.
`;
+}
+
+function onInput(e) {
+ if (e.target.id === "ownQ") { S.q = e.target.value; const pos = e.target.selectionStart; paintPeople(); const q = S.el.querySelector("#ownQ"); if (q) { q.focus(); try { q.setSelectionRange(pos, pos); } catch (_) {} } }
+}
+
+async function onClick(e) {
+ const t = e.target;
+ const f = t.closest("[data-filter]"); if (f) { S.filter = f.dataset.filter; S.open = ""; paintPeople(); return; }
+ const ban = t.closest("[data-ban]"); if (ban) { await toggleBan(ban.dataset.ban); return; }
+ const cp = t.closest("[data-copy]"); if (cp) { try { await navigator.clipboard.writeText(cp.dataset.copy); toast("Email copied", "success"); } catch (_) {} return; }
+ if (t.closest("#ownCsv")) { exportCsv(); return; }
+ const pre = t.closest("[data-preset]"); if (pre) { const [, text] = PRESETS[pre.dataset.preset]; S.el.querySelector("#ownAnnText").value = text; S.el.querySelector("#ownAnnType").value = pre.dataset.preset === "security" ? "warn" : "info"; return; }
+ const act = t.closest("[data-act]");
+ if (act) { await doAct(act.dataset.act, act); return; }
+ const row = t.closest(".own-p[data-uid]");
+ if (row) { S.open = S.open === row.dataset.uid ? "" : row.dataset.uid; paintPeople(); }
+}
+
+async function doAct(act, btn) {
+ const item = btn.closest(".own-item");
+ try {
+ if (act === "grant") {
+ const { rid, uid, tier } = item.dataset;
+ if (!uid || !PLAN[tier]) { toast("This request is missing a person or a plan.", "error"); return; }
+ if (!(await confirmIt("Grant " + PLAN[tier] + "?", "Their plan becomes " + PLAN[tier] + " straight away, and they get a notice in the Deck.", { submitText: "Grant" }))) return;
+ btn.disabled = true;
+ await setDoc(doc(db, "users", uid), { tier, tierGrantedAt: serverTimestamp() }, { merge: true });
+ try { await addDoc(collection(db, "users", uid, "notifications"), { text: "Your plan was upgraded to " + PLAN[tier] + ".", kind: "plan", ts: Date.now(), read: false }); } catch (_) {}
+ await updateDoc(doc(db, "upgradeRequests", rid), { status: "granted", grantedAt: serverTimestamp() });
+ const u = S.users.find((x) => x.uid === uid); if (u) u.tier = tier;
+ S.inbox.upgrades = S.inbox.upgrades.filter((r) => r.id !== rid);
+ toast("Granted " + PLAN[tier], "success"); paintInbox(); paintPeople(); return;
+ }
+ if (act === "dismiss") {
+ await updateDoc(doc(db, "upgradeRequests", item.dataset.rid), { status: "dismissed" });
+ S.inbox.upgrades = S.inbox.upgrades.filter((r) => r.id !== item.dataset.rid); paintInbox(); return;
+ }
+ if (act === "delacct") {
+ const uid = item.dataset.del, who = item.dataset.email || uid;
+ if (!(await confirmIt("Delete " + who + "?", "This permanently deletes the account and everything stored with it, as they asked. It cannot be undone.", { submitText: "Delete account", danger: true }))) return;
+ btn.disabled = true;
+ await api("/api/admin/deletions", { method: "POST", body: { uid } });
+ S.inbox.deletions = S.inbox.deletions.filter((x) => x.uid !== uid);
+ S.users = S.users.filter((x) => x.uid !== uid);
+ toast("Deleted " + who, "success"); paintInbox(); paintTop(); paintPeople(); return;
+ }
+ if (act === "fbdel") {
+ if (!(await confirmIt("Delete this feedback?", "It is removed for good.", { danger: true }))) return;
+ await deleteDoc(doc(db, "feedback", item.dataset.fb));
+ S.inbox.feedback = S.inbox.feedback.filter((x) => x.id !== item.dataset.fb); paintInbox(); return;
+ }
+ if (act === "errclear") {
+ if (!(await confirmIt("Clear every logged error?", "All " + S.inbox.errors.length + " are deleted for good.", { danger: true }))) return;
+ btn.disabled = true;
+ await Promise.all(S.inbox.errors.map((x) => deleteDoc(doc(db, "errors", x.id)).catch(() => {})));
+ S.inbox.errors = []; paintInbox(); return;
+ }
+ if (act === "annon" || act === "annoff") {
+ const text = S.el.querySelector("#ownAnnText").value.trim(), type = S.el.querySelector("#ownAnnType").value === "warn" ? "warn" : "info";
+ const active = act === "annon";
+ if (active && !text) { toast("Write the notice first.", "error"); return; }
+ const me = (S.ctx && S.ctx.user && S.ctx.user.email) || "";
+ await setDoc(doc(db, "announcements", "current"), { text, type, active, updatedBy: me, updatedAt: serverTimestamp() }, { merge: true });
+ S.ann = { ...S.ann, text, type, active };
+ const live = document.getElementById("announcement");
+ if (live) { if (active) { live.textContent = text; live.classList.toggle("banner-info", type !== "warn"); live.hidden = false; } else live.hidden = true; }
+ toast(active ? "The banner is showing to everyone." : "Banner turned off.", "success"); paintSite(); return;
+ }
+ if (act === "banadd") {
+ const v = S.el.querySelector("#ownBanIn").value.trim().toLowerCase();
+ if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)) { toast("Enter an email address.", "error"); return; }
+ if (S.banned.includes(v)) { toast("Already banned.", "info"); return; }
+ await toggleBan(v); return;
+ }
+ } catch (err) { btn.disabled = false; toast((err && err.message) || "That didn't work.", "error"); }
+}
+
+async function toggleBan(email) {
+ email = String(email || "").toLowerCase().trim(); if (!email) return;
+ const banning = !S.banned.includes(email);
+ const me = String((S.ctx && S.ctx.user && S.ctx.user.email) || "").toLowerCase();
+ const target = S.users.find((u) => String(u.email || "").toLowerCase() === email);
+ if (banning && (email === me || isOwnerRow(target))) { toast("An owner account can't be banned.", "error"); return; }
+ if (banning && !(await confirmIt("Ban " + email + "?", "They can no longer sign in. Their account and data are kept; unban any time.", { submitText: "Ban", danger: true }))) return;
+ const next = banning ? S.banned.concat(email) : S.banned.filter((x) => x !== email);
+ try {
+ await setDoc(doc(db, "settings", "whitelist"), { banned: next, enforce: false, updatedBy: me, updatedAt: serverTimestamp() }, { merge: true });
+ S.banned = next;
+ toast(banning ? "Banned " + email : "Unbanned " + email, banning ? "warn" : "success");
+ paintPeople(); paintSite();
+ } catch (err) { toast("Couldn't save the ban list: " + ((err && err.message) || err), "error"); }
+}
+
+// The table as shown (filter and search applied). Cells that start like a formula are quoted.
+function exportCsv() {
+ const now = Date.now();
+ const rows = peopleRows(S.users, { filter: S.filter, q: S.q, banned: S.banned, now });
+ const cell = (v) => `"${String(v ?? "").replace(/^(?=[=+@\t\r]|-(?!\d+(?:\.\d+)?$))/, "'").replace(/"/g, '""')}"`;
+ const lines = [["email", "name", "joined", "last_seen", "days_used", "plan", "verified", "banned"]].concat(rows.map(({ u, p, owner, banned }) =>
+ [u.email, u.name, p.joined ? new Date(p.joined).toISOString() : "", p.last ? new Date(p.last).toISOString() : "", p.days, owner ? "owner" : u.tier || "free", p.verified ? "yes" : "no", banned ? "yes" : "no"]));
+ const url = URL.createObjectURL(new Blob([lines.map((r) => r.map(cell).join(",")).join("\n")], { type: "text/csv" }));
+ const a = document.createElement("a"); a.href = url; a.download = "darknode-people.csv"; document.body.appendChild(a); a.click(); a.remove();
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
+}
+
diff --git a/public/js/deck/routes.js b/public/js/deck/routes.js
index 08e4a871..005831cc 100644
--- a/public/js/deck/routes.js
+++ b/public/js/deck/routes.js
@@ -5,7 +5,7 @@
// Pure data and logic, no imports, so the landing can load it without the Deck.
// scene id -> its element in the Deck
-export const SCENES = { overview: "#dkOverview", surface: "#dkSurface", threat: "#dkThreat", cloud: "#dkCloud", compliance: "#dkCompliance", invest: "#dkInvest", findings: "#dkFindings", inventory: "#dkInventory", correlations: "#dkCorrelations", monitors: "#dkMonitors", deadlines: "#dkDeadlines", apikeys: "#dkApiKeys", device: "#dkDevice", audit: "#dkAudit", section: "#dkSection", con: "#dkCon", tools: "#dkTools", toolkit: "#dkToolkit", activity: "#dkActivity", assistant: "#dkAssistant", plans: "#dkPlans", settings: "#dkSettings", reports: "#dkReports", team: "#dkTeam", personal: "#dkPersonal", enterprise: "#dkEnterprise" };
+export const SCENES = { overview: "#dkOverview", surface: "#dkSurface", threat: "#dkThreat", cloud: "#dkCloud", compliance: "#dkCompliance", invest: "#dkInvest", findings: "#dkFindings", inventory: "#dkInventory", correlations: "#dkCorrelations", monitors: "#dkMonitors", deadlines: "#dkDeadlines", apikeys: "#dkApiKeys", device: "#dkDevice", audit: "#dkAudit", section: "#dkSection", con: "#dkCon", tools: "#dkTools", toolkit: "#dkToolkit", activity: "#dkActivity", assistant: "#dkAssistant", plans: "#dkPlans", settings: "#dkSettings", reports: "#dkReports", team: "#dkTeam", owner: "#dkOwner", personal: "#dkPersonal", enterprise: "#dkEnterprise" };
// Every Deck page has a darknode.ai link: a page is / (the overview is /, a section is
// /area/, a Personal/Organization tab is /personal/). compliance and tools are also
// tool ids, so those pages take another name.
diff --git a/public/js/docs.js b/public/js/docs.js
index 65115308..0c2f8d26 100644
--- a/public/js/docs.js
+++ b/public/js/docs.js
@@ -32,7 +32,7 @@ const STANDOUT = [
];
const CHANGELOG = [
- ["3.3.x", "Live integrations: Deck security integrations are connected only after a live key test, through a relay to fixed provider endpoints (VirusTotal, Shodan, AbuseIPDB, GreyNoise, OTX, urlscan, SecurityTrails, ipinfo, Have I Been Pwned, Hunter, Pulsedive, Hybrid Analysis, plus keyless NVD and CIRCL CVE). The Deck Assistant can run lookups on connected integrations, asking first each time unless you choose Always allow. Text boxes no longer refill from saved lists on reload; a Load saved list button brings them back on request. A full bug sweep fixed about 90 issues across the Deck, the business tools, the flagship tools and all 780 quick utilities, among them wrong file hashes for binary files, a strict CSP graded as broken, missed SQL injection and display-name spoofing, the ASN Explorer (moved from the retired BGPView to RIPEstat), and spreadsheet formula injection in CSV exports. Nexus background sessions (nexus bg / attach / sessions); signed-in Nexus and desktop app report version, OS and VM counts every 6 hours (/shareusage off, or Settings > Share app usage). Docs: the Nexus Commands tab lists every Nexus command, and Cost Saving shows /cheap before-and-after costs on each Claude model, measured on real sessions. A free domain check on the home page, with no sign-up, grades email authentication, HTTPS, certificate expiry (from certificate transparency logs), security headers, DNSSEC, CAA and security.txt and shows what each check is worth; a /check/your-domain link runs it again live, and a new Deck opens on the same check with each issue saved as a finding. The Free plan now watches one domain: after a check, Watch this domain checks its certificate expiry and its email/DNS records (SPF, DMARC, MX, CAA) once a day and emails your verified account address when something changes, with what changed, why it matters and the exact fix (at most 5 alert emails a day, each with a stop link). Monitors can also email your account address on Pro and above. Deadlines: a Deadlines page and an Overview block list the clocks your findings start, soonest first with the time left: a watched certificate's expiry and, only if you opt in, the Cyber Resilience Act Article 14 reporting clocks (early warning 24 hours and vulnerability notification 72 hours after you become aware of an actively exploited vulnerability in an asset you mark as shipped in a product, final report 14 days after a fix is available) and CISA BOD 22-01 due dates. Alerts go out when a clock starts and when a quarter of its time is left, and a certificate's last-week re-alert is now that reminder. A Copy early-warning facts panel lists the CVE, the product, when exploitation was confirmed, when you became aware, the Member States and the measures known. Darknode does not decide whether these rules apply and does not submit anything. Two new monitors, also part of the Free watch: domain registration (expiry, a pending transfer and the transfer lock, read from the registry's RDAP record) and website security (HTTPS, security headers and cookie flags, and an exposed .git or .env). Once a site has been checked, a header that disappears or weakens alerts."],
+ ["3.3.x", "Live integrations: Deck security integrations are connected only after a live key test, through a relay to fixed provider endpoints (VirusTotal, Shodan, AbuseIPDB, GreyNoise, OTX, urlscan, SecurityTrails, ipinfo, Have I Been Pwned, Hunter, Pulsedive, Hybrid Analysis, plus keyless NVD and CIRCL CVE). The Deck Assistant can run lookups on connected integrations, asking first each time unless you choose Always allow. Text boxes no longer refill from saved lists on reload; a Load saved list button brings them back on request. A full bug sweep fixed about 90 issues across the Deck, the business tools, the flagship tools and all 780 quick utilities, among them wrong file hashes for binary files, a strict CSP graded as broken, missed SQL injection and display-name spoofing, the ASN Explorer (moved from the retired BGPView to RIPEstat), and spreadsheet formula injection in CSV exports. Nexus background sessions (nexus bg / attach / sessions); signed-in Nexus and desktop app report version, OS and VM counts every 6 hours (/shareusage off, or Settings > Share app usage). Docs: the Nexus Commands tab lists every Nexus command, and Cost Saving shows /cheap before-and-after costs on each Claude model, measured on real sessions. A free domain check on the home page, with no sign-up, grades email authentication, HTTPS, certificate expiry (from certificate transparency logs), security headers, DNSSEC, CAA and security.txt and shows what each check is worth; a /check/your-domain link runs it again live, and a new Deck opens on the same check with each issue saved as a finding. The Free plan now watches one domain: after a check, Watch this domain checks its certificate expiry and its email/DNS records (SPF, DMARC, MX, CAA) once a day and emails your verified account address when something changes, with what changed, why it matters and the exact fix (at most 5 alert emails a day, each with a stop link). Monitors can also email your account address on Pro and above. Deadlines: a Deadlines page and an Overview block list the clocks your findings start, soonest first with the time left: a watched certificate's expiry and, only if you opt in, the Cyber Resilience Act Article 14 reporting clocks (early warning 24 hours and vulnerability notification 72 hours after you become aware of an actively exploited vulnerability in an asset you mark as shipped in a product, final report 14 days after a fix is available) and CISA BOD 22-01 due dates. Alerts go out when a clock starts and when a quarter of its time is left, and a certificate's last-week re-alert is now that reminder. A Copy early-warning facts panel lists the CVE, the product, when exploitation was confirmed, when you became aware, the Member States and the measures known. Darknode does not decide whether these rules apply and does not submit anything. Two new monitors, also part of the Free watch: domain registration (expiry, a pending transfer and the transfer lock, read from the registry's RDAP record) and website security (HTTPS, security headers and cookie flags, and an exposed .git or .env). Once a site has been checked, a header that disappears or weakens alerts. Getting started on the Overview now takes you through checking your domain, having Darknode watch it and turning on the Monday summary email."],
["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."],
@@ -152,7 +152,7 @@ node darknode.js nexus init # optional: scaffold .nexus/ project
We collect the minimum needed to run the Services.
Local edition. The CLI and desktop app run on your machine. Project state lives in .nexus/. We do not collect your code or prompts.
-
Web Deck. If you sign in, we store your account identifier and preferences to provide the service. We do not sell personal data.
+
Web Deck. If you sign in, we store your account identifier and preferences to provide the service, and the dates (no times) of the days you opened the Deck in the last 60 days with a count of all such days, so we can tell whether Darknode is useful enough to come back to. We do not sell personal data.
Feedback. Feedback you submit is stored to improve the product and is readable only by you and the maintainers.
Retention & deletion. You can delete your account and its data at any time in the Deck under Settings, Data, Delete account. It takes effect at once and cannot be undone.
In-browser tools. Most analysis runs in your browser. Check history and saved domain lists in the Deck spaces are kept in your browser's local storage, unless you turn on the weekly email digest or a monitor (see below). Live checks against a domain you enter are fetched through our edge proxy and are not stored.
We store minimal user data in Firebase (Google Cloud):
-
What we collect: email address, display name, profile photo URL, login timestamps, and ToS acceptance records.
+
What we collect: email address, display name, profile photo URL, login timestamps, the dates you used the Deck in the last 60 days with a count of such days, and ToS acceptance records.
Legal basis: legitimate interest (providing the service) and your consent (accepting these terms).
Data retention: your data is retained while your account is active. After deletion, data is purged within 30 days, except where retention is required by law.
Integration relay: Deck integrations with providers that do not accept calls from a browser (such as VirusTotal, Shodan or AbuseIPDB) send your API key and the value you look up through Darknode's edge relay to that provider only. The relay uses the key for that one request and does not log or store the key, the value or the result; the provider processes them under its own terms. Keys stay in your browser, under your account.
diff --git a/public/js/ui/explain.js b/public/js/ui/explain.js
index 66414d60..adedf55f 100644
--- a/public/js/ui/explain.js
+++ b/public/js/ui/explain.js
@@ -54,6 +54,7 @@ export const EXPLAIN = {
"scene.toolkit": { title: "Toolkit", body: "Quick in-browser utilities: encoders, hashes, converters and calculators. Nothing is sent to a server." },
"scene.assistant": { title: "AI Assistant", body: "Chat with Darknode AI to triage a CVE, draft a runbook, explain a finding or review a config." },
"scene.admin": { title: "Admin", body: "Owner-only controls: users, bans, announcements and platform settings." },
+ "scene.owner": { title: "Owner", body: "Owner only. Whether people come back: sign-ups, how many returned on another day, weekly cohorts and the days each person used the Deck. Then the people list, the requests waiting for an answer (plan upgrades, account deletions, feedback, errors), the site banner and the ban list." },
"scene.settings": { title: "Settings", body: "Your account, appearance and preferences." },
"scene.team": { title: "Team", body: "Members and roles for the active team workspace. Add people by the user id they share with you, set their role (owner, admin, analyst, responder or viewer), and review the append-only membership log. Roles are enforced server-side; your personal workspace has no members." },
diff --git a/test/deck/owner-stats.test.mjs b/test/deck/owner-stats.test.mjs
new file mode 100644
index 00000000..ededaabe
--- /dev/null
+++ b/test/deck/owner-stats.test.mjs
@@ -0,0 +1,131 @@
+// Owner page retention numbers (deck/owner-stats.js) and the per-day activity record
+// (core/active-days.js) that feeds them.
+import { test, group, assert } from "../harness.mjs";
+import { markDay, dayOf, KEEP_DAYS } from "../../public/js/core/active-days.js";
+import { personOf, retention, peopleRows, weekStart, tsMs, ago } from "../../public/js/deck/owner-stats.js";
+
+const NOW = Date.parse("2026-11-29T12:00:00Z"); // a Sunday
+const D = 864e5;
+const iso = (ms) => new Date(ms).toISOString();
+
+group("core/active-days: markDay", () => {
+ test("adds today once and reports the change", () => {
+ const a = markDay([], NOW);
+ assert.deepEqual(a, { days: ["2026-11-29"], changed: true });
+ const b = markDay(a.days, NOW + 3600e3);
+ assert.equal(b.changed, false);
+ assert.deepEqual(b.days, ["2026-11-29"]);
+ });
+ test("drops junk, duplicates, future dates and days older than the window", () => {
+ const old = dayOf(NOW - KEEP_DAYS * D);
+ const { days } = markDay(["2026-11-20", "2026-11-20", "bad", 5, null, "2027-01-01", old, "2026-11-01"], NOW);
+ assert.deepEqual(days, ["2026-11-01", "2026-11-20", "2026-11-29"]);
+ });
+ test("a non-array is treated as no history", () => {
+ assert.deepEqual(markDay(undefined, NOW).days, ["2026-11-29"]);
+ assert.deepEqual(markDay("2026-11-29", NOW).days, ["2026-11-29"]);
+ });
+ test("the window never exceeds KEEP_DAYS dates", () => {
+ const all = Array.from({ length: 90 }, (_, i) => dayOf(NOW - i * D));
+ const { days } = markDay(all, NOW);
+ assert.equal(days.length, KEEP_DAYS);
+ assert.equal(days[days.length - 1], "2026-11-29");
+ });
+});
+
+group("deck/owner-stats: one person", () => {
+ test("tsMs reads Timestamps, seconds, ms and strings", () => {
+ assert.equal(tsMs({ toMillis: () => 5 }), 5);
+ assert.equal(tsMs({ toDate: () => new Date(7) }), 7);
+ assert.equal(tsMs(1700000000), 1700000000000);
+ assert.equal(tsMs(1700000000000), 1700000000000);
+ assert.equal(tsMs("2026-11-29T00:00:00Z"), Date.parse("2026-11-29T00:00:00Z"));
+ assert.equal(tsMs(null), 0);
+ assert.equal(tsMs("nope"), 0);
+ });
+ test("a one-visit sign-up has not returned", () => {
+ const p = personOf({ createdAt: NOW - 3 * D, lastSeen: NOW - 3 * D + 600e3 }, NOW);
+ assert.equal(p.days, 1);
+ assert.equal(p.returned, false);
+ assert.equal(p.active7, true);
+ });
+ test("a lastSeen a day or more after joining counts as a return (accounts older than day tracking)", () => {
+ const p = personOf({ createdAt: NOW - 20 * D, lastSeen: NOW - 10 * D }, NOW);
+ assert.equal(p.returned, true);
+ assert.equal(p.active7, false);
+ });
+ test("recentDays and activeDays give the day count and the last visit", () => {
+ const p = personOf({ createdAt: NOW - 30 * D, recentDays: ["2026-11-02", "2026-11-28"], activeDays: 6 }, NOW);
+ assert.equal(p.days, 6);
+ assert.equal(p.last, Date.parse("2026-11-28T00:00:00Z"));
+ assert.equal(p.returned, true);
+ });
+ test("Auth-only and unverified rows", () => {
+ const p = personOf({ authOnly: true, emailVerified: false, createdAt: iso(NOW - D), lastLoginAt: iso(NOW - D) }, NOW);
+ assert.equal(p.verified, false);
+ assert.equal(p.opened, false);
+ });
+});
+
+group("deck/owner-stats: retention", () => {
+ const users = [
+ { uid: "o", admin: true, createdAt: NOW - 90 * D, lastSeen: NOW },
+ { uid: "a", createdAt: NOW - 2 * D, lastSeen: NOW - 2 * D }, // once, this week
+ { uid: "b", createdAt: NOW - 40 * D, recentDays: ["2026-11-27", "2026-11-29"], activeDays: 9, lastSeen: NOW - 3600e3 }, // regular
+ { uid: "c", createdAt: NOW - 40 * D, lastSeen: NOW - 30 * D }, // came back, then left
+ { uid: "d", authOnly: true, emailVerified: false, createdAt: NOW - D, lastLoginAt: NOW - D }, // never verified
+ ];
+ const r = retention(users, NOW);
+ test("the owner is left out of every number", () => {
+ assert.equal(r.total, 4);
+ assert.equal(r.active1, 1);
+ });
+ test("totals and funnel", () => {
+ assert.equal(r.new7, 2);
+ assert.equal(r.returned, 2);
+ assert.equal(r.active7, 3);
+ assert.deepEqual(r.funnel.map((f) => f.n), [4, 3, 3, 2, 1]);
+ });
+ test("weekly cohorts start on Monday UTC, newest first", () => {
+ assert.equal(r.cohorts.length, 8);
+ assert.equal(new Date(r.cohorts[0].start).getUTCDay(), 1);
+ assert.equal(r.cohorts[0].start, weekStart(NOW));
+ assert.equal(r.cohorts[0].signups, 2); // a and d joined this week
+ const six = r.cohorts.find((c) => c.start <= NOW - 40 * D && NOW - 40 * D < c.start + 7 * D);
+ assert.equal(six.signups, 2);
+ assert.equal(six.returned, 2);
+ assert.equal(six.active7, 1);
+ });
+ test("an empty list is all zeros", () => {
+ const z = retention([], NOW);
+ assert.equal(z.total, 0);
+ assert.ok(z.funnel.every((f) => f.n === 0));
+ });
+});
+
+group("deck/owner-stats: users table", () => {
+ const users = [
+ { uid: "o", admin: true, email: "owner@x.test", lastSeen: NOW },
+ { uid: "a", email: "Ann@x.test", createdAt: NOW - 2 * D, lastSeen: NOW - 2 * D },
+ { uid: "b", email: "bob@x.test", name: "Robert", createdAt: NOW - 40 * D, lastSeen: NOW - 30 * D },
+ { uid: "d", email: "dee@x.test", authOnly: true, emailVerified: false, createdAt: NOW - D },
+ ];
+ const ids = (rows) => rows.map((r) => r.u.uid);
+ test("most recently seen first", () => assert.deepEqual(ids(peopleRows(users, { now: NOW })), ["o", "d", "a", "b"]));
+ test("filters", () => {
+ assert.deepEqual(ids(peopleRows(users, { filter: "active", now: NOW })), ["o", "d", "a"]);
+ assert.deepEqual(ids(peopleRows(users, { filter: "once", now: NOW })), ["d", "a"]);
+ assert.deepEqual(ids(peopleRows(users, { filter: "unverified", now: NOW })), ["d"]);
+ assert.deepEqual(ids(peopleRows(users, { filter: "banned", banned: ["ann@x.test"], now: NOW })), ["a"]);
+ });
+ test("search matches email or name, any case", () => {
+ assert.deepEqual(ids(peopleRows(users, { q: "ROBERT", now: NOW })), ["b"]);
+ assert.deepEqual(ids(peopleRows(users, { q: "ann@", now: NOW })), ["a"]);
+ });
+ test("ago", () => {
+ assert.equal(ago(0, NOW), "never");
+ assert.equal(ago(NOW - 30e3, NOW), "just now");
+ assert.equal(ago(NOW - 5 * 3600e3, NOW), "5 h ago");
+ assert.equal(ago(NOW - 3 * D, NOW), "3 d ago");
+ });
+});
diff --git a/test/deck/usage-client.test.mjs b/test/deck/usage-client.test.mjs
index 3b8af360..c8e1154c 100644
--- a/test/deck/usage-client.test.mjs
+++ b/test/deck/usage-client.test.mjs
@@ -1,8 +1,7 @@
-// The desktop app's usage heartbeat (public/js/usage-ping.js) and the admin panel's
-// "Nexus, desktop app & VMs" list (public/js/admin-usage.js).
+// The desktop app's usage heartbeat (public/js/usage-ping.js). The owner page shows the
+// result per person (deck/owner.js).
import { test, group, assert } from "../harness.mjs";
import { pingAppUsage, usageOff, setUsageOff, OFF_KEY } from "../../public/js/usage-ping.js";
-import { usageRows, usageSummary, render, ago } from "../../public/js/admin-usage.js";
const mem = () => { const m = new Map(); return { getItem: (k) => (m.has(k) ? m.get(k) : null), setItem: (k, v) => m.set(k, String(v)), removeItem: (k) => m.delete(k) }; };
const appWin = (native = {}) => ({ darknode: { desktop: { shell: "web", version: "2.55.4", platform: "linux" }, native } });
@@ -40,43 +39,3 @@ group("usage ping (desktop app)", () => {
assert.equal(await pingAppUsage({ win: appWin(), store, api: async () => ({}), now: 1e13 + 1 }), "sent");
});
});
-
-group("admin usage list", () => {
- const NOW = Date.parse("2026-11-07T12:00:00Z");
- const docs = [
- { uid: "a", email: "test@darknode.ai", nexus: { last: NOW - 3600e3, first: NOW - 40 * 864e5, version: "2.56.0", os: "linux" }, app: { last: NOW - 20 * 864e5, version: "2.55.4", os: "darwin" } },
- { uid: "b", email: "", nexus: { last: NOW - 60e3, version: "2.56.0", os: "win32" }, vm: { last: NOW, count: 3, running: 1 } },
- { uid: "c", email: "x@y.z" },
- ];
- test("rows per product, most recent first; people without that product are left out", () => {
- assert.deepEqual(usageRows(docs, "nexus").map((r) => r.uid), ["b", "a"]);
- assert.deepEqual(usageRows(docs, "app").map((r) => r.uid), ["a"]);
- assert.equal(usageRows(docs, "vm")[0].count, 3);
- });
- test("summary counts everyone and the last 7 days", () => {
- const s = usageSummary(docs, NOW);
- assert.deepEqual(s.nexus, { total: 2, week: 2 });
- assert.deepEqual(s.app, { total: 1, week: 0 });
- assert.deepEqual(s.vm, { total: 1, week: 1 });
- });
- test("Firestore timestamps are read too", () => {
- const r = usageRows([{ uid: "t", nexus: { last: { toMillis: () => NOW } } }], "nexus");
- assert.equal(r[0].last, NOW);
- });
- test("render escapes emails and filters by search", () => {
- const host = { innerHTML: "" };
- render(host, [{ uid: "z", email: "", nexus: { last: NOW } }], { tab: "nexus", q: "" }, esc, NOW);
- assert.ok(host.innerHTML.includes("<img") && !host.innerHTML.includes(" {
- assert.equal(ago(0, NOW), "never");
- assert.equal(ago(NOW - 30e3, NOW), "just now");
- assert.equal(ago(NOW - 5 * 60e3, NOW), "5 min ago");
- assert.equal(ago(NOW - 3 * 3600e3, NOW), "3 h ago");
- });
-});
diff --git a/unused-stuff/README.md b/unused-stuff/README.md
index 79466420..6778b423 100644
--- a/unused-stuff/README.md
+++ b/unused-stuff/README.md
@@ -101,3 +101,12 @@ and `public/js/console-nav.js`. Files are kept at their original names under `js
An unfilled Terms of Service template (21 "[SPECIFY ...]" placeholders and drafting notes)
that was publicly served at /legal/terms-of-service.html. It was never the binding text
(that is public/js/legal.js, shown at /terms); the old URL now redirects to /terms.
+
+## owner-console/
+
+The console's owner Admin page, retired 2026-11-29 when the Deck's Owner scene
+(`public/js/deck/owner.js`, at `/owner`) replaced it. `js/admin.js` is the full old file
+(users list, ban list, announcement, feedback, errors, upgrade and deletion requests, usage,
+analytics, activity log); the live `public/js/admin.js` keeps only `getWhitelist` and the Deck
+launcher re-exports. `js/admin-usage.js` drew the Nexus/app/VM usage list and `js/preview-ui.js`
+was the "Preview UI" view the page launched; nothing else used either.
diff --git a/public/js/admin-usage.js b/unused-stuff/owner-console/js/admin-usage.js
similarity index 100%
rename from public/js/admin-usage.js
rename to unused-stuff/owner-console/js/admin-usage.js
diff --git a/unused-stuff/owner-console/js/admin.js b/unused-stuff/owner-console/js/admin.js
new file mode 100644
index 00000000..80452815
--- /dev/null
+++ b/unused-stuff/owner-console/js/admin.js
@@ -0,0 +1,988 @@
+// Owner-only admin console: live user management, a ban-list (the site is open
+// to everyone; only banned emails are blocked at sign-in), and site-wide
+// announcements. All backed by Firestore.
+import { db } from "/js/firebase.js?v=20261021a";
+
+// The super-admin is no longer a hardcoded email. The set-admin script stamps the
+// owner's own user doc with `admin: true` (alongside the Firebase custom claim),
+// so this owner-only panel can still badge/exclude that row. The access decision
+// itself is enforced by the ID-token claim + Security Rules, not by this flag.
+const isOwnerRow = (u) => !!u && (u.admin === true || u.role === "owner");
+import {
+ collection, getDocs, doc, getDoc, setDoc, deleteDoc, serverTimestamp,
+ addDoc, query, orderBy, updateDoc, limit,
+} from "https://www.gstatic.com/firebasejs/12.17.0/firebase-firestore.js";
+
+// Profile timestamps come as Firestore Timestamps, epoch numbers (the worker's Auth-only rows)
+// or the Auth metadata string ensureUserDoc stores ("Wed, 11 Nov 2026 ..."); all count.
+const tsMs = (ts) => ts && ts.toMillis ? ts.toMillis() : ts && ts.toDate ? ts.toDate().getTime()
+ : typeof ts === "number" ? (ts < 1e12 ? ts * 1000 : ts) : typeof ts === "string" ? (Date.parse(ts) || 0) : 0;
+// Only the sign-in providers' own avatar hosts load: photoURL is user-writable, and any other
+// URL would send the owner's IP and browser to a server the user picked.
+const AVATAR_HOST = /^(lh\d+\.googleusercontent\.com|avatars\.githubusercontent\.com)$/;
+const safeAvatar = (u) => { try { const x = new URL(u); return x.protocol === "https:" && AVATAR_HOST.test(x.hostname) ? x.href : ""; } catch (_) { return ""; } };
+const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) =>
+ ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
+const fmtDate = (ts) => {
+ try { const d = ts?.toDate ? ts.toDate() : (ts ? new Date(ts) : null); return d ? d.toLocaleString() : "—"; } catch (_) { return "—"; }
+};
+
+const WL_REF = () => doc(db, "settings", "whitelist");
+const ANN_REF = () => doc(db, "announcements", "current");
+
+// Read the access-control doc (stored at settings/whitelist for history). It now
+// carries a `banned` list; auth.js denies only those emails. Everyone else is
+// allowed. The legacy `emails`/`enforce` allow-list fields are left untouched
+// for back-compat but are no longer enforced.
+export async function getWhitelist() {
+ try { const s = await getDoc(WL_REF()); return s.exists() ? s.data() : { emails: [], enforce: false, banned: [] }; }
+ catch (_) { return { emails: [], enforce: false, banned: [] }; }
+}
+
+// The Deck launcher lives in its own module so every signed-in user can load it.
+import { openDeck, closeDeck } from "/js/deck/launch.js?v=20261030d";
+export { openDeck, closeDeck };
+
+// ---- Preview UI: a light, single-surface alternate view of every tool, launched from
+// the admin page like the Deck. Same NAV taxonomy, self-contained module (scoped .pvx). ----
+let _previewOff = null;
+export async function openPreview(user) {
+ const nav = await import("/js/console-nav.js?v=20261029d");
+ const { renderPreview } = await import("/js/preview-ui.js?v=20261019h");
+ if (_previewOff) { try { _previewOff(); } catch (_) {} _previewOff = null; }
+ document.querySelectorAll("body > .pvx").forEach((n) => n.remove());
+ _previewOff = renderPreview(document.body, {
+ groups: (nav.NAV || []).map((g) => ({ id: g.id, name: g.name, color: g.color, items: g.items || [] })),
+ onExit: () => { _previewOff = null; },
+ });
+ return _previewOff;
+}
+export async function renderAdmin(main, user) {
+ main.innerHTML = `
+
Admin
+
Owner console — ${esc(user.email)} OWNER
+
+
+
…
users
+
…
new this week
+
…
active today
+
…
banned
+
…
announcement
+
+
+
+
+ OWNER ONLY
+
Darknode Command Center
+
The Deck: grouped sidebar, posture overview, attack surface, investigations and every tool in one workspace, with Ctrl K search. Visible only to you.
+
+
+
+
+
+
+
+
+
+
+
+
Users
+
+
+
Loading users…
+
+
+
Nexus, desktop app & VMs
+
+
+
Loading usage…
+
+
+
Recent new-device sign-ins
+
…
+
+
+
Plan upgrade requests
+
+
Requests from the Deck's Plans page. Granting sets the user's plan tier.
+
Loading requests…
+
+
+
Account deletion requests
+
+
Filed before users could delete their own account. Delete runs the same full deletion a user starts in Settings; only accounts that asked are listed.
+
Loading requests…
+
+
+
Feedback & bug reports
+
+
Loading feedback…
+
+
+
Client Error Log
+
+
+
Automatic crash reports from user sessions.
+
Loading errors…
+
+
+
Data & outreach
+
Export the user base or grab every email for an announcement mailout.
+
+
+
+
+
+
+
+
+
Email Users
+
Send an email from contact@darknode.ai to one user or all registered users.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Quick templates:
+
+
+
+
+
+
+
+
+
+
+
+
Banned emails
+
The site is open to everyone. Add an email here to block that account from signing in.
+
+
+
+
+
+
The owner account can never be banned. This list blocks sign-in in the browser only; to cut off an account completely, run node scripts/suspend-user.mjs <email>.
+
+
+
+
Announcement
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Site Analytics
+
+
+
--
Learn Hub topics
+
--
top learner
+
--
avg XP/user
+
--
total completions
+
+
+
+
+
+
+
+
User Activity Log
+
Recent user actions — sign-ins, page views, and tool usage.
+
Loading activity...
+
+
+
+
Maintenance
+
System health and maintenance actions.
+
+
+
+
+
+
+
+
+
+
Feature Flags
+
Toggle site features on/off without redeploying.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Quick Actions
+
+
+
+
+
+
+
+
+
+
System Status
+
+
Firebaseconnected
+
Firestoreconnected
+
Learn Hub--
+
Render deploy--
+
JS bundle--
+
+
+
+
+
Danger Zone
+
+
+
+
+
+
+
+
`;
+
+ const $ = (id) => main.querySelector(id);
+
+ // ---- Darknode Deck: owner-only command center, launched from here ----
+ // Lazy-loaded so the module never ships to the normal console. Uses the live NAV
+ // taxonomy as the single source of truth for categories.
+ (function wireDeck() {
+ const btn = main.querySelector("#deckLaunch");
+ if (!btn) return;
+ // framed inside the Deck already: opening a second Deck inside its Admin window is no use
+ if (document.documentElement.hasAttribute("data-embed")) { btn.remove(); return; }
+ async function launchDeck() {
+ btn.disabled = true; const label = btn.textContent; btn.textContent = "Loading…";
+ try {
+ await openDeck(user, { isOwner: true });
+ } catch (e) {
+ try { window.showToast ? window.showToast("Command center failed to load: " + e.message, "error") : 0; } catch (_) {}
+ } finally { btn.disabled = false; btn.textContent = label; }
+ }
+ btn.addEventListener("click", launchDeck);
+ // Returning from an OpenRouter account-link: finish the handshake, then re-open
+ // the deck so the user lands back where they started and sees it connected.
+ import("/js/openrouter-connect.js?v=20261028c").then(({ shouldReopenDeck }) => {
+ if (shouldReopenDeck()) Promise.resolve(window.__orConnect).finally(launchDeck);
+ }).catch(() => {});
+ })();
+
+
+ // ---- Preview UI launcher (sits beside the Deck button) ----
+ (function wirePreview() {
+ const btn = main.querySelector("#previewLaunch");
+ if (!btn) return;
+ btn.addEventListener("click", async () => {
+ btn.disabled = true; const label = btn.textContent; btn.textContent = "Loading…";
+ try { await openPreview(user); }
+ catch (e) { try { window.showToast && window.showToast("Preview UI failed to load: " + e.message, "error"); } catch (_) {} }
+ finally { btn.disabled = false; btn.textContent = label; }
+ });
+ })();
+
+ let users = [];
+ let wl = { emails: [], enforce: false, banned: [] };
+
+ // ---- users ----
+ async function loadUsers() {
+ const host = $("#uList");
+ try {
+ const snap = await getDocs(collection(db, "users"));
+ users = snap.docs.map((d) => ({ uid: d.id, ...d.data() }));
+ // Firebase Auth accounts with no users/{uid} doc (an email sign-up that never verified
+ // never writes one). Listed by the Worker with its service account; owner only.
+ try {
+ const { api } = await import("/js/core/api.js");
+ const r = await api("/api/admin/users");
+ const have = new Map(users.map((u) => [u.uid, u]));
+ for (const a of (r && r.users) || []) {
+ const u = have.get(a.uid);
+ if (u) { u.emailVerified = a.emailVerified; u.disabled = a.disabled; continue; }
+ users.push({ uid: a.uid, email: a.email, name: a.name, provider: a.providers.join(", ") || "email", createdAt: a.createdAt, lastLoginAt: a.lastLoginAt, lastSeen: a.lastLoginAt, emailVerified: a.emailVerified, disabled: a.disabled, authOnly: true });
+ }
+ } catch (_) { /* Worker unreachable: the Firestore list still shows */ }
+ $("#stUsers").textContent = users.length;
+ const toMs = tsMs;
+ const now = Date.now(), day = 864e5, midnight = new Date(); midnight.setHours(0, 0, 0, 0);
+ $("#stNew").textContent = users.filter((u) => { const c = toMs(u.created || u.createdAt); return c && now - c < 7 * day; }).length || "—";
+ $("#stActive").textContent = users.filter((u) => toMs(u.lastSeen) >= midnight.getTime()).length;
+ drawUsers();
+ const alerts = [];
+ users.forEach((u) => (u.logins || []).forEach((l) => alerts.push({ email: u.email, device: l.device, ts: l.ts })));
+ alerts.sort((a, b) => (b.ts || 0) - (a.ts || 0));
+ $("#loginList").innerHTML = alerts.length
+ ? alerts.slice(0, 20).map((a) => `
${esc(a.device || "device")}
${esc(a.email || "")}
${esc(fmtDate(a.ts))}
`).join("")
+ : `
No new-device sign-ins recorded yet.
`;
+ } catch (e) {
+ host.innerHTML = `
Couldn't load users: ${esc(e.message)}. Make sure Firestore rules are deployed.