Realtime tickets API (A10/A11)
Feature 003 (Organisations, Team & Access), user story 8. This is how the
Flutter app gets live data flowing — not through this HTTP API itself, but
through the separate TCP ws-gateway (see Architecture → Overall
architecture: this repo
never connects to that backend's Postgres or joins its VPC). The HTTP
API's only job here is to issue a short-lived, signed ticket the app
hands to the WebSocket gateway, and to publish the public key the gateway
verifies that ticket against.
:::caution Code-complete, off by default — not yet captured against a deployment
packages/core/src/realtime/{ticket,jwks,kms-signer}.ts,
packages/api/src/handlers/realtime-{ticket,jwks}.ts and the KMS key in
lib/auth-stack.ts are landed and unit-tested as of 2026-10-03. The whole
subsystem is still behind the -c realtimeTicketsEnabled=true CDK context
flag (same opt-in convention as the integration bus's busEnabled — see
Operations → Edge and integration stacks)
and is off in every stage until a human passes that flag. Every
request/response shape below is illustrative — derived from
docs/openapi.yaml, ADR 0003 (docs/adr/0003-realtime-tickets.md) and the
Zod schemas, not a captured execution against a running stack.
When the flag is off (as on dev), there is no KMS key and no
REALTIME_TICKET_KEY_ARN / REALTIME_WS_URL. the two routes behave differently, because the
route table registers both unconditionally (lib/routes.ts, CreateRealtimeTicket /
GetRealtimeJwks) and the feature gate lives in the handler
(packages/core/src/realtime/kms-signer.ts, dependencyUnavailable('realtime-ticket-key')):
POST /v1/realtime/ticketssits behind the Cognito authorizer. With no or an invalid token the gateway answers401before the handler runs, so the feature gate is never reached (the web team observed401ondev, 2026-10-28). With a valid token, org context is resolved first (400/403errors win), then503 DEPENDENCY_UNAVAILABLEwithdetails.dependencyrealtime-ws-url. With the flag off neither the KMS key ARN nor the WS URL is set, and the handler checks the WS URL before it loads the signing key (packages/core/src/repositories/realtime.ts). Clients should treat anyDEPENDENCY_UNAVAILABLEhere as "realtime tickets unavailable" and not branch on thedependencyvalue.GET /v1/realtime/jwksis public (no authorizer) and answers503 DEPENDENCY_UNAVAILABLE,details.dependency: realtime-ticket-key, to anyone. Both routes stay unavailable ondevuntil a human deploys with-c realtimeTicketsEnabled=true -c realtimeWsUrl=<wss://…>, or saves both keys incdk.jsonundercontext.stages.<stage>.cdk.jsonsaves both fordev(2026-11-03):realtimeTicketsEnabled: trueandrealtimeWsUrl: wss://d2heoz2zkqbsg1.cloudfront.net/ws(the TCP ws-gateway'sWsGatewayUrloutput). They take effect at the nextnpm run deploy:dev; until thendevstill answers the 503s above. With tickets on, synth fails unlessrealtimeWsUrlis awss://URL that is not a loopback host, in every stage, dev included. (Before 2026-11-03, dev quietly fell back towss://localhost/ws, so tickets could be issued pointing at loopback.)
Captured 2026-10-13 against dev, unauthenticated: GET /v1/realtime/jwks
→ HTTP/2 503, cache-control: no-store, x-request-id present, body:
{"error":{"code":"DEPENDENCY_UNAVAILABLE","message":"The service is temporarily unavailable","details":{"dependency":"realtime-ticket-key"},"requestId":"<id>"}}
:::
How it fits together (ADR 0003)
Flutter ──POST /v1/realtime/tickets──▶ this API ──signs with KMS──▶ ticket (JWT)
Flutter ──WSS, ticket in the handshake──▶ ws-gateway (cse-tcp-be)
ws-gateway ──verifies the JWT offline, using GET /v1/realtime/jwks's public key──▶ (no call back to this API)
This repo owns who may see what (the grants a ticket carries, built
from the same membership/role/scope/share model every other route in this
API uses — see Architecture → Authorization
model).
The TCP side owns matching those grants against live telemetry — it
never reads this service's DynamoDB table, and this service never reads the
TCP side's Postgres (CLAUDE.md's hard invariant). The two sides agree only
on the ticket's JWT shape and the public key used to verify it.
Why a ticket, not a per-request authorization call: see ADR 0003's
"Options considered" — a signed, short-lived ticket means the WebSocket
gateway verifies offline (no network round-trip to this API per connection
or per subscription, and no extra load on the account's shared
Lambda-concurrency quota). The trade-off is revocation lag: access
narrowed after a ticket is issued doesn't take effect until the ticket
expires (≤ 10 minutes) unless the TCP side separately consumes this API's
access.revoked.v1 events to drop the connection early.
Overview
| Op | Method + path | Auth | Rate limit |
|---|---|---|---|
| Issue a ticket | POST /v1/realtime/tickets | Any ACTIVE member of the org context, any level | 30/minute/user |
| Public keys | GET /v1/realtime/jwks | None — public, unauthenticated | Stage throttling + WAF only |
POST /v1/realtime/tickets
Purpose: get a ticket to open (or re-authenticate) a WebSocket
connection to ws-gateway for the caller's current org context.
- Authorization: any ACTIVE member of the org context — no
category/level check the way
/v1/orgs/{orgId}/…routes have one. Refused by the same rules as any other authenticated route: a suspended account (403 ACCOUNT_SUSPENDED) or a revoked session (401 SESSION_REVOKED). (403 MFA_REQUIREDis no longer returned since 2026-11-11: two-factor is never required.) - Org context:
X-Org-Idheader. If absent, the mobile-legacy fallback applies — the caller's personal org, if they have one — else400 ORG_CONTEXT_REQUIRED. This is the one route in this feature that readsX-Org-Idas authoritative; every/v1/orgs/{orgId}/…route ignores it in favor of the path. - Idempotency: none. Every call mints a brand-new
jti(ULID) — there is no concept of "the same ticket request" to dedupe. - Rate limit: 30 requests/minute/user (
lib/routes.tsthrottle), independent of the Idempotency-Key mechanism used elsewhere in this API.
Request
Headers: X-Org-Id (see above).
Body (optional):
| Field | Type | Notes |
|---|---|---|
plantIds | array of ULID, 1–100 | Narrows the issued grants to just these plants. A plant the caller can't actually access is silently excluded, not an error — it's listed in the response's excludedPlantIds instead. Omit it to get the caller's full grant set (every plant their org/role/shares cover). |
Response — 201
{
ticket: string; // compact ES256 JWS: header.claims.signature, base64url, dot-joined
expiresAt: string; // iat + 600s (10 minutes) — always exactly this TTL, not configurable per request
kid: string; // matches a `kid` in GET /v1/realtime/jwks's keys[]
wsUrl: string; // the ws-gateway WebSocket URL to connect to with this ticket
grants: Array<{
sel: "all" | "org" | "tag" | "customer" | "plants" | "installer";
ids?: string[]; // absent only for sel: "all"
lv: { alerts: Level; devices: Level; commands: Level; firmware: Level;
registersRead: Level; registersWrite: Level; service: Level }; // the 7 realtime-relevant categories only (register keys: ADR 0014; firmware: 2026-11-12; service: 2026-11-23)
rd?: { serials?: boolean; engineering?: boolean }; // redaction flags, share/portal grants at external VIEW/MONITOR only
}>;
excludedPlantIds: string[]; // from the request's plantIds, those the caller doesn't actually have access to
frozenPlantIds: string[]; // 2026-11-14: plants frozen by Block B these grants would otherwise reach (the ticket's `xp`); empty when none
}
:::info Devices and commands are enforced by TCP (ADR 0012)
The HTTP server no longer serves devices or commands, but every grant still
carries the per-plant devices, commands, registersRead and
registersWrite levels (lv; the register keys were added by ADR 0014 —
until TCP reads them it keeps gating registers on devices/commands,
which equal the derived values for every role stored earlier). The TCP
server's ws-gateway checks those levels when the app reads devices or sends
commands, register reads/writes and device registrations over the WebSocket.
firmware (added 2026-11-12) lets the gateway hide firmware versions below
VIEW and require EDIT for firmware writes; it is capped on share and
customer-portal grants like the other keys.
:::
:::info service level (console request 2026-11-20 §1, added 2026-11-23)
Every grant's lv now also carries service, the role's service / work-order level, capped on share and
customer-portal grants like the other keys. TCP's assign_alert needs alerts ≥ EDIT and service ≥ EDIT
when it assigns an installer. A TCP reader treats a missing service key as NONE. A role whose only
realtime-relevant level is service now gets a grant; before, it got none.
:::
Grants are selectors, not a plant enumeration. A Crown HQ platform
member gets one {sel:"all"} grant, not one entry per plant in the fleet —
this is the whole point of ADR 0003's selector design (keeps the ticket
small even at the widest possible scope). One grant exists per covering
access path — a membership, a share, or a portal relationship — using
exactly the same evaluator every other route's authorization goes through
(see Architecture → Authorization
model):
| Your access path | sel |
|---|---|
PLATFORM membership, X-Org-Id = the PLATFORM org | all |
PLATFORM membership (scope ALL), X-Org-Id = an OPERATOR org or a personal org you are not a member of | org with ids: [that org], at the platform role's levels |
PLATFORM membership (scope ALL), X-Org-Id = a non-personal CUSTOMER org you are not a member of | customer with ids: [that org], no op (its plants under every operator) |
PLATFORM membership (scope ALL), X-Org-Id = a PARTNER org you are not a member of | installer with ids: [that org], no op: the plants it installed under every operator, plus its unbound stock. Only this path emits installer; a PARTNER org's own members reach plants through shares |
OPERATOR membership, scope ALL | org |
OPERATOR membership, scope TAG/REGION | tag |
OPERATOR membership, scope CUSTOMER | customer |
OPERATOR membership, scope PLANTS | plants |
| A share or customer-portal grant | plants (or narrower, per the share's own selector), lv capped at the share/portal's external-level ceiling — same ceiling table Shares documents |
Scope NONE contributes no grant at all.
Platform fallback (2026-11-04, deployed on dev; the PARTNER installer grant is committed, not yet deployed). Before this change, a Super Admin or Administrator who
selected a Business (X-Org-Id set to an org they hold no membership in, the owner Q15 path) got an empty
ticket. The web console's TCP-served Device Inventory and fleet screens were then empty inside that Business. The
fallback grant uses the platform role's own levels. A read-only platform role stays read-only, and the grant has no
rd, so serials are shown. With plantIds, the ticket gets one plants grant over the listed plants that the
selected org operates (for a customer org, is the customer of; for a PARTNER org, is the installer of); the rest
are in excludedPlantIds. No membership is MFA-gated since 2026-11-11.
The installer selector needs a TCP ws-gateway that knows it: a TCP build without it rejects the whole ticket.
TCP's selector was confirmed live on dev on 2026-11-04 (cse_tcp_be 511d777). Deploy TCP with it on staging or prod
before deploying this HTTP change there. TCP matches the plant's installer from its plant_projection, which
plant.upserted.v1 already fills, and an installer grant cannot accept device transfers.
A PLATFORM membership can only be scoped ALL or NONE (the built-in Administrator role forces ALL). So there is
no limited-scope platform Administrator to map to tag/customer/plants.
JWT shape (for the record — the TCP side's concern, not something the
FE app parses)
- Header:
{"alg":"ES256","typ":"JWT","kid":"<key id>"} - Claims:
iss,aud:"cse-tcp-be-ws",sub(Cognito sub),org(the org context's id),iat,nbf,exp(=iat+ 600),jti(ULID, unique per ticket),v:1,grants(as above), and — since 2026-11-05 (cse-mobile issue #98) —sa: trueonly when the subject is a Super Admin of the PLATFORM (Crown) org: the built-in Super Admin role on an ACTIVE, scope-ALLplatform membership in a non-suspended platform org, not MFA-gated, whatever org is selected. Otherwisesais omitted (neverfalse). It is optional and additive, sovstays1. An Administrator also holds asel: "all"grant, which is why TCP needssato tell them apart: ws-gateway hides and refuses the More settings group andwork_mode = 1(Anti-reflux to Meter) without it orpa(below). The app can read the same fact before it has a ticket fromGET /v1/me'splatformSuperAdmin. pa(added later on 2026-11-05, owner decision):pa: truewhen the subject holds the built-in platform Administrator role under exactly thesamembership rule; omitted otherwise,vstays1. ws-gateway treatssa || paas the privileged caller for the More group andwork_mode = 1. The app-side hint isGET /v1/me'splatformAdmin.oa(added 2026-11-06, web console request EB-6):oa: ["<orgId>"]when the subject is an Owner / Admin of the selected Business — the built-in Business (the org's owner), Administrator or Super Admin role on an ACTIVE, scope-ALLmembership of that org, where the org is an OPERATOR org that is neither suspended nor a personal org, and the membership is not MFA-gated. The value is the ticket's ownorg(a ticket is issued for one org context, so the array has at most one entry; it is an array so the shape can widen later without avbump). A custom role with the same levels does not count, nor does a Crown platform member reaching the org through the platform fallback (they carrysa/painstead). Otherwiseoais omitted (never[]);vstays1. ws-gateway can use it to let a Business admin run a bulk task on that Business's devices without a second approver (EB-1) — that rule itself is TCP's, not enforced here.pm(added 2026-11-12, console request §3):pm: truewhen the subject holds an ACTIVE membership in the Crown (PLATFORM) org, whatever its role; omitted otherwise (neverfalse). ws-gateway shows the real actor on alert actions only to apmreader; everyone else sees "Crown Support", matching the HTTP side (Role boundaries).vp(added 2026-11-12, §3):vp: truewhen this ticket reachesorgonly through the Crown platform fallback (no ACTIVE membership inorg, at least one fallback grant); omitted otherwise. ws-gateway records alert actions taken with such a ticket asviaPlatform. Both claims are additive;vstays1.xp(added 2026-11-14, RBAC v2): the ids of plants frozen by Block B that this ticket's grants would otherwise reach — at most 50, omitted when empty (neverxp: []). ws-gateway gives those plants no access under any grant for the whole session. Only plants the caller could reach are named. Never set for a Crown platform member (pm), who keeps view-only access to frozen plants. Additive;vstays1. A plant frozen after the ticket was issued is still cut off by TCP'splant.blocked.v1handling.oj(added 2026-11-30, QA B5): the Cognitoorigin_jtiof the sign-in that asked for the ticket. Omitted when the token has none. When that sign-in ends,access.revoked.v1 {reason: SESSIONS_ENDED, originJtis}lists it, and ws-gateway closes this ticket's sockets (code 4401) and refuses the ticket. Additive;vstays1.- Signed by an ES256 (P-256) key held in AWS KMS, non-exportable — the
private key material never leaves KMS, this service only ever calls
Sign.
Status codes
| Status | code | When | FE action |
|---|---|---|---|
| 201 | — | Ticket issued | Connect to wsUrl, present ticket in the handshake (per ws-gateway's own protocol — see cse-tcp-be's docs for that side) |
| 400 | ORG_CONTEXT_REQUIRED | No X-Org-Id and no personal-org fallback | Send X-Org-Id, or resolve one via GET /v1/me/context first |
| 401 | UNAUTHENTICATED / SESSION_REVOKED | No/bad token, or the session was revoked (sign-out-everywhere, :end-sessions) | Re-authenticate |
| 403 | FORBIDDEN | No ACTIVE membership at all in the org context | Pick a different org context |
| 403 | ACCOUNT_SUSPENDED | Membership in this org is SUSPENDED | Show the suspended-account state |
| 422 | VALIDATION_FAILED | Malformed plantIds (not 1–100 ULIDs) | Fix the request body |
| 422 | LIMIT_EXCEEDED | The encoded ticket exceeds its byte budget (details.maxBytes) — happens at very wide scope with no plantIds narrowing | Retry with an explicit, narrower plantIds list |
| 429 | RATE_LIMITED | Over 30 requests/minute for this user | Back off per Retry-After; cache the ticket client-side until near expiresAt instead of re-requesting per reconnect attempt |
| 500/503 | INTERNAL / DEPENDENCY_UNAVAILABLE | Unexpected, or the KMS Sign call failed/timed out/throttled, or realtime tickets are disabled (503, details.dependency realtime-ticket-key / realtime-ws-url) | Retry with backoff |
Edge case — revocation lag: a ticket already issued keeps working until
it expires (≤ 10 minutes) even if access is narrowed or revoked in the
meantime, unless the TCP side separately consumes access.revoked.v1
events to drop the connection early (ADR 0003's own stated trade-off — not
something the FE can work around by calling this route again sooner than
it needs to).
Update 2026-11-24 (TCP side): for a USER- or ORG-scope access.revoked.v1
(member suspend, remove/detach, end sessions, Business suspend/close), the TCP
gateway closes the user's sockets with code 4401 within seconds. It also
refuses any ticket issued at or before the revocation (auth_result code
TICKET_EXPIRED). After a 4401, request a new ticket from this route
rather than reusing a cached one. Plant-scoped revocations (with plantIds)
only end views of those plants. See the
Installer management handout.
POST /v1/plants/{plantId}/assignee-proofs
Console request 2026-11-20 §1. Assigning an installer to an alert happens on TCP (assign_alert over the
WebSocket). TCP has no copy of memberships, roles or technician profiles, so it cannot decide who is eligible.
This route checks eligibility on the HTTP side and returns a short-lived signed assignee proof. The client
passes it unchanged to TCP as installerProof. This server makes no call to TCP.
| Auth | Cognito authorizer; X-Org-Id optional (selects the org context like other plant routes) |
| AuthZ | the plant is visible (404 otherwise); alerts ≥ EDIT and service ≥ EDIT on it (403 otherwise) |
| Rate limit | 30 per minute per caller (429 RATE_LIMITED) |
| Lambda | the realtime family (the only family granted kms:Sign on the ticket key) |
Request
// POST /v1/plants/{plantId}/assignee-proofs Content-Type: application/json (strict body)
{ installerSub: string } // 1–128 chars: the Cognito sub of the person to assign
Eligibility rule
This is the same rule as work-order assignment: technicianEligibility in
packages/core/src/service/eligibility.ts, applied through resolveTechnician in
services/work-order-service.ts. Partners are not accepted. A person is eligible when all three hold:
- They hold an ACTIVE membership in the plant's operator org (the responsible Business), the org is not suspended, and their scope covers the plant. The plant's assigned Installer also counts.
- Through that membership,
service≥EDITon the plant, or an Installer-template role withservice≥VIEW. This exception applies to the assignee only. The caller always needsservice≥EDIT. - Their technician profile in that org, if one exists, is
active.
Response — 201
{
proof: string; // compact ES256 JWS
expiresAt: string; // iat + 300 s
kid: string; // same key as the realtime ticket: verify with GET /v1/realtime/jwks
assignee: { sub: string; name: string }; // name as written into the proof's `nm`
}
Proof claims
Header: {alg: "ES256", typ: "JWT", kid}. The key is the same KMS key as the ticket, but the audience is
different, so a ticket never passes as a proof and a proof never passes as a ticket.
| Claim | Value |
|---|---|
iss | cse-http-be |
aud | cse-tcp-be-assignee |
typ | assignee |
v | 1 (adding a claim keeps v) |
sub | the installer's sub (TCP requires it to equal assign_alert.installerSub) |
nm | the installer's display name, trimmed, at most 160 characters (technician profile name, else user profile name) |
plt | the plant id (TCP compares it with the alert device's current plant) |
org | the plant's operator org |
by | the caller's sub (TCP requires it to equal the ticket's sub) |
iat, nbf, exp | nbf = iat, exp = iat + 300 |
jti | a ULID (TCP keeps no replay store: a repeated assignment is unchanged) |
The name is a snapshot taken when the installer is assigned; a later rename does not change it. Eligibility is checked once, at assignment, the same as for work orders.
Status codes
| Status | Code | When |
|---|---|---|
201 | — | proof issued |
401 | — | no or invalid token (gateway) |
403 | FORBIDDEN | the caller is below alerts EDIT or service EDIT on the plant |
404 | NOT_FOUND | the plant does not exist or is not visible to the caller |
415 / 400 / 413 | strict-body codes | wrong Content-Type, malformed JSON, body too large |
422 | VALIDATION_FAILED | bad body, or details {field: "installerSub", reason: "INELIGIBLE_ASSIGNEE", cause} where cause is NOT_MEMBER, MEMBERSHIP_INACTIVE, SERVICE_LEVEL or PROFILE_INACTIVE; details.fieldCodes.installerSub is ["INELIGIBLE_ASSIGNEE"] |
429 | RATE_LIMITED | over 30 proofs per minute |
503 | DEPENDENCY_UNAVAILABLE | realtime tickets are off on the stage, or KMS failed |
Illustrative example (not a captured execution)
This route has not been deployed or exercised yet. The values below are made up, derived from the handler and schema.
POST /v1/plants/01JFXPLANT000000000000000A/assignee-proofs
Content-Type: application/json
{ "installerSub": "4f1c2d9e-0000-4000-8000-000000000001" }
{
"proof": "<header>.<claims>.<signature>",
"expiresAt": "2026-11-23T10:05:00.000Z",
"kid": "<kid from GET /v1/realtime/jwks>",
"assignee": { "sub": "4f1c2d9e-0000-4000-8000-000000000001", "name": "Hina R." }
}
Client flow
- The user picks an installer from
GET /v1/orgs/{orgId}/technicians?plantId=…(Service work orders). - Call this route with that sub.
- Send
assign_alert {alertId, installerSub, installerProof: proof, note}to TCP within 5 minutes. To unassign, sendinstallerSub: null; no proof is needed.
GET /v1/realtime/jwks
Purpose: the public key(s) the TCP ws-gateway uses to verify a
ticket's signature offline. This is the FE app's concern only in that it
exists — a mobile client has no reason to call it directly; it's
documented here because it's part of this feature's contract and is the
one deliberately public route in this API.
- Authorization: none. No token, no org context, no DynamoDB reads.
- Backing: KMS
GetPublicKey, memoised per warm Lambda container — not called on every request. - Rate limiting: stage-level API Gateway throttling plus WAF (002), not an app-level per-caller bucket (there's no caller identity to bucket by).
Response — 200
{
"keys": [
{ "kty": "EC", "crv": "P-256", "x": "<base64url, 32 bytes>", "y": "<base64url, 32 bytes>", "kid": "<key id>", "alg": "ES256", "use": "sig" }
]
}
Headers: Cache-Control: public, max-age=300.
During a key rotation, this list carries both the active and the
previous key — see Operations → Realtime ticket signing key
rotation
for the full procedure and why the overlap window matters. A ticket's kid
tells you which entry in keys[] verifies it.
Status codes
| Status | code | When |
|---|---|---|
| 200 | — | OK |
| 503 | DEPENDENCY_UNAVAILABLE | KMS GetPublicKey failed/timed out/throttled, or realtime tickets are disabled in this deployment (details.dependency: realtime-ticket-key) |
Ticket grant changes (Audit wave 1 (2026-10-27))
- Each grant may carry an optional
opfield: the operator org the grant is bound to. TCP contract change: whenopis present,cse-tcp-bemust also requireplant.operatorOrgId === op. Until TCP enforces it, the cross-tenant fix is enforced on the HTTP side only (the grant list itself). - Portal (customer) tickets carry one grant per operator.
- Share grants to an org grantee honour the member's own scope, so a broad ticket can now be narrower than before.
- No ticket is issued to a member of a
SUSPENDEDorg.
Known gaps
- No idempotency on ticket issuance — by design (ADR 0003: every call
is a fresh
jti), not an oversight. - Revocation is not instantaneous — see the edge case above. A ticket
is a bearer credential for its full 10-minute life unless the TCP side
independently watches
access.revoked.v1. - The exact
wsUrlhost/path forws-gatewayis acse-tcp-beconcern; this page documents only the field's presence in the response, not that backend's own connection protocol.