Account API (/v1/me)
GET /v1/me — Current user's profile
Purpose: Returns the caller's profile, their currently-selected plant
(re-validated and self-healed on every call), and an account-wide
plant/device summary. This is the first call the Flutter app makes on every
app launch/session-restore — see
Architecture → Data flow for why
selectedPlantId is validated here rather than only when it is written.
- HTTP method:
GET - Endpoint:
/v1/me - Authentication: Required (Cognito bearer token)
- Authorization: None beyond authentication. Every caller can always read their own profile.
- Side effects: this
GETcan write. It creates the profile if it's missing and rewrites a staleselectedPlantId, which is why its Lambda has a read/write grant. It's still safe to call repeatedly: both writes are idempotent. Feature 003 (FR-003) adds one more: a caller holding at least one legacyOWNERplant membership also gets their personal organisation lazily, idempotently created here if they don't have one yet — seeMeResponsefor the detail. 2026-11-19: an account that holds no ACTIVE membership also gets its personal organisation created (when it has none) or reopened (when it is CLOSED and the user belongs to no live Business). Nobody with an ACTIVE membership is touched (ADR 0026 D5.4). This step is best effort: if it fails, the response is still200withpersonalOrg: null, and the next call retries. - DynamoDB calls:
GetItemon the profile.PutItem(conditional) only if the profile is missing. OneQueryover the caller's legacy memberships, used for both the counts and the heal check.UpdateItemonly if a heal is needed. Feature 003 adds: a conditional personal-org creation transaction (only when the caller has a legacyOWNERmembership and no personal org yet), and aGSI1discoveryQuery+ twoBatchGetItemcalls (orgs/memberships, then any custom roles referenced) to build themembershipslist. 2026-11-19 adds oneGetItemon the personal-org pointer, plus aGetItemon that org only when it is not inmemberships(CLOSED); the create or reopen writes run only for an account with no ACTIVE membership.
Request
Headers
| Header | Required | Value |
|---|---|---|
Authorization | Yes | Bearer <token> |
Path parameters: none. Query parameters: none. Request body: none.
Response
Structure (MeResponse — additive extension of UserProfile, see
Types & schemas):
{
userId: string;
email: string;
displayName?: string;
createdAt: string;
termsAcceptedAt?: string;
selectedPlantId?: string; // absent for a zero-plant account
plantCount: number;
deviceCount: number;
// Additive as of 2026-10 (FR-007) — every field above is unchanged (SC-001):
memberships: MembershipSummary[];
defaultOrgId?: string;
mfa: { enrolled: boolean; requiredSomewhere: boolean };
// Additive 2026-11-05 (cse-mobile issue #98):
platformSuperAdmin: boolean;
platformAdmin: boolean; // added later the same day (owner decision)
// Additive 2026-11-19 (every account has exactly one personal org):
personalOrg: { orgId: string; status: "ACTIVE" | "SUSPENDED" | "CLOSED" } | null;
}
personalOrg is the caller's personal organisation, reported also while it
is CLOSED — it is then missing from memberships, because its plants moved
into a Business the caller joined. Every new account gets it at sign-up
(Cognito PostConfirmation), and this call creates or reopens it for an account
with no ACTIVE membership. null only when none could be made (the account
has no email) or this step failed this time.
platformSuperAdmin is true when memberships holds an ACTIVE, scope-ALL
membership in the PLATFORM (Crown) org with the built-in Super Admin role.
platformAdmin is the same test with the built-in Administrator role.
Each flag is a UI hint: the app shows the privileged inverter settings
to a caller with either flag, and uses them to hide those settings (the More group and the Anti-reflux to Meter work mode) before
it has a realtime ticket. The TCP ws-gateway enforces the rule itself from
the ticket's sa / pa claims (see Realtime), which are also absent
when the platform org is suspended or the membership is MFA-gated for the
request — so a write can still be refused when this flag is true.
Idempotent provisioning: if the caller's Cognito account was confirmed
before the PostConfirmation trigger existed, or that trigger failed at
sign-up, this endpoint creates the missing DynamoDB profile on the fly
instead of returning 404. A profile is guaranteed to exist once this call
returns. A profile created this way has no displayName or
termsAcceptedAt — those only come from the PostConfirmation path. Send
the ID token when you can: it carries email directly, with no extra
AWS call. An access token has no email claim
(requireClaims()/claims.ts reads it from the JWT only), so provisioning
from one falls back to a Cognito AdminGetUser lookup by sub
(IdentityProvider.getUserEmail, T002-039): if that lookup finds a verified
email, it's used; if it can't (user not found, no email attribute), the
profile is still created, with email: "", same as before this fix. Either
way the call itself always succeeds — it never returns 4xx/5xx for a missing
email.
Repairing a previously-empty email. This same AdminGetUser fallback
also runs on every GET /v1/me call, not only provisioning, when the
stored profile's email is exactly "" (from before T002-039, or from
a lookup that couldn't resolve one). If it now succeeds, the profile is
updated in place and the repaired email is returned immediately — the
caller never has to notice and retry. displayName and termsAcceptedAt
have no such repair path; see KI-15.
Field sources:
| Field | Source |
|---|---|
userId | Cognito sub |
email | Copied from the ID token's email claim, or resolved/repaired via AdminGetUser as described above, when the profile is created or on any later GET /v1/me if the stored value is "". Otherwise not re-synced |
displayName, termsAcceptedAt | Copied from Cognito once, when the profile is created. Not re-synced afterwards (KI-15) |
createdAt | When the DynamoDB profile was created, which isn't necessarily the Cognito sign-up time |
selectedPlantId | Stored on the profile. Only ever set by PUT /v1/me/selected-plant or by the self-heal; see the edge cases below |
plantCount | Count of the caller's legacy membership items, paginated across all of them (capped at 20 Query pages — not reachable at realistic per-account plant counts) and excluding any access-index copy item written by a 003/004-owned feature (copyVersion present), so such a copy never inflates the count (CR-13) |
deviceCount | Sum of a per-membership deviceCount attribute; until feature 005 deploys it is 0, afterwards it is maintained by the stream router and access-index seeding and is approximate (KI-10). Summed over the same legacy, non-copy membership items as plantCount |
Successful response — illustrative example
New account, zero plants, no organisation yet:
{
"userId": "01J9Z3K8N4R6X2QYV7M1WB0T3F",
"email": "user@example.com",
"displayName": "Example User",
"createdAt": "2026-09-16T09:12:41.000Z",
"termsAcceptedAt": "2026-09-16T09:12:40.000Z",
"plantCount": 0,
"deviceCount": 0,
"memberships": [],
"mfa": { "enrolled": false, "requiredSomewhere": false }
}
Account with plants whose client has already called
PUT /v1/me/selected-plant, so selectedPlantId is present and valid; this
account's first plant was created with no org context, so it has a personal
organisation (FR-003):
{
"userId": "01J9Z3K8N4R6X2QYV7M1WB0T3F",
"email": "user@example.com",
"displayName": "Example User",
"createdAt": "2026-09-16T09:12:41.000Z",
"selectedPlantId": "01J9Z4A1B2C3D4E5F6G7H8J9K0",
"plantCount": 3,
"deviceCount": 0,
"memberships": [
{
"orgId": "01J9Z5B2C3D4E5F6G7H8J9K0M1",
"code": "OP-0042",
"name": "Example User",
"kind": "CUSTOMER",
"personal": true,
"roleId": "01J9Z5C3D4E5F6G7H8J9K0M1N2",
"roleName": "Administrator",
"scopeKind": "ALL",
"scopeTargetCount": 0,
"status": "ACTIVE",
"mfaRequired": false
}
],
"defaultOrgId": "01J9Z5B2C3D4E5F6G7H8J9K0M1",
"mfa": { "enrolled": false, "requiredSomewhere": false }
}
deviceCount: 0 isn't a placeholder in this example. It's what the API
returns until feature 005 deploys, however many devices are claimed
(KI-10).
Failure response — auth failure (illustrative)
API Gateway's authorizer rejects a missing or invalid token before any Lambda code runs, with API Gateway's own body rather than this API's envelope (see API overview → Gateway responses):
{ "message": "Unauthorized" }
404 NOT_FOUND, 403 FORBIDDEN, 409 CONFLICT: not applicable to this
endpoint — every authenticated caller reads their own profile, which is
always provisioned defensively rather than ever 404ing.
HTTP status codes
| Status | code | When |
|---|---|---|
| 200 | — | Success |
| 401 | — (gateway body {"message":"Unauthorized"}) | Missing/invalid/expired token, or a token from a client other than the two mobile clients |
| 500 | INTERNAL | Unexpected server error |
Edge cases
- Stale
selectedPlantId: if the account's persistedselectedPlantIdpoints at a plant the caller no longer has a membership on (access revoked since their last call), the server transparently replaces it with another accessible plant (or omits the field entirely if the account now has zero plants) before building this response — the caller never sees the stale value and never has to detect/retry around it. - First call after signup: returns
plantCount: 0and noselectedPlantId. selectedPlantIdis never filled in automatically. Creating a plant doesn't select it, and the self-heal only replaces a value that exists and is stale. It never populates a missing one (KI-11). An account with plants has noselectedPlantIduntil the client successfully callsPUT /v1/me/selected-plant. Route to "create your first plant" onplantCount === 0, not on a missingselectedPlantId.- Which plant the heal falls back to: the first membership in sort-key order, i.e. the caller's oldest remaining plant.
PUT /v1/me/selected-plant — Set the currently-selected plant
Purpose: The explicit "switch plant" action for accounts with several
plants. Also how a client overrides a selection that GET /v1/me
self-healed.
- HTTP method:
PUT - Endpoint:
/v1/me/selected-plant - Authentication: Required
- Authorization: Caller must have
plants ≥ VIEWon the targetplantId, evaluated through the canonical access evaluator (feature 003, FR-058) — checked on every call, never assumed from a prior successful call. For a legacy single-owner plant this is satisfied by the caller'sOWNER/ADMIN/VIEWERaccess-index role, same as before 003. - DynamoDB calls (changed by feature 003, response unchanged — FR-058):
in parallel, the evaluator's
loadAccessFactsquery for the caller plus aGetItemon the caller's legacy access-index role (keys.accessIndexKey(sub, plantId)), thenUpdateItemon the profile, then the sameplantCount/deviceCountQueryasGET /v1/me. Before 003 this was a singleGetItemon the access-index item.
Request
Headers
| Header | Required | Value |
|---|---|---|
Authorization | Yes | Bearer <token> |
Content-Type | Yes | application/json |
Path parameters: none. Query parameters: none.
Request body (SetSelectedPlantInput —
schema):
| Field | Type | Required | Validation |
|---|---|---|---|
plantId | string | Yes | Trimmed, minimum 1 character |
Request payload example:
{ "plantId": "01J9Z4A1B2C3D4E5F6G7H8J9K0" }
Response
Same shape as GET /v1/me — the updated profile plus a fresh
plantCount/deviceCount.
Successful response — illustrative example
{
"userId": "01J9Z3K8N4R6X2QYV7M1WB0T3F",
"email": "user@example.com",
"createdAt": "2026-09-16T09:12:41.000Z",
"selectedPlantId": "01J9Z4A1B2C3D4E5F6G7H8J9K0",
"plantCount": 3,
"deviceCount": 0
}
Failure response — validation failure (illustrative)
Empty plantId:
{
"error": {
"code": "VALIDATION_FAILED",
"message": "Request validation failed",
"details": {
"fieldErrors": { "plantId": ["String must contain at least 1 character(s)"] },
"formErrors": []
}
}
}
Failure response — authorization failure (illustrative)
Caller has no membership on the requested plant (never had access, or it was revoked):
{ "error": { "code": "FORBIDDEN", "message": "No access to this plant" } }
Failure response — auth failure (illustrative)
Same as GET /v1/me: 401 with the gateway body {"message":"Unauthorized"},
before any handler code runs.
404 NOT_FOUND, 409 CONFLICT: not applicable — an inaccessible plant
is reported as 403 FORBIDDEN (matching whether the plant genuinely doesn't
exist, per the same non-disclosure reasoning as
the Plants API's GET /v1/plants/{plantId}),
and there is no uniqueness constraint this endpoint could conflict with.
HTTP status codes
| Status | code | When |
|---|---|---|
| 200 | — | Success |
| 401 | — (gateway body) | Missing/invalid token |
| 403 | FORBIDDEN | Caller has no membership on plantId |
| 413 | PAYLOAD_TOO_LARGE | Decoded body over 256 KiB |
| 422 | VALIDATION_FAILED | Missing/empty body, or missing/empty/whitespace-only plantId |
| 500 | INTERNAL | A body that isn't valid JSON (KI-7), or any other unexpected server error |
| 503 | DEPENDENCY_UNAVAILABLE | DynamoDB throttled, errored, or timed out. Carries Retry-After |
Edge cases
- Setting the plant that is already selected: succeeds with no special case. It's an idempotent write.
deviceCount/plantCountin the response come from a fresh summary query, the same asGET /v1/me. The response does not run the self-heal, since the plant was just validated.- This is also the fallback-retry path: if
GET /v1/meself-healed a stale selection to a plant the client's own UI disagrees with (e.g. the client has fresher knowledge of which plant the user was just looking at), the client calls this endpoint to explicitly override it — the server never refuses a valid, currently-accessible plant.
GET /v1/me/context — Organisation shell bootstrap
Purpose: Feature 003 (A03, FR-008). The one call the web-console shell
needs to render a single organisation: the org's own metadata, the caller's
level in each of the 15 permission categories (see Roles & permissions) there, which navigation
modules those levels unlock (except engineering, never listed for the built-in End User role or an Installer-template role since 2026-11-12), the caller's non-level capabilities, three
badge counts (see Badges) and the org's MFA requirement. Unlike GET /v1/me
(which lists every organisation briefly), this is one organisation in full
detail. A successful call also stores the resolved org as the caller's
defaultOrgId, which GET /v1/me returns. This route never falls back to
that stored value: an org selector is required (contract A03). Clients
read defaultOrgId from GET /v1/me and send it as X-Org-Id.
- HTTP method:
GET - Endpoint:
/v1/me/context - Authentication: Required
- Authorization: The selected organisation must be one of the caller's
own ACTIVE memberships, or any organisation at all when the caller holds
an ACTIVE platform membership (FR-009's one documented override — selecting
a foreign org this way does not grant any access by itself:
levelsstill reflects only what the caller actually holds there). - DynamoDB calls: the evaluator's
loadAccessFactsquery plus aGetItemfor the org META and the caller's own membership row, then (for aPARTNER/CUSTOMERorg only) two moreQuerys for the relationship/ share ceiling, then aBatchGetItemfor the two org badge counters. In parallel, forbadges.myInvitations: the caller's verified email (free from an ID token withemail_verified: true, otherwise one CognitoAdminGetUser), then oneQueryof their invitee inbox and, only if it holds entries, oneBatchGetItemof those invitations.
Request
Headers: Authorization: Bearer <token> (required).
Org selector (exactly one of, FR-009 precedence — header wins):
| Parameter | In | Required | Validation |
|---|---|---|---|
X-Org-Id | header | No | ULID |
orgId | query | No | ULID |
If the event carries any query string at all, it must be exactly
{ orgId } — an unknown query parameter, or an orgId that isn't a
syntactically valid ULID, is rejected with 400 VALIDATION_FAILED before
any org-selection logic runs (this route's own documented status set per
contracts/http-api.md A03 and FR-011 — not the generic strict-body
pipeline's 422, which other routes use for a bad request body). A
selector sent only via the X-Org-Id header (no query string) skips this
check. A selector is required: if neither is supplied, the response is
400 ORG_CONTEXT_REQUIRED, even when the caller has a stored defaultOrgId
(there is no fallback to it).
Path parameters: none. Request body: none.
Response
Structure (MeContextResponse — see
Types & schemas):
{
org: Organisation;
membership: Membership;
levels: { plants: Level; devices: Level; alerts: Level; commands: Level;
firmware: Level; service: Level; reports: Level; customers: Level;
team: Level; settings: Level;
registersRead: Level; registersWrite: Level; sharing: Level;
roles: Level; audit: Level }; // last five: ADR 0014
modules: NavModuleKey[];
capabilities: Capability[];
badges: { pendingInvitations: number; pendingAccessRequests: number; myInvitations: number | null };
mfaRequired: boolean;
}
Capabilities
capabilities lists the caller's non-level capabilities in the selected org: grid.protection.write,
firmware.approve, audit.export (Super Admin only — it needs the role's audit-trail flag, RBAC-S1),
plant.delete, device.remove, role.superadmin.assign, and since 2026-11-23 plant.create (RBAC-S11; built,
not deployed): present when the caller may create a plant in this org (plants ≥ EDIT — Crown staff, Business,
Installer, an independent End User in their own account), absent for an End User connected to a Business. Gate the
Add plant action on it. The enum is additive: ignore values you do not know.
Badges
| Field | Meaning | Today |
|---|---|---|
pendingInvitations | Pending invitations the selected organisation has sent (the team's work queue). Not the caller's own invitations. | Always 0. It reads the org counter COUNT#invitations#status#PENDING, and no stream projection maintains that counter for invitations (KI-24). For the real list use GET /v1/orgs/{orgId}/invitations?status=PENDING. |
pendingAccessRequests | Pending access requests the selected organisation must decide | Stream-maintained counter; may lag, and stays stale while the stream-router isn't running (KI-43) |
myInvitations | Added 2026-11-23 (console R2; deployed to dev 2026-11-23). The caller's own pending, unexpired INTERNAL/DELEGATED invitations — the number GET /v1/me/invitations would list, capped at 50. The same for every org the caller selects. | Live read, never stale. null when the account has no verified email (when that route would answer 403) or the count could not be read; the response is still 200. |
For an End User's notification bell, use myInvitations.
Successful response — illustrative example
{
"org": {
"orgId": "01J9Z5B2C3D4E5F6G7H8J9K0M1",
"code": "OP-0042",
"kind": "OPERATOR",
"personal": false,
"name": "Crown Solar Installers",
"status": "ACTIVE",
"countryCode": "PK",
"timezone": "Asia/Karachi",
"locale": "en-PK",
"currency": "PKR",
"dateFormat": "DD_MM_YYYY",
"units": "METRIC",
"mfaRequiredForAll": false,
"version": 3,
"createdAt": "2026-08-01T05:30:00.000Z",
"updatedAt": "2026-09-20T11:00:00.000Z"
},
"membership": {
"orgId": "01J9Z5B2C3D4E5F6G7H8J9K0M1",
"sub": "01J9Z3K8N4R6X2QYV7M1WB0T3F",
"displayName": "Example User",
"roleId": "01J9Z5C3D4E5F6G7H8J9K0M1N2",
"scope": { "kind": "ALL", "targets": [] },
"status": "ACTIVE",
"mfaRequired": false,
"mfaEnabled": false,
"joinedAt": "2026-08-01T05:31:00.000Z",
"version": 1,
"createdAt": "2026-08-01T05:31:00.000Z",
"updatedAt": "2026-08-01T05:31:00.000Z"
},
"levels": {
"plants": "FULL", "devices": "FULL", "alerts": "FULL", "commands": "MANAGE",
"firmware": "VIEW", "service": "MANAGE", "reports": "VIEW", "customers": "NONE",
"team": "MANAGE", "settings": "EDIT", "registersRead": "FULL",
"registersWrite": "MANAGE", "sharing": "NONE", "roles": "VIEW", "audit": "MANAGE"
},
"modules": ["overview", "plants", "analytics", "devices", "alerts", "engineering", "service", "reports", "team", "roles", "audit", "settings"],
"capabilities": ["grid.protection.write"],
"badges": { "pendingInvitations": 0, "pendingAccessRequests": 0, "myInvitations": 1 },
"mfaRequired": false
}
Failure response — org selector failures (illustrative)
{ "error": { "code": "ORG_CONTEXT_REQUIRED", "message": "An organisation context is required" } }
{ "error": { "code": "FORBIDDEN", "message": "Not permitted" } }
{ "error": { "code": "ACCOUNT_SUSPENDED", "message": "..." } }
{ "error": { "code": "MFA_REQUIRED", "message": "..." } }
{
"error": {
"code": "VALIDATION_FAILED",
"message": "Request validation failed",
"details": { "fieldErrors": { "orgId": ["Invalid"] }, "formErrors": [] }
}
}
Failure response — auth failure (illustrative)
API Gateway's own body, not this API's envelope (see API overview → Gateway responses):
{ "message": "Unauthorized" }
HTTP status codes
| Status | code | When |
|---|---|---|
| 200 | — | Success |
| 400 | VALIDATION_FAILED | A query string was sent that isn't exactly { orgId: <ULID> } — checked before ORG_CONTEXT_REQUIRED/org selection, so resolveRequestContext is never reached |
| 400 | ORG_CONTEXT_REQUIRED | No X-Org-Id/orgId selector supplied (a stored defaultOrgId is not used as a fallback) |
| 401 | — (gateway body) | Missing/invalid token |
| 401 | SESSION_REVOKED | The token's auth_time predates a profile- or membership-level revocation (end-sessions, suspend, remove) |
| 403 | FORBIDDEN | The org is not one of the caller's own ACTIVE memberships and they hold no platform membership. Since 2026-11-19 with details.reason: "NOT_A_MEMBER" (removed, detached or never a member) — move to another org: the next ACTIVE membership, else personalOrg from GET /v1/me |
| 403 | ACCOUNT_SUSPENDED | The caller's own membership in this org is SUSPENDED |
| 403 | MFA_REQUIRED | Not returned since 2026-11-11 (two-factor is never required). Earlier: this org/role requires MFA and the caller has none enrolled |
| 500 | INTERNAL | Unexpected server error |
Edge cases
- Platform-member override never grants access by itself: a platform
member can select ANY organisation (FR-009), but
levelsstill reflects only what they actually hold there — selecting a foreign org with no real membership there yieldslevelscomputed from an empty membership (effectively allNONEunless another access path applies). - Per-org-kind
levelscomputation (07-security.md§3.4): anOPERATORorg reports the role's own perms directly; aPARTNERorCUSTOMERorg caps every category atmin(role level, the relevant share/portal-relationship ceiling). Personal orgs are exempt: a personalCUSTOMER/PARTNERorg has no relationships above it, so it reports the role's own perms (packages/core/src/access/context-view.ts). Fix deployed todev2026-10-13; not yet re-verified with a signed-in call (before it, personal orgs reported every levelNONE). defaultOrgIdis set as a side effect of success, not of the request alone — a call that fails (400/401/403) never changes it.
Related: in-app inbox
GET /v1/me/notifications and POST /v1/me/notifications:mark-read (HTTP in-app inbox, not deployed yet) are
documented under Notifications → HTTP in-app inbox.
Related: account settings (feature 010)
The web console Settings screen uses the separate
Account settings API (/v1/me/settings,
/v1/me/profile, /v1/me/preferences, /v1/me/sessions, security verbs).
Side effect (best-effort): since 2026-11-12 (not deployed) every
authenticated route records or refreshes the caller's sign-in record
(device label, lastActiveAt, and the console-forwarded IP) before its
handler runs, and refuses a token whose sign-in was ended with
401 SESSION_REVOKED. See
Sessions. The bookkeeping
never changes a response, and if it fails it fails silently.
Web console additions
See Web console additions (N-37 … N-51) for the newer, not-yet-deployed fields and routes on this area.