@intended-inc/claude-code-hook 0.1.1 → 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/README.md +33 -2
- package/dist/bin.js +272 -3
- package/dist/bin.mjs +274 -5
- package/dist/index.d.mts +45 -13
- package/dist/index.d.ts +45 -13
- package/dist/index.js +278 -2
- package/dist/index.mjs +275 -3
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,145 @@
|
|
|
1
|
+
import { createHash } from 'crypto';
|
|
2
|
+
import { readFileSync, mkdirSync, writeFileSync, renameSync } from 'fs';
|
|
3
|
+
import { dirname } from 'path';
|
|
4
|
+
|
|
5
|
+
// src/wait.ts
|
|
6
|
+
var FINAL = /* @__PURE__ */ new Set(["ALLOW", "DENY", "EXPIRED"]);
|
|
7
|
+
var MAX_POLL_SECONDS = 50;
|
|
8
|
+
var MAX_BACKOFF_MS = 1e4;
|
|
9
|
+
var MIN_REPOLL_MS = 1e3;
|
|
10
|
+
var defaultSleep = (ms) => new Promise((r) => setTimeout(r, Math.max(0, ms)));
|
|
11
|
+
function str(v) {
|
|
12
|
+
return typeof v === "string" && v.length > 0 ? v : null;
|
|
13
|
+
}
|
|
14
|
+
function base(intentId, status, reason) {
|
|
15
|
+
return {
|
|
16
|
+
intentId,
|
|
17
|
+
status,
|
|
18
|
+
reason,
|
|
19
|
+
token: null,
|
|
20
|
+
decidedBy: null,
|
|
21
|
+
decidedAt: null,
|
|
22
|
+
escalationId: null,
|
|
23
|
+
expiresAt: null,
|
|
24
|
+
receiptUrl: null
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
function parseBody(intentId, body, apiUrl) {
|
|
28
|
+
const status = body.status;
|
|
29
|
+
if (status !== "ALLOW" && status !== "DENY" && status !== "PENDING" && status !== "EXPIRED") return null;
|
|
30
|
+
const receipt = str(body.receiptUrl);
|
|
31
|
+
return {
|
|
32
|
+
intentId: str(body.intentId) ?? intentId,
|
|
33
|
+
status,
|
|
34
|
+
reason: str(body.reason) ?? `Decision: ${status}`,
|
|
35
|
+
token: status === "ALLOW" ? str(body.token) : null,
|
|
36
|
+
decidedBy: body.decidedBy && typeof body.decidedBy === "object" ? body.decidedBy : null,
|
|
37
|
+
decidedAt: str(body.decidedAt),
|
|
38
|
+
escalationId: str(body.escalationId),
|
|
39
|
+
expiresAt: str(body.expiresAt),
|
|
40
|
+
receiptUrl: receipt ? /^https?:\/\//.test(receipt) ? receipt : `${apiUrl}${receipt.startsWith("/") ? "" : "/"}${receipt}` : null
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
function retryAfterHeaderMs(res) {
|
|
44
|
+
const raw = res.headers?.get?.("retry-after");
|
|
45
|
+
const n = raw == null ? NaN : Number(raw);
|
|
46
|
+
return Number.isFinite(n) && n > 0 ? n * 1e3 : 0;
|
|
47
|
+
}
|
|
48
|
+
async function waitForDecision(intentId, opts) {
|
|
49
|
+
const apiUrl = (opts.apiUrl ?? "https://api.intended.so").replace(/\/$/, "");
|
|
50
|
+
const fetchImpl = opts.fetchImpl ?? fetch;
|
|
51
|
+
const now = opts.now ?? Date.now;
|
|
52
|
+
const sleep = opts.sleep ?? defaultSleep;
|
|
53
|
+
const deadline = now() + Math.max(0, opts.timeoutMs);
|
|
54
|
+
const headers = {
|
|
55
|
+
authorization: `Bearer ${opts.apiKey}`,
|
|
56
|
+
"x-tenant-id": opts.tenantId
|
|
57
|
+
};
|
|
58
|
+
let backoffMs = 1e3;
|
|
59
|
+
for (; ; ) {
|
|
60
|
+
const remaining = deadline - now();
|
|
61
|
+
const timeoutSec = remaining <= 0 ? 0 : Math.min(MAX_POLL_SECONDS, Math.ceil(remaining / 1e3));
|
|
62
|
+
const url = `${apiUrl}/v1/decisions/${encodeURIComponent(intentId)}/wait?timeout=${timeoutSec}&tenantId=${encodeURIComponent(opts.tenantId)}`;
|
|
63
|
+
const startedAt = now();
|
|
64
|
+
let res = null;
|
|
65
|
+
try {
|
|
66
|
+
res = await fetchImpl(url, {
|
|
67
|
+
headers,
|
|
68
|
+
// The server holds at most timeoutSec; give the network some slack beyond that.
|
|
69
|
+
signal: AbortSignal.timeout(timeoutSec * 1e3 + 15e3)
|
|
70
|
+
});
|
|
71
|
+
} catch {
|
|
72
|
+
res = null;
|
|
73
|
+
}
|
|
74
|
+
let transientWaitMs = 0;
|
|
75
|
+
if (res) {
|
|
76
|
+
if (res.status === 401) {
|
|
77
|
+
return { ...base(intentId, "ERROR", "The Intended API rejected the API key (401). The action is not approved."), error: "unauthorized" };
|
|
78
|
+
}
|
|
79
|
+
if (res.status === 403) {
|
|
80
|
+
return {
|
|
81
|
+
...base(
|
|
82
|
+
intentId,
|
|
83
|
+
"ERROR",
|
|
84
|
+
"This API key cannot read decisions: it needs the intent:read scope. The action is not approved."
|
|
85
|
+
),
|
|
86
|
+
error: "forbidden"
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
if (res.status === 404) {
|
|
90
|
+
return { ...base(intentId, "ERROR", `Intended has no decision for intent ${intentId}. The action is not approved.`), error: "not_found" };
|
|
91
|
+
}
|
|
92
|
+
if (res.status === 429 || res.status >= 500) {
|
|
93
|
+
transientWaitMs = Math.max(backoffMs, retryAfterHeaderMs(res));
|
|
94
|
+
} else {
|
|
95
|
+
const body = await res.json().catch(() => null);
|
|
96
|
+
const parsed = res.status === 200 && body ? parseBody(intentId, body, apiUrl) : null;
|
|
97
|
+
if (!parsed) {
|
|
98
|
+
return {
|
|
99
|
+
...base(intentId, "ERROR", `Unrecognised decision response (HTTP ${res.status}). The action is not approved.`),
|
|
100
|
+
error: "bad_response"
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
if (FINAL.has(parsed.status)) return parsed;
|
|
104
|
+
if (now() >= deadline) return { ...parsed, timedOut: true };
|
|
105
|
+
const retryAfterMs = typeof body?.retryAfterMs === "number" && body.retryAfterMs > 0 ? body.retryAfterMs : 0;
|
|
106
|
+
const answeredFast = now() - startedAt < Math.min(timeoutSec * 1e3, MIN_REPOLL_MS) / 2;
|
|
107
|
+
const pause = retryAfterMs > 0 ? retryAfterMs : answeredFast ? MIN_REPOLL_MS : 0;
|
|
108
|
+
if (pause > 0) await sleep(Math.min(pause, Math.max(0, deadline - now())));
|
|
109
|
+
backoffMs = 1e3;
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
} else {
|
|
113
|
+
transientWaitMs = backoffMs;
|
|
114
|
+
}
|
|
115
|
+
if (now() >= deadline) {
|
|
116
|
+
return {
|
|
117
|
+
...base(
|
|
118
|
+
intentId,
|
|
119
|
+
"PENDING",
|
|
120
|
+
"The Intended decision service could not be reached before the wait ended. The action is still not approved."
|
|
121
|
+
),
|
|
122
|
+
timedOut: true
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
await sleep(Math.min(transientWaitMs, Math.max(0, deadline - now())));
|
|
126
|
+
backoffMs = Math.min(backoffMs * 2, MAX_BACKOFF_MS);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
function canonicalJson(value) {
|
|
130
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
|
|
131
|
+
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
|
|
132
|
+
const obj = value;
|
|
133
|
+
return `{${Object.keys(obj).sort().filter((k) => obj[k] !== void 0).map((k) => `${JSON.stringify(k)}:${canonicalJson(obj[k])}`).join(",")}}`;
|
|
134
|
+
}
|
|
135
|
+
function toolCallKey(toolName, args) {
|
|
136
|
+
return createHash("sha256").update(`${toolName}
|
|
137
|
+
${canonicalJson(args ?? {})}`).digest("hex");
|
|
138
|
+
}
|
|
139
|
+
|
|
1
140
|
// src/evaluate.ts
|
|
2
141
|
var AUTHORITY_STATUSES = /* @__PURE__ */ new Set([200, 202, 403]);
|
|
142
|
+
var DEFAULT_ESCALATION_WAIT_SECONDS = 45;
|
|
3
143
|
var MAX_DESCRIBED_KEYS = 20;
|
|
4
144
|
var SAFE_KEY = /^[A-Za-z_][A-Za-z0-9_.-]{0,63}$/;
|
|
5
145
|
function describeToolCall(name, args) {
|
|
@@ -10,8 +150,17 @@ function describeToolCall(name, args) {
|
|
|
10
150
|
const list = [...named, ...unnamed > 0 ? [`+${unnamed} more`] : []].join(", ");
|
|
11
151
|
return `Call tool "${name}" with args: ${list}`;
|
|
12
152
|
}
|
|
153
|
+
function escalationWaitMs(env) {
|
|
154
|
+
const raw = env.INTENDED_HOOK_ESCALATION_WAIT_SECONDS;
|
|
155
|
+
if (raw === void 0 || raw.trim() === "") return DEFAULT_ESCALATION_WAIT_SECONDS * 1e3;
|
|
156
|
+
const n = Number(raw);
|
|
157
|
+
return Number.isFinite(n) && n >= 0 ? Math.round(n * 1e3) : DEFAULT_ESCALATION_WAIT_SECONDS * 1e3;
|
|
158
|
+
}
|
|
159
|
+
function onPending(env) {
|
|
160
|
+
return env.INTENDED_HOOK_ON_PENDING?.trim().toLowerCase() === "ask" ? "ask" : "deny";
|
|
161
|
+
}
|
|
13
162
|
async function evaluateHookDecision(input) {
|
|
14
|
-
const { event, env } = input;
|
|
163
|
+
const { event, env, pendingStore } = input;
|
|
15
164
|
const fetchImpl = input.fetchImpl ?? globalThis.fetch;
|
|
16
165
|
const toolName = event.tool_name ?? "unknown";
|
|
17
166
|
const args = { ...event.tool_input ?? {} };
|
|
@@ -19,6 +168,21 @@ async function evaluateHookDecision(input) {
|
|
|
19
168
|
const tenantId = env.INTENDED_TENANT_ID;
|
|
20
169
|
const apiUrl = (env.INTENDED_API_URL ?? "https://api.intended.so").replace(/\/$/, "");
|
|
21
170
|
if (!apiKey || !tenantId) return { permissionDecision: "allow" };
|
|
171
|
+
const key = toolCallKey(toolName, args);
|
|
172
|
+
const wait = (intentId) => waitForDecision(intentId, {
|
|
173
|
+
apiUrl,
|
|
174
|
+
apiKey,
|
|
175
|
+
tenantId,
|
|
176
|
+
fetchImpl,
|
|
177
|
+
timeoutMs: escalationWaitMs(env),
|
|
178
|
+
now: input.now,
|
|
179
|
+
sleep: input.sleep
|
|
180
|
+
});
|
|
181
|
+
const pendingIntentId = safe(() => pendingStore?.get(key));
|
|
182
|
+
if (pendingIntentId) {
|
|
183
|
+
const outcome = await wait(pendingIntentId);
|
|
184
|
+
return settle(outcome, pendingIntentId, toolName, key, env, pendingStore);
|
|
185
|
+
}
|
|
22
186
|
let res;
|
|
23
187
|
try {
|
|
24
188
|
res = await fetchImpl(`${apiUrl}/v1/agent-intent`, {
|
|
@@ -49,8 +213,116 @@ async function evaluateHookDecision(input) {
|
|
|
49
213
|
tokenIssued: Boolean(data.authorityDecisionToken)
|
|
50
214
|
};
|
|
51
215
|
if (verdict === "APPROVED") return { permissionDecision: "allow", record };
|
|
52
|
-
if (verdict === "ESCALATED")
|
|
216
|
+
if (verdict === "ESCALATED") {
|
|
217
|
+
if (!data.intentId) {
|
|
218
|
+
return { permissionDecision: "deny", reason: "Intended: escalated without an intent id to wait on \u2014 fail-closed.", record };
|
|
219
|
+
}
|
|
220
|
+
const outcome = await wait(data.intentId);
|
|
221
|
+
return settle(outcome, data.intentId, toolName, key, env, pendingStore, reason);
|
|
222
|
+
}
|
|
53
223
|
return { permissionDecision: "deny", reason: `Intended: denied \u2014 ${reason || "fail-closed (unrecognized decision)"}`, record };
|
|
54
224
|
}
|
|
225
|
+
function settle(outcome, intentId, toolName, key, env, store, escalationReason = "") {
|
|
226
|
+
const record = {
|
|
227
|
+
tool: toolName,
|
|
228
|
+
verdict: outcome.status === "ALLOW" ? "APPROVED_AFTER_ESCALATION" : outcome.status === "PENDING" ? "ESCALATED" : outcome.status,
|
|
229
|
+
reason: outcome.reason || escalationReason,
|
|
230
|
+
intentId,
|
|
231
|
+
tokenIssued: Boolean(outcome.token)
|
|
232
|
+
};
|
|
233
|
+
if (outcome.status === "ALLOW") {
|
|
234
|
+
safe(() => store?.delete(key));
|
|
235
|
+
return { permissionDecision: "allow", record };
|
|
236
|
+
}
|
|
237
|
+
if (outcome.status === "PENDING") {
|
|
238
|
+
safe(() => store?.set(key, intentId, outcome.expiresAt));
|
|
239
|
+
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})` : "");
|
|
240
|
+
return { permissionDecision: onPending(env), reason: message, record };
|
|
241
|
+
}
|
|
242
|
+
safe(() => store?.delete(key));
|
|
243
|
+
if (outcome.status === "EXPIRED") {
|
|
244
|
+
return {
|
|
245
|
+
permissionDecision: "deny",
|
|
246
|
+
reason: `Intended: denied \u2014 no approver decided before the approval request expired (intent ${intentId}).`,
|
|
247
|
+
record
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
if (outcome.status === "ERROR") {
|
|
251
|
+
return { permissionDecision: "deny", reason: `Intended: could not get the approval decision \u2014 ${outcome.reason}`, record };
|
|
252
|
+
}
|
|
253
|
+
return { permissionDecision: "deny", reason: `Intended: denied \u2014 ${outcome.reason}`, record };
|
|
254
|
+
}
|
|
255
|
+
function safe(fn) {
|
|
256
|
+
try {
|
|
257
|
+
return fn();
|
|
258
|
+
} catch {
|
|
259
|
+
return void 0;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
var DEFAULT_TTL_MS = 24 * 60 * 60 * 1e3;
|
|
263
|
+
var FilePendingStore = class {
|
|
264
|
+
constructor(path, maxEntries = 200, now = Date.now) {
|
|
265
|
+
this.path = path;
|
|
266
|
+
this.maxEntries = maxEntries;
|
|
267
|
+
this.now = now;
|
|
268
|
+
}
|
|
269
|
+
path;
|
|
270
|
+
maxEntries;
|
|
271
|
+
now;
|
|
272
|
+
get(key) {
|
|
273
|
+
const entries = this.load();
|
|
274
|
+
const e = entries[key];
|
|
275
|
+
if (!e) return void 0;
|
|
276
|
+
if (e.expiresAt <= this.now()) {
|
|
277
|
+
delete entries[key];
|
|
278
|
+
this.save(entries);
|
|
279
|
+
return void 0;
|
|
280
|
+
}
|
|
281
|
+
return e.intentId;
|
|
282
|
+
}
|
|
283
|
+
set(key, intentId, expiresAt) {
|
|
284
|
+
const entries = this.load();
|
|
285
|
+
const parsed = expiresAt ? Date.parse(expiresAt) : NaN;
|
|
286
|
+
entries[key] = {
|
|
287
|
+
intentId,
|
|
288
|
+
expiresAt: Number.isFinite(parsed) ? parsed : this.now() + DEFAULT_TTL_MS,
|
|
289
|
+
savedAt: this.now()
|
|
290
|
+
};
|
|
291
|
+
const keys = Object.keys(entries).sort((a, b) => entries[a].savedAt - entries[b].savedAt);
|
|
292
|
+
for (const k of keys.slice(0, Math.max(0, keys.length - this.maxEntries))) delete entries[k];
|
|
293
|
+
this.save(entries);
|
|
294
|
+
}
|
|
295
|
+
delete(key) {
|
|
296
|
+
const entries = this.load();
|
|
297
|
+
if (!(key in entries)) return;
|
|
298
|
+
delete entries[key];
|
|
299
|
+
this.save(entries);
|
|
300
|
+
}
|
|
301
|
+
/** Read the file and drop expired entries. */
|
|
302
|
+
load() {
|
|
303
|
+
let raw;
|
|
304
|
+
try {
|
|
305
|
+
raw = JSON.parse(readFileSync(this.path, "utf8"));
|
|
306
|
+
} catch {
|
|
307
|
+
return {};
|
|
308
|
+
}
|
|
309
|
+
const out = {};
|
|
310
|
+
if (!raw || typeof raw !== "object") return out;
|
|
311
|
+
const t = this.now();
|
|
312
|
+
for (const [k, v] of Object.entries(raw)) {
|
|
313
|
+
const e = v;
|
|
314
|
+
if (e && typeof e.intentId === "string" && typeof e.expiresAt === "number" && typeof e.savedAt === "number" && e.expiresAt > t) {
|
|
315
|
+
out[k] = { intentId: e.intentId, expiresAt: e.expiresAt, savedAt: e.savedAt };
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
return out;
|
|
319
|
+
}
|
|
320
|
+
save(entries) {
|
|
321
|
+
mkdirSync(dirname(this.path), { recursive: true });
|
|
322
|
+
const tmp = `${this.path}.${process.pid}.tmp`;
|
|
323
|
+
writeFileSync(tmp, JSON.stringify(entries, null, 2), { mode: 384 });
|
|
324
|
+
renameSync(tmp, this.path);
|
|
325
|
+
}
|
|
326
|
+
};
|
|
55
327
|
|
|
56
|
-
export { evaluateHookDecision };
|
|
328
|
+
export { DEFAULT_ESCALATION_WAIT_SECONDS, FilePendingStore, describeToolCall, escalationWaitMs, evaluateHookDecision };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@intended-inc/claude-code-hook",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Claude Code PreToolUse hook — govern every tool call through Intended's authority layer. Fail-open when unconfigured, fail-closed on DENY / unreachable / non-2xx. npx-invokable from .claude/settings.json.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|