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