@abdulr7man/pensieve 0.0.0-stage → 1.2.2

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.
Files changed (179) hide show
  1. package/LICENSE +684 -0
  2. package/README.md +180 -2
  3. package/VERSION +1 -0
  4. package/agents/README.md +16 -0
  5. package/agents/pensieve-code-auditor.md +58 -0
  6. package/agents/pensieve-mapper.md +46 -0
  7. package/agents/pensieve-planner.md +67 -0
  8. package/agents/pensieve-reconner.md +76 -0
  9. package/agents/pensieve-reporter.md +61 -0
  10. package/agents/pensieve-roe-checker.md +46 -0
  11. package/agents/pensieve-scoper.md +77 -0
  12. package/agents/pensieve-tester.md +83 -0
  13. package/agents/pensieve-validator.md +62 -0
  14. package/bin/pensieve +452 -0
  15. package/bin/pensieve-installer.cjs +5 -0
  16. package/commands/pensieve-close.md +6 -0
  17. package/commands/pensieve-map.md +6 -0
  18. package/commands/pensieve-new-engagement.md +6 -0
  19. package/commands/pensieve-pause.md +15 -0
  20. package/commands/pensieve-plan.md +6 -0
  21. package/commands/pensieve-progress.md +34 -0
  22. package/commands/pensieve-quick.md +8 -0
  23. package/commands/pensieve-recon.md +6 -0
  24. package/commands/pensieve-report.md +6 -0
  25. package/commands/pensieve-resume.md +6 -0
  26. package/commands/pensieve-retest.md +10 -0
  27. package/commands/pensieve-scope.md +49 -0
  28. package/commands/pensieve-surface.md +8 -0
  29. package/commands/pensieve-test.md +6 -0
  30. package/commands/pensieve-validate.md +6 -0
  31. package/docker/Dockerfile.pensieve-toolbox +75 -0
  32. package/docker/compose.pensieve-net.yml +37 -0
  33. package/docker/squid.conf.template +21 -0
  34. package/package.json +39 -4
  35. package/packs/ad/ad-killchain/checklist.md +64 -0
  36. package/packs/ad/ad-killchain/pack.yaml +19 -0
  37. package/packs/cloud/cloud-cis/checklist.md +66 -0
  38. package/packs/cloud/cloud-cis/pack.yaml +20 -0
  39. package/packs/fintech/practice-core/checklist.md +33 -0
  40. package/packs/fintech/practice-core/learnings.md +5 -0
  41. package/packs/fintech/practice-core/pack.yaml +18 -0
  42. package/packs/infra/ptes-infra/checklist.md +22 -0
  43. package/packs/infra/ptes-infra/pack.yaml +19 -0
  44. package/packs/mobile/owasp-masvs/checklist.md +80 -0
  45. package/packs/mobile/owasp-masvs/pack.yaml +20 -0
  46. package/packs/owasp-api-v4/checklist.md +85 -0
  47. package/packs/owasp-api-v4/learnings.md +6 -0
  48. package/packs/owasp-api-v4/pack.yaml +23 -0
  49. package/packs/owasp-api-v4/runbooks/API1/SKILL.md +66 -0
  50. package/packs/owasp-api-v4/runbooks/API10/SKILL.md +67 -0
  51. package/packs/owasp-api-v4/runbooks/API2/SKILL.md +129 -0
  52. package/packs/owasp-api-v4/runbooks/API3/SKILL.md +55 -0
  53. package/packs/owasp-api-v4/runbooks/API4/SKILL.md +59 -0
  54. package/packs/owasp-api-v4/runbooks/API5/SKILL.md +60 -0
  55. package/packs/owasp-api-v4/runbooks/API6/SKILL.md +63 -0
  56. package/packs/owasp-api-v4/runbooks/API7/SKILL.md +70 -0
  57. package/packs/owasp-api-v4/runbooks/API8/SKILL.md +72 -0
  58. package/packs/owasp-api-v4/runbooks/API9/SKILL.md +66 -0
  59. package/packs/thickclient/thickclient-core/checklist.md +60 -0
  60. package/packs/thickclient/thickclient-core/pack.yaml +24 -0
  61. package/packs/web/asvs-l2/checklist.md +50 -0
  62. package/packs/web/asvs-l2/learnings.md +6 -0
  63. package/packs/web/asvs-l2/pack.yaml +19 -0
  64. package/packs/web/asvs-l2/runbooks/V2-AUTH-ENUM/SKILL.md +75 -0
  65. package/packs/web/asvs-l2/runbooks/V2-AUTH-LIVE/SKILL.md +78 -0
  66. package/packs/web/asvs-l2/runbooks/V2-AUTH-MFA/SKILL.md +76 -0
  67. package/packs/web/asvs-l2/runbooks/V2-AUTH-RATE/SKILL.md +72 -0
  68. package/packs/web/owasp-testing-checklist/checklist.md +52 -0
  69. package/packs/web/owasp-testing-checklist/learnings.md +47 -0
  70. package/packs/web/owasp-testing-checklist/pack.yaml +21 -0
  71. package/packs/web/unauth-perimeter/checklist.md +72 -0
  72. package/packs/web/unauth-perimeter/pack.yaml +18 -0
  73. package/packs/web/unauth-perimeter/runbooks/PERIM-01/SKILL.md +60 -0
  74. package/packs/web/unauth-perimeter/runbooks/PERIM-02/SKILL.md +63 -0
  75. package/packs/web/unauth-perimeter/runbooks/PERIM-03/SKILL.md +62 -0
  76. package/packs/web/unauth-perimeter/runbooks/PERIM-04/SKILL.md +75 -0
  77. package/packs/web/unauth-perimeter/runbooks/PERIM-05/SKILL.md +66 -0
  78. package/packs/web/unauth-perimeter/runbooks/PERIM-06/SKILL.md +59 -0
  79. package/packs/web/unauth-perimeter/runbooks/PERIM-07/SKILL.md +56 -0
  80. package/packs/web/unauth-perimeter/runbooks/PERIM-08/SKILL.md +57 -0
  81. package/packs/web/unauth-perimeter/runbooks/PERIM-09/SKILL.md +62 -0
  82. package/packs/web/unauth-perimeter/runbooks/PERIM-10/SKILL.md +60 -0
  83. package/packs/whitebox/code-audit-core/checklist.md +36 -0
  84. package/packs/whitebox/code-audit-core/learnings.md +6 -0
  85. package/packs/whitebox/code-audit-core/pack.yaml +14 -0
  86. package/prompts/orchestrator-core.md +52 -0
  87. package/reference/attack-playbooks.md +57 -0
  88. package/reference/otp-relay.md +98 -0
  89. package/reference/param-profiles.md +48 -0
  90. package/reference/templates/FINDING.md +97 -0
  91. package/reference/tool-selection.md +64 -0
  92. package/reference/vulnerability-finding-standard.md +80 -0
  93. package/runtimes/hermes/hooks/injection-scan.py +290 -0
  94. package/runtimes/hermes/hooks/scope-guard.py +136 -0
  95. package/skills/pensieve/SKILL.md +134 -0
  96. package/skills/pensieve-close/SKILL.md +31 -0
  97. package/skills/pensieve-map/SKILL.md +25 -0
  98. package/skills/pensieve-new-engagement/SKILL.md +28 -0
  99. package/skills/pensieve-pause/SKILL.md +22 -0
  100. package/skills/pensieve-plan/SKILL.md +39 -0
  101. package/skills/pensieve-progress/SKILL.md +35 -0
  102. package/skills/pensieve-quick/SKILL.md +47 -0
  103. package/skills/pensieve-recon/SKILL.md +30 -0
  104. package/skills/pensieve-report/SKILL.md +46 -0
  105. package/skills/pensieve-resume/SKILL.md +33 -0
  106. package/skills/pensieve-retest/SKILL.md +35 -0
  107. package/skills/pensieve-scope/SKILL.md +35 -0
  108. package/skills/pensieve-surface/SKILL.md +36 -0
  109. package/skills/pensieve-test/SKILL.md +35 -0
  110. package/skills/pensieve-validate/SKILL.md +28 -0
  111. package/skills/pensieve-wiki/SKILL.md +39 -0
  112. package/src/installer/cli.cjs +209 -0
  113. package/src/installer/home.cjs +155 -0
  114. package/src/installer/runtimes.cjs +276 -0
  115. package/src/installer/uninstall.cjs +342 -0
  116. package/src/pensieve-sdk/bin/pensieve-sdk.cjs +1045 -0
  117. package/src/pensieve-sdk/lib/agent-translate.cjs +50 -0
  118. package/src/pensieve-sdk/lib/approvals.cjs +408 -0
  119. package/src/pensieve-sdk/lib/audit.cjs +290 -0
  120. package/src/pensieve-sdk/lib/checklist.cjs +337 -0
  121. package/src/pensieve-sdk/lib/clientlist.cjs +814 -0
  122. package/src/pensieve-sdk/lib/close.cjs +133 -0
  123. package/src/pensieve-sdk/lib/config.cjs +156 -0
  124. package/src/pensieve-sdk/lib/cvss.cjs +91 -0
  125. package/src/pensieve-sdk/lib/env.cjs +272 -0
  126. package/src/pensieve-sdk/lib/evidence.cjs +217 -0
  127. package/src/pensieve-sdk/lib/findings.cjs +1096 -0
  128. package/src/pensieve-sdk/lib/frontmatter.cjs +178 -0
  129. package/src/pensieve-sdk/lib/graph.cjs +607 -0
  130. package/src/pensieve-sdk/lib/ids.cjs +63 -0
  131. package/src/pensieve-sdk/lib/init.cjs +79 -0
  132. package/src/pensieve-sdk/lib/liveness.cjs +176 -0
  133. package/src/pensieve-sdk/lib/loop.cjs +619 -0
  134. package/src/pensieve-sdk/lib/migrate.cjs +57 -0
  135. package/src/pensieve-sdk/lib/monitor.cjs +69 -0
  136. package/src/pensieve-sdk/lib/pack.cjs +607 -0
  137. package/src/pensieve-sdk/lib/paths.cjs +73 -0
  138. package/src/pensieve-sdk/lib/pdf.cjs +291 -0
  139. package/src/pensieve-sdk/lib/recon.cjs +296 -0
  140. package/src/pensieve-sdk/lib/renderers/__pycache__/formal_report.cpython-314.pyc +0 -0
  141. package/src/pensieve-sdk/lib/renderers/formal_report.py +608 -0
  142. package/src/pensieve-sdk/lib/report.cjs +1135 -0
  143. package/src/pensieve-sdk/lib/runbook.cjs +124 -0
  144. package/src/pensieve-sdk/lib/sarif.cjs +154 -0
  145. package/src/pensieve-sdk/lib/scope.cjs +621 -0
  146. package/src/pensieve-sdk/lib/security.cjs +61 -0
  147. package/src/pensieve-sdk/lib/skills.cjs +193 -0
  148. package/src/pensieve-sdk/lib/state.cjs +610 -0
  149. package/src/pensieve-sdk/lib/subagent.cjs +658 -0
  150. package/src/pensieve-sdk/lib/target.cjs +149 -0
  151. package/src/pensieve-sdk/lib/tools.cjs +66 -0
  152. package/src/pensieve-sdk/lib/vault.cjs +122 -0
  153. package/src/pensieve-sdk/lib/vendor/cvss40.LICENSE +22 -0
  154. package/src/pensieve-sdk/lib/vendor/cvss40.js +1208 -0
  155. package/src/pensieve-sdk/package.json +11 -0
  156. package/templates/ACCOUNTS.md +35 -0
  157. package/templates/ATTACK-SURFACE.md +30 -0
  158. package/templates/FINDING.md +43 -0
  159. package/templates/PLAN.md +33 -0
  160. package/templates/PROJECT.md +29 -0
  161. package/templates/ROE.md +50 -0
  162. package/templates/RUN-LOG.md +19 -0
  163. package/templates/SCOPE.md +32 -0
  164. package/templates/VALIDATION.md +62 -0
  165. package/templates/report/REPORT.md +49 -0
  166. package/workflows/close.md +34 -0
  167. package/workflows/map.md +39 -0
  168. package/workflows/new-engagement.md +37 -0
  169. package/workflows/plan.md +45 -0
  170. package/workflows/progress.md +28 -0
  171. package/workflows/quick.md +67 -0
  172. package/workflows/recon.md +87 -0
  173. package/workflows/report.md +51 -0
  174. package/workflows/resume.md +26 -0
  175. package/workflows/retest.md +53 -0
  176. package/workflows/scope.md +47 -0
  177. package/workflows/surface.md +29 -0
  178. package/workflows/test.md +95 -0
  179. package/workflows/validate.md +34 -0
