Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
383 changes: 57 additions & 326 deletions functions/package-lock.json

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions functions/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,9 @@
"@google-cloud/firestore": "^9.3.1",
"firebase-admin": "^14.5.0",
"firebase-functions": "^7.4.0"
},
"overrides": {
"glob": "^14.0.2",
"fast-xml-parser": "^5.12.0"
}
}
36 changes: 36 additions & 0 deletions public/js/admin.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,12 @@ export async function renderAdmin(main, user) {
<p class="muted" style="font-size:.82rem;margin:0 0 8px">Requests from the Deck's Plans page. Granting sets the user's plan tier.</p>
<div id="upReqList"><p class="muted">Loading requests…</p></div>
</div>
<div class="panel">
<div class="panel-h"><h2 class="pg-h2" style="margin:0">Account deletion requests</h2>
<button class="btn ghost sm" id="delReqRefresh">Refresh</button></div>
<p class="muted" style="font-size:.82rem;margin:0 0 8px">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.</p>
<div id="delReqList"><p class="muted">Loading requests…</p></div>
</div>
<div class="panel">
<div class="panel-h"><h2 class="pg-h2" style="margin:0">Feedback &amp; bug reports</h2>
<button class="btn ghost sm" id="fbRefresh">Refresh</button></div>
Expand Down Expand Up @@ -483,6 +489,36 @@ export async function renderAdmin(main, user) {
};
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 = `<p class="muted">No pending deletion requests.</p>`; return; }
host.innerHTML = items.map((x) => `
<div class="fb-row" data-uid="${esc(x.uid)}" data-email="${esc(x.email || "")}">
<div class="fb-row-h"><span class="muted">${esc(x.email || x.uid)}</span>
<span style="flex:1"></span><span class="muted" style="font-size:.72rem">${x.requestedAt ? esc(new Date(x.requestedAt).toLocaleString()) : ""}</span>
<button class="btn danger sm dr-del">Delete account</button></div>
</div>`).join("");
} catch (e) { host.innerHTML = `<p class="adm-err">Couldn't load deletion requests: ${esc(e.message)}</p>`; }
}
$("#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;
Expand Down
18 changes: 18 additions & 0 deletions public/js/deck-ui.js
Original file line number Diff line number Diff line change
Expand Up @@ -4544,6 +4544,10 @@ export function renderDeck(host, opts) {

<div class="dk-ovp">
<h2>${IC.folder} Data</h2>
${noAccount ? "" : `<div class="dk-setrow">
<div class="m"><div class="t">Your account data</div><div class="s">Everything Darknode's servers hold about you: account, settings, notifications, requests you sent, workspaces, monitors and API keys (secrets left out), as one JSON file.</div></div>
<button class="dk-settog" id="dkSetAcctExp">Download</button>
</div>`}
<div class="dk-setrow">
<div class="m"><div class="t">Deck state</div><div class="s">Connections, pinned tools and notes (no API keys), as a JSON file you can re-import.</div></div>
<span style="display:flex;gap:8px;flex:none"><button class="dk-settog" id="dkSetExport">Export</button><button class="dk-settog" id="dkSetImport">Import</button></span>
Expand Down Expand Up @@ -4599,6 +4603,20 @@ export function renderDeck(host, opts) {
el.querySelector("#dkSetPlans").onclick = () => go("plans");
const setSu = el.querySelector("#dkSetSignup"); if (setSu) setSu.onclick = toSignup;
el.querySelector("#dkSetExport").onclick = () => exportDeckState();
const acctExp = el.querySelector("#dkSetAcctExp");
if (acctExp) acctExp.onclick = async () => {
acctExp.disabled = true; const was = acctExp.textContent; acctExp.textContent = "Preparing…";
try {
const { api } = await import("/js/core/api.js");
const data = await api("/api/account/export");
const a = document.createElement("a");
a.href = URL.createObjectURL(new Blob([JSON.stringify(data, null, 2)], { type: "application/json" }));
a.download = "darknode-account-" + new Date().toISOString().slice(0, 10) + ".json";
document.body.appendChild(a); a.click(); setTimeout(() => { URL.revokeObjectURL(a.href); a.remove(); }, 1000);
toast("Account data downloaded");
} catch (e) { toast((e && e.message) || "Couldn't export your account data.", "error"); }
finally { acctExp.disabled = false; acctExp.textContent = was; }
};
el.querySelector("#dkSetImport").onclick = () => importDeckState();
const syncPlanBtn = el.querySelector("#dkSetSyncPlan");
if (syncPlanBtn) syncPlanBtn.onclick = () => { toast("Cloud sync is part of the Pro plan"); go("plans"); };
Expand Down
2 changes: 1 addition & 1 deletion public/js/legal.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

60 changes: 56 additions & 4 deletions test/worker/account-delete.test.mjs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// 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 { handleAccountDelete, handleAccountExport, handleAdminDeletions, recentEnough, maybeWipe, plain, RECENT_S } from "../../worker/account-delete.js";
import { matchRoute, authorize } from "../../worker/auth.js";

const json = (body, status = 200) => ({ status, body });
Expand All @@ -16,7 +16,8 @@ function fakeCloud(docs) {
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.endsWith("/accounts:delete")) { if (cloud.authFails) return res(500, {}); authDeleted.push(JSON.parse(init.body).localId); return res(200, {}); }
if (url.endsWith("/accounts:lookup")) return res(200, { users: [{ localId: "u1", email: "test@darknode.ai", emailVerified: true, providerUserInfo: [{ providerId: "password" }], createdAt: "1793404800000" }] });
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) => {
Expand All @@ -40,12 +41,15 @@ function fakeCloud(docs) {
}
return db.has(path) ? res(200, doc(path)) : res(404, {});
};
return { db, fetch, authDeleted };
const cloud = { db, fetch, authDeleted, authFails: false };
return cloud;
}

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 }; } }) });
const ns = (kind) => ({ idFromName: (n) => n, get: (id) => ({ fetch: async (u, init) => {
if (u === "https://do/") { const op = JSON.parse(init.body).op; return { ok: true, status: 200, json: async () => kind === "monitor" ? (op === "list" ? { monitors: [{ id: "m1", target: "example.com", wid: id }], history: [] } : { deadlines: [] }) : { keys: [{ keyId: "k1", prefix: "dk_ab", scopes: ["ingest:write"] }] } }; }
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") } };
}

Expand Down Expand Up @@ -143,4 +147,52 @@ group("account-delete", () => {
const r = await maybeWipe(mk("/__wipe", { "x-dn-wipe": "1" }), storage);
assert.equal(r.status, 200); assert.deepEqual(calls, ["alarm", "all"]);
});

test("export: the caller's own records, secrets redacted, other people's left out", async () => {
const cloud = fakeCloud({
"users/u1": { email: "test@darknode.ai", tier: "free" }, "users/u1/notifications/n1": { text: "hi" },
"users/u2": { email: "other@darknode.ai" }, "pairings/c1": { uid: "u1", apiKey: "dk_secret" }, "pairings/c2": { uid: "u2" },
"feedback/f1": { uid: "u1", message: "nice" }, "waitlist/w1": { email: "test@darknode.ai" },
"workspaces/team0000000000000000": { createdBy: "u2", name: "Team" }, "workspaces/team0000000000000000/members/u1": { uid: "u1", role: "analyst" },
}), dos = fakeDOs();
const r = await handleAccountExport({ method: "GET" }, dos.env, json, me(), { fetch: cloud.fetch, token: async () => "t" });
assert.equal(r.status, 200, JSON.stringify(r.body));
const b = r.body;
assert.equal(b.account.email, "test@darknode.ai"); assert.deepEqual(b.account.signInMethods, ["password"]);
assert.equal(b.profile.tier, "free");
assert.deepEqual(b.profileCollections.notifications, [{ id: "n1", text: "hi" }]);
assert.deepEqual(b.records.pairings, [{ id: "c1", uid: "u1", apiKey: "[redacted]" }]);
assert.equal(b.records.feedback.length, 1); assert.equal(b.records.waitlist.length, 1);
assert.deepEqual(b.memberships, [{ kind: "workspace", id: "team0000000000000000", name: "Team", role: "analyst", createdByYou: false }]);
assert.equal(b.personalWorkspace.monitors[0].target, "example.com"); assert.equal(b.personalWorkspace.apiKeys[0].keyId, "k1");
assert.ok(!JSON.stringify(b).includes("other@darknode.ai"));
assert.equal(cloud.db.size, 9); // nothing was changed
});

test("export decodes every Firestore value type", () => {
assert.deepEqual(plain({ mapValue: { fields: { a: { integerValue: "3" }, b: { arrayValue: { values: [{ booleanValue: true }, { nullValue: null }] } }, t: { timestampValue: "2026-11-27T00:00:00Z" } } } }),
{ a: 3, b: [true, null], t: "2026-11-27T00:00:00Z" });
});

test("admin deletions: owner only; lists requests; deletes only accounts that asked", async () => {
const route = matchRoute("/api/admin/deletions", "POST").route;
assert.equal(authorize(route, { kind: "user", claims: {} }).status, 403);
assert.equal(authorize(route, { kind: "user", claims: { admin: true } }), null);
const cloud = fakeCloud({ "deletionRequests/u1": { uid: "u1", email: "test@darknode.ai" }, "users/u1": {}, "users/u2": {}, "waitlist/w1": { email: "test@darknode.ai" } }), dos = fakeDOs();
const o = { fetch: cloud.fetch, token: async () => "t" };
const list = await handleAdminDeletions({ method: "GET" }, dos.env, json, o);
assert.deepEqual(list.body.requests.map((x) => [x.uid, x.email]), [["u1", "test@darknode.ai"]]);
const no = await handleAdminDeletions(req({ uid: "u2" }), dos.env, json, o);
assert.equal(no.status, 404); assert.ok(cloud.db.has("users/u2"));
const yes = await handleAdminDeletions(req({ uid: "u1" }), dos.env, json, o);
assert.equal(yes.status, 200);
assert.deepEqual([...cloud.db.keys()], ["users/u2"]); assert.deepEqual(cloud.authDeleted, ["u1"]);
});

test("admin deletions: if the sign-in delete fails the request stays, so it can be retried", async () => {
const cloud = fakeCloud({ "deletionRequests/u1": { uid: "u1", email: "" }, "users/u1": {} }), dos = fakeDOs();
cloud.authFails = true;
const r = await handleAdminDeletions(req({ uid: "u1" }), dos.env, json, { fetch: cloud.fetch, token: async () => "t" });
assert.equal(r.status, 502); assert.ok(cloud.db.has("deletionRequests/u1"));
});
});
Loading
Loading