Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -504,6 +504,7 @@ npx github:Lexus2016/claude-code-studio # launch as usual
| **Kanban** | Task queue, parallel + sequential, cross-tab sync, drag-and-drop tabs, dependency graphs, engine + model + effort per task/chain |
| **Scheduler** | One-time + recurring (hourly/daily/weekly/monthly), 5 parallel workers, Run Now, SQLite-persisted, engine + model + effort per task, watchdog auto-recovery |
| **Task Manager** | Autonomous child tasks, chains, context passing, result reporting, cancellation, board-only cards (import a plan without running it) (MCP) |
| **External API** | Drive CCS from an agent outside it: the `ccs` MCP server ([mcp-ccs.js](mcp-ccs.js)) lists projects, creates and follows tasks, reads results, cancels — plus a token-authenticated REST surface (`/api/external/v1`), scoped `read`/`full`, revocable, hashed at rest ([docs](docs/EXTERNAL-API.md)) |
| **Telegram** | Bot control, push notifications, ask_user forwarding (+ file answers), session bridge, Forum Mode, inline stop, deep-link navigation, rich action buttons (localized EN/UA/RU/FR/HE), Write button, file attachments, interrupt queue while busy |
| **Delegation** | Cross-agent handoff/sync (Codex, Antigravity, opencode), CONTEXT.md + DIALOG.md protocol, fs.watch + polling, persistent across restarts, Windows support, sidebar agents manager, auto-seeded defaults, test button |
| **Agents** | Single, Multi (2–5 in-chat, schema-validated planning), Dispatch (Kanban), Room (project bots take serial turns on one message), auto-retry, cascade cancellation, effort propagation |
Expand Down Expand Up @@ -533,6 +534,8 @@ claude-cli.js — spawns `claude` subprocess, parses JSON stream
telegram-bot.js — Telegram bot (Direct Mode)
telegram-bot-forum.js — Forum Mode standalone module (composition pattern)
mcp-task-manager.js — MCP server for autonomous task management
api-token.js — scoped, revocable tokens for the external API (hashed at rest)
mcp-ccs.js — MCP client for OUTSIDE agents: projects + tasks over /api/external/v1
mcp-notify.js — MCP server for non-blocking notifications
public/index.html — entire frontend (HTML + CSS + JS)
config.json — MCP servers + skills catalog
Expand Down
163 changes: 163 additions & 0 deletions api-token.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
'use strict';
// ─── External API tokens (issue #150) ─────────────────────────────────────────
// The web UI authenticates with a 30-day session token held in a cookie. An
// external client (mcp-ccs.js on a laptop, MCPHub in another container) needs
// something different: a credential that
//
// - lives for months without a browser in the loop,
// - can be revoked without logging the owner out (revokeToken() would also
// kill their own session),
// - is not the per-process TASK_MANAGER_SECRET, which is random on every
// restart and therefore unusable outside this process,
// - carries a SCOPE, because "create a task" is code execution in the
// container and a monitoring client should not have that.
//
// So this module is the whole token store: `data/api-tokens.json`, 0600, and
// only a SHA-256 of each token on disk. The plaintext is returned once, by
// createToken(), and never written or logged anywhere. A token is a high-entropy
// random value, not a password, so a plain hash is the right primitive here —
// bcrypt would only buy a work factor against guessing a 192-bit value.
//
// Tokens are opt-in by existing: an install with no tokens cannot call the
// external API at all, and nothing else in the app reads this file.
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');

const APP_DIR = process.env.APP_DIR || __dirname;
const TOKENS_FILE = path.join(APP_DIR, 'data', 'api-tokens.json');

// `ccs_` makes a leaked token greppable in logs and secret scanners, which is
// the one place an opaque 48-hex string would be invisible.
const TOKEN_PREFIX = 'ccs_';
const SCOPES = ['read', 'full'];
// Same ceiling as auth.js's session cap: past this, a list of tokens stops being
// something a person can read, and nothing legitimate needs it.
const MAX_TOKENS = 20;
// lastUsedAt is in-memory and flushed at most this often — an external client
// polls, and a writeFileSync per request would rewrite the file in a loop.
const LAST_USED_FLUSH_INTERVAL = 5 * 60 * 1000;

function hashHex(token) {
return crypto.createHash('sha256').update(String(token), 'utf8').digest('hex');
}

function isHashString(v) {
return typeof v === 'string' && /^[0-9a-f]{64}$/.test(v);
}

