@oked/sdk 0.2.1 → 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
@@ -19,7 +19,7 @@ import { TIER_ORDER } from "./degraded.js";
19
19
  // dirs, OKed's own config), sudo, outward message/email sends.
20
20
  // Tier 4 - high_stakes: push + number matching. Destructive / irreversible /
21
21
  // external: rm of non-temp data, DROP/TRUNCATE/DELETE FROM,
22
- // git push / reset --hard / branch -D, mkfs / dd-to-device /
22
+ // git push --force / reset --hard / branch -D, mkfs / dd-to-device /
23
23
  // shutdown, curl POST/DELETE, ssh/scp, npm publish, kill.
24
24
  // Tools that are always safe (read-only, no side effects)
25
25
  const SAFE_TOOLS = new Set([
@@ -75,7 +75,9 @@ const DELETE_PATTERNS = [
75
75
  // Scanned on the FULL command (some patterns, e.g. download|shell, span a pipe).
76
76
  // File deletion lives in DELETE_PATTERNS (per-stage) instead, see above.
77
77
  const HIGH_STAKES_COMMANDS = [
78
- /\bgit\s+push\b/,
78
+ // Force push rewrites remote history irreversibly. A plain push is downgraded
79
+ // to `warning` in WARNING_COMMANDS below. Mirrors describe.ts force detection.
80
+ /\bgit\s+push\b[^\n]*\s(?:--force(?:-with-lease)?|-f)\b/,
79
81
  /\bgit\s+reset\s+--hard\b/,
80
82
  /\bgit\s+clean\s+-f/,
81
83
  /\bgit\s+checkout\s+--\s+\./,
@@ -87,15 +89,13 @@ const HIGH_STAKES_COMMANDS = [
87
89
  // -c/-e, interpreter -e/-c bodies, heredocs), then classifySqlSeverity.
88
90
  /\bdocker\s+(rm|rmi|system\s+prune)\b/,
89
91
  /\bdocker\s+compose\s+down\b/,
90
- /\bcurl\s+.*-X\s*(DELETE|PUT|POST|PATCH)\b/i,
91
- /\bcurl\s+.*--request\s*(DELETE|PUT|POST|PATCH)\b/i,
92
- // curl flags that send a request body (POST/PUT/PATCH) without an explicit -X
93
- /\bcurl\b.*\s-d[\s=]/,
94
- /\bcurl\b.*\s--data(-raw|-binary|-urlencode|-ascii)?[\s=]/,
95
- /\bcurl\b.*\s-F[\s=]/,
96
- /\bcurl\b.*\s--form[\s=]/,
97
- /\bcurl\b.*\s(-T|--upload-file)[\s=]/,
98
- /\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.
99
99
  /\bwget\s+.*\|\s*(bash|sh|zsh)\b/,
100
100
  /\bcurl\s+.*\|\s*(bash|sh|zsh)\b/,
101
101
  /\bnpm\s+publish\b/,
@@ -147,6 +147,22 @@ const HIGH_STAKES_STAGE = [
147
147
  // Wide-open permissions.
148
148
  /^chmod\s+(?:-\S+\s+)*777\b/,
149
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
+ ];
150
166
  // Outward-but-recoverable commands → review (prompt, simple approve). Sending
151
167
  // mail/messages can't be unsent, but it isn't destructive to local state, so it
152
168
  // sits below high_stakes. Matched per-stage. (Destructive himalaya verbs —
@@ -169,12 +185,16 @@ const REVIEW_COMMANDS = [
169
185
  const WARNING_COMMANDS = [
170
186
  // Local, reversible git writes — stage/commit/switch/stash. They mutate the
171
187
  // local repo but can be undone (amend, reset, checkout). Destructive git
172
- // (push, reset --hard, branch -D, stash drop/clear) is caught above and wins.
188
+ // (force push, reset --hard, branch -D, stash drop/clear) is caught above and wins.
173
189
  /^git\s+add\b/,
174
190
  /^git\s+commit\b/,
175
191
  /^git\s+checkout\s+-b\b/,
176
192
  /^git\s+switch\b/,
177
193
  /^git\s+stash\b(?!\s+(?:drop|clear))/,
194
+ // Plain push (no force). Outward, but the remote keeps full history and the
195
+ // push is recoverable, so by policy it logs rather than prompts. Force push is
196
+ // high_stakes in the full scan above and wins before reaching here.
197
+ /^git\s+push\b/,
178
198
  /^gh\s+pr\s+create\b/,
179
199
  // Package installs always mutate node_modules and run dependency postinstall
180
200
  // scripts — a known local mutation worth an audit line.
@@ -619,98 +639,123 @@ function classifySshStage(stage) {
619
639
  function classifyBashCommand(command) {
620
640
  if (!command)
621
641
  return "safe";
622
- // Strip heredoc bodies up front: their contents are literal data, not shell,
623
- // and must not be scanned for high-stakes tokens, operators, or redirects.
624
- const trimmed = stripHeredocBodies(command).trim();
625
- // High-stakes scan on the FULL command, before any splitting. These patterns
626
- // use \b and several intentionally span an operator (e.g. `curl … | bash`,
627
- // `wget … | sh` — download-and-execute), so they have to be matched against
628
- // the whole string. Most-restrictive-wins: a high-stakes match anywhere in a
629
- // compound command takes the whole command to high_stakes. (File deletion is
630
- // 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.)
631
662
  for (const pattern of HIGH_STAKES_COMMANDS) {
632
- if (pattern.test(trimmed))
663
+ if (pattern.test(stripped))
633
664
  return "high_stakes";
634
665
  }
635
666
  // Compound commands: split on top-level `|`, `||`, `&&`, `;` and take the
636
- // highest tier. Without this, `cat /tmp/draft.eml | himalaya message send`
637
- // would match `^cat\b` and silently allow the send, and `git add … && git
638
- // commit …` couldn't be recognized as the local git ops they are. Only
639
- // recurse when there are 2+ stages so single commands don't loop.
640
- 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);
641
672
  if (stages.length > 1) {
642
673
  return stages.reduce((worst, stage) => maxTier(worst, classifyBashCommand(stage)), "safe");
643
674
  }
644
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) {
645
690
  // File deletion, per-stage so the ephemeral-temp carve-out can win: deleting
646
691
  // only throwaway temp files (/tmp, $TMPDIR, /var/folders, …) → warning; any
647
692
  // non-temp target (or the temp root itself) → high_stakes.
648
- if (isEphemeralOnlyDeletion(trimmed))
693
+ if (isEphemeralOnlyDeletion(stage))
649
694
  return "warning";
650
695
  for (const pattern of DELETE_PATTERNS) {
651
- if (pattern.test(trimmed))
696
+ if (pattern.test(stage))
652
697
  return "high_stakes";
653
698
  }
654
699
  // Destructive/irreversible single commands, matched at stage start with any
655
700
  // leading `sudo ` stripped (so `sudo mkfs …` is still caught, but the word
656
701
  // can't fire inside an argument). These don't span pipes, so `^`-anchoring is
657
702
  // precise and avoids prose false-positives.
658
- const bareStage = trimmed.replace(/^sudo\s+/, "");
703
+ const bareStage = stage.replace(/^sudo\s+/, "");
659
704
  for (const pattern of HIGH_STAKES_STAGE) {
660
705
  if (pattern.test(bareStage))
661
706
  return "high_stakes";
662
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
+ }
663
715
  // Variable assignments: `NAME=value` (pure) or `NAME=$(cmd) rest` (env prefix
664
716
  // / capture). Classify the command-substitution inners and any trailing
665
717
  // command; a purely literal assignment is safe. Dangerous substitutions were
666
718
  // already caught by the high-stakes/delete scans above.
667
- const assignTier = classifyAssignmentStage(trimmed);
719
+ const assignTier = classifyAssignmentStage(stage);
668
720
  if (assignTier !== null)
669
721
  return assignTier;
670
722
  // `env [opts] [NAME=VAL]... cmd` runs cmd with a modified environment. Strip
671
723
  // the env prefix and classify the inner command (a dangerous inner was already
672
724
  // caught by the high-stakes full scan). Bare `env` just prints the env → safe.
673
- const envTier = classifyEnvStage(trimmed);
725
+ const envTier = classifyEnvStage(stage);
674
726
  if (envTier !== null)
675
727
  return envTier;
676
728
  // ssh is a transport — classify the remote command it runs (interactive /
677
729
  // port-forwarding ssh has no inspectable command → review floor). scp/rsync
678
730
  // to a remote are file transfers and stay high_stakes (HIGH_STAKES_STAGE).
679
- const sshTier = classifySshStage(trimmed);
731
+ const sshTier = classifySshStage(stage);
680
732
  if (sshTier !== null)
681
733
  return sshTier;
682
734
  // sudo: privilege escalation. A high-stakes inner command was already caught
683
735
  // by the full-string scan above (\b patterns match through the `sudo` prefix);
684
736
  // anything else still warrants review.
685
- if (/^sudo\s/.test(trimmed))
737
+ if (/^sudo\s/.test(stage))
686
738
  return "review";
687
- // SQL hidden inside an interpreter wrapper (python -c, node -e, heredoc),
688
- // a DB CLI (psql -c, sqlite3 db "...", mysql -e), or at the top of the
689
- // command. Severity comes from the statement, not the wrapper. (High-stakes
690
- // SQL — DROP/TRUNCATE/DELETE FROM — is already covered by the scan above.)
691
- const sql = findSqlInCommand(trimmed);
692
- if (sql)
693
- return classifySqlSeverity(sql);
694
739
  // File-mutating shell patterns (echo > X, tee, dd of=, touch, sed -i, cp, mv).
695
740
  // A file write/copy/move is a reversible LOCAL mutation, classified like the
696
741
  // Write/Edit tool: `warning` (logged) — UNLESS a target is a sensitive path
697
742
  // (system dir, secret store, shell rc, OKed config), which stays `review`.
698
743
  // (Overwriting a raw block device was already caught by the high-stakes scan.)
699
- const ops = extractShellWriteOps(trimmed);
744
+ const ops = extractShellWriteOps(stage);
700
745
  if (ops.length > 0) {
701
746
  const targets = ops.map((o) => o.target);
702
747
  return targets.some((t) => isSensitiveWritePath(t)) ? "review" : "warning";
703
748
  }
704
749
  // Outward sends (email/message) → review.
705
750
  for (const pattern of REVIEW_COMMANDS) {
706
- if (pattern.test(trimmed))
751
+ if (pattern.test(stage))
707
752
  return "review";
708
753
  }
709
754
  // Local-mutation markers (local git, code execution, installs) → warning:
710
755
  // logged, no prompt. Everything else is a read or an unrecognized command with
711
756
  // no detected effect — and under the effect-based model that means `safe`.
712
757
  for (const pattern of WARNING_COMMANDS) {
713
- if (pattern.test(trimmed))
758
+ if (pattern.test(stage))
714
759
  return "warning";
715
760
  }
716
761
  // Default: safe. No destructive/outward/sensitive effect was detected, so we
@@ -789,6 +834,55 @@ export function stripHeredocBodies(command) {
789
834
  }
790
835
  return out.join("\n");
791
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
+ }
792
886
  /** Find output redirects (`>`, `>>`, `&>`, `2>`, …) outside quoted strings.
793
887
  * The target token may itself be quoted. Skips `2>&1`-style FD dups, bare
794
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.2.1",
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",