@oked/sdk 0.3.0 → 0.3.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.
@@ -18,4 +18,5 @@ export interface ShellWriteOp {
18
18
  * body, so SQL/code detection still runs. The opener line is always preserved.
19
19
  */
20
20
  export declare function stripHeredocBodies(command: string): string;
21
+ export declare function stripInlineScriptBodies(command: string): string;
21
22
  export declare function extractShellWriteOps(command: string): ShellWriteOp[];
package/dist/classify.js CHANGED
@@ -60,17 +60,26 @@ const HIGH_STAKES_TOOLS = new Set([]);
60
60
  // effect IS safe by default (reads, queries, `ls`, `grep`, `jq`, `awk`, `sort`,
61
61
  // unknown commands, …). We only enumerate the things that DO warrant a log
62
62
  // (WARNING_*) or a prompt (REVIEW_*, HIGH_STAKES_*).
63
- // File deletion (rm/rmdir/trash). Checked PER-STAGE (not on the full command)
64
- // so the ephemeral-temp downgrade can run first: `something; rm /tmp/x` must be
65
- // warning, but `rm /tmp/x` mixed with a non-temp delete in another stage stays
66
- // high_stakes. Matching the bare word also catches it inside a loop body or a
67
- // $(...) substitution stage.
68
- const DELETE_PATTERNS = [
69
- /\brm\b/,
70
- /\brmdir\b/,
71
- /\btrash\b/,
72
- /\btrash-put\b/,
73
- ];
63
+ // File deletion (rm/rmdir/trash), detected in COMMAND POSITION only. Checked
64
+ // PER-STAGE (not the full command) so the ephemeral-temp downgrade can run
65
+ // first. Earlier this matched the bare word `\brm\b` anywhere, which fired on
66
+ // `rm` sitting in an ARGUMENT — a branch name (`git push origin fix-rm-thing`),
67
+ // a filename (`touch fix-rm.txt`), or echo text — turning benign commands
68
+ // (including file creation) into false high_stakes prompts. Now it only fires
69
+ // when the delete word is the command being run.
70
+ //
71
+ // DELETE_LEAD strips leading command wrappers / loop-body keywords (and their
72
+ // flags) so a real delete that isn't literally first — `sudo rm`, `command rm`,
73
+ // `xargs -0 rm`, `do rm` (from `for …; do rm …; done`) — still anchors at start.
74
+ // Wrappers that take their own structured args (env, ssh, NAME=…, sh -c) are
75
+ // handled by their dedicated stage classifiers, which recurse into the inner
76
+ // command, so they're intentionally not here.
77
+ const DELETE_LEAD = /^(?:(?:sudo|command|exec|builtin|time|nice|xargs|then|do|else)\b\s*(?:-\S+\s+)*)+/;
78
+ // rm/rmdir/trash at the (lead-stripped) start of the stage, at the start of a
79
+ // line, or immediately inside a substitution/subshell/group ($( ), `…`, ( ),
80
+ // { ). Deliberately NOT after `;`/`|`/`&`/a quote, so a delete word sitting in
81
+ // quoted DATA (echo text, a commit message) doesn't match.
82
+ const DELETE_COMMAND_RE = /(?:^|[\n`({]|\$\()\s*(?:rm|rmdir|trash|trash-put)\b/;
74
83
  // Bash commands classified as high stakes (destructive, irreversible, external).
75
84
  // Scanned on the FULL command (some patterns, e.g. download|shell, span a pipe).
76
85
  // File deletion lives in DELETE_PATTERNS (per-stage) instead, see above.
@@ -89,15 +98,13 @@ const HIGH_STAKES_COMMANDS = [
89
98
  // -c/-e, interpreter -e/-c bodies, heredocs), then classifySqlSeverity.
90
99
  /\bdocker\s+(rm|rmi|system\s+prune)\b/,
91
100
  /\bdocker\s+compose\s+down\b/,
92
- /\bcurl\s+.*-X\s*(DELETE|PUT|POST|PATCH)\b/i,
93
- /\bcurl\s+.*--request\s*(DELETE|PUT|POST|PATCH)\b/i,
94
- // curl flags that send a request body (POST/PUT/PATCH) without an explicit -X
95
- /\bcurl\b.*\s-d[\s=]/,
96
- /\bcurl\b.*\s--data(-raw|-binary|-urlencode|-ascii)?[\s=]/,
97
- /\bcurl\b.*\s-F[\s=]/,
98
- /\bcurl\b.*\s--form[\s=]/,
99
- /\bcurl\b.*\s(-T|--upload-file)[\s=]/,
100
- /\bcurl\b.*\s--json[\s=]/,
101
+ // NOTE: curl request-method/body flags (-X DELETE, --data, -F, -T, --json, …)
102
+ // are NOT here. Their `.*` would match greedily across a `&&`/`|` boundary and
103
+ // grab a flag belonging to a LATER command (e.g. `curl -o … && unzip … -d dir`
104
+ // false-matched the curl `-d` POST-body pattern on unzip's destination flag).
105
+ // They belong to a single curl invocation, so they're scanned PER-STAGE in
106
+ // HIGH_STAKES_CURL_STAGE below. Only the download-and-execute patterns
107
+ // (`curl|wget … | sh`) genuinely span a pipe and stay in this full scan.
101
108
  /\bwget\s+.*\|\s*(bash|sh|zsh)\b/,
102
109
  /\bcurl\s+.*\|\s*(bash|sh|zsh)\b/,
103
110
  /\bnpm\s+publish\b/,
@@ -149,6 +156,22 @@ const HIGH_STAKES_STAGE = [
149
156
  // Wide-open permissions.
150
157
  /^chmod\s+(?:-\S+\s+)*777\b/,
151
158
  ];
159
+ // curl request-method / request-body flags, scanned PER-STAGE (a single stage
160
+ // has no top-level pipe, so `\bcurl\b.*` can't cross into another command — the
161
+ // `-d`/`-T`/etc. it finds belongs to THIS curl). A curl that sends a body or a
162
+ // mutating method (POST/PUT/PATCH/DELETE) is an outward write → high_stakes.
163
+ // A plain `curl -o file URL` download has none of these and stays safe.
164
+ const HIGH_STAKES_CURL_STAGE = [
165
+ /\bcurl\s+.*-X\s*(DELETE|PUT|POST|PATCH)\b/i,
166
+ /\bcurl\s+.*--request\s*(DELETE|PUT|POST|PATCH)\b/i,
167
+ // curl flags that send a request body (POST/PUT/PATCH) without an explicit -X
168
+ /\bcurl\b.*\s-d[\s=]/,
169
+ /\bcurl\b.*\s--data(-raw|-binary|-urlencode|-ascii)?[\s=]/,
170
+ /\bcurl\b.*\s-F[\s=]/,
171
+ /\bcurl\b.*\s--form[\s=]/,
172
+ /\bcurl\b.*\s(-T|--upload-file)[\s=]/,
173
+ /\bcurl\b.*\s--json[\s=]/,
174
+ ];
152
175
  // Outward-but-recoverable commands → review (prompt, simple approve). Sending
153
176
  // mail/messages can't be unsent, but it isn't destructive to local state, so it
154
177
  // sits below high_stakes. Matched per-stage. (Destructive himalaya verbs —
@@ -622,101 +645,148 @@ function classifySshStage(stage) {
622
645
  }
623
646
  return "review"; // only options / a bare host token → treat as remote access
624
647
  }
648
+ /**
649
+ * `sh -c '<shell>'` / `bash -c "<shell>"` (also zsh/ksh/dash, and combined flags
650
+ * like `-lc`) runs the quoted argument AS shell. Recurse on the body so its
651
+ * effect is classified by the same rules — mirrors classifySshStage. Only fires
652
+ * when the shell IS the stage's command; a `-c` flag on another tool (e.g.
653
+ * `grep -c`) is unaffected because the stage doesn't start with a shell name.
654
+ * Returns null if the stage isn't a `sh -c`-style invocation.
655
+ */
656
+ function classifyShellCStage(stage) {
657
+ const m = stage.match(/^(?:bash|sh|zsh|ksh|dash)\b[^'"]*?\s-[A-Za-z]*c\s+(['"])([\s\S]*?)\1/);
658
+ if (!m)
659
+ return null;
660
+ return classifyBashCommand(m[2]);
661
+ }
625
662
  function classifyBashCommand(command) {
626
663
  if (!command)
627
664
  return "safe";
628
- // Strip heredoc bodies up front: their contents are literal data, not shell,
629
- // and must not be scanned for high-stakes tokens, operators, or redirects.
630
- const trimmed = stripHeredocBodies(command).trim();
631
- // High-stakes scan on the FULL command, before any splitting. These patterns
632
- // use \b and several intentionally span an operator (e.g. `curl … | bash`,
633
- // `wget … | sh` — download-and-execute), so they have to be matched against
634
- // the whole string. Most-restrictive-wins: a high-stakes match anywhere in a
635
- // compound command takes the whole command to high_stakes. (File deletion is
636
- // NOT here — it's per-stage below so the ephemeral-temp downgrade can run.)
665
+ // Two views of the command:
666
+ // - `intact` : heredoc bodies stripped only. Used for SQL detection, so SQL
667
+ // written inline in an interpreter one-liner (`node -e`,
668
+ // `python -c`) or a DB CLI is still classified (PR #19).
669
+ // - `stripped`: ALSO blanks inline-interpreter script bodies. Used for every
670
+ // SHELL-pattern scan, so a shell token embedded as code/data in
671
+ // an interpreter body (`rm`, `curl -d`, a `>` redirect — e.g. a
672
+ // reddit post fed to `node -e '…samples…'`) does not trip a
673
+ // destructive/outward rule. (SQL keywords in that data can still
674
+ // surface via `intact` — that is the accepted shell-only-opacity
675
+ // trade-off; see classifyStageShellEffects.)
676
+ const intact = stripHeredocBodies(command).trim();
677
+ const stripped = stripInlineScriptBodies(intact).trim();
678
+ // High-stakes scan on the FULL (body-stripped) command, before any splitting.
679
+ // These patterns use \b and several intentionally span an operator (e.g.
680
+ // `curl … | bash`, `wget … | sh` — download-and-execute), so they have to be
681
+ // matched against the whole string. Most-restrictive-wins: a high-stakes match
682
+ // anywhere in a compound command takes the whole command to high_stakes. (File
683
+ // deletion is NOT here — it's per-stage below so the ephemeral-temp downgrade
684
+ // can run.)
637
685
  for (const pattern of HIGH_STAKES_COMMANDS) {
638
- if (pattern.test(trimmed))
686
+ if (pattern.test(stripped))
639
687
  return "high_stakes";
640
688
  }
641
689
  // Compound commands: split on top-level `|`, `||`, `&&`, `;` and take the
642
- // highest tier. Without this, `cat /tmp/draft.eml | himalaya message send`
643
- // would match `^cat\b` and silently allow the send, and `git add … && git
644
- // commit …` couldn't be recognized as the local git ops they are. Only
645
- // recurse when there are 2+ stages so single commands don't loop.
646
- const stages = splitTopLevel(trimmed);
690
+ // highest tier. Split the body-INTACT view so each stage keeps its SQL
691
+ // visible; recursion re-derives both views per stage. (Blanking a script body
692
+ // never changes top-level operator structure — operators inside the quoted
693
+ // body aren't split points either way — so stage boundaries are identical.)
694
+ const stages = splitTopLevel(intact);
647
695
  if (stages.length > 1) {
648
696
  return stages.reduce((worst, stage) => maxTier(worst, classifyBashCommand(stage)), "safe");
649
697
  }
650
698
  // ---- single stage from here ----
651
- // File deletion, per-stage so the ephemeral-temp carve-out can win: deleting
652
- // only throwaway temp files (/tmp, $TMPDIR, /var/folders, …) → warning; any
653
- // non-temp target (or the temp root itself) → high_stakes.
654
- if (isEphemeralOnlyDeletion(trimmed))
699
+ // SQL severity from the body-INTACT view: an interpreter wrapper (python -c,
700
+ // node -e, heredoc), a DB CLI (psql -c, sqlite3 db "...", mysql -e), or SQL at
701
+ // the top of the command. Folded in as a floor so it survives even when the
702
+ // shell pass short-circuits to `safe` (e.g. an assignment-prefixed node -e).
703
+ const sql = findSqlInCommand(intact);
704
+ const sqlTier = sql ? classifySqlSeverity(sql) : "safe";
705
+ return maxTier(sqlTier, classifyStageShellEffects(stripped));
706
+ }
707
+ /**
708
+ * Shell-effect classification of a SINGLE, already-body-stripped stage. No SQL
709
+ * detection here — that runs on the body-intact view in classifyBashCommand and
710
+ * is folded in by the caller. Returns the stage's tier (default `safe`).
711
+ */
712
+ function classifyStageShellEffects(stage) {
713
+ // File deletion in COMMAND POSITION, per-stage so the ephemeral-temp carve-out
714
+ // can win: deleting only throwaway temp files (/tmp, $TMPDIR, /var/folders, …)
715
+ // → warning; any non-temp target (or the temp root itself) → high_stakes.
716
+ // A delete word sitting in an argument (filename, branch name, echo text) is
717
+ // NOT a deletion — that's the false positive DELETE_COMMAND_RE avoids.
718
+ if (isEphemeralOnlyDeletion(stage))
655
719
  return "warning";
656
- for (const pattern of DELETE_PATTERNS) {
657
- if (pattern.test(trimmed))
658
- return "high_stakes";
659
- }
720
+ if (DELETE_COMMAND_RE.test(stage.replace(DELETE_LEAD, "")))
721
+ return "high_stakes";
660
722
  // Destructive/irreversible single commands, matched at stage start with any
661
723
  // leading `sudo ` stripped (so `sudo mkfs …` is still caught, but the word
662
724
  // can't fire inside an argument). These don't span pipes, so `^`-anchoring is
663
725
  // precise and avoids prose false-positives.
664
- const bareStage = trimmed.replace(/^sudo\s+/, "");
726
+ const bareStage = stage.replace(/^sudo\s+/, "");
665
727
  for (const pattern of HIGH_STAKES_STAGE) {
666
728
  if (pattern.test(bareStage))
667
729
  return "high_stakes";
668
730
  }
731
+ // curl with a mutating method or request body → high_stakes. Scanned per-stage
732
+ // (not on the full compound command) so the greedy `.*` can't reach across a
733
+ // `&&`/`|` and match a `-d`/`-T`/etc. flag belonging to a different command.
734
+ for (const pattern of HIGH_STAKES_CURL_STAGE) {
735
+ if (pattern.test(stage))
736
+ return "high_stakes";
737
+ }
669
738
  // Variable assignments: `NAME=value` (pure) or `NAME=$(cmd) rest` (env prefix
670
739
  // / capture). Classify the command-substitution inners and any trailing
671
740
  // command; a purely literal assignment is safe. Dangerous substitutions were
672
741
  // already caught by the high-stakes/delete scans above.
673
- const assignTier = classifyAssignmentStage(trimmed);
742
+ const assignTier = classifyAssignmentStage(stage);
674
743
  if (assignTier !== null)
675
744
  return assignTier;
676
745
  // `env [opts] [NAME=VAL]... cmd` runs cmd with a modified environment. Strip
677
746
  // the env prefix and classify the inner command (a dangerous inner was already
678
747
  // caught by the high-stakes full scan). Bare `env` just prints the env → safe.
679
- const envTier = classifyEnvStage(trimmed);
748
+ const envTier = classifyEnvStage(stage);
680
749
  if (envTier !== null)
681
750
  return envTier;
682
751
  // ssh is a transport — classify the remote command it runs (interactive /
683
752
  // port-forwarding ssh has no inspectable command → review floor). scp/rsync
684
753
  // to a remote are file transfers and stay high_stakes (HIGH_STAKES_STAGE).
685
- const sshTier = classifySshStage(trimmed);
754
+ const sshTier = classifySshStage(stage);
686
755
  if (sshTier !== null)
687
756
  return sshTier;
757
+ // `sh -c '<shell>'` / `bash -c "<shell>"` runs the quoted argument AS shell —
758
+ // recurse so its effect is classified by the same rules (mirrors ssh). This
759
+ // is why the command-position delete scan above can ignore quoted text: a real
760
+ // shell-out like `bash -c 'rm -rf /important'` is caught HERE, by re-running
761
+ // the body as a command, while `echo 'rm …'` (data) is not.
762
+ const shellCTier = classifyShellCStage(stage);
763
+ if (shellCTier !== null)
764
+ return shellCTier;
688
765
  // sudo: privilege escalation. A high-stakes inner command was already caught
689
766
  // by the full-string scan above (\b patterns match through the `sudo` prefix);
690
767
  // anything else still warrants review.
691
- if (/^sudo\s/.test(trimmed))
768
+ if (/^sudo\s/.test(stage))
692
769
  return "review";
693
- // SQL hidden inside an interpreter wrapper (python -c, node -e, heredoc),
694
- // a DB CLI (psql -c, sqlite3 db "...", mysql -e), or at the top of the
695
- // command. Severity comes from the statement, not the wrapper. (High-stakes
696
- // SQL — DROP/TRUNCATE/DELETE FROM — is already covered by the scan above.)
697
- const sql = findSqlInCommand(trimmed);
698
- if (sql)
699
- return classifySqlSeverity(sql);
700
770
  // File-mutating shell patterns (echo > X, tee, dd of=, touch, sed -i, cp, mv).
701
771
  // A file write/copy/move is a reversible LOCAL mutation, classified like the
702
772
  // Write/Edit tool: `warning` (logged) — UNLESS a target is a sensitive path
703
773
  // (system dir, secret store, shell rc, OKed config), which stays `review`.
704
774
  // (Overwriting a raw block device was already caught by the high-stakes scan.)
705
- const ops = extractShellWriteOps(trimmed);
775
+ const ops = extractShellWriteOps(stage);
706
776
  if (ops.length > 0) {
707
777
  const targets = ops.map((o) => o.target);
708
778
  return targets.some((t) => isSensitiveWritePath(t)) ? "review" : "warning";
709
779
  }
710
780
  // Outward sends (email/message) → review.
711
781
  for (const pattern of REVIEW_COMMANDS) {
712
- if (pattern.test(trimmed))
782
+ if (pattern.test(stage))
713
783
  return "review";
714
784
  }
715
785
  // Local-mutation markers (local git, code execution, installs) → warning:
716
786
  // logged, no prompt. Everything else is a read or an unrecognized command with
717
787
  // no detected effect — and under the effect-based model that means `safe`.
718
788
  for (const pattern of WARNING_COMMANDS) {
719
- if (pattern.test(trimmed))
789
+ if (pattern.test(stage))
720
790
  return "warning";
721
791
  }
722
792
  // Default: safe. No destructive/outward/sensitive effect was detected, so we
@@ -795,6 +865,55 @@ export function stripHeredocBodies(command) {
795
865
  }
796
866
  return out.join("\n");
797
867
  }
868
+ // Interpreters whose inline `-e`/`-c`/`--eval` (and perl/deno one-liner) body is
869
+ // opaque CODE — not shell. We blank that body before the SHELL-pattern scans so
870
+ // tokens embedded as code or data (`rm`, `curl -d`, a `>` redirect) don't trip a
871
+ // destructive/outward rule. This matches the documented policy that opaque code
872
+ // execution is `safe` (see the WARNING_COMMANDS note): we can't tell what a
873
+ // `node -e`/`python -c` body does, and a real destructive shell effect buried
874
+ // inside it would slip through the label regardless — so scanning the body for
875
+ // shell tokens only manufactures false positives.
876
+ //
877
+ // NOTE: SQL is the deliberate exception. classifyBashCommand still runs SQL
878
+ // detection on the body-INTACT view, so inline SQL in a `node -e`/`python -c`
879
+ // one-liner stays classified (PR #19). The trade-off ("shell-only opacity"): a
880
+ // SQL keyword sitting in DATA passed to an interpreter can still surface.
881
+ //
882
+ // Deliberately EXCLUDED from stripping: shell interpreters (`sh -c`, `bash -c`)
883
+ // whose body IS shell — those bodies must stay scannable. The matcher requires a
884
+ // quoted body, so an unquoted `node -e expr` (which can't carry spaces/operators)
885
+ // is left untouched.
886
+ const INLINE_SCRIPT_RE = /\b(?:node|deno|bun|python[23]?|ruby|perl)\b[^\n|;&'"]*?\s(?:eval|--eval|--print|-e|-c|-p|-ne|-pe|-ple|-ane|-nae)\b\s*(['"])/g;
887
+ export function stripInlineScriptBodies(command) {
888
+ INLINE_SCRIPT_RE.lastIndex = 0;
889
+ let out = "";
890
+ let last = 0;
891
+ let m;
892
+ while ((m = INLINE_SCRIPT_RE.exec(command)) !== null) {
893
+ const quote = m[1];
894
+ const bodyStart = m.index + m[0].length; // index just past the opening quote
895
+ let j = bodyStart;
896
+ if (quote === "'") {
897
+ // Single quotes: no escaping in shell — body runs to the next single quote.
898
+ while (j < command.length && command[j] !== "'")
899
+ j++;
900
+ }
901
+ else {
902
+ // Double quotes: a backslash escapes the next char.
903
+ while (j < command.length && command[j] !== '"') {
904
+ if (command[j] === "\\")
905
+ j++;
906
+ j++;
907
+ }
908
+ }
909
+ out += command.slice(last, bodyStart); // prefix through the opening quote
910
+ out += quote; // closing quote — interior blanked
911
+ last = j < command.length ? j + 1 : command.length;
912
+ INLINE_SCRIPT_RE.lastIndex = last; // resume after the closing quote
913
+ }
914
+ out += command.slice(last);
915
+ return out;
916
+ }
798
917
  /** Find output redirects (`>`, `>>`, `&>`, `2>`, …) outside quoted strings.
799
918
  * The target token may itself be quoted. Skips `2>&1`-style FD dups, bare
800
919
  * digits, and /dev/null. Heredoc `<<` is ignored (only `>` is a write). */
package/dist/describe.js CHANGED
@@ -859,6 +859,14 @@ function parseRmTargets(argsString) {
859
859
  i++;
860
860
  if (i >= str.length)
861
861
  break;
862
+ // A shell command separator (`;`, `|`, `||`, `&&`, `&`), a redirect (`>`,
863
+ // `>>`, `2>`, `&>`), a closing `)`/`}`, a comment, or a newline ends the rm
864
+ // argument list — everything after belongs to a different command. Without
865
+ // this, a compound `if …; then rm -rf "$P"; else echo "…"; fi` would sweep
866
+ // the trailing `;`/`else`/`echo`/`fi` (and the echo's text) in as "files",
867
+ // rendering a bogus "Delete N files recursively".
868
+ if (/^(?:&?\d*[<>]|[;|&`)}#\n])/.test(str.slice(i)))
869
+ break;
862
870
  let token;
863
871
  if (str[i] === '"') {
864
872
  const close = str.indexOf('"', i + 1);
@@ -884,7 +892,9 @@ function parseRmTargets(argsString) {
884
892
  }
885
893
  else {
886
894
  const start = i;
887
- while (i < str.length && !/\s/.test(str[i]))
895
+ // Stop the bare token at whitespace OR a separator/redirect char, so
896
+ // `"$P";` and `$P;` both yield just the path.
897
+ while (i < str.length && !/[\s;|&<>`)}#]/.test(str[i]))
888
898
  i++;
889
899
  token = str.slice(start, i);
890
900
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oked/sdk",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "description": "OKed SDK - human approval layer for AI agents",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",