Skip to main content

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​

StageBase URL
devhttps://inv-api.crownsolarenergy.com (the old execute-api URL is disabled from 2026-12-03 and answers 403)
prodNot 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.

WhenStatusBody
Authorization header missing, token invalid/expired, or issued to a client the authorizer doesn't accept401{"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​

MethodPathPurposeAuthLambda's DynamoDB grant
GET/v1/meCurrent user's profile, selected plant (self-healing), account summaryRequiredRead/write (may provision the profile or heal selectedPlantId)
PUT/v1/me/selected-plantSet the account's currently-selected plantRequiredRead/write
GET/v1/plantsList plants the caller can accessRequiredRead
POST/v1/plantsCreate a plant (caller becomes OWNER)RequiredRead/write
GET/v1/plants/{plantId}Get one plant's detailRequiredRead
PATCH/v1/plants/{plantId}Edit plant settings (owner/admin, mobile)RequiredRead/write
DELETE/v1/plants/{plantId}Delete a plant (owner only, hard delete)RequiredRead/write
GET/v1/plants/{plantId}/devicesList devices belonging to a plantRequiredRead
POST/v1/plants/{plantId}/devicesClaim a device serial for a plantRequiredRead/write
GET/v1/lookupResolve a display code (e.g. PL-0518) to its entityRequiredRead (one GetItem, plus whatever the resolved type's own authorize reads)
GET/v1/search/suggestionsCross-entity typeahead search, per-type re-authorizedRequiredRead (one Query per searched type; own throttle, { rate: 20, burst: 40 })
GET/v1/catalog/{name}Static vocabulary (plant types, solar modes, …) for dropdownsRequiredNone — no DynamoDB call; built from code at cold start
GET/v1/orgs/{orgId}Organisation settings — name, localisation, contact, MFA requirementRequired, settings ≥ VIEWRead
PATCH/v1/orgs/{orgId}Change organisation settingsRequired, settings ≥ EDIT (mfaRequiredForAll needs FULL)Read/write
GET/v1/orgs/{orgId}/membersList an organisation's peopleRequired, team ≥ VIEWRead
GET/v1/orgs/{orgId}/members/summaryPeople summary tiles + per-department countsRequired, team ≥ VIEWRead
GET/v1/orgs/{orgId}/members/{sub}Member drawer — role, scope, MFA, warningsRequired, team ≥ VIEW (or self)Read
PATCH/v1/orgs/{orgId}/members/{sub}Change a member's role, scope, department or MFA requirementRequired, team ≥ MANAGERead/write
POST/v1/orgs/{orgId}/members/{sub}:suspend|:restore|:end-sessions|:reset-mfa|:removeMember lifecycle actions — suspend, restore, end sessions, reset two-factor, removeRequired, team ≥ MANAGERead/write
GET/v1/orgs/{orgId}/installersBusiness owner's Installers — list or search, page 1 with counts and installerRoleId (Installers)Required, team ≥ MANAGERead
GET/v1/orgs/{orgId}/installers/pendingPending Installer join requests and invitationsRequired, team ≥ MANAGERead
POST/v1/orgs/{orgId}/installers/{sub}:suspend|:restore|:detachSuspend, restore or detach an Installer (If-Match)Required, team ≥ MANAGERead/write
POST/v1/orgs/{orgId}/members:bulk-assign-scopeBulk-assign one scope to up to 50 members (Idempotency-Key required; the plain /v1/orgs/{orgId}/members is a backward-compatible alias)Required, team ≥ MANAGERead/write
GET/v1/orgs/{orgId}/rolesRoles screen — every role, system firstRequired, team ≥ VIEWRead
POST/v1/orgs/{orgId}/rolesCreate a custom role (copy of an existing one)Required, team = FULLRead/write
GET/v1/orgs/{orgId}/roles/{roleId}One role + member/invitation countsRequired, team ≥ VIEWRead
PATCH/v1/orgs/{orgId}/roles/{roleId}Change a custom role's name/perms/scopeRule/auditTrailRequired, team = FULLRead/write
DELETE/v1/orgs/{orgId}/roles/{roleId}Delete an unused custom roleRequired, team = FULLRead/write
GET/v1/orgs/{orgId}/scopes/summaryWho is authorized where — counts per scope kind + a paged listRequired, team ≥ VIEWRead
GET/v1/orgs/{orgId}/departmentsList departmentsRequired, team ≥ VIEWRead
POST/v1/orgs/{orgId}/departmentsCreate a departmentRequired, team ≥ MANAGERead/write
PATCH/v1/orgs/{orgId}/departments/{deptId}Rename/update a departmentRequired, team ≥ MANAGERead/write
DELETE/v1/orgs/{orgId}/departments/{deptId}Delete an unused departmentRequired, team ≥ MANAGERead/write
POST / GET/v1/orgs/{orgId}/invitationsInvite a person by email / list an org's invitationsRequired, team ≥ MANAGE (create: or delegated)Read/write, Read
POST/v1/orgs/{orgId}/invitations/{inviteId}:resendResend an invitation — new token, new expiryRequired, team ≥ MANAGERead/write
DELETE/v1/orgs/{orgId}/invitations/{inviteId}Revoke a pending invitationRequired, team ≥ MANAGERead/write
POST/v1/invitations:acceptAccept an invitation (the plain /v1/invitations is a backward-compatible alias)Required — any signed-in caller, no org contextRead/write
GET/v1/orgs/{orgId}/sharesList an operator's external shares + per-level countsRequired, customers ≥ VIEWRead
POST/v1/orgs/{orgId}/sharesGrant a new share to a CUSTOMER/PARTNER org or an individualRequired, customers ≥ MANAGE, OPERATOR member onlyRead/write
PATCH/v1/orgs/{orgId}/shares/{shareId}Change a share's level, selector, expiry, note or statusRequired, customers ≥ MANAGERead/write
POST/v1/realtime/ticketsIssue a signed WebSocket ticket for the TCP gatewayRequired, any ACTIVE member of the org contextRead
GET/v1/realtime/jwksPublic keys for verifying realtime ticketsNone — publicRead
POST/v1/plants/{plantId}/assignee-proofsSigned proof that an installer may be assigned to alerts on a plant (TCP assign_alert)Required, alerts and service ≥ EDIT on the plantRead/write (rate-limit counter)
GET/v1/orgs/{orgId}/access-logAccess-change log, newest first, filterable by type/dateRequired, team ≥ VIEW (changes/requestId fields need team ≥ MANAGE)Read
POST/v1/plants/{plantId}/access-requestsA grantee org requests a level on a plantRequired, plants ≥ VIEW in the active org (X-Org-Id)Read/write
GET/v1/orgs/{orgId}/access-requestsList incoming or outgoing access requestsRequired, customers ≥ MANAGE (incoming) or plants ≥ VIEW (outgoing)Read
GET / POST/v1/orgs/{orgId}/saved-viewsSaved viewsRequiredRead/write
PATCH / DELETE/v1/orgs/{orgId}/saved-views/{viewId}Saved viewsRequiredRead/write
POST/v1/plants/{plantId}/share-linksPlant share linksRequiredRead/write
DELETE/v1/plants/{plantId}/share-links/{linkId}Plant share linksRequiredRead/write
GET/v1/share-links/{token}Public share-link readNone — publicRead
POST/v1/orgs/{orgId}/access-requests/{requestId}:approve|:rejectApprove (creates a new share) or reject a pending requestRequired, customers ≥ MANAGERead/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:

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}:assign as a route template, because a path variable must fill a whole segment. The route is registered as POST /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 into id and verb, and checks the verb against that route's allow-list. Handlers see only the clean id.
  • 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. So POST /v1/<resource>/{id} with no :verb, or with a verb not in the allow-list, is 404, not 400. 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, and requestId in the error body. Handler-level unknown-action 404s (customers, members, plant lifecycle, access requests) also carry requestId. Deployed to dev 2026-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 plantId or createdAt. The exception is POST /v1/plants: its body is strict, so an unknown field (including status) is a 422.
    • 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-Type is accepted, and a body that's present but isn't valid JSON still returns 500 INTERNAL, not 4xx (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-Type must be application/json (else 415 UNSUPPORTED_MEDIA_TYPE) — checked before the size check below; then, once the body is present, the right Content-Type and within size, invalid JSON or a non-object body is 400 MALFORMED_REQUEST; then Zod failures are 422 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 the Content-Type check above; on a lenient route (which has no Content-Type check) it runs right after the missing/empty-body check.
    • A ZodError escaping any handler is 422 VALIDATION_FAILED with details = Zod's flattened { formErrors, fieldErrors } plus fieldCodes / formCodes.
    • Every VALIDATION_FAILED (422 body, 400 query) carries machine-readable details.fieldCodes next to fieldErrors. Switch on the codes, not the messages; see Validation field codes.
    • A base64-encoded body (isBase64Encoded) is decoded before parsing.
  • Response bodies: JSON, content-type: application/json. Optional fields with no value are left out, never null. This includes nextCursor on the last page.
  • Pagination: every list endpoint accepts limit and cursor.
    • 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 — limit included — is parsed as one unit: ANY problem with it (limit out of range, an unknown parameter, or a bad sort/filter value) is uniformly 400 VALIDATION_FAILED, not the 422 the request-BODY .strict() pipeline above uses.
    • cursor: an opaque base64url string taken from a previous response's nextCursor. Never a page number. GET /v1/plants and GET /v1/plants/{plantId}/devices now 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 v1 LastEvaluatedKey (from before this change), malformed, oversized, or bound to a different query silently restarts from the first page — there is still no INVALID_CURSOR error 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 with 400 INVALID_CURSOR (decodeCursor(…, { strict: true }), packages/core/src/pagination/ cursor.ts) rather than restarting silently.
    • A present nextCursor doesn't guarantee more items. The last page can come back as { "items": [] } with no nextCursor, because DynamoDB returns LastEvaluatedKey whenever it stopped at Limit.
  • 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-Id and X-Correlation-Id, and Cache-Control: no-store. Send an optional X-Correlation-Id request 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) carries Retry-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-console Cognito 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. dev falls 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 fails cdk synth if webOrigins is 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 the Authorization header, not cookies, so browser credentialed mode isn't needed and isn't enabled.
    • Max age: 7200 seconds (2 h) — how long a browser may cache a preflight response before re-asking.
  • 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.throttle in lib/routes.ts, applied via CfnStage.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).

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, …/invitations and …/shares parse the body first: a non-object body is 400 MALFORMED_REQUEST (an invalid object 422) before a missing Idempotency-Key is reported.
  • POST /v1/orgs/{orgId}/customers, …/partners, …/tags, web POST /v1/plants and POST /v1/plant-drafts check the header first: a missing Idempotency-Key is 428 before 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:

