ManiCandles/test/api.test.ts

205 lines
7.3 KiB
TypeScript

import { test, afterEach } from "node:test";
import assert from "node:assert/strict";
import {
apiRequest,
apiPdf,
listProducts,
getProduct,
login,
getPrincipal,
healthCheck,
ApiError,
} from "../src/lib/api.ts";
import { documentDecision, maxDocumentBytes, prepareDocumentUpload } from "../src/lib/supplier-documents.ts";
const originalFetch = globalThis.fetch;
const org = "d66c798a-f764-4b88-8d13-ace328ff1010";
afterEach(() => {
globalThis.fetch = originalFetch;
});
test("supplier document upload sends an authenticated multipart file with a browser-generated boundary", async () => {
const file = new File(["%PDF-1.7\n%%EOF"], "certificate.pdf", { type: "application/pdf" });
const body = prepareDocumentUpload(file);
globalThis.fetch = async (url, options) => {
assert.equal(url, `/api/v1/supplier-documents/${org}/versions`);
assert.equal(options?.method, "POST");
const headers = new Headers(options?.headers);
assert.equal(headers.get("authorization"), "Bearer opaque");
assert.equal(headers.has("content-type"), false);
assert.equal(options?.redirect, "error");
assert.equal(options?.body, body);
assert.equal(body.get("file"), file);
return new Response(JSON.stringify({ version: 1 }));
};
await apiRequest(`/supplier-documents/${org}/versions`, { method: "POST", token: "opaque", body });
assert.throws(() => prepareDocumentUpload(new File(["x"], "unsafe filename.pdf")), /simple .pdf filename/);
assert.throws(() => prepareDocumentUpload(new File([new Uint8Array(maxDocumentBytes + 1)], "large.pdf")), /2 MiB/);
assert.equal(documentDecision.safeParse({ outcome: "REJECTED", reason: " " }).success, false);
assert.equal(documentDecision.safeParse({ outcome: "APPROVED" }).success, true);
});
test("private PDF downloads preserve API denial and require the expected PDF media type and size", async () => {
const controller = new AbortController();
const path = `/supplier-document-versions/${org}/download`;
const content = "%PDF-1.7\n%%EOF";
globalThis.fetch = async (url, options) => {
assert.equal(url, `/api/v1${path}`);
const headers = new Headers(options?.headers);
assert.equal(headers.get("authorization"), "Bearer opaque");
assert.equal(headers.get("accept"), "application/pdf");
assert.equal(options?.cache, "no-store");
assert.equal(options?.redirect, "error");
return new Response(content, { headers: { "Content-Type": "application/pdf" } });
};
assert.equal(await (await apiPdf(path, content.length, "opaque", controller.signal)).text(), content);
await assert.rejects(apiPdf(path, 1, "opaque", controller.signal), { code: "INVALID_RESPONSE" });
globalThis.fetch = async () => new Response(content, { headers: { "Content-Type": "text/html" } });
await assert.rejects(apiPdf(path, content.length, "opaque", controller.signal), { code: "INVALID_RESPONSE" });
globalThis.fetch = async () => Response.json({ code: "DOCUMENT_PENDING_REVIEW" }, { status: 403 });
await assert.rejects(apiPdf(path, content.length, "opaque", controller.signal), { code: "DOCUMENT_PENDING_REVIEW", status: 403 });
});
test("invalid organization cannot trigger catalog requests", async () => {
globalThis.fetch = async () => {
assert.fail("Must not send a request");
};
await assert.rejects(listProducts("../auth/me"));
});
test("catalog search is encoded and uses the deployed list shape", async () => {
globalThis.fetch = async (url) => {
assert.equal(
url,
`/api/v1/storefront/${org}/products?limit=12&offset=12&search=rose+%26+oud`,
);
return new Response(
JSON.stringify([{ id: org, name: "Rose", slug: "rose" }]),
);
};
assert.equal((await listProducts(org, "rose & oud", 12))[0].name, "Rose");
});
test("product variants retain exact decimal and currency strings", async () => {
globalThis.fetch = async () =>
new Response(
JSON.stringify({
id: org,
name: "Rose",
slug: "rose",
description: "",
variants: [
{
id: org,
name: "Small",
sku: "ROSE",
price: "123.45",
currency: "INR",
attributes: {},
},
],
groups: [],
}),
);
assert.equal((await getProduct(org, org)).variants[0].price, "123.45");
});
test("login uses strict body and me uses opaque bearer token", async () => {
globalThis.fetch = async (url, options) => {
assert.equal(url, "/api/v1/auth/login");
assert.deepEqual(JSON.parse(options?.body as string), {
organizationId: org,
email: "staff@example.com",
password: "private",
});
return new Response(
JSON.stringify({
accessToken: "opaque",
tokenType: "Bearer",
expiresAt: "2026-10-12T00:00:00.000Z",
}),
);
};
const session = await login(org, "staff@example.com", "private");
globalThis.fetch = async (url, options) => {
assert.equal(
new Headers(options?.headers).get("Authorization"),
"Bearer opaque",
);
return new Response(
JSON.stringify({
userId: org,
organizationId: org,
sessionId: org,
permissions: ["products.read"],
}),
);
};
assert.deepEqual((await getPrincipal(session.accessToken)).permissions, [
"products.read",
]);
});
test("logout accepts 204 and errors retain code and request reference", async () => {
globalThis.fetch = async () => new Response(null, { status: 204 });
assert.equal(await apiRequest("/auth/logout", { method: "POST" }), null);
globalThis.fetch = async () =>
new Response(
JSON.stringify({
message: "Denied",
code: "ACCESS_DENIED",
requestId: "ref",
}),
{ status: 403 },
);
await assert.rejects(
apiRequest("/auth/me"),
(e) =>
e instanceof ApiError &&
e.status === 403 &&
e.requestId === "ref" &&
e.code === "ACCESS_DENIED",
);
});
test("network errors are sanitized and aborts stay cancellable", async () => {
globalThis.fetch = async () => {
throw new Error("internal host");
};
await assert.rejects(
apiRequest("/health/live"),
(e) =>
e instanceof ApiError &&
e.code === "NETWORK_ERROR" &&
!e.message.includes("internal"),
);
globalThis.fetch = async () => {
throw new DOMException("Aborted", "AbortError");
};
await assert.rejects(
apiRequest("/health/live"),
(e) => e instanceof Error && e.name === "AbortError",
);
});
test("malformed catalog and unsuccessful readiness status are rejected", async () => {
globalThis.fetch = async () => new Response(JSON.stringify({ products: [] }));
await assert.rejects(
listProducts(org),
(e) => e instanceof ApiError && e.code === "INVALID_RESPONSE",
);
globalThis.fetch = async () =>
new Response(JSON.stringify({ status: "failed" }));
await assert.rejects(healthCheck("ready"));
});
test("malformed diagnostic values cannot leak objects into UI rendering", async () => {
globalThis.fetch = async () =>
new Response(
JSON.stringify({
message: ["invalid"],
code: { private: "details" },
requestId: { bad: true },
}),
{ status: 400, headers: { "x-request-id": "safe-ref" } },
);
await assert.rejects(
apiRequest("/auth/login"),
(error) =>
error instanceof ApiError &&
error.code === undefined &&
error.requestId === "safe-ref",
);
});