@goodandready/dsh-approval-gate 0.1.21 → 0.1.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,151 @@
1
+ // lib/escalation.js
2
+ // Redundant sandbox recovery (#101) and privilege escalation justification (#107).
3
+ // Prevents unnecessary danger-full-access requests and enforces accountable escalation justifications.
4
+
5
+ import { isSystemLevelExecution } from "./measure-kinds.js";
6
+
7
+ export const REDUNDANT_SANDBOX_REASON = "redundant-sandbox-privilege";
8
+ export const MISSING_JUSTIFICATION_REASON = "missing-escalation-justification";
9
+ export const INSUFFICIENT_JUSTIFICATION_REASON = "insufficient-escalation-justification";
10
+
11
+ const PLACEHOLDER_JUSTIFICATIONS = new Set([
12
+ "none",
13
+ "n/a",
14
+ "na",
15
+ "test",
16
+ "testing",
17
+ "sudo",
18
+ "fix",
19
+ "run",
20
+ "escalate",
21
+ "please",
22
+ "bypass",
23
+ "temp",
24
+ ]);
25
+
26
+ const INTERNAL_SAFE_COMMAND_REGEX = /^(?:git\s+(?:status|diff|log|branch|show)|npm\s+(?:test|run\s+test|run\s+lint)|pnpm\s+(?:test|run\s+test)|node\s+[\w\-./]+\.m?[jt]s|cat\s+|head\s+|tail\s+|grep\s+|find\s+|ls\b|pwd\b|echo\b)/i;
27
+
28
+ /**
29
+ * Checks whether an elevated sandbox request is redundant for a safe internal command (#101).
30
+ *
31
+ * @param {string} [command]
32
+ * @param {string} [requestedMode]
33
+ * @param {{ toolName?: string, args?: any }} [options]
34
+ * @returns {boolean}
35
+ */
36
+ export function isRedundantSandboxRequest(command, requestedMode, options = {}) {
37
+ const mode = String(requestedMode || options.sandboxMode || "").toLowerCase();
38
+ const isElevated = mode === "danger-full-access" || mode === "full-access" || mode === "danger" || mode === "unrestricted";
39
+ if (!isElevated) return false;
40
+
41
+ const cmd = String(command || "").trim();
42
+ if (!cmd) return false;
43
+
44
+ // If command is system-level, escalation might be genuine (not redundant)
45
+ if (isSystemLevelExecution(cmd, options.toolName, options.args)) {
46
+ return false;
47
+ }
48
+
49
+ // If command contains explicit dangerous tokens, it's not a redundant request
50
+ if (/\b(?:sudo|docker|systemctl|service|apt|apt-get|apk|dnf|pacman|chown|chmod\s+-R)\b/i.test(cmd)) {
51
+ return false;
52
+ }
53
+
54
+ // Safe internal commands: reading, status, unit testing
55
+ return INTERNAL_SAFE_COMMAND_REGEX.test(cmd);
56
+ }
57
+
58
+ /**
59
+ * Builds actionable remediation advice for redundant sandbox requests (#101).
60
+ *
61
+ * @param {string} command
62
+ * @param {"en" | "ru" | "zh"} [lang="en"]
63
+ * @returns {string}
64
+ */
65
+ export function buildRedundantSandboxRemediation(command, lang = "en") {
66
+ const cmd = String(command || "").trim();
67
+ if (lang === "ru") {
68
+ return `Избыточный запрос привилегий песочницы: команда '${cmd}' является безопасной внутрипроектной операцией. Повторите вызов в стандартном режиме песочницы без 'danger-full-access'.`;
69
+ }
70
+ if (lang === "zh") {
71
+ return `请求了冗余的沙箱提权:命令 '${cmd}' 为工作区内部安全操作。请以普通沙箱模式重新执行,无需 'danger-full-access'。`;
72
+ }
73
+ return `Redundant sandbox elevation requested: command '${cmd}' is workspace-internal and safe. Repeat the command in standard sandbox mode without 'danger-full-access'.`;
74
+ }
75
+
76
+ /**
77
+ * Checks whether privilege escalation requires justification and whether provided justification is valid (#107).
78
+ *
79
+ * @param {string} [command]
80
+ * @param {string} [toolName]
81
+ * @param {any} [args]
82
+ * @param {{
83
+ * justification?: string,
84
+ * context?: any,
85
+ * requireJustification?: boolean,
86
+ * lang?: "en" | "ru" | "zh"
87
+ * }} [options]
88
+ * @returns {{
89
+ * required: boolean,
90
+ * valid: boolean,
91
+ * reason?: string,
92
+ * detail?: string,
93
+ * advice?: string
94
+ * }}
95
+ */
96
+ export function checkEscalationJustification(command, toolName, args, options = {}) {
97
+ const cmd = String(command || "").trim();
98
+ const execObj = { name: toolName || "bash", arguments: { ...(args || {}), command: cmd } };
99
+ const isSystem = isSystemLevelExecution(execObj, options.context);
100
+ const explicitRequire = options.requireJustification === true || options.context?.requireJustification === true;
101
+ const isEscalatedSandbox = Boolean(options.context?.sandboxMode && options.context.sandboxMode !== "sandboxed");
102
+
103
+ // Escalation justification is required when explicitly required OR when escalated sandbox mode is requested for system operations
104
+ const escalationRequired = explicitRequire || (isEscalatedSandbox && isSystem);
105
+ if (!escalationRequired) {
106
+ return { required: false, valid: true };
107
+ }
108
+
109
+ const rawJustification =
110
+ (typeof options.justification === "string" && options.justification) ||
111
+ (typeof args?.justification === "string" && args.justification) ||
112
+ (typeof options.context?.justification === "string" && options.context.justification) ||
113
+ "";
114
+
115
+ const justification = rawJustification.trim();
116
+ const lang = options.lang || "en";
117
+
118
+ if (!justification) {
119
+ return {
120
+ required: true,
121
+ valid: false,
122
+ reason: MISSING_JUSTIFICATION_REASON,
123
+ detail: `Privilege escalation for '${cmd || toolName}' requires an explicit justification.`,
124
+ advice: lang === "ru"
125
+ ? "Укажите поле 'justification' с объяснением необходимости системных привилегий."
126
+ : lang === "zh"
127
+ ? "执行系统级操作必须提供 'justification' 理由说明。"
128
+ : "Provide a 'justification' field explaining why elevated privileges are necessary.",
129
+ };
130
+ }
131
+
132
+ if (justification.length < 10 || PLACEHOLDER_JUSTIFICATIONS.has(justification.toLowerCase())) {
133
+ return {
134
+ required: true,
135
+ valid: false,
136
+ reason: INSUFFICIENT_JUSTIFICATION_REASON,
137
+ detail: `Justification '${justification}' is too short or generic (minimum 10 non-placeholder characters required).`,
138
+ advice: lang === "ru"
139
+ ? "Обоснование слишком короткое или шаблонное. Опишите конкретную причину эскалации."
140
+ : lang === "zh"
141
+ ? "理由说明过短或为占位符。请详细描述提权的实际原因(至少10个字符)。"
142
+ : "Justification is too brief or placeholder. Describe the specific reason for privilege escalation.",
143
+ };
144
+ }
145
+
146
+ return {
147
+ required: true,
148
+ valid: true,
149
+ justification,
150
+ };
151
+ }
@@ -0,0 +1,119 @@
1
+ // lib/guidance.js
2
+ // Dynamic security guidance for system prompts (AUTO_MODE_AGENT_GUIDANCE) (#99).
3
+ // Injects structured execution expectations and gate constraints directly into agent context.
4
+
5
+ export const GUIDANCE_MARKER = "<!-- dsh-approval-gate:guidance -->";
6
+
7
+ /**
8
+ * Generates structured agent safety guidance.
9
+ *
10
+ * @param {{
11
+ * language?: "en" | "ru" | "zh",
12
+ * failClosed?: boolean,
13
+ * trashEnabled?: boolean,
14
+ * snapshotsEnabled?: boolean,
15
+ * justificationRequired?: boolean,
16
+ * redundantSandboxRecovery?: boolean,
17
+ * workspaceDir?: string
18
+ * }} [options]
19
+ * @returns {string}
20
+ */
21
+ export function generateAgentGuidance(options = {}) {
22
+ const lang = options.language || "en";
23
+ const failClosed = options.failClosed !== false;
24
+ const trash = options.trashEnabled !== false;
25
+ const snapshots = options.snapshotsEnabled !== false;
26
+ const justification = options.justificationRequired !== false;
27
+
28
+ if (lang === "ru") {
29
+ return [
30
+ GUIDANCE_MARKER,
31
+ "### Инструкции безопасности среды выполнения (dsh-approval-gate)",
32
+ failClosed
33
+ ? "- **Режим выполнения**: Включен строгий контроль (fail-closed). Нераспознанные шелл-команды требуют ручного подтверждения."
34
+ : "- **Режим выполнения**: Стандартный контроль команд.",
35
+ snapshots
36
+ ? "- **Снимки файлов**: Перед изменением файлов автоматически создаются pre-execution снимки. Избегайте слепой перезаписи."
37
+ : "",
38
+ trash
39
+ ? "- **Удаление файлов**: Запрещено безусловное `rm -rf`. Используйте перемещение в сессионную корзину `.dsh/trash/<session>/` или очистку сессионных артефактов."
40
+ : "- **Удаление файлов**: Удаляйте файлы строго в границах текущего рабочего каталога.",
41
+ "- **Песочница**: Не запрашивайте `danger-full-access` или выход из песочницы для стандартных задач внутри проекта.",
42
+ justification
43
+ ? "- **Эскалация привилегий**: Любая системная операция (apt, systemctl, сетевые вызовы) требует обязательного поля `justification` с обоснованием."
44
+ : "",
45
+ "- **Безопасные команды**: Чтение файлов, `git status`, `git diff`, `npm test` выполняются быстро и без запроса подтверждения.",
46
+ ].filter(Boolean).join("\n");
47
+ }
48
+
49
+ if (lang === "zh") {
50
+ return [
51
+ GUIDANCE_MARKER,
52
+ "### 执行环境安全指引 (dsh-approval-gate)",
53
+ failClosed
54
+ ? "- **执行模式**: 已启用严格安全保护 (fail-closed)。未识别的命令需人工确认。"
55
+ : "- **执行模式**: 标准命令控制。",
56
+ snapshots
57
+ ? "- **文件快照**: 修改文件前会自动生成执行前快照。请避免盲目覆盖文件。"
58
+ : "",
59
+ trash
60
+ ? "- **文件删除**: 禁止盲目运行 `rm -rf`。优先移动至会话回收站 `.dsh/trash/<session>/`。"
61
+ : "- **文件删除**: 请确保仅在项目工作区内删除文件。",
62
+ "- **沙箱权限**: 请勿对常规项目任务请求 `danger-full-access` 或沙箱提升。",
63
+ justification
64
+ ? "- **权限提升**: 任何系统级操作或跨目录访问必须附带明确的 `justification` 说明。"
65
+ : "",
66
+ "- **安全检查**: `git status`、`git diff`、`npm test` 等检查操作自动放行。",
67
+ ].filter(Boolean).join("\n");
68
+ }
69
+
70
+ // Default: English
71
+ return [
72
+ GUIDANCE_MARKER,
73
+ "### Security & Execution Guidance (dsh-approval-gate)",
74
+ failClosed
75
+ ? "- **Execution Mode**: Strict fail-closed policy is active. Unrecognized shell commands require human approval."
76
+ : "- **Execution Mode**: Standard execution controls active.",
77
+ snapshots
78
+ ? "- **File Mutations**: Pre-execution snapshots are captured automatically before writes. Avoid blind destructive overwrites."
79
+ : "",
80
+ trash
81
+ ? "- **Deletion Policy**: Do NOT run unconditional `rm -rf`. Prefer moving to session trash `.dsh/trash/<session>/` or safe artifact cleanup."
82
+ : "- **Deletion Policy**: Keep all deletions strictly within the workspace boundary.",
83
+ "- **Sandbox Boundaries**: Do NOT request `danger-full-access` or sandbox elevation for standard internal project tasks.",
84
+ justification
85
+ ? "- **Privilege Escalation**: Any system-level command or out-of-workspace access requires an explicit `justification` explanation."
86
+ : "",
87
+ "- **Safe Inspection**: Inspection commands (`git status`, `git diff`, `npm test`, `cat`, `ls`) are fast-tracked and safe.",
88
+ ].filter(Boolean).join("\n");
89
+ }
90
+
91
+ /**
92
+ * Injects guidance into system prompt idempotently.
93
+ *
94
+ * @param {string} systemPrompt
95
+ * @param {Parameters<typeof generateAgentGuidance>[0]} [options]
96
+ * @returns {string}
97
+ */
98
+ export function injectAgentGuidance(systemPrompt, options = {}) {
99
+ if (typeof systemPrompt !== "string") {
100
+ return generateAgentGuidance(options);
101
+ }
102
+ if (systemPrompt.includes(GUIDANCE_MARKER)) {
103
+ return systemPrompt;
104
+ }
105
+ const guidance = generateAgentGuidance(options);
106
+ return `${systemPrompt.trimEnd()}\n\n${guidance}`;
107
+ }
108
+
109
+ /**
110
+ * Extracts injected guidance block from prompt if present.
111
+ * @param {string} prompt
112
+ * @returns {string|null}
113
+ */
114
+ export function extractGuidance(prompt) {
115
+ if (typeof prompt !== "string") return null;
116
+ const idx = prompt.indexOf(GUIDANCE_MARKER);
117
+ if (idx === -1) return null;
118
+ return prompt.slice(idx);
119
+ }
package/lib/index.js CHANGED
@@ -8,6 +8,9 @@ import { assertHarnessCompatibility, provideServicePolyfill } from "./compat.js"
8
8
  import { extractFilePath } from "./dispatcher.js";
