@contro1/claude-code 0.1.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Contro1
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,60 @@
1
+ # @contro1/claude-code
2
+
3
+ Route Claude Code `PreToolUse` approvals to CENTCOM.
4
+
5
+ The hook reads Claude tool calls from stdin, creates an approval request in CENTCOM, polls for the operator decision, then returns a Claude-compatible permission decision.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install -g @contro1/claude-code
11
+ ```
12
+
13
+ ## Configuration
14
+
15
+ Set env vars (or use `.centcom.json` in working directory):
16
+
17
+ - `CENTCOM_API_KEY` (required)
18
+ - `CENTCOM_BASE_URL` (default: `https://contro1.com/api/centcom/v1`)
19
+ - `CENTCOM_TOOLS` (default: `Write,Edit,Bash`)
20
+ - `CENTCOM_TIMEOUT` (default: `300000` ms)
21
+ - `CENTCOM_POLL_INTERVAL` (default: `3000` ms)
22
+ - `CENTCOM_PRIORITY` (default: `urgent`)
23
+ - `CENTCOM_SLA_MINUTES` (optional)
24
+ - `CENTCOM_REQUIRED_ROLE` (optional)
25
+ - `CENTCOM_FALLBACK` (`deny` default; supported: `deny`, `ask`, `allow`)
26
+ - `CENTCOM_CALLBACK_URL` (default internal placeholder, can be overridden)
27
+
28
+ ## Claude Code Hook Setup
29
+
30
+ Add this in `.claude/settings.json`:
31
+
32
+ ```json
33
+ {
34
+ "hooks": {
35
+ "PreToolUse": [
36
+ {
37
+ "matcher": "",
38
+ "command": "centcom-claude-code",
39
+ "timeout": 310000
40
+ }
41
+ ]
42
+ }
43
+ }
44
+ ```
45
+
46
+ ## Behavior
47
+
48
+ - Tools outside `CENTCOM_TOOLS` are auto-allowed.
49
+ - Approved response -> `allow`.
50
+ - Rejected response -> `deny`.
51
+ - Timeout -> request cancel attempt + `deny`.
52
+ - API errors -> fallback decision (`CENTCOM_FALLBACK`).
53
+
54
+ ## Development
55
+
56
+ ```bash
57
+ npm install
58
+ npm run build
59
+ npm pack
60
+ ```
@@ -0,0 +1,33 @@
1
+ interface CentcomClientConfig {
2
+ apiKey: string;
3
+ baseUrl: string;
4
+ timeoutMs: number;
5
+ }
6
+ interface CreateRequestParams {
7
+ type: "approval" | "yes_no" | "free_text";
8
+ context: string;
9
+ question: string;
10
+ callback_url: string;
11
+ priority: "normal" | "urgent";
12
+ required_role?: string;
13
+ metadata?: Record<string, unknown>;
14
+ sla_minutes?: number;
15
+ idempotency_key?: string;
16
+ }
17
+ export interface CentcomRequest {
18
+ id: string;
19
+ state: string;
20
+ response?: Record<string, unknown> | null;
21
+ }
22
+ export declare class CentcomClient {
23
+ private readonly apiKey;
24
+ private readonly baseUrl;
25
+ private readonly timeoutMs;
26
+ constructor(config: CentcomClientConfig);
27
+ private request;
28
+ createRequest(params: CreateRequestParams): Promise<CentcomRequest>;
29
+ getRequest(requestId: string): Promise<CentcomRequest>;
30
+ cancelRequest(requestId: string): Promise<void>;
31
+ waitForResponse(requestId: string, intervalMs: number, timeoutMs: number): Promise<CentcomRequest>;
32
+ }
33
+ export {};
@@ -0,0 +1,66 @@
1
+ export class CentcomClient {
2
+ apiKey;
3
+ baseUrl;
4
+ timeoutMs;
5
+ constructor(config) {
6
+ this.apiKey = config.apiKey;
7
+ this.baseUrl = config.baseUrl.replace(/\/$/, "");
8
+ this.timeoutMs = config.timeoutMs;
9
+ }
10
+ async request(method, path, body, extraHeaders) {
11
+ const controller = new AbortController();
12
+ const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
13
+ try {
14
+ const res = await fetch(`${this.baseUrl}${path}`, {
15
+ method,
16
+ headers: {
17
+ Authorization: `Bearer ${this.apiKey}`,
18
+ "Content-Type": "application/json",
19
+ ...(extraHeaders ?? {}),
20
+ },
21
+ body: body ? JSON.stringify(body) : undefined,
22
+ signal: controller.signal,
23
+ });
24
+ const json = (await res.json());
25
+ if (!res.ok) {
26
+ throw new Error(json.message || `HTTP ${res.status}`);
27
+ }
28
+ return json;
29
+ }
30
+ finally {
31
+ clearTimeout(timeout);
32
+ }
33
+ }
34
+ async createRequest(params) {
35
+ const { idempotency_key, ...body } = params;
36
+ const headers = {};
37
+ if (idempotency_key)
38
+ headers["Idempotency-Key"] = idempotency_key;
39
+ return this.request("POST", "/requests", body, headers);
40
+ }
41
+ async getRequest(requestId) {
42
+ return this.request("GET", `/requests/${requestId}`);
43
+ }
44
+ async cancelRequest(requestId) {
45
+ await this.request("DELETE", `/requests/${requestId}`);
46
+ }
47
+ async waitForResponse(requestId, intervalMs, timeoutMs) {
48
+ const deadline = Date.now() + timeoutMs;
49
+ const terminal = new Set([
50
+ "answered",
51
+ "callback_pending",
52
+ "callback_delivered",
53
+ "callback_failed",
54
+ "closed",
55
+ "expired",
56
+ "cancelled",
57
+ ]);
58
+ while (Date.now() < deadline) {
59
+ const req = await this.getRequest(requestId);
60
+ if (terminal.has(req.state))
61
+ return req;
62
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
63
+ }
64
+ throw new Error(`Timeout waiting for response on request ${requestId}`);
65
+ }
66
+ }
@@ -0,0 +1,2 @@
1
+ import type { CentcomClaudeConfig } from "./types.js";
2
+ export declare function loadConfig(): CentcomClaudeConfig;
package/dist/config.js ADDED
@@ -0,0 +1,59 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ const DEFAULT_BASE_URL = "https://contro1.com/api/centcom/v1";
4
+ const DEFAULT_TOOLS = "Write,Edit,Bash";
5
+ const DEFAULT_TIMEOUT_MS = 300_000;
6
+ const DEFAULT_POLL_INTERVAL_MS = 3_000;
7
+ const DEFAULT_PRIORITY = "urgent";
8
+ const DEFAULT_FALLBACK = "deny";
9
+ const DEFAULT_CALLBACK_URL = "https://centcom.local/claude-code";
10
+ function readLocalConfig() {
11
+ const path = join(process.cwd(), ".centcom.json");
12
+ if (!existsSync(path))
13
+ return {};
14
+ try {
15
+ const raw = readFileSync(path, "utf-8");
16
+ return JSON.parse(raw);
17
+ }
18
+ catch {
19
+ return {};
20
+ }
21
+ }
22
+ function parseTools(value) {
23
+ return new Set((value ?? DEFAULT_TOOLS)
24
+ .split(",")
25
+ .map((part) => part.trim())
26
+ .filter(Boolean));
27
+ }
28
+ export function loadConfig() {
29
+ const file = readLocalConfig();
30
+ const env = process.env;
31
+ const apiKey = env.CENTCOM_API_KEY ?? file.CENTCOM_API_KEY;
32
+ if (!apiKey) {
33
+ throw new Error("CENTCOM_API_KEY is required");
34
+ }
35
+ const baseUrl = env.CENTCOM_BASE_URL ?? file.CENTCOM_BASE_URL ?? DEFAULT_BASE_URL;
36
+ const tools = parseTools(env.CENTCOM_TOOLS ?? file.CENTCOM_TOOLS);
37
+ const timeoutMs = Number(env.CENTCOM_TIMEOUT ?? file.CENTCOM_TIMEOUT ?? DEFAULT_TIMEOUT_MS);
38
+ const pollIntervalMs = Number(env.CENTCOM_POLL_INTERVAL ?? file.CENTCOM_POLL_INTERVAL ?? DEFAULT_POLL_INTERVAL_MS);
39
+ const priorityRaw = env.CENTCOM_PRIORITY ?? file.CENTCOM_PRIORITY ?? DEFAULT_PRIORITY;
40
+ const priority = priorityRaw === "normal" ? "normal" : "urgent";
41
+ const fallbackRaw = (env.CENTCOM_FALLBACK ?? file.CENTCOM_FALLBACK ?? DEFAULT_FALLBACK);
42
+ const fallback = fallbackRaw === "ask" || fallbackRaw === "allow" ? fallbackRaw : "deny";
43
+ const slaValue = env.CENTCOM_SLA_MINUTES ?? file.CENTCOM_SLA_MINUTES;
44
+ const slaMinutes = slaValue !== undefined ? Number(slaValue) : undefined;
45
+ const requiredRole = env.CENTCOM_REQUIRED_ROLE ?? file.CENTCOM_REQUIRED_ROLE;
46
+ const callbackUrl = env.CENTCOM_CALLBACK_URL ?? file.CENTCOM_CALLBACK_URL ?? DEFAULT_CALLBACK_URL;
47
+ return {
48
+ apiKey,
49
+ baseUrl,
50
+ tools,
51
+ timeoutMs,
52
+ pollIntervalMs,
53
+ priority,
54
+ slaMinutes: Number.isFinite(slaMinutes) ? slaMinutes : undefined,
55
+ requiredRole: requiredRole || undefined,
56
+ fallback,
57
+ callbackUrl,
58
+ };
59
+ }
@@ -0,0 +1,7 @@
1
+ import type { HookInput } from "./types.js";
2
+ export declare function buildIdempotencyKey(input: HookInput): string;
3
+ export declare function formatRequest(input: HookInput): {
4
+ question: string;
5
+ context: string;
6
+ metadata: Record<string, unknown>;
7
+ };
@@ -0,0 +1,58 @@
1
+ import { createHash } from "node:crypto";
2
+ const MAX_PREVIEW = 500;
3
+ function redactSecrets(text) {
4
+ return text
5
+ .replace(/(cc_(?:live|test)_[a-zA-Z0-9_-]{8,})/g, "[REDACTED_API_KEY]")
6
+ .replace(/(whsec_[a-zA-Z0-9_-]{8,})/g, "[REDACTED_WEBHOOK_SECRET]")
7
+ .replace(/(Bearer\s+)[^\s]+/gi, "$1[REDACTED_TOKEN]");
8
+ }
9
+ function clip(text, size = MAX_PREVIEW) {
10
+ if (text.length <= size)
11
+ return text;
12
+ return `${text.slice(0, size)}... [truncated]`;
13
+ }
14
+ function stableStringify(value) {
15
+ if (value === null || typeof value !== "object")
16
+ return JSON.stringify(value);
17
+ if (Array.isArray(value))
18
+ return `[${value.map(stableStringify).join(",")}]`;
19
+ const entries = Object.entries(value).sort(([a], [b]) => a.localeCompare(b));
20
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(",")}}`;
21
+ }
22
+ export function buildIdempotencyKey(input) {
23
+ const raw = `${input.session_id}|${input.tool_name}|${stableStringify(input.tool_input)}`;
24
+ const hash = createHash("sha256").update(raw).digest("hex").slice(0, 24);
25
+ return `claude:${input.session_id}:${input.tool_name}:${hash}`;
26
+ }
27
+ export function formatRequest(input) {
28
+ const tool = input.tool_name;
29
+ const toolInput = input.tool_input ?? {};
30
+ const safeJson = redactSecrets(stableStringify(toolInput));
31
+ let question = `Approve ${tool}?`;
32
+ let context = `Tool input:\n${safeJson}`;
33
+ if (tool === "Write" || tool === "Edit") {
34
+ const path = typeof toolInput.file_path === "string" ? toolInput.file_path : "unknown file";
35
+ const contentRaw = typeof toolInput.content === "string"
36
+ ? toolInput.content
37
+ : typeof toolInput.new_string === "string"
38
+ ? toolInput.new_string
39
+ : safeJson;
40
+ question = `Approve ${tool} to ${path}?`;
41
+ context = `Preview:\n${clip(redactSecrets(contentRaw))}`;
42
+ }
43
+ else if (tool === "Bash" || tool === "Shell") {
44
+ const command = typeof toolInput.command === "string" ? toolInput.command : clip(safeJson, MAX_PREVIEW);
45
+ question = `Approve command: ${redactSecrets(command)}?`;
46
+ context = `Command detail:\n${redactSecrets(command)}`;
47
+ }
48
+ return {
49
+ question,
50
+ context,
51
+ metadata: {
52
+ source: "claude-code",
53
+ session_id: input.session_id,
54
+ tool_name: tool,
55
+ cwd: input.cwd ?? "",
56
+ },
57
+ };
58
+ }
package/dist/hook.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/hook.js ADDED
@@ -0,0 +1,111 @@
1
+ #!/usr/bin/env node
2
+ import { stdin, stdout, stderr } from "node:process";
3
+ import { CentcomClient } from "./centcomClient.js";
4
+ import { loadConfig } from "./config.js";
5
+ import { buildIdempotencyKey, formatRequest } from "./formatter.js";
6
+ let activeRequestId = null;
7
+ let activeClient = null;
8
+ let fallbackDecision = "deny";
9
+ function readStdin() {
10
+ return new Promise((resolve, reject) => {
11
+ let data = "";
12
+ stdin.setEncoding("utf8");
13
+ stdin.on("data", (chunk) => {
14
+ data += chunk;
15
+ });
16
+ stdin.on("end", () => resolve(data));
17
+ stdin.on("error", reject);
18
+ });
19
+ }
20
+ function writeDecision(permissionDecision, systemMessage) {
21
+ const output = {
22
+ hookSpecificOutput: { permissionDecision },
23
+ ...(systemMessage ? { systemMessage } : {}),
24
+ };
25
+ stdout.write(JSON.stringify(output));
26
+ process.exit(0);
27
+ }
28
+ async function safeCancel() {
29
+ if (!activeClient || !activeRequestId)
30
+ return;
31
+ try {
32
+ await activeClient.cancelRequest(activeRequestId);
33
+ }
34
+ catch {
35
+ // Best-effort cleanup only.
36
+ }
37
+ }
38
+ function registerSignalHandlers() {
39
+ const handler = async () => {
40
+ await safeCancel();
41
+ writeDecision(fallbackDecision, "Approval interrupted before decision.");
42
+ };
43
+ process.on("SIGINT", handler);
44
+ process.on("SIGTERM", handler);
45
+ }
46
+ function parseInput(raw) {
47
+ if (!raw.trim()) {
48
+ throw new Error("Hook input is empty");
49
+ }
50
+ return JSON.parse(raw);
51
+ }
52
+ function responseApproved(response) {
53
+ if (!response || typeof response !== "object")
54
+ return false;
55
+ if (typeof response.approved === "boolean")
56
+ return response.approved;
57
+ if (typeof response.value === "boolean")
58
+ return response.value;
59
+ return false;
60
+ }
61
+ async function main() {
62
+ const config = loadConfig();
63
+ fallbackDecision = config.fallback;
64
+ registerSignalHandlers();
65
+ const raw = await readStdin();
66
+ const input = parseInput(raw);
67
+ if (!config.tools.has(input.tool_name)) {
68
+ writeDecision("allow");
69
+ }
70
+ const client = new CentcomClient({
71
+ apiKey: config.apiKey,
72
+ baseUrl: config.baseUrl,
73
+ timeoutMs: Math.min(config.timeoutMs, 30_000),
74
+ });
75
+ activeClient = client;
76
+ const formatted = formatRequest(input);
77
+ const idempotencyKey = buildIdempotencyKey(input);
78
+ try {
79
+ const request = await client.createRequest({
80
+ type: "approval",
81
+ question: formatted.question,
82
+ context: formatted.context,
83
+ callback_url: config.callbackUrl,
84
+ priority: config.priority,
85
+ required_role: config.requiredRole,
86
+ metadata: formatted.metadata,
87
+ sla_minutes: config.slaMinutes,
88
+ idempotency_key: idempotencyKey,
89
+ });
90
+ activeRequestId = request.id;
91
+ const result = await client.waitForResponse(request.id, config.pollIntervalMs, config.timeoutMs);
92
+ const approved = responseApproved(result.response ?? null);
93
+ writeDecision(approved ? "allow" : "deny");
94
+ }
95
+ catch (error) {
96
+ if (error instanceof Error &&
97
+ error.message.toLowerCase().includes("timeout") &&
98
+ activeRequestId) {
99
+ await safeCancel();
100
+ writeDecision("deny", "Approval timed out and was denied.");
101
+ }
102
+ const message = error instanceof Error ? error.message : "Unknown approval error";
103
+ stderr.write(`centcom-claude-code: ${message}\n`);
104
+ writeDecision(config.fallback, `CENTCOM unavailable, fallback=${config.fallback}.`);
105
+ }
106
+ }
107
+ main().catch((error) => {
108
+ const message = error instanceof Error ? error.message : "Unhandled error";
109
+ stderr.write(`centcom-claude-code: ${message}\n`);
110
+ writeDecision(fallbackDecision, `CENTCOM hook failed, fallback=${fallbackDecision}.`);
111
+ });
@@ -0,0 +1,27 @@
1
+ export type PermissionDecision = "allow" | "deny" | "ask";
2
+ export interface HookInput {
3
+ session_id: string;
4
+ tool_name: string;
5
+ tool_input: Record<string, unknown>;
6
+ cwd?: string;
7
+ permission_mode?: string;
8
+ hook_event_name?: string;
9
+ }
10
+ export interface HookOutput {
11
+ hookSpecificOutput: {
12
+ permissionDecision: PermissionDecision;
13
+ };
14
+ systemMessage?: string;
15
+ }
16
+ export interface CentcomClaudeConfig {
17
+ apiKey: string;
18
+ baseUrl: string;
19
+ tools: Set<string>;
20
+ timeoutMs: number;
21
+ pollIntervalMs: number;
22
+ priority: "normal" | "urgent";
23
+ slaMinutes?: number;
24
+ requiredRole?: string;
25
+ fallback: PermissionDecision;
26
+ callbackUrl: string;
27
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "@contro1/claude-code",
3
+ "version": "0.1.0",
4
+ "description": "CENTCOM approval hook for Claude Code PreToolUse",
5
+ "type": "module",
6
+ "main": "dist/hook.js",
7
+ "types": "dist/hook.d.ts",
8
+ "bin": {
9
+ "centcom-claude-code": "dist/hook.js"
10
+ },
11
+ "files": [
12
+ "dist",
13
+ "README.md",
14
+ "LICENSE"
15
+ ],
16
+ "scripts": {
17
+ "build": "tsc",
18
+ "typecheck": "tsc --noEmit",
19
+ "prepublishOnly": "npm run build"
20
+ },
21
+ "keywords": [
22
+ "centcom",
23
+ "claude-code",
24
+ "approval",
25
+ "hook",
26
+ "hitl"
27
+ ],
28
+ "license": "MIT",
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "dependencies": {},
33
+ "devDependencies": {
34
+ "@types/node": "^20.0.0",
35
+ "typescript": "^5.4.0"
36
+ },
37
+ "engines": {
38
+ "node": ">=18"
39
+ }
40
+ }