@oked/sdk 0.3.0 → 0.3.1

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
@@ -89,15 +89,13 @@ const HIGH_STAKES_COMMANDS = [
89
89
  // -c/-e, interpreter -e/-c bodies, heredocs), then classifySqlSeverity.
90
90
  /\bdocker\s+(rm|rmi|system\s+prune)\b/,
91
91
  /\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=]/,
92
+ // NOTE: curl request-method/body flags (-X DELETE, --data, -F, -T, --json, …)
93
+ // are NOT here. Their `.*` would match greedily across a `&&`/`|` boundary and
94
+ // grab a flag belonging to a LATER command (e.g. `curl -o … && unzip … -d dir`
95
+ // false-matched the curl `-d` POST-body pattern on unzip's destination flag).
96
+ // They belong to a single curl invocation, so they're scanned PER-STAGE in
97
+ // HIGH_STAKES_CURL_STAGE below. Only the download-and-execute patterns
98
+ // (`curl|wget … | sh`) genuinely span a pipe and stay in this full scan.
101
99
  /\bwget\s+.*\|\s*(bash|sh|zsh)\b/,
102
100
  /\bcurl\s+.*\|\s*(bash|sh|zsh)\b/,
103
101
  /\bnpm\s+publish\b/,
@@ -149,6 +147,22 @@ const HIGH_STAKES_STAGE = [
149
147
  // Wide-open permissions.
150
148
  /^chmod\s+(?:-\S+\s+)*777\b/,
151
149
  ];
150
+ // curl request-method / request-body flags, scanned PER-STAGE (a single stage
151
+ // has no top-level pipe, so `\bcurl\b.*` can't cross into another command — the
152
+ // `-d`/`-T`/etc. it finds belongs to THIS curl). A curl that sends a body or a
153
+ // mutating method (POST/PUT/PATCH/DELETE) is an outward write → high_stakes.
154
+ // A plain `curl -o file URL` download has none of these and stays safe.
155
+ const HIGH_STAKES_CURL_STAGE = [
156
+ /\bcurl\s+.*-X\s*(DELETE|PUT|POST|PATCH)\b/i,
157
+ /\bcurl\s+.*--request\s*(DELETE|PUT|POST|PATCH)\b/i,
158
+ // curl flags that send a request body (POST/PUT/PATCH) without an explicit -X
159
+ /\bcurl\b.*\s-d[\s=]/,
160
+ /\bcurl\b.*\s--data(-raw|-binary|-urlencode|-ascii)?[\s=]/,
161
+ /\bcurl\b.*\s-F[\s=]/,
162
+ /\bcurl\b.*\s--form[\s=]/,
163
+ /\bcurl\b.*\s(-T|--upload-file)[\s=]/,
164
+ /\bcurl\b.*\s--json[\s=]/,
165
+ ];
152
166
  // Outward-but-recoverable commands → review (prompt, simple approve). Sending
153
167
  // mail/messages can't be unsent, but it isn't destructive to local state, so it
154
168
  // sits below high_stakes. Matched per-stage. (Destructive himalaya verbs —
