mirror of
https://github.com/Nezumi-2711/9router.git
synced 2026-09-22 13:38:31 +00:00
feat(xai): add Grok Imagine video generation (/v1/videos) + CLI
Async video job proxy mirroring the existing image-generation layer split:
Next routes → src/sse/handlers/videoGeneration.js (auth gate, account
fallback loop, refresh persistence) → open-sse/handlers/videoCore.js
(transparent upstream proxy, 401 refresh-once/retry-once, secret sanitization).
- POST /v1/videos/{generations,edits,extensions}: byte-exact body forward
(JSON + multipart), request_id passthrough, Idempotency-Key forwarded
- GET /v1/videos/{request_id}: status/progress/video.url passthrough
- Register grok-imagine-video (kind: "video"); add "video" to MODEL_TYPE_TO_KIND
so video models stay out of chat lists (also fixes runwayml leak)
- 9router xai video CLI: submit → poll → atomic MP4 download
- No auto-retry of creation POSTs (billable jobs); rotate accounts only on
401/403/429; sanitize Bearer tokens + credential values from errors/logs
Closes #1285
This commit is contained in:
@@ -0,0 +1,273 @@
|
||||
/**
|
||||
* Tests for the `9router xai video` CLI command (cli/src/cli/commands/xaiVideo.js)
|
||||
*
|
||||
* Uses a real local HTTP server standing in for the 9router gateway + video CDN.
|
||||
* No real credentials or upstream calls.
|
||||
*
|
||||
* Covers:
|
||||
* - arg parsing (defaults, flags, unknown flag rejection)
|
||||
* - full happy path: create → poll (pending → done) → MP4 download → atomic rename
|
||||
* - x-connection-id pinning from the create response header
|
||||
* - failed job → non-zero exit, no output file, no stray .part
|
||||
* - poll timeout → non-zero exit
|
||||
* - download failure cleans up the .part file
|
||||
* - no Authorization/token material in output
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
|
||||
import http from "node:http";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { createRequire } from "node:module";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const { run, parseArgs, downloadToFile, sanitizeText, imageInputToUrl } = require("../../cli/src/cli/commands/xaiVideo.js");
|
||||
|
||||
const MP4_BYTES = Buffer.from("FAKE-MP4-DATA-0123456789");
|
||||
|
||||
function startServer(handler) {
|
||||
return new Promise((resolve) => {
|
||||
const server = http.createServer(handler);
|
||||
server.listen(0, "127.0.0.1", () => resolve({ server, port: server.address().port }));
|
||||
});
|
||||
}
|
||||
|
||||
const closeServer = (server) => new Promise((r) => server.close(r));
|
||||
|
||||
let tmpDir;
|
||||
let server;
|
||||
|
||||
beforeEach(async () => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "xai-video-test-"));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
if (server) {
|
||||
await closeServer(server);
|
||||
server = null;
|
||||
}
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("parseArgs", () => {
|
||||
it("applies defaults", () => {
|
||||
const opts = parseArgs(["--prompt", "hi"]);
|
||||
expect(opts.prompt).toBe("hi");
|
||||
expect(opts.model).toBe("xai/grok-imagine-video");
|
||||
expect(opts.output).toBe("video.mp4");
|
||||
expect(opts.port).toBe(20128);
|
||||
});
|
||||
|
||||
it("parses all documented flags", () => {
|
||||
const opts = parseArgs([
|
||||
"--prompt", "p", "--output", "o.mp4", "--model", "m",
|
||||
"--duration", "10", "--aspect-ratio", "16:9", "--resolution", "720p",
|
||||
"--image", "https://x/img.png", "--timeout", "30", "--port", "1234", "--api-key", "k",
|
||||
]);
|
||||
expect(opts).toMatchObject({
|
||||
prompt: "p", output: "o.mp4", model: "m", duration: 10,
|
||||
aspectRatio: "16:9", resolution: "720p", image: "https://x/img.png",
|
||||
timeoutSec: 30, port: 1234, apiKey: "k",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects unknown flags", () => {
|
||||
expect(() => parseArgs(["--bogus"])).toThrow(/Unknown option/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("imageInputToUrl", () => {
|
||||
it("passes URLs and data URLs through", () => {
|
||||
expect(imageInputToUrl("https://example.com/a.png")).toBe("https://example.com/a.png");
|
||||
expect(imageInputToUrl("data:image/png;base64,AAA")).toBe("data:image/png;base64,AAA");
|
||||
});
|
||||
|
||||
it("converts a local file to a base64 data URL", () => {
|
||||
const p = path.join(tmpDir, "in.png");
|
||||
fs.writeFileSync(p, Buffer.from([1, 2, 3]));
|
||||
expect(imageInputToUrl(p)).toBe(`data:image/png;base64,${Buffer.from([1, 2, 3]).toString("base64")}`);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sanitizeText", () => {
|
||||
it("redacts bearer tokens from error output", () => {
|
||||
expect(sanitizeText("boom Bearer abcdefghijklmnop!")).toBe("boom Bearer [redacted]!");
|
||||
});
|
||||
});
|
||||
|
||||
describe("run (against a mock gateway)", () => {
|
||||
it("creates, polls to done, downloads the MP4, and exits 0", async () => {
|
||||
let pollCount = 0;
|
||||
const seen = { createAuth: null, pollConnectionIds: [] };
|
||||
|
||||
({ server } = await startServer((req, res) => {
|
||||
if (req.method === "POST" && req.url === "/v1/videos/generations") {
|
||||
seen.createAuth = req.headers.authorization || null;
|
||||
let body = "";
|
||||
req.on("data", (c) => (body += c));
|
||||
req.on("end", () => {
|
||||
seen.createBody = JSON.parse(body);
|
||||
res.writeHead(200, { "Content-Type": "application/json", "x-9router-connection-id": "conn-42" });
|
||||
res.end(JSON.stringify({ request_id: "job-1" }));
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (req.method === "GET" && req.url === "/v1/videos/job-1") {
|
||||
seen.pollConnectionIds.push(req.headers["x-connection-id"] || null);
|
||||
pollCount++;
|
||||
const port = server.address().port;
|
||||
const payload = pollCount < 3
|
||||
? { status: "pending", progress: pollCount * 30 }
|
||||
: { status: "done", video: { url: `http://127.0.0.1:${port}/files/out.mp4`, duration: 8 } };
|
||||
res.writeHead(200, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify(payload));
|
||||
return;
|
||||
}
|
||||
if (req.method === "GET" && req.url === "/files/out.mp4") {
|
||||
res.writeHead(200, { "Content-Type": "video/mp4" });
|
||||
res.end(MP4_BYTES);
|
||||
return;
|
||||
}
|
||||
res.writeHead(404).end();
|
||||
}));
|
||||
|
||||
const output = path.join(tmpDir, "result.mp4");
|
||||
const logs = [];
|
||||
vi.spyOn(console, "log").mockImplementation((...a) => logs.push(a.join(" ")));
|
||||
vi.spyOn(console, "error").mockImplementation((...a) => logs.push(a.join(" ")));
|
||||
|
||||
const code = await run([
|
||||
"--prompt", "a neon city",
|
||||
"--output", output,
|
||||
"--port", String(server.address().port),
|
||||
"--api-key", "local-key-secret",
|
||||
"--timeout", "10",
|
||||
"--poll-interval-ms", "20",
|
||||
]);
|
||||
|
||||
expect(code).toBe(0);
|
||||
expect(fs.readFileSync(output)).toEqual(MP4_BYTES);
|
||||
expect(fs.existsSync(`${output}.part`)).toBe(false);
|
||||
|
||||
// Model prefix forwarded as-is to the gateway (gateway strips it)
|
||||
expect(seen.createBody.model).toBe("xai/grok-imagine-video");
|
||||
expect(seen.createBody.prompt).toBe("a neon city");
|
||||
// Polls pinned to the connection that created the job
|
||||
expect(seen.pollConnectionIds.every((id) => id === "conn-42")).toBe(true);
|
||||
// No token material in user-facing output
|
||||
expect(logs.join("\n")).not.toContain("local-key-secret");
|
||||
expect(logs.join("\n")).not.toContain("Authorization");
|
||||
});
|
||||
|
||||
it("exits non-zero when the job fails, without leaving files", async () => {
|
||||
({ server } = await startServer((req, res) => {
|
||||
if (req.method === "POST") {
|
||||
res.writeHead(200, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ request_id: "job-f" }));
|
||||
return;
|
||||
}
|
||||
res.writeHead(200, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ status: "failed", error: { code: "invalid_argument", message: "bad prompt" } }));
|
||||
}));
|
||||
|
||||
const output = path.join(tmpDir, "nope.mp4");
|
||||
const errors = [];
|
||||
vi.spyOn(console, "log").mockImplementation(() => {});
|
||||
vi.spyOn(console, "error").mockImplementation((...a) => errors.push(a.join(" ")));
|
||||
|
||||
const code = await run([
|
||||
"--prompt", "x", "--output", output,
|
||||
"--port", String(server.address().port),
|
||||
"--timeout", "10", "--poll-interval-ms", "10",
|
||||
]);
|
||||
|
||||
expect(code).toBe(1);
|
||||
expect(errors.join("\n")).toContain("bad prompt");
|
||||
expect(fs.existsSync(output)).toBe(false);
|
||||
expect(fs.existsSync(`${output}.part`)).toBe(false);
|
||||
});
|
||||
|
||||
it("exits non-zero when polling exceeds the timeout", async () => {
|
||||
({ server } = await startServer((req, res) => {
|
||||
res.writeHead(200, { "Content-Type": "application/json" });
|
||||
res.end(req.method === "POST" ? JSON.stringify({ request_id: "job-slow" }) : JSON.stringify({ status: "pending", progress: 1 }));
|
||||
}));
|
||||
|
||||
vi.spyOn(console, "log").mockImplementation(() => {});
|
||||
const errors = [];
|
||||
vi.spyOn(console, "error").mockImplementation((...a) => errors.push(a.join(" ")));
|
||||
|
||||
const code = await run([
|
||||
"--prompt", "x", "--output", path.join(tmpDir, "slow.mp4"),
|
||||
"--port", String(server.address().port),
|
||||
"--timeout", "1", "--poll-interval-ms", "50",
|
||||
]);
|
||||
|
||||
expect(code).toBe(1);
|
||||
expect(errors.join("\n")).toMatch(/Timed out/i);
|
||||
}, 15000);
|
||||
|
||||
it("reports a helpful error when no xAI account is connected", async () => {
|
||||
({ server } = await startServer((req, res) => {
|
||||
res.writeHead(400, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ error: { message: "No credentials for provider: xai", type: "invalid_request_error" } }));
|
||||
}));
|
||||
|
||||
vi.spyOn(console, "log").mockImplementation(() => {});
|
||||
const errors = [];
|
||||
vi.spyOn(console, "error").mockImplementation((...a) => errors.push(a.join(" ")));
|
||||
|
||||
const code = await run([
|
||||
"--prompt", "x", "--output", path.join(tmpDir, "n.mp4"),
|
||||
"--port", String(server.address().port),
|
||||
]);
|
||||
|
||||
expect(code).toBe(1);
|
||||
expect(errors.join("\n")).toContain("No credentials");
|
||||
expect(errors.join("\n")).toContain("Connect an xAI account");
|
||||
});
|
||||
});
|
||||
|
||||
describe("downloadToFile", () => {
|
||||
it("downloads via .part and renames atomically", async () => {
|
||||
({ server } = await startServer((req, res) => {
|
||||
res.writeHead(200, { "Content-Type": "video/mp4" });
|
||||
res.end(MP4_BYTES);
|
||||
}));
|
||||
|
||||
const out = path.join(tmpDir, "dl.mp4");
|
||||
await downloadToFile(`http://127.0.0.1:${server.address().port}/f.mp4`, out);
|
||||
expect(fs.readFileSync(out)).toEqual(MP4_BYTES);
|
||||
expect(fs.existsSync(`${out}.part`)).toBe(false);
|
||||
});
|
||||
|
||||
it("follows redirects", async () => {
|
||||
({ server } = await startServer((req, res) => {
|
||||
if (req.url === "/start") {
|
||||
res.writeHead(302, { Location: `/final` });
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
res.writeHead(200);
|
||||
res.end(MP4_BYTES);
|
||||
}));
|
||||
|
||||
const out = path.join(tmpDir, "redir.mp4");
|
||||
await downloadToFile(`http://127.0.0.1:${server.address().port}/start`, out);
|
||||
expect(fs.readFileSync(out)).toEqual(MP4_BYTES);
|
||||
});
|
||||
|
||||
it("removes the .part file when the download fails", async () => {
|
||||
({ server } = await startServer((req, res) => {
|
||||
res.writeHead(500);
|
||||
res.end("nope");
|
||||
}));
|
||||
|
||||
const out = path.join(tmpDir, "fail.mp4");
|
||||
await expect(downloadToFile(`http://127.0.0.1:${server.address().port}/f.mp4`, out)).rejects.toThrow(/HTTP 500/);
|
||||
expect(fs.existsSync(out)).toBe(false);
|
||||
expect(fs.existsSync(`${out}.part`)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,301 @@
|
||||
/**
|
||||
* Unit tests for the xAI video proxy core (open-sse/handlers/videoCore.js)
|
||||
*
|
||||
* Covers:
|
||||
* - registry wiring (videoConfig, grok-imagine-video kind)
|
||||
* - byte-exact body forwarding (JSON + multipart)
|
||||
* - request_id / polling-status passthrough (pending, processing, done, failed)
|
||||
* - 401 → refresh once → retry once; refresh failure → no retry loop
|
||||
* - no auto-retry of creation POSTs on network error
|
||||
* - upstream error propagation with secret sanitization
|
||||
* - abort/cancellation
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
|
||||
vi.mock("open-sse/services/tokenRefresh.js", () => ({
|
||||
refreshTokenByProvider: vi.fn(),
|
||||
}));
|
||||
|
||||
import { handleVideoProxyCore, getVideoConfig, sanitizeSecrets, VIDEO_ACTIONS } from "open-sse/handlers/videoCore.js";
|
||||
import { refreshTokenByProvider } from "open-sse/services/tokenRefresh.js";
|
||||
import { PROVIDER_MEDIA, PROVIDER_MODELS } from "open-sse/providers/index.js";
|
||||
|
||||
const originalFetch = global.fetch;
|
||||
|
||||
const jsonResponse = (body, status = 200) =>
|
||||
new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } });
|
||||
|
||||
describe("registry wiring", () => {
|
||||
it("exposes videoConfig for xai", () => {
|
||||
expect(getVideoConfig("xai")).toEqual({ baseUrl: "https://api.x.ai/v1/videos" });
|
||||
expect(PROVIDER_MEDIA.xai.serviceKinds).toContain("video");
|
||||
});
|
||||
|
||||
it("registers grok-imagine-video with kind video (kept out of LLM lists)", () => {
|
||||
const model = PROVIDER_MODELS.xai.find((m) => m.id === "grok-imagine-video");
|
||||
expect(model).toBeTruthy();
|
||||
expect(model.kind || model.type).toBe("video");
|
||||
});
|
||||
|
||||
it("supports exactly the three creation actions", () => {
|
||||
expect([...VIDEO_ACTIONS].sort()).toEqual(["edits", "extensions", "generations"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("handleVideoProxyCore", () => {
|
||||
beforeEach(() => {
|
||||
global.fetch = vi.fn();
|
||||
refreshTokenByProvider.mockReset();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
global.fetch = originalFetch;
|
||||
});
|
||||
|
||||
it("rejects providers without videoConfig", async () => {
|
||||
const result = await handleVideoProxyCore({
|
||||
provider: "openai",
|
||||
action: "generations",
|
||||
rawBody: "{}",
|
||||
credentials: { apiKey: "k" },
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.status).toBe(400);
|
||||
expect(result.error).toContain("does not support video generation");
|
||||
});
|
||||
|
||||
it("forwards a creation POST byte-for-byte and passes request_id through", async () => {
|
||||
global.fetch.mockResolvedValueOnce(jsonResponse({ request_id: "req-123" }));
|
||||
|
||||
const raw = '{"model":"grok-imagine-video","prompt":"neon city","duration":8}';
|
||||
const result = await handleVideoProxyCore({
|
||||
provider: "xai",
|
||||
action: "generations",
|
||||
rawBody: raw,
|
||||
contentType: "application/json",
|
||||
idempotencyKey: "idem-1",
|
||||
credentials: { accessToken: "tok-A", refreshToken: "ref-A" },
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
const [url, init] = global.fetch.mock.calls[0];
|
||||
expect(url).toBe("https://api.x.ai/v1/videos/generations");
|
||||
expect(init.method).toBe("POST");
|
||||
expect(init.body).toBe(raw); // byte-exact, no reshaping
|
||||
expect(init.headers.Authorization).toBe("Bearer tok-A");
|
||||
expect(init.headers["Content-Type"]).toBe("application/json");
|
||||
expect(init.headers["Idempotency-Key"]).toBe("idem-1");
|
||||
|
||||
expect(await result.response.json()).toEqual({ request_id: "req-123" });
|
||||
});
|
||||
|
||||
it("forwards multipart bodies untouched with the original boundary header", async () => {
|
||||
global.fetch.mockResolvedValueOnce(jsonResponse({ request_id: "req-mp" }));
|
||||
|
||||
const boundary = "----vitestBoundary42";
|
||||
const multipartBody = Buffer.from(
|
||||
`--${boundary}\r\nContent-Disposition: form-data; name="prompt"\r\n\r\nextend it\r\n--${boundary}--\r\n`
|
||||
);
|
||||
const result = await handleVideoProxyCore({
|
||||
provider: "xai",
|
||||
action: "extensions",
|
||||
rawBody: multipartBody,
|
||||
contentType: `multipart/form-data; boundary=${boundary}`,
|
||||
credentials: { apiKey: "xai-key" },
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
const [url, init] = global.fetch.mock.calls[0];
|
||||
expect(url).toBe("https://api.x.ai/v1/videos/extensions");
|
||||
expect(init.body).toBe(multipartBody); // same Buffer, no re-encode
|
||||
expect(init.headers["Content-Type"]).toBe(`multipart/form-data; boundary=${boundary}`);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["pending", { status: "pending", progress: 10 }],
|
||||
["processing", { status: "processing", progress: 55 }],
|
||||
["done", { status: "done", video: { url: "https://cdn.x.ai/v.mp4", duration: 8 } }],
|
||||
])("passes %s polling payload through verbatim", async (_label, payload) => {
|
||||
global.fetch.mockResolvedValueOnce(jsonResponse(payload));
|
||||
|
||||
const result = await handleVideoProxyCore({
|
||||
provider: "xai",
|
||||
requestId: "req-123",
|
||||
credentials: { accessToken: "tok" },
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
const [url, init] = global.fetch.mock.calls[0];
|
||||
expect(url).toBe("https://api.x.ai/v1/videos/req-123");
|
||||
expect(init.method).toBe("GET");
|
||||
expect(await result.response.json()).toEqual(payload);
|
||||
});
|
||||
|
||||
it("passes a failed job (HTTP 200, status failed) through without translating", async () => {
|
||||
const payload = { status: "failed", error: { code: "internal_error", message: "render crashed" } };
|
||||
global.fetch.mockResolvedValueOnce(jsonResponse(payload));
|
||||
|
||||
const result = await handleVideoProxyCore({
|
||||
provider: "xai",
|
||||
requestId: "req-bad",
|
||||
credentials: { accessToken: "tok" },
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(await result.response.json()).toEqual(payload);
|
||||
});
|
||||
|
||||
it("url-encodes the request id when polling", async () => {
|
||||
global.fetch.mockResolvedValueOnce(jsonResponse({ status: "pending" }));
|
||||
await handleVideoProxyCore({
|
||||
provider: "xai",
|
||||
requestId: "id with/slash",
|
||||
credentials: { accessToken: "tok" },
|
||||
});
|
||||
expect(global.fetch.mock.calls[0][0]).toBe("https://api.x.ai/v1/videos/id%20with%2Fslash");
|
||||
});
|
||||
|
||||
it("401 → refreshes once and retries once with the new token", async () => {
|
||||
global.fetch
|
||||
.mockResolvedValueOnce(jsonResponse({ error: "expired" }, 401))
|
||||
.mockResolvedValueOnce(jsonResponse({ request_id: "req-after-refresh" }));
|
||||
refreshTokenByProvider.mockResolvedValueOnce({ accessToken: "tok-NEW", refreshToken: "ref-NEW" });
|
||||
|
||||
const credentials = { accessToken: "tok-OLD", refreshToken: "ref-OLD" };
|
||||
const onCredentialsRefreshed = vi.fn();
|
||||
|
||||
const result = await handleVideoProxyCore({
|
||||
provider: "xai",
|
||||
action: "generations",
|
||||
rawBody: '{"prompt":"x"}',
|
||||
contentType: "application/json",
|
||||
credentials,
|
||||
onCredentialsRefreshed,
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(refreshTokenByProvider).toHaveBeenCalledTimes(1);
|
||||
expect(global.fetch).toHaveBeenCalledTimes(2);
|
||||
expect(global.fetch.mock.calls[1][1].headers.Authorization).toBe("Bearer tok-NEW");
|
||||
expect(onCredentialsRefreshed).toHaveBeenCalledWith(expect.objectContaining({ accessToken: "tok-NEW" }));
|
||||
expect(await result.response.json()).toEqual({ request_id: "req-after-refresh" });
|
||||
});
|
||||
|
||||
it("401 twice → still only one refresh and one retry (no loop)", async () => {
|
||||
global.fetch
|
||||
.mockResolvedValueOnce(jsonResponse({ error: "expired" }, 401))
|
||||
.mockResolvedValueOnce(jsonResponse({ error: "still expired" }, 401));
|
||||
refreshTokenByProvider.mockResolvedValueOnce({ accessToken: "tok-NEW" });
|
||||
|
||||
const result = await handleVideoProxyCore({
|
||||
provider: "xai",
|
||||
action: "generations",
|
||||
rawBody: "{}",
|
||||
credentials: { accessToken: "tok-OLD", refreshToken: "ref" },
|
||||
});
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.status).toBe(401);
|
||||
expect(refreshTokenByProvider).toHaveBeenCalledTimes(1);
|
||||
expect(global.fetch).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("failed refresh → 401 propagates with a single upstream call (account flagged for re-auth upstream)", async () => {
|
||||
global.fetch.mockResolvedValueOnce(jsonResponse({ error: "expired" }, 401));
|
||||
refreshTokenByProvider.mockResolvedValueOnce(null);
|
||||
|
||||
const result = await handleVideoProxyCore({
|
||||
provider: "xai",
|
||||
action: "generations",
|
||||
rawBody: "{}",
|
||||
credentials: { accessToken: "tok-OLD", refreshToken: "ref" },
|
||||
});
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.status).toBe(401);
|
||||
expect(global.fetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("API-key accounts (no refreshToken) never attempt refresh on 401", async () => {
|
||||
global.fetch.mockResolvedValueOnce(jsonResponse({ error: "bad key" }, 401));
|
||||
|
||||
const result = await handleVideoProxyCore({
|
||||
provider: "xai",
|
||||
action: "generations",
|
||||
rawBody: "{}",
|
||||
credentials: { apiKey: "xai-key" },
|
||||
});
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(refreshTokenByProvider).not.toHaveBeenCalled();
|
||||
expect(global.fetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("never re-sends a creation POST after a network error", async () => {
|
||||
global.fetch.mockRejectedValueOnce(new Error("socket hang up"));
|
||||
|
||||
const result = await handleVideoProxyCore({
|
||||
provider: "xai",
|
||||
action: "generations",
|
||||
rawBody: "{}",
|
||||
credentials: { accessToken: "tok", refreshToken: "ref" },
|
||||
});
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.status).toBe(502);
|
||||
expect(global.fetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("sanitizes bearer tokens and credential values out of upstream errors", async () => {
|
||||
global.fetch.mockResolvedValueOnce(
|
||||
jsonResponse({ error: "denied for Bearer sk-secret-token-value-123456 (token tok-SECRETSECRET)" }, 403)
|
||||
);
|
||||
|
||||
const result = await handleVideoProxyCore({
|
||||
provider: "xai",
|
||||
action: "generations",
|
||||
rawBody: "{}",
|
||||
credentials: { apiKey: "tok-SECRETSECRET" },
|
||||
});
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).not.toContain("sk-secret-token-value-123456");
|
||||
expect(result.error).not.toContain("tok-SECRETSECRET");
|
||||
expect(result.error).toContain("[redacted]");
|
||||
});
|
||||
|
||||
it("maps client aborts to 408 without retrying", async () => {
|
||||
const abortError = new Error("This operation was aborted");
|
||||
abortError.name = "AbortError";
|
||||
global.fetch.mockRejectedValueOnce(abortError);
|
||||
|
||||
const result = await handleVideoProxyCore({
|
||||
provider: "xai",
|
||||
action: "generations",
|
||||
rawBody: "{}",
|
||||
credentials: { accessToken: "tok" },
|
||||
signal: new AbortController().signal,
|
||||
});
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.status).toBe(408);
|
||||
expect(global.fetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sanitizeSecrets", () => {
|
||||
it("redacts bearer tokens", () => {
|
||||
expect(sanitizeSecrets("Authorization: Bearer abc.def-ghi_jkl")).not.toContain("abc.def-ghi_jkl");
|
||||
});
|
||||
|
||||
it("redacts explicit credential values", () => {
|
||||
const creds = { accessToken: "supersecretaccess", refreshToken: "supersecretrefresh" };
|
||||
const out = sanitizeSecrets("leak supersecretaccess and supersecretrefresh", creds);
|
||||
expect(out).toBe("leak [redacted] and [redacted]");
|
||||
});
|
||||
|
||||
it("leaves normal text untouched", () => {
|
||||
expect(sanitizeSecrets("video render failed: invalid_argument")).toBe("video render failed: invalid_argument");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,221 @@
|
||||
/**
|
||||
* Unit tests for the app-side video handler (src/sse/handlers/videoGeneration.js)
|
||||
*
|
||||
* Covers:
|
||||
* - `xai/` model prefix stripping before the body is forwarded upstream
|
||||
* - byte-exact forwarding when no prefix rewrite is needed
|
||||
* - multi-account selection (preferred connection id, rotation on 401)
|
||||
* - NO rotation on 5xx creation errors (a job may already exist upstream)
|
||||
* - connection id surfaced via x-9router-connection-id
|
||||
* - GET polling pinned to x-connection-id, no rotation
|
||||
* - refresh failure recorded via markAccountUnavailable (dashboard re-auth signal)
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
|
||||
const authMocks = vi.hoisted(() => ({
|
||||
getProviderCredentials: vi.fn(),
|
||||
markAccountUnavailable: vi.fn(async () => ({ shouldFallback: true, cooldownMs: 0 })),
|
||||
clearAccountError: vi.fn(async () => {}),
|
||||
extractApiKey: vi.fn(() => null),
|
||||
isValidApiKey: vi.fn(async () => true),
|
||||
}));
|
||||
const tokenMocks = vi.hoisted(() => ({
|
||||
checkAndRefreshToken: vi.fn(async (_p, creds) => creds),
|
||||
updateProviderCredentials: vi.fn(async () => {}),
|
||||
}));
|
||||
|
||||
vi.mock("@/sse/services/auth.js", () => authMocks);
|
||||
vi.mock("@/sse/services/tokenRefresh.js", () => tokenMocks);
|
||||
vi.mock("@/lib/localDb", () => ({
|
||||
getSettings: vi.fn(async () => ({ requireApiKey: false })),
|
||||
getComboByName: vi.fn(async () => null),
|
||||
getModelAliases: vi.fn(async () => ({})),
|
||||
getProviderNodes: vi.fn(async () => []),
|
||||
}));
|
||||
vi.mock("@/sse/utils/logger.js", () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }));
|
||||
|
||||
import { handleVideoCreate, handleVideoGet } from "@/sse/handlers/videoGeneration.js";
|
||||
|
||||
const originalFetch = global.fetch;
|
||||
|
||||
const jsonResponse = (body, status = 200) =>
|
||||
new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } });
|
||||
|
||||
const makeRequest = (body, { headers = {}, contentType = "application/json" } = {}) =>
|
||||
new Request("http://localhost/v1/videos/generations", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": contentType, ...headers },
|
||||
body: typeof body === "string" ? body : JSON.stringify(body),
|
||||
});
|
||||
|
||||
const account = (overrides = {}) => ({
|
||||
connectionId: "conn-1",
|
||||
accessToken: "tok-1",
|
||||
refreshToken: "ref-1",
|
||||
authType: "oauth",
|
||||
...overrides,
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
global.fetch = vi.fn();
|
||||
authMocks.getProviderCredentials.mockReset();
|
||||
authMocks.markAccountUnavailable.mockClear();
|
||||
authMocks.clearAccountError.mockClear();
|
||||
tokenMocks.checkAndRefreshToken.mockClear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
global.fetch = originalFetch;
|
||||
});
|
||||
|
||||
describe("handleVideoCreate", () => {
|
||||
it("strips the xai/ prefix from model before forwarding", async () => {
|
||||
authMocks.getProviderCredentials.mockResolvedValueOnce(account());
|
||||
global.fetch.mockResolvedValueOnce(jsonResponse({ request_id: "r1" }));
|
||||
|
||||
const res = await handleVideoCreate(
|
||||
makeRequest({ model: "xai/grok-imagine-video", prompt: "a cat" }),
|
||||
"generations"
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const forwarded = JSON.parse(global.fetch.mock.calls[0][1].body);
|
||||
expect(forwarded.model).toBe("grok-imagine-video");
|
||||
expect(forwarded.prompt).toBe("a cat");
|
||||
});
|
||||
|
||||
it("forwards the original raw JSON bytes when no rewrite is needed", async () => {
|
||||
authMocks.getProviderCredentials.mockResolvedValueOnce(account());
|
||||
global.fetch.mockResolvedValueOnce(jsonResponse({ request_id: "r1" }));
|
||||
|
||||
// Odd spacing survives only if we forward the raw string untouched
|
||||
const raw = '{ "model" : "grok-imagine-video", "prompt" : "spaced" }';
|
||||
await handleVideoCreate(makeRequest(raw), "generations");
|
||||
|
||||
expect(global.fetch.mock.calls[0][1].body).toBe(raw);
|
||||
});
|
||||
|
||||
it("rejects providers without video support", async () => {
|
||||
const res = await handleVideoCreate(
|
||||
makeRequest({ model: "openai/sora-alike", prompt: "x" }),
|
||||
"generations"
|
||||
);
|
||||
expect(res.status).toBe(400);
|
||||
expect(await res.text()).toContain("does not support video generation");
|
||||
expect(global.fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns the serving connection id in x-9router-connection-id", async () => {
|
||||
authMocks.getProviderCredentials.mockResolvedValueOnce(account({ connectionId: "conn-77" }));
|
||||
global.fetch.mockResolvedValueOnce(jsonResponse({ request_id: "r1" }));
|
||||
|
||||
const res = await handleVideoCreate(makeRequest({ prompt: "x" }), "generations");
|
||||
expect(res.headers.get("x-9router-connection-id")).toBe("conn-77");
|
||||
expect(await res.json()).toEqual({ request_id: "r1" });
|
||||
});
|
||||
|
||||
it("honors preferred x-connection-id when selecting the account", async () => {
|
||||
authMocks.getProviderCredentials.mockResolvedValueOnce(account());
|
||||
global.fetch.mockResolvedValueOnce(jsonResponse({ request_id: "r1" }));
|
||||
|
||||
await handleVideoCreate(
|
||||
makeRequest({ prompt: "x" }, { headers: { "x-connection-id": "conn-9" } }),
|
||||
"generations"
|
||||
);
|
||||
|
||||
expect(authMocks.getProviderCredentials).toHaveBeenCalledWith(
|
||||
"xai", expect.anything(), null, expect.objectContaining({ preferredConnectionId: "conn-9" })
|
||||
);
|
||||
});
|
||||
|
||||
it("rotates to the next account on 401 (auth errors cannot have created a job)", async () => {
|
||||
authMocks.getProviderCredentials
|
||||
.mockResolvedValueOnce(account({ connectionId: "conn-1", refreshToken: null }))
|
||||
.mockResolvedValueOnce(account({ connectionId: "conn-2", accessToken: "tok-2", refreshToken: null }));
|
||||
global.fetch
|
||||
.mockResolvedValueOnce(jsonResponse({ error: "unauthorized" }, 401))
|
||||
.mockResolvedValueOnce(jsonResponse({ request_id: "r2" }));
|
||||
|
||||
const res = await handleVideoCreate(makeRequest({ prompt: "x" }), "generations");
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("x-9router-connection-id")).toBe("conn-2");
|
||||
expect(authMocks.markAccountUnavailable).toHaveBeenCalledWith(
|
||||
"conn-1", 401, expect.any(String), "xai", null
|
||||
);
|
||||
});
|
||||
|
||||
it("does NOT rotate accounts on a 500 creation error (job may exist upstream)", async () => {
|
||||
authMocks.getProviderCredentials.mockResolvedValueOnce(account({ refreshToken: null }));
|
||||
global.fetch.mockResolvedValueOnce(jsonResponse({ error: "boom" }, 500));
|
||||
|
||||
const res = await handleVideoCreate(makeRequest({ prompt: "x" }), "generations");
|
||||
|
||||
expect(res.status).toBe(500);
|
||||
expect(global.fetch).toHaveBeenCalledTimes(1);
|
||||
expect(authMocks.getProviderCredentials).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("forwards multipart bodies byte-exact with default xai provider", async () => {
|
||||
authMocks.getProviderCredentials.mockResolvedValueOnce(account());
|
||||
global.fetch.mockResolvedValueOnce(jsonResponse({ request_id: "r-mp" }));
|
||||
|
||||
const boundary = "----handlerBoundary";
|
||||
const raw = `--${boundary}\r\nContent-Disposition: form-data; name="prompt"\r\n\r\nedit\r\n--${boundary}--\r\n`;
|
||||
const req = new Request("http://localhost/v1/videos/edits", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": `multipart/form-data; boundary=${boundary}` },
|
||||
body: raw,
|
||||
});
|
||||
|
||||
const res = await handleVideoCreate(req, "edits");
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
const [url, init] = global.fetch.mock.calls[0];
|
||||
expect(url).toBe("https://api.x.ai/v1/videos/edits");
|
||||
expect(Buffer.from(init.body).toString()).toBe(raw);
|
||||
expect(init.headers["Content-Type"]).toContain(boundary);
|
||||
});
|
||||
|
||||
it("returns 400 when no credentials are connected", async () => {
|
||||
authMocks.getProviderCredentials.mockResolvedValueOnce(null);
|
||||
const res = await handleVideoCreate(makeRequest({ prompt: "x" }), "generations");
|
||||
expect(res.status).toBe(400);
|
||||
expect(await res.text()).toContain("No credentials for provider: xai");
|
||||
});
|
||||
|
||||
it("returns 400 on invalid JSON", async () => {
|
||||
const res = await handleVideoCreate(makeRequest("{not json"), "generations");
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe("handleVideoGet", () => {
|
||||
it("polls upstream pinned to the x-connection-id account and passes status through", async () => {
|
||||
authMocks.getProviderCredentials.mockResolvedValueOnce(account({ connectionId: "conn-5" }));
|
||||
global.fetch.mockResolvedValueOnce(jsonResponse({ status: "pending", progress: 42 }));
|
||||
|
||||
const req = new Request("http://localhost/v1/videos/req-1", {
|
||||
headers: { "x-connection-id": "conn-5" },
|
||||
});
|
||||
const res = await handleVideoGet(req, "req-1");
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({ status: "pending", progress: 42 });
|
||||
expect(authMocks.getProviderCredentials).toHaveBeenCalledWith(
|
||||
"xai", null, null, expect.objectContaining({ preferredConnectionId: "conn-5" })
|
||||
);
|
||||
expect(global.fetch.mock.calls[0][0]).toBe("https://api.x.ai/v1/videos/req-1");
|
||||
});
|
||||
|
||||
it("records the failure when polling hits a terminal auth error", async () => {
|
||||
authMocks.getProviderCredentials.mockResolvedValueOnce(account({ refreshToken: null }));
|
||||
global.fetch.mockResolvedValueOnce(jsonResponse({ error: "unauthorized" }, 401));
|
||||
|
||||
const res = await handleVideoGet(new Request("http://localhost/v1/videos/req-1"), "req-1");
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
expect(authMocks.markAccountUnavailable).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user