@oked/sdk 0.1.8 → 0.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.
Files changed (2) hide show
  1. package/dist/classify.js +190 -126
  2. package/package.json +1 -1
package/dist/classify.js CHANGED
@@ -2,10 +2,25 @@ import path from "path";
2
2
  import os from "os";
3
3
  import { findSqlInCommand } from "./describe.js";
4
4
  import { TIER_ORDER } from "./degraded.js";
5
- // Tier 1 - safe: auto-allow, no notification (Read, Glob, ls, git status, etc.)
6
- // Tier 2 - warning: terminal log only, no push (Write/Edit inside project dir)
7
- // Tier 3 - review: push notification required (Write/Edit outside project, unknown bash)
8
- // Tier 4 - high_stakes: push + number matching (rm -rf, git push, DROP TABLE, etc.)
5
+ // Classification is EFFECT-BASED, not command-name-based. We don't keep an
6
+ // allowlist of "safe commands"; instead we detect the few categories of effect
7
+ // that warrant a human in the loop, and DEFAULT TO NO PROMPT for everything
8
+ // else. Running a command, reading, copying a file, a DB SELECT, or deleting a
9
+ // /tmp scratch file must never prompt — only destructive, irreversible, or
10
+ // outward-facing operations do.
11
+ //
12
+ // Tier 1 - safe: auto-allow, silent. No detected side effect (reads, queries,
13
+ // and any command we don't recognize as mutating — the default).
14
+ // Tier 2 - warning: terminal log only, no push. A reversible LOCAL mutation
15
+ // (file create/copy/move, /tmp delete, local git, install,
16
+ // code-exec, SQL INSERT/CREATE).
17
+ // Tier 3 - review: push notification, tap to approve. Prompt-worthy but not
18
+ // catastrophic: sensitive-path writes (~/.ssh, shell rc, system
19
+ // dirs, OKed's own config), sudo, outward message/email sends.
20
+ // Tier 4 - high_stakes: push + number matching. Destructive / irreversible /
21
+ // external: rm of non-temp data, DROP/TRUNCATE/DELETE FROM,
22
+ // git push / reset --hard / branch -D, mkfs / dd-to-device /
23
+ // shutdown, curl POST/DELETE, ssh/scp, npm publish, kill.
9
24
  // Tools that are always safe (read-only, no side effects)
