// portal-query-allowlist (F38): the one way a BFF route builds the query it sends to mobile-api. // Only allow-listed keys are forwarded, each value is validated, and the output is percent-encoded, // so a client can neither smuggle an extra upstream parameter (`a=1%26memberCode%3DX`) nor reach // a parameter the route never meant to expose. This file is identical in both portals. export type QueryRule = | { type: "int"; min: number; max: number } | { type: "string"; maxLength: number; pattern?: RegExp } | { type: "enum"; values: readonly string[] }; const INT = /^-?\d{1,15}$/; function accept(value: string, rule: QueryRule): string | null { if (value === "") return null; switch (rule.type) { case "int": { if (!INT.test(value)) return null; return String(Math.min(rule.max, Math.max(rule.min, Number(value)))); } case "string": if (value.length > rule.maxLength) return null; return !rule.pattern || rule.pattern.test(value) ? value : null; case "enum": return rule.values.includes(value) ? value : null; } } /** * The upstream query for `source`: "" when nothing is forwarded, otherwise "?k=v&…". Keys absent from * `rules` are dropped; a repeated key forwards its first value only; an empty or invalid value is dropped, * except an out-of-range int, which is clamped to its rule's min/max. Keys keep the caller's order. */ export function upstreamQuery(source: URLSearchParams, rules: Readonly>): string { const out = new URLSearchParams(); for (const [key, raw] of source) { if (out.has(key) || !Object.hasOwn(rules, key)) continue; const value = accept(raw, rules[key]); if (value !== null) out.append(key, value); } // Serialised with encodeURIComponent (a space is %20, not URLSearchParams' "+"): both decode the same upstream. const qs = [...out].map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join("&"); return qs ? `?${qs}` : ""; } /** Rules shared by most list routes. Each route still names its own keys; nothing is forwarded by default. */ export function paging(maxSize: number): Record<"page" | "size", QueryRule> { return { page: { type: "int", min: 0, max: 10000 }, size: { type: "int", min: 1, max: maxSize } }; } export const SORT: Readonly> = { sortBy: { type: "string", maxLength: 64, pattern: /^[A-Za-z0-9_.]+$/ }, sortDir: { type: "enum", values: ["asc", "desc"] }, }; /** Free text or an id/date filter that mobile-api validates itself: bounded, no control characters. */ export const TEXT: QueryRule = { type: "string", maxLength: 200, pattern: /^[^\x00-\x1f\x7f]*$/ }; /** A query value used as a path segment: the integer when it is a plain integer within [min, max], else null. */ export function pathInt(value: string | null, min: number, max: number): number | null { if (value === null || !/^\d{1,15}$/.test(value)) return null; const n = Number(value); return n >= min && n <= max ? n : null; }