Repository navigation
fix(inference): inject OpenRouter runtime headers via adapter #6584
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 2 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
8b3dafe
fix(inference): inject OpenRouter runtime headers via adapter
sandl99 a77fa50
refactor(inference): split OpenRouter runtime adapter
sandl99 bd5dd18
fix(inference): harden OpenRouter adapter port and body handling
sandl99 380eb40
refactor(onboard): keep top-level wiring net neutral
sandl99 760e466
fix(inference): sanitize OpenRouter adapter JSON responses
sandl99 183c3cb
test(inference): keep OpenRouter adapter test linear
sandl99 2b07a0b
fix(inference): harden OpenRouter adapter failures
sandl99 a5ffcd0
test(uninstall): keep OpenRouter cleanup tests linear
sandl99 8dab711
fix(inference): tighten OpenRouter adapter follow-up
sandl99 a2a392a
test(inference): cover OpenRouter upstream aborts
sandl99 98ed421
merge(main): resolve OpenRouter docs conflict
sandl99 c2a9921
fix(inference): avoid user-controlled auth bypass
sandl99 1b42233
fix(inference): clean up OpenRouter adapter setup failures
sandl99 ec29c65
Revert "fix(inference): clean up OpenRouter adapter setup failures"
sandl99 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| import crypto from "node:crypto"; | ||
| import http from "node:http"; | ||
| import path from "node:path"; | ||
|
|
||
| import { compactText } from "../core/url-utils"; | ||
| import { OPENROUTER_DEFAULT_HEADERS, OPENROUTER_ENDPOINT_URL } from "./openrouter"; | ||
| import { | ||
| DEFAULT_LOCAL_ADAPTER_STATE_DIR, | ||
| appendLocalAdapterJsonLine, | ||
| type JsonObject, | ||
| } from "./local-adapter-lifecycle"; | ||
|
|
||
| export const STATE_DIR = DEFAULT_LOCAL_ADAPTER_STATE_DIR; | ||
| export const PID_PATH = path.join(STATE_DIR, "openrouter-runtime-adapter.pid"); | ||
| export const STATE_PATH = path.join(STATE_DIR, "openrouter-runtime-adapter.json"); | ||
| export const LOCK_PATH = path.join(STATE_DIR, "openrouter-runtime-adapter.lock"); | ||
| export const LOG_PATH = path.join(STATE_DIR, "openrouter-runtime-adapter.log"); | ||
| export const ADAPTER_NAME = "openrouter-runtime"; | ||
|
|
||
| export type AdapterLogFields = Record<string, string | number | boolean | null | undefined>; | ||
| export type AdapterLogger = (event: string, fields?: AdapterLogFields) => void; | ||
|
|
||
| function normalizeLogField( | ||
| value: string | number | boolean | null | undefined, | ||
| ): string | number | boolean | null { | ||
| if (value === undefined) return null; | ||
| if (typeof value === "string") return compactText(value).slice(0, 180); | ||
| return value; | ||
| } | ||
|
|
||
| export function defaultAdapterLogger(event: string, fields: AdapterLogFields = {}): void { | ||
| try { | ||
| const payload: Record<string, string | number | boolean | null> = { | ||
| ts: new Date().toISOString(), | ||
| event: normalizeLogField(event) as string, | ||
| }; | ||
| for (const [key, value] of Object.entries(fields)) { | ||
| payload[key] = normalizeLogField(value); | ||
| } | ||
| appendLocalAdapterJsonLine(LOG_PATH, payload); | ||
| } catch (err) { | ||
| const message = err instanceof Error ? err.message : String(err); | ||
| console.error(`OpenRouter Runtime adapter log write failed: ${compactText(message)}`); | ||
| } | ||
| } | ||
|
|
||
| export function logAdapterEvent( | ||
| logger: AdapterLogger, | ||
| event: string, | ||
| fields: AdapterLogFields = {}, | ||
| ): void { | ||
| try { | ||
| logger(event, fields); | ||
| } catch (err) { | ||
| const message = err instanceof Error ? err.message : String(err); | ||
| console.error(`OpenRouter Runtime adapter logger failed: ${compactText(message)}`); | ||
| } | ||
| } | ||
|
|
||
| function stableJson(value: unknown): string { | ||
| if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`; | ||
| if (value && typeof value === "object") { | ||
| return `{${Object.keys(value as JsonObject) | ||
| .sort() | ||
| .map((key) => `${JSON.stringify(key)}:${stableJson((value as JsonObject)[key])}`) | ||
| .join(",")}}`; | ||
| } | ||
| return JSON.stringify(value); | ||
| } | ||
|
|
||
| export function adapterConfigHash(upstreamBaseUrl = OPENROUTER_ENDPOINT_URL): string { | ||
| return crypto | ||
| .createHash("sha256") | ||
| .update( | ||
| stableJson({ | ||
| adapter: ADAPTER_NAME, | ||
| upstreamBaseUrl, | ||
| defaultHeaders: OPENROUTER_DEFAULT_HEADERS, | ||
| }), | ||
| ) | ||
| .digest("hex"); | ||
| } | ||
|
|
||
| export function sendJson(res: http.ServerResponse, status: number, body: unknown): void { | ||
| res.writeHead(status, { "Content-Type": "application/json" }); | ||
| res.end(JSON.stringify(body)); | ||
|
github-advanced-security[bot] marked this conversation as resolved.
Fixed
|
||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| import { startOpenRouterRuntimeAdapterFromEnv } from "./openrouter-runtime-adapter-server"; | ||
|
|
||
| try { | ||
| startOpenRouterRuntimeAdapterFromEnv(); | ||
| } catch (err) { | ||
| console.error(err instanceof Error ? err.message : String(err)); | ||
| process.exit(1); | ||
| } |
103 changes: 103 additions & 0 deletions
103
src/lib/inference/openrouter-runtime-adapter-forward.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,103 @@ | ||
| // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| import http from "node:http"; | ||
| import https from "node:https"; | ||
|
|
||
| import { compactText } from "../core/url-utils"; | ||
| import { OPENROUTER_DEFAULT_HEADERS } from "./openrouter"; | ||
| import { sendJson } from "./openrouter-runtime-adapter-common"; | ||
|
|
||
| const HOP_BY_HOP_HEADERS = new Set([ | ||
| "connection", | ||
| "host", | ||
| "keep-alive", | ||
| "proxy-authenticate", | ||
| "proxy-authorization", | ||
| "te", | ||
| "trailer", | ||
| "transfer-encoding", | ||
| "upgrade", | ||
| ]); | ||
|
|
||
| export function hasBearerAuthorization(actual: string | string[] | undefined): boolean { | ||
| const header = Array.isArray(actual) ? actual[0] : actual; | ||
| return typeof header === "string" && /^Bearer\s+\S+/.test(header); | ||
| } | ||
|
|
||
| export function buildUpstreamUrl(upstreamBaseUrl: string, reqUrl: string | undefined): URL { | ||
| const incoming = new URL(reqUrl || "/", "http://127.0.0.1"); | ||
| const upstream = new URL(upstreamBaseUrl); | ||
| const basePath = upstream.pathname.replace(/\/+$/, ""); | ||
| const suffix = incoming.pathname.startsWith("/v1") | ||
| ? incoming.pathname.slice("/v1".length) | ||
| : incoming.pathname; | ||
| upstream.pathname = `${basePath}${suffix.startsWith("/") ? suffix : `/${suffix}`}`; | ||
| upstream.search = incoming.search; | ||
| return upstream; | ||
| } | ||
|
|
||
| export function buildForwardRequestHeaders(req: http.IncomingMessage): http.OutgoingHttpHeaders { | ||
| const headers: http.OutgoingHttpHeaders = {}; | ||
| for (const [name, value] of Object.entries(req.headers)) { | ||
| if (value === undefined || HOP_BY_HOP_HEADERS.has(name.toLowerCase())) continue; | ||
| headers[name] = value; | ||
| } | ||
| for (const [name, value] of OPENROUTER_DEFAULT_HEADERS) { | ||
| headers[name] = value; | ||
| } | ||
| return headers; | ||
| } | ||
|
|
||
| function buildForwardResponseHeaders(source: http.IncomingHttpHeaders): http.OutgoingHttpHeaders { | ||
| const headers: http.OutgoingHttpHeaders = {}; | ||
| for (const [name, value] of Object.entries(source)) { | ||
| if (value === undefined || HOP_BY_HOP_HEADERS.has(name.toLowerCase())) continue; | ||
| headers[name] = value; | ||
| } | ||
| return headers; | ||
| } | ||
|
|
||
| export function forwardOpenRouterRequest(options: { | ||
| req: http.IncomingMessage; | ||
| res: http.ServerResponse; | ||
| upstreamBaseUrl: string; | ||
| }): Promise<number> { | ||
| const upstreamUrl = buildUpstreamUrl(options.upstreamBaseUrl, options.req.url); | ||
| const transport = upstreamUrl.protocol === "http:" ? http : https; | ||
| return new Promise((resolve) => { | ||
| const upstreamReq = transport.request( | ||
| upstreamUrl, | ||
| { | ||
| method: options.req.method, | ||
| headers: buildForwardRequestHeaders(options.req), | ||
| }, | ||
| (upstreamRes) => { | ||
| const status = upstreamRes.statusCode || 502; | ||
| options.res.writeHead(status, buildForwardResponseHeaders(upstreamRes.headers)); | ||
| upstreamRes.pipe(options.res); | ||
| upstreamRes.on("end", () => resolve(status)); | ||
| }, | ||
| ); | ||
| upstreamReq.on("error", (err) => { | ||
| const message = err instanceof Error ? err.message : String(err); | ||
| if (!options.res.headersSent) { | ||
| sendJson(options.res, 502, { | ||
| error: { | ||
| message: compactText(message || "OpenRouter request failed."), | ||
| type: "openrouter_runtime_error", | ||
| code: "openrouter_runtime_error", | ||
| }, | ||
| }); | ||
| } else { | ||
| options.res.destroy(err instanceof Error ? err : undefined); | ||
| } | ||
| resolve(502); | ||
| }); | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
| options.req.on("error", () => { | ||
| upstreamReq.destroy(); | ||
| resolve(499); | ||
| }); | ||
| options.req.pipe(upstreamReq); | ||
| }); | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.