dsh-cmd-guard 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,260 @@
1
+ import { effectiveTokens } from './normalize.js';
2
+ const MUTATING_VERBS = new Set([
3
+ 'del',
4
+ 'erase',
5
+ 'rd',
6
+ 'rmdir',
7
+ 'rm',
8
+ 'mv',
9
+ 'move',
10
+ 'copy',
11
+ 'xcopy',
12
+ 'robocopy',
13
+ 'ren',
14
+ 'rename',
15
+ 'mkdir',
16
+ 'md',
17
+ 'attrib',
18
+ 'icacls',
19
+ 'takeown',
20
+ 'reg',
21
+ 'sc',
22
+ 'net',
23
+ 'taskkill',
24
+ 'setx',
25
+ 'wmic',
26
+ 'diskpart',
27
+ 'bcdedit',
28
+ 'schtasks',
29
+ 'netsh',
30
+ 'cipher',
31
+ ]);
32
+ /**
33
+ * Read-only subcommands of tools that also mutate.
34
+ *
35
+ * `reg` and `sc` sit in MUTATING_VERBS whole, so `reg query` and
36
+ * `sc query` demanded an intent statement for a read. Measured as a false
37
+ * ask: with no approval UI composed, ask degrades to deny, and the tool
38
+ * becomes unusable for the one thing it is best at - inspection.
39
+ */
40
+ const READ_ONLY_SUB = new Map([
41
+ ['reg', new Set(['query', 'export', 'compare'])],
42
+ [
43
+ 'sc',
44
+ new Set([
45
+ 'query',
46
+ 'queryex',
47
+ 'qc',
48
+ 'qdescription',
49
+ 'qfailure',
50
+ 'qfailureflag',
51
+ 'qprivs',
52
+ 'qsidtype',
53
+ 'qtriggerinfo',
54
+ 'querier',
55
+ 'getdisplayname',
56
+ 'getkeyname',
57
+ 'enumdepend',
58
+ 'interrogate',
59
+ 'sdshow',
60
+ ]),
61
+ ],
62
+ // `wmic os get caption` puts the verb third: the second token is the alias.
63
+ // Reading only tokens[1] made a read demand an intent statement, and then
64
+ // read that statement as a contradiction with the command.
65
+ ['wmic', new Set(['get', 'list', 'status', 'apath'])],
66
+ ]);
67
+ /** Does this invocation only read state the tool is otherwise able to change? */
68
+ function isReadOnlySubcommand(head, tokens) {
69
+ const allowed = READ_ONLY_SUB.get(head);
70
+ if (allowed === undefined)
71
+ return false;
72
+ // wmic spells the verb after an alias (`os get caption`), so any token
73
+ // may be the read-only verb. Judging tokens[1] alone saw 'os'.
74
+ if (head === 'wmic')
75
+ return tokens.some((t) => allowed.has(t.toLowerCase()));
76
+ const sub = (tokens[1] ?? '').toLowerCase();
77
+ return allowed.has(sub);
78
+ }
79
+ const HOST_CONTROL = new Set(['shutdown', 'restart', 'logoff']);
80
+ /** A reason shorter than this is a placeholder, not a reason. */
81
+ const MIN_WHY_LENGTH = 8;
82
+ /**
83
+ * Statements that pass a non-empty check and say nothing. Kept as exact
84
+ * matches after normalisation: "test the parser against the corpus" must not
85
+ * be caught by a substring match on "test".
86
+ */
87
+ const PLACEHOLDERS = new Set([
88
+ 'run',
89
+ 'run it',
90
+ 'run command',
91
+ 'run the command',
92
+ 'run this',
93
+ 'run this command',
94
+ 'execute',
95
+ 'execute it',
96
+ 'execute command',
97
+ 'execute the command',
98
+ 'command',
99
+ 'cmd',
100
+ 'do it',
101
+ 'do the thing',
102
+ 'test',
103
+ 'testing',
104
+ 'try',
105
+ 'fix',
106
+ 'fix it',
107
+ 'update',
108
+ 'update it',
109
+ 'change',
110
+ 'changes',
111
+ 'cleanup',
112
+ 'clean up',
113
+ 'misc',
114
+ 'todo',
115
+ 'n a',
116
+ 'na',
117
+ 'none',
118
+ 'as requested',
119
+ 'as asked',
120
+ 'per instructions',
121
+ 'because',
122
+ 'needed',
123
+ 'required',
124
+ 'no reason',
125
+ 'same as before',
126
+ 'see above',
127
+ ]);
128
+ /** Words that only make sense for a read. */
129
+ const READONLY_CLAIM = /\b(read|reads|view|views|list|lists|listing|show|shows|inspect|inspects|check|checks|print|prints|display|displays|cat|look|looking|examine|examines|verify|verifies|review|reviews|report|reports|scan|scans|monitor|query|queries)\b/;
130
+ /** Words that admit to changing something. */
131
+ const MUTATION_WORD = /\b(delete|deletes|deleting|remove|removes|removing|wipe|wipes|wipe|overwrite|overwrites|erase|erases|force|forces|reset|resets|drop|drops|purge|purges|install|installs|uninstall|uninstalls|rewrite|rewrites|replace|replaces|clean|cleans|prune|prunes)\b/;
132
+ function normalize(s) {
133
+ return s
134
+ .toLowerCase()
135
+ .replace(/[^\p{L}\p{N}\s]/gu, ' ')
136
+ .replace(/\s+/g, ' ')
137
+ .trim();
138
+ }
139
+ function isGlobalInstall(tokens) {
140
+ const head = tokens[0]?.toLowerCase();
141
+ const second = tokens[1]?.toLowerCase();
142
+ const lowered = tokens.map((t) => t.toLowerCase());
143
+ if (head === 'npm' && (second === 'i' || second === 'install') && lowered.includes('-g'))
144
+ return true;
145
+ if (head === 'yarn' && second === 'global')
146
+ return true;
147
+ if (head === 'pnpm' && second === 'add' && lowered.includes('-g'))
148
+ return true;
149
+ return false;
150
+ }
151
+ /**
152
+ * Git subcommands that rewrite or discard history. These are legitimate often
153
+ * enough that denying them would be wrong, and destructive enough that running
154
+ * them silently is worse. That combination is exactly what this layer is for.
155
+ */
156
+ function isHistoryRewrite(tokens) {
157
+ if (tokens[0]?.toLowerCase() !== 'git')
158
+ return false;
159
+ const sub = tokens[1]?.toLowerCase();
160
+ const rest = tokens.slice(2).map((t) => t.toLowerCase());
161
+ if (sub === 'push') {
162
+ return rest.some((t) => t === '--force' || t === '-f' || t === '--force-with-lease' || t.startsWith('--force-with-lease='));
163
+ }
164
+ if (sub === 'reset')
165
+ return rest.includes('--hard');
166
+ if (sub === 'clean')
167
+ return rest.some((t) => /^-[a-z]*f[a-z]*$/i.test(t));
168
+ if (sub === 'branch')
169
+ return rest.some((t) => t === '-d' || t === '-D' || t === '--delete' || t === '--delete-force');
170
+ if (sub === 'checkout' || sub === 'restore')
171
+ return rest.includes('--');
172
+ return false;
173
+ }
174
+ /**
175
+ * Package publication.
176
+ *
177
+ * Not a filesystem mutation, so no verb in MUTATING_VERBS matched, and
178
+ * `npm publish` was a measured silent pass. A published version cannot be
179
+ * withdrawn from mirrors, which puts it in the same class as a history
180
+ * rewrite: legitimate often enough to allow, destructive enough that
181
+ * running it without a stated reason is worse.
182
+ */
183
+ function isPublish(tokens) {
184
+ const head = tokens[0]?.toLowerCase();
185
+ const sub = tokens[1]?.toLowerCase();
186
+ if (head === 'npm' && (sub === 'publish' || sub === 'unpublish'))
187
+ return true;
188
+ if ((head === 'yarn' || head === 'pnpm') && sub === 'publish')
189
+ return true;
190
+ if (head === 'twine' && sub === 'upload')
191
+ return true;
192
+ return false;
193
+ }
194
+ /**
195
+ * Removals a later step cannot undo.
196
+ *
197
+ * The stated reason unlocks an ask by design: a recoverable delete with a real
198
+ * intent behind it is ordinary work. That trade is wrong for removals with no
199
+ * recovery path, because the model writes its own reason and a well-phrased
200
+ * one is then a bypass. Measured: `rm -rf ~` and `git clean -xfd` both
201
+ * passed with a fluent why.
202
+ */
203
+ function isIrrecoverableRemoval(tokens) {
204
+ const head = tokens[0]?.toLowerCase();
205
+ const rest = tokens.slice(1).map((t) => t.toLowerCase());
206
+ if (head === 'git') {
207
+ const sub = rest[0];
208
+ const args = rest.slice(1);
209
+ if (sub === 'clean' && args.some((t) => /^-[a-z]*f/i.test(t)))
210
+ return true;
211
+ if (sub === 'reset' && args.includes('--hard'))
212
+ return true;
213
+ return false;
214
+ }
215
+ const removes = head === 'rm' || head === 'rd' || head === 'rmdir' || head === 'del' || head === 'erase';
216
+ if (!removes)
217
+ return false;
218
+ const recursive = rest.some((t) => /^-[a-z]*r/i.test(t) || t === '/s' || t === '-recurse');
219
+ const home = rest.some((t) => t === '~' || t === '$home' || t === '%userprofile%' || /^\/(?:root|home)(?:\/|$)/.test(t));
220
+ return recursive && home;
221
+ }
222
+ function ask(code, reason) {
223
+ return { layer: 'why', verdict: 'ask', code, reason };
224
+ }
225
+ export function check(input, _state) {
226
+ const tokens = effectiveTokens(input.cmd);
227
+ const head = tokens[0]?.toLowerCase();
228
+ if (head === undefined)
229
+ return null;
230
+ const needsWhy = (MUTATING_VERBS.has(head) && !isReadOnlySubcommand(head, tokens)) ||
231
+ HOST_CONTROL.has(head) ||
232
+ isGlobalInstall(tokens) ||
233
+ isHistoryRewrite(tokens) ||
234
+ isPublish(tokens);
235
+ if (!needsWhy)
236
+ return null;
237
+ if (isIrrecoverableRemoval(tokens)) {
238
+ return ask('WHY_IRRECOVERABLE', `"${head}" removes data a later step cannot restore. A stated reason unlocks a recoverable delete; it cannot unlock this one.`);
239
+ }
240
+ const why = (input.why ?? '').trim();
241
+ if (why.length === 0) {
242
+ return ask('WHY_MISSING', `"${head}" changes state on disk, in the registry, in history, or on the host. State why before it runs.`);
243
+ }
244
+ if (why.length < MIN_WHY_LENGTH) {
245
+ return ask('WHY_TOO_SHORT', `The stated reason is ${why.length} characters. A placeholder is not an intent statement.`);
246
+ }
247
+ const stated = normalize(why);
248
+ if (PLACEHOLDERS.has(stated)) {
249
+ return ask('WHY_GENERIC', `"${why}" names the act, not a goal. A non-empty description is already required by the tool schema, so passing that bar proves nothing.`);
250
+ }
251
+ // The description carries no information the command string did not already
252
+ // carry. It satisfies the schema and answers nothing.
253
+ if (stated.length > 0 && normalize(input.cmd).includes(stated)) {
254
+ return ask('WHY_RESTATES_COMMAND', `The stated reason is contained in the command itself ("${why}"). Restating the command is not a statement of purpose.`);
255
+ }
256
+ if (READONLY_CLAIM.test(stated) && !MUTATION_WORD.test(stated)) {
257
+ return ask('WHY_CONTRADICTS', `The stated reason describes reading, but "${head}" changes state. Either the description is wrong or the command is not what it claims.`);
258
+ }
259
+ return null;
260
+ }
@@ -0,0 +1,32 @@
1
+ export declare const name = "dsh-cmd-guard";
2
+ /** ctx.tools for the hard-deny mount; the waterfall events arrive via ctx.on. */
3
+ export declare const inject: readonly ["tools"];
4
+ export interface CmdGuardConfig {
5
+ guard?: {
6
+ enabled?: boolean;
7
+ /** Absolute root used for path provenance. Defaults to the process cwd. */
8
+ workspaceRoot?: string;
9
+ /**
10
+ * Track files written earlier in the session so write-then-run is not
11
+ * judged as two unrelated calls. On by default: the TOCTOU hole is wide
12
+ * open otherwise, and this listener only observes.
13
+ */
14
+ recordWrites?: boolean;
15
+ };
16
+ changeset?: {
17
+ /** Accepted by the config, not implemented. Enabling it logs a warning. */
18
+ enabled?: boolean;
19
+ ledgerDir?: string;
20
+ };
21
+ }
22
+ /**
23
+ * Did this call fail? The ledger exists to prove "this path now holds content
24
+ * I just wrote". A failed write proves nothing, and recording it produced a
25
+ * false INTERP_RECENT_WRITE on the next legitimate run of that path.
26
+ */
27
+ export declare function isFailedResult(result: unknown): boolean;
28
+ /**
29
+ * Mount point. Deliberately does no parsing itself: guard/ owns the analysis,
30
+ * changeset/ owns the bookkeeping.
31
+ */
32
+ export declare function apply(ctx: any, raw?: CmdGuardConfig): void;
@@ -0,0 +1,162 @@
1
+ import { verify } from './guard/verify.js';
2
+ import { isPreToolDecision, toDecision, toGuardInput, toHardDeny } from './guard/mount.js';
3
+ export const name = 'dsh-cmd-guard';
4
+ /** ctx.tools for the hard-deny mount; the waterfall events arrive via ctx.on. */
5
+ export const inject = ['tools'];
6
+ const DEFAULTS = {
7
+ guard: { enabled: true, recordWrites: true },
8
+ changeset: { enabled: false },
9
+ };
10
+ /** Tools whose written path feeds the TOCTOU rule. */
11
+ const WRITE_TOOLS = new Set([
12
+ 'write_file',
13
+ 'writefile',
14
+ 'create_file',
15
+ 'edit_file',
16
+ 'apply_patch',
17
+ 'str_replace_editor',
18
+ 'multiedit',
19
+ ]);
20
+ const PATH_KEYS = ['filepath', 'file_path', 'path', 'file', 'target'];
21
+ /** Bounded so a long session cannot grow the ledger without limit. */
22
+ const MAX_RECENT_WRITES = 256;
23
+ function resolve(raw) {
24
+ return {
25
+ guard: {
26
+ ...DEFAULTS.guard,
27
+ ...(raw.guard ?? {}),
28
+ workspaceRoot: raw.guard?.workspaceRoot ?? process.cwd(),
29
+ },
30
+ changeset: {
31
+ enabled: raw.changeset?.enabled ?? DEFAULTS.changeset.enabled,
32
+ ledgerDir: raw.changeset?.ledgerDir,
33
+ },
34
+ };
35
+ }
36
+ /**
37
+ * Log through the harness when it has a logger, fall back to the console.
38
+ * Used only for degraded-mode notices: a guard that quietly loses half its
39
+ * enforcement is the failure this package exists to prevent.
40
+ */
41
+ function warn(ctx, message) {
42
+ const logger = ctx?.logger;
43
+ if (typeof logger?.warn === 'function') {
44
+ logger.warn(message);
45
+ return;
46
+ }
47
+ console.warn(`[dsh-cmd-guard] ${message}`);
48
+ }
49
+ function asExecution(value) {
50
+ const e = value;
51
+ return { name: e?.name, arguments: e?.arguments };
52
+ }
53
+ /**
54
+ * Did this call fail? The ledger exists to prove "this path now holds content
55
+ * I just wrote". A failed write proves nothing, and recording it produced a
56
+ * false INTERP_RECENT_WRITE on the next legitimate run of that path.
57
+ */
58
+ export function isFailedResult(result) {
59
+ if (result instanceof Error)
60
+ return true;
61
+ if (typeof result !== 'object' || result === null)
62
+ return false;
63
+ const r = result;
64
+ if (r.isError === true)
65
+ return true;
66
+ if (r.ok === false)
67
+ return true;
68
+ if (r.error !== undefined && r.error !== null)
69
+ return true;
70
+ return false;
71
+ }
72
+ function recordWrite(ledger, exec) {
73
+ if (typeof exec.name !== 'string' || !WRITE_TOOLS.has(exec.name.toLowerCase()))
74
+ return;
75
+ const args = typeof exec.arguments === 'object' && exec.arguments !== null
76
+ ? exec.arguments
77
+ : {};
78
+ for (const key of PATH_KEYS) {
79
+ const v = args[key];
80
+ if (typeof v !== 'string' || v.trim().length === 0)
81
+ continue;
82
+ ledger.push(v);
83
+ if (ledger.length > MAX_RECENT_WRITES)
84
+ ledger.shift();
85
+ return;
86
+ }
87
+ }
88
+ /**
89
+ * Mount point. Deliberately does no parsing itself: guard/ owns the analysis,
90
+ * changeset/ owns the bookkeeping.
91
+ */
92
+ export function apply(ctx, raw = {}) {
93
+ const cfg = resolve(raw);
94
+ if (cfg.guard.enabled)
95
+ installGuard(ctx, cfg);
96
+ if (cfg.changeset.enabled)
97
+ installChangeset(ctx, cfg.changeset.ledgerDir);
98
+ }
99
+ function installGuard(ctx, cfg) {
100
+ const recentWrites = [];
101
+ const state = () => ({ workspaceRoot: cfg.guard.workspaceRoot, recentWrites });
102
+ const dispose = (off) => {
103
+ if (typeof off === 'function')
104
+ ctx.on('dispose', off);
105
+ };
106
+ // Write ledger. Observed, not intercepted: it only feeds the TOCTOU rule, so
107
+ // it must never alter a decision.
108
+ if (cfg.guard.recordWrites) {
109
+ dispose(ctx.on('tools/post-execute', async (exec, result, next) => {
110
+ if (!isFailedResult(result))
111
+ recordWrite(recentWrites, asExecution(exec));
112
+ return next();
113
+ }));
114
+ }
115
+ // Ask / deny path. Returning a decision instead of awaiting `next()` skips
116
+ // every listener mounted after this one, so a pass defers explicitly.
117
+ dispose(ctx.on('tools/pre-execute', async (exec, next) => {
118
+ const mapping = toGuardInput(asExecution(exec));
119
+ if (mapping.kind === 'skip')
120
+ return next();
121
+ const decision = toDecision(verify(mapping.input, state()));
122
+ if (decision === null)
123
+ return next();
124
+ // Fail closed on shape drift. An unrecognised decision is a gate that
125
+ // silently did nothing - the exact failure this package exists to stop.
126
+ if (!isPreToolDecision(decision)) {
127
+ return {
128
+ kind: 'deny',
129
+ reason: '[ENTRY_BAD_DECISION_SHAPE] dsh-cmd-guard produced a decision the registry would ignore; failing closed.',
130
+ };
131
+ }
132
+ return decision;
133
+ }));
134
+ // Hard-deny path. Survives approval and listener ordering because this mount
135
+ // has no allow exit at all.
136
+ if (typeof ctx.tools?.guard === 'function') {
137
+ dispose(ctx.tools.guard((exec) => {
138
+ const mapping = toGuardInput(asExecution(exec));
139
+ if (mapping.kind === 'skip')
140
+ return undefined;
141
+ return toHardDeny(verify(mapping.input, state()));
142
+ }));
143
+ }
144
+ else {
145
+ // Measured gap: without this mount the deny layer is simply absent, while
146
+ // the plugin still looks installed and active. Deny rules would only ever
147
+ // surface as ask from the waterfall, which an operator can approve.
148
+ warn(ctx, 'ctx.tools.guard is unavailable: hard-deny rules are degraded to ask. ' +
149
+ 'This build of the harness cannot enforce non-overridable denials for this plugin.');
150
+ }
151
+ }
152
+ /**
153
+ * Self-patch bookkeeping. Opt-in and off by default: it needs
154
+ * danger-full-access, and a plugin that can rewrite itself should not be
155
+ * something a user gets for free on install.
156
+ *
157
+ * Not implemented yet. Enabling it warns rather than pretending to work.
158
+ */
159
+ function installChangeset(ctx, ledgerDir) {
160
+ void ledgerDir;
161
+ warn(ctx, 'changeset module is not implemented in this version; no ledger, rollback or promotion was installed.');
162
+ }
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
- {
2
- "name": "dsh-cmd-guard",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "dsh-cmd-guard",
3
+ "version": "0.1.0",
4
+ "description": "Structural command parser for DeepSeek Harness. Eight layers read every command, the stated intent is checked against the action, and hard denies cannot be overridden.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./lib/src/index.js",
8
+ "types": "./lib/src/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./lib/src/index.d.ts",
12
+ "default": "./lib/src/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "lib/src",
17
+ "cordis.patch.yml",
18
+ "README.md",
19
+ "LICENSE"
20
+ ],
21
+ "keywords": [
22
+ "dsh-plugin",
23
+ "deepseek-harness",
24
+ "guard",
25
+ "security"
26
+ ],
27
+ "dsh": {
28
+ "bundle": {
29
+ "patch": "./cordis.patch.yml"
30
+ }
31
+ },
32
+ "peerDependencies": {
33
+ "@deepseek-ai/dsh": ">=0.2.0-0 <0.3.0"
34
+ },
35
+ "peerDependenciesMeta": {
36
+ "@deepseek-ai/dsh": {
37
+ "optional": false
38
+ }
39
+ },
40
+ "devDependencies": {
41
+ "typescript": "5.7.2",
42
+ "@types/node": "22.10.2"
43
+ },
44
+ "dependencies": {},
45
+ "engines": {
46
+ "node": ">=20.0.0"
47
+ },
48
+ "scripts": {
49
+ "clean": "node -e \"require('fs').rmSync('lib',{recursive:true,force:true})\"",
50
+ "build": "npm run clean && tsc -p tsconfig.json",
51
+ "prepare": "npm run build",
52
+ "prepublishOnly": "npm test",
53
+ "typecheck": "tsc -p tsconfig.json --noEmit",
54
+ "test": "npm run build && node --test lib/test/*.test.js"
55
+ }
56
+ }