9
9
  import { SnapshotManager } from "./snapshots.js";
10
10
  import { MEASURE_KINDS, classifyMeasureKind } from "./measure-kinds.js";
11
+ import { LineageManager } from "./lineage.js";
12
+ import { generateAgentGuidance, injectAgentGuidance, extractGuidance, GUIDANCE_MARKER } from "./guidance.js";
13
+ import { isRedundantSandboxRequest, buildRedundantSandboxRemediation, checkEscalationJustification } from "./escalation.js";
11
14
  import Schema from "@deepseek-ai/schemastery";
12
15
 
13
16
  if (typeof Schema.prototype?.volatile !== "function") {
@@ -183,6 +186,16 @@ export function readKnobs(ctx, execution) {
183
186
  }
184
187
  }
185
188
 
189
+ // 5b. Lineage authority inheritance (#98)
190
+ if (!policy && session && (session.parentSession || session.parentId || session.parentSessionId)) {
191
+ const parent = session.parentSession || { id: session.parentId || session.parentSessionId };
192
+ if (typeof parent.approvalPolicy === "string") {
193
+ policy = parent.approvalPolicy;
194
+ } else if (approval && typeof approval.effectivePolicy === "function") {
195
+ try { policy = approval.effectivePolicy(parent) || ""; } catch {}
196
+ }
197
+ }
198
+
186
199
  // 6. Global static fallback from approval service config
