| import test from "node:test"; |
| import assert from "node:assert/strict"; |
| import { mkdtemp, writeFile, rm } from "node:fs/promises"; |
| import { tmpdir } from "node:os"; |
| import path from "node:path"; |
| import { createApp } from "../src/app.js"; |
|
|
| test("applies permissive CORS headers to API responses and preflight requests", async () => { |
| const publicDir = await mkdtemp(path.join(tmpdir(), "oapix-app-test-")); |
| await writeFile(path.join(publicDir, "index.html"), "<!doctype html><title>test</title>"); |
|
|
| const app = createApp({ |
| jsonLimit: "1mb", |
| publicDir, |
| chatController(_req, res) { |
| res.json({ ok: true }); |
| }, |
| mediaController(_req, res) { |
| res.json({ media: true }); |
| } |
| }); |
|
|
| const server = await new Promise((resolve) => { |
| const nextServer = app.listen(0, () => resolve(nextServer)); |
| }); |
|
|
| const address = server.address(); |
| const baseUrl = `http://127.0.0.1:${address.port}`; |
|
|
| try { |
| const response = await fetch(`${baseUrl}/v1/chat/completions`, { |
| method: "POST", |
| headers: { |
| origin: "https://example.com", |
| "content-type": "application/json" |
| }, |
| body: JSON.stringify({ model: "test", messages: [] }) |
| }); |
|
|
| assert.equal(response.status, 200); |
| assert.equal(response.headers.get("access-control-allow-origin"), "*"); |
| assert.equal(response.headers.get("access-control-allow-methods"), "GET,POST,PUT,PATCH,DELETE,OPTIONS"); |
|
|
| const preflight = await fetch(`${baseUrl}/v1/chat/completions`, { |
| method: "OPTIONS", |
| headers: { |
| origin: "https://example.com", |
| "access-control-request-method": "POST", |
| "access-control-request-headers": "content-type, authorization" |
| } |
| }); |
|
|
| assert.equal(preflight.status, 204); |
| assert.equal(preflight.headers.get("access-control-allow-origin"), "*"); |
| assert.equal(preflight.headers.get("access-control-allow-methods"), "GET,POST,PUT,PATCH,DELETE,OPTIONS"); |
| assert.equal(preflight.headers.get("access-control-allow-headers"), "content-type, authorization"); |
| } finally { |
| await new Promise((resolve, reject) => { |
| server.close((error) => { |
| if (error) { |
| reject(error); |
| return; |
| } |
|
|
| resolve(); |
| }); |
| }); |
| await rm(publicDir, { recursive: true, force: true }); |
| } |
| }); |
|
|