@picassohq/cli 0.0.0-stage → 1.0.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.
- package/agents/browser_agent.yaml +53 -0
- package/agents/code_reviewer.yaml +49 -0
- package/agents/codebase_investigator.yaml +70 -0
- package/agents/design_auditor.yaml +50 -0
- package/agents/devex_auditor.yaml +50 -0
- package/agents/doc_writer.yaml +54 -0
- package/agents/engineering_architect.yaml +51 -0
- package/agents/generalist.yaml +55 -0
- package/agents/migration_planner.yaml +51 -0
- package/agents/product_reviewer.yaml +48 -0
- package/agents/qa_operator.yaml +52 -0
- package/agents/release_engineer.yaml +50 -0
- package/agents/security_auditor.yaml +62 -0
- package/agents/test_writer.yaml +52 -0
- package/assets/first-light-lockup.png +0 -0
- package/assets/first-light-tagline.png +0 -0
- package/assets/house/README.md +26 -0
- package/assets/house/auraone-banner.png +0 -0
- package/assets/house/auraone-logo.png +0 -0
- package/assets/house/kiro-prism-banner.png +0 -0
- package/assets/house/kiro-prism-logo.png +0 -0
- package/assets/house/picasso-banner.png +0 -0
- package/assets/house/picasso-logo.png +0 -0
- package/assets/wordmark-app.png +0 -0
- package/assets/wordmark-tight.png +0 -0
- package/assets/wordmark.png +0 -0
- package/design/styles.css +1042 -0
- package/dist/build-info.json +37 -0
- package/dist/index.js +3028 -0
- package/goals/cli-hardening.yaml +40 -0
- package/goals/repo-maintenance.yaml +40 -0
- package/package.json +49 -4
- package/runtime/dsh/picasso-ecosystem.community.amendments.yml +24 -0
- package/runtime/dsh/picasso-ecosystem.community.json +185 -0
- package/runtime/dsh/picasso-ecosystem.community.patch.yml +40 -0
- package/runtime/dsh/picasso-ecosystem.cordis.patch.yml +143 -0
- package/runtime/dsh/picasso-isolation.patch.yml +25 -0
- package/runtime/dsh/picasso-providers.patch.yml +373 -0
- package/runtime/dsh/picasso-runtime.cordis.yml +738 -0
- package/runtime/dsh/picasso-sdk.patch.yml +204 -0
- package/runtime/engine-manifest.json +214 -0
- package/runtime/package.json +6 -0
- package/runtime/packages/picasso-cache-probe/cordis.patch.yml +5 -0
- package/runtime/packages/picasso-cache-probe/index.js +477 -0
- package/runtime/packages/picasso-cache-probe/package.json +38 -0
- package/runtime/packages/picasso-commands/cordis.patch.yml +4 -0
- package/runtime/packages/picasso-commands/fresh-review.js +573 -0
- package/runtime/packages/picasso-commands/index.js +497 -0
- package/runtime/packages/picasso-commands/package.json +28 -0
- package/runtime/packages/picasso-instructions/conflicts.js +115 -0
- package/runtime/packages/picasso-instructions/formats.js +145 -0
- package/runtime/packages/picasso-instructions/frontmatter.js +175 -0
- package/runtime/packages/picasso-instructions/glob.js +114 -0
- package/runtime/packages/picasso-instructions/globals.js +90 -0
- package/runtime/packages/picasso-instructions/imports.js +123 -0
- package/runtime/packages/picasso-instructions/index.js +326 -0
- package/runtime/packages/picasso-instructions/modes.js +64 -0
- package/runtime/packages/picasso-instructions/package.json +30 -0
- package/runtime/packages/picasso-instructions/parse.js +134 -0
- package/runtime/packages/picasso-instructions/report.js +161 -0
- package/runtime/packages/picasso-instructions/resolve.js +939 -0
- package/runtime/packages/picasso-instructions/scan.js +181 -0
- package/runtime/packages/picasso-instructions/settings.js +150 -0
- package/runtime/packages/picasso-instructions/skills.js +345 -0
- package/runtime/packages/picasso-lean-context/cordis.patch.yml +13 -0
- package/runtime/packages/picasso-lean-context/index.js +6049 -0
- package/runtime/packages/picasso-lean-context/package.json +26 -0
- package/runtime/packages/picasso-lean-context/timeline.js +417 -0
- package/runtime/packages/picasso-librarian/classify.js +146 -0
- package/runtime/packages/picasso-librarian/cordis.patch.yml +10 -0
- package/runtime/packages/picasso-librarian/index.js +878 -0
- package/runtime/packages/picasso-librarian/notes.js +159 -0
- package/runtime/packages/picasso-librarian/package.json +34 -0
- package/runtime/packages/picasso-librarian/state.js +478 -0
- package/runtime/packages/picasso-memory/index.js +1184 -0
- package/runtime/packages/picasso-memory/package.json +21 -0
- package/runtime/packages/picasso-model-router/connections.js +895 -0
- package/runtime/packages/picasso-model-router/cordis.patch.yml +17 -0
- package/runtime/packages/picasso-model-router/index.js +1081 -0
- package/runtime/packages/picasso-model-router/package.json +30 -0
- package/runtime/packages/picasso-options/cordis.patch.yml +4 -0
- package/runtime/packages/picasso-options/index.js +263 -0
- package/runtime/packages/picasso-options/package.json +28 -0
- package/runtime/packages/picasso-progress-reports/cordis.patch.yml +10 -0
- package/runtime/packages/picasso-progress-reports/index.js +267 -0
- package/runtime/packages/picasso-progress-reports/package.json +30 -0
- package/runtime/packages/picasso-progress-reports/report.js +235 -0
- package/runtime/packages/picasso-sdk-server/aside.js +128 -0
- package/runtime/packages/picasso-sdk-server/connections.js +38 -0
- package/runtime/packages/picasso-sdk-server/context-timeline.js +27 -0
- package/runtime/packages/picasso-sdk-server/egress-gate.js +520 -0
- package/runtime/packages/picasso-sdk-server/failure-policy.js +246 -0
- package/runtime/packages/picasso-sdk-server/file-input.js +169 -0
- package/runtime/packages/picasso-sdk-server/goal.js +131 -0
- package/runtime/packages/picasso-sdk-server/ignore-file.js +458 -0
- package/runtime/packages/picasso-sdk-server/ignore-plugin.js +12 -0
- package/runtime/packages/picasso-sdk-server/ignore-sandbox.js +122 -0
- package/runtime/packages/picasso-sdk-server/ignore-snapshot.js +131 -0
- package/runtime/packages/picasso-sdk-server/image-input.js +44 -0
- package/runtime/packages/picasso-sdk-server/index.js +886 -0
- package/runtime/packages/picasso-sdk-server/instructions.js +34 -0
- package/runtime/packages/picasso-sdk-server/jobs.js +113 -0
- package/runtime/packages/picasso-sdk-server/mcp-gate.js +51 -0
- package/runtime/packages/picasso-sdk-server/model-selection.js +162 -0
- package/runtime/packages/picasso-sdk-server/package.json +50 -0
- package/runtime/packages/picasso-sdk-server/picasso-records.js +50 -0
- package/runtime/packages/picasso-sdk-server/provider-reload.js +84 -0
- package/runtime/packages/picasso-sdk-server/queue.js +322 -0
- package/runtime/packages/picasso-sdk-server/requester.js +43 -0
- package/runtime/packages/picasso-sdk-server/rewind.js +108 -0
- package/runtime/packages/picasso-sdk-server/schedule.js +187 -0
- package/runtime/packages/picasso-sdk-server/session-grants.js +35 -0
- package/runtime/packages/picasso-sdk-server/session-state.js +118 -0
- package/runtime/packages/picasso-sdk-server/shell-paths.js +869 -0
- package/runtime/packages/picasso-sdk-server/stream-deltas.js +211 -0
- package/runtime/packages/picasso-sdk-server/team-tasks.js +451 -0
- package/runtime/packages/picasso-sdk-server/tool-output.js +128 -0
- package/runtime/packages/picasso-sdk-server/tools-list.js +51 -0
- package/runtime/packages/picasso-sdk-server/wave2-hooks.js +612 -0
- package/runtime/packages/picasso-sdk-server/workspace-archive.js +170 -0
- package/runtime/packages/picasso-sdk-server/workspace-restore.js +180 -0
- package/runtime/packages/picasso-web-search/backends.js +350 -0
- package/runtime/packages/picasso-web-search/config.js +121 -0
- package/runtime/packages/picasso-web-search/cordis.patch.yml +7 -0
- package/runtime/packages/picasso-web-search/failure.js +111 -0
- package/runtime/packages/picasso-web-search/format.js +35 -0
- package/runtime/packages/picasso-web-search/index.js +66 -0
- package/runtime/packages/picasso-web-search/package.json +38 -0
- package/runtime/packages/picasso-web-search/router.js +155 -0
- package/runtime/packages/picasso-x-reader/circle.js +324 -0
- package/runtime/packages/picasso-x-reader/command.js +169 -0
- package/runtime/packages/picasso-x-reader/cordis.patch.yml +8 -0
- package/runtime/packages/picasso-x-reader/index.js +170 -0
- package/runtime/packages/picasso-x-reader/package.json +39 -0
- package/runtime/packages/picasso-x-reader/read.js +370 -0
- package/runtime/packages/picasso-x-reader/rewrite.js +38 -0
- package/runtime/packages/picasso-x-reader/settings.js +131 -0
- package/runtime/packages/picasso-x-reader/urls.js +154 -0
- package/runtime/packages/picasso-x-reader/xmd.js +512 -0
- package/runtime/plugins/picasso-auth-bridge/index.js +380 -0
- package/runtime/plugins/picasso-auth-bridge/package.json +28 -0
- package/runtime/plugins/picasso-auto-approve/index.js +1003 -0
- package/runtime/plugins/picasso-auto-approve/package.json +28 -0
- package/runtime/plugins/picasso-browser/index.js +424 -0
- package/runtime/plugins/picasso-browser/package.json +28 -0
- package/runtime/plugins/picasso-checkpoints/evidence.js +210 -0
- package/runtime/plugins/picasso-checkpoints/index.js +885 -0
- package/runtime/plugins/picasso-checkpoints/package.json +29 -0
- package/runtime/plugins/picasso-commands/fresh-review.js +573 -0
- package/runtime/plugins/picasso-commands/index.js +497 -0
- package/runtime/plugins/picasso-commands/package.json +28 -0
- package/runtime/plugins/picasso-instructions/conflicts.js +115 -0
- package/runtime/plugins/picasso-instructions/formats.js +145 -0
- package/runtime/plugins/picasso-instructions/frontmatter.js +175 -0
- package/runtime/plugins/picasso-instructions/glob.js +114 -0
- package/runtime/plugins/picasso-instructions/globals.js +90 -0
- package/runtime/plugins/picasso-instructions/imports.js +123 -0
- package/runtime/plugins/picasso-instructions/index.js +326 -0
- package/runtime/plugins/picasso-instructions/modes.js +64 -0
- package/runtime/plugins/picasso-instructions/package.json +30 -0
- package/runtime/plugins/picasso-instructions/parse.js +134 -0
- package/runtime/plugins/picasso-instructions/report.js +161 -0
- package/runtime/plugins/picasso-instructions/resolve.js +939 -0
- package/runtime/plugins/picasso-instructions/scan.js +181 -0
- package/runtime/plugins/picasso-instructions/settings.js +150 -0
- package/runtime/plugins/picasso-instructions/skills.js +345 -0
- package/runtime/plugins/picasso-lean-context/index.js +6049 -0
- package/runtime/plugins/picasso-lean-context/package.json +26 -0
- package/runtime/plugins/picasso-lean-context/timeline.js +417 -0
- package/runtime/plugins/picasso-librarian/classify.js +146 -0
- package/runtime/plugins/picasso-librarian/index.js +878 -0
- package/runtime/plugins/picasso-librarian/notes.js +159 -0
- package/runtime/plugins/picasso-librarian/package.json +34 -0
- package/runtime/plugins/picasso-librarian/state.js +478 -0
- package/runtime/plugins/picasso-lifecycle-hooks/index.js +186 -0
- package/runtime/plugins/picasso-lifecycle-hooks/package.json +25 -0
- package/runtime/plugins/picasso-mail/inbox.js +207 -0
- package/runtime/plugins/picasso-mail/index.js +293 -0
- package/runtime/plugins/picasso-mail/package.json +22 -0
- package/runtime/plugins/picasso-memory/index.js +1184 -0
- package/runtime/plugins/picasso-memory/package.json +21 -0
- package/runtime/plugins/picasso-model-router/connections.js +895 -0
- package/runtime/plugins/picasso-model-router/index.js +1081 -0
- package/runtime/plugins/picasso-model-router/package.json +30 -0
- package/runtime/plugins/picasso-options/index.js +263 -0
- package/runtime/plugins/picasso-options/package.json +28 -0
- package/runtime/plugins/picasso-progress-reports/index.js +267 -0
- package/runtime/plugins/picasso-progress-reports/package.json +30 -0
- package/runtime/plugins/picasso-progress-reports/report.js +235 -0
- package/runtime/plugins/picasso-provider-models/index.js +436 -0
- package/runtime/plugins/picasso-provider-models/package.json +28 -0
- package/runtime/plugins/picasso-repo-index/index.js +1850 -0
- package/runtime/plugins/picasso-repo-index/package.json +28 -0
- package/runtime/plugins/picasso-schedule-pause/index.js +344 -0
- package/runtime/plugins/picasso-schedule-pause/package.json +28 -0
- package/runtime/plugins/picasso-session-lifecycle/index.js +796 -0
- package/runtime/plugins/picasso-session-lifecycle/package.json +28 -0
- package/runtime/plugins/picasso-trackers/index.js +895 -0
- package/runtime/plugins/picasso-trackers/package.json +28 -0
- package/runtime/plugins/picasso-web-search/backends.js +350 -0
- package/runtime/plugins/picasso-web-search/config.js +121 -0
- package/runtime/plugins/picasso-web-search/failure.js +111 -0
- package/runtime/plugins/picasso-web-search/format.js +35 -0
- package/runtime/plugins/picasso-web-search/index.js +66 -0
- package/runtime/plugins/picasso-web-search/package.json +38 -0
- package/runtime/plugins/picasso-web-search/router.js +155 -0
- package/runtime/plugins/picasso-x-reader/circle.js +324 -0
- package/runtime/plugins/picasso-x-reader/command.js +169 -0
- package/runtime/plugins/picasso-x-reader/index.js +170 -0
- package/runtime/plugins/picasso-x-reader/package.json +39 -0
- package/runtime/plugins/picasso-x-reader/read.js +370 -0
- package/runtime/plugins/picasso-x-reader/rewrite.js +38 -0
- package/runtime/plugins/picasso-x-reader/settings.js +131 -0
- package/runtime/plugins/picasso-x-reader/urls.js +154 -0
- package/runtime/plugins/picasso-x-reader/xmd.js +512 -0
- package/runtime/relay/attachment-text.mjs +737 -0
- package/runtime/relay/companion/companion.css +126 -0
- package/runtime/relay/companion/companion.js +648 -0
- package/runtime/relay/companion/icon.svg +5 -0
- package/runtime/relay/companion/index.html +25 -0
- package/runtime/relay/companion/manifest.json +13 -0
- package/runtime/relay/companion/sw.js +41 -0
- package/runtime/relay/main.mjs +37252 -0
- package/runtime/relay/model-listing.mjs +614 -0
- package/runtime/relay/versions-routes.mjs +1198 -0
- package/runtime/verify-plugins.mjs +205 -0
- package/runtime-lock/package-lock.json +10779 -0
- package/runtime-lock/package.json +7 -0
- package/scripts/install-runtime.mjs +400 -0
- package/README.md +0 -3
|
@@ -0,0 +1,1003 @@
|
|
|
1
|
+
// @picasso/auto-approve — auto-approves dsh tool executions against an
|
|
2
|
+
// allowlist of tool names, plus the durable rule store the Mac's "Always
|
|
3
|
+
// allow" affordance edits (B02).
|
|
4
|
+
//
|
|
5
|
+
// Two seams, matching how dsh itself gates tool calls (dsh 0.2.1-rc.3):
|
|
6
|
+
//
|
|
7
|
+
// approval/request — the canonical audited seam. `tools` turns a
|
|
8
|
+
// `{kind:'ask'}` pre-execute gate into `ctx.approval.request({agent,
|
|
9
|
+
// toolName, callId, signal})`, and tool bodies (e.g. bash sandbox
|
|
10
|
+
// escalations via approveEscalation) call it directly. The service appends
|
|
11
|
+
// the `approval/asked` + `approval/decided` audit pair, then dispatches the
|
|
12
|
+
// `approval/request` waterfall whose answerers return one of
|
|
13
|
+
// 'allowed-once' | 'rejected' | 'cancelled' | 'unavailable'. This plugin
|
|
14
|
+
// answers 'allowed-once' for allowlisted tool names — the grant lands in
|
|
15
|
+
// the session log exactly like a human click (the "F10 gate" equivalent),
|
|
16
|
+
// and every other request defers to `next()` downstream.
|
|
17
|
+
//
|
|
18
|
+
// tools/pre-execute — the earlier waterfall (exec → {kind:'allow'|'deny'|
|
|
19
|
+
// 'ask'|'cancel'}). When NO approval service is mounted in the composition,
|
|
20
|
+
// `serviceAsk` fail-closes every ask ("requires approval (not yet
|
|
21
|
+
// supported)"); for allowlisted tools only, the ask is rewritten to allow so
|
|
22
|
+
// a configured policy still means "auto-run" in that composition. When the
|
|
23
|
+
// service exists the gate passes through untouched so the audited
|
|
24
|
+
// approval/request path above owns the decision.
|
|
25
|
+
//
|
|
26
|
+
// Content guard (the deny layer): before any allow logic runs, both seams scan
|
|
27
|
+
// the execution's string leaves — `arguments` recursively plus a top-level
|
|
28
|
+
// `command` — against a denylist of regular-expression rules ({id, pattern,
|
|
29
|
+
// description}, `pattern` compiled `new RegExp(pattern, 'i')`). A hit denies the
|
|
30
|
+
// gate (`{kind:'deny', reason: 'contentGuard/<id>: …'}` — model-visible like the
|
|
31
|
+
// ignore-file guard's) or answers the approval waterfall 'rejected'; a `*`
|
|
32
|
+
// allowlist can never rescue blocked content, and a sandbox escalation carrying
|
|
33
|
+
// denied content is rejected outright rather than deferred to a human. Deny
|
|
34
|
+
// rules come from four sources (first tag wins on id: builtin > config > env >
|
|
35
|
+
// sidecar): DEFAULT_DENY_RULES always-on built-ins (shell root/disk destruction,
|
|
36
|
+
// pipe-to-shell, fork bombs, .env/SSH/credential/keychain/cloud-token reads),
|
|
37
|
+
// `config.deny`, `PICASSO_CONTENT_GUARD` (a JSON array of rule objects — a
|
|
38
|
+
// malformed entry fails the mount like config.allow's), and the sidecar
|
|
39
|
+
// `<dsh data>/picasso-content-guard.json` the `denyAdd|denyRemove|denyClear`
|
|
40
|
+
// remote methods edit live (same atomic tmp+rename 0o600, last-writer-wins
|
|
41
|
+
// shape as the allow sidecar). Every denial lands in a 100-entry in-memory
|
|
42
|
+
// journal served by `denials`.
|
|
43
|
+
//
|
|
44
|
+
// Rules come from three sources, unioned (first tag wins the row's label, so a
|
|
45
|
+
// rule the UI cannot revoke is never drawn as editable):
|
|
46
|
+
//
|
|
47
|
+
// config.allow — the boot-time list mounted by a patch layer row; exact
|
|
48
|
+
// ("bash"), trailing-star prefix ("mcp__github__*"), or "*" (every tool —
|
|
49
|
+
// mount deliberately). Malformed entries fail the mount: a misconfigured
|
|
50
|
+
// boot policy is never a silent allow/deny.
|
|
51
|
+
// PICASSO_AUTO_APPROVE — the same patterns comma-separated, for hosts that
|
|
52
|
+
// mount the plugin without config (e.g. the generated Picasso layer).
|
|
53
|
+
// The sidecar — `<dsh data>/picasso-auto-approve.json`, the durable store
|
|
54
|
+
// `autoApprove/add|remove|clear` edit live; `root` config points beside it
|
|
55
|
+
// (the `dshHomePath('permissions')` convention, so the file lands in the
|
|
56
|
+
// dsh data dir like picasso-schedule-pause's). Writes are atomic
|
|
57
|
+
// (tmp+rename, mode 0o600) and every mutation re-reads first, so the
|
|
58
|
+
// last writer wins a whole-file race.
|
|
59
|
+
//
|
|
60
|
+
// AO-006.12 — durable "Always allow" rules are scoped, never bare tool names:
|
|
61
|
+
// scope fields `session`, `workspace` and `args` ride the sidecar row
|
|
62
|
+
// (`{pattern, session?, workspace?, args?, addedAt}`). A scoped rule grants
|
|
63
|
+
// only when the deciding context matches every bound field: `session` and
|
|
64
|
+
// `workspace` must equal the asking agent's session/workspace, and `args`
|
|
65
|
+
// (a canonical-JSON fingerprint of the approved arguments, `*` suffix for
|
|
66
|
+
// prefix) is enforced wherever the seam exposes arguments — the
|
|
67
|
+
// `tools/pre-execute` gate always sees `exec.arguments`; the
|
|
68
|
+
// `approval/request` answerer sees them only when the asker supplied them,
|
|
69
|
+
// where session/workspace scope still applies. A child/subagent session has
|
|
70
|
+
// its own session id, so a parent-bound rule never reaches it (inherited
|
|
71
|
+
// children can never exceed the parent's stored grants).
|
|
72
|
+
// Sandbox escalation is never auto-approved: an ask carrying escalation
|
|
73
|
+
// markers (escalation/sandbox flags, `sandbox_permissions` or
|
|
74
|
+
// `dangerouslyDisableSandbox` arguments, or an escalation reason) defers
|
|
75
|
+
// even when a broad tool-name rule like `bash` matches.
|
|
76
|
+
//
|
|
77
|
+
// The `autoApprove` Host Remote (`list | add | remove | clear`) uses the
|
|
78
|
+
// gateway's source-mode markers like @picasso/schedule-pause, and failures are
|
|
79
|
+
// structural dsh RemoteErrors (code `autoApprove/<code>`). Config and env rows
|
|
80
|
+
// are boot-time, so `remove` refuses them (`autoApprove/not-removable`) — the
|
|
81
|
+
// UI draws them read-only off `list`'s `source` tag.
|
|
82
|
+
//
|
|
83
|
+
// Posture: the remote is always mounted and both listeners subscribe
|
|
84
|
+
// unconditionally — a no-match defers to `next()`/passes the gate either way,
|
|
85
|
+
// so a rule added mid-run takes effect on the next ask in the same engine run
|
|
86
|
+
// instead of waiting for a boot-time policy.
|
|
87
|
+
import { readFileSync } from 'node:fs';
|
|
88
|
+
import { mkdir, rename, writeFile } from 'node:fs/promises';
|
|
89
|
+
import { homedir } from 'node:os';
|
|
90
|
+
import { dirname, join, resolve } from 'node:path';
|
|
91
|
+
|
|
92
|
+
export const name = 'picasso-auto-approve';
|
|
93
|
+
export const dshTarget = '0.2.2-rc.3';
|
|
94
|
+
export const ENV_ALLOW = 'PICASSO_AUTO_APPROVE';
|
|
95
|
+
export const ENV_DENY = 'PICASSO_CONTENT_GUARD';
|
|
96
|
+
export const OUTCOME_ALLOW = 'allowed-once';
|
|
97
|
+
export const SERVICE_KEY = 'autoApprove';
|
|
98
|
+
export const SIDECAR_FILENAME = 'picasso-auto-approve.json';
|
|
99
|
+
export const DENY_SIDECAR_FILENAME = 'picasso-content-guard.json';
|
|
100
|
+
const REMOTE_METHOD_DESCRIPTOR = '@deepseek-ai/dsh-typert-protocol/remote-methods';
|
|
101
|
+
|
|
102
|
+
export class AutoApproveError extends Error {
|
|
103
|
+
constructor(code, message, details = {}) {
|
|
104
|
+
super(message);
|
|
105
|
+
this.name = 'RemoteError';
|
|
106
|
+
this.code = `autoApprove/${code}`;
|
|
107
|
+
this.details = details;
|
|
108
|
+
this.isDSHRemoteError = true;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* One allow pattern, normalized: a non-empty string trimmed of edge space, a
|
|
116
|
+
* bare `*` (every tool), a single trailing star prefix ("mcp__github__*"), or
|
|
117
|
+
* an exact tool name. A `*` anywhere else — `**`, `a*b` — is junk the matcher
|
|
118
|
+
* could only misread, so it is rejected rather than silently allowed or
|
|
119
|
+
* denied. Throws a plain Error for config/env (boot misconfiguration) or an
|
|
120
|
+
* AutoApproveError through `validate` for the remote's `add`.
|
|
121
|
+
*/
|
|
122
|
+
function patternFor(entry, errorFor) {
|
|
123
|
+
if (typeof entry !== 'string' || entry.trim() === '') throw errorFor('must be a non-empty string');
|
|
124
|
+
const pattern = entry.trim();
|
|
125
|
+
if (pattern.length > 256) throw errorFor('must be at most 256 characters');
|
|
126
|
+
// `*` is legal only as the whole pattern or one trailing prefix star; anywhere else (`**`, `a*b`, `*a`) is
|
|
127
|
+
// junk that would never match a real tool name — rejected, never silently allowed or denied.
|
|
128
|
+
const star = pattern.indexOf('*');
|
|
129
|
+
if (star !== -1 && star !== pattern.length - 1) throw errorFor(`may use "*" only as a whole wildcard or one trailing prefix star`);
|
|
130
|
+
if (pattern === '*') return { pattern, exact: false, prefix: '' };
|
|
131
|
+
if (pattern.endsWith('*')) return { pattern, exact: false, prefix: pattern.slice(0, -1) };
|
|
132
|
+
return { pattern, exact: true, prefix: pattern };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Normalize an allow pattern list into compiled matchers. Entries must be
|
|
137
|
+
* non-empty strings: a trailing `*` matches a prefix, a bare `*` matches
|
|
138
|
+
* everything. Anything else throws — a malformed policy mounted at boot is a
|
|
139
|
+
* misconfiguration, never a silent allow/deny.
|
|
140
|
+
*/
|
|
141
|
+
export function compilePolicy(allow, label = 'config.allow') {
|
|
142
|
+
if (allow === undefined || allow === null) return [];
|
|
143
|
+
if (!Array.isArray(allow)) throw new Error(`${name}: ${label} must be an array of tool names/patterns`);
|
|
144
|
+
return allow.map((entry, index) => patternFor(entry, (reason) => new Error(`${name}: ${label}[${index}] ${reason}`)));
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** `add`/`remove` argument validation: the trimmed pattern, or an `autoApprove/bad-pattern` refusal. */
|
|
148
|
+
export function normalizePattern(value) {
|
|
149
|
+
try {
|
|
150
|
+
return patternFor(value, (reason) => new AutoApproveError('bad-pattern', `A rule pattern ${reason} (e.g. "bash", "mcp__github__*", "*").`, { value })).pattern;
|
|
151
|
+
} catch (error) {
|
|
152
|
+
if (error instanceof AutoApproveError) throw error;
|
|
153
|
+
throw new AutoApproveError('bad-pattern', String(error?.message ?? error), { value });
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// ── Content guard (the deny layer) ────────────────────────────────────────────────────────────────────────────────
|
|
158
|
+
|
|
159
|
+
const DENY_RULE_ID = /^[a-z0-9][a-z0-9/_-]{0,63}$/;
|
|
160
|
+
const DENY_PATTERN_MAX = 512;
|
|
161
|
+
const DENY_DESCRIPTION_MAX = 512;
|
|
162
|
+
const SCAN_MAX_LEAVES = 256;
|
|
163
|
+
const SCAN_MAX_BYTES = 1024 * 1024;
|
|
164
|
+
const SCAN_MAX_DEPTH = 24;
|
|
165
|
+
const SCAN_EXCERPT_MAX = 160;
|
|
166
|
+
const DENIAL_JOURNAL_LIMIT = 100;
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* The always-on deny rules. Patterns are RegExp sources compiled case-insensitively. A "rooted target" is the bare
|
|
170
|
+
* root, home, or a named system directory — optionally quoted, optionally slash-terminated — never a subpath
|
|
171
|
+
* (`rm -rf /usr/local` and `rm -rf /tmp` are allowed; `rm -rf /usr` and `rm -rf /` are denied). Rules match any
|
|
172
|
+
* string leaf of the execution, so they fire on writes and patches that carry the payload, not only shell commands.
|
|
173
|
+
* Every repetition span is bounded and lazy — a pathological leaf must never degrade a rule into quadratic
|
|
174
|
+
* backtracking (scanned text can run to 1 MiB).
|
|
175
|
+
*/
|
|
176
|
+
export const DEFAULT_DENY_RULES = Object.freeze([
|
|
177
|
+
{
|
|
178
|
+
id: 'shell/rm-rooted',
|
|
179
|
+
// `rm` carrying a recursive flag (-r/-R/--recursive in any cluster) AND a force flag (-f/--force or
|
|
180
|
+
// --no-preserve-root), anywhere in the command segment, plus a bare root/home/system-dir token as an
|
|
181
|
+
// argument. Flag order and combined/separate spellings all match; operands after `--` do too.
|
|
182
|
+
pattern:
|
|
183
|
+
'\\brm\\b(?=[^;&|\\n]{0,1024}?\\s-\\w*r\\w*(?=[\\s;&|]|$)|[^;&|\\n]{0,1024}?--recursive\\b)' +
|
|
184
|
+
'(?=[^;&|\\n]{0,1024}?\\s-\\w*f\\w*(?=[\\s;&|]|$)|[^;&|\\n]{0,1024}?--force\\b|[^;&|\\n]{0,1024}?--no-preserve-root\\b)' +
|
|
185
|
+
'[^;&|\\n]{0,1024}?\\s["\']?(?:/\\*?|~/?|\\$HOME/?|\\$\\{HOME\\}/?|/(?:Users|System|Library|var|usr|etc|bin|sbin|opt|private)/?|--no-preserve-root)["\']?(?=[\\s;&|]|$)',
|
|
186
|
+
description: 'rm -rf against a filesystem root, home, or system directory',
|
|
187
|
+
},
|
|
188
|
+
{
|
|
189
|
+
id: 'shell/disk-destructive',
|
|
190
|
+
pattern:
|
|
191
|
+
'\\b(?:mkfs(?:\\.\\w+)?|newfs_\\w*|fdisk|gparted)\\b|' +
|
|
192
|
+
'\\bdiskutil\\s{1,8}(?:eraseDisk|eraseVolume|partitionDisk|apfs\\s{1,8}deleteContainer)\\b|' +
|
|
193
|
+
'\\bdd\\b[^;&|\\n]{0,1024}?\\bof\\s{0,4}=\\s{0,4}["\']?/dev/',
|
|
194
|
+
description: 'a disk-formatting or raw-device write command',
|
|
195
|
+
},
|
|
196
|
+
{
|
|
197
|
+
id: 'shell/find-delete-root',
|
|
198
|
+
pattern:
|
|
199
|
+
'\\bfind\\s{1,8}["\']?(?:/\\*?|~/?|\\$HOME/?|\\$\\{HOME\\}/?|/(?:Users|System|Library|var|usr|etc|bin|sbin|opt|private)/?)["\']?(?=[\\s;&|]|$)' +
|
|
200
|
+
'[^;&|\\n]{0,1024}?\\s-delete\\b',
|
|
201
|
+
description: 'find -delete starting at a filesystem root or home',
|
|
202
|
+
},
|
|
203
|
+
{
|
|
204
|
+
id: 'shell/pipe-to-shell',
|
|
205
|
+
// curl/wget output piped (through up to 16 intermediate filters) into sh/bash/zsh, optionally via sudo.
|
|
206
|
+
pattern: '\\b(?:curl|wget)\\b(?:[^|\\n]{0,1024}\\|\\s{0,16}){1,16}(?:sudo\\s{1,8})?(?:sh|bash|zsh)\\b',
|
|
207
|
+
description: 'a download piped straight into a shell',
|
|
208
|
+
},
|
|
209
|
+
{
|
|
210
|
+
id: 'shell/fork-bomb',
|
|
211
|
+
// `NAME(){ NAME | NAME & }` — a function that re-invokes itself piped to itself in the background
|
|
212
|
+
// (`:(){ :|:& };:` is the canonical spelling; any name variant matches). The name is capped at 64 chars
|
|
213
|
+
// so the `+`/backreference pair can't backtrack quadratically on huge text.
|
|
214
|
+
pattern: '([^\\s(){}|&;]{1,64})\\s{0,8}\\(\\s{0,8}\\)\\s{0,8}\\{\\s{0,8}\\1\\s{0,8}\\|\\s{0,8}\\1\\s{0,8}&',
|
|
215
|
+
description: 'a fork-bomb function definition',
|
|
216
|
+
},
|
|
217
|
+
{
|
|
218
|
+
id: 'secret/env-file',
|
|
219
|
+
// `.env`, `.envrc`, `.env.<name>` as a token — the preceding character may not be a word char or hyphen,
|
|
220
|
+
// so `my.env`, `some.envfile`, `NODE_ENV` and `.environment` do not match.
|
|
221
|
+
pattern: '(?:^|[^\\w-])\\.env(?:rc)?(?:\\.[\\w-]+)*\\b',
|
|
222
|
+
description: 'a .env file reference',
|
|
223
|
+
},
|
|
224
|
+
{
|
|
225
|
+
id: 'secret/ssh',
|
|
226
|
+
// `.ssh` as a directory (covers every file under it — config edits are persistence too), or a private-key /
|
|
227
|
+
// authorized_keys name anywhere it appears.
|
|
228
|
+
pattern: '(?:^|[^\\w-])(?:\\.ssh(?:[/;\'"\\s]|$)|id_(?:rsa|ed25519|ecdsa|dsa)\\b|authorized_keys\\b)',
|
|
229
|
+
description: 'an SSH directory or key-material reference',
|
|
230
|
+
},
|
|
231
|
+
{
|
|
232
|
+
id: 'secret/credentials',
|
|
233
|
+
pattern:
|
|
234
|
+
'(?:^|[^\\w-])(?:\\.aws/credentials\\b|\\.netrc\\b|\\.npmrc\\b|\\.pypirc\\b|\\.gnupg\\b|' +
|
|
235
|
+
'\\.kube/config\\b|\\.docker/config\\.json\\b|credentials\\.json\\b)',
|
|
236
|
+
description: 'a credential-store file reference',
|
|
237
|
+
},
|
|
238
|
+
{
|
|
239
|
+
id: 'secret/keychain',
|
|
240
|
+
pattern: '\\bsecurity\\s{1,8}(?:find-generic-password|find-internet-password|dump-keychain)\\b',
|
|
241
|
+
description: 'a macOS keychain secret read',
|
|
242
|
+
},
|
|
243
|
+
{
|
|
244
|
+
id: 'secret/cloud-tokens',
|
|
245
|
+
pattern:
|
|
246
|
+
'\\bgcloud\\s{1,8}auth\\s{1,8}print-(?:access|identity)-token\\b|\\baws\\s{1,8}sts\\s{1,8}get-session-token\\b|' +
|
|
247
|
+
'\\baz\\s{1,8}account\\s{1,8}get-access-token\\b|\\bvault\\s{1,8}(?:read|kv\\s{1,8}get)\\b',
|
|
248
|
+
description: 'a command that prints a cloud or vault token',
|
|
249
|
+
},
|
|
250
|
+
]);
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* One deny rule, normalized: `{id, pattern, description}` where `id` is a lowercase slug (`shell/rm-rooted`),
|
|
254
|
+
* `pattern` a RegExp source string (≤ 512 chars, must compile under the `i` flag) and `description` a non-empty
|
|
255
|
+
* sentence for the denial reason. Throws a plain Error for config/env/builtin (boot misconfiguration) or an
|
|
256
|
+
* AutoApproveError through `errorFor` for the remote's `denyAdd`.
|
|
257
|
+
*/
|
|
258
|
+
function denyRuleFor(entry, errorFor) {
|
|
259
|
+
if (!isRecord(entry)) throw errorFor('must be an object {id, pattern, description}');
|
|
260
|
+
const id = typeof entry.id === 'string' ? entry.id.trim() : '';
|
|
261
|
+
if (!DENY_RULE_ID.test(id)) throw errorFor(`id must match ${DENY_RULE_ID} (e.g. "shell/no-sudo")`);
|
|
262
|
+
const pattern = typeof entry.pattern === 'string' ? entry.pattern : '';
|
|
263
|
+
if (pattern.trim() === '') throw errorFor('pattern must be a non-empty regular-expression source string');
|
|
264
|
+
if (pattern.length > DENY_PATTERN_MAX) throw errorFor(`pattern must be at most ${DENY_PATTERN_MAX} characters`);
|
|
265
|
+
let regex;
|
|
266
|
+
try {
|
|
267
|
+
regex = new RegExp(pattern, 'i');
|
|
268
|
+
} catch (cause) {
|
|
269
|
+
throw errorFor(`pattern does not compile: ${cause?.message ?? cause}`);
|
|
270
|
+
}
|
|
271
|
+
const description = typeof entry.description === 'string' ? entry.description.trim() : '';
|
|
272
|
+
if (description === '') throw errorFor('description must be a non-empty string');
|
|
273
|
+
if (description.length > DENY_DESCRIPTION_MAX) throw errorFor(`description must be at most ${DENY_DESCRIPTION_MAX} characters`);
|
|
274
|
+
return { id, pattern, description, regex };
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Normalize a deny-rule list into compiled matchers. Anything malformed throws — a malformed policy mounted at
|
|
279
|
+
* boot is a misconfiguration, never a silent allow/deny (same posture as `compilePolicy`).
|
|
280
|
+
*/
|
|
281
|
+
export function compileDenyList(list, label = 'config.deny') {
|
|
282
|
+
if (list === undefined || list === null) return [];
|
|
283
|
+
if (!Array.isArray(list)) throw new Error(`${name}: ${label} must be an array of {id, pattern, description} rules`);
|
|
284
|
+
return list.map((entry, index) => denyRuleFor(entry, (reason) => new Error(`${name}: ${label}[${index}] ${reason}`)));
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** `denyAdd` argument validation: the normalized rule, or an `autoApprove/bad-rule` refusal. */
|
|
288
|
+
export function normalizeDenyRule(value) {
|
|
289
|
+
try {
|
|
290
|
+
return denyRuleFor(value, (reason) => new AutoApproveError('bad-rule', `A deny rule ${reason} (e.g. {id: "shell/no-sudo", pattern: "\\\\bsudo\\\\b", description: "…"}).`, { value }));
|
|
291
|
+
} catch (error) {
|
|
292
|
+
if (error instanceof AutoApproveError) throw error;
|
|
293
|
+
throw new AutoApproveError('bad-rule', String(error?.message ?? error), { value });
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** `denyRemove` argument validation: the rule id, or an `autoApprove/bad-rule` refusal. */
|
|
298
|
+
function normalizeDenyId(value) {
|
|
299
|
+
const id = isRecord(value) ? value.id : value;
|
|
300
|
+
if (typeof id !== 'string' || !DENY_RULE_ID.test(id.trim())) {
|
|
301
|
+
throw new AutoApproveError('bad-rule', `A deny rule id must match ${DENY_RULE_ID} (e.g. "shell/no-sudo").`, { value });
|
|
302
|
+
}
|
|
303
|
+
return id.trim();
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** `PICASSO_CONTENT_GUARD=[{"id":…,"pattern":…,"description":…}]` → rule list; unset/blank → undefined. */
|
|
307
|
+
export function denyFromEnv(env = process.env) {
|
|
308
|
+
const raw = env[ENV_DENY];
|
|
309
|
+
if (typeof raw !== 'string' || raw.trim() === '') return undefined;
|
|
310
|
+
try {
|
|
311
|
+
return JSON.parse(raw);
|
|
312
|
+
} catch (cause) {
|
|
313
|
+
throw new Error(`${name}: ${ENV_DENY} is not valid JSON (${cause?.message ?? cause})`);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** The ≤160-char leaf excerpt the denial reason reports. */
|
|
318
|
+
const leafExcerpt = (leaf) => (leaf.length > SCAN_EXCERPT_MAX ? `${leaf.slice(0, SCAN_EXCERPT_MAX - 1)}…` : leaf);
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* String leaves to scan: the top-level `command` (when a string) plus every string value inside `arguments`
|
|
322
|
+
* (objects and arrays recursed, cycles and depth > 24 pruned). Caps are generous — 256 leaves, 1 MiB of text —
|
|
323
|
+
* and what fits is still scanned whole when the caps cut collection short.
|
|
324
|
+
*/
|
|
325
|
+
function collectScanLeaves(args, command) {
|
|
326
|
+
const leaves = [];
|
|
327
|
+
const budget = { bytes: SCAN_MAX_BYTES };
|
|
328
|
+
const push = (value) => {
|
|
329
|
+
if (leaves.length >= SCAN_MAX_LEAVES || budget.bytes <= 0 || value === '') return;
|
|
330
|
+
const piece = value.length > budget.bytes ? value.slice(0, budget.bytes) : value;
|
|
331
|
+
budget.bytes -= piece.length;
|
|
332
|
+
leaves.push(piece);
|
|
333
|
+
};
|
|
334
|
+
if (typeof command === 'string') push(command);
|
|
335
|
+
const seen = new Set();
|
|
336
|
+
const walk = (value, depth) => {
|
|
337
|
+
if (depth > SCAN_MAX_DEPTH || leaves.length >= SCAN_MAX_LEAVES || budget.bytes <= 0) return;
|
|
338
|
+
if (typeof value === 'string') return push(value);
|
|
339
|
+
if (!isRecord(value) && !Array.isArray(value)) return;
|
|
340
|
+
if (seen.has(value)) return;
|
|
341
|
+
seen.add(value);
|
|
342
|
+
for (const item of Array.isArray(value) ? value : Object.values(value)) walk(item, depth + 1);
|
|
343
|
+
};
|
|
344
|
+
walk(args, 0);
|
|
345
|
+
return leaves;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
const emptyDenySidecar = () => ({ version: 1, rules: [] });
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* The deny-rule store and its effective denylist — same shape as {@link AutoApprove}: sources unioned first-tag-
|
|
352
|
+
* wins on id (builtin > config > env > sidecar), mutations serialize through `tail` and re-read the sidecar
|
|
353
|
+
* before writing. `scanExec`/`scanRequest` run before any allow logic; every hit lands in `journal` (cap 100).
|
|
354
|
+
*/
|
|
355
|
+
export class ContentGuard {
|
|
356
|
+
constructor(options) {
|
|
357
|
+
this.dataDir = resolve(options.dataDir);
|
|
358
|
+
this.sidecar = join(this.dataDir, DENY_SIDECAR_FILENAME);
|
|
359
|
+
this.now = options.now ?? Date.now;
|
|
360
|
+
this.tail = Promise.resolve();
|
|
361
|
+
// The denial journal: in-memory only (the session log's approval/asked+decided pair is the durable record);
|
|
362
|
+
// newest first, capped so a looping denial storm cannot grow it.
|
|
363
|
+
this.journal = [];
|
|
364
|
+
// Boot-time sources throw here, at mount, never at scan time — even the shipped defaults are validated.
|
|
365
|
+
this.builtinRules = denySourceRules(compileDenyList(DEFAULT_DENY_RULES, 'DEFAULT_DENY_RULES'), 'builtin');
|
|
366
|
+
this.configRules = denySourceRules(compileDenyList(options.deny, 'config.deny'), 'config');
|
|
367
|
+
this.envRules = denySourceRules(compileDenyList(denyFromEnv(options.env ?? process.env), ENV_DENY), 'env');
|
|
368
|
+
this.rebuild();
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// ── Remote surface (served as autoApprove/deny*; wire args are the parameter names) ───────────────────────────
|
|
372
|
+
|
|
373
|
+
/** `denyList` → `{path, rules:[{id, pattern, description, source, removable}]}` sorted by id for a stable UI. */
|
|
374
|
+
list() {
|
|
375
|
+
return this.serial(async () => {
|
|
376
|
+
this.rebuild();
|
|
377
|
+
return {
|
|
378
|
+
path: this.sidecar,
|
|
379
|
+
rules: [...this.ruleSources.entries()]
|
|
380
|
+
.map(([id, source]) => ({ id, pattern: this.ruleRows.get(id)?.pattern ?? '', description: this.ruleRows.get(id)?.description ?? '', source, removable: source === 'sidecar' }))
|
|
381
|
+
.sort((a, b) => a.id.localeCompare(b.id)),
|
|
382
|
+
};
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* `denyAdd {request:{id, pattern, description}}` — validates, persists into the sidecar and recompiles in
|
|
388
|
+
* place, so the rule denies the very next execution. Idempotent: an id any source already owns answers
|
|
389
|
+
* `added:false` with the owning source.
|
|
390
|
+
*/
|
|
391
|
+
add(request) {
|
|
392
|
+
return this.serial(async () => {
|
|
393
|
+
const rule = normalizeDenyRule(isRecord(request) ? request : {});
|
|
394
|
+
this.rebuild();
|
|
395
|
+
const existing = this.ruleSources.get(rule.id);
|
|
396
|
+
if (existing) return { id: rule.id, added: false, source: existing };
|
|
397
|
+
const state = this.read();
|
|
398
|
+
state.rules.push({ id: rule.id, pattern: rule.pattern, description: rule.description, addedAt: this.now() });
|
|
399
|
+
await this.write(state);
|
|
400
|
+
this.rebuild();
|
|
401
|
+
return { id: rule.id, added: true, source: 'sidecar' };
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* `denyRemove {request:{id}}` — drops the matching sidecar row. Builtin, config and env rules are not in the
|
|
407
|
+
* editable store: removing them here would lie about the effective denylist, so they refuse
|
|
408
|
+
* `autoApprove/not-removable`.
|
|
409
|
+
*/
|
|
410
|
+
remove(request) {
|
|
411
|
+
return this.serial(async () => {
|
|
412
|
+
const id = normalizeDenyId(request);
|
|
413
|
+
this.rebuild();
|
|
414
|
+
if (!this.ruleSources.has(id)) throw new AutoApproveError('not-found', `No deny rule named ${JSON.stringify(id)}.`, { id });
|
|
415
|
+
const source = this.ruleSources.get(id);
|
|
416
|
+
const state = this.read();
|
|
417
|
+
const before = state.rules.length;
|
|
418
|
+
state.rules = state.rules.filter((entry) => entry.id !== id);
|
|
419
|
+
if (state.rules.length === before) {
|
|
420
|
+
const origin = source === 'builtin' ? 'the built-in defaults' : source === 'env' ? ENV_DENY : 'the mounted config';
|
|
421
|
+
throw new AutoApproveError('not-removable', `Deny rule ${JSON.stringify(id)} comes from ${origin} — edit it there.`, { id, source });
|
|
422
|
+
}
|
|
423
|
+
await this.write(state);
|
|
424
|
+
this.rebuild();
|
|
425
|
+
return { id, removed: true };
|
|
426
|
+
});
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/** `denyClear` — drops every sidecar row (the UI's "remove all"); builtin, config and env rules stay. */
|
|
430
|
+
clear() {
|
|
431
|
+
return this.serial(async () => {
|
|
432
|
+
const state = this.read();
|
|
433
|
+
const removed = state.rules.length;
|
|
434
|
+
state.rules = [];
|
|
435
|
+
await this.write(state);
|
|
436
|
+
this.rebuild();
|
|
437
|
+
return { removed };
|
|
438
|
+
});
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/** `denials` → `{events:[…]}` — the in-memory denial journal, newest first. */
|
|
442
|
+
denials() {
|
|
443
|
+
return this.serial(async () => ({ events: [...this.journal] }));
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
// ── Scanning ────────────────────────────────────────────────────────────────────────────────────────────────
|
|
447
|
+
|
|
448
|
+
/** The first deny hit in a `tools/pre-execute` exec (`arguments` leaves plus a top-level `command`). */
|
|
449
|
+
scanExec(exec) {
|
|
450
|
+
if (!isRecord(exec)) return undefined;
|
|
451
|
+
return this.scan(collectScanLeaves(exec.arguments, exec.command), exec.name);
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/** The first deny hit in an `approval/request` (`arguments`/`input` leaves plus a top-level `command`). */
|
|
455
|
+
scanRequest(request) {
|
|
456
|
+
if (!isRecord(request)) return undefined;
|
|
457
|
+
return this.scan(collectScanLeaves(request.arguments ?? request.input, request.command), request.toolName);
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/**
|
|
461
|
+
* Rules outer, leaves inner: the earliest rule that hits any leaf wins, so the reported rule is the highest-
|
|
462
|
+
* precedence match (builtin > config > env > sidecar, then list order). Returns
|
|
463
|
+
* `{rule, leaf, toolName}` — `leaf` the ≤160-char excerpt the denial reason quotes.
|
|
464
|
+
*/
|
|
465
|
+
scan(leaves, toolName) {
|
|
466
|
+
for (const rule of this.policy) {
|
|
467
|
+
for (const leaf of leaves) {
|
|
468
|
+
if (rule.regex.test(leaf)) return { rule: { id: rule.id, pattern: rule.pattern, description: rule.description }, leaf: leafExcerpt(leaf), toolName };
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
return undefined;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/** Records a denial in the journal (`{at, rule, toolName, sessionId?, workspace?}`, newest first, cap 100). */
|
|
475
|
+
record(hit, context = {}) {
|
|
476
|
+
const entry = { at: this.now(), rule: hit.rule.id, toolName: hit.toolName };
|
|
477
|
+
if (typeof context.sessionId === 'string' && context.sessionId) entry.sessionId = context.sessionId;
|
|
478
|
+
if (typeof context.workspace === 'string' && context.workspace) entry.workspace = context.workspace;
|
|
479
|
+
this.journal.unshift(entry);
|
|
480
|
+
if (this.journal.length > DENIAL_JOURNAL_LIMIT) this.journal.length = DENIAL_JOURNAL_LIMIT;
|
|
481
|
+
return entry;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/** Rebuilds `ruleSources`/`ruleRows` (deduped on id, first tag wins: builtin > config > env > sidecar) and the live matcher set. */
|
|
485
|
+
rebuild() {
|
|
486
|
+
const rules = [...this.builtinRules, ...this.configRules, ...this.envRules, ...denySourceRules(this.read().rules.map((entry) => entry.compiled), 'sidecar')];
|
|
487
|
+
const sources = new Map();
|
|
488
|
+
const rows = new Map();
|
|
489
|
+
for (const { source, compiled } of rules) {
|
|
490
|
+
if (!sources.has(compiled.id)) {
|
|
491
|
+
sources.set(compiled.id, source);
|
|
492
|
+
rows.set(compiled.id, { pattern: compiled.pattern, description: compiled.description });
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
this.ruleSources = sources;
|
|
496
|
+
this.ruleRows = rows;
|
|
497
|
+
this.policy = rules.filter((rule) => sources.get(rule.compiled.id) === rule.source).map((rule) => rule.compiled);
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
// ── Store ───────────────────────────────────────────────────────────────────────────────────────────────────
|
|
501
|
+
|
|
502
|
+
/** The sidecar, leniently: a missing, malformed or corrupt document is no rules; junk entries drop out. */
|
|
503
|
+
read() {
|
|
504
|
+
try {
|
|
505
|
+
const parsed = JSON.parse(readFileSync(this.sidecar, 'utf8'));
|
|
506
|
+
if (!isRecord(parsed) || !Array.isArray(parsed.rules)) return emptyDenySidecar();
|
|
507
|
+
const rules = [];
|
|
508
|
+
for (const entry of parsed.rules) {
|
|
509
|
+
try {
|
|
510
|
+
const compiled = denyRuleFor(entry, () => new Error('skip'));
|
|
511
|
+
const addedAt = typeof entry.addedAt === 'number' ? entry.addedAt : 0;
|
|
512
|
+
rules.push({ id: compiled.id, pattern: compiled.pattern, description: compiled.description, addedAt, compiled });
|
|
513
|
+
} catch { /* a hand-edited junk row is skipped, never silently allowed or denied */ }
|
|
514
|
+
}
|
|
515
|
+
return { version: 1, rules };
|
|
516
|
+
} catch {
|
|
517
|
+
return emptyDenySidecar();
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
async write(state) {
|
|
522
|
+
await mkdir(this.dataDir, { recursive: true });
|
|
523
|
+
const temporary = `${this.sidecar}.${process.pid}.tmp`;
|
|
524
|
+
const rules = state.rules.map((entry) => ({ id: entry.id, pattern: entry.pattern, description: entry.description, addedAt: entry.addedAt ?? 0 }));
|
|
525
|
+
await writeFile(temporary, `${JSON.stringify({ version: 1, rules }, null, 2)}\n`, { mode: 0o600 });
|
|
526
|
+
await rename(temporary, this.sidecar);
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
serial(body) {
|
|
530
|
+
const run = this.tail.then(body, body);
|
|
531
|
+
this.tail = run.catch(() => undefined);
|
|
532
|
+
return run;
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
/** `(compiled, source)` rows for one deny-rule source list (builtin/config/env) or compiled sidecar entries. */
|
|
537
|
+
function denySourceRules(compiled, source) {
|
|
538
|
+
return compiled.map((rule) => ({ source, compiled: rule }));
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* Canonical JSON for argument fingerprints: object keys sorted recursively so
|
|
543
|
+
* `{a:1,b:2}` and `{b:2,a:1}` hash the same. Returns undefined for unserializable input.
|
|
544
|
+
*/
|
|
545
|
+
export function canonicalJson(value) {
|
|
546
|
+
if (value === undefined) return undefined;
|
|
547
|
+
const canon = (v) => {
|
|
548
|
+
if (v === null || typeof v !== 'object') return v;
|
|
549
|
+
if (Array.isArray(v)) return v.map(canon);
|
|
550
|
+
const out = {};
|
|
551
|
+
for (const key of Object.keys(v).sort()) {
|
|
552
|
+
const item = v[key];
|
|
553
|
+
if (item !== undefined && typeof item !== 'function') out[key] = canon(item);
|
|
554
|
+
}
|
|
555
|
+
return out;
|
|
556
|
+
};
|
|
557
|
+
try {
|
|
558
|
+
return JSON.stringify(canon(value));
|
|
559
|
+
} catch {
|
|
560
|
+
return undefined;
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
const ESCALATION_REASON = /escalat|elevated|sandbox_permissions|dangerouslydisablesandbox|outside the sandbox|outside the workspace/i;
|
|
565
|
+
|
|
566
|
+
/** An approval request that is a sandbox escalation — never auto-approvable (AO-006.12). */
|
|
567
|
+
export function isEscalationRequest(request) {
|
|
568
|
+
if (!isRecord(request)) return false;
|
|
569
|
+
if (request['escalation'] === true || request['sandboxEscalation'] === true || request['sandbox'] === true) return true;
|
|
570
|
+
const args = isRecord(request['arguments']) ? request['arguments'] : isRecord(request['input']) ? request['input'] : undefined;
|
|
571
|
+
if (args !== undefined && (args['sandbox_permissions'] !== undefined || args['dangerouslyDisableSandbox'] !== undefined)) return true;
|
|
572
|
+
return ESCALATION_REASON.test(String(request['reason'] ?? ''));
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
const MCP_SHARED_TOOLS = new Set(['list_mcp_resources', 'list_mcp_resource_templates', 'read_mcp_resource']);
|
|
576
|
+
|
|
577
|
+
/** `mcp__<server>__<tool>` plus the shared MCP resource tools (same vocabulary as picasso-sdk-server/mcp-gate.js). */
|
|
578
|
+
export function isMcpToolName(name) {
|
|
579
|
+
return typeof name === 'string' && (name.startsWith('mcp__') || MCP_SHARED_TOOLS.has(name));
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/** A `tools/pre-execute` exec whose arguments request sandbox escalation (e.g. `bash`'s `sandbox_permissions`). */
|
|
583
|
+
export function isEscalationExec(exec) {
|
|
584
|
+
if (!isRecord(exec)) return false;
|
|
585
|
+
if (exec['escalation'] === true || exec['sandboxEscalation'] === true) return true;
|
|
586
|
+
const args = isRecord(exec['arguments']) ? exec['arguments'] : undefined;
|
|
587
|
+
return args !== undefined && (args['sandbox_permissions'] !== undefined || args['dangerouslyDisableSandbox'] !== undefined);
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
const stringField = (value) => (typeof value === 'string' && value.trim() ? value.trim() : undefined);
|
|
591
|
+
|
|
592
|
+
/** The deciding context for a `approval/request` waterfall entry (the borrowed public request). */
|
|
593
|
+
export function contextFromRequest(request) {
|
|
594
|
+
if (!isRecord(request)) return {};
|
|
595
|
+
const agent = isRecord(request['agent']) ? request['agent'] : {};
|
|
596
|
+
const session = isRecord(agent['session']) ? agent['session'] : {};
|
|
597
|
+
return {
|
|
598
|
+
sessionId:
|
|
599
|
+
stringField(request['sessionId']) ??
|
|
600
|
+
stringField(session['id']) ??
|
|
601
|
+
stringField(agent['sessionId']) ??
|
|
602
|
+
stringField(agent['id']),
|
|
603
|
+
workspace:
|
|
604
|
+
stringField(request['workspace']) ??
|
|
605
|
+
stringField(request['cwd']) ??
|
|
606
|
+
stringField(agent['cwd']) ??
|
|
607
|
+
stringField(agent['workspace']),
|
|
608
|
+
argsCanonical: canonicalJson(request['arguments'] ?? request['input']),
|
|
609
|
+
child:
|
|
610
|
+
request['parent'] !== undefined ||
|
|
611
|
+
agent['parent'] !== undefined ||
|
|
612
|
+
agent['parentAgent'] !== undefined ||
|
|
613
|
+
request['depth'] === 'subagent',
|
|
614
|
+
};
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/** The deciding context for a `tools/pre-execute` exec. */
|
|
618
|
+
export function contextFromExec(exec) {
|
|
619
|
+
if (!isRecord(exec)) return {};
|
|
620
|
+
const agent = isRecord(exec['agent']) ? exec['agent'] : {};
|
|
621
|
+
const session = isRecord(agent['session']) ? agent['session'] : {};
|
|
622
|
+
return {
|
|
623
|
+
sessionId:
|
|
624
|
+
stringField(exec['sessionId']) ??
|
|
625
|
+
stringField(session['id']) ??
|
|
626
|
+
stringField(agent['sessionId']) ??
|
|
627
|
+
stringField(agent['id']),
|
|
628
|
+
workspace:
|
|
629
|
+
stringField(exec['workspace']) ??
|
|
630
|
+
stringField(agent['cwd']) ??
|
|
631
|
+
stringField(agent['workspace']),
|
|
632
|
+
argsCanonical: canonicalJson(exec['arguments']),
|
|
633
|
+
child: exec['parent'] !== undefined || agent['parent'] !== undefined || agent['parentAgent'] !== undefined,
|
|
634
|
+
};
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/** Optional scope fields a rule row may bind: `session`, `workspace`, `args`. */
|
|
638
|
+
export function normalizeScope(scope = {}) {
|
|
639
|
+
if (!isRecord(scope)) throw new AutoApproveError('bad-scope', 'Rule scope must be an object with optional session/workspace/args strings.');
|
|
640
|
+
const out = {};
|
|
641
|
+
for (const field of ['session', 'workspace', 'args']) {
|
|
642
|
+
const raw = scope[field];
|
|
643
|
+
if (raw === undefined || raw === null || raw === '') continue;
|
|
644
|
+
const max = field === 'args' ? 8192 : 1024;
|
|
645
|
+
if (typeof raw !== 'string' || !raw.trim()) {
|
|
646
|
+
throw new AutoApproveError('bad-scope', `Rule scope "${field}" must be a non-empty string when provided.`, { field, value: raw });
|
|
647
|
+
}
|
|
648
|
+
const trimmed = raw.trim();
|
|
649
|
+
if (trimmed.length > max) {
|
|
650
|
+
throw new AutoApproveError('bad-scope', `Rule scope "${field}" must be at most ${max} characters.`, { field });
|
|
651
|
+
}
|
|
652
|
+
out[field] = trimmed;
|
|
653
|
+
}
|
|
654
|
+
return out;
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
/** Dedupe/identity key for one rule row: pattern plus every bound scope field. */
|
|
658
|
+
const ruleKey = (rule) =>
|
|
659
|
+
`${rule.pattern}` +
|
|
660
|
+
(rule.session !== undefined ? `\0s:${rule.session}` : '') +
|
|
661
|
+
(rule.workspace !== undefined ? `\0w:${rule.workspace}` : '') +
|
|
662
|
+
(rule.args !== undefined ? `\0a:${rule.args}` : '');
|
|
663
|
+
|
|
664
|
+
/** Canonical-args match: exact, or trailing-`*` prefix like the tool-name patterns. */
|
|
665
|
+
const argsPatternMatches = (pattern, canonical) =>
|
|
666
|
+
pattern.endsWith('*') && pattern.length > 1 ? canonical.startsWith(pattern.slice(0, -1)) : canonical === pattern;
|
|
667
|
+
|
|
668
|
+
/**
|
|
669
|
+
* Whether one compiled rule's scope binds the deciding context. Unscoped rules match
|
|
670
|
+
* anything (operator boot policy). A bound `session`/`workspace` must equal the
|
|
671
|
+
* context's; a bound `args` pattern requires the ask to carry arguments that
|
|
672
|
+
* match it — an ask with no arguments never satisfies an args-bound rule.
|
|
673
|
+
*/
|
|
674
|
+
function scopeMatches(rule, context) {
|
|
675
|
+
if (rule.session === undefined && rule.workspace === undefined && rule.args === undefined) return true;
|
|
676
|
+
if (!isRecord(context)) return false;
|
|
677
|
+
if (rule.session !== undefined && rule.session !== context.sessionId) return false;
|
|
678
|
+
if (rule.workspace !== undefined && rule.workspace !== context.workspace) return false;
|
|
679
|
+
if (rule.args !== undefined && (context.argsCanonical === undefined || !argsPatternMatches(rule.args, context.argsCanonical))) return false;
|
|
680
|
+
return true;
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
/** True when a compiled policy grants `toolName` in `context` (optional scope context). */
|
|
684
|
+
export function policyAllows(policy, toolName, context) {
|
|
685
|
+
if (typeof toolName !== 'string' || toolName.length === 0) return false;
|
|
686
|
+
return policy.some(
|
|
687
|
+
(rule) => (rule.exact ? rule.prefix === toolName : toolName.startsWith(rule.prefix)) && scopeMatches(rule, context),
|
|
688
|
+
);
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
/** `PICASSO_AUTO_APPROVE=bash,fs_*,mcp__github__*` → pattern list; unset/blank → []. */
|
|
692
|
+
export function allowFromEnv(env = process.env) {
|
|
693
|
+
const raw = env[ENV_ALLOW];
|
|
694
|
+
if (typeof raw !== 'string' || raw.trim() === '') return undefined;
|
|
695
|
+
return raw.split(',').map((entry) => entry.trim()).filter(Boolean);
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
/** The dsh data directory: the parent of config `root` (dshHomePath('permissions')), else `$DSH_HOME`, else `~/.dsh`. */
|
|
699
|
+
export function dataDirFor(config) {
|
|
700
|
+
if (isRecord(config) && typeof config.root === 'string' && config.root) return dirname(config.root);
|
|
701
|
+
return process.env.DSH_HOME || join(homedir(), '.dsh');
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
const emptySidecar = () => ({ version: 1, rules: [] });
|
|
705
|
+
|
|
706
|
+
/**
|
|
707
|
+
* The rule store and its effective policy. `configAllow` is `config.allow`,
|
|
708
|
+
* `env` injectable for tests; mutations serialize through `tail` and re-read
|
|
709
|
+
* the sidecar before writing (last writer wins a whole-file race).
|
|
710
|
+
*/
|
|
711
|
+
export class AutoApprove {
|
|
712
|
+
constructor(options) {
|
|
713
|
+
this.dataDir = resolve(options.dataDir);
|
|
714
|
+
this.sidecar = join(this.dataDir, SIDECAR_FILENAME);
|
|
715
|
+
this.now = options.now ?? Date.now;
|
|
716
|
+
this.tail = Promise.resolve();
|
|
717
|
+
// Boot-time sources: a malformed config or env list is a misconfiguration —
|
|
718
|
+
// it throws here, at mount, never at decision time.
|
|
719
|
+
this.configRules = sourceRules(compilePolicy(options.allow, 'config.allow'), 'config');
|
|
720
|
+
this.envRules = sourceRules(compilePolicy(allowFromEnv(options.env ?? process.env), ENV_ALLOW), 'env');
|
|
721
|
+
// The content guard (deny layer) shares the data dir, so `picasso-content-guard.json` lands beside the
|
|
722
|
+
// allow sidecar; `deny:` mounts `config.deny`, `env` injects PICASSO_CONTENT_GUARD for tests.
|
|
723
|
+
this.guard = options.guard ?? new ContentGuard({ dataDir: this.dataDir, deny: options.deny, env: options.env ?? process.env, now: this.now });
|
|
724
|
+
this.rebuild();
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
// ── Remote surface (`autoApprove/<method>`; wire args are the parameter names) ─────────────────────────────────
|
|
728
|
+
|
|
729
|
+
/** `autoApprove/list` → `{path, rules:[{pattern, source, removable, session?, workspace?, args?}]}` sorted by pattern for a stable UI. */
|
|
730
|
+
list() {
|
|
731
|
+
return this.serial(async () => {
|
|
732
|
+
this.rebuild();
|
|
733
|
+
return {
|
|
734
|
+
path: this.sidecar,
|
|
735
|
+
rules: [...this.ruleSources.entries()]
|
|
736
|
+
.map(([key, source]) => ({
|
|
737
|
+
pattern: this.ruleRows.get(key)?.pattern ?? key,
|
|
738
|
+
source,
|
|
739
|
+
removable: source === 'sidecar',
|
|
740
|
+
...(['session', 'workspace', 'args'].reduce((out, field) => {
|
|
741
|
+
const value = this.ruleRows.get(key)?.[field];
|
|
742
|
+
if (value !== undefined) out[field] = value;
|
|
743
|
+
return out;
|
|
744
|
+
}, {})),
|
|
745
|
+
}))
|
|
746
|
+
.sort((a, b) => a.pattern.localeCompare(b.pattern) || ruleKey(a).localeCompare(ruleKey(b))),
|
|
747
|
+
};
|
|
748
|
+
});
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
/**
|
|
752
|
+
* `autoApprove/add {request:{pattern, session?, workspace?, args?}}` — validates, then persists into the
|
|
753
|
+
* sidecar and recompiles in place, so the rule answers the very next ask. AO-006.12: durable
|
|
754
|
+
* rules carry scope bindings (`session`/`workspace`/`args`) recorded by the "Always allow"
|
|
755
|
+
* click; a rule only grants when every bound field matches the asking context. Idempotent:
|
|
756
|
+
* a rule any source already grants (same pattern + scope) answers `added:false` with the
|
|
757
|
+
* source that owns it.
|
|
758
|
+
*/
|
|
759
|
+
add(request) {
|
|
760
|
+
return this.serial(async () => {
|
|
761
|
+
// The gateway binds one wire field per parameter name; scope rides inside `request`
|
|
762
|
+
// (`{pattern, session?, workspace?, args?}` — a bare string still means `{pattern}`).
|
|
763
|
+
const body = isRecord(request) ? request : { pattern: request };
|
|
764
|
+
const rule = normalizePattern(body.pattern);
|
|
765
|
+
const scope = normalizeScope({ session: body.session, workspace: body.workspace, args: body.args });
|
|
766
|
+
const key = ruleKey({ pattern: rule, ...scope });
|
|
767
|
+
this.rebuild();
|
|
768
|
+
const existing = this.ruleSources.get(key);
|
|
769
|
+
if (existing) return { pattern: rule, ...scope, added: false, source: existing };
|
|
770
|
+
const state = this.read();
|
|
771
|
+
state.rules.push({ pattern: rule, ...scope, addedAt: this.now() });
|
|
772
|
+
await this.write(state);
|
|
773
|
+
this.rebuild();
|
|
774
|
+
return { pattern: rule, ...scope, added: true, source: 'sidecar' };
|
|
775
|
+
});
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
/**
|
|
779
|
+
* `autoApprove/remove {request:{pattern, session?, workspace?, args?}}` — drops the matching sidecar
|
|
780
|
+
* row (scope binds the row to drop; unscoped remove only matches unscoped rows). Config and
|
|
781
|
+
* env rules are boot-time: removing them here would lie about the effective policy, so they
|
|
782
|
+
* refuse `autoApprove/not-removable`.
|
|
783
|
+
*/
|
|
784
|
+
remove(request) {
|
|
785
|
+
return this.serial(async () => {
|
|
786
|
+
const body = isRecord(request) ? request : { pattern: request };
|
|
787
|
+
const rule = normalizePattern(body.pattern);
|
|
788
|
+
const scope = normalizeScope({ session: body.session, workspace: body.workspace, args: body.args });
|
|
789
|
+
const key = ruleKey({ pattern: rule, ...scope });
|
|
790
|
+
this.rebuild();
|
|
791
|
+
if (!this.ruleSources.has(key)) throw new AutoApproveError('not-found', `No rule named ${JSON.stringify(rule)}.`, { pattern: rule, ...scope });
|
|
792
|
+
const source = this.ruleSources.get(key);
|
|
793
|
+
const state = this.read();
|
|
794
|
+
const before = state.rules.length;
|
|
795
|
+
state.rules = state.rules.filter((entry) => ruleKey(entry) !== key);
|
|
796
|
+
if (state.rules.length === before) {
|
|
797
|
+
throw new AutoApproveError('not-removable', `Rule ${JSON.stringify(rule)} comes from ${source === 'env' ? ENV_ALLOW : 'the mounted config'} — edit it there.`, { pattern: rule, ...scope, source });
|
|
798
|
+
}
|
|
799
|
+
await this.write(state);
|
|
800
|
+
this.rebuild();
|
|
801
|
+
return { pattern: rule, ...scope, removed: true };
|
|
802
|
+
});
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
/** `autoApprove/clear` — drops every sidecar row (the UI's "remove all"); config and env rules stay. */
|
|
806
|
+
clear() {
|
|
807
|
+
return this.serial(async () => {
|
|
808
|
+
const state = this.read();
|
|
809
|
+
const removed = state.rules.length;
|
|
810
|
+
state.rules = [];
|
|
811
|
+
await this.write(state);
|
|
812
|
+
this.rebuild();
|
|
813
|
+
return { removed };
|
|
814
|
+
});
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
// ── Content-guard remotes (`autoApprove/deny*`, same namespace so the relay admits them whole) ────────────────
|
|
818
|
+
|
|
819
|
+
/** `autoApprove/denyList` → `{path, rules:[{id, pattern, description, source, removable}]}` sorted by id. */
|
|
820
|
+
denyList() {
|
|
821
|
+
return this.guard.list();
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
/** `autoApprove/denyAdd {request:{id, pattern, description}}` — validates (`autoApprove/bad-rule`), persists, live next exec. */
|
|
825
|
+
denyAdd(request) {
|
|
826
|
+
return this.guard.add(request);
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
/** `autoApprove/denyRemove {request:{id}}` — sidecar rows only; builtin/config/env refuse `autoApprove/not-removable`. */
|
|
830
|
+
denyRemove(request) {
|
|
831
|
+
return this.guard.remove(request);
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
/** `autoApprove/denyClear` — drops every sidecar deny row; builtin/config/env rules stay. */
|
|
835
|
+
denyClear() {
|
|
836
|
+
return this.guard.clear();
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
/** `autoApprove/denials` → `{events:[…]}` — the denial journal, newest first. */
|
|
840
|
+
denials() {
|
|
841
|
+
return this.guard.denials();
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
// ── Policy ─────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
845
|
+
|
|
846
|
+
/** The live compiled policy grants `toolName` in `context` — read at decision time, so `add` lands on the next ask. */
|
|
847
|
+
allows(toolName, context) {
|
|
848
|
+
return policyAllows(this.policy, toolName, context);
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
/** Rebuilds `ruleSources`/`ruleRows` (deduped, first tag wins: config > env > sidecar) and the compiled matcher set. */
|
|
852
|
+
rebuild() {
|
|
853
|
+
const rules = [...this.configRules, ...this.envRules, ...sourceRules(this.read().rules.map((entry) => entry.compiled), 'sidecar')];
|
|
854
|
+
const sources = new Map();
|
|
855
|
+
const rows = new Map();
|
|
856
|
+
for (const { pattern, session, workspace, args, source, compiled } of rules) {
|
|
857
|
+
const key = ruleKey(compiled);
|
|
858
|
+
if (!sources.has(key)) {
|
|
859
|
+
sources.set(key, { source, compiled });
|
|
860
|
+
rows.set(key, { pattern, session, workspace, args });
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
this.ruleSources = new Map([...sources.entries()].map(([key, entry]) => [key, entry.source]));
|
|
864
|
+
this.ruleRows = rows;
|
|
865
|
+
this.policy = [...sources.values()].map((entry) => entry.compiled);
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
// ── Store ───────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
869
|
+
|
|
870
|
+
/** The sidecar, leniently: a missing, malformed or corrupt document is no rules; junk entries drop out. */
|
|
871
|
+
read() {
|
|
872
|
+
try {
|
|
873
|
+
const parsed = JSON.parse(readFileSync(this.sidecar, 'utf8'));
|
|
874
|
+
if (!isRecord(parsed) || !Array.isArray(parsed.rules)) return emptySidecar();
|
|
875
|
+
const rules = [];
|
|
876
|
+
for (const entry of parsed.rules) {
|
|
877
|
+
const raw = typeof entry === 'string' ? entry : isRecord(entry) ? entry.pattern : undefined;
|
|
878
|
+
const addedAt = isRecord(entry) && typeof entry.addedAt === 'number' ? entry.addedAt : 0;
|
|
879
|
+
try {
|
|
880
|
+
const compiled = patternFor(raw, () => new Error('skip'));
|
|
881
|
+
const scope = {};
|
|
882
|
+
for (const field of ['session', 'workspace', 'args']) {
|
|
883
|
+
const value = isRecord(entry) ? entry[field] : undefined;
|
|
884
|
+
if (typeof value === 'string' && value.trim()) scope[field] = value.trim();
|
|
885
|
+
}
|
|
886
|
+
rules.push({ pattern: compiled.pattern, ...scope, addedAt, compiled: { ...compiled, ...scope } });
|
|
887
|
+
} catch { /* a hand-edited junk row is skipped, never silently allowed or denied */ }
|
|
888
|
+
}
|
|
889
|
+
return { version: 1, rules };
|
|
890
|
+
} catch {
|
|
891
|
+
return emptySidecar();
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
async write(state) {
|
|
896
|
+
await mkdir(this.dataDir, { recursive: true });
|
|
897
|
+
const temporary = `${this.sidecar}.${process.pid}.tmp`;
|
|
898
|
+
const rules = state.rules.map((entry) => ({
|
|
899
|
+
pattern: entry.pattern,
|
|
900
|
+
...(['session', 'workspace', 'args'].reduce((out, field) => {
|
|
901
|
+
if (typeof entry[field] === 'string' && entry[field]) out[field] = entry[field];
|
|
902
|
+
return out;
|
|
903
|
+
}, {})),
|
|
904
|
+
addedAt: entry.addedAt ?? 0,
|
|
905
|
+
}));
|
|
906
|
+
await writeFile(temporary, `${JSON.stringify({ version: 1, rules }, null, 2)}\n`, { mode: 0o600 });
|
|
907
|
+
await rename(temporary, this.sidecar);
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
serial(body) {
|
|
911
|
+
const run = this.tail.then(body, body);
|
|
912
|
+
this.tail = run.catch(() => undefined);
|
|
913
|
+
return run;
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
/** `(pattern, scope, source)` rows for one source list (config/env) or compiled sidecar entries. */
|
|
918
|
+
function sourceRules(compiled, source) {
|
|
919
|
+
return compiled.map((rule) => ({
|
|
920
|
+
pattern: rule.pattern,
|
|
921
|
+
session: rule.session,
|
|
922
|
+
workspace: rule.workspace,
|
|
923
|
+
args: rule.args,
|
|
924
|
+
source,
|
|
925
|
+
compiled: rule,
|
|
926
|
+
}));
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
const REMOTE_METHODS = ['list', 'add', 'remove', 'clear', 'denyList', 'denyAdd', 'denyRemove', 'denyClear', 'denials'];
|
|
930
|
+
|
|
931
|
+
Object.defineProperty(AutoApprove.prototype, REMOTE_METHOD_DESCRIPTOR, {
|
|
932
|
+
configurable: true,
|
|
933
|
+
value: Object.freeze({ version: 1, methods: Object.freeze(REMOTE_METHODS.map((method) => Object.freeze({ method, invocation: Object.freeze({ kind: 'direct' }) }))) }),
|
|
934
|
+
});
|
|
935
|
+
|
|
936
|
+
/**
|
|
937
|
+
* Cordis entry. Provides `autoApprove` bound for the Typert gateway and always mounts both listeners: a
|
|
938
|
+
* request no rule matches defers (`next()` / the untouched gate), so an empty policy costs two pass-through
|
|
939
|
+
* handlers — and a rule added through the remote takes effect this engine run, no restart.
|
|
940
|
+
*/
|
|
941
|
+
export function apply(ctx, config = {}) {
|
|
942
|
+
const service = new AutoApprove({ dataDir: dataDirFor(config), allow: config?.allow, deny: config?.deny, env: process.env });
|
|
943
|
+
service.typertRemote = Object.freeze({ service, serviceKey: SERVICE_KEY, namespace: SERVICE_KEY });
|
|
944
|
+
ctx.provide(SERVICE_KEY, service);
|
|
945
|
+
const disposers = [
|
|
946
|
+
ctx.on('approval/request', (request, next) => {
|
|
947
|
+
// The content guard answers first: denied content is rejected outright (the
|
|
948
|
+
// service still logs the approval/asked+decided audit pair), and a `*`
|
|
949
|
+
// allowlist — or the escalation deferral — can never rescue it.
|
|
950
|
+
const hit = service.guard.scanRequest(request);
|
|
951
|
+
if (hit) {
|
|
952
|
+
service.guard.record(hit, contextFromRequest(request));
|
|
953
|
+
return 'rejected';
|
|
954
|
+
}
|
|
955
|
+
// AO-006.12: sandbox escalation asks are never auto-approved — a broad rule
|
|
956
|
+
// like `bash` cannot widen into an escalation grant — and scoped durable
|
|
957
|
+
// rules only grant when every bound field matches the asking context
|
|
958
|
+
// (a child session never matches its parent's session-scoped rule).
|
|
959
|
+
if (
|
|
960
|
+
isRecord(request) &&
|
|
961
|
+
!isEscalationRequest(request) &&
|
|
962
|
+
service.allows(request.toolName, contextFromRequest(request))
|
|
963
|
+
) {
|
|
964
|
+
return OUTCOME_ALLOW;
|
|
965
|
+
}
|
|
966
|
+
return next();
|
|
967
|
+
}),
|
|
968
|
+
ctx.on('tools/pre-execute', async (exec, next) => {
|
|
969
|
+
// The content guard gates first: a hit is `{kind:'deny', reason}` (model-
|
|
970
|
+
// visible, like the ignore-file guard) before any downstream gate runs —
|
|
971
|
+
// deny evaluation always precedes allow evaluation.
|
|
972
|
+
const hit = service.guard.scanExec(exec);
|
|
973
|
+
if (hit) {
|
|
974
|
+
service.guard.record(hit, contextFromExec(exec));
|
|
975
|
+
return { kind: 'deny', reason: `contentGuard/${hit.rule.id}: ${hit.rule.description} — matched ${hit.leaf}` };
|
|
976
|
+
}
|
|
977
|
+
let gate = await next();
|
|
978
|
+
// MCP admission condition 1 (docs/mcp-connector-review.md): a third-party MCP call never runs ungated. The
|
|
979
|
+
// CLI's sdk-server mounts mcp-gate.js; this composition (the Mac) does not, so the gate is here. The ask goes
|
|
980
|
+
// through approval/request below, where an "Always allow" rule for the tool or server answers it.
|
|
981
|
+
if ((gate === undefined || gate?.kind === 'allow') && isMcpToolName(exec?.name)) {
|
|
982
|
+
gate = { kind: 'ask', reason: `MCP tool "${exec.name}" — third-party MCP server call requires per-call approval.` };
|
|
983
|
+
}
|
|
984
|
+
// Only rescue asks that would fail closed for want of an approval service;
|
|
985
|
+
// a mounted service owns the (audited) answer through approval/request.
|
|
986
|
+
// AO-006.12: an execution whose arguments request sandbox escalation
|
|
987
|
+
// (`sandbox_permissions`, `dangerouslyDisableSandbox`) is never rescued —
|
|
988
|
+
// it must reach a human answerer even under a `bash` allowlist.
|
|
989
|
+
if (
|
|
990
|
+
gate?.kind === 'ask' &&
|
|
991
|
+
ctx.get?.('approval') === undefined &&
|
|
992
|
+
!isEscalationExec(exec) &&
|
|
993
|
+
service.allows(exec?.name, contextFromExec(exec))
|
|
994
|
+
) {
|
|
995
|
+
return { kind: 'allow' };
|
|
996
|
+
}
|
|
997
|
+
return gate;
|
|
998
|
+
}),
|
|
999
|
+
];
|
|
1000
|
+
return () => {
|
|
1001
|
+
for (const dispose of disposers) dispose?.();
|
|
1002
|
+
};
|
|
1003
|
+
}
|