@intended-inc/claude-code-hook 0.1.1 → 0.3.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/README.md +41 -3
- package/dist/bin.js +379 -26
- package/dist/bin.mjs +381 -28
- package/dist/index.d.mts +77 -13
- package/dist/index.d.ts +77 -13
- package/dist/index.js +389 -5
- package/dist/index.mjs +379 -6
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -24,13 +24,51 @@ authority layer — "no token, no action" before execution.
|
|
|
24
24
|
|
|
25
25
|
| State | Result |
|
|
26
26
|
|---|---|
|
|
27
|
-
| Unconfigured (no `INTENDED_API_KEY` / `INTENDED_TENANT_ID
|
|
27
|
+
| Unconfigured (no `INTENDED_API_KEY` / `INTENDED_TENANT_ID`, or either is blank) | **deny** every governed tool call, with a message naming what is missing and how to fix it |
|
|
28
|
+
| Unconfigured with `INTENDED_HOOK_UNCONFIGURED=allow` | allow, **ungoverned**, with a warning on every call (for local trials only) |
|
|
29
|
+
| Hook input that is not a JSON object, or any error inside the hook | **deny** (the hook always exits 0 with an answer, so a crash never lets a tool run) |
|
|
28
30
|
| `200 APPROVED` | allow |
|
|
29
|
-
| `202 ESCALATED` | **
|
|
31
|
+
| `202 ESCALATED` | **wait** for the approver in Intended (see below) |
|
|
30
32
|
| `403 DENIED` | **deny** (with reason) |
|
|
31
33
|
| Unreachable, non-2xx (401/429/5xx/…), or unrecognized body | **deny** (fail-closed) — never falls through to allow |
|
|
32
34
|
|
|
33
|
-
|
|
35
|
+
## What happens on ESCALATE
|
|
36
|
+
|
|
37
|
+
The hook waits for a human approver to decide in the Intended console, for up to
|
|
38
|
+
`INTENDED_HOOK_ESCALATION_WAIT_SECONDS` (default `45`).
|
|
39
|
+
|
|
40
|
+
- Approved in time: **allow**.
|
|
41
|
+
- Rejected, or the approval request expired: **deny** with the reason.
|
|
42
|
+
- Still undecided: **deny** (fail-closed) with a message giving the intent id: ask an
|
|
43
|
+
approver to approve it in the Intended console, then retry the same tool call. The
|
|
44
|
+
pending intent is saved in `~/.intended/pending.json`, keyed by a hash of the tool name
|
|
45
|
+
and arguments (bounded; expired entries are dropped). When Claude retries the same
|
|
46
|
+
tool call with the same arguments, the hook checks that intent instead of creating a
|
|
47
|
+
new escalation, and allows the call once it is approved.
|
|
48
|
+
|
|
49
|
+
Set `INTENDED_HOOK_ON_PENDING=ask` to defer a still-undecided call to Claude Code's own
|
|
50
|
+
permission prompt instead of denying it.
|
|
51
|
+
|
|
52
|
+
A wait that fails with 401, 403 (the key needs the `intent:read` scope), 404, or an
|
|
53
|
+
unrecognised response is a deny. Only an approval allows.
|
|
54
|
+
|
|
55
|
+
Claude Code hooks time out after 60 seconds by default. To wait longer than about 55
|
|
56
|
+
seconds, raise the hook's `timeout` (in seconds) above the wait:
|
|
57
|
+
|
|
58
|
+
```json
|
|
59
|
+
{ "type": "command", "command": "npx -y @intended-inc/claude-code-hook", "timeout": 300 }
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
and set `INTENDED_HOOK_ESCALATION_WAIT_SECONDS` below it (for example `280`).
|
|
63
|
+
|
|
64
|
+
Config (env): `INTENDED_API_KEY` (scopes `intent:write` and `intent:read`), `INTENDED_TENANT_ID`,
|
|
65
|
+
`INTENDED_API_URL` (optional), `INTENDED_HOOK_ESCALATION_WAIT_SECONDS` (default `45`),
|
|
66
|
+
`INTENDED_HOOK_ON_PENDING` (`deny` or `ask`, default `deny`), `INTENDED_HOOK_UNCONFIGURED`
|
|
67
|
+
(set to `allow` to let tool calls through ungoverned while the hook is unconfigured; anything
|
|
68
|
+
else, or unset, denies).
|
|
69
|
+
|
|
70
|
+
Upgrading from 0.2: an unconfigured hook used to allow every call silently. It now denies.
|
|
71
|
+
Set the key and tenant, or set `INTENDED_HOOK_UNCONFIGURED=allow` while you try it out.
|
|
34
72
|
Attribution: actor = `claude-code:<tool>`. Last decision → `~/.intended/last-decision.json`.
|
|
35
73
|
|
|
36
74
|
It's a CLI (the SDK is the library). Apache-2.0.
|
package/dist/bin.js
CHANGED
|
@@ -4,9 +4,145 @@
|
|
|
4
4
|
var fs = require('fs');
|
|
5
5
|
var os = require('os');
|
|
6
6
|
var path = require('path');
|
|
7
|
+
var crypto = require('crypto');
|
|
8
|
+
|
|
9
|
+
var FINAL = /* @__PURE__ */ new Set(["ALLOW", "DENY", "EXPIRED"]);
|
|
10
|
+
var MAX_POLL_SECONDS = 50;
|
|
11
|
+
var MAX_BACKOFF_MS = 1e4;
|
|
12
|
+
var MIN_REPOLL_MS = 1e3;
|
|
13
|
+
var defaultSleep = (ms) => new Promise((r) => setTimeout(r, Math.max(0, ms)));
|
|
14
|
+
function str(v) {
|
|
15
|
+
return typeof v === "string" && v.length > 0 ? v : null;
|
|
16
|
+
}
|
|
17
|
+
function base(intentId, status, reason) {
|
|
18
|
+
return {
|
|
19
|
+
intentId,
|
|
20
|
+
status,
|
|
21
|
+
reason,
|
|
22
|
+
token: null,
|
|
23
|
+
decidedBy: null,
|
|
24
|
+
decidedAt: null,
|
|
25
|
+
escalationId: null,
|
|
26
|
+
expiresAt: null,
|
|
27
|
+
receiptUrl: null
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
function parseBody(intentId, body, apiUrl) {
|
|
31
|
+
const status = body.status;
|
|
32
|
+
if (status !== "ALLOW" && status !== "DENY" && status !== "PENDING" && status !== "EXPIRED") return null;
|
|
33
|
+
const receipt = str(body.receiptUrl);
|
|
34
|
+
return {
|
|
35
|
+
intentId: str(body.intentId) ?? intentId,
|
|
36
|
+
status,
|
|
37
|
+
reason: str(body.reason) ?? `Decision: ${status}`,
|
|
38
|
+
token: status === "ALLOW" ? str(body.token) : null,
|
|
39
|
+
decidedBy: body.decidedBy && typeof body.decidedBy === "object" ? body.decidedBy : null,
|
|
40
|
+
decidedAt: str(body.decidedAt),
|
|
41
|
+
escalationId: str(body.escalationId),
|
|
42
|
+
expiresAt: str(body.expiresAt),
|
|
43
|
+
receiptUrl: receipt ? /^https?:\/\//.test(receipt) ? receipt : `${apiUrl}${receipt.startsWith("/") ? "" : "/"}${receipt}` : null
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
function retryAfterHeaderMs(res) {
|
|
47
|
+
const raw = res.headers?.get?.("retry-after");
|
|
48
|
+
const n = raw == null ? NaN : Number(raw);
|
|
49
|
+
return Number.isFinite(n) && n > 0 ? n * 1e3 : 0;
|
|
50
|
+
}
|
|
51
|
+
async function waitForDecision(intentId, opts) {
|
|
52
|
+
const apiUrl = (opts.apiUrl ?? "https://api.intended.so").replace(/\/$/, "");
|
|
53
|
+
const fetchImpl = opts.fetchImpl ?? fetch;
|
|
54
|
+
const now = opts.now ?? Date.now;
|
|
55
|
+
const sleep = opts.sleep ?? defaultSleep;
|
|
56
|
+
const deadline = now() + Math.max(0, opts.timeoutMs);
|
|
57
|
+
const headers = {
|
|
58
|
+
authorization: `Bearer ${opts.apiKey}`,
|
|
59
|
+
"x-tenant-id": opts.tenantId
|
|
60
|
+
};
|
|
61
|
+
let backoffMs = 1e3;
|
|
62
|
+
for (; ; ) {
|
|
63
|
+
const remaining = deadline - now();
|
|
64
|
+
const timeoutSec = remaining <= 0 ? 0 : Math.min(MAX_POLL_SECONDS, Math.ceil(remaining / 1e3));
|
|
65
|
+
const url = `${apiUrl}/v1/decisions/${encodeURIComponent(intentId)}/wait?timeout=${timeoutSec}&tenantId=${encodeURIComponent(opts.tenantId)}`;
|
|
66
|
+
const startedAt = now();
|
|
67
|
+
let res = null;
|
|
68
|
+
try {
|
|
69
|
+
res = await fetchImpl(url, {
|
|
70
|
+
headers,
|
|
71
|
+
// The server holds at most timeoutSec; give the network some slack beyond that.
|
|
72
|
+
signal: AbortSignal.timeout(timeoutSec * 1e3 + 15e3)
|
|
73
|
+
});
|
|
74
|
+
} catch {
|
|
75
|
+
res = null;
|
|
76
|
+
}
|
|
77
|
+
let transientWaitMs = 0;
|
|
78
|
+
if (res) {
|
|
79
|
+
if (res.status === 401) {
|
|
80
|
+
return { ...base(intentId, "ERROR", "The Intended API rejected the API key (401). The action is not approved."), error: "unauthorized" };
|
|
81
|
+
}
|
|
82
|
+
if (res.status === 403) {
|
|
83
|
+
return {
|
|
84
|
+
...base(
|
|
85
|
+
intentId,
|
|
86
|
+
"ERROR",
|
|
87
|
+
"This API key cannot read decisions: it needs the intent:read scope. The action is not approved."
|
|
88
|
+
),
|
|
89
|
+
error: "forbidden"
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
if (res.status === 404) {
|
|
93
|
+
return { ...base(intentId, "ERROR", `Intended has no decision for intent ${intentId}. The action is not approved.`), error: "not_found" };
|
|
94
|
+
}
|
|
95
|
+
if (res.status === 429 || res.status >= 500) {
|
|
96
|
+
transientWaitMs = Math.max(backoffMs, retryAfterHeaderMs(res));
|
|
97
|
+
} else {
|
|
98
|
+
const body = await res.json().catch(() => null);
|
|
99
|
+
const parsed = res.status === 200 && body ? parseBody(intentId, body, apiUrl) : null;
|
|
100
|
+
if (!parsed) {
|
|
101
|
+
return {
|
|
102
|
+
...base(intentId, "ERROR", `Unrecognised decision response (HTTP ${res.status}). The action is not approved.`),
|
|
103
|
+
error: "bad_response"
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
if (FINAL.has(parsed.status)) return parsed;
|
|
107
|
+
if (now() >= deadline) return { ...parsed, timedOut: true };
|
|
108
|
+
const retryAfterMs = typeof body?.retryAfterMs === "number" && body.retryAfterMs > 0 ? body.retryAfterMs : 0;
|
|
109
|
+
const answeredFast = now() - startedAt < Math.min(timeoutSec * 1e3, MIN_REPOLL_MS) / 2;
|
|
110
|
+
const pause = retryAfterMs > 0 ? retryAfterMs : answeredFast ? MIN_REPOLL_MS : 0;
|
|
111
|
+
if (pause > 0) await sleep(Math.min(pause, Math.max(0, deadline - now())));
|
|
112
|
+
backoffMs = 1e3;
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
} else {
|
|
116
|
+
transientWaitMs = backoffMs;
|
|
117
|
+
}
|
|
118
|
+
if (now() >= deadline) {
|
|
119
|
+
return {
|
|
120
|
+
...base(
|
|
121
|
+
intentId,
|
|
122
|
+
"PENDING",
|
|
123
|
+
"The Intended decision service could not be reached before the wait ended. The action is still not approved."
|
|
124
|
+
),
|
|
125
|
+
timedOut: true
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
await sleep(Math.min(transientWaitMs, Math.max(0, deadline - now())));
|
|
129
|
+
backoffMs = Math.min(backoffMs * 2, MAX_BACKOFF_MS);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
function canonicalJson(value) {
|
|
133
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
|
|
134
|
+
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
|
|
135
|
+
const obj = value;
|
|
136
|
+
return `{${Object.keys(obj).sort().filter((k) => obj[k] !== void 0).map((k) => `${JSON.stringify(k)}:${canonicalJson(obj[k])}`).join(",")}}`;
|
|
137
|
+
}
|
|
138
|
+
function toolCallKey(toolName, args) {
|
|
139
|
+
return crypto.createHash("sha256").update(`${toolName}
|
|
140
|
+
${canonicalJson(args ?? {})}`).digest("hex");
|
|
141
|
+
}
|
|
7
142
|
|
|
8
143
|
// src/evaluate.ts
|
|
9
144
|
var AUTHORITY_STATUSES = /* @__PURE__ */ new Set([200, 202, 403]);
|
|
145
|
+
var DEFAULT_ESCALATION_WAIT_SECONDS = 45;
|
|
10
146
|
var MAX_DESCRIBED_KEYS = 20;
|
|
11
147
|
var SAFE_KEY = /^[A-Za-z_][A-Za-z0-9_.-]{0,63}$/;
|
|
12
148
|
function describeToolCall(name, args) {
|
|
@@ -17,15 +153,79 @@ function describeToolCall(name, args) {
|
|
|
17
153
|
const list = [...named, ...unnamed > 0 ? [`+${unnamed} more`] : []].join(", ");
|
|
18
154
|
return `Call tool "${name}" with args: ${list}`;
|
|
19
155
|
}
|
|
156
|
+
function escalationWaitMs(env) {
|
|
157
|
+
const raw = env.INTENDED_HOOK_ESCALATION_WAIT_SECONDS;
|
|
158
|
+
if (raw === void 0 || raw.trim() === "") return DEFAULT_ESCALATION_WAIT_SECONDS * 1e3;
|
|
159
|
+
const n = Number(raw);
|
|
160
|
+
return Number.isFinite(n) && n >= 0 ? Math.round(n * 1e3) : DEFAULT_ESCALATION_WAIT_SECONDS * 1e3;
|
|
161
|
+
}
|
|
162
|
+
function onPending(env) {
|
|
163
|
+
return env.INTENDED_HOOK_ON_PENDING?.trim().toLowerCase() === "ask" ? "ask" : "deny";
|
|
164
|
+
}
|
|
165
|
+
var UNCONFIGURED_OPT_OUT = "allow";
|
|
166
|
+
function unconfiguredOptOut(env) {
|
|
167
|
+
return env.INTENDED_HOOK_UNCONFIGURED?.trim().toLowerCase() === UNCONFIGURED_OPT_OUT;
|
|
168
|
+
}
|
|
169
|
+
function missingConfig(env) {
|
|
170
|
+
const missing = [];
|
|
171
|
+
if (!env.INTENDED_API_KEY?.trim()) missing.push("INTENDED_API_KEY");
|
|
172
|
+
if (!env.INTENDED_TENANT_ID?.trim()) missing.push("INTENDED_TENANT_ID");
|
|
173
|
+
return missing;
|
|
174
|
+
}
|
|
175
|
+
function unconfiguredDenyReason(missing, toolName) {
|
|
176
|
+
return `Intended: blocked "${toolName}" because the Intended Claude Code hook is not configured (missing ${missing.join(" and ")}). The hook fails closed: without a key it cannot get an authority decision, so it denies every tool call it governs. To configure it, set INTENDED_API_KEY (an Intended API key with the intent:write and intent:read scopes) and INTENDED_TENANT_ID (your workspace id) in the environment Claude Code runs in, for example in the "env" block of .claude/settings.json or your shell profile, then retry. For a local trial without Intended, set INTENDED_HOOK_UNCONFIGURED=allow: tool calls then run ungoverned, with a warning on every call. Setup: https://www.intended.so/developers/docs/developer/decision-outcomes#claude-code-hook`;
|
|
177
|
+
}
|
|
178
|
+
function unconfiguredAllowWarning(missing, toolName) {
|
|
179
|
+
return `WARNING: Intended is NOT governing tool calls. "${toolName}" is running without an authority decision because INTENDED_HOOK_UNCONFIGURED=allow is set and the hook is not configured (missing ${missing.join(" and ")}). Use this only for local trials. Set INTENDED_API_KEY and INTENDED_TENANT_ID and remove INTENDED_HOOK_UNCONFIGURED to govern tool calls.`;
|
|
180
|
+
}
|
|
20
181
|
async function evaluateHookDecision(input) {
|
|
21
|
-
const { event, env } = input;
|
|
182
|
+
const { event, env, pendingStore } = input;
|
|
183
|
+
if (event === null || typeof event !== "object" || Array.isArray(event) || event.tool_input !== void 0 && (event.tool_input === null || typeof event.tool_input !== "object" || Array.isArray(event.tool_input))) {
|
|
184
|
+
const reason2 = "Intended: the tool call from Claude Code is not in the expected format, so it is not authorized (fail-closed).";
|
|
185
|
+
return {
|
|
186
|
+
permissionDecision: "deny",
|
|
187
|
+
reason: reason2,
|
|
188
|
+
record: { tool: "unknown", verdict: "UNREADABLE", reason: reason2, intentId: null, tokenIssued: false }
|
|
189
|
+
};
|
|
190
|
+
}
|
|
22
191
|
const fetchImpl = input.fetchImpl ?? globalThis.fetch;
|
|
23
192
|
const toolName = event.tool_name ?? "unknown";
|
|
24
193
|
const args = { ...event.tool_input ?? {} };
|
|
25
|
-
const apiKey = env.INTENDED_API_KEY;
|
|
26
|
-
const tenantId = env.INTENDED_TENANT_ID;
|
|
27
194
|
const apiUrl = (env.INTENDED_API_URL ?? "https://api.intended.so").replace(/\/$/, "");
|
|
28
|
-
|
|
195
|
+
const missing = missingConfig(env);
|
|
196
|
+
if (missing.length > 0) {
|
|
197
|
+
if (unconfiguredOptOut(env)) {
|
|
198
|
+
const warning = unconfiguredAllowWarning(missing, toolName);
|
|
199
|
+
return {
|
|
200
|
+
permissionDecision: "allow",
|
|
201
|
+
warning,
|
|
202
|
+
record: { tool: toolName, verdict: "UNGOVERNED", reason: warning, intentId: null, tokenIssued: false }
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
const reason2 = unconfiguredDenyReason(missing, toolName);
|
|
206
|
+
return {
|
|
207
|
+
permissionDecision: "deny",
|
|
208
|
+
reason: reason2,
|
|
209
|
+
record: { tool: toolName, verdict: "UNCONFIGURED", reason: reason2, intentId: null, tokenIssued: false }
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
const apiKey = env.INTENDED_API_KEY.trim();
|
|
213
|
+
const tenantId = env.INTENDED_TENANT_ID.trim();
|
|
214
|
+
const key = toolCallKey(toolName, args);
|
|
215
|
+
const wait = (intentId) => waitForDecision(intentId, {
|
|
216
|
+
apiUrl,
|
|
217
|
+
apiKey,
|
|
218
|
+
tenantId,
|
|
219
|
+
fetchImpl,
|
|
220
|
+
timeoutMs: escalationWaitMs(env),
|
|
221
|
+
now: input.now,
|
|
222
|
+
sleep: input.sleep
|
|
223
|
+
});
|
|
224
|
+
const pendingIntentId = safe(() => pendingStore?.get(key));
|
|
225
|
+
if (pendingIntentId) {
|
|
226
|
+
const outcome = await wait(pendingIntentId);
|
|
227
|
+
return settle(outcome, pendingIntentId, toolName, key, env, pendingStore);
|
|
228
|
+
}
|
|
29
229
|
let res;
|
|
30
230
|
try {
|
|
31
231
|
res = await fetchImpl(`${apiUrl}/v1/agent-intent`, {
|
|
@@ -56,38 +256,191 @@ async function evaluateHookDecision(input) {
|
|
|
56
256
|
tokenIssued: Boolean(data.authorityDecisionToken)
|
|
57
257
|
};
|
|
58
258
|
if (verdict === "APPROVED") return { permissionDecision: "allow", record };
|
|
59
|
-
if (verdict === "ESCALATED")
|
|
259
|
+
if (verdict === "ESCALATED") {
|
|
260
|
+
if (!data.intentId) {
|
|
261
|
+
return { permissionDecision: "deny", reason: "Intended: escalated without an intent id to wait on \u2014 fail-closed.", record };
|
|
262
|
+
}
|
|
263
|
+
const outcome = await wait(data.intentId);
|
|
264
|
+
return settle(outcome, data.intentId, toolName, key, env, pendingStore, reason);
|
|
265
|
+
}
|
|
60
266
|
return { permissionDecision: "deny", reason: `Intended: denied \u2014 ${reason || "fail-closed (unrecognized decision)"}`, record };
|
|
61
267
|
}
|
|
268
|
+
function settle(outcome, intentId, toolName, key, env, store, escalationReason = "") {
|
|
269
|
+
const record = {
|
|
270
|
+
tool: toolName,
|
|
271
|
+
verdict: outcome.status === "ALLOW" ? "APPROVED_AFTER_ESCALATION" : outcome.status === "PENDING" ? "ESCALATED" : outcome.status,
|
|
272
|
+
reason: outcome.reason || escalationReason,
|
|
273
|
+
intentId,
|
|
274
|
+
tokenIssued: Boolean(outcome.token)
|
|
275
|
+
};
|
|
276
|
+
if (outcome.status === "ALLOW") {
|
|
277
|
+
safe(() => store?.delete(key));
|
|
278
|
+
return { permissionDecision: "allow", record };
|
|
279
|
+
}
|
|
280
|
+
if (outcome.status === "PENDING") {
|
|
281
|
+
safe(() => store?.set(key, intentId, outcome.expiresAt));
|
|
282
|
+
const message = `Intended: awaiting human approval (intent ${intentId}). Ask an approver to approve it in the Intended console, then retry the same tool call; it will be allowed then.` + (outcome.timedOut && /could not be reached/.test(outcome.reason) ? ` (${outcome.reason})` : "");
|
|
283
|
+
return { permissionDecision: onPending(env), reason: message, record };
|
|
284
|
+
}
|
|
285
|
+
safe(() => store?.delete(key));
|
|
286
|
+
if (outcome.status === "EXPIRED") {
|
|
287
|
+
return {
|
|
288
|
+
permissionDecision: "deny",
|
|
289
|
+
reason: `Intended: denied \u2014 no approver decided before the approval request expired (intent ${intentId}).`,
|
|
290
|
+
record
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
if (outcome.status === "ERROR") {
|
|
294
|
+
return { permissionDecision: "deny", reason: `Intended: could not get the approval decision \u2014 ${outcome.reason}`, record };
|
|
295
|
+
}
|
|
296
|
+
return { permissionDecision: "deny", reason: `Intended: denied \u2014 ${outcome.reason}`, record };
|
|
297
|
+
}
|
|
298
|
+
function hookOutput(decision) {
|
|
299
|
+
if (decision.permissionDecision === "allow") {
|
|
300
|
+
return decision.warning ? { systemMessage: decision.warning } : null;
|
|
301
|
+
}
|
|
302
|
+
return {
|
|
303
|
+
...decision.warning ? { systemMessage: decision.warning } : {},
|
|
304
|
+
hookSpecificOutput: {
|
|
305
|
+
hookEventName: "PreToolUse",
|
|
306
|
+
permissionDecision: decision.permissionDecision,
|
|
307
|
+
permissionDecisionReason: decision.reason
|
|
308
|
+
}
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
function safe(fn) {
|
|
312
|
+
try {
|
|
313
|
+
return fn();
|
|
314
|
+
} catch {
|
|
315
|
+
return void 0;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
var DEFAULT_TTL_MS = 24 * 60 * 60 * 1e3;
|
|
319
|
+
var FilePendingStore = class {
|
|
320
|
+
constructor(path, maxEntries = 200, now = Date.now) {
|
|
321
|
+
this.path = path;
|
|
322
|
+
this.maxEntries = maxEntries;
|
|
323
|
+
this.now = now;
|
|
324
|
+
}
|
|
325
|
+
path;
|
|
326
|
+
maxEntries;
|
|
327
|
+
now;
|
|
328
|
+
get(key) {
|
|
329
|
+
const entries = this.load();
|
|
330
|
+
const e = entries[key];
|
|
331
|
+
if (!e) return void 0;
|
|
332
|
+
if (e.expiresAt <= this.now()) {
|
|
333
|
+
delete entries[key];
|
|
334
|
+
this.save(entries);
|
|
335
|
+
return void 0;
|
|
336
|
+
}
|
|
337
|
+
return e.intentId;
|
|
338
|
+
}
|
|
339
|
+
set(key, intentId, expiresAt) {
|
|
340
|
+
const entries = this.load();
|
|
341
|
+
const parsed = expiresAt ? Date.parse(expiresAt) : NaN;
|
|
342
|
+
entries[key] = {
|
|
343
|
+
intentId,
|
|
344
|
+
expiresAt: Number.isFinite(parsed) ? parsed : this.now() + DEFAULT_TTL_MS,
|
|
345
|
+
savedAt: this.now()
|
|
346
|
+
};
|
|
347
|
+
const keys = Object.keys(entries).sort((a, b) => entries[a].savedAt - entries[b].savedAt);
|
|
348
|
+
for (const k of keys.slice(0, Math.max(0, keys.length - this.maxEntries))) delete entries[k];
|
|
349
|
+
this.save(entries);
|
|
350
|
+
}
|
|
351
|
+
delete(key) {
|
|
352
|
+
const entries = this.load();
|
|
353
|
+
if (!(key in entries)) return;
|
|
354
|
+
delete entries[key];
|
|
355
|
+
this.save(entries);
|
|
356
|
+
}
|
|
357
|
+
/** Read the file and drop expired entries. */
|
|
358
|
+
load() {
|
|
359
|
+
let raw;
|
|
360
|
+
try {
|
|
361
|
+
raw = JSON.parse(fs.readFileSync(this.path, "utf8"));
|
|
362
|
+
} catch {
|
|
363
|
+
return {};
|
|
364
|
+
}
|
|
365
|
+
const out = {};
|
|
366
|
+
if (!raw || typeof raw !== "object") return out;
|
|
367
|
+
const t = this.now();
|
|
368
|
+
for (const [k, v] of Object.entries(raw)) {
|
|
369
|
+
const e = v;
|
|
370
|
+
if (e && typeof e.intentId === "string" && typeof e.expiresAt === "number" && typeof e.savedAt === "number" && e.expiresAt > t) {
|
|
371
|
+
out[k] = { intentId: e.intentId, expiresAt: e.expiresAt, savedAt: e.savedAt };
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
return out;
|
|
375
|
+
}
|
|
376
|
+
save(entries) {
|
|
377
|
+
fs.mkdirSync(path.dirname(this.path), { recursive: true });
|
|
378
|
+
const tmp = `${this.path}.${process.pid}.tmp`;
|
|
379
|
+
fs.writeFileSync(tmp, JSON.stringify(entries, null, 2), { mode: 384 });
|
|
380
|
+
fs.renameSync(tmp, this.path);
|
|
381
|
+
}
|
|
382
|
+
};
|
|
62
383
|
|
|
63
|
-
// src/
|
|
64
|
-
|
|
65
|
-
|
|
384
|
+
// src/run.ts
|
|
385
|
+
var UNREADABLE_INPUT_REASON = "Intended: could not read the tool call from Claude Code, so it is not authorized (fail-closed).";
|
|
386
|
+
var HOOK_ERROR_REASON = "Intended: the hook failed before reaching a decision, so the tool call is not authorized (fail-closed).";
|
|
387
|
+
function failClosedOutput(reason = HOOK_ERROR_REASON) {
|
|
388
|
+
return JSON.stringify(hookOutput({ permissionDecision: "deny", reason }));
|
|
389
|
+
}
|
|
390
|
+
function parseHookEvent(raw) {
|
|
391
|
+
try {
|
|
392
|
+
const value = JSON.parse(raw);
|
|
393
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return null;
|
|
394
|
+
return value;
|
|
395
|
+
} catch {
|
|
396
|
+
return null;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
async function runHook(io) {
|
|
400
|
+
let decision;
|
|
66
401
|
try {
|
|
67
|
-
event =
|
|
402
|
+
const event = parseHookEvent(io.readInput());
|
|
403
|
+
if (!event) {
|
|
404
|
+
io.write(failClosedOutput(UNREADABLE_INPUT_REASON));
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
const pendingStore = new FilePendingStore(path.join(io.stateDir, "pending.json"));
|
|
408
|
+
decision = await (io.evaluate ?? evaluateHookDecision)({ event, env: io.env, pendingStore });
|
|
68
409
|
} catch {
|
|
69
|
-
|
|
410
|
+
io.write(failClosedOutput());
|
|
70
411
|
return;
|
|
71
412
|
}
|
|
72
|
-
|
|
413
|
+
if (decision.warning) {
|
|
414
|
+
try {
|
|
415
|
+
io.writeError(`${decision.warning}
|
|
416
|
+
`);
|
|
417
|
+
} catch {
|
|
418
|
+
}
|
|
419
|
+
}
|
|
73
420
|
if (decision.record) {
|
|
74
421
|
try {
|
|
75
|
-
|
|
76
|
-
fs.
|
|
77
|
-
|
|
422
|
+
fs.mkdirSync(io.stateDir, { recursive: true });
|
|
423
|
+
fs.writeFileSync(
|
|
424
|
+
path.join(io.stateDir, "last-decision.json"),
|
|
425
|
+
JSON.stringify({ ...decision.record, at: (/* @__PURE__ */ new Date()).toISOString() }, null, 2)
|
|
426
|
+
);
|
|
78
427
|
} catch {
|
|
79
428
|
}
|
|
80
429
|
}
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
JSON.stringify({
|
|
84
|
-
hookSpecificOutput: {
|
|
85
|
-
hookEventName: "PreToolUse",
|
|
86
|
-
permissionDecision: decision.permissionDecision,
|
|
87
|
-
permissionDecisionReason: decision.reason
|
|
88
|
-
}
|
|
89
|
-
})
|
|
90
|
-
);
|
|
91
|
-
process.exit(0);
|
|
430
|
+
const output = hookOutput(decision);
|
|
431
|
+
if (output) io.write(JSON.stringify(output));
|
|
92
432
|
}
|
|
93
|
-
|
|
433
|
+
|
|
434
|
+
// src/bin.ts
|
|
435
|
+
runHook({
|
|
436
|
+
readInput: () => fs.readFileSync(0, "utf8"),
|
|
437
|
+
env: process.env,
|
|
438
|
+
write: (text) => process.stdout.write(text),
|
|
439
|
+
writeError: (text) => process.stderr.write(text),
|
|
440
|
+
stateDir: path.join(os.homedir(), ".intended")
|
|
441
|
+
}).catch(() => {
|
|
442
|
+
try {
|
|
443
|
+
process.stdout.write(failClosedOutput());
|
|
444
|
+
} catch {
|
|
445
|
+
}
|
|
446
|
+
}).finally(() => process.exit(0));
|