function isRecord(r) {
return r !== null && typeof r === 'object' && !Array.isArray(r) &&
typeof r.id === 'string' && r.id.length > 0 &&
isHashString(r.hash) &&
SCOPES.includes(r.scope) &&
typeof r.created_at === 'string';
}

// No cache: unlike the sessions file (read on every HTTP request) this one is
// read only by the external surface and the token management endpoints, and a
// stale read here would mean a revoked token that still works.
function loadTokens() {
let parsed;
try { parsed = JSON.parse(fs.readFileSync(TOKENS_FILE, 'utf-8')); }
catch { return []; }
if (!Array.isArray(parsed)) return [];
// Accept only records this module writes; a hand-edited file must fail closed,
// not turn every request into a throw.
return parsed.filter(isRecord);
}

function saveTokens(list) {
const dir = path.dirname(TOKENS_FILE);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
const tmp = TOKENS_FILE + '.tmp';
// 0600: token hashes are not the token, but they are still credential material
// on a shared host — the same reason auth.json is written this way.
fs.writeFileSync(tmp, JSON.stringify(list, null, 2), { mode: 0o600 });
try { fs.chmodSync(tmp, 0o600); } catch {}
fs.renameSync(tmp, TOKENS_FILE);
}

function sanitizeName(name) {
// eslint-disable-next-line no-control-regex
const cleaned = String(name == null ? '' : name)
.replace(/[\x00-\x1F\x7F\u0080-\u009F\u200B-\u200F\u2028\u2029\u202A-\u202E\uFEFF]/g, '')
.trim()
.slice(0, 60);
return cleaned;
}

function publicRecord(r) {
return { id: r.id, name: r.name, scope: r.scope, created_at: r.created_at, last_used_at: r.last_used_at || null };
}

/** Metadata only — never the hash, never the token. */
function listTokens() {
return loadTokens().map(publicRecord);
}

/**
* Mint a token. Returns { token, record } — `token` is the only time the
* plaintext exists; the caller (HTTP response or scripts/api-token.js) is
* responsible for showing it once.
*/
function createToken({ name, scope } = {}) {
const cleanName = sanitizeName(name) || 'external client';
if (!SCOPES.includes(scope)) throw new Error(`scope must be one of: ${SCOPES.join(', ')}`);
const tokens = loadTokens();
if (tokens.length >= MAX_TOKENS) throw new Error(`token limit reached (${MAX_TOKENS}); revoke one first`);

// 24 random bytes = 192 bits. The prefix is stripped before hashing so the
// stored value is over the secret alone.
const token = TOKEN_PREFIX + crypto.randomBytes(24).toString('hex');
const record = {
id: crypto.randomBytes(8).toString('hex'),
name: cleanName,
scope,
hash: hashHex(token),
created_at: new Date().toISOString(),
last_used_at: null,
};
tokens.push(record);
saveTokens(tokens);
return { token, record: publicRecord(record) };
}

function revokeToken(id) {
if (!id) return false;
const tokens = loadTokens();
const kept = tokens.filter(t => t.id !== id);
if (kept.length === tokens.length) return false;
saveTokens(kept);
return true;
}

/**
* Verify a presented bearer token. Returns { id, name, scope } or null.
* Constant-time on the hash: comparing hex strings with === would leak the
* matching prefix of a token an attacker is guessing.
*/
function verifyToken(plain) {
if (typeof plain !== 'string' || !plain.startsWith(TOKEN_PREFIX)) return null;
const presented = crypto.createHash('sha256').update(plain, 'utf8').digest();
const tokens = loadTokens();
let match = null;
for (const t of tokens) {
const stored = Buffer.from(t.hash, 'hex');
if (stored.length === presented.length && crypto.timingSafeEqual(stored, presented)) match = t;
}
if (!match) return null;

const now = Date.now();
const last = Date.parse(match.last_used_at || '') || 0;
if (now - last > LAST_USED_FLUSH_INTERVAL) {
match.last_used_at = new Date(now).toISOString();
try { saveTokens(tokens); } catch { /* a read path must not fail on a stats write */ }
}
return { id: match.id, name: match.name, scope: match.scope };
}

module.exports = {
TOKENS_FILE, TOKEN_PREFIX, SCOPES,
listTokens, createToken, revokeToken, verifyToken,
};
121 changes: 121 additions & 0 deletions docs/EXTERNAL-API.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
# External API and the `ccs` MCP server (issue #150)

Drive Claude Code Studio **from outside**: another Claude Code session, an MCP hub,
a monitoring script, a CI job. This document covers stage 1 — projects and tasks.
Chats (create a chat, send a message, read the reply, stop a turn) are stage 2,
because `send_message`/`stop_turn` have no documented server contract yet.