RequestPage 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/plants with X-Org-Id (the web variant only; the mobile variant keeps 25)
  • GET /v1/orgs/{orgId}/customers
  • GET /v1/orgs/{orgId}/partners
  • GET /v1/orgs/{orgId}/tags
  • GET /v1/orgs/{orgId}/businesses
  • GET /v1/orgs/{orgId}/members
  • GET /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/sessions
  • GET /v1/orgs/{orgId}/shares, /departments, /access-requests, /reports, /report-schedules, /maintenance-history, /maintenance-plans, /technicians (also with q: the cursor is bound to q, so keep sending the same q with it), /teams
  • GET /v1/plant-drafts, GET /v1/plants/{plantId}/installer-history, GET /v1/work-orders/{workOrderId}/events
  • GET /v1/plants/{plantId}/service: the open work orders use openLimit instead of limit (max 20): 15 on the first load, 10 with cursor = the previous openWorkOrders.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 a required route, a missing header is 428 PRECONDITION_REQUIRED (details: { header: "Idempotency-Key" }). On an optional route, a missing header just skips idempotency for that call. A present but malformed key (wrong length or characters) is 400 VALIDATION_FAILED — note this is 400, not the usual 422 for 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-Id if any, and body all match): the original response is replayed verbatim, with Idempotent-Replayed: true added. 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_PROGRESS with Retry-After: 1. Wait and resend the identical request.
  • A response that fails with 429, 503, or any 5xx is 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:

  1. The {orgId} path parameter — only for routes shaped /v1/orgs/{orgId}/…, where the path is authoritative.
  2. The X-Org-Id header.
  3. The orgId query 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.)

