Compare commits
17 Commits
67c1c3f9a4
...
v1.0.0
| Author | SHA1 | Date | |
|---|---|---|---|
| f2d32a3faa | |||
| 62d2480cd4 | |||
| 0d1e25019e | |||
| fa4a7a99f8 | |||
| 412e322a69 | |||
| 507eb7584d | |||
| ca7ae930cc | |||
| 50f49c366a | |||
| c45d196702 | |||
| 81ad722e84 | |||
| e8bbcb293f | |||
| 0a3ab14053 | |||
| 4b064f1bf8 | |||
| 0568026e7c | |||
| b83ae686c4 | |||
| 2bf658dc5f | |||
| ac82501b48 |
2
.npmignore
Normal file
2
.npmignore
Normal file
@@ -0,0 +1,2 @@
|
||||
secrets.json
|
||||
filtered-secrets.json
|
||||
198
README.md
198
README.md
@@ -1,66 +1,176 @@
|
||||
# claude-code-conduit
|
||||
|
||||
A supervised action bridge between Claude Code and the host system.
|
||||
A supervised action bridge between Claude Code and the host system. Claude requests structured actions; the server applies per-action policies and optionally holds them for human approval before executing.
|
||||
|
||||
Claude requests structured actions. The server applies per-action policies:
|
||||
- **auto-accept** — executed immediately (e.g. open a file in editor)
|
||||
- **auto-deny** — rejected immediately
|
||||
- **queue** — held for user approval (e.g. open a browser URL)
|
||||
## Concepts
|
||||
|
||||
## Setup
|
||||
**Actions** are typed verbs with named parameters — not shell commands. The server defines what actions exist and what happens when they are called. Example:
|
||||
|
||||
```json
|
||||
{ "action": "edit-file", "filename": "/workspace/foo.mjs" }
|
||||
```
|
||||
|
||||
**Policies** control what happens when an action is requested:
|
||||
- `auto-accept` — executed immediately (e.g. open a file in the editor)
|
||||
- `auto-deny` — rejected immediately
|
||||
- `queue` — held for human approval (e.g. open a browser URL)
|
||||
|
||||
**Authentication** uses HMAC-SHA256. Every request is signed with the caller's secret. Secrets live in a JSON file — never in environment variables.
|
||||
|
||||
**Users** each have a secret and a `canApprove` list controlling whose queued actions they may approve.
|
||||
|
||||
---
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
# Global install from Gitea
|
||||
npm install -g git+https://gitea.efforting.tech/mikael-lovqvists-claude-agent/claude-code-conduit.git
|
||||
|
||||
# Or clone and link locally
|
||||
git clone git@git.efforting.tech:mikael-lovqvists-claude-agent/claude-code-conduit.git
|
||||
cd claude-code-conduit
|
||||
npm install
|
||||
npm link
|
||||
```
|
||||
|
||||
## Running the server
|
||||
### Generate secrets
|
||||
|
||||
```bash
|
||||
node server/index.js
|
||||
# or
|
||||
CONDUIT_PORT=3333 CONDUIT_ROOT=/workspace node server/index.js
|
||||
# Create a secrets file with random secrets for each user
|
||||
ccc-keygen --create user,agent
|
||||
|
||||
# Edit secrets.json to configure who can approve whom:
|
||||
# set user.canApprove = ["agent"]
|
||||
|
||||
# Produce a filtered file for the agent (e.g. to copy into a Docker container)
|
||||
ccc-keygen --filter agent --output agent-secrets.json
|
||||
```
|
||||
|
||||
## Using the CLI client
|
||||
The full `secrets.json` stays on the host. `agent-secrets.json` goes into the container.
|
||||
|
||||
---
|
||||
|
||||
## Running
|
||||
|
||||
### Server (host)
|
||||
|
||||
```bash
|
||||
# List available actions
|
||||
node client/index.js list-actions
|
||||
|
||||
# Open a file in the editor (auto-accepted)
|
||||
node client/index.js edit-file filename=/workspace/myfile.js
|
||||
|
||||
# Open a URL (queued for user approval)
|
||||
node client/index.js open-browser url=https://example.com
|
||||
ccc-server --secrets secrets.json
|
||||
```
|
||||
|
||||
When a queued action is submitted, the server prints the approve/deny URLs to stdout:
|
||||
|
||||
```
|
||||
[QUEUE] New request #a1b2c3d4
|
||||
Action: open-browser
|
||||
Params: {"url":"https://example.com"}
|
||||
Approve: POST /queue/a1b2c3d4.../approve
|
||||
Deny: POST /queue/a1b2c3d4.../deny
|
||||
```
|
||||
|
||||
User approves via:
|
||||
```bash
|
||||
curl -X POST http://localhost:3333/queue/<id>/approve
|
||||
```
|
||||
|
||||
## Environment variables
|
||||
|
||||
Server environment variables:
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `CONDUIT_PORT` | `3333` | Server port |
|
||||
| `CONDUIT_PORT` | `3015` | Port to listen on |
|
||||
| `CONDUIT_BIND` | `127.0.0.1` | Address to bind to |
|
||||
| `CONDUIT_ROOT` | `/workspace` | Workspace root for path resolution |
|
||||
| `CONDUIT_URL` | `http://localhost:3333` | Server URL (client-side) |
|
||||
|
||||
## Adding actions
|
||||
### Client (container / agent)
|
||||
|
||||
Edit `server/actions.js`. Each action needs:
|
||||
- `description` — shown in list-actions
|
||||
- `params` — array of `{ name, required, type }`
|
||||
- `policy` — `"auto-accept"` | `"auto-deny"` | `"queue"`
|
||||
- `handler(params, helpers)` — async function that performs the action
|
||||
```bash
|
||||
ccc-client --secrets agent-secrets.json --user agent --url http://192.168.2.99:3015 '{"action": "list-actions"}'
|
||||
ccc-client --secrets agent-secrets.json --user agent '{"action": "edit-file", "filename": "/workspace/foo.mjs"}'
|
||||
```
|
||||
|
||||
`--secrets`, `--user`, and `--url` can also be set via environment variables:
|
||||
|
||||
```bash
|
||||
export CCC_SECRETS=/path/to/agent-secrets.json
|
||||
export CCC_USER=agent
|
||||
export CONDUIT_URL=http://192.168.2.99:3015
|
||||
ccc-client '{"action": "list-actions"}'
|
||||
```
|
||||
|
||||
The JSON payload can be spread across multiple arguments — they are space-joined before parsing:
|
||||
|
||||
```bash
|
||||
ccc-client '{"action": "edit-file",' '"filename": "/workspace/foo.mjs"}'
|
||||
```
|
||||
|
||||
### Queue manager (host)
|
||||
|
||||
```bash
|
||||
ccc-queue --secrets secrets.json --user user --url http://192.168.2.99:3015
|
||||
```
|
||||
|
||||
Opens an interactive TUI showing pending actions:
|
||||
|
||||
```
|
||||
┌─ Pending Actions ──────────┐ ┌─ Details ────────────────────────────┐
|
||||
│ │ │ │
|
||||
│ > [a1b2c3] open-browser │ │ Action: open-browser │
|
||||
│ [d4e5f6] open-terminal │ │ ID: a1b2c3d4-... │
|
||||
│ │ │ Submitted by: agent │
|
||||
│ │ │ Created: 2026-03-07T12:00:00Z │
|
||||
│ │ │ │
|
||||
│ │ │ Params: │
|
||||
│ │ │ url: https://example.com │
|
||||
└────────────────────────────┘ └──────────────────────────────────────┘
|
||||
[y] approve [n] deny [r] refresh [q] quit
|
||||
```
|
||||
|
||||
Client environment variables:
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `CCC_SECRETS` | — | Path to secrets file |
|
||||
| `CCC_USER` | — | Username to authenticate as |
|
||||
| `CONDUIT_URL` | `http://localhost:3015` | Server URL |
|
||||
|
||||
---
|
||||
|
||||
## Actions
|
||||
|
||||
Query available actions at runtime:
|
||||
|
||||
```bash
|
||||
ccc-client '{"action": "list-actions"}'
|
||||
```
|
||||
|
||||
Built-in actions:
|
||||
|
||||
| Action | Policy | Params |
|
||||
|--------|--------|--------|
|
||||
| `list-actions` | auto-accept | — |
|
||||
| `edit-file` | auto-accept | `filename` (path) |
|
||||
| `open-browser` | queue | `url` (http/https only) |
|
||||
| `open-terminal` | queue | `path` (optional) |
|
||||
|
||||
### Adding actions
|
||||
|
||||
Edit `server/actions.mjs`. Each entry needs:
|
||||
|
||||
```js
|
||||
'my-action': {
|
||||
description: 'What this does',
|
||||
params: [{ name: 'foo', required: true, type: 'string' }],
|
||||
policy: 'auto-accept', // or 'auto-deny' | 'queue'
|
||||
handler: ({ foo }) => {
|
||||
// do something
|
||||
return { result: foo };
|
||||
},
|
||||
},
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Path resolution
|
||||
|
||||
The server translates container-side paths to host-side paths using the volume map in `server/helpers.mjs`. By default this matches the `docker-compose.yml` layout:
|
||||
|
||||
| Container path | Host path |
|
||||
|----------------|-----------|
|
||||
| `/workspace` | `<CONTAINER_PATH>/workspace` |
|
||||
| `/home/claude` | `<CONTAINER_PATH>/claude-home` |
|
||||
|
||||
Paths outside known volumes are rejected. Edit `CONTAINER_PATH` and `VOLUME_MAPPING` in `server/helpers.mjs` to match your setup.
|
||||
|
||||
---
|
||||
|
||||
## Security notes
|
||||
|
||||
- Secrets are never passed via environment variables or command line arguments — only via a file
|
||||
- HMAC signatures include a timestamp; requests older than 30 seconds are rejected
|
||||
- `canApprove` is empty by default — permissions must be explicitly granted
|
||||
- Browser URLs are validated to `http`/`https` only before being passed to `xdg-open`
|
||||
- All path arguments are resolved against the volume map; traversal outside known volumes is rejected
|
||||
|
||||
2
bin/ccc-client.mjs
Executable file
2
bin/ccc-client.mjs
Executable file
@@ -0,0 +1,2 @@
|
||||
#!/usr/bin/env node
|
||||
import '../client/index.mjs';
|
||||
85
bin/ccc-keygen.mjs
Executable file
85
bin/ccc-keygen.mjs
Executable file
@@ -0,0 +1,85 @@
|
||||
#!/usr/bin/env node
|
||||
import { randomBytes } from 'crypto';
|
||||
import { readFileSync, writeFileSync, existsSync } from 'fs';
|
||||
|
||||
function get_arg(argv, flag) {
|
||||
const i = argv.indexOf(flag);
|
||||
return i !== -1 ? argv[i + 1] : null;
|
||||
}
|
||||
|
||||
function has_flag(argv, flag) {
|
||||
return argv.includes(flag);
|
||||
}
|
||||
|
||||
function parse_names(value, flag) {
|
||||
if (!value) {
|
||||
console.error(`${flag} requires a comma-separated list of usernames`);
|
||||
process.exit(1);
|
||||
}
|
||||
return value.split(',').map(s => s.trim()).filter(Boolean);
|
||||
}
|
||||
|
||||
function generate_secret() {
|
||||
return randomBytes(32).toString('hex');
|
||||
}
|
||||
|
||||
function read_secrets_file(input_path) {
|
||||
if (!existsSync(input_path)) {
|
||||
console.error(`Secrets file not found: ${input_path}`);
|
||||
process.exit(1);
|
||||
}
|
||||
try {
|
||||
return JSON.parse(readFileSync(input_path, 'utf8'));
|
||||
} catch (err) {
|
||||
console.error(`Cannot read secrets file: ${err.message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
function write_secrets_file(output_path, data) {
|
||||
writeFileSync(output_path, JSON.stringify(data, null, '\t') + '\n', 'utf8');
|
||||
console.log(`Written: ${output_path}`);
|
||||
}
|
||||
|
||||
const argv = process.argv;
|
||||
const create_arg = get_arg(argv, '--create');
|
||||
const filter_arg = get_arg(argv, '--filter');
|
||||
const input_arg = get_arg(argv, '--input') || 'secrets.json';
|
||||
const output_arg = get_arg(argv, '--output');
|
||||
|
||||
if (!create_arg && !filter_arg) {
|
||||
console.error(
|
||||
'Usage:\n' +
|
||||
' ccc-keygen --create <names> [--output secrets.json]\n' +
|
||||
' ccc-keygen --filter <names> [--input secrets.json] [--output filtered-secrets.json]'
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (create_arg) {
|
||||
const names = parse_names(create_arg, '--create');
|
||||
const output_path = output_arg || 'secrets.json';
|
||||
const users = {};
|
||||
for (const name of names) {
|
||||
users[name] = { secret: generate_secret(), canApprove: [] };
|
||||
}
|
||||
write_secrets_file(output_path, { users });
|
||||
console.log(`Created users: ${names.join(', ')}`);
|
||||
console.log('Edit canApprove lists to configure approval permissions.');
|
||||
}
|
||||
|
||||
if (filter_arg) {
|
||||
const names = parse_names(filter_arg, '--filter');
|
||||
const output_path = output_arg || 'filtered-secrets.json';
|
||||
const source = read_secrets_file(input_arg);
|
||||
const users = {};
|
||||
for (const name of names) {
|
||||
if (!source.users?.[name]) {
|
||||
console.error(`User '${name}' not found in ${input_arg}`);
|
||||
process.exit(1);
|
||||
}
|
||||
users[name] = source.users[name];
|
||||
}
|
||||
write_secrets_file(output_path, { users });
|
||||
console.log(`Filtered users: ${names.join(', ')}`);
|
||||
}
|
||||
166
bin/ccc-queue.mjs
Executable file
166
bin/ccc-queue.mjs
Executable file
@@ -0,0 +1,166 @@
|
||||
#!/usr/bin/env node
|
||||
import blessed from 'blessed';
|
||||
import { load_client_config } from '../client/config.mjs';
|
||||
import { create_conduit_client } from '../client/conduit.mjs';
|
||||
|
||||
const POLL_INTERVAL = 2000;
|
||||
|
||||
const { username, secret, url } = load_client_config(process.argv);
|
||||
const client = create_conduit_client(username, secret, url);
|
||||
|
||||
const screen = blessed.screen({
|
||||
smartCSR: true,
|
||||
title: 'ccc-queue',
|
||||
});
|
||||
|
||||
// ── Layout ────────────────────────────────────────────────────────────────────
|
||||
|
||||
const list_box = blessed.list({
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: '40%',
|
||||
height: '100%-3',
|
||||
border: { type: 'line' },
|
||||
label: ' Pending Actions ',
|
||||
scrollable: true,
|
||||
keys: true,
|
||||
vi: true,
|
||||
mouse: true,
|
||||
tags: true,
|
||||
style: {
|
||||
selected: { bg: 'blue', fg: 'white', bold: true },
|
||||
border: { fg: 'cyan' },
|
||||
label: { fg: 'cyan', bold: true },
|
||||
},
|
||||
});
|
||||
|
||||
const detail_box = blessed.box({
|
||||
top: 0,
|
||||
left: '40%',
|
||||
width: '60%',
|
||||
height: '100%-3',
|
||||
border: { type: 'line' },
|
||||
label: ' Details ',
|
||||
scrollable: true,
|
||||
alwaysScroll: true,
|
||||
tags: true,
|
||||
style: {
|
||||
border: { fg: 'cyan' },
|
||||
label: { fg: 'cyan', bold: true },
|
||||
},
|
||||
});
|
||||
|
||||
const status_bar = blessed.box({
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
width: '100%',
|
||||
height: 3,
|
||||
border: { type: 'line' },
|
||||
tags: true,
|
||||
style: { border: { fg: 'grey' } },
|
||||
});
|
||||
|
||||
screen.append(list_box);
|
||||
screen.append(detail_box);
|
||||
screen.append(status_bar);
|
||||
|
||||
// ── State ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
let items = [];
|
||||
let status_text = '';
|
||||
|
||||
function set_status(text, is_error = false) {
|
||||
status_text = text;
|
||||
const color = is_error ? 'red' : 'green';
|
||||
status_bar.setContent(
|
||||
` {${color}-fg}${text}{/${color}-fg} ` +
|
||||
`{grey-fg}[y]{/grey-fg} approve ` +
|
||||
`{grey-fg}[n]{/grey-fg} deny ` +
|
||||
`{grey-fg}[r]{/grey-fg} refresh ` +
|
||||
`{grey-fg}[q]{/grey-fg} quit`
|
||||
);
|
||||
screen.render();
|
||||
}
|
||||
|
||||
function render_detail(item) {
|
||||
if (!item) {
|
||||
detail_box.setContent('{grey-fg}No item selected{/grey-fg}');
|
||||
return;
|
||||
}
|
||||
const lines = [
|
||||
`{bold}Action:{/bold} ${item.action}`,
|
||||
`{bold}ID:{/bold} ${item.id}`,
|
||||
`{bold}Submitted by:{/bold} ${item.submitted_by}`,
|
||||
`{bold}Created:{/bold} ${item.created_at}`,
|
||||
'',
|
||||
'{bold}Params:{/bold}',
|
||||
];
|
||||
for (const [k, v] of Object.entries(item.params ?? {})) {
|
||||
lines.push(` {cyan-fg}${k}{/cyan-fg}: ${v}`);
|
||||
}
|
||||
detail_box.setContent(lines.join('\n'));
|
||||
}
|
||||
|
||||
function render_list() {
|
||||
const selected = list_box.selected ?? 0;
|
||||
list_box.clearItems();
|
||||
if (items.length === 0) {
|
||||
list_box.addItem('{grey-fg}(no pending items){/grey-fg}');
|
||||
} else {
|
||||
for (const item of items) {
|
||||
list_box.addItem(`{yellow-fg}${item.id.slice(0, 8)}{/yellow-fg} ${item.action}`);
|
||||
}
|
||||
list_box.select(Math.min(selected, items.length - 1));
|
||||
}
|
||||
render_detail(items[list_box.selected] ?? null);
|
||||
screen.render();
|
||||
}
|
||||
|
||||
// ── Polling ───────────────────────────────────────────────────────────────────
|
||||
|
||||
async function refresh() {
|
||||
try {
|
||||
items = await client.get_queue();
|
||||
render_list();
|
||||
set_status(`Last refresh: ${new Date().toLocaleTimeString()}`);
|
||||
} catch (err) {
|
||||
set_status(`Refresh failed: ${err.message}`, true);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Actions ───────────────────────────────────────────────────────────────────
|
||||
|
||||
async function decide(decision) {
|
||||
const item = items[list_box.selected];
|
||||
if (!item) {
|
||||
return;
|
||||
}
|
||||
set_status(`Sending ${decision} for ${item.id.slice(0, 8)}…`);
|
||||
try {
|
||||
await client.resolve_queue_item(item.id, decision);
|
||||
await refresh();
|
||||
} catch (err) {
|
||||
set_status(`Failed: ${err.message}`, true);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Keys ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
screen.key(['q', 'C-c'], () => process.exit(0));
|
||||
screen.key('r', refresh);
|
||||
screen.key('y', () => decide('approve'));
|
||||
screen.key('n', () => decide('deny'));
|
||||
|
||||
list_box.on('select item', () => {
|
||||
render_detail(items[list_box.selected] ?? null);
|
||||
screen.render();
|
||||
});
|
||||
|
||||
list_box.focus();
|
||||
|
||||
// ── Boot ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
set_status('Connecting…');
|
||||
refresh();
|
||||
const poll = setInterval(refresh, POLL_INTERVAL);
|
||||
poll.unref();
|
||||
2
bin/ccc-server.mjs
Executable file
2
bin/ccc-server.mjs
Executable file
@@ -0,0 +1,2 @@
|
||||
#!/usr/bin/env node
|
||||
import '../server/index.mjs';
|
||||
@@ -3,16 +3,16 @@
|
||||
|
||||
import { sign_request } from "./auth.mjs";
|
||||
|
||||
const BASE_URL = process.env.CONDUIT_URL || "http://localhost:3015";
|
||||
const DEFAULT_URL = 'http://localhost:3015';
|
||||
|
||||
export function create_conduit_client(username, secret) {
|
||||
export function create_conduit_client(username, secret, base_url = process.env.CONDUIT_URL || DEFAULT_URL) {
|
||||
function auth_headers(body_string) {
|
||||
return sign_request(secret, username, body_string);
|
||||
}
|
||||
|
||||
async function call_action(action, params = {}) {
|
||||
const body_string = JSON.stringify({ action, ...params });
|
||||
const res = await fetch(`${BASE_URL}/action`, {
|
||||
const res = await fetch(`${base_url}/action`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", ...auth_headers(body_string) },
|
||||
body: body_string,
|
||||
@@ -25,11 +25,19 @@ export function create_conduit_client(username, secret) {
|
||||
}
|
||||
|
||||
async function get_queue() {
|
||||
const res = await fetch(`${BASE_URL}/queue`, {
|
||||
headers: auth_headers(""),
|
||||
const res = await fetch(`${base_url}/queue`, {
|
||||
headers: auth_headers(''),
|
||||
});
|
||||
return res.json();
|
||||
}
|
||||
|
||||
return { call_action, list_actions, get_queue };
|
||||
async function resolve_queue_item(id, decision) {
|
||||
const res = await fetch(`${base_url}/queue/${id}/${decision}`, {
|
||||
method: 'POST',
|
||||
headers: auth_headers(''),
|
||||
});
|
||||
return res.json();
|
||||
}
|
||||
|
||||
return { call_action, list_actions, get_queue, resolve_queue_item };
|
||||
}
|
||||
|
||||
61
client/config.mjs
Normal file
61
client/config.mjs
Normal file
@@ -0,0 +1,61 @@
|
||||
// Resolve client config from CLI args or environment variables.
|
||||
// Precedence: CLI args > env vars > defaults
|
||||
//
|
||||
// Env vars:
|
||||
// CCC_SECRETS path to secrets file
|
||||
// CCC_USER username to authenticate as
|
||||
// CONDUIT_URL server URL
|
||||
|
||||
import { readFileSync } from 'fs';
|
||||
|
||||
const DEFAULT_URL = 'http://localhost:3015';
|
||||
|
||||
function get_arg(argv, flag) {
|
||||
const i = argv.indexOf(flag);
|
||||
return i !== -1 ? argv[i + 1] : null;
|
||||
}
|
||||
|
||||
export function load_client_config(argv) {
|
||||
const secrets_path = get_arg(argv, '--secrets') || process.env.CCC_SECRETS;
|
||||
const username = get_arg(argv, '--user') || process.env.CCC_USER;
|
||||
const url = get_arg(argv, '--url') || process.env.CONDUIT_URL || DEFAULT_URL;
|
||||
|
||||
if (!secrets_path) {
|
||||
console.error('Secrets file required: --secrets <path> or CCC_SECRETS=<path>');
|
||||
process.exit(1);
|
||||
}
|
||||
if (!username) {
|
||||
console.error('Username required: --user <name> or CCC_USER=<name>');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
let secrets;
|
||||
try {
|
||||
secrets = JSON.parse(readFileSync(secrets_path, 'utf8'));
|
||||
} catch (err) {
|
||||
console.error(`Cannot read secrets file: ${err.message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const user_entry = secrets.users?.[username];
|
||||
if (!user_entry) {
|
||||
console.error(`User '${username}' not found in secrets file`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
return { username, secret: user_entry.secret, url };
|
||||
}
|
||||
|
||||
export function get_remaining(argv) {
|
||||
const result = [];
|
||||
let i = 2;
|
||||
while (i < argv.length) {
|
||||
if (argv[i] === '--secrets' || argv[i] === '--user' || argv[i] === '--url') {
|
||||
i += 2;
|
||||
} else {
|
||||
result.push(argv[i]);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -1,93 +1,46 @@
|
||||
#!/usr/bin/env node
|
||||
// Conduit client — thin CLI wrapper for Claude to call the conduit server.
|
||||
// Usage:
|
||||
// node client/index.mjs --secrets /path/to/secrets.json --user agent <action> [key=value ...]
|
||||
// node client/index.mjs --secrets /path/to/secrets.json --user agent list-actions
|
||||
// node client/index.mjs --secrets /path/to/secrets.json --user agent edit-file filename=/workspace/foo.mjs
|
||||
// ccc-client '{"action": "list-actions"}'
|
||||
// ccc-client '{"action":' '"edit-file",' '"filename": "/workspace/foo.mjs"}'
|
||||
|
||||
import { readFileSync } from "fs";
|
||||
import { sign_request } from "./auth.mjs";
|
||||
import { sign_request } from './auth.mjs';
|
||||
import { load_client_config, get_remaining } from './config.mjs';
|
||||
|
||||
const BASE_URL = process.env.CONDUIT_URL || "http://localhost:3015";
|
||||
|
||||
function get_arg(argv, flag) {
|
||||
const i = argv.indexOf(flag);
|
||||
return i !== -1 ? argv[i + 1] : null;
|
||||
}
|
||||
|
||||
async function call_action(action, params, auth_headers) {
|
||||
const body_string = JSON.stringify({ action, ...params });
|
||||
const res = await fetch(`${BASE_URL}/action`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", ...auth_headers(body_string) },
|
||||
async function call_action(payload, username, secret, url) {
|
||||
const body_string = JSON.stringify(payload);
|
||||
const res = await fetch(`${url}/action`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...sign_request(secret, username, body_string) },
|
||||
body: body_string,
|
||||
});
|
||||
const body = await res.json();
|
||||
return { status: res.status, body };
|
||||
}
|
||||
|
||||
function parse_args(argv) {
|
||||
// Skip --secrets and --user flags and their values
|
||||
const filtered = [];
|
||||
let i = 2;
|
||||
while (i < argv.length) {
|
||||
if (argv[i] === "--secrets" || argv[i] === "--user") {
|
||||
i += 2;
|
||||
} else {
|
||||
filtered.push(argv[i]);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
const [action, ...rest] = filtered;
|
||||
const params = {};
|
||||
for (const arg of rest) {
|
||||
const eq = arg.indexOf("=");
|
||||
if (eq === -1) {
|
||||
console.error(`Bad argument (expected key=value): ${arg}`);
|
||||
process.exit(1);
|
||||
}
|
||||
params[arg.slice(0, eq)] = arg.slice(eq + 1);
|
||||
}
|
||||
return { action, params };
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const secrets_path = get_arg(process.argv, "--secrets");
|
||||
const username = get_arg(process.argv, "--user");
|
||||
const { username, secret, url } = load_client_config(process.argv);
|
||||
const remaining = get_remaining(process.argv);
|
||||
|
||||
if (!secrets_path || !username) {
|
||||
console.error("Usage: conduit --secrets <path> --user <name> <action> [key=value ...]");
|
||||
if (!remaining.length) {
|
||||
console.error('Usage: ccc-client <json payload>');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
let secrets;
|
||||
let payload;
|
||||
try {
|
||||
secrets = JSON.parse(readFileSync(secrets_path, "utf8"));
|
||||
payload = JSON.parse(remaining.join(' '));
|
||||
} catch (err) {
|
||||
console.error(`Cannot read secrets file: ${err.message}`);
|
||||
console.error(`Invalid JSON payload: ${err.message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const user_entry = secrets.users?.[username];
|
||||
if (!user_entry) {
|
||||
console.error(`User '${username}' not found in secrets file`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const { action, params } = parse_args(process.argv);
|
||||
if (!action) {
|
||||
console.error("Usage: conduit --secrets <path> --user <name> <action> [key=value ...]");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const auth_headers = (body_string) => sign_request(user_entry.secret, username, body_string);
|
||||
const { status, body } = await call_action(action, params, auth_headers);
|
||||
|
||||
const { status, body } = await call_action(payload, username, secret, url);
|
||||
console.log(JSON.stringify(body, null, 2));
|
||||
process.exit(status >= 400 ? 1 : 0);
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error("Conduit error:", err.message);
|
||||
console.error('Conduit error:', err.message);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
@@ -1,13 +1,20 @@
|
||||
{
|
||||
"name": "claude-code-conduit",
|
||||
"version": "0.1.0",
|
||||
"version": "1.0.0",
|
||||
"description": "A supervised action bridge between Claude Code and the host system",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"server": "node server/index.mjs",
|
||||
"client": "node client/index.mjs"
|
||||
},
|
||||
"bin": {
|
||||
"ccc-server": "bin/ccc-server.mjs",
|
||||
"ccc-client": "bin/ccc-client.mjs",
|
||||
"ccc-queue": "bin/ccc-queue.mjs",
|
||||
"ccc-keygen": "bin/ccc-keygen.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"blessed": "^0.1.81",
|
||||
"express": "^5.2.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"users": {
|
||||
"agent": { "secret": "change-me-agent", "canApprove": [] },
|
||||
"user": { "secret": "change-me-user", "canApprove": ["agent"] }
|
||||
"<username>": { "secret": "<hex secret>", "canApprove": [] },
|
||||
"<username>": { "secret": "<hex secret>", "canApprove": ["<username>"] }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Action registry — defines all available actions, their parameters, and policies.
|
||||
// policy: "auto-accept" | "auto-deny" | "queue"
|
||||
|
||||
|
||||
import { resolve_path, exec } from "./helpers.mjs";
|
||||
|
||||
export const actions = {
|
||||
@@ -8,7 +9,7 @@ export const actions = {
|
||||
description: "List all available actions and their definitions",
|
||||
params: [],
|
||||
policy: "auto-accept",
|
||||
handler: async () => {
|
||||
handler: () => {
|
||||
return Object.entries(actions).map(([name, def]) => ({
|
||||
action: name,
|
||||
description: def.description,
|
||||
@@ -22,41 +23,47 @@ export const actions = {
|
||||
description: "Open a file in the editor",
|
||||
params: [{ name: "filename", required: true, type: "path" }],
|
||||
policy: "auto-accept",
|
||||
handler: async ({ filename }) => {
|
||||
handler: ({ filename }) => {
|
||||
const resolved = resolve_path(filename);
|
||||
await exec("xdg-open", [resolved]);
|
||||
exec('subl3', [resolved]);
|
||||
return { opened: resolved };
|
||||
},
|
||||
},
|
||||
|
||||
/*
|
||||
"open-directory": {
|
||||
description: "Open a directory in the file manager",
|
||||
params: [{ name: "path", required: true, type: "path" }],
|
||||
policy: "auto-accept",
|
||||
handler: async ({ path }) => {
|
||||
policy: 'queue',
|
||||
handler: ({ path }) => {
|
||||
const resolved = resolve_path(path);
|
||||
await exec("xdg-open", [resolved]);
|
||||
// exec( ... );
|
||||
return { opened: resolved };
|
||||
},
|
||||
},
|
||||
*/
|
||||
|
||||
"open-browser": {
|
||||
description: "Open a URL in the web browser",
|
||||
params: [{ name: "url", required: true, type: "string" }],
|
||||
policy: "queue",
|
||||
handler: async ({ url }) => {
|
||||
await exec("xdg-open", [url]);
|
||||
return { opened: url };
|
||||
handler: ({ url }) => {
|
||||
const parsed = new URL(url);
|
||||
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
||||
throw new Error(`Disallowed protocol: ${parsed.protocol}`);
|
||||
}
|
||||
exec('xdg-open', [parsed.href]);
|
||||
return { opened: parsed.href };
|
||||
},
|
||||
},
|
||||
|
||||
"open-terminal": {
|
||||
description: "Open a terminal in a given directory",
|
||||
params: [{ name: "path", required: false, type: "path" }],
|
||||
policy: "queue",
|
||||
handler: async ({ path }) => {
|
||||
const resolved = path ? resolve_path(path) : process.env.HOME;
|
||||
await exec("xdg-open", [resolved]);
|
||||
policy: 'queue',
|
||||
handler: ({ path }) => {
|
||||
const resolved = resolve_path(path ?? 'workspace');
|
||||
exec('konsole', ['--workdir', resolved, '-e', 'bash']);
|
||||
return { opened: resolved };
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1,25 +1,30 @@
|
||||
import { spawnSync } from "child_process";
|
||||
import { spawn } from "child_process";
|
||||
import path from "path";
|
||||
|
||||
const WORKSPACE_ROOT = process.env.CONDUIT_ROOT || "/workspace";
|
||||
const CONTAINER_PATH = "/home/devilholk/Projekt/claude-docker/";
|
||||
|
||||
// Resolve a path param relative to WORKSPACE_ROOT, preventing traversal.
|
||||
|
||||
// Docker image → host conversation
|
||||
const VOLUME_MAPPING = [
|
||||
['/home/claude', path.resolve(CONTAINER_PATH, 'claude-home')],
|
||||
['/workspace', path.resolve(CONTAINER_PATH, 'workspace')],
|
||||
];
|
||||
|
||||
// Translate a container-side path to its host-side equivalent using VOLUME_MAP.
|
||||
// Throws if the path escapes all known volumes.
|
||||
export function resolve_path(user_path) {
|
||||
const resolved = path.resolve(WORKSPACE_ROOT, user_path.replace(/^\//, ""));
|
||||
if (!resolved.startsWith(WORKSPACE_ROOT)) {
|
||||
throw new Error(`Path escapes workspace root: ${user_path}`);
|
||||
const abs = path.resolve(user_path);
|
||||
|
||||
for (const [container_prefix, host_prefix] of VOLUME_MAPPING) {
|
||||
if (abs === container_prefix || abs.startsWith(container_prefix + "/")) {
|
||||
return host_prefix + abs.slice(container_prefix.length);
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
// Execute a binary with an argument list — no shell interpolation.
|
||||
throw new Error(`Path is outside all known volumes: ${user_path}`);
|
||||
}
|
||||
|
||||
// Launch a binary with an argument list — no shell interpolation, fire and forget.
|
||||
export function exec(bin, args = []) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const result = spawnSync(bin, args, { stdio: "inherit" });
|
||||
if (result.error) {
|
||||
reject(result.error);
|
||||
} else {
|
||||
resolve(result.status);
|
||||
}
|
||||
});
|
||||
spawn(bin, args, { stdio: 'ignore', detached: true }).unref();
|
||||
}
|
||||
|
||||
@@ -1,17 +1,22 @@
|
||||
import express from "express";
|
||||
import { actions } from "./actions.mjs";
|
||||
import { enqueue, get_entry, list_pending, resolve } from "./queue.mjs";
|
||||
import { load_secrets } from "./secrets.mjs";
|
||||
import { create_auth_middleware, check_can_approve } from "./auth.mjs";
|
||||
|
||||
const PORT = process.env.CONDUIT_PORT || 3015;
|
||||
import express from 'express';
|
||||
import { actions } from './actions.mjs';
|
||||
import { enqueue, get_entry, list_pending, resolve } from './queue.mjs';
|
||||
import { load_secrets } from './secrets.mjs';
|
||||
import { create_auth_middleware, check_can_approve } from './auth.mjs';
|
||||
|
||||
function get_arg(argv, flag) {
|
||||
const i = argv.indexOf(flag);
|
||||
return i !== -1 ? argv[i + 1] : null;
|
||||
}
|
||||
|
||||
const secrets_path = get_arg(process.argv, "--secrets");
|
||||
function ts() {
|
||||
return new Date().toLocaleTimeString();
|
||||
}
|
||||
|
||||
const PORT = process.env.CONDUIT_PORT || 3015;
|
||||
const BIND = get_arg(process.argv, '--bind') || process.env.CONDUIT_BIND || '127.0.0.1';
|
||||
|
||||
const secrets_path = get_arg(process.argv, '--secrets');
|
||||
let secrets;
|
||||
try {
|
||||
secrets = load_secrets(secrets_path);
|
||||
@@ -24,11 +29,16 @@ const { users } = secrets;
|
||||
const app = express();
|
||||
app.use(express.json({
|
||||
verify: (req, _res, buf) => {
|
||||
req.raw_body = buf.toString("utf8");
|
||||
req.raw_body = buf.toString('utf8');
|
||||
},
|
||||
}));
|
||||
app.use(create_auth_middleware(users));
|
||||
|
||||
app.use((req, _res, next) => {
|
||||
console.log(`[${ts()}] ${req.method} ${req.path} — ${req.conduit_user}`);
|
||||
next();
|
||||
});
|
||||
|
||||
function validate_params(action_def, params) {
|
||||
const errors = [];
|
||||
for (const p of action_def.params) {
|
||||
@@ -40,7 +50,7 @@ function validate_params(action_def, params) {
|
||||
}
|
||||
|
||||
// POST /action — main entry point
|
||||
app.post("/action", async (req, res) => {
|
||||
app.post('/action', async (req, res) => {
|
||||
const { action, ...params } = req.body ?? {};
|
||||
|
||||
if (!action) {
|
||||
@@ -54,75 +64,77 @@ app.post("/action", async (req, res) => {
|
||||
|
||||
const errors = validate_params(def, params);
|
||||
if (errors.length) {
|
||||
return res.status(400).json({ error: "Invalid params", details: errors });
|
||||
return res.status(400).json({ error: 'Invalid params', details: errors });
|
||||
}
|
||||
|
||||
if (def.policy === "auto-deny") {
|
||||
return res.status(403).json({ status: "denied", reason: "Policy: auto-deny" });
|
||||
if (def.policy === 'auto-deny') {
|
||||
return res.status(403).json({ status: 'denied', reason: 'Policy: auto-deny' });
|
||||
}
|
||||
|
||||
if (def.policy === "auto-accept") {
|
||||
if (def.policy === 'auto-accept') {
|
||||
try {
|
||||
const result = await def.handler(params);
|
||||
return res.json({ status: "accepted", result });
|
||||
return res.json({ status: 'accepted', result });
|
||||
} catch (err) {
|
||||
return res.status(500).json({ status: "error", error: err.message });
|
||||
return res.status(500).json({ status: 'error', error: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
if (def.policy === "queue") {
|
||||
if (def.policy === 'queue') {
|
||||
const id = enqueue(action, params, req.conduit_user);
|
||||
return res.status(202).json({ status: "queued", id });
|
||||
return res.status(202).json({ status: 'queued', id });
|
||||
}
|
||||
});
|
||||
|
||||
// GET /queue — list pending items
|
||||
app.get("/queue", (req, res) => {
|
||||
app.get('/queue', (req, res) => {
|
||||
res.json(list_pending());
|
||||
});
|
||||
|
||||
// POST /queue/:id/approve — user approves a queued action
|
||||
app.post("/queue/:id/approve", async (req, res) => {
|
||||
app.post('/queue/:id/approve', async (req, res) => {
|
||||
const entry = get_entry(req.params.id);
|
||||
if (!entry) {
|
||||
return res.status(404).json({ error: "Not found" });
|
||||
return res.status(404).json({ error: 'Not found' });
|
||||
}
|
||||
if (entry.status !== "pending") {
|
||||
return res.status(409).json({ error: "Already resolved" });
|
||||
if (entry.status !== 'pending') {
|
||||
return res.status(409).json({ error: 'Already resolved' });
|
||||
}
|
||||
if (!check_can_approve(users, req.conduit_user, entry.submitted_by)) {
|
||||
return res.status(403).json({ error: "Not authorized to approve this entry" });
|
||||
return res.status(403).json({ error: 'Not authorized to approve this entry' });
|
||||
}
|
||||
|
||||
resolve(req.params.id, "approved");
|
||||
entry.resolved_by = req.conduit_user;
|
||||
resolve(req.params.id, 'approved');
|
||||
|
||||
const def = actions[entry.action];
|
||||
try {
|
||||
const result = await def.handler(entry.params);
|
||||
res.json({ status: "approved", result });
|
||||
res.json({ status: 'approved', result });
|
||||
} catch (err) {
|
||||
res.status(500).json({ status: "error", error: err.message });
|
||||
res.status(500).json({ status: 'error', error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// POST /queue/:id/deny — user denies a queued action
|
||||
app.post("/queue/:id/deny", (req, res) => {
|
||||
app.post('/queue/:id/deny', (req, res) => {
|
||||
const entry = get_entry(req.params.id);
|
||||
if (!entry) {
|
||||
return res.status(404).json({ error: "Not found" });
|
||||
return res.status(404).json({ error: 'Not found' });
|
||||
}
|
||||
if (entry.status !== "pending") {
|
||||
return res.status(409).json({ error: "Already resolved" });
|
||||
if (entry.status !== 'pending') {
|
||||
return res.status(409).json({ error: 'Already resolved' });
|
||||
}
|
||||
if (!check_can_approve(users, req.conduit_user, entry.submitted_by)) {
|
||||
return res.status(403).json({ error: "Not authorized to deny this entry" });
|
||||
return res.status(403).json({ error: 'Not authorized to deny this entry' });
|
||||
}
|
||||
|
||||
resolve(req.params.id, "denied");
|
||||
res.json({ status: "denied" });
|
||||
entry.resolved_by = req.conduit_user;
|
||||
resolve(req.params.id, 'denied');
|
||||
res.json({ status: 'denied' });
|
||||
});
|
||||
|
||||
app.listen(PORT, () => {
|
||||
console.log(`claude-code-conduit server running on port ${PORT}`);
|
||||
console.log(`Workspace root: ${process.env.CONDUIT_ROOT || "/workspace"}`);
|
||||
app.listen(PORT, BIND, () => {
|
||||
console.log(`claude-code-conduit server running on ${BIND}:${PORT}`);
|
||||
console.log(`Workspace root: ${process.env.CONDUIT_ROOT || '/workspace'}`);
|
||||
});
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { randomUUID } from "crypto";
|
||||
import { randomUUID } from 'crypto';
|
||||
|
||||
const pending = new Map();
|
||||
|
||||
function ts() {
|
||||
return new Date().toLocaleTimeString();
|
||||
}
|
||||
|
||||
export function enqueue(action, params, submitted_by) {
|
||||
const id = randomUUID();
|
||||
const entry = {
|
||||
@@ -9,16 +13,11 @@ export function enqueue(action, params, submitted_by) {
|
||||
action,
|
||||
params,
|
||||
submitted_by,
|
||||
status: "pending",
|
||||
status: 'pending',
|
||||
created_at: new Date().toISOString(),
|
||||
};
|
||||
pending.set(id, entry);
|
||||
console.log(`\n[QUEUE] New request #${id.slice(0, 8)}`);
|
||||
console.log(` Action: ${action}`);
|
||||
console.log(` Params: ${JSON.stringify(params)}`);
|
||||
console.log(` Submitted by: ${submitted_by}`);
|
||||
console.log(` Approve: POST /queue/${id}/approve`);
|
||||
console.log(` Deny: POST /queue/${id}/deny\n`);
|
||||
console.log(`[${ts()}] [QUEUE] ${submitted_by} requested '${action}' (${id.slice(0, 8)}) — params: ${JSON.stringify(params)}`);
|
||||
return id;
|
||||
}
|
||||
|
||||
@@ -27,7 +26,7 @@ export function get_entry(id) {
|
||||
}
|
||||
|
||||
export function list_pending() {
|
||||
return [...pending.values()].filter((e) => e.status === "pending");
|
||||
return [...pending.values()].filter((e) => e.status === 'pending');
|
||||
}
|
||||
|
||||
export function resolve(id, decision) {
|
||||
@@ -35,7 +34,8 @@ export function resolve(id, decision) {
|
||||
if (!entry) {
|
||||
return null;
|
||||
}
|
||||
entry.status = decision; // "approved" | "denied"
|
||||
entry.status = decision; // 'approved' | 'denied'
|
||||
entry.resolved_at = new Date().toISOString();
|
||||
console.log(`[${ts()}] [QUEUE] ${id.slice(0, 8)} ${decision} by ${entry.resolved_by ?? 'unknown'}`);
|
||||
return entry;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user