From bf37d29fb5148af7ff6fa7c36e80285bd49bd1c8 Mon Sep 17 00:00:00 2001 From: Darknode-Official Date: Sun, 29 Nov 2026 11:38:25 -0800 Subject: [PATCH] Owner page in the Deck, built around whether people come back The console Admin page is replaced by an Owner scene at /owner (owner only): - Retention first: people signed up, new this week, came back on another day, used it this week and today; a sign-up-to-habit funnel; weekly cohorts. - People table, most recently seen first, with filters (active this week, came once, unverified, banned), search, days used, plan, Nexus/app use, a 60-day activity strip per person, ban/unban and CSV export. - One inbox for plan requests, account deletion requests, feedback and errors. - Site banner and ban list. To measure return visits, the Deck records the dates it was opened (last 60 days) and a count of such days on users/{uid}, at most one write a day. Getting started on the Overview becomes the return loop: check your domain, have Darknode watch it (alert emails), turn on the Monday summary. The old admin page code, the Preview UI and the usage list are archived under unused-stuff/owner-console/. Docs Privacy, the TOS data list and the changelog mention the new dates. --- firebase.json | 4 +- public/js/admin.js | 988 +----------------- public/js/auth.js | 2 +- public/js/core/active-days.js | 19 + public/js/deck-ui.js | 99 +- public/js/deck/launch.js | 27 +- public/js/deck/owner-stats.js | 102 ++ public/js/deck/owner.js | 403 +++++++ public/js/deck/routes.js | 2 +- public/js/docs.js | 4 +- public/js/legal.js | 2 +- public/js/ui/explain.js | 1 + test/deck/owner-stats.test.mjs | 131 +++ test/deck/usage-client.test.mjs | 45 +- unused-stuff/README.md | 9 + .../owner-console}/js/admin-usage.js | 0 unused-stuff/owner-console/js/admin.js | 988 ++++++++++++++++++ .../owner-console}/js/preview-ui.js | 0 18 files changed, 1767 insertions(+), 1059 deletions(-) create mode 100644 public/js/core/active-days.js create mode 100644 public/js/deck/owner-stats.js create mode 100644 public/js/deck/owner.js create mode 100644 test/deck/owner-stats.test.mjs rename {public => unused-stuff/owner-console}/js/admin-usage.js (100%) create mode 100644 unused-stuff/owner-console/js/admin.js rename {public => unused-stuff/owner-console}/js/preview-ui.js (100%) 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.

`; - $("#stUsers").textContent = "—"; - } - } - function drawUsers() { - const q = ($("#uSearch").value || "").toLowerCase().trim(); - const rows = users - .filter((u) => !q || (u.email + " " + (u.name || "") + " " + (u.provider || "")).toLowerCase().includes(q)) - .sort((a, b) => (a.email || "").localeCompare(b.email || "")); - const host = $("#uList"); - if (!rows.length) { host.innerHTML = `

No matching users.

`; return; } - host.innerHTML = rows.map((u) => { - const isOwner = isOwnerRow(u); - const banned = (wl.banned || []).includes((u.email || "").toLowerCase()); - const prov = u.provider || "email"; - const provBadge = prov.includes("google") ? 'Google' - : prov.includes("github") ? 'GitHub' - : 'Email'; - const pic = safeAvatar(u.photoURL); - const avatar = pic - ? `` - : `${esc((u.email || "?")[0].toUpperCase())}`; - return `
- ${avatar} -
-
${esc(u.name || "(no name)")} ${provBadge}${isOwner ? 'OWNER' : ""}${banned ? 'banned' : ""}${u.emailVerified === false ? 'email not verified' : ""}${u.authOnly ? 'no profile yet' : ""}${u.disabled ? 'disabled' : ""}
-
${esc(u.email || u.uid)}
-
last seen ${esc(fmtDate(u.lastSeen))}${u.createdAt ? " · joined " + esc(fmtDate(u.createdAt)) : ""}
-
-
- - ${isOwner ? "" : ``} - ${isOwner ? "" : ``} -
-
- `; - }).join(""); - } - $("#uRefresh").onclick = loadUsers; - - // ---- feedback / bug reports ---- - async function loadFeedback() { - const host = $("#fbAdminList"); if (!host) return; - try { - const snap = await getDocs(collection(db, "feedback")); - const toMs = (ts) => (ts && ts.toMillis ? ts.toMillis() : 0); - const items = snap.docs.map((d) => ({ id: d.id, ...d.data() })).sort((a, b) => toMs(b.ts) - toMs(a.ts)); - if (!items.length) { host.innerHTML = `

No feedback yet.

`; return; } - host.innerHTML = items.map((f) => ` -
-
${esc((f.type || "note").toUpperCase())} ${esc(f.email || "anon")}${f.ts && f.ts.toDate ? esc(fmtDate(f.ts)) : ""}
-
${esc(f.message || "")}
- ${f.url ? `
${esc(f.url)}
` : ""} -
`).join(""); - } catch (e) { host.innerHTML = `

Couldn't load feedback: ${esc(e.message)}. Ensure Firestore rules allow the owner to read the 'feedback' collection.

`; } - } - $("#fbRefresh").onclick = loadFeedback; - $("#fbAdminList").onclick = async (e) => { - const del = e.target.closest(".fb-del"); if (!del) return; - const row = del.closest(".fb-row"); if (!row) return; - if (!(await window.dnConfirm("Delete feedback?", "This permanently removes this feedback entry.", { danger: true }))) return; - try { await deleteDoc(doc(db, "feedback", row.dataset.id)); row.remove(); } catch (err) { window.showToast("Delete failed: " + err.message, "error"); } - }; - loadFeedback(); - - // ---- plan upgrade requests ---- - async function loadUpgradeRequests() { - const host = $("#upReqList"); if (!host) return; - try { - const snap = await getDocs(query(collection(db, "upgradeRequests"), orderBy("ts", "desc"))); - const items = snap.docs.map((d) => ({ id: d.id, ...d.data() })); - const pending = items.filter((r) => r.status === "pending"); - if (!items.length) { host.innerHTML = `

No upgrade requests yet.

`; return; } - host.innerHTML = items.map((r) => ` -
-
${esc((r.tier || "—").toUpperCase())} ${esc(r.email || r.uid || "user")} - ${r.status === "pending" ? "pending" : esc(r.status || "")} - ${r.ts && r.ts.toDate ? esc(fmtDate(r.ts)) : ""} - ${r.status === "pending" ? `` : ``}
- ${r.note ? `
${esc(r.note)}
` : ""} -
`).join(""); - $("#upReqList").dataset.pending = String(pending.length); - } catch (e) { host.innerHTML = `

Couldn't load upgrade requests: ${esc(e.message)}. Ensure the 'upgradeRequests' rules are deployed.

`; } - } - $("#upReqRefresh").onclick = loadUpgradeRequests; - $("#upReqList").onclick = async (e) => { - const row = e.target.closest(".fb-row"); if (!row) return; - const rid = row.dataset.id, uid = row.dataset.uid, tier = row.dataset.tier; - if (e.target.closest(".upr-grant")) { - if (!uid || !tier) { window.showToast("Request is missing a user or tier.", "error"); return; } - if (!(await window.dnConfirm("Grant " + tier + "?", "This sets this user's plan tier to '" + tier + "'. They get the tier's features immediately.", { submitText: "Grant" }))) return; - try { - await setDoc(doc(db, "users", uid), { tier, tierGrantedAt: serverTimestamp() }, { merge: true }); - // Durable notification so the user learns of the upgrade on any device (A6). - try { - await addDoc(collection(db, "users", uid, "notifications"), { - text: "Your plan was upgraded to " + (tier.charAt(0).toUpperCase() + tier.slice(1)) + ".", - kind: "plan", ts: Date.now(), read: false, - }); - } catch (_) {} - await updateDoc(doc(db, "upgradeRequests", rid), { status: "granted", grantedAt: serverTimestamp() }); - window.showToast("Granted " + tier, "success"); loadUpgradeRequests(); - } catch (err) { window.showToast("Grant failed: " + err.message, "error"); } - return; - } - if (e.target.closest(".upr-dismiss")) { - try { await updateDoc(doc(db, "upgradeRequests", rid), { status: "dismissed" }); loadUpgradeRequests(); } - catch (err) { window.showToast("Dismiss failed: " + err.message, "error"); } - return; - } - if (e.target.closest(".upr-del")) { - if (!(await window.dnConfirm("Delete request?", "This permanently removes this request.", { danger: true }))) return; - try { await deleteDoc(doc(db, "upgradeRequests", rid)); row.remove(); } - catch (err) { window.showToast("Delete failed: " + err.message, "error"); } - } - }; - loadUpgradeRequests(); - - // ---- account deletion requests (Worker /api/admin/deletions, service account) ---- - async function loadDeletionRequests() { - const host = $("#delReqList"); if (!host) return; - try { - const { api } = await import("/js/core/api.js"); - const r = await api("/api/admin/deletions"); - const items = (r && r.requests) || []; - if (!items.length) { host.innerHTML = `

No pending deletion requests.

`; return; } - host.innerHTML = items.map((x) => ` -
-
${esc(x.email || x.uid)} - ${x.requestedAt ? esc(new Date(x.requestedAt).toLocaleString()) : ""} -
-
`).join(""); - } catch (e) { host.innerHTML = `

Couldn't load deletion requests: ${esc(e.message)}

`; } - } - $("#delReqRefresh").onclick = loadDeletionRequests; - $("#delReqList").onclick = async (e) => { - const btn = e.target.closest(".dr-del"); if (!btn) return; - const row = btn.closest(".fb-row"), uid = row.dataset.uid, who = row.dataset.email || uid; - if (!(await window.dnConfirm("Delete " + who + "?", "This permanently deletes the account and everything stored with it, as the user asked. It cannot be undone.", { submitText: "Delete account", danger: true }))) return; - btn.disabled = true; - try { - const { api } = await import("/js/core/api.js"); - await api("/api/admin/deletions", { method: "POST", body: { uid } }); - window.showToast("Deleted " + who, "success"); row.remove(); - } catch (err) { btn.disabled = false; window.showToast(err.message || "Delete failed", "error"); } - }; - loadDeletionRequests(); - - // ---- client error log ---- - async function loadErrors() { - const host = $("#errAdminList"); if (!host) return; - try { - const snap = await getDocs(collection(db, "errors")); - const toMs = (ts) => (ts && ts.toMillis ? ts.toMillis() : 0); - const items = snap.docs.map((d) => ({ id: d.id, ...d.data() })).sort((a, b) => toMs(b.ts) - toMs(a.ts)); - if (!items.length) { host.innerHTML = `

No errors logged.

`; return; } - host.innerHTML = items.slice(0, 50).map((e) => ` -
-
- ERROR - ${esc(e.email || "anon")} - - ${e.ts && e.ts.toDate ? esc(fmtDate(e.ts)) : ""} - -
-
${esc(e.message || "")}
- ${e.source && e.source !== "unhandledrejection" ? `
${esc(e.source)}${e.line ? ':' + e.line : ''}${e.col ? ':' + e.col : ''}
` : ""} - ${e.stack ? `
Stack trace
${esc(e.stack)}
` : ""} - ${e.url ? `
${esc(e.url)}
` : ""} - ${e.ua ? `
${esc(e.ua)}
` : ""} -
`).join("") + (items.length > 50 ? `

Showing 50 of ${items.length} errors

` : ""); - } catch (e) { host.innerHTML = `

Couldn't load errors: ${esc(e.message)}