Two pieces:

- `mcp-ccs.js` — a self-contained stdio MCP server (zero dependencies) that talks to
the HTTP API over `http` or `https`. Copy it anywhere; it needs no sibling files.
- `/api/external/v1/*` — a small, token-authenticated REST surface. It is the entire
contract an external client gets; chats, files, settings and terminals are not
reachable with an external token.

## 1. Create a token

Tokens are opt-in: with none on disk, every call to the external API is `401`.

```bash
# in the CCS data directory (or a container: docker exec -it claude-code-studio …)
node scripts/api-token.js create --name mcphub --scope read
```

The plaintext is printed **once**. Only a SHA-256 is stored, in `data/api-tokens.json`
(mode 0600), so a lost token is revoked and replaced, never recovered.

```bash
node scripts/api-token.js list # metadata + last use, never the secret
node scripts/api-token.js revoke <id> # effective on the next request
```

Scopes:

| scope | may |
| --- | --- |
| `read` (default) | list projects, list/read tasks, read results |
| `full` | the above, plus create and cancel tasks |

`full` is code execution: a created task runs `claude` with the description as its
prompt, in the project workdir, with the container's permissions. Use `read` for
monitoring. Revoking a token does not affect the owner's browser session, and a
session logout does not revoke tokens.

The same operations exist over HTTP for a logged-in client:
`GET /api/api-tokens`, `POST /api/api-tokens {name, scope}`, `DELETE /api/api-tokens/<id>`.

## 2. Point a client at it

Claude Code (`~/.claude.json` or `.mcp.json`):

```json
{
"mcpServers": {
"ccs": {
"command": "node",
"args": ["/path/to/claude-code-studio/mcp-ccs.js"],
"env": {
"CCS_URL": "http://127.0.0.1:3000",
"CCS_TOKEN": "ccs_…"
}
}
}
}
```

MCPHub or any host that runs stdio servers in its own container: mount or copy
`mcp-ccs.js`, then set the same two variables. `CCS_URL` may be any address the
container can reach (`http://claude-code-studio:3000` on a compose network, or an
`https://` reverse proxy) and may include a path prefix (`https://host/ccs`).

| variable | default | meaning |
| --- | --- | --- |
| `CCS_URL` | `http://127.0.0.1:3000` | server base URL, `http` or `https`, without `/api` |
| `CCS_TOKEN` | — | token from step 1; without it every tool call explains what is missing |

## 3. Tools

| tool | scope | notes |
| --- | --- | --- |
| `list_projects` | read | returns `id`, `name`, `workdir`, `isRemote` |
| `list_tasks` | read | filters: `project`, `status`, `limit` (default 20, max 100), newest first |
| `get_task` | read | one task, with its description |
| `get_task_result` | read | the structured result a finished run reported |
| `create_task` | full | **requires `project`**; defaults to `status: "backlog"` |
| `cancel_task` | full | refuses a completed task; idempotent otherwise |

`create_task` never inherits a workdir — an outside caller has no parent task, and
guessing one would start an unattended run in an arbitrary tree. A card created
without `status` lands in `backlog` and nothing runs; pass `status: "todo"` to queue
a run now (optionally with `scheduled_at`). Tasks get their own git worktree, the
same as a card created in the UI.

## 4. REST surface

All endpoints take `Authorization: Bearer ccs_…` and return JSON.

| method | path | scope |
| --- | --- | --- |
| GET | `/api/external/v1/me` | read |
| GET | `/api/external/v1/projects` | read |
| GET | `/api/external/v1/tasks?project=&status=&limit=` | read |
| GET | `/api/external/v1/tasks/:id` | read |
| GET | `/api/external/v1/tasks/:id/result` | read |
| POST | `/api/external/v1/tasks` | full |
| POST | `/api/external/v1/tasks/:id/cancel` | full |

`project` accepts an id or an exact name (case-insensitive). An ambiguous name is
refused with the candidate ids instead of resolved to whichever came first.

## 5. Boundaries

- A request carrying an `Origin` header is refused (`403`). Browsers attach one to
every cross-site fetch; MCP clients never send one. This keeps a page the owner
visits from spending a token that is sitting in a shell.
- Tokens are a fixed bearer credential, not a session: no expiry, revocable at any
time, at most 20 at once.
- Remote (SSH) projects are not writable through this API yet; they are listed, and
creating a task in one returns `400`.
- The external API is a local/trusted-network surface. Terminate TLS in front of it
if it crosses an untrusted network; the server itself speaks plain HTTP.
Loading
Loading