fullcourtdefense 2.1.2 → 2.2.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.
@@ -0,0 +1,21 @@
1
+ export declare const DETECTION_SCHEMA = 1;
2
+ export declare const MAX_DETECTION_BYTES = 16384;
3
+ export declare const DETECTION_SIGNATURE_DOMAIN = "fullcourtdefense/detection-data/v1\n";
4
+ export declare const DETECTION_PUBLIC_KEY = "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEALTPVDAPBFn0XNHo+y3GFHQ8Inr/OM7z1vqUixWL8R00=\n-----END PUBLIC KEY-----";
5
+ export interface DetectionData {
6
+ schema: 1;
7
+ revision: number;
8
+ /** These capabilities never execute data, and never contain a policy verdict. */
9
+ googleAuthScopes: string[];
10
+ firestoreQueryOrigins: string[];
11
+ }
12
+ export declare const BUNDLED_DETECTION_DATA: Readonly<DetectionData>;
13
+ export declare function getDetectionData(): Readonly<DetectionData>;
14
+ export declare function validateDetectionData(value: unknown): DetectionData;
15
+ export interface DetectionEnvelope {
16
+ payload: string;
17
+ signature: string;
18
+ }
19
+ export declare function verifyDetectionEnvelope(raw: string, now?: number, publicKey?: string): DetectionData;
20
+ /** Callers must authenticate envelopes before activation; always copy/freeze to avoid mutation. */
21
+ export declare function activateDetectionData(data: DetectionData): boolean;
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BUNDLED_DETECTION_DATA = exports.DETECTION_PUBLIC_KEY = exports.DETECTION_SIGNATURE_DOMAIN = exports.MAX_DETECTION_BYTES = exports.DETECTION_SCHEMA = void 0;
4
+ exports.getDetectionData = getDetectionData;
5
+ exports.validateDetectionData = validateDetectionData;
6
+ exports.verifyDetectionEnvelope = verifyDetectionEnvelope;
7
+ exports.activateDetectionData = activateDetectionData;
8
+ /** Pure, bounded detection vocabulary. Vendored with the policy engine into CLI/demo. */
9
+ const crypto_1 = require("crypto");
10
+ exports.DETECTION_SCHEMA = 1;
11
+ exports.MAX_DETECTION_BYTES = 16384;
12
+ exports.DETECTION_SIGNATURE_DOMAIN = 'fullcourtdefense/detection-data/v1\n';
13
+ exports.DETECTION_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
14
+ MCowBQYDK2VwAyEALTPVDAPBFn0XNHo+y3GFHQ8Inr/OM7z1vqUixWL8R00=
15
+ -----END PUBLIC KEY-----`;
16
+ exports.BUNDLED_DETECTION_DATA = Object.freeze({
17
+ schema: 1, revision: 1,
18
+ googleAuthScopes: Object.freeze(['https://www.googleapis.com/auth/datastore']),
19
+ firestoreQueryOrigins: Object.freeze(['https://firestore.googleapis.com']),
20
+ });
21
+ let active = exports.BUNDLED_DETECTION_DATA;
22
+ function getDetectionData() { return active; }
23
+ function exactKeys(value, keys) {
24
+ return !!value && typeof value === 'object' && !Array.isArray(value)
25
+ && Object.keys(value).length === keys.length && keys.every(key => Object.prototype.hasOwnProperty.call(value, key));
26
+ }
27
+ function validateDetectionData(value) {
28
+ const data = value;
29
+ if (!exactKeys(data, ['schema', 'revision', 'googleAuthScopes', 'firestoreQueryOrigins'])
30
+ || data.schema !== exports.DETECTION_SCHEMA || !Number.isSafeInteger(data.revision) || data.revision < 1)
31
+ throw new Error('Unsupported detection schema/revision');
32
+ const list = (items, valid) => {
33
+ if (!Array.isArray(items) || items.length < 1 || items.length > 32
34
+ || items.some(item => typeof item !== 'string' || item.length > 200 || !valid(item))
35
+ || new Set(items).size !== items.length)
36
+ throw new Error('Invalid detection vocabulary');
37
+ return [...items];
38
+ };
39
+ // Scope URLs are authorization metadata, not destinations. Restrict to the provider namespace.
40
+ const scopes = list(data.googleAuthScopes, s => /^https:\/\/www\.googleapis\.com\/auth\/[a-z][a-z0-9._-]*$/.test(s));
41
+ // Only Firestore service origins can use the fixed structuredQuery body/path proof.
42
+ // No wildcard host, arbitrary URL, regex, flag, verdict, or shell pattern is supported.
43
+ const origins = list(data.firestoreQueryOrigins, s => /^https:\/\/firestore(?:\.[a-z][a-z0-9-]{0,40})?\.googleapis\.com$/.test(s));
44
+ return { schema: 1, revision: data.revision, googleAuthScopes: scopes, firestoreQueryOrigins: origins };
45
+ }
46
+ function verifyDetectionEnvelope(raw, now = Date.now(), publicKey = exports.DETECTION_PUBLIC_KEY) {
47
+ if (Buffer.byteLength(raw) > exports.MAX_DETECTION_BYTES)
48
+ throw new Error('Detection update too large');
49
+ const envelope = JSON.parse(raw);
50
+ if (!exactKeys(envelope, ['payload', 'signature']) || typeof envelope.payload !== 'string'
51
+ || typeof envelope.signature !== 'string' || !/^[A-Za-z0-9+/]{86}==$/.test(envelope.signature))
52
+ throw new Error('Invalid detection envelope');
53
+ if (!(0, crypto_1.verify)(null, Buffer.from(exports.DETECTION_SIGNATURE_DOMAIN + envelope.payload), (0, crypto_1.createPublicKey)(publicKey), Buffer.from(envelope.signature, 'base64')))
54
+ throw new Error('Invalid detection signature');
55
+ const payload = JSON.parse(envelope.payload);
56
+ if (!exactKeys(payload, ['issuedAt', 'expiresAt', 'data']) || !Number.isSafeInteger(payload.issuedAt)
57
+ || !Number.isSafeInteger(payload.expiresAt) || payload.issuedAt > now + 60000
58
+ || payload.expiresAt <= now || payload.expiresAt <= payload.issuedAt
59
+ || payload.expiresAt - payload.issuedAt > 90 * 86400000)
60
+ throw new Error('Detection update outside validity window');
61
+ return validateDetectionData(payload.data);
62
+ }
63
+ /** Callers must authenticate envelopes before activation; always copy/freeze to avoid mutation. */
64
+ function activateDetectionData(data) {
65
+ const valid = validateDetectionData(data);
66
+ if (valid.revision <= active.revision)
67
+ return false;
68
+ active = Object.freeze({ ...valid, googleAuthScopes: Object.freeze(valid.googleAuthScopes),
69
+ firestoreQueryOrigins: Object.freeze(valid.firestoreQueryOrigins) });
70
+ return true;
71
+ }
@@ -0,0 +1,27 @@
1
+ /** In-memory detector contract. No downloads, file reads or model calls here. */
2
+ export interface DetectorFacts {
3
+ operation: string;
4
+ context: Record<string, string>;
5
+ }
6
+ /** A terminated worker cannot recover on the next action. */
7
+ export declare class DetectorWorkerUnavailable extends Error {
8
+ }
9
+ type Detector = ((tool: string, args: Record<string, any>) => DetectorFacts) & {
10
+ dispose?(): void;
11
+ };
12
+ export declare function detectorRuntimeStatus(): {
13
+ revision: number;
14
+ failures: number;
15
+ active: boolean;
16
+ };
17
+ export declare function installDetector(next: Detector, nextRevision: number): void;
18
+ export declare function updatedDetectorFacts(tool: string, args: Record<string, any>): DetectorFacts | undefined;
19
+ /**
20
+ * Fact names a detector may never produce, in any letter case. The engine keeps
21
+ * call arguments spelled so away from detectors (actionPolicyEngine
22
+ * inferToolContext): an argument NAME must never fail a detector's result.
23
+ */
24
+ export declare function detectorRejectsFactName(key: string): boolean;
25
+ /** Shared validation for smoke tests and every actual inference result. */
26
+ export declare function validateDetectorFacts(result: DetectorFacts): DetectorFacts;
27
+ export {};
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DetectorWorkerUnavailable = void 0;
4
+ exports.detectorRuntimeStatus = detectorRuntimeStatus;
5
+ exports.installDetector = installDetector;
6
+ exports.updatedDetectorFacts = updatedDetectorFacts;
7
+ exports.detectorRejectsFactName = detectorRejectsFactName;
8
+ exports.validateDetectorFacts = validateDetectorFacts;
9
+ /** A terminated worker cannot recover on the next action. */
10
+ class DetectorWorkerUnavailable extends Error {
11
+ }
12
+ exports.DetectorWorkerUnavailable = DetectorWorkerUnavailable;
13
+ let detector;
14
+ let revision = 0;
15
+ let failures = 0;
16
+ function detectorRuntimeStatus() { return { revision, failures, active: Boolean(detector) }; }
17
+ function installDetector(next, nextRevision) {
18
+ if (!Number.isSafeInteger(nextRevision) || nextRevision <= revision)
19
+ throw new Error('Detector revision must increase');
20
+ detector?.dispose?.();
21
+ detector = next;
22
+ revision = nextRevision;
23
+ failures = 0;
24
+ }
25
+ function updatedDetectorFacts(tool, args) {
26
+ if (!detector)
27
+ return undefined;
28
+ try {
29
+ return validateDetectorFacts(detector(tool, args));
30
+ }
31
+ catch (error) {
32
+ failures++;
33
+ if (error instanceof DetectorWorkerUnavailable || failures >= 3) {
34
+ detector?.dispose?.();
35
+ detector = undefined;
36
+ }
37
+ return undefined;
38
+ }
39
+ }
40
+ /**
41
+ * Fact names a detector may never produce, in any letter case. The engine keeps
42
+ * call arguments spelled so away from detectors (actionPolicyEngine
43
+ * inferToolContext): an argument NAME must never fail a detector's result.
44
+ */
45
+ function detectorRejectsFactName(key) {
46
+ return /^(?:__proto__|constructor|prototype|verdict|decision|approval)$/i.test(key);
47
+ }
48
+ /** Shared validation for smoke tests and every actual inference result. */
49
+ function validateDetectorFacts(result) {
50
+ if (!result || typeof result.operation !== 'string' || !result.operation || result.operation.length > 100
51
+ || !result.context || typeof result.context !== 'object' || Array.isArray(result.context))
52
+ throw new Error('Invalid detector result');
53
+ const entries = Object.entries(result.context);
54
+ if (entries.length > 200 || entries.some(([key, value]) => key.length > 160 || typeof value !== 'string' || value.length > 100000
55
+ || detectorRejectsFactName(key)))
56
+ throw new Error('Invalid detector facts');
57
+ return { operation: result.operation, context: Object.fromEntries(entries) };
58
+ }
@@ -0,0 +1,406 @@
1
+ export type DeterministicDirection = 'request' | 'response';
2
+ export type DeterministicCategory = 'sensitive_file' | 'metadata_ssrf' | 'credential_command' | 'destructive_command' | 'destructive_sql' | 'infra_destroy' | 'reverse_shell' | 'secret_exfiltration' | 'remote_control' | 'honeypot' | 'agent_guard_tamper';
3
+ /**
4
+ * Per-rule enforcement action (org-configured, shipped in the Local Safety
5
+ * snapshot). Absent everywhere = 'block' — the only behavior older CLIs and
6
+ * older snapshots know, so mixed fleets stay fail-strict.
7
+ * - 'block' — stop the action (today's behavior).
8
+ * - 'warn' — let the action proceed; surface + report the finding as a warning.
9
+ * - 'mask' — redact the matched secret where the surface can rewrite content
10
+ * (MCP tool responses); surfaces that cannot rewrite treat it as block.
11
+ * - 'ask' — the developer's IDE shows its Allow / Deny prompt (the same
12
+ * self-confirmation flow as an Action Policy "Ask the developer"). Where
13
+ * nobody can answer — CI / ephemeral machines, the MCP gateway, prompt
14
+ * events, shell wrappers — it is block. Never a silent allow.
15
+ */
16
+ export type LocalSafetyRuleAction = 'block' | 'warn' | 'mask' | 'ask';
17
+ /** Whitelist for values that arrive from a snapshot; anything else is unknown → caller defaults to block. */
18
+ export declare function toLocalSafetyRuleAction(value: unknown): LocalSafetyRuleAction | undefined;
19
+ export interface DeterministicFinding {
20
+ blocked: true;
21
+ ruleId: string;
22
+ category: DeterministicCategory;
23
+ categoryId: string;
24
+ itemId: string;
25
+ source: 'builtin' | 'custom';
26
+ reason: string;
27
+ evidence: string;
28
+ explanation?: string;
29
+ policyHash?: string;
30
+ /** Org-configured enforcement action for the matched rule. Absent = 'block'. */
31
+ action?: LocalSafetyRuleAction;
32
+ /**
33
+ * The exact matched secret string, present only for secret_exfiltration
34
+ * findings — the seam 'mask' uses to redact tool responses. Never spooled.
35
+ */
36
+ matchedSecret?: string;
37
+ /** Catalog facts for remote_control findings (bridge id, mode, launcher) — no argument text. */
38
+ remoteControl?: RemoteControlFacts;
39
+ }
40
+ export interface LocalSafetyCustomBlock {
41
+ id: string;
42
+ categoryId: string;
43
+ pattern: string;
44
+ explanation?: string;
45
+ /** Absent = 'block'. */
46
+ action?: LocalSafetyRuleAction;
47
+ }
48
+ export interface LocalSafetyScanOptions {
49
+ disabledBuiltInItemIds?: string[];
50
+ /** Built-in items with a NON-default action (absent item = 'block'). */
51
+ itemActions?: Record<string, LocalSafetyRuleAction>;
52
+ /**
53
+ * Whether an actual Local Safety snapshot was resolved for this scan. When
54
+ * explicitly `false` (cold cache / wiped file / fetch failed with nothing on
55
+ * disk) the guard must NOT hard-block on the catalog default — it mirrors the
56
+ * server's warn-first gate for unarmed machines. `undefined` preserves the
57
+ * legacy "absent item = block" contract for callers that don't set it.
58
+ */
59
+ snapshotPresent?: boolean;
60
+ /** Captured transport identity, separate from untrusted tool argument data. */
61
+ mcpServerName?: string;
62
+ customBlocks?: LocalSafetyCustomBlock[];
63
+ policyHash?: string;
64
+ cwd?: string;
65
+ inspectScripts?: boolean;
66
+ /**
67
+ * The write target is a script that an already-approved delayed or background
68
+ * shell command will still run (deferredRunWindowMs). Its content was read at
69
+ * approval; the content written now is judged as that script.
70
+ */
71
+ scriptRunPending?: boolean;
72
+ /** Absolute paths of planted honeypot decoy files — ANY reference blocks. */
73
+ honeypotPaths?: string[];
74
+ /**
75
+ * Org-managed trusted script paths (substring match on the normalized path).
76
+ * Content scanning is skipped for referenced scripts under these paths — the
77
+ * admin-controlled exception for repos whose test suites legitimately contain
78
+ * attack fixtures (security tooling, guard regression tests).
79
+ */
80
+ trustedScriptPaths?: string[];
81
+ /**
82
+ * ProductCodes (`{GUID}`) of the installed FullCourtDefense MSI, recorded on
83
+ * this machine by the daemon from the uninstall registry key. The code changes
84
+ * with every build, so `msiexec /x {GUID}` is ours only when it is listed here.
85
+ */
86
+ fcdProductCodes?: string[];
87
+ /**
88
+ * The installation this check runs from (`msi`: the bundled runtime in the
89
+ * install folder, `npm`: the global package). With `fcdProductCodes` it says
90
+ * whether removing one installation leaves another protecting the machine —
91
+ * the tamper explanation's words only, never the decision. Absent: unknown.
92
+ */
93
+ fcdActiveInstall?: 'msi' | 'npm';
94
+ /**
95
+ * A best-effort scanner (GuardScanner) threw. Returning true contains the
96
+ * failure: that scanner adds nothing to this scan, and every other Local
97
+ * Safety rule still decides (the caller records the failure and lets its
98
+ * action policies decide after the guard). Absent, returning false (a
99
+ * fail-closed machine) or throwing itself: the error propagates to the
100
+ * caller's crash handling, as before.
101
+ */
102
+ onScannerError?: (scanner: GuardScanner, error: unknown) => boolean;
103
+ }
104
+ /**
105
+ * Scanners that only ADD a reason to stop an action and are never its only
106
+ * check: the content of a script the shell line runs (`inspectScripts`), and
107
+ * the content written into a script an approved delayed command will still
108
+ * run (`scriptRunPending`). A throw in one must not take the rest of the
109
+ * evaluation with it (LocalSafetyScanOptions.onScannerError).
110
+ */
111
+ export type GuardScanner = 'referenced_script' | 'pending_script_write';
112
+ /**
113
+ * Built-ins that ship OFF until an org switches them on in the console. Shared
114
+ * with the terminal guards so a machine with no snapshot yet (fresh install,
115
+ * wiped cache) enforces the SAME default set in the IDE and in a shell.
116
+ */
117
+ export declare const DEFAULT_DISABLED_BUILT_INS: ReadonlySet<string>;
118
+ /**
119
+ * NS-01 — OVERSIZE ACTIONS (owner decision; interim default of 2026-10-09).
120
+ * The most text one action may hand to the analysis: the strings the Local
121
+ * Safety guard reads as a command, a path or request, outbound data or SQL —
122
+ * not inert content such as the body of a local file write or edit, which is
123
+ * never analysed that way. Every pass over a command (execution view,
124
+ * de-obfuscated variants, script and tamper views, the policy engine's shell
125
+ * reading) grows with its length: 64 KiB takes ~70 ms of evaluation on a fast
126
+ * laptop, 1 MiB 1.7 s and ~170 MB, 4 MiB 12-37 s and ~1 GB (never-stuck
127
+ * matrix NS-01). Past the limit the action is NOT analysed at all
128
+ * (oversizedAction):
129
+ * enforce -> blocked: "too large to check safely within the time limit;
130
+ * split the command or ask your admin";
131
+ * monitor -> allowed and recorded "not fully analysed (too large)".
132
+ * Up to the limit a command is analysed in full: a command longer than one
133
+ * variant (VARIANT_MAX_CHARS) is matched statement chunk by statement chunk
134
+ * (commandChunks). Before, every command rule skipped a command over 8000
135
+ * characters — padding hid a destructive command. One constant for every
136
+ * surface (IDE hooks, the daemon, the MCP gateway) and the console's simulator
137
+ * (the backend twin of this file).
138
+ */
139
+ export declare const MAX_ANALYSED_ACTION_CHARS: number;
140
+ /**
141
+ * One command rule shared by EVERY surface that can see a typed command: the
142
+ * IDE/agent hooks (this module), the PowerShell / bash / zsh profile guards and
143
+ * the cmd.exe doskey guard (shellGuard.ts loads this table into the terminal
144
+ * rule file verbatim). `pattern` is a regex SOURCE that must compile — and
145
+ * mean the same thing — under both JS and .NET with IgnoreCase: `\b`, `\s`,
146
+ * `(?:…)`, lookaheads and `[^\n;|&]` only. No lookbehind, no named groups,
147
+ * no `\d`-class differences. `commands` are the leading binaries a rule can
148
+ * fire on — the only thing a first-token hook (doskey) can key on.
149
+ */
150
+ export interface SharedCommandRule {
151
+ itemId: string;
152
+ /** Catalog category id (local-safety-catalog.ts). */
153
+ categoryId: 'credential_commands' | 'remote_control';
154
+ severity: 'critical' | 'high' | 'medium' | 'low';
155
+ pattern: string;
156
+ reason: string;
157
+ /** Leading command names this rule anchors on (for name-keyed hooks such as cmd.exe doskey). */
158
+ commands: string[];
159
+ }
160
+ /**
161
+ * Commands that PRINT stored credentials to stdout — the file-path rules are
162
+ * useless against them because the secret never comes from a watched file
163
+ * ("gh auth token" emits the same token that lives in hosts.yml). Obvious,
164
+ * rarely-legitimate-for-agents forms are on by default; cloud token printers
165
+ * that legitimate deploy tooling uses constantly are strict (warn by default,
166
+ * see DEFAULT_WARN_BUILT_INS). Ids match local-safety-catalog.ts.
167
+ */
168
+ export declare const CREDENTIAL_COMMAND_RULES: readonly SharedCommandRule[];
169
+ export declare const REMOTE_CONTROL_CATALOG_VERSION = "2026-09-26.1";
170
+ export interface RemoteControlFacts {
171
+ /** Catalog entry id. */
172
+ bridge: string;
173
+ /** Catalog mode label: 'remote' | 'serve' | 'connect'. */
174
+ mode: string;
175
+ /** How it was started: 'npx', 'npm exec', 'pnpm dlx', …, or 'direct' for an installed binary. */
176
+ launcher: string;
177
+ }
178
+ export interface RemoteControlBridge {
179
+ id: string;
180
+ title: string;
181
+ kind: 'remote_control' | 'remote_connector';
182
+ /** Registry package names (npm / PyPI), as typed after a launcher. */
183
+ packages: string[];
184
+ /** Executable names when installed globally or run from node_modules/.bin. */
185
+ bins: string[];
186
+ mode: 'remote' | 'serve' | 'connect';
187
+ /** Regex source applied right after the package token (JS + .NET, IgnoreCase). */
188
+ modePattern: string;
189
+ /** Short label for the console and evidence. */
190
+ label: string;
191
+ /** Decision Card sentence — what starting it means, in plain words. */
192
+ card: string;
193
+ }
194
+ export declare const REMOTE_CONTROL_BRIDGES: readonly RemoteControlBridge[];
195
+ /** The positional pattern for one catalog entry: program at a statement start, package, then its mode. */
196
+ export declare function remoteControlBridgePattern(bridge: RemoteControlBridge): string;
197
+ /** Shared command rules for the terminal guards: one per remote-control entry, same Local Safety item. */
198
+ export declare const REMOTE_CONTROL_COMMAND_RULES: readonly SharedCommandRule[];
199
+ export interface RemoteControlMatch {
200
+ bridge: RemoteControlBridge;
201
+ facts: RemoteControlFacts;
202
+ }
203
+ /** A shell line that starts a remote-control bridge (any statement, any de-obfuscated variant). */
204
+ export declare function remoteControlBridgeInCommand(command: string): RemoteControlMatch | undefined;
205
+ /**
206
+ * An MCP server launch (config `command` + `args`) that is a catalogued bridge:
207
+ * a remote-control bridge first, else a remote connector. Arguments with
208
+ * spaces are re-quoted so a `--stdio "npx server"` value stays one argument.
209
+ */
210
+ export declare function classifyRemoteMcpLaunch(command: string | undefined, args?: readonly string[]): RemoteControlMatch | undefined;
211
+ /** Wire-supplied facts constrained to the catalog vocabulary (backend ingest); anything else is dropped. */
212
+ export declare function sanitizeRemoteControlFacts(raw: unknown): RemoteControlFacts | undefined;
213
+ /** The engine fact provider: the catalog id of the remote-control bridge this line starts. */
214
+ export declare function remoteControlFactFor(command: string): string | undefined;
215
+ /** What an "Always allow" on a bridge is bound to: the package and its mode, never the launcher that ran it. */
216
+ export declare function remoteControlGrantKey(bridge: RemoteControlBridge): string;
217
+ /**
218
+ * Every distinct remote-control bridge a line starts (as grant keys), plus the
219
+ * line with each verbatim launch cut out — statement separators kept — so the
220
+ * caller can still read the OTHER programs on the line. A launch seen only in a
221
+ * de-obfuscated variant is not cut: the rest is over-counted, never under-counted.
222
+ */
223
+ export declare function remoteControlLaunches(command: string): {
224
+ bridges: string[];
225
+ rest: string;
226
+ };
227
+ export type ShellAstMode = 'off' | 'shadow' | 'primary';
228
+ /** Structural subset of shellAst.ts ShellFacts that the guard reads. */
229
+ export interface ShellAstFactsLike {
230
+ complete: boolean;
231
+ incompleteReason?: string;
232
+ dynamicExecution?: boolean;
233
+ commands: Array<{
234
+ name: string;
235
+ argv: string[];
236
+ literal: boolean[];
237
+ cwdScope: 'scoped' | 'unscoped' | 'unknown';
238
+ wrapper?: {
239
+ kind: string;
240
+ program: string;
241
+ inner?: ShellAstFactsLike;
242
+ };
243
+ }>;
244
+ }
245
+ export interface ShellAstComparison {
246
+ mode: ShellAstMode;
247
+ complete: boolean;
248
+ /** Destructive-rm item id the regex floor produced (undefined = clean). */
249
+ regex?: string;
250
+ /** Destructive-rm item id the AST produced (undefined = clean). */
251
+ ast?: string;
252
+ agree: boolean;
253
+ }
254
+ export declare function setShellAstProvider(provider: ((command: string) => ShellAstFactsLike | undefined) | undefined): void;
255
+ export declare function setShellAstMode(mode: ShellAstMode): void;
256
+ export declare function getShellAstMode(): ShellAstMode;
257
+ /** Shadow telemetry: the comparison recorded by the most recent shell scan (consumed once). */
258
+ export declare function takeShellAstComparison(): ShellAstComparison | undefined;
259
+ /**
260
+ * PowerShell line, judged on its CODE only (`unquotedCode`): a cmdlet named
261
+ * inside a commit message or issue body does not change how the shell reads it.
262
+ */
263
+ export declare function isPowerShellLine(text: string): boolean;
264
+ /**
265
+ * Code-only view of a line: each `'…'` / `"…"` / `` `…` `` span becomes a
266
+ * space. Detectors that ask "does this EXECUTE" must look here; the raw line
267
+ * still carries fixture strings and docs.
268
+ */
269
+ export declare function unquotedCode(text: string): string;
270
+ /** POSIX heredocs of a command line, in order: body span, delimiter-line end, and receiver. */
271
+ export declare function posixHeredocs(text: string): Array<{
272
+ bodyStart: number;
273
+ bodyEnd: number;
274
+ end: number;
275
+ body: string;
276
+ receiver: {
277
+ kind: 'shell' | 'language' | 'data';
278
+ program: string;
279
+ };
280
+ }>;
281
+ export declare function stripInertDataSegments(text: string): string;
282
+ /**
283
+ * What an uninstall-shaped command removes, when it is FullCourtDefense's:
284
+ * `all` = FullCourtDefense's own uninstall (hooks and service for this user),
285
+ * `npm` / `msi` = that installation, `tasks` / `processes` = its scheduled tasks
286
+ * or running processes, `machine_state` = `ProgramData\FullCourtDefense`.
287
+ */
288
+ type FcdRemovalKind = 'all' | 'npm' | 'msi' | 'tasks' | 'processes' | 'machine_state' | 'always_on';
289
+ /**
290
+ * What a tamper finding touches — the explanation names the installation or the
291
+ * files it affects and whether protection stays on (never "switches off the
292
+ * protection" when another installation keeps protecting the machine).
293
+ */
294
+ type TamperTarget = 'hooks_off' | 'hook_config' | 'env_keys' | 'node_options' | FcdRemovalKind | 'user_state';
295
+ interface TamperHit {
296
+ itemId: string;
297
+ reason: string;
298
+ target: TamperTarget;
299
+ verb?: 'delete' | 'move' | 'change';
300
+ }
301
+ /**
302
+ * The finding's sentence: what the action touches, which installation, and
303
+ * whether protection stays on. `fcdProductCodes` (an MSI installation recorded on
304
+ * this machine) and `fcdActiveInstall` (the installation this check runs from)
305
+ * say whether another installation keeps protecting the machine; without them
306
+ * (the backend twin, an older snapshot) the sentence says what it depends on.
307
+ */
308
+ export declare function tamperFindingReason(hit: Pick<TamperHit, 'target' | 'reason' | 'verb'>, options?: Pick<LocalSafetyScanOptions, 'fcdProductCodes' | 'fcdActiveInstall'>): string;
309
+ export declare function scanDeterministicToolCall(toolName: string, toolArgs: Record<string, unknown>, options?: LocalSafetyScanOptions): DeterministicFinding | undefined;
310
+ export interface OversizedAction {
311
+ /** Characters of analysed text in the action. */
312
+ chars: number;
313
+ /** MAX_ANALYSED_ACTION_CHARS. */
314
+ limit: number;
315
+ /** The argument holding most of it (`args.command`). */
316
+ field: string;
317
+ }
318
+ /**
319
+ * The action's analysed text when it is longer in total than
320
+ * MAX_ANALYSED_ACTION_CHARS (see above), else undefined. Linear and cheap:
321
+ * callers run it before any other analysis of the action.
322
+ */
323
+ export declare function oversizedAction(toolName: string, toolArgs: Record<string, unknown>, options?: Pick<LocalSafetyScanOptions, 'mcpServerName'>): OversizedAction | undefined;
324
+ /** What every surface says and records for an oversize action (NS-01). `what`: "command", "tool call", … */
325
+ export declare function oversizeWording(oversize: OversizedAction, what: string): {
326
+ ruleId: string;
327
+ blockedRecord: string;
328
+ monitorRecord: string;
329
+ userMessage: string;
330
+ agentMessage: string;
331
+ };
332
+ export declare function scanDeterministicTextResponse(text: string, options?: LocalSafetyScanOptions): DeterministicFinding | undefined;
333
+ /**
334
+ * Prompt (chat text) scan. A prompt is TEXT, not an action: the only thing that
335
+ * can leave the machine through it is what is literally in it. So the prompt
336
+ * path decides on exactly two things:
337
+ * 1. an explicit org custom block, and
338
+ * 2. a real secret VALUE pasted into the prompt (with send intent, or next to
339
+ * credential wording — once it is in agent context it can leak anywhere).
340
+ *
341
+ * Mentioning a command (`gh auth token`, `rm -rf /`, `kubectl config view --raw`),
342
+ * a sensitive path or a metadata IP is NOT judged here. Those are ACTIONS and
343
+ * are decided when they happen — beforeShellExecution / file read / MCP call —
344
+ * where the developer's "Ask" answer can actually be collected and the target,
345
+ * cwd and actor are real. A prompt hook has no Allow / Deny to offer, so a rule
346
+ * set to Ask could only degrade to a block here, and a developer asking how a
347
+ * command works would be stopped for typing its name. (action-only decision path)
348
+ */
349
+ export declare function scanDeterministicPrompt(text: string, options?: LocalSafetyScanOptions): DeterministicFinding | undefined;
350
+ export declare function referencedScripts(command: string, cwd?: string): string[];
351
+ /**
352
+ * How long after approval a shell command may still run a script it references:
353
+ * 0 when it runs now in the foreground, else the parsed delay plus a base window
354
+ * (capped). Deferred = a delay program (`sleep`, `Start-Sleep`, cmd `timeout /t`)
355
+ * or a background program (`nohup`, cmd `start`, `Start-Process`) at a command
356
+ * start, or a background `&`. Such a script is read when it runs, not when the
357
+ * hook read it at approval.
358
+ */
359
+ export declare function deferredRunWindowMs(command: string): number;
360
+ export interface DeterministicScanOutcome {
361
+ /** The finding that stops the action, if any. */
362
+ blockingFinding?: DeterministicFinding;
363
+ /**
364
+ * The first ask-action finding, when NO block rule also matched. The surface
365
+ * decides what "ask" means for it: the IDE hook raises the developer's own
366
+ * Allow / Deny prompt; every surface that cannot ask (MCP gateway, prompt
367
+ * events, shell wrappers, no human present) treats it exactly as a block.
368
+ */
369
+ askFinding?: DeterministicFinding;
370
+ /** Every matching approval obligation, retained for diagnostics and tests. */
371
+ askFindings?: DeterministicFinding[];
372
+ /** warn-action findings that matched — the action proceeds; report these. */
373
+ warnings: DeterministicFinding[];
374
+ }
375
+ export interface DeterministicTextResponseOutcome extends DeterministicScanOutcome {
376
+ /** mask-action secret findings that WERE redacted from the text. */
377
+ maskFindings: DeterministicFinding[];
378
+ /** The response text with every masked secret redacted. */
379
+ maskedText: string;
380
+ }
381
+ /**
382
+ * Resolve a scan under per-rule actions WITHOUT letting a warn rule shadow a
383
+ * block rule. Scans return the FIRST match, so a single pass would let one
384
+ * warn-mode rule hide a second, block-mode rule matching the same value. This
385
+ * re-scans with each warn rule suppressed until a blocking finding surfaces or
386
+ * nothing matches. Default (no itemActions configured) is a single pass
387
+ * returning today's behavior exactly.
388
+ *
389
+ * 'mask' degrades to block here: these surfaces (tool calls, prompts, shell
390
+ * commands) cannot rewrite content, so mask can only fail strict.
391
+ *
392
+ * 'ask' is likewise suppressed and re-scanned, so a block rule hiding behind
393
+ * an ask rule still wins; only when nothing blocks is the first ask finding
394
+ * returned for the surface to raise (IDE) or fail strict (everything else).
395
+ */
396
+ export declare function resolveDeterministicOutcome(scan: (options?: LocalSafetyScanOptions) => DeterministicFinding | undefined, options?: LocalSafetyScanOptions): DeterministicScanOutcome;
397
+ /**
398
+ * Resolve a TOOL RESPONSE under per-rule actions. The response is the one
399
+ * surface that can be rewritten, so 'mask' redacts here: each masked secret is
400
+ * replaced in the text and the REDACTED text is rescanned — a second secret of
401
+ * the same type is still found (rule suppression would hide it). Warn rules
402
+ * are suppressed as in resolveDeterministicOutcome. Any 'block' rule match
403
+ * blocks regardless of what was masked before it.
404
+ */
405
+ export declare function resolveDeterministicTextResponse(text: string, options?: LocalSafetyScanOptions): DeterministicTextResponseOutcome;
406
+ export {};