From 13c9b8fd04a066ffb25e076471e5130407005de6 Mon Sep 17 00:00:00 2001 From: Darknode-Official Date: Sun, 29 Nov 2026 12:44:52 -0800 Subject: [PATCH] One reminder email for people who came once A daily Worker cron (15:00 UTC, production only, gated by WINBACK_CRON) emails, once per account ever, people who used Darknode on a single day: verified, signed up 2 to 45 days ago, not seen for 2 days, no monitor, digest off, not banned or the owner. The email points at the daily domain watch and checks their own domain when the address is on one. Each send is recorded before it goes out; a signed link turns reminders off. Owner page: a Reminder email panel (sent, came back after it, turned off, next run, send me a test) and a per-person line. Deleting an account now also removes its digest and reminder records (the digest record was left behind before). Privacy, TOS Section 14 and the changelog describe the email. --- public/js/deck/owner-stats.js | 15 +++ public/js/deck/owner.js | 49 +++++++- public/js/docs.js | 3 +- public/js/legal.js | 1 + test/deck/owner-stats.test.mjs | 11 +- test/worker/winback.test.mjs | 158 +++++++++++++++++++++++++ worker/account-delete.js | 4 +- worker/admin-users.js | 21 ++-- worker/auth.js | 3 + worker/winback.js | 206 +++++++++++++++++++++++++++++++++ worker/worker.js | 14 ++- worker/wrangler.toml | 7 +- 12 files changed, 470 insertions(+), 22 deletions(-) create mode 100644 test/worker/winback.test.mjs create mode 100644 worker/winback.js diff --git a/public/js/deck/owner-stats.js b/public/js/deck/owner-stats.js index d5485102..33b1c87c 100644 --- a/public/js/deck/owner-stats.js +++ b/public/js/deck/owner-stats.js @@ -100,3 +100,18 @@ export function ago(ms, now = Date.now()) { if (s < 30 * 86400) return Math.round(s / 86400) + " d ago"; return new Date(ms).toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" }); } + +// The one-time reminder email (worker/winback.js): sent = [{ uid, sentAt, off }] from +// /api/admin/winback. -> { sent, off, cameBack }: cameBack = used Darknode after it arrived. +export function winbackStats(users = [], sent = [], now = Date.now()) { + const by = new Map(users.map((u) => [u.uid, u])); + let n = 0, off = 0, back = 0; + for (const w of sent) { + if (w.off) off++; + if (!w.sentAt) continue; + n++; + const u = by.get(w.uid); + if (u && personOf(u, now).last > w.sentAt) back++; + } + return { sent: n, off, cameBack: back }; +} diff --git a/public/js/deck/owner.js b/public/js/deck/owner.js index 8404b8fa..ee635f67 100644 --- a/public/js/deck/owner.js +++ b/public/js/deck/owner.js @@ -11,9 +11,9 @@ 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"; +import { retention, peopleRows, tsMs, isOwnerRow, ago, FILTERS, winbackStats } 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 S = { el: null, ctx: null, seq: 0, users: [], usage: new Map(), banned: [], filter: "all", q: "", open: "", inbox: null, ann: null, wb: 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)); @@ -118,6 +118,7 @@ export function mountOwner(el, ctx) {
Loading…
+
`; el.querySelector("#ownReload").onclick = () => load(); @@ -132,9 +133,9 @@ async function load() { if (!live()) return; S.users = users; S.usage = usage; S.banned = banned; S.ann = ann; paintTop(); paintPeople(); paintSite(); - const inbox = await loadInbox(); + const [inbox, wb] = await Promise.all([loadInbox(), loadWb()]); if (!live()) return; - S.inbox = inbox; paintInbox(); + S.inbox = inbox; S.wb = wb; paintInbox(); paintWb(); if (S.open) paintPeople(); } // users/{uid} docs plus the Auth accounts that never got one (an email sign-up that never verified) @@ -163,6 +164,9 @@ async function loadBanned() { async function loadAnn() { try { const s = await getDoc(doc(db, "announcements", "current")); return s.exists() ? s.data() : {}; } catch (_) { return {}; } } +async function loadWb() { + try { return await api("/api/admin/winback"); } catch (e) { return { error: e.message || String(e) }; } +} async function loadInbox() { const out = { upgrades: null, deletions: null, feedback: null, errors: null, fail: {} }; const byTs = (a, b) => tsMs(b.ts) - tsMs(a.ts); @@ -238,7 +242,7 @@ function detailHtml(u, p, owner, banned, uses, now) { ${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("")} + ${wbLine(u.uid, now)}${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}
@@ -247,6 +251,13 @@ function detailHtml(u, p, owner, banned, uses, now) { `; } +function wbLine(uid, now) { + const w = S.wb && (S.wb.sent || []).find((x) => x.uid === uid); + if (!w) return ""; + const v = (w.sentAt ? "Sent " + ago(w.sentAt, now) : "Not sent") + (w.off ? ", turned off" : ""); + return `
Reminder email${E(v)}
`; +} + function itemsHtml(list, fail, empty, row) { if (fail) return `

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

`; if (!list) return `

Loading…

`; @@ -282,6 +293,28 @@ function paintInbox() { ${ib.errors && ib.errors.length > 20 ? `

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

` : ""}`; } +// The one-time reminder email to people who came once (worker/winback.js). +function paintWb() { + const host = S.el.querySelector("#ownWb"); if (!host) return; + const w = S.wb; + const head = (badge) => `

Reminder email ${badge}

+

One email, once per person, to people who used Darknode on a single day and have no watch or weekly summary: it asks them to set up the daily domain watch. Sent daily at 15:00 UTC to at most 25 people who joined 2 to 45 days ago.

`; + if (!w) { host.innerHTML = head("") + '

Loading…

'; return; } + if (w.error) { host.innerHTML = head("") + `

Couldn't load: ${E(w.error)}

`; return; } + const st = winbackStats(S.users, w.sent || []); + const email = new Map(S.users.map((u) => [u.uid, u.email || u.uid])); + const next = (w.next || []).map((uid) => email.get(uid) || uid); + host.innerHTML = head(`${w.on ? "On" : "Off on this server"}`) + ` +
+
Sent${st.sent}
+
Came back after it${st.sent ? st.cameBack + " (" + pct(st.cameBack, st.sent) + "%)" : "-"}
+
Turned reminders off${st.off}
+
Next run${next.length ? next.length + (next.length === 1 ? " person" : " people") : "No one"}
+
+ ${next.length ? `

${next.map(E).join(", ")}

` : ""} +
`; +} + function paintSite() { const host = S.el.querySelector("#ownSite"); if (!host) return; const a = S.ann || {}; @@ -333,6 +366,12 @@ async function doAct(act, btn) { 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 === "wbtest") { + btn.disabled = true; + try { const r = await api("/api/admin/winback", { method: "POST", body: { op: "preview" } }); toast("Test sent to " + ((r && r.to) || "your address"), "success"); } + finally { btn.disabled = false; } + 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; diff --git a/public/js/docs.js b/public/js/docs.js index 0c2f8d26..09a5a112 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. Getting started on the Overview now takes you through checking your domain, having Darknode watch it and turning on the Monday summary email."], + ["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. People who used Darknode on a single day and set up nothing get one reminder email, once, about the domain watch, with a link to turn reminders off."], ["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."], @@ -157,6 +157,7 @@ node darknode.js nexus init # optional: scaffold .nexus/ project
  • 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.
  • +
  • One reminder email. If you used Darknode on a single day and set up no watch or digest, we may send one email, once, between 2 and 45 days after you sign up, explaining how to have Darknode watch your domain. It goes to your verified account email through Resend, and we record when it was sent. It has a link to turn reminders off.
  • 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 or registration's expiry date, the domain's SPF and DMARC policy, and which security headers its website sends, so a later change can be named; a website watch keeps the URL of an exposed .git or .env file, never its contents) 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.
  • Deadlines. We store the deadlines your monitors find (what is due and when, its status, and the reason and account when someone marks one done or dismisses it), the two opt-ins under Deadlines, and the assets you mark as shipped in a product (their names and Security Graph ids). For a Cyber Resilience Act case we also store the CVE, the matched assets, the CISA KEV date, the times you enter for becoming aware and for the fix, the Member States and the measures you type. Deadline alerts go to the channels of the monitor that found them; to apply the limit of 20 Cyber Resilience Act alert emails a day we keep a count per account for the current UTC day. Closed certificate and BOD 22-01 deadlines are deleted after 180 days; Cyber Resilience Act cases are kept as your record until you ask us to delete them. Darknode does not send any of this to a CSIRT, ENISA or anyone else.
  • AI assistant. Questions to the built-in assistant pass through our edge proxy to the model provider and are not logged or stored by us. To apply the daily message limits we keep a count of messages for the current UTC day, per account (or per IP address when you are not signed in); the count holds no message content and is cleared the next day.
  • diff --git a/public/js/legal.js b/public/js/legal.js index 0bd8e4aa..3456435d 100644 --- a/public/js/legal.js +++ b/public/js/legal.js @@ -78,6 +78,7 @@ export const TOS_HTML = `
  • 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.
  • Weekly email digest (optional): only if you turn it on, we store your watched domains and latest certificate-check results to build a weekly email, sent to your account email through our email provider (Resend). You can turn it off at any time in Settings or from the unsubscribe link.
  • +
  • One reminder email: if you used the service on a single day and set up no watch or digest, we may send one email, once, to your verified account email (through Resend) explaining how to set up a watch, and we record when it was sent. Each one has a link to turn reminders off.
  • Monitors and domain watch (optional): only if you set up a monitor, including the Free plan's one-domain watch, we store the domains it watches, its settings and latest results, and a log of its runs and alert deliveries, so it can run on a schedule and report what changed. Email alerts are sent only to your own verified account email, through our email provider (Resend), at most 5 a day. You can turn a watch off under Monitors or from the stop link in any alert email.
  • Deadlines (optional): the deadlines your monitors find, the opt-ins you set, the assets you mark as shipped in a product, and for a Cyber Resilience Act case the times, Member States and measures you enter. Nothing is sent to a CSIRT, ENISA or anyone else.
  • Product usage: when you are signed in to the Nexus terminal agent or the Darknode desktop app, it tells us about every 6 hours that your account uses it, with the app version and operating system; the desktop app also reports how many virtual machines its VM manager holds and when one last started (never their names, disks or contents). We use this to know which products and versions to support. Turn it off with /shareusage off in Nexus or Settings > Share app usage in the desktop app.
  • diff --git a/test/deck/owner-stats.test.mjs b/test/deck/owner-stats.test.mjs index ededaabe..eb55eba1 100644 --- a/test/deck/owner-stats.test.mjs +++ b/test/deck/owner-stats.test.mjs @@ -2,7 +2,7 @@ // (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"; +import { personOf, retention, peopleRows, weekStart, tsMs, ago, winbackStats } from "../../public/js/deck/owner-stats.js"; const NOW = Date.parse("2026-11-29T12:00:00Z"); // a Sunday const D = 864e5; @@ -129,3 +129,12 @@ group("deck/owner-stats: users table", () => { assert.equal(ago(NOW - 3 * D, NOW), "3 d ago"); }); }); + +group("owner-stats/winbackStats", () => { + test("counts sends, opt-outs and who came back after the email", () => { + const sentAt = NOW - 5 * D; + const users = [{ uid: "a", createdAt: NOW - 20 * D, lastSeen: NOW - D }, { uid: "b", createdAt: NOW - 20 * D, lastSeen: NOW - 19 * D }]; + const r = winbackStats(users, [{ uid: "a", sentAt }, { uid: "b", sentAt, off: true }, { uid: "gone", sentAt }, { uid: "c", off: true }], NOW); + assert.deepEqual(r, { sent: 3, off: 2, cameBack: 1 }); + }); +}); diff --git a/test/worker/winback.test.mjs b/test/worker/winback.test.mjs new file mode 100644 index 00000000..81c8db3c --- /dev/null +++ b/test/worker/winback.test.mjs @@ -0,0 +1,158 @@ +// Unit tests for worker/winback.js — the one-time reminder email for people who came once. +import { test, group, assert } from "../harness.mjs"; +import { pickWinBack, buildWinBack, ownDomain, MAX_PER_RUN, runWinBack, handleWinBackStop } from "../../worker/winback.js"; +import { matchRoute, authorize } from "../../worker/auth.js"; +import { cronJob, WINBACK_CRON } from "../../worker/worker.js"; +import { KEYED_BY_UID } from "../../worker/account-delete.js"; + +const NOW = Date.parse("2026-11-29T15:00:00Z"); +const DAY = 86400000; +const acct = (uid, o = {}) => ({ uid, email: uid + "@example.com", emailVerified: true, disabled: false, createdAt: NOW - 10 * DAY, lastLoginAt: NOW - 10 * DAY, ...o }); +const pick = (accounts, o = {}) => pickWinBack({ accounts, now: NOW, ...o }).map((c) => c.uid); + +group("winback/pickWinBack", () => { + test("someone who came once, 10 days ago, gets it", () => { + assert.deepEqual(pick([acct("a")]), ["a"]); + }); + test("unverified, disabled or address-less accounts do not", () => { + assert.deepEqual(pick([acct("a", { emailVerified: false }), acct("b", { disabled: true }), acct("c", { email: "" })]), []); + }); + test("only between 2 and 45 days after sign-up", () => { + assert.deepEqual(pick([acct("new", { createdAt: NOW - DAY, lastLoginAt: NOW - DAY }), acct("old", { createdAt: NOW - 50 * DAY, lastLoginAt: NOW - 50 * DAY })]), []); + }); + test("anyone who came back on another day does not", () => { + const profiles = new Map([["b", { recentDays: ["2026-11-19", "2026-11-21"], activeDays: 2 }]]); + assert.deepEqual(pick([acct("a", { lastLoginAt: NOW - 5 * DAY }), acct("b")], { profiles }), []); + }); + test("seen in the last 2 days does not, even if it is still their first day", () => { + assert.deepEqual(pick([acct("a", { createdAt: NOW - 3 * DAY, lastLoginAt: NOW - 3 * DAY + 3600e3 })], { profiles: new Map([["a", { lastSeen: NOW - DAY }]]) }), []); + }); + test("already sent, digest on, banned or the owner: skipped", () => { + const r = pick([acct("s"), acct("d"), acct("b"), acct("o")], { + sent: new Map([["s", { sentAt: NOW - DAY }]]), digestOn: new Set(["d"]), banned: ["B@EXAMPLE.COM"], profiles: new Map([["o", { admin: true }]]), + }); + assert.deepEqual(r, []); + }); + test("oldest sign-up first, capped per run", () => { + const many = Array.from({ length: MAX_PER_RUN + 5 }, (_, i) => acct("u" + i, { createdAt: NOW - (5 + i) * DAY, lastLoginAt: NOW - (5 + i) * DAY })); + const r = pick(many); + assert.equal(r.length, MAX_PER_RUN); + assert.equal(r[0], "u" + (MAX_PER_RUN + 4)); + }); +}); + +group("winback/buildWinBack", () => { + test("an address on its own domain checks that domain", () => { + const m = buildWinBack({ email: "test@darknode.ai", joined: NOW - 10 * DAY, stopUrl: "https://x/stop?u=1&t=2", now: NOW }); + assert.ok(m.subject.includes("darknode.ai")); + assert.ok(m.html.includes('href="https://darknode.ai/check/darknode.ai"')); + assert.ok(m.text.includes("https://darknode.ai/check/darknode.ai")); + assert.ok(m.html.includes("https://x/stop?u=1&t=2")); + assert.ok(m.text.includes("Turn off reminders: https://x/stop?u=1&t=2")); + }); + test("webmail goes to the Overview and names no domain", () => { + const m = buildWinBack({ email: "someone@gmail.com", stopUrl: "s", now: NOW }); + assert.ok(m.html.includes('href="https://darknode.ai/overview"')); + assert.ok(!m.subject.includes("gmail")); + }); + test("the address is escaped in the HTML", () => { + const m = buildWinBack({ email: '""@example.com', stopUrl: "s", now: NOW }); + assert.ok(!m.html.includes("")); + }); + test("a test send is marked", () => { + assert.ok(buildWinBack({ email: "test@darknode.ai", stopUrl: "s", test: true }).subject.startsWith("[Test]")); + }); + test("ownDomain ignores webmail and junk", () => { + assert.equal(ownDomain("a@Example.COM"), "example.com"); + assert.equal(ownDomain("a@outlook.com"), ""); + assert.equal(ownDomain("a@localhost"), ""); + assert.equal(ownDomain("nope"), ""); + }); +}); + +group("winback/wiring", () => { + test("the stop link needs no sign-in; the owner route is owner only", () => { + assert.equal(matchRoute("/api/winback/stop", "GET").route.id, "winback-stop"); + assert.equal(matchRoute("/api/winback/stop", "POST").route.auth, "none"); + const { route } = matchRoute("/api/admin/winback", "GET"); + assert.equal(route.id, "admin-winback"); + assert.equal(authorize(route, { kind: "user", claims: {} }).status, 403); + assert.equal(authorize(route, { kind: "user", claims: { admin: true } }), null); + }); + test("the daily cron runs the reminder and the Monday cron the digest", () => { + assert.equal(cronJob(WINBACK_CRON).name, "winback"); + assert.equal(cronJob("0 14 * * 1").name, "digest"); + assert.equal(cronJob(undefined).name, "digest"); + }); + test("the cron does nothing unless WINBACK_CRON is on", async () => { + assert.ok((await runWinBack({ WINBACK_CRON: "off" })).skipped); + assert.ok((await runWinBack({ WINBACK_CRON: "on" })).skipped); // not configured + }); + test("a bad stop token changes nothing", async () => { + const r = await handleWinBackStop(new Request("https://w/api/winback/stop?u=a&t=bad"), { FIREBASE_SA: "{}", RESEND_KEY: "k", FIREBASE_PROJECT_ID: "p", DIGEST_SECRET: "s" }); + assert.ok((await r.text()).includes("Link not valid")); + }); + test("deleting an account removes its digest and reminder records", () => { + assert.ok(KEYED_BY_UID.includes("digest") && KEYED_BY_UID.includes("winback")); + }); +}); + +// The whole daily run against stubbed Google, Firestore, Durable Object and Resend endpoints. +group("winback/runWinBack end to end", () => { + const sa = async () => { + const k = await crypto.subtle.generateKey({ name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" }, true, ["sign"]); + const der = new Uint8Array(await crypto.subtle.exportKey("pkcs8", k.privateKey)); + return JSON.stringify({ client_email: "sa@p.iam", private_key: "-----BEGIN PRIVATE KEY-----\n" + btoa(String.fromCharCode(...der)) + "\n-----END PRIVATE KEY-----\n" }); + }; + const ok = (body) => ({ ok: true, status: 200, json: async () => body, text: async () => JSON.stringify(body) }); + const now = Date.now(); + const mkEnv = async (calls) => ({ + WINBACK_CRON: "on", FIREBASE_SA: await sa(), RESEND_KEY: "rk", FIREBASE_PROJECT_ID: "p", DIGEST_API_BASE: "https://w", + MONITOR: { idFromName: (n) => n, get: (id) => ({ fetch: async () => { calls.push("do:" + id); return ok({ monitors: id === "watcher" ? [{ id: "m1" }] : [] }); } }) }, + }); + const stub = (calls) => async (url, o = {}) => { + const u = String(url); calls.push((o.method || "GET") + " " + u.replace(/\?.*/, "")); + if (u.startsWith("https://oauth2.googleapis.com/token")) return ok({ access_token: "tok", expires_in: 3600 }); + if (u.includes("accounts:batchGet")) return ok({ users: [ + { localId: "once", email: "test@darknode.ai", emailVerified: true, createdAt: String(now - 10 * DAY), lastLoginAt: String(now - 10 * DAY) }, + { localId: "watcher", email: "test+w@darknode.ai", emailVerified: true, createdAt: String(now - 10 * DAY), lastLoginAt: String(now - 10 * DAY) }, + { localId: "back", email: "test+b@darknode.ai", emailVerified: true, createdAt: String(now - 10 * DAY), lastLoginAt: String(now - 3 * DAY) }, + { localId: "sent", email: "test+s@darknode.ai", emailVerified: true, createdAt: String(now - 10 * DAY), lastLoginAt: String(now - 10 * DAY) }, + ] }); + if (u.includes("/documents/users?")) return ok({ documents: [{ name: "projects/p/databases/(default)/documents/users/once", fields: { activeDays: { integerValue: "1" } } }] }); + if (u.includes("/documents/winback?")) return ok({ documents: [{ name: "projects/p/databases/(default)/documents/winback/sent", fields: { sentAt: { integerValue: String(now - DAY) } } }] }); + if (u.includes("/documents/digest?")) return ok({}); + if (u.includes("/documents/settings/whitelist")) return { ok: false, status: 404, json: async () => ({}) }; + if (u.endsWith("documents:commit")) { calls.commit = JSON.parse(o.body); return ok({}); } + if (u.includes("/documents/winback/")) { calls.patch = { url: u, body: JSON.parse(o.body) }; return ok({}); } + if (u === "https://api.resend.com/emails/batch") { calls.mail = JSON.parse(o.body); return ok({ data: [] }); } + throw new Error("unexpected fetch " + u); + }; + test("emails only the person who came once and has no watch, after recording it", async () => { + const calls = []; const real = globalThis.fetch; globalThis.fetch = stub(calls); + try { + const env = await mkEnv(calls); + const r = await runWinBack(env, now); + assert.deepEqual(r, { sent: 1 }); + assert.deepEqual(calls.commit.writes.map((w) => w.update.name), ["projects/p/databases/(default)/documents/winback/once"]); + assert.ok(calls.indexOf("POST https://firestore.googleapis.com/v1/projects/p/databases/(default)/documents:commit") < calls.indexOf("POST https://api.resend.com/emails/batch")); + assert.equal(calls.mail.length, 1); + assert.deepEqual(calls.mail[0].to, ["test@darknode.ai"]); + assert.ok(calls.mail[0].headers["List-Unsubscribe"].startsWith(" Object.fromEntries(Object.entries(f || {}).map const SECRET_FIELDS = new Set(["apiKey", "keyHash", "hash", "secret", "token"]); const redact = (o) => Object.fromEntries(Object.entries(o).map(([k, v]) => [k, SECRET_FIELDS.has(k) ? "[redacted]" : v])); -async function doList(ns, id, headers, body = { op: "list" }) { +export async function doList(ns, id, headers, body = { op: "list" }) { if (!ns) return null; const r = await ns.get(ns.idFromName(id)).fetch("https://do/", { method: "POST", headers: { "Content-Type": "application/json", ...headers }, body: JSON.stringify(body) }); return r.ok ? r.json() : null; diff --git a/worker/admin-users.js b/worker/admin-users.js index 8424ae29..ec237dd9 100644 --- a/worker/admin-users.js +++ b/worker/admin-users.js @@ -17,22 +17,27 @@ export function authUserRow(u) { }; } -export async function handleAdminUsers(env, json, opts = {}) { - if (!env.FIREBASE_PROJECT_ID) return json({ error: "FIREBASE_PROJECT_ID is not set" }, 503); - 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); } +// Every Firebase Auth account as authUserRow rows. Throws on a failed page. +export async function listAuthAccounts(env, token, doFetch = fetch) { const users = []; let next = ""; for (let page = 0; page < 20; page++) { // 20 x 1000 accounts const url = "https://identitytoolkit.googleapis.com/v1/projects/" + env.FIREBASE_PROJECT_ID + "/accounts:batchGet?maxResults=1000" + (next ? "&nextPageToken=" + encodeURIComponent(next) : ""); const r = await doFetch(url, { headers: { Authorization: "Bearer " + token } }); - if (!r.ok) return json({ error: "Firebase Auth listing failed (HTTP " + r.status + ")." }, 502); + if (!r.ok) throw new Error("Firebase Auth listing failed (HTTP " + r.status + ")."); const d = await r.json().catch(() => ({})); for (const u of d.users || []) users.push(authUserRow(u)); next = d.nextPageToken || ""; if (!next) break; } - return json({ users, truncated: !!next }); + return { users, truncated: !!next }; +} + +export async function handleAdminUsers(env, json, opts = {}) { + if (!env.FIREBASE_PROJECT_ID) return json({ error: "FIREBASE_PROJECT_ID is not set" }, 503); + let token; + try { token = await (opts.token || googleToken)(env); } + catch (e) { return json({ error: "Server credentials unavailable: " + e.message }, 503); } + try { return json(await listAuthAccounts(env, token, opts.fetch || fetch)); } + catch (e) { return json({ error: e.message }, 502); } } diff --git a/worker/auth.js b/worker/auth.js index 559962b9..c59dfae8 100644 --- a/worker/auth.js +++ b/worker/auth.js @@ -28,12 +28,15 @@ export const ROUTES = [ { id: "digest-unsub", path: "/api/digest/unsubscribe", methods: ["GET", "POST"], auth: "none" }, // the stop link in a monitor alert email (an HMAC token in the URL, not a sign-in) { id: "watch-stop", path: "/api/watch/stop", methods: ["GET", "POST"], auth: "none" }, + // the turn-off link in the one-time reminder email (HMAC token, like watch-stop) + { id: "winback-stop", path: "/api/winback/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: "account-export", path: "/api/account/export", methods: ["GET"], auth: "user" }, { id: "admin-deletions", path: "/api/admin/deletions", methods: ["GET", "POST"], auth: "user", role: "admin" }, { id: "admin-users", path: "/api/admin/users", methods: ["GET"], auth: "user", role: "admin" }, + { id: "admin-winback", path: "/api/admin/winback", methods: ["GET", "POST"], 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/winback.js b/worker/winback.js new file mode 100644 index 00000000..486154a3 --- /dev/null +++ b/worker/winback.js @@ -0,0 +1,206 @@ +// One reminder email for people who signed up, used Darknode on a single day and did not come +// back. It is sent once per account, ever, by a daily cron (production only, gated by +// WINBACK_CRON), and only when all of these hold: +// - the address is verified, the account is not disabled, banned or the owner's; +// - they signed up between 2 and 45 days ago and were last seen 2 or more days ago; +// - they used the Deck on one day only (deck/owner-stats.js personOf, the same rule the +// Owner page counts with); +// - they have no monitor running and the weekly digest is off: those people already get +// something from Darknode by email; +// - they did not turn reminders off. +// The email points at the one thing that keeps working without them: the daily domain watch. +// When their address is on their own domain, the button checks that domain. +// +// Storage: Firestore winback/{uid} = { sentAt, off }. Only this Worker writes it (rules: the +// owner may read it). Mail goes through Resend, like the digest. +import { SITE, FROM, googleToken, unsubToken, unsubSecret } from "./digest.js"; +import { firestore, plainFields, doList } from "./account-delete.js"; +import { listAuthAccounts } from "./admin-users.js"; +import { personOf, isOwnerRow } from "../public/js/deck/owner-stats.js"; + +const DAY = 86400000; +export const WINDOW = { minDays: 2, maxDays: 45, quietDays: 2 }; +export const MAX_PER_RUN = 25; +export const STOP_PATH = "/api/winback/stop"; + +// Webmail and ISP domains: an address there says nothing about which domain the person runs. +const FREEMAIL = new Set(("gmail.com googlemail.com outlook.com hotmail.com hotmail.co.uk live.com msn.com yahoo.com yahoo.co.uk ymail.com " + + "icloud.com me.com mac.com aol.com proton.me protonmail.com pm.me gmx.com gmx.de gmx.net web.de mail.com yandex.com yandex.ru " + + "zoho.com zohomail.com qq.com 163.com 126.com tutanota.com tuta.io fastmail.com hey.com duck.com mail.ru rediffmail.com " + + "comcast.net verizon.net att.net btinternet.com orange.fr free.fr t-online.de libero.it seznam.cz naver.com").split(" ")); +const DOMAIN_RE = /^(?=.{1,253}$)(?!-)[a-z0-9-]{1,63}(?:\.[a-z0-9-]{1,63})+$/; + +const esc = (s) => String(s == null ? "" : s).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); + +// ---- pure ---------------------------------------------------------------------------------- + +// The domain worth checking for this address, or "" for webmail / anything odd. +export function ownDomain(email) { + const d = String(email || "").toLowerCase().trim().split("@")[1] || ""; + return DOMAIN_RE.test(d) && !FREEMAIL.has(d) ? d : ""; +} + +// accounts: Firebase Auth rows (admin-users.js authUserRow); profiles: Map uid -> users/{uid} +// fields; sent: Map uid -> winback/{uid}; digestOn: Set of uids; banned: lower-cased emails. +// -> the accounts to remind, oldest sign-up first, at most `max`. +export function pickWinBack({ accounts = [], profiles = new Map(), sent = new Map(), digestOn = new Set(), banned = [], now = Date.now(), max = MAX_PER_RUN } = {}) { + const ban = new Set(banned.map((e) => String(e).toLowerCase())); + const out = []; + for (const a of accounts) { + if (!a || !a.uid || !a.email || !a.emailVerified || a.disabled) continue; + if (ban.has(String(a.email).toLowerCase()) || sent.has(a.uid) || digestOn.has(a.uid)) continue; + const prof = profiles.get(a.uid) || {}; + if (isOwnerRow(prof)) continue; + const joined = Number(a.createdAt) || 0; + if (!joined || now - joined < WINDOW.minDays * DAY || now - joined > WINDOW.maxDays * DAY) continue; + const p = personOf({ ...prof, createdAt: joined, lastLoginAt: Number(a.lastLoginAt) || 0 }, now); + if (p.returned || now - p.last < WINDOW.quietDays * DAY) continue; + out.push({ uid: a.uid, email: a.email, joined }); + } + return out.sort((x, y) => x.joined - y.joined).slice(0, max); +} + +// -> { subject, html, text } +export function buildWinBack({ email = "", joined = 0, stopUrl = "", now = Date.now(), test = false } = {}) { + const dom = ownDomain(email); + const cta = dom ? SITE + "/check/" + dom : SITE + "/overview"; + const ctaLabel = dom ? "Check " + dom : "Check your domain"; + const subject = (test ? "[Test] " : "") + (dom ? "Let Darknode watch " + dom + " for you" : "Let Darknode watch your domain for you"); + const when = joined ? new Date(joined).toLocaleDateString("en-GB", { day: "numeric", month: "long", timeZone: "UTC" }) : ""; + const intro = "You signed up for Darknode" + (when ? " on " + when : "") + ". The part that saves you work is the watch: Darknode checks your domain every day and emails you only when something breaks or is about to expire."; + const items = [ + ["The certificate", "before it expires"], + ["The domain registration", "before it lapses, or if a transfer starts"], + ["Email and DNS records (SPF, DMARC, MX, CAA)", "if one disappears or changes"], + ["The website", "missing security headers, or an exposed .git or .env file"], + ]; + const plan = "The Free plan watches one domain. Alerts go only to " + email + "."; + const why = "You get this one reminder because you have a Darknode account and have not set up a watch. We do not send it again."; + const text = [intro, "", "What it watches:", ...items.map(([a, b]) => "- " + a + ": " + b), "", + ctaLabel + ": " + cta, "Then choose Watch this domain.", "", plan, "", why, "Turn off reminders: " + stopUrl].join("\n"); + + const F = "-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica,Arial,sans-serif"; + const rows = items.map(([a, b]) => `${esc(a)}
    ${esc(b)}
    `).join(""); + const date = new Date(now).toISOString().slice(0, 10); + const html = `${esc(subject)} + +
    One check, then an email only when something breaks or is about to expire.
    +
    + + + + +
    Darknode${esc(date)}${test ? " · test send" : ""}
    + + + + + + + +
    Two minutes, then it runs without you
    ${esc(intro)}
    What it watches
    ${rows}
    ${esc(ctaLabel)}
    Then choose Watch this domain. ${esc(plan)}
    ${esc(why)}
    Turn off reminders · darknode.ai
    `; + return { subject, html, text }; +} + +// ---- IO -------------------------------------------------------------------------------------- + +const ready = (env) => !!(env.FIREBASE_SA && env.RESEND_KEY && env.FIREBASE_PROJECT_ID && unsubSecret(env)); // no secret, no unforgeable stop link +const stopToken = (env, uid) => unsubToken("winback:" + uid, unsubSecret(env)); +async function stopUrl(env, uid) { + return (env.DIGEST_API_BASE || "https://darknode-proxy.darknode-ai.workers.dev") + STOP_PATH + "?u=" + encodeURIComponent(uid) + "&t=" + (await stopToken(env, uid)); +} +async function resend(env, path, payload) { + const r = await fetch("https://api.resend.com" + path, { method: "POST", headers: { Authorization: "Bearer " + env.RESEND_KEY, "Content-Type": "application/json" }, body: JSON.stringify(payload) }); + const d = await r.json().catch(() => ({})); + if (!r.ok) throw new Error("Email provider error (" + r.status + "): " + String(d.message || d.error || "").slice(0, 160)); + return d; +} +const mail = (to, d, url) => ({ from: FROM, to: [to], subject: d.subject, html: d.html, text: d.text, + headers: { "List-Unsubscribe": "<" + url + ">", "List-Unsubscribe-Post": "List-Unsubscribe=One-Click" } }); + +// Everything the pick needs, in a handful of reads. +async function gather(env, token) { + const fs = firestore(env, token); + const [accounts, users, sentDocs, digestDocs, wl] = await Promise.all([ + listAuthAccounts(env, token).then((a) => a.users), fs.list("users"), fs.list("winback"), fs.list("digest"), fs.get("settings/whitelist"), + ]); + const id = (d) => d.path.split("/").pop(); + return { + fs, accounts, + profiles: new Map(users.map((d) => [id(d), plainFields(d.fields)])), + sent: new Map(sentDocs.map((d) => [id(d), plainFields(d.fields)])), + digestOn: new Set(digestDocs.filter((d) => d.fields.on && d.fields.on.booleanValue).map(id)), + banned: ((wl && plainFields(wl.fields).banned) || []).map(String), + }; +} + +// The pick, minus anyone with a monitor in their personal workspace (one Durable Object read each). +async function eligible(env, data, now) { + const out = []; + for (const c of pickWinBack({ ...data, now })) { + const mon = await doList(env.MONITOR, c.uid, { "x-mon-uid": c.uid, "x-mon-role": "owner", "x-mon-wid": c.uid }).catch(() => null); + if (mon === null && env.MONITOR) continue; // could not tell: do not email + if (mon && (mon.monitors || []).length) continue; + out.push(c); + } + return out; +} + +// Cron. Records each reminder before sending it, so a failure can never send one twice. +export async function runWinBack(env, now = Date.now()) { + if (env.WINBACK_CRON !== "on") return { skipped: "WINBACK_CRON is not on" }; + if (!ready(env)) return { skipped: "not configured" }; + const token = await googleToken(env); + const data = await gather(env, token); + const picks = await eligible(env, data, now); + if (!picks.length) { console.log(JSON.stringify({ type: "winback", sent: 0 })); return { sent: 0 }; } + const writes = picks.map((c) => ({ update: { name: data.fs.name("winback/" + c.uid), fields: { sentAt: { integerValue: String(now) } } } })); + const r = await fetch("https://firestore.googleapis.com/v1/projects/" + env.FIREBASE_PROJECT_ID + "/databases/(default)/documents:commit", + { method: "POST", headers: { Authorization: "Bearer " + token, "Content-Type": "application/json" }, body: JSON.stringify({ writes }) }); + if (!r.ok) throw new Error("winback record " + r.status); + const out = []; + for (const c of picks) { const url = await stopUrl(env, c.uid); out.push(mail(c.email, buildWinBack({ email: c.email, joined: c.joined, stopUrl: url, now }), url)); } + await resend(env, "/emails/batch", out); + console.log(JSON.stringify({ type: "winback", sent: out.length })); + return { sent: out.length }; +} + +// GET /api/admin/winback (owner): whether it runs, who got one, who gets one at the next run. +// POST {op:"preview"}: send the email to the owner's own address, as a test. +export async function handleAdminWinBack(request, env, json, principal) { + if (!ready(env)) return json({ error: "Reminder emails are not configured on this server." }, 503); + try { + const token = await googleToken(env); + if (request.method === "POST") { + let b; try { b = JSON.parse(await request.text()); } catch (_) { return json({ error: "Invalid JSON body" }, 400); } + if (!b || b.op !== "preview") return json({ error: "Unknown op" }, 400); + const to = principal.email || ""; + if (!to || !(principal.claims && principal.claims.email_verified)) return json({ error: "Your address is not verified." }, 400); + const url = await stopUrl(env, principal.uid); + await resend(env, "/emails", mail(to, buildWinBack({ email: to, joined: Date.now() - 5 * DAY, stopUrl: url, test: true }), url)); + return json({ ok: true, to }); + } + const data = await gather(env, token); + const next = await eligible(env, data, Date.now()); + return json({ + on: env.WINBACK_CRON === "on", + sent: [...data.sent].map(([uid, w]) => ({ uid, sentAt: Number(w.sentAt) || null, off: !!w.off })), + next: next.map((c) => c.uid), + }); + } catch (e) { return json({ error: String((e && e.message) || e).slice(0, 200) }, 502); } +} + +const page = (title, msg) => new Response(`${esc(title)} · Darknode
    Darknode

    ${esc(title)}

    ${msg}

    `, { headers: { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" } }); + +// GET/POST /api/winback/stop?u=&t= (the link in the email; POST is one-click unsubscribe) +export async function handleWinBackStop(request, env) { + const u = new URL(request.url), uid = u.searchParams.get("u") || "", t = u.searchParams.get("t") || ""; + if (!(uid && uid.length <= 128 && t && ready(env) && t === (await stopToken(env, uid)))) return page("Link not valid", "This link is incomplete. Darknode sends this reminder only once, so there is nothing more to stop."); + try { + const token = await googleToken(env); + const fs = firestore(env, token); + const r = await fetch("https://firestore.googleapis.com/v1/" + fs.name("winback/" + uid) + "?updateMask.fieldPaths=off", { method: "PATCH", headers: { Authorization: "Bearer " + token, "Content-Type": "application/json" }, body: JSON.stringify({ fields: { off: { booleanValue: true } } }) }); + if (!r.ok) throw new Error(String(r.status)); + } catch (_) { return page("Something went wrong", "We could not save that just now. Try the link again in a minute."); } + return page("Reminders off", "Darknode will not send you reminder emails. Alerts from a watch you set up, and the weekly digest if you turn it on, are separate and still come."); +} diff --git a/worker/worker.js b/worker/worker.js index 930c2797..8b12e67c 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 { runWinBack, handleAdminWinBack, handleWinBackStop, STOP_PATH as WINBACK_STOP_PATH } from "./winback.js"; import { handleAccountDelete, handleAccountExport, handleAdminDeletions } from "./account-delete.js"; import { handleUsage } from "./usage.js"; export { VaultDO } from "./vault.js"; @@ -732,6 +733,9 @@ async function smartAsk(env, keys, contents) { return json({ steps, answer: typeof parsed.answer === "string" && parsed.answer.trim() ? parsed.answer : null }); } +export const WINBACK_CRON = "0 15 * * *"; +export const cronJob = (cron) => (cron === WINBACK_CRON ? { name: "winback", run: runWinBack } : { name: "digest", run: runDigest }); + export default { // A handler that throws (e.g. a JSON body of `null` on /api/intel) must not become // Cloudflare's HTML 1101 page with no CORS headers: answer JSON 500, no stack. @@ -742,9 +746,11 @@ export default { try { res = await route(request, env, rid); } catch (_) { res = json({ error: "Internal error." }, 500); } return withHeaders(res, { "x-request-id": rid }); }, - // Weekly email digest (cron in wrangler.toml; production only, gated by DIGEST_CRON). + // Crons in wrangler.toml, production only: the Monday digest (DIGEST_CRON) and the daily + // one-time reminder (WINBACK_CRON). async scheduled(event, env, ctx) { - ctx.waitUntil(runDigest(env).catch((e) => console.error(JSON.stringify({ type: "digest-error", message: String((e && e.message) || e).slice(0, 300) })))); + const job = cronJob(event.cron); + ctx.waitUntil(job.run(env).catch((e) => console.error(JSON.stringify({ type: job.name + "-error", message: String((e && e.message) || e).slice(0, 300) })))); }, }; @@ -787,7 +793,7 @@ async function route(request, env, rid) { // origin. That route spends nothing and acts only with a signed token (monitor.js handleWatchStop). const origin = request.headers.get("Origin"); const { pathname } = new URL(request.url); - if (!originAllowed(origin) && pathname !== STOP_PATH) return json({ error: "Origin not allowed" }, 403); + if (!originAllowed(origin) && pathname !== STOP_PATH && pathname !== WINBACK_STOP_PATH) return json({ error: "Origin not allowed" }, 403); const ip = request.headers.get("cf-connecting-ip") || "unknown"; const limited = (wait) => withHeaders(json({ error: "Rate limit exceeded — slow down and retry shortly." }, 429), { "Retry-After": String(wait) }); // The route table (auth.js) declares what each path needs; enforce it here. @@ -820,8 +826,10 @@ async function route(request, env, rid) { case "keys": return handleKeys(request, env, rest, json); case "digest-unsub": return handleUnsubscribe(request, env); case "watch-stop": return handleWatchStop(request, env); + case "winback-stop": return handleWinBackStop(request, env); case "digest": return handleDigest(request, env, rest, json, principal); case "admin-users": return handleAdminUsers(env, json); + case "admin-winback": return handleAdminWinBack(request, env, json, principal); case "usage": return handleUsage(request, env, json, principal); case "account-delete": return handleAccountDelete(request, env, json, principal); case "account-export": return handleAccountExport(request, env, json, principal); diff --git a/worker/wrangler.toml b/worker/wrangler.toml index ded90eb6..b5d0dfa2 100644 --- a/worker/wrangler.toml +++ b/worker/wrangler.toml @@ -2,9 +2,10 @@ name = "darknode-proxy" main = "worker.js" compatibility_date = "2024-11-01" -# Weekly email digest: Mondays 14:00 UTC (worker/digest.js). Staging has no cron. +# Weekly email digest: Mondays 14:00 UTC (worker/digest.js). One-time reminder email: daily +# 15:00 UTC (worker/winback.js). Staging has no cron. [triggers] -crons = ["0 14 * * 1"] +crons = ["0 14 * * 1", "0 15 * * *"] # Non-secret config. Set DARKNODE_URL here (or as a secret) once your GPU-hosted # Darknode model is up; until then the flagship falls back to Gemini. @@ -12,6 +13,7 @@ crons = ["0 14 * * 1"] GEMINI_FALLBACK_MODEL = "gemini-flash-lite-latest" FIREBASE_PROJECT_ID = "sentinel-b4194" DIGEST_CRON = "on" +WINBACK_CRON = "on" DIGEST_API_BASE = "https://darknode-proxy.darknode-ai.workers.dev" # DARKNODE_URL = "https://your-gpu-box/v1/chat/completions" @@ -87,6 +89,7 @@ crons = [] GEMINI_FALLBACK_MODEL = "gemini-flash-lite-latest" FIREBASE_PROJECT_ID = "sentinel-b4194" DIGEST_CRON = "off" +WINBACK_CRON = "off" DIGEST_API_BASE = "https://darknode-proxy-staging.darknode-ai.workers.dev" [[env.staging.durable_objects.bindings]]