fix(server): send the session token on the sidecar's calls to its own proxy (UF-044)

Since the server stopped trusting loopback callers, the built-in model proxy
needs the session token like every other route, but the sidecar's own calls
to it sent none. The Models key check read the proxy's 401 as a rejected key,
so a working Anthropic key showed "Key found but not responding". Scheduled AI
tasks and loops, the dream diary narrative and the profile calls failed the
same way; the profile calls also built the port from address().toString(),
and the scheduled tasks used the configured port, which the desktop app's
port fallback can leave pointing at another Waggle server.

self-request.ts now builds the address from the bound port and adds the
session token; all these calls and command.ts use it, and the token is never
sent to Ollama. An end-to-end test runs the key check through the real
middleware and proxy with localhost trust off; it fails without the fix.

UF-045 records the persona generator, which posts to a route that does not
exist; it is left open.
This commit is contained in:
shumeiko.it
2026-10-26 01:46:29 +01:00
parent 5268881f46
commit d6217ad7c2
10 changed files with 200 additions and 34 deletions

View File

@@ -13,6 +13,7 @@ import websocket from '@fastify/websocket';
import { WaggleDB, importLegacyMindData, workspaceDataScope, type LegacyMindSource, WorkspaceManager, WaggleConfig, createEmbeddingProvider, type EmbeddingProviderConfig, type EmbeddingProviderInstance, CronStore, AwarenessLayer, VaultStore, SkillHashStore, TelemetryStore, TELEMETRY_EVENTS, ExecutionTraceStore } from '@waggle/core';
import { corsOriginAllowed } from './cors-config.js';
import { InstallAuditStore } from './install-audit.js';
import { selfBaseUrl, selfRequestHeaders } from './self-request.js';
import { getStorageProvider } from './storage/index.js';
import { isLoopbackBind, resolveBindHost } from './net-config.js';
import { isLocalRequest } from './origin-guard.js';
@@ -1550,10 +1551,10 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
}
// Use the built-in Anthropic proxy to process the prompt
const proxyUrl = `http://127.0.0.1:${fullConfig.port ?? 3333}/v1/chat/completions`;
const proxyUrl = `${selfBaseUrl(server)}/v1/chat/completions`;
const response = await fetch(proxyUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
headers: selfRequestHeaders(server),
body: JSON.stringify({
model: server.agentState.currentModel ?? 'claude-sonnet-4-6',
max_tokens: 2048,
@@ -1662,11 +1663,11 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
}
if (wsId && wsId !== '*') activateWorkspaceMind(wsId);
const loopModel = server.agentState.currentModel ?? 'claude-sonnet-4-6';
const loopProxyUrl = `http://127.0.0.1:${fullConfig.port ?? 3333}/v1/chat/completions`;
const loopProxyUrl = `${selfBaseUrl(server)}/v1/chat/completions`;
const loopChat = async (prompt: string, maxTokens = 2048): Promise<string> => {
const resp = await fetch(loopProxyUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
headers: selfRequestHeaders(server),
body: JSON.stringify({
model: loopModel,
max_tokens: maxTokens,

View File

@@ -28,6 +28,7 @@ import os from 'node:os';
import path from 'node:path';
import fs from 'node:fs';
import type { FastifyPluginAsync } from 'fastify';
import { selfBaseUrl, selfRequestHeaders } from '../self-request.js';
import type { CommandResult, Command } from '@waggle/shared';
import type { Orchestrator, LoadedSkill } from '@waggle/agent';
import { loadSkills } from '@waggle/agent';
@@ -321,25 +322,16 @@ export const commandRoutes: FastifyPluginAsync = async (server) => {
(m) => server.log.warn(m),
);
// Fast-model call via the in-process OpenAI-compatible proxy. The proxy is
// served on this server's own port and behind the same bearer auth as every
// other route, so we read the bound port from `address().port` (NOT
// `.toString()`, which is `[object Object]`) and pass the session token.
// Fast-model call via the in-process OpenAI-compatible proxy, which sits
// behind the same bearer auth as every other route (see self-request.ts).
// No key / non-200 / throw → null → graceful Tier-0 fallback.
const llm = async (systemPrompt: string, userText: string): Promise<string | null> => {
const apiKey = server.vault?.get('anthropic')?.value;
if (!apiKey) return null;
const addr = server.server.address();
const envPort = Number(process.env.WAGGLE_PORT);
const port = (addr && typeof addr === 'object' ? addr.port : undefined) ?? (Number.isFinite(envPort) ? envPort : 3333);
const token = server.agentState.wsSessionToken;
try {
const res = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, {
const res = await fetch(`${selfBaseUrl(server)}/v1/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {}),
},
headers: selfRequestHeaders(server),
body: JSON.stringify({
model: 'claude-haiku-4-5',
max_tokens: 600,

View File

@@ -10,7 +10,8 @@
* skip the LLM entirely.
*/
import type { FastifyPluginAsync } from 'fastify';
import type { FastifyInstance, FastifyPluginAsync } from 'fastify';
import { selfBaseUrl, selfRequestHeaders } from '../self-request.js';
import { createLogger } from '../logger.js';
import { isLocalRequest } from '../origin-guard.js';
import { DreamJournal, QUIET_NIGHT_SUMMARY, type DreamDay } from '../dream-journal.js';
@@ -28,7 +29,7 @@ declare module 'fastify' {
export type NarrativePolish = (day: DreamDay) => Promise<string>;
/** Build the default polish fn — one proxy call, fast tier, hard length cap. */
export function makeProxyPolish(port: number): NarrativePolish {
export function makeProxyPolish(server: FastifyInstance): NarrativePolish {
return async (day: DreamDay): Promise<string> => {
const prompt =
'You are Waggle, a personal AI with persistent memory. While the user slept, ' +
@@ -36,9 +37,9 @@ export function makeProxyPolish(port: number): NarrativePolish {
`${day.summary}\nRaw counters: ${JSON.stringify(day.events.map(e => ({ action: e.action, ...e.stats })))}\n\n` +
'Write 2-3 warm first-person sentences telling the user what you did overnight. ' +
'Mention only work reflected in the counters. No greetings, no markdown, no emoji.';
const res = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, {
const res = await fetch(`${selfBaseUrl(server)}/v1/chat/completions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
headers: selfRequestHeaders(server),
signal: AbortSignal.timeout(30_000),
body: JSON.stringify({
model: 'claude-haiku-4-5',
@@ -61,7 +62,7 @@ export interface DreamRoutesOptions {
export const dreamRoutes: FastifyPluginAsync<DreamRoutesOptions> = async (server, opts) => {
const polish = opts.polish
?? makeProxyPolish(server.localConfig?.port ?? 3333);
?? makeProxyPolish(server);
// Single-flight guard per date — a 5s-polling Home card must not stack
// duplicate LLM calls while the first one is in flight.
const polishInFlight = new Set<string>();

View File

@@ -15,6 +15,7 @@
*/
import type { FastifyPluginAsync } from 'fastify';
import { selfBaseUrl, selfRequestHeaders } from '../self-request.js';
import fs from 'node:fs';
import path from 'node:path';
import { PERSONAL_SCOPE } from '@waggle/memory-contract';
@@ -289,10 +290,10 @@ export const profileRoutes: FastifyPluginAsync = async (fastify) => {
return reply.code(503).send({ error: 'No Anthropic key — cannot analyze style' });
}
const proxyUrl = `http://127.0.0.1:${fastify.server.address()?.toString().split(':').pop() ?? '3333'}`;
const proxyUrl = selfBaseUrl(fastify);
const res = await fetch(`${proxyUrl}/v1/chat/completions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
headers: selfRequestHeaders(fastify),
body: JSON.stringify({
model: 'claude-haiku-4-5',
max_tokens: 500,
@@ -346,10 +347,10 @@ Sample text:
return reply.code(503).send({ error: 'No Anthropic key — cannot analyze brand' });
}
const proxyUrl = `http://127.0.0.1:${fastify.server.address()?.toString().split(':').pop() ?? '3333'}`;
const proxyUrl = selfBaseUrl(fastify);
const res = await fetch(`${proxyUrl}/v1/chat/completions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
headers: selfRequestHeaders(fastify),
body: JSON.stringify({
model: 'claude-haiku-4-5',
max_tokens: 500,
@@ -423,10 +424,10 @@ Brand description:
return reply.code(503).send({ error: 'No Anthropic key for research' });
}
const proxyUrl = `http://127.0.0.1:${fastify.server.address()?.toString().split(':').pop() ?? '3333'}`;
const proxyUrl = selfBaseUrl(fastify);
const res = await fetch(`${proxyUrl}/v1/chat/completions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
headers: selfRequestHeaders(fastify),
body: JSON.stringify({
model: 'claude-haiku-4-5',
max_tokens: 500,

View File

@@ -6,6 +6,7 @@ import { WaggleConfig } from '@waggle/core';
import type { AutonomyLevel } from '@waggle/agent';
import { validateBody } from '../../validate-body.js';
import { probeProviderKey, validateKeyFormat } from '../llm-key-probe.js';
import { selfBaseUrl, selfRequestHeaders } from '../self-request.js';
import { resolveExplicitRoutableModel, resolveUsableModel } from '../model-availability.js';
import { applyProviderKeyToEnv } from '../provider-env.js';
import { refreshManagedLiteLLM, type LiteLLMRefreshResult } from '../litellm-runtime-config.js';
@@ -320,14 +321,12 @@ export const settingsRoutes: FastifyPluginAsync = async (server) => {
// Endpoint selection mirrors chat.ts: Ollama models go direct to Ollama's
// OpenAI-compatible endpoint (strip the 'ollama/' prefix); everything else
// through the built-in proxy on this same sidecar (port from the address
// info, harvest.ts pattern).
// through the built-in proxy on this same sidecar, with the session token
// (UF-044). The token never goes to Ollama.
const isOllama = model.startsWith('ollama/');
const addr = server.server.address();
const port = typeof addr === 'object' && addr ? addr.port : server.localConfig.port;
const url = isOllama
? (process.env.OLLAMA_HOST?.replace(/\/+$/, '') ?? 'http://localhost:11434') + '/v1/chat/completions'
: `http://127.0.0.1:${port}/v1/chat/completions`;
: `${selfBaseUrl(server)}/v1/chat/completions`;
const sendModel = isOllama ? model.slice('ollama/'.length) : model;
const controller = new AbortController();
@@ -335,7 +334,7 @@ export const settingsRoutes: FastifyPluginAsync = async (server) => {
try {
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
headers: isOllama ? { 'Content-Type': 'application/json' } : selfRequestHeaders(server),
signal: controller.signal,
body: JSON.stringify({ model: sendModel, max_tokens: 1, messages: [{ role: 'user', content: 'hi' }] }),
});

View File

@@ -0,0 +1,25 @@
/**
* Requests the sidecar sends to its own routes: the built-in model proxy at
* /v1/chat/completions and /api/anthropic/*. The server does not trust loopback
* callers (D1), so these carry the session token like any other client. They
* target the port the server is bound to, which differs from the configured one
* when the desktop shell falls back to a free port. Resolve both when the
* request is made: the address is known only once the server listens.
*/
import type { FastifyInstance } from 'fastify';
export function selfBaseUrl(server: FastifyInstance): string {
const addr = server.server.address();
const envPort = Number(process.env.WAGGLE_PORT);
const port = (addr && typeof addr === 'object' ? addr.port : undefined)
?? (Number.isInteger(envPort) && envPort > 0 ? envPort : 3333);
return `http://127.0.0.1:${port}`;
}
export function selfRequestHeaders(server: FastifyInstance): Record<string, string> {
const token = server.agentState.wsSessionToken;
return {
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {}),
};
}