Skip to main content

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/tickets sits behind the Cognito authorizer. With no or an invalid token the gateway answers 401 before the handler runs, so the feature gate is never reached (the web team observed 401 on dev, 2026-10-28). With a valid token, org context is resolved first (400/403 errors win), then 503 DEPENDENCY_UNAVAILABLE with details.dependency realtime-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 any DEPENDENCY_UNAVAILABLE here as "realtime tickets unavailable" and not branch on the dependency value.
  • GET /v1/realtime/jwks is public (no authorizer) and answers 503 DEPENDENCY_UNAVAILABLE, details.dependency: realtime-ticket-key, to anyone. Both routes stay unavailable on dev until a human deploys with -c realtimeTicketsEnabled=true -c realtimeWsUrl=<wss://…>, or saves both keys in cdk.json under context.stages.<stage>. cdk.json saves both for dev (2026-11-03): realtimeTicketsEnabled: true and realtimeWsUrl: wss://d2heoz2zkqbsg1.cloudfront.net/ws (the TCP ws-gateway's WsGatewayUrl output). They take effect at the next npm run deploy:dev; until then dev still answers the 503s above. With tickets on, synth fails unless realtimeWsUrl is a wss:// URL that is not a loopback host, in every stage, dev included. (Before 2026-11-03, dev quietly fell back to wss://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​

OpMethod + pathAuthRate limit
Issue a ticketPOST /v1/realtime/ticketsAny ACTIVE member of the org context, any level30/minute/user
Public keysGET /v1/realtime/jwksNone — public, unauthenticatedStage 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_REQUIRED is no longer returned since 2026-11-11: two-factor is never required.)
  • Org context: X-Org-Id header. If absent, the mobile-legacy fallback applies — the caller's personal org, if they have one — else 400 ORG_CONTEXT_REQUIRED. This is the one route in this feature that reads X-Org-Id as 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.ts throttle), independent of the Idempotency-Key mechanism used elsewhere in this API.

Request​

Headers: X-Org-Id (see above).

Body (optional):

