thumbgate 1.40.12 → 1.40.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,161 @@
1
+ 'use strict';
2
+
3
+ // Cost meter: what it costs to run ThumbGate's hosted service, measured from inside the container for free.
4
+ //
5
+ // Railway bills each service by the minute for the vCPU and memory it uses. This meter samples the container's own
6
+ // cgroup counters once a minute (falling back to this Node process when the cgroup files are not readable), keeps
7
+ // one row per UTC day for 35 days in <feedbackDir>/cost-meter.json, and counts emails the mailer sent. Nothing here
8
+ // calls a paid API, and no address, subject or customer identity is stored: only daily totals.
9
+ //
10
+ // The owner console turns these totals into dollars with the list rates in config/unit-costs.json.
11
+
12
+ const fs = require('node:fs');
13
+ const path = require('node:path');
14
+
15
+ const FILE = 'cost-meter.json';
16
+ const KEEP_DAYS = 35;
17
+ const MAX_FILE_BYTES = 256 * 1024;
18
+ const state = { feedbackDir: null, days: {}, loaded: false, last: null, timer: null };
19
+
20
+ const dayKey = (ms) => new Date(ms).toISOString().slice(0, 10);
21
+ const finite = (n) => (Number.isFinite(n) && n >= 0 ? n : 0);
22
+
23
+ function readFileSafe(file) {
24
+ try {
25
+ const stat = fs.statSync(file);
26
+ if (!stat.isFile() || stat.size > MAX_FILE_BYTES) return null;
27
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
28
+ } catch { return null; }
29
+ }
30
+
31
+ function cleanDays(raw) {
32
+ const out = {};
33
+ for (const [key, row] of Object.entries(raw && typeof raw === 'object' ? raw : {})) {
34
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(key) || !row || typeof row !== 'object') continue;
35
+ out[key] = { sampledSeconds: finite(row.sampledSeconds), cpuSeconds: finite(row.cpuSeconds), memoryGbSeconds: finite(row.memoryGbSeconds), emails: Math.floor(finite(row.emails)), source: typeof row.source === 'string' ? row.source.slice(0, 16) : null };
36
+ }
37
+ return out;
38
+ }
39
+
40
+ function prune(days, nowMs) {
41
+ const oldest = dayKey(nowMs - KEEP_DAYS * 86400000);
42
+ for (const key of Object.keys(days)) if (key < oldest) delete days[key];
43
+ return days;
44
+ }
45
+
46
+ function load() {
47
+ if (state.loaded || !state.feedbackDir) return;
48
+ state.loaded = true;
49
+ const saved = readFileSafe(path.join(state.feedbackDir, FILE));
50
+ // Counts made before the file was read (for example an email sent during start-up) are added to what was saved.
51
+ const saved_days = cleanDays(saved?.days);
52
+ for (const [key, row] of Object.entries(state.days)) {
53
+ const into = saved_days[key] || (saved_days[key] = { sampledSeconds: 0, cpuSeconds: 0, memoryGbSeconds: 0, emails: 0, source: row.source });
54
+ into.sampledSeconds += row.sampledSeconds; into.cpuSeconds += row.cpuSeconds; into.memoryGbSeconds += row.memoryGbSeconds; into.emails += row.emails;
55
+ }
56
+ state.days = saved_days;
57
+ }
58
+
59
+ function flush(nowMs = Date.now()) {
60
+ if (!state.feedbackDir) return false;
61
+ load();
62
+ prune(state.days, nowMs);
63
+ const file = path.join(state.feedbackDir, FILE);
64
+ const tmp = `${file}.${process.pid}.tmp`;
65
+ try {
66
+ fs.mkdirSync(state.feedbackDir, { recursive: true });
67
+ fs.writeFileSync(tmp, JSON.stringify({ version: 1, updatedAt: new Date(nowMs).toISOString(), days: state.days }));
68
+ fs.renameSync(tmp, file);
69
+ return true;
70
+ } catch {
71
+ try { fs.rmSync(tmp, { force: true }); } catch { /* nothing to clean */ }
72
+ return false;
73
+ }
74
+ }
75
+
76
+ function row(nowMs, source) {
77
+ const key = dayKey(nowMs);
78
+ return state.days[key] || (state.days[key] = { sampledSeconds: 0, cpuSeconds: 0, memoryGbSeconds: 0, emails: 0, source });
79
+ }
80
+
81
+ // Container counters when Railway's cgroup v2 files are readable, else this process. Returns null when nothing is readable.
82
+ function readCounters({ cgroupRoot = '/sys/fs/cgroup', proc = process } = {}) {
83
+ try {
84
+ const stat = fs.readFileSync(path.join(cgroupRoot, 'cpu.stat'), 'utf8');
85
+ const usage = /usage_usec\s+(\d+)/.exec(stat);
86
+ const memory = Number(fs.readFileSync(path.join(cgroupRoot, 'memory.current'), 'utf8').trim());
87
+ if (usage && Number.isFinite(memory)) return { source: 'container', cpuSeconds: Number(usage[1]) / 1e6, memoryBytes: memory };
88
+ } catch { /* not a cgroup v2 container */ }
89
+ try {
90
+ const cpu = proc.cpuUsage();
91
+ return { source: 'process', cpuSeconds: (cpu.user + cpu.system) / 1e6, memoryBytes: proc.memoryUsage().rss };
92
+ } catch { return null; }
93
+ }
94
+
95
+ // One sample: CPU used since the last sample, and memory held for the time between them.
96
+ function sample({ nowMs = Date.now(), counters = readCounters() } = {}) {
97
+ if (!counters) return null;
98
+ const last = state.last;
99
+ state.last = { at: nowMs, ...counters };
100
+ if (!last || last.source !== counters.source) return null;
101
+ const seconds = (nowMs - last.at) / 1000;
102
+ const cpu = counters.cpuSeconds - last.cpuSeconds;
103
+ // A restart, a clock jump or a counter reset gives a gap or a negative step: skip it rather than guess.
104
+ if (!(seconds > 0 && seconds <= 600) || !(cpu >= 0)) return null;
105
+ load();
106
+ const into = row(nowMs, counters.source);
107
+ into.sampledSeconds += seconds;
108
+ into.cpuSeconds += cpu;
109
+ into.memoryGbSeconds += ((last.memoryBytes + counters.memoryBytes) / 2 / 1e9) * seconds;
110
+ into.source = counters.source;
111
+ return { seconds, cpuSeconds: cpu };
112
+ }
113
+
114
+ function recordEmailSend({ nowMs = Date.now(), count = 1 } = {}) {
115
+ if (!Number.isInteger(count) || count < 1) return;
116
+ load();
117
+ row(nowMs, state.last?.source || null).emails += count;
118
+ }
119
+
120
+ function configure({ feedbackDir } = {}) {
121
+ if (feedbackDir && feedbackDir !== state.feedbackDir) { state.feedbackDir = feedbackDir; state.loaded = false; }
122
+ return state.feedbackDir;
123
+ }
124
+
125
+ function start({ feedbackDir, intervalMs = 60000 } = {}) {
126
+ configure({ feedbackDir });
127
+ if (state.timer) return state.timer;
128
+ sample();
129
+ state.timer = setInterval(() => { sample(); flush(); }, intervalMs);
130
+ state.timer.unref?.();
131
+ return state.timer;
132
+ }
133
+
134
+ function stop() { if (state.timer) clearInterval(state.timer); state.timer = null; }
135
+
136
+ function reset() { stop(); state.feedbackDir = null; state.days = {}; state.loaded = false; state.last = null; }
137
+
138
+ // Totals for the last `days` UTC days, today included, read from disk plus anything not yet written.
139
+ function readWindow({ feedbackDir = state.feedbackDir, days = 30, nowMs = Date.now() } = {}) {
140
+ let rows = {};
141
+ if (feedbackDir && feedbackDir === state.feedbackDir) { load(); rows = state.days; }
142
+ else if (feedbackDir) rows = cleanDays(readFileSafe(path.join(feedbackDir, FILE))?.days);
143
+ const oldest = dayKey(nowMs - (days - 1) * 86400000);
144
+ const total = { days, daysWithSamples: 0, sampledSeconds: 0, cpuSeconds: 0, memoryGbSeconds: 0, emails: 0, sources: [] };
145
+ const sources = new Set();
146
+ for (const [key, entry] of Object.entries(rows)) {
147
+ if (key < oldest || key > dayKey(nowMs)) continue;
148
+ if (entry.sampledSeconds > 0) total.daysWithSamples += 1;
149
+ total.sampledSeconds += entry.sampledSeconds;
150
+ total.cpuSeconds += entry.cpuSeconds;
151
+ total.memoryGbSeconds += entry.memoryGbSeconds;
152
+ total.emails += entry.emails;
153
+ if (entry.source) sources.add(entry.source);
154
+ }
155
+ total.sources = [...sources].sort();
156
+ total.windowSeconds = days * 86400;
157
+ total.coverage = Math.min(1, total.sampledSeconds / total.windowSeconds);
158
+ return total;
159
+ }
160
+
161
+ module.exports = { configure, start, stop, reset, sample, flush, recordEmailSend, readWindow, readCounters, FILE };
@@ -277,6 +277,8 @@ async function sendEmail({ to, subject, html, text, from, replyTo, idempotencyKe
277
277
  console.warn(`[mailer] Resend returned ${res.status}:`, bodyText);
278
278
  return { sent: false, reason: 'api_error', status: res.status, body: bodyJson || bodyText };
279
279
  }
280
+ // Daily send count for the owner console's delivery cost. A count only: nothing about the message is kept.
281
+ try { require('../cost-meter').recordEmailSend(); } catch { /* best-effort */ }
280
282
  return buildSendSuccess({ bodyJson, status: res.status, senderFallback: sender.senderFallback });
281
283
  } catch (err) {
282
284
  // eslint-disable-next-line no-console
@@ -9,12 +9,14 @@ const ownerTelemetry = require('./owner-telemetry');
9
9
  const opsLog = require('./ops-log');
10
10
  const opsReport = require('./ops-report');
11
11
  const ownerAlerts = require('./owner-alerts');
12
+ const costMeter = require('./cost-meter');
13
+ const unitEconomics = require('./unit-economics');
12
14
 
13
15
  const JSON_LIMIT = 8 * 1024 * 1024;
14
16
  const LOG_LIMIT = 16 * 1024 * 1024;
15
17
  const RESPONSE_LIMIT = 1024 * 1024;
16
18
  const RESOURCES = Object.freeze({ customers: 'cus', subscriptions: 'sub', payments: 'ch', refunds: 're', products: 'prod', prices: 'price', 'subscription-items': 'si' });
17
- const SECTIONS = new Set(['overview', 'money', 'data', 'analytics', 'observability', 'summary', 'alerts']);
19
+ const SECTIONS = new Set(['overview', 'money', 'data', 'analytics', 'observability', 'summary', 'alerts', 'economics']);
18
20
  const MONEY_CACHE_MS = 60000;
19
21
  let moneyCache = null;
20
22
  const PRIVATE_HEADERS = Object.freeze({ 'Cache-Control': 'private, no-store', Vary: 'Cookie', 'X-Robots-Tag': 'noindex, nofollow', 'Referrer-Policy': 'no-referrer', 'X-Content-Type-Options': 'nosniff' });
@@ -530,7 +532,9 @@ const thumbgateSession = (row) => /thumbgate/i.test(String(row.success_url || ''
530
532
  // Why a Stripe source failed, in words a person can act on. Never a bare "Unknown".
531
533
  function stripeReason(error) {
532
534
  if (/STRIPE_SECRET_KEY is missing/i.test(String(error?.message || ''))) return 'Stripe key missing';
533
- if (error?.code === 'collection_timeout') return 'Stripe did not answer in time';
535
+ // The request's own timeout is set to the time left before the shared deadline, so it can fire first: that is the
536
+ // same "no answer in time", not an outage.
537
+ if (error?.code === 'collection_timeout' || error?.code === 'ETIMEDOUT' || /timed? ?out/i.test(String(error?.message || ''))) return 'Stripe did not answer in time';
534
538
  if (error?.code === 'provider_busy') return 'Stripe is busy, refresh in a moment';
535
539
  return 'Stripe unavailable';
536
540
  }
@@ -542,6 +546,53 @@ const telemetryReason = (error) => (error?.code === 'collection_timeout' ? 'tele
542
546
 
543
547
  const trafficFields = (read) => ({ visitors: read.traffic.visitors, realVisitors: read.traffic.realVisitors, botOrInternalVisitors: read.traffic.botOrInternalVisitors, pageViewers: read.traffic.pageViewers, checkoutStartsByType: read.traffic.checkoutStartsByType, sessions: read.traffic.sessions, pageViews: read.traffic.pageViews, ctaClicks: read.traffic.ctaClicks, checkoutStarts: read.traffic.checkoutStarts, checkoutPaidConfirmations: read.traffic.checkoutPaidConfirmations });
544
548
 
549
+ const attemptSync = (work) => { try { return work(); } catch { return { status: 'unavailable', reason: 'The key store could not be read.' }; } };
550
+
551
+ // Payment to access: every purchase that still grants access should have a ThumbGate key that works, and every working paid
552
+ // key should trace to a payment. Counts only; no customer id or address leaves this function.
553
+ // - `entitled` is who should hold access now: credit-pack buyers (one year) and active subscribers. Service orders and
554
+ // canceled subscriptions grant no key, so they are not expected to have one.
555
+ // - A key works the way billing.validateApiKey() decides: active, and not a credit pack with no credits left. A used-up
556
+ // credit pack was provisioned, so it is counted apart (`exhaustedCreditKeys`), never as a provisioning failure.
557
+ // - A working paid key with no Stripe match is listed for review, not called wrong: GitHub Marketplace, PayPal and manual
558
+ // grants also make keys.
559
+ const isTrialOrFree = (meta) => /free|trial/i.test(String(meta.plan || '') + ' ' + String(meta.tier || '') + ' ' + String(meta.source || ''));
560
+ const creditsExhausted = (meta) => meta.remainingCredits !== undefined && meta.remainingCredits !== null && meta.remainingCredits <= 0;
561
+ function paymentAccessCheck({ entitled, failing, store, complete = true }) {
562
+ const active = Object.values(store?.keys || {}).filter((meta) => meta && meta.active === true);
563
+ const working = active.filter((meta) => !creditsExhausted(meta));
564
+ const owners = (list) => {
565
+ const out = new Set();
566
+ for (const meta of list) {
567
+ if (meta.customerId) out.add(String(meta.customerId));
568
+ if (meta.customerEmail) out.add(String(meta.customerEmail).toLowerCase());
569
+ }
570
+ return out;
571
+ };
572
+ const provisioned = owners(active);
573
+ const withAccess = owners(working);
574
+ const has = (set, who) => set.has(String(who)) || set.has(String(who).toLowerCase());
575
+ const paidKeys = working.filter((meta) => !isTrialOrFree(meta));
576
+ const paidWithoutAccess = [...entitled].filter((who) => !has(provisioned, who)).length;
577
+ const accessWithoutStripePayment = paidKeys.filter((meta) => !entitled.has(String(meta.customerId || '')) && !entitled.has(String(meta.customerEmail || '').toLowerCase())).length;
578
+ const failingIds = Array.isArray(failing) ? failing.map((row) => row.customer).filter(Boolean) : null;
579
+ const failedPaymentWithAccess = failingIds ? failingIds.filter((who) => has(withAccess, who)).length : null;
580
+ const problems = paidWithoutAccess + (failedPaymentWithAccess || 0);
581
+ return {
582
+ status: problems ? 'needs_review' : accessWithoutStripePayment ? 'review' : 'ok',
583
+ complete: complete && failingIds !== null,
584
+ entitledCustomers: entitled.size,
585
+ activeKeys: working.length,
586
+ activePaidKeys: paidKeys.length,
587
+ activeTrialOrFreeKeys: working.length - paidKeys.length,
588
+ exhaustedCreditKeys: active.length - working.length,
589
+ paidWithoutAccess,
590
+ accessWithoutStripePayment,
591
+ failedPaymentSubscriptions: failingIds ? failingIds.length : null,
592
+ failedPaymentWithAccess,
593
+ };
594
+ }
595
+
545
596
  // Money board. Each block fails alone: its fields are null and a plain-words reason is returned beside them.
546
597
  // Stripe answers paying customers, revenue and checkouts; our own page-view telemetry answers visitors.
547
598
  async function collectMoney(deps, signal) {
@@ -579,7 +630,7 @@ async function collectMoney(deps, signal) {
579
630
  const paidAndProLane = (async () => {
580
631
  const paidResult = await withLastGood('paid', async () => {
581
632
  const result = await listIt((params, options) => stripe().checkout.sessions.list(params, options),
582
- { status: 'complete', created: { gte: nowSeconds - 365 * 86400 }, expand: ['data.payment_intent.latest_charge'] },
633
+ { status: 'complete', created: { gte: nowSeconds - 365 * 86400 }, expand: ['data.payment_intent.latest_charge.balance_transaction'] },
583
634
  (row) => row.status === 'complete' && thumbgateSession(row), 10);
584
635
  // Paid and not refunded in full, owner and test purchases excluded. A partial refund comes off the revenue.
585
636
  const charge = (row) => (object(row.payment_intent) && object(row.payment_intent.latest_charge) ? row.payment_intent.latest_charge : null);
@@ -594,15 +645,27 @@ async function collectMoney(deps, signal) {
594
645
  const who = id(row.customer) || String(row.customer_details?.email || row.customer_email || row.id).toLowerCase();
595
646
  if (!counted.has(who)) { counted.add(who); channel(channelOf(row)).paidCustomers += 1; }
596
647
  }
648
+ // Stripe's own fee on each 30-day checkout, read from the charge's balance transaction when Stripe returns it.
649
+ const fees = { reportedFees: {}, unreportedCharges: 0, unreportedAmount: {}, subscriptionFirstCharges: {} };
597
650
  for (const row of paid) {
598
651
  if (!(row.created >= nowSeconds - 30 * 86400) || !Number.isSafeInteger(row.amount_total) || !/^[a-z]{3}$/i.test(row.currency || '')) continue;
599
652
  const code = row.currency.toUpperCase();
600
653
  const refunded = Number.isSafeInteger(charge(row)?.amount_refunded) ? charge(row).amount_refunded : 0;
601
654
  revenue[code] = (revenue[code] || 0) + row.amount_total - refunded;
655
+ const fee = charge(row)?.balance_transaction?.fee;
656
+ if (Number.isSafeInteger(fee)) {
657
+ const feeCode = String(charge(row).balance_transaction.currency || row.currency).toUpperCase();
658
+ fees.reportedFees[feeCode] = (fees.reportedFees[feeCode] || 0) + fee;
659
+ } else { fees.unreportedCharges += 1; fees.unreportedAmount[code] = (fees.unreportedAmount[code] || 0) + row.amount_total; }
660
+ if (row.mode === 'subscription') fees.subscriptionFirstCharges[code] = (fees.subscriptionFirstCharges[code] || 0) + row.amount_total;
602
661
  const byChannel = channel(channelOf(row)).revenue30d;
603
662
  byChannel[code] = (byChannel[code] || 0) + row.amount_total - refunded;
604
663
  }
605
- return { customers, revenue, channels, complete: result.complete };
664
+ // Credit-pack buyers keep access for the pack's life; a subscription checkout's access is checked against active
665
+ // subscriptions instead, and a service order grants no key.
666
+ const grant = deps.resolveCheckoutProvisioningGrant || billing._resolveCheckoutProvisioningGrant;
667
+ const creditPackCustomers = new Set(paid.filter((row) => grant(row).kind === 'credit_pack').map((row) => id(row.customer) || String(row.customer_details?.email || row.customer_email || row.id).toLowerCase()));
668
+ return { customers, creditPackCustomers, revenue, channels, fees, complete: result.complete };
606
669
  });
607
670
  const proResult = await withLastGood('subscriptions', async () => {
608
671
  const result = await listIt((params, options) => stripe().subscriptions.list(params, options), { status: 'active', expand: ['data.customer'] }, () => true, 5);
@@ -630,7 +693,15 @@ async function collectMoney(deps, signal) {
630
693
  }
631
694
  const cancelled = await listIt((params, options) => stripe().subscriptions.list(params, options), { status: 'canceled', expand: ['data.customer'] },
632
695
  (row) => Number(row.canceled_at || row.ended_at) >= since30 && !isOwnerEmail(row.customer?.email), 5);
633
- return { renewals, renewalCount: invoices.rows.length, churned: cancelled.rows.length, churnedMrr: monthlyRecurring(cancelled.rows).mrr, complete: invoices.complete && cancelled.complete };
696
+ // Failed payments: subscriptions Stripe could not charge. Their customer ids feed the payment-to-access check.
697
+ const failing = [];
698
+ let failingComplete = true;
699
+ for (const status of ['past_due', 'unpaid']) {
700
+ const listed = await listIt((params, options) => stripe().subscriptions.list(params, options), { status }, (row) => row.status === status, 2);
701
+ failingComplete &&= listed.complete;
702
+ for (const row of listed.rows) failing.push({ status, customer: id(row.customer) });
703
+ }
704
+ return { renewals, renewalCount: invoices.rows.length, churned: cancelled.rows.length, churnedMrr: monthlyRecurring(cancelled.rows).mrr, failing, complete: invoices.complete && cancelled.complete && failingComplete };
634
705
  });
635
706
  let paidAndPro; let sessionRun; let trafficRun; let summaryRun; let recurringRun;
636
707
  try {
@@ -685,6 +756,12 @@ async function collectMoney(deps, signal) {
685
756
  internal: counts.excluded.internal,
686
757
  } : null);
687
758
  const bothStripe = paid && proRun.value;
759
+ const access = bothStripe ? attemptSync(() => paymentAccessCheck({
760
+ entitled: new Set([...(paid.creditPackCustomers || []), ...proRun.value.customers]),
761
+ failing: recurringRun.ok ? recurringRun.value.failing : null,
762
+ store: (deps.loadKeyStore || billing.loadKeyStore)(),
763
+ complete: paid.complete && proRun.value.complete,
764
+ })) : null;
688
765
  // The checkout panel: sessions with no bot check on record come first, then people, bots and owner only for sessions
689
766
  // created after the bot check began, then the gap between the site's own start events and Stripe's sessions.
690
767
  const checkoutBotCheck = (counts, traffic) => {
@@ -741,6 +818,7 @@ async function collectMoney(deps, signal) {
741
818
  renewalInvoices: recurringRun.value.renewalCount,
742
819
  churnedSubscriptions: recurringRun.value.churned,
743
820
  churnedMrr: recurringRun.value.churnedMrr,
821
+ failedPaymentSubscriptions: recurringRun.value.failing.length,
744
822
  churnRate: proRun.value && proRun.value.count + recurringRun.value.churned > 0 ? Math.round((recurringRun.value.churned / (proRun.value.count + recurringRun.value.churned)) * 1000) / 1000 : null,
745
823
  complete: recurringRun.value.complete,
746
824
  } : null,
@@ -754,6 +832,8 @@ async function collectMoney(deps, signal) {
754
832
  weekOverWeek: trafficReason ? null : (trafficRead.weeks || null),
755
833
  activeProBasis: proRun.value ? (proRun.value.complete ? 'stripe_active_subscriptions_excluding_owner' : 'stripe_active_subscriptions_first_100_only') : 'unavailable',
756
834
  revenueLast30Days: paid ? paid.revenue : null,
835
+ paymentFees30d: paid ? paid.fees : null,
836
+ paymentAccess: access,
757
837
  revenueBasis: 'stripe_paid_checkouts_after_refunds',
758
838
  checkouts7d: sessionBuckets(sessions?.d7),
759
839
  checkouts30d: sessionBuckets(sessions?.d30),
@@ -820,6 +900,24 @@ async function collectAnalytics(deps, signal) {
820
900
  return envelope('telemetry_tail_and_billing_summary_30d', data, warnings);
821
901
  }
822
902
 
903
+ // Unit economics: delivery cost per active install and per paying customer, contribution per plan, payment-to-access.
904
+ function economicsFrom(money, deps) {
905
+ const meter = (deps.readCostMeter || ((options) => costMeter.readWindow(options)))({ feedbackDir: deps.feedbackDir, days: 30 });
906
+ return unitEconomics.computeUnitEconomics({ money, usage: money?.usage30d || null, meter, costs: deps.unitCosts || unitEconomics.loadUnitCosts() });
907
+ }
908
+
909
+ async function collectEconomics(deps, signal) {
910
+ const moneyRun = await attempt(() => collectMoney(deps, signal), () => 'Money collection failed');
911
+ const money = moneyRun.ok ? moneyRun.value.data : null;
912
+ const data = economicsFrom(money, deps);
913
+ data.paymentAccess = money?.paymentAccess || null;
914
+ data.firstValue = money?.usage30d ? { activeInstalls30d: money.usage30d.activeInstalls30d, initsInWindow: money.usage30d.initsInWindow, firstValueInstalls: money.usage30d.firstValueInstalls ?? null, timeToFirstValue: money.usage30d.timeToFirstValue || null } : null;
915
+ const warnings = [];
916
+ if (!money) warnings.push('money_unavailable');
917
+ if (data.status !== 'ok') warnings.push('costs_partial');
918
+ return envelope('unit_economics_30d', data, warnings);
919
+ }
920
+
823
921
  // One metric of the read-only summary: its value, where it came from, when that source was read, and one of these states:
824
922
  // ok a number from a source that answered in full
825
923
  // verified_zero a zero from a source that answered in full
@@ -880,6 +978,14 @@ async function collectSummary(deps, signal) {
880
978
  add('money.signups_by_source', 'Signups by source', money.leadsBySource?.signups ?? null, leadOpts);
881
979
  add('money.workflow_sprint_leads', 'Setup Sprint leads', money.leadsBySource?.workflowSprint ?? null, leadOpts);
882
980
  add('money.newsletter', 'Newsletter signups', money.leadsBySource?.newsletter ?? null, leadOpts);
981
+ add('money.payment_access', 'Payment to access check: entitled customers (active subscription or credit pack) without a key, working paid keys without a Stripe payment, failed payments still holding a working key', money.paymentAccess || null, stripeOpts('paid', why.payingCustomers));
982
+ const econ = economicsFrom(money, deps);
983
+ const econOpts = { source: 'cost_meter_and_stripe', collectedAt: refreshed, partial: econ.status !== 'ok', reason: econ.reasons?.hosting || null };
984
+ add('economics.delivery_cost_30d_usd', 'Cost to deliver the service, past 30 days, US dollars (hosting, email, payment fees, fixed)', econ.delivery?.totalUsd ?? null, econOpts);
985
+ add('economics.cost_per_active_install_usd', 'Hosting, email and fixed cost per active CLI install, past 30 days, US dollars', econ.perActiveInstallUsd ?? null, { ...econOpts, reason: econ.reasons?.activeInstalls || econOpts.reason });
986
+ add('economics.cost_per_paying_customer_usd', 'Delivery cost per paying customer, past 30 days, US dollars', econ.perPayingCustomerUsd ?? null, { ...econOpts, reason: econ.reasons?.payingCustomers || econOpts.reason });
987
+ add('economics.contribution_30d', 'Revenue minus delivery cost, past 30 days, US dollars', econ.contribution || null, econOpts);
988
+ add('economics.plans', 'Contribution per sale for each plan, US dollars', econ.plans || null, econOpts);
883
989
  }
884
990
  const traffic = analytics?.trafficMetrics || money?.traffic30d || null;
885
991
  const trafficField = (key, label, name) => add(key, label, traffic ? traffic[name] ?? null : null, trafficOpts);
@@ -895,6 +1001,8 @@ async function collectSummary(deps, signal) {
895
1001
  usageField('usage.active_installs_30d', 'CLI installs active in the past 30 days (owner and CI excluded)', 'activeInstalls30d');
896
1002
  usageField('usage.activated_installs_30d', 'Active installs that captured feedback (30 days)', 'activatedInstalls');
897
1003
  usageField('usage.returning_installs_30d', 'Active installs seen on 2 or more days (30 days)', 'returningInstalls');
1004
+ usageField('usage.first_value_installs_30d', 'Installs whose first real gate block arrived in the past 30 days', 'firstValueInstalls');
1005
+ usageField('usage.time_to_first_value', 'Minutes from install to first real gate block (median and 75th percentile)', 'timeToFirstValue');
898
1006
  add('usage.install_cohorts_8w', 'Weekly CLI install cohorts and how many came back each later week (8 weeks)', analytics?.cohorts?.cohorts ?? null, { ...trafficOpts, partial: analytics?.cohorts?.partial === true });
899
1007
  if (money) add('money.channels', 'Checkout starts (30 days), paying customers (first paid checkout, 1 year) and revenue (30 days) by channel', money.channels, stripeOpts('paid', why.revenue));
900
1008
  add('traffic.week_over_week', 'Past 7 days against the 7 days before', analytics?.weekOverWeek || money?.weekOverWeek || null, trafficOpts);
@@ -911,7 +1019,9 @@ async function collectSummary(deps, signal) {
911
1019
 
912
1020
  // A permanent, stated gap is listed apart so the overall state reflects sources that failed, not a feature not built yet.
913
1021
  const knownGaps = [];
914
- const states = Object.entries(fields).filter(([key]) => !knownGaps.includes(key)).map(([, entry]) => entry.status);
1022
+ // Unit economics are estimates at list rates and start empty until the cost meter has samples, so they never decide the
1023
+ // summary's overall state; each one carries its own status.
1024
+ const states = Object.entries(fields).filter(([key]) => !knownGaps.includes(key) && !key.startsWith('economics.')).map(([, entry]) => entry.status);
915
1025
  const bad = states.filter((state) => state === 'unavailable').length;
916
1026
  const overall = !money && !analytics ? 'unavailable' : states.every((state) => state === 'ok' || state === 'verified_zero') ? 'ok' : 'partial';
917
1027
  return envelope('owner_console_summary', { generatedAt: refreshed, readOnly: true, windows: { checkouts: '7d and 30d', traffic: '30d', revenue: '30d' }, freshness: { displayRefreshedAt: refreshed, stripeCollectedAt: fresh.checkouts?.collectedAt || null, telemetryCollectedAt: fresh.traffic?.collectedAt || null, leadsCollectedAt: fresh.leads?.collectedAt || null, telemetryCacheSeconds: Math.round((deps.telemetryCacheMs ?? TELEMETRY_CACHE_MS) / 1000), billingSummaryCacheSeconds: Math.round(SUMMARY_TTL_MS / 1000) }, fields, knownGaps, unavailableFields: bad }, [], overall);
@@ -960,7 +1070,7 @@ function postOwnerWebhook(platform, webhookUrl, title, message) {
960
1070
  }
961
1071
 
962
1072
  // Checks the alerts every 15 minutes and sends the new ones to the channels above. Does nothing when none is set.
963
- function startAlertDelivery(makeDeps, { intervalMs = 15 * 60 * 1000, send } = {}) {
1073
+ function startAlertDelivery(makeDeps, { intervalMs = 15 * 60 * 1000, firstCheckMs = 60000, send } = {}) {
964
1074
  const channels = alertChannels();
965
1075
  if (!channels.length && !send) return null;
966
1076
  const url = String(process.env.THUMBGATE_OWNER_ALERT_WEBHOOK || '').trim();
@@ -969,21 +1079,33 @@ function startAlertDelivery(makeDeps, { intervalMs = 15 * 60 * 1000, send } = {}
969
1079
  if (channels.includes('webhook')) await postOwnerWebhook(platform, url, title, message).catch(() => null);
970
1080
  if (channels.includes('email')) {
971
1081
  const to = require('./bot-detection').getOwnerEmails();
972
- if (to.length) await require('./mailer/resend-mailer').sendEmail({ to: String(to[0]), subject: title, text: message }).catch(() => null);
1082
+ const sent = to.length ? await require('./mailer/resend-mailer').sendEmail({ to: String(to[0]), subject: title, text: message }).catch(() => null) : null;
1083
+ console.log('[owner-alerts] email ' + (sent && sent.sent !== false ? 'sent' : 'not sent (' + (sent?.reason || (to.length ? 'error' : 'no_owner_address')) + ')'));
973
1084
  }
974
1085
  });
975
- const tracker = ownerAlerts.createAlertTracker();
1086
+ console.log('[owner-alerts] delivery on: ' + (channels.join(', ') || 'custom'));
1087
+ // State lives on the volume (owner-alert-delivery.json), so a deploy or restart never re-sends an alert that is
1088
+ // still firing. The first check ever also sends one confirmation, so the channel is proven before a real alert needs it.
1089
+ const readState = (deps) => { const read = readObject(deps.feedbackDir, 'owner-alert-delivery.json'); return read.state === 'ok' ? read.value : null; };
1090
+ const writeState = (deps, state) => fs.writeFileSync(path.join(deps.feedbackDir, 'owner-alert-delivery.json'), JSON.stringify(state));
976
1091
  const run = async () => {
977
1092
  try {
978
- const result = await collectAlerts(makeDeps(), AbortSignal.timeout(30000));
979
- const added = tracker.fresh(result.data.alerts.filter((alert) => alert.level !== 'info'));
1093
+ const deps = makeDeps();
1094
+ const result = await collectAlerts(deps, AbortSignal.timeout(30000));
1095
+ const firing = result.data.alerts.filter((alert) => alert.level !== 'info');
1096
+ const state = readState(deps);
1097
+ const before = new Set(Array.isArray(state?.firing) ? state.firing : []);
1098
+ const added = firing.filter((alert) => !before.has(alert.id));
1099
+ writeState(deps, { confirmedAt: state?.confirmedAt || new Date().toISOString(), channels, firing: firing.map((alert) => alert.id), checkedAt: new Date().toISOString() });
1100
+ if (!state?.confirmedAt) await deliver({ title: 'ThumbGate: alert delivery is on', message: 'This is the one-time test that owner alerts reach you. New alerts from thumbgate.ai/admin will arrive here, each once, checked every 15 minutes. Firing right now: ' + firing.length + '.\nhttps://thumbgate.ai/admin' });
1101
+ console.log('[owner-alerts] checked: ' + firing.length + ' firing, ' + added.length + ' new');
980
1102
  if (!added.length) return;
981
1103
  await deliver(ownerAlerts.formatAlertMessage(added));
982
1104
  } catch { /* an alert check never takes the server down */ }
983
1105
  };
984
1106
  const timer = setInterval(run, intervalMs);
985
1107
  timer.unref?.();
986
- setTimeout(run, 60000).unref?.();
1108
+ setTimeout(run, firstCheckMs).unref?.();
987
1109
  return timer;
988
1110
  }
989
1111
 
@@ -1002,6 +1124,7 @@ async function collectAdminSection(route, deps, externalSignal) {
1002
1124
  if (route.section === 'money') return collectMoney(deps, controller.signal);
1003
1125
  if (route.section === 'summary') return collectSummary(deps, controller.signal);
1004
1126
  if (route.section === 'alerts') return collectAlerts(deps, controller.signal);
1127
+ if (route.section === 'economics') return collectEconomics(deps, controller.signal);
1005
1128
  if (route.section === 'stripe') return collectStripe(route, deps, controller.signal);
1006
1129
  if (route.section === 'data') return collectData(route, deps, controller.signal);
1007
1130
  if (route.section === 'observability') return collectObservability(deps, controller.signal);
@@ -1015,4 +1138,4 @@ async function collectAdminSection(route, deps, externalSignal) {
1015
1138
  }
1016
1139
  }
1017
1140
 
1018
- module.exports = { PRIVATE_HEADERS, RESPONSE_LIMIT, monthlyRecurring, collectAlerts, startAlertDelivery,adminPath, parseAdminRoute, readOwnerIdentity, readSessionState, collectMoney, collectAnalytics, collectSummary, summaryParts, collectAdminSection, createRuntimeObservations, githubCommitTitle, collectObservability, projectAnalytics, projectStripe, readObject, countRecords, guardPath };
1141
+ module.exports = { paymentAccessCheck, PRIVATE_HEADERS, RESPONSE_LIMIT, monthlyRecurring, collectAlerts, startAlertDelivery,adminPath, parseAdminRoute, readOwnerIdentity, readSessionState, collectMoney, collectAnalytics, collectSummary, summaryParts, collectAdminSection, createRuntimeObservations, githubCommitTitle, collectObservability, projectAnalytics, projectStripe, readObject, countRecords, guardPath };
@@ -107,6 +107,10 @@ const isCli = (entry) => (entry.clientType || entry.client) === 'cli';
107
107
  const isOwnOrCiInstall = (entry) => isFlagged(entry) || ['owner', 'ci'].includes(String(entry.visitorType || '').toLowerCase());
108
108
  // An install counts as activated once it has captured a piece of feedback: that is the first moment ThumbGate does its job.
109
109
  const ACTIVATION_EVENT = 'cli_capture';
110
+ // The first value event: a gate really fired and blocked a tool call in the user's own workflow. The CLI sends it once per
111
+ // install with the minutes since install, so time to first value comes from the same ping.
112
+ const FIRST_VALUE_EVENT = 'first_blocked_tool_call';
113
+ const quantile = (sorted, q) => (sorted.length ? sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))] : null);
110
114
  const topCounts = (counts, limit = 10) => Object.fromEntries(Object.entries(counts).sort((a, b) => b[1] - a[1]).slice(0, limit));
111
115
 
112
116
  // Visitors, sessions, page views, CTA clicks, checkout starts and paid confirmations, in total and per UTC day.
@@ -148,10 +152,18 @@ async function readTrafficWindow(options) {
148
152
  const day = dayOf(time);
149
153
  day.activeInstalls.add(install);
150
154
  if (week) weeks[week].activeInstalls.add(install);
151
- const seen = installs.get(install) || { days: new Set(), lastMs: 0, inited: false, activated: false, version: null, platform: null };
155
+ const seen = installs.get(install) || { days: new Set(), lastMs: 0, inited: false, activated: false, firstValue: false, firstValueMinutes: null, version: null, platform: null };
152
156
  seen.days.add(day.date);
153
157
  seen.inited ||= type === 'cli_init';
154
158
  seen.activated ||= type === ACTIVATION_EVENT;
159
+ if (type === FIRST_VALUE_EVENT) {
160
+ seen.firstValue = true;
161
+ // null or a blank means the CLI could not read its install marker: the install still reached first value, but its
162
+ // duration is unknown, so it stays out of the percentiles (Number(null) would count it as zero minutes).
163
+ const raw = entry.minutesSinceInstall;
164
+ const minutes = raw === null || raw === undefined || raw === '' || typeof raw === 'boolean' ? NaN : Number(raw);
165
+ if (Number.isFinite(minutes) && minutes >= 0 && (seen.firstValueMinutes === null || minutes < seen.firstValueMinutes)) seen.firstValueMinutes = minutes;
166
+ }
155
167
  if (time >= seen.lastMs) { seen.lastMs = time; seen.version = entry.version || entry.pkgVersion || seen.version; seen.platform = entry.platform || seen.platform; }
156
168
  installs.set(install, seen);
157
169
  return;
@@ -180,12 +192,14 @@ async function readTrafficWindow(options) {
180
192
  const daily = [...days.values()].sort((a, b) => a.date.localeCompare(b.date)).map((day) => ({ date: day.date, visitors: day.visitors.size, pageViewers: day.pageViewers.size, sessions: day.sessions.size, activeInstalls: day.activeInstalls.size, pageViews: day.pageViews, ctaClicks: day.ctaClicks, checkoutStarts: day.checkoutStarts, checkoutPaidConfirmations: day.checkoutPaidConfirmations }));
181
193
  const byVersion = {};
182
194
  const byPlatform = {};
183
- let newInstalls = 0; let activated = 0; let returning = 0; let active7 = 0;
195
+ let newInstalls = 0; let activated = 0; let returning = 0; let active7 = 0; let firstValue = 0;
196
+ const firstValueMinutes = [];
184
197
  for (const seen of installs.values()) {
185
198
  byVersion[seen.version || 'unknown'] = (byVersion[seen.version || 'unknown'] || 0) + 1;
186
199
  byPlatform[seen.platform || 'unknown'] = (byPlatform[seen.platform || 'unknown'] || 0) + 1;
187
200
  if (seen.inited) newInstalls += 1;
188
201
  if (seen.activated) activated += 1;
202
+ if (seen.firstValue) { firstValue += 1; if (seen.firstValueMinutes !== null) firstValueMinutes.push(seen.firstValueMinutes); }
189
203
  if (seen.days.size >= 2) returning += 1;
190
204
  if (seen.lastMs >= nowMs - 7 * DAY_MS) active7 += 1;
191
205
  }
@@ -199,6 +213,12 @@ async function readTrafficWindow(options) {
199
213
  initsInWindow: newInstalls,
200
214
  activatedInstalls: activated,
201
215
  returningInstalls: returning,
216
+ // Installs whose first real gate block arrived in the window, and how long after install it came.
217
+ firstValueInstalls: firstValue,
218
+ timeToFirstValue: (() => {
219
+ const sorted = firstValueMinutes.sort((a, b) => a - b);
220
+ return { installs: sorted.length, medianMinutes: quantile(sorted, 0.5), p75Minutes: quantile(sorted, 0.75) };
221
+ })(),
202
222
  excludedInstalls: excludedInstalls.size,
203
223
  eventsByType: topCounts(cliEvents, 20),
204
224
  byVersion: topCounts(byVersion),