Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(openai-compat): redact ask_user secrets and enforce minimum secret header length
jonathanwxh-cell80d569e28502
diff --git a/server/drivers/openai-chat-protocol.ts b/server/drivers/openai-chat-protocol.tsindex 116c74668d..7161eb631e 100644--- a/server/drivers/openai-chat-protocol.ts+++ b/server/drivers/openai-chat-protocol.ts@@ -1,5 +1,6 @@// Structured chat-completions calls. Assistant content becomes a tool call only for a local model, in chat-text-tool-calls.ts.import { randomUUID } from "node:crypto";+import type { AskQuestion } from "../../shared/ask-question.ts";export interface ChatToolCall {id: string;@@ -213,3 +214,17 @@ export class ChatToolCalls {return calls;}}++/** Scrubs display strings in parsed ask_user questions before emission while preserving card structure. */+export function redactAskQuestions(questions: AskQuestion[], redact: (text: string) => string): AskQuestion[] {+ return questions.map((entry) => ({+ ...entry,+ question: redact(entry.question),+ ...(entry.header !== undefined ? { header: redact(entry.header) } : {}),+ options: entry.options.map((option) => ({+ ...option,+ label: redact(option.label),+ ...(option.description !== undefined ? { description: redact(option.description) } : {}),+ })),+ }));+}diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.tsindex 3472a4de75..3cab94e43e 100644--- a/server/drivers/openai-chat.ts+++ b/server/drivers/openai-chat.ts@@ -13,7 +13,7 @@ import { chatToolLimitFor, chatToolLimitKey } from "../tool-count-limit.ts";import { assertImageTransport, chatImageBudget, chatToolImages, chatUserContent, type ChatContentPart } from "./chat-images.ts";import { promptHalves, volatileContextNote, withContextNote } from "./prompt-split.ts";import { createChatToolApproval, refusal } from "./chat-tool-approval.ts";-import { ChatProtocolError, ChatReasoningDetails, ChatToolCalls, CUT_REPLY_NOTE, cutReplyContinues, cutReplyWillContinue, object, replayableToolCalls, toolArguments, type ChatToolCall } from "./openai-chat-protocol.ts";+import { ChatProtocolError, ChatReasoningDetails, ChatToolCalls, CUT_REPLY_NOTE, cutReplyContinues, cutReplyWillContinue, object, redactAskQuestions, replayableToolCalls, toolArguments, type ChatToolCall } from "./openai-chat-protocol.ts";import { ContinuedReply, MaskedDeltas, maskSecretHalves } from "./cut-reply-text.ts";import { CORRECTIVE_ROUND, NUDGE_ANNOUNCED_ACTION, TEXT_ONLY_ATTACHMENT_NOTE, TEXT_ONLY_SCREENSHOT_NOTE, UNREADABLE_CALL } from "./openai-chat-prompts.ts";import { ChatHttpError, completionError, httpErrorDetail, refusedToolCall, refusedToolCallFailure, rejectsReasoningReplay, rejectsToolsParameter, RejectedToolCallError, sseData, StreamTruncatedError, UnsupportedChatToolsError, UnsupportedReasoningReplayError, type ProviderBody } from "./openai-chat-refusals.ts";@@ -808,7 +808,8 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)denials.push(ASK_USER_TOOL);result = { ok: false, text: "The ask_user arguments are malformed: pass a JSON object with a questions array of one to six questions, each with a question string and at most twelve options carrying a label. Ask again with valid arguments." };} else {- const answer = await approval.question(ASK_USER_TOOL, askQuestionSummary(questions), questions);+ const safeQuestions = redactAskQuestions(questions, safeText);+ const answer = await approval.question(ASK_USER_TOOL, askQuestionSummary(safeQuestions), safeQuestions);abort.signal.throwIfAborted();if (answer === null) {result = { ok: true, text: "The person did not answer this question. Do not guess an answer; ask again later or proceed without it." };diff --git a/server/drivers/openai-compat-headers.ts b/server/drivers/openai-compat-headers.tsindex 091f16b3d3..17a800fc3f 100644--- a/server/drivers/openai-compat-headers.ts+++ b/server/drivers/openai-compat-headers.ts@@ -168,6 +168,11 @@ export function decodeCustomHeaders(raw: unknown): OpenAICompatCustomHeadersConfrequired: entry.required !== false,secret: entry.secret === true || isSecretName(name) || holdsCredential(value),};+ if (rule.secret && !PLACEHOLDER_TEST.test(value) && value.length < MIN_MASKABLE_SECRET_LENGTH) {+ throw new CustomHeaderValidationError(+ `Secret header "${name}" value must be at least ${MIN_MASKABLE_SECRET_LENGTH} characters so it can be safely masked.`,+ );+ }headers.push(rule);}return { enabled: raw.enabled, headers };diff --git a/server/drivers/openai-compat.test.ts b/server/drivers/openai-compat.test.tsindex 92217cd8be..67e8d1b5d5 100644--- a/server/drivers/openai-compat.test.ts+++ b/server/drivers/openai-compat.test.ts@@ -1499,5 +1499,59 @@ describe("opt-in custom OpenAI-compatible request headers", () => {await expect(inst.generateText!("say hi")).rejects.toThrow(/bad token \[redacted\]/);await inst.dispose();});++ it("masks secret custom header values in ask_user question events without altering answer handling", async () => {+ const askBody = 'data: {"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_ask_1","type":"function","function":{"name":"ask_user","arguments":'+ + JSON.stringify(JSON.stringify({+ questions: [{+ header: "Token gw-secret-question-999",+ question: "Confirm token gw-secret-question-999?",+ options: [+ { label: "Use gw-secret-question-999", description: "Header gw-secret-question-999" },+ { label: "Skip", description: "Continue without token" },+ ],+ }],+ }))+ + '}}]}}]}\n\n'+ + 'data: {"choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}\n\n';+ const finalBody = 'data: {"choices":[{"index":0,"delta":{"content":"done"}}]}\n\n'+ + 'data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}\n\n';+ let call = 0;+ vi.stubGlobal("fetch", vi.fn(async (url: string | URL) => {+ if (String(url).endsWith("/models")) return Response.json({ data: [] });+ call++;+ return new Response(call === 1 ? askBody : finalBody, { status: 200, headers: { "content-type": "text/event-stream" } });+ }));+ const inst = await OpenAICompatDriver.create({+ instanceId: "gw-ask", displayName: "Ask", enabled: true,+ config: OpenAICompatDriver.decodeConfig({+ url: "https://gw.example/v1", model: "m1",+ customHeaders: {+ enabled: true,+ headers: [{ name: "X-Gateway-Token", value: "gw-secret-question-999", secret: true }],+ },+ }),+ environment: { OPENAI_COMPAT_API_KEY: "test-api-key-123456" },+ });+ const rec = recordEvents(inst.adapter);+ await inst.adapter.sendTurn({ threadId: "t-ask", botId: "b1", text: "ask me" });+ const asked = await rec.until((e) => e.type === "request.opened" && e.requestType === "question");+ expect(asked.type === "request.opened" && asked.requestType === "question").toBe(true);+ if (asked.type === "request.opened" && asked.requestType === "question") {+ expect(JSON.stringify(asked)).not.toContain("gw-secret-question-999");+ expect(asked.summary).toContain("[redacted]");+ expect(asked.questions?.[0]?.question).toContain("[redacted]");+ expect(asked.questions?.[0]?.header).toContain("[redacted]");+ expect(asked.questions?.[0]?.options?.[0]?.label).toContain("[redacted]");+ expect(asked.questions?.[0]?.options?.[0]?.description).toContain("[redacted]");+ expect(asked.choices?.[0]).toContain("[redacted]");+ expect(asked.requestId).toBeTruthy();+ const outcome = await inst.adapter.respondToRequest("t-ask", asked.requestId!, { behavior: "answer", message: "Skip" });+ expect(outcome).toBe("answered");+ }+ await rec.until((e) => e.type === "turn.completed");+ rec.stop();+ await inst.dispose();+ }, 20_000);});diff --git a/server/routes/instances.test.ts b/server/routes/instances.test.tsindex 3367f37a2f..4c18eefe9c 100644--- a/server/routes/instances.test.ts+++ b/server/routes/instances.test.ts@@ -438,6 +438,9 @@ describe("a server's reply wait", () => {expect(await status("a", { customHeaders: { enabled: true, headers: [{ name: "X-Ok", value: "1" }] } })).toBe(400);expect(await status("openai-compat-1", { customHeaders: { enabled: true, headers: [{ name: "Authorization", value: "Bearer bad" }] } })).toBe(400);expect(await status("openai-compat-1", { customHeaders: { enabled: true, headers: [{ name: "X-Bad", value: "line1\r\nline2" }] } })).toBe(400);+ expect(await status("openai-compat-1", { customHeaders: { enabled: true, headers: [{ name: "X-Gateway-Token", value: "s3cr3t", secret: true }] } })).toBe(400);+ expect(await status("openai-compat-1", { customHeaders: { enabled: true, headers: [{ name: "X-Api-Key", value: "short" }] } })).toBe(400);+ expect(await status("openai-compat-1", { customHeaders: { enabled: true, headers: [{ name: "X-Client-Tag", value: "short", secret: false }] } })).toBe(200);await call("PATCH", "/api/instances/openai-compat-1", {customHeaders: { enabled: true, headers: [{ name: "X-Tenant-Pin", value: "pin-987654", secret: true }] },