@@ -625,98 +639,123 @@ function classifySshStage(stage) {
625
639
  function classifyBashCommand(command) {
626
640
  if (!command)
627
641
  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.)
642
+ // Two views of the command:
643
+ // - `intact` : heredoc bodies stripped only. Used for SQL detection, so SQL
644
+ // written inline in an interpreter one-liner (`node -e`,
645
+ // `python -c`) or a DB CLI is still classified (PR #19).
646
+ // - `stripped`: ALSO blanks inline-interpreter script bodies. Used for every
647
+ // SHELL-pattern scan, so a shell token embedded as code/data in
648
+ // an interpreter body (`rm`, `curl -d`, a `>` redirect — e.g. a
649
+ // reddit post fed to `node -e '…samples…'`) does not trip a
650
+ // destructive/outward rule. (SQL keywords in that data can still
651
+ // surface via `intact` — that is the accepted shell-only-opacity
652
+ // trade-off; see classifyStageShellEffects.)
653
+ const intact = stripHeredocBodies(command).trim();
654
+ const stripped = stripInlineScriptBodies(intact).trim();
655
+ // High-stakes scan on the FULL (body-stripped) command, before any splitting.
656
+ // These patterns use \b and several intentionally span an operator (e.g.
657
+ // `curl … | bash`, `wget … | sh` — download-and-execute), so they have to be
658
+ // matched against the whole string. Most-restrictive-wins: a high-stakes match
659
+ // anywhere in a compound command takes the whole command to high_stakes. (File
660
+ // deletion is NOT here — it's per-stage below so the ephemeral-temp downgrade
661
+ // can run.)
637
662
  for (const pattern of HIGH_STAKES_COMMANDS) {
638
- if (pattern.test(trimmed))
663
+ if (pattern.test(stripped))
639
664
  return "high_stakes";
640
665
  }
641
666
  // 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);
667
+ // highest tier. Split the body-INTACT view so each stage keeps its SQL
668
+ // visible; recursion re-derives both views per stage. (Blanking a script body
669
+ // never changes top-level operator structure — operators inside the quoted
670
+ // body aren't split points either way — so stage boundaries are identical.)
671
+ const stages = splitTopLevel(intact);
647
672
  if (stages.length > 1) {
648
673
  return stages.reduce((worst, stage) => maxTier(worst, classifyBashCommand(stage)), "safe");
649
674
  }
650
675
  // ---- single stage from here ----
676
+ // SQL severity from the body-INTACT view: an interpreter wrapper (python -c,
677
+ // node -e, heredoc), a DB CLI (psql -c, sqlite3 db "...", mysql -e), or SQL at
678
+ // the top of the command. Folded in as a floor so it survives even when the
679
+ // shell pass short-circuits to `safe` (e.g. an assignment-prefixed node -e).
680
+ const sql = findSqlInCommand(intact);
681
+ const sqlTier = sql ? classifySqlSeverity(sql) : "safe";
682
+ return maxTier(sqlTier, classifyStageShellEffects(stripped));
683
+ }
684
+ /**
685
+ * Shell-effect classification of a SINGLE, already-body-stripped stage. No SQL
686
+ * detection here — that runs on the body-intact view in classifyBashCommand and
687
+ * is folded in by the caller. Returns the stage's tier (default `safe`).
688
+ */
689
+ function classifyStageShellEffects(stage) {
651
690
  // File deletion, per-stage so the ephemeral-temp carve-out can win: deleting
652
691
  // only throwaway temp files (/tmp, $TMPDIR, /var/folders, …) → warning; any
653
692
  // non-temp target (or the temp root itself) → high_stakes.
654
- if (isEphemeralOnlyDeletion(trimmed))
693
+ if (isEphemeralOnlyDeletion(stage))
655
694
  return "warning";
656
695
  for (const pattern of DELETE_PATTERNS) {
657
- if (pattern.test(trimmed))
696
+ if (pattern.test(stage))
658
697
  return "high_stakes";
659
698
  }
660
699
  // Destructive/irreversible single commands, matched at stage start with any
661
700
  // leading `sudo ` stripped (so `sudo mkfs …` is still caught, but the word
662
701
  // can't fire inside an argument). These don't span pipes, so `^`-anchoring is
663
702
  // precise and avoids prose false-positives.
664
- const bareStage = trimmed.replace(/^sudo\s+/, "");
703
+ const bareStage = stage.replace(/^sudo\s+/, "");
665
704
  for (const pattern of HIGH_STAKES_STAGE) {
666
705
  if (pattern.test(bareStage))
667
706
  return "high_stakes";
668
707
  }
708
+ // curl with a mutating method or request body → high_stakes. Scanned per-stage
709
+ // (not on the full compound command) so the greedy `.*` can't reach across a
710
+ // `&&`/`|` and match a `-d`/`-T`/etc. flag belonging to a different command.
711
+ for (const pattern of HIGH_STAKES_CURL_STAGE) {
712
+ if (pattern.test(stage))
713
+ return "high_stakes";
714
+ }
669
715
  // Variable assignments: `NAME=value` (pure) or `NAME=$(cmd) rest` (env prefix
670
716
  // / capture). Classify the command-substitution inners and any trailing
671
717
  // command; a purely literal assignment is safe. Dangerous substitutions were
672
718
  // already caught by the high-stakes/delete scans above.
673
- const assignTier = classifyAssignmentStage(trimmed);
719
+ const assignTier = classifyAssignmentStage(stage);
674
720
  if (assignTier !== null)
675
721
  return assignTier;
676
722
  // `env [opts] [NAME=VAL]... cmd` runs cmd with a modified environment. Strip
677
723
  // the env prefix and classify the inner command (a dangerous inner was already
678
724
  // caught by the high-stakes full scan). Bare `env` just prints the env → safe.
679
- const envTier = classifyEnvStage(trimmed);
725
+ const envTier = classifyEnvStage(stage);
680
726
  if (envTier !== null)
681
727
  return envTier;
682
728
  // ssh is a transport — classify the remote command it runs (interactive /
683
729
  // port-forwarding ssh has no inspectable command → review floor). scp/rsync
684
730
  // to a remote are file transfers and stay high_stakes (HIGH_STAKES_STAGE).
685
- const sshTier = classifySshStage(trimmed);
731
+ const sshTier = classifySshStage(stage);
686
732
  if (sshTier !== null)
687
733
  return sshTier;
688
734
  // sudo: privilege escalation. A high-stakes inner command was already caught
689
735
  // by the full-string scan above (\b patterns match through the `sudo` prefix);
690
736
  // anything else still warrants review.
691
- if (/^sudo\s/.test(trimmed))
737
+ if (/^sudo\s/.test(stage))
692
738
  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
739
  // File-mutating shell patterns (echo > X, tee, dd of=, touch, sed -i, cp, mv).
701
740
  // A file write/copy/move is a reversible LOCAL mutation, classified like the
702
741
  // Write/Edit tool: `warning` (logged) — UNLESS a target is a sensitive path
703
742
  // (system dir, secret store, shell rc, OKed config), which stays `review`.
704
743
  // (Overwriting a raw block device was already caught by the high-stakes scan.)
705
- const ops = extractShellWriteOps(trimmed);
744
+ const ops = extractShellWriteOps(stage);
706
745
  if (ops.length > 0) {
707
746
  const targets = ops.map((o) => o.target);
708
747
  return targets.some((t) => isSensitiveWritePath(t)) ? "review" : "warning";
709
748
  }
710
749
  // Outward sends (email/message) → review.
711
750
  for (const pattern of REVIEW_COMMANDS) {
712
- if (pattern.test(trimmed))
751
+ if (pattern.test(stage))
713
752
  return "review";
714
753
  }
715
754
  // Local-mutation markers (local git, code execution, installs) → warning:
716
755
  // logged, no prompt. Everything else is a read or an unrecognized command with
717
756
  // no detected effect — and under the effect-based model that means `safe`.
718
757
  for (const pattern of WARNING_COMMANDS) {
719
- if (pattern.test(trimmed))
758
+ if (pattern.test(stage))
720
759
  return "warning";
721
760
  }
722
761
  // Default: safe. No destructive/outward/sensitive effect was detected, so we
@@ -795,6 +834,55 @@ export function stripHeredocBodies(command) {
795
834
  }
796
835
  return out.join("\n");
797
836
  }
