route.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. import { getSession } from "@/lib/auth/session";
  2. import { canAccessBranch } from "@/lib/auth/permissions";
  3. import {
  4. withErrorHandling,
  5. json,
  6. badRequest,
  7. unauthorized,
  8. forbidden,
  9. } from "@/lib/api/errors";
  10. import { search as searchBackend } from "@/lib/search";
  11. /**
  12. * Search API (RHL-016)
  13. *
  14. * - Sync-first (Qsirch /search/) with cursor-based pagination.
  15. * - Provider abstraction allows later switch to async-search without changing this endpoint.
  16. *
  17. * Query params:
  18. * - scope: "branch" | "multi" | "all" (admin/dev only; branch users are forced to their own branch)
  19. * - branch: NLxx (for scope=branch)
  20. * - branches: comma-separated NLxx list (for scope=multi)
  21. * - q: optional text query
  22. * - from/to: optional inclusive ISO date (YYYY-MM-DD)
  23. * - limit: optional (default 100, allowed 50..200)
  24. * - cursor: optional opaque string
  25. */
  26. export const dynamic = "force-dynamic";
  27. const BRANCH_RE = /^NL\d+$/;
  28. const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
  29. function isValidIsoDate(value) {
  30. if (!ISO_DATE_RE.test(value)) return false;
  31. const [y, m, d] = value.split("-").map((x) => Number(x));
  32. if (!Number.isInteger(y) || !Number.isInteger(m) || !Number.isInteger(d))
  33. return false;
  34. // Basic calendar sanity (month/day ranges; does not validate month-length precisely,
  35. // but rejects obvious invalid formats and keeps behavior predictable).
  36. if (m < 1 || m > 12) return false;
  37. if (d < 1 || d > 31) return false;
  38. return true;
  39. }
  40. function parseLimitOrThrow(raw) {
  41. if (raw === null || raw === undefined || raw === "") return 100;
  42. if (!/^\d+$/.test(String(raw))) {
  43. throw badRequest("VALIDATION_SEARCH_LIMIT", "Invalid limit parameter", {
  44. limit: raw,
  45. });
  46. }
  47. const n = Number(raw);
  48. if (!Number.isInteger(n) || n < 50 || n > 200) {
  49. throw badRequest("VALIDATION_SEARCH_LIMIT", "Invalid limit parameter", {
  50. limit: n,
  51. min: 50,
  52. max: 200,
  53. });
  54. }
  55. return n;
  56. }
  57. function parseScope(raw) {
  58. const s = (raw || "").trim().toLowerCase();
  59. if (!s) return null;
  60. if (s === "branch" || s === "multi" || s === "all") return s;
  61. throw badRequest("VALIDATION_SEARCH_SCOPE", "Invalid scope parameter", {
  62. scope: raw,
  63. });
  64. }
  65. function parseBranchesCsv(raw) {
  66. if (!raw) return [];
  67. return String(raw)
  68. .split(",")
  69. .map((x) => x.trim())
  70. .filter(Boolean);
  71. }
  72. function unique(items) {
  73. return Array.from(new Set(items));
  74. }
  75. export const GET = withErrorHandling(
  76. async function GET(request) {
  77. const session = await getSession();
  78. if (!session) {
  79. throw unauthorized("AUTH_UNAUTHENTICATED", "Unauthorized");
  80. }
  81. const { searchParams } = new URL(request.url);
  82. const rawScope = searchParams.get("scope");
  83. const scope = parseScope(rawScope);
  84. const qRaw = searchParams.get("q");
  85. const q = typeof qRaw === "string" && qRaw.trim() ? qRaw.trim() : null;
  86. const fromRaw = searchParams.get("from");
  87. const toRaw = searchParams.get("to");
  88. const from =
  89. typeof fromRaw === "string" && fromRaw.trim() ? fromRaw.trim() : null;
  90. const to = typeof toRaw === "string" && toRaw.trim() ? toRaw.trim() : null;
  91. if (from && !isValidIsoDate(from)) {
  92. throw badRequest("VALIDATION_SEARCH_DATE", "Invalid from date", { from });
  93. }
  94. if (to && !isValidIsoDate(to)) {
  95. throw badRequest("VALIDATION_SEARCH_DATE", "Invalid to date", { to });
  96. }
  97. if (from && to && from > to) {
  98. throw badRequest("VALIDATION_SEARCH_RANGE", "Invalid date range", {
  99. from,
  100. to,
  101. });
  102. }
  103. // At least one of q or date range must be provided to avoid "match everything"
  104. // queries by accident (especially dangerous for global admin searches).
  105. if (!q && !from && !to) {
  106. throw badRequest(
  107. "VALIDATION_SEARCH_MISSING_FILTER",
  108. "At least one of q or date range must be provided"
  109. );
  110. }
  111. const limit = parseLimitOrThrow(searchParams.get("limit"));
  112. const cursor = searchParams.get("cursor");
  113. const branchParam = searchParams.get("branch");
  114. const branchesParam = searchParams.get("branches");
  115. const requestedSingleBranch =
  116. typeof branchParam === "string" && branchParam.trim()
  117. ? branchParam.trim()
  118. : null;
  119. const requestedBranches =
  120. branchesParam && String(branchesParam).trim()
  121. ? unique(parseBranchesCsv(branchesParam))
  122. : [];
  123. // RBAC: branch users are forced to their own branch.
  124. if (session.role === "branch") {
  125. if (!session.branchId) {
  126. throw forbidden("AUTH_FORBIDDEN_BRANCH", "Forbidden");
  127. }
  128. // If the caller attempts to query other branches, reject.
  129. if (requestedSingleBranch && requestedSingleBranch !== session.branchId) {
  130. throw forbidden("AUTH_FORBIDDEN_BRANCH", "Forbidden");
  131. }
  132. if (requestedBranches.length > 0) {
  133. const hasForeign = requestedBranches.some(
  134. (b) => b !== session.branchId
  135. );
  136. if (hasForeign) throw forbidden("AUTH_FORBIDDEN_BRANCH", "Forbidden");
  137. }
  138. if (scope === "all") {
  139. throw forbidden("AUTH_FORBIDDEN_BRANCH", "Forbidden");
  140. }
  141. return json(
  142. await searchBackend({
  143. mode: "branch",
  144. branches: [session.branchId],
  145. q,
  146. from,
  147. to,
  148. limit,
  149. cursor: cursor ? String(cursor) : null,
  150. }),
  151. 200
  152. );
  153. }
  154. // Admin/dev: scope can be branch/multi/all
  155. let mode;
  156. let branches = null;
  157. if (scope === "all") {
  158. mode = "all";
  159. branches = null;
  160. } else if (requestedBranches.length > 0 || scope === "multi") {
  161. mode = "multi";
  162. branches = requestedBranches;
  163. if (!Array.isArray(branches) || branches.length === 0) {
  164. throw badRequest(
  165. "VALIDATION_SEARCH_BRANCHES",
  166. "Missing branches parameter for multi scope"
  167. );
  168. }
  169. } else {
  170. // Default to branch scope
  171. mode = "branch";
  172. if (!requestedSingleBranch) {
  173. throw badRequest(
  174. "VALIDATION_SEARCH_BRANCH",
  175. "Missing branch parameter for branch scope"
  176. );
  177. }
  178. branches = [requestedSingleBranch];
  179. }
  180. // Validate branch patterns (even for admin/dev) to avoid weird inputs.
  181. if (mode === "branch" || mode === "multi") {
  182. for (const b of branches) {
  183. if (!BRANCH_RE.test(b)) {
  184. throw badRequest(
  185. "VALIDATION_SEARCH_BRANCH",
  186. "Invalid branch parameter",
  187. {
  188. branch: b,
  189. }
  190. );
  191. }
  192. // Enforce RBAC helper semantics consistently, even though admin/dev will pass.
  193. if (!canAccessBranch(session, b)) {
  194. throw forbidden("AUTH_FORBIDDEN_BRANCH", "Forbidden");
  195. }
  196. }
  197. }
  198. const result = await searchBackend({
  199. mode,
  200. branches,
  201. q,
  202. from,
  203. to,
  204. limit,
  205. cursor: cursor ? String(cursor) : null,
  206. });
  207. return json(result, 200);
  208. },
  209. { logPrefix: "[api/search]" }
  210. );