`; } - } - $("#errRefresh").onclick = loadErrors; - $("#errAdminList").onclick = async (e) => { - const del = e.target.closest(".fb-del"); if (!del) return; - const row = del.closest(".fb-row"); if (!row) return; - if (!(await window.dnConfirm("Delete error?", "This permanently removes this logged error.", { danger: true }))) return; - try { await deleteDoc(doc(db, "errors", row.dataset.id)); row.remove(); } catch (err) { window.showToast("Delete failed: " + err.message, "error"); } - }; - $("#errClear").onclick = async () => { - if (!(await window.dnConfirm("Clear all errors?", "This permanently deletes every logged client error.", { danger: true }))) return; - try { - const snap = await getDocs(collection(db, "errors")); - for (const d of snap.docs) { try { await deleteDoc(doc(db, "errors", d.id)); } catch (_) {} } - } catch (err) { window.showToast("Clear failed: " + err.message, "error"); } - loadErrors(); - }; - loadErrors(); - - $("#uSearch").oninput = drawUsers; - $("#uList").onclick = async (e) => { - const detailBtn = e.target.closest("[data-detail]"); - if (detailBtn) { - const panel = main.querySelector("#detail-" + detailBtn.dataset.detail); - if (panel) { panel.style.display = panel.style.display === "none" ? "" : "none"; detailBtn.textContent = panel.style.display === "none" ? "Details" : "Hide"; } - return; - } - const wlBtn = e.target.closest("[data-wl]"), delBtn = e.target.closest("[data-del]"); - if (wlBtn) { await toggleWl(wlBtn.dataset.wl); } - else if (delBtn) { - if (!(await window.dnConfirm("Remove user?", `This deletes the Firestore record for ${delBtn.dataset.mail || "this user"}.`, { danger: true }))) return; - try { await deleteDoc(doc(db, "users", delBtn.dataset.del)); users = users.filter((u) => u.uid !== delBtn.dataset.del); $("#stUsers").textContent = users.length; drawUsers(); } - catch (err) { window.showToast("Delete failed: " + err.message, "error"); } - } - }; - - // ---- ban-list (site is open to all; only these emails are blocked) ---- - const notify = (m, t) => { try { (window.showToast || (() => {}))(m, t || "info"); } catch (_) {} }; - async function loadWl() { - wl = await getWhitelist(); - wl.banned = (wl.banned || []).map((x) => String(x).toLowerCase()); - $("#stWl").textContent = wl.banned.length; - drawWl(); - } - function drawWl() { - const host = $("#wlList"); - host.innerHTML = wl.banned.length - ? wl.banned.map((em) => `
${esc(em)}
`).join("") - : `

No one is banned. Everyone can sign in.

`; - } - async function saveWl() { - try { - await setDoc(WL_REF(), { banned: wl.banned, enforce: false, updatedBy: user.email, updatedAt: serverTimestamp() }, { merge: true }); - $("#stWl").textContent = wl.banned.length; - return true; - } catch (e) { notify("Couldn't save ban-list: " + e.message, "error"); return false; } - } - async function toggleWl(email) { - email = (email || "").toLowerCase().trim(); if (!email) return; - // Never let the owner ban themselves or another owner out of the console. - const target = users.find((u) => (u.email || "").toLowerCase() === email); - if (!wl.banned.includes(email) && (email === (user.email || "").toLowerCase() || isOwnerRow(target))) { - notify("You can't ban an owner account.", "error"); return; - } - const banning = !wl.banned.includes(email); - if (banning) wl.banned.push(email); - else wl.banned = wl.banned.filter((x) => x !== email); - if (await saveWl()) { drawWl(); drawUsers(); notify(banning ? `Banned ${email}` : `Unbanned ${email}`, banning ? "warn" : "success"); } - } - $("#wlAdd").onclick = async () => { const v = $("#wlEmail").value.trim(); if (v) { await toggleWl(v); $("#wlEmail").value = ""; } }; - $("#wlEmail").onkeydown = (e) => { if (e.key === "Enter") $("#wlAdd").click(); }; - $("#wlList").onclick = (e) => { const b = e.target.closest("[data-rm]"); if (b) toggleWl(b.dataset.rm); }; - - // ---- announcement ---- - let annType = "info"; - $("#annType").onclick = (e) => { const b = e.target.closest("button[data-v]"); if (!b) return; annType = b.dataset.v; $("#annType").querySelectorAll("button").forEach((x) => x.classList.toggle("on", x === b)); }; - async function loadAnn() { - try { - const s = await getDoc(ANN_REF()); - if (s.exists()) { - const d = s.data(); - $("#annText").value = d.text || ""; - $("#annActive").checked = !!d.active; - annType = d.type === "warn" ? "warn" : "info"; - $("#annType").querySelectorAll("button").forEach((x) => x.classList.toggle("on", x.dataset.v === annType)); - $("#stAnn").textContent = d.active ? "live" : "off"; - } else { $("#stAnn").textContent = "off"; } - } catch (_) { $("#stAnn").textContent = "—"; } - } - async function publishAnn(active) { - const msg = $("#annMsg"), text = $("#annText").value.trim(); - try { - await setDoc(ANN_REF(), { text, type: annType, active, updatedBy: user.email, updatedAt: serverTimestamp() }, { merge: true }); - $("#annActive").checked = active; - $("#stAnn").textContent = active ? "live" : "off"; - // update the live banner in this session immediately - const el = document.getElementById("announcement"); - if (el) { if (active && text) { el.textContent = text; el.classList.toggle("banner-info", annType !== "warn"); el.hidden = false; } else { el.hidden = true; } } - msg.className = "adm-msg ok"; msg.textContent = active ? "Published — visible to everyone." : "Banner cleared."; - setTimeout(() => (msg.textContent = ""), 2500); - } catch (e) { msg.className = "adm-msg err"; msg.textContent = "Failed: " + e.message; } - } - $("#annPublish").onclick = () => { - if (!$("#annText").value.trim()) { const m = $("#annMsg"); m.className = "adm-msg err"; m.textContent = "write a message first"; return; } - $("#annActive").checked = true; publishAnn(true); - }; - $("#annClear").onclick = () => publishAnn(false); - - // ---- announcement presets ---- - const PRESETS = { - maint: "Scheduled maintenance is underway — some features may be briefly unavailable. Thanks for your patience.", - release: "New release is live! Update the desktop app and CLI from the Downloads page to get the latest tools and fixes.", - security: "Security notice: rotate any credentials you've stored and review recent sign-ins. Contact the owner with questions.", - }; - $("#annPresets").onclick = (e) => { const b = e.target.closest("[data-preset]"); if (!b) return; $("#annText").value = PRESETS[b.dataset.preset] || ""; annType = b.dataset.preset === "security" ? "warn" : "info"; $("#annType").querySelectorAll("button").forEach((x) => x.classList.toggle("on", x.dataset.v === annType)); }; - - // ---- data & outreach ---- - const dmsg = (t) => { const m = $("#dataMsg"); m.className = "adm-msg ok"; m.textContent = t; setTimeout(() => (m.textContent = ""), 2000); }; - const emailsOf = (list) => list.map((u) => u.email).filter(Boolean).join(", "); - $("#copyEmails").onclick = () => { navigator.clipboard?.writeText(emailsOf(users)); dmsg(users.filter((u) => u.email).length + " emails copied"); }; - $("#copyOwnerless").onclick = () => { const l = users.filter((u) => !isOwnerRow(u)); navigator.clipboard?.writeText(emailsOf(l)); dmsg(l.filter((u) => u.email).length + " emails copied"); }; - $("#expCsv").onclick = () => { - const esc2 = (v) => `"${String(v ?? "").replace(/^(?=[=+@\t\r]|-(?!\d+(?:\.\d+)?$))/, "'").replace(/"/g, '""')}"`; - const rows = [["email", "name", "uid", "lastSeen", "banned"]].concat(users.map((u) => [u.email, u.name, u.uid, fmtDate(u.lastSeen), (wl.banned || []).includes((u.email || "").toLowerCase()) ? "yes" : "no"])); - const csv = rows.map((r) => r.map(esc2).join(",")).join("\n"); - const url = URL.createObjectURL(new Blob([csv], { type: "text/csv" })); - const a = document.createElement("a"); a.href = url; a.download = "darknode-users.csv"; document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(url), 1000); - dmsg("exported " + users.length + " users"); - }; - - // ---- who uses Nexus, the desktop app and its VMs (usage/{uid}, written by the Worker) ---- - const usState = { tab: "nexus", q: "" }; - let usDocs = []; - async function loadUsage() { - const host = $("#usList"); - try { - const [mod, snap] = await Promise.all([import("/js/admin-usage.js?v=1"), getDocs(collection(db, "usage"))]); - usDocs = snap.docs.map((d) => ({ uid: d.id, ...d.data() })); - const draw = () => mod.render(host, usDocs, usState, esc); - host.onclick = (e) => { const t = e.target.closest("[data-utab]"); if (t) { usState.tab = t.dataset.utab; draw(); } }; - $("#usSearch").oninput = (e) => { usState.q = e.target.value; draw(); }; - draw(); - } catch (e) { host.innerHTML = `

Couldn't load usage: ${esc(e.message)}. Make sure Firestore rules are deployed.

