API reference — overview
Base path: every route is under /v1/. All request/response bodies are
application/json, camelCase. All timestamps are ISO-8601 UTC. All IDs are
ULIDs (sortable lexicographically), except
the user identifier, which is the Cognito sub.
Base URL
| Stage | Base URL |
|---|---|
dev | https://inv-api.crownsolarenergy.com (the old execute-api URL is disabled from 2026-12-03 and answers 403) |
prod | Not deployed yet — see Intro |
Every path below is relative to this base — e.g. GET /v1/me against dev
is GET https://inv-api.crownsolarenergy.com/v1/me. There
is no stage prefix in the path itself (the $default API Gateway stage is
deliberately unnamed — see
Architecture → Overall architecture),
so don't prepend /dev/.
:::caution Every example on these pages is illustrative, not captured
A dev deployment now exists (deployed 2026-09-17 — see
Infrastructure for the real Cognito/API IDs), but no
request/response trace has been captured against it yet. Every
request/response shown across this API reference is still derived directly
from the Zod schemas and handler source in cse-http-be — accurate to the
code, but explicitly not a real execution. See
Operations → Capturing real execution results
for how to replace these with genuine traces once one is run.
:::
Authentication
Every route below requires a bearer token:
Authorization: Bearer <Cognito ID or access token>
Tokens are obtained by the Flutter app talking directly to Cognito
(SRP or the custom email OTP flow) — this API has no /login or /signup
endpoint of its own; see Architecture → Authentication
for why, and see Authentication for the exact Cognito calls,
parameters, and deployed client/pool IDs the FE team needs to integrate
sign-up, sign-in (both flows), password reset, and sign-out.
Send the Cognito IdToken, not the AccessToken. The authorizer accepts
either one, since it validates aud on ID tokens and client_id on access
tokens against the two mobile app clients. But only the ID token carries the
email claim; an access-token call falls back to a Cognito AdminGetUser
lookup by sub (see GET /v1/me),
which is an extra AWS call this endpoint otherwise never makes. Tokens
minted by the server-admin client are rejected by the authorizer
(401), because that client isn't in its accepted list.
A missing, malformed, expired, or wrong-client token never reaches application
code. API Gateway's HttpUserPoolAuthorizer rejects it with 401 before any
Lambda runs, using API Gateway's own body (see below), not this API's error
envelope.
Gateway-generated responses
Some responses come from API Gateway itself, before or instead of a Lambda
handler. They do not use the { "error": { "code", "message" } }
envelope. The client has to handle them by HTTP status.
| When | Status | Body |
|---|---|---|
Authorization header missing, token invalid/expired, or issued to a client the authorizer doesn't accept | 401 | {"message":"Unauthorized"} |
Method + path matches no route (e.g. GET /v1/plant, PATCH /v1/plants/{id}) | 404 | {"message":"Not Found"} |
Lambda timed out (10 s limit), crashed outside handler(), or was throttled (the account concurrency quota is 1000, shared with TCP ingest) | 5xx | {"message":"..."} from API Gateway |
Only the 401 UNAUTHENTICATED envelope comes from application code. It
appears only when a route has no authorizer attached, which is a
misconfiguration (see
Architecture → Security).
A client should treat any 401 as "re-authenticate".
Endpoints
| Method | Path | Purpose | Auth | Lambda's DynamoDB grant |
|---|---|---|---|---|
GET | /v1/me | Current user's profile, selected plant (self-healing), account summary | Required | Read/write (may provision the profile or heal selectedPlantId) |
PUT | /v1/me/selected-plant | Set the account's currently-selected plant | Required | Read/write |
GET | /v1/plants | List plants the caller can access | Required | Read |
POST | /v1/plants | Create a plant (caller becomes OWNER) | Required | Read/write |
GET | /v1/plants/{plantId} | Get one plant's detail | Required | Read |
PATCH | /v1/plants/{plantId} | Edit plant settings (owner/admin, mobile) | Required | Read/write |
DELETE | /v1/plants/{plantId} | Delete a plant (owner only, hard delete) | Required | Read/write |
GET | /v1/plants/{plantId}/devices | List devices belonging to a plant | Required | Read |
POST | /v1/plants/{plantId}/devices | Claim a device serial for a plant | Required | Read/write |
GET | /v1/lookup | Resolve a display code (e.g. PL-0518) to its entity | Required | Read (one GetItem, plus whatever the resolved type's own authorize reads) |
GET | /v1/search/suggestions | Cross-entity typeahead search, per-type re-authorized | Required | Read (one Query per searched type; own throttle, { rate: 20, burst: 40 }) |
GET | /v1/catalog/{name} | Static vocabulary (plant types, solar modes, …) for dropdowns | Required | None — no DynamoDB call; built from code at cold start |
GET | /v1/orgs/{orgId} | Organisation settings — name, localisation, contact, MFA requirement | Required, settings ≥ VIEW | Read |
PATCH | /v1/orgs/{orgId} | Change organisation settings | Required, settings ≥ EDIT (mfaRequiredForAll needs FULL) | Read/write |
GET | /v1/orgs/{orgId}/members | List an organisation's people | Required, team ≥ VIEW | Read |
GET | /v1/orgs/{orgId}/members/summary | People summary tiles + per-department counts | Required, team ≥ VIEW | Read |
GET | /v1/orgs/{orgId}/members/{sub} | Member drawer — role, scope, MFA, warnings | Required, team ≥ VIEW (or self) | Read |
PATCH | /v1/orgs/{orgId}/members/{sub} | Change a member's role, scope, department or MFA requirement | Required, team ≥ MANAGE | Read/write |
POST | /v1/orgs/{orgId}/members/{sub}:suspend|:restore|:end-sessions|:reset-mfa|:remove | Member lifecycle actions — suspend, restore, end sessions, reset two-factor, remove | Required, team ≥ MANAGE | Read/write |
GET | /v1/orgs/{orgId}/installers | Business owner's Installers — list or search, page 1 with counts and installerRoleId (Installers) | Required, team ≥ MANAGE | Read |
GET | /v1/orgs/{orgId}/installers/pending | Pending Installer join requests and invitations | Required, team ≥ MANAGE | Read |
POST | /v1/orgs/{orgId}/installers/{sub}:suspend|:restore|:detach | Suspend, restore or detach an Installer (If-Match) | Required, team ≥ MANAGE | Read/write |
POST | /v1/orgs/{orgId}/members:bulk-assign-scope | Bulk-assign one scope to up to 50 members (Idempotency-Key required; the plain /v1/orgs/{orgId}/members is a backward-compatible alias) | Required, team ≥ MANAGE | Read/write |
GET | /v1/orgs/{orgId}/roles | Roles screen — every role, system first | Required, team ≥ VIEW | Read |
POST | /v1/orgs/{orgId}/roles | Create a custom role (copy of an existing one) | Required, team = FULL | Read/write |
GET | /v1/orgs/{orgId}/roles/{roleId} | One role + member/invitation counts | Required, team ≥ VIEW | Read |
PATCH | /v1/orgs/{orgId}/roles/{roleId} | Change a custom role's name/perms/scopeRule/auditTrail | Required, team = FULL | Read/write |
DELETE | /v1/orgs/{orgId}/roles/{roleId} | Delete an unused custom role | Required, team = FULL | Read/write |
GET | /v1/orgs/{orgId}/scopes/summary | Who is authorized where — counts per scope kind + a paged list | Required, team ≥ VIEW | Read |
GET | /v1/orgs/{orgId}/departments | List departments | Required, team ≥ VIEW | Read |
POST | /v1/orgs/{orgId}/departments | Create a department | Required, team ≥ MANAGE | Read/write |
PATCH | /v1/orgs/{orgId}/departments/{deptId} | Rename/update a department | Required, team ≥ MANAGE | Read/write |
DELETE | /v1/orgs/{orgId}/departments/{deptId} | Delete an unused department | Required, team ≥ MANAGE | Read/write |
POST / GET | /v1/orgs/{orgId}/invitations | Invite a person by email / list an org's invitations | Required, team ≥ MANAGE (create: or delegated) | Read/write, Read |
POST | /v1/orgs/{orgId}/invitations/{inviteId}:resend | Resend an invitation — new token, new expiry | Required, team ≥ MANAGE | Read/write |
DELETE | /v1/orgs/{orgId}/invitations/{inviteId} | Revoke a pending invitation | Required, team ≥ MANAGE | Read/write |
POST | /v1/invitations:accept | Accept an invitation (the plain /v1/invitations is a backward-compatible alias) | Required — any signed-in caller, no org context | Read/write |
GET | /v1/orgs/{orgId}/shares | List an operator's external shares + per-level counts | Required, customers ≥ VIEW | Read |
POST | /v1/orgs/{orgId}/shares | Grant a new share to a CUSTOMER/PARTNER org or an individual | Required, customers ≥ MANAGE, OPERATOR member only | Read/write |
PATCH | /v1/orgs/{orgId}/shares/{shareId} | Change a share's level, selector, expiry, note or status | Required, customers ≥ MANAGE | Read/write |
POST | /v1/realtime/tickets | Issue a signed WebSocket ticket for the TCP gateway | Required, any ACTIVE member of the org context | Read |
GET | /v1/realtime/jwks | Public keys for verifying realtime tickets | None — public | Read |
POST | /v1/plants/{plantId}/assignee-proofs | Signed proof that an installer may be assigned to alerts on a plant (TCP assign_alert) | Required, alerts and service ≥ EDIT on the plant | Read/write (rate-limit counter) |
GET | /v1/orgs/{orgId}/access-log | Access-change log, newest first, filterable by type/date | Required, team ≥ VIEW (changes/requestId fields need team ≥ MANAGE) | Read |
POST | /v1/plants/{plantId}/access-requests | A grantee org requests a level on a plant | Required, plants ≥ VIEW in the active org (X-Org-Id) | Read/write |
GET | /v1/orgs/{orgId}/access-requests | List incoming or outgoing access requests | Required, customers ≥ MANAGE (incoming) or plants ≥ VIEW (outgoing) | Read |
GET / POST | /v1/orgs/{orgId}/saved-views | Saved views | Required | Read/write |
PATCH / DELETE | /v1/orgs/{orgId}/saved-views/{viewId} | Saved views | Required | Read/write |
POST | /v1/plants/{plantId}/share-links | Plant share links | Required | Read/write |
DELETE | /v1/plants/{plantId}/share-links/{linkId} | Plant share links | Required | Read/write |
GET | /v1/share-links/{token} | Public share-link read | None — public | Read |
POST | /v1/orgs/{orgId}/access-requests/{requestId}:approve|:reject | Approve (creates a new share) or reject a pending request | Required, customers ≥ MANAGE | Read/write |
Registration, sign-in, password reset and sign-out are client-direct Cognito
calls (see Authentication). The five invitation routes above
are code-complete and unit-tested, not yet captured against a deployment —
see Invitations's own caveat, including two routes
(resend, accept) whose real wire-level path differs from the spec
contract's documentation shorthand. The four shares routes above are code-complete and unit-tested, not yet
captured against a deployment — see Shares's own caveat,
including two known gaps (TAG/REGION selectors aren't validated against a
tag catalog yet, and the level-band can/cannot lists are raw category
keys, not UI copy). The two realtime routes above are code-complete and
unit-tested, not yet captured against a deployment, and off by default
behind -c realtimeTicketsEnabled=true (cdk.json turns it on for dev; a stage without it answers
503 DEPENDENCY_UNAVAILABLE) — see Realtime
tickets's own caveat. The access-change log and the three
access-request routes above are likewise code-complete and unit-tested, not
yet captured against a deployment — see Access-change
log and Access requests for their
own caveats. There is no endpoint yet for
updating or deleting a plant or device, or for creating/editing roles or
departments — see Team for exactly which Team & Access
operations exist today vs. are still planned.
The whole discovery family (GET /v1/lookup, GET /v1/search/suggestions,
GET /v1/catalog/{name}) is deployed on dev (verified 2026-10-13) — see
Search, lookup & catalog.
Deploy status (dev verification, 2026-10-13). Live on dev: the web
plant list, /v1/plants/summary, /v1/plants/geo, plant drafts, workspace,
customers, partners, tags, favourites and discovery. Saved views and plant
share links are code-complete but have not been deployed or executed against
any stage. The realtime routes are
deployed but dev runs with realtimeTicketsEnabled off, so they answer
503 DEPENDENCY_UNAVAILABLE there. The 2026-10-13 code fixes were deployed
to dev the same day — see Known issues.
Planned changes (not implemented): see Roadmap → API conventions & planned inventory.
Full detail (headers, path/query params, request/response bodies, validation, status codes, edge cases) is on each resource's own page:
- Authentication (Cognito, client-direct)
- Account (
/v1/me) - Plants (
/v1/plants) - Create a plant: FE integration guide
- Plant devices — binding (
/v1/plants/{plantId}/devices) — the only device routes left; device inventory, transfers, imports, catalog, commands, bulk tasks, firmware and device files were removed by ADR 0012 (stub pages under "Removed:" in the sidebar) - Search, lookup & catalog (
/v1/lookup,/v1/search/suggestions,/v1/catalog/{name}) - Team & Access (
/v1/orgs/{orgId}/members,/roles,/scopes/summary) - Invitations (
/v1/orgs/{orgId}/invitations,POST /v1/invitations) - Shares (
/v1/orgs/{orgId}/shares) - Realtime tickets (
/v1/realtime/tickets,/v1/realtime/jwks) - Access-change log (
/v1/orgs/{orgId}/access-log) - Access requests (
/v1/plants/{plantId}/access-requests,/v1/orgs/{orgId}/access-requests)
Action routes (colon-verbs)
Some operations are verbs on a resource rather than CRUD, and are written
POST /v1/<resource>/{id}:<verb>, for example {workOrderId}:assign. The
colon form is the real, callable URL: send it literally. No such route exists
yet, so every route in the table above is plain CRUD. This is how they behave
once a route declares verbs:
- API Gateway can't declare
{id}:assignas a route template, because a path variable must fill a whole segment. The route is registered asPOST /v1/<resource>/{id}, and the single path parameter arrives at the Lambda as the string<id>:<verb>. - The family router (
parseActionSegment) splits it at the first colon intoidandverb, and checks the verb against that route's allow-list. Handlers see only the cleanid. - Some routes have no id, only a verb (
/v1/me/{action}). There the whole segment is the verb. - An unknown or missing verb is
404 NOT_FOUND(this API's error envelope, from the Lambda), the same status as an unmatched route. SoPOST /v1/<resource>/{id}with no:verb, or with a verb not in the allow-list, is404, not400. The FE should treat it as a bug in the client, not a retryable condition. - Router
404s carry tracing. An unknown colon-verb (e.g.POST /v1/plants/{id}:bogusverb), unknown action or unregistered route key goes through the standard pipeline:X-Request-Id,X-Correlation-Id,Cache-Control: no-store, andrequestIdin the error body. Handler-level unknown-action404s (customers, members, plant lifecycle, access requests) also carryrequestId. Deployed todev2026-10-13.
Each route's own page lists its exact verbs.
Conventions that apply to every endpoint
- Request bodies (
POST/PUT): JSON, validated with the route's Zod schema.- Unknown fields are silently dropped, not rejected, with one
exception. That includes an attempt to set a server-owned field such as
plantIdorcreatedAt. The exception isPOST /v1/plants: its body is strict, so an unknown field (includingstatus) is a422. - Strings are trimmed before length checks.
- Every route with a body, lenient or strict: a missing or empty body is
422 VALIDATION_FAILED("Request body is required") — this is checked first, before any strict-only check below, so it's the same status whether or not the route is strict. - Lenient routes (all seven current routes, kept lenient because the
shipped APK is): any
Content-Typeis accepted, and a body that's present but isn't valid JSON still returns500 INTERNAL, not4xx(KI-7). Unknown query parameters are ignored. - Strict routes (every new route — Team's
PATCH /v1/orgs/{orgId}/members/{sub}is the first one live):Content-Typemust beapplication/json(else415 UNSUPPORTED_MEDIA_TYPE) — checked before the size check below; then, once the body is present, the rightContent-Typeand within size, invalid JSON or a non-object body is400 MALFORMED_REQUEST; then Zod failures are422 VALIDATION_FAILED. - Every route with a body: a decoded body over 256 KiB is
413 PAYLOAD_TOO_LARGE. On a strict route this check runs after theContent-Typecheck above; on a lenient route (which has noContent-Typecheck) it runs right after the missing/empty-body check. - A
ZodErrorescaping any handler is422 VALIDATION_FAILEDwithdetails= Zod's flattened{ formErrors, fieldErrors }plusfieldCodes/formCodes. - Every
VALIDATION_FAILED(422body,400query) carries machine-readabledetails.fieldCodesnext tofieldErrors. Switch on the codes, not the messages; see Validation field codes. - A base64-encoded body (
isBase64Encoded) is decoded before parsing.
- Unknown fields are silently dropped, not rejected, with one
exception. That includes an attempt to set a server-owned field such as
- Response bodies: JSON,
content-type: application/json. Optional fields with no value are left out, nevernull. This includesnextCursoron the last page. - Pagination: every list endpoint accepts
limitandcursor.limit: integer, 1–50, default 25 — except the lazy-loading lists below (default 15 / 10). On the seven legacy routes, an out-of-range/non-numeric value silently falls back to the default (never rejected). On Team's strict list routes (the first live strict routes), the whole query string —limitincluded — is parsed as one unit: ANY problem with it (limitout of range, an unknown parameter, or a badsort/filter value) is uniformly400 VALIDATION_FAILED, not the422the request-BODY.strict()pipeline above uses.cursor: an opaque base64url string taken from a previous response'snextCursor. Never a page number.GET /v1/plantsandGET /v1/plants/{plantId}/devicesnow both issue "cursor v2" (packages/core/src/pagination/cursor.ts, T002-072): the cursor is bound to a hash of the route, org context, filters and sort it was issued for, plus a structural check that its key's partition matches the query about to run. Both routes stay lenient (CR-13): a cursor that's a plain v1LastEvaluatedKey(from before this change), malformed, oversized, or bound to a different query silently restarts from the first page — there is still noINVALID_CURSORerror on these two routes. A client mid-pagination across the deploy that shipped cursor v2 sees this once: its in-flight v1 cursor restarts at page one on its next call, not an error. Team's strict list routes (GET .../members,GET .../scopes/summary) instead reject a cursor that's malformed or bound to a different query with400 INVALID_CURSOR(decodeCursor(…, { strict: true }),packages/core/src/pagination/ cursor.ts) rather than restarting silently.- A present
nextCursordoesn't guarantee more items. The last page can come back as{ "items": [] }with nonextCursor, because DynamoDB returnsLastEvaluatedKeywhenever it stopped atLimit.
- List ordering: ascending by sort key. Plants are listed in creation order, oldest first (the IDs are ULIDs). Devices are listed by serial, lexicographic and case-sensitive.
- Errors: always the same envelope,
{ "error": { "code", "message", "details"?, "requestId"? } }, except for the gateway-generated responses above. See Types & schemas → Error codes for the full table. - Tracing headers: every Lambda response (success or error) carries
X-Request-IdandX-Correlation-Id, andCache-Control: no-store. Send an optionalX-Correlation-Idrequest header (^[A-Za-z0-9._:-]{1,64}$); if it's absent or doesn't match, the server uses the request id instead and echoes that. See Types & schemas → Response headers. - Transient failures:
503 DEPENDENCY_UNAVAILABLE(a throttled or unavailable AWS dependency) carriesRetry-After: 1. Retry with backoff and jitter. See the error code table. - Authorization: read fresh from DynamoDB on every request, never cached in the token. A role change, or losing access to a plant entirely, takes effect on the caller's very next request, not when their token expires.
- CORS (FR-034/FR-035, T002-058): configured for the planned web console
(
web-consoleCognito client), not for Flutter — native Flutter doesn't enforce same-origin, so this exists purely for browser callers.- Allowed origins come from CDK context, not a hardcoded list:
-c webOrigins=https://a.example.com,https://b.example.com(comma- separated) or a JSON array.devfalls back to the Vite dev server origin (http://localhost:5173) when no context is given, so local web-console development needs no extra flags. Every other stage failscdk synthifwebOriginsis empty, and*is rejected in every stage, dev included — an open CORS policy combined with bearer tokens is a real cross-site exposure, not just a cost guardrail. See Operations → Deployment process for the prod implication. - Allowed methods:
GET,POST,PUT,PATCH,DELETE,OPTIONS. - Allowed request headers:
Authorization,Content-Type,Idempotency-Key,If-Match,If-None-Match,X-Org-Id,X-Correlation-Id. - Exposed response headers (readable by browser JS):
ETag,X-Request-Id,X-Correlation-Id,Idempotent-Replayed,Retry-After,Location. - Credentials:
allowCredentials: false— the web console sends its bearer token in theAuthorizationheader, not cookies, so browser credentialed mode isn't needed and isn't enabled. - Max age:
7200seconds (2 h) — how long a browser may cache a preflight response before re-asking.
- Allowed origins come from CDK context, not a hardcoded list:
- Rate limiting / throttling (FR-037, T002-059): two independent layers.
- API Gateway stage throttling: a default of 50 requests/second,
burst 100 applies to every route, context-tunable
(
-c throttleRateLimit=… -c throttleBurstLimit=…) without a code change for a future stage that needs a different ceiling. This sits in front of the account's shared Lambda concurrency quota (1000, CLAUDE.md) as the first line of defence against exhausting it. - Per-route overrides (
RouteDef.throttleinlib/routes.ts, applied viaCfnStage.routeSettings): a route can declare its own, tighter{ rate, burst }— e.g. a future search-suggestions endpoint. No route declares one yet, so every route runs at the 50/100 stage default today. - Beyond these, don't load-test this API (see Architecture → Security).
- API Gateway stage throttling: a default of 50 requests/second,
burst 100 applies to every route, context-tunable
(
Check order on create routes
When a create request is wrong in two ways at once, routes disagree on which error comes first (current behaviour, verified in the handlers):
POST /v1/orgs/{orgId}/departments,…/invitationsand…/sharesparse the body first: a non-object body is400 MALFORMED_REQUEST(an invalid object422) before a missingIdempotency-Keyis reported.POST /v1/orgs/{orgId}/customers,…/partners,…/tags, webPOST /v1/plantsandPOST /v1/plant-draftscheck the header first: a missingIdempotency-Keyis428before the body is looked at.
Clients should always send a JSON object body and an Idempotency-Key on
these routes; the order then only matters for a malformed client.
Lazy-loading page sizes
Added 2026-11-24 for the web console's /plants and /customers screens, which
load more rows as the user scrolls. These lists use their own limit default
instead of the general 25:
| Request | Page size |
|---|---|
limit sent (1–50) | that value, always |
No limit, no cursor (first load) | 15 |
No limit, with cursor (each further load) | 10 |
A limit outside 1–50 is still 400 VALIDATION_FAILED. Keep requesting with
the last nextCursor until a response leaves it out.
The lists that follow this rule:
GET /v1/plantswithX-Org-Id(the web variant only; the mobile variant keeps 25)GET /v1/orgs/{orgId}/customersGET /v1/orgs/{orgId}/partnersGET /v1/orgs/{orgId}/tagsGET /v1/orgs/{orgId}/businessesGET /v1/orgs/{orgId}/membersGET /v1/orgs/{orgId}/invitations
Added the same day for every other console list (cse-admin-web ticket §5):
GET /v1/me/invitations,GET /v1/me/join-requests(paged since this change — it returned at most 50 rows in one response before),GET /v1/me/notifications,GET /v1/me/sessionsGET /v1/orgs/{orgId}/shares,/departments,/access-requests,/reports,/report-schedules,/maintenance-history,/maintenance-plans,/technicians(also withq: the cursor is bound toq, so keep sending the sameqwith it),/teamsGET /v1/plant-drafts,GET /v1/plants/{plantId}/installer-history,GET /v1/work-orders/{workOrderId}/eventsGET /v1/plants/{plantId}/service: the open work orders useopenLimitinstead oflimit(max 20): 15 on the first load, 10 withcursor= the previousopenWorkOrders.nextCursor
GET /v1/orgs/{orgId}/saved-views and GET /v1/orgs/{orgId}/roles are not
paged: both return a small, capped set in one response (saved views are capped
per org and per user when created; roles is a screen object with the system
roles plus the org's custom roles).
Optimistic concurrency (If-Match / ETag)
The mechanism (FR-016, FR-017) is fully implemented
(packages/core/src/concurrency.ts: parseIfMatch, versionedUpdate,
versionConflictFromCancellation, etag) but no route uses it yet — no
entity in this feature carries a version attribute, and no route in
lib/routes.ts is versioned: true. Once a route adopts it: a response
carries ETag: "<version>"; a write to that resource must send
If-Match: "<version>" (or the weak form, W/"<version>") back. A missing
header is 428 PRECONDITION_REQUIRED; a malformed one (*, a
comma-separated list, an unquoted number, or a quoted non-integer) is
400 VALIDATION_FAILED — not the usual 422 for that code, since it's a
header-shape problem caught before the request body is otherwise processed.
A well-formed but stale value is 409 VERSION_CONFLICT with
details.currentVersion.
Idempotency
The mechanism (Idempotency-Key header, FR-012–FR-015) is fully implemented
(packages/core/src/idempotency.ts, packages/api/src/http/idempotent.ts)
and live on six feature-003 create routes (idempotency: 'required' in
lib/routes.ts): POST /v1/orgs/{orgId}/members (bulk-assign-scope),
POST /v1/orgs/{orgId}/roles, POST /v1/orgs/{orgId}/departments,
POST /v1/orgs/{orgId}/invitations, POST /v1/orgs/{orgId}/shares, and
POST /v1/plants/{plantId}/access-requests — each page documents it in its
own request-headers table. The seven original legacy mobile routes
(including POST /v1/plants) are still 'none' — see
KI-21, unchanged by feature 003.
packages/api/test/contract/idempotency-required.test.ts is a standing
sweep: every RouteDef flagged required is driven through its real
handler with the header missing, asserting 428 — never 400 — so a
future route that forgets the wiring fails CI rather than drifting from this
page.
On a route configured required or optional:
- Send
Idempotency-Key: <1-128 chars of [A-Za-z0-9_-]>. On arequiredroute, a missing header is428 PRECONDITION_REQUIRED(details: { header: "Idempotency-Key" }). On anoptionalroute, a missing header just skips idempotency for that call. A present but malformed key (wrong length or characters) is400 VALIDATION_FAILED— note this is400, not the usual422for that code, since it's a header shape problem caught before the request is otherwise processed. - Same key, same request (method, route, path params,
X-Org-Idif any, and body all match): the original response is replayed verbatim, withIdempotent-Replayed: trueadded. This is true whether the original call already finished (COMPLETED, response replayed from storage) or its business transaction committed but the response was never stored, e.g. the Lambda crashed right after (COMMITTED, response rebuilt from the created/ changed resource instead). - Same key, different body:
422 IDEMPOTENCY_KEY_REUSED. Generate a new key for a genuinely different request. - Same key, original request still in flight:
409 IDEMPOTENCY_IN_PROGRESSwithRetry-After: 1. Wait and resend the identical request. - A response that fails with
429,503, or any5xxis never stored under the key — the claim is released, so a retry with the same key executes fresh rather than replaying a failure. A successful or business-failure response (2xx,403,404,409 VERSION_CONFLICT,422, etc.) is stored and replayed. - A response body over 64 KB is not stored. The record still advances to
COMMITTED(the resource was genuinely created/changed), but a replay for that key rebuilds the response from the resource itself rather than from a saved body. - The key is scoped per caller and per route: the same key value used by a different user, or against a different route, is entirely independent.
- Idempotency records keep a 24 h TTL (
IDEM#<sub>items), after which the same key can be reused for a brand new request.
Per-verb idempotency on colon-verb actions (CR-25). A single route can
carry several {id}:<verb> actions with DIFFERENT Idempotency-Key
requirements — RouteDef.actionIdempotency (lib/routes.ts) is an optional
{ [verb]: 'required' | 'optional' | 'none' } map; when the request's own
verb has an entry there, it overrides that route's top-level idempotency
value for that call only. For example, a work-order route might declare
idempotency: 'none' overall but actionIdempotency: { assign: 'required', cancel: 'optional' }, so POST /v1/work-orders/{id}:assign enforces the
header while POST /v1/work-orders/{id}:cancel makes it optional and every
other verb on that same route stays none. Two feature-003 routes declare
actions today — POST /v1/orgs/{orgId}/invitations/{inviteId}:resend
(idempotency: 'none' — see Invitations for why a
resend has no create-time duplicate hazard) and the id-less
POST /v1/invitations (:accept is documentation shorthand, D-09) — neither
currently sets a per-verb actionIdempotency override, so this mechanism
still awaits its first real user; this section documents the contract ahead
of that.
Request context and authorization errors
This mechanism (packages/api/src/http/context.ts, revocation.ts,
authorize.ts) is what every /v1/orgs/{orgId}/… route in the table above
(all of feature 003 — org settings, team, roles, departments, scopes,
invitations, shares, realtime tickets, the access-change log, access
requests) resolves its caller through, via resolveRequestContext. It does
not apply to the original seven legacy mobile routes (/v1/me,
/v1/plants…), which still authorize through the single-plant
OWNER/ADMIN/VIEWER membership described in Architecture →
Authentication and authorization.
See Authorization for the full model
this context resolution feeds into (roles, scopes, shares, the evaluator).
Selecting an organisation context
A route that needs an organisation context resolves one, per request, from up to three places, in this order:
- The
{orgId}path parameter — only for routes shaped/v1/orgs/{orgId}/…, where the path is authoritative. - The
X-Org-Idheader. - The
orgIdquery parameter.
A route that requires a context but finds none in any of these (and isn't a
path-based route) returns 400 ORG_CONTEXT_REQUIRED. A route that takes the
org from the path but gets no {orgId} segment returns the same code.
The resolved id is then checked against the caller's own memberships, never
trusted outright — and this includes a malformed value. A non-ULID or
otherwise malformed X-Org-Id gets no separate validation error: it's
treated exactly like any other value that doesn't resolve to a real
membership, below. (A header that fails a basic ULID shape check is still
surfaced, unresolved, on the base per-request logging context for
tracing/debugging — that's a separate, format-validated field used only for
logs, not an authorization decision.)
| Situation | Status |
|---|---|
| The caller has no ACTIVE membership in that org, and isn't an ACTIVE member of the platform organisation (which can act on any org) — including when the supplied id doesn't resolve to any real org at all | 403 FORBIDDEN |
The caller has a membership there, but it's SUSPENDED | 403 ACCOUNT_SUSPENDED |
| The caller has an ACTIVE membership there | Resolves normally |
A platform member who isn't otherwise a member of the selected org can still select it (the platform override); their request context then carries no org-specific membership, and a resource-level check (below) governs what they can actually do there.
Session revocation
Every resolved context compares the token's auth_time claim — the moment
the user originally authenticated, never a refreshed iat — against two
revocation watermarks: the account's own (UserProfile.tokensValidAfter,
always checked) and, when a real in-org membership was selected, that
membership's (Membership.tokensValidAfter). If auth_time is strictly
before either one, the request fails with 401 SESSION_REVOKED before
anything else runs. Since 2026-11-12 (not deployed) every authenticated
route also refuses a token whose sign-in was ended (current:end,
{sessionId}:end, :end-others, :end-all), matched by the token's
origin_jti, with the same 401 SESSION_REVOKED — see
Sessions. The FE should treat this exactly like any other 401:
drop the cached token and send the user back through sign-in — a revoked
session can't be refreshed into a valid one.
MFA requirement
Superseded 2026-11-11 (product decision): two-factor is the user's own choice. No organisation, org kind or role requires it —
effectiveMfaRequiredis alwaysfalse— so no route returns403 MFA_REQUIRED, whateverMFA_ENFORCEMENTis set to. The code stays reserved in the contract. The text below describes the earlier behaviour.
Once a context resolves to a real membership (the caller's own, or the
platform one on an override), its effective MFA requirement is evaluated
(explicit flag, PLATFORM org, or a role holding FULL on any category —
see Architecture → Authorization model;
personal organisations are always exempt). When it's on and not satisfied —
TOTP not enrolled, or enrolled but the token came from a mobile
(CUSTOM_AUTH-capable) client rather than the web console, which never
counts as satisfying it — the request fails with 403 MFA_REQUIRED.
This only actually refuses the request when the MFA_ENFORCEMENT
environment variable is on. The default, warn, logs the would-be
refusal server-side and lets the request through — so today, in every stage
that hasn't explicitly set MFA_ENFORCEMENT=on, this check is observable in
logs but never blocks anyone. When a client does receive 403 MFA_REQUIRED,
the right FE action is to send the user to TOTP enrolment through the web
console (the mobile app's email-OTP flow can't satisfy this), then retry.
Under MFA_ENFORCEMENT=on the same check can instead return 503 DEPENDENCY_UNAVAILABLE (Retry-After: 1) when the live Cognito MFA
re-check fails and the cached value is stale — retry after a second. See
Authorization.
Since OQ-09 (owner, 2026-10-27) the error carries additive
details: { reason, orgId, message } (code unchanged):
details.reason | When | FE action |
|---|---|---|
WEB_CONSOLE_SIGN_IN_REQUIRED | The token was not issued to a web-console client (for example the mobile app's email-OTP sign-in) | Tell the user this organisation must be used from the web console |
TOTP_ENROLMENT_REQUIRED | Web-console token, but no TOTP enrolled | Send to authenticator enrolment, then sign in again |
Under MFA_ENFORCEMENT=on,
403 MFA_REQUIRED (same reasons) can come from any route that acts through
an MFA-requiring membership, with or without X-Org-Id: plant routes and
PUT /v1/me/selected-plant, report get/download/delete/regenerate, schedule
get/patch/delete/pause/run, plant reports, delegated invitations, customer
change, plant jobs, service routes (roster, work orders) and device binding.
The membership that grants access decides. Exempt: individual shares, legacy
roles, personal orgs, and self routes (for example MFA enrolment). Lists,
batches and lookups hide gated items instead of failing.
A web user who has just enrolled TOTP may get one TOTP_ENROLMENT_REQUIRED
refusal before being accepted, when no org is selected: the cached MFA
mirror is re-checked against Cognito only after that refusal.
In warn mode the API logs, once per org per request,
MFA_ENFORCEMENT=warn: plant access would be refused MFA_REQUIRED and
MFA_ENFORCEMENT=warn: org access would be refused MFA_REQUIRED, plus the
request-level MFA_ENFORCEMENT=warn: request would be refused MFA_REQUIRED.
Watch all three before setting -c mfaEnforcement=on.
Resource-level checks: 404 vs 403
Once a context is resolved, a specific action on a specific resource (a
plant, an organisation's own settings, a capability like
grid.protection.write) is checked separately, and distinguishes "you can't
see this at all" from "you can see it but can't do that":
| Situation | Status |
|---|---|
| The caller has no access path to the resource at all (no membership, share, or portal relationship reaches it) | 404 NOT_FOUND — non-disclosure: a missing resource and one the caller can't see look identical |
Exceptions (kept for mobile compatibility): the legacy GET /v1/plants/{id} route, which has always returned 403 for a plant the caller can't see, and GET/POST /v1/plants/{plantId}/devices (owner decision Q16/Q8, 2026-10-27; a nonexistent plant is also 403 "You do not have access to this plant"). DELETE /v1/plants/{plantId}/devices/{serial} keeps 404 | 403 FORBIDDEN |
| The resource is visible, but the caller's level in the relevant category is below what the action needs | 403 FORBIDDEN |
| A bulk/multi-plant operation where the caller falls short on one or more of the plants | 403 FORBIDDEN with details.deniedPlantIds — the plant ids the caller lacks the level on, capped at 20 even if more actually failed |
Every denial in this section also increments a AuthzDenied operational
metric dimensioned only by category (plants, devices, …) — never by
plant id or user, so it stays within the low-cardinality CloudWatch metric
budget. This is an internal signal, not something that appears in the HTTP
response.
Authorization and error changes (Audit wave 1 (2026-10-27))
- An
ACTIVEmembership in aSUSPENDEDorg returns403 ACCOUNT_SUSPENDED. Since RBAC v2 (deployed to dev 2026-11-13): in a Business that is SUSPENDED or CLOSED, Business members and Installers get403 FORBIDDENdetails.reason: BUSINESS_SUSPENDED | BUSINESS_CLOSEDwhile its End Users keep working; any otherCLOSEDorg no longer grants access. Since 2026-11-19 closing a Business also removes every member and returns them to their own account (RBAC v2), and an org the caller holds no usable membership in answers403 FORBIDDENdetails.reason: NOT_A_MEMBER. - Org-level
:end-sessionsrevokes access on every path: memberships withtokensValidAfterlater than the token'sauth_timeare ignored. Selecting that org returns401 SESSION_REVOKED, including when the only path in was a revoked platform membership. - After sign-out-everywhere,
/v1/meand legacyGET /v1/plantsreturn401 SESSION_REVOKED. - Platform shortcuts reach only the selected org, and only when that org passed the Q15 verification.
- Several reads now return
503 DEPENDENCY_UNAVAILABLE, not a 500 or a partial result, when DynamoDB cannot serve a batch read. - A role
DELETEthat returns409can also mean the invitation count was truncated (rare). - Renaming a role or department by case only (for example
opstoOps) now works.