187
200
  if (!policy && approval && approval.config && approval.config.policy) {
188
201
  policy = approval.config.policy;
@@ -253,6 +266,10 @@ export const Config = Schema.object({
253
266
  agentsRules: Schema.boolean().default(true).volatile(),
254
267
  /** Enforce human confirmation on breaking major dependency bumps in package.json (#95). */
255
268
  versionGuard: Schema.boolean().default(true).volatile(),
269
+ /** Require explicit justification for privilege escalation (#107). */
270
+ requireJustification: Schema.boolean().default(false).volatile(),
271
+ /** Enable automatic remediation advice for redundant sandbox privilege requests (#101). */
272
+ enableRedundantSandboxRecovery: Schema.boolean().default(true).volatile(),
256
273
  /** Security engine instance (internal/testing). */
257
274
  engine: Schema.any().hidden(),
258
275
  });
@@ -321,6 +338,8 @@ export function apply(ctx, config) {
321
338
  slaMs: cfg.classifierSlaMs !== undefined ? cfg.classifierSlaMs : 2000,
322
339
  }),
323
340
  defaultVerdict: cfg.defaultVerdict || "ask",
341
+ requireJustification: cfg.requireJustification === true,
342
+ enableRedundantSandboxRecovery: cfg.enableRedundantSandboxRecovery !== false,
324
343
  snapshotManager: new SnapshotManager({ workspaceDir: cfg.workspaceDir || "", maxSnapshotsPerSession: cfg.maxSnapshotsPerSession, maxSnapshotBytes: cfg.maxSnapshotBytes }),