`; } - } - $("#usRefresh").onclick = loadUsage; - - await Promise.all([loadWl(), loadUsers(), loadAnn(), loadUsage()]); - - // ---- Analytics ---- - async function loadAnalytics() { - try { - let totalXP = 0, totalCompletions = 0, topUser = { email: '-', xp: 0 }; - users.forEach(u => { - const xp = u.learnXP || 0; - const completed = (u.learnCompleted || []).length; - totalXP += xp; - totalCompletions += completed; - if (xp > topUser.xp) topUser = { email: u.email || '?', xp }; - }); - const avgXP = users.length ? Math.round(totalXP / users.length) : 0; - const anaTotalTopics = $("#anaTotalTopics"); - if (anaTotalTopics) { - try { - const r = await fetch('/data/topics.json'); - const topics = await r.json(); - anaTotalTopics.textContent = topics.length; - } catch(_) { anaTotalTopics.textContent = '?'; } - } - const anaTopLearner = $("#anaTopLearner"); - if (anaTopLearner) anaTopLearner.textContent = topUser.email ? topUser.email.split('@')[0] : '-'; - const anaAvgXP = $("#anaAvgXP"); - if (anaAvgXP) anaAvgXP.textContent = avgXP; - const anaCompletions = $("#anaCompletions"); - if (anaCompletions) anaCompletions.textContent = totalCompletions; - - // Registration chart (last 7 days) - const chart = $("#anaChart"); - if (chart) { - const days = []; - for (let i = 6; i >= 0; i--) { - const d = new Date(Date.now() - i * 864e5); - const label = d.toLocaleDateString('en', { weekday: 'short' }); - const dayStart = new Date(d); dayStart.setHours(0,0,0,0); - const dayEnd = new Date(d); dayEnd.setHours(23,59,59,999); - const toMs = tsMs; - const count = users.filter(u => { const c = toMs(u.created || u.createdAt); return c >= dayStart.getTime() && c <= dayEnd.getTime(); }).length; - days.push({ label, count }); - } - const max = Math.max(...days.map(d => d.count), 1); - chart.innerHTML = '
New users (last 7 days)
' + - '
' + - days.map(d => `
${d.label}
`).join('') + - '
'; - } - } catch(e) { console.error('Analytics error:', e); } - } - const anaRefresh = $("#anaRefresh"); - if (anaRefresh) anaRefresh.onclick = loadAnalytics; - - // ---- Activity log ---- - async function loadActivityLog() { - const log = $("#actLog"); - if (!log) return; - try { - const activities = []; - users.forEach(u => { - if (u.lastSeen) activities.push({ email: u.email, action: 'active', ts: u.lastSeen }); - (u.logins || []).forEach(l => activities.push({ email: u.email, action: 'login from ' + (l.device || 'unknown'), ts: l.ts })); - }); - activities.sort((a, b) => { - const ta = a.ts && a.ts.toMillis ? a.ts.toMillis() : (a.ts || 0); - const tb = b.ts && b.ts.toMillis ? b.ts.toMillis() : (b.ts || 0); - return tb - ta; - }); - log.innerHTML = activities.length - ? activities.slice(0, 15).map(a => `
${esc(a.email || '?')}
${esc(a.action)}
${fmtDate(a.ts)}
`).join('') - : '

No activity recorded.

'; - } catch(e) { log.innerHTML = '

Could not load activity log.

'; } - } - - // ---- Maintenance ---- - const clearInactive = $("#admClearInactive"); - if (clearInactive) clearInactive.onclick = async () => { - const msg = $("#maintMsg"); - const cutoff = Date.now() - 90 * 864e5; - const toMs = tsMs; - const inactive = users.filter(u => { - const last = toMs(u.lastSeen) || toMs(u.created || u.createdAt); - return last && last < cutoff && !isOwnerRow(u); - }); - if (!inactive.length) { if (msg) msg.textContent = 'No inactive users found.'; return; } - if (!(await window.dnConfirm('Remove inactive users?', 'This deletes ' + inactive.length + ' users inactive for 90+ days.', { danger: true }))) return; - let removed = 0; - for (const u of inactive) { - try { await deleteDoc(doc(db, "users", u.uid)); removed++; } catch(_) {} - } - if (msg) msg.textContent = 'Removed ' + removed + ' inactive users.'; - loadUsers(); - }; - - const exportFeedback = $("#admExportFeedback"); - if (exportFeedback) exportFeedback.onclick = async () => { - try { - const snap = await getDocs(collection(db, "feedback")); - const data = snap.docs.map(d => ({ id: d.id, ...d.data() })); - const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' }); - const url = URL.createObjectURL(blob); - const a = document.createElement('a'); a.href = url; a.download = 'feedback-export.json'; a.click(); - URL.revokeObjectURL(url); - } catch(e) { const msg = $("#maintMsg"); if (msg) msg.textContent = 'Export failed: ' + e.message; } - }; - - // ---- Feature flags ---- - const ffSave = $("#ffSave"); - if (ffSave) ffSave.onclick = async () => { - const flags = {}; - ['ffLearn','ffWebshell','ffVmlab','ffAI','ffGmail','ffGithub'].forEach(id => { - const el = $('#' + id); - if (el) flags[id.replace('ff','')] = el.checked; - }); - try { - await setDoc(doc(db, "settings", "features"), { ...flags, updatedBy: user.email, updatedAt: serverTimestamp() }, { merge: true }); - const msg = $("#ffMsg"); if (msg) msg.textContent = 'Flags saved.'; - } catch(e) { const msg = $("#ffMsg"); if (msg) msg.textContent = 'Save failed: ' + e.message; } - }; - // Load saved flags - try { - const flagDoc = await getDoc(doc(db, "settings", "features")); - if (flagDoc.exists()) { - const d = flagDoc.data(); - ['Learn','Webshell','Vmlab','AI','Gmail','Github'].forEach(f => { - const el = $('#ff' + f); - if (el && d[f] !== undefined) el.checked = d[f]; - }); - } - } catch(_) {} - - // ---- System status ---- - const sysLh = $("#sysLh"); - if (sysLh) { - try { - const r = await fetch('/data/topics.json', { method: 'HEAD' }); - sysLh.textContent = r.ok ? 'OK' : 'error'; - sysLh.style.color = r.ok ? '#3fb950' : '#f85149'; - } catch(_) { sysLh.textContent = 'unreachable'; sysLh.style.color = '#f85149'; } - } - const sysBundle = $("#sysBundle"); - if (sysBundle) { - const scripts = document.querySelectorAll('script[src]'); - sysBundle.textContent = scripts.length + ' scripts loaded'; - } - const sysDeploy = $("#sysDeploy"); - if (sysDeploy) { - try { - const r = await fetch('/js/auth.js', { method: 'HEAD' }); - const lm = r.headers.get('last-modified'); - sysDeploy.textContent = lm ? new Date(lm).toLocaleDateString() : 'unknown'; - } catch(_) { sysDeploy.textContent = 'unknown'; } - } - - // ---- Quick actions ---- - const admBackup = $("#admBackup"); - if (admBackup) admBackup.onclick = async () => { - try { - const [usersSnap, wlSnap, annSnap] = await Promise.all([ - getDocs(collection(db, "users")), - getDoc(WL_REF()), - getDoc(ANN_REF()), - ]); - const backup = { - exportedAt: new Date().toISOString(), - users: usersSnap.docs.map(d => ({ id: d.id, ...d.data() })), - whitelist: wlSnap.exists() ? wlSnap.data() : {}, - announcement: annSnap.exists() ? annSnap.data() : {}, - }; - const blob = new Blob([JSON.stringify(backup, null, 2)], { type: 'application/json' }); - const url = URL.createObjectURL(blob); - const a = document.createElement('a'); a.href = url; a.download = 'darknode-backup-' + new Date().toISOString().slice(0,10) + '.json'; a.click(); - URL.revokeObjectURL(url); - } catch(e) { window.showToast('Backup failed: ' + e.message, "error"); } - }; - - const admMsgAll = $("#admMsgAll"); - if (admMsgAll) admMsgAll.onclick = async () => { - const msg = await window.dnPrompt('Message to all users', { desc: 'Shown as an announcement.', placeholder: 'Announcement text…', textarea: true }); - if (!msg) return; - const annText = $("#annText"); - if (annText) { annText.value = msg; } - window.showToast('Announcement text set. Click Publish to send it.', "info"); - }; - - // ---- Email panel ---- - const emailTarget = $("#emailTarget"); - const emailOneRow = $("#emailOneRow"); - const emailCount = $("#emailCount"); - const emailMsg = $("#emailMsg"); - let emailMode = "one"; - - if (emailTarget) { - emailTarget.querySelectorAll("button").forEach((b) => { - b.onclick = () => { - emailTarget.querySelectorAll("button").forEach((x) => x.classList.remove("on")); - b.classList.add("on"); - emailMode = b.dataset.v; - if (emailOneRow) emailOneRow.style.display = emailMode === "one" ? "" : "none"; - if (emailCount) emailCount.textContent = emailMode === "all" ? users.filter((u) => u.email).length + " recipients" : ""; - }; - }); - } - - // Quick templates - const templates = { - downtime: { - subject: "We're sorry — Darknode was briefly down", - body: "Hi there,\n\nWe wanted to reach out and apologize for the brief downtime on darknode.ai yesterday. We know you rely on the platform and we take uptime seriously.\n\nWhat happened: A configuration change caused the site to become temporarily unavailable. We identified and resolved the issue, and the platform is now fully operational.\n\nWhat we're doing: We've added monitoring to prevent this from happening again.\n\nThank you for your patience and for being part of the Darknode community.\n\nBest,\nThe Darknode Team\ncontact@darknode.ai" - }, - update: { - subject: "What's new on Darknode", - body: "Hi there,\n\nWe've shipped some updates to Darknode:\n\n- [Feature 1]\n- [Feature 2]\n- [Bug fix]\n\nCheck it out at darknode.ai\n\nBest,\nThe Darknode Team" - }, - welcome: { - subject: "Welcome to Darknode", - body: "Welcome to Darknode!\n\nThanks for signing up. Here's what you can do:\n\n- Work across offensive security, reconnaissance, OSINT, forensics, malware analysis and blue-team operations\n- Use the Nexus AI coding agent\n- Practice in our security labs\n- Track your progress in the Learn Hub\n\nGet started at darknode.ai\n\nBest,\nThe Darknode Team\ncontact@darknode.ai" - }, - security: { - subject: "Security Notice — Darknode", - body: "Hi there,\n\nThis is a security notice from Darknode.\n\n[Describe the security event]\n\nWhat you should do:\n- [Action item 1]\n- [Action item 2]\n\nIf you have questions, reply to this email.\n\nBest,\nThe Darknode Team\ncontact@darknode.ai" - } - }; - - main.querySelectorAll(".emailTpl").forEach((b) => { - b.onclick = () => { - const tpl = templates[b.dataset.tpl]; - if (!tpl) return; - const subj = $("#emailSubject"), body = $("#emailBody"); - if (subj) subj.value = tpl.subject; - if (body) body.value = tpl.body; - if (emailMsg) emailMsg.textContent = "Template loaded: " + b.dataset.tpl; - }; - }); - - // Send via Gmail (mailto or Gmail compose URL) - const emailSend = $("#emailSend"); - if (emailSend) emailSend.onclick = () => { - const subj = ($("#emailSubject")?.value || "").trim(); - const body = ($("#emailBody")?.value || "").trim(); - if (!subj || !body) { if (emailMsg) emailMsg.textContent = "Subject and body required."; return; } - - let to; - if (emailMode === "one") { - to = ($("#emailTo")?.value || "").trim(); - if (!to) { if (emailMsg) emailMsg.textContent = "Enter a recipient email."; return; } - } else { - const emails = users.filter((u) => u.email && !isOwnerRow(u)).map((u) => u.email); - if (!emails.length) { if (emailMsg) emailMsg.textContent = "No users to email."; return; } - to = emails.join(","); - } - - const gmailUrl = "https://mail.google.com/mail/?view=cm" - + "&to=" + encodeURIComponent(to) - + "&su=" + encodeURIComponent(subj) - + "&body=" + encodeURIComponent(body) - + "&from=" + encodeURIComponent("contact@darknode.ai"); - window.open(gmailUrl, "_blank", "noopener,noreferrer"); - if (emailMsg) emailMsg.textContent = emailMode === "all" - ? "Opened Gmail with " + users.filter((u) => u.email && !isOwnerRow(u)).length + " recipients" - : "Opened Gmail draft to " + to; - }; - - // Copy as text - const emailCopy = $("#emailCopyDraft"); - if (emailCopy) emailCopy.onclick = () => { - const subj = ($("#emailSubject")?.value || "").trim(); - const body = ($("#emailBody")?.value || "").trim(); - const draft = "Subject: " + subj + "\n\n" + body; - navigator.clipboard?.writeText(draft); - if (emailMsg) emailMsg.textContent = "Draft copied to clipboard."; - }; - - // ---- Danger zone ---- - const admPurge = $("#admPurgeData"); - if (admPurge) admPurge.onclick = async () => { - const msg = $("#dangerMsg"); - if (!(await window.dnConfirm('Delete ALL user data?', 'DANGER: this permanently deletes every non-owner user record. This cannot be undone.', { danger: true, submitText: 'Continue' }))) return; - if ((await window.dnPrompt('Type DELETE to confirm', { placeholder: 'DELETE' })) !== 'DELETE') return; - let count = 0; - for (const u of users) { - if (isOwnerRow(u)) continue; - try { await deleteDoc(doc(db, "users", u.uid)); count++; } catch(_) {} - } - if (msg) msg.textContent = 'Purged ' + count + ' users.'; - loadUsers(); - }; - - const admRevoke = $("#admRevokeAll"); - if (admRevoke) admRevoke.onclick = () => { - const msg = $("#dangerMsg"); - if (msg) msg.textContent = 'Session revocation requires Firebase Admin SDK (server-side). Use the Firebase Console to revoke refresh tokens.'; - }; - - // Load analytics + activity - loadAnalytics(); - loadActivityLog(); +// An old /admin link opened as a page (not through the Deck, which routes it to /owner). +export function renderAdmin(main) { + main.innerHTML = '

The owner page has moved

It is in the Deck now, under Owner.

Open the Owner page

'; } 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 ? ` -
-
Getting started${onbDone} of ${steps.length} done
-
${steps.map((x) => ` - `).join("")}
-
` : ""; + const onbCard = onbCardHtml(steps); + if (onbCard) askOnbLive(); el.innerHTML = `

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

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

