diff --git a/docs/pr/issue-1322.md b/docs/pr/issue-1322.md new file mode 100644 index 0000000..c801b5b --- /dev/null +++ b/docs/pr/issue-1322.md @@ -0,0 +1,43 @@ +# Add SDK CORS handling (#1322) + +## Summary + +Adds a transport-agnostic `CorsHandler` so `@stellar-split/sdk` consumers can serve browser requests safely. It +resolves origins (including async allow-list predicates), answers preflight requests, applies credential-safe header +rules, supports custom headers and tracks decisions with bounded, payload-free events. + +## What changed + +- **New module `src/cors.ts`** + - `CorsHandler.handle(request)` evaluates a minimal `{ method, origin, headers }` request and returns `{ allowed, isPreflight, headers, reason }` that any HTTP layer can apply. + - **Origin support**: wildcard (`*`), explicit string, allow-list array, `true` (reflect any origin), or an async predicate function. `isOriginAllowed()` exposes the same rule for reuse. + - **Preflight support**: detects `OPTIONS` + `Access-Control-Request-Method`, validates the requested method and headers case-insensitively, and emits `Access-Control-Allow-Methods`, `Access-Control-Allow-Headers` and `Access-Control-Max-Age`. + - **Credential safety**: never emits `Access-Control-Allow-Origin: *` together with `Access-Control-Allow-Credentials: true`; the concrete origin is reflected instead and `Vary: Origin` is always set on browser responses. + - **Custom headers**: configurable `allowedHeaders` and `exposedHeaders` (`Access-Control-Expose-Headers`), plus default SDK trace headers. + - `stats()` counts requests, preflights, approvals and denials; `eventsTrail()` keeps a bounded record of decisions including denial reasons; `reset()` clears state. +- **Exports** added to `src/index.ts` for the handler and all public types. +- **Tests** in `test/cors.test.ts` (11 tests) covering wildcard/fixed/predicate origins, missing origins, credential safety on actual and preflight requests, custom methods/headers/max-age, unsupported methods/headers, stats and bounded tracking. + +## Acceptance criteria addressed + +- **CORS works** — browser origins are resolved and correct response headers produced. +- **Preflight handled** — `OPTIONS` requests are validated and answered with method/header/max-age headers. +- **Credentials safe** — wildcard is never combined with credentials; origins are reflected and `Vary: Origin` is set. +- **Headers supported** — configurable allowed and exposed headers with case-insensitive matching. +- **All tests pass** — 11 new Vitest tests. +- **Browser compatible** — no Node-only APIs; the handler works with any request/response adapter. +- **Tracking** — bounded decision events and counters for observability. + +## Testing + +```bash +npx vitest run test/cors.test.ts +``` + +`npm run lint` was already failing before this change because of pre-existing syntax errors/merge-conflict markers in unrelated files; this change adds no new TypeScript errors. + +## Backwards compatibility + +Additive only; no existing module or API is modified. + +closes #1322 diff --git a/src/cors.ts b/src/cors.ts new file mode 100644 index 0000000..857f607 --- /dev/null +++ b/src/cors.ts @@ -0,0 +1,261 @@ +/** + * CORS handling for browser-based SDK usage. + * + * Resolves origins (including asynchronous allow-list predicates), answers + * preflight requests, applies credential-safe header rules and keeps a bounded + * tracking trail. The handler is transport-agnostic: it consumes a small + * request shape and returns headers that any HTTP layer can apply. + */ + +/** Rule describing which origins may access the resource. */ +export type CorsOriginRule = + | string + | string[] + | true + | ((origin: string) => boolean | Promise); + +/** Minimal request shape needed to make a CORS decision. */ +export interface CorsRequest { + method: string; + origin?: string | null; + headers?: Record; +} + +/** Result of evaluating a request. */ +export interface CorsDecision { + allowed: boolean; + isPreflight: boolean; + headers: Record; + reason?: string; +} + +/** Bounded diagnostic record of one CORS evaluation. */ +export interface CorsEvent { + timestamp: number; + origin: string; + method: string; + isPreflight: boolean; + allowed: boolean; + reason?: string; +} + +/** Counters describing CORS decisions. */ +export interface CorsStats { + requests: number; + preflights: number; + allowed: number; + denied: number; +} + +/** Configuration for {@link CorsHandler}. */ +export interface CorsOptions { + /** Allowed origins. Defaults to `*` (reflected when credentials are enabled). */ + origins?: CorsOriginRule; + /** Methods advertised on preflight. */ + methods?: string[]; + /** Headers clients may send on actual requests. */ + allowedHeaders?: string[]; + /** Response headers exposed to browser code. */ + exposedHeaders?: string[]; + /** Whether browsers may include credentials. Defaults to false. */ + credentials?: boolean; + /** Preflight cache lifetime in seconds. Defaults to 600. */ + maxAge?: number; + /** Maximum number of retained tracking events. Defaults to 100. */ + maxTrackedEvents?: number; + /** Injectable clock. */ + now?: () => number; +} + +const DEFAULT_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]; +const DEFAULT_ALLOWED_HEADERS = [ + "Content-Type", + "Authorization", + "X-Requested-With", + "X-Stellar-Split-Trace-Id", +]; + +function headerValue(headers: CorsRequest["headers"], name: string): string | undefined { + if (!headers) { + return undefined; + } + const key = Object.keys(headers).find((candidate) => candidate.toLowerCase() === name); + if (!key) { + return undefined; + } + const value = headers[key]; + return Array.isArray(value) ? value.join(", ") : value; +} + +/** Evaluate browser CORS rules for the StellarSplit SDK. */ +export class CorsHandler { + private readonly options: Required< + Pick + > & + CorsOptions; + private readonly events: CorsEvent[] = []; + private counters: CorsStats = { requests: 0, preflights: 0, allowed: 0, denied: 0 }; + + constructor(options: CorsOptions = {}) { + this.options = { + ...options, + origins: options.origins ?? "*", + methods: options.methods ?? DEFAULT_METHODS, + allowedHeaders: options.allowedHeaders ?? DEFAULT_ALLOWED_HEADERS, + exposedHeaders: options.exposedHeaders ?? [], + credentials: options.credentials ?? false, + maxAge: options.maxAge ?? 600, + maxTrackedEvents: options.maxTrackedEvents ?? 100, + }; + } + + /** Evaluate a request and return the decision plus headers to apply. */ + async handle(request: CorsRequest): Promise { + const origin = request.origin ?? ""; + const method = (request.method || "GET").toUpperCase(); + const isPreflight = + method === "OPTIONS" && Boolean(headerValue(request.headers, "access-control-request-method")); + + this.counters.requests += 1; + if (isPreflight) { + this.counters.preflights += 1; + } + + let decision: CorsDecision; + if (!origin) { + // Non-browser / same-origin requests need no CORS headers. + decision = { allowed: true, isPreflight, headers: {} }; + } else { + decision = await this.evaluateOrigin(origin, method, request, isPreflight); + } + + if (decision.allowed) { + this.counters.allowed += 1; + } else { + this.counters.denied += 1; + } + this.track({ + timestamp: this.now(), + origin: origin || "(none)", + method, + isPreflight, + allowed: decision.allowed, + reason: decision.reason, + }); + return decision; + } + + /** Check an origin against the configured rule without building headers. */ + async isOriginAllowed(origin: string): Promise { + if (!origin) { + return true; + } + const rule = this.options.origins; + if (rule === true) { + return true; + } + if (typeof rule === "string") { + return rule === "*" || rule === origin; + } + if (Array.isArray(rule)) { + return rule.includes("*") || rule.includes(origin); + } + return Boolean(await rule(origin)); + } + + /** Operation counters. */ + stats(): CorsStats { + return { ...this.counters }; + } + + /** Copy of the bounded CORS decision trail. */ + eventsTrail(): CorsEvent[] { + return this.events.map((event) => ({ ...event })); + } + + /** Reset counters and tracking history. */ + reset(): void { + this.events.length = 0; + this.counters = { requests: 0, preflights: 0, allowed: 0, denied: 0 }; + } + + private async evaluateOrigin( + origin: string, + method: string, + request: CorsRequest, + isPreflight: boolean, + ): Promise { + if (!(await this.isOriginAllowed(origin))) { + return { + allowed: false, + isPreflight, + headers: { Vary: "Origin" }, + reason: "origin-not-allowed", + }; + } + + const headers: Record = { Vary: "Origin" }; + const wildcard = this.resolvesToWildcard(); + headers["Access-Control-Allow-Origin"] = wildcard && !this.options.credentials ? "*" : origin; + if (this.options.credentials) { + headers["Access-Control-Allow-Credentials"] = "true"; + } + + if (isPreflight) { + const requestedMethod = (headerValue(request.headers, "access-control-request-method") ?? "").toUpperCase(); + const requestedHeaders = (headerValue(request.headers, "access-control-request-headers") ?? "") + .split(",") + .map((value) => value.trim()) + .filter((value) => value.length > 0); + + if (!this.options.methods.some((candidate) => candidate.toUpperCase() === requestedMethod)) { + return { + allowed: false, + isPreflight, + headers: { Vary: "Origin" }, + reason: "method-not-allowed", + }; + } + + const allowed = new Set(this.options.allowedHeaders.map((name) => name.toLowerCase())); + const unsupported = requestedHeaders.filter((name) => !allowed.has(name.toLowerCase())); + if (unsupported.length > 0) { + return { + allowed: false, + isPreflight, + headers: { Vary: "Origin" }, + reason: "headers-not-allowed", + }; + } + + headers["Access-Control-Allow-Methods"] = this.options.methods.join(", "); + headers["Access-Control-Allow-Headers"] = + requestedHeaders.length > 0 ? requestedHeaders.join(", ") : this.options.allowedHeaders.join(", "); + headers["Access-Control-Max-Age"] = String(this.options.maxAge); + // Avoid a '*' with credentials on preflights as well. + if (this.options.credentials && headers["Access-Control-Allow-Headers"] === "*") { + headers["Access-Control-Allow-Headers"] = this.options.allowedHeaders.join(", "); + } + } else if (this.options.exposedHeaders.length > 0) { + headers["Access-Control-Expose-Headers"] = this.options.exposedHeaders.join(", "); + } + + return { allowed: true, isPreflight, headers }; + } + + private resolvesToWildcard(): boolean { + const rule = this.options.origins; + return rule === true || rule === "*" || (Array.isArray(rule) && rule.includes("*")); + } + + private now(): number { + return this.options.now ? this.options.now() : Date.now(); + } + + private track(event: CorsEvent): void { + if (this.events.length >= this.options.maxTrackedEvents) { + this.events.shift(); + } + this.events.push(event); + } +} diff --git a/test/cors.test.ts b/test/cors.test.ts new file mode 100644 index 0000000..9c776d1 --- /dev/null +++ b/test/cors.test.ts @@ -0,0 +1,157 @@ +import { describe, it, expect, beforeEach } from "vitest"; +import { CorsHandler, type CorsRequest } from "../src/cors.js"; + +const get = (origin?: string): CorsRequest => ({ + method: "GET", + origin, + headers: {}, +}); + +const preflight = ( + origin: string, + requestMethod: string, + requestHeaders?: string, +): CorsRequest => ({ + method: "OPTIONS", + origin, + headers: { + "access-control-request-method": requestMethod, + ...(requestHeaders ? { "access-control-request-headers": requestHeaders } : {}), + }, +}); + +describe("CorsHandler", () => { + let handler: CorsHandler; + + beforeEach(() => { + handler = new CorsHandler(); + }); + + describe("origin resolution", () => { + it("allows the default wildcard origin and emits CORS headers", async () => { + const decision = await handler.handle(get("https://app.example.com")); + + expect(decision.allowed).toBe(true); + expect(decision.isPreflight).toBe(false); + expect(decision.headers).toMatchObject({ + "Access-Control-Allow-Origin": "*", + Vary: "Origin", + }); + }); + + it("allows a fixed origin list and rejects unknown origins", async () => { + handler = new CorsHandler({ origins: ["https://app.example.com", "https://admin.example.com"] }); + + expect( + (await handler.handle(get("https://app.example.com"))).headers["Access-Control-Allow-Origin"], + ).toBe("https://app.example.com"); + const denied = await handler.handle(get("https://evil.example.com")); + expect(denied.allowed).toBe(false); + expect(denied.reason).toBe("origin-not-allowed"); + expect(denied.headers["Access-Control-Allow-Origin"]).toBeUndefined(); + }); + + it("supports asynchronous origin predicates", async () => { + handler = new CorsHandler({ + origins: async (origin) => origin.endsWith(".trusted.example"), + }); + + expect((await handler.handle(get("https://api.trusted.example"))).allowed).toBe(true); + expect((await handler.handle(get("https://api.other.example"))).allowed).toBe(false); + expect(await handler.isOriginAllowed("https://a.trusted.example")).toBe(true); + }); + + it("skips CORS headers for requests without an origin", async () => { + const decision = await handler.handle(get()); + + expect(decision.allowed).toBe(true); + expect(decision.headers).toEqual({}); + }); + }); + + describe("credentials safety", () => { + it("reflects the origin instead of emitting a wildcard with credentials", async () => { + handler = new CorsHandler({ credentials: true, exposedHeaders: ["X-Request-Id"] }); + + const decision = await handler.handle(get("https://app.example.com")); + expect(decision.headers["Access-Control-Allow-Origin"]).toBe("https://app.example.com"); + expect(decision.headers["Access-Control-Allow-Credentials"]).toBe("true"); + expect(decision.headers["Access-Control-Allow-Origin"]).not.toBe("*"); + expect(decision.headers["Access-Control-Expose-Headers"]).toBe("X-Request-Id"); + }); + + it("applies credential rules to preflights too", async () => { + handler = new CorsHandler({ credentials: true }); + const decision = await handler.handle(preflight("https://app.example.com", "POST")); + + expect(decision.headers["Access-Control-Allow-Origin"]).toBe("https://app.example.com"); + expect(decision.headers["Access-Control-Allow-Credentials"]).toBe("true"); + }); + }); + + describe("preflight handling", () => { + it("answers allowed preflights with methods, headers and max age", async () => { + handler = new CorsHandler({ maxAge: 120 }); + const decision = await handler.handle( + preflight("https://app.example.com", "POST", "Content-Type, X-Stellar-Split-Trace-Id"), + ); + + expect(decision.allowed).toBe(true); + expect(decision.isPreflight).toBe(true); + expect(decision.headers["Access-Control-Allow-Methods"]).toContain("POST"); + expect(decision.headers["Access-Control-Allow-Headers"]).toBe( + "Content-Type, X-Stellar-Split-Trace-Id", + ); + expect(decision.headers["Access-Control-Max-Age"]).toBe("120"); + }); + + it("rejects unsupported methods and headers", async () => { + const badMethod = await handler.handle(preflight("https://app.example.com", "TRACE")); + expect(badMethod.allowed).toBe(false); + expect(badMethod.reason).toBe("method-not-allowed"); + + const badHeaders = await handler.handle( + preflight("https://app.example.com", "POST", "X-Unknown-Header"), + ); + expect(badHeaders.allowed).toBe(false); + expect(badHeaders.reason).toBe("headers-not-allowed"); + expect(badHeaders.headers["Access-Control-Allow-Methods"]).toBeUndefined(); + }); + + it("supports custom allowed headers", async () => { + handler = new CorsHandler({ allowedHeaders: ["X-Custom"] }); + const decision = await handler.handle( + preflight("https://app.example.com", "POST", "x-custom"), + ); + + expect(decision.allowed).toBe(true); + expect(decision.headers["Access-Control-Allow-Headers"]).toBe("x-custom"); + }); + }); + + describe("tracking", () => { + it("counts requests, preflights, approvals and denials", async () => { + handler = new CorsHandler({ origins: ["https://app.example.com"] }); + await handler.handle(get("https://app.example.com")); + await handler.handle(get("https://evil.example.com")); + await handler.handle(preflight("https://app.example.com", "POST")); + + expect(handler.stats()).toEqual({ requests: 3, preflights: 1, allowed: 2, denied: 1 }); + expect(handler.eventsTrail()).toHaveLength(3); + expect(handler.eventsTrail()[2]).toMatchObject({ isPreflight: true, allowed: true }); + }); + + it("keeps the trail bounded", async () => { + handler = new CorsHandler({ maxTrackedEvents: 2 }); + for (let i = 0; i < 5; i += 1) { + await handler.handle(get(`https://app${i}.example.com`)); + } + + expect(handler.eventsTrail()).toHaveLength(2); + expect(handler.eventsTrail().map((event) => event.origin)).toEqual([ + "https://app3.example.com", + "https://app4.example.com", + ]); + }); + }); +});