refactor: launch external tools without Room credentials or hook settings

A Launcher launch still opens the tool in the active workspace's folder,
tracks its process, streams observed output and stops it. What it no
longer does:

- set WAGGLE_SIGNAL_EMIT, WAGGLE_SIDECAR_URL, HIVE_MIND_DATA_DIR or the
  Room identity variables (WAGGLE_RUN_ID, WAGGLE_ROOM_ID,
  WAGGLE_DANCE_TEAM_ID, WAGGLE_SENDER_ID, WAGGLE_RUN_TOKEN). Only the
  removed coding-agent hooks and the WaggleDance CLI read them. The
  external-process allowlist now admits WAGGLE_WORKSPACE_ID alone;
- issue a run credential. Run tokens existed for Room workers (the dance
  CLI and OpenClaw's model calls), so the registry's credential store,
  the middleware's run-token bearer on /v1/chat/completions and the
  proxy's per-run model scope go. While an agent run with a model is
  active, the proxy still serves only the session bearer.

The run record that a launch creates in the agent-run registry stays: it
backs cancel from the Room canvas, which this change does not remove.
This commit is contained in:
shumeiko.it
2026-11-01 11:12:31 +01:00
parent 80db300485
commit 25f95c584b
12 changed files with 65 additions and 665 deletions

View File

@@ -27,12 +27,7 @@ const BASE_ENV_ALLOWLIST = new Set([
/** Explicit Waggle runtime metadata constructed by trusted launch code. */
const WAGGLE_ENV_ALLOWLIST = new Set([
'WAGGLE_WORKSPACE_ID', 'WAGGLE_WORKSPACE_PATH',
'WAGGLE_RUN_ID', 'WAGGLE_ROOM_ID', 'WAGGLE_SENDER_ID',
'WAGGLE_DANCE_TEAM_ID', 'WAGGLE_DANCE_URL', 'WAGGLE_RUN_TOKEN',
'WAGGLE_CLI_NODE_PATH', 'WAGGLE_CLI_ENTRY',
'WAGGLE_SIGNAL_EMIT', 'WAGGLE_SIDECAR_URL',
'HIVE_MIND_DATA_DIR', 'NO_COLOR',
'WAGGLE_WORKSPACE_ID',
]);
/**

View File

@@ -195,11 +195,7 @@ export interface LaunchOptions {
* detection is the source of truth for where the tool lives.
*/
installedPath: string;
/**
* Workspace id to inject as `WAGGLE_WORKSPACE_ID` in the spawned
* tool's environment. Hooks pick this up via workspace-resolver
* for context-aware capture.
*/
/** Workspace id to inject as `WAGGLE_WORKSPACE_ID` in the spawned tool's environment. */
workspaceId?: string;
/**
* Working directory for the spawned process. Defaults to the
@@ -208,29 +204,6 @@ export interface LaunchOptions {
cwd?: string;
/** Extra arguments to pass to the binary. */
args?: string[];
/**
* When true (default), inject `WAGGLE_SIGNAL_EMIT='1'` so the launched
* tool's hive-mind hook emits discovery signals back to the sidecar
* bus. This is what turns the detect→launch→hook→bus→UI pipeline on:
* without it a dock-launched tool saves memory but stays silent on the
* bus it was built to feed. Set `false` for a silent launch.
*/
signalEmit?: boolean;
/**
* Sidecar base URL injected as `WAGGLE_SIDECAR_URL` so the launched
* tool's hook posts signals to the right loopback port (the emitter's
* fallback is `http://127.0.0.1:3333`). Omit to let the hook use that
* default. Callers (the /launch route) derive this from the loopback
* address the UI itself reached.
*/
sidecarUrl?: string;
/** Canonical Waggle/Hive Mind data root for launched hook processes. */
dataDir?: string;
/** Canonical collaboration identity for authenticated hook signals. */
runId?: string;
roomId?: string;
/** Ephemeral credential accepted only by WaggleDance transport routes. */
runToken?: string;
/**
* When true, launch in OBSERVED mode (piped stdio) so stdout/stderr can be
* streamed to the dock. The process is tethered to the sidecar (dies on
@@ -300,24 +273,6 @@ export function launchTool(opts: LaunchOptions): LaunchResult {
if (opts.workspaceId) {
waggleEnv.WAGGLE_WORKSPACE_ID = opts.workspaceId;
}
// Self-enabling: light the SignalBus this pipeline was built to feed.
// Opt out with signalEmit:false for a silent launch.
if (opts.signalEmit !== false) {
waggleEnv.WAGGLE_SIGNAL_EMIT = '1';
}
if (opts.sidecarUrl) {
waggleEnv.WAGGLE_SIDECAR_URL = opts.sidecarUrl;
}
if (opts.dataDir) {
waggleEnv.HIVE_MIND_DATA_DIR = opts.dataDir;
}
if (opts.runId && opts.roomId && opts.runToken) {
waggleEnv.WAGGLE_RUN_ID = opts.runId;
waggleEnv.WAGGLE_ROOM_ID = opts.roomId;
waggleEnv.WAGGLE_DANCE_TEAM_ID = `room::${opts.roomId}`;
waggleEnv.WAGGLE_SENDER_ID = `run::${opts.runId}`;
waggleEnv.WAGGLE_RUN_TOKEN = opts.runToken;
}
const env = buildExternalProcessEnv(deps.baseEnv, waggleEnv, deps.platform);
// Observed mode: piped-stdio spawn that surfaces a live output handle.
// Tethered to the sidecar (not unref'd) and tracked in-memory only.

View File

@@ -69,9 +69,6 @@ describe('launchTool', () => {
id: 'claude-code',
installedPath: 'C:\\tools\\claude.exe',
workspaceId: 'ws-isolated',
runId: 'run-1',
roomId: 'room-1',
runToken: 'narrow-room-token',
deps: {
platform: 'win32',
baseEnv: {
@@ -108,13 +105,12 @@ describe('launchTool', () => {
HERMES_HOME: 'D:\\Hermes Data',
TERM: 'xterm-256color',
WAGGLE_WORKSPACE_ID: 'ws-isolated',
WAGGLE_RUN_TOKEN: 'narrow-room-token',
});
for (const name of [
'ANTHROPIC_API_KEY', 'OPENAI_API_KEY', 'OPENROUTER_API_KEY',
'GEMINI_API_KEY', 'STRIPE_SECRET_KEY', 'AWS_SECRET_ACCESS_KEY',
'DATABASE_URL', 'SSH_AUTH_SOCK', 'GIT_ASKPASS', 'HTTPS_PROXY',
'NODE_OPTIONS',
'NODE_OPTIONS', 'WAGGLE_RUN_TOKEN',
]) {
expect(calls[0].options.env?.[name], name).toBeUndefined();
}
@@ -237,69 +233,22 @@ describe('launchTool', () => {
});
});
// ── launchTool — self-enabling signal env (#1) ──────────────────────
// A dock launch should light the SignalBus it was built to feed: the
// launched tool's hive-mind hook only emits when WAGGLE_SIGNAL_EMIT is
// truthy, and it posts to WAGGLE_SIDECAR_URL. Without these the whole
// detect→launch→hook→bus→UI pipeline stays dark.
// ── launchTool — no hook or Room env ─────────────────────────────────
// The coding-agent hooks and Waggle Room are not part of the community
// edition, so a launch sets only the workspace id.
describe('launchTool — self-enabling signal env', () => {
it('injects WAGGLE_SIGNAL_EMIT=1 by default (lights the bus)', () => {
const { calls, spawnDetached } = captureSpawn();
launchTool({
id: 'claude-code',
installedPath: '/usr/local/bin/claude',
deps: { spawnDetached },
});
expect(calls[0].options.env?.WAGGLE_SIGNAL_EMIT).toBe('1');
});
it('omits WAGGLE_SIGNAL_EMIT when signalEmit:false (silent launch opt-out)', () => {
const { calls, spawnDetached } = captureSpawn();
launchTool({
id: 'claude-code',
installedPath: '/usr/local/bin/claude',
signalEmit: false,
deps: { spawnDetached },
});
expect(calls[0].options.env?.WAGGLE_SIGNAL_EMIT).toBeUndefined();
});
it('injects WAGGLE_SIDECAR_URL when provided', () => {
const { calls, spawnDetached } = captureSpawn();
launchTool({
id: 'claude-code',
installedPath: '/usr/local/bin/claude',
sidecarUrl: 'http://127.0.0.1:7777',
deps: { spawnDetached },
});
expect(calls[0].options.env?.WAGGLE_SIDECAR_URL).toBe('http://127.0.0.1:7777');
});
it('does not inject WAGGLE_SIDECAR_URL when absent', () => {
const { calls, spawnDetached } = captureSpawn();
launchTool({
id: 'claude-code',
installedPath: '/usr/local/bin/claude',
deps: { spawnDetached },
});
expect(calls[0].options.env?.WAGGLE_SIDECAR_URL).toBeUndefined();
});
it('injects signal env alongside WAGGLE_WORKSPACE_ID', () => {
describe('launchTool env', () => {
it('sets only WAGGLE_WORKSPACE_ID among Waggle variables', () => {
const { calls, spawnDetached } = captureSpawn();
launchTool({
id: 'claude-code',
installedPath: '/usr/local/bin/claude',
workspaceId: 'ws-1',
sidecarUrl: 'http://127.0.0.1:3333',
deps: { spawnDetached },
});
expect(calls[0].options.env).toMatchObject({
WAGGLE_WORKSPACE_ID: 'ws-1',
WAGGLE_SIGNAL_EMIT: '1',
WAGGLE_SIDECAR_URL: 'http://127.0.0.1:3333',
deps: { spawnDetached, baseEnv: { PATH: '/usr/bin' } },
});
const waggleVars = Object.keys(calls[0].options.env ?? {})
.filter((name) => name.startsWith('WAGGLE_') || name.startsWith('HIVE_MIND_'));
expect(waggleVars).toEqual(['WAGGLE_WORKSPACE_ID']);
});
});
@@ -403,36 +352,6 @@ describe('launchTool observe mode', () => {
});
});
describe('launchTool collaboration env', () => {
it('injects the canonical Waggle data root', () => {
const { calls, spawnDetached } = captureSpawn();
launchTool({
id: 'claude-code',
installedPath: '/usr/local/bin/claude',
dataDir: '/waggle-data',
deps: { spawnDetached },
});
expect(calls[0].options.env?.HIVE_MIND_DATA_DIR).toBe('/waggle-data');
});
it('injects only the narrow Room credential and canonical run identity', () => {
const { calls, spawnDetached } = captureSpawn();
launchTool({
id: 'claude-code', installedPath: '/usr/local/bin/claude',
runId: 'run-1', roomId: 'room-1', runToken: 'secret-run-token',
deps: { spawnDetached },
});
expect(calls[0].options.env).toMatchObject({
WAGGLE_RUN_ID: 'run-1',
WAGGLE_ROOM_ID: 'room-1',
WAGGLE_DANCE_TEAM_ID: 'room::room-1',
WAGGLE_SENDER_ID: 'run::run-1',
WAGGLE_RUN_TOKEN: 'secret-run-token',
});
expect(calls[0].options.env?.WAGGLE_SESSION_TOKEN).toBeUndefined();
});
});
describe('resolveSpawnInvocation', () => {
it('rejects unrecognized Windows batch shims instead of invoking cmd.exe', () => {
expect(() => resolveSpawnInvocation(

View File

@@ -1,4 +1,4 @@
import { createHash, randomBytes, randomUUID } from 'node:crypto';
import { randomUUID } from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import {
@@ -125,8 +125,6 @@ export class AgentRunRegistry {
private readonly persistPath: string;
private readonly runs = new Map<string, CollaborationRun>();
private readonly controls = new Map<string, RunControls>();
/** Ephemeral, narrowly-scoped credentials for external run communication. */
private readonly credentialRuns = new Map<string, string>();
private readonly listeners = new Set<RunListener>();
private events: CollaborationRunEvent[] = [];
private lastSeq = 0;
@@ -347,37 +345,6 @@ export class AgentRunRegistry {
return this.applyPatch(id, { status: 'cancelled' }, true) as CollaborationRoomRun;
}
/**
* Issue a process-local credential that can authenticate only the
* collaboration endpoints for one active worker. The raw token is never
* persisted; only its SHA-256 digest is retained in memory.
*/
issueCredential(runId: string): string {
const run = this.runs.get(runId);
if (!run || run.kind !== 'worker') throw new Error(`Worker run not found: ${runId}`);
if (!ACTIVE_STATUSES.has(run.status)) throw new Error(`Run is already ${run.status}`);
const token = randomBytes(32).toString('base64url');
this.credentialRuns.set(hashCredential(token), runId);
return token;
}
authenticateCredential(token: string): CollaborationWorkerRun | undefined {
if (typeof token !== 'string' || token.length < 32 || token.length > 200) return undefined;
const digest = hashCredential(token);
const runId = this.credentialRuns.get(digest);
if (!runId) return undefined;
const run = this.runs.get(runId);
if (!run || run.kind !== 'worker' || !ACTIVE_STATUSES.has(run.status)) {
this.credentialRuns.delete(digest);
return undefined;
}
return clone(run);
}
revokeCredential(token: string): void {
this.credentialRuns.delete(hashCredential(token));
}
reconcileExternalProcesses(alivePids: ReadonlySet<number>): number {
let interrupted = 0;
for (const run of [...this.runs.values()]) {
@@ -401,7 +368,6 @@ export class AgentRunRegistry {
close(): void {
this.controls.clear();
this.credentialRuns.clear();
this.listeners.clear();
}
@@ -452,7 +418,6 @@ export class AgentRunRegistry {
...(!current.completedAt && isTerminal(patch.status) ? { completedAt: now } : {}),
};
this.runs.set(id, next);
if (TERMINAL_STATUSES.has(next.status)) this.revokeCredentialsForRun(id);
this.record(next);
if (recomputeParent && next.kind === 'worker') this.recomputeParent(next.parentRunId);
return clone(next);
@@ -488,12 +453,6 @@ export class AgentRunRegistry {
return direct.flatMap((run) => [run, ...this.descendants(run.id)]);
}
private revokeCredentialsForRun(runId: string): void {
for (const [digest, ownerRunId] of this.credentialRuns) {
if (ownerRunId === runId) this.credentialRuns.delete(digest);
}
}
private record(run: CollaborationRun): void {
const event: CollaborationRunEvent = {
seq: ++this.lastSeq,
@@ -586,10 +545,6 @@ function uniqueNonEmpty(values: string[]): string[] {
return [...new Set(values.map((value) => value.trim()).filter(Boolean))];
}
function hashCredential(token: string): string {
return createHash('sha256').update(token).digest('hex');
}
function clone<T>(value: T): T {
return JSON.parse(JSON.stringify(value)) as T;
}

View File

@@ -1855,11 +1855,6 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
token,
server.agentState.browserCompanionCredentialHash,
),
authenticateRunToken: (token) => {
const run = agentRunRegistry.authenticateCredential(token);
if (!run) return false;
return { runId: run.id, model: run.executor.model };
},
rateLimiter: Object.keys(rateLimiterConfig).length > 0 ? rateLimiterConfig : undefined,
});

View File

@@ -12,7 +12,6 @@ import { validateOrigin } from '../cors-config.js';
import { applyProviderKeyToEnv, getProviderApiKeys } from '../provider-env.js';
import { isRemoteOllamaAlias, PROVIDER_MODEL_CATALOGS } from '../provider-model-catalog.js';
import { fetchOllamaRoutingModels } from '../model-availability.js';
import { getAuthenticatedRunToken } from '../security-middleware.js';
interface OpenAIMessage {
role: 'system' | 'user' | 'assistant' | 'tool';
@@ -466,65 +465,21 @@ function resolveProviderRoute(model: string): ProviderRoute | null {
return providerId ? { providerId, model: trimmed } : null;
}
function validateRunTokenModelScope(
/**
* While agent runs with an assigned completion model are active, the proxy
* serves only the session bearer (or the LiteLLM key).
*/
function validateActiveRunBearer(
server: FastifyInstance,
request: FastifyRequest,
requestedModel: string,
requestedRoute: ProviderRoute,
): { statusCode: number; message: string } | null {
const activeRunProxy = hasActiveRunCompletionScope(server);
if (!hasActiveRunCompletionScope(server)) return null;
const token = parseBearerToken(request.headers.authorization);
if (!token) {
return activeRunProxy
? { statusCode: 401, message: 'A Bearer credential is required while scoped agent runs are active.' }
: null;
return { statusCode: 401, message: 'A Bearer credential is required while scoped agent runs are active.' };
}
const authenticatedRun = getAuthenticatedRunToken(request);
if (authenticatedRun) {
const currentRun = server.agentRunRegistry?.authenticateCredential(token);
if (!currentRun) {
return { statusCode: 401, message: 'The authenticated run credential is no longer active.' };
}
if (authenticatedRun.runId && authenticatedRun.runId !== currentRun.id) {
return { statusCode: 401, message: 'The authenticated run credential no longer matches the active run.' };
}
return validateAssignedRunModel(
currentRun.executor.model?.trim(),
requestedModel,
requestedRoute,
);
}
const run = server.agentRunRegistry?.authenticateCredential(token);
if (!run) {
if (isSessionBearer(server, token)) return null;
return activeRunProxy
? { statusCode: 401, message: 'The supplied bearer token is not an active run credential.' }
: null;
}
const assignedModel = run.executor.model?.trim();
return validateAssignedRunModel(assignedModel, requestedModel, requestedRoute);
}
function validateAssignedRunModel(
assignedModel: string | undefined,
requestedModel: string,
requestedRoute: ProviderRoute,
): { statusCode: number; message: string } | null {
const assignedRoute = assignedModel ? resolveProviderRoute(assignedModel) : null;
if (!assignedRoute) {
return {
statusCode: 403,
message: 'This run token cannot use the model proxy because the run has no assigned completion model.',
};
}
if (!providerRoutesMatch(assignedRoute, requestedRoute)) {
return {
statusCode: 403,
message: `Requested model "${requestedModel}" is outside the assigned run model "${assignedModel}".`,
};
}
return null;
if (isSessionBearer(server, token)) return null;
return { statusCode: 401, message: 'The supplied bearer token is not accepted while scoped agent runs are active.' };
}
function parseBearerToken(authHeader: string | undefined): string | undefined {
@@ -546,14 +501,6 @@ function isSessionBearer(server: FastifyInstance, token: string): boolean {
.some((candidate) => typeof candidate === 'string' && candidate === token);
}
function providerRoutesMatch(a: ProviderRoute, b: ProviderRoute): boolean {
if (a.providerId.toLowerCase() !== b.providerId.toLowerCase()) return false;
const normalize = (route: ProviderRoute) => (
route.providerId === 'anthropic' ? mapModel(route.model) : route.model
).trim().toLowerCase();
return normalize(a) === normalize(b);
}
function completionEndpoint(baseUrl: string): string {
let normalized = baseUrl.trim().replace(/\/+$/, '');
if (normalized.endsWith('/chat/completions')) return normalized;
@@ -1084,12 +1031,7 @@ export const anthropicProxyRoutes: FastifyPluginAsync = async (server) => {
},
});
}
const runScopeViolation = validateRunTokenModelScope(
server,
request,
body.model,
route,
);
const runScopeViolation = validateActiveRunBearer(server, request);
if (runScopeViolation) {
return reply.status(runScopeViolation.statusCode).send({
error: { message: runScopeViolation.message },

View File

@@ -30,26 +30,6 @@ export function resolveLaunchArgs(
return undefined;
}
/**
* Loopback host:port → sidecar base URL; anything else → undefined.
* IPv6 loopback must be bracketed (`[::1]`) — a bare `::1` would yield
* a malformed `http://::1` URL and a conformant Host header always
* brackets IPv6 anyway, so we only accept the bracketed form.
*/
const LOOPBACK_HOST = /^(?:127\.0\.0\.1|localhost|\[::1\])(?::\d+)?$/i;
/**
* Derive the sidecar base URL to hand a launched tool's hook, from the
* loopback address the UI itself reached. Returns undefined for any
* missing / non-loopback host so a launched hook is never pointed at an
* arbitrary external origin — the emitter then falls back to its own
* `127.0.0.1:3333` default. Exported for unit testing.
*/
export function loopbackSidecarUrl(host: string | undefined): string | undefined {
if (!host || !LOOPBACK_HOST.test(host)) return undefined;
return `http://${host}`;
}
declare module 'fastify' {
interface FastifyInstance {
/** AI-OS Phase 4 — in-memory tracker of processes spawned via /api/tools/launch. */
@@ -124,7 +104,6 @@ const toolsRoutesImpl: FastifyPluginAsync = async (server) => {
}
interface InteractiveRunBinding {
runId: string;
token?: string;
unregister: () => void;
cancelRequested: boolean;
}
@@ -193,7 +172,6 @@ const toolsRoutesImpl: FastifyPluginAsync = async (server) => {
if (interactiveRuns.get(pid) !== binding) return;
interactiveRuns.delete(pid);
binding.unregister();
if (binding.token) server.agentRunRegistry.revokeCredential(binding.token);
releaseWorkspaceLeaseForPid(pid);
};
const settleInteractiveRun = (
@@ -220,7 +198,6 @@ const toolsRoutesImpl: FastifyPluginAsync = async (server) => {
const bindInteractiveRun = (
pid: number,
runId: string,
token?: string,
): InteractiveRunBinding => {
const existing = interactiveRuns.get(pid);
if (existing?.runId === runId) return existing;
@@ -240,7 +217,6 @@ const toolsRoutesImpl: FastifyPluginAsync = async (server) => {
}
const binding: InteractiveRunBinding = {
runId,
...(token ? { token } : {}),
unregister: () => {},
cancelRequested: false,
};
@@ -469,7 +445,6 @@ const toolsRoutesImpl: FastifyPluginAsync = async (server) => {
let roomId: string | undefined;
let workerId: string | undefined;
let issuedToken: string | undefined;
let launchedPid: number | undefined;
try {
const room = server.agentRunRegistry.createRoom({
@@ -491,29 +466,17 @@ const toolsRoutesImpl: FastifyPluginAsync = async (server) => {
capabilities: { cancel: true },
});
workerId = worker.id;
const runToken = server.agentRunRegistry.issueCredential(worker.id);
issuedToken = runToken;
// Self-enabling launch: turn on signal emission and tell the hook
// which loopback sidecar to post to, so a dock launch lights the
// SignalBus instead of staying dark.
const result = launchTool({
id: body.id,
installedPath,
workspaceId,
cwd: workspaceRoot,
args: resolveLaunchArgs(manifest, body),
signalEmit: true,
sidecarUrl: loopbackSidecarUrl(request.headers.host),
dataDir: server.localConfig.dataDir,
runId: worker.id,
roomId: room.id,
runToken,
observe: body.observe,
toolRegistry,
});
launchedPid = result.pid ?? undefined;
if (!result.ok) {
server.agentRunRegistry.revokeCredential(runToken);
server.agentRunRegistry.update(worker.id, {
status: 'failed',
result: { error: result.error ?? 'Tool launch failed' },
@@ -529,7 +492,7 @@ const toolsRoutesImpl: FastifyPluginAsync = async (server) => {
observed: body.observe === true,
});
attachWorkspaceLease(result.pid, reservation.root, reservation.lease);
const binding = bindInteractiveRun(result.pid, worker.id, runToken);
const binding = bindInteractiveRun(result.pid, worker.id);
server.agentRunRegistry.update(worker.id, {
status: 'running',
executor: { pid: result.pid },
@@ -551,7 +514,6 @@ const toolsRoutesImpl: FastifyPluginAsync = async (server) => {
});
}
} else {
server.agentRunRegistry.revokeCredential(runToken);
server.agentRunRegistry.update(worker.id, {
status: 'failed',
result: { error: 'Tool launch returned no process id' },
@@ -616,11 +578,6 @@ const toolsRoutesImpl: FastifyPluginAsync = async (server) => {
}
}
const retainedBinding =
launchedPid == null ? undefined : interactiveRuns.get(launchedPid);
if (issuedToken && !retainedBinding) {
server.agentRunRegistry.revokeCredential(issuedToken);
}
if (workerId) {
try {
const run = server.agentRunRegistry.get(workerId);

View File

@@ -216,22 +216,8 @@ export interface SecurityMiddlewareOpts {
sessionToken?: string;
/** Validate the persisted, scoped Browser Companion credential. */
authenticateBrowserCompanionToken?: (token: string) => boolean;
/** Validate a narrow per-run credential for the model-completion route. */
authenticateRunToken?: (token: string) => RunTokenAuthResult;
}
export interface AuthenticatedRunToken {
runId?: string;
model?: string;
}
export type RunTokenAuthResult = boolean | AuthenticatedRunToken | null | undefined;
/** OpenClaw's OpenAI-compatible client can send only a Bearer credential here. */
const RUN_TOKEN_BEARER_PATHS = new Set([
'/v1/chat/completions',
]);
const UNSAFE_WORKSPACE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
/**
@@ -253,7 +239,6 @@ const DEFAULT_WORKSPACE_MUTATION_PATHS = new Set([
]);
const resolvedChatWorkspaceIds = new WeakMap<FastifyRequest, string | null>();
const authenticatedRunTokens = new WeakMap<FastifyRequest, AuthenticatedRunToken>();
export function getResolvedChatWorkspaceId(
request: FastifyRequest,
@@ -261,12 +246,6 @@ export function getResolvedChatWorkspaceId(
return resolvedChatWorkspaceIds.get(request);
}
export function getAuthenticatedRunToken(
request: FastifyRequest,
): AuthenticatedRunToken | undefined {
return authenticatedRunTokens.get(request);
}
const STORED_CRON_OWNER_PATHS = new Set([
'/api/cron/:id',
'/api/cron/:id/trigger',
@@ -296,15 +275,6 @@ function bearerTokenFromAuth(authHeader: string | undefined): string | undefined
return match?.[1]?.trim() || undefined;
}
function runTokenAuthSnapshot(result: RunTokenAuthResult): AuthenticatedRunToken | null {
if (result === true) return {};
if (!result || typeof result !== 'object') return null;
return {
...(typeof result.runId === 'string' ? { runId: result.runId } : {}),
...(typeof result.model === 'string' ? { model: result.model } : {}),
};
}
function stringFields(
record: Record<string, unknown> | null,
fields: readonly string[],
@@ -659,16 +629,7 @@ async function securityMiddlewarePlugin(
if (browserCompanionEligible) {
browserCompanionRequests.add(request);
}
const runTokenSnapshot = request.method === 'POST'
&& RUN_TOKEN_BEARER_PATHS.has(requestPath)
&& bearerToken
? runTokenAuthSnapshot(opts.authenticateRunToken?.(bearerToken))
: null;
if (runTokenSnapshot) {
authenticatedRunTokens.set(request, runTokenSnapshot);
}
const runTokenValid = Boolean(runTokenSnapshot);
if (!isAuthExempt && !runTokenValid && !browserCompanionEligible) {
if (!isAuthExempt && !browserCompanionEligible) {
// P1b-SSE: header-less GETs on the SSE allowlist may authenticate via
// `?token=` (EventSource cannot send headers). A header, when present,
// always wins — the query path is a fallback transport, not an

View File

@@ -170,28 +170,6 @@ describe('AgentRunRegistry', () => {
await expect(registry.control(first.id, 'cancel')).rejects.toThrow(/already cancelled/);
});
it('issues ephemeral worker credentials and revokes them at terminal state', () => {
const { registry, file } = createRegistry();
const room = registry.createRoom({
workspaceIds: ['alpha'], source: 'external_tool', title: 'External', task: 'Collaborate',
});
const worker = registry.createWorker({
parentRunId: room.id, workspaceId: 'alpha', source: 'external_tool',
executor: { kind: 'external_tool', toolId: 'codex' }, title: 'Codex', task: room.task,
status: 'running',
});
const token = registry.issueCredential(worker.id);
expect(token.length).toBeGreaterThanOrEqual(32);
expect(registry.authenticateCredential(token)?.id).toBe(worker.id);
expect(registry.authenticateCredential('x'.repeat(43))).toBeUndefined();
expect(fs.readFileSync(file, 'utf8')).not.toContain(token);
registry.update(worker.id, { status: 'completed' });
expect(registry.authenticateCredential(token)).toBeUndefined();
expect(() => registry.issueCredential(room.id)).toThrow(/Worker run not found/);
});
it('marks internal work interrupted after restart and reconciles external pids separately', () => {
const { registry, file } = createRegistry();
const internalRoom = registry.createRoom({

View File

@@ -19,7 +19,7 @@ import { CostTracker, runAgentLoop } from '@waggle/agent';
import { ExecutionTraceStore, WaggleDB } from '@waggle/core';
import { AgentRunRegistry } from '../../src/local/agent-run-registry.js';
import { anthropicProxyRoutes } from '../../src/local/routes/anthropic-proxy.js';
import { securityMiddleware, type RunTokenAuthResult } from '../../src/local/security-middleware.js';
import { securityMiddleware } from '../../src/local/security-middleware.js';
import { PROVIDER_ENV_NAMES } from '../../src/local/provider-env.js';
const MODEL_SPEND_RESERVATION_HEADER = 'x-waggle-model-spend-reservation';
@@ -32,7 +32,6 @@ function createTestServer(options: {
configApiKey?: string;
dataDir?: string;
sessionToken?: string;
authenticateRunToken?: (token: string) => RunTokenAuthResult;
costTracker?: CostTracker;
traceStore?: FastifyInstance['traceStore'];
registerSpendTarget?: string;
@@ -70,10 +69,9 @@ function createTestServer(options: {
dataDir: options.dataDir ?? '/tmp/nonexistent-waggle-test',
});
if (options.sessionToken || options.authenticateRunToken) {
if (options.sessionToken) {
server.register(securityMiddleware, {
sessionToken: options.sessionToken,
authenticateRunToken: options.authenticateRunToken,
});
}
server.register(anthropicProxyRoutes);
@@ -1420,232 +1418,53 @@ describe('Anthropic Proxy Routes', () => {
costTracker.releaseReservedModelSpend(reservation);
});
it('rejects a run token completion when the requested model is outside the assigned run model', async () => {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-run-token-model-scope-'));
it('serves only the session bearer while an agent run with a model is active', async () => {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-active-run-bearer-'));
const registry = new AgentRunRegistry(path.join(dataDir, 'agent-runs.json'));
const room = registry.createRoom({
workspaceIds: ['workspace-1'],
source: 'external_tool',
title: 'OpenClaw room',
task: 'Use the assigned model only',
source: 'fleet',
title: 'Fleet room',
task: 'Answer with the assigned model',
});
const run = registry.createWorker({
registry.createWorker({
parentRunId: room.id,
workspaceId: 'workspace-1',
source: 'external_tool',
executor: { kind: 'external_tool', toolId: 'openclaw', model: 'anthropic/claude-sonnet-4-6' },
title: 'OpenClaw',
source: 'fleet',
executor: { kind: 'waggle_agent', model: 'anthropic/claude-sonnet-4-6' },
title: 'Fleet agent',
task: room.task,
status: 'running',
});
const runToken = registry.issueCredential(run.id);
server = createTestServer({
vaultApiKey: 'anthropic-key',
vaultProviders: { openai: { value: 'openai-key' } },
});
server = createTestServer({ vaultApiKey: 'anthropic-key' });
server.decorate('agentRunRegistry', registry);
server.decorate('agentState', { wsSessionToken: 'desktop-session-token' } as FastifyInstance['agentState']);
globalThis.fetch = vi.fn(async () => new Response(JSON.stringify({
content: [{ type: 'text', text: 'assigned model response' }],
content: [{ type: 'text', text: 'ok' }],
model: 'claude-sonnet-4-6',
stop_reason: 'end_turn',
usage: { input_tokens: 1, output_tokens: 2 },
}), { status: 200, headers: { 'content-type': 'application/json' } })) as unknown as typeof globalThis.fetch;
try {
const response = await server.inject({
method: 'POST',
url: '/v1/chat/completions',
headers: { authorization: `Bearer ${runToken}` },
payload: {
model: 'openai/gpt-4.1',
messages: [{ role: 'user', content: 'Use a different provider' }],
stream: false,
},
});
expect(response.statusCode).toBe(403);
expect(response.json().error.message).toContain('outside the assigned run model');
expect(globalThis.fetch).not.toHaveBeenCalled();
const sameProvider = await server.inject({
method: 'POST',
url: '/v1/chat/completions',
headers: { authorization: `Bearer ${runToken}` },
payload: {
model: 'anthropic/claude-opus-4-6',
messages: [{ role: 'user', content: 'Use a different Anthropic model' }],
stream: false,
},
});
expect(sameProvider.statusCode).toBe(403);
expect(sameProvider.json().error.message).toContain('outside the assigned run model');
expect(globalThis.fetch).not.toHaveBeenCalled();
const missingToken = await server.inject({
method: 'POST',
url: '/v1/chat/completions',
payload: {
model: 'openai/gpt-4.1',
messages: [{ role: 'user', content: 'Use a different provider without a run token' }],
stream: false,
},
});
expect(missingToken.statusCode).toBe(401);
expect(globalThis.fetch).not.toHaveBeenCalled();
const invalidToken = await server.inject({
method: 'POST',
url: '/v1/chat/completions',
headers: { authorization: 'Bearer invalid-run-token-with-enough-entropy-123' },
payload: {
model: 'openai/gpt-4.1',
messages: [{ role: 'user', content: 'Use a different provider with an invalid run token' }],
stream: false,
},
});
expect(invalidToken.statusCode).toBe(401);
expect(globalThis.fetch).not.toHaveBeenCalled();
const assigned = await server.inject({
method: 'POST',
url: '/v1/chat/completions',
headers: { authorization: `bearer ${runToken}` },
payload: {
model: 'claude-sonnet-4.6',
messages: [{ role: 'user', content: 'Use the assigned provider' }],
stream: false,
},
});
expect(assigned.statusCode).toBe(200);
expect(assigned.json().choices[0].message.content).toBe('assigned model response');
expect(vi.mocked(globalThis.fetch).mock.calls[0][0]).toBe('https://api.anthropic.com/v1/messages');
} finally {
registry.close();
fs.rmSync(dataDir, { recursive: true, force: true });
}
});
it('rejects a run token completion when the token is revoked between auth and route handling', async () => {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-run-token-revocation-race-'));
const registry = new AgentRunRegistry(path.join(dataDir, 'agent-runs.json'));
const room = registry.createRoom({
workspaceIds: ['workspace-1'],
source: 'external_tool',
title: 'OpenClaw room',
task: 'Use the assigned model only',
});
const run = registry.createWorker({
parentRunId: room.id,
workspaceId: 'workspace-1',
source: 'external_tool',
executor: { kind: 'external_tool', toolId: 'openclaw', model: 'anthropic/claude-sonnet-4-6' },
title: 'OpenClaw',
task: room.task,
});
const runToken = registry.issueCredential(run.id);
let revokedAfterMiddlewareAuth = false;
server = createTestServer({
vaultApiKey: 'anthropic-key',
sessionToken: 'desktop-session-token',
authenticateRunToken: (candidate) => {
if (candidate !== runToken) return false;
const authenticatedRun = registry.authenticateCredential(candidate);
if (!authenticatedRun) return false;
if (!revokedAfterMiddlewareAuth) {
revokedAfterMiddlewareAuth = true;
registry.revokeCredential(candidate);
}
return { runId: authenticatedRun.id, model: authenticatedRun.executor.model };
const completion = (authorization?: string) => server.inject({
method: 'POST',
url: '/v1/chat/completions',
headers: authorization ? { authorization } : {},
payload: {
model: 'claude-sonnet-4.6',
messages: [{ role: 'user', content: 'Hello' }],
stream: false,
},
});
server.decorate('agentRunRegistry', registry);
globalThis.fetch = vi.fn(async () => new Response(JSON.stringify({
content: [{ type: 'text', text: 'should not forward' }],
model: 'claude-sonnet-4-6',
stop_reason: 'end_turn',
usage: { input_tokens: 1, output_tokens: 2 },
}), { status: 200, headers: { 'content-type': 'application/json' } })) as unknown as typeof globalThis.fetch;
try {
const response = await server.inject({
method: 'POST',
url: '/v1/chat/completions',
headers: { authorization: `Bearer ${runToken}` },
payload: {
model: 'openai/gpt-4.1',
messages: [{ role: 'user', content: 'Use a different provider after token revocation' }],
stream: false,
},
});
expect(response.statusCode).toBe(401);
expect(response.json().error.message).toContain('no longer active');
const missing = await completion();
expect(missing.statusCode).toBe(401);
const foreign = await completion('Bearer run-token-with-enough-entropy-1234567890');
expect(foreign.statusCode).toBe(401);
expect(globalThis.fetch).not.toHaveBeenCalled();
} finally {
registry.close();
fs.rmSync(dataDir, { recursive: true, force: true });
}
});
it('rejects a run token completion when the assigned model changes after middleware auth', async () => {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-run-token-model-reassignment-'));
const registry = new AgentRunRegistry(path.join(dataDir, 'agent-runs.json'));
const room = registry.createRoom({
workspaceIds: ['workspace-1'],
source: 'external_tool',
title: 'OpenClaw room',
task: 'Use the currently assigned model only',
});
const run = registry.createWorker({
parentRunId: room.id,
workspaceId: 'workspace-1',
source: 'external_tool',
executor: { kind: 'external_tool', toolId: 'openclaw', model: 'anthropic/claude-sonnet-4-6' },
title: 'OpenClaw',
task: room.task,
});
const runToken = registry.issueCredential(run.id);
let reassignedAfterMiddlewareAuth = false;
server = createTestServer({
vaultApiKey: 'anthropic-key',
sessionToken: 'desktop-session-token',
authenticateRunToken: (candidate) => {
if (candidate !== runToken) return false;
const authenticatedRun = registry.authenticateCredential(candidate);
if (!authenticatedRun) return false;
if (!reassignedAfterMiddlewareAuth) {
reassignedAfterMiddlewareAuth = true;
registry.update(authenticatedRun.id, { executor: { model: 'anthropic/claude-haiku-4-5' } });
}
return { runId: authenticatedRun.id, model: authenticatedRun.executor.model };
},
});
server.decorate('agentRunRegistry', registry);
globalThis.fetch = vi.fn(async () => new Response(JSON.stringify({
content: [{ type: 'text', text: 'should not forward' }],
model: 'claude-sonnet-4-6',
stop_reason: 'end_turn',
usage: { input_tokens: 1, output_tokens: 2 },
}), { status: 200, headers: { 'content-type': 'application/json' } })) as unknown as typeof globalThis.fetch;
try {
const response = await server.inject({
method: 'POST',
url: '/v1/chat/completions',
headers: { authorization: `Bearer ${runToken}` },
payload: {
model: 'claude-sonnet-4.6',
messages: [{ role: 'user', content: 'Use the model that was assigned during middleware auth' }],
stream: false,
},
});
expect(response.statusCode).toBe(403);
expect(response.json().error.message).toContain('outside the assigned run model');
expect(globalThis.fetch).not.toHaveBeenCalled();
const session = await completion('Bearer desktop-session-token');
expect(session.statusCode, session.body).toBe(200);
} finally {
registry.close();
fs.rmSync(dataDir, { recursive: true, force: true });

View File

@@ -23,13 +23,11 @@ import {
async function createTestServer(opts?: {
rateLimiter?: { maxRequests?: number; windowMs?: number };
sessionToken?: string;
authenticateRunToken?: (token: string) => boolean;
}) {
const server = Fastify({ logger: false });
await server.register(securityMiddleware, {
rateLimiter: opts?.rateLimiter,
sessionToken: opts?.sessionToken,
authenticateRunToken: opts?.authenticateRunToken,
});
// Simple test routes
@@ -424,52 +422,21 @@ describe('Bearer Token Authentication', () => {
}
});
it('accepts a narrow run token only as a Bearer on the model completion route', async () => {
const runToken = 'run-token-with-enough-entropy-1234567890';
const server = await createTestServer({
sessionToken: TEST_TOKEN,
authenticateRunToken: (candidate) => candidate === runToken,
});
it('accepts only the session token on the model completion route (no run tokens)', async () => {
const server = await createTestServer({ sessionToken: TEST_TOKEN });
try {
const completion = await server.inject({
method: 'POST', url: '/v1/chat/completions',
headers: { authorization: `Bearer ${runToken}` },
headers: { authorization: `Bearer ${TEST_TOKEN}` },
});
expect(completion.statusCode).toBe(200);
const unrelated = await server.inject({
method: 'GET', url: '/api/test',
headers: { 'x-waggle-run-token': runToken },
});
expect(unrelated.statusCode).toBe(401);
const unrelatedBearer = await server.inject({
method: 'GET', url: '/api/test',
headers: { authorization: `Bearer ${runToken}` },
});
expect(unrelatedBearer.statusCode).toBe(401);
const wrongTransport = await server.inject({
const runTokenShaped = await server.inject({
method: 'POST', url: '/v1/chat/completions',
headers: { 'x-waggle-run-token': runToken },
headers: { authorization: 'Bearer run-token-with-enough-entropy-1234567890' },
});
expect(wrongTransport.statusCode).toBe(401);
// The WaggleDance transport no longer accepts run tokens in either form.
const danceHeader = await server.inject({
method: 'POST', url: '/api/waggle-dance/signal',
headers: { 'x-waggle-run-token': runToken },
});
expect(danceHeader.statusCode).toBe(401);
expect(danceHeader.json().code).toBe('MISSING_TOKEN');
const danceBearer = await server.inject({
method: 'POST', url: '/api/waggle-dance/signal',
headers: { authorization: `Bearer ${runToken}` },
});
expect(danceBearer.statusCode).toBe(401);
const wrongCompletion = await server.inject({
method: 'POST', url: '/v1/chat/completions',
headers: { authorization: 'Bearer wrong-run-token-with-enough-entropy-123' },
});
expect(wrongCompletion.statusCode).toBe(401);
expect(wrongCompletion.json().code).toBe('INVALID_TOKEN');
expect(runTokenShaped.statusCode).toBe(401);
expect(runTokenShaped.json().code).toBe('INVALID_TOKEN');
} finally {
await server.close();
}

View File

@@ -58,7 +58,6 @@ vi.mock('@waggle/agent', async (importOriginal) => {
import { buildLocalServer } from '../src/local/index.js';
import { injectWithAuth } from './test-utils.js';
import { detectInstalledTools, launchTool } from '@waggle/agent';
import { loopbackSidecarUrl } from '../src/local/routes/tools.js';
import { resolveWorkspaceExecutionRoot } from '../src/local/workspace-execution-root.js';
function createTmpDir(prefix: string): string {
@@ -131,10 +130,6 @@ describe('POST /api/tools/launch', () => {
id: 'claude-code',
installedPath: '/server-detected/claude-code',
workspaceId,
dataDir: tmpDir,
runId: expect.stringMatching(/^run_/),
roomId: expect.stringMatching(/^room_/),
runToken: expect.any(String),
}),
);
expect(body.roomId).toMatch(/^room_/);
@@ -168,18 +163,15 @@ describe('POST /api/tools/launch', () => {
},
});
const body = response.json() as { runId: string };
const call = vi.mocked(launchTool).mock.calls[0][0] as { runToken?: string };
expect(server.agentRunRegistry.authenticateCredential(call.runToken ?? '')?.id).toBe(body.runId);
for (const listener of exitListeners) listener(0);
expect(server.agentRunRegistry.get(body.runId)).toMatchObject({
status: 'completed', result: { summary: 'Interactive tool process exited successfully' },
});
expect(server.agentRunRegistry.authenticateCredential(call.runToken ?? '')).toBeUndefined();
});
it('passes signalEmit:true so a dock launch lights the bus (#1)', async () => {
it('passes no hook, Room or data-directory settings to the launched tool', async () => {
vi.mocked(launchTool).mockClear();
const res = await injectWithAuth(server, {
method: 'POST',
@@ -188,15 +180,9 @@ describe('POST /api/tools/launch', () => {
payload: { id: 'claude-code', installedPath: '/usr/local/bin/claude' },
});
expect(res.statusCode).toBe(202);
expect(launchTool).toHaveBeenCalledWith(
expect.objectContaining({ signalEmit: true }),
);
// sidecarUrl is derived from the loopback host fastify.inject used,
// so it is either undefined (non-loopback authority) or an
// http://<loopback> string — never a non-loopback origin.
const callArg = vi.mocked(launchTool).mock.calls[0][0] as { sidecarUrl?: string };
if (callArg.sidecarUrl !== undefined) {
expect(callArg.sidecarUrl).toMatch(/^http:\/\/(127\.0\.0\.1|localhost|\[::1\]|::1)(:\d+)?$/i);
const callArg = vi.mocked(launchTool).mock.calls[0][0] as unknown as Record<string, unknown>;
for (const removed of ['signalEmit', 'sidecarUrl', 'dataDir', 'runId', 'roomId', 'runToken']) {
expect(callArg, removed).not.toHaveProperty(removed);
}
});
@@ -929,31 +915,6 @@ describe('POST /api/tools/hooks', () => {
});
});
// ── loopbackSidecarUrl helper (#1) ──────────────────────────────────
describe('loopbackSidecarUrl', () => {
it.each([
['127.0.0.1:3333', 'http://127.0.0.1:3333'],
['localhost', 'http://localhost'],
['localhost:8080', 'http://localhost:8080'],
['[::1]:3000', 'http://[::1]:3000'],
])('maps loopback host %s → %s', (host, expected) => {
expect(loopbackSidecarUrl(host)).toBe(expected);
});
it.each([
undefined,
'',
'evil.com',
'10.0.0.5:3333',
'example.com:80',
'169.254.1.1',
'::1', // bare (unbracketed) IPv6 → rejected; would be a malformed URL
])('returns undefined for non-loopback / missing host %s', (host) => {
expect(loopbackSidecarUrl(host as string | undefined)).toBeUndefined();
});
});
// ── persistence + reconcile across sidecar restart (#2) ─────────────
describe('POST /api/tools/launch — persistence + reconcile', () => {
@@ -989,7 +950,6 @@ describe('POST /api/tools/launch — persistence + reconcile', () => {
});
expect(response.statusCode).toBe(202);
const { runId } = response.json() as { runId: string };
const runToken = (vi.mocked(launchTool).mock.calls[0][0] as { runToken: string }).runToken;
expect(fs.existsSync(path.join(tmpDir, 'launched-processes.json'))).toBe(true);
await server1.close();
server1 = undefined;
@@ -997,7 +957,6 @@ describe('POST /api/tools/launch — persistence + reconcile', () => {
server2 = await buildLocalServer({ dataDir: tmpDir });
await server2.ready();
expect(server2.agentRunRegistry.get(runId)?.status).toBe('running');
expect(server2.agentRunRegistry.authenticateCredential(runToken)).toBeUndefined();
expect(server2.toolProcessTracker?.list().some((process) => process.pid === child.pid)).toBe(true);
const launchCallsBeforeCompeting = vi.mocked(launchTool).mock.calls.length;
@@ -1146,7 +1105,6 @@ describe('POST /api/tools/launch — persistence + reconcile', () => {
payload: { id: 'claude-code', installedPath: '/x', workspaceId },
});
const { runId } = response.json() as { runId: string };
const runToken = (vi.mocked(launchTool).mock.calls[0][0] as { runToken: string }).runToken;
await server1.close();
server1 = undefined;
await stopChild(child);
@@ -1157,7 +1115,6 @@ describe('POST /api/tools/launch — persistence + reconcile', () => {
status: 'interrupted',
result: { error: 'External process was not running when Waggle restarted' },
});
expect(server2.agentRunRegistry.authenticateCredential(runToken)).toBeUndefined();
expect(server2.toolProcessTracker?.list().some((process) => process.pid === child.pid)).toBe(false);
} finally {
if (server1) await server1.close();