837
+ // Interpreters whose inline `-e`/`-c`/`--eval` (and perl/deno one-liner) body is
838
+ // opaque CODE — not shell. We blank that body before the SHELL-pattern scans so
839
+ // tokens embedded as code or data (`rm`, `curl -d`, a `>` redirect) don't trip a
840
+ // destructive/outward rule. This matches the documented policy that opaque code
841
+ // execution is `safe` (see the WARNING_COMMANDS note): we can't tell what a
842
+ // `node -e`/`python -c` body does, and a real destructive shell effect buried
843
+ // inside it would slip through the label regardless — so scanning the body for
844
+ // shell tokens only manufactures false positives.
845
+ //
846
+ // NOTE: SQL is the deliberate exception. classifyBashCommand still runs SQL
847
+ // detection on the body-INTACT view, so inline SQL in a `node -e`/`python -c`
848
+ // one-liner stays classified (PR #19). The trade-off ("shell-only opacity"): a
849
+ // SQL keyword sitting in DATA passed to an interpreter can still surface.
850
+ //
851
+ // Deliberately EXCLUDED from stripping: shell interpreters (`sh -c`, `bash -c`)
852
+ // whose body IS shell — those bodies must stay scannable. The matcher requires a
853
+ // quoted body, so an unquoted `node -e expr` (which can't carry spaces/operators)
854
+ // is left untouched.
855
+ 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;
856
+ export function stripInlineScriptBodies(command) {
857
+ INLINE_SCRIPT_RE.lastIndex = 0;
858
+ let out = "";
859
+ let last = 0;
860
+ let m;
861
+ while ((m = INLINE_SCRIPT_RE.exec(command)) !== null) {
862
+ const quote = m[1];
863
+ const bodyStart = m.index + m[0].length; // index just past the opening quote
864
+ let j = bodyStart;
865
+ if (quote === "'") {
866
+ // Single quotes: no escaping in shell — body runs to the next single quote.
867
+ while (j < command.length && command[j] !== "'")
868
+ j++;
869
+ }
870
+ else {
871
+ // Double quotes: a backslash escapes the next char.
872
+ while (j < command.length && command[j] !== '"') {
873
+ if (command[j] === "\\")
874
+ j++;
875
+ j++;
876
+ }
877
+ }
878
+ out += command.slice(last, bodyStart); // prefix through the opening quote
879
+ out += quote; // closing quote — interior blanked
880
+ last = j < command.length ? j + 1 : command.length;
881
+ INLINE_SCRIPT_RE.lastIndex = last; // resume after the closing quote
882
+ }
883
+ out += command.slice(last);
884
+ return out;
885
+ }
798
886
  /** Find output redirects (`>`, `>>`, `&>`, `2>`, …) outside quoted strings.
799
887
  * The target token may itself be quoted. Skips `2>&1`-style FD dups, bare
800
888
  * digits, and /dev/null. Heredoc `<<` is ignored (only `>` is a write). */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oked/sdk",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "OKed SDK - human approval layer for AI agents",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",