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
19 changes: 14 additions & 5 deletions public/js/admin.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@ import {
addDoc, query, orderBy, updateDoc, limit,
} from "https://www.gstatic.com/firebasejs/12.17.0/firebase-firestore.js";

// Profile timestamps come as Firestore Timestamps, epoch numbers (the worker's Auth-only rows)
// or the Auth metadata string ensureUserDoc stores ("Wed, 11 Nov 2026 ..."); all count.
const tsMs = (ts) => ts && ts.toMillis ? ts.toMillis() : ts && ts.toDate ? ts.toDate().getTime()
: typeof ts === "number" ? (ts < 1e12 ? ts * 1000 : ts) : typeof ts === "string" ? (Date.parse(ts) || 0) : 0;
// Only the sign-in providers' own avatar hosts load: photoURL is user-writable, and any other
// URL would send the owner's IP and browser to a server the user picked.
const AVATAR_HOST = /^(lh\d+\.googleusercontent\.com|avatars\.githubusercontent\.com)$/;
const safeAvatar = (u) => { try { const x = new URL(u); return x.protocol === "https:" && AVATAR_HOST.test(x.hostname) ? x.href : ""; } catch (_) { return ""; } };
const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) =>
({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
const fmtDate = (ts) => {
Expand Down Expand Up @@ -329,7 +337,7 @@ export async function renderAdmin(main, user) {
}
} catch (_) { /* Worker unreachable: the Firestore list still shows */ }
$("#stUsers").textContent = users.length;
const toMs = (ts) => ts && ts.toMillis ? ts.toMillis() : (ts && ts.toDate ? ts.toDate().getTime() : (typeof ts === "number" ? (ts < 1e12 ? ts * 1000 : ts) : 0));
const toMs = tsMs;
const now = Date.now(), day = 864e5, midnight = new Date(); midnight.setHours(0, 0, 0, 0);
$("#stNew").textContent = users.filter((u) => { const c = toMs(u.created || u.createdAt); return c && now - c < 7 * day; }).length || "—";
$("#stActive").textContent = users.filter((u) => toMs(u.lastSeen) >= midnight.getTime()).length;
Expand Down Expand Up @@ -359,8 +367,9 @@ export async function renderAdmin(main, user) {
const provBadge = prov.includes("google") ? '<span class="ur-prov google">Google</span>'
: prov.includes("github") ? '<span class="ur-prov github">GitHub</span>'
: '<span class="ur-prov email">Email</span>';
const avatar = u.photoURL
? `<img class="ur-avatar" src="${esc(u.photoURL)}" alt="" width="32" height="32">`
const pic = safeAvatar(u.photoURL);
const avatar = pic
? `<img class="ur-avatar" src="${esc(pic)}" alt="" width="32" height="32" referrerpolicy="no-referrer">`
: `<span class="ur-avatar ur-initials">${esc((u.email || "?")[0].toUpperCase())}</span>`;
return `<div class="user-row" data-uid="${esc(u.uid)}">
${avatar}
Expand Down Expand Up @@ -681,7 +690,7 @@ export async function renderAdmin(main, user) {
const label = d.toLocaleDateString('en', { weekday: 'short' });
const dayStart = new Date(d); dayStart.setHours(0,0,0,0);
const dayEnd = new Date(d); dayEnd.setHours(23,59,59,999);
const toMs = (ts) => ts && ts.toMillis ? ts.toMillis() : (ts && ts.toDate ? ts.toDate().getTime() : 0);
const toMs = tsMs;
const count = users.filter(u => { const c = toMs(u.created || u.createdAt); return c >= dayStart.getTime() && c <= dayEnd.getTime(); }).length;
days.push({ label, count });
}
Expand Down Expand Up @@ -722,7 +731,7 @@ export async function renderAdmin(main, user) {
if (clearInactive) clearInactive.onclick = async () => {
const msg = $("#maintMsg");
const cutoff = Date.now() - 90 * 864e5;
const toMs = (ts) => ts && ts.toMillis ? ts.toMillis() : (ts && ts.toDate ? ts.toDate().getTime() : 0);
const toMs = tsMs;
const inactive = users.filter(u => {
const last = toMs(u.lastSeen) || toMs(u.created || u.createdAt);
return last && last < cutoff && !isOwnerRow(u);
Expand Down
1 change: 1 addition & 0 deletions public/js/deck/monitors.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ function paint() {
<span class="mon-name">${E(m.name)}</span>
<span class="mon-pill">${E(m.type)}</span>
${m.paused ? '<span class="mon-pill paused">Paused</span>' : ""}
${!m.paused && m.planHeld ? '<span class="mon-pill paused" title="The plan of the person who set this up no longer includes monitoring. Pause and resume it from an account on Pro to restart it.">Held: plan</span>' : ""}
<span class="mon-meta">${dom.length ? E(dom.slice(0, 3).join(", ")) + (dom.length > 3 ? ` +${dom.length - 3}` : "") + " · " : m.config && m.config.epssFloor != null ? "KEV or EPSS ≥ " + E(m.config.epssFloor) + " · " : ""}every ${every(m.intervalMs)} · last run ${E(ago(m.lastRunAt))} · ${m.lastResultCount || 0} open · ${(m.channels || []).length} channel${(m.channels || []).length === 1 ? "" : "s"}</span>
<span class="mon-actions">
<button class="mon-btn" data-act="run">Run now</button>
Expand Down
24 changes: 24 additions & 0 deletions test/worker/ingest-do.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -138,3 +138,27 @@ group("ingest DO/prototype safety", () => {
assert.equal(list.keys.length, 1, "the real key is unaffected");
});
});

group("ingest DO/plan", () => {
const withWid = (key, body) => new Request("https://ingest/", { method: "POST", headers: { "x-ing-key": key, "x-ing-wid": "u1", "content-type": "application/json" }, body });
const tierIs = (tier, status = 200) => ({ token: async () => "sa", cache: new Map(), fetch: async () => ({ ok: status === 200, status, json: async () => ({ fields: { tier: { stringValue: tier } } }) }) });
const mkd = () => { const d = new IngestDO(memState(), { FIREBASE_PROJECT_ID: "p1" }); return d; };
test("a key keeps ingesting while its creator has Team", async () => {
const d = mkd(); const k = await newKey(d, ["ingest:write"]);
d.planOpts = tierIs("team");
assert.equal((await d.fetch(withWid(k.key, JSON.stringify([{ title: "A", severity: "low" }])))).status, 200);
});
test("after the creator is downgraded the key is refused with 402; read-back stays open", async () => {
const d = mkd(); const k = await newKey(d, ["ingest:write", "findings:read"]);
await d.fetch(withWid(k.key, JSON.stringify([{ title: "A", severity: "low" }])));
d.planOpts = tierIs("free");
const r = await jsonOf(await d.fetch(withWid(k.key, JSON.stringify([{ title: "B", severity: "low" }]))));
assert.equal(r.status, 402); assert.equal(r.json.plan, true);
assert.equal((await d.fetch(readback(k.key))).status, 200);
});
test("a plan that cannot be read does not break CI (fails open)", async () => {
const d = mkd(); const k = await newKey(d, ["ingest:write"]);
d.planOpts = tierIs("free", 503);
assert.equal((await d.fetch(withWid(k.key, JSON.stringify([{ title: "A", severity: "low" }])))).status, 200);
});
});
49 changes: 49 additions & 0 deletions test/worker/monitor-do.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -466,3 +466,52 @@ group("monitor DO/alert window + viewer redaction", () => {
assert.equal(sevRank("HIGH"), 3);
});
});

group("monitor DO/plan", () => {
const mk = async (net) => {
const st = memState(); const mon = new MonitorDO(st);
const r = await post(mon, { op: "upsert", monitor: { name: "Certs", type: "cert-expiry", config: { domains: ["a.test.darknode.ai"] }, channels: [{ type: "webhook", url: "https://hook.test/x" }] } });
return { st, mon, id: r.json.monitor.id };
};
test("upsert records who set the monitor up", async () => {
const { st, id } = await mk();
assert.equal(st._map.get("monitors")[id].by, "u1");
});
test("a scheduled run is held when the creator's plan lapsed, and waits a full interval", async () => {
const { st, mon, id } = await mk();
const net = fakeNet(day(5));
const r = await mon.runDue({ fetch: net.fetch, sleep: async () => {}, planOk: async () => false });
assert.equal(r.ran.length, 0, "nothing ran");
assert.equal(net.deliveries.length, 0, "no alert delivered");
const m = st._map.get("monitors")[id];
assert.equal(m.planHeld, true);
assert.equal(m.lastRunAt, 0, "last run is not faked");
assert.ok(st.storage._alarm() > Date.now() + 60000, "no tight alarm loop while held");
assert.ok(/held/.test(st._map.get("history")[0].error));
});
test("once the plan is back the next scheduled run goes ahead and clears the hold", async () => {
const { st, mon, id } = await mk();
await mon.runDue({ planOk: async () => false });
st._map.get("monitors")[id].planHeldAt = 0; // pretend the interval passed
const net = fakeNet(day(5));
const r = await mon.runDue({ fetch: net.fetch, sleep: async () => {}, planOk: async () => true });
assert.equal(r.ran.length, 1);
assert.equal(st._map.get("monitors")[id].planHeld, undefined);
});
test("alarm() checks the creator's live plan (free -> held)", async () => {
const { st, mon, id } = await mk();
await st.storage.put("wid", "u1");
mon.env = { FIREBASE_PROJECT_ID: "p1" };
mon.planOpts = { token: async () => "sa", cache: new Map(), fetch: async () => ({ ok: true, status: 200, json: async () => ({ fields: { tier: { stringValue: "free" } } }) }) };
await mon.alarm();
assert.equal(st._map.get("monitors")[id].planHeld, true);
});
test("resuming hands the plan check to the resumer and clears a hold", async () => {
const { st, mon, id } = await mk();
Object.assign(st._map.get("monitors")[id], { by: "gone", planHeld: true, planHeldAt: 5 });
await post(mon, { op: "pause", id, paused: true });
await post(mon, { op: "pause", id, paused: false });
const m = st._map.get("monitors")[id];
assert.equal(m.by, "u1"); assert.equal(m.planHeld, undefined);
});
});
30 changes: 30 additions & 0 deletions test/worker/plan-share.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,33 @@ group("worker: workspace plan sharing", () => {
} finally { globalThis.fetch = real; _resetShareCache(); }
});
});

// liveTier: the plan behind work with no user request (monitor alarms, API-key ingest).
import { liveTier } from "../../worker/plan-share.js";
group("worker: live plan for background work", () => {
const lo = (fetch) => ({ fetch, token: async () => "sa-token", cache: new Map(), shareCache: new Map() });
test("reads the creator's live plan with the service account", async () => {
const seen = [];
assert.equal(await liveTier(ENV, "u1", "u1", lo(fs({ users: { u1: { tier: "pro" } } }, seen))), "pro");
assert.ok(seen.every(([, t]) => t === "sa-token"), "service account token");
});
test("a downgraded creator reads as free; no profile reads as free", async () => {
assert.equal(await liveTier(ENV, "u1", "u1", lo(fs({ users: { u1: { tier: "free" } } }))), "free");
assert.equal(await liveTier(ENV, "u1", "u1", lo(fs({ users: {} }))), "free");
});
test("the owner's admin flag counts as the top plan", async () => {
assert.equal(await liveTier(ENV, "boss", "boss", lo(fs({ users: { boss: { admin: true } } }))), "enterprise");
});
test("no recorded creator: personal workspace uses its own user, a team workspace its createdBy", async () => {
assert.equal(await liveTier(ENV, "u9", "", lo(fs({ users: { u9: { tier: "pro" } } }))), "pro");
assert.equal(await liveTier(ENV, TEAM, "", lo(fs({ ws: { createdBy: { stringValue: "boss" } }, users: { boss: { tier: "team" } } }))), "team");
});
test("a member's work in a team workspace counts the owner's shared plan", async () => {
assert.equal(await liveTier(ENV, TEAM, "u1", lo(fs({ ws: on(), users: { boss: { tier: "team" } } }))), "team");
});
test("an unreadable profile or missing service account is unknown (null), never a false downgrade", async () => {
assert.equal(await liveTier(ENV, "u1", "u1", lo(async () => ({ ok: false, status: 503, json: async () => ({}) }))), null);
assert.equal(await liveTier(ENV, "u1", "u1", { fetch: fs(), token: async () => { throw new Error("FIREBASE_SA is not set"); }, cache: new Map() }), null);
assert.equal(await liveTier(undefined, "u1", "u1", lo(fs())), null);
});
});
16 changes: 11 additions & 5 deletions worker/ingest.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { ingestToFindings } from "../public/js/ingest/formats.js";
import { requireUser, presentedKey } from "./auth.js";
import { resolveWorkspaceRole, canDo } from "./workspace.js";
import { featureDenied } from "./plan.js";
import { workspaceTier } from "./plan-share.js";
import { workspaceTier, liveTier } from "./plan-share.js";
import { readCapped } from "./body-cap.js";

const WID = /^[A-Za-z0-9_-]{1,128}$/;
Expand All @@ -33,7 +33,7 @@ const capFields = (f) => {
const safeKey = (k) => ({ keyId: k.keyId, prefix: keyPrefix(k.keyId), scopes: k.scopes, label: k.label, createdAt: k.createdAt, lastUsedAt: k.lastUsedAt || 0, revoked: !!k.revoked });

export class IngestDO {
constructor(state) { this.state = state; this.storage = state.storage; }
constructor(state, env) { this.state = state; this.storage = state.storage; this.env = env || {}; }
// Null-proto map: keyId comes from an API caller, so a key named "__proto__"/
// "constructor" must be an ordinary own entry, never reach Object.prototype.
async _keys() { return Object.assign(Object.create(null), await this.storage.get("keys")); }
Expand Down Expand Up @@ -78,7 +78,7 @@ export class IngestDO {
if (!timingSafeEqual(h, rec.hash)) { out = { ok: false, status: 401, error: "Invalid API key." }; return; }
if (scope && !hasScope(rec.scopes, scope)) { out = { ok: false, status: 403, error: `This key lacks the ${scope} scope.` }; return; }
rec.lastUsedAt = now(); await this.storage.put("keys", keys);
out = { ok: true, keyId, scopes: rec.scopes };
out = { ok: true, keyId, scopes: rec.scopes, by: rec.by || "" };
});
return out;
}
Expand All @@ -98,6 +98,12 @@ export class IngestDO {
return reply({ pending: findings.length, findings });
}
const v = await this._verify(apiKey, "ingest:write"); if (!v.ok) return reply({ error: v.error }, v.status);
// a key keeps ingesting only while its creator still has the plan (read-back stays open
// so findings already sent can be pulled after a downgrade)
const wid = request.headers.get("x-ing-wid");
const tier = wid ? await liveTier(this.env, wid, v.by, this.planOpts) : null; // planOpts: test seam (fetch/token), unset in production
const planMsg = tier === null ? null : featureDenied("apiKeys", tier);
if (planMsg) return reply({ error: planMsg + " (checked against the plan of the person who created this key)", plan: true }, 402);
const text = await request.text();
if (text.length > BODY_CAP) return reply({ error: "Body too large." }, 413);
const { format, findings: parsed, errors } = ingestToFindings(text);
Expand Down Expand Up @@ -133,7 +139,7 @@ export class IngestDO {
// let a concurrent create/revoke drop this key (its await hashKey yields).
await this.state.blockConcurrencyWhile(async () => {
const keys = await this._keys();
keys[keyId] = { keyId, hash: await hashKey(key), scopes, label: String(body.label || "").slice(0, 80) || "API key", createdAt: now(), lastUsedAt: 0, revoked: false };
keys[keyId] = { keyId, hash: await hashKey(key), scopes, label: String(body.label || "").slice(0, 80) || "API key", by: mgmtUid, createdAt: now(), lastUsedAt: 0, revoked: false };
await this.storage.put("keys", keys);
});
return reply({ key, keyId, prefix, scopes }); // full key shown once
Expand Down Expand Up @@ -207,6 +213,6 @@ export async function handleIngest(request, env, wid, json, kind) {
const bodyText = isRead ? null : await readCapped(request, BODY_CAP);
if (!isRead && bodyText === null) return json({ error: "Body too large." }, 413);
const stub = env.INGEST.get(env.INGEST.idFromName(wid));
const res = await stub.fetch("https://ingest/" + (isRead ? "findings" : ""), { method: isRead ? "GET" : "POST", body: bodyText, headers: { "x-ing-key": key, "Content-Type": "application/json" } });
const res = await stub.fetch("https://ingest/" + (isRead ? "findings" : ""), { method: isRead ? "GET" : "POST", body: bodyText, headers: { "x-ing-key": key, "x-ing-wid": wid, "Content-Type": "application/json" } });
return json(await res.json(), res.status);
}
Loading
Loading