diff --git a/server/src/__tests__/cloud-trial-inference.test.ts b/server/src/__tests__/cloud-trial-inference.test.ts index db9cb141590..3f66d72c106 100644 --- a/server/src/__tests__/cloud-trial-inference.test.ts +++ b/server/src/__tests__/cloud-trial-inference.test.ts @@ -708,4 +708,132 @@ describe("cloud-trial-inference", () => { }), ).rejects.toBeInstanceOf(CloudTrialWorkRequiresModelError); }); + + it("keeps signed starter proxy tokens valid across warm session reuse and restarts, while failing closed on tampering or revocation", async () => { + const db = fakeDbWithFlag(true); + const sharedEnv = { + PAPERCLIP_ONBOARDING_VARIANT: "free_inference_1", + PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN: "stable-tenant-secret-across-restarts", + PAPERCLIP_CLOUD_TRIAL_OPENROUTER_API_KEY: "sk-or-v1-warm-session-secret", + }; + const mockFetch: typeof fetch = async (input) => { + const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + if (url.endsWith("/key")) { + return new Response(JSON.stringify({ data: { usage: 0.02, limit: 1.0 } }), { + status: 200, + headers: { "content-type": "application/json" }, + }); + } + return new Response( + JSON.stringify({ + id: "chatcmpl-warm", + choices: [{ message: { role: "assistant", content: "Warm turn reply!" } }], + }), + { status: 200, headers: { "content-type": "application/json" } }, + ); + }; + + const controller1 = createCloudTrialInferenceController({ env: sharedEnv, fetchImpl: mockFetch }); + const app1 = express(); + app1.use("/api/internal/cloud-inference", cloudInferenceInternalProxyRoutes(controller1)); + const proxy1 = await listenExpress(app1); + const controller2 = createCloudTrialInferenceController({ env: sharedEnv, fetchImpl: mockFetch }); + const app2 = express(); + app2.use("/api/internal/cloud-inference", cloudInferenceInternalProxyRoutes(controller2)); + const proxy2 = await listenExpress(app2); + try { + // Run 1 prepares runtime and completes cleanup() + const run1 = await controller1.prepareCloudTrialRuntime(db, { + companyId: "comp-warm", + agentId: "agent-warm", + runId: "run-1", + model: "openrouter/openai/gpt-6-luna", + }); + const token1 = run1.env.PAPERCLIP_OPENROUTER_PROXY_TOKEN!; + expect(token1.startsWith("pctrial_v1.")).toBe(true); + await run1.cleanup(); + + // Warm session turn 2 reuses run 1's token AFTER run 1 cleanup() -> succeeds on attempt #1 + const warmTurnRes = await fetch(`${proxy1.baseUrl}/api/internal/cloud-inference/v1/chat/completions`, { + method: "POST", + headers: { authorization: `Bearer ${token1}`, "content-type": "application/json" }, + body: JSON.stringify({ model: "openai/gpt-6-luna", messages: [{ role: "user", content: "2+2?" }] }), + }); + expect(warmTurnRes.status).toBe(200); + + // Consecutive prepareCloudTrialRuntime for the same agent yields the exact same stable token + const run2 = await controller1.prepareCloudTrialRuntime(db, { + companyId: "comp-warm", + agentId: "agent-warm", + runId: "run-2", + model: "openrouter/openai/gpt-6-luna", + }); + expect(run2.env.PAPERCLIP_OPENROUTER_PROXY_TOKEN).toBe(token1); + await run2.cleanup(); + + // Fresh controller (simulating server restart / sleep-wake) still accepts the signed warm token + const afterRestartRes = await fetch(`${proxy2.baseUrl}/api/internal/cloud-inference/v1/chat/completions`, { + method: "POST", + headers: { authorization: `Bearer ${token1}`, "content-type": "application/json" }, + body: JSON.stringify({ model: "openai/gpt-6-luna", messages: [{ role: "user", content: "still warm?" }] }), + }); + expect(afterRestartRes.status).toBe(200); + + // Tampered token fails closed with 401 + const tamperedRes = await fetch(`${proxy2.baseUrl}/api/internal/cloud-inference/v1/chat/completions`, { + method: "POST", + headers: { authorization: `Bearer ${token1}x`, "content-type": "application/json" }, + body: JSON.stringify({ model: "openai/gpt-6-luna", messages: [] }), + }); + expect(tamperedRes.status).toBe(401); + + // Partial migration revokes ONLY the migrated agent, leaving sibling trial agents working + const siblingRun = await controller2.prepareCloudTrialRuntime(db, { + companyId: "comp-warm", + agentId: "agent-sibling", + runId: "run-sibling", + model: "openrouter/openai/gpt-6-luna", + }); + const siblingToken = siblingRun.env.PAPERCLIP_OPENROUTER_PROXY_TOKEN!; + controller2.revokeAgentTokens("comp-warm", ["agent-warm"]); + const revokedRes = await fetch(`${proxy2.baseUrl}/api/internal/cloud-inference/v1/chat/completions`, { + method: "POST", + headers: { authorization: `Bearer ${token1}`, "content-type": "application/json" }, + body: JSON.stringify({ model: "openai/gpt-6-luna", messages: [] }), + }); + expect(revokedRes.status).toBe(401); + const siblingRes = await fetch(`${proxy2.baseUrl}/api/internal/cloud-inference/v1/chat/completions`, { + method: "POST", + headers: { authorization: `Bearer ${siblingToken}`, "content-type": "application/json" }, + body: JSON.stringify({ model: "openai/gpt-6-luna", messages: [{ role: "user", content: "sibling ok?" }] }), + }); + expect(siblingRes.status).toBe(200); + await siblingRun.cleanup(); + + // Changing PAPERCLIP_CLOUD_TRIAL_MODEL invalidates tokens signed for the old model (403) + const rotatedController = createCloudTrialInferenceController({ + env: { ...sharedEnv, PAPERCLIP_CLOUD_TRIAL_MODEL: "openrouter/openai/gpt-6-new" }, + fetchImpl: mockFetch, + }); + const rotatedApp = express(); + rotatedApp.use("/api/internal/cloud-inference", cloudInferenceInternalProxyRoutes(rotatedController)); + const rotatedProxy = await listenExpress(rotatedApp); + try { + const staleModelRes = await fetch( + `${rotatedProxy.baseUrl}/api/internal/cloud-inference/v1/chat/completions`, + { + method: "POST", + headers: { authorization: `Bearer ${siblingToken}`, "content-type": "application/json" }, + body: JSON.stringify({ model: "openai/gpt-6-luna", messages: [] }), + }, + ); + expect(staleModelRes.status).toBe(403); + } finally { + await rotatedProxy.close(); + } + } finally { + await proxy1.close(); + await proxy2.close(); + } + }); }); diff --git a/server/src/__tests__/cloud-trial-proxy-middleware-order.test.ts b/server/src/__tests__/cloud-trial-proxy-middleware-order.test.ts index 3622bece39d..1d034964a80 100644 --- a/server/src/__tests__/cloud-trial-proxy-middleware-order.test.ts +++ b/server/src/__tests__/cloud-trial-proxy-middleware-order.test.ts @@ -4,7 +4,8 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { randomUUID } from "node:crypto"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import { companies, createDb } from "@paperclipai/db"; +import { eq } from "drizzle-orm"; +import { agents, companies, createDb } from "@paperclipai/db"; import { createApp } from "../app.js"; import { getDefaultCloudTrialInferenceController } from "../services/cloud-trial-inference.js"; import { instanceSettingsService } from "../services/instance-settings.js"; @@ -83,11 +84,19 @@ describePostgres("cloud inference internal proxy middleware order", () => { it("mounts /api/internal/cloud-inference before actorMiddleware so pctrial_ Bearer tokens are not rejected as agent tokens", async () => { await instanceSettingsService(db).updateExperimental({ enableCloudTrialInference: true }); const companyId = randomUUID(); + const agentId = randomUUID(); await db.insert(companies).values({ id: companyId, name: "Proxy Order Co", issuePrefix: "PO", }); + await db.insert(agents).values({ + id: agentId, + companyId, + name: "Starter Agent", + adapterType: "paperclip_runner", + runtimeConfig: { cloudTrialInference: true }, + }); const app: App = await createApp(db, { uiMode: "none", @@ -127,7 +136,7 @@ describePostgres("cloud inference internal proxy middleware order", () => { // 2. Valid active pctrial_ token proxies cleanly to upstream OpenRouter with server-held key const runtime = await getDefaultCloudTrialInferenceController().prepareCloudTrialRuntime(db, { companyId, - agentId: randomUUID(), + agentId, runId: randomUUID(), model: "openrouter/openai/gpt-6-luna", }); @@ -149,6 +158,21 @@ describePostgres("cloud inference internal proxy middleware order", () => { }; expect(okBody.choices[0]?.message.content).toBe("Hello from starter proxy!"); expect(seenUpstreamAuth).toBe("Bearer sk-or-v1-middleware-order-secret"); + + // 3. Once the agent is migrated off cloudTrialInference in DB, the old signed token fails closed (401) + await db.update(agents).set({ runtimeConfig: {} }).where(eq(agents.id, agentId)); + const migratedRes = await fetch(`${baseUrl}/api/internal/cloud-inference/v1/chat/completions`, { + method: "POST", + headers: { + authorization: `Bearer ${runtime.env.PAPERCLIP_OPENROUTER_PROXY_TOKEN}`, + "content-type": "application/json", + }, + body: JSON.stringify({ + model: "openai/gpt-6-luna", + messages: [{ role: "user", content: "After migration" }], + }), + }); + expect(migratedRes.status).toBe(401); } finally { await runtime.cleanup(); } diff --git a/server/src/app.ts b/server/src/app.ts index bb0e96bf606..35baecddfd5 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -682,7 +682,7 @@ export async function createApp( void instanceSettingsService(db) .getExperimental() .catch(() => {}); - app.use("/api/internal/cloud-inference", cloudInferenceInternalProxyRoutes(cloudTrialInferenceController)); + app.use("/api/internal/cloud-inference", cloudInferenceInternalProxyRoutes(cloudTrialInferenceController, db)); app.use( actorMiddleware(db, { deploymentMode: opts.deploymentMode, diff --git a/server/src/routes/cloud-inference.ts b/server/src/routes/cloud-inference.ts index b21b0c6f454..77bf4c88d4d 100644 --- a/server/src/routes/cloud-inference.ts +++ b/server/src/routes/cloud-inference.ts @@ -20,13 +20,14 @@ import { assertBoard, assertCompanyAccess, getActorInfo } from "./authz.js"; */ export function cloudInferenceInternalProxyRoutes( controller: CloudTrialInferenceController = getDefaultCloudTrialInferenceController(), + db?: Db, ) { const router = Router(); router.all("/v1/*subpath", async (req, res) => { const rawSubpath = (req.params as Record).subpath; const subpath = Array.isArray(rawSubpath) ? rawSubpath.join("/") : rawSubpath ?? ""; - await controller.proxyOpenRouterRequest(req, res, subpath); + await controller.proxyOpenRouterRequest(req, res, subpath, db); }); return router; diff --git a/server/src/services/cloud-trial-inference.ts b/server/src/services/cloud-trial-inference.ts index 42a013c93fc..1777bc5fcca 100644 --- a/server/src/services/cloud-trial-inference.ts +++ b/server/src/services/cloud-trial-inference.ts @@ -85,12 +85,20 @@ export function createCloudTrialInferenceController(opts: CloudTrialInferenceOpt companyId: string, options: { refreshUsage?: boolean; actor?: AuthorizationActor } = {}, ) => getCompanyCloudTrialStatus(db, companyId, keyStore, options), - migrateTrialAgents: ( + migrateTrialAgents: async ( db: Db, companyId: string, input: MigrateCloudTrialAgentsInput, actor: CloudTrialMigrationActor, - ) => migrateCloudTrialAgents(db, companyId, input, actor, keyStore), + ) => { + const result = await migrateCloudTrialAgents(db, companyId, input, actor, keyStore); + const migratedAgentIds = result.agents.map((a) => a.agentId); + if (migratedAgentIds.length > 0) { + proxy.revokeAgentTokens(companyId, migratedAgentIds); + } + return result; + }, + revokeAgentTokens: proxy.revokeAgentTokens, markExhausted: keyStore.markExhausted, probeOpenRouterUsage: keyStore.probeOpenRouterUsage, _resetForTests: () => { diff --git a/server/src/services/cloud-trial-proxy.ts b/server/src/services/cloud-trial-proxy.ts index fd7de51fc5f..1d77c549f67 100644 --- a/server/src/services/cloud-trial-proxy.ts +++ b/server/src/services/cloud-trial-proxy.ts @@ -1,12 +1,14 @@ -import { randomBytes, timingSafeEqual } from "node:crypto"; +import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto"; import type { IncomingMessage, ServerResponse } from "node:http"; import { Readable } from "node:stream"; import { pipeline } from "node:stream/promises"; import type { ReadableStream as NodeReadableStream } from "node:stream/web"; -import type { Db } from "@paperclipai/db"; +import { and, eq, ne } from "drizzle-orm"; +import { agents, type Db } from "@paperclipai/db"; import { CLOUD_TRIAL_EXHAUSTED_ERROR_CODE, CLOUD_TRIAL_WORK_REQUIRES_MODEL_ERROR_CODE, + isAgentUsingCloudTrialInference, type AiConnectionMetadata, } from "@paperclipai/shared"; import { OPENROUTER_ATTRIBUTION_HEADERS } from "@paperclipai/shared/openrouter-attribution"; @@ -27,6 +29,7 @@ import { const PROXY_REQUEST_TIMEOUT_MS = 180_000; const MAX_PROXY_REQUEST_BYTES = 16 * 1024 * 1024; const RUN_TOKEN_PREFIX = "pctrial_"; +const SIGNED_TOKEN_PREFIX = "pctrial_v1."; interface RunProxyTokenRecord { token: string; @@ -61,30 +64,106 @@ function looksLikeOpenRouterLimitExhausted(status: number, bodyText: string): bo return false; } +function deriveProxyTokenSigningKey(env: CloudTrialKeyStore["env"]): Buffer { + const seed = + env.PAPERCLIP_CLOUD_CONNECTOR_SIGN_PRIVATE_KEY?.trim() || + env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN?.trim() || + env.PAPERCLIP_AGENT_JWT_SECRET?.trim() || + env.BETTER_AUTH_SECRET?.trim(); + if (seed) { + return createHash("sha256") + .update("paperclip-cloud-trial-proxy-token-v1:") + .update(seed) + .digest(); + } + return randomBytes(32); +} + /** - * Per-run OpenRouter reverse proxy for starter-trial runs. + * OpenRouter reverse proxy for starter-trial runs. * - * Ephemeral tokens live in this single-replica stack process for the lifetime - * of the active run (sliding idle TTL refreshed on every proxied request, and - * revoked immediately on run exit or budget exhaustion). + * Issues a stable, HMAC-signed per-(companyId, agentId, allowedModel) proxy + * token so warm OpenCode sessions reused across consecutive turns (or across + * stack restarts / sleep-wake) keep authenticating through `/api/internal/cloud-inference/v1` + * without failing on a deleted single-run token. Tokens fail closed immediately + * on `work_requires_model`, `$1` budget exhaustion, wrong model, or migration. */ export function createCloudTrialProxy(keyStore: CloudTrialKeyStore) { const { env, fetchImpl } = keyStore; + const signingKey = deriveProxyTokenSigningKey(env); const activeRunTokens = new Map(); + const revokedAgents = new Set(); + + const agentRevocationKey = (companyId: string, agentId: string) => `${companyId}:${agentId}`; keyStore.setOnExhausted(() => { activeRunTokens.clear(); }); + function signProxyToken(companyId: string, agentId: string, allowedModel: string): string { + const payloadB64 = Buffer.from( + JSON.stringify({ c: companyId, a: agentId, m: allowedModel }), + "utf8", + ).toString("base64url"); + const sigB64 = createHmac("sha256", signingKey).update(payloadB64).digest("base64url"); + return `${SIGNED_TOKEN_PREFIX}${payloadB64}.${sigB64}`; + } + + function verifySignedProxyToken(presented: string): RunProxyTokenRecord | null { + if (!presented.startsWith(SIGNED_TOKEN_PREFIX)) return null; + const rest = presented.slice(SIGNED_TOKEN_PREFIX.length); + const dotIndex = rest.indexOf("."); + if (dotIndex <= 0 || dotIndex === rest.length - 1 || rest.indexOf(".", dotIndex + 1) !== -1) { + return null; + } + const payloadB64 = rest.slice(0, dotIndex); + const sigB64 = rest.slice(dotIndex + 1); + const expectedSigB64 = createHmac("sha256", signingKey).update(payloadB64).digest("base64url"); + const actualBuf = Buffer.from(sigB64, "utf8"); + const expectedBuf = Buffer.from(expectedSigB64, "utf8"); + if (actualBuf.length !== expectedBuf.length || !timingSafeEqual(actualBuf, expectedBuf)) { + return null; + } + try { + const parsed = readJsonRecord(JSON.parse(Buffer.from(payloadB64, "base64url").toString("utf8"))); + const companyId = typeof parsed.c === "string" ? parsed.c.trim() : ""; + const agentId = typeof parsed.a === "string" ? parsed.a.trim() : ""; + const allowedModel = typeof parsed.m === "string" ? parsed.m.trim() : ""; + if (!companyId || !agentId || !allowedModel) return null; + if (revokedAgents.has(agentRevocationKey(companyId, agentId))) return null; + return { + token: presented, + companyId, + agentId, + runId: activeRunTokens.get(presented)?.runId ?? "warm-session", + allowedModel, + }; + } catch { + return null; + } + } + function findActiveRunToken(presented: string): RunProxyTokenRecord | null { const presentedBuf = Buffer.from(presented, "utf8"); for (const [stored, record] of activeRunTokens) { const storedBuf = Buffer.from(stored, "utf8"); if (storedBuf.length === presentedBuf.length && timingSafeEqual(storedBuf, presentedBuf)) { - return record; + return revokedAgents.has(agentRevocationKey(record.companyId, record.agentId)) ? null : record; + } + } + return verifySignedProxyToken(presented); + } + + function revokeAgentTokens(companyId: string, agentIds: readonly string[]): void { + const targets = new Set(agentIds); + for (const agentId of targets) { + revokedAgents.add(agentRevocationKey(companyId, agentId)); + } + for (const [stored, record] of activeRunTokens) { + if (record.companyId === companyId && targets.has(record.agentId)) { + activeRunTokens.delete(stored); } } - return null; } /** @@ -159,19 +238,19 @@ export function createCloudTrialProxy(keyStore: CloudTrialKeyStore) { const serverOrigin = (env.PAPERCLIP_API_URL?.trim() || "http://127.0.0.1:3100").replace(/\/+$/, ""); const proxyUrl = `${serverOrigin}/api/internal/cloud-inference/v1`; - const token = `${RUN_TOKEN_PREFIX}${randomBytes(32).toString("base64url")}`; + const token = signProxyToken(input.companyId, input.agentId, allowedModel); if (!input.probeOnly) { + revokedAgents.delete(agentRevocationKey(input.companyId, input.agentId)); keyStore.recordRunPrepared(); + activeRunTokens.set(token, { + token, + companyId: input.companyId, + agentId: input.agentId, + runId: input.runId, + allowedModel, + }); } - activeRunTokens.set(token, { - token, - companyId: input.companyId, - agentId: input.agentId, - runId: input.runId, - allowedModel, - }); - return { env: { OPENROUTER_API_KEY: "", @@ -181,7 +260,8 @@ export function createCloudTrialProxy(keyStore: CloudTrialKeyStore) { secretValues: [token, state.apiKey], defaultModel: state.defaultModel, cleanup: async () => { - activeRunTokens.delete(token); + // Keep the signed token valid for warm OpenCode session reuse across + // consecutive turns; revocation happens on exhaustion, work gate, or migration. await keyStore.probeOpenRouterUsage(input.companyId, true); }, }; @@ -196,6 +276,7 @@ export function createCloudTrialProxy(keyStore: CloudTrialKeyStore) { req: IncomingMessage & { originalUrl?: string; url?: string; body?: unknown }, res: ServerResponse, subpath: string, + db?: Db, ): Promise { const authHeader = typeof req.headers.authorization === "string" ? req.headers.authorization : ""; const bearer = authHeader.startsWith("Bearer ") ? authHeader.slice("Bearer ".length).trim() : ""; @@ -220,7 +301,40 @@ export function createCloudTrialProxy(keyStore: CloudTrialKeyStore) { return; } - if (keyStore.getGateReason(tokenRecord.companyId) === "work_requires_model") { + if (db) { + // Authoritative DB check so migrated/deleted agents cannot keep using old + // signed tokens after a server restart or sleep-wake. + const [agentRow] = await db + .select({ runtimeConfig: agents.runtimeConfig }) + .from(agents) + .where( + and( + eq(agents.id, tokenRecord.agentId), + eq(agents.companyId, tokenRecord.companyId), + ne(agents.status, "terminated"), + ), + ) + .limit(1); + if (!agentRow || !isAgentUsingCloudTrialInference(agentRow.runtimeConfig)) { + revokeAgentTokens(tokenRecord.companyId, [tokenRecord.agentId]); + res.statusCode = 401; + res.setHeader("content-type", "application/json"); + res.end( + JSON.stringify({ + error: { + code: "proxy_token_not_found_on_instance", + message: "Trial proxy token is no longer active for this agent", + }, + }), + ); + return; + } + } + + const workGateActive = + keyStore.getGateReason(tokenRecord.companyId) === "work_requires_model" || + (db ? (await resolveHeldTrialIssues(db, tokenRecord.companyId, keyStore, true)).length > 0 : false); + if (workGateActive) { activeRunTokens.delete(tokenRecord.token); res.statusCode = 402; res.setHeader("content-type", "application/json"); @@ -256,6 +370,21 @@ export function createCloudTrialProxy(keyStore: CloudTrialKeyStore) { return; } + const currentAllowedModel = stripOpenRouterPrefix(state.defaultModel); + if (tokenRecord.allowedModel !== currentAllowedModel) { + res.statusCode = 403; + res.setHeader("content-type", "application/json"); + res.end( + JSON.stringify({ + error: { + code: "model_not_allowed", + message: `Trial inference is restricted to ${currentAllowedModel}`, + }, + }), + ); + return; + } + const normalizedSubpath = subpath.replace(/^\/+/, ""); if (!["chat/completions", "responses", "models"].includes(normalizedSubpath)) { res.statusCode = 404; @@ -583,6 +712,10 @@ export function createCloudTrialProxy(keyStore: CloudTrialKeyStore) { prepareCloudTrialFastResponse, getFastResponseModel: keyStore.configuredFastResponseModel, proxyOpenRouterRequest, - clearTokens: () => activeRunTokens.clear(), + revokeAgentTokens, + clearTokens: () => { + activeRunTokens.clear(); + revokedAgents.clear(); + }, }; }