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';