diff --git a/public/js/admin.js b/public/js/admin.js
index 059d9fbd..06a66141 100644
--- a/public/js/admin.js
+++ b/public/js/admin.js
@@ -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) =>
({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
const fmtDate = (ts) => {
@@ -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;
@@ -359,8 +367,9 @@ export async function renderAdmin(main, user) {
const provBadge = prov.includes("google") ? 'Google'
: prov.includes("github") ? 'GitHub'
: 'Email';
- const avatar = u.photoURL
- ? `
`
+ const pic = safeAvatar(u.photoURL);
+ const avatar = pic
+ ? `
`
: `${esc((u.email || "?")[0].toUpperCase())}`;
return `
${avatar}
@@ -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 });
}
@@ -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);
diff --git a/public/js/deck/monitors.js b/public/js/deck/monitors.js
index 7ceadb91..0222572a 100644
--- a/public/js/deck/monitors.js
+++ b/public/js/deck/monitors.js
@@ -84,6 +84,7 @@ function paint() {
${E(m.name)}
${E(m.type)}
${m.paused ? 'Paused' : ""}
+ ${!m.paused && m.planHeld ? 'Held: plan' : ""}
${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"}
diff --git a/test/worker/ingest-do.test.mjs b/test/worker/ingest-do.test.mjs
index e8cbc9a0..172b2f46 100644
--- a/test/worker/ingest-do.test.mjs
+++ b/test/worker/ingest-do.test.mjs
@@ -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);
+ });
+});
diff --git a/test/worker/monitor-do.test.mjs b/test/worker/monitor-do.test.mjs
index 92725550..2f589f09 100644
--- a/test/worker/monitor-do.test.mjs
+++ b/test/worker/monitor-do.test.mjs
@@ -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);
+ });
+});
diff --git a/test/worker/plan-share.test.mjs b/test/worker/plan-share.test.mjs
index e136c279..a00f5b82 100644
--- a/test/worker/plan-share.test.mjs
+++ b/test/worker/plan-share.test.mjs
@@ -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);
+ });
+});
diff --git a/worker/ingest.js b/worker/ingest.js
index 32944bd8..29706905 100644
--- a/worker/ingest.js
+++ b/worker/ingest.js
@@ -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}$/;
@@ -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")); }
@@ -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;
}
@@ -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);
@@ -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
@@ -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);
}
diff --git a/worker/monitor.js b/worker/monitor.js
index d8ae2214..21af00ea 100644
--- a/worker/monitor.js
+++ b/worker/monitor.js
@@ -12,7 +12,7 @@ import { deliver, RETRY_BACKOFF_MS } from "./notify.js";
import { requireUser } 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}$/;
@@ -25,6 +25,8 @@ const uid = () => "m_" + Math.random().toString(36).slice(2, 10) + now().toStrin
// A Slack/Discord/Teams webhook URL is itself the credential: viewers see only its host.
const hideUrl = (u) => { try { const x = new URL(u); return x.origin + (x.pathname.length > 1 || x.search ? "/…" : ""); } catch (_) { return "…"; } };
const safeChannel = (c, full = true) => ({ type: c.type, url: full ? c.url : hideUrl(c.url), hasSecret: !!c.secret });
+// next run: a run held for the plan waits a full interval too, or the alarm would refire every second
+const dueAt = (m) => Math.max(m.lastRunAt || 0, m.planHeldAt || 0) + Math.max(m.intervalMs || 0, MIN_INTERVAL);
const safeMonitor = (m, full = true) => ({ ...m, channels: (m.channels || []).map((c) => safeChannel(c, full)), lastResults: undefined, graphMeta: undefined, lastResultCount: (m.lastResults || []).length });
export class MonitorDO {
@@ -90,7 +92,7 @@ export class MonitorDO {
let soonest = null;
for (const m of Object.values(mons)) {
if (m.paused) continue;
- const due = (m.lastRunAt || 0) + Math.max(m.intervalMs || 0, MIN_INTERVAL);
+ const due = dueAt(m);
if (soonest == null || due < soonest) soonest = due;
}
if (soonest != null) await this.storage.setAlarm(Math.max(soonest, now() + 1000));
@@ -220,8 +222,16 @@ export class MonitorDO {
const ran = [];
for (const m of Object.values(mons)) {
if (m.paused) continue;
- const due = (m.lastRunAt || 0) + Math.max(m.intervalMs || 0, MIN_INTERVAL);
- if (deps.force || t >= due) ran.push(await this._runOne(m, deps, mons));
+ if (!deps.force && t < dueAt(m)) continue;
+ // scheduled runs re-check the plan of whoever set the monitor up: a downgrade (or the
+ // workspace owner turning plan sharing off) holds it until someone with the plan resumes
+ if (!deps.force && deps.planOk && !(await deps.planOk(m))) {
+ m.planHeld = true; m.planHeldAt = t;
+ await this._log("history", HISTORY_CAP, { id: m.id, at: t, error: "held: the plan of the person who set this monitor up no longer includes monitoring" });
+ continue;
+ }
+ if (m.planHeld) { delete m.planHeld; delete m.planHeldAt; }
+ ran.push(await this._runOne(m, deps, mons));
}
await this._put(mons);
await this._reschedule();
@@ -229,7 +239,9 @@ export class MonitorDO {
}
async alarm() {
- await this.state.blockConcurrencyWhile(async () => { await this.runDue({}); });
+ const wid = await this.storage.get("wid");
+ const planOk = async (m) => { if (!wid) return true; const t = await liveTier(this.env, wid, m.by || "", this.planOpts); return t === null || !featureDenied("monitors", t); };
+ await this.state.blockConcurrencyWhile(async () => { await this.runDue({ planOk }); });
}
// ---- HTTP interface for the Deck (via handleMonitor) ----
@@ -264,13 +276,15 @@ export class MonitorDO {
const mons = await this._monitors();
const id = m.id && mons[m.id] ? m.id : uid();
const prev = mons[id] || {};
- mons[id] = { id, name: m.name || m.type, type: m.type, config: m.config || {}, rules: m.rules || prev.rules || {}, channels: Array.isArray(m.channels) ? m.channels : (prev.channels || []), intervalMs: Math.max(m.intervalMs || prev.intervalMs || MIN_INTERVAL, MIN_INTERVAL), paused: !!m.paused, lastRunAt: prev.lastRunAt || 0, lastResults: prev.lastResults || [], graphMeta: prev.graphMeta || {}, baselined: prev.baselined || [] };
+ mons[id] = { id, name: m.name || m.type, type: m.type, config: m.config || {}, rules: m.rules || prev.rules || {}, channels: Array.isArray(m.channels) ? m.channels : (prev.channels || []), intervalMs: Math.max(m.intervalMs || prev.intervalMs || MIN_INTERVAL, MIN_INTERVAL), paused: !!m.paused, by: request.headers.get("x-mon-uid"), lastRunAt: prev.lastRunAt || 0, lastResults: prev.lastResults || [], graphMeta: prev.graphMeta || {}, baselined: prev.baselined || [] };
await this._put(mons); await this._reschedule();
return reply({ monitor: safeMonitor(mons[id]) });
}
if (op === "pause") {
const mons = await this._monitors(); const m = mons[body.id]; if (!m) return reply({ error: "not found" }, 404);
- m.paused = !!body.paused; await this._put(mons); await this._reschedule();
+ m.paused = !!body.paused;
+ if (!m.paused) { m.by = request.headers.get("x-mon-uid"); delete m.planHeld; delete m.planHeldAt; } // resuming passed the plan check: the resumer now carries it
+ await this._put(mons); await this._reschedule();
return reply({ monitor: safeMonitor(m) });
}
if (op === "delete") {
@@ -313,9 +327,10 @@ export async function handleMonitor(request, env, wid, json) {
const bodyText = await readCapped(request, 256 * 1024);
if (bodyText === null) return json({ error: "Request too large." }, 413);
// Adding, editing or running a monitor needs the plan; list, pause and delete stay open
- // so someone who downgrades can still see and clean up what they had.
- let op = ""; try { op = String((JSON.parse(bodyText || "{}") || {}).op || ""); } catch (_) {}
- if (MON_PAID_OPS.has(op)) {
+ // so someone who downgrades can still see and clean up what they had (but not resume).
+ // Resuming a paused monitor restarts paid work, so it needs the plan too.
+ let op = "", resume = false; try { const b = JSON.parse(bodyText || "{}") || {}; op = String(b.op || ""); resume = op === "pause" && b.paused === false; } catch (_) {}
+ if (MON_PAID_OPS.has(op) || resume) {
const planMsg = featureDenied("monitors", await workspaceTier(env, wid, who));
if (planMsg) return json({ error: planMsg, plan: true }, 402);
}
diff --git a/worker/plan-share.js b/worker/plan-share.js
index bbbbe128..5c195c7f 100644
--- a/worker/plan-share.js
+++ b/worker/plan-share.js
@@ -63,4 +63,35 @@ export async function workspaceTier(env, wid, principal, opts = {}) {
return planRank(lent) > planRank(own) ? lent : own;
}
-export const _resetShareCache = () => _cache.clear(); // tests
+// The plan behind work that runs with no user request (monitor alarms, API-key ingest): the live
+// plan of `uid` (whoever set the work up) inside `wid`, read with the service account. Work set
+// up before the creator was recorded falls back to the workspace's owner: the personal
+// workspace's own user, or a team workspace's createdBy. null when it cannot be read, so a
+// Firestore blip never stops paid work; callers treat null as allowed.
+const _live = new Map(); // wid|uid -> { at, tier }
+export async function liveTier(env, wid, uid, opts = {}) {
+ const projectId = (env || {}).FIREBASE_PROJECT_ID;
+ if (!projectId || !wid) return null;
+ const cache = opts.cache || _live, now = opts.now ?? Date.now(), ck = wid + "|" + (uid || "");
+ const hit = cache.get(ck);
+ if (hit && now - hit.at < TTL_MS) return hit.tier;
+ const f = opts.fetch || fetch;
+ try {
+ const sa = await (opts.token || googleToken)(env);
+ if (!uid) {
+ if (!isTeamWorkspaceId(wid)) uid = wid;
+ else { const w = await getFields(fsDoc(projectId, "workspaces/" + encodeURIComponent(wid), ["createdBy"]), sa, f); uid = w && w.createdBy && w.createdBy.stringValue; if (!uid) return null; }
+ }
+ const r = await f(fsDoc(projectId, "users/" + encodeURIComponent(uid), ["tier", "admin"]), { headers: { Authorization: "Bearer " + sa } });
+ if (!r.ok && r.status !== 404) return null; // 404 = no profile = free
+ const u = r.ok ? (((await r.json().catch(() => null)) || {}).fields || {}) : {};
+ const v = u.tier && u.tier.stringValue;
+ let tier = u.admin && u.admin.booleanValue === true ? "enterprise" : (v && planRank(v) > 0 ? v.toLowerCase() : "free");
+ if (isTeamWorkspaceId(wid)) { const lent = await sharedWorkspaceTier(env, wid, { token: sa }, { fetch: opts.fetch, now: opts.now, token: opts.token, cache: opts.shareCache }); if (planRank(lent) > planRank(tier)) tier = lent; }
+ if (cache.size > 5000) cache.clear();
+ cache.set(ck, { at: now, tier });
+ return tier;
+ } catch (_) { return null; }
+}
+
+export const _resetShareCache = () => { _cache.clear(); _live.clear(); }; // tests