@@ -3340,9 +3382,7 @@ export function renderDeck(host, opts) { sf.querySelector("[data-tool]").onclick = () => (isLocked("tool:codescan") ? openSpaceTool("personal", "secrets") : openTool("codescan", secLabel.codescan || "Code Scanner")); } // onboarding checklist - 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(); }; + wireOnbCard(el, steps); // role-based home focus (optional; default off) setupRoleFocus(el); // pinned tools + live system status @@ -4145,6 +4185,7 @@ export function renderDeck(host, opts) { function renderInventory(){ lazyScene(sceneEls.inventory, invMod, (m) => m.mountInventory(sceneEls.inventory, { withGraph, esc, IC, IC_SEARCH, openEntityDrawer, openTool, agoISO: agoISO, toast })); } function renderCorrelations(){ lazyScene(sceneEls.correlations, corrMod, (m) => m.mountCorrelations(sceneEls.correlations, { withGraph, esc, IC, IC_SEARCH, openEntityDrawer, openTool, toast })); } function renderMonitors(){ lazyScene(sceneEls.monitors, monMod, (m) => m.mountMonitors(sceneEls.monitors, { esc, IC, toast, tier: planTier, go, noAccount, signup: toSignup })); } + function renderOwner(){ lazyScene(sceneEls.owner, ownerMod, (m) => m.mountOwner(sceneEls.owner, { toast, user, go })); } function renderDeadlines(){ lazyScene(sceneEls.deadlines, dlMod, (m) => m.mountDeadlines(sceneEls.deadlines, { toast, tier: planTier, go, noAccount, signup: toSignup })); } function renderApiKeys(){ lazyScene(sceneEls.apikeys, keysMod, (m) => m.mountApiKeys(sceneEls.apikeys, { esc, IC, toast })); } function renderAudit(){ lazyScene(sceneEls.audit, auditMod, (m) => m.mountAudit(sceneEls.audit, { esc, IC, toast })); } @@ -4571,10 +4612,10 @@ export function renderDeck(host, opts) {
${opts.isOwner ? `
-

${IC.key} Admin

+

${IC.key} Owner

-
Owner console
User management, feature flags, upgrade requests and platform settings.
- +
Owner page
Who comes back, the people list, requests waiting for you, the site banner and the ban list.
+
` : ""} `; @@ -4663,7 +4704,7 @@ export function renderDeck(host, opts) { finally { delAcct.disabled = false; } }; const admBtn = el.querySelector("#dkSetAdmin"); - if (admBtn) admBtn.onclick = () => openTool("admin", "Admin"); + if (admBtn) admBtn.onclick = () => go("owner"); fqMod().then((m) => m.renderSlaSettings(el.querySelector(".dk-setgrid"), fqCtx()), () => {}); } diff --git a/public/js/deck/launch.js b/public/js/deck/launch.js index 7d19aa2c..ed4949ab 100644 --- a/public/js/deck/launch.js +++ b/public/js/deck/launch.js @@ -1,13 +1,32 @@ // Copyright (c) 2026 Darknode-Official. All rights reserved. // Deck launcher: loads the signed-in user's workspace profile, plan and notifications, // then mounts the Deck. Shared by the web home (every signed-in user), the desktop app -// and the owner's Admin page. +// and the owner's account. import { db } from "/js/firebase.js?v=20261021a"; import { collection, getDocs, doc, getDoc, setDoc, serverTimestamp, - addDoc, query, orderBy, updateDoc, limit, + addDoc, query, orderBy, updateDoc, limit, increment, } from "https://www.gstatic.com/firebasejs/12.17.0/firebase-firestore.js"; +// Days the Deck was used (core/active-days.js): written when it opens and again when a tab +// left open is brought back on a later day. At most one small write per day. +let _days = null, _daysHooked = false; +async function trackDays(uid, recent) { + const { markDay, dayOf } = await import("/js/core/active-days.js?v=1"); + const mark = () => { + const { days, changed } = markDay(_days.recent); + if (!changed) return; + _days.recent = days; + setDoc(doc(db, "users", _days.uid), { recentDays: days, activeDays: increment(1), lastActiveDay: dayOf(Date.now()) }, { merge: true }).catch(() => {}); + }; + _days = { uid, recent: _days && _days.uid === uid ? _days.recent : recent }; + mark(); + if (!_daysHooked) { + _daysHooked = true; + document.addEventListener("visibilitychange", () => { if (document.visibilityState === "visible" && _days) mark(); }); + } +} + let _deckOff = null; // teardown of the mounted Deck, so relaunching never stacks two // Mount the Deck for a signed-in user. `extra` adds renderDeck options: isOwner (from the // admin custom claim; Security Rules enforce it server-side) unlocks the owner-only @@ -28,6 +47,8 @@ export async function openDeck(user, extra = {}) { wsProfile = { name: d.workspaceName || "", logo: d.workspaceLogo || "", accent: d.workspaceAccent || "" }; deckTier = d.tier || ""; onboarding = d.onboarding || {}; + // Record today (once a day) so the owner page can tell who came back from who came once. + if (snap.exists()) trackDays(user.uid, d.recentDays); } catch (_) {} })(); // Plan sharing: when the remembered active workspace is a team whose owner shares their @@ -90,4 +111,4 @@ export async function openDeck(user, extra = {}) { }); return _deckOff; } -export function closeDeck() { if (_deckOff) { try { _deckOff(); } catch (_) {} _deckOff = null; } } +export function closeDeck() { _days = null; if (_deckOff) { try { _deckOff(); } catch (_) {} _deckOff = null; } } diff --git a/public/js/deck/owner-stats.js b/public/js/deck/owner-stats.js new file mode 100644 index 00000000..d5485102 --- /dev/null +++ b/public/js/deck/owner-stats.js @@ -0,0 +1,102 @@ +// Copyright (c) 2026 Darknode-Official. All rights reserved. See LICENSE. +// Owner page numbers: who signed up, who came back and who is still here. PURE (no imports), +// so the node tests run it as is; deck/owner.js draws the result. +// +// Inputs are the users/{uid} docs (plus Auth-only rows from /api/admin/users for sign-ups that +// never verified). A person "came back" when they used Darknode on two or more days: counted +// from recentDays/activeDays (core/active-days.js) and, for accounts older than that tracking, +// from a lastSeen at least a day after they joined. + +const DAY = 864e5; + +// Firestore Timestamp, epoch seconds or ms, or a date string -> ms (0 when unknown) +export 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; + +export const isOwnerRow = (u) => !!u && (u.admin === true || u.role === "owner"); + +// One account -> { joined, last, days, returned, active7, verified, opened } +export function personOf(u = {}, now = Date.now()) { + const joined = tsMs(u.createdAt || u.created); + const recent = Array.isArray(u.recentDays) ? u.recentDays : []; + const lastDay = recent.length ? Date.parse(recent[recent.length - 1] + "T00:00:00Z") || 0 : 0; + const last = Math.max(tsMs(u.lastSeen), tsMs(u.lastLoginAt), lastDay, joined); // at least the sign-up itself + let days = Math.max(Number(u.activeDays) || 0, recent.length); + if (days < 2 && joined && last - joined >= DAY) days = 2; // came back before day tracking existed + if (!days && (last || joined)) days = 1; + return { + joined, last, days, + returned: days >= 2, + active7: !!last && now - last < 7 * DAY, + verified: u.emailVerified !== false, + opened: !u.authOnly, // has a profile: got past sign-up into the app + }; +} + +// Monday 00:00 UTC of the week holding ms +export function weekStart(ms) { + const d = new Date(ms); d.setUTCHours(0, 0, 0, 0); + return d.getTime() - ((d.getUTCDay() + 6) % 7) * DAY; +} + +// users -> { total, new7, funnel: [{ label, n }], returned, active7, active1, cohorts: [{ start, signups, returned, active7 }] } +// The owner's own account is left out of every number. +export function retention(users = [], now = Date.now(), weeks = 8) { + const people = users.filter((u) => u && !isOwnerRow(u)).map((u) => personOf(u, now)); + const n = (f) => people.filter(f).length; + const total = people.length; + const from = weekStart(now) - (weeks - 1) * 7 * DAY; + const cohorts = []; + for (let s = weekStart(now); s >= from; s -= 7 * DAY) { + const c = people.filter((p) => p.joined >= s && p.joined < s + 7 * DAY); + cohorts.push({ start: s, signups: c.length, returned: c.filter((p) => p.returned).length, active7: c.filter((p) => p.active7).length }); + } + return { + total, + new7: n((p) => p.joined && now - p.joined < 7 * DAY), + returned: n((p) => p.returned), + active7: n((p) => p.active7), + active1: n((p) => p.last && now - p.last < DAY), + funnel: [ + { label: "Signed up", n: total }, + { label: "Verified email", n: n((p) => p.verified) }, + { label: "Opened the Deck", n: n((p) => p.verified && p.opened) }, + { label: "Came back another day", n: n((p) => p.returned) }, + { label: "Used it this week", n: n((p) => p.returned && p.active7) }, + ], + cohorts, + }; +} + +export const FILTERS = [ + ["all", "Everyone"], + ["active", "Active this week"], + ["once", "Came once"], + ["unverified", "Unverified"], + ["banned", "Banned"], +]; + +// The users table: filter + search, most recently seen first. banned: lower-cased emails. +export function peopleRows(users = [], { filter = "all", q = "", banned = [], now = Date.now() } = {}) { + const ban = new Set(banned); + const s = String(q || "").toLowerCase().trim(); + return users + .map((u) => ({ u, p: personOf(u, now), owner: isOwnerRow(u), banned: ban.has(String(u.email || "").toLowerCase()) })) + .filter((r) => !s || ((r.u.email || "") + " " + (r.u.name || "")).toLowerCase().includes(s)) + .filter((r) => filter === "all" || (filter === "active" ? r.p.active7 + : filter === "once" ? !r.owner && !r.p.returned + : filter === "unverified" ? !r.p.verified + : filter === "banned" ? r.banned : true)) + .sort((a, b) => b.p.last - a.p.last || String(a.u.email || "").localeCompare(String(b.u.email || ""))); +} + +// "3 h ago", "5 d ago", a date after a month; "never" for 0 +export function ago(ms, now = Date.now()) { + if (!ms) return "never"; + const s = Math.max(0, Math.round((now - ms) / 1000)); + if (s < 90) return "just now"; + if (s < 3600) return Math.round(s / 60) + " min ago"; + if (s < 86400) return Math.round(s / 3600) + " h ago"; + if (s < 30 * 86400) return Math.round(s / 86400) + " d ago"; + return new Date(ms).toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" }); +} diff --git a/public/js/deck/owner.js b/public/js/deck/owner.js new file mode 100644 index 00000000..8404b8fa --- /dev/null +++ b/public/js/deck/owner.js @@ -0,0 +1,403 @@ +// Copyright (c) 2026 Darknode-Official. All rights reserved. See LICENSE. +// Owner page (Deck scene "owner", owner only): are people coming back? Retention first (the +// numbers come from deck/owner-stats.js), then the people themselves, then what is waiting +// for an answer (upgrade and deletion requests, feedback, client errors), then the site-wide +// controls (announcement banner, ban list). Replaces the old console Admin page. +// +// Reads users/, usage/, upgradeRequests/, feedback/, errors/ and the settings docs directly +// (the rules let only the owner read them) and the Auth-only accounts and deletion requests +// through the Worker's owner-only /api/admin routes. +import { db } from "/js/firebase.js?v=20261021a"; +import { + collection, getDocs, doc, getDoc, setDoc, deleteDoc, addDoc, updateDoc, query, orderBy, serverTimestamp, +} from "https://www.gstatic.com/firebasejs/12.17.0/firebase-firestore.js"; +import { retention, peopleRows, tsMs, isOwnerRow, ago, FILTERS } from "./owner-stats.js?v=1"; + +const S = { el: null, ctx: null, seq: 0, users: [], usage: new Map(), banned: [], filter: "all", q: "", open: "", inbox: null, ann: null }; +const E = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); +const toast = (m, t) => { try { S.ctx && S.ctx.toast ? S.ctx.toast(m, t) : window.showToast && window.showToast(m, t); } catch (_) {} }; +const confirmIt = (title, body, o) => (window.dnConfirm ? window.dnConfirm(title, body, o) : Promise.resolve(false)); +const api = async (path, o) => (await import("/js/core/api.js")).api(path, o); +const pct = (n, d) => (d ? Math.round((n / d) * 100) : 0); +const when = (ms) => (ms ? new Date(ms).toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" }) : "-"); +const PLAN = { free: "Free", pro: "Pro", team: "Team", enterprise: "Enterprise" }; +const PRESETS = { + maint: ["Maintenance", "Scheduled maintenance is underway. Some features may be briefly unavailable."], + release: ["New release", "A new release is live. Update the desktop app and Nexus from Downloads to get the latest fixes."], + security: ["Security notice", "Security notice: review your recent sign-ins and rotate any credentials you have stored."], +}; + +function injectStyle() { + if (document.getElementById("own-css")) return; + const st = document.createElement("style"); st.id = "own-css"; + st.textContent = ` +.own-sub{color:#5a6680;font-size:12.5px;margin:-2px 0 0;line-height:1.5} +#ownKpis .own-kpis{grid-template-columns:repeat(5,minmax(0,1fr));margin:0 0 14px} +.own-kpi em{font-style:normal;font-size:.8rem;font-weight:600;opacity:.7;margin-left:6px} +.own-grid{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:14px;margin:0 0 14px;align-items:start} +.own-panel{border:1px solid rgba(23,33,56,.12);border-radius:10px;background:#fff;padding:14px 16px;min-width:0} +.own-panel h2{margin:0 0 4px;font-size:14px;font-weight:650;color:#141c2e;display:flex;align-items:center;gap:8px;flex-wrap:wrap} +.own-panel h2 .n{font-size:11px;font-weight:700;border-radius:20px;padding:1px 8px;background:rgba(23,33,56,.07);color:#45506a} +.own-panel h2 .n.hot{background:rgba(198,40,40,.1);color:#c62828} +.own-note{font-size:12px;color:#5a6680;margin:0 0 10px;line-height:1.5} +.own-fun{display:grid;grid-template-columns:150px minmax(0,1fr) 72px;gap:6px 10px;align-items:center;font-size:12.5px;color:#2a3450} +.own-bar{height:10px;border-radius:5px;background:rgba(23,33,56,.06);overflow:hidden} +.own-bar i{display:block;height:100%;background:var(--dk-acc,#2552c6);border-radius:5px} +.own-fun .v{text-align:right;font-variant-numeric:tabular-nums;color:#141c2e;font-weight:600} +.own-fun .v small{color:#5a6680;font-weight:500} +.own-tbl{width:100%;border-collapse:collapse;font-size:12.5px;font-variant-numeric:tabular-nums} +.own-tbl th{text-align:left;font-weight:600;color:#5a6680;padding:5px 6px;border-bottom:1px solid rgba(23,33,56,.1)} +.own-tbl td{padding:6px;border-bottom:1px solid rgba(23,33,56,.06);color:#141c2e} +.own-tbl tr.z td{color:#9aa3b5} +.own-tbl td+td,.own-tbl th+th{text-align:right} +.own-bar2{display:flex;gap:6px;flex-wrap:wrap;align-items:center;margin:0 0 10px} +.own-chip{appearance:none;border:1px solid rgba(23,33,56,.16);background:#fff;border-radius:20px;font:inherit;font-size:12px;font-weight:600;color:#2a3450;padding:3px 11px;cursor:pointer} +.own-chip.on{background:#141c2e;border-color:#141c2e;color:#fff} +.own-chip small{font-weight:500;opacity:.75;margin-left:3px} +.own-in{font:inherit;font-size:13px;border:1px solid rgba(23,33,56,.18);border-radius:7px;padding:6px 9px;box-sizing:border-box;background:#fff;min-width:0} +.own-bar2 .own-in{flex:1 1 200px;max-width:320px;margin-left:auto} +.own-btn{appearance:none;border:1px solid rgba(23,33,56,.16);background:#fff;border-radius:7px;font:inherit;font-size:12px;font-weight:600;color:#2a3450;padding:4px 10px;cursor:pointer;white-space:nowrap} +.own-btn:hover{border-color:var(--dk-acc,#2552c6);color:var(--dk-acc,#2552c6)} +.own-btn.pri{background:var(--dk-acc,#2552c6);border-color:var(--dk-acc,#2552c6);color:#fff} +.own-btn.bad{color:#c62828;border-color:rgba(198,40,40,.35)} +.own-btn:disabled{opacity:.55;cursor:default} +.own-ppl{border:1px solid rgba(23,33,56,.1);border-radius:8px;overflow:hidden} +.own-p{display:grid;grid-template-columns:minmax(0,2.4fr) repeat(4,minmax(0,1fr)) minmax(0,1.3fr);gap:4px 10px;align-items:center;padding:8px 12px;font-size:12.5px;color:#141c2e;cursor:pointer} +.own-p+.own-p,.own-p+.own-d,.own-d+.own-p{border-top:1px solid rgba(23,33,56,.07)} +.own-p:hover{background:rgba(23,33,56,.025)} +.own-p.hd{cursor:default;background:rgba(23,33,56,.03);font-size:11.5px;font-weight:600;color:#5a6680} +.own-p .who{min-width:0} +.own-p .who b{display:block;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.own-p .who>span{display:block;font-size:11.5px;color:#5a6680;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.own-p [data-l]::before{content:none} +.own-tag{display:inline-block;font-size:10.5px;font-weight:700;border-radius:20px;padding:0 7px;margin-left:5px;background:rgba(23,33,56,.07);color:#45506a;vertical-align:1px} +.own-tag.bad{background:rgba(198,40,40,.1);color:#c62828} +.own-tag.ok{background:rgba(18,168,95,.1);color:#0e7a46} +.own-d{padding:10px 12px 12px;background:rgba(23,33,56,.02);font-size:12.5px;color:#2a3450} +.own-kv{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:6px 16px;margin:0 0 10px} +.own-kv div span{display:block;font-size:11px;color:#5a6680} +.own-kv div b{font-weight:600;overflow-wrap:anywhere} +.own-days{display:flex;gap:2px;flex-wrap:wrap;margin:2px 0 10px} +.own-days i{width:9px;height:9px;border-radius:2px;background:rgba(23,33,56,.08)} +.own-days i.on{background:var(--dk-acc,#2552c6)} +.own-item{border-top:1px solid rgba(23,33,56,.07);padding:8px 0;font-size:12.5px;color:#141c2e} +.own-item:first-of-type{border-top:0} +.own-item .h{display:flex;gap:8px;align-items:center;flex-wrap:wrap} +.own-item .h .m{color:#5a6680;font-size:11.5px} +.own-item .h .sp{flex:1} +.own-item .msg{margin:4px 0 0;white-space:pre-wrap;overflow-wrap:anywhere;color:#2a3450} +.own-item pre{font-size:11px;white-space:pre-wrap;word-break:break-all;color:#5a6680;margin:4px 0 0} +.own-empty{font-size:12.5px;color:#5a6680;margin:2px 0} +.own-err{font-size:12.5px;color:#c62828;margin:2px 0} +.own-ann textarea{width:100%;min-height:62px;resize:vertical} +.own-row{display:flex;gap:6px;flex-wrap:wrap;align-items:center;margin:8px 0 0} +.own-bans{display:flex;gap:6px;flex-wrap:wrap;margin:8px 0 0} +.own-bans span{font-size:12px;border:1px solid rgba(23,33,56,.14);border-radius:20px;padding:2px 4px 2px 10px;display:inline-flex;gap:4px;align-items:center} +.own-bans button{appearance:none;border:0;background:none;cursor:pointer;color:#5a6680;font:inherit;font-size:12px;padding:0 6px} +@media (max-width:900px){#ownKpis .own-kpis{grid-template-columns:repeat(3,minmax(0,1fr))}.own-grid{grid-template-columns:minmax(0,1fr)}} +@media (max-width:720px){ + #ownKpis .own-kpis{grid-template-columns:repeat(2,minmax(0,1fr))} + .own-fun{grid-template-columns:110px minmax(0,1fr) 64px} + .own-p{grid-template-columns:minmax(0,1fr) minmax(0,1fr)} + .own-p .who{grid-column:1/-1} + .own-p.hd{display:none} + .own-p [data-l]::before{content:attr(data-l) " ";color:#5a6680;font-size:11px} + .own-bar2 .own-in{max-width:none;margin-left:0} +}`; + document.head.appendChild(st); +} + +// ctx: { toast, user, go } +export function mountOwner(el, ctx) { + injectStyle(); + S.el = el; S.ctx = ctx || S.ctx; S.open = ""; + el.innerHTML = ` +

Owner

Who signs up, who comes back and what is waiting for your answer. Your own account is left out of the numbers.

+
+
+
Loading…
+
+
+
+
`; + el.querySelector("#ownReload").onclick = () => load(); + if (!el._ownWired) { el._ownWired = true; el.addEventListener("click", onClick); el.addEventListener("input", onInput); } + load(); +} + +async function load() { + const my = ++S.seq; + const live = () => my === S.seq && S.el && S.el.isConnected; + const [users, usage, banned, ann] = await Promise.all([loadUsers(), loadUsage(), loadBanned(), loadAnn()]); + if (!live()) return; + S.users = users; S.usage = usage; S.banned = banned; S.ann = ann; + paintTop(); paintPeople(); paintSite(); + const inbox = await loadInbox(); + if (!live()) return; + S.inbox = inbox; paintInbox(); +} + +// users/{uid} docs plus the Auth accounts that never got one (an email sign-up that never verified) +async function loadUsers() { + let users = []; + try { users = (await getDocs(collection(db, "users"))).docs.map((d) => ({ uid: d.id, ...d.data() })); } + catch (e) { S.loadErr = e.message || String(e); return []; } + S.loadErr = ""; + try { + 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; if (!u.lastLoginAt) u.lastLoginAt = a.lastLoginAt; if (!u.createdAt) u.createdAt = a.createdAt; continue; } + users.push({ uid: a.uid, email: a.email, name: a.name, provider: (a.providers || []).join(", ") || "email", createdAt: a.createdAt, lastLoginAt: a.lastLoginAt, emailVerified: a.emailVerified, disabled: a.disabled, authOnly: true }); + } + } catch (_) { /* Worker unreachable: the Firestore list still shows */ } + return users; +} +async function loadUsage() { + try { return new Map((await getDocs(collection(db, "usage"))).docs.map((d) => [d.id, d.data()])); } catch (_) { return new Map(); } +} +async function loadBanned() { + try { const s = await getDoc(doc(db, "settings", "whitelist")); return ((s.exists() && s.data().banned) || []).map((x) => String(x).toLowerCase()); } catch (_) { return []; } +} +async function loadAnn() { + try { const s = await getDoc(doc(db, "announcements", "current")); return s.exists() ? s.data() : {}; } catch (_) { return {}; } +} +async function loadInbox() { + const out = { upgrades: null, deletions: null, feedback: null, errors: null, fail: {} }; + const byTs = (a, b) => tsMs(b.ts) - tsMs(a.ts); + await Promise.all([ + getDocs(query(collection(db, "upgradeRequests"), orderBy("ts", "desc"))).then((s) => { out.upgrades = s.docs.map((d) => ({ id: d.id, ...d.data() })); }, (e) => { out.fail.upgrades = e.message; }), + api("/api/admin/deletions").then((r) => { out.deletions = (r && r.requests) || []; }, (e) => { out.fail.deletions = e.message; }), + getDocs(collection(db, "feedback")).then((s) => { out.feedback = s.docs.map((d) => ({ id: d.id, ...d.data() })).sort(byTs); }, (e) => { out.fail.feedback = e.message; }), + getDocs(collection(db, "errors")).then((s) => { out.errors = s.docs.map((d) => ({ id: d.id, ...d.data() })).sort(byTs); }, (e) => { out.fail.errors = e.message; }), + ]); + return out; +} + +function paintTop() { + const box = (id) => S.el.querySelector(id); + if (S.loadErr) { box("#ownKpis").innerHTML = `

Couldn't read the user list: ${E(S.loadErr)}

`; box("#ownFunnel").innerHTML = ""; box("#ownCohorts").innerHTML = ""; return; } + const r = retention(S.users); + const kpi = (n, label, extra) => `
${n}${extra ? `${extra}` : ""}${label}
`; + box("#ownKpis").innerHTML = `
+ ${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.

+
${r.funnel.map((f) => `${E(f.label)}${f.n} ${top ? pct(f.n, top) + "%" : ""}`).join("")}
`; + const rows = r.cohorts.map((c) => `${E(new Date(c.start).toLocaleDateString(undefined, { day: "numeric", month: "short" }))}${c.signups}${c.signups ? `${c.returned} (${pct(c.returned, c.signups)}%)` : "-"}${c.signups ? c.active7 : "-"}`).join(""); + box("#ownCohorts").innerHTML = `

By week they joined

+

Each row is the people who signed up that week (weeks start Monday, UTC) and how many of them stayed.

+ ${rows}
Week ofSigned upCame backActive now
`; +} + +function usageOf(uid) { + const d = S.usage.get(uid) || {}; + return [["nexus", "Nexus"], ["app", "App"], ["vm", "VMs"]].filter(([k]) => d[k] && tsMs(d[k].last)).map(([k, l]) => ({ label: l, last: tsMs(d[k].last), version: d[k].version || "" })); +} + +function paintPeople() { + const host = S.el.querySelector("#ownPeople"); if (!host) return; + if (S.loadErr) { host.innerHTML = ""; return; } + const now = Date.now(); + const count = (f) => peopleRows(S.users, { filter: f, banned: S.banned, now }).length; + const rows = peopleRows(S.users, { filter: S.filter, q: S.q, banned: S.banned, now }); + const chips = FILTERS.map(([id, label]) => ``).join(""); + const list = rows.map(({ u, p, owner, banned }) => { + const uses = usageOf(u.uid); + const tags = (owner ? 'You' : "") + (banned ? 'Banned' : "") + + (!p.verified ? 'Unverified' : "") + (u.disabled ? 'Disabled' : ""); + const open = S.open === u.uid; + return `
+
${E(u.email || u.uid)}${tags}${E(u.name || (u.authOnly ? "Signed up, never opened the Deck" : ""))}
+
${E(when(p.joined))}
+
${E(ago(p.last, now))}
+
${p.days}
+
${E(owner ? "Owner" : PLAN[u.tier] || "Free")}
+
${uses.length ? E(uses.map((x) => x.label).join(", ")) : "-"}
+
${open ? detailHtml(u, p, owner, banned, uses, now) : ""}`; + }).join(""); + host.innerHTML = `

People ${S.users.length}

+

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.

+
${chips}
+
Person
Joined
Last seen
Days used
Plan
Also uses
+ ${list || `
No one matches.
`}
`; +} + +function detailHtml(u, p, owner, banned, uses, now) { + const days = new Set(Array.isArray(u.recentDays) ? u.recentDays : []); + const strip = Array.from({ length: 60 }, (_, i) => { const d = new Date(now - (59 - i) * 864e5).toISOString().slice(0, 10); return ``; }).join(""); + const kv = (k, v) => `
${E(k)}${E(v)}
`; + return `
+
+ ${kv("Account id", u.uid)}${kv("Sign-in", u.provider || "email")}${kv("Joined", p.joined ? new Date(p.joined).toLocaleString() : "-")} + ${kv("Last seen", p.last ? new Date(p.last).toLocaleString() : "-")}${kv("Days used", p.days + (u.activeDays ? "" : " (estimated)"))} + ${kv("Email verified", p.verified ? "Yes" : "No")}${kv("Terms accepted", u.tosAccepted ? "Yes" + (u.tosVersion ? ", " + u.tosVersion : "") : "No")} + ${uses.map((x) => kv(x.label, ago(x.last, now) + (x.version ? " (" + x.version + ")" : ""))).join("")} +
+
Days the Deck was opened, last 60 days${days.size ? "" : ": none recorded yet"}
+
${strip}
+ ${owner ? "" : `
+ ${u.email ? `` : ""}
`} +
`; +} + +function itemsHtml(list, fail, empty, row) { + if (fail) return `

Couldn't load: ${E(fail)}

`; + if (!list) return `

Loading…

`; + if (!list.length) return `

${E(empty)}

`; + return list.map(row).join(""); +} + +function paintInbox() { + const host = S.el.querySelector("#ownInbox"); if (!host) return; + const ib = S.inbox || { fail: {} }; + const ups = ib.upgrades ? ib.upgrades.filter((r) => r.status === "pending") : null; + const errs = ib.errors ? ib.errors.slice(0, 20) : null; + const n = (list, hot) => `${list ? list.length : "…"}`; + host.innerHTML = `

Waiting for you

+

Answer these first: each one is a person asking for something.

+

Plan requests ${n(ups, true)}

+ ${itemsHtml(ups, ib.fail.upgrades, "No open requests.", (r) => `
+
${E(PLAN[r.tier] || r.tier || "-")}${E(r.email || r.uid || "")} · ${E(ago(tsMs(r.ts)))} +
+ ${r.note ? `
${E(r.note)}
` : ""}
`)} +

Account deletion requests ${n(ib.deletions, true)}

+ ${itemsHtml(ib.deletions, ib.fail.deletions, "None.", (x) => `
+
${E(x.email || x.uid)}asked ${E(ago(tsMs(x.requestedAt)))}
`)} +

Feedback ${n(ib.feedback)}

+ ${itemsHtml(ib.feedback, ib.fail.feedback, "No feedback yet.", (f) => `
+
${E(String(f.type || "note").replace(/^./, (c) => c.toUpperCase()))}${E(f.email || "anonymous")} · ${E(ago(tsMs(f.ts)))}
+
${E(f.message || "")}
${f.url ? `
${E(f.url)}
` : ""}
`)} +

Errors people hit ${n(ib.errors)}${ib.errors && ib.errors.length ? '' : ""}

+ ${itemsHtml(errs, ib.fail.errors, "No errors logged.", (x) => `
+
${E(x.message || "")}
+
${E(x.email || "anonymous")} · ${E(ago(tsMs(x.ts)))}${x.url ? " · " + E(x.url) : ""}
+ ${x.stack ? `
Stack trace
${E(x.stack)}
` : ""}
`)} + ${ib.errors && ib.errors.length > 20 ? `

Showing the newest 20 of ${ib.errors.length}.

` : ""}`; +} + +function paintSite() { + const host = S.el.querySelector("#ownSite"); if (!host) return; + const a = S.ann || {}; + host.innerHTML = `

Site banner ${a.active ? "Showing" : "Off"}

+

A one-line notice at the top of the site for everyone, for maintenance or a release.

+
+
${Object.entries(PRESETS).map(([k, [l]]) => ``).join("")} +
+
${a.active ? '' : ""}
+

Banned ${S.banned.length}

+

These email addresses cannot sign in. Everyone else can.

+
+
${S.banned.length ? S.banned.map((e) => `${E(e)}`).join("") : '

No one is banned.

'}
`; +} + +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.
  • diff --git a/public/js/legal.js b/public/js/legal.js index 019d3fe8..0bd8e4aa 100644 --- a/public/js/legal.js +++ b/public/js/legal.js @@ -73,7 +73,7 @@ export const TOS_HTML = `

    14. Data & Privacy

    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.

      `; + $("#stUsers").textContent = "—"; + } + } + function drawUsers() { + const q = ($("#uSearch").value || "").toLowerCase().trim(); + const rows = users + .filter((u) => !q || (u.email + " " + (u.name || "") + " " + (u.provider || "")).toLowerCase().includes(q)) + .sort((a, b) => (a.email || "").localeCompare(b.email || "")); + const host = $("#uList"); + if (!rows.length) { host.innerHTML = `

      No matching users.

      `; return; } + host.innerHTML = rows.map((u) => { + const isOwner = isOwnerRow(u); + const banned = (wl.banned || []).includes((u.email || "").toLowerCase()); + const prov = u.provider || "email"; + const provBadge = prov.includes("google") ? 'Google' + : prov.includes("github") ? 'GitHub' + : ''; + const pic = safeAvatar(u.photoURL); + const avatar = pic + ? `` + : `${esc((u.email || "?")[0].toUpperCase())}`; + return `
      + ${avatar} +
      +
      ${esc(u.name || "(no name)")} ${provBadge}${isOwner ? 'OWNER' : ""}${banned ? 'banned' : ""}${u.emailVerified === false ? 'email not verified' : ""}${u.authOnly ? 'no profile yet' : ""}${u.disabled ? 'disabled' : ""}
      +
      ${esc(u.email || u.uid)}
      +
      last seen ${esc(fmtDate(u.lastSeen))}${u.createdAt ? " · joined " + esc(fmtDate(u.createdAt)) : ""}
      +
      +
      + + ${isOwner ? "" : ``} + ${isOwner ? "" : ``} +
      +
      + `; + }).join(""); + } + $("#uRefresh").onclick = loadUsers; + + // ---- feedback / bug reports ---- + async function loadFeedback() { + const host = $("#fbAdminList"); if (!host) return; + try { + const snap = await getDocs(collection(db, "feedback")); + const toMs = (ts) => (ts && ts.toMillis ? ts.toMillis() : 0); + const items = snap.docs.map((d) => ({ id: d.id, ...d.data() })).sort((a, b) => toMs(b.ts) - toMs(a.ts)); + if (!items.length) { host.innerHTML = `

      No feedback yet.

      `; return; } + host.innerHTML = items.map((f) => ` +
      +
      ${esc((f.type || "note").toUpperCase())} ${esc(f.email || "anon")}${f.ts && f.ts.toDate ? esc(fmtDate(f.ts)) : ""}
      +
      ${esc(f.message || "")}
      + ${f.url ? `
      ${esc(f.url)}
      ` : ""} +
      `).join(""); + } catch (e) { host.innerHTML = `

      Couldn't load feedback: ${esc(e.message)}. Ensure Firestore rules allow the owner to read the 'feedback' collection.

      `; } + } + $("#fbRefresh").onclick = loadFeedback; + $("#fbAdminList").onclick = async (e) => { + const del = e.target.closest(".fb-del"); if (!del) return; + const row = del.closest(".fb-row"); if (!row) return; + if (!(await window.dnConfirm("Delete feedback?", "This permanently removes this feedback entry.", { danger: true }))) return; + try { await deleteDoc(doc(db, "feedback", row.dataset.id)); row.remove(); } catch (err) { window.showToast("Delete failed: " + err.message, "error"); } + }; + loadFeedback(); + + // ---- plan upgrade requests ---- + async function loadUpgradeRequests() { + const host = $("#upReqList"); if (!host) return; + try { + const snap = await getDocs(query(collection(db, "upgradeRequests"), orderBy("ts", "desc"))); + const items = snap.docs.map((d) => ({ id: d.id, ...d.data() })); + const pending = items.filter((r) => r.status === "pending"); + if (!items.length) { host.innerHTML = `

      No upgrade requests yet.

      `; return; } + host.innerHTML = items.map((r) => ` +
      +
      ${esc((r.tier || "—").toUpperCase())} ${esc(r.email || r.uid || "user")} + ${r.status === "pending" ? "pending" : esc(r.status || "")} + ${r.ts && r.ts.toDate ? esc(fmtDate(r.ts)) : ""} + ${r.status === "pending" ? `` : ``}
      + ${r.note ? `
      ${esc(r.note)}
      ` : ""} +
      `).join(""); + $("#upReqList").dataset.pending = String(pending.length); + } catch (e) { host.innerHTML = `

      Couldn't load upgrade requests: ${esc(e.message)}. Ensure the 'upgradeRequests' rules are deployed.

      `; } + } + $("#upReqRefresh").onclick = loadUpgradeRequests; + $("#upReqList").onclick = async (e) => { + const row = e.target.closest(".fb-row"); if (!row) return; + const rid = row.dataset.id, uid = row.dataset.uid, tier = row.dataset.tier; + if (e.target.closest(".upr-grant")) { + if (!uid || !tier) { window.showToast("Request is missing a user or tier.", "error"); return; } + if (!(await window.dnConfirm("Grant " + tier + "?", "This sets this user's plan tier to '" + tier + "'. They get the tier's features immediately.", { submitText: "Grant" }))) return; + try { + await setDoc(doc(db, "users", uid), { tier, tierGrantedAt: serverTimestamp() }, { merge: true }); + // Durable notification so the user learns of the upgrade on any device (A6). + try { + await addDoc(collection(db, "users", uid, "notifications"), { + text: "Your plan was upgraded to " + (tier.charAt(0).toUpperCase() + tier.slice(1)) + ".", + kind: "plan", ts: Date.now(), read: false, + }); + } catch (_) {} + await updateDoc(doc(db, "upgradeRequests", rid), { status: "granted", grantedAt: serverTimestamp() }); + window.showToast("Granted " + tier, "success"); loadUpgradeRequests(); + } catch (err) { window.showToast("Grant failed: " + err.message, "error"); } + return; + } + if (e.target.closest(".upr-dismiss")) { + try { await updateDoc(doc(db, "upgradeRequests", rid), { status: "dismissed" }); loadUpgradeRequests(); } + catch (err) { window.showToast("Dismiss failed: " + err.message, "error"); } + return; + } + if (e.target.closest(".upr-del")) { + if (!(await window.dnConfirm("Delete request?", "This permanently removes this request.", { danger: true }))) return; + try { await deleteDoc(doc(db, "upgradeRequests", rid)); row.remove(); } + catch (err) { window.showToast("Delete failed: " + err.message, "error"); } + } + }; + loadUpgradeRequests(); + + // ---- account deletion requests (Worker /api/admin/deletions, service account) ---- + async function loadDeletionRequests() { + const host = $("#delReqList"); if (!host) return; + try { + const { api } = await import("/js/core/api.js"); + const r = await api("/api/admin/deletions"); + const items = (r && r.requests) || []; + if (!items.length) { host.innerHTML = `

      No pending deletion requests.

      `; return; } + host.innerHTML = items.map((x) => ` +
      +
      ${esc(x.email || x.uid)} + ${x.requestedAt ? esc(new Date(x.requestedAt).toLocaleString()) : ""} +
      +
      `).join(""); + } catch (e) { host.innerHTML = `

      Couldn't load deletion requests: ${esc(e.message)}

      `; } + } + $("#delReqRefresh").onclick = loadDeletionRequests; + $("#delReqList").onclick = async (e) => { + const btn = e.target.closest(".dr-del"); if (!btn) return; + const row = btn.closest(".fb-row"), uid = row.dataset.uid, who = row.dataset.email || uid; + if (!(await window.dnConfirm("Delete " + who + "?", "This permanently deletes the account and everything stored with it, as the user asked. It cannot be undone.", { submitText: "Delete account", danger: true }))) return; + btn.disabled = true; + try { + const { api } = await import("/js/core/api.js"); + await api("/api/admin/deletions", { method: "POST", body: { uid } }); + window.showToast("Deleted " + who, "success"); row.remove(); + } catch (err) { btn.disabled = false; window.showToast(err.message || "Delete failed", "error"); } + }; + loadDeletionRequests(); + + // ---- client error log ---- + async function loadErrors() { + const host = $("#errAdminList"); if (!host) return; + try { + const snap = await getDocs(collection(db, "errors")); + const toMs = (ts) => (ts && ts.toMillis ? ts.toMillis() : 0); + const items = snap.docs.map((d) => ({ id: d.id, ...d.data() })).sort((a, b) => toMs(b.ts) - toMs(a.ts)); + if (!items.length) { host.innerHTML = `

      No errors logged.

      `; return; } + host.innerHTML = items.slice(0, 50).map((e) => ` +
      +
      + ERROR + ${esc(e.email || "anon")} + + ${e.ts && e.ts.toDate ? esc(fmtDate(e.ts)) : ""} + +
      +
      ${esc(e.message || "")}
      + ${e.source && e.source !== "unhandledrejection" ? `
      ${esc(e.source)}${e.line ? ':' + e.line : ''}${e.col ? ':' + e.col : ''}
      ` : ""} + ${e.stack ? `
      Stack trace
      ${esc(e.stack)}
      ` : ""} + ${e.url ? `
      ${esc(e.url)}
      ` : ""} + ${e.ua ? `
      ${esc(e.ua)}
      ` : ""} +
      `).join("") + (items.length > 50 ? `

      Showing 50 of ${items.length} errors

      ` : ""); + } catch (e) { host.innerHTML = `

      Couldn't load errors: ${esc(e.message)}

      `; } + } + $("#errRefresh").onclick = loadErrors; + $("#errAdminList").onclick = async (e) => { + const del = e.target.closest(".fb-del"); if (!del) return; + const row = del.closest(".fb-row"); if (!row) return; + if (!(await window.dnConfirm("Delete error?", "This permanently removes this logged error.", { danger: true }))) return; + try { await deleteDoc(doc(db, "errors", row.dataset.id)); row.remove(); } catch (err) { window.showToast("Delete failed: " + err.message, "error"); } + }; + $("#errClear").onclick = async () => { + if (!(await window.dnConfirm("Clear all errors?", "This permanently deletes every logged client error.", { danger: true }))) return; + try { + const snap = await getDocs(collection(db, "errors")); + for (const d of snap.docs) { try { await deleteDoc(doc(db, "errors", d.id)); } catch (_) {} } + } catch (err) { window.showToast("Clear failed: " + err.message, "error"); } + loadErrors(); + }; + loadErrors(); + + $("#uSearch").oninput = drawUsers; + $("#uList").onclick = async (e) => { + const detailBtn = e.target.closest("[data-detail]"); + if (detailBtn) { + const panel = main.querySelector("#detail-" + detailBtn.dataset.detail); + if (panel) { panel.style.display = panel.style.display === "none" ? "" : "none"; detailBtn.textContent = panel.style.display === "none" ? "Details" : "Hide"; } + return; + } + const wlBtn = e.target.closest("[data-wl]"), delBtn = e.target.closest("[data-del]"); + if (wlBtn) { await toggleWl(wlBtn.dataset.wl); } + else if (delBtn) { + if (!(await window.dnConfirm("Remove user?", `This deletes the Firestore record for ${delBtn.dataset.mail || "this user"}.`, { danger: true }))) return; + try { await deleteDoc(doc(db, "users", delBtn.dataset.del)); users = users.filter((u) => u.uid !== delBtn.dataset.del); $("#stUsers").textContent = users.length; drawUsers(); } + catch (err) { window.showToast("Delete failed: " + err.message, "error"); } + } + }; + + // ---- ban-list (site is open to all; only these emails are blocked) ---- + const notify = (m, t) => { try { (window.showToast || (() => {}))(m, t || "info"); } catch (_) {} }; + async function loadWl() { + wl = await getWhitelist(); + wl.banned = (wl.banned || []).map((x) => String(x).toLowerCase()); + $("#stWl").textContent = wl.banned.length; + drawWl(); + } + function drawWl() { + const host = $("#wlList"); + host.innerHTML = wl.banned.length + ? wl.banned.map((em) => `
      ${esc(em)}
      `).join("") + : `

      No one is banned. Everyone can sign in.

      `; + } + async function saveWl() { + try { + await setDoc(WL_REF(), { banned: wl.banned, enforce: false, updatedBy: user.email, updatedAt: serverTimestamp() }, { merge: true }); + $("#stWl").textContent = wl.banned.length; + return true; + } catch (e) { notify("Couldn't save ban-list: " + e.message, "error"); return false; } + } + async function toggleWl(email) { + email = (email || "").toLowerCase().trim(); if (!email) return; + // Never let the owner ban themselves or another owner out of the console. + const target = users.find((u) => (u.email || "").toLowerCase() === email); + if (!wl.banned.includes(email) && (email === (user.email || "").toLowerCase() || isOwnerRow(target))) { + notify("You can't ban an owner account.", "error"); return; + } + const banning = !wl.banned.includes(email); + if (banning) wl.banned.push(email); + else wl.banned = wl.banned.filter((x) => x !== email); + if (await saveWl()) { drawWl(); drawUsers(); notify(banning ? `Banned ${email}` : `Unbanned ${email}`, banning ? "warn" : "success"); } + } + $("#wlAdd").onclick = async () => { const v = $("#wlEmail").value.trim(); if (v) { await toggleWl(v); $("#wlEmail").value = ""; } }; + $("#wlEmail").onkeydown = (e) => { if (e.key === "Enter") $("#wlAdd").click(); }; + $("#wlList").onclick = (e) => { const b = e.target.closest("[data-rm]"); if (b) toggleWl(b.dataset.rm); }; + + // ---- announcement ---- + let annType = "info"; + $("#annType").onclick = (e) => { const b = e.target.closest("button[data-v]"); if (!b) return; annType = b.dataset.v; $("#annType").querySelectorAll("button").forEach((x) => x.classList.toggle("on", x === b)); }; + async function loadAnn() { + try { + const s = await getDoc(ANN_REF()); + if (s.exists()) { + const d = s.data(); + $("#annText").value = d.text || ""; + $("#annActive").checked = !!d.active; + annType = d.type === "warn" ? "warn" : "info"; + $("#annType").querySelectorAll("button").forEach((x) => x.classList.toggle("on", x.dataset.v === annType)); + $("#stAnn").textContent = d.active ? "live" : "off"; + } else { $("#stAnn").textContent = "off"; } + } catch (_) { $("#stAnn").textContent = "—"; } + } + async function publishAnn(active) { + const msg = $("#annMsg"), text = $("#annText").value.trim(); + try { + await setDoc(ANN_REF(), { text, type: annType, active, updatedBy: user.email, updatedAt: serverTimestamp() }, { merge: true }); + $("#annActive").checked = active; + $("#stAnn").textContent = active ? "live" : "off"; + // update the live banner in this session immediately + const el = document.getElementById("announcement"); + if (el) { if (active && text) { el.textContent = text; el.classList.toggle("banner-info", annType !== "warn"); el.hidden = false; } else { el.hidden = true; } } + msg.className = "adm-msg ok"; msg.textContent = active ? "Published — visible to everyone." : "Banner cleared."; + setTimeout(() => (msg.textContent = ""), 2500); + } catch (e) { msg.className = "adm-msg err"; msg.textContent = "Failed: " + e.message; } + } + $("#annPublish").onclick = () => { + if (!$("#annText").value.trim()) { const m = $("#annMsg"); m.className = "adm-msg err"; m.textContent = "write a message first"; return; } + $("#annActive").checked = true; publishAnn(true); + }; + $("#annClear").onclick = () => publishAnn(false); + + // ---- announcement presets ---- + const PRESETS = { + maint: "Scheduled maintenance is underway — some features may be briefly unavailable. Thanks for your patience.", + release: "New release is live! Update the desktop app and CLI from the Downloads page to get the latest tools and fixes.", + security: "Security notice: rotate any credentials you've stored and review recent sign-ins. Contact the owner with questions.", + }; + $("#annPresets").onclick = (e) => { const b = e.target.closest("[data-preset]"); if (!b) return; $("#annText").value = PRESETS[b.dataset.preset] || ""; annType = b.dataset.preset === "security" ? "warn" : "info"; $("#annType").querySelectorAll("button").forEach((x) => x.classList.toggle("on", x.dataset.v === annType)); }; + + // ---- data & outreach ---- + const dmsg = (t) => { const m = $("#dataMsg"); m.className = "adm-msg ok"; m.textContent = t; setTimeout(() => (m.textContent = ""), 2000); }; + const emailsOf = (list) => list.map((u) => u.email).filter(Boolean).join(", "); + $("#copyEmails").onclick = () => { navigator.clipboard?.writeText(emailsOf(users)); dmsg(users.filter((u) => u.email).length + " emails copied"); }; + $("#copyOwnerless").onclick = () => { const l = users.filter((u) => !isOwnerRow(u)); navigator.clipboard?.writeText(emailsOf(l)); dmsg(l.filter((u) => u.email).length + " emails copied"); }; + $("#expCsv").onclick = () => { + const esc2 = (v) => `"${String(v ?? "").replace(/^(?=[=+@\t\r]|-(?!\d+(?:\.\d+)?$))/, "'").replace(/"/g, '""')}"`; + const rows = [["email", "name", "uid", "lastSeen", "banned"]].concat(users.map((u) => [u.email, u.name, u.uid, fmtDate(u.lastSeen), (wl.banned || []).includes((u.email || "").toLowerCase()) ? "yes" : "no"])); + const csv = rows.map((r) => r.map(esc2).join(",")).join("\n"); + const url = URL.createObjectURL(new Blob([csv], { type: "text/csv" })); + const a = document.createElement("a"); a.href = url; a.download = "darknode-users.csv"; document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(url), 1000); + dmsg("exported " + users.length + " users"); + }; + + // ---- who uses Nexus, the desktop app and its VMs (usage/{uid}, written by the Worker) ---- + const usState = { tab: "nexus", q: "" }; + let usDocs = []; + async function loadUsage() { + const host = $("#usList"); + try { + const [mod, snap] = await Promise.all([import("/js/admin-usage.js?v=1"), getDocs(collection(db, "usage"))]); + usDocs = snap.docs.map((d) => ({ uid: d.id, ...d.data() })); + const draw = () => mod.render(host, usDocs, usState, esc); + host.onclick = (e) => { const t = e.target.closest("[data-utab]"); if (t) { usState.tab = t.dataset.utab; draw(); } }; + $("#usSearch").oninput = (e) => { usState.q = e.target.value; draw(); }; + draw(); + } catch (e) { host.innerHTML = `

      Couldn't load usage: ${esc(e.message)}. Make sure Firestore rules are deployed.

      `; } + } + $("#usRefresh").onclick = loadUsage; + + await Promise.all([loadWl(), loadUsers(), loadAnn(), loadUsage()]); + + // ---- Analytics ---- + async function loadAnalytics() { + try { + let totalXP = 0, totalCompletions = 0, topUser = { email: '-', xp: 0 }; + users.forEach(u => { + const xp = u.learnXP || 0; + const completed = (u.learnCompleted || []).length; + totalXP += xp; + totalCompletions += completed; + if (xp > topUser.xp) topUser = { email: u.email || '?', xp }; + }); + const avgXP = users.length ? Math.round(totalXP / users.length) : 0; + const anaTotalTopics = $("#anaTotalTopics"); + if (anaTotalTopics) { + try { + const r = await fetch('/data/topics.json'); + const topics = await r.json(); + anaTotalTopics.textContent = topics.length; + } catch(_) { anaTotalTopics.textContent = '?'; } + } + const anaTopLearner = $("#anaTopLearner"); + if (anaTopLearner) anaTopLearner.textContent = topUser.email ? topUser.email.split('@')[0] : '-'; + const anaAvgXP = $("#anaAvgXP"); + if (anaAvgXP) anaAvgXP.textContent = avgXP; + const anaCompletions = $("#anaCompletions"); + if (anaCompletions) anaCompletions.textContent = totalCompletions; + + // Registration chart (last 7 days) + const chart = $("#anaChart"); + if (chart) { + const days = []; + for (let i = 6; i >= 0; i--) { + const d = new Date(Date.now() - i * 864e5); + const label = d.toLocaleDateString('en', { weekday: 'short' }); + const dayStart = new Date(d); dayStart.setHours(0,0,0,0); + const dayEnd = new Date(d); dayEnd.setHours(23,59,59,999); + const toMs = tsMs; + const count = users.filter(u => { const c = toMs(u.created || u.createdAt); return c >= dayStart.getTime() && c <= dayEnd.getTime(); }).length; + days.push({ label, count }); + } + const max = Math.max(...days.map(d => d.count), 1); + chart.innerHTML = '
      New users (last 7 days)
      ' + + '
      ' + + days.map(d => `
      ${d.label}
      `).join('') + + '
      '; + } + } catch(e) { console.error('Analytics error:', e); } + } + const anaRefresh = $("#anaRefresh"); + if (anaRefresh) anaRefresh.onclick = loadAnalytics; + + // ---- Activity log ---- + async function loadActivityLog() { + const log = $("#actLog"); + if (!log) return; + try { + const activities = []; + users.forEach(u => { + if (u.lastSeen) activities.push({ email: u.email, action: 'active', ts: u.lastSeen }); + (u.logins || []).forEach(l => activities.push({ email: u.email, action: 'login from ' + (l.device || 'unknown'), ts: l.ts })); + }); + activities.sort((a, b) => { + const ta = a.ts && a.ts.toMillis ? a.ts.toMillis() : (a.ts || 0); + const tb = b.ts && b.ts.toMillis ? b.ts.toMillis() : (b.ts || 0); + return tb - ta; + }); + log.innerHTML = activities.length + ? activities.slice(0, 15).map(a => `
      ${esc(a.email || '?')}
      ${esc(a.action)}
      ${fmtDate(a.ts)}
      `).join('') + : '

      No activity recorded.

      '; + } catch(e) { log.innerHTML = '

      Could not load activity log.

      '; } + } + + // ---- Maintenance ---- + const clearInactive = $("#admClearInactive"); + if (clearInactive) clearInactive.onclick = async () => { + const msg = $("#maintMsg"); + const cutoff = Date.now() - 90 * 864e5; + const toMs = tsMs; + const inactive = users.filter(u => { + const last = toMs(u.lastSeen) || toMs(u.created || u.createdAt); + return last && last < cutoff && !isOwnerRow(u); + }); + if (!inactive.length) { if (msg) msg.textContent = 'No inactive users found.'; return; } + if (!(await window.dnConfirm('Remove inactive users?', 'This deletes ' + inactive.length + ' users inactive for 90+ days.', { danger: true }))) return; + let removed = 0; + for (const u of inactive) { + try { await deleteDoc(doc(db, "users", u.uid)); removed++; } catch(_) {} + } + if (msg) msg.textContent = 'Removed ' + removed + ' inactive users.'; + loadUsers(); + }; + + const exportFeedback = $("#admExportFeedback"); + if (exportFeedback) exportFeedback.onclick = async () => { + try { + const snap = await getDocs(collection(db, "feedback")); + const data = snap.docs.map(d => ({ id: d.id, ...d.data() })); + const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); a.href = url; a.download = 'feedback-export.json'; a.click(); + URL.revokeObjectURL(url); + } catch(e) { const msg = $("#maintMsg"); if (msg) msg.textContent = 'Export failed: ' + e.message; } + }; + + // ---- Feature flags ---- + const ffSave = $("#ffSave"); + if (ffSave) ffSave.onclick = async () => { + const flags = {}; + ['ffLearn','ffWebshell','ffVmlab','ffAI','ffGmail','ffGithub'].forEach(id => { + const el = $('#' + id); + if (el) flags[id.replace('ff','')] = el.checked; + }); + try { + await setDoc(doc(db, "settings", "features"), { ...flags, updatedBy: user.email, updatedAt: serverTimestamp() }, { merge: true }); + const msg = $("#ffMsg"); if (msg) msg.textContent = 'Flags saved.'; + } catch(e) { const msg = $("#ffMsg"); if (msg) msg.textContent = 'Save failed: ' + e.message; } + }; + // Load saved flags + try { + const flagDoc = await getDoc(doc(db, "settings", "features")); + if (flagDoc.exists()) { + const d = flagDoc.data(); + ['Learn','Webshell','Vmlab','AI','Gmail','Github'].forEach(f => { + const el = $('#ff' + f); + if (el && d[f] !== undefined) el.checked = d[f]; + }); + } + } catch(_) {} + + // ---- System status ---- + const sysLh = $("#sysLh"); + if (sysLh) { + try { + const r = await fetch('/data/topics.json', { method: 'HEAD' }); + sysLh.textContent = r.ok ? 'OK' : 'error'; + sysLh.style.color = r.ok ? '#3fb950' : '#f85149'; + } catch(_) { sysLh.textContent = 'unreachable'; sysLh.style.color = '#f85149'; } + } + const sysBundle = $("#sysBundle"); + if (sysBundle) { + const scripts = document.querySelectorAll('script[src]'); + sysBundle.textContent = scripts.length + ' scripts loaded'; + } + const sysDeploy = $("#sysDeploy"); + if (sysDeploy) { + try { + const r = await fetch('/js/auth.js', { method: 'HEAD' }); + const lm = r.headers.get('last-modified'); + sysDeploy.textContent = lm ? new Date(lm).toLocaleDateString() : 'unknown'; + } catch(_) { sysDeploy.textContent = 'unknown'; } + } + + // ---- Quick actions ---- + const admBackup = $("#admBackup"); + if (admBackup) admBackup.onclick = async () => { + try { + const [usersSnap, wlSnap, annSnap] = await Promise.all([ + getDocs(collection(db, "users")), + getDoc(WL_REF()), + getDoc(ANN_REF()), + ]); + const backup = { + exportedAt: new Date().toISOString(), + users: usersSnap.docs.map(d => ({ id: d.id, ...d.data() })), + whitelist: wlSnap.exists() ? wlSnap.data() : {}, + announcement: annSnap.exists() ? annSnap.data() : {}, + }; + const blob = new Blob([JSON.stringify(backup, null, 2)], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); a.href = url; a.download = 'darknode-backup-' + new Date().toISOString().slice(0,10) + '.json'; a.click(); + URL.revokeObjectURL(url); + } catch(e) { window.showToast('Backup failed: ' + e.message, "error"); } + }; + + const admMsgAll = $("#admMsgAll"); + if (admMsgAll) admMsgAll.onclick = async () => { + const msg = await window.dnPrompt('Message to all users', { desc: 'Shown as an announcement.', placeholder: 'Announcement text…', textarea: true }); + if (!msg) return; + const annText = $("#annText"); + if (annText) { annText.value = msg; } + window.showToast('Announcement text set. Click Publish to send it.', "info"); + }; + + // ---- Email panel ---- + const emailTarget = $("#emailTarget"); + const emailOneRow = $("#emailOneRow"); + const emailCount = $("#emailCount"); + const emailMsg = $("#emailMsg"); + let emailMode = "one"; + + if (emailTarget) { + emailTarget.querySelectorAll("button").forEach((b) => { + b.onclick = () => { + emailTarget.querySelectorAll("button").forEach((x) => x.classList.remove("on")); + b.classList.add("on"); + emailMode = b.dataset.v; + if (emailOneRow) emailOneRow.style.display = emailMode === "one" ? "" : "none"; + if (emailCount) emailCount.textContent = emailMode === "all" ? users.filter((u) => u.email).length + " recipients" : ""; + }; + }); + } + + // Quick templates + const templates = { + downtime: { + subject: "We're sorry — Darknode was briefly down", + body: "Hi there,\n\nWe wanted to reach out and apologize for the brief downtime on darknode.ai yesterday. We know you rely on the platform and we take uptime seriously.\n\nWhat happened: A configuration change caused the site to become temporarily unavailable. We identified and resolved the issue, and the platform is now fully operational.\n\nWhat we're doing: We've added monitoring to prevent this from happening again.\n\nThank you for your patience and for being part of the Darknode community.\n\nBest,\nThe Darknode Team\ncontact@darknode.ai" + }, + update: { + subject: "What's new on Darknode", + body: "Hi there,\n\nWe've shipped some updates to Darknode:\n\n- [Feature 1]\n- [Feature 2]\n- [Bug fix]\n\nCheck it out at darknode.ai\n\nBest,\nThe Darknode Team" + }, + welcome: { + subject: "Welcome to Darknode", + body: "Welcome to Darknode!\n\nThanks for signing up. Here's what you can do:\n\n- Work across offensive security, reconnaissance, OSINT, forensics, malware analysis and blue-team operations\n- Use the Nexus AI coding agent\n- Practice in our security labs\n- Track your progress in the Learn Hub\n\nGet started at darknode.ai\n\nBest,\nThe Darknode Team\ncontact@darknode.ai" + }, + security: { + subject: "Security Notice — Darknode", + body: "Hi there,\n\nThis is a security notice from Darknode.\n\n[Describe the security event]\n\nWhat you should do:\n- [Action item 1]\n- [Action item 2]\n\nIf you have questions, reply to this email.\n\nBest,\nThe Darknode Team\ncontact@darknode.ai" + } + }; + + main.querySelectorAll(".emailTpl").forEach((b) => { + b.onclick = () => { + const tpl = templates[b.dataset.tpl]; + if (!tpl) return; + const subj = $("#emailSubject"), body = $("#emailBody"); + if (subj) subj.value = tpl.subject; + if (body) body.value = tpl.body; + if (emailMsg) emailMsg.textContent = "Template loaded: " + b.dataset.tpl; + }; + }); + + // Send via Gmail (mailto or Gmail compose URL) + const emailSend = $("#emailSend"); + if (emailSend) emailSend.onclick = () => { + const subj = ($("#emailSubject")?.value || "").trim(); + const body = ($("#emailBody")?.value || "").trim(); + if (!subj || !body) { if (emailMsg) emailMsg.textContent = "Subject and body required."; return; } + + let to; + if (emailMode === "one") { + to = ($("#emailTo")?.value || "").trim(); + if (!to) { if (emailMsg) emailMsg.textContent = "Enter a recipient email."; return; } + } else { + const emails = users.filter((u) => u.email && !isOwnerRow(u)).map((u) => u.email); + if (!emails.length) { if (emailMsg) emailMsg.textContent = "No users to email."; return; } + to = emails.join(","); + } + + const gmailUrl = "https://mail.google.com/mail/?view=cm" + + "&to=" + encodeURIComponent(to) + + "&su=" + encodeURIComponent(subj) + + "&body=" + encodeURIComponent(body) + + "&from=" + encodeURIComponent("contact@darknode.ai"); + window.open(gmailUrl, "_blank", "noopener,noreferrer"); + if (emailMsg) emailMsg.textContent = emailMode === "all" + ? "Opened Gmail with " + users.filter((u) => u.email && !isOwnerRow(u)).length + " recipients" + : "Opened Gmail draft to " + to; + }; + + // Copy as text + const emailCopy = $("#emailCopyDraft"); + if (emailCopy) emailCopy.onclick = () => { + const subj = ($("#emailSubject")?.value || "").trim(); + const body = ($("#emailBody")?.value || "").trim(); + const draft = "Subject: " + subj + "\n\n" + body; + navigator.clipboard?.writeText(draft); + if (emailMsg) emailMsg.textContent = "Draft copied to clipboard."; + }; + + // ---- Danger zone ---- + const admPurge = $("#admPurgeData"); + if (admPurge) admPurge.onclick = async () => { + const msg = $("#dangerMsg"); + if (!(await window.dnConfirm('Delete ALL user data?', 'DANGER: this permanently deletes every non-owner user record. This cannot be undone.', { danger: true, submitText: 'Continue' }))) return; + if ((await window.dnPrompt('Type DELETE to confirm', { placeholder: 'DELETE' })) !== 'DELETE') return; + let count = 0; + for (const u of users) { + if (isOwnerRow(u)) continue; + try { await deleteDoc(doc(db, "users", u.uid)); count++; } catch(_) {} + } + if (msg) msg.textContent = 'Purged ' + count + ' users.'; + loadUsers(); + }; + + const admRevoke = $("#admRevokeAll"); + if (admRevoke) admRevoke.onclick = () => { + const msg = $("#dangerMsg"); + if (msg) msg.textContent = 'Session revocation requires Firebase Admin SDK (server-side). Use the Firebase Console to revoke refresh tokens.'; + }; + + // Load analytics + activity + loadAnalytics(); + loadActivityLog(); +} diff --git a/public/js/preview-ui.js b/unused-stuff/owner-console/js/preview-ui.js similarity index 100% rename from public/js/preview-ui.js rename to unused-stuff/owner-console/js/preview-ui.js