FieldTypeNotes
plantIdsarray of ULID, 1–100Narrows 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 pathsel
PLATFORM membership, X-Org-Id = the PLATFORM orgall
PLATFORM membership (scope ALL), X-Org-Id = an OPERATOR org or a personal org you are not a member oforg 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 ofcustomer 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 ofinstaller 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 ALLorg
OPERATOR membership, scope TAG/REGIONtag
OPERATOR membership, scope CUSTOMERcustomer
OPERATOR membership, scope PLANTSplants
A share or customer-portal grantplants (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: true only when the subject is a Super Admin of the PLATFORM (Crown) org: the built-in Super Admin role on an ACTIVE, scope-ALL platform membership in a non-suspended platform org, not MFA-gated, whatever org is selected. Otherwise sa is omitted (never false). It is optional and additive, so v stays 1. An Administrator also holds a sel: "all" grant, which is why TCP needs sa to tell them apart: ws-gateway hides and refuses the More settings group and work_mode = 1 (Anti-reflux to Meter) without it or pa (below). The app can read the same fact before it has a ticket from GET /v1/me's platformSuperAdmin.
  • pa (added later on 2026-11-05, owner decision): pa: true when the subject holds the built-in platform Administrator role under exactly the sa membership rule; omitted otherwise, v stays 1. ws-gateway treats sa || pa as the privileged caller for the More group and work_mode = 1. The app-side hint is GET /v1/me's platformAdmin.
  • 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-ALL membership 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 own org (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 a v bump). A custom role with the same levels does not count, nor does a Crown platform member reaching the org through the platform fallback (they carry sa / pa instead). Otherwise oa is omitted (never []); v stays 1. 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: true when the subject holds an ACTIVE membership in the Crown (PLATFORM) org, whatever its role; omitted otherwise (never false). ws-gateway shows the real actor on alert actions only to a pm reader; everyone else sees "Crown Support", matching the HTTP side (Role boundaries).
  • vp (added 2026-11-12, §3): vp: true when this ticket reaches org only through the Crown platform fallback (no ACTIVE membership in org, at least one fallback grant); omitted otherwise. ws-gateway records alert actions taken with such a ticket as viaPlatform. Both claims are additive; v stays 1.
  • 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 (never xp: []). 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; v stays 1. A plant frozen after the ticket was issued is still cut off by TCP's plant.blocked.v1 handling.
  • oj (added 2026-11-30, QA B5): the Cognito origin_jti of 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; v stays 1.
  • 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​

StatuscodeWhenFE action
201—Ticket issuedConnect to wsUrl, present ticket in the handshake (per ws-gateway's own protocol — see cse-tcp-be's docs for that side)
400ORG_CONTEXT_REQUIREDNo X-Org-Id and no personal-org fallbackSend X-Org-Id, or resolve one via GET /v1/me/context first
401UNAUTHENTICATED / SESSION_REVOKEDNo/bad token, or the session was revoked (sign-out-everywhere, :end-sessions)Re-authenticate
403FORBIDDENNo ACTIVE membership at all in the org contextPick a different org context
403ACCOUNT_SUSPENDEDMembership in this org is SUSPENDEDShow the suspended-account state
422VALIDATION_FAILEDMalformed plantIds (not 1–100 ULIDs)Fix the request body
422LIMIT_EXCEEDEDThe encoded ticket exceeds its byte budget (details.maxBytes) — happens at very wide scope with no plantIds narrowingRetry with an explicit, narrower plantIds list
429RATE_LIMITEDOver 30 requests/minute for this userBack off per Retry-After; cache the ticket client-side until near expiresAt instead of re-requesting per reconnect attempt
500/503INTERNAL / DEPENDENCY_UNAVAILABLEUnexpected, 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.

AuthCognito authorizer; X-Org-Id optional (selects the org context like other plant routes)
AuthZthe plant is visible (404 otherwise); alerts ≥ EDIT and service ≥ EDIT on it (403 otherwise)
Rate limit30 per minute per caller (429 RATE_LIMITED)
Lambdathe 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:

  1. 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.
  2. Through that membership, service ≥ EDIT on the plant, or an Installer-template role with service ≥ VIEW. This exception applies to the assignee only. The caller always needs service ≥ EDIT.
  3. 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.

ClaimValue
isscse-http-be
audcse-tcp-be-assignee
typassignee
v1 (adding a claim keeps v)
subthe installer's sub (TCP requires it to equal assign_alert.installerSub)
nmthe installer's display name, trimmed, at most 160 characters (technician profile name, else user profile name)
pltthe plant id (TCP compares it with the alert device's current plant)
orgthe plant's operator org
bythe caller's sub (TCP requires it to equal the ticket's sub)
iat, nbf, expnbf = iat, exp = iat + 300
jtia 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​

StatusCodeWhen
201—proof issued
401—no or invalid token (gateway)
403FORBIDDENthe caller is below alerts EDIT or service EDIT on the plant
404NOT_FOUNDthe plant does not exist or is not visible to the caller
415 / 400 / 413strict-body codeswrong Content-Type, malformed JSON, body too large
422VALIDATION_FAILEDbad 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"]
429RATE_LIMITEDover 30 proofs per minute
503DEPENDENCY_UNAVAILABLErealtime 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​

  1. The user picks an installer from GET /v1/orgs/{orgId}/technicians?plantId=… (Service work orders).
  2. Call this route with that sub.
  3. Send assign_alert {alertId, installerSub, installerProof: proof, note} to TCP within 5 minutes. To unassign, send installerSub: 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​

StatuscodeWhen
200—OK
503DEPENDENCY_UNAVAILABLEKMS 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 op field: the operator org the grant is bound to. TCP contract change: when op is present, cse-tcp-be must also require plant.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 SUSPENDED org.

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 wsUrl host/path for ws-gateway is a cse-tcp-be concern; this page documents only the field's presence in the response, not that backend's own connection protocol.