import { EventEmitter } from "node:events"; import { readFile } from "node:fs/promises"; import type { RequestOptions } from "node:https"; import { join } from "node:path"; import { PassThrough } from "node:stream"; import { fauxAssistantMessage, fauxToolCall, InMemoryCredentialStore, } from "@earendil-works/pi-ai"; import { afterEach, describe, expect, it, vi } from "vitest"; import { createPiSession, type PiSession, } from "../../../test/fixture/create-pi-session.ts"; import minimax from "../index.ts"; const fake = vi.hoisted(() => ({ lookup: vi.fn(), request: vi.fn() })); vi.mock("node:dns/promises", () => ({ lookup: fake.lookup })); vi.mock("node:https", () => ({ request: fake.request })); import { artifactUrl, download, publicAddress } from "../src/artifacts.ts"; let fixture: PiSession | undefined; afterEach(async () => { await fixture?.dispose(); fixture = undefined; vi.unstubAllGlobals(); vi.resetAllMocks(); }); function transport( status = 200, chunks = [Buffer.from("artifact")], headers: Record = {}, ) { fake.lookup.mockResolvedValue([{ address: "8.8.8.8", family: 4 }]); fake.request.mockImplementation( ( _url: URL, options: RequestOptions, callback: ( res: PassThrough & { statusCode: number; headers: Record; }, ) => void, ) => { const req = Object.assign(new EventEmitter(), { end: () => queueMicrotask(() => { if (options.signal?.aborted) { req.emit("error", new Error("abort")); return; } const res = Object.assign(new PassThrough(), { statusCode: status, headers, }); callback(res); if (!res.destroyed) for (const chunk of chunks) res.write(chunk); res.end(); }), }); return req; }, ); } describe("HTTPS artifact authorization", () => { it("pins validated public address, keeps original TLS hostname, upgrades HTTP without API headers", async () => { transport(); const bytes = await download( "http://bucket.example/file?signature=synthetic", 100, ); expect(bytes.toString()).toBe("artifact"); expect(fake.lookup).toHaveBeenCalledOnce(); const [url, opts] = fake.request.mock.calls[0] as [URL, RequestOptions]; expect(url.href).toBe("https://bucket.example/file?signature=synthetic"); expect(opts.agent).toBe(false); expect(opts.headers).toBeUndefined(); const callback = vi.fn(); if (!opts.lookup) throw new Error("Pin missing"); opts.lookup("bucket.example", {}, callback); expect(callback).toHaveBeenCalledWith(null, "8.8.8.8", 4); }); it.each([ "127.0.0.1", "10.0.0.1", "169.254.169.254", "100.64.0.1", "192.168.0.1", "::1", "::ffff:8.8.8.8", "64:ff9b::0808:0808", "2002:0808:0808::", "2001::1", "2001:db8::1", "fc00::1", "fe80::1", ])("rejects %s without connecting", async (address) => { fake.lookup.mockResolvedValue([ { address, family: address.includes(":") ? 6 : 4 }, ]); await expect( download("https://bucket.example/?signature=synthetic", 100), ).rejects.toThrow("non-public"); expect(fake.request).not.toHaveBeenCalled(); }); it("rejects mixed public/private DNS to prevent address roulette", async () => { fake.lookup.mockResolvedValue([ { address: "8.8.8.8", family: 4 }, { address: "10.0.0.1", family: 4 }, ]); await expect(download("https://bucket.example/file", 100)).rejects.toThrow( "non-public", ); expect(fake.request).not.toHaveBeenCalled(); }); it.each([302, 403])("never follows HTTP %s or downgrades", async (status) => { transport(status, [], { location: "http://127.0.0.1/?signature=synthetic", }); await expect( download("https://bucket.example/?signature=synthetic", 100), ).rejects.toThrow("redirects rejected"); expect(fake.request).toHaveBeenCalledOnce(); }); it("enforces declared and streamed byte caps with redacted errors", async () => { transport(200, [Buffer.alloc(11)]); await expect( download("https://bucket.example/?signature=synthetic", 10), ).rejects.toThrow("byte limit"); transport(200, [], { "content-length": "100" }); await expect( download("https://bucket.example/?signature=synthetic", 10), ).rejects.toThrow("byte limit"); }); it("settles cancellation even while OS DNS lookup remains unresolved", async () => { fake.lookup.mockReturnValue(new Promise(() => {})); const ctrl = new AbortController(); const pending = download( "https://bucket.example/?signature=synthetic", 10, ctrl.signal, ); ctrl.abort(); await expect(pending).rejects.toThrow("cancelled"); expect(fake.request).not.toHaveBeenCalled(); }); it.each([ "https://user:pass@bucket.example/file", "https://bucket.example:8443/file", "file:///etc/passwd", "https://bucket.example/#secret", ])("rejects unsafe URL %s", (url) => expect(() => artifactUrl(url)).toThrow(), ); it("permits ordinary public IPv6 without permitting documentation/transition blocks", () => expect(publicAddress("2606:4700:4700::1111")).toBe(true)); }); it("real Pi retrieves owned H3 artifact safely and attaches known native usage only once", async () => { const credentials = new InMemoryCredentialStore(); await credentials.modify("minimax", async () => ({ type: "api_key", key: ["sk", "cp", "fixture"].join("-"), })); fixture = await createPiSession({ extensionFactories: [minimax], credentials, userSettings: { minimax: { videoApproval: "always" } }, env: { PI_MINIMAX_DEBUG: "0", PI_MINIMAX_VIDEO_APPROVAL: undefined, PI_MINIMAX_REGION: undefined, }, }); expect(fixture.errors).toEqual([]); const bytes = Buffer.from([ 0, 0, 0, 20, 102, 116, 121, 112, 105, 115, 111, 109, ]); transport(200, [bytes]); const fetch = vi.fn( async (_url: string | URL | Request, init?: RequestInit) => Response.json( init?.method === "POST" ? { task_id: "download-task" } : { task: { id: "download-task", model: "MiniMax-H3", status: "succeeded", resolution: "768P", duration: 4, usage: { output_seconds: 4, input_seconds: 0, input_image_count: 0, }, content: { url: "http://third-party.example/output.mp4?signature=synthetic-private", }, }, }, ), ); vi.stubGlobal("fetch", fetch); const path = join(fixture.cwd, "video.mp4"); fixture.setResponses([ fauxAssistantMessage( fauxToolCall("minimax_video", { action: "submit", job: "download", prompt: "A ball", }), { stopReason: "toolUse" }, ), fauxAssistantMessage( fauxToolCall("minimax_video", { action: "retrieve", job: "download", outputPath: path, }), { stopReason: "toolUse" }, ), fauxAssistantMessage("Done"), ]); await fixture.session.prompt("Exercise download"); const media = fixture.session.messages.filter( (m) => m.role === "toolResult" && m.toolName === "minimax_video", ); expect(media).toHaveLength(2); const returned = media[1]; expect(returned?.role).toBe("toolResult"); if (returned?.role !== "toolResult") throw new Error("Missing artifact result"); expect(returned.isError).toBe(false); expect(returned.usage?.cost.total).toBe(0.32); expect(returned.details).toMatchObject({ artifact: { path, bytes: 12, format: "mp4" }, encodedDuration: "not measured", providerSettings: { durationSeconds: 4, resolution: "768P" }, }); expect(await readFile(path)).toEqual(bytes); expect(JSON.stringify(returned)).not.toContain("synthetic-private"); expect(fake.request.mock.calls[0]?.[1].headers).toBeUndefined(); fixture.setResponses([ fauxAssistantMessage( fauxToolCall("minimax_video", { action: "retrieve", job: "download", outputPath: join(fixture.cwd, "video-again.mp4"), }), { stopReason: "toolUse" }, ), fauxAssistantMessage("Done"), ]); await fixture.session.prompt("Retrieve again"); const repeated = fixture.session.messages .filter((m) => m.role === "toolResult" && m.toolName === "minimax_video") .at(-1); expect( repeated?.role === "toolResult" ? repeated.usage : undefined, ).toBeUndefined(); expect(fetch.mock.calls.filter((c) => c[1]?.method === "POST")).toHaveLength( 1, ); });