325
344
  dryRun: Boolean(cfg.dryRun || cfg.shadowMode),
326
345
  auditFailClosed: Boolean(cfg.auditFailClosed),
@@ -356,6 +375,20 @@ export function apply(ctx, config) {
356
375
  clearSnapshots: (sessionId) => (engine.clearSnapshots ? engine.clearSnapshots(sessionId) : { cleared: 0 }),
357
376
  clearAllSnapshots: () => (engine.clearAllSnapshots ? engine.clearAllSnapshots() : { cleared: 0 }),
358
377
  getSnapshotStats: () => (engine.snapshotManager ? engine.snapshotManager.getStats() : null),
378
+ lineage: engine.lineage,
379
+ registerLineage: (child, parent, root) => engine.registerLineage(child, parent, root),
380
+ getLineage: (id) => engine.getLineage(id),
381
+ guidance: {
382
+ generate: (opts) => generateAgentGuidance(opts),
383
+ inject: (prompt, opts) => injectAgentGuidance(prompt, opts),
384
+ extract: (prompt) => extractGuidance(prompt),
385
+ },
386
+ getAgentGuidance: (opts) => generateAgentGuidance(opts),
387
+ redundantSandbox: {
388
+ check: (cmd, mode, opts) => isRedundantSandboxRequest(cmd, mode, opts),
389
+ remediation: (cmd, lang) => buildRedundantSandboxRemediation(cmd, lang),
390
+ },
391
+ checkEscalationJustification: (cmd, tool, args, opts) => checkEscalationJustification(cmd, tool, args, opts),
359
392
  getSnapshot: () => ({
360
393
  active: true,
361
394
  dryRun: Boolean(cfg.dryRun || cfg.shadowMode),
@@ -379,9 +412,12 @@ export function apply(ctx, config) {
379
412
  const knobs = readKnobs(ctx, execution);
380
413
  const who = sessionTag(execution);
381
414
  const sessionId = resolveSessionId(execution);
415
+ const callId = execution?.callId || execution?.id || null;
416
+ const agentId = execution?.agent?.id || execution?.agentId || null;
417
+ const subagentId = execution?.agent?.subagentId || execution?.subagentId || null;
382
418
  let decision;
383
419
  try {
384
- decision = engine.decide(execution, { sessionId, knobs });
420
+ decision = engine.decide(execution, { sessionId, knobs, callId, agentId, subagentId, sandboxMode: knobs.sandbox, preset: knobs.preset });
385
421
  } catch (err) {
386
422
  const hit = {
387
423
  ask: true,
@@ -444,9 +480,12 @@ export function apply(ctx, config) {
444
480
  const guard = function (execution) {
445
481
  const who = sessionTag(execution);
446
482
  const sessionId = resolveSessionId(execution);
483
+ const callId = execution?.callId || execution?.id || null;
484
+ const agentId = execution?.agent?.id || execution?.agentId || null;
485
+ const subagentId = execution?.agent?.subagentId || execution?.subagentId || null;
447
486
  let decision;
448
487
  try {
449
- decision = engine.decide(execution, { sessionId });
488
+ decision = engine.decide(execution, { sessionId, callId, agentId, subagentId });
450
489
  } catch (err) {
451
490
  const hit = {
452
491
  deny: true,
@@ -493,12 +532,7 @@ export function apply(ctx, config) {
493
532
 
494
533
  export { SecurityEngine } from "./engine.js";
495
534
  export { BandsEngine } from "./bands.js";
496
- export {
497
- CircuitBreaker,
498
- CIRCUIT_STATE_ACTIVE,
499
- CIRCUIT_STATE_TRIPPED,
500
- CIRCUIT_STATE_RESUMED,
501
- } from "./breaker.js";
535
+ export { CircuitBreaker, CIRCUIT_STATE_ACTIVE, CIRCUIT_STATE_TRIPPED, CIRCUIT_STATE_RESUMED } from "./breaker.js";
502
536
  export { SessionGrantStore, DEFAULT_GRANT_TTL_MS, DEFAULT_GRANT_MAX_USES, matchGrantCriteria } from "./grants.js";
503
537
  export { canonicalizeCall, canonicalString, hashCall, sortKeys } from "./canonical.js";
504
538
  export { expandHome, resolveSafePath, isPathTraversal, canonicalizeFsPath } from "./paths.js";
@@ -511,7 +545,7 @@ export { isLoopbackHost, isLoopbackUrl, isLoopbackCommand } from "./loopback.js"
511
545
  export { computeFingerprint, computeFingerprintHash, normalizeCommandString } from "./fingerprint.js";
512
546
  export { VerdictCache, DEFAULT_CACHE_MAX_SIZE, DEFAULT_CACHE_TTL_MS } from "./cache.js";
513
547
  export { RetryExhaustionGuard, DEFAULT_MAX_RETRY_ATTEMPTS } from "./retry-exhaustion.js";
514
- export { QualityLedger, MAX_LEDGER_EVENTS_PER_SESSION } from "./ledger.js";
548
+ export { QualityLedger, MAX_LEDGER_EVENTS_PER_SESSION, CURRENT_SCHEMA_VERSION, SUPPORTED_SCHEMA_VERSIONS, migrateVerdictRecord } from "./ledger.js";
515
549
  export { AuditLogger, DEFAULT_AUDIT_LOG_RELATIVE, DEFAULT_MAX_AUDIT_BYTES, DEFAULT_MAX_AUDIT_LINES, DEFAULT_RETAIN_LINES, auditRotateContent } from "./audit-log.js";
516
550
  export { BlockCounters, categorizeReason } from "./counters.js";
517
551
  export { isCriticalOperation } from "./engine.js";
@@ -533,6 +567,10 @@ export { detectHarnessCapabilities, assertHarnessCompatibility, provideServicePo
533
567
  export { parseSemver, isMajorBump, inspectPackageJsonDiff, VersionGuard } from "./version-guard.js";
534
568
  export { SnapshotManager, DEFAULT_MAX_SNAPSHOTS_PER_SESSION, DEFAULT_MAX_SNAPSHOT_BYTES } from "./snapshots.js";
535
569
  export { MEASURE_KINDS, classifyMeasureKind, isSystemLevelExecution, isWorkspaceWideExecution } from "./measure-kinds.js";
536
-
537
-
538
-
570
+ export { LineageManager } from "./lineage.js";
571
+ export { generateAgentGuidance, injectAgentGuidance, extractGuidance, GUIDANCE_MARKER } from "./guidance.js";
572
+ export { isRedundantSandboxRequest, buildRedundantSandboxRemediation, checkEscalationJustification, REDUNDANT_SANDBOX_REASON, MISSING_JUSTIFICATION_REASON, INSUFFICIENT_JUSTIFICATION_REASON } from "./escalation.js";
573
+ export { TRACK_TYPES, classifyTrack, isInternalTrack, isExternalTrack } from "./dualtrack.js";
574
+ export { GATE_MODES, PRESET_MODE_MAP, resolveSessionGateMode, applySessionModePolicy, SessionModeRegistry } from "./session-modes.js";
575
+ export { buildEvidenceDossier, formatDossierSummary, MAX_PROMPT_CHARS, MAX_DIFF_CHARS, MAX_OUTPUT_CHARS } from "./dossier.js";
576
+ export { DRIFT_CATEGORIES, detectTrajectoryDrift, TrajectoryTracker } from "./drift.js";