fix(cloud-trial): mount internal OpenRouter proxy before actorMiddleware (#23571)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Cloud starter-inference OpenCode runs in remote plugin Runners
authenticate to `/api/internal/cloud-inference/v1/*` using an ephemeral
per-run `pctrial_` Bearer token.
> - In `server/src/app.ts`, `/api/internal/cloud-inference` was mounted
after `actorMiddleware`.
> - In authenticated deployments, `actorMiddleware` intercepted every
`Authorization: Bearer pctrial_...` request, tried to verify it as an
agent JWT/API key, and returned HTTP 401 (`Agent token did not verify`)
before the proxy route ever ran.
> - This pull request mounts `/api/internal/cloud-inference` before
`actorMiddleware` (alongside `voiceWebhookRoutes`, which uses the same
pre-`actorMiddleware` pattern) and adds a full `createApp` regression
test in `authenticated` deployment mode.
> - The benefit is that remote Cloud starter-inference OpenCode runs
authenticate cleanly through `/api/internal/cloud-inference/v1/*` and
stream real replies.

## Linked Issues or Issue Description

Refs #23401, #23559

**Summary**
Mount `cloudInferenceInternalProxyRoutes` before `actorMiddleware` in
`server/src/app.ts` so ephemeral `pctrial_` Bearer tokens are not
rejected as invalid agent tokens.

**Steps to Reproduce**
1. Run Paperclip in `authenticated` deployment mode with Cloud starter
inference enabled.
2. Start a starter-inference OpenCode run in a remote plugin Runner
environment.
3. Observe HTTP 401 (`Unauthorized: Agent token did not verify; obtain
fresh credentials and retry`) when OpenCode calls
`/api/internal/cloud-inference/v1/chat/completions`.

**Expected Behavior**
Requests to `/api/internal/cloud-inference/v1/*` reach
`cloudInferenceInternalProxyRoutes`, validate the active per-run
`pctrial_` token, and forward to OpenRouter with the server-held starter
key.

## What Changed

- `server/src/app.ts`: Moved `cloudTrialInferenceController`
initialization and `app.use("/api/internal/cloud-inference",
cloudInferenceInternalProxyRoutes(cloudTrialInferenceController))` above
`app.use(actorMiddleware(...))`, alongside `voiceWebhookRoutes`.
- `server/src/__tests__/cloud-trial-proxy-middleware-order.test.ts`:
Added a full `createApp` regression test (`deploymentMode:
"authenticated"`) verifying that unknown `pctrial_` tokens reach
`cloudInferenceInternalProxyRoutes`
(`proxy_token_not_found_on_instance`) and active `pctrial_` tokens proxy
cleanly to upstream OpenRouter with the server-held key.

## Verification

- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/cloud-trial-proxy-middleware-order.test.ts
src/__tests__/cloud-trial-inference.test.ts` — passed (7/7 tests).
- `pnpm --filter @paperclipai/server typecheck` — passed (0 errors).

## Risks

- Low risk. `/api/internal/cloud-inference` strictly authenticates every
request against active per-run `pctrial_` tokens in memory using
`timingSafeEqual` and rejects all unauthenticated or unknown tokens with
HTTP 401.

## Model Used

- Google Gemini (Antigravity agentic runtime, thinking mode with tool
use and local code execution).

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [ ] I will address all Greptile and reviewer comments before
requesting merge
This commit is contained in:
Dotta authored and GitHub committed 2026-12-02 18:45:16 -06:00
1 parent cc2e1d9d43
commit b066a3ddd3
2 files changed
+174 -11

No files matched your search

@@ -0,0 +1,162 @@
import { createServer, type Server } from "node:http";
import { mkdtemp, rm } from "node:fs/promises";
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 { createApp } from "../app.js";
import { getDefaultCloudTrialInferenceController } from "../services/cloud-trial-inference.js";
import { instanceSettingsService } from "../services/instance-settings.js";
import { createLocalDiskStorageProvider } from "../storage/local-disk-provider.js";
import { createStorageService } from "../storage/service.js";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
const support = await getEmbeddedPostgresTestSupport();
const describePostgres = support.supported ? describe : describe.skip;
type Db = ReturnType<typeof createDb>;
type App = Awaited<ReturnType<typeof createApp>>;
describePostgres("cloud inference internal proxy middleware order", () => {
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: Db;
let directory: string;
let upstream: Server;
let upstreamUrl: string;
let seenUpstreamAuth: string | undefined;
const savedEnv: Record<string, string | undefined> = {};
beforeAll(async () => {
database = await startEmbeddedPostgresTestDatabase("cloud-trial-proxy-order-");
db = createDb(database.connectionString);
directory = await mkdtemp(join(tmpdir(), "cloud-trial-proxy-order-storage-"));
upstream = createServer((req, res) => {
if (req.url === "/v1/key") {
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify({ data: { usage: 0.01, limit: 1.0 } }));
return;
}
if (req.url === "/v1/chat/completions") {
seenUpstreamAuth = req.headers.authorization;
res.writeHead(200, { "content-type": "application/json" });
res.end(
JSON.stringify({
id: "chatcmpl-test",
choices: [{ message: { role: "assistant", content: "Hello from starter proxy!" } }],
}),
);
return;
}
res.writeHead(404).end();
});
await new Promise<void>((resolve) => upstream.listen(0, "127.0.0.1", resolve));
const addr = upstream.address();
if (!addr || typeof addr === "string") throw new Error("No upstream address");
upstreamUrl = `http://127.0.0.1:${addr.port}/v1`;
for (const [key, value] of Object.entries({
PAPERCLIP_ONBOARDING_VARIANT: "free_inference_1",
PAPERCLIP_CLOUD_TRIAL_OPENROUTER_API_KEY: "sk-or-v1-middleware-order-secret",
PAPERCLIP_CLOUD_TRIAL_OPENROUTER_BASE_URL: upstreamUrl,
})) {
savedEnv[key] = process.env[key];
process.env[key] = value;
}
}, 120_000);
afterAll(async () => {
for (const [key, value] of Object.entries(savedEnv)) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
await new Promise<void>((resolve) => upstream?.close(() => resolve()));
await db?.$client.end();
await database?.cleanup();
if (directory) await rm(directory, { recursive: true, force: true });
});
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();
await db.insert(companies).values({
id: companyId,
name: "Proxy Order Co",
issuePrefix: "PO",
});
const app: App = await createApp(db, {
uiMode: "none",
serverPort: 0,
bindHost: "127.0.0.1",
allowedHostnames: ["127.0.0.1"],
deploymentMode: "authenticated",
deploymentExposure: "private",
authReady: true,
companyDeletionEnabled: false,
managedPluginAutoInstall: [],
storageService: createStorageService(createLocalDiskStorageProvider(directory)),
decisionServiceOptions: { wakeOriginAgent: async () => null },
});
await app.locals.bundledPluginsStartup;
const server = app.listen(0, "127.0.0.1");
try {
await new Promise<void>((resolve) => server.once("listening", resolve));
const addr = server.address();
if (!addr || typeof addr === "string") throw new Error("No HTTP test address");
const baseUrl = `http://127.0.0.1:${addr.port}`;
// 1. Unknown pctrial_ token reaches cloudInferenceInternalProxyRoutes (NOT actorMiddleware)
const unknownRes = await fetch(`${baseUrl}/api/internal/cloud-inference/v1/chat/completions`, {
method: "POST",
headers: {
authorization: "Bearer pctrial_unknown_token",
"content-type": "application/json",
},
body: JSON.stringify({ model: "openai/gpt-6-luna", messages: [] }),
});
expect(unknownRes.status).toBe(401);
const unknownBody = (await unknownRes.json()) as { error?: { code?: string; message?: string } };
expect(unknownBody.error?.code).toBe("proxy_token_not_found_on_instance");
expect(unknownBody.error?.message).not.toContain("Agent token did not verify");
// 2. Valid active pctrial_ token proxies cleanly to upstream OpenRouter with server-held key
const runtime = await getDefaultCloudTrialInferenceController().prepareCloudTrialRuntime(db, {
companyId,
agentId: randomUUID(),
runId: randomUUID(),
model: "openrouter/openai/gpt-6-luna",
});
try {
const okRes = 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: "Hi" }],
}),
});
expect(okRes.status).toBe(200);
const okBody = (await okRes.json()) as {
choices: Array<{ message: { content: string } }>;
};
expect(okBody.choices[0]?.message.content).toBe("Hello from starter proxy!");
expect(seenUpstreamAuth).toBe("Bearer sk-or-v1-middleware-order-secret");
} finally {
await runtime.cleanup();
}
} finally {
await app.locals.paperclipShutdown?.();
await new Promise<void>((resolve, reject) =>
server.close((error) => (error ? reject(error) : resolve())),
);
}
}, 60_000);
});
+12 -11
View File
@@ -671,6 +671,18 @@ export async function createApp(
// board/agent bearer authentication. Mount before actorMiddleware so its
// per-session Bearer cannot be mistaken for an agent API key.
app.use(voiceWebhookRoutes(db, chatChannels.voice));
// Internal OpenRouter trial inference proxy (authenticated strictly by
// ephemeral per-run `pctrial_` bearer token, not board cookies or agent API
// keys). Mount before actorMiddleware so its per-run Bearer token is not
// rejected as an invalid agent token.
const cloudTrialInferenceController = createCloudTrialInferenceController();
setDefaultCloudTrialInferenceController(cloudTrialInferenceController);
// Warm resolved experimental settings at startup so staging overrides sync
// into PostHog cohort properties before the first request or event.
void instanceSettingsService(db)
.getExperimental()
.catch(() => {});
app.use("/api/internal/cloud-inference", cloudInferenceInternalProxyRoutes(cloudTrialInferenceController));
app.use(
actorMiddleware(db, {
deploymentMode: opts.deploymentMode,
@@ -764,17 +776,6 @@ export async function createApp(
})
: undefined;
// Internal OpenRouter trial inference proxy (authenticated strictly by
// ephemeral per-run bearer token; never requires board session cookies).
const cloudTrialInferenceController = createCloudTrialInferenceController();
setDefaultCloudTrialInferenceController(cloudTrialInferenceController);
// Warm resolved experimental settings at startup so staging overrides sync
// into PostHog cohort properties before the first request or event.
void instanceSettingsService(db)
.getExperimental()
.catch(() => {});
app.use("/api/internal/cloud-inference", cloudInferenceInternalProxyRoutes(cloudTrialInferenceController));
// Mount API routes
const api = Router();
const agentAvatars = agentAvatarRoutes();