@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/dist/index.mjs CHANGED
@@ -1,5 +1,145 @@
1
+ import { createHash } from 'crypto';
2
+ import { readFileSync, mkdirSync, writeFileSync, renameSync } from 'fs';
3
+ import { dirname, join } 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,15 +150,79 @@ 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
+ }
162
+ var UNCONFIGURED_OPT_OUT = "allow";
163
+ function unconfiguredOptOut(env) {
164
+ return env.INTENDED_HOOK_UNCONFIGURED?.trim().toLowerCase() === UNCONFIGURED_OPT_OUT;
165
+ }
166
+ function missingConfig(env) {
167
+ const missing = [];
168
+ if (!env.INTENDED_API_KEY?.trim()) missing.push("INTENDED_API_KEY");
169
+ if (!env.INTENDED_TENANT_ID?.trim()) missing.push("INTENDED_TENANT_ID");
170
+ return missing;
171
+ }
172
+ function unconfiguredDenyReason(missing, toolName) {
173
+ 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`;
174
+ }
175
+ function unconfiguredAllowWarning(missing, toolName) {
176
+ 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.`;
177
+ }
13
178
  async function evaluateHookDecision(input) {
14
- const { event, env } = input;
179
+ const { event, env, pendingStore } = input;
180
+ 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))) {
181
+ const reason2 = "Intended: the tool call from Claude Code is not in the expected format, so it is not authorized (fail-closed).";
182
+ return {
183
+ permissionDecision: "deny",
184
+ reason: reason2,
185
+ record: { tool: "unknown", verdict: "UNREADABLE", reason: reason2, intentId: null, tokenIssued: false }
186
+ };
187
+ }
15
188
  const fetchImpl = input.fetchImpl ?? globalThis.fetch;
16
189
  const toolName = event.tool_name ?? "unknown";
17
190
  const args = { ...event.tool_input ?? {} };
18
- const apiKey = env.INTENDED_API_KEY;
19
- const tenantId = env.INTENDED_TENANT_ID;
20
191
  const apiUrl = (env.INTENDED_API_URL ?? "https://api.intended.so").replace(/\/$/, "");
21
- if (!apiKey || !tenantId) return { permissionDecision: "allow" };
192
+ const missing = missingConfig(env);
193
+ if (missing.length > 0) {
194
+ if (unconfiguredOptOut(env)) {
195
+ const warning = unconfiguredAllowWarning(missing, toolName);
196
+ return {
197
+ permissionDecision: "allow",
198
+ warning,
199
+ record: { tool: toolName, verdict: "UNGOVERNED", reason: warning, intentId: null, tokenIssued: false }
200
+ };
201
+ }
202
+ const reason2 = unconfiguredDenyReason(missing, toolName);
203
+ return {
204
+ permissionDecision: "deny",
205
+ reason: reason2,
206
+ record: { tool: toolName, verdict: "UNCONFIGURED", reason: reason2, intentId: null, tokenIssued: false }
207
+ };
208
+ }
209
+ const apiKey = env.INTENDED_API_KEY.trim();
210
+ const tenantId = env.INTENDED_TENANT_ID.trim();
211
+ const key = toolCallKey(toolName, args);
212
+ const wait = (intentId) => waitForDecision(intentId, {
213
+ apiUrl,
214
+ apiKey,
215
+ tenantId,
216
+ fetchImpl,
217
+ timeoutMs: escalationWaitMs(env),
218
+ now: input.now,
219
+ sleep: input.sleep
220
+ });
221
+ const pendingIntentId = safe(() => pendingStore?.get(key));
222
+ if (pendingIntentId) {
223
+ const outcome = await wait(pendingIntentId);
224
+ return settle(outcome, pendingIntentId, toolName, key, env, pendingStore);
225
+ }
22
226
  let res;
