Files
openclaw/test/e2e/qa-lab/runtime/openai-image-auth-docker-client.ts
Peter Steinberger fe261b0f59 chore(tooling): typecheck root test/** with a dedicated tsgo lane (#104475)
* chore(types): add declaration files for scripts/lib and scripts/e2e modules

* chore(types): add declaration files for top-level script modules (a-m)

* chore(types): add declaration files for top-level script modules (n-z)

* test: use a non-secret-shaped gateway token fixture

* test: type ci workflow guard helpers for the root test lane

* chore(tooling): typecheck root test/** with a dedicated tsgo lane

- test/tsconfig/tsconfig.test.root.json: root-test program (strict unused checks,
  fixtures excluded; two Docker E2E clients that import built dist/** stay out,
  same rationale as the scripts/e2e exclusion in tsconfig.scripts.json)
- tsgo:test:root wired into tsgo:test, check:test-types, scripts/check.mjs, and
  the ci.yml test-types shard, mirroring the tsgo:scripts lane (#104348)
- changed-lane routing: test/**/*.ts (excluding fixtures) and the lane tsconfig
  now trigger 'typecheck test root' in check:changed; previously test/ paths ran
  lint only, so harness type errors surfaced first in CI (#104287 envDir case)
- burn down all 1071 latent type errors in the program: precise param/local
  types across test/scripts, test/vitest, test/e2e, and transitive scripts/e2e
  program members; 205 sibling .d.mts declaration files for imported .mjs
  modules (committed separately); zero any, zero ts-expect-error
- resolve the pre-existing testing star-export ambiguity in
  scripts/e2e/parallels/common.ts with an explicit re-export

Closes #104388

* chore(types): correct declaration fidelity per structured review

- re-derive 51 .d.mts files from implementation data flow instead of
  initializers: fix a wrong never return (runTestProjectsDelegation returns
  the child), add encoding-sensitive exec/spawn overloads (plain-gh), restore
  the full release profile union, make parsed paths string | null, add missing
  parseArgs fields via help/non-help unions, add a missing sibling declaration
  (budget-number-args), drop 15 unused lint directives
- precise install-record/tuple typing removes the type-aware oxlint
  regressions the first declarations caused in scripts/e2e implementations
- route .mts declaration edits under test/ to the testRoot lane and reference
  the test-root project from tsconfig.projects.json so tsgo:all covers it
  (closes both review findings against the lane wiring)

* chore(scripts): keep telegram runner dist typing structural for the boundary guard

* chore(types): declare runtime pack and gateway readiness exports added on main

* test: pin the importTargetPlan form of the plugin-contract plan import

The guard expectation still referenced the raw await import( form that
7ae5996bb3 (#103975) replaced with the importTargetPlan fallback helper;
the assertion fails on current main.
2026-07-11 06:15:41 -07:00

259 lines
7.9 KiB
TypeScript

// Openai Image Auth Docker Client script supports OpenClaw repository automation.
import http from "node:http";
import type { AddressInfo } from "node:net";
import path from "node:path";
import { fileURLToPath } from "node:url";
import {
isRequestBodyTooLargeError,
readBody,
} from "../../../../scripts/e2e/lib/mock-openai-http.mjs";
const DIRECT_IMAGE_BYTES = Buffer.from("docker-direct-image");
const CODEX_IMAGE_BYTES = Buffer.from("docker-codex-image");
const DIRECT_TOKEN = "sk-openclaw-image-auth-e2e";
const CODEX_TOKEN = "docker-codex-oauth-token";
export type RequestRecord = {
method?: string;
url?: string;
authorization?: string;
accept?: string;
contentType?: string;
body: string;
};
function assert(condition: unknown, message: string): asserts condition {
if (!condition) {
throw new Error(message);
}
}
function writeJson(res: http.ServerResponse, status: number, body: unknown): void {
res.writeHead(status, { "content-type": "application/json" });
res.end(JSON.stringify(body));
}
function writeCodexSse(res: http.ServerResponse): void {
const events = [
{
type: "response.output_item.done",
item: {
type: "image_generation_call",
result: CODEX_IMAGE_BYTES.toString("base64"),
revised_prompt: "docker codex revised prompt",
},
},
{
type: "response.completed",
response: {
usage: { input_tokens: 1, output_tokens: 2, total_tokens: 3 },
tool_usage: { image_gen: { total_tokens: 3 } },
},
},
];
res.writeHead(200, { "content-type": "text/event-stream" });
for (const event of events) {
res.write(`data: ${JSON.stringify(event)}\n\n`);
}
res.end("data: [DONE]\n\n");
}
export async function startMockServer(records: RequestRecord[]): Promise<{
baseUrl: string;
close: () => Promise<void>;
}> {
const server = http.createServer((req, res) => {
void (async () => {
try {
let body: string;
try {
body = await readBody(req);
} catch (error) {
if (isRequestBodyTooLargeError(error)) {
writeJson(res, 413, { error: { message: error.message } });
return;
}
throw error;
}
records.push({
method: req.method,
url: req.url,
authorization: req.headers.authorization,
accept: req.headers.accept,
contentType: req.headers["content-type"],
body,
});
if (req.method === "POST" && req.url === "/v1/images/generations") {
assert(
req.headers.authorization === `Bearer ${DIRECT_TOKEN}`,
`direct image route used wrong auth: ${req.headers.authorization}`,
);
const parsed = JSON.parse(body) as { model?: string; prompt?: string; size?: string };
assert(parsed.model === "gpt-image-2", `direct route model mismatch: ${body}`);
assert(
parsed.prompt === "docker direct image auth",
`direct route prompt mismatch: ${body}`,
);
assert(parsed.size === "1024x1024", `direct route size mismatch: ${body}`);
writeJson(res, 200, {
data: [
{
b64_json: DIRECT_IMAGE_BYTES.toString("base64"),
revised_prompt: "docker direct revised prompt",
},
],
});
return;
}
if (req.method === "POST" && req.url === "/backend-api/codex/responses") {
assert(
req.headers.authorization === `Bearer ${CODEX_TOKEN}`,
`codex image route used wrong auth: ${req.headers.authorization}`,
);
const parsed = JSON.parse(body) as {
tools?: Array<{ type?: string; model?: string; size?: string }>;
input?: Array<{ content?: Array<{ type?: string; text?: string }> }>;
};
assert(
parsed.tools?.[0]?.type === "image_generation" &&
parsed.tools[0].model === "gpt-image-2" &&
parsed.tools[0].size === "1024x1024",
`codex image tool mismatch: ${body}`,
);
assert(
parsed.input?.[0]?.content?.some(
(entry) =>
entry.type === "input_text" && entry.text === "docker codex oauth image auth",
),
`codex prompt missing: ${body}`,
);
writeCodexSse(res);
return;
}
writeJson(res, 404, { error: `unexpected ${req.method} ${req.url}` });
} catch (error) {
writeJson(res, 500, { error: String(error instanceof Error ? error.message : error) });
}
})();
});
await new Promise<void>((resolve) => {
server.listen(0, "127.0.0.1", resolve);
});
const address = server.address() as AddressInfo;
return {
baseUrl: `http://127.0.0.1:${address.port}`,
close: () =>
new Promise<void>((resolve, reject) => {
server.close((error) => (error ? reject(error) : resolve()));
}),
};
}
function createCodexOAuthStore() {
return {
version: 1,
profiles: {
"openai:chatgpt": {
type: "oauth",
provider: "openai",
access: CODEX_TOKEN,
refresh: "docker-codex-refresh-token",
expires: Date.now() + 60 * 60 * 1000,
},
},
} as const;
}
export async function main() {
assert(
process.env.OPENAI_API_KEY === DIRECT_TOKEN,
"Docker lane must expose the direct OpenAI API key",
);
const records: RequestRecord[] = [];
const mock = await startMockServer(records);
try {
const providerModulePath =
"../../../../dist/extensions/openai/image-generation-provider.js" as string;
const { buildOpenAIImageGenerationProvider } = (await import(
providerModulePath
)) as typeof import("../../../../extensions/openai/image-generation-provider.js");
const provider = buildOpenAIImageGenerationProvider();
const directResult = await provider.generateImage({
provider: "openai",
model: "gpt-image-2",
prompt: "docker direct image auth",
cfg: {
models: {
providers: {
openai: {
baseUrl: `${mock.baseUrl}/v1`,
request: { allowPrivateNetwork: true },
models: [],
},
},
},
},
});
assert(
directResult.images?.[0]?.buffer?.equals(DIRECT_IMAGE_BYTES),
"direct image route did not return expected bytes",
);
assert(
records.some((entry) => entry.url === "/v1/images/generations"),
"direct image route was not called",
);
records.length = 0;
const codexResult = await provider.generateImage({
provider: "openai",
model: "gpt-image-2",
prompt: "docker codex oauth image auth",
cfg: {
models: {
providers: {
openai: {
baseUrl: `${mock.baseUrl}/backend-api/codex`,
api: "openai-chatgpt-responses",
request: { allowPrivateNetwork: true },
models: [],
},
},
},
},
authStore: createCodexOAuthStore(),
});
assert(
codexResult.images?.[0]?.buffer?.equals(CODEX_IMAGE_BYTES),
"Codex OAuth image route did not return expected bytes",
);
assert(
records.some((entry) => entry.url === "/backend-api/codex/responses"),
"Codex OAuth image route was not called",
);
assert(
!records.some((entry) => entry.url === "/v1/images/generations"),
"Codex OAuth image route fell back to the direct OpenAI API key",
);
process.stdout.write(
JSON.stringify({
ok: true,
routes: records.map((entry) => entry.url),
directBytes: directResult.images[0]?.buffer.length,
codexBytes: codexResult.images[0]?.buffer.length,
}) + "\n",
);
} finally {
await mock.close();
}
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
await main();
}