thumbgate 1.40.3 → 1.40.5
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.
- package/.claude-plugin/plugin.json +1 -1
- package/.well-known/mcp/server-card.json +1 -1
- package/README.md +2 -2
- package/adapters/claude/.mcp.json +3 -3
- package/adapters/forge/forge.yaml +3 -3
- package/adapters/future-agi/.mcp.json +1 -1
- package/adapters/future-agi/config.toml +1 -1
- package/adapters/future-agi/opencode.json +1 -1
- package/adapters/herdr/herdr-plugin.toml +2 -2
- package/adapters/mcp/server-stdio.js +1 -1
- package/adapters/opencode/opencode.json +1 -1
- package/config/github-about.json +1 -1
- package/config/post-deploy-marketing-pages.json +1 -1
- package/package.json +27 -6
- package/public/about.html +2 -2
- package/public/admin.html +329 -47
- package/public/case-studies.html +1 -0
- package/public/dashboard.html +7 -6
- package/public/diagnostic.html +15 -12
- package/public/index.html +210 -78
- package/public/install.html +9 -8
- package/public/js/connect-panel.js +437 -0
- package/public/numbers.html +2 -2
- package/public/preview.html +42 -0
- package/public/pricing.html +55 -10
- package/scripts/auto-promote-gates.js +16 -1
- package/scripts/billing.js +189 -4
- package/scripts/cap-hit-counter.js +47 -0
- package/scripts/checkout-human-gate.js +248 -0
- package/scripts/checkout-session-count.js +115 -0
- package/scripts/feedback-loop.js +4 -0
- package/scripts/first-block-upsell.js +187 -0
- package/scripts/gates-engine.js +37 -108
- package/scripts/human-feedback.js +20 -1
- package/scripts/ops-log.js +91 -0
- package/scripts/ops-report.js +174 -0
- package/scripts/owner-admin.js +373 -26
- package/scripts/owner-telemetry.js +142 -0
- package/scripts/rate-limiter.js +8 -2
- package/scripts/statusline-human-counts.js +71 -8
- package/scripts/statusline.sh +15 -2
- package/scripts/telemetry-analytics.js +4 -0
- package/scripts/tool-contract-validator.js +13 -3
- package/scripts/tool-registry.js +1 -1
- package/scripts/utm-source-summary.js +88 -0
- package/server.json +2 -2
- package/src/api/server.js +607 -107
package/scripts/owner-admin.js
CHANGED
|
@@ -5,12 +5,17 @@ const path = require('node:path');
|
|
|
5
5
|
const crypto = require('node:crypto');
|
|
6
6
|
const readline = require('node:readline');
|
|
7
7
|
const billing = require('./billing');
|
|
8
|
+
const ownerTelemetry = require('./owner-telemetry');
|
|
9
|
+
const opsLog = require('./ops-log');
|
|
10
|
+
const opsReport = require('./ops-report');
|
|
8
11
|
|
|
9
12
|
const JSON_LIMIT = 8 * 1024 * 1024;
|
|
10
13
|
const LOG_LIMIT = 16 * 1024 * 1024;
|
|
11
14
|
const RESPONSE_LIMIT = 1024 * 1024;
|
|
12
15
|
const RESOURCES = Object.freeze({ customers: 'cus', subscriptions: 'sub', payments: 'ch', refunds: 're', products: 'prod', prices: 'price', 'subscription-items': 'si' });
|
|
13
|
-
const SECTIONS = new Set(['overview', 'data', 'analytics', 'observability']);
|
|
16
|
+
const SECTIONS = new Set(['overview', 'money', 'data', 'analytics', 'observability']);
|
|
17
|
+
const MONEY_CACHE_MS = 60000;
|
|
18
|
+
let moneyCache = null;
|
|
14
19
|
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' });
|
|
15
20
|
let activeCollections = 0;
|
|
16
21
|
const text = (value, max = 256) => typeof value === 'string' ? value.slice(0, max) : null;
|
|
@@ -29,7 +34,7 @@ function adminPath(raw) {
|
|
|
29
34
|
|
|
30
35
|
function parseAdminRoute(pathname, params) {
|
|
31
36
|
if (pathname === '/admin' || pathname === '/admin/' || pathname === '/admin.html') {
|
|
32
|
-
|
|
37
|
+
// The page takes no options: any query string (for example ?product=dayglass) is ignored and the ThumbGate board is served.
|
|
33
38
|
return { page: true };
|
|
34
39
|
}
|
|
35
40
|
const match = /^\/v1\/admin\/([^/]+)(?:\/([^/]+))?$/.exec(pathname || '');
|
|
@@ -97,6 +102,18 @@ function readOwnerIdentity({ feedbackDir, token, isOwner, now = Date.now() }) {
|
|
|
97
102
|
return { provider: entry.ssoProvider };
|
|
98
103
|
}
|
|
99
104
|
|
|
105
|
+
// Three states: no usable session, a valid session that is not the owner (any provider, API-key sessions included), or the owner.
|
|
106
|
+
function readSessionState({ feedbackDir, token, isOwner, now = Date.now() }) {
|
|
107
|
+
if (typeof token !== 'string' || !/^[a-f0-9]{64}$/.test(token)) return { state: 'none' };
|
|
108
|
+
const store = readObject(feedbackDir, 'auth-sessions.json');
|
|
109
|
+
if (store.state !== 'ok') return { state: 'none' };
|
|
110
|
+
const entry = store.value[crypto.createHash('sha256').update(token).digest('hex')];
|
|
111
|
+
if (!object(entry) || !Number.isFinite(entry.expiresAt) || entry.expiresAt <= now) return { state: 'none' };
|
|
112
|
+
const provider = ['apple', 'google'].includes(entry.ssoProvider) ? entry.ssoProvider : 'key';
|
|
113
|
+
if (provider !== 'key' && isOwner(entry.ssoEmail)) return { state: 'owner', provider };
|
|
114
|
+
return { state: 'non_owner', provider };
|
|
115
|
+
}
|
|
116
|
+
|
|
100
117
|
function envelope(source, data, warnings = [], status = warnings.length ? 'partial' : 'ok') {
|
|
101
118
|
return { status, generatedAt: new Date().toISOString(), source, data, warnings };
|
|
102
119
|
}
|
|
@@ -105,7 +122,25 @@ function createRuntimeObservations(now = Date.now()) {
|
|
|
105
122
|
const errors = [];
|
|
106
123
|
const buckets = new Map();
|
|
107
124
|
const trim = (stamp) => { for (const key of buckets.keys()) if (key < Math.floor(stamp / 1000) - 59) buckets.delete(key); };
|
|
125
|
+
const timings = new Map();
|
|
126
|
+
const percentile = (sorted, p) => sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil(p * sorted.length) - 1))];
|
|
108
127
|
return {
|
|
128
|
+
// Response time per route category, kept for the newest 1,000 requests of each. Resets when the server restarts.
|
|
129
|
+
recordTiming(route, ms) {
|
|
130
|
+
if (!Number.isFinite(ms) || ms < 0) return;
|
|
131
|
+
const list = timings.get(route) || [];
|
|
132
|
+
list.push(ms);
|
|
133
|
+
if (list.length > 1000) list.shift();
|
|
134
|
+
timings.set(route, list);
|
|
135
|
+
},
|
|
136
|
+
speed() {
|
|
137
|
+
const out = {};
|
|
138
|
+
for (const [route, list] of timings) {
|
|
139
|
+
const sorted = list.slice().sort((a, b) => a - b);
|
|
140
|
+
out[route] = { samples: sorted.length, p50: Math.round(percentile(sorted, 0.5)), p95: Math.round(percentile(sorted, 0.95)) };
|
|
141
|
+
}
|
|
142
|
+
return out;
|
|
143
|
+
},
|
|
109
144
|
recordResponse(status, route, stamp = Date.now()) {
|
|
110
145
|
if (status < 500 || status > 599) return;
|
|
111
146
|
errors.push({ timestamp: new Date(stamp).toISOString(), status, route: ['admin', 'telemetry', 'health', 'api', 'page'].includes(route) ? route : 'other' });
|
|
@@ -268,17 +303,6 @@ function projectAnalytics(summary) {
|
|
|
268
303
|
};
|
|
269
304
|
}
|
|
270
305
|
|
|
271
|
-
async function preflightAnalytics(root) {
|
|
272
|
-
let total = 0;
|
|
273
|
-
for (const source of billing.getBillingAnalyticsReadPaths()) {
|
|
274
|
-
try {
|
|
275
|
-
const stat = await fs.promises.stat(guardPath(root, source));
|
|
276
|
-
total += stat.size;
|
|
277
|
-
if (!stat.isFile() || total > JSON_LIMIT) throw failure('analytics_source_budget');
|
|
278
|
-
} catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
279
|
-
}
|
|
280
|
-
}
|
|
281
|
-
|
|
282
306
|
async function collectObservability(deps, signal) {
|
|
283
307
|
stopped(signal);
|
|
284
308
|
let disk = null;
|
|
@@ -287,7 +311,51 @@ async function collectObservability(deps, signal) {
|
|
|
287
311
|
const stats = await fs.promises.statfs(guardPath(deps.feedbackDir, deps.feedbackDir));
|
|
288
312
|
disk = { capacityBytes: stats.blocks * stats.bsize, freeBytes: stats.bavail * stats.bsize, usedBytes: (stats.blocks - stats.bfree) * stats.bsize, scope: 'volume_filesystem' };
|
|
289
313
|
} catch { warnings.push('disk_unavailable'); }
|
|
290
|
-
|
|
314
|
+
const health = deps.health();
|
|
315
|
+
const snapshot = deps.runtime.snapshot();
|
|
316
|
+
const now = Date.now();
|
|
317
|
+
let events = [];
|
|
318
|
+
let beats = [];
|
|
319
|
+
try {
|
|
320
|
+
events = (await opsLog.readLog(deps.feedbackDir, opsLog.EVENTS_FILE, { now, days: 30, signal })).rows;
|
|
321
|
+
beats = (await opsLog.readLog(deps.feedbackDir, opsLog.HEARTBEAT_FILE, { now, days: 30, signal })).rows.map((row) => row.time);
|
|
322
|
+
} catch (error) { if (error.code === 'collection_timeout') throw error; warnings.push('ops_log_unavailable'); }
|
|
323
|
+
const sha = text(deps.buildMetadata?.buildSha, 64) || text(health.buildSha, 64);
|
|
324
|
+
let commitTitle = null;
|
|
325
|
+
let commitTitleReason = null;
|
|
326
|
+
if (sha && typeof deps.lookupCommitTitle === 'function') {
|
|
327
|
+
try { commitTitle = (await deps.lookupCommitTitle(sha, signal)) || null; } catch { commitTitle = null; }
|
|
328
|
+
if (!commitTitle) commitTitleReason = 'GitHub did not return the commit title.';
|
|
329
|
+
} else if (sha) commitTitleReason = 'The commit title lookup is not set up on this server.';
|
|
330
|
+
const report = opsReport.buildReport({
|
|
331
|
+
now, events, beats, disk,
|
|
332
|
+
speed: typeof deps.runtime.speed === 'function' ? deps.runtime.speed() : null,
|
|
333
|
+
startedAt: snapshot.processStartedAt,
|
|
334
|
+
uptimeSeconds: health.uptime,
|
|
335
|
+
sha, commitTitle, commitTitleReason,
|
|
336
|
+
repo: deps.githubRepo === undefined ? 'IgorGanapolsky/ThumbGate' : deps.githubRepo,
|
|
337
|
+
});
|
|
338
|
+
return envelope('current_process', { ...health, ...snapshot, deployment: { id: text(process.env.RAILWAY_DEPLOYMENT_ID, 128), commit: text(process.env.RAILWAY_GIT_COMMIT_SHA, 64), deployedAt: null, deploymentTimeStatus: 'unavailable', buildGeneratedAt: text(deps.buildMetadata?.generatedAt, 64) }, disk, report }, warnings);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
const commitTitleCache = new Map();
|
|
342
|
+
// The first line of a commit message from GitHub's public API, cached an hour. Returns null on any failure.
|
|
343
|
+
async function githubCommitTitle(sha, signal, repo = 'IgorGanapolsky/ThumbGate') {
|
|
344
|
+
if (!/^[0-9a-f]{7,64}$/i.test(sha)) return null;
|
|
345
|
+
const cached = commitTitleCache.get(sha);
|
|
346
|
+
if (cached && Date.now() - cached.at < 3600000) return cached.title;
|
|
347
|
+
try {
|
|
348
|
+
const controller = new AbortController();
|
|
349
|
+
const timer = setTimeout(() => controller.abort(), 3000);
|
|
350
|
+
signal?.addEventListener?.('abort', () => controller.abort(), { once: true });
|
|
351
|
+
const response = await fetch('https://api.github.com/repos/' + repo + '/commits/' + sha, { headers: { Accept: 'application/vnd.github+json', 'User-Agent': 'thumbgate-owner-console' }, signal: controller.signal });
|
|
352
|
+
clearTimeout(timer);
|
|
353
|
+
if (!response.ok) return null;
|
|
354
|
+
const body = await response.json();
|
|
355
|
+
const title = text(String(body?.commit?.message || '').split('\n')[0], 200);
|
|
356
|
+
if (title) commitTitleCache.set(sha, { at: Date.now(), title });
|
|
357
|
+
return title;
|
|
358
|
+
} catch { return null; }
|
|
291
359
|
}
|
|
292
360
|
|
|
293
361
|
function deadline(promise, ms, signal) {
|
|
@@ -301,6 +369,293 @@ function deadline(promise, ms, signal) {
|
|
|
301
369
|
});
|
|
302
370
|
}
|
|
303
371
|
|
|
372
|
+
const countMap = (value) => Object.fromEntries(Object.entries(object(value) ? value : {}).filter(([, n]) => Number.isFinite(n)).slice(0, 50).map(([key, n]) => [String(key).slice(0, 64), n]));
|
|
373
|
+
|
|
374
|
+
// The shared billing summary reads about 97 MB of ledgers on the hosted volume, so it never runs in the request:
|
|
375
|
+
// a child process computes it, the result is cached, and tabs that need it say "refreshing" until it lands.
|
|
376
|
+
// Telemetry (visitors, page views, clicks, checkouts) never waits for it: it is streamed from the log tail.
|
|
377
|
+
const SUMMARY_TTL_MS = 10 * 60 * 1000;
|
|
378
|
+
const TELEMETRY_CACHE_MS = 60000;
|
|
379
|
+
const SUMMARY_WORKER = `
|
|
380
|
+
const admin = require(process.argv[1]);
|
|
381
|
+
const billing = require(process.argv[2]);
|
|
382
|
+
billing.getBillingSummaryLive({ window: '30d', stripeReconciliationTimeoutMs: 3000 }, { signal: AbortSignal.timeout(60000) }).then((s) => {
|
|
383
|
+
if (!s || s.error) process.exit(2);
|
|
384
|
+
process.stdout.write(JSON.stringify(admin.summaryParts(s)));
|
|
385
|
+
process.exit(0);
|
|
386
|
+
}).catch(() => process.exit(3));
|
|
387
|
+
`;
|
|
388
|
+
let summarySnapshot = { at: 0, value: null, inflight: null, failed: false };
|
|
389
|
+
const trafficCache = new Map();
|
|
390
|
+
|
|
391
|
+
function summaryParts(summary) {
|
|
392
|
+
return {
|
|
393
|
+
analytics: projectAnalytics(summary),
|
|
394
|
+
leads: {
|
|
395
|
+
signups: countMap(summary.signups?.bySource),
|
|
396
|
+
workflowSprint: { total: number(summary.pipeline?.workflowSprintLeads?.total), bySource: countMap(summary.pipeline?.workflowSprintLeads?.bySource) },
|
|
397
|
+
newsletter: { total: number(summary.newsletter?.total), bySource: countMap(summary.newsletter?.bySource) },
|
|
398
|
+
emailSignups: number(summary.signups?.emailSignups),
|
|
399
|
+
},
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function startSummaryWorker() {
|
|
404
|
+
if (summarySnapshot.inflight) return;
|
|
405
|
+
summarySnapshot.inflight = new Promise((resolve) => {
|
|
406
|
+
require('node:child_process').execFile(process.execPath, ['-e', SUMMARY_WORKER, require.resolve('./owner-admin'), require.resolve('./billing')], { timeout: 90000, maxBuffer: 4 * 1024 * 1024, env: process.env }, (error, stdout) => {
|
|
407
|
+
summarySnapshot.failed = Boolean(error);
|
|
408
|
+
if (!error) { try { summarySnapshot.value = JSON.parse(stdout); summarySnapshot.at = Date.now(); } catch { summarySnapshot.failed = true; } }
|
|
409
|
+
resolve();
|
|
410
|
+
});
|
|
411
|
+
}).finally(() => { summarySnapshot.inflight = null; });
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
async function readSummary(deps, signal) {
|
|
415
|
+
if (deps.getBillingSummaryLive) {
|
|
416
|
+
const injected = await deps.getBillingSummaryLive({ window: '30d', stripeReconciliationTimeoutMs: 8000 }, { signal });
|
|
417
|
+
if (!injected || injected.error) throw failure('analytics_unavailable');
|
|
418
|
+
return { value: summaryParts(injected), state: 'ok' };
|
|
419
|
+
}
|
|
420
|
+
const fresh = summarySnapshot.value && Date.now() - summarySnapshot.at < SUMMARY_TTL_MS;
|
|
421
|
+
if (!fresh) startSummaryWorker();
|
|
422
|
+
// First visit after a restart: wait for the worker a few seconds instead of answering "not ready".
|
|
423
|
+
if (!summarySnapshot.value && summarySnapshot.inflight) {
|
|
424
|
+
await Promise.race([summarySnapshot.inflight, new Promise((resolve) => { const timer = setTimeout(resolve, 7000); timer.unref?.(); })]);
|
|
425
|
+
}
|
|
426
|
+
const state = summarySnapshot.value ? (fresh ? 'ok' : 'stale') : (summarySnapshot.failed ? 'failed' : 'refreshing');
|
|
427
|
+
return { value: summarySnapshot.value, state };
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
// 30 days of site traffic, streamed from the newest end of the telemetry log. Cached for a minute.
|
|
431
|
+
async function readTraffic(deps, signal) {
|
|
432
|
+
const ttl = deps.telemetryCacheMs ?? TELEMETRY_CACHE_MS;
|
|
433
|
+
const key = String(deps.feedbackDir);
|
|
434
|
+
const hit = trafficCache.get(key);
|
|
435
|
+
if (ttl > 0 && hit && Date.now() - hit.at < ttl) return hit.value;
|
|
436
|
+
const value = await ownerTelemetry.readTrafficWindow({ feedbackDir: guardPath(deps.feedbackDir, deps.feedbackDir), days: 30, signal, maxBytes: deps.telemetryMaxBytes });
|
|
437
|
+
if (ttl > 0) trafficCache.set(key, { at: Date.now(), value });
|
|
438
|
+
return value;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
// Why the Money board used to say "Stripe is busy": every list held one of the account's two read slots for its whole run
|
|
442
|
+
// (a 30-day checkout list is about six pages), a read that found both taken failed at once, and a read that timed out kept
|
|
443
|
+
// running and kept its slot. Now each page waits for a slot until one shared deadline, a stopped list stops between pages,
|
|
444
|
+
// and a block that still fails shows its last good result for five minutes.
|
|
445
|
+
const STRIPE_DEADLINE_MS = 8500;
|
|
446
|
+
const LAST_GOOD_MS = 5 * 60 * 1000;
|
|
447
|
+
const lastGood = new Map();
|
|
448
|
+
const pause = (ms, signal) => new Promise((resolve) => {
|
|
449
|
+
const timer = setTimeout(resolve, ms);
|
|
450
|
+
timer.unref?.();
|
|
451
|
+
signal?.addEventListener('abort', () => { clearTimeout(timer); resolve(); }, { once: true });
|
|
452
|
+
});
|
|
453
|
+
|
|
454
|
+
async function withSlot(work, signal) {
|
|
455
|
+
for (;;) {
|
|
456
|
+
stopped(signal);
|
|
457
|
+
try { return await billing.withStripeReadSlot(work, { signal }); } catch (error) {
|
|
458
|
+
if (error?.code !== 'provider_busy') throw error;
|
|
459
|
+
await pause(100, signal);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
// Pages a Stripe list with starting_after, 100 rows at a time, newest first. `complete` is false when the page cap was hit.
|
|
465
|
+
async function listAll({ list, params, keep = () => true, maxPages = 40, signal, until }) {
|
|
466
|
+
const rows = [];
|
|
467
|
+
let after = null;
|
|
468
|
+
for (let page = 0; ; page += 1) {
|
|
469
|
+
stopped(signal);
|
|
470
|
+
if (page >= maxPages) return { rows, complete: false };
|
|
471
|
+
const left = Math.max(1, until - Date.now());
|
|
472
|
+
const result = await deadline(withSlot(() => list({ ...params, limit: 100, ...(after ? { starting_after: after } : {}) }, { timeout: Math.min(8000, left), maxNetworkRetries: 0 }), signal), left, signal);
|
|
473
|
+
if (!Array.isArray(result?.data)) throw failure('provider_unavailable');
|
|
474
|
+
for (const row of result.data) if (keep(row)) rows.push(row);
|
|
475
|
+
if (result.has_more !== true || !result.data.length) return { rows, complete: true };
|
|
476
|
+
after = result.data.at(-1).id;
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
const thumbgateSession = (row) => /thumbgate/i.test(String(row.success_url || ''));
|
|
481
|
+
|
|
482
|
+
// Why a Stripe source failed, in words a person can act on. Never a bare "Unknown".
|
|
483
|
+
function stripeReason(error) {
|
|
484
|
+
if (/STRIPE_SECRET_KEY is missing/i.test(String(error?.message || ''))) return 'Stripe key missing';
|
|
485
|
+
if (error?.code === 'collection_timeout') return 'Stripe did not answer in time';
|
|
486
|
+
if (error?.code === 'provider_busy') return 'Stripe is busy, refresh in a moment';
|
|
487
|
+
return 'Stripe unavailable';
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
const attempt = async (work, reasonOf) => {
|
|
491
|
+
try { return { ok: true, value: await work(), reason: null }; } catch (error) { return { ok: false, value: null, reason: reasonOf(error) }; }
|
|
492
|
+
};
|
|
493
|
+
const telemetryReason = (error) => (error?.code === 'collection_timeout' ? 'telemetry read timed out' : 'telemetry read failed');
|
|
494
|
+
|
|
495
|
+
const trafficFields = (read) => ({ visitors: read.traffic.visitors, realVisitors: read.traffic.realVisitors, botOrInternalVisitors: read.traffic.botOrInternalVisitors, sessions: read.traffic.sessions, pageViews: read.traffic.pageViews, ctaClicks: read.traffic.ctaClicks, checkoutStarts: read.traffic.checkoutStarts, checkoutPaidConfirmations: read.traffic.checkoutPaidConfirmations });
|
|
496
|
+
|
|
497
|
+
// Money board. Each block fails alone: its fields are null and a plain-words reason is returned beside them.
|
|
498
|
+
// Stripe answers paying customers, revenue and checkouts; our own page-view telemetry answers visitors.
|
|
499
|
+
async function collectMoney(deps, signal) {
|
|
500
|
+
const ttl = deps.moneyCacheMs ?? MONEY_CACHE_MS;
|
|
501
|
+
if (ttl > 0 && moneyCache && Date.now() - moneyCache.at < ttl) return moneyCache.value;
|
|
502
|
+
const ownerEmails = (deps.getOwnerEmails || require('./bot-detection').getOwnerEmails)();
|
|
503
|
+
const stripe = () => (deps.getStripeClient || billing.getStripeClient)();
|
|
504
|
+
const { countSessions, classifySession } = require('./checkout-session-count');
|
|
505
|
+
const nowSeconds = Math.floor(Date.now() / 1000);
|
|
506
|
+
|
|
507
|
+
// One deadline for all of Stripe's reads, shared by every block below.
|
|
508
|
+
const stripeMs = deps.stripeDeadlineMs ?? STRIPE_DEADLINE_MS;
|
|
509
|
+
const until = Date.now() + stripeMs;
|
|
510
|
+
const shared = new AbortController();
|
|
511
|
+
const stopShared = () => shared.abort();
|
|
512
|
+
signal?.addEventListener('abort', stopShared, { once: true });
|
|
513
|
+
const sharedTimer = setTimeout(stopShared, stripeMs);
|
|
514
|
+
if (signal?.aborted) stopShared();
|
|
515
|
+
const keepMs = deps.lastGoodMs ?? LAST_GOOD_MS;
|
|
516
|
+
const staleBlocks = {};
|
|
517
|
+
// A block that fails shows its last good result when that is under five minutes old, and says so.
|
|
518
|
+
const withLastGood = async (key, work) => {
|
|
519
|
+
const run = await attempt(work, stripeReason);
|
|
520
|
+
if (run.ok) { if (keepMs > 0) lastGood.set(key, { at: Date.now(), value: run.value }); return run; }
|
|
521
|
+
const kept = keepMs > 0 ? lastGood.get(key) : null;
|
|
522
|
+
if (kept && Date.now() - kept.at < keepMs) { staleBlocks[key] = kept.at; return { ok: true, value: kept.value, reason: null }; }
|
|
523
|
+
return run;
|
|
524
|
+
};
|
|
525
|
+
const listIt = (list, params, keep, maxPages) => listAll({ list, params, keep, maxPages, signal: shared.signal, until });
|
|
526
|
+
|
|
527
|
+
// Two lanes: one lists paid checkouts then subscriptions, the other lists checkout sessions. Each page waits for a free slot.
|
|
528
|
+
const paidAndProLane = (async () => {
|
|
529
|
+
const paidResult = await withLastGood('paid', async () => {
|
|
530
|
+
const result = await listIt((params, options) => stripe().checkout.sessions.list(params, options),
|
|
531
|
+
{ status: 'complete', created: { gte: nowSeconds - 365 * 86400 }, expand: ['data.payment_intent.latest_charge'] },
|
|
532
|
+
(row) => row.status === 'complete' && thumbgateSession(row), 10);
|
|
533
|
+
// Paid and not refunded in full, owner and test purchases excluded. A partial refund comes off the revenue.
|
|
534
|
+
const charge = (row) => (object(row.payment_intent) && object(row.payment_intent.latest_charge) ? row.payment_intent.latest_charge : null);
|
|
535
|
+
const paid = result.rows.filter((row) => row.payment_status === 'paid' && classifySession(row, { ownerEmails }) !== 'internal' && charge(row)?.refunded !== true);
|
|
536
|
+
const customers = new Set(paid.map((row) => id(row.customer) || String(row.customer_details?.email || row.customer_email || row.id).toLowerCase()));
|
|
537
|
+
const revenue = {};
|
|
538
|
+
for (const row of paid) {
|
|
539
|
+
if (!(row.created >= nowSeconds - 30 * 86400) || !Number.isSafeInteger(row.amount_total) || !/^[a-z]{3}$/i.test(row.currency || '')) continue;
|
|
540
|
+
const code = row.currency.toUpperCase();
|
|
541
|
+
const refunded = Number.isSafeInteger(charge(row)?.amount_refunded) ? charge(row).amount_refunded : 0;
|
|
542
|
+
revenue[code] = (revenue[code] || 0) + row.amount_total - refunded;
|
|
543
|
+
}
|
|
544
|
+
return { customers, revenue, complete: result.complete };
|
|
545
|
+
});
|
|
546
|
+
const proResult = await withLastGood('subscriptions', async () => {
|
|
547
|
+
const result = await listIt((params, options) => stripe().subscriptions.list(params, options), { status: 'active', expand: ['data.customer'] }, () => true, 5);
|
|
548
|
+
const external = result.rows.filter((row) => {
|
|
549
|
+
const email = String(row.customer?.email || '').toLowerCase();
|
|
550
|
+
return !(email && ownerEmails.some((owner) => email === String(owner).toLowerCase()));
|
|
551
|
+
});
|
|
552
|
+
const customers = new Set(external.map((row) => id(row.customer) || String(row.customer?.email || row.id).toLowerCase()));
|
|
553
|
+
return { count: external.length, customers, complete: result.complete };
|
|
554
|
+
});
|
|
555
|
+
return [paidResult, proResult];
|
|
556
|
+
})();
|
|
557
|
+
let paidAndPro; let sessionRun; let trafficRun; let summaryRun;
|
|
558
|
+
try {
|
|
559
|
+
[paidAndPro, sessionRun, trafficRun, summaryRun] = await Promise.all([
|
|
560
|
+
paidAndProLane,
|
|
561
|
+
withLastGood('checkouts', async () => {
|
|
562
|
+
const result = await listIt((params, options) => stripe().checkout.sessions.list(params, options), { created: { gte: nowSeconds - 30 * 86400 } }, thumbgateSession, 40);
|
|
563
|
+
const since7 = nowSeconds - 7 * 86400;
|
|
564
|
+
return { d30: countSessions(result.rows, { ownerEmails }), d7: countSessions(result.rows.filter((row) => !row.created || row.created >= since7), { ownerEmails }), complete: result.complete };
|
|
565
|
+
}),
|
|
566
|
+
attempt(() => readTraffic(deps, signal), telemetryReason),
|
|
567
|
+
attempt(() => readSummary(deps, signal), () => 'lead ledgers failed'),
|
|
568
|
+
]);
|
|
569
|
+
} finally {
|
|
570
|
+
clearTimeout(sharedTimer);
|
|
571
|
+
signal?.removeEventListener('abort', stopShared);
|
|
572
|
+
stopShared();
|
|
573
|
+
}
|
|
574
|
+
const [paidRun, proRun] = paidAndPro;
|
|
575
|
+
|
|
576
|
+
const parts = summaryRun.value?.value || null;
|
|
577
|
+
const leadsReason = parts ? null : summaryRun.ok && summaryRun.value.state === 'refreshing' ? 'lead ledgers still calculating, refresh in a minute' : 'lead ledgers failed';
|
|
578
|
+
const trafficRead = trafficRun.value;
|
|
579
|
+
const trafficReason = !trafficRun.ok ? trafficRun.reason : trafficRead.empty ? 'telemetry store empty' : null;
|
|
580
|
+
const paid = paidRun.value;
|
|
581
|
+
const sessions = sessionRun.value;
|
|
582
|
+
const sessionBuckets = (counts) => (counts ? {
|
|
583
|
+
started: counts.started,
|
|
584
|
+
human: counts.nonCrawlerStarted,
|
|
585
|
+
completedHuman: counts.nonCrawlerCompleted,
|
|
586
|
+
paidHuman: counts.nonCrawlerPaid,
|
|
587
|
+
bot: counts.excluded.bot,
|
|
588
|
+
notClassified: counts.excluded.unclassified + counts.excluded.unknownUa,
|
|
589
|
+
internal: counts.excluded.internal,
|
|
590
|
+
} : null);
|
|
591
|
+
const bothStripe = paid && proRun.value;
|
|
592
|
+
const data = {
|
|
593
|
+
windows: { revenue: '30d', checkouts: '7d', traffic: '30d', leads: '30d' },
|
|
594
|
+
// Counted straight from Stripe: people with a paid, unrefunded checkout in the past year plus active subscribers, once each.
|
|
595
|
+
payingCustomers: bothStripe ? new Set([...paid.customers, ...proRun.value.customers]).size : null,
|
|
596
|
+
payingCustomersSource: 'stripe',
|
|
597
|
+
payingCustomersBasis: bothStripe ? (paid.complete && proRun.value.complete ? 'stripe_paid_and_active' : 'stripe_paid_and_active_partial') : 'unavailable',
|
|
598
|
+
activePro: proRun.value ? proRun.value.count : null,
|
|
599
|
+
activeProBasis: proRun.value ? (proRun.value.complete ? 'stripe_active_subscriptions_excluding_owner' : 'stripe_active_subscriptions_first_100_only') : 'unavailable',
|
|
600
|
+
revenueLast30Days: paid ? paid.revenue : null,
|
|
601
|
+
revenueBasis: 'stripe_paid_checkouts_after_refunds',
|
|
602
|
+
checkouts7d: sessionBuckets(sessions?.d7),
|
|
603
|
+
checkouts30d: sessionBuckets(sessions?.d30),
|
|
604
|
+
traffic30d: trafficReason ? null : { ...trafficFields(trafficRead), partial: trafficRead.partial },
|
|
605
|
+
leadsBySource: parts ? parts.leads : null,
|
|
606
|
+
reasons: {
|
|
607
|
+
payingCustomers: bothStripe ? null : (paidRun.reason || proRun.reason),
|
|
608
|
+
activePro: proRun.value ? null : proRun.reason,
|
|
609
|
+
revenue: paid ? null : paidRun.reason,
|
|
610
|
+
checkouts: sessions ? null : sessionRun.reason,
|
|
611
|
+
visitors: trafficReason,
|
|
612
|
+
leads: leadsReason,
|
|
613
|
+
},
|
|
614
|
+
notes: ['Every started checkout is counted once: real people, bots, not classified, or owner and test.', 'Sessions created before the bot check carry no browser class, so they are counted as not classified.'],
|
|
615
|
+
};
|
|
616
|
+
const staleLabel = { paid: 'paying customers and revenue', subscriptions: 'active subscriptions', checkouts: 'checkout counts' };
|
|
617
|
+
for (const [key, at] of Object.entries(staleBlocks)) {
|
|
618
|
+
const minutes = Math.max(1, Math.round((Date.now() - at) / 60000));
|
|
619
|
+
data.notes.push(`Showing the last good ${staleLabel[key]} from ${minutes} minute${minutes === 1 ? '' : 's'} ago, because Stripe did not answer this time.`);
|
|
620
|
+
}
|
|
621
|
+
if (sessions && sessions.complete === false) data.notes.push('The 30-day checkout list was cut short at 4,000 sessions, so the 30-day counts are a lower bound.');
|
|
622
|
+
const warnings = [];
|
|
623
|
+
if (Object.keys(staleBlocks).length) warnings.push('showing_last_good_stripe_numbers');
|
|
624
|
+
if (sessions && sessions.complete === false) warnings.push('checkout_list_partial');
|
|
625
|
+
if (!paidRun.ok) warnings.push('paid_checkout_list_unavailable');
|
|
626
|
+
if (!sessionRun.ok) warnings.push('checkout_list_unavailable');
|
|
627
|
+
if (!proRun.ok) warnings.push('subscription_list_unavailable');
|
|
628
|
+
if (trafficReason) warnings.push('telemetry_unavailable');
|
|
629
|
+
if (leadsReason) warnings.push('leads_unavailable');
|
|
630
|
+
const failed = [paidRun, sessionRun, proRun].filter((run) => !run.ok).length;
|
|
631
|
+
const value = envelope('stripe_and_telemetry', data, warnings, failed === 3 && trafficReason ? 'unavailable' : warnings.length ? 'partial' : 'ok');
|
|
632
|
+
if (ttl > 0 && warnings.length === 0) moneyCache = { at: Date.now(), value };
|
|
633
|
+
return value;
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
// Analytics: 30 days of traffic streamed from the telemetry tail (never refused for size), a daily series, and the
|
|
637
|
+
// billing totals from the cached child-process summary when it is ready.
|
|
638
|
+
async function collectAnalytics(deps, signal) {
|
|
639
|
+
const [trafficRun, summaryRun] = await Promise.all([
|
|
640
|
+
attempt(() => readTraffic(deps, signal), telemetryReason),
|
|
641
|
+
attempt(() => readSummary(deps, signal), () => 'billing totals failed'),
|
|
642
|
+
]);
|
|
643
|
+
const parts = summaryRun.value?.value || null;
|
|
644
|
+
const trafficRead = trafficRun.value;
|
|
645
|
+
if (!trafficRun.ok && !parts) throw Object.assign(new Error('analytics_unavailable'), { code: trafficRun.reason === 'telemetry read timed out' ? 'collection_timeout' : 'analytics_unavailable' });
|
|
646
|
+
const data = parts?.analytics ? { ...parts.analytics } : { window: '30d' };
|
|
647
|
+
const hasTraffic = trafficRun.ok && !trafficRead.empty;
|
|
648
|
+
data.trafficMetrics = hasTraffic ? trafficFields(trafficRead) : (data.trafficMetrics || null);
|
|
649
|
+
data.daily = hasTraffic ? trafficRead.daily : [];
|
|
650
|
+
data.dataQuality = { ...(data.dataQuality || {}), telemetryWindowComplete: hasTraffic ? !trafficRead.partial : false, telemetryBytesRead: trafficRead ? trafficRead.bytesRead : 0, telemetrySizeBytes: trafficRead ? trafficRead.size : 0 };
|
|
651
|
+
const warnings = [];
|
|
652
|
+
if (data.reconciliation && (data.reconciliation.status !== 'ok' || !data.reconciliation.complete)) warnings.push('stripe_reconciliation_' + data.reconciliation.status);
|
|
653
|
+
if (!parts) warnings.push(summaryRun.ok && summaryRun.value.state === 'refreshing' ? 'billing_totals_refreshing' : 'billing_totals_unavailable');
|
|
654
|
+
if (!hasTraffic) warnings.push(trafficRun.ok ? 'telemetry_store_empty' : 'telemetry_unavailable');
|
|
655
|
+
else if (trafficRead.partial) warnings.push('telemetry_incomplete');
|
|
656
|
+
return envelope('telemetry_tail_and_billing_summary_30d', data, warnings);
|
|
657
|
+
}
|
|
658
|
+
|
|
304
659
|
async function collectAdminSection(route, deps, externalSignal) {
|
|
305
660
|
if (activeCollections >= 2) throw failure('collection_busy');
|
|
306
661
|
activeCollections += 1;
|
|
@@ -313,26 +668,18 @@ async function collectAdminSection(route, deps, externalSignal) {
|
|
|
313
668
|
const operation = async () => {
|
|
314
669
|
stopped(controller.signal);
|
|
315
670
|
if (route.section === 'overview') return envelope('current_process', { health: deps.health(), sections: ['stripe', 'data', 'analytics', 'observability'] });
|
|
671
|
+
if (route.section === 'money') return collectMoney(deps, controller.signal);
|
|
316
672
|
if (route.section === 'stripe') return collectStripe(route, deps, controller.signal);
|
|
317
673
|
if (route.section === 'data') return collectData(route, deps, controller.signal);
|
|
318
674
|
if (route.section === 'observability') return collectObservability(deps, controller.signal);
|
|
319
|
-
|
|
320
|
-
stopped(controller.signal);
|
|
321
|
-
const summary = await (deps.getBillingSummaryLive || billing.getBillingSummaryLive)({ window: '30d', stripeReconciliationTimeoutMs: 8000 }, { signal: controller.signal });
|
|
322
|
-
stopped(controller.signal);
|
|
323
|
-
if (summary.error) throw failure('analytics_unavailable');
|
|
324
|
-
const data = projectAnalytics(summary);
|
|
325
|
-
const warnings = data.reconciliation.status !== 'ok' || !data.reconciliation.complete ? ['stripe_reconciliation_' + data.reconciliation.status] : [];
|
|
326
|
-
if (summary.sourceDiagnostics?.warnings?.length) warnings.push('source_quality_warning');
|
|
327
|
-
if (!data.dataQuality.telemetryWindowComplete) warnings.push('telemetry_incomplete');
|
|
328
|
-
return envelope('shared_billing_summary_30d', data, warnings);
|
|
675
|
+
return collectAnalytics(deps, controller.signal);
|
|
329
676
|
};
|
|
330
677
|
return await deadline(operation(), deps.sectionTimeoutMs || 10000, controller.signal);
|
|
331
678
|
} catch (error) {
|
|
332
|
-
return envelope(route.section, null, [error.code === 'collection_timeout' ? 'collection_timeout' :
|
|
679
|
+
return envelope(route.section, null, [error.code === 'collection_timeout' ? 'collection_timeout' : 'source_unavailable'], 'unavailable');
|
|
333
680
|
} finally {
|
|
334
681
|
abort(); clearTimeout(timer); externalSignal?.removeEventListener('abort', abort); activeCollections -= 1;
|
|
335
682
|
}
|
|
336
683
|
}
|
|
337
684
|
|
|
338
|
-
module.exports = { PRIVATE_HEADERS, RESPONSE_LIMIT, adminPath, parseAdminRoute, readOwnerIdentity, collectAdminSection, createRuntimeObservations, projectAnalytics, projectStripe, readObject, countRecords, guardPath };
|
|
685
|
+
module.exports = { PRIVATE_HEADERS, RESPONSE_LIMIT, adminPath, parseAdminRoute, readOwnerIdentity, readSessionState, collectMoney, collectAnalytics, summaryParts, collectAdminSection, createRuntimeObservations, githubCommitTitle, collectObservability, projectAnalytics, projectStripe, readObject, countRecords, guardPath };
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Owner-only telemetry reader. Streams the telemetry log newest-first and stops at the window edge
|
|
5
|
+
* or a byte cap, so a log of any size answers in bounded time and memory. Never refuses a large file:
|
|
6
|
+
* when the cap is hit before the window edge, the result says `partial`.
|
|
7
|
+
*
|
|
8
|
+
* Stored telemetry lines are already normalised by appendTelemetryEvent (event type, visitor, source,
|
|
9
|
+
* audience flags), so they are read as stored instead of being re-sanitised line by line.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
const fs = require('node:fs');
|
|
13
|
+
const path = require('node:path');
|
|
14
|
+
const telemetry = require('./telemetry-analytics');
|
|
15
|
+
|
|
16
|
+
const DAY_MS = 86400000;
|
|
17
|
+
const CHUNK_BYTES = 1024 * 1024;
|
|
18
|
+
const DEFAULT_MAX_BYTES = 96 * 1024 * 1024;
|
|
19
|
+
const OLD_RUN_TO_STOP = 200;
|
|
20
|
+
|
|
21
|
+
function stopped(signal) {
|
|
22
|
+
if (signal && signal.aborted) throw Object.assign(new Error('Collection stopped'), { code: 'collection_timeout' });
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function entryTime(entry) {
|
|
26
|
+
const stamp = Date.parse(entry.receivedAt || entry.timestamp || '');
|
|
27
|
+
return Number.isFinite(stamp) ? stamp : null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Streams one file newest-first. `onEntry(entry, time)` is called for every in-window line.
|
|
31
|
+
async function scanFile(filePath, { edgeMs, maxBytes, signal, onEntry }) {
|
|
32
|
+
const meta = { bytesRead: 0, size: 0, reachedWindowEdge: false, capped: false, lines: 0 };
|
|
33
|
+
let handle;
|
|
34
|
+
try { handle = await fs.promises.open(filePath, 'r'); } catch (error) {
|
|
35
|
+
if (error.code === 'ENOENT') return meta;
|
|
36
|
+
throw error;
|
|
37
|
+
}
|
|
38
|
+
try {
|
|
39
|
+
const { size } = await handle.stat();
|
|
40
|
+
meta.size = size;
|
|
41
|
+
let position = size;
|
|
42
|
+
let carry = Buffer.alloc(0);
|
|
43
|
+
let oldRun = 0;
|
|
44
|
+
const buffer = Buffer.allocUnsafe(CHUNK_BYTES);
|
|
45
|
+
const handleLine = (bytes) => {
|
|
46
|
+
if (!bytes.length) return true;
|
|
47
|
+
let entry;
|
|
48
|
+
try { entry = JSON.parse(bytes.toString('utf8')); } catch { return true; }
|
|
49
|
+
if (!entry || typeof entry !== 'object') return true;
|
|
50
|
+
meta.lines += 1;
|
|
51
|
+
const time = entryTime(entry);
|
|
52
|
+
if (time === null) return true;
|
|
53
|
+
if (time < edgeMs) { oldRun += 1; return oldRun < OLD_RUN_TO_STOP; }
|
|
54
|
+
oldRun = 0;
|
|
55
|
+
onEntry(entry, time);
|
|
56
|
+
return true;
|
|
57
|
+
};
|
|
58
|
+
while (position > 0) {
|
|
59
|
+
stopped(signal);
|
|
60
|
+
if (meta.bytesRead >= maxBytes) { meta.capped = true; return meta; }
|
|
61
|
+
const length = Math.min(CHUNK_BYTES, position);
|
|
62
|
+
position -= length;
|
|
63
|
+
await handle.read(buffer, 0, length, position);
|
|
64
|
+
meta.bytesRead += length;
|
|
65
|
+
const joined = carry.length ? Buffer.concat([buffer.subarray(0, length), carry]) : Buffer.from(buffer.subarray(0, length));
|
|
66
|
+
let end = joined.length;
|
|
67
|
+
let newline = joined.lastIndexOf(10, end - 1);
|
|
68
|
+
while (newline >= 0) {
|
|
69
|
+
if (!handleLine(joined.subarray(newline + 1, end))) { meta.reachedWindowEdge = true; return meta; }
|
|
70
|
+
end = newline;
|
|
71
|
+
newline = end > 0 ? joined.lastIndexOf(10, end - 1) : -1;
|
|
72
|
+
}
|
|
73
|
+
carry = Buffer.from(joined.subarray(0, end));
|
|
74
|
+
}
|
|
75
|
+
if (carry.length && !handleLine(carry)) meta.reachedWindowEdge = true;
|
|
76
|
+
else if (position <= 0) meta.reachedWindowEdge = true;
|
|
77
|
+
return meta;
|
|
78
|
+
} finally {
|
|
79
|
+
await handle.close();
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function telemetryPaths(feedbackDir) {
|
|
84
|
+
try {
|
|
85
|
+
const found = telemetry.getTelemetrySourceDiagnostics(feedbackDir).activePaths;
|
|
86
|
+
if (found.length) return found;
|
|
87
|
+
} catch { /* fall through to the default location */ }
|
|
88
|
+
return [path.join(feedbackDir, telemetry.TELEMETRY_FILE_NAME)];
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function scanTelemetry({ feedbackDir, days = 30, now = Date.now(), maxBytes = DEFAULT_MAX_BYTES, signal, onEntry }) {
|
|
92
|
+
const edgeMs = now - days * DAY_MS;
|
|
93
|
+
const files = [];
|
|
94
|
+
for (const filePath of telemetryPaths(feedbackDir)) files.push({ file: path.basename(filePath), ...(await scanFile(filePath, { edgeMs, maxBytes, signal, onEntry })) });
|
|
95
|
+
const bytesRead = files.reduce((sum, file) => sum + file.bytesRead, 0);
|
|
96
|
+
const size = files.reduce((sum, file) => sum + file.size, 0);
|
|
97
|
+
const partial = files.some((file) => file.capped);
|
|
98
|
+
return { windowDays: days, edge: new Date(edgeMs).toISOString(), bytesRead, size, partial, empty: size === 0, files: files.map(({ file, size: fileSize, bytesRead: read, capped }) => ({ file, size: fileSize, bytesRead: read, capped })) };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const kind = (entry) => String(entry.eventType || entry.event || '').toLowerCase();
|
|
102
|
+
const isWeb = (entry) => (entry.clientType || entry.client) === 'web';
|
|
103
|
+
const isFlagged = (entry) => entry.isBotTraffic === true || entry.isInternal === true || entry.isTest === true;
|
|
104
|
+
|
|
105
|
+
// Visitors, sessions, page views, CTA clicks, checkout starts and paid confirmations, in total and per UTC day.
|
|
106
|
+
async function readTrafficWindow(options) {
|
|
107
|
+
const days = new Map();
|
|
108
|
+
const visitors = new Set();
|
|
109
|
+
const flagged = new Set();
|
|
110
|
+
const sessions = new Set();
|
|
111
|
+
const totals = { pageViews: 0, ctaClicks: 0, checkoutStarts: 0, checkoutPaidConfirmations: 0, webEvents: 0 };
|
|
112
|
+
const dayOf = (time) => {
|
|
113
|
+
const key = new Date(time).toISOString().slice(0, 10);
|
|
114
|
+
let day = days.get(key);
|
|
115
|
+
if (!day) { day = { date: key, visitors: new Set(), sessions: new Set(), pageViews: 0, ctaClicks: 0, checkoutStarts: 0, checkoutPaidConfirmations: 0 }; days.set(key, day); }
|
|
116
|
+
return day;
|
|
117
|
+
};
|
|
118
|
+
const meta = await scanTelemetry({
|
|
119
|
+
...options,
|
|
120
|
+
onEntry(entry, time) {
|
|
121
|
+
if (!isWeb(entry)) return;
|
|
122
|
+
totals.webEvents += 1;
|
|
123
|
+
const day = dayOf(time);
|
|
124
|
+
const who = entry.visitorId || entry.installId || entry.sessionId || null;
|
|
125
|
+
if (who) { visitors.add(who); day.visitors.add(who); if (isFlagged(entry)) flagged.add(who); }
|
|
126
|
+
if (entry.sessionId) { sessions.add(entry.sessionId); day.sessions.add(entry.sessionId); }
|
|
127
|
+
const type = kind(entry);
|
|
128
|
+
if (type === 'landing_page_view') { totals.pageViews += 1; day.pageViews += 1; }
|
|
129
|
+
if (telemetry.isMarketingClickEvent(type) && !telemetry.isDirectStripeBeacon(entry)) { totals.ctaClicks += 1; day.ctaClicks += 1; }
|
|
130
|
+
if (telemetry.isCheckoutStartEvent(type)) { totals.checkoutStarts += 1; day.checkoutStarts += 1; }
|
|
131
|
+
if (type === 'checkout_paid_confirmed') { totals.checkoutPaidConfirmations += 1; day.checkoutPaidConfirmations += 1; }
|
|
132
|
+
},
|
|
133
|
+
});
|
|
134
|
+
const daily = [...days.values()].sort((a, b) => a.date.localeCompare(b.date)).map((day) => ({ date: day.date, visitors: day.visitors.size, sessions: day.sessions.size, pageViews: day.pageViews, ctaClicks: day.ctaClicks, checkoutStarts: day.checkoutStarts, checkoutPaidConfirmations: day.checkoutPaidConfirmations }));
|
|
135
|
+
return {
|
|
136
|
+
...meta,
|
|
137
|
+
traffic: { visitors: visitors.size, realVisitors: visitors.size - flagged.size, botOrInternalVisitors: flagged.size, sessions: sessions.size, pageViews: totals.pageViews, ctaClicks: totals.ctaClicks, checkoutStarts: totals.checkoutStarts, checkoutPaidConfirmations: totals.checkoutPaidConfirmations },
|
|
138
|
+
daily,
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
module.exports = { scanFile, scanTelemetry, readTrafficWindow, DEFAULT_MAX_BYTES };
|
package/scripts/rate-limiter.js
CHANGED
|
@@ -29,7 +29,6 @@ const FREE_TIER_LIMITS = {
|
|
|
29
29
|
};
|
|
30
30
|
|
|
31
31
|
const FREE_TIER_MAX_GATES = 3; // 3 active prevention rules on free; Pro is unlimited
|
|
32
|
-
const FREE_TIER_DAILY_BLOCKS = 2; // 3 gate blocks/day on free; after limit, deny → warn + upgrade CTA
|
|
33
32
|
|
|
34
33
|
const UPGRADE_MESSAGE = `Pro: ${PRO_PRICE_LABEL} — unlimited rules, recall, lesson search, dashboard, and exports: ${PRO_MONTHLY_PAYMENT_LINK}\n Enterprise: ${ENTERPRISE_PRICE_LABEL} after workflow qualification.`;
|
|
35
34
|
|
|
@@ -242,6 +241,13 @@ function proWouldHaveBlockedSentence(mistake) {
|
|
|
242
241
|
return `Pro would have blocked this repeat: ${clean}. ${PRO_REPEAT_URL}`;
|
|
243
242
|
}
|
|
244
243
|
|
|
244
|
+
// One plain line shown the moment a free install learns a rule it cannot enforce (rule 4 and up).
|
|
245
|
+
function capUpgradeLine(rule, maxActive = FREE_TIER_MAX_GATES) {
|
|
246
|
+
const clean = scrubRepeatText(rule);
|
|
247
|
+
if (!clean) return null;
|
|
248
|
+
return `ThumbGate learned a ${maxActive + 1}th rule (${clean}), but Free enforces ${maxActive}. Pro enforces all of them: ${PRO_REPEAT_URL}`;
|
|
249
|
+
}
|
|
250
|
+
|
|
245
251
|
function droppedRepeatFromRulesMarkdown(markdown, maxActive = FREE_TIER_MAX_GATES) {
|
|
246
252
|
const mistakes = [];
|
|
247
253
|
for (const section of String(markdown || '').split(/\n## /)) {
|
|
@@ -268,12 +274,12 @@ module.exports = {
|
|
|
268
274
|
todayKey,
|
|
269
275
|
FREE_TIER_LIMITS,
|
|
270
276
|
FREE_TIER_MAX_GATES,
|
|
271
|
-
FREE_TIER_DAILY_BLOCKS,
|
|
272
277
|
TRIAL_DAYS,
|
|
273
278
|
UPGRADE_MESSAGE,
|
|
274
279
|
PAYWALL_MESSAGES,
|
|
275
280
|
USAGE_FILE,
|
|
276
281
|
proWouldHaveBlockedSentence,
|
|
282
|
+
capUpgradeLine,
|
|
277
283
|
droppedRepeatFromRulesMarkdown,
|
|
278
284
|
scrubRepeatText,
|
|
279
285
|
};
|