@odingard/guardian-hook 0.0.0-stage → 0.1.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/LICENSE +201 -0
- package/README.md +88 -2
- package/dist/index.js +419 -0
- package/package.json +40 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,89 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @odingard/guardian-hook
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Guardian for coding agents.** A [Claude Code](https://code.claude.com/docs/en/hooks) `PreToolUse` hook that sends every consequential tool call (shell commands, file writes, web fetches, MCP tools) to Guardian before it runs.
|
|
4
|
+
|
|
5
|
+
- `npm test` runs under **Allow**.
|
|
6
|
+
- `terraform apply` waits until **you approve it on your phone**.
|
|
7
|
+
- `rm -rf` is **denied** if that is the mode you set.
|
|
8
|
+
|
|
9
|
+
There is no model in the decision: Guardian decides ALLOW / ASK / DENY deterministically from the permissions you set, and every allowed call carries a signed receipt you can verify offline.
|
|
10
|
+
|
|
11
|
+
## How it works
|
|
12
|
+
|
|
13
|
+
| Guardian says | What happens |
|
|
14
|
+
| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
15
|
+
| **ALLOW** | The hook redeems the single-use capability (revocation and expiry are checked now, and the receipt is recorded), then tells the agent to run the call. |
|
|
16
|
+
| **ASK** | The agent waits. You get the request on your phone or in the console. On approval the hook claims and redeems the capability, then the call runs. It is never auto-approved. |
|
|
17
|
+
| **DENY** | The agent is told no, with the reason. Nothing runs. |
|
|
18
|
+
|
|
19
|
+
**Fail closed.** If Guardian can't be reached, the configuration is wrong, approval times out or redemption fails, the call is denied. Each request stays open for 5 minutes (Guardian's limit), and the hook waits that long for an approval, under Claude Code's 600-second hook timeout, because a hook that times out does not block. An ASK not approved within 5 minutes expires; the call is denied and the agent can ask again.
|
|
20
|
+
|
|
21
|
+
## Tools the hook proposes
|
|
22
|
+
|
|
23
|
+
Shell commands are routed by consequence. That routing is what lets you put deploys behind your phone while ordinary commands flow freely.
|
|
24
|
+
|
|
25
|
+
| Guardian tool | Suggested mode | Covers |
|
|
26
|
+
| --------------------- | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
27
|
+
| `shell` | Allow | Ordinary commands (build, test, inspect) |
|
|
28
|
+
| `shell_deploy` | Ask me first | terraform/tofu apply and destroy, pulumi up, kubectl apply and delete, helm install and upgrade, cloud deploy CLIs, package publish, `gh pr merge` |
|
|
29
|
+
| `shell_destructive` | Ask me first | rm -rf, git reset --hard, git clean, force push, DROP/TRUNCATE, disk tools |
|
|
30
|
+
| `git_push` | Ask me first | Pushing commits |
|
|
31
|
+
| `file_write` | Allow | Write and edit (the approver sees the path, size and a SHA-256 of the content; the content itself is not sent) |
|
|
32
|
+
| `web_fetch` | Allow | Fetching a URL |
|
|
33
|
+
| `mcp.<server>.<tool>` | your choice | Any MCP tool, e.g. `mcp.github.create_pull_request` |
|
|
34
|
+
|
|
35
|
+
Read-only tools (Read, Grep, Glob, LS, WebSearch) are not routed through Guardian.
|
|
36
|
+
|
|
37
|
+
## Setup
|
|
38
|
+
|
|
39
|
+
Guardian sets modes **per connection**, not per tool. So the hook uses two record-only tool servers, one per risk tier. That lets `ls` run straight away while `terraform apply` waits for your phone.
|
|
40
|
+
|
|
41
|
+
1. In the Guardian console, go to **Connections → Register a tool server → record-only** and create two:
|
|
42
|
+
- **"Coding agent — everyday"** with `shell`, `file_write` and `web_fetch`.
|
|
43
|
+
- **"Coding agent — needs approval"** with `shell_deploy`, `shell_destructive`, `git_push`, and any MCP tools you use. `npx @odingard/guardian-mcp tools -- <server>` lists them.
|
|
44
|
+
2. Under **Agents**, open your coding agent:
|
|
45
|
+
- set **Allow** on the first connection and **Ask me first** on the second;
|
|
46
|
+
- on each connection's card, type every tool name into **"Allow a tool by name"** and press **Allow tool**, once per tool.
|
|
47
|
+
|
|
48
|
+
Without this, every call is denied as `INVALID_REQUEST`.
|
|
49
|
+
|
|
50
|
+
3. In the shell that starts Claude Code, export:
|
|
51
|
+
- `GUARDIAN_AGENT_CREDENTIAL`;
|
|
52
|
+
- `GUARDIAN_CONNECTION_ID`: the everyday connection;
|
|
53
|
+
- `GUARDIAN_HOOK_ASK_CONNECTION_ID`: the needs-approval connection;
|
|
54
|
+
- `GUARDIAN_BASE_URL`: optional, defaults to `https://guardian-api.odingard.com`.
|
|
55
|
+
|
|
56
|
+
With only `GUARDIAN_CONNECTION_ID` set, every tool shares that one connection and its single mode.
|
|
57
|
+
|
|
58
|
+
4. Add the hook to `.claude/settings.json` (one project) or `~/.claude/settings.json` (all projects):
|
|
59
|
+
|
|
60
|
+
```json
|
|
61
|
+
{
|
|
62
|
+
"hooks": {
|
|
63
|
+
"PreToolUse": [
|
|
64
|
+
{
|
|
65
|
+
"matcher": "Bash|Write|Edit|MultiEdit|NotebookEdit|WebFetch|mcp__.*",
|
|
66
|
+
"hooks": [
|
|
67
|
+
{
|
|
68
|
+
"type": "command",
|
|
69
|
+
"command": "npx -y @odingard/guardian-hook",
|
|
70
|
+
"timeout": 600
|
|
71
|
+
}
|
|
72
|
+
]
|
|
73
|
+
}
|
|
74
|
+
]
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
`npx @odingard/guardian-hook setup` prints all of this. To see where a command would be routed, run `npx @odingard/guardian-hook classify "terraform apply"`, which prints `shell_deploy`.
|
|
80
|
+
|
|
81
|
+
## Limits (read these)
|
|
82
|
+
|
|
83
|
+
- **Decision-gated.** The agent performs the effect after Guardian authorizes and redeems the call. The receipt proves Guardian's authorization of that exact call, not the command's own outcome.
|
|
84
|
+
- **Routing is local.** The classification patterns run on your machine and err toward the Ask tools. An agent that can edit your settings or environment can remove the hook. Use managed settings (or `allow_managed_hooks_only`-style controls) where that matters.
|
|
85
|
+
- **Only calls through the hook are governed.** Commands you run yourself, or other credentials on the machine, are not.
|
|
86
|
+
- **Arguments are bounded.** Commands over 2,000 characters are truncated in what the approver sees; MCP inputs over that size are sent as a digest.
|
|
87
|
+
- **Claude Code only for now.** Cursor and Codex adapters will ship once their hook contracts are verified against their documentation.
|
|
88
|
+
|
|
89
|
+
Licensed Apache-2.0.
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,419 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/index.ts
|
|
4
|
+
import { createGuardianClient } from "@odingard/guardian-sdk";
|
|
5
|
+
|
|
6
|
+
// src/classify.ts
|
|
7
|
+
import { createHash } from "node:crypto";
|
|
8
|
+
var HOOK_TOOLS = [
|
|
9
|
+
{
|
|
10
|
+
name: "shell",
|
|
11
|
+
suggestedMode: "allow",
|
|
12
|
+
description: "Ordinary shell commands (build, test, read-only inspection)."
|
|
13
|
+
},
|
|
14
|
+
{
|
|
15
|
+
name: "shell_deploy",
|
|
16
|
+
suggestedMode: "ask",
|
|
17
|
+
description: "Infrastructure and deploy commands: terraform/tofu apply or destroy, pulumi up, kubectl apply/delete, helm install/upgrade, cdk/serverless/fly/vercel deploys, cloud deploy CLIs."
|
|
18
|
+
},
|
|
19
|
+
{
|
|
20
|
+
name: "shell_destructive",
|
|
21
|
+
suggestedMode: "ask",
|
|
22
|
+
description: "Destructive commands: rm -rf, git reset --hard, git clean, force pushes, dropping databases, disk formatting."
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
name: "git_push",
|
|
26
|
+
suggestedMode: "ask",
|
|
27
|
+
description: "Pushing commits to a remote."
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
name: "file_write",
|
|
31
|
+
suggestedMode: "allow",
|
|
32
|
+
description: "Creating or editing files in the workspace."
|
|
33
|
+
},
|
|
34
|
+
{
|
|
35
|
+
name: "web_fetch",
|
|
36
|
+
suggestedMode: "allow",
|
|
37
|
+
description: "Fetching a URL."
|
|
38
|
+
}
|
|
39
|
+
];
|
|
40
|
+
var MAX_COMMAND = 2e3;
|
|
41
|
+
var DEPLOY = [
|
|
42
|
+
/\b(terraform|tofu)\b.*\s(apply|destroy|import|state\s+(rm|mv|push))\b/,
|
|
43
|
+
/\bpulumi\s+(up|destroy|update)\b/,
|
|
44
|
+
/\bkubectl\b.*\s(apply|delete|create|replace|patch|scale|rollout|drain|cordon)\b/,
|
|
45
|
+
/\bhelm\s+(install|upgrade|uninstall|rollback|delete)\b/,
|
|
46
|
+
/\b(cdk|serverless|sls|sam)\s+(deploy|destroy|remove)\b/,
|
|
47
|
+
/\bfly(ctl)?\s+(deploy|destroy|apps\s+destroy|scale)\b/,
|
|
48
|
+
/\bvercel\b.*(--prod\b|\bdeploy\b|\bpromote\b|\bremove\b)/,
|
|
49
|
+
/\bnetlify\s+deploy\b.*--prod\b/,
|
|
50
|
+
/\bgcloud\s+.*\b(deploy|delete)\b/,
|
|
51
|
+
/\baws\s+.*\b(deploy|delete-stack|create-stack|update-stack|terminate-instances|delete-db-instance)\b/,
|
|
52
|
+
/\baz\s+.*\b(deploy|delete|create)\b/,
|
|
53
|
+
/\bwrangler\s+(deploy|publish|delete)\b/,
|
|
54
|
+
/\bdocker\s+(push|compose\s+.*\bup\b.*--remote)\b/,
|
|
55
|
+
/\b(npm|pnpm|yarn)\s+publish\b/,
|
|
56
|
+
/\btwine\s+upload\b/,
|
|
57
|
+
/\bgh\s+(release\s+create|workflow\s+run|pr\s+merge)\b/
|
|
58
|
+
];
|
|
59
|
+
var DESTRUCTIVE = [
|
|
60
|
+
/\brm\s+(?:-\S*[rR]\S*\s+(?:-\S+\s+)*|-\S*f\S*\s+-\S*[rR])/,
|
|
61
|
+
/\bgit\s+reset\s+.*--hard\b/,
|
|
62
|
+
/\bgit\s+clean\s+-\S*f/,
|
|
63
|
+
/\bgit\s+push\b.*(\s--force\b|\s-f\b|--force-with-lease|\s\+\S)/,
|
|
64
|
+
/\bgit\s+(branch\s+-D|checkout\s+--\s|restore\s+--source)\b/,
|
|
65
|
+
/\b(drop|truncate)\s+(table|database|schema)\b/i,
|
|
66
|
+
/\bdelete\s+from\s+\w+\s*(;|$)/i,
|
|
67
|
+
/\b(mkfs|dd\s+if=|shred|wipefs)\b/,
|
|
68
|
+
/\bchmod\s+-R\s+777\b/,
|
|
69
|
+
/\bfind\b.*\s-delete\b/
|
|
70
|
+
];
|
|
71
|
+
var GIT_PUSH = /\bgit\s+push\b/;
|
|
72
|
+
function classifyCommand(command) {
|
|
73
|
+
if (DESTRUCTIVE.some((re) => re.test(command))) return "shell_destructive";
|
|
74
|
+
if (DEPLOY.some((re) => re.test(command))) return "shell_deploy";
|
|
75
|
+
if (GIT_PUSH.test(command)) return "git_push";
|
|
76
|
+
return "shell";
|
|
77
|
+
}
|
|
78
|
+
function mcpToolName(server, tool) {
|
|
79
|
+
const part = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "").replace(/^(\d)/, "x$1") || "x";
|
|
80
|
+
return `mcp.${part(server)}.${part(tool)}`.slice(0, 64).replace(/[._-]+$/, "");
|
|
81
|
+
}
|
|
82
|
+
function bounded(text, max = MAX_COMMAND) {
|
|
83
|
+
return text.length <= max ? text : `${text.slice(0, max)}\u2026 [${text.length - max} more chars]`;
|
|
84
|
+
}
|
|
85
|
+
function digest(text) {
|
|
86
|
+
return `sha256:${createHash("sha256").update(text).digest("hex")}`;
|
|
87
|
+
}
|
|
88
|
+
function str(value) {
|
|
89
|
+
return typeof value === "string" ? value : "";
|
|
90
|
+
}
|
|
91
|
+
function governedCall(call) {
|
|
92
|
+
const { tool, input } = call;
|
|
93
|
+
const cwd = call.cwd ? { cwd: call.cwd } : {};
|
|
94
|
+
if (tool === "Bash" || tool === "shell") {
|
|
95
|
+
const command = str(input.command);
|
|
96
|
+
const toolName = classifyCommand(command);
|
|
97
|
+
return {
|
|
98
|
+
toolName,
|
|
99
|
+
arguments: { command: bounded(command), ...cwd },
|
|
100
|
+
summary: `Run: ${bounded(command, 160)}`
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
if (["Write", "Edit", "MultiEdit", "NotebookEdit"].includes(tool)) {
|
|
104
|
+
const path = str(input.file_path) || str(input.notebook_path);
|
|
105
|
+
const content = str(input.content) || str(input.new_string) || str(input.new_source) || (Array.isArray(input.edits) ? JSON.stringify(input.edits) : "");
|
|
106
|
+
return {
|
|
107
|
+
toolName: "file_write",
|
|
108
|
+
arguments: {
|
|
109
|
+
operation: tool,
|
|
110
|
+
path,
|
|
111
|
+
contentBytes: Buffer.byteLength(content),
|
|
112
|
+
contentDigest: digest(content),
|
|
113
|
+
...cwd
|
|
114
|
+
},
|
|
115
|
+
summary: `${tool === "Write" ? "Write" : "Edit"} ${path}`
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
if (tool === "WebFetch") {
|
|
119
|
+
const url = str(input.url);
|
|
120
|
+
return {
|
|
121
|
+
toolName: "web_fetch",
|
|
122
|
+
arguments: { url: bounded(url, 500) },
|
|
123
|
+
summary: `Fetch ${bounded(url, 160)}`
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
const mcp = /^mcp__(.+?)__(.+)$/.exec(tool);
|
|
127
|
+
if (mcp) {
|
|
128
|
+
const [, server, name] = mcp;
|
|
129
|
+
const json = JSON.stringify(input);
|
|
130
|
+
return {
|
|
131
|
+
toolName: mcpToolName(server, name),
|
|
132
|
+
arguments: json.length <= MAX_COMMAND ? { server, tool: name, input } : {
|
|
133
|
+
server,
|
|
134
|
+
tool: name,
|
|
135
|
+
inputBytes: json.length,
|
|
136
|
+
inputDigest: digest(json)
|
|
137
|
+
},
|
|
138
|
+
summary: `MCP ${server} \u2192 ${name}`
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
143
|
+
function tierOf(toolName) {
|
|
144
|
+
const known = HOOK_TOOLS.find((t) => t.name === toolName);
|
|
145
|
+
return known ? known.suggestedMode : "ask";
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// src/decide.ts
|
|
149
|
+
var PLAIN = {
|
|
150
|
+
NOT_AUTHORIZED: "this agent is not authorized for it",
|
|
151
|
+
APPROVAL_DENIED: "the approver declined it",
|
|
152
|
+
APPROVAL_NOT_SATISFIED: "the approver declined it",
|
|
153
|
+
APPROVAL_EXPIRED: "the approval expired",
|
|
154
|
+
UNAUTHENTICATED: "the Guardian agent credential was rejected",
|
|
155
|
+
INVALID_REQUEST: `this tool is not allowed for the agent yet. In the Guardian console: Agents \u2192 this agent \u2192 the connection's card \u2192 "Allow a tool by name"`,
|
|
156
|
+
SERVICE_UNAVAILABLE: "Guardian could not be reached",
|
|
157
|
+
REQUEST_CONFLICT: "Guardian saw a conflicting request"
|
|
158
|
+
};
|
|
159
|
+
function plain(code) {
|
|
160
|
+
return PLAIN[code] ?? code;
|
|
161
|
+
}
|
|
162
|
+
function denied(call, code, extra = {}) {
|
|
163
|
+
return {
|
|
164
|
+
decision: "deny",
|
|
165
|
+
reason: `Guardian blocked ${call.toolName} (${code}): ${plain(code)}. Do not retry or work around this; ask the developer to review it in the Guardian console.`,
|
|
166
|
+
...extra
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
var isPending = (r) => !r.ok && (r.reasonCode === "APPROVAL_REQUIRED" || r.reasonCode === "APPROVAL_PENDING") || r.ok && r.decision === "ASK";
|
|
170
|
+
async function decide(call, options) {
|
|
171
|
+
const wait = options.wait ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
172
|
+
const now = options.now ?? Date.now;
|
|
173
|
+
const log = options.log ?? (() => {
|
|
174
|
+
});
|
|
175
|
+
let result;
|
|
176
|
+
try {
|
|
177
|
+
result = await options.client.request({
|
|
178
|
+
action: "tool.invoke",
|
|
179
|
+
connectionId: options.connectionId,
|
|
180
|
+
toolName: call.toolName,
|
|
181
|
+
arguments: call.arguments,
|
|
182
|
+
purpose: `${options.agentName}: ${call.summary}`,
|
|
183
|
+
...options.requestTtlMs !== void 0 ? { ttlMs: options.requestTtlMs } : {}
|
|
184
|
+
});
|
|
185
|
+
} catch {
|
|
186
|
+
return denied(call, "SERVICE_UNAVAILABLE");
|
|
187
|
+
}
|
|
188
|
+
const requestId = result.requestId;
|
|
189
|
+
let approvedByHuman = false;
|
|
190
|
+
if (isPending(result)) {
|
|
191
|
+
if (!requestId) return denied(call, "MISSING_REQUEST_ID");
|
|
192
|
+
log(
|
|
193
|
+
`Guardian: "${call.summary}" is held for approval (request ${requestId}). Approve it on your phone or in the console.`
|
|
194
|
+
);
|
|
195
|
+
const deadline = now() + options.approvalTimeoutMs;
|
|
196
|
+
const maxInterval = Math.max(
|
|
197
|
+
options.maxPollIntervalMs ?? 1e4,
|
|
198
|
+
options.pollIntervalMs
|
|
199
|
+
);
|
|
200
|
+
let interval = options.pollIntervalMs;
|
|
201
|
+
for (; ; ) {
|
|
202
|
+
await wait(interval);
|
|
203
|
+
interval = Math.min(Math.ceil(interval * 1.5), maxInterval);
|
|
204
|
+
let claimed;
|
|
205
|
+
try {
|
|
206
|
+
claimed = await options.client.claim(requestId);
|
|
207
|
+
} catch {
|
|
208
|
+
claimed = { ok: false, reasonCode: "APPROVAL_REQUIRED", requestId };
|
|
209
|
+
}
|
|
210
|
+
if (!isPending(claimed)) {
|
|
211
|
+
result = claimed;
|
|
212
|
+
approvedByHuman = claimed.ok && claimed.decision === "ALLOW";
|
|
213
|
+
break;
|
|
214
|
+
}
|
|
215
|
+
if (now() >= deadline) {
|
|
216
|
+
return {
|
|
217
|
+
decision: "deny",
|
|
218
|
+
reason: `Guardian is still waiting for a human to approve ${call.toolName} (request ${requestId}). Nothing ran. Tell the developer it needs approval in the Guardian app, then try again.`,
|
|
219
|
+
requestId,
|
|
220
|
+
guardianDecision: "ASK"
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
if (!result.ok || result.decision !== "ALLOW" || !result.capabilityToken) {
|
|
226
|
+
const code = result.ok ? result.reasonCode ?? (result.decision === "DENY" ? "DENIED" : "MISSING_CAPABILITY") : result.reasonCode;
|
|
227
|
+
return denied(call, code, {
|
|
228
|
+
...requestId ? { requestId } : {},
|
|
229
|
+
guardianDecision: "DENY"
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
let executed;
|
|
233
|
+
try {
|
|
234
|
+
executed = await options.client.execute({
|
|
235
|
+
requestId: result.requestId,
|
|
236
|
+
capabilityToken: result.capabilityToken
|
|
237
|
+
});
|
|
238
|
+
} catch {
|
|
239
|
+
executed = { ok: false, reasonCode: "SERVICE_UNAVAILABLE" };
|
|
240
|
+
}
|
|
241
|
+
if (!executed.ok) {
|
|
242
|
+
return denied(call, executed.reasonCode, {
|
|
243
|
+
requestId: result.requestId,
|
|
244
|
+
guardianDecision: approvedByHuman ? "ASK" : "ALLOW",
|
|
245
|
+
approvedByHuman
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
return {
|
|
249
|
+
decision: "allow",
|
|
250
|
+
reason: approvedByHuman ? `Approved by a human in Guardian (request ${result.requestId}).` : `Allowed by Guardian policy (request ${result.requestId}).`,
|
|
251
|
+
requestId: result.requestId,
|
|
252
|
+
guardianDecision: approvedByHuman ? "ASK" : "ALLOW",
|
|
253
|
+
approvedByHuman
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// src/index.ts
|
|
258
|
+
var DEFAULT_BASE_URL = "https://guardian-api.odingard.com";
|
|
259
|
+
var REQUEST_TTL_MS = 3e5;
|
|
260
|
+
var MAX_WAIT_MS = REQUEST_TTL_MS;
|
|
261
|
+
function claudeCodeOutput(verdict) {
|
|
262
|
+
return JSON.stringify({
|
|
263
|
+
hookSpecificOutput: {
|
|
264
|
+
hookEventName: "PreToolUse",
|
|
265
|
+
permissionDecision: verdict.decision,
|
|
266
|
+
permissionDecisionReason: verdict.reason
|
|
267
|
+
}
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
var SETTINGS_SNIPPET = {
|
|
271
|
+
hooks: {
|
|
272
|
+
PreToolUse: [
|
|
273
|
+
{
|
|
274
|
+
matcher: "Bash|Write|Edit|MultiEdit|NotebookEdit|WebFetch|mcp__.*",
|
|
275
|
+
hooks: [
|
|
276
|
+
{
|
|
277
|
+
type: "command",
|
|
278
|
+
command: "npx -y @odingard/guardian-hook",
|
|
279
|
+
timeout: 600
|
|
280
|
+
}
|
|
281
|
+
]
|
|
282
|
+
}
|
|
283
|
+
]
|
|
284
|
+
}
|
|
285
|
+
};
|
|
286
|
+
function connectionFor(toolName, env) {
|
|
287
|
+
const allow = env.GUARDIAN_CONNECTION_ID?.trim() || void 0;
|
|
288
|
+
if (tierOf(toolName) === "allow") return allow;
|
|
289
|
+
return env.GUARDIAN_HOOK_ASK_CONNECTION_ID?.trim() || allow;
|
|
290
|
+
}
|
|
291
|
+
function setupText() {
|
|
292
|
+
const list = (mode) => HOOK_TOOLS.filter((t) => t.suggestedMode === mode).map((t) => ` ${t.name.padEnd(18)} ${t.description}`).join("\n");
|
|
293
|
+
return [
|
|
294
|
+
"Guardian modes are set per connection, so the hook uses two record-only tool servers.",
|
|
295
|
+
"",
|
|
296
|
+
"1. In the Guardian console, Connections \u2192 Register a tool server \u2192 record-only:",
|
|
297
|
+
' a) "Coding agent \u2014 everyday" with these tools:',
|
|
298
|
+
list("allow"),
|
|
299
|
+
' b) "Coding agent \u2014 needs approval" with these tools:',
|
|
300
|
+
list("ask"),
|
|
301
|
+
" plus any MCP tools you use, named mcp.<server>.<tool>",
|
|
302
|
+
" (`npx @odingard/guardian-mcp tools -- <server>` lists them).",
|
|
303
|
+
"",
|
|
304
|
+
"2. Agents \u2192 your coding agent:",
|
|
305
|
+
" - set Allow on (a) and Ask me first on (b);",
|
|
306
|
+
" - on each of the two connection cards, type every tool name above into",
|
|
307
|
+
' "Allow a tool by name" and press Allow tool (once per tool).',
|
|
308
|
+
" Without this step every call is denied as INVALID_REQUEST.",
|
|
309
|
+
"",
|
|
310
|
+
"3. In the shell that starts the agent, export GUARDIAN_AGENT_CREDENTIAL,",
|
|
311
|
+
" GUARDIAN_CONNECTION_ID (a) and GUARDIAN_HOOK_ASK_CONNECTION_ID (b).",
|
|
312
|
+
"",
|
|
313
|
+
"4. Add this to .claude/settings.json (project) or ~/.claude/settings.json (all projects):",
|
|
314
|
+
JSON.stringify(SETTINGS_SNIPPET, null, 2),
|
|
315
|
+
"",
|
|
316
|
+
"Read-only tools (Read, Grep, Glob, LS, WebSearch) are not routed through Guardian."
|
|
317
|
+
].join("\n");
|
|
318
|
+
}
|
|
319
|
+
async function runHook(stdin, env, deps = {}) {
|
|
320
|
+
const failClosed = (reason) => claudeCodeOutput({ decision: "deny", reason: `Guardian hook: ${reason}` });
|
|
321
|
+
let input;
|
|
322
|
+
try {
|
|
323
|
+
input = JSON.parse(stdin);
|
|
324
|
+
} catch {
|
|
325
|
+
return failClosed(
|
|
326
|
+
"could not read the tool call from the agent. Nothing ran."
|
|
327
|
+
);
|
|
328
|
+
}
|
|
329
|
+
if (typeof input.tool_name !== "string") {
|
|
330
|
+
return failClosed("the tool call had no tool name. Nothing ran.");
|
|
331
|
+
}
|
|
332
|
+
const call = governedCall({
|
|
333
|
+
tool: input.tool_name,
|
|
334
|
+
input: input.tool_input && typeof input.tool_input === "object" ? input.tool_input : {},
|
|
335
|
+
...typeof input.cwd === "string" ? { cwd: input.cwd } : {}
|
|
336
|
+
});
|
|
337
|
+
if (call === null) return "";
|
|
338
|
+
const connectionId = connectionFor(call.toolName, env);
|
|
339
|
+
const credential = env.GUARDIAN_AGENT_CREDENTIAL?.trim();
|
|
340
|
+
const baseUrl = (env.GUARDIAN_BASE_URL?.trim() || DEFAULT_BASE_URL).replace(
|
|
341
|
+
/\/+$/,
|
|
342
|
+
""
|
|
343
|
+
);
|
|
344
|
+
if (!deps.client && (!credential || !connectionId)) {
|
|
345
|
+
return failClosed(
|
|
346
|
+
"GUARDIAN_AGENT_CREDENTIAL and GUARDIAN_CONNECTION_ID must be set (run `npx @odingard/guardian-hook setup`). Nothing ran."
|
|
347
|
+
);
|
|
348
|
+
}
|
|
349
|
+
if (!deps.client && !baseUrl.startsWith("https://")) {
|
|
350
|
+
return failClosed("GUARDIAN_BASE_URL must be https. Nothing ran.");
|
|
351
|
+
}
|
|
352
|
+
const requested = Number(
|
|
353
|
+
env.GUARDIAN_HOOK_APPROVAL_TIMEOUT_MS ?? MAX_WAIT_MS
|
|
354
|
+
);
|
|
355
|
+
const approvalTimeoutMs = Number.isFinite(requested) ? Math.min(Math.max(requested, 0), MAX_WAIT_MS) : MAX_WAIT_MS;
|
|
356
|
+
const verdict = await decide(call, {
|
|
357
|
+
client: deps.client ?? createGuardianClient({
|
|
358
|
+
baseUrl,
|
|
359
|
+
credential,
|
|
360
|
+
...env.GUARDIAN_ADAPTER_ID ? { adapterId: env.GUARDIAN_ADAPTER_ID } : {}
|
|
361
|
+
}),
|
|
362
|
+
connectionId: connectionId ?? "",
|
|
363
|
+
agentName: env.GUARDIAN_HOOK_AGENT_NAME?.trim() || "Claude Code",
|
|
364
|
+
approvalTimeoutMs,
|
|
365
|
+
requestTtlMs: REQUEST_TTL_MS,
|
|
366
|
+
pollIntervalMs: 2e3,
|
|
367
|
+
...deps.wait ? { wait: deps.wait } : {},
|
|
368
|
+
...deps.now ? { now: deps.now } : {},
|
|
369
|
+
...deps.log ? { log: deps.log } : {}
|
|
370
|
+
});
|
|
371
|
+
return claudeCodeOutput(verdict);
|
|
372
|
+
}
|
|
373
|
+
async function readStdin() {
|
|
374
|
+
const chunks = [];
|
|
375
|
+
for await (const chunk of process.stdin) chunks.push(chunk);
|
|
376
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
377
|
+
}
|
|
378
|
+
async function main(argv) {
|
|
379
|
+
const [command, ...rest] = argv;
|
|
380
|
+
if (command === "setup") {
|
|
381
|
+
process.stdout.write(`${setupText()}
|
|
382
|
+
`);
|
|
383
|
+
return;
|
|
384
|
+
}
|
|
385
|
+
if (command === "classify") {
|
|
386
|
+
process.stdout.write(`${classifyCommand(rest.join(" "))}
|
|
387
|
+
`);
|
|
388
|
+
return;
|
|
389
|
+
}
|
|
390
|
+
if (command === "--help" || command === "-h") {
|
|
391
|
+
process.stdout.write("guardian-hook [setup | classify <command>]\n");
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
394
|
+
const output = await runHook(await readStdin(), process.env, {
|
|
395
|
+
log: (line) => process.stderr.write(`${line}
|
|
396
|
+
`)
|
|
397
|
+
});
|
|
398
|
+
if (output) process.stdout.write(`${output}
|
|
399
|
+
`);
|
|
400
|
+
}
|
|
401
|
+
var invokedDirectly = process.argv[1] !== void 0 && /guardian-hook|hook[\\/]dist[\\/]index\.js$/.test(process.argv[1]);
|
|
402
|
+
if (invokedDirectly) {
|
|
403
|
+
main(process.argv.slice(2)).catch(() => {
|
|
404
|
+
process.stdout.write(
|
|
405
|
+
`${claudeCodeOutput({ decision: "deny", reason: "Guardian hook crashed. Nothing ran." })}
|
|
406
|
+
`
|
|
407
|
+
);
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
export {
|
|
411
|
+
DEFAULT_BASE_URL,
|
|
412
|
+
MAX_WAIT_MS,
|
|
413
|
+
REQUEST_TTL_MS,
|
|
414
|
+
SETTINGS_SNIPPET,
|
|
415
|
+
claudeCodeOutput,
|
|
416
|
+
connectionFor,
|
|
417
|
+
runHook,
|
|
418
|
+
setupText
|
|
419
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,42 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@odingard/guardian-hook",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Guardian for coding agents: a Claude Code PreToolUse hook that sends shell commands, file writes and MCP calls to Guardian for a deterministic ALLOW/ASK/DENY decision. Deploys and destructive commands wait for a human approval on your phone; every allowed call carries a verifiable receipt.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "dist/index.js",
|
|
8
|
+
"bin": {
|
|
9
|
+
"guardian-hook": "dist/index.js"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"dist",
|
|
13
|
+
"README.md"
|
|
14
|
+
],
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=22"
|
|
17
|
+
},
|
|
18
|
+
"scripts": {
|
|
19
|
+
"build": "esbuild src/index.ts --bundle --platform=node --format=esm --target=node22 --external:@odingard/guardian-sdk --outfile=dist/index.js",
|
|
20
|
+
"test": "vitest run",
|
|
21
|
+
"typecheck": "tsc -p tsconfig.json",
|
|
22
|
+
"prepublishOnly": "npm run build && npm test"
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"@odingard/guardian-sdk": "^0.3.5"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"@types/node": "^22",
|
|
29
|
+
"esbuild": "^0.28.2",
|
|
30
|
+
"typescript": "^5.9.3",
|
|
31
|
+
"vitest": "^5.1.0"
|
|
32
|
+
},
|
|
33
|
+
"publishConfig": {
|
|
34
|
+
"access": "public"
|
|
35
|
+
},
|
|
36
|
+
"repository": {
|
|
37
|
+
"type": "git",
|
|
38
|
+
"url": "https://github.com/Odingard/guardian-sdk.git",
|
|
39
|
+
"directory": "packages/hook"
|
|
40
|
+
},
|
|
41
|
+
"homepage": "https://guardian.odingard.com"
|
|
42
|
+
}
|