10
25
  const SAFE_TOOLS = new Set([
11
26
  "Read",
@@ -40,80 +55,11 @@ const SAFE_TOOL_ALIASES = new Set([
40
55
  const REVIEW_TOOLS = new Set([]);
41
56
  // Tools that are always high stakes
42
57
  const HIGH_STAKES_TOOLS = new Set([]);
43
- // Bash commands classified as safe (read-only, informational)
44
- const SAFE_COMMANDS = [
45
- /^ls\b/,
46
- /^pwd$/,
47
- /^echo\b/,
48
- /^cat\b/,
49
- /^head\b/,
50
- /^tail\b/,
51
- /^wc\b/,
52
- /^date$/,
53
- /^whoami$/,
54
- /^which\b/,
55
- /^type\b/,
56
- /^file\b/,
57
- /^stat\b/,
58
- /^du\b/,
59
- /^df\b/,
60
- /^uname\b/,
61
- /^env$/,
62
- /^printenv\b/,
63
- /^node\s+(-v|--version)/,
64
- /^npm\s+(list|ls|--version|-v|view|info|outdated|audit)\b/,
65
- /^npx\s+-v/,
66
- /^git\s+(status|log|diff|branch|remote|show|tag|stash\s+list|ls-files|ls-tree|ls-remote|check-ignore|check-attr|rev-parse|rev-list|describe|cat-file|blame|shortlog|reflog|name-rev|whatchanged|for-each-ref|symbolic-ref|merge-base|var|grep|count-objects|show-ref|cherry|verify-commit|fsck)\b/,
67
- /^git\s+config\s+(--get|--get-all|--get-regexp|--list|-l)\b/,
68
- /^docker\s+(ps|images|inspect|logs)\b/,
69
- /^docker\s+compose\s+(ps|logs)\b/,
70
- /^tree\b/,
71
- /^find\b/,
72
- /^grep\b/,
73
- /^rg\b/,
74
- /^fd\b/,
75
- /^jq\b/,
76
- /^curl\s+-s.*\|\s*(jq|python|node)/, // curl piped to parser (usually read-only)
77
- /^curl\b/, // curl without -X defaults to GET (high-stakes patterns checked first)
78
- // himalaya (email CLI) read-only ops. Listing/reading mail or folder state
79
- // never mutates anything remotely. Only `message send|reply|forward` and
80
- // `message delete` / `folder delete|expunge|purge` matter; those land in
81
- // the review/high-stakes paths.
82
- /^himalaya\s+(account|folder|envelope|message\s+(?:read|export|search|copy|move)|attachment\s+(?:download|list)|template|search)\b/,
83
- // cd just changes directory — no side effect of its own. Any dangerous
84
- // command chained after it (`cd x && rm -rf`) is caught per-stage.
85
- /^cd\b/,
86
- // sed without -i / --in-place only prints to stdout (read-only). In-place
87
- // edits are detected as a write op (below) before this is reached.
88
- /^sed\b/,
89
- // gh read-only subcommands — listing/viewing PRs, issues, runs, etc.
90
- /^gh\s+(pr|issue|repo|run|workflow|release|api)\s+(list|view|status|diff|checks)\b/,
91
- // Test runners — running the project's own tests is part of the dev loop.
92
- // (Arbitrary node/npx/python execution is `warning`, see WARNING_COMMANDS.)
93
- /^npm\s+(test|t)\b/,
94
- /^npx\s+(tsx|ts-node|jest|vitest|mocha|ava|cypress|playwright|tsc)\b/,
95
- /^(jest|vitest|mocha|pytest|ava)\b/,
96
- /^python3?\s+-m\s+pytest\b/,
97
- // Shell control-flow keywords. A compound like `for f in *; do cmd; done`
98
- // is split on `;` into stages; these keyword stages carry no risk of their
99
- // own, and any real command in the body is classified per-stage. Dangerous
100
- // commands hidden in a $(...) on a keyword line are still caught by the
101
- // high-stakes scan, which runs on the full command first.
102
- /^(for|while|until|do|done|then|else|elif|fi|case|esac|if|select)\b/,
103
- /^(done|fi|esac|\}|\{|:|true|false)\s*$/,
104
- // Inert shell builtins / flow helpers with no side effects.
105
- /^sleep\b/,
106
- /^exit\b/,
107
- /^return\b/,
108
- /^seq\b/,
109
- /^test\b/,
110
- /^\[\[?\s/, // [ ... ] and [[ ... ]] conditionals
111
- // `<cmd> --help` / `--version` just prints usage. (Dangerous verbs like
112
- // `git push` are matched by HIGH_STAKES on the full command first.)
113
- /\s--(help|version)\b/,
114
- // Read-only npm subcommands beyond the install/version ones above.
115
- /^npm\s+(prefix|root|bin|whoami|ping|docs|repo|why|explain|pkg\s+get|config\s+get)\b/,
116
- ];
58
+ // NOTE: there is intentionally NO "safe commands" allowlist. Under the
59
+ // effect-based model, anything we don't detect as a mutation or a prompt-worthy
60
+ // effect IS safe by default (reads, queries, `ls`, `grep`, `jq`, `awk`, `sort`,
61
+ // unknown commands, …). We only enumerate the things that DO warrant a log
62
+ // (WARNING_*) or a prompt (REVIEW_*, HIGH_STAKES_*).
117
63
  // File deletion (rm/rmdir/trash). Checked PER-STAGE (not on the full command)
118
64
  // so the ephemeral-temp downgrade can run first: `something; rm /tmp/x` must be
119
65
  // warning, but `rm /tmp/x` mixed with a non-temp delete in another stage stays
@@ -141,10 +87,6 @@ const HIGH_STAKES_COMMANDS = [
141
87
  // -c/-e, interpreter -e/-c bodies, heredocs), then classifySqlSeverity.
142
88
  /\bdocker\s+(rm|rmi|system\s+prune)\b/,
143
89
  /\bdocker\s+compose\s+down\b/,
144
- /\bkill\b/,
145
- /\bpkill\b/,
146
- /\bkillall\b/,
147
- /\bchmod\s+777\b/,
148
90
  /\bcurl\s+.*-X\s*(DELETE|PUT|POST|PATCH)\b/i,
149
91
  /\bcurl\s+.*--request\s*(DELETE|PUT|POST|PATCH)\b/i,
150
92
  // curl flags that send a request body (POST/PUT/PATCH) without an explicit -X
@@ -170,36 +112,73 @@ const HIGH_STAKES_COMMANDS = [
170
112
  /\bhimalaya\s+message\s+delete\b/,
171
113
  /\bhimalaya\s+folder\s+(delete|expunge|purge)\b/,
172
114
  /\bhimalaya\s+account\s+delete\b/,
115
+ // Overwriting a raw block device (`> /dev/sda`, `… > /dev/nvme0n1`) destroys a
116
+ // disk irreversibly. (dd to a device is in HIGH_STAKES_STAGE.)
117
+ />\s*\/dev\/(sd|nvme|hd|disk|mmcblk|vd)\w*/,
118
+ ];
119
+ // Destructive / irreversible commands matched PER-STAGE at the start of a stage
120
+ // (after stripping a leading `sudo `), so the destructive WORD can't be hit
121
+ // inside an argument or a commit message (`git commit -m "kill the flaky test"`
122
+ // must not be high_stakes). These don't span pipes, so per-stage `^`-anchoring
123
+ // is both safe and precise.
124
+ const HIGH_STAKES_STAGE = [
125
+ // Filesystem / disk destruction.
126
+ /^mkfs(\.\w+)?\b/,
127
+ /^mkswap\b/,
128
+ /^(fdisk|parted|gparted)\b/,
129
+ /^dd\b.*\bof=\/dev\//,
130
+ /^shred\b/,
131
+ /^truncate\b/, // `truncate -s 0 file` wipes contents
132
+ /^find\b.*\s-delete\b/, // `find … -delete` removes matches
133
+ // Power / system state.
134
+ /^(shutdown|reboot|halt|poweroff)\b/,
135
+ // Remote/outward file transfer (almost always a remote target).
136
+ /^scp\b/,
137
+ /^rsync\b.*(--delete|\s\S+:)/, // rsync --delete, or to a host:path target
138
+ // Local git history/work destruction (force branch delete, tag delete,
139
+ // dropping/clearing stashed work). Reversible local git (add/commit/stash) is
140
+ // a WARNING marker below.
141
+ /^git\s+branch\s+(?:-D|--delete)\b/,
142
+ /^git\s+tag\s+(?:-d|--delete)\b/,
143
+ /^git\s+stash\s+(?:drop|clear)\b/,
144
+ // Process termination.
145
+ /^kill\b/,
146
+ /^pkill\b/,
147
+ /^killall\b/,
148
+ // Wide-open permissions.
149
+ /^chmod\s+(?:-\S+\s+)*777\b/,
150
+ ];
151
+ // Outward-but-recoverable commands → review (prompt, simple approve). Sending
152
+ // mail/messages can't be unsent, but it isn't destructive to local state, so it
153
+ // sits below high_stakes. Matched per-stage. (Destructive himalaya verbs —
154
+ // message delete, folder purge — are high_stakes in the full scan above.)
155
+ const REVIEW_COMMANDS = [
156
+ /^himalaya\s+message\s+(send|reply|forward)\b/,
173
157
  ];
174
- // Commands that auto-allow without a phone prompt but are logged (warning):
175
- // reversible/local actions where an audit line is enough.
158
+ // Local-mutation MARKERS for DETECTED side effects. These never gate a prompt —
159
+ // under the effect-based model anything not flagged destructive/outward/sensitive
160
+ // already auto-allows. They exist only to pick the `warning` (logged) vs `safe`
161
+ // (silent) label, and cover the local mutations we can recognize by shape but
162
+ // that aren't a plain file write (those are handled by extractShellWriteOps).
163
+ //
164
+ // Opaque code execution (node/npx/python/claude/test runners) is intentionally
165
+ // NOT here: we can't tell whether it mutated anything, and a destructive effect
166
+ // buried inside `node -e …` would slip through regardless of the label — so
167
+ // logging it adds terminal noise without buying safety. It stays `safe`, just
168
+ // like any other unrecognized command. A real file write it performs is a
169
+ // separate Bash/Write call that gets classified on its own.
176
170
  const WARNING_COMMANDS = [
177
- // Local, reversible git ops — branch/stage/commit/stash/switch. They touch
178
- // only the local repo and can be undone (amend, reset, checkout).
179
- // Destructive/remote git (push, reset --hard, clean, checkout -- .) is matched
180
- // by HIGH_STAKES_COMMANDS above and wins first. `git stash drop|clear` is
181
- // excluded — those discard stashed work — so it stays `review`.
171
+ // Local, reversible git writes — stage/commit/switch/stash. They mutate the
172
+ // local repo but can be undone (amend, reset, checkout). Destructive git
173
+ // (push, reset --hard, branch -D, stash drop/clear) is caught above and wins.
182
174
  /^git\s+add\b/,
183
175
  /^git\s+commit\b/,
184
176
  /^git\s+checkout\s+-b\b/,
185
177
  /^git\s+switch\b/,
186
178
  /^git\s+stash\b(?!\s+(?:drop|clear))/,
187
- // PR creation is reversible (a PR can be closed); the underlying branch push
188
- // is separately high_stakes.
189
179
  /^gh\s+pr\s+create\b/,
190
- // Arbitrary code execution (node/npx/python/npm run/bun/deno). The spawned
191
- // process can do anything and its syscalls don't pass back through OKed, so
192
- // we don't prompt but keep a local trail. Known test runners and read-only
193
- // version flags are handled as `safe` (SAFE_COMMANDS) before reaching here.
194
- /^node\b/,
195
- /^npx\b/,
196
- /^python3?\b/,
197
- /^npm\s+run\b/,
198
- /^bun\b/,
199
- /^deno\b/,
200
- // Package installs run dependency postinstall scripts (code execution), so
201
- // they're not "safe" — but they're a constant part of the dev loop, so log
202
- // (warning) rather than prompt.
180
+ // Package installs always mutate node_modules and run dependency postinstall
181
+ // scripts — a known local mutation worth an audit line.
203
182
  /^npm\s+(install|ci|i|update|upgrade|rebuild|prune|dedupe)\b/,
204
183
  /^(pnpm|yarn)\s+(install|add|ci|up|upgrade)\b/,
205
184
  ];
@@ -227,14 +206,21 @@ function isEphemeralPath(filePath) {
227
206
  function isSensitiveWritePath(filePath) {
228
207
  if (!filePath)
229
208
  return true; // unknown target → err toward review
209
+ const home = os.homedir();
210
+ // Expand a leading `~` / `$HOME` / `${HOME}` to the real home dir BEFORE
211
+ // resolving. In a shell `echo x > ~/.zshrc` the tilde IS the home dir, but
212
+ // path.resolve treats `~` as a literal segment under cwd, which would miss
213
+ // sensitive home targets (shell rc, ~/.ssh, …) and silently downgrade them.
214
+ const expanded = filePath
215
+ .replace(/^~(?=\/|$)/, home)
216
+ .replace(/^\$\{?HOME\}?(?=\/|$)/, home);
230
217
  let resolved;
231
218
  try {
232
- resolved = path.resolve(filePath);
219
+ resolved = path.resolve(expanded);
233
220
  }
234
221
  catch {
235
222
  return true;
236
223
  }
237
- const home = os.homedir();
238
224
  const underHome = (rel) => {
239
225
  const base = path.join(home, rel);
240
226
  return resolved === base || resolved.startsWith(base + path.sep);
@@ -491,6 +477,69 @@ function classifyAssignmentStage(stage) {
491
477
  tier = maxTier(tier, classifyBashCommand(rest));
492
478
  return tier;
493
479
  }
480
+ /**
481
+ * `env [OPTION]... [NAME=VALUE]... [COMMAND [ARG]...]` runs COMMAND with a
482
+ * modified environment (a wrapper like sudo / an assignment prefix). Strips
483
+ * env's own options (`-i`, `-u NAME`, `-C dir`, `-`, `--unset=NAME`, …) and any
484
+ * leading NAME=VALUE pairs, then classifies the inner COMMAND from its original
485
+ * (quote-preserving) offset. `env` with no command just prints the environment
486
+ * → safe. Returns null if the stage doesn't start with `env`.
487
+ */
488
+ function classifyEnvStage(stage) {
489
+ const lead = /^env\b[ \t]*/.exec(stage);
490
+ if (!lead)
491
+ return null;
492
+ // env options that consume a following argument token.
493
+ const argTaking = new Set(["-u", "--unset", "-C", "--chdir", "-P", "-S", "--split-string"]);
494
+ const readToken = (from) => {
495
+ let i = from;
496
+ let quote = null;
497
+ while (i < stage.length) {
498
+ const ch = stage[i];
499
+ if (quote) {
500
+ if (ch === quote)
501
+ quote = null;
502
+ i++;
503
+ continue;
504
+ }
505
+ if (ch === '"' || ch === "'") {
506
+ quote = ch;
507
+ i++;
508
+ continue;
509
+ }
510
+ if (/\s/.test(ch))
511
+ break;
512
+ i++;
513
+ }
514
+ return i;
515
+ };
516
+ let i = lead[0].length;
517
+ while (i < stage.length) {
518
+ while (i < stage.length && /\s/.test(stage[i]))
519
+ i++;
520
+ if (i >= stage.length)
521
+ break;
522
+ const start = i;
523
+ i = readToken(i);
524
+ const tok = stage.slice(start, i);
525
+ if (tok === "-")
526
+ continue; // ignore-environment marker
527
+ if (tok.startsWith("--") && tok.includes("="))
528
+ continue; // --unset=NAME etc.
529
+ if (tok.startsWith("-")) {
530
+ if (argTaking.has(tok)) { // consume its argument token
531
+ while (i < stage.length && /\s/.test(stage[i]))
532
+ i++;
533
+ i = readToken(i);
534
+ }
535
+ continue;
536
+ }
537
+ if (/^\w+=/.test(tok))
538
+ continue; // NAME=VALUE
539
+ return classifyBashCommand(stage.slice(start).trim()); // first real word → the command
540
+ }
541
+ return "safe"; // `env` / `env -u X` with no command just prints the environment
542
+ }
494
543
  function classifyBashCommand(command) {
495
544
  if (!command)
496
545
  return "safe";
@@ -526,6 +575,15 @@ function classifyBashCommand(command) {
526
575
  if (pattern.test(trimmed))
527
576
  return "high_stakes";
528
577
  }
578
+ // Destructive/irreversible single commands, matched at stage start with any
579
+ // leading `sudo ` stripped (so `sudo mkfs …` is still caught, but the word
580
+ // can't fire inside an argument). These don't span pipes, so `^`-anchoring is
581
+ // precise and avoids prose false-positives.
582
+ const bareStage = trimmed.replace(/^sudo\s+/, "");
583
+ for (const pattern of HIGH_STAKES_STAGE) {
584
+ if (pattern.test(bareStage))
585
+ return "high_stakes";
586
+ }
529
587
  // Variable assignments: `NAME=value` (pure) or `NAME=$(cmd) rest` (env prefix
530
588
  // / capture). Classify the command-substitution inners and any trailing
531
589
  // command; a purely literal assignment is safe. Dangerous substitutions were
@@ -533,6 +591,12 @@ function classifyBashCommand(command) {
533
591
  const assignTier = classifyAssignmentStage(trimmed);
534
592
  if (assignTier !== null)
535
593
  return assignTier;
594
+ // `env [opts] [NAME=VAL]... cmd` runs cmd with a modified environment. Strip
595
+ // the env prefix and classify the inner command (a dangerous inner was already
596
+ // caught by the high-stakes full scan). Bare `env` just prints the env → safe.
597
+ const envTier = classifyEnvStage(trimmed);
598
+ if (envTier !== null)
599
+ return envTier;
536
600
  // sudo: privilege escalation. A high-stakes inner command was already caught
537
601
  // by the full-string scan above (\b patterns match through the `sudo` prefix);
538
602
  // anything else still warrants review.
@@ -545,34 +609,31 @@ function classifyBashCommand(command) {
545
609
  const sql = findSqlInCommand(trimmed);
546
610
  if (sql)
547
611
  return classifySqlSeverity(sql);
548
- // File-mutating shell patterns. Content-creation idioms (echo > X, tee,
549
- // dd of=, touch, sed -i) are the bypass route from a denied Write, so they're
550
- // classified exactly like the Write/Edit tool: `warning` unless a target is a
551
- // sensitive path (system dir, secret store, shell rc, OKed config), which
552
- // stays `review`. cp/mv (which can clobber/relocate existing files) stay
553
- // review.
612
+ // File-mutating shell patterns (echo > X, tee, dd of=, touch, sed -i, cp, mv).
613
+ // A file write/copy/move is a reversible LOCAL mutation, classified like the
614
+ // Write/Edit tool: `warning` (logged) — UNLESS a target is a sensitive path
615
+ // (system dir, secret store, shell rc, OKed config), which stays `review`.
616
+ // (Overwriting a raw block device was already caught by the high-stakes scan.)
554
617
  const ops = extractShellWriteOps(trimmed);
555
618
  if (ops.length > 0) {
556
- const creates = ops.filter((o) => o.kind !== "copy" && o.kind !== "move");
557
- if (creates.length > 0) {
558
- return creates.some((o) => isSensitiveWritePath(o.target)) ? "review" : "warning";
559
- }
560
- return "review";
619
+ const targets = ops.map((o) => o.target);
620
+ return targets.some((t) => isSensitiveWritePath(t)) ? "review" : "warning";
561
621
  }
562
- // Check safe patterns
563
- for (const pattern of SAFE_COMMANDS) {
622
+ // Outward sends (email/message) → review.
623
+ for (const pattern of REVIEW_COMMANDS) {
564
624
  if (pattern.test(trimmed))
565
- return "safe";
625
+ return "review";
566
626
  }
567
- // Reversible/local commands (local git, gh pr create, code execution) →
568
- // warning: logged, no phone approval. Checked after SAFE so read-only git
569
- // (status/log/`stash list`) and known test runners stay fully silent.
627
+ // Local-mutation markers (local git, code execution, installs) → warning:
628
+ // logged, no prompt. Everything else is a read or an unrecognized command with
629
+ // no detected effect — and under the effect-based model that means `safe`.
570
630
  for (const pattern of WARNING_COMMANDS) {
571
631
  if (pattern.test(trimmed))
572
632
  return "warning";
573
633
  }
574
- // Default: review (require approval for unknown commands)
575
- return "review";
634
+ // Default: safe. No destructive/outward/sensitive effect was detected, so we
635
+ // do NOT put a human in the loop just for "running a command".
636
+ return "safe";
576
637
  }
577
638
  function classifySqlSeverity(sql) {
578
639
  if (/\bDROP\s+(TABLE|DATABASE|INDEX|VIEW)\b/i.test(sql))
@@ -592,7 +653,10 @@ function classifySqlSeverity(sql) {
592
653
  // SQLite dot-commands (.tables, .schema, .dump, etc.) — safe unless they mutate
593
654
  if (/^\s*\./.test(sql) && !/^\s*\.(import|read|restore)\b/i.test(sql))
594
655
  return "safe";
595
- return "review";
656
+ // INSERT/ALTER and other non-destructive DML: a reversible row/schema change,
657
+ // not a data wipe → warning (logged, no prompt). Destructive SQL (DROP /
658
+ // TRUNCATE / DELETE FROM / UPDATE-without-WHERE) returned high_stakes above.
659
+ return "warning";
596
660
  }
597
661
  /**
598
662
  * Detects shell idioms that mutate the filesystem. Used by classify (to
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oked/sdk",
3
- "version": "0.1.8",
3
+ "version": "0.2.0",
4
4
  "description": "OKed SDK - human approval layer for AI agents",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",