refactor(server): drop WaggleDance run tokens and the team session timeout (P1.1)

- The WaggleDance routes left the sidecar with team mode, so the
  x-waggle-run-token header no longer opens /api/waggle-dance/signal or
  /api/waggle-dance/signals. A run token still authenticates only as a
  Bearer on /v1/chat/completions (OpenClaw).
- Remove the session inactivity timeout. It switched on only in team
  mode, when CLERK_SECRET_KEY was set.
This commit is contained in:
shumeiko.it
2026-10-24 16:39:16 +02:00
parent d426440da7
commit 3d966e2aca
3 changed files with 18 additions and 354 deletions

View File

@@ -5,10 +5,7 @@
* 1. Security headers (CSP, X-Content-Type-Options, X-Frame-Options)
* 2. Per-client, per-endpoint rate limiter (sliding window, Map-based)
* with stricter limits for expensive routes (chat, vault reveal, backup, restore)
* 3. Session inactivity timeout (team mode only — when CLERK_SECRET_KEY is set)
* 4. Bearer token authentication for local server (SEC-011)
*
* Only applied to the local server — team server may have different needs.
* 3. Bearer token authentication for local server (SEC-011)
*/
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
@@ -163,76 +160,6 @@ export class RateLimiter {
}
}
// ── Session Timeout (Team Mode Only) ────────────────────────────────────
/** Routes exempt from session timeout (health + vault for re-auth) */
const TIMEOUT_EXEMPT_PATHS = ['/health', '/api/vault'];
/** Default session inactivity timeout: 30 minutes */
const DEFAULT_SESSION_TIMEOUT_MS = 30 * 60 * 1000; // 1_800_000
export class SessionTimeoutTracker {
private lastActivity = new Map<string, number>();
private timeoutMs: number;
private cleanupInterval: ReturnType<typeof setInterval> | null = null;
constructor(timeoutMs?: number) {
this.timeoutMs = timeoutMs ?? (parseInt(process.env.WAGGLE_SESSION_TIMEOUT_MS ?? '', 10) || DEFAULT_SESSION_TIMEOUT_MS);
// Cleanup stale entries every 2x timeout to prevent memory leak
const cleanupPeriod = this.timeoutMs * 2;
this.cleanupInterval = setInterval(() => this.cleanup(), cleanupPeriod);
if (this.cleanupInterval.unref) {
this.cleanupInterval.unref();
}
}
/** Get the configured timeout duration in milliseconds. */
getTimeoutMs(): number {
return this.timeoutMs;
}
/**
* Check if the session for the given IP is expired.
* Returns true if expired (last activity was more than timeoutMs ago).
* Updates last activity timestamp on every call (resets timer).
*/
check(ip: string): boolean {
const now = Date.now();
const last = this.lastActivity.get(ip);
if (last !== undefined && (now - last) > this.timeoutMs) {
// Expired — remove the entry so re-auth starts fresh
this.lastActivity.delete(ip);
return true; // expired
}
// Reset timer on every request
this.lastActivity.set(ip, now);
return false; // not expired
}
/** Remove entries older than 2x the timeout to prevent memory leak. */
private cleanup(): void {
const now = Date.now();
const maxAge = this.timeoutMs * 2;
for (const [ip, lastTime] of this.lastActivity) {
if (now - lastTime > maxAge) {
this.lastActivity.delete(ip);
}
}
}
/** Stop the cleanup interval (for graceful shutdown). */
destroy(): void {
if (this.cleanupInterval) {
clearInterval(this.cleanupInterval);
this.cleanupInterval = null;
}
this.lastActivity.clear();
}
}
// ── Auth Token (Local Server) ────────────────────────────────────────────
/**
@@ -289,7 +216,7 @@ export interface SecurityMiddlewareOpts {
sessionToken?: string;
/** Validate the persisted, scoped Browser Companion credential. */
authenticateBrowserCompanionToken?: (token: string) => boolean;
/** Validate a narrow per-run credential for WaggleDance and one model-completion route. */
/** Validate a narrow per-run credential for the model-completion route. */
authenticateRunToken?: (token: string) => RunTokenAuthResult;
}
@@ -300,11 +227,6 @@ export interface AuthenticatedRunToken {
export type RunTokenAuthResult = boolean | AuthenticatedRunToken | null | undefined;
const RUN_TOKEN_METHODS = new Map<string, string>([
['/api/waggle-dance/signal', 'POST'],
['/api/waggle-dance/signals', 'GET'],
]);
/** OpenClaw's OpenAI-compatible client can send only a Bearer credential here. */
const RUN_TOKEN_BEARER_PATHS = new Set([
'/v1/chat/completions',
@@ -688,17 +610,12 @@ async function securityMiddlewarePlugin(
// Expose the rate limiter on the fastify instance for test access (e.g., reset between tests)
fastify.decorate('rateLimiter', limiter);
// Session timeout — only enabled in team mode (when CLERK_SECRET_KEY is set)
const isTeamMode = !!process.env.CLERK_SECRET_KEY;
const sessionTimeout = isTeamMode ? new SessionTimeoutTracker() : null;
// Clean up limiter and session timeout on server close
// Clean up the limiter on server close
fastify.addHook('onClose', async () => {
limiter.destroy();
sessionTimeout?.destroy();
});
// Add security headers + bearer auth + rate limiting + session timeout to every response
// Add security headers + bearer auth + rate limiting to every response
fastify.addHook('onRequest', async (request: FastifyRequest, reply: FastifyReply) => {
// ── Security headers ──
for (const [header, value] of Object.entries(SECURITY_HEADERS)) {
@@ -735,8 +652,6 @@ async function securityMiddlewarePlugin(
AUTH_EXEMPT_PATHS.some(p => requestPath === p) ||
isNonApiGet ||
(trustLocalhost && isLocalhost);
const rawRunToken = request.headers['x-waggle-run-token'];
const runToken = typeof rawRunToken === 'string' ? rawRunToken : undefined;
const authHeader = request.headers.authorization;
const bearerToken = bearerTokenFromAuth(authHeader);
const browserCompanionCredentialValid = typeof bearerToken === 'string'
@@ -749,21 +664,15 @@ async function securityMiddlewarePlugin(
if (browserCompanionEligible) {
browserCompanionRequests.add(request);
}
const runTokenEligible = RUN_TOKEN_METHODS.get(requestPath) === request.method;
const headerRunTokenSnapshot = runTokenEligible && runToken
? runTokenAuthSnapshot(opts.authenticateRunToken?.(runToken))
: null;
const bearerRunTokenSnapshot = request.method === 'POST'
const runTokenSnapshot = request.method === 'POST'
&& RUN_TOKEN_BEARER_PATHS.has(requestPath)
&& bearerToken
? runTokenAuthSnapshot(opts.authenticateRunToken?.(bearerToken))
: null;
if (headerRunTokenSnapshot || bearerRunTokenSnapshot) {
authenticatedRunTokens.set(request, headerRunTokenSnapshot ?? bearerRunTokenSnapshot!);
if (runTokenSnapshot) {
authenticatedRunTokens.set(request, runTokenSnapshot);
}
const headerRunTokenValid = Boolean(headerRunTokenSnapshot);
const bearerRunTokenValid = Boolean(bearerRunTokenSnapshot);
const runTokenValid = headerRunTokenValid || bearerRunTokenValid;
const runTokenValid = Boolean(runTokenSnapshot);
if (!isAuthExempt && !runTokenValid && !browserCompanionEligible) {
// P1b-SSE: header-less GETs on the SSE allowlist may authenticate via
// `?token=` (EventSource cannot send headers). A header, when present,
@@ -778,10 +687,7 @@ async function securityMiddlewarePlugin(
}
} else {
if (!authHeader) {
return reply.code(401).send({
error: 'Unauthorized',
code: runToken ? 'INVALID_TOKEN' : 'MISSING_TOKEN',
});
return reply.code(401).send({ error: 'Unauthorized', code: 'MISSING_TOKEN' });
}
const token = bearerTokenFromAuth(authHeader) ?? null;
if (token !== sessionToken) {
@@ -791,22 +697,6 @@ async function securityMiddlewarePlugin(
}
}
// ── Session timeout (team mode only) ──
if (sessionTimeout) {
const isExempt = TIMEOUT_EXEMPT_PATHS.some(p => requestPath.startsWith(p));
if (!isExempt) {
const clientIp = request.ip || '127.0.0.1';
const expired = sessionTimeout.check(clientIp);
if (expired) {
return reply.code(401).send({
error: 'Session expired',
code: 'SESSION_TIMEOUT',
});
}
}
}
// ── Rate limiting (CQ-008: per-client keying + per-endpoint limits) ──
// Key: clientIP:method route (e.g., "127.0.0.1:POST /api/vault/:name/reveal")
const clientIp = request.ip || '127.0.0.1';

View File

@@ -48,18 +48,10 @@ async function createTestServer(opts?: {
server.post('/api/backup', async () => {
return { ok: true };
});
// Stands in for the WaggleDance transport route that left with team mode (ADR-0003).
server.post('/api/waggle-dance/signal', async () => {
return { ok: true };
});
server.get('/api/waggle-dance/signal', async () => {
return { ok: true };
});
server.get('/api/waggle-dance/signals', async () => {
return { ok: true };
});
server.post('/api/waggle-dance/signals', async () => {
return { ok: true };
});
server.post('/v1/chat/completions', async () => {
return { ok: true };
});
@@ -432,24 +424,13 @@ describe('Bearer Token Authentication', () => {
}
});
it('accepts a narrow run token only on WaggleDance transport and model completion routes', async () => {
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,
});
try {
const send = await server.inject({
method: 'POST', url: '/api/waggle-dance/signal',
headers: { 'x-waggle-run-token': runToken },
});
expect(send.statusCode).toBe(200);
const receive = await server.inject({
method: 'GET', url: '/api/waggle-dance/signals',
headers: { 'x-waggle-run-token': runToken },
});
expect(receive.statusCode).toBe(200);
const completion = await server.inject({
method: 'POST', url: '/v1/chat/completions',
headers: { authorization: `Bearer ${runToken}` },
@@ -471,27 +452,18 @@ describe('Bearer Token Authentication', () => {
headers: { 'x-waggle-run-token': runToken },
});
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 wrongSendMethod = await server.inject({
method: 'GET', url: '/api/waggle-dance/signal',
headers: { 'x-waggle-run-token': runToken },
});
expect(wrongSendMethod.statusCode).toBe(401);
const wrongReceiveMethod = await server.inject({
method: 'POST', url: '/api/waggle-dance/signals',
headers: { 'x-waggle-run-token': runToken },
});
expect(wrongReceiveMethod.statusCode).toBe(401);
const wrong = await server.inject({
method: 'POST', url: '/api/waggle-dance/signal',
headers: { 'x-waggle-run-token': 'wrong-run-token-with-enough-entropy-123' },
});
expect(wrong.statusCode).toBe(401);
expect(wrong.json().code).toBe('INVALID_TOKEN');
const wrongCompletion = await server.inject({
method: 'POST', url: '/v1/chat/completions',
headers: { authorization: 'Bearer wrong-run-token-with-enough-entropy-123' },

View File

@@ -1,198 +0,0 @@
/**
* Session Timeout Middleware Tests
*
* Verifies:
* - SessionTimeoutTracker returns expired after inactivity
* - Timer resets on activity
* - Disabled in solo mode (no CLERK_SECRET_KEY)
* - Exempt paths (/health, /api/vault) bypass timeout
* - Cleanup prevents memory leak
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { SessionTimeoutTracker } from '../../src/local/security-middleware.js';
describe('SessionTimeoutTracker', () => {
let tracker: SessionTimeoutTracker;
afterEach(() => {
tracker?.destroy();
});
it('does not expire on first request', () => {
tracker = new SessionTimeoutTracker(30_000); // 30 seconds for testing
const expired = tracker.check('192.168.1.1');
expect(expired).toBe(false);
});
it('does not expire when activity is within timeout', () => {
tracker = new SessionTimeoutTracker(30_000);
tracker.check('192.168.1.1');
// Immediately check again — should not be expired
const expired = tracker.check('192.168.1.1');
expect(expired).toBe(false);
});
it('expires after inactivity exceeds timeout', () => {
tracker = new SessionTimeoutTracker(100); // 100ms timeout for testing
// First request — sets last activity
tracker.check('192.168.1.1');
// Simulate time passing beyond the timeout
vi.useFakeTimers();
vi.advanceTimersByTime(150); // 150ms > 100ms timeout
const expired = tracker.check('192.168.1.1');
expect(expired).toBe(true);
vi.useRealTimers();
});
it('resets timer on every request', () => {
tracker = new SessionTimeoutTracker(200); // 200ms timeout
vi.useFakeTimers();
// First request
tracker.check('192.168.1.1');
// 100ms later — still within timeout
vi.advanceTimersByTime(100);
let expired = tracker.check('192.168.1.1');
expect(expired).toBe(false);
// Another 100ms — still within timeout because timer was reset
vi.advanceTimersByTime(100);
expired = tracker.check('192.168.1.1');
expect(expired).toBe(false);
// 250ms without any request — should expire
vi.advanceTimersByTime(250);
expired = tracker.check('192.168.1.1');
expect(expired).toBe(true);
vi.useRealTimers();
});
it('tracks different IPs independently', () => {
tracker = new SessionTimeoutTracker(100);
vi.useFakeTimers();
// Both IPs make a request
tracker.check('192.168.1.1');
tracker.check('192.168.1.2');
// 50ms later, only IP1 makes another request
vi.advanceTimersByTime(50);
tracker.check('192.168.1.1');
// 60ms more — IP2's last activity was 110ms ago (expired), IP1's was 60ms ago (not expired)
vi.advanceTimersByTime(60);
const ip1Expired = tracker.check('192.168.1.1');
expect(ip1Expired).toBe(false);
const ip2Expired = tracker.check('192.168.1.2');
expect(ip2Expired).toBe(true);
vi.useRealTimers();
});
it('allows fresh request after expiration', () => {
tracker = new SessionTimeoutTracker(100);
vi.useFakeTimers();
tracker.check('192.168.1.1');
// Expire
vi.advanceTimersByTime(150);
const expired = tracker.check('192.168.1.1');
expect(expired).toBe(true);
// Next request should succeed (entry was cleared on expiration)
const freshRequest = tracker.check('192.168.1.1');
expect(freshRequest).toBe(false);
vi.useRealTimers();
});
it('returns configured timeout value', () => {
tracker = new SessionTimeoutTracker(45_000);
expect(tracker.getTimeoutMs()).toBe(45_000);
});
it('defaults to 30 minutes when no timeout specified', () => {
// Clear env var to ensure default
const original = process.env.WAGGLE_SESSION_TIMEOUT_MS;
delete process.env.WAGGLE_SESSION_TIMEOUT_MS;
tracker = new SessionTimeoutTracker();
expect(tracker.getTimeoutMs()).toBe(30 * 60 * 1000);
process.env.WAGGLE_SESSION_TIMEOUT_MS = original;
});
it('reads timeout from WAGGLE_SESSION_TIMEOUT_MS env var', () => {
const original = process.env.WAGGLE_SESSION_TIMEOUT_MS;
process.env.WAGGLE_SESSION_TIMEOUT_MS = '60000';
tracker = new SessionTimeoutTracker();
expect(tracker.getTimeoutMs()).toBe(60_000);
process.env.WAGGLE_SESSION_TIMEOUT_MS = original;
});
it('destroy clears all state', () => {
tracker = new SessionTimeoutTracker(30_000);
tracker.check('192.168.1.1');
tracker.check('192.168.1.2');
tracker.destroy();
// After destroy, a new check should work (fresh state)
// We verify destroy doesn't throw and a new tracker works
const newTracker = new SessionTimeoutTracker(30_000);
const expired = newTracker.check('192.168.1.1');
expect(expired).toBe(false);
newTracker.destroy();
});
});
describe('Session timeout in solo vs team mode', () => {
it('session timeout is only enabled when CLERK_SECRET_KEY is set', () => {
// This test verifies the design contract:
// The securityMiddlewarePlugin checks `process.env.CLERK_SECRET_KEY`
// and only creates a SessionTimeoutTracker when it's present.
//
// In solo mode (no CLERK_SECRET_KEY), session timeout is null/disabled.
const original = process.env.CLERK_SECRET_KEY;
delete process.env.CLERK_SECRET_KEY;
const isTeamMode = !!process.env.CLERK_SECRET_KEY;
expect(isTeamMode).toBe(false);
// Restore for other tests
if (original) process.env.CLERK_SECRET_KEY = original;
});
it('exempt paths are correctly defined', () => {
// Verify the exempt path patterns match the spec
const TIMEOUT_EXEMPT_PATHS = ['/health', '/api/vault'];
// /health should be exempt
expect(TIMEOUT_EXEMPT_PATHS.some(p => '/health'.startsWith(p))).toBe(true);
// /api/vault/* should be exempt
expect(TIMEOUT_EXEMPT_PATHS.some(p => '/api/vault/my-secret/reveal'.startsWith(p))).toBe(true);
// /api/chat should NOT be exempt
expect(TIMEOUT_EXEMPT_PATHS.some(p => '/api/chat'.startsWith(p))).toBe(false);
// /api/feedback/stats should NOT be exempt
expect(TIMEOUT_EXEMPT_PATHS.some(p => '/api/feedback/stats'.startsWith(p))).toBe(false);
});
});