SituationStatus
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 all403 FORBIDDEN
The caller has a membership there, but it's SUSPENDED403 ACCOUNT_SUSPENDED
The caller has an ACTIVE membership thereResolves 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 — effectiveMfaRequired is always false — so no route returns 403 MFA_REQUIRED, whatever MFA_ENFORCEMENT is 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.reasonWhenFE action
WEB_CONSOLE_SIGN_IN_REQUIREDThe 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_REQUIREDWeb-console token, but no TOTP enrolledSend 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":

SituationStatus
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 404403 FORBIDDEN
The resource is visible, but the caller's level in the relevant category is below what the action needs403 FORBIDDEN
A bulk/multi-plant operation where the caller falls short on one or more of the plants403 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 ACTIVE membership in a SUSPENDED org returns 403 ACCOUNT_SUSPENDED. Since RBAC v2 (deployed to dev 2026-11-13): in a Business that is SUSPENDED or CLOSED, Business members and Installers get 403 FORBIDDEN details.reason: BUSINESS_SUSPENDED | BUSINESS_CLOSED while its End Users keep working; any other CLOSED org 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 answers 403 FORBIDDEN details.reason: NOT_A_MEMBER.
  • Org-level :end-sessions revokes access on every path: memberships with tokensValidAfter later than the token's auth_time are ignored. Selecting that org returns 401 SESSION_REVOKED, including when the only path in was a revoked platform membership.
  • After sign-out-everywhere, /v1/me and legacy GET /v1/plants return 401 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 DELETE that returns 409 can also mean the invitation count was truncated (rare).
  • Renaming a role or department by case only (for example ops to Ops) now works.