Skip to main content

Search, lookup & catalog (discovery family)

Routes that resolve or search across entities by something other than their own id/path — "discovery" is this family's name in lib/routes.ts (family: 'discovery', one shared Lambda). All three routes in this family ship in this feature (002): GET /v1/lookup (A13), GET /v1/search/suggestions (A12) and GET /v1/catalog/{name} (A14).

:::note Deployed on dev These routes are live on dev (verified 2026-10-13). Every example below is illustrative, derived from the schema and handler code, not a captured execution. :::

GET /v1/lookup — Resolve a display code​

Purpose: resolves a display code (PL-0518, WO-2026-0498) to its entity — for deep links and pasting a code into global search. Display codes are short, human-typeable identifiers allocated by codeGuard (packages/core/src/codes.ts, FR-030); this route is the one place that turns one back into an entity reference.

  • HTTP method: GET
  • Endpoint: /v1/lookup
  • Authentication: Required (Cognito bearer token — any of the four clients: flutter-app-default, flutter-app-remembered, web-console, and server-admin in dev only).
  • Authorization: Per-entity, via the prefix lookup type that resolved the code. Each registered type supplies its own authorize(ctx, entityId, orgId) (registerLookupType, packages/core/src/codes.ts) — this route has no authorization logic of its own beyond calling it. 004 registers its display-code prefix types and 006 registers WO- (work orders). The 005 device-id/serial resolvers and the 007 OP-/BLK-/FW- types are no longer registered (ADR 0012 phase 2).
  • Side effects: none. Pure read.
  • DynamoDB calls: one strongly consistent GetItem on the code guard item (CODE#<code>/GUARD for a platform-wide type, or CODE#<operatorOrgId>#<code>/GUARD for a per-operator WO- type), plus whatever reads the matched type's own authorize callback makes (not controlled by this route).

Request​

Headers

HeaderRequiredValue
AuthorizationYesBearer <token>
X-Org-IdOnly to resolve a per-operator (WO-) codeThe caller's active operator organisation, as a ULID

Path parameters: none.

Query parameters

ParamTypeRequiredValidation
codestringYesTrimmed, max 80 chars, /^(?:[A-Z]{1,4}(-\d{4})?-\d{2,}|[A-Z0-9._][A-Z0-9._ -]{2,})$/i — a display code (PL-0518, WO-2026-0498), a device id (26-char ULID) or a device serial as entered (005, T005-108). Upper-cased server-side before matching

This is a strict route: code is the only accepted query parameter — any other one (e.g. ?code=PL-0518&foo=bar) is rejected, whether or not code itself is valid.

Request body: none.

Response​

Structure (LookupResult — see Types & schemas):

{
type: string; // the resolved entity's registered lookup type, e.g. "plant"
id: string; // ULID of the resolved entity
code: string; // the code, normalised (trimmed, upper-cased) — may differ from what was sent
orgId: string; // owning organisation of the resolved entity
}

Successful response — illustrative example​

{ "type": "plant", "id": "01J9Z4A1B2C3D4E5F6G7H8J9K0", "code": "PL-0518", "orgId": "01J9Z3K8N4R6X2QYV7M1WB0T3F" }

Failure response — not found (illustrative)​

{ "error": { "code": "NOT_FOUND", "message": "Code not found", "requestId": "Abc123Xyz=" } }

This EXACT body and status is returned for every one of: an unparseable code, a code whose prefix has no registered type, a WO- code sent with no (or the wrong) X-Org-Id, a code with no guard item at all, and a code the caller's authorize callback denies. See Edge cases below — this is deliberate non-disclosure, not an accident.

Failure response — validation failure (illustrative)​

A missing or malformed code:

{ "error": { "code": "VALIDATION_FAILED", "message": "is not a recognised display code, device id or serial format", "details": { "formErrors": [], "fieldErrors": { "code": ["is not a recognised display code, device id or serial format"] } }, "requestId": "Abc123Xyz=" } }

An unknown query parameter:

{ "error": { "code": "VALIDATION_FAILED", "message": "Unknown query parameter", "details": { "unknown": ["foo"] }, "requestId": "Abc123Xyz=" } }

HTTP status codes​

StatuscodeWhenFE guidance
200—Code found, and the resolved entity's authorize allowed itUse the type/id to route (e.g. open the matching plant screen)
401— (gateway body {"message":"Unauthorized"})Missing/invalid/expired token, or a client not accepted by the authorizerRe-authenticate / refresh the token
401SESSION_REVOKEDThe token is valid but its session was revoked (standard { error: { code, message } } envelope, from the Lambda, not the gateway)Sign the user in again
403FORBIDDEN / ACCOUNT_SUSPENDEDX-Org-Id names an organisation the caller is not a member of (or the membership is suspended) — checked before any lookup/search runs (004, T004-1212)Don't retry; switch to an org the user belongs to
404NOT_FOUNDNo guard item, unregistered type, WO- code with no/wrong org context, or denied — all identical (non-disclosure)Show a generic "code not found" message. Never tell the user which specific case applied — the server doesn't either
400VALIDATION_FAILEDcode missing or fails its pattern (details.fieldErrors), or an unknown query parameter was sent (details.unknown)Fix the client request — this is a client bug, not retryable as-is
500INTERNALUnexpected server errorRetry once; if it persists, report it
503DEPENDENCY_UNAVAILABLEDynamoDB throttled/unavailableRetry with backoff; honor Retry-After if present

Edge cases​

  • Non-disclosure is deliberate and total. An unknown code, a code belonging to a type nobody registered, a WO- code looked up without (or with the wrong) organisation context, and a code that exists but the caller isn't authorized to view all return the exact same 404 NOT_FOUND body. Do not try to distinguish these cases in the UI from the response alone — there is nothing in the response that does.
  • Platform-wide vs. per-operator codes. PL- and RPT-YYYY- are platform-wide: they resolve with no org context at all. Only WO- (work order) codes are per-operator — resolving one requires X-Org-Id to be the same operator organisation whose sequence issued it; a different (or missing) organisation is 404, not 403 (same non-disclosure reasoning as above).
  • X-Org-Id format. As implemented in 002, a malformed X-Org-Id value is silently treated as absent (buildContext only accepts a well-formed 26-character ULID and drops anything else) — it is not rejected with a 400. Full validation/trust of this header is feature 003's job; don't rely on the server rejecting a malformed value today.
  • Registered lookup types (004). plant (PL-), customer (CU-), partner (PB-) and tag (TG-) are registered in packages/core/src/plants/lookup.ts. plant re-checks VIEW on that exact plant; customer/partner need customers access and tag needs plants access in the owning org. A caller without access gets the same 404 NOT_FOUND as an unknown code (non-disclosure). OP-, BLK- and FW- codes always return 404 (their 007 types were removed by ADR 0012); WO- is registered by 006 (below).
  • Membership check on X-Org-Id. If the optional X-Org-Id is sent and the caller is not a member of that org, the response is 403, not 404 — the header is the caller's own claim, so this discloses nothing about the code.
  • Device lookup — removed (ADR 0012 phase 2). The prefix-less device (deviceId) and serial resolvers are no longer registered: a deviceId or a serial still passes the code pattern but always returns 404 NOT_FOUND. Devices are served by the TCP server over the WebSocket.
  • Work-order lookup (006, T006-130). WO-YYYY-NNNN codes are registered as type workOrder in packages/core/src/service/lookup.ts (loaded through @cse/core, so it is active in the routed GET /v1/lookup function from the next ApiStack deploy — not yet executed against any stage). Codes are per operator: the guard is read under the caller's ACTIVE operator-org context only (X-Org-Id / current context); no or a different context → 404. The resolved order is then re-authorized with E04's rule (service ≥ VIEW on the order's plant); any denial is the same 404. type: "workOrder", id = workOrderId. The work-order routes themselves are registered in code (stack cse-http-be-<stage>-api-service) and routed (work orders; observed answering on dev on 2026-10-28). MP- plan codes are deliberately not resolvable globally.
  • Code normalisation. The code in a 200 response is the normalised form (trimmed, upper-cased) the server matched against, not necessarily byte-identical to what was sent — a client that sent pl-0518 gets back PL-0518.

GET /v1/search/suggestions — Global search typeahead​

Purpose: cross-entity "type and see suggestions" search for a toolbar search box (Claude Design: Crown Solar Admin Dashboard — Dashboard v2 · Plants toolbar search suggestions), returning at most limit hits re-filtered by the caller's own authorization per entity type.

  • HTTP method: GET
  • Endpoint: /v1/search/suggestions
  • Authentication: Required (same four Cognito clients as every other route — see GET /v1/lookup above).
  • Authorization: Per-hit, via each registered type's own authorize/authorizeMany (registerLookupType, packages/core/src/codes.ts) — a hit the caller cannot view is dropped silently, never surfaced and then rejected. 004 and 005 register real lookup types for their prefixes; 006 registers WO- (work orders). The device, serial, OP, BLK and FW types were removed by ADR 0012 phase 2. Platform mode (ADR 0015) has its own rule, described in Platform-wide search.
  • Side effects: none. Pure read.
  • DynamoDB calls: one Query per searched entity type (parallel fan-out) against that type's SRCH#<org>#<collection>#<first-2-chars> token partition (data-model.md §2.7), Limit: 3 × limit per type for word-filtering/authorization margin — never a Scan. Tokens are written by the stream router from registry/collections.ts registrations (packages/core/src/stream/plan.ts), so a hit only exists once the entity's stream record has been processed — eventually consistent, not read-your-writes (see Edge cases).
  • Throttle: this route carries its own per-route throttle, { rate: 20, burst: 40 } (lib/routes.ts), tighter than the API's default — it's the one discovery route that fans out a Query per requested/registered type per keystroke.

Request​

Headers

HeaderRequiredValue
AuthorizationYesBearer <token>
X-Org-IdYesThe caller's active organisation, as a ULID. There is no active-org concept yet in 002 (feature 003's job) — this header is currently the only source of org context, so it's required on every call, not optional like on GET /v1/lookup.

Path parameters: none.

Query parameters

ParamTypeRequiredValidation
qstringYesTrimmed and normalised (NFKD diacritic-folded, lower-cased, non-alphanumerics collapsed to spaces) before matching; 2-64 chars after trimming
typesstring[]NoEither repeated (types=plant&types=tag) or comma-joined (types=plant,tag) — both accepted and merged. Each value must be a type registered via registerLookupType; omitted → every registered type is searched, in registration order
limitintegerNo1-20, default 6. Not the usual list-endpoint cap of 50 — this is a typeahead, not a paged list
operatorOrgIdULIDNoPlatform mode only: search just this org instead of every org. Sent by any other caller, or malformed → 400 VALIDATION_FAILED (details.field: "operatorOrgId")

This is a strict route: q, types and limit are the only accepted query parameters — any other one is rejected.

Matching semantics: the first word of q is matched as a prefix against the token partition; any additional words are matched as a substring against the token's own denormalised text (words: every searchable field of the entity, normalised). "ghori kar" matches an entity tokenised from "Ghori Residence, Karachi" but not one with only "Ghori Towers, Lahore". Punctuation splits words, so a code query PL-0003 is the two words pl and 0003.

Fixed 2026-11-03, committed, not yet deployed. Before this, token rows stored no entityId and no words, and their label was the field name. In practice A12 returned no hit for any stream-written token, and could not have matched a second word or shown the entity's name. After the deploy, rows written by the stream-router are correct straight away; older rows need npm run rebuild:projections per org and collection (see Operations). Until that runs, an old row matches a one-word query but shows the field name (name) as its label.

Request body: none.

Response​

Structure (SuggestionItem[], wrapped — see Types & schemas):

{
items: Array<{
type: string; // registered search/lookup entity type, e.g. "plant"
id: string; // ULID of the matched entity — for type `customer` it is the CUSTOMER ORG's id (`customerOrgId`), not a user or membership id
label: string; // the entity's display value: plant name, customer/partner name, tag label
sublabel?: string; // the entity's display code (`PL-`, `CU-`, `PB-`, `TG-`), when it has one
matchedField: string; // which field matched, e.g. "name", "serial"
code?: string; // the entity's display code, when it has one
orgId?: string; // the org that owns the hit; always set since ADR 0015. Open the result in this org
orgName?: string; // platform mode only: the owning org's name
orgKind?: 'OPERATOR' | 'PARTNER' | 'CUSTOMER' | 'PERSONAL'; // platform mode only; PERSONAL = an Independent End User's own org
}>;
}

A customer hit that matched only on the contact name or email is dropped for a caller below customers: MANAGE in the org (the Installer template holds VIEW; RBAC-S7, 2026-11-24), so a search cannot confirm a customer's address.

Platform-wide search (Super Admin and Administrator)​

Committed 2026-11-03 (ADR 0015, docs/adr/0015-platform-wide-search.md in the cse-http-be repo), not yet deployed.

  • Who: a caller whose X-Org-Id is a PLATFORM org (Crown HQ) in which they hold the built-in Super Admin or Administrator role, ACTIVE, scope ALL (MFA policy applied as on any request). A custom role in the PLATFORM org, plants ≥ VIEW in any org, and every other role stay org-scoped: they search only the X-Org-Id org, with per-hit authorization as above. operatorOrgId can never switch platform mode on.
  • What: without operatorOrgId, every org: Businesses, partners, customers and Independent End Users' personal orgs. Plants created on mobile and on the web are included once they are indexed. With operatorOrgId, that one org only.
  • Which hits: those whose owning org is ACTIVE and not PLATFORM. Hits of suspended or closed orgs are dropped silently.
  • Response: every item carries orgId, orgName and orgKind. Show the owner (e.g. "Crown R&D Lab · Ghori Solar Pvt Ltd") and open the result in that org (X-Org-Id: <orgId>), which a platform Super Admin/Administrator may select.
  • How: one Query per type on the all-org view of the token rows (GSI1, SRCH#ALL#<collection>#<p2>), plus one BatchGetItem for the owning orgs. Token rows written before this change are not on that view until npm run rebuild:projections -- --all-orgs --execute has run (see Operations).
  • Audit: platform reads in other orgs are not written to those orgs' access logs (existing policy: only state-changing platform actions are).

Platform-mode response — illustrative example​

Derived from SuggestionItem in packages/core/src/schemas.ts; not a captured call.

{
"items": [
{ "type": "plant", "id": "01J9Z4A1B2C3D4E5F6G7H8J9K0", "label": "Crown R&D Lab", "sublabel": "PL-0003", "code": "PL-0003",
"matchedField": "name", "orgId": "01J9Z3K8N4R6X2QYV7M1WB0T3F", "orgName": "Ghori Solar Pvt Ltd", "orgKind": "OPERATOR" }
]
}

Customer hits: a customer item's id is the customer organisation's id — the customerOrgId of the CUSTOMER_PROFILE record the search token was projected from (packages/core/src/customers/projections.ts). Use it as the {customerOrgId}/org id when opening the customer.

Results are grouped by entity type in request order (or registration order when types was omitted), token order within a type, then truncated to limit across all types combined — not limit per type.

Successful response — illustrative example​

{
"items": [
{ "type": "plant", "id": "01J9Z4A1B2C3D4E5F6G7H8J9K0", "label": "Ghori Residence", "matchedField": "name" }
]
}

An empty, still-successful response (no hits, or every hit denied by authorization):

{ "items": [] }

Failure response — validation failure (illustrative)​

An unregistered types value — note details.allowed lists the real options, unlike GET /v1/lookup's non-disclosure 404:

{ "error": { "code": "VALIDATION_FAILED", "message": "Unknown search type \"bogus\"", "details": { "allowed": ["plant"] }, "requestId": "Abc123Xyz=" } }

q too short/long, bad limit, or any other schema violation:

{ "error": { "code": "VALIDATION_FAILED", "message": "Invalid search query", "details": { "formErrors": [], "fieldErrors": { "q": ["String must contain at least 2 character(s)"] } }, "requestId": "Abc123Xyz=" } }

A missing X-Org-Id:

{ "error": { "code": "VALIDATION_FAILED", "message": "X-Org-Id header is required", "requestId": "Abc123Xyz=" } }

An unknown query parameter:

{ "error": { "code": "VALIDATION_FAILED", "message": "Unknown query parameter", "details": { "unknown": ["foo"] }, "requestId": "Abc123Xyz=" } }

HTTP status codes​

StatuscodeWhenFE guidance
200—Always, even with zero hits — an empty items is not an errorRender an empty state, not an error, for items: []
401— (gateway body {"message":"Unauthorized"})Missing/invalid/expired token, or a client not accepted by the authorizerRe-authenticate / refresh the token
401SESSION_REVOKEDThe token is valid but its session was revoked (standard { error: { code, message } } envelope, from the Lambda, not the gateway)Sign the user in again
400VALIDATION_FAILEDAn unknown query parameter, q/limit failing the schema, an unregistered types value (details.allowed), a missing X-Org-Id, or operatorOrgId malformed or sent outside platform mode (details.field)Fix the client request before retrying — all of these are client bugs, not transient
403FORBIDDEN / ACCOUNT_SUSPENDEDX-Org-Id names an organisation the caller is not a member of (or the membership is suspended) — checked before any lookup/search runs (004, T004-1212)Don't retry; switch to an org the user belongs to
429— (gateway body {"message":"Too Many Requests"})The route's own API Gateway throttle ({ rate: 20, burst: 40 }, tighter than the API default) is exceeded — rejected before the Lambda runs, so no X-Request-IdBack off (debounce keystrokes client-side rather than firing a request per character) and retry
500INTERNALUnexpected server errorRetry once; if it persists, report it
503DEPENDENCY_UNAVAILABLEDynamoDB throttled/unavailableRetry with backoff; honor Retry-After if present

Edge cases​

  • Silent drop, not an error, for denied hits. A hit the caller's authorize/authorizeMany denies is simply absent from items — the response is still 200, and the FE has no way to tell "zero matches" apart from "matches existed but were all denied". Same non-disclosure reasoning as GET /v1/lookup's 404.
  • Eventual consistency. Search tokens are written by the stream router reacting to a DynamoDB stream record, not inside the original write's own transaction — an entity created or renamed a moment ago may not be searchable yet. Don't build a "search immediately after create" flow that assumes read-your-writes here.
  • limit truncates across types, not per type. Requesting types=plant,tag&limit=6 can return 6 plants and 0 tags (or any other split) — it is not an even distribution.
  • Searchable types (004). plant, customer, partner and tag are registered; their search collections are the stream entity types PLANT, CUSTOMER_PROFILE, PARTNER_PROFILE and TAG (SEARCH_COLLECTION_ENTITY_TYPES in packages/core/src/plants/lookup.ts). Tags are tokenised on their label since 2026-11-03 (committed, not yet deployed); before that no tag ever matched. Omitting types searches all four; a types value outside that set is 400 VALIDATION_FAILED with details.allowed listing the registered ones. Hits the caller may not view are dropped silently (see above).
  • Membership is checked. An X-Org-Id naming an org the caller is not a member of returns 403 FORBIDDEN before any search runs; it never returns hits from that org.
  • X-Org-Id is mandatory here, unlike on GET /v1/lookup. 002 has no active-org concept (feature 003's job) — this route cannot scope a search to an organisation any other way yet, so a missing header is always a 400, never silently treated as "search nothing" or "search everything".

GET /v1/catalog/{name} — Registered vocabulary lookup​

Purpose: serves a registered vocabulary (plant types, solar modes, grid connections, countries, timezones) for populating a dropdown, so the FE never hand-maintains a copy of a schemas.ts enum client-side.

  • HTTP method: GET
  • Endpoint: /v1/catalog/{name}
  • Authentication: Required (same four Cognito clients as every other route).
  • Authorization: None beyond being signed in — any authenticated caller may read any registered catalog. There is no per-resource or per-org access control on this route.
  • Side effects: none. Pure read, no DynamoDB involved at all — catalogs are built from code (registry/catalogs.ts) at Lambda cold start.
  • Caching: ETag is a content hash of the catalog's items (packages/core/src/registry/catalogs.ts, first 12 hex chars of a SHA-256), stable until that vocabulary's values change; Cache-Control: private, max-age=300 lets a client cache for 5 minutes without re-fetching every screen load.

Request​

Headers

HeaderRequiredValue
AuthorizationYesBearer <token>
If-None-MatchNoA previously received ETag value (quoted), e.g. "abc123def456" — a match short-circuits to 304 with no body

Path parameters

ParamTypeRequiredValidation
namestringYesOne of the registered catalog names below. Any other value is 404 NOT_FOUND

002's registered catalog names: plant-types, solar-modes, grid-connections, countries, timezones. Later features register their own (planned: levels, categories, work types, priorities, tariff types, device types). The former device-models and commands catalogues (and their dedicated routes) were removed by ADR 0012: both names now reach this {name} route and return 404 NOT_FOUND like any unregistered name; the device-model and command catalogues are served by the TCP server.

This route accepts no query parameters at all — sending any is rejected.

Request body: none.

Response​

Structure (CatalogResponse — see Types & schemas):

{
name: string;
version: string; // content-hash version, also carried in the ETag header (quoted)
items: Array<{ value: string; label: string; deprecated?: boolean }>;
}

Successful response — illustrative example​

{
"name": "plant-types",
"version": "abc123def456",
"items": [
{ "value": "RESIDENTIAL", "label": "Residential" },
{ "value": "COMMERCIAL", "label": "Commercial" },
{ "value": "INDUSTRIAL", "label": "Industrial" }
]
}

Response headers on 200: ETag: "abc123def456", Cache-Control: private, max-age=300.

Failure response — not found (illustrative)​

{ "error": { "code": "NOT_FOUND", "message": "Catalog not found", "requestId": "Abc123Xyz=" } }

Failure response — validation failure (illustrative)​

Any query parameter at all (this route takes none):

{ "error": { "code": "VALIDATION_FAILED", "message": "This route accepts no query parameters", "requestId": "Abc123Xyz=" } }

HTTP status codes​

StatuscodeWhenFE guidance
200—name is a registered catalog, and If-None-Match (if sent) didn't match the current ETagCache for up to 5 minutes per Cache-Control; populate the dropdown from items
304— (no body)If-None-Match matched the catalog's current ETagKeep using the previously cached items
401— (gateway body {"message":"Unauthorized"})Missing/invalid/expired token, or a client not accepted by the authorizerRe-authenticate / refresh the token
401SESSION_REVOKEDThe token is valid but its session was revoked (standard { error: { code, message } } envelope, from the Lambda, not the gateway)Sign the user in again
404NOT_FOUNDname is not a registered catalog (including device-models/commands)Treat as a client bug — the set of valid names is fixed and known at build time, not user input
400VALIDATION_FAILEDAny query parameter was sentFix the client request — this is a client bug, not retryable as-is
500INTERNALUnexpected server errorRetry once; if it persists, report it
503DEPENDENCY_UNAVAILABLEN/A today (no DynamoDB call on this route) — listed for completeness with every other route's error table—

Edge cases​

  • version/ETag only changes when the vocabulary's values change, not on every deploy or cold start — it's a content hash of the items, so the same five 002 catalogs produce the same ETag across restarts. deprecated: true on an item is a value change too (it changes the hash), so a value transitioning to deprecated invalidates caches. Intl.DisplayNames/Intl.supportedValuesOf output (countries, timezones) is itself ICU-version-dependent — a Node/ICU upgrade can change a label or the exact timezone list, and therefore the hash, with no code change in this repo. See also CatalogResponse.
  • device-models/commands are gone (ADR 0012). They return the same 404 NOT_FOUND as a typo in name — fetch those catalogues from the TCP server instead.
  • No per-caller variation. Every signed-in caller gets the identical catalog for a given name — there is no per-org or per-role filtering, so Cache-Control: private is about per-client HTTP caching hygiene, not about the data actually varying per caller.