23
227
  try {
24
228
  res = await fetchImpl(`${apiUrl}/v1/agent-intent`, {
@@ -49,8 +253,177 @@ async function evaluateHookDecision(input) {
49
253
  tokenIssued: Boolean(data.authorityDecisionToken)
50
254
  };
51
255
  if (verdict === "APPROVED") return { permissionDecision: "allow", record };
52
- if (verdict === "ESCALATED") return { permissionDecision: "ask", reason: `Intended: requires human approval \u2014 ${reason}`, record };
256
+ if (verdict === "ESCALATED") {
257
+ if (!data.intentId) {
258
+ return { permissionDecision: "deny", reason: "Intended: escalated without an intent id to wait on \u2014 fail-closed.", record };
259
+ }
260
+ const outcome = await wait(data.intentId);
261
+ return settle(outcome, data.intentId, toolName, key, env, pendingStore, reason);
262
+ }
53
263
  return { permissionDecision: "deny", reason: `Intended: denied \u2014 ${reason || "fail-closed (unrecognized decision)"}`, record };
54
264
  }
265
+ function settle(outcome, intentId, toolName, key, env, store, escalationReason = "") {
266
+ const record = {
267
+ tool: toolName,
268
+ verdict: outcome.status === "ALLOW" ? "APPROVED_AFTER_ESCALATION" : outcome.status === "PENDING" ? "ESCALATED" : outcome.status,
269
+ reason: outcome.reason || escalationReason,
270
+ intentId,
271
+ tokenIssued: Boolean(outcome.token)
272
+ };
273
+ if (outcome.status === "ALLOW") {
274
+ safe(() => store?.delete(key));
275
+ return { permissionDecision: "allow", record };
276
+ }
277
+ if (outcome.status === "PENDING") {
278
+ safe(() => store?.set(key, intentId, outcome.expiresAt));
279
+ 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})` : "");
280
+ return { permissionDecision: onPending(env), reason: message, record };
281
+ }
282
+ safe(() => store?.delete(key));
283
+ if (outcome.status === "EXPIRED") {
284
+ return {
285
+ permissionDecision: "deny",
286
+ reason: `Intended: denied \u2014 no approver decided before the approval request expired (intent ${intentId}).`,
287
+ record
288
+ };
289
+ }
290
+ if (outcome.status === "ERROR") {
291
+ return { permissionDecision: "deny", reason: `Intended: could not get the approval decision \u2014 ${outcome.reason}`, record };
292
+ }
293
+ return { permissionDecision: "deny", reason: `Intended: denied \u2014 ${outcome.reason}`, record };
294
+ }
295
+ function hookOutput(decision) {
296
+ if (decision.permissionDecision === "allow") {
297
+ return decision.warning ? { systemMessage: decision.warning } : null;
298
+ }
299
+ return {
300
+ ...decision.warning ? { systemMessage: decision.warning } : {},
301
+ hookSpecificOutput: {
302
+ hookEventName: "PreToolUse",
303
+ permissionDecision: decision.permissionDecision,
304
+ permissionDecisionReason: decision.reason
305
+ }
306
+ };
307
+ }
308
+ function safe(fn) {
309
+ try {
310
+ return fn();
311
+ } catch {
312
+ return void 0;
313
+ }
314
+ }
315
+ var DEFAULT_TTL_MS = 24 * 60 * 60 * 1e3;
316
+ var FilePendingStore = class {
317
+ constructor(path, maxEntries = 200, now = Date.now) {
318
+ this.path = path;
319
+ this.maxEntries = maxEntries;
320
+ this.now = now;
321
+ }
322
+ path;
323
+ maxEntries;
324
+ now;
325
+ get(key) {
326
+ const entries = this.load();
327
+ const e = entries[key];
328
+ if (!e) return void 0;
329
+ if (e.expiresAt <= this.now()) {
330
+ delete entries[key];
331
+ this.save(entries);
332
+ return void 0;
333
+ }
334
+ return e.intentId;
335
+ }
336
+ set(key, intentId, expiresAt) {
337
+ const entries = this.load();
338
+ const parsed = expiresAt ? Date.parse(expiresAt) : NaN;
339
+ entries[key] = {
340
+ intentId,
341
+ expiresAt: Number.isFinite(parsed) ? parsed : this.now() + DEFAULT_TTL_MS,
342
+ savedAt: this.now()
343
+ };
344
+ const keys = Object.keys(entries).sort((a, b) => entries[a].savedAt - entries[b].savedAt);
345
+ for (const k of keys.slice(0, Math.max(0, keys.length - this.maxEntries))) delete entries[k];
346
+ this.save(entries);
347
+ }
348
+ delete(key) {
349
+ const entries = this.load();
350
+ if (!(key in entries)) return;
351
+ delete entries[key];
352
+ this.save(entries);
353
+ }
354
+ /** Read the file and drop expired entries. */
355
+ load() {
356
+ let raw;
357
+ try {
358
+ raw = JSON.parse(readFileSync(this.path, "utf8"));
359
+ } catch {
360
+ return {};
361
+ }
362
+ const out = {};
363
+ if (!raw || typeof raw !== "object") return out;
364
+ const t = this.now();
365
+ for (const [k, v] of Object.entries(raw)) {
366
+ const e = v;
367
+ if (e && typeof e.intentId === "string" && typeof e.expiresAt === "number" && typeof e.savedAt === "number" && e.expiresAt > t) {
368
+ out[k] = { intentId: e.intentId, expiresAt: e.expiresAt, savedAt: e.savedAt };
369
+ }
370
+ }
371
+ return out;
372
+ }
373
+ save(entries) {
374
+ mkdirSync(dirname(this.path), { recursive: true });
375
+ const tmp = `${this.path}.${process.pid}.tmp`;
376
+ writeFileSync(tmp, JSON.stringify(entries, null, 2), { mode: 384 });
377
+ renameSync(tmp, this.path);
378
+ }
379
+ };
380
+ var UNREADABLE_INPUT_REASON = "Intended: could not read the tool call from Claude Code, so it is not authorized (fail-closed).";
381
+ var HOOK_ERROR_REASON = "Intended: the hook failed before reaching a decision, so the tool call is not authorized (fail-closed).";
382
+ function failClosedOutput(reason = HOOK_ERROR_REASON) {
383
+ return JSON.stringify(hookOutput({ permissionDecision: "deny", reason }));
384
+ }
385
+ function parseHookEvent(raw) {
386
+ try {
387
+ const value = JSON.parse(raw);
388
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return null;
389
+ return value;
390
+ } catch {
391
+ return null;
392
+ }
393
+ }
394
+ async function runHook(io) {
395
+ let decision;
396
+ try {
397
+ const event = parseHookEvent(io.readInput());
398
+ if (!event) {
399
+ io.write(failClosedOutput(UNREADABLE_INPUT_REASON));
400
+ return;
401
+ }
402
+ const pendingStore = new FilePendingStore(join(io.stateDir, "pending.json"));
403
+ decision = await (io.evaluate ?? evaluateHookDecision)({ event, env: io.env, pendingStore });
404
+ } catch {
405
+ io.write(failClosedOutput());
406
+ return;
407
+ }
408
+ if (decision.warning) {
409
+ try {
410
+ io.writeError(`${decision.warning}
411
+ `);
412
+ } catch {
413
+ }
414
+ }
415
+ if (decision.record) {
416
+ try {
417
+ mkdirSync(io.stateDir, { recursive: true });
418
+ writeFileSync(
419
+ join(io.stateDir, "last-decision.json"),
420
+ JSON.stringify({ ...decision.record, at: (/* @__PURE__ */ new Date()).toISOString() }, null, 2)
421
+ );
422
+ } catch {
423
+ }
424
+ }
425
+ const output = hookOutput(decision);
426
+ if (output) io.write(JSON.stringify(output));
427
+ }
55
428
 
56
- export { evaluateHookDecision };
429
+ export { DEFAULT_ESCALATION_WAIT_SECONDS, FilePendingStore, UNCONFIGURED_OPT_OUT, describeToolCall, escalationWaitMs, evaluateHookDecision, failClosedOutput, hookOutput, missingConfig, parseHookEvent, runHook, unconfiguredOptOut };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@intended-inc/claude-code-hook",
3
- "version": "0.1.1",
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.",
3
+ "version": "0.3.0",
4
+ "description": "Claude Code PreToolUse hook — govern every tool call through Intended's authority layer. Fail-closed when unconfigured (opt out with INTENDED_HOOK_UNCONFIGURED=allow) and on DENY / unreachable / non-2xx. npx-invokable from .claude/settings.json.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
7
7
  "type": "git",