@@ -0,0 +1,621 @@
1
+ 'use strict';
2
+ const fs = require('node:fs');
3
+ const path = require('node:path');
4
+ const crypto = require('node:crypto');
5
+ const paths = require('./paths.cjs');
6
+ const fm = require('./frontmatter.cjs');
7
+ const pack = require('./pack.cjs');
8
+ /**
9
+ * scope.cjs — SCOPE.md parse, scope check, command host extraction (ADR-003/008).
10
+ * Default-deny: empty scope or unknown host => deny. Layer-1 (squid) sees the
11
+ * real destination; this module powers both the hook guard (layer 2) and the
12
+ * egress allowlist generator.
13
+ *
14
+ * 32-01 / SCOP-01 home decision: setChecklists lives HERE (not a new lib)
15
+ * because this module owns SCOPE.md mutation (the section write) and the verb
16
+ * is scope.*; it ORCHESTRATES pack.cjs (the ONE 31-01 multi-root resolver +
17
+ * pack.enable's merge) and clientlist.cjs (the EXISTING import engine) —
18
+ * reuse, never re-implement.
19
+ *
20
+ * CYCLE NOTE: state.cjs → approvals.cjs → scope.cjs is a top-level require
21
+ * cycle edge (approvals calls scope.parse at approval time). This module
22
+ * REASSIGNS module.exports, so anything requiring it mid-cycle captures a
23
+ * stale empty object. state.cjs and clientlist.cjs are therefore required
24
+ * LAZILY inside setChecklists (state.cjs's own line-295 convention) — a
25
+ * top-level require here would re-enter scope during its own load.
26
+ */
27
+
28
+ function parseSection(text, header) {
29
+ const lines = String(text).split('\n');
30
+ const out = [];
31
+ let inSection = false;
32
+ for (const line of lines) {
33
+ if (/^##\s+/.test(line)) {
34
+ inSection = new RegExp(`^##\\s+${header}\\s*$`, 'i').test(line);
35
+ continue;
36
+ }
37
+ if (inSection && /^\s*-\s+/.test(line)) out.push(line.replace(/^\s*-\s+/, '').trim());
38
+ }
39
+ return out;
40
+ }
41
+
42
+ function isCidr(s) { return /^\d{1,3}(\.\d{1,3}){3}\/\d{1,2}$/.test(s); }
43
+
44
+ // 36-02 / TD-05: the In-Scope parser is FAIL-CLOSED. A line that neither
45
+ // matches the canonical grammar ('- [AST-NNN] host (desc, ports …)' / '- host')
46
+ // NOR starts with a host-shaped token (dotted hostname / IP / CIDR) used to
47
+ // fall through the bare-token fallback and silently emit its FIRST token as
48
+ // the host — live (release test): 'AST-001' landed in the squid allowlist.
49
+ // Such a line now throws a NAMED error quoting itself and the expected
50
+ // grammar, so parse / egressConf / scope.check all refuse loudly (they funnel
51
+ // through parse) and the containment stack cannot render from a garbage scope.
52
+ const SCOPE_GRAMMAR = '"- [AST-NNN] host (description, ports 80,443)" or "- host"';
53
+
54
+ class ScopeParseError extends Error {
55
+ constructor(line, token) {
56
+ super(
57
+ `malformed In-Scope asset line: "${line}" — expected ${SCOPE_GRAMMAR}; `
58
+ + `first token "${token}" is not host-shaped (expected: dotted hostname, IP, or CIDR)`
59
+ );
60
+ this.name = 'ScopeParseError';
61
+ this.line = line;
62
+ this.token = token;
63
+ }
64
+ }
65
+
66
+ /** host-shaped = dotted hostname / IPv4 / CIDR (the IPv4 forms all carry dots).
67
+ * A single-label, dotless token (an asset id like 'AST-001', a bare filename,
68
+ * a flag value) is NOT host-shaped: the bare-token fallback must refuse it. */
69
+ function isHostShapedToken(tok) {
70
+ return tok.includes('.') || isIp(tok) || isCidr(tok);
71
+ }
72
+
73
+ function stripUrlGarbage(s) {
74
+ let h = s.replace(/^https?:\/\//, '');
75
+ if (!isCidr(h)) h = h.replace(/\/.*$/, '');
76
+ return h;
77
+ }
78
+
79
+ function parseAsset(line) {
80
+ // "- AST-001 api.acme.com (production API, ports 80,443)" or bare "- api.acme.com"
81
+ const m = /^([A-Z][A-Z0-9-]{1,15})\s+(\S+)(?:\s*\((.*)\))?$/.exec(line);
82
+ let id = null, hostPort, desc = '';
83
+ if (m) { id = m[1]; hostPort = m[2]; desc = m[3] || ''; }
84
+ else {
85
+ // TD-05: the bare-token fallback is ONLY for host-shaped first tokens.
86
+ // Anything else (id + trailing prose, a bare id, prose words) is a
87
+ // malformed line — refuse it instead of inventing a host.
88
+ const first = line.split(/\s+/)[0];
89
+ if (!isHostShapedToken(first)) throw new ScopeParseError(line, first);
90
+ hostPort = first; desc = line;
91
+ }
92
+
93
+ const ports = [];
94
+ const pm = /ports?\s+([0-9,\s]+)/i.exec(desc);
95
+ if (pm) for (const p of pm[1].split(',')) { const n = parseInt(p, 10); if (n > 0 && n < 65536) ports.push(n); }
96
+
97
+ // `init --target host:port` writes the asset as "host:port". The command side
98
+ // always strips the port before matching (extractHost), so normalize it off the
99
+ // asset host too — and keep the port — or the primary target never matches.
100
+ let host = stripUrlGarbage(hostPort);
101
+ if (!host.includes('/')) {
102
+ // IPv6 literals (e.g. ::1) carry multiple colons; the host:port stripper
103
+ // would mangle `::1` into `:`. Only strip a trailing :port off a single-colon
104
+ // host (hostname / IPv4); leave bare IPv6 literals intact (SEED-004/HARDEN-04).
105
+ if ((host.match(/:/g) || []).length === 1) {
106
+ const hp = /^(.+):(\d{1,5})$/.exec(host);
107
+ if (hp) { host = hp[1]; const n = parseInt(hp[2], 10); if (n > 0 && n < 65536 && !ports.includes(n)) ports.push(n); }
108
+ }
109
+ }
110
+
111
+ return { id, host, ports, raw: line };
112
+ }
113
+
114
+ function parse(scopeText) {
115
+ const assets = parseSection(scopeText, 'In Scope').map(parseAsset);
116
+ const outOfScope = parseSection(scopeText, 'Out of Scope').map((l) => {
117
+ const m = /^([A-Z][A-Z0-9-]{1,15})\s+(\S+)/.exec(l);
118
+ return stripUrlGarbage(m ? m[2] : l.split(/\s+/)[0]);
119
+ }).filter(Boolean);
120
+ return { assets, outOfScope };
121
+ }
122
+
123
+ function extractHost(hostOrUrl) {
124
+ let s = String(hostOrUrl).trim();
125
+ const um = /^[a-z][a-z0-9+.-]*:\/\/([^/?#]+)/i.exec(s);
126
+ if (um) s = um[1];
127
+ s = s.replace(/^[^@/]*@/, ''); // userinfo
128
+ s = s.replace(/:\d+$/, ''); // :port
129
+ return s.toLowerCase();
130
+ }
131
+
132
+ function isIp(s) { return /^\d{1,3}(\.\d{1,3}){3}$/.test(s); }
133
+
134
+ function ipToInt(ip) {
135
+ return ip.split('.').reduce((acc, o) => (acc << 8) + parseInt(o, 10) >>> 0, 0);
136
+ }
137
+
138
+ function ipInCidr(ip, cidr) {
139
+ const [base, bitsStr] = cidr.split('/');
140
+ const bits = parseInt(bitsStr, 10);
141
+ if (!isIp(ip) || !isIp(base) || isNaN(bits) || bits < 0 || bits > 32) return false;
142
+ const mask = bits === 0 ? 0 : (~0 << (32 - bits)) >>> 0;
143
+ return (ipToInt(ip) & mask) === (ipToInt(base) & mask);
144
+ }
145
+
146
+ function hostMatches(host, pattern) {
147
+ const p = pattern.toLowerCase();
148
+ if (p.startsWith('*.')) return host === p.slice(2) || host.endsWith('.' + p.slice(2));
149
+ return host === p || host.endsWith('.' + p);
150
+ }
151
+
152
+ function assetMatchesExact(host, asset) {
153
+ if (asset.host.includes('/')) return isIp(host) && ipInCidr(host, asset.host);
154
+ return host === asset.host.toLowerCase();
155
+ }
156
+
157
+ function check(ast, hostOrUrl) {
158
+ const host = extractHost(hostOrUrl);
159
+ if (!host) return { verdict: 'deny', host, reason: 'no host recognizable' };
160
+ // 1. exact asset match wins over out-of-scope patterns
161
+ // (api.acme.com in-scope must survive acme.com being out-of-scope)
162
+ for (const asset of ast.assets) {
163
+ if (assetMatchesExact(host, asset)) {
164
+ return { verdict: 'allow', host, reason: `in scope${asset.id ? ` (${asset.id})` : ''}` };
165
+ }
166
+ }
167
+ // 2. explicit out-of-scope (covers its subdomains)
168
+ for (const oos of ast.outOfScope) {
169
+ if (hostMatches(host, oos)) return { verdict: 'deny', host, reason: `explicitly out of scope (${oos})` };
170
+ }
171
+ // 3. subdomain of an in-scope host asset
172
+ for (const asset of ast.assets) {
173
+ if (!asset.host.includes('/') && hostMatches(host, asset.host)) {
174
+ return { verdict: 'allow', host, reason: `subdomain of in-scope ${asset.host}` };
175
+ }
176
+ }
177
+ return { verdict: 'deny', host, reason: 'not in scope (default-deny)' };
178
+ }
179
+
180
+ // 36-02 / TD-06: hosts come ONLY from host-shaped operands (live finding:
181
+ // 'plans/PATH.md' and 'recon/' tokens were read as hosts and the guard denied
182
+ // file-touching commands as 'not in scope' — 3 runs needed heredoc workarounds).
183
+ // A host-shaped operand is either
184
+ // - URL-shaped: scheme://host… (the tail may carry :port and /path),
185
+ // - bare: a dot-bearing hostname-like token (labels split by '.',
186
+ // each a hostname label, last label alphabetic — an IPv4
187
+ // operand qualifies; a trailing :port is tolerated).
188
+ // NOT host operands: file paths (any '/' without a scheme), extension-bearing
189
+ // filenames (last label a known file extension), flag tokens, single labels.
190
+ // 36-03 / TD-10 adds the OPERAND-CONTEXT rule on top (see below): the BARE
191
+ // form is a host candidate only as an operand of a NETWORK TOOL verb; the
192
+ // URL form is unambiguous and extracts anywhere.
193
+ // Layer 2 deliberately narrows to plausibly-real host operands; squid (layer 1)
194
+ // sees the real destination and stays the final word on everything else.
195
+ const URL_TOKEN_RE = /^[a-z][a-z0-9+.-]*:\/\//i;
196
+
197
+ // filename extensions: a bare token whose last dot-label is one of these is a
198
+ // FILE, not a hostname ('PLAN-001.md', 'exploit.py', 'wordlist.txt').
199
+ const FILE_EXTS = new Set([
200
+ 'md', 'txt', 'py', 'sh', 'bash', 'zsh', 'json', 'jsonl', 'ndjson', 'csv', 'tsv', 'log',
201
+ 'yaml', 'yml', 'toml', 'ini', 'conf', 'cfg', 'env', 'html', 'htm', 'xml', 'js', 'mjs',
202
+ 'cjs', 'ts', 'css', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'svg', 'ico', 'webp', 'zip',
203
+ 'tar', 'gz', 'bz2', 'xz', '7z', 'rar', 'sql', 'db', 'sqlite', 'sqlite3', 'pem', 'key',
204
+ 'crt', 'csr', 'pub', 'bak', 'swp', 'tmp', 'orig', 'patch', 'diff', 'lock', 'map',
205
+ 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'rtf', 'epub', 'mp4', 'mp3',
206
+ 'wav', 'avi', 'mov', 'war', 'jar', 'class', 'php', 'asp', 'aspx', 'jsp', 'rb', 'go',
207
+ 'rs', 'c', 'h', 'cpp', 'hpp', 'java', 'pl', 'lua', 'r', 'ps1', 'bat', 'cmd', 'awk',
208
+ 'ipynb', 'har',
209
+ ]);
210
+
211
+ /** bare host-shaped operand? dotted hostname-like token (IPv4 included,
212
+ * trailing :port tolerated) — never a path fragment or extension filename. */
213
+ function isBareHostnameLike(t) {
214
+ let s = t;
215
+ const pm = /^(.+):(\d{1,5})$/.exec(s);
216
+ if (pm && !pm[1].includes(':')) s = pm[1]; // host:port (leave IPv6 ::1 alone)
217
+ if (isIp(s)) return true; // bare IPv4 operand
218
+ if (s.includes('/')) return false; // path fragment — not a host
219
+ const labels = s.split('.');
220
+ if (labels.length < 2) return false; // no dot: not host-shaped
221
+ for (const l of labels) {
222
+ if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/i.test(l)) return false;
223
+ }
224
+ const last = labels[labels.length - 1].toLowerCase();
225
+ if (!/^[a-z]{2,}$/.test(last)) return false; // TLD-ish: alphabetic last label
226
+ if (FILE_EXTS.has(last)) return false; // extension-bearing filename
227
+ return true;
228
+ }
229
+
230
+ // ---- 36-03 / TD-10: network-operand host extraction ----
231
+ //
232
+ // TD-06 narrowed host candidates to host-shaped OPERANDS; the live
233
+ // the live engagement still hit a recurring false-positive class
234
+ // (units 003/004/016/020/024): dot-bearing capture filenames
235
+ // ('capture.session.raw') whose last label is NOT a known extension passed
236
+ // the TD-06 shape test, and the guard denied cat/grep/python runs as 'not
237
+ // in scope'. TD-10 adds the OPERAND-CONTEXT rule: a bare dot-bearing token
238
+ // is a host candidate ONLY when it is an operand of a NETWORK TOOL verb —
239
+ // URL-shaped tokens (scheme://) stay unambiguous and extract ANYWHERE.
240
+ // Dotted filenames/paths/versions outside a network-operand position defer
241
+ // to the network layer (verdict unknown — layer 1, squid, is default-deny
242
+ // and stays the final word on everything layer 2 declines to decide).
243
+
244
+ // verbs whose non-flag operands are plausibly network destinations
245
+ const NETWORK_TOOLS = new Set([
246
+ 'curl', 'wget', 'dig', 'nslookup', 'nmap', 'nc', 'ncat', 'ping', 'traceroute',
247
+ 'httpx', 'ffuf', 'nuclei', 'katana', 'arjun', 'gau', 'sqlmap', 'nikto',
248
+ 'whatweb', 'ssh', 'scp', 'sftp', 'ftp', 'telnet', 'adb',
249
+ ]);
250
+ // conditional verbs: network ONLY for these subcommands (a dotted arg to
251
+ // 'git checkout' / 'docker logs' / 'npm test' is a file/branch/tag, not a host)
252
+ const NETWORK_SUBCOMMANDS = {
253
+ git: ['clone', 'fetch', 'pull', 'push', 'ls-remote'],
254
+ docker: ['pull', 'run', 'build'],
255
+ node: ['install', 'fetch'],
256
+ npm: ['install', 'fetch'],
257
+ pip: ['install'],
258
+ pip3: ['install'],
259
+ openssl: ['s_client'],
260
+ };
261
+ // wrapper prefixes that never hide the segment's real verb (sudo nmap …)
262
+ const VERB_WRAPPERS = new Set(['sudo', 'nohup', 'env', 'command', 'time', 'nice', 'watch', 'strace']);
263
+
264
+ // shell separators: a compound command is a sequence of SEGMENTS, each with
265
+ // its own verb — a bare token is judged against ITS segment's verb
266
+ // ('cat x.raw && curl example.com': x.raw is a cat operand (file),
267
+ // example.com is a curl operand (host)).
268
+ const SHELL_SEGMENT_RE = /\|\||&&|\n|;|&|\|/;
269
+
270
+ function tokenizeSegment(text) {
271
+ const tokens = String(text).split(/\s+/).filter(Boolean);
272
+ // POSIX env-assignment prefixes (FOO=bar cmd …) are not the command
273
+ while (tokens.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[0])) tokens.shift();
274
+ return tokens;
275
+ }
276
+
277
+ /** does this segment's verb plausibly take network-destination operands? */
278
+ function segmentIsNetwork(tokens) {
279
+ let i = 0;
280
+ while (i < tokens.length) {
281
+ const t = tokens[i].toLowerCase();
282
+ if (VERB_WRAPPERS.has(t) || /^[a-z_][a-z0-9_]*=/.test(t)) { i += 1; continue; }
283
+ break;
284
+ }
285
+ // basename: '/usr/bin/curl' and './tool' resolve to their last segment
286
+ const verb = (tokens[i] || '').toLowerCase().replace(/^.*\//, '');
287
+ if (NETWORK_TOOLS.has(verb)) return true;
288
+ const subs = NETWORK_SUBCOMMANDS[verb];
289
+ return !!subs && subs.includes((tokens[i + 1] || '').toLowerCase());
290
+ }
291
+
292
+ /** bare host operand in a NETWORK position — user@host (ssh/scp) forms
293
+ * included; extractHost() strips the userinfo before matching. */
294
+ function isBareNetworkOperand(t) {
295
+ let s = t;
296
+ const at = s.indexOf('@');
297
+ if (at > 0 && !s.slice(0, at).includes('/')) s = s.slice(at + 1);
298
+ return isBareHostnameLike(s);
299
+ }
300
+
301
+ function checkCommand(ast, command) {
302
+ const segments = String(command).split(SHELL_SEGMENT_RE).map(tokenizeSegment);
303
+ // pensieve-sdk self-enforces scope internally where relevant; dotted
304
+ // subcommands (findings.status, state.current) would otherwise read as
305
+ // hostnames and the guard would block its own tooling (live M1 finding).
306
+ const head = segments[0] || [];
307
+ if (head[0] === 'pensieve-sdk' || /(?:^|\/)pensieve-sdk(?:\.cjs)?$/.test(head[0] || '')
308
+ || (head[0] === 'node' && /pensieve-sdk\.cjs$/.test(head[1] || ''))) {
309
+ return { verdict: 'unknown', reason: 'pensieve-sdk self-enforces scope internally', asset: null, token: head[0] };
310
+ }
311
+ const network = segments.map(segmentIsNetwork);
312
+ for (let s = 0; s < segments.length; s++) {
313
+ const toks = segments[s];
314
+ for (let i = 0; i < toks.length; i++) {
315
+ let t = toks[i];
316
+ if ((t === '-u' || t === '--url' || t === '-target' || t === '--target' || t === '-h') && toks[i + 1]) {
317
+ t = toks[i + 1]; // host-bearing flag: the VALUE is the operand
318
+ }
319
+ if (/^-/.test(t)) continue; // flag tokens are never hosts
320
+ // a token that names an existing local file is a FILE, not a host —
321
+ // hosts don't exist on disk (belt-and-braces to the extension rule)
322
+ if (fs.existsSync(path.resolve(process.cwd(), t))) continue;
323
+ if (URL_TOKEN_RE.test(t)) {
324
+ // URL-shaped operands are unambiguous: they extract ANYWHERE
325
+ // (a URL in an echo or a script argument still scope-checks)
326
+ } else if (!network[s] || !isBareNetworkOperand(t)) {
327
+ // TD-10: bare dot-bearing tokens are host candidates ONLY as
328
+ // operands of a NETWORK TOOL verb — dotted filenames/versions in
329
+ // cat/grep/python/checkout text defer to the network layer
330
+ continue;
331
+ }
332
+ const host = extractHost(t);
333
+ // Skip loopback-addressed command tokens: incidental toolbox-local tool
334
+ // chatter (a tool talking to its own loopback) is never an in-scope TARGET
335
+ // — loopback targets are rejected at scope time (SEED-004/HARDEN-04), so this
336
+ // broadened skip opens no target path (T-14-03, accepted).
337
+ if (!host || isLocalhost(host)) continue;
338
+ return { ...check(ast, host), token: t };
339
+ }
340
+ }
341
+ return { verdict: 'unknown', reason: 'no remote host recognized in command' };
342
+ }
343
+
344
+ // isLocalhost(host) — loopback predicate covering the WHOLE 127.0.0.0/8 range
345
+ // (reusing ipInCidr/isIp) plus localhost and ::1 (SEED-004/HARDEN-04).
346
+ function isLocalhost(host) {
347
+ if (host === 'localhost' || host === '::1') return true;
348
+ return isIp(host) && ipInCidr(host, '127.0.0.0/8');
349
+ }
350
+
351
+ // loopbackTargets(ast) — in-scope asset hosts that are loopback addresses. A
352
+ // loopback target can never run under containment (inside pensieve-net it resolves
353
+ // to the toolbox itself, not the real target), so these are rejected fail-closed
354
+ // at scope finalization. Empty for a service-name lab-attach target.
355
+ function loopbackTargets(ast) {
356
+ const assets = (ast && Array.isArray(ast.assets)) ? ast.assets : [];
357
+ return assets.map((a) => a.host).filter((h) => h && isLocalhost(String(h).toLowerCase()));
358
+ }
359
+
360
+ /**
361
+ * egressConf(ast) — squid dstdomain allowlist text + safe-ports comment.
362
+ * CIDR assets are NOT emitted (they join pensieve-net by network membership).
363
+ * Empty scope => empty allowlist (squid default-deny blocks everything).
364
+ */
365
+ function egressConf(ast) {
366
+ const hosts = [];
367
+ const ports = new Set();
368
+ for (const a of ast.assets) {
369
+ if (a.host.includes('/')) continue; // CIDR: network membership lane
370
+ // squid dstdomain has no '*' wildcard — its subdomain+apex form is a
371
+ // LEADING DOT (.foo.com). Translate our scope syntax (live M2 finding:
372
+ // '*.foo.com' matched nothing; every wildcard asset was squid-403'd).
373
+ const h = a.host.startsWith('*.') ? '.' + a.host.slice(2) : a.host;
374
+ if (!hosts.includes(h)) hosts.push(h);
375
+ for (const p of a.ports) ports.add(p);
376
+ }
377
+ // BLOCKER-1 (13-CONTEXT): the enforced ports are the scope's asset ports
378
+ // (squid target_ports). Do NOT fabricate a 80/443 default — that was the drift
379
+ // the ROE-checker caught (comment said 3001, squid enforced 80/443/3001). 80/443
380
+ // live on the separate provision lane now, never on the target.
381
+ const portList = [...ports].sort((x, y) => x - y).join(',');
382
+ return `# generated by pensieve-sdk scope.egress-conf — do not hand-edit
383
+ # safe_ports: ${portList}
384
+ ${hosts.join('\n')}${hosts.length ? '\n' : ''}`;
385
+ }
386
+
387
+ const BOX_LEVELS = ['white', 'gray', 'black'];
388
+ const CREDENTIALS_WAIVERS = ['self-provision', 'unauthenticated-only'];
389
+
390
+ /**
391
+ * recordBox — persist the engagement box level (+ optional waivers) into
392
+ * config.yaml at scope time (BOX-01). Fail-closed: an invalid box level or
393
+ * credentials waiver throws and writes nothing. Preserves all pre-existing
394
+ * config keys, rewriting them in init.cjs's flat `k: JSON.stringify(v)` form so
395
+ * config.load validates box/waivers on read and the plan-02 gate can trust them.
396
+ */
397
+ function recordBox(engagementDir, { box, sourceWaiver, credentialsWaiver } = {}) {
398
+ if (!BOX_LEVELS.includes(box)) {
399
+ throw new Error(`invalid box level: ${box} (expected white|gray|black)`);
400
+ }
401
+ if (credentialsWaiver !== undefined && credentialsWaiver !== null
402
+ && !CREDENTIALS_WAIVERS.includes(credentialsWaiver)) {
403
+ throw new Error(`invalid credentials waiver: ${credentialsWaiver} (expected self-provision|unauthenticated-only)`);
404
+ }
405
+ const file = paths.configFile(engagementDir);
406
+ const current = fs.existsSync(file) ? fm.parseYaml(fs.readFileSync(file, 'utf8')) : {};
407
+ current.box = box;
408
+ if (sourceWaiver !== undefined) current.box_source_waiver = !!sourceWaiver;
409
+ if (credentialsWaiver !== undefined && credentialsWaiver !== null) current.box_credentials_waiver = credentialsWaiver;
410
+ const out = Object.entries(current).map(([k, v]) => `${k}: ${JSON.stringify(v)}`).join('\n') + '\n';
411
+ fs.writeFileSync(file, out);
412
+ return { box, box_source_waiver: current.box_source_waiver, box_credentials_waiver: current.box_credentials_waiver };
413
+ }
414
+
415
+ // ---- NPX-05 (v1.2): the autonomy dial recorder ----
416
+ //
417
+ // The scoping interview's autonomy answer lands here, in config.yaml — the
418
+ // dial's single source of truth (read by approvals.autoRecord* and the
419
+ // state boundary gates). Levels: supervised (every checkpoint explicit),
420
+ // semi-autonomous (plans via the AI approver; scope + report human),
421
+ // autonomous (full walk-away — checkpoints auto-RECORDED with provenance
422
+ // approved_by: autonomous-mode; mechanical gates + blockers still stop).
423
+ const AUTONOMY_LEVELS = ['supervised', 'semi-autonomous', 'autonomous'];
424
+
425
+ function recordAutonomy(engagementDir, { level } = {}) {
426
+ if (!AUTONOMY_LEVELS.includes(level)) {
427
+ throw new Error(`invalid autonomy level: ${level} (expected ${AUTONOMY_LEVELS.join('|')})`);
428
+ }
429
+ const file = paths.configFile(engagementDir);
430
+ const current = fs.existsSync(file) ? fm.parseYaml(fs.readFileSync(file, 'utf8')) : {};
431
+ current.autonomy = level;
432
+ const out = Object.entries(current).map(([k, v]) => `${k}: ${JSON.stringify(v)}`).join('\n') + '\n';
433
+ fs.writeFileSync(file, out);
434
+ return { autonomy: level, levels: AUTONOMY_LEVELS };
435
+ }
436
+
437
+ // ---- 32-01 / SCOP-01: the scoping interview's checklist-selection recorder ----
438
+ //
439
+ // Which checklist(s) will this engagement run? The scoper answers that ONCE,
440
+ // here, and the single scope approval covers it: the selection lands in
441
+ // SCOPE.md's `## Checklists` section (the existing approved artifact), the
442
+ // packs are enabled in config.yaml (MERGED via pack.enable — never clobbered),
443
+ // and a client-supplied workbook imports through the EXISTING clientlist
444
+ // engine. VALIDATE-THEN-WRITE: every slug resolves across BOTH pack roots and
445
+ // the workbook imports BEFORE any engagement state is written — a refusal
446
+ // leaves SCOPE.md, config.yaml AND clientlist/ untouched.
447
+ //
448
+ // Refusals carry RAW envelopes (report.pdf convention) because the remedy IS
449
+ // the path: the searched roots (unknown slug) and both colliding paths name
450
+ // filesystem locations security.sanitizeError would redact to "[path]".
451
+
452
+ const CHECKLISTS_HEADING_RE = /^##\s+Checklists\s*$/;
453
+
454
+ /** root label for a resolved pack dir — pack.list's repo|user convention */
455
+ function rootLabel(rootList, dir) {
456
+ for (let i = 0; i < rootList.length; i++) {
457
+ if (dir === rootList[i] || dir.startsWith(rootList[i] + path.sep)) {
458
+ return i === 0 ? 'repo' : 'user';
459
+ }
460
+ }
461
+ return 'user';
462
+ }
463
+
464
+ /** the deterministic `## Checklists` section body (NO timestamps: a re-run is
465
+ * byte-identical) */
466
+ function renderChecklistsSection(selected, clInfo) {
467
+ const lines = [
468
+ '## Checklists', '',
469
+ '_Checklist selection recorded via `scope.set-checklists` — covered by the single scope approval (nothing new to approve)._', '',
470
+ ];
471
+ for (const s of selected) {
472
+ lines.push(`- pack: ${s.slug} (root: ${s.root}, version: ${s.version})`);
473
+ }
474
+ if (clInfo) {
475
+ lines.push(`- client workbook: ${clInfo.slug} (snapshot: ${clInfo.snapshot}, sha256: ${clInfo.sha256}, rows: ${clInfo.total_rows})`);
476
+ }
477
+ return lines.join('\n');
478
+ }
479
+
480
+ /** splice the section into SCOPE.md: an existing `## Checklists` section is
481
+ * REPLACED in place (up to the next ## heading / EOF); otherwise it is
482
+ * appended at the end. Output always ends with exactly one newline. */
483
+ function replaceChecklistsSection(scopeText, sectionBody) {
484
+ const lines = String(scopeText).split('\n');
485
+ const start = lines.findIndex((l) => CHECKLISTS_HEADING_RE.test(l));
486
+ const body = sectionBody.split('\n');
487
+ let out;
488
+ if (start === -1) {
489
+ out = `${String(scopeText).replace(/\n+$/, '')}\n\n${sectionBody}`;
490
+ } else {
491
+ let end = lines.length;
492
+ for (let i = start + 1; i < lines.length; i++) {
493
+ if (/^##\s+/.test(lines[i])) { end = i; break; }
494
+ }
495
+ if (end < lines.length) body.push(''); // blank line before the next heading
496
+ out = lines.slice(0, start).concat(body, lines.slice(end)).join('\n');
497
+ }
498
+ return out.endsWith('\n') ? out : `${out}\n`;
499
+ }
500
+
501
+ /** idempotent re-import: clientlist.import refuses a slug that is already
502
+ * imported. When the workbook on disk is the SAME (same slug, same bytes —
503
+ * sha256 proof) the existing snapshot IS the import result, so the re-run
504
+ * reuses it instead of failing; different bytes keep the refusal verbatim. */
505
+ function reuseSnapshot(dir, file, refusal) {
506
+ try {
507
+ const clientlist = require('./clientlist.cjs'); // lazy — see CYCLE NOTE above
508
+ const slug = clientlist._internals.slugify(path.basename(file));
509
+ const snap = JSON.parse(fs.readFileSync(path.join(dir, 'clientlist', `${slug}.json`), 'utf8'));
510
+ const bytes = fs.readFileSync(file);
511
+ const same = snap.source
512
+ && snap.source.file === path.basename(file)
513
+ && snap.source.sha256 === crypto.createHash('sha256').update(bytes).digest('hex');
514
+ if (!same) return null;
515
+ return {
516
+ ok: true,
517
+ slug: snap.slug,
518
+ snapshot: path.join('clientlist', `${slug}.json`),
519
+ sha256: snap.source.sha256,
520
+ total_rows: snap.sheets.reduce((n, s) => n + (s.rows || []).length, 0),
521
+ reused: true,
522
+ refusal_note: refusal.error,
523
+ };
524
+ } catch {
525
+ return null; // unreadable snapshot -> the refusal stands, verbatim
526
+ }
527
+ }
528
+
529
+ /**
530
+ * setChecklists(engagementDir, { packs, clientWorkbook?, packsRoot? })
531
+ *
532
+ * `packs` is the comma-separated slug list as the CLI receives it. Returns
533
+ * { ok: true, packs, enabled_packs, clientlist, scope } on success, or a raw
534
+ * ok:false refusal envelope (gate + paths/searched, unsanitized) on any
535
+ * validation failure — with NO engagement state written either way.
536
+ */
537
+ function setChecklists(engagementDir, { packs, clientWorkbook = null, packsRoot } = {}) {
538
+ const state = require('./state.cjs'); // lazy — see CYCLE NOTE above
539
+ const clientlist = require('./clientlist.cjs'); // lazy — see CYCLE NOTE above
540
+ if (!engagementDir || !state.isEngagement(engagementDir)) {
541
+ throw new Error(
542
+ 'scope.set-checklists requires an engagement dir (no STATE.md with status frontmatter at the given path)'
543
+ );
544
+ }
545
+ const dir = path.resolve(engagementDir);
546
+ const slugs = [...new Set(String(packs || '').split(',').map((s) => s.trim()).filter(Boolean))];
547
+ if (slugs.length === 0) {
548
+ throw new Error('scope.set-checklists requires --packs <slugs,comma-separated>');
549
+ }
550
+ const scopePath = paths.scopeFile(dir);
551
+ if (!fs.existsSync(scopePath)) {
552
+ throw new Error(`SCOPE.md not found in the engagement dir — the selection records into the existing approved artifact (run init first)`);
553
+ }
554
+
555
+ // ---- VALIDATE (nothing below writes until every check passes) ----
556
+ const rootList = pack.roots(packsRoot);
557
+ const selected = [];
558
+ for (const slug of slugs) {
559
+ const dirs = pack.resolveDirs(packsRoot, slug);
560
+ if (dirs.length === 0) {
561
+ return {
562
+ ok: false, gate: 'scope-checklists',
563
+ error: `pack not found (unknown pack): ${slug} — searched: ${rootList.join(', ')}`,
564
+ searched: rootList,
565
+ };
566
+ }
567
+ if (dirs.length > 1) {
568
+ const e = pack.collisionError(slug, dirs); // the pack-collision envelope, verbatim
569
+ return { ok: false, gate: 'pack-collision', error: e.message, slug, paths: dirs };
570
+ }
571
+ let meta;
572
+ try {
573
+ meta = pack.load(packsRoot, slug).meta; // pack.yaml must load (version comes from it)
574
+ } catch (e) {
575
+ return { ok: false, gate: 'scope-checklists', error: e.message, slug };
576
+ }
577
+ selected.push({ slug, root: rootLabel(rootList, dirs[0]), version: String(meta.version || ''), path: dirs[0] });
578
+ }
579
+
580
+ // ---- client workbook: the EXISTING import engine (its refusals surface
581
+ // verbatim; it parses content BEFORE writing any state, so a bad workbook
582
+ // still leaves the engagement untouched) ----
583
+ let clInfo = null;
584
+ if (clientWorkbook) {
585
+ let imp;
586
+ try {
587
+ imp = clientlist.importWorkbook(dir, { file: clientWorkbook });
588
+ } catch (e) {
589
+ return { ok: false, gate: 'clientlist-import', error: e.message };
590
+ }
591
+ if (imp.ok === false) {
592
+ if (imp.gate === 'clientlist-import' && /already imported/.test(imp.error)) {
593
+ const reuse = reuseSnapshot(dir, clientWorkbook, imp);
594
+ if (reuse) imp = reuse; // same workbook re-selected: idempotent
595
+ else return imp; // different bytes under the same slug: refusal verbatim
596
+ } else {
597
+ return imp; // bridge miss etc.: refusal verbatim
598
+ }
599
+ }
600
+ clInfo = {
601
+ slug: imp.slug,
602
+ snapshot: imp.snapshot,
603
+ sha256: imp.sha256,
604
+ total_rows: imp.total_rows,
605
+ ...(imp.reused ? { reused: true } : {}),
606
+ };
607
+ }
608
+
609
+ // ---- WRITE (full validation passed) ----
610
+ for (const s of selected) pack.enable(dir, s.slug, { packsRoot }); // merge, never clobber
611
+ const enabled = pack.enabled(dir);
612
+ const next = replaceChecklistsSection(
613
+ fs.readFileSync(scopePath, 'utf8'),
614
+ renderChecklistsSection(selected, clInfo)
615
+ );
616
+ fs.writeFileSync(scopePath, next, 'utf8');
617
+
618
+ return { ok: true, packs: selected, enabled_packs: enabled, clientlist: clInfo, scope: { file: scopePath } };
619
+ }
620
+
621
+ module.exports = { parse, check, checkCommand, extractHost, ipInCidr, isLocalhost, loopbackTargets, egressConf, recordBox, recordAutonomy, setChecklists, ScopeParseError };