thumbgate 1.40.3 → 1.40.6
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/.agents/skills/comet-session-logger/SKILL.md +8 -5
- package/.claude-plugin/plugin.json +1 -1
- package/.well-known/mcp/server-card.json +1 -1
- package/README.md +7 -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 +35 -7
- package/public/about.html +2 -2
- package/public/admin.html +546 -50
- package/public/case-studies.html +1 -0
- package/public/dashboard.html +7 -6
- package/public/diagnostic.html +15 -12
- package/public/index.html +210 -88
- package/public/install.html +9 -8
- package/public/js/connect-panel.js +437 -0
- package/public/learn.html +8 -0
- package/public/numbers.html +2 -2
- package/public/preview.html +42 -0
- package/public/pricing.html +55 -10
- package/public/support.html +1 -1
- package/public/terms.html +1 -1
- package/scripts/auto-promote-gates.js +29 -4
- 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 +119 -0
- package/scripts/claude-feedback-sync.js +4 -2
- package/scripts/feedback-loop.js +41 -5
- 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 +508 -27
- package/scripts/owner-telemetry.js +151 -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/skills/comet-session-logger/SKILL.md +8 -5
- package/src/api/server.js +649 -107
- package/src/mcp/email-triage-server/index.js +92 -14
package/scripts/gates-engine.js
CHANGED
|
@@ -16,7 +16,7 @@ const crypto = require('crypto');
|
|
|
16
16
|
const { execFileSync, spawnSync } = require('child_process');
|
|
17
17
|
const { loadOptionalModule } = require('./private-core-boundary');
|
|
18
18
|
|
|
19
|
-
const { isProTier, isInTrialPeriod, FREE_TIER_MAX_GATES
|
|
19
|
+
const { isProTier, isInTrialPeriod, FREE_TIER_MAX_GATES } = require('./rate-limiter');
|
|
20
20
|
const {
|
|
21
21
|
DEFAULT_BASE_BRANCH,
|
|
22
22
|
evaluateOperationalIntegrity,
|
|
@@ -186,10 +186,9 @@ const SELF_PROTECT_HARD_FLOOR_GATE_IDS = new Set([
|
|
|
186
186
|
'self-protect-hooks-disable',
|
|
187
187
|
]);
|
|
188
188
|
// An expired task-scope lease gets its OWN gate id so it can be exempted from the two downgrade
|
|
189
|
-
//
|
|
190
|
-
// cosmetic: applyEnforcementPosture turns denials into warnings by default,
|
|
191
|
-
//
|
|
192
|
-
// A lease that stops binding when you are busy or over quota is not a lease.
|
|
189
|
+
// posture downgrade without touching ordinary task-scope denials. Without this the fail-closed
|
|
190
|
+
// guarantee is cosmetic: applyEnforcementPosture turns denials into warnings by default, so an
|
|
191
|
+
// edit under a lapsed lease would execute anyway. A lease that stops binding is not a lease.
|
|
193
192
|
const TASK_SCOPE_LEASE_EXPIRED_GATE_ID = 'task-scope-lease-expired';
|
|
194
193
|
|
|
195
194
|
const UNCONDITIONAL_HARD_FLOOR_GATE_IDS = new Set([
|
|
@@ -214,19 +213,20 @@ const UNCONDITIONAL_HARD_FLOOR_GATE_IDS = new Set([
|
|
|
214
213
|
'teams-single-reply-per-message',
|
|
215
214
|
'az-repos-pr-publish-requires-cross-review',
|
|
216
215
|
'mabl-failure-honesty',
|
|
216
|
+
// Catastrophic, effectively irreversible commands (issue #2782). A default install
|
|
217
|
+
// (no THUMBGATE_* variables) must deny these, same as secret exfiltration.
|
|
218
|
+
'force-push',
|
|
219
|
+
'git-reset-hard',
|
|
220
|
+
'git-clean-force',
|
|
221
|
+
'rm-rf-home-or-root',
|
|
222
|
+
'db-drop-table-production',
|
|
217
223
|
TASK_SCOPE_LEASE_EXPIRED_GATE_ID,
|
|
218
224
|
...SELF_PROTECT_HARD_FLOOR_GATE_IDS,
|
|
219
225
|
]);
|
|
220
|
-
//
|
|
221
|
-
//
|
|
222
|
-
//
|
|
223
|
-
//
|
|
224
|
-
// A free-tier user past their daily cap could have `rm -rf ~`, a force push,
|
|
225
|
-
// `git reset --hard`, or `git clean -f` silently allowed through. These four
|
|
226
|
-
// map directly to CLAUDE.md's own hard-block list and must never be subject
|
|
227
|
-
// to the daily cap discount, regardless of tier or strict-mode setting.
|
|
228
|
-
// financial-control is included for the same reason: a daily-cap discount on
|
|
229
|
-
// checkout/subscription spends would re-open the never-spend interlock.
|
|
226
|
+
// Catastrophic, effectively irreversible commands (issue #2782): `rm -rf ~`, a
|
|
227
|
+
// force push, `git reset --hard`, `git clean -f`, spend paths. These are
|
|
228
|
+
// evaluated before posture and are never downgraded to a warning, regardless
|
|
229
|
+
// of tier or strict-mode setting.
|
|
230
230
|
const CATASTROPHIC_DECLARATIVE_GATE_IDS = new Set([
|
|
231
231
|
TASK_SCOPE_LEASE_EXPIRED_GATE_ID,
|
|
232
232
|
'force-push',
|
|
@@ -238,13 +238,14 @@ const CATASTROPHIC_DECLARATIVE_GATE_IDS = new Set([
|
|
|
238
238
|
'financial-control',
|
|
239
239
|
'oneshot-control',
|
|
240
240
|
'oneshot-goal-done',
|
|
241
|
-
//
|
|
241
|
+
// A denied autonomous email send is the same class as force-push.
|
|
242
242
|
'outbound-email-send',
|
|
243
243
|
'outbound-off-brand-vertical-block',
|
|
244
244
|
'swarm-claim-exit-3-write-after-loss',
|
|
245
245
|
'teams-single-reply-per-message',
|
|
246
246
|
'az-repos-pr-publish-requires-cross-review',
|
|
247
247
|
'mabl-failure-honesty',
|
|
248
|
+
'db-drop-table-production',
|
|
248
249
|
]);
|
|
249
250
|
const SELF_PROTECT_CONFIG_TARGET_PATTERN = /(?:^|\/)(?:config\/gates\/|config\/(?:budget|enforcement|mcp-allowlists)\.json$|\.thumbgate\/config\.json$|thumbgate\.json$)/i;
|
|
250
251
|
const SELF_PROTECT_HOOK_TARGET_PATTERN = /(?:^|\/)(?:\.claude\/settings(?:\.local)?\.json|\.codex\/config\.toml|scripts\/hook-[^/]+\.(?:js|sh))$/i;
|
|
@@ -285,6 +286,11 @@ function alignmentLayerForResult(result) {
|
|
|
285
286
|
return 'business';
|
|
286
287
|
}
|
|
287
288
|
|
|
289
|
+
// A downgraded gate warns and the action runs, so its text must not say "blocked".
|
|
290
|
+
function describeAsFlagged(message) {
|
|
291
|
+
return String(message || '').replace(/\bblocked\b/gi, 'flagged');
|
|
292
|
+
}
|
|
293
|
+
|
|
288
294
|
function applyEnforcementPosture(result) {
|
|
289
295
|
if (!result || (result.decision !== 'deny' && result.decision !== 'approve')) return result;
|
|
290
296
|
const mode = resolveGovernanceMode();
|
|
@@ -304,7 +310,7 @@ function applyEnforcementPosture(result) {
|
|
|
304
310
|
governanceMode: mode,
|
|
305
311
|
alignmentLayer,
|
|
306
312
|
simulated: true,
|
|
307
|
-
message: `${result.message}\n\n⚠️ ThumbGate governance mode=${mode} — flagged and logged, not blocked.`,
|
|
313
|
+
message: `${describeAsFlagged(result.message)}\n\n⚠️ ThumbGate governance mode=${mode} — flagged and logged, not blocked.`,
|
|
308
314
|
};
|
|
309
315
|
}
|
|
310
316
|
return { ...result, governanceMode: mode, alignmentLayer, simulated: true };
|
|
@@ -325,7 +331,7 @@ function applyEnforcementPosture(result) {
|
|
|
325
331
|
warnByDefault: true,
|
|
326
332
|
governanceMode: 'sidecar',
|
|
327
333
|
alignmentLayer,
|
|
328
|
-
message: `${result.message}\n\n⚠️ ThumbGate is in warn-by-default mode (sidecar) — this was flagged and logged, not blocked. Set THUMBGATE_STRICT_ENFORCEMENT=1 or THUMBGATE_GOVERNANCE_MODE=live to hard-block other flagged actions.`,
|
|
334
|
+
message: `${describeAsFlagged(result.message)}\n\n⚠️ ThumbGate is in warn-by-default mode (sidecar) — this was flagged and logged, not blocked. Set THUMBGATE_STRICT_ENFORCEMENT=1 or THUMBGATE_GOVERNANCE_MODE=live to hard-block other flagged actions.`,
|
|
329
335
|
};
|
|
330
336
|
}
|
|
331
337
|
const BREAK_GLASS_CONDITION = 'thumbgate_break_glass';
|
|
@@ -1148,75 +1154,6 @@ function recordStat(gateId, action, gate, options = {}) {
|
|
|
1148
1154
|
}
|
|
1149
1155
|
}
|
|
1150
1156
|
|
|
1151
|
-
// ---------------------------------------------------------------------------
|
|
1152
|
-
// Free-tier daily block cap
|
|
1153
|
-
// ---------------------------------------------------------------------------
|
|
1154
|
-
|
|
1155
|
-
/**
|
|
1156
|
-
* Count today's gate blocks from stats. Free tier gets FREE_TIER_DAILY_BLOCKS
|
|
1157
|
-
* blocks/day. After the limit, deny → warn + upgrade CTA so the action proceeds
|
|
1158
|
-
* but the user sees they lost protection.
|
|
1159
|
-
*/
|
|
1160
|
-
function getTodayBlockCount() {
|
|
1161
|
-
const stats = loadStats();
|
|
1162
|
-
const today = todayKey();
|
|
1163
|
-
if (!stats.dailyBlocks || !stats.dailyBlocks[today]) return 0;
|
|
1164
|
-
return stats.dailyBlocks[today];
|
|
1165
|
-
}
|
|
1166
|
-
|
|
1167
|
-
function incrementTodayBlockCount() {
|
|
1168
|
-
const stats = loadStats();
|
|
1169
|
-
const today = todayKey();
|
|
1170
|
-
if (!stats.dailyBlocks) stats.dailyBlocks = {};
|
|
1171
|
-
// Clean old dates (keep only last 7 days to prevent unbounded growth)
|
|
1172
|
-
const keys = Object.keys(stats.dailyBlocks);
|
|
1173
|
-
if (keys.length > 7) {
|
|
1174
|
-
keys.sort();
|
|
1175
|
-
for (const k of keys.slice(0, keys.length - 7)) {
|
|
1176
|
-
delete stats.dailyBlocks[k];
|
|
1177
|
-
}
|
|
1178
|
-
}
|
|
1179
|
-
stats.dailyBlocks[today] = (stats.dailyBlocks[today] || 0) + 1;
|
|
1180
|
-
saveStats(stats);
|
|
1181
|
-
return stats.dailyBlocks[today];
|
|
1182
|
-
}
|
|
1183
|
-
|
|
1184
|
-
/**
|
|
1185
|
-
* If the user is free-tier and has exceeded daily block limit, downgrade
|
|
1186
|
-
* a deny result to a warn with an upgrade CTA. Returns null if no cap applies.
|
|
1187
|
-
*/
|
|
1188
|
-
function applyDailyBlockCap(denyResult) {
|
|
1189
|
-
if (process.env.THUMBGATE_SANDBOX_EVAL === '1') return null;
|
|
1190
|
-
// Catastrophic/irreversible commands (force-push, git reset --hard, git
|
|
1191
|
-
// clean -f, rm -rf on home/root) never get the free-tier daily-cap
|
|
1192
|
-
// discount — see issue #2782. Checked first, before any tier/CI shortcut,
|
|
1193
|
-
// so nothing can accidentally exempt a catastrophic gate from this floor.
|
|
1194
|
-
if (denyResult && CATASTROPHIC_DECLARATIVE_GATE_IDS.has(denyResult.gate)) return null;
|
|
1195
|
-
// Pro, trial, CI, and THUMBGATE_NO_RATE_LIMIT users are uncapped
|
|
1196
|
-
if (isProTier()) return null;
|
|
1197
|
-
if (process.env.CI || process.env.GITHUB_ACTIONS) return null;
|
|
1198
|
-
|
|
1199
|
-
const todayCount = getTodayBlockCount();
|
|
1200
|
-
if (todayCount < FREE_TIER_DAILY_BLOCKS) {
|
|
1201
|
-
// Under limit: allow the block, increment counter
|
|
1202
|
-
incrementTodayBlockCount();
|
|
1203
|
-
return null;
|
|
1204
|
-
}
|
|
1205
|
-
|
|
1206
|
-
// Over limit: downgrade deny → warn with upgrade CTA
|
|
1207
|
-
const remaining = 0;
|
|
1208
|
-
return {
|
|
1209
|
-
decision: 'warn',
|
|
1210
|
-
gate: denyResult.gate,
|
|
1211
|
-
message: `⚠️ ${denyResult.message}\n\n🔓 Daily protection limit reached (${FREE_TIER_DAILY_BLOCKS}/${FREE_TIER_DAILY_BLOCKS} blocks used). This action was allowed through. Upgrade for unlimited protection: https://thumbgate.ai/go/pro`,
|
|
1212
|
-
severity: denyResult.severity,
|
|
1213
|
-
reasoning: (denyResult.reasoning || []).concat([
|
|
1214
|
-
`Free-tier daily block limit (${FREE_TIER_DAILY_BLOCKS}) exceeded — deny downgraded to warn`,
|
|
1215
|
-
]),
|
|
1216
|
-
dailyBlockCapApplied: true,
|
|
1217
|
-
};
|
|
1218
|
-
}
|
|
1219
|
-
|
|
1220
1157
|
// ---------------------------------------------------------------------------
|
|
1221
1158
|
// Reasoning chain builder
|
|
1222
1159
|
// ---------------------------------------------------------------------------
|
|
@@ -2464,8 +2401,8 @@ function recordStructuralGateBlock(toolName, toolInput, result, options = {}) {
|
|
|
2464
2401
|
* Config order is useful for normal policy routing, but it must not let a broad
|
|
2465
2402
|
* rule mask a narrower irreversible-action rule. For example, the generic
|
|
2466
2403
|
* `push-without-thread-check` gate also matches `git push --force`; selecting it
|
|
2467
|
-
* first
|
|
2468
|
-
*
|
|
2404
|
+
* first let a downgrade path turn the action into a warning before the
|
|
2405
|
+
* `force-push` gate was ever evaluated.
|
|
2469
2406
|
*
|
|
2470
2407
|
* Catastrophic gates are deliberately limited to the audited allowlist above.
|
|
2471
2408
|
* Metric-backed gates are excluded because their condition is asynchronous and
|
|
@@ -3885,14 +3822,6 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath, options
|
|
|
3885
3822
|
reasoning,
|
|
3886
3823
|
...(adminOverride ? { requiresAdminOverride: true, adminOverride } : {}),
|
|
3887
3824
|
};
|
|
3888
|
-
// Free-tier daily block cap: after N blocks/day, deny → warn + upgrade CTA
|
|
3889
|
-
const cappedResult = applyDailyBlockCap(denyResult);
|
|
3890
|
-
if (cappedResult) {
|
|
3891
|
-
recordStat(gate.id, 'warn', gate, { ...execution, toolName, toolInput });
|
|
3892
|
-
const auditRecord = recordAuditEvent({ ...execution, toolName, toolInput, decision: 'warn', gateId: gate.id, message: cappedResult.message, severity: gate.severity, source: 'gates-engine', dailyBlockCapApplied: true });
|
|
3893
|
-
auditToFeedback(auditRecord, execution);
|
|
3894
|
-
return cappedResult;
|
|
3895
|
-
}
|
|
3896
3825
|
recordStat(gate.id, 'block', gate, { ...execution, toolName, toolInput });
|
|
3897
3826
|
const auditRecord = recordAuditEvent({ ...execution, toolName, toolInput, decision: 'deny', gateId: gate.id, message: overrideMessage, severity: gate.severity, source: 'gates-engine' });
|
|
3898
3827
|
auditToFeedback(auditRecord, execution);
|
|
@@ -4206,14 +4135,6 @@ function evaluateGatesInner(toolName, toolInput, configPath, options = {}) {
|
|
|
4206
4135
|
reasoning,
|
|
4207
4136
|
...(adminOverride ? { requiresAdminOverride: true, adminOverride } : {}),
|
|
4208
4137
|
};
|
|
4209
|
-
// Free-tier daily block cap: after N blocks/day, deny → warn + upgrade CTA
|
|
4210
|
-
const cappedResult = applyDailyBlockCap(denyResult);
|
|
4211
|
-
if (cappedResult) {
|
|
4212
|
-
recordStat(gate.id, 'warn', gate, { ...execution, toolName, toolInput });
|
|
4213
|
-
const auditRecord = recordAuditEvent({ ...execution, toolName, toolInput, decision: 'warn', gateId: gate.id, message: cappedResult.message, severity: gate.severity, source: 'gates-engine', dailyBlockCapApplied: true });
|
|
4214
|
-
auditToFeedback(auditRecord, execution);
|
|
4215
|
-
return cappedResult;
|
|
4216
|
-
}
|
|
4217
4138
|
recordStat(gate.id, 'block', gate, { ...execution, toolName, toolInput });
|
|
4218
4139
|
const auditRecord = recordAuditEvent({ ...execution, toolName, toolInput, decision: 'deny', gateId: gate.id, message: overrideMessage, severity: gate.severity, source: 'gates-engine' });
|
|
4219
4140
|
auditToFeedback(auditRecord, execution);
|
|
@@ -5513,7 +5434,18 @@ function buildDesignSelfCorrectionContext(toolName, toolInput = {}) {
|
|
|
5513
5434
|
}
|
|
5514
5435
|
}
|
|
5515
5436
|
|
|
5437
|
+
// Hook-facing entry. The first real block (then at most once per 7 days) carries one upgrade line in
|
|
5438
|
+
// the host-shown `systemMessage`; the reason the model reads is untouched. See first-block-upsell.js.
|
|
5516
5439
|
async function runAsync(rawInput) {
|
|
5440
|
+
const output = await runAsyncCore(rawInput);
|
|
5441
|
+
try {
|
|
5442
|
+
return require('./first-block-upsell').withFirstBlockUpsell(output);
|
|
5443
|
+
} catch {
|
|
5444
|
+
return output;
|
|
5445
|
+
}
|
|
5446
|
+
}
|
|
5447
|
+
|
|
5448
|
+
async function runAsyncCore(rawInput) {
|
|
5517
5449
|
const input = canonicalizeHookInput(rawInput);
|
|
5518
5450
|
const { hardFloor, securityScan } = evaluateUnconditionalHardFloor(input);
|
|
5519
5451
|
if (hardFloor) return formatOutput(hardFloor);
|
|
@@ -6213,9 +6145,6 @@ module.exports = {
|
|
|
6213
6145
|
PR_THREAD_RESOLUTION_ACTION,
|
|
6214
6146
|
HELPER_BYPASS_ACTION,
|
|
6215
6147
|
buildBlockActionProCta,
|
|
6216
|
-
applyDailyBlockCap,
|
|
6217
|
-
getTodayBlockCount,
|
|
6218
|
-
incrementTodayBlockCount,
|
|
6219
6148
|
effectiveCommandCwd,
|
|
6220
6149
|
resolveRepoRoot,
|
|
6221
6150
|
};
|
|
@@ -20,4 +20,23 @@ function isCountedHumanFeedback(entry) {
|
|
|
20
20
|
return !NON_HUMAN_TAGS.has(source);
|
|
21
21
|
}
|
|
22
22
|
|
|
23
|
-
|
|
23
|
+
// Before #5119 the MCP server stamped every capture_feedback call
|
|
24
|
+
// `reviewOrigin: automated`, so a thumb the agent recorded for the person sits in
|
|
25
|
+
// the log looking like a script's entry. Such a row is recognisable by what the
|
|
26
|
+
// capture tool writes and scripts and hooks do not: a store-learning or
|
|
27
|
+
// store-mistake action inside an agent session, with no source marker and no
|
|
28
|
+
// scraper tag. Rows from the shared store only count for the project named in
|
|
29
|
+
// scope.projectId, which the caller checks.
|
|
30
|
+
const MCP_CAPTURE_ACTIONS = new Set(['store-learning', 'store-mistake']);
|
|
31
|
+
|
|
32
|
+
function isLegacyMcpCapture(entry) {
|
|
33
|
+
if (!entry || String(entry.reviewOrigin || '').trim().toLowerCase() !== 'automated') return false;
|
|
34
|
+
if (!MCP_CAPTURE_ACTIONS.has(String(entry.actionType || ''))) return false;
|
|
35
|
+
const sessionId = entry.scope && entry.scope.sessionId;
|
|
36
|
+
if (typeof sessionId !== 'string' || !sessionId.startsWith('session_')) return false;
|
|
37
|
+
if (entry.memorySource || entry.source || entry.sourceEvent) return false;
|
|
38
|
+
const tags = Array.isArray(entry.tags) ? entry.tags : [];
|
|
39
|
+
return !tags.some((tag) => NON_HUMAN_TAGS.has(String(tag).trim().toLowerCase()));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
module.exports = { NON_HUMAN_TAGS, isCountedHumanFeedback, isLegacyMcpCapture };
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Owner-console operations log: server errors, Stripe webhook arrivals and failures, failed sign-ins, and a
|
|
5
|
+
* once-a-minute heartbeat the uptime figure is computed from. Append-only JSON lines in the feedback directory,
|
|
6
|
+
* trimmed to the newest half when a file passes MAX_BYTES (about 50,000 heartbeats: more than 30 days).
|
|
7
|
+
* Holds no personal data: an event is a time, a kind and a short plain-words label.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const fs = require('node:fs');
|
|
11
|
+
const path = require('node:path');
|
|
12
|
+
const { scanFile } = require('./owner-telemetry');
|
|
13
|
+
|
|
14
|
+
const EVENTS_FILE = 'ops-events.jsonl';
|
|
15
|
+
const HEARTBEAT_FILE = 'uptime-heartbeats.jsonl';
|
|
16
|
+
const HEARTBEAT_MS = 60000;
|
|
17
|
+
const MAX_BYTES = 4 * 1024 * 1024;
|
|
18
|
+
const DAY_MS = 86400000;
|
|
19
|
+
let directory = null;
|
|
20
|
+
let timer = null;
|
|
21
|
+
|
|
22
|
+
function setDirectory(dir) { directory = dir ? path.resolve(dir) : null; }
|
|
23
|
+
|
|
24
|
+
// The directory must already exist: a log write never recreates a directory someone removed.
|
|
25
|
+
function append(file, row) {
|
|
26
|
+
if (!directory) return false;
|
|
27
|
+
try {
|
|
28
|
+
fs.appendFileSync(path.join(directory, file), JSON.stringify(row) + '\n');
|
|
29
|
+
return true;
|
|
30
|
+
} catch { return false; }
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const stamp = () => new Date().toISOString();
|
|
34
|
+
|
|
35
|
+
// A server error in plain words, from the route that failed. Never a path with ids or query strings.
|
|
36
|
+
function describeError(pathname) {
|
|
37
|
+
const route = String(pathname || '');
|
|
38
|
+
if (/^\/v1\/billing\/webhook|^\/webhook\/stripe/.test(route)) return 'Stripe payment notification failed';
|
|
39
|
+
if (/^\/v1\/(billing\/checkout|checkout)|^\/checkout|^\/go\//.test(route)) return 'Checkout failed';
|
|
40
|
+
if (/^\/v1\/(cloud\/sso|auth)|^\/signin|^\/logout/.test(route)) return 'Sign-in or sign-out failed';
|
|
41
|
+
if (/^\/v1\/telemetry/.test(route)) return 'Site telemetry was not saved';
|
|
42
|
+
if (/^\/(v1\/admin|admin)/.test(route)) return 'Owner console request failed';
|
|
43
|
+
if (/^\/(dashboard|cloud)/.test(route)) return 'Dashboard page failed';
|
|
44
|
+
if (/^\/v1\//.test(route)) return 'API request failed';
|
|
45
|
+
return 'Web page failed';
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function recordError(pathname, status) { return append(EVENTS_FILE, { timestamp: stamp(), kind: 'error', what: describeError(pathname), status: Number.isFinite(status) ? status : null }); }
|
|
49
|
+
function recordWebhook(ok, status) { return append(EVENTS_FILE, { timestamp: stamp(), kind: 'webhook', ok: Boolean(ok), status: Number.isFinite(status) ? status : null }); }
|
|
50
|
+
function recordSignInFailure(reason) {
|
|
51
|
+
const safe = /^[a-z0-9_]{1,48}$/.test(String(reason || '')) ? String(reason) : 'sign_in_failed';
|
|
52
|
+
return append(EVENTS_FILE, { timestamp: stamp(), kind: 'sign_in_failed', reason: safe });
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function trim(file) {
|
|
56
|
+
if (!directory) return;
|
|
57
|
+
const target = path.join(directory, file);
|
|
58
|
+
try {
|
|
59
|
+
const { size } = fs.statSync(target);
|
|
60
|
+
if (size <= MAX_BYTES) return;
|
|
61
|
+
const fd = fs.openSync(target, 'r');
|
|
62
|
+
try {
|
|
63
|
+
const keep = Math.floor(MAX_BYTES / 2);
|
|
64
|
+
const buffer = Buffer.alloc(keep);
|
|
65
|
+
fs.readSync(fd, buffer, 0, keep, size - keep);
|
|
66
|
+
const text = buffer.toString('utf8');
|
|
67
|
+
const firstNewline = text.indexOf('\n');
|
|
68
|
+
fs.writeFileSync(target, firstNewline >= 0 ? text.slice(firstNewline + 1) : '');
|
|
69
|
+
} finally { fs.closeSync(fd); }
|
|
70
|
+
} catch { /* the log is best effort */ }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// One beat now and one a minute from now on, for as long as the process lives. Calling it again restarts the timer.
|
|
74
|
+
function startHeartbeat(dir) {
|
|
75
|
+
if (dir) setDirectory(dir);
|
|
76
|
+
if (timer) clearInterval(timer);
|
|
77
|
+
const beat = () => { append(HEARTBEAT_FILE, { timestamp: stamp() }); trim(HEARTBEAT_FILE); trim(EVENTS_FILE); };
|
|
78
|
+
beat();
|
|
79
|
+
timer = setInterval(beat, HEARTBEAT_MS);
|
|
80
|
+
timer.unref?.();
|
|
81
|
+
return () => { clearInterval(timer); timer = null; };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Every row of one log file inside the window, as {time, ...row}, newest first.
|
|
85
|
+
async function readLog(feedbackDir, file, { now = Date.now(), days = 30, signal } = {}) {
|
|
86
|
+
const rows = [];
|
|
87
|
+
const meta = await scanFile(path.join(feedbackDir, file), { edgeMs: now - days * DAY_MS, maxBytes: 8 * 1024 * 1024, signal, onEntry: (entry, time) => rows.push({ ...entry, time }) });
|
|
88
|
+
return { rows, size: meta.size };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
module.exports = { EVENTS_FILE, HEARTBEAT_FILE, HEARTBEAT_MS, MAX_BYTES, setDirectory, describeError, recordError, recordWebhook, recordSignInFailure, startHeartbeat, readLog };
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Pure functions that turn the operations log, the in-memory response timings and the deploy facts into the
|
|
5
|
+
* plain-words Observability report the owner console shows. Every block carries either its numbers and a
|
|
6
|
+
* `source`, or a `reason` saying why the numbers are missing: nothing here returns a bare null for a human to guess at.
|
|
7
|
+
* Times travel as ISO strings; the page formats them in the owner's own clock.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const MIN = 60000;
|
|
11
|
+
const HOUR = 3600000;
|
|
12
|
+
const DAY = 86400000;
|
|
13
|
+
const HEARTBEAT_MS = 60000;
|
|
14
|
+
const BEAT_GAP_MS = 150000;
|
|
15
|
+
const GB = 1024 ** 3;
|
|
16
|
+
|
|
17
|
+
const iso = (ms) => new Date(ms).toISOString();
|
|
18
|
+
const plural = (n, word) => n + ' ' + word + (n === 1 ? '' : 's');
|
|
19
|
+
|
|
20
|
+
function ago(ms) {
|
|
21
|
+
if (ms < MIN) return 'under a minute ago';
|
|
22
|
+
if (ms < HOUR) return plural(Math.round(ms / MIN), 'minute') + ' ago';
|
|
23
|
+
if (ms < DAY) return plural(Math.round(ms / HOUR), 'hour') + ' ago';
|
|
24
|
+
return plural(Math.round(ms / DAY), 'day') + ' ago';
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function uptimeBlock({ beats, now }) {
|
|
28
|
+
const source = 'server heartbeat, one a minute';
|
|
29
|
+
if (!beats.length) return { percent: null, observedDays: null, since: null, lastOutage: null, source, reason: 'Uptime is not collected yet: the server heartbeat has not written anything.' };
|
|
30
|
+
const times = beats.slice().sort((a, b) => a - b);
|
|
31
|
+
const first = times[0];
|
|
32
|
+
const observedMs = now - first;
|
|
33
|
+
if (times.length < 3 || observedMs < 5 * MIN) return { percent: null, observedDays: null, since: iso(first), lastOutage: null, source, reason: 'Not enough heartbeats yet to measure uptime.' };
|
|
34
|
+
let downMs = 0;
|
|
35
|
+
let lastOutage = null;
|
|
36
|
+
for (let i = 1; i < times.length; i += 1) {
|
|
37
|
+
const gap = times[i] - times[i - 1];
|
|
38
|
+
if (gap <= BEAT_GAP_MS) continue;
|
|
39
|
+
const down = gap - HEARTBEAT_MS;
|
|
40
|
+
downMs += down;
|
|
41
|
+
lastOutage = { startedAt: iso(times[i - 1] + HEARTBEAT_MS), endedAt: iso(times[i]), minutes: Math.max(1, Math.round(down / MIN)) };
|
|
42
|
+
}
|
|
43
|
+
return { percent: Math.round((1 - downMs / observedMs) * 10000) / 100, observedDays: Math.round((observedMs / DAY) * 10) / 10, since: iso(first), lastOutage, source, reason: null };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function errorsBlock({ events, now, collectingSince }) {
|
|
47
|
+
const source = 'server error log (HTTP 500 to 599 answers)';
|
|
48
|
+
if (collectingSince === null) return { lastHour: null, last24Hours: null, top: [], since: null, source, reason: 'The error log is not collected yet.' };
|
|
49
|
+
const errors = events.filter((event) => event.kind === 'error');
|
|
50
|
+
const within = (event, span) => now - event.time <= span;
|
|
51
|
+
const groups = new Map();
|
|
52
|
+
for (const event of errors.filter((e) => within(e, DAY))) {
|
|
53
|
+
const key = event.what + '|' + event.status;
|
|
54
|
+
const group = groups.get(key) || { what: String(event.what || 'Server error'), status: event.status ?? null, count: 0, lastSeenMs: 0 };
|
|
55
|
+
group.count += 1;
|
|
56
|
+
group.lastSeenMs = Math.max(group.lastSeenMs, event.time);
|
|
57
|
+
groups.set(key, group);
|
|
58
|
+
}
|
|
59
|
+
const top = [...groups.values()].sort((a, b) => b.count - a.count || b.lastSeenMs - a.lastSeenMs).slice(0, 5).map((g) => ({ what: g.what, status: g.status, count: g.count, lastSeenAt: iso(g.lastSeenMs) }));
|
|
60
|
+
return { lastHour: errors.filter((e) => within(e, HOUR)).length, last24Hours: errors.filter((e) => within(e, DAY)).length, top, since: iso(collectingSince), source, reason: null };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const SPEED_GROUPS = [['page', 'Web pages'], ['api', 'API'], ['telemetry', 'Site telemetry']];
|
|
64
|
+
function speedBlock({ speed, startedAt }) {
|
|
65
|
+
const source = 'response times measured by this server since it started';
|
|
66
|
+
const groups = [];
|
|
67
|
+
for (const [key, name] of SPEED_GROUPS) {
|
|
68
|
+
const entry = speed && speed[key];
|
|
69
|
+
if (entry && entry.samples > 0) groups.push({ name, samples: entry.samples, typicalMs: entry.p50, slowestFivePercentMs: entry.p95 });
|
|
70
|
+
}
|
|
71
|
+
if (!groups.length) return { groups: [], since: startedAt, source, reason: 'No requests have been measured since the server started.' };
|
|
72
|
+
return { groups, since: startedAt, source, reason: null };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function deployBlock({ startedAt, sha, title, titleReason, repo }) {
|
|
76
|
+
const full = typeof sha === 'string' && /^[0-9a-f]{7,64}$/i.test(sha) ? sha.toLowerCase() : null;
|
|
77
|
+
return {
|
|
78
|
+
startedAt: startedAt || null,
|
|
79
|
+
sha: full,
|
|
80
|
+
shortSha: full ? full.slice(0, 9) : null,
|
|
81
|
+
commitUrl: full && repo ? 'https://github.com/' + repo + '/commit/' + full : null,
|
|
82
|
+
commitTitle: title || null,
|
|
83
|
+
reason: full ? (title ? null : (titleReason || 'The commit title could not be looked up.')) : 'This build did not report which commit it came from.',
|
|
84
|
+
source: 'build record and GitHub',
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function webhookBlock({ events, now, collectingSince }) {
|
|
89
|
+
const source = 'Stripe notifications received by this server';
|
|
90
|
+
if (collectingSince === null) return { lastArrivedAt: null, failures24h: null, lastFailureAt: null, since: null, source, reason: 'Stripe notification logging is not collected yet.' };
|
|
91
|
+
const hooks = events.filter((event) => event.kind === 'webhook').sort((a, b) => b.time - a.time);
|
|
92
|
+
const failures = hooks.filter((event) => event.ok === false);
|
|
93
|
+
const failures24h = failures.filter((event) => now - event.time <= DAY).length;
|
|
94
|
+
return {
|
|
95
|
+
lastArrivedAt: hooks.length ? iso(hooks[0].time) : null,
|
|
96
|
+
failures24h,
|
|
97
|
+
lastFailureAt: failures.length ? iso(failures[0].time) : null,
|
|
98
|
+
since: iso(collectingSince),
|
|
99
|
+
source,
|
|
100
|
+
reason: hooks.length ? null : 'No Stripe notification has arrived since logging began.',
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const SIGN_IN_WORDS = {
|
|
105
|
+
invalid_state: 'sign-in link expired or was reused',
|
|
106
|
+
invalid_id_token: 'provider sent a bad token',
|
|
107
|
+
invalid_signature: 'token signature did not match',
|
|
108
|
+
expired_token: 'token had expired',
|
|
109
|
+
wrong_audience: 'token was meant for another app',
|
|
110
|
+
invalid_issuer: 'token came from an unexpected issuer',
|
|
111
|
+
unverified_email: 'email address not verified',
|
|
112
|
+
sso_not_configured: 'sign-in is not configured',
|
|
113
|
+
jwks_unavailable: 'provider keys could not be loaded',
|
|
114
|
+
unknown_signing_key: 'provider key not recognised',
|
|
115
|
+
invalid_nonce: 'sign-in check value did not match',
|
|
116
|
+
sign_in_failed: 'sign-in failed',
|
|
117
|
+
};
|
|
118
|
+
function signInBlock({ events, now, collectingSince }) {
|
|
119
|
+
const source = 'sign-in failures logged by this server';
|
|
120
|
+
if (collectingSince === null) return { failed24h: null, reasons: [], since: null, source, reason: 'Sign-in failures are not collected yet.' };
|
|
121
|
+
const failed = events.filter((event) => event.kind === 'sign_in_failed' && now - event.time <= DAY);
|
|
122
|
+
const counts = new Map();
|
|
123
|
+
for (const event of failed) counts.set(event.reason, (counts.get(event.reason) || 0) + 1);
|
|
124
|
+
const reasons = [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, 3).map(([reason, count]) => ({ words: SIGN_IN_WORDS[reason] || String(reason).replaceAll('_', ' '), count }));
|
|
125
|
+
return { failed24h: failed.length, reasons, since: iso(collectingSince), source, reason: null };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function diskBlock(disk) {
|
|
129
|
+
const source = 'the volume holding the data folder';
|
|
130
|
+
if (!disk || !Number.isFinite(disk.capacityBytes) || disk.capacityBytes <= 0) return { usedGb: null, capacityGb: null, percent: null, source, reason: 'Disk size could not be read from the server.' };
|
|
131
|
+
const round1 = (value) => Math.round(value * 10) / 10;
|
|
132
|
+
return { usedGb: round1(disk.usedBytes / GB), capacityGb: round1(disk.capacityBytes / GB), percent: Math.round((disk.usedBytes / disk.capacityBytes) * 100), source, reason: null };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function headline({ uptime, errors, webhooks, signIn, disk, now }) {
|
|
136
|
+
const problems = [];
|
|
137
|
+
let red = false;
|
|
138
|
+
if (errors.lastHour > 0) { problems.push(plural(errors.lastHour, 'server error') + ' in the last hour'); if (errors.lastHour >= 10) red = true; }
|
|
139
|
+
if (uptime.lastOutage && now - Date.parse(uptime.lastOutage.endedAt) <= DAY) problems.push('the site was down for ' + plural(uptime.lastOutage.minutes, 'minute') + ', ' + ago(now - Date.parse(uptime.lastOutage.endedAt)));
|
|
140
|
+
if (webhooks.failures24h > 0) {
|
|
141
|
+
problems.push(plural(webhooks.failures24h, 'Stripe notification') + ' failed in 24 hours');
|
|
142
|
+
if (webhooks.lastFailureAt && now - Date.parse(webhooks.lastFailureAt) <= HOUR) red = true;
|
|
143
|
+
}
|
|
144
|
+
if (signIn.failed24h >= 5) problems.push(signIn.failed24h + ' failed sign-ins in 24 hours');
|
|
145
|
+
if (disk.percent !== null && disk.percent >= 85) { problems.push('the disk is ' + disk.percent + '% full'); if (disk.percent >= 95) red = true; }
|
|
146
|
+
if (problems.length) return { level: red ? 'red' : 'amber', sentence: (red ? 'Problem: ' : 'Needs a look: ') + problems.join('; ') + '.' };
|
|
147
|
+
if (errors.reason) return { level: 'amber', sentence: 'The site is up, but server errors are not being counted yet.' };
|
|
148
|
+
if (errors.since && now - Date.parse(errors.since) < HOUR) return { level: 'green', sentence: 'All good so far: site up, no errors since error counting began ' + ago(now - Date.parse(errors.since)) + '.' };
|
|
149
|
+
return { level: 'green', sentence: 'All good: site up, no errors in the last hour.' };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// events: ops-events rows {time, kind, ...}; beats: heartbeat times in ms; collectingSince: ms of the first heartbeat or event, or null.
|
|
153
|
+
function buildReport({ now = Date.now(), events = [], beats = [], speed = null, startedAt = null, uptimeSeconds = null, sha = null, commitTitle = null, commitTitleReason = null, repo = null, disk = null }) {
|
|
154
|
+
const times = [...beats, ...events.map((event) => event.time)];
|
|
155
|
+
const collectingSince = times.length ? Math.min(...times) : null;
|
|
156
|
+
const uptime = uptimeBlock({ beats, now });
|
|
157
|
+
const errors = errorsBlock({ events, now, collectingSince });
|
|
158
|
+
const webhooks = webhookBlock({ events, now, collectingSince });
|
|
159
|
+
const signIn = signInBlock({ events, now, collectingSince });
|
|
160
|
+
const diskReport = diskBlock(disk);
|
|
161
|
+
return {
|
|
162
|
+
headline: headline({ uptime, errors, webhooks, signIn, disk: diskReport, now }),
|
|
163
|
+
uptime,
|
|
164
|
+
errors,
|
|
165
|
+
speed: speedBlock({ speed, startedAt }),
|
|
166
|
+
lastDeploy: deployBlock({ startedAt, sha, title: commitTitle, titleReason: commitTitleReason, repo }),
|
|
167
|
+
webhooks,
|
|
168
|
+
signIn,
|
|
169
|
+
disk: diskReport,
|
|
170
|
+
runningFor: { seconds: Number.isFinite(uptimeSeconds) ? Math.floor(uptimeSeconds) : null, since: startedAt, source: 'this server process', reason: Number.isFinite(uptimeSeconds) ? null : 'The server did not report how long it has been running.' },
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
module.exports = { buildReport, uptimeBlock, errorsBlock, speedBlock, deployBlock, webhookBlock, signInBlock, diskBlock, headline, ago };
|