@justfortytwo/gate 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/policy.js ADDED
@@ -0,0 +1,253 @@
1
+ // Content-trust policy engine: the "who said this, and may it instruct the agent?"
2
+ // half of the gate's contract. It classifies an inbound source into an authority
3
+ // level and a memory class, decides whether content may be used as an instruction
4
+ // vs. merely analyzed, and ranks recalled items by trust. It is deliberately free
5
+ // of any storage/DB concern — it is pure data in, pure decision out.
6
+ //
7
+ // The shape of these types + the classification rules are the `policySchema`
8
+ // contract that downstream `@justfortytwo/*` packages depend on; the version of
9
+ // that contract is exported as POLICY_SCHEMA_VERSION from ./index.ts. Any change
10
+ // to the meaning of an Authority/MemoryClass, or to a decidePolicy() outcome, is a
11
+ // contract break and must bump the major version (and the schema version).
12
+ //
13
+ // NOTE: a handful of SourceKind values below describe inbound transport channels
14
+ // (chat messages, email, direct-owner statements). They are kept as generic,
15
+ // host-agnostic labels here. A host integration may want to map its own channels
16
+ // onto these.
17
+ // TODO(extract): host channel -> SourceKind mapping belongs to the host
18
+ // integration package, not to the standalone gate. The gate only needs the
19
+ // trusted/untrusted distinction.
20
+ import { createHash } from 'node:crypto';
21
+ const TRUSTED_SOURCES = {
22
+ repo_policy: 'trusted_policy',
23
+ approved_rule: 'trusted_policy',
24
+ installed_skill: 'trusted_procedure',
25
+ owner_direct: 'trusted_user',
26
+ approval_record: 'trusted_approval',
27
+ repo_document: 'evidence',
28
+ assistant_message: 'evidence',
29
+ guide_doc: 'evidence',
30
+ memory_recall: 'evidence',
31
+ };
32
+ const UNTRUSTED_SOURCES = new Set([
33
+ 'chat_message', 'chat_photo', 'chat_document', 'quoted_text', 'document', 'web_page', 'email', 'tool_output', 'mcp_output', 'plugin_output',
34
+ ]);
35
+ const SOURCE_DEFAULT_CLASS = {
36
+ repo_policy: 'canonical_rule',
37
+ repo_document: 'working_note',
38
+ approved_rule: 'canonical_rule',
39
+ installed_skill: 'working_note',
40
+ owner_direct: 'journal_fact',
41
+ approval_record: 'pending_decision',
42
+ assistant_message: 'journal_fact',
43
+ guide_doc: 'journal_fact',
44
+ chat_message: 'journal_fact',
45
+ chat_photo: 'untrusted_claim',
46
+ chat_document: 'untrusted_claim',
47
+ quoted_text: 'untrusted_claim',
48
+ document: 'untrusted_claim',
49
+ web_page: 'untrusted_claim',
50
+ email: 'untrusted_claim',
51
+ tool_output: 'untrusted_claim',
52
+ mcp_output: 'untrusted_claim',
53
+ plugin_output: 'untrusted_claim',
54
+ memory_recall: 'journal_fact',
55
+ };
56
+ const CLASS_PRIORITY = {
57
+ canonical_rule: 100,
58
+ preference: 80,
59
+ pending_decision: 75,
60
+ journal_fact: 60,
61
+ working_note: 45,
62
+ inferred_trait: 25,
63
+ untrusted_claim: 15,
64
+ secret: 0,
65
+ };
66
+ const AUTHORITIES = new Set([
67
+ 'trusted_policy', 'trusted_user', 'trusted_approval', 'trusted_procedure', 'evidence', 'untrusted_content',
68
+ ]);
69
+ function sha256(s) {
70
+ return createHash('sha256').update(s).digest('hex');
71
+ }
72
+ function isAuthority(value) {
73
+ return typeof value === 'string' && AUTHORITIES.has(value);
74
+ }
75
+ function isKnownSourceKind(value) {
76
+ return Object.prototype.hasOwnProperty.call(SOURCE_DEFAULT_CLASS, value);
77
+ }
78
+ function stableSourceId(input, contentHash) {
79
+ return `src_${sha256([
80
+ input.source_kind,
81
+ input.actor ?? '',
82
+ input.channel ?? '',
83
+ input.parent_source_id ?? '',
84
+ contentHash,
85
+ ].join('\0')).slice(0, 24)}`;
86
+ }
87
+ export function classifyAuthority(source) {
88
+ if (UNTRUSTED_SOURCES.has(source))
89
+ return 'untrusted_content';
90
+ if (isKnownSourceKind(source))
91
+ return TRUSTED_SOURCES[source] ?? 'untrusted_content';
92
+ return 'untrusted_content';
93
+ }
94
+ export function defaultMemoryClassForSource(source) {
95
+ return isKnownSourceKind(source) ? SOURCE_DEFAULT_CLASS[source] : 'untrusted_claim';
96
+ }
97
+ export function recallPriorityForMemoryClass(memoryClass) {
98
+ return CLASS_PRIORITY[memoryClass];
99
+ }
100
+ export function createSourceEnvelope(input) {
101
+ const sourceKind = String(input.source_kind);
102
+ const classifiedAuthority = classifyAuthority(sourceKind);
103
+ const authority = isAuthority(input.authority) && input.authority === classifiedAuthority
104
+ ? input.authority
105
+ : classifiedAuthority;
106
+ const memoryClass = input.memory_class ?? defaultMemoryClassForSource(sourceKind);
107
+ const contentHash = sha256(input.content);
108
+ return {
109
+ source_id: input.source_id ?? stableSourceId(input, contentHash),
110
+ source_kind: sourceKind,
111
+ authority,
112
+ memory_class: memoryClass,
113
+ actor: input.actor,
114
+ channel: input.channel,
115
+ content_hash: contentHash,
116
+ parent_source_id: input.parent_source_id ?? null,
117
+ created_at: input.created_at ?? new Date().toISOString(),
118
+ metadata: input.metadata,
119
+ };
120
+ }
121
+ function defaultClassFor(input, authority) {
122
+ if (input.memory_class)
123
+ return input.memory_class;
124
+ switch (input.requested_operation) {
125
+ case 'store_working_note': return 'working_note';
126
+ case 'store_preference': return authority === 'trusted_user' && input.direct_user_statement ? 'preference' : 'inferred_trait';
127
+ case 'promote_to_canonical_rule': return 'canonical_rule';
128
+ case 'store_inferred_trait': return 'inferred_trait';
129
+ case 'store_secret': return 'secret';
130
+ case 'approve_action': return 'pending_decision';
131
+ case 'extract_fact': return authority === 'untrusted_content' ? 'untrusted_claim' : 'journal_fact';
132
+ default: return defaultMemoryClassForSource(input.source);
133
+ }
134
+ }
135
+ function classPolicy(memoryClass) {
136
+ switch (memoryClass) {
137
+ case 'canonical_rule': return { approval_required: true, provenance_required: true, must_propose: true };
138
+ case 'preference': return { approval_required: false, provenance_required: true, must_propose: false };
139
+ case 'inferred_trait': return { approval_required: true, provenance_required: true, must_propose: true };
140
+ case 'secret': return { approval_required: true, provenance_required: true, must_propose: false };
141
+ case 'untrusted_claim': return { approval_required: false, provenance_required: true, must_propose: false };
142
+ case 'pending_decision': return { approval_required: true, provenance_required: true, must_propose: false };
143
+ case 'working_note': return { approval_required: false, provenance_required: true, must_propose: false };
144
+ case 'journal_fact': return { approval_required: false, provenance_required: true, must_propose: false };
145
+ }
146
+ }
147
+ function isTrustedInstructionAuthority(authority) {
148
+ return authority === 'trusted_policy' || authority === 'trusted_user' || authority === 'trusted_approval' || authority === 'trusted_procedure';
149
+ }
150
+ export function canUseAsInstruction(sourceOrAuthority) {
151
+ const authority = isAuthority(sourceOrAuthority)
152
+ ? sourceOrAuthority
153
+ : classifyAuthority(sourceOrAuthority);
154
+ return isTrustedInstructionAuthority(authority);
155
+ }
156
+ export function decidePolicy(input) {
157
+ const authority = classifyAuthority(input.source);
158
+ const memoryClass = defaultClassFor(input, authority);
159
+ const policy = classPolicy(memoryClass);
160
+ const canInstruct = canUseAsInstruction(authority);
161
+ let allowed = true;
162
+ let mustPropose = policy.must_propose;
163
+ let approvalRequired = policy.approval_required;
164
+ let reason = 'allowed under class policy';
165
+ if (input.requested_operation === 'summarize' || input.requested_operation === 'extract_fact') {
166
+ allowed = true;
167
+ approvalRequired = false;
168
+ reason = 'content may be analyzed as content';
169
+ }
170
+ if (input.requested_operation === 'use_as_instruction') {
171
+ allowed = canInstruct;
172
+ approvalRequired = !canInstruct;
173
+ reason = canInstruct ? 'trusted authority may instruct the agent' : 'content/evidence cannot instruct the agent';
174
+ }
175
+ if (input.requested_operation === 'execute_tool' || input.requested_operation === 'approve_action') {
176
+ allowed = authority === 'trusted_approval';
177
+ approvalRequired = !allowed;
178
+ reason = allowed ? 'explicit approval record grants action' : 'action requires explicit approval';
179
+ }
180
+ if (input.requested_operation === 'promote_to_canonical_rule') {
181
+ allowed = authority === 'trusted_policy' || authority === 'trusted_approval';
182
+ approvalRequired = !allowed;
183
+ mustPropose = !allowed;
184
+ reason = allowed ? 'trusted policy/approval may change canonical rules' : 'canonical rule changes must be proposed and approved';
185
+ }
186
+ if (input.requested_operation === 'store_preference') {
187
+ if (authority === 'trusted_user' && input.direct_user_statement) {
188
+ allowed = true;
189
+ mustPropose = false;
190
+ approvalRequired = false;
191
+ reason = 'direct user preference may be stored with provenance';
192
+ }
193
+ else {
194
+ allowed = false;
195
+ mustPropose = true;
196
+ approvalRequired = true;
197
+ reason = 'inferred or untrusted preference must be proposed';
198
+ }
199
+ }
200
+ if (input.requested_operation === 'store_secret') {
201
+ allowed = false;
202
+ approvalRequired = true;
203
+ reason = 'secrets must not be stored in durable memory';
204
+ }
205
+ return {
206
+ authority,
207
+ memory_class: memoryClass,
208
+ allowed,
209
+ must_propose: mustPropose,
210
+ approval_required: approvalRequired,
211
+ provenance_required: policy.provenance_required,
212
+ recall_priority: recallPriorityForMemoryClass(memoryClass),
213
+ can_use_as_instruction: canInstruct,
214
+ reason,
215
+ };
216
+ }
217
+ export function rankRecall(items) {
218
+ return items
219
+ .map((item) => {
220
+ const authority = classifyAuthority(item.source);
221
+ return {
222
+ ...item,
223
+ authority,
224
+ recall_priority: recallPriorityForMemoryClass(item.memory_class),
225
+ can_use_as_instruction: canUseAsInstruction(authority),
226
+ };
227
+ })
228
+ .sort((a, b) => b.recall_priority - a.recall_priority);
229
+ }
230
+ function packText(s) {
231
+ return s
232
+ .replace(/\r?\n/g, ' ')
233
+ .replace(/\|/g, '\\|')
234
+ .replace(/\s+/g, ' ')
235
+ .trim();
236
+ }
237
+ export function renderContextPack(items) {
238
+ const lines = ['CP/1 rows: id|src|auth|mc|p|can|txt'];
239
+ for (const item of items) {
240
+ const source = item.source_kind ?? String(item.source ?? 'unknown');
241
+ lines.push([
242
+ packText(String(item.id)),
243
+ packText(source),
244
+ item.authority,
245
+ item.memory_class,
246
+ String(item.recall_priority),
247
+ item.can_use_as_instruction ? '1' : '0',
248
+ packText(item.content),
249
+ ].join('|'));
250
+ }
251
+ return lines.join('\n');
252
+ }
253
+ //# sourceMappingURL=policy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"policy.js","sourceRoot":"","sources":["../src/policy.ts"],"names":[],"mappings":"AAAA,mFAAmF;AACnF,iFAAiF;AACjF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-allowlist.jsonl in your project (or point the gate at it
3
+ # via the GATE_BASH_ALLOWLIST env var).
4
+ #
5
+ # Fields: command_glob (required), cwd_glob (optional, default *), expires_at
6
+ # (optional ISO 8601), approved_by (optional), note (optional).
7
+ #
8
+ # Bash fails CLOSED: a command that is not matched here (and is not an auto
9
+ # read/internal tool) is deferred for approval. This file is the ONE place
10
+ # known-safe commands are permitted. Make it a [guard] file so the agent cannot
11
+ # silently weaken it — only you can.
12
+ #
13
+ # SECURITY: command_glob is anchored (^...$) and matched against the WHOLE command.
14
+ # - Prefer EXACT commands (no trailing *). An exact glob like "npm test" will NOT
15
+ # match "npm test && curl evil" — that is the point.
16
+ # - A trailing * (e.g. "git diff *") re-enables command chaining
17
+ # ("git diff x && rm -rf /"), so use it sparingly and only for safe verbs.
18
+ # - DENY ALWAYS WINS: any command flagged by a [bash] pattern in capabilities.toml
19
+ # (git push, curl --data/wget, chmod, rm -rf, sudo, ...) can NEVER be permitted
20
+ # here, even with a matching glob. A broad "git *" will fast-path "git status"
21
+ # but still defers "git push" for approval.
22
+ #
23
+ # Starter set: read-only inspection + in-repo dev commands.
24
+ {"command_glob":"git status","note":"read-only repo status"}
25
+ {"command_glob":"git diff","note":"read-only unstaged diff"}
26
+ {"command_glob":"git diff --staged","note":"read-only staged diff"}
27
+ {"command_glob":"git log --oneline -20","note":"read-only recent history"}
28
+ {"command_glob":"git branch","note":"read-only branch list"}
29
+ {"command_glob":"npm test","note":"in-repo test script"}
30
+ {"command_glob":"npm run build","note":"in-repo build script"}
@@ -0,0 +1,70 @@
1
+ # Example capability manifest — the safety gate's source of truth.
2
+ #
3
+ # Copy this to .claude/policy/capabilities.toml in your project (or point the gate
4
+ # at it via the GATE_MANIFEST env var) and tune it to your tools.
5
+ #
6
+ # Every tool the agent can call is tagged with an autonomy tier:
7
+ # read auto — fetch/lookup (web, files)
8
+ # internal auto — own workspace: notes, files, todos
9
+ # draft auto — produce drafts, stage work
10
+ # external confirm — outward message/email/post to a 3rd party
11
+ # irreversible confirm — payments, deletes, signing, AND editing this guard
12
+ #
13
+ # On an [external]/[irreversible] call the PreToolUse hook defers (pauses the turn),
14
+ # stages a one-shot approval, and only an out-of-band approval lets it run once.
15
+ # THIS FILE IS ITSELF GUARDED (see [guard]); the agent cannot silently weaken it.
16
+
17
+ default_tier = "external"
18
+
19
+ [tiers]
20
+ # --- read-only native tools ---
21
+ "Read" = "read"
22
+ "Glob" = "read"
23
+ "Grep" = "read"
24
+ "WebFetch" = "read"
25
+ "WebSearch" = "read"
26
+ # --- own-workspace native tools ---
27
+ "TodoWrite" = "internal"
28
+ "Write" = "internal"
29
+ "Edit" = "internal"
30
+ "NotebookEdit" = "internal"
31
+ "Task" = "internal"
32
+ "ExitPlanMode" = "internal"
33
+ "AskUserQuestion" = "internal"
34
+ # Bash: fails CLOSED. Base tier is external (defer) — the [bash] patterns below
35
+ # only ELEVATE (e.g. to irreversible), never lower it. An unmatched command is
36
+ # deferred for approval, not auto-run. Known-safe commands are permitted via the
37
+ # bash allowlist JSONL (allowlist), not by tiering them down here.
38
+ "Bash" = "external"
39
+ # --- example: a third-party messaging MCP — anything outward is external ---
40
+ "mcp__messaging__*" = "external"
41
+
42
+ # Bash command patterns (JS regex) that ELEVATE the tier above the external base.
43
+ # Highest matching tier wins; patterns can only raise, never lower. They double as
44
+ # a DENYLIST: a command matching ANY pattern here can never be satisfied by the
45
+ # bash allowlist (deny always wins), so a broad allowlist glob like `git *` cannot
46
+ # launder `git push`. Their job is to flag the clearly-dangerous commands; ordinary
47
+ # commands are already deferred by the external base.
48
+ # NOTE: these are JS-regex literals consumed by the gate's own raw-passthrough TOML
49
+ # parser, so use SINGLE backslashes (\b, \s) — not the doubled \\b a strict TOML
50
+ # parser would require.
51
+ [bash]
52
+ "\brm\s+(-[a-zA-Z]*r[a-zA-Z]*f?|--force)\b" = "irreversible"
53
+ "\brm\s+-rf?\b" = "irreversible"
54
+ "\bdd\s+if=" = "irreversible"
55
+ "\bmkfs\b" = "irreversible"
56
+ ":\(\)\s*\{.*\}\s*;\s*:" = "irreversible" # fork bomb
57
+ "\bsudo\b" = "irreversible"
58
+ "\bchmod\b|\bchown\b" = "external"
59
+ "\bgit\s+push\b" = "external"
60
+ "\bcurl\b.*-X\s*POST|\bcurl\b.*--data|\bwget\b" = "external"
61
+ "\bDROP\s+TABLE\b|\bDELETE\s+FROM\b" = "external"
62
+
63
+ # Editing these files is [irreversible] — protect the guard.
64
+ # Project-relative paths.
65
+ [guard]
66
+ files = [
67
+ ".claude/policy/capabilities.toml",
68
+ ".claude/settings.json",
69
+ "rules/bash-allowlist.jsonl",
70
+ ]
@@ -0,0 +1,15 @@
1
+ {
2
+ "hooks": {
3
+ "PreToolUse": [
4
+ {
5
+ "matcher": "*",
6
+ "hooks": [
7
+ {
8
+ "type": "command",
9
+ "command": "node ${CLAUDE_PLUGIN_ROOT}/dist/gate-hook.js"
10
+ }
11
+ ]
12
+ }
13
+ ]
14
+ }
15
+ }
package/package.json ADDED
@@ -0,0 +1,65 @@
1
+ {
2
+ "name": "@justfortytwo/gate",
3
+ "version": "0.1.0",
4
+ "description": "Standalone, agent-agnostic PreToolUse safety gate for Claude Code: an autonomy-tier policy engine, a fail-closed bash allowlist, and a hook that turns dangerous tool calls into one-shot approvals.",
5
+ "license": "MIT",
6
+ "author": {
7
+ "name": "Enrico Deleo",
8
+ "url": "https://enricodeleo.com"
9
+ },
10
+ "homepage": "https://forty-two.it",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/justfortytwo/gate.git"
14
+ },
15
+ "type": "module",
16
+ "engines": {
17
+ "node": ">=18"
18
+ },
19
+ "main": "./dist/index.js",
20
+ "types": "./dist/index.d.ts",
21
+ "exports": {
22
+ ".": {
23
+ "types": "./dist/index.d.ts",
24
+ "import": "./dist/index.js"
25
+ },
26
+ "./gate-hook": "./dist/gate-hook.js"
27
+ },
28
+ "bin": {
29
+ "fortytwo-gate-hook": "./dist/gate-hook.js",
30
+ "fortytwo-gate": "./dist/cli-bin.js"
31
+ },
32
+ "files": [
33
+ "dist",
34
+ "hooks",
35
+ ".claude-plugin",
36
+ "examples",
37
+ "README.md",
38
+ "LICENSE"
39
+ ],
40
+ "scripts": {
41
+ "build": "tsc",
42
+ "test": "vitest run",
43
+ "test:watch": "vitest",
44
+ "prepublishOnly": "npm run build"
45
+ },
46
+ "keywords": [
47
+ "claude-code",
48
+ "claude-code-plugin",
49
+ "pretooluse",
50
+ "hook",
51
+ "safety",
52
+ "policy",
53
+ "allowlist",
54
+ "agent",
55
+ "guardrail"
56
+ ],
57
+ "devDependencies": {
58
+ "@types/node": "^20.0.0",
59
+ "typescript": "^5.4.0",
60
+ "vitest": "^1.6.0"
61
+ },
62
+ "publishConfig": {
63
+ "access": "public"
64
+ }
65
+ }