diff --git a/app/api/0pt/search/[indexName]/query/route.ts b/app/api/0pt/search/[indexName]/query/route.ts new file mode 100644 index 0000000..701102f --- /dev/null +++ b/app/api/0pt/search/[indexName]/query/route.ts @@ -0,0 +1,65 @@ +import { NextRequest, NextResponse } from "next/server"; + +import { assertTenantMatchesVerified } from "@/src/http/tenant-guard"; +import { siaxErrorResponse } from "@/src/http/siax-error-response"; +import { SiaxError } from "@/src/platform/errors"; +import { getSearchService } from "@/src/services/search"; + +function primitiveFilters(value: unknown): Record | undefined { + if (value === undefined) return undefined; + if (!value || typeof value !== "object" || Array.isArray(value)) { + throw new SiaxError("INVALID_REQUEST", "0pt.search", "filters must be an object"); + } + const result: Record = {}; + for (const [key, item] of Object.entries(value as Record)) { + if (typeof item !== "string" && typeof item !== "number" && typeof item !== "boolean") { + throw new SiaxError("INVALID_REQUEST", "0pt.search", `filter ${key} must be string, number or boolean`); + } + result[key] = item; + } + return result; +} + +export async function POST( + request: NextRequest, + { params }: { params: Promise<{ indexName: string }> }, +) { + try { + const { indexName } = await params; + const raw = await request.json(); + if (!raw || typeof raw !== "object" || Array.isArray(raw)) { + throw new SiaxError("INVALID_REQUEST", "0pt.search", "JSON object body is required"); + } + const body = raw as Record; + const tenantId = typeof body.tenant_id === "string" ? body.tenant_id.trim() : ""; + const purpose = typeof body.purpose === "string" ? body.purpose.trim() : ""; + if (!tenantId) throw new SiaxError("INVALID_REQUEST", "0pt.search", "tenant_id is required"); + if (!purpose) throw new SiaxError("INVALID_REQUEST", "0pt.search", "purpose is required"); + const guard = assertTenantMatchesVerified(request, tenantId); + if (guard) return guard; + + // Public/authenticated traffic is deliberately fixed to internal rights. + // A client-supplied higher rights_tag would be privilege escalation by + // request body; broader tags require a future CL0UD-derived entitlement. + if (body.rights_tag !== undefined && body.rights_tag !== "internal") { + throw new SiaxError( + "AUTHORIZATION_DENIED", + "0pt.search", + "rights_tag cannot be elevated by the caller", + ); + } + + const result = await getSearchService().query(indexName, { + tenant_id: tenantId, + purpose, + rights_tag: "internal", + ...(typeof body.text === "string" ? { text: body.text } : {}), + ...(body.from === undefined ? {} : { from: Number(body.from) }), + ...(body.size === undefined ? {} : { size: Number(body.size) }), + ...(body.filters === undefined ? {} : { filters: primitiveFilters(body.filters) }), + }); + return NextResponse.json(result); + } catch (error: unknown) { + return siaxErrorResponse(error); + } +}