From 53ec565a90a2e7932d8e55e98e617aee433ef5a8 Mon Sep 17 00:00:00 2001 From: Darknode-Official Date: Thu, 26 Nov 2026 22:00:56 -0800 Subject: [PATCH] Self-service account deletion; remove the public template Terms page Deleting an account used to mean filing a request that nothing read (the deletionRequests docs had no reader) or emailing an unconfirmed inbox, and the Deck had no way to do it at all. - Worker POST /api/account/delete (signed in within the last 5 minutes, body {"confirm":"DELETE"}): wipes the personal workspace's graph, monitors and API keys; deletes team workspaces and vaults the user holds alone; removes their member docs elsewhere and every Firestore record that names them; then deletes the Firebase Auth account last. A workspace they created that still has members blocks deletion (409) before anything is touched. Retrying finishes a half-done deletion. - Each Durable Object answers an internal /__wipe route that no user-facing forward can reach (they all use fixed paths). - Deck Settings > Data > Delete account, the older settings page, and the "Verify your email" screen (unverified sign-ups could not delete at all) use public/js/account-delete.js: type DELETE, sign in again if needed, then this account's browser data is cleared. - Terms/Privacy/Docs describe the self-service path (wording only, no TOS_VERSION bump). - public/legal/terms-of-service.html was an unfilled template with 21 "[SPECIFY ...]" placeholders served publicly; moved to unused-stuff/ and the URL now redirects to /terms. --- firebase.json | 6 + public/js/account-delete.js | 92 ++++++++++ public/js/auth.js | 16 +- public/js/deck-ui.js | 11 ++ public/js/docs.js | 2 +- public/js/legal.js | 4 +- test/worker/account-delete.test.mjs | 146 +++++++++++++++ unused-stuff/README.md | 6 + .../legal-terms-of-service-template.html | 0 worker/account-delete.js | 171 ++++++++++++++++++ worker/auth.js | 1 + worker/graph.js | 2 + worker/ingest.js | 2 + worker/monitor.js | 2 + worker/vault.js | 2 + worker/worker.js | 2 + 16 files changed, 456 insertions(+), 9 deletions(-) create mode 100644 public/js/account-delete.js create mode 100644 test/worker/account-delete.test.mjs rename public/legal/terms-of-service.html => unused-stuff/legal-terms-of-service-template.html (100%) create mode 100644 worker/account-delete.js diff --git a/firebase.json b/firebase.json index 80165b7b..7e35fea6 100644 --- a/firebase.json +++ b/firebase.json @@ -5,6 +5,9 @@ "predeploy": ["node scripts/build.mjs"], "site": "sentinel-b4194", "ignore": ["firebase/**", "**/.git/**", "**/node_modules/**", "**/*.exe", "**/*.deb", "**/*.AppImage", "**/*.dmg"], + "redirects": [ + { "source": "/legal/terms-of-service.html", "destination": "/terms", "type": 301 } + ], "rewrites": [ { "source": "/api/chat", "function": { "functionId": "chat", "region": "us-central1" } }, { "source": "/version", "destination": "/version.txt" }, @@ -89,6 +92,9 @@ "predeploy": ["node scripts/build.mjs"], "site": "sentinel-b4194-6173e", "ignore": ["firebase/**", "**/.git/**", "**/node_modules/**", "**/*.exe", "**/*.deb", "**/*.AppImage", "**/*.dmg"], + "redirects": [ + { "source": "/legal/terms-of-service.html", "destination": "/terms", "type": 301 } + ], "rewrites": [ { "source": "/api/chat", "function": { "functionId": "chat", "region": "us-central1" } }, { "source": "/version", "destination": "/version.txt" }, diff --git a/public/js/account-delete.js b/public/js/account-delete.js new file mode 100644 index 00000000..3a5b48a1 --- /dev/null +++ b/public/js/account-delete.js @@ -0,0 +1,92 @@ +// Self-service account deletion (Deck Settings > Data, and the older settings page). The +// Worker's POST /api/account/delete removes every server record and then the sign-in +// (worker/account-delete.js); this side confirms, re-checks the sign-in when it is older +// than 5 minutes, and clears this account's data from the browser afterwards. +import { auth, googleProvider, githubProvider } from "/js/firebase.js?v=20261021a"; +import { reauthenticateWithPopup, reauthenticateWithCredential, EmailAuthProvider, signOut } from "https://www.gstatic.com/firebasejs/12.17.0/firebase-auth.js"; + +const proxyBase = () => { try { return String(window.DARKNODE_PROXY_URL || "").replace(/\/api\/chat$/, ""); } catch (_) { return ""; } }; +const modal = (o) => (typeof window.dnModal === "function" ? window.dnModal(o) : Promise.resolve(null)); + +async function callDelete(user, fresh) { + const r = await fetch(proxyBase() + "/api/account/delete", { + method: "POST", + headers: { Authorization: "Bearer " + (await user.getIdToken(fresh)), "Content-Type": "application/json" }, + body: JSON.stringify({ confirm: "DELETE" }), + }); + let body = {}; try { body = await r.json(); } catch (_) {} + return { ok: r.ok, status: r.status, body }; +} + +// Sign in again with the account's own method. -> true when it worked. +async function reauth(user) { + const ids = (user.providerData || []).map((p) => p.providerId); + try { + if (ids.includes("google.com")) { await reauthenticateWithPopup(user, googleProvider); return true; } + if (ids.includes("github.com")) { await reauthenticateWithPopup(user, githubProvider); return true; } + if (ids.includes("password") && user.email) { + const v = await modal({ title: "Confirm it's you", desc: "Enter the password for " + user.email + ".", fields: [{ inputType: "password", placeholder: "Password" }], submitText: "Continue" }); + if (!v || !v[0]) return false; + await reauthenticateWithCredential(user, EmailAuthProvider.credential(user.email, v[0])); + return true; + } + } catch (_) {} + return false; +} + +// Remove this account's data from this browser only: keys named with its uid, its saved +// API keys, and its local security-graph snapshots. Other accounts on a shared browser keep theirs. +async function clearLocal(uid) { + try { if (window.dnKeys && window.dnKeys.clearForUid) window.dnKeys.clearForUid(uid); } catch (_) {} + try { + const rm = []; + for (let i = 0; i < localStorage.length; i++) { const k = localStorage.key(i); if (k && k.includes(uid)) rm.push(k); } + rm.forEach((k) => localStorage.removeItem(k)); + localStorage.removeItem("dn_active_ws"); + } catch (_) {} + try { + await new Promise((resolve) => { + const req = indexedDB.open("dn-secgraph", 1); + req.onerror = req.onblocked = () => resolve(); + req.onupgradeneeded = () => { try { req.result.createObjectStore("snap"); } catch (_) {} }; + req.onsuccess = () => { + try { + const db = req.result, tx = db.transaction("snap", "readwrite"), st = tx.objectStore("snap"); + const kr = st.getAllKeys(); + kr.onsuccess = () => { (kr.result || []).filter((k) => String(k).includes(uid)).forEach((k) => st.delete(k)); }; + tx.oncomplete = tx.onerror = tx.onabort = () => { db.close(); resolve(); }; + } catch (_) { resolve(); } + }; + }); + } catch (_) {} +} + +export async function deleteAccount({ toast = () => {} } = {}) { + const user = auth.currentUser; + if (!user) { toast("Sign in first.", "error"); return false; } + if (!proxyBase()) { toast("Account deletion needs the cloud proxy, which this build has not configured.", "error"); return false; } + const v = await modal({ + title: "Delete your Darknode account?", + desc: "This permanently deletes the account " + (user.email || "") + " and everything stored with it: your security graph, monitors and domain watch, API keys, settings and notifications, and any team workspace you hold alone. Team workspaces you joined keep their own data. This cannot be undone. Type DELETE to confirm.", + fields: [{ placeholder: "DELETE" }], + submitText: "Delete account", danger: true, + }); + if (!v) return false; + if (String(v[0] || "").trim() !== "DELETE") { toast("Type DELETE in capitals to confirm.", "error"); return false; } + let r; + try { + r = await callDelete(user, false); + if (r.status === 401 && r.body.reauth) { + if (!(await reauth(user))) { toast("Couldn't confirm it's you. Sign out, sign in again, then delete within 5 minutes.", "error"); return false; } + r = await callDelete(user, true); + } + } catch (_) { toast("Couldn't reach Darknode. Check your connection and try again.", "error"); return false; } + if (r.status === 409) { await modal({ title: "Remove the other members first", desc: r.body.error, submitText: "OK", cancelText: "Close" }); return false; } + if (!r.ok) { toast(r.body.error || "Deletion failed (HTTP " + r.status + "). Try again.", "error"); return false; } + const uid = user.uid; + await clearLocal(uid); + await modal({ title: "Your account is deleted", desc: "Your Darknode account and its data are gone. You can sign up again at any time with a new account.", submitText: "OK", cancelText: "Close" }); + try { await signOut(auth); } catch (_) {} + try { location.replace("/"); } catch (_) {} + return true; +} diff --git a/public/js/auth.js b/public/js/auth.js index 416718b1..968ee5f5 100644 --- a/public/js/auth.js +++ b/public/js/auth.js @@ -970,7 +970,13 @@ function renderVerify(user) {

+

Wrong address, or don't want the account? Delete this account

`; + document.getElementById("delacct").onclick = async (e) => { + e.preventDefault(); + try { const m = await import("/js/account-delete.js?v=1"); await m.deleteAccount({ toast: showToast }); } + catch (_) { showToast("Couldn't load account deletion. Reload and try again.", "error"); } + }; document.getElementById("reload").onclick = async () => { await reload(user); if (user.emailVerified) location.reload(); @@ -1540,8 +1546,8 @@ claude mcp add darknode -- node ~/darknode-cli/darknode.js mcp ${isGuest ? "" : `
- Delete my accountRequest permanent deletion of your Darknode account and its records. We confirm by email. - + Delete my accountPermanently delete your Darknode account and everything stored with it. This cannot be undone. +
`}

Questions about your data? Email contact@darknode.ai.

`, @@ -1649,10 +1655,8 @@ claude mcp add darknode -- node ~/darknode-cli/darknode.js mcp }; const dataDelete = main.querySelector("#data-delete"); if (dataDelete) dataDelete.onclick = async () => { - const ok = window.dnConfirm ? await window.dnConfirm("Request account deletion?", "We'll permanently delete your Darknode account and its records, then confirm by email to " + (user.email || "your address") + ".", { submitText: "Request deletion", danger: true }) : true; - if (!ok) return; - try { await setDoc(doc(db, "deletionRequests", user.uid), { uid: user.uid, email: user.email || "", requestedAt: serverTimestamp() }, { merge: true }); showToast("Deletion request received. We'll confirm by email.", "success"); } - catch (e) { showToast("Could not file the request: " + ((e && e.message) || "try emailing contact@darknode.ai"), "error"); } + try { const m = await import("/js/account-delete.js?v=1"); await m.deleteAccount({ toast: showToast }); } + catch (_) { showToast("Couldn't load account deletion. Reload and try again.", "error"); } }; // MCP + code-block copy buttons const mcpCopy = main.querySelector("#dn-mcp-copy2"); diff --git a/public/js/deck-ui.js b/public/js/deck-ui.js index 5e2a9d0f..2a9aac08 100644 --- a/public/js/deck-ui.js +++ b/public/js/deck-ui.js @@ -4560,6 +4560,10 @@ export function renderDeck(host, opts) {
Reset local Deck state
Clears connections, pins, notes and layout in this browser. Does not touch your account or the security graph.
+ ${noAccount ? "" : `
+
Delete account
Permanently deletes your account and everything stored with it: security graph, monitors, API keys, settings, and team workspaces you hold alone. Export first if you want a copy.
+ +
`} ${opts.isOwner ? `
@@ -4633,6 +4637,13 @@ export function renderDeck(host, opts) { toast("Local Deck state reset — reloading"); setTimeout(() => { try { location.reload(); } catch (_) {} }, 600); }; + const delAcct = el.querySelector("#dkSetDelAcct"); + if (delAcct) delAcct.onclick = async () => { + delAcct.disabled = true; + try { const m = await import("/js/account-delete.js?v=1"); await m.deleteAccount({ toast }); } + catch (_) { toast("Couldn't load account deletion. Reload and try again.", "error"); } + finally { delAcct.disabled = false; } + }; const admBtn = el.querySelector("#dkSetAdmin"); if (admBtn) admBtn.onclick = () => openTool("admin", "Admin"); fqMod().then((m) => m.renderSlaSettings(el.querySelector(".dk-setgrid"), fqCtx()), () => {}); diff --git a/public/js/docs.js b/public/js/docs.js index 9b0925b0..c105edc9 100644 --- a/public/js/docs.js +++ b/public/js/docs.js @@ -154,7 +154,7 @@ node darknode.js nexus init # optional: scaffold .nexus/ project
  • 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.
  • Feedback. Feedback you submit is stored to improve the product and is readable only by you and the maintainers.
  • -
  • Retention & deletion. You may request deletion of your account data at any time via Settings or by contacting the maintainers.
  • +
  • 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.
  • Weekly email digest. Off unless you turn it on in Settings. While it is on we store your watched domains and your latest certificate-check results (domain, expiry date, issuer) on our servers to build the email, and send it to your account email through our email provider, Resend. Turn it off in Settings or with the unsubscribe link in any digest.
  • Monitors and the domain watch. When you set up a monitor, including the Free plan's one-domain watch, we store on our servers the domains it watches, its settings, its latest results (such as a certificate's expiry date and issuer, and the domain's SPF and DMARC policy, so a later change can be named) and a log of its runs and alert deliveries. Email alerts go only to your own verified account email, looked up in our sign-in provider when each alert is sent, and are sent through our email provider, Resend; to apply the limit of 5 alert emails a day we keep a count per account for the current UTC day. Webhook and chat URLs you add to a monitor are stored to deliver its alerts. Turn a watch off or delete it under Monitors, or use the stop link in any alert email.
  • diff --git a/public/js/legal.js b/public/js/legal.js index 6b6b9704..075997be 100644 --- a/public/js/legal.js +++ b/public/js/legal.js @@ -85,10 +85,10 @@ export const TOS_HTML = `
  • Cookies: we use only essential cookies and localStorage for session management and user preferences. We do not use tracking cookies or third-party analytics.
  • International transfers: data is processed and stored in Google Cloud data centers. By using the Platform, you consent to transfer of data to servers that may be outside your country of residence.
  • -

    Your rights (GDPR, CCPA, and similar laws): depending on your jurisdiction, you may have the right to access, correct, delete, or export your personal data, restrict processing, object to processing, or withdraw consent. To exercise any of these rights, email contact@darknode.ai. We will respond within 30 days. You also have the right to lodge a complaint with your local data protection authority.

    +

    Your rights (GDPR, CCPA, and similar laws): depending on your jurisdiction, you may have the right to access, correct, delete, or export your personal data, restrict processing, object to processing, or withdraw consent. You can export your Deck state and security graph and delete your account yourself in the Deck under Settings, Data. To exercise any other right, email contact@darknode.ai. We will respond within 30 days. You also have the right to lodge a complaint with your local data protection authority.

    15. Account Termination

    -

    By you: you may stop using the Platform and request account deletion at any time by emailing contact@darknode.ai. Upon deletion, your data will be removed in accordance with Section 14.

    +

    By you: you may stop using the Platform and delete your account at any time in the Deck under Settings, Data, Delete account (or by emailing contact@darknode.ai). Deletion removes your account and its stored data at once, including any team workspace you hold alone; while a team workspace you created still has other members, remove them first. Data is otherwise removed in accordance with Section 14.

    By us: we may suspend or terminate your account immediately, without prior notice, if we reasonably believe you have violated these terms. We may also discontinue the Platform or any feature at any time with reasonable notice.

    16. Paid Plans & Pricing

    diff --git a/test/worker/account-delete.test.mjs b/test/worker/account-delete.test.mjs new file mode 100644 index 00000000..423c3052 --- /dev/null +++ b/test/worker/account-delete.test.mjs @@ -0,0 +1,146 @@ +// Unit tests for worker/account-delete.js: self-service account deletion. Firestore REST and +// Firebase Auth are an in-memory stand-in behind a fake fetch; Durable Objects are stubs. +import { test, group, assert } from "../harness.mjs"; +import { handleAccountDelete, recentEnough, maybeWipe, RECENT_S } from "../../worker/account-delete.js"; +import { matchRoute, authorize } from "../../worker/auth.js"; + +const json = (body, status = 200) => ({ status, body }); +const NOW = 1795000000; +const ROOT = "https://firestore.googleapis.com/v1/projects/p/databases/(default)/documents"; +const S = (v) => ({ stringValue: v }); + +function fakeCloud(docs) { + const db = new Map(Object.entries(docs).map(([k, v]) => [k, Object.fromEntries(Object.entries(v).map(([f, x]) => [f, S(x)]))])); + const authDeleted = []; + const res = (status, body) => ({ ok: status < 300, status, json: async () => body }); + const doc = (path) => ({ name: "projects/p/databases/(default)/documents/" + path, fields: db.get(path) }); + const fetch = async (url, init = {}) => { + const m = init.method || "GET"; + if (url.endsWith("/accounts:delete")) { authDeleted.push(JSON.parse(init.body).localId); return res(200, {}); } + if (url === ROOT + ":runQuery") { + const q = JSON.parse(init.body).structuredQuery, from = q.from[0], ff = q.where.fieldFilter; + const hits = [...db.keys()].filter((p) => { + const seg = p.split("/"); if (seg.length % 2) return false; + const coll = seg[seg.length - 2]; + if (coll !== from.collectionId || (!from.allDescendants && seg.length !== 2)) return false; + const v = db.get(p)[ff.field.fieldPath]; return v && v.stringValue === ff.value.stringValue; + }); + return res(200, hits.map((p) => ({ document: doc(p) }))); + } + const path = decodeURIComponent(url.slice(ROOT.length + 1)).split("?")[0]; + if (path.endsWith(":listCollectionIds")) { + const base = path.slice(0, -":listCollectionIds".length) + "/"; + const ids = new Set([...db.keys()].filter((p) => p.startsWith(base)).map((p) => p.slice(base.length).split("/")[0]).filter((c, _, a) => c)); + return res(200, { collectionIds: [...ids].filter((c) => [...db.keys()].some((p) => p.startsWith(base + c + "/") && p.slice(base.length).split("/").length === 2)) }); + } + if (m === "DELETE") { db.delete(path); return res(200, {}); } + if (path.split("/").length % 2) { // a collection + const kids = [...db.keys()].filter((p) => p.startsWith(path + "/") && p.split("/").length === path.split("/").length + 1); + return res(200, { documents: kids.map(doc) }); + } + return db.has(path) ? res(200, doc(path)) : res(404, {}); + }; + return { db, fetch, authDeleted }; +} + +function fakeDOs() { + const wiped = []; + const ns = (kind) => ({ idFromName: (n) => n, get: (id) => ({ fetch: async (u, init) => { assert.equal(u, "https://do/__wipe"); assert.equal(init.headers["x-dn-wipe"], "1"); wiped.push(kind + ":" + id); return { ok: true, status: 200 }; } }) }); + return { wiped, env: { FIREBASE_PROJECT_ID: "p", GRAPH: ns("graph"), MONITOR: ns("monitor"), INGEST: ns("ingest"), VAULT: ns("vault") } }; +} + +const req = (body = { confirm: "DELETE" }) => ({ method: "POST", json: async () => body }); +const me = (extra = {}) => ({ kind: "user", uid: "u1", email: "test@darknode.ai", claims: { auth_time: NOW - 30 }, ...extra }); +const run = (cloud, dos, principal = me(), body) => handleAccountDelete(req(body), dos.env, json, principal, { fetch: cloud.fetch, token: async () => "t", now: NOW }); + +group("account-delete", () => { + test("the route needs a signed-in user", () => { + const { route } = matchRoute("/api/account/delete", "POST"); + assert.equal(route.id, "account-delete"); + assert.equal(authorize(route, { kind: "anonymous" }).status, 401); + assert.equal(authorize(route, { kind: "key" }).status, 401); + assert.equal(authorize(route, { kind: "user", claims: {} }), null); + }); + + test("a sign-in older than 5 minutes must sign in again", async () => { + assert.equal(recentEnough({ auth_time: NOW - RECENT_S }, NOW), true); + assert.equal(recentEnough({ auth_time: NOW - RECENT_S - 1 }, NOW), false); + assert.equal(recentEnough({}, NOW), false); + const cloud = fakeCloud({ "users/u1": { email: "test@darknode.ai" } }), dos = fakeDOs(); + const r = await run(cloud, dos, me({ claims: { auth_time: NOW - 3600 } })); + assert.equal(r.status, 401); assert.equal(r.body.reauth, true); + assert.ok(cloud.db.has("users/u1")); assert.equal(dos.wiped.length, 0); assert.equal(cloud.authDeleted.length, 0); + }); + + test("without the confirm word nothing happens", async () => { + const cloud = fakeCloud({ "users/u1": {} }), dos = fakeDOs(); + const r = await run(cloud, dos, me(), { confirm: "yes" }); + assert.equal(r.status, 400); assert.ok(cloud.db.has("users/u1")); + }); + + test("everything the user owns is deleted; other people's data is kept", async () => { + const cloud = fakeCloud({ + "users/u1": { email: "test@darknode.ai" }, "users/u1/notifications/n1": { text: "hi" }, "users/u1/config/deck": { a: "b" }, + "users/u2": { email: "other@darknode.ai" }, + "usage/u1": {}, "usage/u2": {}, "deletionRequests/u1": { uid: "u1" }, + "pairings/c1": { uid: "u1" }, "pairings/c2": { uid: "u2" }, + "upgradeRequests/r1": { uid: "u1" }, "toolRequests/t1": { uid: "u1" }, "feedback/f1": { uid: "u1" }, "errors/e1": { uid: "u1" }, + "ip_reports/i1": { reporter_uid: "u1" }, "ip_reports/i2": { reporter_uid: "u2" }, + "waitlist/w1": { email: "test@darknode.ai" }, "waitlist/w2": { email: "other@darknode.ai" }, + // a team workspace they created and hold alone: deleted with its stores + "workspaces/solo0000000000000000": { createdBy: "u1", name: "Solo" }, "workspaces/solo0000000000000000/members/u1": { uid: "u1", role: "owner" }, + "workspaces/solo0000000000000000/memberLog/l1": { uid: "u1" }, + // someone else's workspace they joined: only their member doc goes + "workspaces/team0000000000000000": { createdBy: "u2", name: "Team" }, "workspaces/team0000000000000000/members/u1": { uid: "u1", role: "analyst" }, + "workspaces/team0000000000000000/members/u2": { uid: "u2", role: "owner" }, + // a vault they created alone + "vaults/vault0001": { createdBy: "u1", name: "V" }, "vaults/vault0001/members/u1": { uid: "u1", role: "owner" }, + }), dos = fakeDOs(); + const r = await run(cloud, dos); + assert.equal(r.status, 200, JSON.stringify(r.body)); + const left = [...cloud.db.keys()].sort(); + assert.deepEqual(left, ["ip_reports/i2", "pairings/c2", "usage/u2", "users/u2", "waitlist/w2", "workspaces/team0000000000000000", "workspaces/team0000000000000000/members/u2"]); + assert.deepEqual(cloud.authDeleted, ["u1"]); + for (const w of ["graph:u1", "monitor:u1", "ingest:u1", "graph:solo0000000000000000", "monitor:solo0000000000000000", "ingest:solo0000000000000000", "vault:vault0001"]) assert.ok(dos.wiped.includes(w), w); + assert.ok(!dos.wiped.some((w) => w.includes("team0000"))); + }); + + test("a workspace they created that still has members blocks deletion, before anything is touched", async () => { + const cloud = fakeCloud({ + "users/u1": {}, "workspaces/acme0000000000000000": { createdBy: "u1", name: "Acme" }, + "workspaces/acme0000000000000000/members/u1": { uid: "u1", role: "owner" }, + "workspaces/acme0000000000000000/members/u3": { uid: "u3", role: "viewer" }, + "workspaces/acme0000000000000000/members/u4": { uid: "u4", role: "removed" }, + }), dos = fakeDOs(); + const r = await run(cloud, dos); + assert.equal(r.status, 409); + assert.ok(/"Acme"/.test(r.body.error)); + assert.deepEqual(r.body.blocking, [{ kind: "workspace", id: "acme0000000000000000", name: "Acme", members: 1 }]); + assert.ok(cloud.db.has("users/u1")); assert.equal(dos.wiped.length, 0); assert.equal(cloud.authDeleted.length, 0); + }); + + test("removed members don't count, and a second run finishes a half-done one", async () => { + const cloud = fakeCloud({ "workspaces/acme0000000000000000": { createdBy: "u1", name: "Acme" }, "workspaces/acme0000000000000000/members/u1": { uid: "u1", role: "owner" }, "workspaces/acme0000000000000000/members/u4": { uid: "u4", role: "removed" } }), dos = fakeDOs(); + assert.equal((await run(cloud, dos)).status, 200); + assert.equal(cloud.db.size, 0); + assert.equal((await run(cloud, dos)).status, 200); // users/u1 already gone: still ok + }); + + test("a failure stops before the sign-in is deleted", async () => { + const cloud = fakeCloud({ "users/u1": {} }), dos = fakeDOs(); + dos.env.MONITOR = { idFromName: (n) => n, get: () => ({ fetch: async () => ({ ok: false, status: 500 }) }) }; + const r = await run(cloud, dos); + assert.equal(r.status, 502); assert.equal(cloud.authDeleted.length, 0); assert.ok(cloud.db.has("users/u1")); + }); + + test("the DO wipe route answers only the internal path and header", async () => { + const calls = []; + const storage = { deleteAlarm: async () => calls.push("alarm"), deleteAll: async () => calls.push("all") }; + const mk = (path, h) => ({ url: "https://do" + path, headers: { get: (k) => h[k] } }); + assert.equal(await maybeWipe(mk("/", { "x-dn-wipe": "1" }), storage), null); + assert.equal(await maybeWipe(mk("/__wipe", {}), storage), null); + assert.equal(calls.length, 0); + const r = await maybeWipe(mk("/__wipe", { "x-dn-wipe": "1" }), storage); + assert.equal(r.status, 200); assert.deepEqual(calls, ["alarm", "all"]); + }); +}); diff --git a/unused-stuff/README.md b/unused-stuff/README.md index 99d6ee20..79466420 100644 --- a/unused-stuff/README.md +++ b/unused-stuff/README.md @@ -95,3 +95,9 @@ themed fiction rather than real tools: PROMETHEUS made up confidence and risk nu `Math.random()`, and Sentinel Eye showed a "TOP SECRET" banner over simulated SIGINT and aircraft. Their routes (`prometheus`, `sentineleye`) were removed from `public/js/auth.js` and `public/js/console-nav.js`. Files are kept at their original names under `js/`. + +## legal-terms-of-service-template.html + +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. diff --git a/public/legal/terms-of-service.html b/unused-stuff/legal-terms-of-service-template.html similarity index 100% rename from public/legal/terms-of-service.html rename to unused-stuff/legal-terms-of-service-template.html diff --git a/worker/account-delete.js b/worker/account-delete.js new file mode 100644 index 00000000..01f52afb --- /dev/null +++ b/worker/account-delete.js @@ -0,0 +1,171 @@ +// POST /api/account/delete: a signed-in user deletes their own Darknode account, with no +// email to anyone and no manual step. Uses the Worker's service account (FIREBASE_SA). +// +// Order matters, and every step can be retried (a second call finishes a half-done one): +// 1. refuse unless the sign-in is recent (auth_time within RECENT_S) and the body says +// {confirm: "DELETE"}; +// 2. refuse while the user founded a team workspace or vault that still has other members. +// Those members' work is not theirs to delete; they remove the members first; +// 3. wipe the Durable Objects of the personal workspace (graph, monitors and the free +// watch, API keys) and of every team workspace or vault they hold alone; +// 4. delete their Firestore records: users/{uid} with its subcollections, usage, +// deletionRequests, pairings, upgrade/tool requests, feedback, error reports, IP +// reports, the waitlist entry for their email, and their member docs elsewhere; +// 5. delete the Firebase Auth account last, so a failure earlier leaves a user who +// can still sign in and try again. +import { googleToken } from "./digest.js"; + +export const RECENT_S = 300; +const PAGE = 300; + +// Collections holding docs the user wrote, and the field that names them. +export const OWNED_BY_FIELD = [ + ["pairings", "uid"], ["upgradeRequests", "uid"], ["toolRequests", "uid"], + ["feedback", "uid"], ["errors", "uid"], ["ip_reports", "reporter_uid"], +]; +// Docs keyed by the user's uid. +export const KEYED_BY_UID = ["usage", "deletionRequests"]; + +export function recentEnough(claims, now = Math.floor(Date.now() / 1000)) { + const t = Number(claims && claims.auth_time); + return Number.isFinite(t) && t > 0 && now - t <= RECENT_S; +} + +// A thin Firestore REST client on one access token. +export function firestore(env, token, doFetch = fetch) { + const root = "https://firestore.googleapis.com/v1/projects/" + env.FIREBASE_PROJECT_ID + "/databases/(default)/documents"; + const H = { Authorization: "Bearer " + token, "Content-Type": "application/json" }; + const ok = async (r, what) => { if (!r.ok && r.status !== 404) throw new Error(what + " failed (HTTP " + r.status + ")"); return r; }; + const name = (path) => "projects/" + env.FIREBASE_PROJECT_ID + "/databases/(default)/documents/" + path; + const rel = (full) => String(full).split("/documents/")[1] || ""; + const val = (f) => (f ? f.stringValue ?? f.integerValue ?? f.booleanValue ?? null : null); + return { + rel, val, + async del(path) { await ok(await doFetch(root + "/" + path, { method: "DELETE", headers: H }), "Delete " + path); }, + async get(path) { + const r = await ok(await doFetch(root + "/" + path, { headers: H }), "Read " + path); + return r.status === 404 ? null : r.json(); + }, + // every doc path in a collection + async list(path) { + const out = []; let next = ""; + for (let i = 0; i < 100; i++) { + const r = await ok(await doFetch(root + "/" + path + "?pageSize=" + PAGE + (next ? "&pageToken=" + encodeURIComponent(next) : ""), { headers: H }), "List " + path); + if (r.status === 404) break; + const d = await r.json().catch(() => ({})); + for (const doc of d.documents || []) out.push({ path: rel(doc.name), fields: doc.fields || {} }); + next = d.nextPageToken || ""; if (!next) break; + } + return out; + }, + async subcollections(path) { + const r = await ok(await doFetch(root + "/" + path + ":listCollectionIds", { method: "POST", headers: H, body: JSON.stringify({ pageSize: 100 }) }), "List subcollections of " + path); + if (r.status === 404) return []; + const d = await r.json().catch(() => ({})); + return d.collectionIds || []; + }, + // docs where field == value; group = search every collection with that id + async where(collectionId, field, value, group = false) { + const body = { structuredQuery: { from: [{ collectionId, allDescendants: group }], where: { fieldFilter: { field: { fieldPath: field }, op: "EQUAL", value: { stringValue: value } } }, limit: 1000 } }; + const r = await ok(await doFetch(root + ":runQuery", { method: "POST", headers: H, body: JSON.stringify(body) }), "Query " + collectionId); + const rows = await r.json().catch(() => []); + return (Array.isArray(rows) ? rows : []).filter((x) => x && x.document).map((x) => ({ path: rel(x.document.name), fields: x.document.fields || {} })); + }, + name, + }; +} + +// Delete a doc and everything under it (one level of subcollections and their own). +export async function deleteTree(fs, path, depth = 0) { + if (depth < 3) { + for (const c of await fs.subcollections(path)) { + for (const d of await fs.list(path + "/" + c)) await deleteTree(fs, d.path, depth + 1); + } + } + await fs.del(path); +} + +// Where the user is a member: [{ kind: "workspaces"|"vaults", id, role, founder, others }] +export async function memberships(fs, uid) { + const rows = await fs.where("members", "uid", uid, true); + const out = []; + for (const m of rows) { + const [kind, id] = m.path.split("/"); + if ((kind !== "workspaces" && kind !== "vaults") || !id) continue; + const role = fs.val(m.fields.role) || ""; + if (role === "removed") { out.push({ kind, id, role, founder: false, others: 0, name: "", memberPath: m.path }); continue; } + const top = await fs.get(kind + "/" + id); + const f = (top && top.fields) || {}; + const founder = fs.val(f.createdBy) === uid; + const all = await fs.list(kind + "/" + id + "/members"); + const others = all.filter((x) => fs.val(x.fields.uid) !== uid && fs.val(x.fields.role) !== "removed").length; + out.push({ kind, id, role, founder, others, name: fs.val(f.name) || id, memberPath: m.path }); + } + return out; +} + +// Wipe one Durable Object's storage through its internal /__wipe route. +async function wipeDO(ns, id) { + if (!ns) return; + const r = await ns.get(ns.idFromName(id)).fetch("https://do/__wipe", { method: "POST", headers: { "x-dn-wipe": "1" } }); + if (!r.ok) throw new Error("Could not clear stored data (HTTP " + r.status + ")"); +} + +// The /__wipe route each DO answers. Only the Worker builds that URL: every user-facing +// forward uses a fixed path ("/" or "/findings"), so outside input never reaches it. +export async function maybeWipe(request, storage) { + if (new URL(request.url).pathname !== "/__wipe" || request.headers.get("x-dn-wipe") !== "1") return null; + try { await storage.deleteAlarm(); } catch (_) {} + await storage.deleteAll(); + return new Response('{"ok":true}', { headers: { "Content-Type": "application/json" } }); +} + +export async function handleAccountDelete(request, env, json, principal, opts = {}) { + if (request.method !== "POST") return json({ error: "POST only" }, 405); + if (!env.FIREBASE_PROJECT_ID) return json({ error: "FIREBASE_PROJECT_ID is not set" }, 503); + const uid = principal && principal.uid; + if (!uid || principal.kind !== "user") return json({ error: "Sign in required" }, 401); + let body = {}; try { body = await request.json(); } catch (_) {} + if (!body || body.confirm !== "DELETE") return json({ error: 'Send {"confirm":"DELETE"} to delete the account.' }, 400); + if (!recentEnough(principal.claims, opts.now)) return json({ error: "Sign in again to confirm it's you, then delete.", reauth: true }, 401); + + const doFetch = opts.fetch || fetch; + let token; + try { token = await (opts.token || googleToken)(env); } + catch (e) { return json({ error: "Server credentials unavailable: " + e.message }, 503); } + const fs = firestore(env, token, doFetch); + + try { + const mine = await memberships(fs, uid); + const blocking = mine.filter((m) => m.founder && m.others > 0); + if (blocking.length) { + return json({ + error: "You created " + blocking.map((b) => '"' + b.name + '"').join(", ") + ", which still " + (blocking.length > 1 ? "have" : "has") + " other members. Remove them first, then delete your account.", + blocking: blocking.map((b) => ({ kind: b.kind === "vaults" ? "vault" : "workspace", id: b.id, name: b.name, members: b.others })), + }, 409); + } + // personal workspace (wid === uid) and every space they hold alone + await wipeDO(env.GRAPH, uid); await wipeDO(env.MONITOR, uid); await wipeDO(env.INGEST, uid); + for (const m of mine) { + const alone = m.role !== "removed" && m.others === 0 && (m.founder || m.role === "owner"); + if (alone && m.kind === "workspaces") { await wipeDO(env.GRAPH, m.id); await wipeDO(env.MONITOR, m.id); await wipeDO(env.INGEST, m.id); await deleteTree(fs, "workspaces/" + m.id); } + else if (alone && m.kind === "vaults") { await wipeDO(env.VAULT, m.id); await deleteTree(fs, "vaults/" + m.id); } + else await fs.del(m.memberPath); + } + for (const [c, field] of OWNED_BY_FIELD) for (const d of await fs.where(c, field, uid)) await fs.del(d.path); + if (principal.email) for (const d of await fs.where("waitlist", "email", principal.email)) await fs.del(d.path); + for (const c of KEYED_BY_UID) await fs.del(c + "/" + uid); + await deleteTree(fs, "users/" + uid); + + const r = await doFetch("https://identitytoolkit.googleapis.com/v1/projects/" + env.FIREBASE_PROJECT_ID + "/accounts:delete", { + method: "POST", headers: { Authorization: "Bearer " + token, "Content-Type": "application/json" }, body: JSON.stringify({ localId: uid }), + }); + if (!r.ok) { + const d = await r.json().catch(() => ({})); + if (!(d && d.error && /USER_NOT_FOUND/.test(d.error.message || ""))) throw new Error("Deleting the sign-in failed (HTTP " + r.status + ")"); + } + } catch (e) { + return json({ error: (e && e.message ? e.message : "Deletion failed") + ". Part of the account may already be deleted; try again to finish." }, 502); + } + return json({ ok: true }); +} diff --git a/worker/auth.js b/worker/auth.js index 4e1a82a6..7a3b5f1c 100644 --- a/worker/auth.js +++ b/worker/auth.js @@ -30,6 +30,7 @@ export const ROUTES = [ { id: "watch-stop", path: "/api/watch/stop", methods: ["GET", "POST"], auth: "none" }, { id: "digest", prefix: "/api/digest/", auth: "user" }, { id: "usage", path: "/api/v1/usage", methods: ["POST"], auth: "user" }, + { id: "account-delete", path: "/api/account/delete", methods: ["POST"], auth: "user" }, { id: "admin-users", path: "/api/admin/users", methods: ["GET"], auth: "user", role: "admin" }, { id: "ingest", prefix: "/api/v1/ingest/", auth: "key", scope: "ingest:write" }, { id: "findings", prefix: "/api/v1/findings/", auth: "key", scope: "findings:read" }, diff --git a/worker/graph.js b/worker/graph.js index 560a3d2a..6c205afe 100644 --- a/worker/graph.js +++ b/worker/graph.js @@ -25,6 +25,7 @@ import { featureDenied } from "./plan.js"; import { workspaceTier } from "./plan-share.js"; import { readCapped } from "./body-cap.js"; import { chainAppend, chainVerify, GENESIS, pad } from "./audit-chain.js"; +import { maybeWipe } from "./account-delete.js"; // The audit chain is never trimmed: "verify from genesis" must stay meaningful. It only // grows on a real change (an idle sync that writes nothing appends nothing), and each @@ -214,6 +215,7 @@ export class GraphDO { } async fetch(request) { + const wiped = await maybeWipe(request, this.storage); if (wiped) return wiped; // account deletion (worker/account-delete.js) const reply = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } }); const uid = request.headers.get("x-graph-uid"); if (!uid) return reply({ error: "forbidden" }, 403); diff --git a/worker/ingest.js b/worker/ingest.js index 29706905..888fd3cb 100644 --- a/worker/ingest.js +++ b/worker/ingest.js @@ -11,6 +11,7 @@ import { resolveWorkspaceRole, canDo } from "./workspace.js"; import { featureDenied } from "./plan.js"; import { workspaceTier, liveTier } from "./plan-share.js"; import { readCapped } from "./body-cap.js"; +import { maybeWipe } from "./account-delete.js"; const WID = /^[A-Za-z0-9_-]{1,128}$/; const QUEUE_CAP = 2000; // max findings held awaiting a browser drain @@ -84,6 +85,7 @@ export class IngestDO { } async fetch(request) { + const wiped = await maybeWipe(request, this.storage); if (wiped) return wiped; // account deletion (worker/account-delete.js) const reply = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } }); const mgmtUid = request.headers.get("x-ing-uid"); const apiKey = request.headers.get("x-ing-key"); diff --git a/worker/monitor.js b/worker/monitor.js index 8d25bc29..7d1820b9 100644 --- a/worker/monitor.js +++ b/worker/monitor.js @@ -10,6 +10,7 @@ // clocks) are kept here too, one storage key each ("dl:", CRA cases "cra:"), and // alerted when they start and when a quarter of their time is left (public/js/core/deadlines.js). import { runCheck, cvesFromEntities, hostOnly } from "./checks.js"; +import { maybeWipe } from "./account-delete.js"; import { diffFindings, diffToEvents, shouldAlert, defaultAlertRules, inQuietHours } from "./monitor-core.js"; import { buildGraphWrite } from "./monitor-graph.js"; import { deliver, RETRY_BACKOFF_MS } from "./notify.js"; @@ -458,6 +459,7 @@ export class MonitorDO { // ---- HTTP interface for the Deck (via handleMonitor) ---- async fetch(request) { + const wiped = await maybeWipe(request, this.storage); if (wiped) return wiped; // account deletion (worker/account-delete.js) const reply = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } }); if (!request.headers.get("x-mon-uid")) return reply({ error: "forbidden" }, 403); const role = request.headers.get("x-mon-role") || "viewer"; diff --git a/worker/vault.js b/worker/vault.js index 6500b544..b337be1d 100644 --- a/worker/vault.js +++ b/worker/vault.js @@ -19,6 +19,7 @@ import { Ledger, toCents, fmtCents, hashStr, canon } from "../public/js/vault/le import { readCapped } from "./body-cap.js"; import { requireUser } from "./auth.js"; import { ROLES, canDo } from "../public/js/vault/roles.js"; +import { maybeWipe } from "./account-delete.js"; export { ROLES, canDo }; @@ -215,6 +216,7 @@ export class VaultDO { } async fetch(request) { + const wiped = await maybeWipe(request, this.storage); if (wiped) return wiped; // account deletion (worker/account-delete.js) const actor = { uid: request.headers.get("x-vault-uid") || "", role: request.headers.get("x-vault-role") || "" }; const reply = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } }); if (!actor.uid || !ROLES.includes(actor.role)) return reply({ error: "forbidden" }, 403); diff --git a/worker/worker.js b/worker/worker.js index 5d1ded83..d221208e 100644 --- a/worker/worker.js +++ b/worker/worker.js @@ -30,6 +30,7 @@ import { GEMINI_MODELS, CLAUDE_PLAN, userTier, planDenied } from "./plan.js"; import { chargeQuota, refundQuota, quotaMessage } from "./quota.js"; import { handleDigest, handleUnsubscribe, runDigest } from "./digest.js"; import { handleAdminUsers } from "./admin-users.js"; +import { handleAccountDelete } from "./account-delete.js"; import { handleUsage } from "./usage.js"; export { VaultDO } from "./vault.js"; export { GraphDO } from "./graph.js"; @@ -822,6 +823,7 @@ async function route(request, env, rid) { case "digest": return handleDigest(request, env, rest, json, principal); case "admin-users": return handleAdminUsers(env, json); case "usage": return handleUsage(request, env, json, principal); + case "account-delete": return handleAccountDelete(request, env, json, principal); case "ingest": return handleIngest(request, env, rest, json, "ingest"); case "findings": return handleIngest(request, env, rest, json, "findings"); }