ctxtop 0.0.0-stage → 4.1.0
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/.antigravity-plugin/plugin.json +36 -0
- package/.claude-plugin/plugin.json +18 -0
- package/CHECKSUMS.sha256 +166 -0
- package/LICENSE +27 -0
- package/README.md +350 -2
- package/SECURITY.md +22 -0
- package/agents/ah-flash-scout.md +25 -0
- package/assets/advanced_view_loaded_420px.png +0 -0
- package/assets/hero-demo.svg +188 -0
- package/assets/logo.svg +19 -0
- package/assets/simple_view_lean_420px.png +0 -0
- package/assets/simple_view_loaded_420px.png +0 -0
- package/assets/social-preview.svg +72 -0
- package/assets/zone_c_step3_shield_full.png +0 -0
- package/bin/ah-statusline.mjs +175 -0
- package/bin/cli.mjs +3 -0
- package/bin/ctxtop.mjs +1799 -0
- package/commands/cost-radar.md +11 -0
- package/commands/evolve.md +10 -0
- package/commands/handoff.md +10 -0
- package/commands/horizon.md +10 -0
- package/commands/inspect.md +10 -0
- package/commands/precheck.md +10 -0
- package/config/default_flightcheck.json +133 -0
- package/config/modelCatalog.json +785 -0
- package/config/platformQuirks.json +19 -0
- package/hooks/handlers/compact-lifecycle.mjs +577 -0
- package/hooks/handlers/config-change.mjs +402 -0
- package/hooks/handlers/hookIo.mjs +311 -0
- package/hooks/handlers/hookIpcClient.mjs +83 -0
- package/hooks/handlers/post-model-switch.mjs +111 -0
- package/hooks/handlers/post-tool-use.mjs +366 -0
- package/hooks/handlers/pre-model-switch.mjs +1048 -0
- package/hooks/handlers/pre-tool-use.mjs +632 -0
- package/hooks/handlers/stop-gate.mjs +526 -0
- package/hooks/handlers/user-prompt-submit.mjs +367 -0
- package/hooks/hooks.json +131 -0
- package/hooks/post_invocation.mjs +13 -0
- package/hooks/post_tool_use.mjs +25 -0
- package/hooks/pre_invocation.mjs +14 -0
- package/hooks/pre_tool_use.mjs +97 -0
- package/hooks/register.js +726 -0
- package/hooks/session_start.mjs +24 -0
- package/hooks/stop.mjs +23 -0
- package/hooks.json +56 -0
- package/package.json +110 -4
- package/packages/antigravity/package.json +14 -0
- package/packages/antigravity/src/index.mjs +1 -0
- package/packages/claude-code/package.json +14 -0
- package/packages/claude-code/src/index.mjs +2 -0
- package/packages/core/package.json +14 -0
- package/packages/core/src/index.mjs +1 -0
- package/packages/engine-node/package.json +14 -0
- package/packages/engine-node/src/index.mjs +1 -0
- package/packages/mcp/package.json +17 -0
- package/packages/mcp/src/server.mjs +396 -0
- package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
- package/packages/pro/README-SIGNING.md +30 -0
- package/packages/pro/package.json +16 -0
- package/packages/pro/src/index.mjs +3 -0
- package/packages/pro/src/team_finops_pack.mjs +241 -0
- package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
- package/plugin.json +36 -0
- package/rules/AGENTS.md +10 -0
- package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
- package/sidecars/horizon-daemon/server.mjs +2038 -0
- package/sidecars/horizon-daemon/sidecar.json +19 -0
- package/skills/cost-radar/SKILL.md +21 -0
- package/skills/evolve/SKILL.md +21 -0
- package/skills/handoff/SKILL.md +50 -0
- package/skills/horizon/SKILL.md +17 -0
- package/skills/inspect/SKILL.md +18 -0
- package/skills/precheck/SKILL.md +44 -0
- package/src/adapters/antigravity/index.mjs +109 -0
- package/src/adapters/claude-code/index.mjs +194 -0
- package/src/cli/cost_radar.mjs +70 -0
- package/src/cli/doctor.mjs +351 -0
- package/src/cli/horizon_hud.mjs +888 -0
- package/src/cli/init.mjs +425 -0
- package/src/cli/postmortem.mjs +515 -0
- package/src/coach/cacheGravityRouter.mjs +12 -0
- package/src/config/modelCatalog.json +704 -0
- package/src/config/platformQuirks.json +19 -0
- package/src/core/action_queue.mjs +264 -0
- package/src/core/ag_bridge.mjs +346 -0
- package/src/core/atomic_io.mjs +124 -0
- package/src/core/baseline.mjs +607 -0
- package/src/core/blindspot_sensors.mjs +399 -0
- package/src/core/bucket_b_runtime.mjs +1200 -0
- package/src/core/classifier.mjs +1757 -0
- package/src/core/coach/circuit_breakers.mjs +650 -0
- package/src/core/coach/contradiction_auditor.mjs +239 -0
- package/src/core/coach/effort_advisor.mjs +143 -0
- package/src/core/coach/handoff_hydrator.mjs +483 -0
- package/src/core/coach/progressive_checkpointer.mjs +551 -0
- package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
- package/src/core/coach/reflector_queue.mjs +505 -0
- package/src/core/coach/saved_quota_ledger.mjs +615 -0
- package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
- package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
- package/src/core/coach/task_quota_router.mjs +955 -0
- package/src/core/coach/turn_zero_gate.mjs +574 -0
- package/src/core/compaction_coach.mjs +1126 -0
- package/src/core/config.mjs +214 -0
- package/src/core/constants.mjs +1987 -0
- package/src/core/detectors_det01_to_16.mjs +1523 -0
- package/src/core/doc_indexer.mjs +338 -0
- package/src/core/episodic_memory.mjs +135 -0
- package/src/core/fts5_output_compressor.mjs +359 -0
- package/src/core/git_ledger.mjs +189 -0
- package/src/core/handoff_audit.mjs +558 -0
- package/src/core/history.mjs +221 -0
- package/src/core/hook_diagnostics.mjs +158 -0
- package/src/core/horizon_classifier.mjs +326 -0
- package/src/core/horizon_config.mjs +802 -0
- package/src/core/host_watchdog.mjs +200 -0
- package/src/core/layer5_hygiene.mjs +1084 -0
- package/src/core/log_resolver.mjs +231 -0
- package/src/core/mcp_auditor.mjs +138 -0
- package/src/core/micro_skills_store.mjs +91 -0
- package/src/core/offenders.mjs +161 -0
- package/src/core/parser.mjs +1997 -0
- package/src/core/path_canonicalizer.mjs +73 -0
- package/src/core/paths.mjs +311 -0
- package/src/core/prefix_cache_shield.mjs +386 -0
- package/src/core/pro_license.mjs +385 -0
- package/src/core/prompt_rubric.mjs +518 -0
- package/src/core/pruner.mjs +433 -0
- package/src/core/quota.mjs +1860 -0
- package/src/core/rsi_instinct_engine.mjs +1197 -0
- package/src/core/rsl_clash_auditor.mjs +423 -0
- package/src/core/rsl_distiller.mjs +372 -0
- package/src/core/rsl_ledger.mjs +969 -0
- package/src/core/rsl_triage.mjs +909 -0
- package/src/core/sanitizer.mjs +121 -0
- package/src/core/session_auditor.mjs +658 -0
- package/src/core/session_forensics.mjs +303 -0
- package/src/core/session_timeline.mjs +358 -0
- package/src/core/settings.mjs +99 -0
- package/src/core/shared/detectors.mjs +1342 -0
- package/src/core/shared/fnv1a64.mjs +85 -0
- package/src/core/shared/handoff_schema.mjs +123 -0
- package/src/core/shared/index.mjs +5 -0
- package/src/core/shared/ipi_sanitizer.mjs +165 -0
- package/src/core/shared/micro_skills.mjs +1 -0
- package/src/core/shared/plugin_validator.mjs +202 -0
- package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
- package/src/core/shield_manager.mjs +1417 -0
- package/src/core/sidecar_store.mjs +302 -0
- package/src/core/sprint_metrics.mjs +366 -0
- package/src/core/sqlite_client.mjs +283 -0
- package/src/core/storage_doctor.mjs +358 -0
- package/src/core/subagents.mjs +609 -0
- package/src/core/swarm_topology.mjs +360 -0
- package/src/core/task_quota_router.mjs +1656 -0
- package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
- package/src/core/telemetry/scope_lock_registry.mjs +578 -0
- package/src/core/telemetry/shadow_file_detector.mjs +291 -0
- package/src/core/telemetry/trajectory_watcher.mjs +259 -0
- package/src/core/timeline_svg.mjs +236 -0
- package/src/core/tool_surgeon.mjs +305 -0
- package/src/core/trajectory_stitcher.mjs +645 -0
- package/src/core/u_shaped_optimizer.mjs +789 -0
- package/src/core/wal_hygiene.mjs +233 -0
- package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
- package/src/core-isomorphic/catalog/index.mjs +1 -0
- package/src/core-isomorphic/coach/cacheGravityRouter.mjs +1547 -0
- package/src/core-isomorphic/coach/microSkills.mjs +1 -0
- package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
- package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
- package/src/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
- package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
- package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +305 -0
- package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
- package/src/core-isomorphic/coach/ttlWatchdog.mjs +464 -0
- package/src/core-isomorphic/config/anthropicModelCatalog.json +606 -0
- package/src/core-isomorphic/config/catalogLoader.mjs +1268 -0
- package/src/core-isomorphic/config/horizonConfig.mjs +1055 -0
- package/src/core-isomorphic/control/callTree.mjs +338 -0
- package/src/core-isomorphic/control/coachLatches.mjs +126 -0
- package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
- package/src/core-isomorphic/control/index.mjs +49 -0
- package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
- package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
- package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
- package/src/core-isomorphic/diagnostics/index.mjs +9 -0
- package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
- package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +888 -0
- package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
- package/src/core-isomorphic/economics/cacheGravity.mjs +369 -0
- package/src/core-isomorphic/economics/cliffBreaker.mjs +256 -0
- package/src/core-isomorphic/economics/driftLatency.mjs +433 -0
- package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
- package/src/core-isomorphic/economics/index.mjs +47 -0
- package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
- package/src/core-isomorphic/guards/bucketBAlphaBeta.mjs +860 -0
- package/src/core-isomorphic/guards/bucketBGamma.mjs +442 -0
- package/src/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
- package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
- package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1184 -0
- package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +572 -0
- package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +913 -0
- package/src/core-isomorphic/guards/docIndexCore.mjs +446 -0
- package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +317 -0
- package/src/core-isomorphic/guards/slopsquatGate.mjs +551 -0
- package/src/core-isomorphic/index.js +27 -0
- package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
- package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
- package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
- package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
- package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1156 -0
- package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
- package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
- package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
- package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1237 -0
- package/src/core-isomorphic/ui/modViews.mjs +1504 -0
- package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
- package/src/core-isomorphic/ustf/index.mjs +7 -0
- package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
- package/src/core-isomorphic/ustf/schema.mjs +186 -0
- package/src/core-isomorphic/utils/runtime.mjs +962 -0
- package/src/demo/synthetic_states.mjs +661 -0
- package/src/diagnostics/bugReportGenerator.mjs +253 -0
- package/src/diagnostics/claudeHookCapabilities.mjs +396 -0
- package/src/diagnostics/doctorEngine.mjs +295 -0
- package/src/engine-node/db/index.mjs +58 -0
- package/src/engine-node/db/jsonl_fallback.mjs +184 -0
- package/src/engine-node/db/probe.mjs +342 -0
- package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
- package/src/engine-node/index.mjs +12 -0
- package/src/engine-node/ipc/client.mjs +447 -0
- package/src/engine-node/ipc/index.mjs +22 -0
- package/src/engine-node/ipc/protocol.mjs +177 -0
- package/src/engine-node/ipc/server.mjs +445 -0
- package/src/engine-node/offloader/index.mjs +6 -0
- package/src/engine-node/offloader/tool_offloader.mjs +241 -0
- package/src/engine-node/sensors/blindspots.mjs +376 -0
- package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
- package/src/engine-node/sensors/index.mjs +7 -0
- package/src/hooks/antigravity_rsl_hook.mjs +250 -0
- package/src/hooks/claude_rsl_hook.mjs +288 -0
- package/src/hooks/portfolio_runtime.mjs +858 -0
- package/src/hooks/post_invocation.mjs +611 -0
- package/src/hooks/pre_invocation.mjs +1725 -0
- package/src/hooks/session_start.mjs +199 -0
- package/src/shims/agy_cli_compressor.mjs +705 -0
- package/src/shims/agy_git_guard.mjs +749 -0
- package/src/shims/ah_log_query.mjs +39 -0
- package/src/ui/costRadarSvg.mjs +6 -0
- package/src/ui/horizonGrid.mjs +1 -0
- package/src/ui/horizonPanelHtml.mjs +1 -0
- package/src/ui/horizon_panel.css +167 -0
- package/src/ui/horizon_panel.js +212 -0
- package/src/ui/modViews.mjs +1 -0
- package/src/utils/modelSwitchTelemetry.mjs +308 -0
- package/src/utils/nodeIo.mjs +59 -0
- package/src/utils/runtime.mjs +1 -0
- package/src/utils/sessionCalibration.mjs +657 -0
- package/src/webview/advanced_view.html +1808 -0
- package/src/webview/horizon_panel.html +12397 -0
- package/src/webview/registry.mjs +80 -0
- package/src/webview/simple_view.html +1370 -0
|
@@ -0,0 +1,749 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import crypto from 'node:crypto';
|
|
5
|
+
import { spawnSync } from 'node:child_process';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { atomicWriteFileSync } from '../core/atomic_io.mjs';
|
|
8
|
+
import { recordHookDiagnostic } from '../core/hook_diagnostics.mjs';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* DET-19: Git Hook-Bypass Guard Shim (`src/shims/agy_git_guard.mjs`)
|
|
12
|
+
*
|
|
13
|
+
* Intercepts `git` invocations and strictly blocks evasion flags:
|
|
14
|
+
* - `git commit`, `push`, `merge`, `rebase`, `cherry-pick`, `am` with `--no-verify` or `-n` (where `-n` = `--no-verify`).
|
|
15
|
+
* - `git commit` with `--no-gpg-sign`.
|
|
16
|
+
* - Global / subcommand config overrides: `-c core.hooksPath=...`, `-ccore.hooksPath=...`, `git config ... core.hooksPath`.
|
|
17
|
+
* - Child environment overrides: `HUSKY=0`, `GIT_HOOKS=0`, `HUSKY_SKIP_HOOKS=1`, `GIT_CONFIG_COUNT` + `GIT_CONFIG_KEY_i=core.hooksPath`.
|
|
18
|
+
*
|
|
19
|
+
* Anti-Gaming Human Override:
|
|
20
|
+
* - Stores human bypass nonces outside the agent-writable workspace in
|
|
21
|
+
* `~/.attention-horizon/security/git_bypass_nonce.json` signed with a `0o600` HMAC key.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
const currentFilePath = fileURLToPath(import.meta.url);
|
|
25
|
+
const currentShimDir = path.dirname(currentFilePath);
|
|
26
|
+
|
|
27
|
+
export const DET19_CONSTANTS = Object.freeze({
|
|
28
|
+
DETECTOR_ID: 'DET-19',
|
|
29
|
+
EXIT_CODE_BLOCKED: 126,
|
|
30
|
+
EXIT_CODE_GIT_NOT_FOUND: 127,
|
|
31
|
+
BLOCKED_MESSAGE:
|
|
32
|
+
'[HORIZON DET-19 BLOCKED] Pre-commit / verification bypass flags (--no-verify, -n, hooksPath override) are prohibited. Read the hook failure output and fix the underlying lint, type, or test error.',
|
|
33
|
+
BYPASS_NONCE_TTL_MS: 60000,
|
|
34
|
+
PROTECTED_SUBCOMMANDS: Object.freeze(['commit', 'push', 'merge', 'rebase', 'cherry-pick', 'am']),
|
|
35
|
+
SHORT_N_NO_VERIFY_SUBCOMMANDS: Object.freeze(['commit', 'push', 'merge', 'cherry-pick', 'am'])
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
function normalizePathForCompare(targetPath, fsModule = fs, platform = process.platform) {
|
|
39
|
+
let resolved = path.resolve(String(targetPath || ''));
|
|
40
|
+
try {
|
|
41
|
+
if (typeof fsModule.realpathSync === 'function' && fsModule.existsSync(resolved)) {
|
|
42
|
+
resolved = fsModule.realpathSync(resolved);
|
|
43
|
+
}
|
|
44
|
+
} catch (err) {
|
|
45
|
+
// Keep path.resolve result if realpathSync fails
|
|
46
|
+
recordHookDiagnostic('agy_git_guard', 'normalizePathForCompare.realpathSync', err, {
|
|
47
|
+
ignoreCodes: ['ENOENT'],
|
|
48
|
+
persist: false
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
const slashNorm = resolved.replace(/\\/g, '/').replace(/\/+$/, '');
|
|
52
|
+
return platform === 'win32' ? slashNorm.toLowerCase() : slashNorm;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Resolves the real system git binary while combining `PATH` + `Path` + `path` on Windows,
|
|
57
|
+
* filtering out shim directories/self-paths, and returning `null` (fail-closed) when missing.
|
|
58
|
+
*/
|
|
59
|
+
export function resolveRealGitBinary({
|
|
60
|
+
env = process.env,
|
|
61
|
+
platform = process.platform,
|
|
62
|
+
fsModule = fs,
|
|
63
|
+
shimFilePath = currentFilePath
|
|
64
|
+
} = {}) {
|
|
65
|
+
const pathSeparator = platform === 'win32' ? ';' : ':';
|
|
66
|
+
const rawSegments = [];
|
|
67
|
+
if (platform === 'win32') {
|
|
68
|
+
for (const key of ['PATH', 'Path', 'path']) {
|
|
69
|
+
if (typeof env[key] === 'string' && env[key].length > 0) {
|
|
70
|
+
rawSegments.push(...env[key].split(pathSeparator));
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
// Also inspect any remaining case-variant keys in custom env objects
|
|
74
|
+
for (const [k, v] of Object.entries(env || {})) {
|
|
75
|
+
if (k.toLowerCase() === 'path' && !['PATH', 'Path', 'path'].includes(k) && typeof v === 'string') {
|
|
76
|
+
rawSegments.push(...v.split(pathSeparator));
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
} else {
|
|
80
|
+
const posixPath = env.PATH || env.Path || '';
|
|
81
|
+
rawSegments.push(...posixPath.split(pathSeparator));
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const seenDirs = new Set();
|
|
85
|
+
const selfFileNorm = normalizePathForCompare(shimFilePath, fsModule, platform);
|
|
86
|
+
const selfDirNorm = normalizePathForCompare(path.dirname(shimFilePath), fsModule, platform);
|
|
87
|
+
|
|
88
|
+
const filteredDirs = [];
|
|
89
|
+
for (const rawDir of rawSegments) {
|
|
90
|
+
const trimmed = String(rawDir || '').trim().replace(/^"(.*)"$/, '$1');
|
|
91
|
+
if (!trimmed) continue;
|
|
92
|
+
const normLower = trimmed.replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase();
|
|
93
|
+
if (normLower.includes('.agents/shims') || normLower.endsWith('/shims')) {
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
const dirNorm = normalizePathForCompare(trimmed, fsModule, platform);
|
|
97
|
+
if (dirNorm === selfDirNorm || seenDirs.has(dirNorm)) {
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
seenDirs.add(dirNorm);
|
|
101
|
+
filteredDirs.push(trimmed);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const gitExeNames = platform === 'win32' ? ['git.exe', 'git.cmd'] : ['git'];
|
|
105
|
+
|
|
106
|
+
for (const dir of filteredDirs) {
|
|
107
|
+
for (const exe of gitExeNames) {
|
|
108
|
+
const candidate = path.join(dir, exe);
|
|
109
|
+
try {
|
|
110
|
+
if (fsModule.existsSync(candidate) && fsModule.statSync(candidate).isFile()) {
|
|
111
|
+
const candNorm = normalizePathForCompare(candidate, fsModule, platform);
|
|
112
|
+
if (candNorm === selfFileNorm || path.dirname(candNorm) === selfDirNorm) {
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
return candidate;
|
|
116
|
+
}
|
|
117
|
+
} catch (err) {
|
|
118
|
+
// Continue searching
|
|
119
|
+
recordHookDiagnostic('agy_git_guard', 'resolveRealGitBinary.pathProbe', err, {
|
|
120
|
+
ignoreCodes: ['ENOENT', 'ENOTDIR']
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// System fallbacks when PATH does not resolve
|
|
127
|
+
const fallbacks = platform === 'win32'
|
|
128
|
+
? [
|
|
129
|
+
'C:\\Program Files\\Git\\cmd\\git.exe',
|
|
130
|
+
'C:\\Program Files\\Git\\bin\\git.exe',
|
|
131
|
+
'C:\\Program Files (x86)\\Git\\cmd\\git.exe',
|
|
132
|
+
'C:\\Program Files (x86)\\Git\\bin\\git.exe'
|
|
133
|
+
]
|
|
134
|
+
: ['/usr/bin/git', '/usr/local/bin/git', '/opt/homebrew/bin/git'];
|
|
135
|
+
|
|
136
|
+
for (const candidate of fallbacks) {
|
|
137
|
+
try {
|
|
138
|
+
if (fsModule.existsSync(candidate) && fsModule.statSync(candidate).isFile()) {
|
|
139
|
+
const candNorm = normalizePathForCompare(candidate, fsModule, platform);
|
|
140
|
+
if (candNorm !== selfFileNorm && path.dirname(candNorm) !== selfDirNorm) {
|
|
141
|
+
return candidate;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
} catch (err) {
|
|
145
|
+
// Ignore inaccessible fallback
|
|
146
|
+
recordHookDiagnostic('agy_git_guard', 'resolveRealGitBinary.fallbackProbe', err, {
|
|
147
|
+
ignoreCodes: ['ENOENT', 'ENOTDIR']
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Fail closed: NEVER return bare 'git' (prevents infinite fork-bomb recursion)
|
|
153
|
+
return null;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function extractSecurityOptions(workspaceDirOrOptions, maybeOptions) {
|
|
157
|
+
if (workspaceDirOrOptions && typeof workspaceDirOrOptions === 'object') {
|
|
158
|
+
return workspaceDirOrOptions;
|
|
159
|
+
}
|
|
160
|
+
if (maybeOptions && typeof maybeOptions === 'object') {
|
|
161
|
+
return maybeOptions;
|
|
162
|
+
}
|
|
163
|
+
return {};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Returns the path to the user-private bypass nonce file outside the agent-writable workspace.
|
|
168
|
+
* Never reads `.agents/cache/git_bypass_nonce.json` from workspace CWD by default.
|
|
169
|
+
*/
|
|
170
|
+
export function getBypassNonceFilePath(options = {}) {
|
|
171
|
+
const opts = extractSecurityOptions(options);
|
|
172
|
+
if (opts.nonceFilePath && typeof opts.nonceFilePath === 'string') {
|
|
173
|
+
return path.resolve(opts.nonceFilePath);
|
|
174
|
+
}
|
|
175
|
+
return path.join(os.homedir(), '.attention-horizon', 'security', 'git_bypass_nonce.json');
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Returns the path to the `0o600` HMAC secret key file used to authenticate bypass nonces.
|
|
180
|
+
*/
|
|
181
|
+
export function getBypassHmacKeyPath(options = {}) {
|
|
182
|
+
const opts = extractSecurityOptions(options);
|
|
183
|
+
if (opts.secretKeyPath && typeof opts.secretKeyPath === 'string') {
|
|
184
|
+
return path.resolve(opts.secretKeyPath);
|
|
185
|
+
}
|
|
186
|
+
return path.join(os.homedir(), '.attention-horizon', 'security', 'git_bypass_hmac.key');
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function getOrCreateBypassHmacSecret(options = {}) {
|
|
190
|
+
const keyPath = getBypassHmacKeyPath(options);
|
|
191
|
+
if (fs.existsSync(keyPath)) {
|
|
192
|
+
const existing = fs.readFileSync(keyPath, 'utf8').trim();
|
|
193
|
+
if (existing.length >= 32) {
|
|
194
|
+
return existing;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
const secret = crypto.randomBytes(32).toString('hex');
|
|
198
|
+
atomicWriteFileSync(keyPath, `${secret}\n`, {
|
|
199
|
+
encoding: 'utf8',
|
|
200
|
+
mode: 0o600,
|
|
201
|
+
dirMode: 0o700
|
|
202
|
+
});
|
|
203
|
+
try {
|
|
204
|
+
fs.chmodSync(keyPath, 0o600);
|
|
205
|
+
} catch (err) {
|
|
206
|
+
recordHookDiagnostic('agy_git_guard', 'getOrCreateBypassHmacSecret.chmod', err, {
|
|
207
|
+
ignoreCodes: ['ENOSYS', 'EINVAL'],
|
|
208
|
+
persist: false
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
return secret;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export function signBypassNoncePayload(secret, { nonce, createdAtMs, expiresAtMs }) {
|
|
215
|
+
return crypto
|
|
216
|
+
.createHmac('sha256', String(secret))
|
|
217
|
+
.update(`${nonce}:${createdAtMs}:${expiresAtMs}`, 'utf8')
|
|
218
|
+
.digest('hex');
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Returns the path to the security events log.
|
|
223
|
+
*/
|
|
224
|
+
export function getSecurityEventsFilePath(workspaceDir = process.cwd()) {
|
|
225
|
+
return path.join(workspaceDir, '.agents', 'cache', 'security_events.jsonl');
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Generates an HMAC-SHA256 signed one-time cryptographic bypass nonce with a 60-second TTL.
|
|
230
|
+
*/
|
|
231
|
+
export function generateGitBypassNonce(
|
|
232
|
+
workspaceDirOrOptions = {},
|
|
233
|
+
ttlMs = DET19_CONSTANTS.BYPASS_NONCE_TTL_MS,
|
|
234
|
+
maybeOptions = {}
|
|
235
|
+
) {
|
|
236
|
+
const opts = extractSecurityOptions(workspaceDirOrOptions, maybeOptions);
|
|
237
|
+
const effectiveTtlMs = typeof workspaceDirOrOptions === 'object' && typeof workspaceDirOrOptions?.ttlMs === 'number'
|
|
238
|
+
? workspaceDirOrOptions.ttlMs
|
|
239
|
+
: ttlMs;
|
|
240
|
+
|
|
241
|
+
const secret = getOrCreateBypassHmacSecret(opts);
|
|
242
|
+
const nonce = crypto.randomBytes(16).toString('hex');
|
|
243
|
+
const now = Date.now();
|
|
244
|
+
const createdAtMs = now;
|
|
245
|
+
const expiresAtMs = now + effectiveTtlMs;
|
|
246
|
+
const signature = signBypassNoncePayload(secret, { nonce, createdAtMs, expiresAtMs });
|
|
247
|
+
|
|
248
|
+
const payload = {
|
|
249
|
+
nonce,
|
|
250
|
+
createdAtMs,
|
|
251
|
+
expiresAtMs,
|
|
252
|
+
createdAtIso: new Date(now).toISOString(),
|
|
253
|
+
signature
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
const noncePath = getBypassNonceFilePath(opts);
|
|
257
|
+
atomicWriteFileSync(noncePath, JSON.stringify(payload, null, 2) + '\n', {
|
|
258
|
+
encoding: 'utf8',
|
|
259
|
+
mode: 0o600,
|
|
260
|
+
dirMode: 0o700
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
return payload;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* Consumes the one-time bypass nonce if present, validly HMAC-signed, and unexpired.
|
|
268
|
+
* Immediately unlinks the file to prevent replay attacks.
|
|
269
|
+
*/
|
|
270
|
+
export function consumeGitBypassNonce(workspaceDirOrOptions = {}, maybeOptions = {}) {
|
|
271
|
+
const opts = extractSecurityOptions(workspaceDirOrOptions, maybeOptions);
|
|
272
|
+
const noncePath = getBypassNonceFilePath(opts);
|
|
273
|
+
if (!fs.existsSync(noncePath)) {
|
|
274
|
+
return { allowed: false, reason: 'NO_NONCE' };
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
try {
|
|
278
|
+
const raw = fs.readFileSync(noncePath, 'utf8');
|
|
279
|
+
// Invalidate immediately regardless of validity to prevent replay
|
|
280
|
+
try {
|
|
281
|
+
fs.unlinkSync(noncePath);
|
|
282
|
+
} catch (unlinkErr) {
|
|
283
|
+
recordHookDiagnostic('agy_git_guard', 'consumeGitBypassNonce.unlink', unlinkErr, {
|
|
284
|
+
ignoreCodes: ['ENOENT']
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
const data = JSON.parse(raw);
|
|
289
|
+
const keyPath = getBypassHmacKeyPath(opts);
|
|
290
|
+
if (
|
|
291
|
+
!data ||
|
|
292
|
+
typeof data.nonce !== 'string' ||
|
|
293
|
+
!data.nonce ||
|
|
294
|
+
typeof data.createdAtMs !== 'number' ||
|
|
295
|
+
typeof data.expiresAtMs !== 'number' ||
|
|
296
|
+
typeof data.signature !== 'string' ||
|
|
297
|
+
!/^[0-9a-f]{64}$/i.test(data.signature) ||
|
|
298
|
+
!fs.existsSync(keyPath)
|
|
299
|
+
) {
|
|
300
|
+
return { allowed: false, reason: 'INVALID_SIGNATURE' };
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
const secret = fs.readFileSync(keyPath, 'utf8').trim();
|
|
304
|
+
if (!secret) {
|
|
305
|
+
return { allowed: false, reason: 'INVALID_SIGNATURE' };
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
const expectedHex = signBypassNoncePayload(secret, {
|
|
309
|
+
nonce: data.nonce,
|
|
310
|
+
createdAtMs: data.createdAtMs,
|
|
311
|
+
expiresAtMs: data.expiresAtMs
|
|
312
|
+
});
|
|
313
|
+
const actualBuf = Buffer.from(data.signature, 'hex');
|
|
314
|
+
const expectedBuf = Buffer.from(expectedHex, 'hex');
|
|
315
|
+
if (actualBuf.length !== 32 || expectedBuf.length !== 32 || !crypto.timingSafeEqual(actualBuf, expectedBuf)) {
|
|
316
|
+
return { allowed: false, reason: 'INVALID_SIGNATURE' };
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
const now = Date.now();
|
|
320
|
+
if (now <= data.expiresAtMs) {
|
|
321
|
+
return { allowed: true, nonce: data.nonce };
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
return { allowed: false, reason: 'EXPIRED_NONCE' };
|
|
325
|
+
} catch (err) {
|
|
326
|
+
recordHookDiagnostic('agy_git_guard', 'consumeGitBypassNonce', err);
|
|
327
|
+
try {
|
|
328
|
+
if (fs.existsSync(noncePath)) fs.unlinkSync(noncePath);
|
|
329
|
+
} catch (cleanupErr) {
|
|
330
|
+
recordHookDiagnostic('agy_git_guard', 'consumeGitBypassNonce.cleanupUnlink', cleanupErr, {
|
|
331
|
+
ignoreCodes: ['ENOENT']
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
return { allowed: false, reason: 'INVALID_NONCE' };
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* Records a security event in `.agents/cache/security_events.jsonl`.
|
|
340
|
+
*/
|
|
341
|
+
export function recordSecurityEvent(workspaceDir = process.cwd(), eventPayload = {}) {
|
|
342
|
+
try {
|
|
343
|
+
const eventsPath = getSecurityEventsFilePath(workspaceDir);
|
|
344
|
+
fs.mkdirSync(path.dirname(eventsPath), { recursive: true });
|
|
345
|
+
const line = JSON.stringify({
|
|
346
|
+
timestamp: new Date().toISOString(),
|
|
347
|
+
...eventPayload
|
|
348
|
+
}) + '\n';
|
|
349
|
+
fs.appendFileSync(eventsPath, line, 'utf8');
|
|
350
|
+
} catch (err) {
|
|
351
|
+
// Non-fatal telemetry failure
|
|
352
|
+
recordHookDiagnostic('agy_git_guard', 'recordSecurityEvent', err);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
function hasHooksPathEnvOverride(env = {}) {
|
|
357
|
+
if (!env || typeof env !== 'object') return null;
|
|
358
|
+
|
|
359
|
+
if (String(env.HUSKY || '') === '0' || String(env.GIT_HOOKS || '') === '0') {
|
|
360
|
+
return 'HUSKY=0 / GIT_HOOKS=0';
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
const huskySkip = String(env.HUSKY_SKIP_HOOKS ?? '').trim().toLowerCase();
|
|
364
|
+
if (huskySkip && huskySkip !== '0' && huskySkip !== 'false') {
|
|
365
|
+
return `HUSKY_SKIP_HOOKS=${env.HUSKY_SKIP_HOOKS}`;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
if (typeof env.GIT_CONFIG_PARAMETERS === 'string' && /core\.hooksPath/i.test(env.GIT_CONFIG_PARAMETERS)) {
|
|
369
|
+
return 'GIT_CONFIG_PARAMETERS=core.hooksPath';
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
const count = parseInt(String(env.GIT_CONFIG_COUNT ?? '0'), 10);
|
|
373
|
+
if (Number.isFinite(count) && count > 0) {
|
|
374
|
+
for (let idx = 0; idx < Math.min(count, 64); idx++) {
|
|
375
|
+
const kVal = String(env[`GIT_CONFIG_KEY_${idx}`] || '').trim();
|
|
376
|
+
if (/^core\.hooksPath$/i.test(kVal)) {
|
|
377
|
+
return `GIT_CONFIG_KEY_${idx}=${kVal}`;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
for (const [k, v] of Object.entries(env)) {
|
|
383
|
+
if (/^GIT_CONFIG_KEY_\d+$/i.test(k) && /^core\.hooksPath$/i.test(String(v || '').trim())) {
|
|
384
|
+
return `${k}=${v}`;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
return null;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* Inspects raw git CLI arguments and environment for DET-19 evasion patterns.
|
|
393
|
+
*/
|
|
394
|
+
export function inspectGitArgs(rawArgs = [], env = process.env) {
|
|
395
|
+
// 1. Check hook-disabling environment variables
|
|
396
|
+
const envViolation = hasHooksPathEnvOverride(env);
|
|
397
|
+
if (envViolation) {
|
|
398
|
+
return {
|
|
399
|
+
blocked: true,
|
|
400
|
+
detectorId: DET19_CONSTANTS.DETECTOR_ID,
|
|
401
|
+
reason: `Hook-disabling environment variable detected (${envViolation})`,
|
|
402
|
+
subcommand: null,
|
|
403
|
+
flags: [envViolation]
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
// 2. Parse global flags vs subcommand
|
|
408
|
+
let subcommand = null;
|
|
409
|
+
let subcommandIdx = -1;
|
|
410
|
+
const globalFlags = [];
|
|
411
|
+
const subcommandArgs = [];
|
|
412
|
+
|
|
413
|
+
let i = 0;
|
|
414
|
+
while (i < rawArgs.length) {
|
|
415
|
+
const arg = String(rawArgs[i] ?? '');
|
|
416
|
+
if (arg === '--') {
|
|
417
|
+
i++;
|
|
418
|
+
continue;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
if (subcommand === null) {
|
|
422
|
+
if (arg.startsWith('-')) {
|
|
423
|
+
globalFlags.push(arg);
|
|
424
|
+
if (
|
|
425
|
+
arg === '-c' ||
|
|
426
|
+
arg === '-C' ||
|
|
427
|
+
arg === '--git-dir' ||
|
|
428
|
+
arg === '--work-tree' ||
|
|
429
|
+
arg === '--namespace' ||
|
|
430
|
+
arg === '--config-env'
|
|
431
|
+
) {
|
|
432
|
+
if (i + 1 < rawArgs.length) {
|
|
433
|
+
globalFlags.push(String(rawArgs[i + 1] ?? ''));
|
|
434
|
+
i++;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
} else {
|
|
438
|
+
subcommand = arg.toLowerCase();
|
|
439
|
+
subcommandIdx = i;
|
|
440
|
+
i++;
|
|
441
|
+
break;
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
i++;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
if (subcommandIdx !== -1) {
|
|
448
|
+
for (; i < rawArgs.length; i++) {
|
|
449
|
+
subcommandArgs.push(String(rawArgs[i] ?? ''));
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// 3. Inspect global flags for core.hooksPath overrides (both `-c core.hooksPath=...` and attached `-ccore.hooksPath=...`)
|
|
454
|
+
for (let j = 0; j < globalFlags.length; j++) {
|
|
455
|
+
const gf = globalFlags[j];
|
|
456
|
+
if (gf === '-c' || gf === '--config-env') {
|
|
457
|
+
const nextVal = globalFlags[j + 1] || '';
|
|
458
|
+
if (/^core\.hooksPath(?:\s*=|$)/i.test(nextVal)) {
|
|
459
|
+
return {
|
|
460
|
+
blocked: true,
|
|
461
|
+
detectorId: DET19_CONSTANTS.DETECTOR_ID,
|
|
462
|
+
subcommand,
|
|
463
|
+
flags: [gf, nextVal],
|
|
464
|
+
reason: 'Global config override core.hooksPath is prohibited.'
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
} else if (/^-c\s*core\.hooksPath(?:\s*=|$)/i.test(gf) || /^--config-env=core\.hooksPath(?:\s*=|$)/i.test(gf)) {
|
|
468
|
+
return {
|
|
469
|
+
blocked: true,
|
|
470
|
+
detectorId: DET19_CONSTANTS.DETECTOR_ID,
|
|
471
|
+
subcommand,
|
|
472
|
+
flags: [gf],
|
|
473
|
+
reason: 'Global config override core.hooksPath is prohibited.'
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
if (!subcommand) {
|
|
479
|
+
return { blocked: false, subcommand: null, flags: [] };
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
// 3b. Block mutating `git config ... core.hooksPath ...` while allowing read-only `--get` / `--list`
|
|
483
|
+
if (subcommand === 'config') {
|
|
484
|
+
const isReadOnlyQuery = subcommandArgs.some((a) =>
|
|
485
|
+
/^(--get|--get-all|--get-regexp|--get-urlmatch|--list|-l)$/i.test(String(a || ''))
|
|
486
|
+
);
|
|
487
|
+
if (!isReadOnlyQuery) {
|
|
488
|
+
const positionalConfigArgs = [];
|
|
489
|
+
for (let i = 0; i < subcommandArgs.length; i++) {
|
|
490
|
+
const sArg = String(subcommandArgs[i] ?? '');
|
|
491
|
+
if (sArg === '--') {
|
|
492
|
+
positionalConfigArgs.push(...subcommandArgs.slice(i + 1).map((x) => String(x ?? '')));
|
|
493
|
+
break;
|
|
494
|
+
}
|
|
495
|
+
if (sArg === '-f' || sArg === '--file' || sArg === '--blob') {
|
|
496
|
+
i++;
|
|
497
|
+
continue;
|
|
498
|
+
}
|
|
499
|
+
if (/^(--unset|--unset-all|--replace-all|--add)$/i.test(sArg)) {
|
|
500
|
+
const targetKey = String(subcommandArgs[i + 1] ?? '');
|
|
501
|
+
if (/^core\.hooksPath$/i.test(targetKey)) {
|
|
502
|
+
return {
|
|
503
|
+
blocked: true,
|
|
504
|
+
detectorId: DET19_CONSTANTS.DETECTOR_ID,
|
|
505
|
+
subcommand,
|
|
506
|
+
flags: [sArg, targetKey],
|
|
507
|
+
reason: 'Modifying git config core.hooksPath is prohibited.'
|
|
508
|
+
};
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
if (!sArg.startsWith('-')) {
|
|
512
|
+
positionalConfigArgs.push(sArg);
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
// `git config core.hooksPath <value>` has >= 2 positional args (or `core.hooksPath=...`)
|
|
516
|
+
for (let p = 0; p < positionalConfigArgs.length; p++) {
|
|
517
|
+
const pos = positionalConfigArgs[p];
|
|
518
|
+
if (/^core\.hooksPath=/i.test(pos) || (/^core\.hooksPath$/i.test(pos) && positionalConfigArgs.length >= p + 2)) {
|
|
519
|
+
return {
|
|
520
|
+
blocked: true,
|
|
521
|
+
detectorId: DET19_CONSTANTS.DETECTOR_ID,
|
|
522
|
+
subcommand,
|
|
523
|
+
flags: [pos],
|
|
524
|
+
reason: 'Modifying git config core.hooksPath is prohibited.'
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
return { blocked: false, subcommand, flags: [] };
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
// 4. Subcommand-specific bypass detection with strict left-to-right short-flag parsing
|
|
533
|
+
const blockedFlags = [];
|
|
534
|
+
const VALUE_TAKING_LONG_FLAGS = new Set([
|
|
535
|
+
'--message',
|
|
536
|
+
'--file',
|
|
537
|
+
'--author',
|
|
538
|
+
'--date',
|
|
539
|
+
'--template',
|
|
540
|
+
'--cleanup',
|
|
541
|
+
'--reuse-message',
|
|
542
|
+
'--reedit-message',
|
|
543
|
+
'--fixup',
|
|
544
|
+
'--squash',
|
|
545
|
+
'--trailer',
|
|
546
|
+
'--pathspec-from-file',
|
|
547
|
+
'--strategy',
|
|
548
|
+
'--strategy-option',
|
|
549
|
+
'--exec',
|
|
550
|
+
'--onto'
|
|
551
|
+
]);
|
|
552
|
+
const VALUE_TAKING_SHORT_CHARS = new Set(['m', 'F', 'C', 'c', 't', 'u']);
|
|
553
|
+
const shortNMeansNoVerify = DET19_CONSTANTS.SHORT_N_NO_VERIFY_SUBCOMMANDS.includes(subcommand);
|
|
554
|
+
|
|
555
|
+
if (DET19_CONSTANTS.PROTECTED_SUBCOMMANDS.includes(subcommand)) {
|
|
556
|
+
for (let k = 0; k < subcommandArgs.length; k++) {
|
|
557
|
+
const sArg = String(subcommandArgs[k] ?? '');
|
|
558
|
+
if (sArg === '--') break;
|
|
559
|
+
|
|
560
|
+
if (sArg === '--no-verify') {
|
|
561
|
+
blockedFlags.push(sArg);
|
|
562
|
+
continue;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
if (subcommand === 'commit' && sArg === '--no-gpg-sign') {
|
|
566
|
+
blockedFlags.push(sArg);
|
|
567
|
+
continue;
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
if (/^-c\s*core\.hooksPath(?:\s*=|$)/i.test(sArg)) {
|
|
571
|
+
blockedFlags.push(sArg);
|
|
572
|
+
continue;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
if (VALUE_TAKING_LONG_FLAGS.has(sArg)) {
|
|
576
|
+
// Skip the next token because it is the value for this long option (e.g. --message "-next")
|
|
577
|
+
k++;
|
|
578
|
+
continue;
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
if (/^-[^-].*$/.test(sArg)) {
|
|
582
|
+
const cluster = sArg.slice(1);
|
|
583
|
+
for (let idx = 0; idx < cluster.length; idx++) {
|
|
584
|
+
const ch = cluster[idx];
|
|
585
|
+
|
|
586
|
+
if (ch === 'n' && shortNMeansNoVerify) {
|
|
587
|
+
blockedFlags.push(sArg);
|
|
588
|
+
continue;
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
if (VALUE_TAKING_SHORT_CHARS.has(ch)) {
|
|
592
|
+
if (idx < cluster.length - 1) {
|
|
593
|
+
const attachedVal = cluster.slice(idx + 1);
|
|
594
|
+
if (ch === 'c' && /^core\.hooksPath(?:\s*=|$)/i.test(attachedVal)) {
|
|
595
|
+
blockedFlags.push(sArg);
|
|
596
|
+
break;
|
|
597
|
+
}
|
|
598
|
+
// Special case: grouped flags like `-amn "fix"` where boolean flag(s) precede `m`,
|
|
599
|
+
// the remainder is solely `n`, and a separate non-flag message token immediately follows.
|
|
600
|
+
if (
|
|
601
|
+
subcommand === 'commit' &&
|
|
602
|
+
idx > 0 &&
|
|
603
|
+
attachedVal === 'n' &&
|
|
604
|
+
k + 1 < subcommandArgs.length &&
|
|
605
|
+
!String(subcommandArgs[k + 1] ?? '').startsWith('-')
|
|
606
|
+
) {
|
|
607
|
+
blockedFlags.push(sArg);
|
|
608
|
+
k++;
|
|
609
|
+
break;
|
|
610
|
+
}
|
|
611
|
+
// Otherwise remainder is this option's attached argument (e.g. `-mnotes`, `-mfoo`, `-uno`):
|
|
612
|
+
// stop scanning cluster without checking remaining chars for `n` and WITHOUT incrementing `k`!
|
|
613
|
+
break;
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
// `idx === cluster.length - 1`: option is at the end of the cluster
|
|
617
|
+
if (ch === 'c' && k + 1 < subcommandArgs.length) {
|
|
618
|
+
const nextVal = String(subcommandArgs[k + 1] ?? '');
|
|
619
|
+
if (/^core\.hooksPath(?:\s*=|$)/i.test(nextVal)) {
|
|
620
|
+
blockedFlags.push(`${sArg} ${nextVal}`);
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
if (ch === 'u') {
|
|
624
|
+
// In `git commit` (`-u[<mode>]`) and `git push` (`-u`), standalone `-u` does not consume a following flag token.
|
|
625
|
+
break;
|
|
626
|
+
}
|
|
627
|
+
k++;
|
|
628
|
+
break;
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
if (blockedFlags.length > 0) {
|
|
636
|
+
return {
|
|
637
|
+
blocked: true,
|
|
638
|
+
detectorId: DET19_CONSTANTS.DETECTOR_ID,
|
|
639
|
+
subcommand,
|
|
640
|
+
flags: blockedFlags,
|
|
641
|
+
reason: `Pre-commit / verification bypass flags (${blockedFlags.join(', ')}) are prohibited for "git ${subcommand}".`
|
|
642
|
+
};
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
return { blocked: false, subcommand, flags: [] };
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
/**
|
|
649
|
+
* Runs the Git Guard engine for a CLI or process invocation.
|
|
650
|
+
*/
|
|
651
|
+
export function runGitGuard({
|
|
652
|
+
args = process.argv.slice(2),
|
|
653
|
+
env = process.env,
|
|
654
|
+
cwd = process.cwd(),
|
|
655
|
+
realGitBinary = null,
|
|
656
|
+
spawnFn = spawnSync,
|
|
657
|
+
stderr = process.stderr,
|
|
658
|
+
nonceFilePath = null,
|
|
659
|
+
secretKeyPath = null,
|
|
660
|
+
fsModule = fs,
|
|
661
|
+
platform = process.platform
|
|
662
|
+
} = {}) {
|
|
663
|
+
const inspection = inspectGitArgs(args, env);
|
|
664
|
+
const nonceOpts = {};
|
|
665
|
+
if (nonceFilePath) nonceOpts.nonceFilePath = nonceFilePath;
|
|
666
|
+
if (secretKeyPath) nonceOpts.secretKeyPath = secretKeyPath;
|
|
667
|
+
|
|
668
|
+
if (inspection.blocked) {
|
|
669
|
+
// Check for valid single-use HMAC-signed human cryptographic nonce outside workspace
|
|
670
|
+
const nonceResult = consumeGitBypassNonce(nonceOpts);
|
|
671
|
+
if (nonceResult.allowed) {
|
|
672
|
+
recordSecurityEvent(cwd, {
|
|
673
|
+
event: 'DET-19_HOOK_BYPASS_AUTHORIZED_BY_NONCE',
|
|
674
|
+
detectorId: DET19_CONSTANTS.DETECTOR_ID,
|
|
675
|
+
subcommand: inspection.subcommand,
|
|
676
|
+
flags: inspection.flags,
|
|
677
|
+
cwd,
|
|
678
|
+
nonce: nonceResult.nonce,
|
|
679
|
+
blocked: false
|
|
680
|
+
});
|
|
681
|
+
} else {
|
|
682
|
+
if (stderr && typeof stderr.write === 'function') {
|
|
683
|
+
stderr.write(`${DET19_CONSTANTS.BLOCKED_MESSAGE}\n`);
|
|
684
|
+
}
|
|
685
|
+
recordSecurityEvent(cwd, {
|
|
686
|
+
event: 'DET-19_HOOK_BYPASS_ATTEMPT',
|
|
687
|
+
detectorId: DET19_CONSTANTS.DETECTOR_ID,
|
|
688
|
+
subcommand: inspection.subcommand,
|
|
689
|
+
flags: inspection.flags,
|
|
690
|
+
cwd,
|
|
691
|
+
blocked: true,
|
|
692
|
+
reason: inspection.reason
|
|
693
|
+
});
|
|
694
|
+
|
|
695
|
+
return {
|
|
696
|
+
blocked: true,
|
|
697
|
+
exitCode: DET19_CONSTANTS.EXIT_CODE_BLOCKED,
|
|
698
|
+
reason: inspection.reason,
|
|
699
|
+
inspection
|
|
700
|
+
};
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
// Resolve real git binary; fail closed with exit code 127 if unavailable
|
|
705
|
+
const binary = realGitBinary || resolveRealGitBinary({ env, platform, fsModule });
|
|
706
|
+
if (!binary) {
|
|
707
|
+
const msg = '[HORIZON DET-19 ERROR] Real git binary could not be resolved outside shim directories.\n';
|
|
708
|
+
if (stderr && typeof stderr.write === 'function') {
|
|
709
|
+
stderr.write(msg);
|
|
710
|
+
}
|
|
711
|
+
return {
|
|
712
|
+
blocked: true,
|
|
713
|
+
exitCode: DET19_CONSTANTS.EXIT_CODE_GIT_NOT_FOUND,
|
|
714
|
+
reason: 'Real git binary not found in PATH'
|
|
715
|
+
};
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
const child = spawnFn(binary, args, {
|
|
719
|
+
cwd,
|
|
720
|
+
env,
|
|
721
|
+
stdio: 'inherit'
|
|
722
|
+
});
|
|
723
|
+
|
|
724
|
+
return {
|
|
725
|
+
blocked: false,
|
|
726
|
+
exitCode: child.status ?? 0
|
|
727
|
+
};
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
// CLI Direct Invocation
|
|
731
|
+
const invokedFilePath = process.argv[1] ? path.resolve(process.argv[1]) : '';
|
|
732
|
+
if (invokedFilePath && path.resolve(currentFilePath) === invokedFilePath) {
|
|
733
|
+
const result = runGitGuard();
|
|
734
|
+
process.exit(result.exitCode);
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
export default {
|
|
738
|
+
DET19_CONSTANTS,
|
|
739
|
+
resolveRealGitBinary,
|
|
740
|
+
getBypassNonceFilePath,
|
|
741
|
+
getBypassHmacKeyPath,
|
|
742
|
+
signBypassNoncePayload,
|
|
743
|
+
getSecurityEventsFilePath,
|
|
744
|
+
generateGitBypassNonce,
|
|
745
|
+
consumeGitBypassNonce,
|
|
746
|
+
recordSecurityEvent,
|
|
747
|
+
inspectGitArgs,
|
|
748
|
+
runGitGuard
|
|
749
|
+
};
|