@scopebond/hook 0.2.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/LICENSE +201 -0
- package/README.md +74 -0
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +195 -0
- package/dist/cli.js.map +1 -0
- package/dist/cloud.d.ts +23 -0
- package/dist/cloud.d.ts.map +1 -0
- package/dist/cloud.js +49 -0
- package/dist/cloud.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +9 -0
- package/dist/index.js.map +1 -0
- package/dist/init.d.ts +9 -0
- package/dist/init.d.ts.map +1 -0
- package/dist/init.js +46 -0
- package/dist/init.js.map +1 -0
- package/dist/map.d.ts +17 -0
- package/dist/map.d.ts.map +1 -0
- package/dist/map.js +104 -0
- package/dist/map.js.map +1 -0
- package/dist/minimize.d.ts +7 -0
- package/dist/minimize.d.ts.map +1 -0
- package/dist/minimize.js +31 -0
- package/dist/minimize.js.map +1 -0
- package/dist/runtime.d.ts +41 -0
- package/dist/runtime.d.ts.map +1 -0
- package/dist/runtime.js +76 -0
- package/dist/runtime.js.map +1 -0
- package/package.json +54 -0
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 Derivative
|
|
95
|
+
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 2026 Avouro LLC
|
|
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
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# @scopebond/hook
|
|
2
|
+
|
|
3
|
+
The Scopebond connector for **Claude Code** and **Cursor**. It checks every tool
|
|
4
|
+
call a coding agent makes against your policy *before it runs*, blocks the ones
|
|
5
|
+
outside policy, and records a signed receipt — locally, on the machine, and
|
|
6
|
+
optionally mirrored to your Scopebond Cloud workspace for monitoring.
|
|
7
|
+
|
|
8
|
+
- **Label:** in-path · prevents (a Claude Code `PreToolUse` deny via exit code 2
|
|
9
|
+
blocks even in bypass-permissions mode).
|
|
10
|
+
- **Ceiling:** it governs actions the harness routes through its tool system
|
|
11
|
+
(shell, file, MCP, web). A process started outside the harness is not covered.
|
|
12
|
+
|
|
13
|
+
## Enroll
|
|
14
|
+
|
|
15
|
+
```
|
|
16
|
+
npx @scopebond/hook init # Claude Code (or: init --cursor)
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
`init` scaffolds `.scopebond/` (a machine signing key, a countersigning key, a
|
|
20
|
+
starter policy — "protect main and production paths" — and a `.gitignore` so none
|
|
21
|
+
of it is committed) and prints the hook configuration to add to
|
|
22
|
+
`.claude/settings.json` or `.cursor/hooks.json`. Then run one safe command in the
|
|
23
|
+
agent and see the receipt in `.scopebond/receipts.db`.
|
|
24
|
+
|
|
25
|
+
## Connect it to your workspace (optional)
|
|
26
|
+
|
|
27
|
+
To see the receipts in your hosted Scopebond workspace, create a connection from
|
|
28
|
+
the portal's **Connect** step (it gives you a one-use enrollment bundle), save it
|
|
29
|
+
as `scopebond-enrollment.json`, then:
|
|
30
|
+
|
|
31
|
+
```
|
|
32
|
+
npx @scopebond/hook connect https://<your-workspace> scopebond-enrollment.json
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
`connect` scaffolds `.scopebond/` if needed, enrolls this machine's countersigning
|
|
36
|
+
key with the workspace, and stores a scoped machine credential in
|
|
37
|
+
`.scopebond/cloud.json` (a secret — never commit it). From then on every receipt is
|
|
38
|
+
mirrored to the workspace through a **durable outbox**: delivery is best-effort and
|
|
39
|
+
never blocks a tool call, and receipts are retained locally and retried if the
|
|
40
|
+
workspace is unreachable. `scopebond-hook flush` delivers anything still queued —
|
|
41
|
+
run it on a session-end hook (and set `SCOPEBOND_HOOK_FLUSH_MS=0`) if you want zero
|
|
42
|
+
per-call latency.
|
|
43
|
+
|
|
44
|
+
## How it works
|
|
45
|
+
|
|
46
|
+
Each tool call is mapped to a normalized [Action Taxonomy](https://github.com/avouro-com/scopebond)
|
|
47
|
+
action (`shell.exec`, `git.push`, `file.write`, `mcp.tool.call`, …), signed by the
|
|
48
|
+
machine key and decided against your policy by an in-process check-only gateway.
|
|
49
|
+
An allowed action is a **cooperative allow** (recorded, never executed by the
|
|
50
|
+
hook — the agent performs it); a denied action is blocked. Unknown tools are
|
|
51
|
+
recorded as *not evaluated* and grant nothing. Anything unexpected fails closed
|
|
52
|
+
(deny) with a repair message.
|
|
53
|
+
|
|
54
|
+
Commands are stored as a scrubbed head plus a digest; file contents are never
|
|
55
|
+
stored; common secret shapes are removed before signing.
|
|
56
|
+
|
|
57
|
+
**Strict mode.** By default a tool with no taxonomy mapping is recorded *not
|
|
58
|
+
evaluated* (not blocked). Add `--strict` (or `SCOPEBOND_HOOK_STRICT=1`) to deny
|
|
59
|
+
unmapped tools too — fail-closed coverage for anything the taxonomy does not map.
|
|
60
|
+
|
|
61
|
+
## Library
|
|
62
|
+
|
|
63
|
+
The mapper and runtime are exported for testing and embedding:
|
|
64
|
+
|
|
65
|
+
```js
|
|
66
|
+
import { mapClaudeToolUse, createHookRuntime } from "@scopebond/hook";
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
`mapClaudeToolUse` / `mapCursorEvent` are pure functions (native payload →
|
|
70
|
+
normalized action). `createHookRuntime` builds the check-only gateway from a
|
|
71
|
+
policy, a machine key and a local receipt log; pass `cloud: { connection }` (from
|
|
72
|
+
`connectCloud`) to mirror receipts to a workspace.
|
|
73
|
+
|
|
74
|
+
Experimental alpha; controlled test use only.
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":""}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// scopebond-hook — govern a coding agent's tool calls against policy, in-path,
|
|
3
|
+
// before they run, with a signed local receipt.
|
|
4
|
+
//
|
|
5
|
+
// scopebond-hook claude evaluate a Claude Code PreToolUse call (stdin JSON)
|
|
6
|
+
// scopebond-hook cursor evaluate a Cursor hook event (stdin JSON)
|
|
7
|
+
// scopebond-hook init [--cursor] scaffold keys + starter policy, print the config
|
|
8
|
+
// scopebond-hook connect <url> <bundle.json> [--cursor]
|
|
9
|
+
// enroll with a Cloud workspace and start exporting
|
|
10
|
+
// scopebond-hook flush deliver any queued receipts to Cloud now
|
|
11
|
+
//
|
|
12
|
+
// Config dir: $SCOPEBOND_HOOK_DIR, else ./.scopebond
|
|
13
|
+
// Fail-closed: any error denies the action with a repair message.
|
|
14
|
+
import { readFileSync } from "node:fs";
|
|
15
|
+
import { join } from "node:path";
|
|
16
|
+
import { mapClaudeToolUse, mapCursorEvent } from "./map.js";
|
|
17
|
+
import { createHookRuntime } from "./runtime.js";
|
|
18
|
+
import { scaffold, harnessSnippet } from "./init.js";
|
|
19
|
+
import { connectCloud, loadConnection, connectionPath } from "./cloud.js";
|
|
20
|
+
function configDir() {
|
|
21
|
+
return process.env.SCOPEBOND_HOOK_DIR ?? join(process.cwd(), ".scopebond");
|
|
22
|
+
}
|
|
23
|
+
function runtimePaths(dir) {
|
|
24
|
+
const connection = loadConnection(dir);
|
|
25
|
+
return {
|
|
26
|
+
policyPath: join(dir, "policy.json"),
|
|
27
|
+
keyPath: join(dir, "agent.key"),
|
|
28
|
+
attesterPath: join(dir, "attester.key"),
|
|
29
|
+
dbPath: join(dir, "receipts.db"),
|
|
30
|
+
// Strict: deny (not just observe) tools with no taxonomy mapping.
|
|
31
|
+
strict: process.argv.includes("--strict") || process.env.SCOPEBOND_HOOK_STRICT === "1",
|
|
32
|
+
// When connected, auto-export receipts. A short bounded flush keeps the hot path
|
|
33
|
+
// fast; undelivered receipts persist in the durable outbox and flush next time
|
|
34
|
+
// (or via `scopebond-hook flush`, e.g. on a session-end hook).
|
|
35
|
+
...(connection ? { cloud: { connection, flushTimeoutMs: Number(process.env.SCOPEBOND_HOOK_FLUSH_MS ?? 800) } } : {}),
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
function readStdin() {
|
|
39
|
+
try {
|
|
40
|
+
return readFileSync(0, "utf8");
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return "";
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
function denyClaude(reason) {
|
|
47
|
+
process.stdout.write(JSON.stringify({
|
|
48
|
+
hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: reason },
|
|
49
|
+
}) + "\n");
|
|
50
|
+
process.stderr.write(`Scopebond: ${reason}\n`);
|
|
51
|
+
process.exit(2);
|
|
52
|
+
}
|
|
53
|
+
async function runClaude() {
|
|
54
|
+
let input;
|
|
55
|
+
try {
|
|
56
|
+
input = JSON.parse(readStdin());
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
denyClaude("hook received invalid JSON on stdin");
|
|
60
|
+
}
|
|
61
|
+
try {
|
|
62
|
+
const runtime = createHookRuntime(runtimePaths(configDir()));
|
|
63
|
+
const decision = await runtime.evaluate(mapClaudeToolUse(input));
|
|
64
|
+
await runtime.flush();
|
|
65
|
+
if (decision.decision === "deny")
|
|
66
|
+
denyClaude(decision.reason);
|
|
67
|
+
if (decision.decision === "allow") {
|
|
68
|
+
process.stdout.write(JSON.stringify({
|
|
69
|
+
hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "allow", permissionDecisionReason: decision.reason },
|
|
70
|
+
}) + "\n");
|
|
71
|
+
process.exit(0);
|
|
72
|
+
}
|
|
73
|
+
// not_evaluated: defer to the harness default (grant nothing, block nothing).
|
|
74
|
+
process.exit(0);
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
denyClaude(`Scopebond hook failed closed: ${error.message}. Repair: run \`scopebond-hook init\`.`);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
async function runCursor() {
|
|
81
|
+
let input = {};
|
|
82
|
+
try {
|
|
83
|
+
input = JSON.parse(readStdin());
|
|
84
|
+
}
|
|
85
|
+
catch { /* fall through to fail-closed deny below */ }
|
|
86
|
+
const event = String(input?.hook_event_name ?? input?.event ?? process.argv[3] ?? "");
|
|
87
|
+
let permission = "deny";
|
|
88
|
+
let message = "Scopebond hook failed closed";
|
|
89
|
+
try {
|
|
90
|
+
const runtime = createHookRuntime(runtimePaths(configDir()));
|
|
91
|
+
const decision = await runtime.evaluate(mapCursorEvent(event, input));
|
|
92
|
+
await runtime.flush();
|
|
93
|
+
permission = decision.decision === "deny" ? "deny" : decision.decision === "allow" ? "allow" : "ask";
|
|
94
|
+
message = decision.reason;
|
|
95
|
+
}
|
|
96
|
+
catch (error) {
|
|
97
|
+
permission = "deny";
|
|
98
|
+
message = `Scopebond hook failed closed: ${error.message}. Repair: run \`scopebond-hook init\`.`;
|
|
99
|
+
}
|
|
100
|
+
process.stdout.write(JSON.stringify({ permission, agentMessage: message }) + "\n");
|
|
101
|
+
process.exit(0);
|
|
102
|
+
}
|
|
103
|
+
function runInit(args) {
|
|
104
|
+
const harness = args.includes("--cursor") ? "cursor" : "claude";
|
|
105
|
+
const dir = configDir();
|
|
106
|
+
const { agentKid, policyPath } = scaffold(dir, { force: args.includes("--force") });
|
|
107
|
+
console.log(`Scopebond hook enrolled in ${dir}`);
|
|
108
|
+
console.log(` machine key ${agentKid}`);
|
|
109
|
+
console.log(` policy ${policyPath} (starter — edit the limits)`);
|
|
110
|
+
console.log("");
|
|
111
|
+
console.log(`Add this to your ${harness === "cursor" ? ".cursor/hooks.json" : ".claude/settings.json"}:`);
|
|
112
|
+
console.log(harnessSnippet(harness));
|
|
113
|
+
console.log("");
|
|
114
|
+
console.log("Then run one safe command in the agent and see the receipt in .scopebond/receipts.db.");
|
|
115
|
+
console.log("To send receipts to your workspace, run: scopebond-hook connect <workspace-url> scopebond-enrollment.json");
|
|
116
|
+
}
|
|
117
|
+
async function runConnect(args) {
|
|
118
|
+
const positional = args.filter((a) => !a.startsWith("--"));
|
|
119
|
+
const url = positional[0];
|
|
120
|
+
const bundleFile = positional[1];
|
|
121
|
+
if (!url) {
|
|
122
|
+
console.error("usage: scopebond-hook connect <workspace-url> <enrollment-bundle.json> [--cursor]");
|
|
123
|
+
process.exit(1);
|
|
124
|
+
}
|
|
125
|
+
const dir = configDir();
|
|
126
|
+
// One command sets everything up: scaffold the key, attester and starter policy if
|
|
127
|
+
// they do not exist, then enroll and persist the scoped machine credential.
|
|
128
|
+
scaffold(dir, {});
|
|
129
|
+
let bundleText;
|
|
130
|
+
try {
|
|
131
|
+
bundleText = bundleFile ? readFileSync(bundleFile, "utf8") : readStdin();
|
|
132
|
+
}
|
|
133
|
+
catch {
|
|
134
|
+
console.error(`could not read the enrollment bundle${bundleFile ? ` from ${bundleFile}` : " on stdin"}`);
|
|
135
|
+
process.exit(1);
|
|
136
|
+
}
|
|
137
|
+
let bundle;
|
|
138
|
+
try {
|
|
139
|
+
bundle = JSON.parse(bundleText);
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
console.error("the enrollment bundle is not valid JSON");
|
|
143
|
+
process.exit(1);
|
|
144
|
+
}
|
|
145
|
+
try {
|
|
146
|
+
const c = await connectCloud(dir, url, bundle);
|
|
147
|
+
console.log(`Connected to ${c.url}`);
|
|
148
|
+
console.log(` workspace org ${c.organization_id} · env ${c.environment_id}`);
|
|
149
|
+
console.log(` gateway id ${c.gateway_id}`);
|
|
150
|
+
console.log(` attester kid ${c.attester_kid}`);
|
|
151
|
+
console.log(` credential stored in ${connectionPath(dir)} — a secret, do not commit`);
|
|
152
|
+
console.log("");
|
|
153
|
+
console.log(`Add this to your ${args.includes("--cursor") ? ".cursor/hooks.json" : ".claude/settings.json"}:`);
|
|
154
|
+
console.log(harnessSnippet(args.includes("--cursor") ? "cursor" : "claude"));
|
|
155
|
+
console.log("");
|
|
156
|
+
console.log("Run one safe command in the agent; the receipt appears in your workspace within seconds.");
|
|
157
|
+
}
|
|
158
|
+
catch (error) {
|
|
159
|
+
console.error(`connect failed: ${error.message}`);
|
|
160
|
+
process.exit(1);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
async function runFlush() {
|
|
164
|
+
const dir = configDir();
|
|
165
|
+
if (!loadConnection(dir)) {
|
|
166
|
+
console.error("not connected to a workspace; run `scopebond-hook connect` first");
|
|
167
|
+
process.exit(1);
|
|
168
|
+
}
|
|
169
|
+
const runtime = createHookRuntime(runtimePaths(dir));
|
|
170
|
+
await runtime.exporter?.flush();
|
|
171
|
+
const status = runtime.exporter?.status();
|
|
172
|
+
console.log(`flushed; ${status?.pending ?? 0} receipt(s) still pending${status?.lastError ? ` (last error: ${status.lastError})` : ""}`);
|
|
173
|
+
process.exit(status && status.pending > 0 ? 1 : 0);
|
|
174
|
+
}
|
|
175
|
+
const [cmd, ...rest] = process.argv.slice(2);
|
|
176
|
+
if (cmd === "claude") {
|
|
177
|
+
await runClaude();
|
|
178
|
+
}
|
|
179
|
+
else if (cmd === "cursor") {
|
|
180
|
+
await runCursor();
|
|
181
|
+
}
|
|
182
|
+
else if (cmd === "init") {
|
|
183
|
+
runInit(rest);
|
|
184
|
+
}
|
|
185
|
+
else if (cmd === "connect") {
|
|
186
|
+
await runConnect(rest);
|
|
187
|
+
}
|
|
188
|
+
else if (cmd === "flush") {
|
|
189
|
+
await runFlush();
|
|
190
|
+
}
|
|
191
|
+
else {
|
|
192
|
+
console.error("usage: scopebond-hook <claude|cursor|init|connect|flush> [--cursor] [--force] [--strict]");
|
|
193
|
+
process.exit(1);
|
|
194
|
+
}
|
|
195
|
+
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/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SAAS,EAAE,CAAC;IAAC,MAAM,UAAU,CAAC,IAAI,CAAC,CAAC;AAAC,CAAC;KAClD,IAAI,GAAG,KAAK,OAAO,EAAE,CAAC;IAAC,MAAM,QAAQ,EAAE,CAAC;AAAC,CAAC;KAC1C,CAAC;IACJ,OAAO,CAAC,KAAK,CAAC,0FAA0F,CAAC,CAAC;IAC1G,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC","sourcesContent":["#!/usr/bin/env node\n// scopebond-hook — govern a coding agent's tool calls against policy, in-path,\n// before they run, with a signed local receipt.\n//\n// scopebond-hook claude evaluate a Claude Code PreToolUse call (stdin JSON)\n// scopebond-hook cursor evaluate a Cursor hook event (stdin JSON)\n// scopebond-hook init [--cursor] scaffold keys + starter policy, print the config\n// scopebond-hook connect <url> <bundle.json> [--cursor]\n// enroll with a Cloud workspace and start exporting\n// scopebond-hook flush deliver any queued receipts to Cloud now\n//\n// Config dir: $SCOPEBOND_HOOK_DIR, else ./.scopebond\n// Fail-closed: any error denies the action with a repair message.\n\nimport { readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { CloudEnrollmentBundle } from \"@scopebond/gateway\";\nimport { mapClaudeToolUse, mapCursorEvent } from \"./map.js\";\nimport { createHookRuntime } from \"./runtime.js\";\nimport { scaffold, harnessSnippet } from \"./init.js\";\nimport { connectCloud, loadConnection, connectionPath } from \"./cloud.js\";\n\nfunction configDir(): string {\n return process.env.SCOPEBOND_HOOK_DIR ?? join(process.cwd(), \".scopebond\");\n}\nfunction runtimePaths(dir: string) {\n const connection = loadConnection(dir);\n return {\n policyPath: join(dir, \"policy.json\"),\n keyPath: join(dir, \"agent.key\"),\n attesterPath: join(dir, \"attester.key\"),\n dbPath: join(dir, \"receipts.db\"),\n // Strict: deny (not just observe) tools with no taxonomy mapping.\n strict: process.argv.includes(\"--strict\") || process.env.SCOPEBOND_HOOK_STRICT === \"1\",\n // When connected, auto-export receipts. A short bounded flush keeps the hot path\n // fast; undelivered receipts persist in the durable outbox and flush next time\n // (or via `scopebond-hook flush`, e.g. on a session-end hook).\n ...(connection ? { cloud: { connection, flushTimeoutMs: Number(process.env.SCOPEBOND_HOOK_FLUSH_MS ?? 800) } } : {}),\n };\n}\nfunction readStdin(): string {\n try { return readFileSync(0, \"utf8\"); } catch { return \"\"; }\n}\n\nfunction denyClaude(reason: string): never {\n process.stdout.write(JSON.stringify({\n hookSpecificOutput: { hookEventName: \"PreToolUse\", permissionDecision: \"deny\", permissionDecisionReason: reason },\n }) + \"\\n\");\n process.stderr.write(`Scopebond: ${reason}\\n`);\n process.exit(2);\n}\n\nasync function runClaude(): Promise<void> {\n let input: Record<string, unknown>;\n try { input = JSON.parse(readStdin()); } catch { denyClaude(\"hook received invalid JSON on stdin\"); }\n try {\n const runtime = createHookRuntime(runtimePaths(configDir()));\n const decision = await runtime.evaluate(mapClaudeToolUse(input!));\n await runtime.flush();\n if (decision.decision === \"deny\") denyClaude(decision.reason);\n if (decision.decision === \"allow\") {\n process.stdout.write(JSON.stringify({\n hookSpecificOutput: { hookEventName: \"PreToolUse\", permissionDecision: \"allow\", permissionDecisionReason: decision.reason },\n }) + \"\\n\");\n process.exit(0);\n }\n // not_evaluated: defer to the harness default (grant nothing, block nothing).\n process.exit(0);\n } catch (error) {\n denyClaude(`Scopebond hook failed closed: ${(error as Error).message}. Repair: run \\`scopebond-hook init\\`.`);\n }\n}\n\nasync function runCursor(): Promise<void> {\n let input: Record<string, unknown> = {};\n try { input = JSON.parse(readStdin()); } catch { /* fall through to fail-closed deny below */ }\n const event = String(input?.hook_event_name ?? input?.event ?? process.argv[3] ?? \"\");\n let permission: \"allow\" | \"deny\" | \"ask\" = \"deny\";\n let message = \"Scopebond hook failed closed\";\n try {\n const runtime = createHookRuntime(runtimePaths(configDir()));\n const decision = await runtime.evaluate(mapCursorEvent(event, input));\n await runtime.flush();\n permission = decision.decision === \"deny\" ? \"deny\" : decision.decision === \"allow\" ? \"allow\" : \"ask\";\n message = decision.reason;\n } catch (error) {\n permission = \"deny\";\n message = `Scopebond hook failed closed: ${(error as Error).message}. Repair: run \\`scopebond-hook init\\`.`;\n }\n process.stdout.write(JSON.stringify({ permission, agentMessage: message }) + \"\\n\");\n process.exit(0);\n}\n\nfunction runInit(args: string[]): void {\n const harness = args.includes(\"--cursor\") ? \"cursor\" : \"claude\";\n const dir = configDir();\n const { agentKid, policyPath } = scaffold(dir, { force: args.includes(\"--force\") });\n console.log(`Scopebond hook enrolled in ${dir}`);\n console.log(` machine key ${agentKid}`);\n console.log(` policy ${policyPath} (starter — edit the limits)`);\n console.log(\"\");\n console.log(`Add this to your ${harness === \"cursor\" ? \".cursor/hooks.json\" : \".claude/settings.json\"}:`);\n console.log(harnessSnippet(harness));\n console.log(\"\");\n console.log(\"Then run one safe command in the agent and see the receipt in .scopebond/receipts.db.\");\n console.log(\"To send receipts to your workspace, run: scopebond-hook connect <workspace-url> scopebond-enrollment.json\");\n}\n\nasync function runConnect(args: string[]): Promise<void> {\n const positional = args.filter((a) => !a.startsWith(\"--\"));\n const url = positional[0];\n const bundleFile = positional[1];\n if (!url) {\n console.error(\"usage: scopebond-hook connect <workspace-url> <enrollment-bundle.json> [--cursor]\");\n process.exit(1);\n }\n const dir = configDir();\n // One command sets everything up: scaffold the key, attester and starter policy if\n // they do not exist, then enroll and persist the scoped machine credential.\n scaffold(dir, {});\n let bundleText: string;\n try { bundleText = bundleFile ? readFileSync(bundleFile, \"utf8\") : readStdin(); }\n catch { console.error(`could not read the enrollment bundle${bundleFile ? ` from ${bundleFile}` : \" on stdin\"}`); process.exit(1); }\n let bundle: CloudEnrollmentBundle;\n try { bundle = JSON.parse(bundleText) as CloudEnrollmentBundle; }\n catch { console.error(\"the enrollment bundle is not valid JSON\"); process.exit(1); }\n try {\n const c = await connectCloud(dir, url, bundle);\n console.log(`Connected to ${c.url}`);\n console.log(` workspace org ${c.organization_id} · env ${c.environment_id}`);\n console.log(` gateway id ${c.gateway_id}`);\n console.log(` attester kid ${c.attester_kid}`);\n console.log(` credential stored in ${connectionPath(dir)} — a secret, do not commit`);\n console.log(\"\");\n console.log(`Add this to your ${args.includes(\"--cursor\") ? \".cursor/hooks.json\" : \".claude/settings.json\"}:`);\n console.log(harnessSnippet(args.includes(\"--cursor\") ? \"cursor\" : \"claude\"));\n console.log(\"\");\n console.log(\"Run one safe command in the agent; the receipt appears in your workspace within seconds.\");\n } catch (error) {\n console.error(`connect failed: ${(error as Error).message}`);\n process.exit(1);\n }\n}\n\nasync function runFlush(): Promise<void> {\n const dir = configDir();\n if (!loadConnection(dir)) { console.error(\"not connected to a workspace; run `scopebond-hook connect` first\"); process.exit(1); }\n const runtime = createHookRuntime(runtimePaths(dir));\n await runtime.exporter?.flush();\n const status = runtime.exporter?.status();\n console.log(`flushed; ${status?.pending ?? 0} receipt(s) still pending${status?.lastError ? ` (last error: ${status.lastError})` : \"\"}`);\n process.exit(status && status.pending > 0 ? 1 : 0);\n}\n\nconst [cmd, ...rest] = process.argv.slice(2);\nif (cmd === \"claude\") { await runClaude(); }\nelse if (cmd === \"cursor\") { await runCursor(); }\nelse if (cmd === \"init\") { runInit(rest); }\nelse if (cmd === \"connect\") { await runConnect(rest); }\nelse if (cmd === \"flush\") { await runFlush(); }\nelse {\n console.error(\"usage: scopebond-hook <claude|cursor|init|connect|flush> [--cursor] [--force] [--strict]\");\n process.exit(1);\n}\n"]}
|
package/dist/cloud.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { type CloudEnrollmentBundle, type CloudEnrollmentResult, type CloudExporter, type ReceiptStore } from "@scopebond/gateway";
|
|
2
|
+
/** The persisted connection between this machine and a Cloud workspace. Holds the
|
|
3
|
+
* scoped machine credential; treat cloud.json as a secret (written 0600). */
|
|
4
|
+
export interface HookConnection extends CloudEnrollmentResult {
|
|
5
|
+
url: string;
|
|
6
|
+
}
|
|
7
|
+
export declare const connectionPath: (dir: string) => string;
|
|
8
|
+
/** Read the persisted connection, or null when the hook is not connected to Cloud. */
|
|
9
|
+
export declare function loadConnection(dir: string): HookConnection | null;
|
|
10
|
+
/** Enroll the machine's attester with a workspace using the portal's one-use handoff,
|
|
11
|
+
* then persist the scoped machine credential. The attester whose possession is proved
|
|
12
|
+
* here is the same key the hook countersigns receipts with, so ingest accepts them. */
|
|
13
|
+
export declare function connectCloud(dir: string, url: string, bundle: CloudEnrollmentBundle, fetchImpl?: typeof fetch): Promise<HookConnection>;
|
|
14
|
+
/** Wrap a receipt store so every stored receipt is enqueued to a durable outbox and
|
|
15
|
+
* exported to Cloud. Returns the wrapped store and the exporter (flush + stop). */
|
|
16
|
+
export declare function attachExporter(outboxDbPath: string, connection: HookConnection, store: ReceiptStore, fetchImpl?: typeof fetch): {
|
|
17
|
+
store: ReceiptStore;
|
|
18
|
+
exporter: CloudExporter;
|
|
19
|
+
};
|
|
20
|
+
/** Attempt delivery with a bounded timeout so a per-invocation hook never hangs the
|
|
21
|
+
* agent; undelivered receipts stay in the durable outbox and flush next time. */
|
|
22
|
+
export declare function flushBounded(exporter: CloudExporter, timeoutMs?: number): Promise<void>;
|
|
23
|
+
//# sourceMappingURL=cloud.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cloud.d.ts","sourceRoot":"","sources":["../src/cloud.ts"],"names":[],"mappings":"AAQA,OAAO,EAEL,KAAK,qBAAqB,EAAE,KAAK,qBAAqB,EAAE,KAAK,aAAa,EAAE,KAAK,YAAY,EAC9F,MAAM,oBAAoB,CAAC;AAG5B;8EAC8E;AAC9E,MAAM,WAAW,cAAe,SAAQ,qBAAqB;IAC3D,GAAG,EAAE,MAAM,CAAC;CACb;AAED,eAAO,MAAM,cAAc,GAAI,KAAK,MAAM,KAAG,MAAiC,CAAC;AAE/E,sFAAsF;AACtF,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,cAAc,GAAG,IAAI,CAQjE;AAED;;wFAEwF;AACxF,wBAAsB,YAAY,CAChC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,qBAAqB,EAAE,SAAS,CAAC,EAAE,OAAO,KAAK,GAChF,OAAO,CAAC,cAAc,CAAC,CAMzB;AAED;oFACoF;AACpF,wBAAgB,cAAc,CAC5B,YAAY,EAAE,MAAM,EAAE,UAAU,EAAE,cAAc,EAAE,KAAK,EAAE,YAAY,EAAE,SAAS,CAAC,EAAE,OAAO,KAAK,GAC9F;IAAE,KAAK,EAAE,YAAY,CAAC;IAAC,QAAQ,EAAE,aAAa,CAAA;CAAE,CAIlD;AAED;kFACkF;AAClF,wBAAsB,YAAY,CAAC,QAAQ,EAAE,aAAa,EAAE,SAAS,SAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAK3F"}
|
package/dist/cloud.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// scopebond-hook → Scopebond Cloud: enroll the machine's countersigning key with a
|
|
2
|
+
// workspace and auto-export signed receipts to the hosted portal, so a connected
|
|
3
|
+
// hook starts monitoring automatically. Reuses the gateway's enrollment and bounded
|
|
4
|
+
// durable exporter (D40 — no new transport). The machine credential and the complete
|
|
5
|
+
// receipt log stay local-first; export is best-effort and never blocks a tool call.
|
|
6
|
+
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { completeCloudEnrollment, createCloudExporter, withCloudExporter, } from "@scopebond/gateway";
|
|
9
|
+
import { SqliteCloudOutbox, loadOrCreateAttester } from "@scopebond/gateway/node";
|
|
10
|
+
export const connectionPath = (dir) => join(dir, "cloud.json");
|
|
11
|
+
/** Read the persisted connection, or null when the hook is not connected to Cloud. */
|
|
12
|
+
export function loadConnection(dir) {
|
|
13
|
+
const path = connectionPath(dir);
|
|
14
|
+
if (!existsSync(path))
|
|
15
|
+
return null;
|
|
16
|
+
try {
|
|
17
|
+
const parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
18
|
+
if (typeof parsed.url === "string" && typeof parsed.credential === "string")
|
|
19
|
+
return parsed;
|
|
20
|
+
}
|
|
21
|
+
catch { /* fall through */ }
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
/** Enroll the machine's attester with a workspace using the portal's one-use handoff,
|
|
25
|
+
* then persist the scoped machine credential. The attester whose possession is proved
|
|
26
|
+
* here is the same key the hook countersigns receipts with, so ingest accepts them. */
|
|
27
|
+
export async function connectCloud(dir, url, bundle, fetchImpl) {
|
|
28
|
+
const { attester } = loadOrCreateAttester({ file: join(dir, "attester.key") });
|
|
29
|
+
const result = await completeCloudEnrollment({ url, bundle, attester, fetch: fetchImpl });
|
|
30
|
+
const connection = { url, ...result };
|
|
31
|
+
writeFileSync(connectionPath(dir), JSON.stringify(connection, null, 2) + "\n", { mode: 0o600 });
|
|
32
|
+
return connection;
|
|
33
|
+
}
|
|
34
|
+
/** Wrap a receipt store so every stored receipt is enqueued to a durable outbox and
|
|
35
|
+
* exported to Cloud. Returns the wrapped store and the exporter (flush + stop). */
|
|
36
|
+
export function attachExporter(outboxDbPath, connection, store, fetchImpl) {
|
|
37
|
+
const outbox = new SqliteCloudOutbox(outboxDbPath);
|
|
38
|
+
const exporter = createCloudExporter({ url: connection.url, credential: connection.credential, outbox, fetch: fetchImpl });
|
|
39
|
+
return { store: withCloudExporter(store, exporter), exporter };
|
|
40
|
+
}
|
|
41
|
+
/** Attempt delivery with a bounded timeout so a per-invocation hook never hangs the
|
|
42
|
+
* agent; undelivered receipts stay in the durable outbox and flush next time. */
|
|
43
|
+
export async function flushBounded(exporter, timeoutMs = 3000) {
|
|
44
|
+
await Promise.race([
|
|
45
|
+
exporter.flush().catch(() => { }),
|
|
46
|
+
new Promise((resolve) => setTimeout(resolve, Math.max(0, timeoutMs)).unref?.()),
|
|
47
|
+
]);
|
|
48
|
+
}
|
|
49
|
+
//# sourceMappingURL=cloud.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cloud.js","sourceRoot":"","sources":["../src/cloud.ts"],"names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ace and auto-export signed receipts to the hosted portal, so a connected\n// hook starts monitoring automatically. Reuses the gateway's enrollment and bounded\n// durable exporter (D40 — no new transport). The machine credential and the complete\n// receipt log stay local-first; export is best-effort and never blocks a tool call.\n\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n completeCloudEnrollment, createCloudExporter, withCloudExporter,\n type CloudEnrollmentBundle, type CloudEnrollmentResult, type CloudExporter, type ReceiptStore,\n} from \"@scopebond/gateway\";\nimport { SqliteCloudOutbox, loadOrCreateAttester } from \"@scopebond/gateway/node\";\n\n/** The persisted connection between this machine and a Cloud workspace. Holds the\n * scoped machine credential; treat cloud.json as a secret (written 0600). */\nexport interface HookConnection extends CloudEnrollmentResult {\n url: string;\n}\n\nexport const connectionPath = (dir: string): string => join(dir, \"cloud.json\");\n\n/** Read the persisted connection, or null when the hook is not connected to Cloud. */\nexport function loadConnection(dir: string): HookConnection | null {\n const path = connectionPath(dir);\n if (!existsSync(path)) return null;\n try {\n const parsed = JSON.parse(readFileSync(path, \"utf8\")) as Partial<HookConnection>;\n if (typeof parsed.url === \"string\" && typeof parsed.credential === \"string\") return parsed as HookConnection;\n } catch { /* fall through */ }\n return null;\n}\n\n/** Enroll the machine's attester with a workspace using the portal's one-use handoff,\n * then persist the scoped machine credential. The attester whose possession is proved\n * here is the same key the hook countersigns receipts with, so ingest accepts them. */\nexport async function connectCloud(\n dir: string, url: string, bundle: CloudEnrollmentBundle, fetchImpl?: typeof fetch,\n): Promise<HookConnection> {\n const { attester } = loadOrCreateAttester({ file: join(dir, \"attester.key\") });\n const result = await completeCloudEnrollment({ url, bundle, attester, fetch: fetchImpl });\n const connection: HookConnection = { url, ...result };\n writeFileSync(connectionPath(dir), JSON.stringify(connection, null, 2) + \"\\n\", { mode: 0o600 });\n return connection;\n}\n\n/** Wrap a receipt store so every stored receipt is enqueued to a durable outbox and\n * exported to Cloud. Returns the wrapped store and the exporter (flush + stop). */\nexport function attachExporter(\n outboxDbPath: string, connection: HookConnection, store: ReceiptStore, fetchImpl?: typeof fetch,\n): { store: ReceiptStore; exporter: CloudExporter } {\n const outbox = new SqliteCloudOutbox(outboxDbPath);\n const exporter = createCloudExporter({ url: connection.url, credential: connection.credential, outbox, fetch: fetchImpl });\n return { store: withCloudExporter(store, exporter), exporter };\n}\n\n/** Attempt delivery with a bounded timeout so a per-invocation hook never hangs the\n * agent; undelivered receipts stay in the durable outbox and flush next time. */\nexport async function flushBounded(exporter: CloudExporter, timeoutMs = 3000): Promise<void> {\n await Promise.race([\n exporter.flush().catch(() => {}),\n new Promise<void>((resolve) => setTimeout(resolve, Math.max(0, timeoutMs)).unref?.()),\n ]);\n}\n"]}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { mapClaudeToolUse, mapCursorEvent } from "./map.js";
|
|
2
|
+
export type { Mapped, NormalizedIntent } from "./map.js";
|
|
3
|
+
export { createHookRuntime, starterPolicy } from "./runtime.js";
|
|
4
|
+
export type { RuntimeConfig, Decision } from "./runtime.js";
|
|
5
|
+
export { scaffold, harnessSnippet } from "./init.js";
|
|
6
|
+
export { connectCloud, loadConnection, attachExporter, flushBounded, connectionPath } from "./cloud.js";
|
|
7
|
+
export type { HookConnection } from "./cloud.js";
|
|
8
|
+
export { scrubSecrets, redactCommand, digest, sha256 } from "./minimize.js";
|
|
9
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAC5D,YAAY,EAAE,MAAM,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AACzD,OAAO,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAChE,YAAY,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,cAAc,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AACxG,YAAY,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AACjD,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// @scopebond/hook — the Claude Code + Cursor connector. The library surface is
|
|
2
|
+
// the deterministic mapper and the check-only runtime; the `scopebond-hook`
|
|
3
|
+
// binary is the thin harness adapter over them.
|
|
4
|
+
export { mapClaudeToolUse, mapCursorEvent } from "./map.js";
|
|
5
|
+
export { createHookRuntime, starterPolicy } from "./runtime.js";
|
|
6
|
+
export { scaffold, harnessSnippet } from "./init.js";
|
|
7
|
+
export { connectCloud, loadConnection, attachExporter, flushBounded, connectionPath } from "./cloud.js";
|
|
8
|
+
export { scrubSecrets, redactCommand, digest, sha256 } from "./minimize.js";
|
|
9
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,4EAA4E;AAC5E,gDAAgD;AAEhD,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAE5D,OAAO,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAEhE,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,cAAc,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAExG,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC","sourcesContent":["// @scopebond/hook — the Claude Code + Cursor connector. The library surface is\n// the deterministic mapper and the check-only runtime; the `scopebond-hook`\n// binary is the thin harness adapter over them.\n\nexport { mapClaudeToolUse, mapCursorEvent } from \"./map.js\";\nexport type { Mapped, NormalizedIntent } from \"./map.js\";\nexport { createHookRuntime, starterPolicy } from \"./runtime.js\";\nexport type { RuntimeConfig, Decision } from \"./runtime.js\";\nexport { scaffold, harnessSnippet } from \"./init.js\";\nexport { connectCloud, loadConnection, attachExporter, flushBounded, connectionPath } from \"./cloud.js\";\nexport type { HookConnection } from \"./cloud.js\";\nexport { scrubSecrets, redactCommand, digest, sha256 } from \"./minimize.js\";\n"]}
|
package/dist/init.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export declare function scaffold(dir: string, opts?: {
|
|
2
|
+
force?: boolean;
|
|
3
|
+
}): {
|
|
4
|
+
agentKid: string;
|
|
5
|
+
policyPath: string;
|
|
6
|
+
};
|
|
7
|
+
/** The harness configuration snippet to install the hook. */
|
|
8
|
+
export declare function harnessSnippet(harness: "claude" | "cursor"): string;
|
|
9
|
+
//# sourceMappingURL=init.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../src/init.ts"],"names":[],"mappings":"AAUA,wBAAgB,QAAQ,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,GAAE;IAAE,KAAK,CAAC,EAAE,OAAO,CAAA;CAAO,GAAG;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,CAgB9G;AAED,6DAA6D;AAC7D,wBAAgB,cAAc,CAAC,OAAO,EAAE,QAAQ,GAAG,QAAQ,GAAG,MAAM,CAiBnE"}
|
package/dist/init.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// `scopebond-hook init` — scaffold the local enrollment: a machine signing key, a
|
|
2
|
+
// gateway countersigning key and a starter policy. Keys and receipts stay on the
|
|
3
|
+
// machine; no credentials are handled.
|
|
4
|
+
import { mkdirSync, writeFileSync, existsSync, readFileSync } from "node:fs";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { loadOrCreateAttester } from "@scopebond/gateway/node";
|
|
7
|
+
import { createSigner } from "@scopebond/sdk";
|
|
8
|
+
import { starterPolicy } from "./runtime.js";
|
|
9
|
+
export function scaffold(dir, opts = {}) {
|
|
10
|
+
mkdirSync(dir, { recursive: true });
|
|
11
|
+
const keyPath = join(dir, "agent.key");
|
|
12
|
+
const attesterPath = join(dir, "attester.key");
|
|
13
|
+
const policyPath = join(dir, "policy.json");
|
|
14
|
+
// Never let the signing keys, the Cloud credential or the local log be committed.
|
|
15
|
+
const gitignorePath = join(dir, ".gitignore");
|
|
16
|
+
if (!existsSync(gitignorePath))
|
|
17
|
+
writeFileSync(gitignorePath, "*\n");
|
|
18
|
+
// Machine signing key (agent) + gateway countersigning key (attester). Reused if present.
|
|
19
|
+
loadOrCreateAttester({ file: keyPath });
|
|
20
|
+
loadOrCreateAttester({ file: attesterPath });
|
|
21
|
+
const agent = createSigner({ privateKeyPem: readFileSync(keyPath, "utf8") });
|
|
22
|
+
if (!existsSync(policyPath) || opts.force) {
|
|
23
|
+
writeFileSync(policyPath, JSON.stringify(starterPolicy(agent.kid), null, 2) + "\n");
|
|
24
|
+
}
|
|
25
|
+
return { agentKid: agent.kid, policyPath };
|
|
26
|
+
}
|
|
27
|
+
/** The harness configuration snippet to install the hook. */
|
|
28
|
+
export function harnessSnippet(harness) {
|
|
29
|
+
if (harness === "cursor") {
|
|
30
|
+
return JSON.stringify({
|
|
31
|
+
version: 1,
|
|
32
|
+
hooks: {
|
|
33
|
+
beforeShellExecution: [{ command: "scopebond-hook cursor" }],
|
|
34
|
+
beforeMCPExecution: [{ command: "scopebond-hook cursor" }],
|
|
35
|
+
beforeReadFile: [{ command: "scopebond-hook cursor" }],
|
|
36
|
+
afterFileEdit: [{ command: "scopebond-hook cursor" }],
|
|
37
|
+
},
|
|
38
|
+
}, null, 2);
|
|
39
|
+
}
|
|
40
|
+
return JSON.stringify({
|
|
41
|
+
hooks: {
|
|
42
|
+
PreToolUse: [{ matcher: "*", hooks: [{ type: "command", command: "scopebond-hook claude" }] }],
|
|
43
|
+
},
|
|
44
|
+
}, null, 2);
|
|
45
|
+
}
|
|
46
|
+
//# sourceMappingURL=init.js.map
|
package/dist/init.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"init.js","sourceRoot":"","sources":["../src/init.ts"],"names":[],"mappings":"AAAA,kFAAkF;AAClF,iFAAiF;AACjF,uCAAuC;AAEvC,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAC7E,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAC/D,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAE7C,MAAM,UAAU,QAAQ,CAAC,GAAW,EAAE,OAA4B,EAAE;IAClE,SAAS,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IACpC,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,EAAE,WAAW,CAAC,CAAC;IACvC,MAAM,YAAY,GAAG,IAAI,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC;IAC/C,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,EAAE,aAAa,CAAC,CAAC;IAC5C,kFAAkF;IAClF,MAAM,aAAa,GAAG,IAAI,CAAC,GAAG,EAAE,YAAY,CAAC,CAAC;IAC9C,IAAI,CAAC,UAAU,CAAC,aAAa,CAAC;QAAE,aAAa,CAAC,aAAa,EAAE,KAAK,CAAC,CAAC;IACpE,0FAA0F;IAC1F,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E,CAAC;SAC/F;KACF,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;AACd,CAAC","sourcesContent":["// `scopebond-hook init` — scaffold the local enrollment: a machine signing key, a\n// gateway countersigning key and a starter policy. Keys and receipts stay on the\n// machine; no credentials are handled.\n\nimport { mkdirSync, writeFileSync, existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { loadOrCreateAttester } from \"@scopebond/gateway/node\";\nimport { createSigner } from \"@scopebond/sdk\";\nimport { starterPolicy } from \"./runtime.js\";\n\nexport function scaffold(dir: string, opts: { force?: boolean } = {}): { agentKid: string; policyPath: string } {\n mkdirSync(dir, { recursive: true });\n const keyPath = join(dir, \"agent.key\");\n const attesterPath = join(dir, \"attester.key\");\n const policyPath = join(dir, \"policy.json\");\n // Never let the signing keys, the Cloud credential or the local log be committed.\n const gitignorePath = join(dir, \".gitignore\");\n if (!existsSync(gitignorePath)) writeFileSync(gitignorePath, \"*\\n\");\n // Machine signing key (agent) + gateway countersigning key (attester). Reused if present.\n loadOrCreateAttester({ file: keyPath });\n loadOrCreateAttester({ file: attesterPath });\n const agent = createSigner({ privateKeyPem: readFileSync(keyPath, \"utf8\") });\n if (!existsSync(policyPath) || opts.force) {\n writeFileSync(policyPath, JSON.stringify(starterPolicy(agent.kid), null, 2) + \"\\n\");\n }\n return { agentKid: agent.kid, policyPath };\n}\n\n/** The harness configuration snippet to install the hook. */\nexport function harnessSnippet(harness: \"claude\" | \"cursor\"): string {\n if (harness === \"cursor\") {\n return JSON.stringify({\n version: 1,\n hooks: {\n beforeShellExecution: [{ command: \"scopebond-hook cursor\" }],\n beforeMCPExecution: [{ command: \"scopebond-hook cursor\" }],\n beforeReadFile: [{ command: \"scopebond-hook cursor\" }],\n afterFileEdit: [{ command: \"scopebond-hook cursor\" }],\n },\n }, null, 2);\n }\n return JSON.stringify({\n hooks: {\n PreToolUse: [{ matcher: \"*\", hooks: [{ type: \"command\", command: \"scopebond-hook claude\" }] }],\n },\n }, null, 2);\n}\n"]}
|
package/dist/map.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export interface NormalizedIntent {
|
|
2
|
+
action_type: string;
|
|
3
|
+
params: Record<string, unknown>;
|
|
4
|
+
}
|
|
5
|
+
export interface Mapped {
|
|
6
|
+
intent: NormalizedIntent;
|
|
7
|
+
/** false when no taxonomy type applies: emitted as tool.<name> and routed to the
|
|
8
|
+
* observation path (not_evaluated), never granted. */
|
|
9
|
+
evaluated: boolean;
|
|
10
|
+
/** The native tool/event name, for diagnostics. */
|
|
11
|
+
source: string;
|
|
12
|
+
}
|
|
13
|
+
/** Map a Claude Code PreToolUse payload to a normalized taxonomy action. */
|
|
14
|
+
export declare function mapClaudeToolUse(input: Record<string, unknown>): Mapped;
|
|
15
|
+
/** Map a Cursor hook event to a normalized taxonomy action. */
|
|
16
|
+
export declare function mapCursorEvent(event: string, payload: Record<string, unknown>): Mapped;
|
|
17
|
+
//# sourceMappingURL=map.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"map.d.ts","sourceRoot":"","sources":["../src/map.ts"],"names":[],"mappings":"AAMA,MAAM,WAAW,gBAAgB;IAC/B,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACjC;AACD,MAAM,WAAW,MAAM;IACrB,MAAM,EAAE,gBAAgB,CAAC;IACzB;2DACuD;IACvD,SAAS,EAAE,OAAO,CAAC;IACnB,mDAAmD;IACnD,MAAM,EAAE,MAAM,CAAC;CAChB;AAqDD,4EAA4E;AAC5E,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAkBvE;AAED,+DAA+D;AAC/D,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAkBtF"}
|
package/dist/map.js
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// The mapper: a pure function from a coding agent's native tool call to a
|
|
2
|
+
// normalized Scopebond action (Action Taxonomy v1). This is the connector's core
|
|
3
|
+
// — deterministic and side-effect free, so it can be conformance-tested directly.
|
|
4
|
+
import { digest, redactCommand } from "./minimize.js";
|
|
5
|
+
const rel = (value, cwd) => {
|
|
6
|
+
const s = String(value ?? "");
|
|
7
|
+
if (cwd && s.startsWith(cwd))
|
|
8
|
+
return s.slice(cwd.length).replace(/^[\\/]+/, "");
|
|
9
|
+
return s;
|
|
10
|
+
};
|
|
11
|
+
/** The invoked program's basename, after stripping sudo and `env VAR=val` prefixes. */
|
|
12
|
+
function programOf(command) {
|
|
13
|
+
const stripped = command.trim().replace(/^sudo\s+/, "").replace(/^(?:env\s+\S+=\S+\s+)+/, "");
|
|
14
|
+
const first = stripped.split(/\s+/)[0] ?? "";
|
|
15
|
+
return first.replace(/^.*[\\/]/, "");
|
|
16
|
+
}
|
|
17
|
+
// Best-effort `git push [--force|-f] [remote] [ref]` parse. Ambiguous pushes omit
|
|
18
|
+
// the ref, which a ref bound then denies (fail closed).
|
|
19
|
+
function parseGitPush(command) {
|
|
20
|
+
const t = command.trim().replace(/^sudo\s+/, "");
|
|
21
|
+
if (!/^git\s+push(\s|$)/.test(t))
|
|
22
|
+
return null;
|
|
23
|
+
const force = /(?:^|\s)(?:--force\b|--force-with-lease\b|-f\b)/.test(t);
|
|
24
|
+
const rest = t.replace(/^git\s+push\b/, "").trim();
|
|
25
|
+
const positional = rest.split(/\s+/).filter((a) => a && !a.startsWith("-"));
|
|
26
|
+
const params = { force };
|
|
27
|
+
if (positional[0])
|
|
28
|
+
params.remote = positional[0];
|
|
29
|
+
if (positional[1])
|
|
30
|
+
params.ref = positional[1].replace(/^[^:]*:/, ""); // src:dst → dst
|
|
31
|
+
return params;
|
|
32
|
+
}
|
|
33
|
+
function mapShell(command, cwd) {
|
|
34
|
+
const push = parseGitPush(command);
|
|
35
|
+
if (push)
|
|
36
|
+
return { intent: { action_type: "git.push", params: push }, evaluated: true, source: "shell" };
|
|
37
|
+
return {
|
|
38
|
+
intent: {
|
|
39
|
+
action_type: "shell.exec",
|
|
40
|
+
params: { command: redactCommand(command), program: programOf(command), ...(cwd ? { cwd } : {}) },
|
|
41
|
+
},
|
|
42
|
+
evaluated: true, source: "shell",
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
function parseMcpName(name) {
|
|
46
|
+
if (!name.startsWith("mcp__"))
|
|
47
|
+
return null;
|
|
48
|
+
const parts = name.split("__");
|
|
49
|
+
if (parts.length < 3)
|
|
50
|
+
return null;
|
|
51
|
+
return { server: parts[1], tool: parts.slice(2).join("__") };
|
|
52
|
+
}
|
|
53
|
+
function splitUrl(url) {
|
|
54
|
+
try {
|
|
55
|
+
const u = new URL(url);
|
|
56
|
+
return { host: u.host, path: u.pathname };
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return { host: url, path: "" };
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/** Map a Claude Code PreToolUse payload to a normalized taxonomy action. */
|
|
63
|
+
export function mapClaudeToolUse(input) {
|
|
64
|
+
const name = String(input?.tool_name ?? "");
|
|
65
|
+
const ti = (input?.tool_input ?? {});
|
|
66
|
+
const cwd = input?.cwd ? String(input.cwd) : undefined;
|
|
67
|
+
if (name === "Bash")
|
|
68
|
+
return mapShell(String(ti.command ?? ""), cwd);
|
|
69
|
+
if (name === "Write" || name === "Edit" || name === "MultiEdit")
|
|
70
|
+
return { intent: { action_type: "file.write", params: { path: rel(ti.file_path, cwd) } }, evaluated: true, source: name };
|
|
71
|
+
if (name === "NotebookEdit")
|
|
72
|
+
return { intent: { action_type: "file.write", params: { path: rel(ti.notebook_path ?? ti.file_path, cwd) } }, evaluated: true, source: name };
|
|
73
|
+
if (name === "Read")
|
|
74
|
+
return { intent: { action_type: "file.read", params: { path: rel(ti.file_path, cwd) } }, evaluated: true, source: name };
|
|
75
|
+
if (name === "WebFetch") {
|
|
76
|
+
const { host, path } = splitUrl(String(ti.url ?? ""));
|
|
77
|
+
return { intent: { action_type: "net.fetch", params: { host, path, method: "GET" } }, evaluated: true, source: name };
|
|
78
|
+
}
|
|
79
|
+
const mcp = parseMcpName(name);
|
|
80
|
+
if (mcp)
|
|
81
|
+
return { intent: { action_type: "mcp.tool.call", params: { server: mcp.server, tool: mcp.tool, args_digest: digest(ti) } }, evaluated: true, source: name };
|
|
82
|
+
return { intent: { action_type: `tool.${name.toLowerCase()}`, params: {} }, evaluated: false, source: name };
|
|
83
|
+
}
|
|
84
|
+
/** Map a Cursor hook event to a normalized taxonomy action. */
|
|
85
|
+
export function mapCursorEvent(event, payload) {
|
|
86
|
+
const p = payload ?? {};
|
|
87
|
+
const cwd = p.cwd ? String(p.cwd) : undefined;
|
|
88
|
+
switch (event) {
|
|
89
|
+
case "beforeShellExecution":
|
|
90
|
+
return mapShell(String(p.command ?? ""), cwd);
|
|
91
|
+
case "beforeReadFile":
|
|
92
|
+
return { intent: { action_type: "file.read", params: { path: rel(p.path ?? p.file_path, cwd) } }, evaluated: true, source: event };
|
|
93
|
+
case "afterFileEdit":
|
|
94
|
+
return { intent: { action_type: "file.write", params: { path: rel(p.path ?? p.file_path, cwd) } }, evaluated: true, source: event };
|
|
95
|
+
case "beforeMCPExecution": {
|
|
96
|
+
const server = String(p.server ?? p.server_name ?? "");
|
|
97
|
+
const tool = String(p.tool ?? p.tool_name ?? "");
|
|
98
|
+
return { intent: { action_type: "mcp.tool.call", params: { server, tool, args_digest: digest(p.args ?? p.arguments ?? {}) } }, evaluated: true, source: event };
|
|
99
|
+
}
|
|
100
|
+
default:
|
|
101
|
+
return { intent: { action_type: `tool.${event.toLowerCase()}`, params: {} }, evaluated: false, source: event };
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
//# sourceMappingURL=map.js.map
|
package/dist/map.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"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AoB,CAAC,CAAC,CAAC;YAC1B,MAAM,MAAM,GAAG,MAAM,CAAC,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC,WAAW,IAAI,EAAE,CAAC,CAAC;YACvD,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,SAAS,IAAI,EAAE,CAAC,CAAC;YACjD,OAAO,EAAE,MAAM,EAAE,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,SAAS,IAAI,EAAE,CAAC,EAAE,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC;QAClK,CAAC;QACD;YACE,OAAO,EAAE,MAAM,EAAE,EAAE,WAAW,EAAE,QAAQ,KAAK,CAAC,WAAW,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC;IACnH,CAAC;AACH,CAAC","sourcesContent":["// The mapper: a pure function from a coding agent's native tool call to a\n// normalized Scopebond action (Action Taxonomy v1). This is the connector's core\n// — deterministic and side-effect free, so it can be conformance-tested directly.\n\nimport { digest, redactCommand } from \"./minimize.js\";\n\nexport interface NormalizedIntent {\n action_type: string;\n params: Record<string, unknown>;\n}\nexport interface Mapped {\n intent: NormalizedIntent;\n /** false when no taxonomy type applies: emitted as tool.<name> and routed to the\n * observation path (not_evaluated), never granted. */\n evaluated: boolean;\n /** The native tool/event name, for diagnostics. */\n source: string;\n}\n\nconst rel = (value: unknown, cwd?: string): string => {\n const s = String(value ?? \"\");\n if (cwd && s.startsWith(cwd)) return s.slice(cwd.length).replace(/^[\\\\/]+/, \"\");\n return s;\n};\n\n/** The invoked program's basename, after stripping sudo and `env VAR=val` prefixes. */\nfunction programOf(command: string): string {\n const stripped = command.trim().replace(/^sudo\\s+/, \"\").replace(/^(?:env\\s+\\S+=\\S+\\s+)+/, \"\");\n const first = stripped.split(/\\s+/)[0] ?? \"\";\n return first.replace(/^.*[\\\\/]/, \"\");\n}\n\n// Best-effort `git push [--force|-f] [remote] [ref]` parse. Ambiguous pushes omit\n// the ref, which a ref bound then denies (fail closed).\nfunction parseGitPush(command: string): Record<string, unknown> | null {\n const t = command.trim().replace(/^sudo\\s+/, \"\");\n if (!/^git\\s+push(\\s|$)/.test(t)) return null;\n const force = /(?:^|\\s)(?:--force\\b|--force-with-lease\\b|-f\\b)/.test(t);\n const rest = t.replace(/^git\\s+push\\b/, \"\").trim();\n const positional = rest.split(/\\s+/).filter((a) => a && !a.startsWith(\"-\"));\n const params: Record<string, unknown> = { force };\n if (positional[0]) params.remote = positional[0];\n if (positional[1]) params.ref = positional[1].replace(/^[^:]*:/, \"\"); // src:dst → dst\n return params;\n}\n\nfunction mapShell(command: string, cwd?: string): Mapped {\n const push = parseGitPush(command);\n if (push) return { intent: { action_type: \"git.push\", params: push }, evaluated: true, source: \"shell\" };\n return {\n intent: {\n action_type: \"shell.exec\",\n params: { command: redactCommand(command), program: programOf(command), ...(cwd ? { cwd } : {}) },\n },\n evaluated: true, source: \"shell\",\n };\n}\n\nfunction parseMcpName(name: string): { server: string; tool: string } | null {\n if (!name.startsWith(\"mcp__\")) return null;\n const parts = name.split(\"__\");\n if (parts.length < 3) return null;\n return { server: parts[1], tool: parts.slice(2).join(\"__\") };\n}\n\nfunction splitUrl(url: string): { host: string; path: string } {\n try { const u = new URL(url); return { host: u.host, path: u.pathname }; }\n catch { return { host: url, path: \"\" }; }\n}\n\n/** Map a Claude Code PreToolUse payload to a normalized taxonomy action. */\nexport function mapClaudeToolUse(input: Record<string, unknown>): Mapped {\n const name = String(input?.tool_name ?? \"\");\n const ti = (input?.tool_input ?? {}) as Record<string, unknown>;\n const cwd = input?.cwd ? String(input.cwd) : undefined;\n if (name === \"Bash\") return mapShell(String(ti.command ?? \"\"), cwd);\n if (name === \"Write\" || name === \"Edit\" || name === \"MultiEdit\")\n return { intent: { action_type: \"file.write\", params: { path: rel(ti.file_path, cwd) } }, evaluated: true, source: name };\n if (name === \"NotebookEdit\")\n return { intent: { action_type: \"file.write\", params: { path: rel(ti.notebook_path ?? ti.file_path, cwd) } }, evaluated: true, source: name };\n if (name === \"Read\")\n return { intent: { action_type: \"file.read\", params: { path: rel(ti.file_path, cwd) } }, evaluated: true, source: name };\n if (name === \"WebFetch\") {\n const { host, path } = splitUrl(String(ti.url ?? \"\"));\n return { intent: { action_type: \"net.fetch\", params: { host, path, method: \"GET\" } }, evaluated: true, source: name };\n }\n const mcp = parseMcpName(name);\n if (mcp) return { intent: { action_type: \"mcp.tool.call\", params: { server: mcp.server, tool: mcp.tool, args_digest: digest(ti) } }, evaluated: true, source: name };\n return { intent: { action_type: `tool.${name.toLowerCase()}`, params: {} }, evaluated: false, source: name };\n}\n\n/** Map a Cursor hook event to a normalized taxonomy action. */\nexport function mapCursorEvent(event: string, payload: Record<string, unknown>): Mapped {\n const p = payload ?? {};\n const cwd = p.cwd ? String(p.cwd) : undefined;\n switch (event) {\n case \"beforeShellExecution\":\n return mapShell(String(p.command ?? \"\"), cwd);\n case \"beforeReadFile\":\n return { intent: { action_type: \"file.read\", params: { path: rel(p.path ?? p.file_path, cwd) } }, evaluated: true, source: event };\n case \"afterFileEdit\":\n return { intent: { action_type: \"file.write\", params: { path: rel(p.path ?? p.file_path, cwd) } }, evaluated: true, source: event };\n case \"beforeMCPExecution\": {\n const server = String(p.server ?? p.server_name ?? \"\");\n const tool = String(p.tool ?? p.tool_name ?? \"\");\n return { intent: { action_type: \"mcp.tool.call\", params: { server, tool, args_digest: digest(p.args ?? p.arguments ?? {}) } }, evaluated: true, source: event };\n }\n default:\n return { intent: { action_type: `tool.${event.toLowerCase()}`, params: {} }, evaluated: false, source: event };\n }\n}\n"]}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export declare const sha256: (value: string) => string;
|
|
2
|
+
export declare const digest: (value: unknown) => string;
|
|
3
|
+
export declare function scrubSecrets(text: string): string;
|
|
4
|
+
/** A privacy-preserving representation of a shell command: a scrubbed, truncated
|
|
5
|
+
* head plus a digest of the full original. The full command is never retained. */
|
|
6
|
+
export declare function redactCommand(command: string, headLen?: number): string;
|
|
7
|
+
//# sourceMappingURL=minimize.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"minimize.d.ts","sourceRoot":"","sources":["../src/minimize.ts"],"names":[],"mappings":"AAOA,eAAO,MAAM,MAAM,GAAI,OAAO,MAAM,KAAG,MAAsE,CAAC;AAC9G,eAAO,MAAM,MAAM,GAAI,OAAO,OAAO,KAAG,MAA2C,CAAC;AAYpF,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAMjD;AAED;mFACmF;AACnF,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,SAAK,GAAG,MAAM,CAInE"}
|
package/dist/minimize.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// Data minimization for the hook: file contents are never stored, shell commands
|
|
2
|
+
// are reduced to a scrubbed head plus a digest, and common secret shapes are
|
|
3
|
+
// removed before anything is written or signed (SB09).
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
import { canonical } from "@scopebond/policy-schema/canonical";
|
|
6
|
+
export const sha256 = (value) => "sha256:" + createHash("sha256").update(value).digest("hex");
|
|
7
|
+
export const digest = (value) => sha256(canonical(value));
|
|
8
|
+
// Command-line shapes that commonly carry secrets. Over-scrubbing is safe.
|
|
9
|
+
const SECRET_PATTERNS = [
|
|
10
|
+
/(--?(?:password|passwd|pwd|token|secret|api[-_]?key|auth)[=\s]+)(\S+)/gi,
|
|
11
|
+
/(Authorization:\s*Bearer\s+)(\S+)/gi,
|
|
12
|
+
/\b(gh[pousr]_[A-Za-z0-9]{20,})\b/g, // GitHub tokens
|
|
13
|
+
/\b(sk-[A-Za-z0-9]{20,})\b/g, // OpenAI-style keys
|
|
14
|
+
/\b(AKIA[0-9A-Z]{16})\b/g, // AWS access key id
|
|
15
|
+
/\b([A-Za-z0-9+/]{40,}={0,2})\b/g, // long base64 blobs
|
|
16
|
+
];
|
|
17
|
+
export function scrubSecrets(text) {
|
|
18
|
+
let out = text;
|
|
19
|
+
for (const re of SECRET_PATTERNS) {
|
|
20
|
+
out = out.replace(re, (_m, p1, p2) => (p2 !== undefined ? `${p1}***` : "***"));
|
|
21
|
+
}
|
|
22
|
+
return out;
|
|
23
|
+
}
|
|
24
|
+
/** A privacy-preserving representation of a shell command: a scrubbed, truncated
|
|
25
|
+
* head plus a digest of the full original. The full command is never retained. */
|
|
26
|
+
export function redactCommand(command, headLen = 64) {
|
|
27
|
+
const scrubbed = scrubSecrets(command);
|
|
28
|
+
const head = scrubbed.length > headLen ? `${scrubbed.slice(0, headLen)}…` : scrubbed;
|
|
29
|
+
return `${head} (${sha256(command)})`;
|
|
30
|
+
}
|
|
31
|
+
//# sourceMappingURL=minimize.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"minimize.js","sourceRoot":"","sources":["../src/minimize.ts"],"names":[],"mappings":"AAAA,iFAAiF;AACjF,6EAA6E;AAC7E,uDAAuD;AAEvD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,oCAAoC,CAAC;AAE/D,MAAM,CAAC,MAAM,MAAM,GAAG,CAAC,KAAa,EAAU,EAAE,CAAC,SAAS,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAC9G,MAAM,CAAC,MAAM,MAAM,GAAG,CAAC,KAAc,EAAU,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,KAAc,CAAC,CAAC,CAAC;AAEpF,2EAA2E;AAC3E,MAAM,eAAe,GAAa;IAChC,yEAAyE;IACzE,qCAAqC;IACrC,mCAAmC,EAAY,gBAAgB;IAC/D,4BAA4B,EAAoB,oBAAoB;IACpE,yBAAyB,EAAuB,oBAAoB;IACpE,iCAAiC,EAAe,oBAAoB;CACrE,CAAC;AAEF,MAAM,UAAU,YAAY,CAAC,IAAY;IACvC,IAAI,GAAG,GAAG,IAAI,CAAC;IACf,KAAK,MAAM,EAAE,IAAI,eAAe,EAAE,CAAC;QACjC,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,EAAU,EAAE,EAAW,EAAE,EAAE,CAAC,CAAC,EAAE,KAAK,SAAS,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;IAClG,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAED;mFACmF;AACnF,MAAM,UAAU,aAAa,CAAC,OAAe,EAAE,OAAO,GAAG,EAAE;IACzD,MAAM,QAAQ,GAAG,YAAY,CAAC,OAAO,CAAC,CAAC;IACvC,MAAM,IAAI,GAAG,QAAQ,CAAC,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC;IACrF,OAAO,GAAG,IAAI,KAAK,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC;AACxC,CAAC","sourcesContent":["// Data minimization for the hook: file contents are never stored, shell commands\n// are reduced to a scrubbed head plus a digest, and common secret shapes are\n// removed before anything is written or signed (SB09).\n\nimport { createHash } from \"node:crypto\";\nimport { canonical } from \"@scopebond/policy-schema/canonical\";\n\nexport const sha256 = (value: string): string => \"sha256:\" + createHash(\"sha256\").update(value).digest(\"hex\");\nexport const digest = (value: unknown): string => sha256(canonical(value as never));\n\n// Command-line shapes that commonly carry secrets. Over-scrubbing is safe.\nconst SECRET_PATTERNS: RegExp[] = [\n /(--?(?:password|passwd|pwd|token|secret|api[-_]?key|auth)[=\\s]+)(\\S+)/gi,\n /(Authorization:\\s*Bearer\\s+)(\\S+)/gi,\n /\\b(gh[pousr]_[A-Za-z0-9]{20,})\\b/g, // GitHub tokens\n /\\b(sk-[A-Za-z0-9]{20,})\\b/g, // OpenAI-style keys\n /\\b(AKIA[0-9A-Z]{16})\\b/g, // AWS access key id\n /\\b([A-Za-z0-9+/]{40,}={0,2})\\b/g, // long base64 blobs\n];\n\nexport function scrubSecrets(text: string): string {\n let out = text;\n for (const re of SECRET_PATTERNS) {\n out = out.replace(re, (_m, p1: string, p2?: string) => (p2 !== undefined ? `${p1}***` : \"***\"));\n }\n return out;\n}\n\n/** A privacy-preserving representation of a shell command: a scrubbed, truncated\n * head plus a digest of the full original. The full command is never retained. */\nexport function redactCommand(command: string, headLen = 64): string {\n const scrubbed = scrubSecrets(command);\n const head = scrubbed.length > headLen ? `${scrubbed.slice(0, headLen)}…` : scrubbed;\n return `${head} (${sha256(command)})`;\n}\n"]}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { type CloudExporter } from "@scopebond/gateway";
|
|
2
|
+
import type { Mapped } from "./map.js";
|
|
3
|
+
import { type HookConnection } from "./cloud.js";
|
|
4
|
+
export interface RuntimeConfig {
|
|
5
|
+
policyPath: string;
|
|
6
|
+
keyPath: string;
|
|
7
|
+
attesterPath: string;
|
|
8
|
+
dbPath: string;
|
|
9
|
+
/** Strict mode: an unmapped tool is policy-checked (and denied by a closed
|
|
10
|
+
* allowlist) instead of observed. Fail-closed for tools with no taxonomy
|
|
11
|
+
* mapping; default false (observe, matching the connector conformance vector). */
|
|
12
|
+
strict?: boolean;
|
|
13
|
+
/** When connected to a Cloud workspace, receipts are auto-exported to the portal.
|
|
14
|
+
* Export is best-effort and never changes the local decision. */
|
|
15
|
+
cloud?: {
|
|
16
|
+
connection: HookConnection;
|
|
17
|
+
fetch?: typeof fetch;
|
|
18
|
+
flushTimeoutMs?: number;
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
export interface Decision {
|
|
22
|
+
decision: "allow" | "deny" | "not_evaluated";
|
|
23
|
+
reason: string;
|
|
24
|
+
receipt?: unknown;
|
|
25
|
+
}
|
|
26
|
+
/** The default starter policy for a coding agent: protect release branches, deny
|
|
27
|
+
* destructive programs, allow workspace file access, and trust only the enrolled
|
|
28
|
+
* machine key. Every threshold is the operator's to edit. */
|
|
29
|
+
export declare function starterPolicy(agentKid: string): Record<string, unknown>;
|
|
30
|
+
/** Build the runtime. Throws on any setup failure (unparseable policy, missing
|
|
31
|
+
* key, unavailable store) — the CLI turns that into a fail-closed deny. */
|
|
32
|
+
export declare function createHookRuntime(config: RuntimeConfig): {
|
|
33
|
+
gateway: import("@scopebond/gateway").Gateway;
|
|
34
|
+
agentKid: string;
|
|
35
|
+
exporter: CloudExporter | undefined;
|
|
36
|
+
/** Deliver queued receipts to Cloud with a bounded timeout, then it is safe to
|
|
37
|
+
* exit. Undelivered receipts persist in the durable outbox for the next run. */
|
|
38
|
+
flush(): Promise<void>;
|
|
39
|
+
evaluate(mapped: Mapped): Promise<Decision>;
|
|
40
|
+
};
|
|
41
|
+
//# sourceMappingURL=runtime.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../src/runtime.ts"],"names":[],"mappings":"AAMA,OAAO,EAA6C,KAAK,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAGnG,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AACvC,OAAO,EAAgC,KAAK,cAAc,EAAE,MAAM,YAAY,CAAC;AAE/E,MAAM,WAAW,aAAa;IAC5B,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;IAChB,YAAY,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,MAAM,CAAC;IACf;;uFAEmF;IACnF,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB;sEACkE;IAClE,KAAK,CAAC,EAAE;QAAE,UAAU,EAAE,cAAc,CAAC;QAAC,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;QAAC,cAAc,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CACvF;AAED,MAAM,WAAW,QAAQ;IACvB,QAAQ,EAAE,OAAO,GAAG,MAAM,GAAG,eAAe,CAAC;IAC7C,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED;;8DAE8D;AAC9D,wBAAgB,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAkBvE;AAED;4EAC4E;AAC5E,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,aAAa;;;;IAuBnD;qFACiF;aAClE,OAAO,CAAC,IAAI,CAAC;qBAGL,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC;EAapD"}
|
package/dist/runtime.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// The hook runtime: a check-only (M0) gateway built once from the enrolled
|
|
2
|
+
// machine key, policy and a durable local receipt log. Each mapped action is
|
|
3
|
+
// signed by the machine key, decided against policy and countersigned — locally,
|
|
4
|
+
// with no HTTP server and no Cloud dependency in 0.1.
|
|
5
|
+
import { readFileSync } from "node:fs";
|
|
6
|
+
import { createGateway, StaticPrincipalKeyRegistry } from "@scopebond/gateway";
|
|
7
|
+
import { loadOrCreateAttester, openReceiptStore } from "@scopebond/gateway/node";
|
|
8
|
+
import { createSigner } from "@scopebond/sdk";
|
|
9
|
+
import { attachExporter, flushBounded } from "./cloud.js";
|
|
10
|
+
/** The default starter policy for a coding agent: protect release branches, deny
|
|
11
|
+
* destructive programs, allow workspace file access, and trust only the enrolled
|
|
12
|
+
* machine key. Every threshold is the operator's to edit. */
|
|
13
|
+
export function starterPolicy(agentKid) {
|
|
14
|
+
return {
|
|
15
|
+
vocabulary_version: "1.0", policy_id: "coding-agent", version: 1,
|
|
16
|
+
clauses: [
|
|
17
|
+
{
|
|
18
|
+
id: "protect-branches", type: "action_allowlist", mode: "enforce", action_types: ["git.push"],
|
|
19
|
+
param_bounds: { ref: { pattern: "^(?!(?:main|master)$)(?!release/).+" } },
|
|
20
|
+
description: "Deny pushes to main, master and release/*.",
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
id: "safe-shell", type: "action_allowlist", mode: "enforce", action_types: ["shell.exec"],
|
|
24
|
+
param_bounds: { program: { pattern: "^(?!(?:rm|sudo|shutdown|reboot|mkfs|dd)$).+" } },
|
|
25
|
+
description: "Deny destructive programs (rm, sudo, …).",
|
|
26
|
+
},
|
|
27
|
+
{ id: "workspace-files", type: "action_allowlist", mode: "enforce", action_types: ["file.write", "file.read"] },
|
|
28
|
+
{ id: "keys", type: "key_policy", active_keys: [agentKid], description: "Only the enrolled machine key may sign." },
|
|
29
|
+
],
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
/** Build the runtime. Throws on any setup failure (unparseable policy, missing
|
|
33
|
+
* key, unavailable store) — the CLI turns that into a fail-closed deny. */
|
|
34
|
+
export function createHookRuntime(config) {
|
|
35
|
+
const policy = JSON.parse(readFileSync(config.policyPath, "utf8"));
|
|
36
|
+
const agent = createSigner({ privateKeyPem: readFileSync(config.keyPath, "utf8") });
|
|
37
|
+
const keys = new StaticPrincipalKeyRegistry([
|
|
38
|
+
{ kid: agent.kid, publicKeyPem: agent.publicKeyPem, purposes: ["agent"], status: "active" },
|
|
39
|
+
]);
|
|
40
|
+
const { attester } = loadOrCreateAttester({ file: config.attesterPath });
|
|
41
|
+
const { store: baseStore } = openReceiptStore({ db: config.dbPath });
|
|
42
|
+
// When connected, mirror every stored receipt to the hosted portal through a
|
|
43
|
+
// durable outbox. The wrapped store's decision is unchanged; export is best-effort.
|
|
44
|
+
let store = baseStore;
|
|
45
|
+
let exporter;
|
|
46
|
+
if (config.cloud) {
|
|
47
|
+
const attached = attachExporter(config.dbPath + ".cloud-outbox.db", config.cloud.connection, baseStore, config.cloud.fetch);
|
|
48
|
+
store = attached.store;
|
|
49
|
+
exporter = attached.exporter;
|
|
50
|
+
}
|
|
51
|
+
const gateway = createGateway({ policy, authentication: { keys }, attester, store, mode: "check_only" });
|
|
52
|
+
return {
|
|
53
|
+
gateway,
|
|
54
|
+
agentKid: agent.kid,
|
|
55
|
+
exporter,
|
|
56
|
+
/** Deliver queued receipts to Cloud with a bounded timeout, then it is safe to
|
|
57
|
+
* exit. Undelivered receipts persist in the durable outbox for the next run. */
|
|
58
|
+
async flush() {
|
|
59
|
+
if (exporter)
|
|
60
|
+
await flushBounded(exporter, config.cloud?.flushTimeoutMs);
|
|
61
|
+
},
|
|
62
|
+
async evaluate(mapped) {
|
|
63
|
+
const signed = agent.sign(mapped.intent);
|
|
64
|
+
if (!mapped.evaluated && !config.strict) {
|
|
65
|
+
// Unknown tool, non-strict: observe without evaluating — grants nothing (D30).
|
|
66
|
+
const { receipt } = await gateway.observeAction({ intent: signed.intent, authorization: signed.authorization });
|
|
67
|
+
return { decision: "not_evaluated", reason: `no policy applies to ${mapped.intent.action_type}`, receipt };
|
|
68
|
+
}
|
|
69
|
+
// Evaluated tools, and (in strict mode) unmapped tool.<name> actions, go
|
|
70
|
+
// through policy — a closed allowlist denies an unlisted action.
|
|
71
|
+
const result = await gateway.handleAction({ intent: signed.intent, authorization: signed.authorization });
|
|
72
|
+
return { decision: result.allowed ? "allow" : "deny", reason: result.reason, receipt: result.receipt };
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
//# sourceMappingURL=runtime.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../src/runtime.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,6EAA6E;AAC7E,iFAAiF;AACjF,sDAAsD;AAEtD,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,aAAa,EAAE,0BAA0B,EAAsB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ACjF,KAAK,CAAC,KAAK;YACT,IAAI,QAAQ;gBAAE,MAAM,YAAY,CAAC,QAAQ,EAAE,MAAM,CAAC,KAAK,EAAE,cAAc,CAAC,CAAC;QAC3E,CAAC;QACD,KAAK,CAAC,QAAQ,CAAC,MAAc;YAC3B,MAAM,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YACzC,IAAI,CAAC,MAAM,CAAC,SAAS,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;gBACxC,+EAA+E;gBAC/E,MAAM,EAAE,OAAO,EAAE,GAAG,MAAM,OAAO,CAAC,aAAa,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,EAAE,MAAM,CAAC,aAAa,EAAE,CAAC,CAAC;gBAChH,OAAO,EAAE,QAAQ,EAAE,eAAe,EAAE,MAAM,EAAE,wBAAwB,MAAM,CAAC,MAAM,CAAC,WAAW,EAAE,EAAE,OAAO,EAAE,CAAC;YAC7G,CAAC;YACD,yEAAyE;YACzE,iEAAiE;YACjE,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,EAAE,MAAM,CAAC,aAAa,EAAE,CAAC,CAAC;YAC1G,OAAO,EAAE,QAAQ,EAAE,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,CAAC;QACzG,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// The hook runtime: a check-only (M0) gateway built once from the enrolled\n// machine key, policy and a durable local receipt log. Each mapped action is\n// signed by the machine key, decided against policy and countersigned — locally,\n// with no HTTP server and no Cloud dependency in 0.1.\n\nimport { readFileSync } from \"node:fs\";\nimport { createGateway, StaticPrincipalKeyRegistry, type CloudExporter } from \"@scopebond/gateway\";\nimport { loadOrCreateAttester, openReceiptStore } from \"@scopebond/gateway/node\";\nimport { createSigner } from \"@scopebond/sdk\";\nimport type { Mapped } from \"./map.js\";\nimport { attachExporter, flushBounded, type HookConnection } from \"./cloud.js\";\n\nexport interface RuntimeConfig {\n policyPath: string;\n keyPath: string;\n attesterPath: string;\n dbPath: string;\n /** Strict mode: an unmapped tool is policy-checked (and denied by a closed\n * allowlist) instead of observed. Fail-closed for tools with no taxonomy\n * mapping; default false (observe, matching the connector conformance vector). */\n strict?: boolean;\n /** When connected to a Cloud workspace, receipts are auto-exported to the portal.\n * Export is best-effort and never changes the local decision. */\n cloud?: { connection: HookConnection; fetch?: typeof fetch; flushTimeoutMs?: number };\n}\n\nexport interface Decision {\n decision: \"allow\" | \"deny\" | \"not_evaluated\";\n reason: string;\n receipt?: unknown;\n}\n\n/** The default starter policy for a coding agent: protect release branches, deny\n * destructive programs, allow workspace file access, and trust only the enrolled\n * machine key. Every threshold is the operator's to edit. */\nexport function starterPolicy(agentKid: string): Record<string, unknown> {\n return {\n vocabulary_version: \"1.0\", policy_id: \"coding-agent\", version: 1,\n clauses: [\n {\n id: \"protect-branches\", type: \"action_allowlist\", mode: \"enforce\", action_types: [\"git.push\"],\n param_bounds: { ref: { pattern: \"^(?!(?:main|master)$)(?!release/).+\" } },\n description: \"Deny pushes to main, master and release/*.\",\n },\n {\n id: \"safe-shell\", type: \"action_allowlist\", mode: \"enforce\", action_types: [\"shell.exec\"],\n param_bounds: { program: { pattern: \"^(?!(?:rm|sudo|shutdown|reboot|mkfs|dd)$).+\" } },\n description: \"Deny destructive programs (rm, sudo, …).\",\n },\n { id: \"workspace-files\", type: \"action_allowlist\", mode: \"enforce\", action_types: [\"file.write\", \"file.read\"] },\n { id: \"keys\", type: \"key_policy\", active_keys: [agentKid], description: \"Only the enrolled machine key may sign.\" },\n ],\n };\n}\n\n/** Build the runtime. Throws on any setup failure (unparseable policy, missing\n * key, unavailable store) — the CLI turns that into a fail-closed deny. */\nexport function createHookRuntime(config: RuntimeConfig) {\n const policy = JSON.parse(readFileSync(config.policyPath, \"utf8\"));\n const agent = createSigner({ privateKeyPem: readFileSync(config.keyPath, \"utf8\") });\n const keys = new StaticPrincipalKeyRegistry([\n { kid: agent.kid, publicKeyPem: agent.publicKeyPem, purposes: [\"agent\"], status: \"active\" },\n ]);\n const { attester } = loadOrCreateAttester({ file: config.attesterPath });\n const { store: baseStore } = openReceiptStore({ db: config.dbPath });\n // When connected, mirror every stored receipt to the hosted portal through a\n // durable outbox. The wrapped store's decision is unchanged; export is best-effort.\n let store = baseStore;\n let exporter: CloudExporter | undefined;\n if (config.cloud) {\n const attached = attachExporter(config.dbPath + \".cloud-outbox.db\", config.cloud.connection, baseStore, config.cloud.fetch);\n store = attached.store;\n exporter = attached.exporter;\n }\n const gateway = createGateway({ policy, authentication: { keys }, attester, store, mode: \"check_only\" });\n\n return {\n gateway,\n agentKid: agent.kid,\n exporter,\n /** Deliver queued receipts to Cloud with a bounded timeout, then it is safe to\n * exit. Undelivered receipts persist in the durable outbox for the next run. */\n async flush(): Promise<void> {\n if (exporter) await flushBounded(exporter, config.cloud?.flushTimeoutMs);\n },\n async evaluate(mapped: Mapped): Promise<Decision> {\n const signed = agent.sign(mapped.intent);\n if (!mapped.evaluated && !config.strict) {\n // Unknown tool, non-strict: observe without evaluating — grants nothing (D30).\n const { receipt } = await gateway.observeAction({ intent: signed.intent, authorization: signed.authorization });\n return { decision: \"not_evaluated\", reason: `no policy applies to ${mapped.intent.action_type}`, receipt };\n }\n // Evaluated tools, and (in strict mode) unmapped tool.<name> actions, go\n // through policy — a closed allowlist denies an unlisted action.\n const result = await gateway.handleAction({ intent: signed.intent, authorization: signed.authorization });\n return { decision: result.allowed ? \"allow\" : \"deny\", reason: result.reason, receipt: result.receipt };\n },\n };\n}\n"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@scopebond/hook",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Scopebond hook for Claude Code and Cursor — checks each coding-agent tool call against policy before it runs (in-path, cooperative M0) and records a signed receipt, locally.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"author": "Avouro LLC",
|
|
7
|
+
"homepage": "https://github.com/avouro-com/scopebond/tree/main/packages/hook#readme",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "https://github.com/avouro-com/scopebond.git",
|
|
11
|
+
"directory": "packages/hook"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/avouro-com/scopebond/issues"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"scopebond",
|
|
18
|
+
"claude-code",
|
|
19
|
+
"cursor",
|
|
20
|
+
"hooks",
|
|
21
|
+
"ai-agents",
|
|
22
|
+
"policy"
|
|
23
|
+
],
|
|
24
|
+
"engines": {
|
|
25
|
+
"node": ">=22"
|
|
26
|
+
},
|
|
27
|
+
"type": "module",
|
|
28
|
+
"main": "dist/index.js",
|
|
29
|
+
"types": "dist/index.d.ts",
|
|
30
|
+
"exports": {
|
|
31
|
+
".": {
|
|
32
|
+
"types": "./dist/index.d.ts",
|
|
33
|
+
"default": "./dist/index.js"
|
|
34
|
+
}
|
|
35
|
+
},
|
|
36
|
+
"bin": {
|
|
37
|
+
"scopebond-hook": "dist/cli.js"
|
|
38
|
+
},
|
|
39
|
+
"files": [
|
|
40
|
+
"dist"
|
|
41
|
+
],
|
|
42
|
+
"dependencies": {
|
|
43
|
+
"@scopebond/policy-schema": "^0.3.0",
|
|
44
|
+
"@scopebond/sdk": "^0.1.1",
|
|
45
|
+
"@scopebond/gateway": "^0.5.0"
|
|
46
|
+
},
|
|
47
|
+
"publishConfig": {
|
|
48
|
+
"access": "public"
|
|
49
|
+
},
|
|
50
|
+
"scripts": {
|
|
51
|
+
"build": "tsc -p tsconfig.json",
|
|
52
|
+
"test": "tsc -p tsconfig.json && node --test test/*.test.mjs"
|
|
53
|
+
}
|
|
54
|
+
}
|