diff --git a/services/appraisal-api/README.md b/services/appraisal-api/README.md index 105d7910..1126268a 100644 --- a/services/appraisal-api/README.md +++ b/services/appraisal-api/README.md @@ -71,6 +71,14 @@ A `POST /appraise` body larger than 8192 bytes is rejected with **HTTP 413** `{ "error": "payload_too_large", "limitBytes": 8192 }` before the bytes are parsed as JSON, so the request never receives a 402 payment quote. +`POST /appraise` requires `Content-Type: application/json`. A `charset` +parameter is allowed only when it is UTF-8 (`application/json; charset=utf-8`). +Any other media type, a non-UTF-8 charset, or a missing header is rejected with +**HTTP 415** `{ "error": "unsupported_media_type", "expected": "application/json" }` +and an `Accept-Post: application/json` header, before the body is read and +before any payment quote is built. Clients using `createPaidFetch` must set the +header themselves, as in the examples. + All appraisal quote challenges (`402`), paid appraisal responses (`200`), and error responses include `Cache-Control: no-store`, `Pragma: no-cache`, `Expires: 0`, and `X-Content-Type-Options: nosniff` so intermediary caches diff --git a/services/appraisal-api/package.json b/services/appraisal-api/package.json index 3f5a2ef4..bfaf4dcf 100644 --- a/services/appraisal-api/package.json +++ b/services/appraisal-api/package.json @@ -12,7 +12,7 @@ "main": "src/index.ts", "scripts": { "start": "node --import tsx src/run.ts", - "test": "node --import tsx --test src/appraisal.test.ts src/appraisal-fixtures.test.ts src/config.test.ts src/client.test.ts src/quote-guard.test.ts src/quote-rate-limit.test.ts src/body-limit.test.ts", + "test": "node --import tsx --test src/appraisal.test.ts src/appraisal-fixtures.test.ts src/config.test.ts src/client.test.ts src/quote-guard.test.ts src/quote-rate-limit.test.ts src/body-limit.test.ts src/content-type.test.ts", "typecheck": "tsc --noEmit -p tsconfig.json" }, "dependencies": { diff --git a/services/appraisal-api/src/content-type.test.ts b/services/appraisal-api/src/content-type.test.ts new file mode 100644 index 00000000..a4f1e0d9 --- /dev/null +++ b/services/appraisal-api/src/content-type.test.ts @@ -0,0 +1,176 @@ +// Copyright (c) 2026 Sub Rosa contributors +import assert from "node:assert/strict"; +import { once } from "node:events"; +import http from "node:http"; +import { describe, test } from "node:test"; + +import { Keypair, Networks } from "@stellar/stellar-sdk"; +import { STELLAR_TESTNET_CAIP2, USDC_TESTNET_ADDRESS } from "@x402/stellar"; + +import { + APPRAISAL_UNSUPPORTED_MEDIA_TYPE, + appraisalUnsupportedMediaTypeBody, + isAppraisalJsonContentType, +} from "./content-type.js"; +import { validRequest } from "./fixtures/index.js"; +import { buildAppraisalServer } from "./server.js"; + +describe("isAppraisalJsonContentType", () => { + test("accepts application/json with and without a UTF-8 charset", () => { + for (const header of [ + "application/json", + "application/json; charset=utf-8", + "application/json;charset=utf-8", + "application/json ; charset=UTF-8", + 'application/json; charset="utf-8"', + "APPLICATION/JSON; CHARSET=Utf-8", + "application/json; charset=utf8", + "application/json; boundary=ignored", + ]) { + assert.equal(isAppraisalJsonContentType(header), true, header); + } + }); + + test("rejects a missing header and every other media type", () => { + for (const header of [ + undefined, + "", + " ", + "text/plain", + "text/json", + "text/html", + "application/x-www-form-urlencoded", + "multipart/form-data; boundary=abc", + "application/xml", + "application/jsonp", + "application/jsonx", + "application/json-patch+json", + "application/vnd.api+json", + "application/json,text/html", + "json", + ]) { + assert.equal(isAppraisalJsonContentType(header), false, String(header)); + } + }); + + test("rejects a JSON type whose charset the server cannot decode", () => { + for (const header of [ + "application/json; charset=iso-8859-1", + "application/json; charset=utf-16", + 'application/json; charset="latin1"', + "application/json; charset=", + ]) { + assert.equal(isAppraisalJsonContentType(header), false, header); + } + }); + + test("the 415 body is stable", () => { + assert.deepEqual(appraisalUnsupportedMediaTypeBody(), { + error: "unsupported_media_type", + expected: "application/json", + }); + assert.equal(APPRAISAL_UNSUPPORTED_MEDIA_TYPE, "unsupported_media_type"); + }); +}); + +async function startServer(): Promise<{ server: http.Server; url: string }> { + const facilitator = Keypair.fromRawEd25519Seed(Buffer.alloc(32, 3)); + const payee = Keypair.fromRawEd25519Seed(Buffer.alloc(32, 4)); + const server = await buildAppraisalServer( + { + facilitatorSecret: facilitator.secret(), + payTo: payee.publicKey(), + asset: USDC_TESTNET_ADDRESS, + price: 0.1, + network: STELLAR_TESTNET_CAIP2, + networkPassphrase: Networks.TESTNET, + rpcUrl: "https://soroban-testnet.stellar.org", + port: 0, + }, + { nowSeconds: () => 1_700_000_000 }, + ); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const address = server.address(); + if (address === null || typeof address === "string") throw new Error("expected a TCP port"); + return { server, url: `http://127.0.0.1:${address.port}/appraise` }; +} + +describe("POST /appraise media type", () => { + test("returns a stable 415 for unsupported media types, before any payment offer", async () => { + const { server, url } = await startServer(); + try { + for (const headers of [ + { "content-type": "text/plain" }, + { "content-type": "application/x-www-form-urlencoded" }, + { "content-type": "application/json; charset=iso-8859-1" }, + {} as Record, + ]) { + const res = await fetch(url, { + method: "POST", + headers, + body: JSON.stringify(validRequest.value), + }); + const label = JSON.stringify(headers); + assert.equal(res.status, 415, label); + assert.deepEqual(await res.json(), appraisalUnsupportedMediaTypeBody(), label); + assert.equal(res.headers.get("accept-post"), "application/json", label); + assert.equal(res.headers.get("cache-control"), "no-store", label); + assert.equal(res.headers.get("x-content-type-options"), "nosniff", label); + assert.equal(res.headers.get("payment-required"), null, "no payment quote on a 415"); + } + } finally { + server.closeAllConnections?.(); + server.close(); + } + }); + + test("an empty body with an unsupported type is 415, not 400 or 402", async () => { + const { server, url } = await startServer(); + try { + const res = await fetch(url, { method: "POST", headers: { "content-type": "text/plain" }, body: "" }); + assert.equal(res.status, 415); + } finally { + server.closeAllConnections?.(); + server.close(); + } + }); + + test("valid JSON with a charset parameter still reaches the payment challenge", async () => { + const { server, url } = await startServer(); + try { + for (const contentType of ["application/json", "application/json; charset=utf-8"]) { + const res = await fetch(url, { + method: "POST", + headers: { "content-type": contentType }, + body: JSON.stringify(validRequest.value), + }); + assert.equal(res.status, 402, contentType); + } + } finally { + server.closeAllConnections?.(); + server.close(); + } + }); + + test("a supported type with an invalid body keeps its existing 400", async () => { + const { server, url } = await startServer(); + try { + const bad = await fetch(url, { + method: "POST", + headers: { "content-type": "application/json; charset=utf-8" }, + body: "{not json", + }); + assert.equal(bad.status, 400); + const empty = await fetch(url, { + method: "POST", + headers: { "content-type": "application/json" }, + body: "", + }); + assert.equal(empty.status, 400); + } finally { + server.closeAllConnections?.(); + server.close(); + } + }); +}); diff --git a/services/appraisal-api/src/content-type.ts b/services/appraisal-api/src/content-type.ts new file mode 100644 index 00000000..99f49820 --- /dev/null +++ b/services/appraisal-api/src/content-type.ts @@ -0,0 +1,48 @@ +// Copyright (c) 2026 Sub Rosa contributors + +/** Stable error code for a `POST /appraise` with an unsupported media type. */ +export const APPRAISAL_UNSUPPORTED_MEDIA_TYPE = "unsupported_media_type"; + +/** The only media type `POST /appraise` accepts. */ +export const APPRAISAL_MEDIA_TYPE = "application/json"; + +/** Charsets the server can decode (bodies are read as UTF-8). */ +const SUPPORTED_CHARSETS = new Set(["utf-8", "utf8"]); + +/** Stable 415 body: callers can branch on `error` and read the expected type. */ +export function appraisalUnsupportedMediaTypeBody(): { + error: typeof APPRAISAL_UNSUPPORTED_MEDIA_TYPE; + expected: typeof APPRAISAL_MEDIA_TYPE; +} { + return { error: APPRAISAL_UNSUPPORTED_MEDIA_TYPE, expected: APPRAISAL_MEDIA_TYPE }; +} + +function unquote(value: string): string { + return value.length >= 2 && value.startsWith('"') && value.endsWith('"') + ? value.slice(1, -1) + : value; +} + +/** + * True when a `Content-Type` header value is `application/json`, optionally with + * parameters. The media type is matched case-insensitively and exactly, so + * `application/jsonp`, `text/json` and `application/json-patch+json` are all + * rejected. A `charset` parameter is allowed only when it is UTF-8, because the + * body is decoded as UTF-8; any other charset would be silently mis-decoded. + * A missing or empty header is not acceptable. + */ +export function isAppraisalJsonContentType(header: string | undefined): boolean { + if (typeof header !== "string") return false; + const [mediaType = "", ...params] = header.split(";"); + if (mediaType.trim().toLowerCase() !== APPRAISAL_MEDIA_TYPE) return false; + + for (const param of params) { + const eq = param.indexOf("="); + if (eq === -1) continue; + const name = param.slice(0, eq).trim().toLowerCase(); + if (name !== "charset") continue; + const value = unquote(param.slice(eq + 1).trim()).toLowerCase(); + if (!SUPPORTED_CHARSETS.has(value)) return false; + } + return true; +} diff --git a/services/appraisal-api/src/server.ts b/services/appraisal-api/src/server.ts index 566e099a..3c5677f4 100644 --- a/services/appraisal-api/src/server.ts +++ b/services/appraisal-api/src/server.ts @@ -40,6 +40,11 @@ import { ExactStellarScheme as ServerStellarScheme } from "@x402/stellar/exact/s import { appraise, AppraisalInputError, buildAppraisalQuote, MAX_APPRAISAL_BODY_BYTES, parseAppraisalRequest } from "./appraisal.js"; import { takeAppraisalRequestBody } from "./body-limit.js"; import type { AppraisalServerConfig } from "./config.js"; +import { + APPRAISAL_MEDIA_TYPE, + appraisalUnsupportedMediaTypeBody, + isAppraisalJsonContentType, +} from "./content-type.js"; import { appraisalQuoteRateKey, createMemoryQuoteRateLimiter, @@ -216,6 +221,16 @@ export async function buildAppraisalServer( }); } + // Only JSON is accepted. Reject any other media type with a stable 415 + // before the body is read and before any payment offer is built. + if (method === "POST" && url.pathname === "/appraise") { + if (!isAppraisalJsonContentType(req.headers["content-type"])) { + send(res, 415, { "accept-post": APPRAISAL_MEDIA_TYPE }, appraisalUnsupportedMediaTypeBody()); + res.on("finish", () => req.destroy()); + return; + } + } + const taken = await takeAppraisalRequestBody(req, MAX_APPRAISAL_BODY_BYTES); if ("status" in taken) { // Fail closed before JSON parsing and before any payment offer.