Skip to main content

Team & Access API (/v1/orgs/{orgId}/…)

Feature 003 (Organisations, Team & Access). These are the first routes in this repo's OpenAPI contract backed by the new authorization model — plants, devices, alerts, commands, firmware, service, reports, customers, team, settings levels, evaluated fresh on every request, never cached in the token. Every route on this page is {orgId}-scoped: the path is authoritative — an X-Org-Id header is ignored on these routes (it only matters for GET /v1/me/context). They are also the first strict (CR-13) routes in this API: unknown query parameters are rejected rather than silently ignored, and PATCH /v1/orgs/{orgId}/members/{sub} is the first versioned route (If-Match/ETag).

:::caution Illustrative examples only No request/response trace has been captured against a real deployment yet. Every example below is derived directly from the Zod schemas (packages/core/src/schemas.ts) and handler/repository source (packages/api/src/handlers/{org,members,departments,scopes,roles}.ts, packages/core/src/repositories/{organizations,memberships,roles,departments}.ts) — accurate to the code as of 2026-10-03, not a genuine execution. :::

Authorization used on this page​

Most routes below require team ≥ a level; GET/PATCH /v1/orgs/{orgId} require settings ≥ a level instead — both are ordinary categories in the same 15-category permission map (role routes use roles, not team, since ADR 0014 — see Roles & permissions) (see Architecture → Authorization model for the full level/category/role model and the 7 seeded roles' columns):

Roleteam levelsettings levelroles level
Super AdminFULLFULLFULL
AdministratorMANAGEMANAGE (was EDIT)MANAGE (was VIEW)
Business (R-90)MANAGEMANAGEMANAGE
Installer (R-91 template)NONENONENONE

These are the five product roles (2026-11-03, see Roles & permissions). Viewer and the old Operations Manager, Technician, Sales and Compliance Auditor templates are retired; members who still hold them keep their old levels (Authorization).

So every team ≥ VIEW and team ≥ MANAGE route below is reachable by Super Admin, Administrator and Business. Role routes (B08) are gated on the roles category instead (ADR 0014): reads need roles ≥ VIEW, writes roles ≥ MANAGE — Super Admin, Administrator and Business by default. A Super Admin skips the escalation check everywhere (R-0). settings ≥ EDIT (org settings PATCH) is Super Admin, Administrator and Business; mfaRequiredForAll specifically needs settings = FULL — Super Admin only. A caller with no ACTIVE membership in {orgId} at all (and no platform-membership override) gets 404 NOT_FOUND — the organisation itself is invisible, not merely under-permissioned. A caller who IS a member but below the required level gets 403 FORBIDDEN.


GET/PATCH /v1/orgs/{orgId} — Organisation settings​

Purpose: Read and change organisation-wide settings — name, localisation, contact details, work week, fiscal year start, and the org-wide MFA requirement.

  • HTTP methods: GET, PATCH
  • Authentication: Required
  • Authorization: GET — settings ≥ VIEW (any ACTIVE member). PATCH — settings ≥ EDIT; mfaRequiredForAll specifically requires settings = FULL (403 FORBIDDEN otherwise, checked inside patchOrganization itself, not a .strict() shape error).
  • Concurrency: PATCH is versioned — If-Match required, response carries ETag. GET also carries ETag ("<version>").
  • DynamoDB calls: GET — one GetItem on the org META. PATCH — the same read, then one TransactWriteCommand (conditional org update on version, an outbox PutItem for org.upserted.v1, one access-log PutItem for ORG_UPDATED).

Request​

Path parameters: orgId (ULID).

PATCH headers

HeaderRequiredNotes
If-MatchYesMissing → 428. Malformed (not a single quoted integer version) → 400, not 422.
Content-TypeYesapplication/json

PATCH body — at least one field required, all optional:

FieldTypeNotes
namestring, 1–120 chars
countryCodestringISO 3166-1 alpha-2
timezonestringIANA zone name. "Re-labels history" only — no data migration against already-recorded timestamps.
localestring, BCP-47 tag, 2–35 charsTrimmed; stored in canonical form (e.g. en-pk → en-PK); a non-BCP-47 tag is 422
secondaryLocalestring, BCP-47 tag, 2–35 chars, or nullCanonicalised like locale; null clears it
currencystring, 3 lettersISO 4217, upper-cased server-side; must be in the runtime currency list, else 422
dateFormatDD_MM_YYYY | MM_DD_YYYY | YYYY_MM_DD | D_MMM_YYYY (e.g. 5 Mar 2026)
unitsMETRICthe only value today
workWeekarray of MON..SUN, 1–7 itemsdays must be unique
fiscalYearStartstring MM-DDMust be a real calendar day (02-29 ok, 02-31 is 422)
contact{legalName?, businessType?, address?, phone?, email?, website?, taxNumber?}Shallow-merged onto the current contact — an omitted key is left alone; there is no way to clear a single sub-field, only overwrite it with a new value
mfaRequiredForAllbooleanRequires settings = FULL. Org-wide MFA requirement, independent of any individual member's own mfaRequired flag. Advisory only since 2026-11-11 — stored and returned, but never refuses a request or mfa:disable

Server-owned fields (kind, code, personal, status) are rejected with 422 if sent — a generic .strict() shape error, not a dedicated reason.

Response​

{
orgId: string; code: string; // "ORG-0001"
kind: "PLATFORM"|"OPERATOR"|"PARTNER"|"CUSTOMER";
personal: boolean; name: string;
status: "ACTIVE"|"SUSPENDED";
countryCode: string; timezone: string;
locale: string; secondaryLocale?: string;
currency: string;
dateFormat: "DD_MM_YYYY"|"MM_DD_YYYY"|"YYYY_MM_DD"|"D_MMM_YYYY";
units: "METRIC";
workWeek?: Array<"MON"|"TUE"|"WED"|"THU"|"FRI"|"SAT"|"SUN">;
fiscalYearStart?: string; // "MM-DD"
contact?: { legalName?: string; businessType?: string; address?: string; phone?: string; email?: string; website?: string; taxNumber?: string };
mfaRequiredForAll: boolean;
version: number; // also the ETag, quoted: "4"
createdAt: string; updatedAt: string;
}

Successful response — illustrative example​

{
"orgId": "01J9Z4ORG000000000000001",
"code": "ORG-0003",
"kind": "OPERATOR",
"personal": false,
"name": "Crown Solar Pakistan",
"status": "ACTIVE",
"countryCode": "PK",
"timezone": "Asia/Karachi",
"locale": "en-PK",
"currency": "PKR",
"dateFormat": "DD_MM_YYYY",
"units": "METRIC",
"fiscalYearStart": "07-01",
"mfaRequiredForAll": false,
"version": 4,
"createdAt": "2026-08-01T09:00:00.000Z",
"updatedAt": "2026-09-20T11:00:00.000Z"
}

Failure responses​

StatuscodeWhenFE action
400VALIDATION_FAILEDPATCH: malformed If-MatchFix the header
401— (gateway)Missing/invalid tokenRe-authenticate
403FORBIDDENsettings below the route's floor; PATCH with mfaRequiredForAll and settings < FULLDon't retry; caller isn't allowed
404NOT_FOUNDCaller has no visibility into orgIdRe-fetch the org switcher
409VERSION_CONFLICTPATCH: details.currentVersion — someone else changed it since the ETag was readRe-GET, retry with the new If-Match
422VALIDATION_FAILEDPATCH: generic .strict() body error (unknown/server-owned field); the plain "No changes supplied" message (every field matched the current value); or details.fields — a personal org was sent a field other than nameFix the request
428PRECONDITION_REQUIREDPATCH: If-Match missingGET first, then retry
500 / 503INTERNAL / DEPENDENCY_UNAVAILABLEServer/dependency errorRetry with backoff

Edge cases​

  • A personal organisation only accepts name. Any other field in the body is refused with 422 VALIDATION_FAILED and details.fields listing the disallowed field names sent — not silently ignored, and not a different status than any other validation failure on this route.
  • contact is a shallow merge, never a deep one. Sending {"contact": {"phone": "+92-300-0000000"}} leaves every other contact sub-field untouched — but there is no way to clear just phone alone without re-sending the rest of the object; only the whole contact key can be reset to {} by a caller prepared to re-supply everything it wants kept.
  • timezone changes affect display only. No historical telemetry or log timestamp is rewritten.
  • Publishes org.upserted.v1 and writes one ORG_UPDATED access-log entry with the changed fields on every successful PATCH. Since feature 004 the event also carries currency (optional in the event schema).

Business profile, localisation and branding (feature 004, FR-048)​

Three optional nested objects extend the same PATCH body and the GET/PATCH response. There is no new route; same auth, If-Match, ETag and error table as above. Verified against packages/core/src/orgs/business-profile.ts and BusinessProfilePatch in packages/core/src/schemas.ts. Not yet executed on any stage, so the example below is illustrative.

profile: merged field by field. Sending null for a field clears it. Unknown keys get 422.

FieldTypeConstraint
legalNamestring | null1–160 chars
businessTypestring | null1–80 chars
countryCodestring | nullISO 3166-1 alpha-2
addressstring | null1–400 chars
phonestring | nullE.164, e.g. +923001234567
emailstring | nullemail, max 254
websitestring | nullURL, must start with https://, max 200
taxNumberstring | null1–40 chars

localisation: a nested way to set the existing flat settings. Each key is stored on its flat field, so there is only one stored value. The response always includes a derived localisation object.

KeyFlat fieldConstraint
timezonetimezoneIANA zone
localelocaleBCP-47
secondLocalesecondaryLocaleBCP-47; null clears
currencycurrencyISO 4217 from the runtime currency list
unitSystemunitsonly METRIC
dateFormatdateFormatDD_MM_YYYY | MM_DD_YYYY | YYYY_MM_DD | D_MMM_YYYY (e.g. 5 Mar 2026)
workingWeekworkWeek{start, end}, both MON…SUN, inclusive and may wrap (SUN→THU = 5 days)
fiscalYearStartfiscalYearStartMM-DD, a real calendar day

In the GET view, unitSystem defaults to METRIC. workingWeek is omitted when the stored workWeek days are not one contiguous run, and secondLocale is omitted when it is unset.

branding: slots PRIMARY_LOCKUP, REVERSE_LOCKUP, APP_MARK, REPORT_COVER. {"assetId": "<ULID>", "fileName": "logo.png"} (fileName 1–120 chars) sets a slot. null clears it, and a slot you leave out is not changed. This API does not upload files; assetId must refer to an asset that has already been uploaded.

Request, illustrative:

{
"profile": { "legalName": "Acme Solar (Pvt) Ltd", "taxNumber": null },
"localisation": { "currency": "PKR", "workingWeek": { "start": "MON", "end": "FRI" } },
"branding": { "APP_MARK": { "assetId": "01J9Z8Y7X6W5V4T3S2R1Q0P9N8", "fileName": "mark.png" } }
}

Response additions, illustrative:

{
"profile": { "legalName": "Acme Solar (Pvt) Ltd" },
"branding": { "APP_MARK": { "assetId": "01J9Z8Y7X6W5V4T3S2R1Q0P9N8", "fileName": "mark.png" } },
"localisation": {
"timezone": "Asia/Karachi", "locale": "en-PK", "currency": "PKR", "unitSystem": "METRIC",
"dateFormat": "DD_MM_YYYY", "workingWeek": { "start": "MON", "end": "FRI" }, "fiscalYearStart": "07-01"
}
}

Edge cases:

  • The same setting sent flat and nested (e.g. currency and localisation.currency) returns 422 VALIDATION_FAILED with details.fields: ["localisation.currency"]. Send each setting once, in either form.
  • A personal org still accepts only name, so profile/localisation/branding get 422 with details.fields.
  • If every merged value equals the current value, the request returns 422 with "No changes supplied".
  • org.upserted.v1 carries timezone and currency from the flat fields, so a nested change reaches the TCP side the same way as a flat one.

GET /v1/orgs/{orgId}/members — List an organisation's people​

Purpose: The People table — every member, filterable, searchable, sorted by name.

  • HTTP method: GET
  • Endpoint: /v1/orgs/{orgId}/members
  • Authentication: Required
  • Authorization: team ≥ VIEW
  • DynamoDB calls: one Query, on GSI3 (ORG#<o>#MEMBERS#<status>) when exactly one status value is given, else GSI2 (ORG#<o>#MEMBERS) with a post-query FilterExpression for 2–3 statuses/roleId/departmentId; a separate search path (below) when q is given. Role/department names are resolved with follow-up BatchGets.
  • Dev status: GSI3 was deployed to dev on 2026-10-13, so a single-status filter is expected to work now, not yet re-verified on dev.

Request​

Headers: Authorization: Bearer <token> only.

Path parameters

NameRequiredNotes
orgIdYesULID

Query parameters

NameRequiredTypeNotes
statusNoACTIVE | INVITED | SUSPENDED, repeatable1–3 values (status=ACTIVE&status=SUSPENDED). Default: every status (no filter sent). INVITED currently matches zero rows — see Edge cases.
roleIdNoULIDExact match.
departmentIdNoULIDExact match.
qNostring, 2–64 charsA single prefix search term (see Edge cases) — switches to a different query path, paged with nextCursor since 2026-11-25.
sortNoname onlyThe only supported value. Checked before the rest of the query is parsed, and separately from the MembersQuery Zod schema.
limitNointeger 1–50; default 15 on the first page, 10 with a cursor (lazy loading)
cursorNoopaque stringFrom a previous response's nextCursor.

This route is strict (CR-13): an unknown query parameter, or any sort value other than name, is 400 VALIDATION_FAILED — not the 422 the .strict() body-validation pipeline uses elsewhere on this API.

Request body: none.

Response​

Structure (MemberListItem[]):

{
items: Array<{
sub?: string; // Cognito sub. Always present today (see Edge cases).
inviteId?: string; // ULID. Reserved for an invitation row — never emitted yet.
displayName: string;
emailMasked: string; // full email at caller's team >= MANAGE, else "r***@domain"
role: { roleId: string; code: string; name: string };
department?: { deptId: string; name: string };
status: "ACTIVE" | "INVITED" | "SUSPENDED" | "REMOVED";
scope: { kind: "ALL"|"REGION"|"TAG"|"CUSTOMER"|"PLANTS"|"NONE"; targetCount: number; label: string };
mfa: { enabled: boolean; required: boolean }; // required = the EFFECTIVE requirement (same computation as B04's MemberDetail.mfa.required below)
lastSignInAt?: string; // never populated today
joinedAt?: string;
invitedAt?: string; // reserved, never emitted yet
expiresAt?: string; // reserved, never emitted yet
}>;
nextCursor?: string; // omitted on the last page (a `q` search pages too, since 2026-11-25)
}

emailMasked is computed server-side from the caller's own team level — never trust a client-supplied value, and never assume it reflects the target member's own permissions.

Successful response — illustrative example​

{
"items": [
{
"sub": "01J9Z4A1B2C3D4E5F6G7H8J9K0",
"displayName": "Ayesha Raza",
"emailMasked": "a***@example.com",
"role": { "roleId": "01M3W3PECHZHW97E14E6H8X3MM", "code": "R-02", "name": "Administrator" },
"department": { "deptId": "01J9Z5DEPT000000000000001", "name": "Operations" },
"status": "ACTIVE",
"scope": { "kind": "ALL", "targetCount": 0, "label": "All plants" },
"mfa": { "enabled": true, "required": true },
"joinedAt": "2026-08-12T09:00:00.000Z"
}
],
"nextCursor": "eyJvcmdJZCI6Ii4uLiJ9"
}

Failure responses​

StatuscodeWhen
400VALIDATION_FAILEDUnknown query parameter (details.unknown) or unsupported sort (details.allowed)
400INVALID_CURSORcursor is malformed, or was issued for a different route/org/filter/sort combination
401— (gateway)Missing/invalid token
403FORBIDDENteam < VIEW
404NOT_FOUNDCaller has no visibility into orgId at all
500INTERNALUnexpected error
503DEPENDENCY_UNAVAILABLEDynamoDB error/throttle

Edge cases​

  • q is a single prefix term, not per-word. normText(q) is matched against a search-token index (listMembersBySearch) — unlike GET /v1/search/suggestions's per-word typeahead. This switches the WHOLE query to a different code path: status/roleId/departmentId still apply as post-filters and sort is ignored. Since 2026-11-25 (console request M1) the search is paged: nextCursor comes back while more matches may remain, a page can be short (even empty) with a nextCursor, and a member whose name has several matching words (q=a on "Ali Ahmed") appears only once. Before that, no nextCursor was returned and results stopped at limit.
  • q matches name, role, department and email (2026-12-01, F8). Every word must prefix a word of the member's display name, role name, department name or — only for a viewer at team ≥ MANAGE, who sees full emails — email (local part and domain words: q=crown finds admin1@crowngroup.com). Matching runs on the server over the org's members (at most 500, then truncated: true), sorted by sort (default name), with an offset cursor bound to the query — no search-token index and no backfill needed.
  • Column sorts (2026-12-01, S3). sort = name (default), role, department, status or lastSignIn, each also with a leading -. Anything but name is sorted on the server over the filtered set (≤ 500); members with no value (no department, never signed in) sort last both ways.
  • Invitations never appear. Pending invitations are listed by GET …/invitations, not here. Internally an invitation is stored in the same index the People list reads (data model D-05), and the list drops every item that is not a membership before building rows (KI-24). status=INVITED is a valid filter value but always matches zero rows, and no item ever carries inviteId, invitedAt or expiresAt. Fixed 2026-11-04 (cse-http-backend#15): before that, one pending invitation made this route answer 500 INTERNAL.
  • Pages can be shorter than limit. limit caps the items DynamoDB reads, and invitation items are dropped after the read, so a page can hold fewer than limit members (even zero) while nextCursor is still present. Keep paging until nextCursor is absent.
  • A malformed membership item is skipped, not a 500. A MEMBER# item with no sub or displayName is left out of the page and logged as member_row_skipped_bad_shape with its keys only (no personal data).
  • REMOVED rows never appear regardless of the status filter — they carry no GSI2/GSI3 attributes at all, so they're invisible to both query paths.
  • Empty result: { "items": [] }, with no nextCursor.

:::note Admin-web 2026-11-24 Page 1 of the members list also carries statusCounts (ACTIVE, SUSPENDED, INVITED). Every item carries an approximate plantCount. GET /departments items already carry memberCount. See Admin-web list totals, counts and filter options. :::

Page-1 counts: statusCounts and matched (2026-11-25, deployed to dev)​

Page 1 (no cursor, on both the index and the q path) carries:

statusCounts: {
ACTIVE: number; // COUNT#members#status#ACTIVE — approximate, stream-maintained
SUSPENDED: number; // COUNT#members#status#SUSPENDED — approximate
INVITED: number; // exact: PENDING, unexpired invitations of the org (any kind)
total: number; // ACTIVE + SUSPENDED + INVITED
approximate: true;
};
matched?: number; // members the filters match — see the table
Filters on the requestmatched
noneACTIVE + SUSPENDED
status onlythe sum of the requested statuses (INVITED and REMOVED add 0)
roleId onlyCOUNT#members#roleId#<roleId> (that role's ACTIVE + SUSPENDED members)
departmentId onlyCOUNT#members#departmentId#<id>
q, or two or more of status / roleId / departmentIdabsent: no counter answers it, so the console shows no total

statusCounts is always the whole organisation's, whatever the filters.

  • INVITED is exact since 2026-11-25. It is a Select: COUNT Query on the org's own INVITE# items (PENDING and expiresAt not passed), the same rows GET …/invitations?status=PENDING lists, so a caller at team VIEW (who cannot list invitations) still gets the number. Before, it read COUNT#invitations#status#PENDING, which nothing maintains, and was always 0. It is not a stream counter on purpose: expiry is decided at read time and invitations leave through TTL deletes the stream router ignores.
  • ACTIVE/SUSPENDED, role and department counts were 0 on every deployed stack before this change (KI-57): the stream-router never loaded the members registration. Fixed on dev 2026-11-25 (deploy, then rebuild:projections --all-orgs --execute, 0 failures). If a counter is ever smaller than the rows on the page, the console treats it as unavailable and shows N/A.
  • REMOVED members never count (since 2026-11-25): a membership moved to REMOVED is taken off every member counter (status, role, department, scope kind, MFA). Before, it stayed in its role's and department's memberCount, which also blocked deleting that department.

Members of other organisations: Crown Super Admin and Administrator (console review 2026-11-25 §2–3)​

There is no cross-organisation members list. The owner's decision (2026-11-25): the console's Members tab always has one organisation selected; an "All organisations" option needs a new platform-wide member index and is not built. Everything the console needs for one chosen organisation already exists:

NeedRouteNotes
The members of organisation XGET /v1/orgs/{X}/membersSame paging, filters, statusCounts, matched
Organisation filter optionsGET /v1/orgs/{crownOrgId}/businesses?q=&status=&cursor= (Businesses, paged, q ≥ 2 chars) plus the Crown org itself from GET /v1/mePersonal and customer orgs are End Users: use Customers
Role filter options in XGET /v1/orgs/{X}/rolesBuilt-in roles plus X's custom roles
Departments in XGET /v1/orgs/{X}/departments
Member actions in XPATCH /v1/orgs/{X}/members/{sub}, POST …/members/{sub}:suspend / :restore / :remove / :end-sessions / :reset-mfaThrough the platform fallback

Who may do it. The platform fallback (access/evaluator.ts platformOrgFallback) applies when the caller holds an ACTIVE, scope-ALL membership in a non-suspended Crown (PLATFORM) org and no membership of its own in X. Super Admin and Administrator get the same reach: every Business (including a SUSPENDED or CLOSED one), customer org and personal org; never another PLATFORM org. Each caller acts at their platform role's own levels (a read-only custom platform role stays read-only), MFA-gated, and the access is recorded in X's access log. A Business, Installer or End User caller has no platform membership, so GET /v1/orgs/{X}/members for an org they don't belong to is 403 FORBIDDEN (or 404 when they have no visibility of X at all).

Refusals on that path: in a personal org reached through the fallback, an Administrator's PATCH …/members/{sub} is refused with 403 FORBIDDEN details.reason: PLATFORM_PERSONAL_ORG (no lasting access created from an MFA-exempt personal org; http/authorize.ts refuseStandingGrantViaPlatform). A Super Admin is not refused, so on this one point the two roles differ. Suspend, restore, remove, end-sessions and reset-MFA are not affected. A Business member (not Crown staff) suspending or restoring an End User gets 403 FORBIDDEN details.reason: END_USER_CROWN_ONLY; the usual member-action rules (not yourself, not the last ACTIVE Super Admin, Super Admin assignment only by a Super Admin) still apply.

Who is a member of a Business (§3).

  • An Installer accepted through a join code (POST …/join-requests/{id}:accept) is written as an ACTIVE membership of the Business on its Installer-type role in the same transaction, so it is listed by GET /v1/orgs/{businessOrgId}/members with that role's name.
  • A connected End User (plant shared to them, or joined with their own plants) is both: an ACTIVE membership of the Business (on the End User role; it is how they see the Business's plants) and a customer (REL#CUSTOMER profile on their personal org, Customers). They appear in the Members tab and in Customers.

GET /v1/orgs/{orgId}/members/summary — People summary tiles​

Purpose: The People screen's stat tiles and per-department member counts.

  • HTTP method: GET
  • Authorization: team ≥ VIEW
  • DynamoDB calls: one BatchGet of 4 facet counters (COUNT#members#status#ACTIVE/SUSPENDED, COUNT#members#scopeKind#ALL, COUNT#members#mfa#OFF), one Select: COUNT Query over the org's INVITE# items for pendingInvitations (2026-11-25), plus one bounded Query over this org's departments and a follow-up BatchGet of their own per-department member counters — never an unbounded scan over every member.

Request​

Path parameters: orgId (ULID). Query/body: none.

Response​

{
active: number;
total: number; // active + suspended (REMOVED excluded)
unrestricted: { count: number; flagged: boolean }; // flagged = count > 3
withoutTwoFactor: number;
pendingInvitations: number; // exact since 2026-11-25 — see Edge cases
byDepartment: Array<{ departmentId: string; name: string; count: number }>;
approximate: true; // counter-derived; always true
}

Successful response — illustrative example​

{
"active": 11,
"total": 12,
"unrestricted": { "count": 2, "flagged": false },
"withoutTwoFactor": 3,
"pendingInvitations": 0,
"byDepartment": [
{ "departmentId": "01J9Z5DEPT000000000000001", "name": "Operations", "count": 7 }
],
"approximate": true
}

Failure responses​

StatuscodeWhen
401— (gateway)Missing/invalid token
403FORBIDDENteam < VIEW
500 / 503INTERNAL / DEPENDENCY_UNAVAILABLEServer/dependency error

Edge cases​

  • Counts are approximate. They're read from facet counters maintained by a stream projection (projections/member-counters.ts), not computed live — they can lag the true state by seconds. approximate is always true.
  • pendingInvitations is exact (since 2026-11-25, deployed to dev). It counts the org's PENDING, unexpired invitations with one Select: COUNT Query, the same rows GET …/invitations?status=PENDING lists. Before, it read COUNT#invitations#status#PENDING, which no projection maintains, and was always 0. Pending invitations are not counted in active or total and never appear in member lists (KI-24).
  • active, total, unrestricted, withoutTwoFactor and byDepartment were always 0 on deployed stacks until the 2026-11-25 fix and rebuild on dev (KI-57).

GET /v1/orgs/{orgId}/members/{sub} — Member drawer​

Purpose: Everything the member drawer needs in one call: identity, department, role + full permission map, scope + target labels + plant previews, MFA state, and warning flags.

  • HTTP method: GET
  • Authorization: team ≥ VIEW, except a caller may always read their own row (sub equal to the caller's own) regardless of their team level — the authorization check is skipped entirely for a self-read.
  • DynamoDB calls: one strongly-consistent GetItem on the member plus the org META, then role resolution, scope-target resolution (a BatchGet of up to 10 plant META items for a PLANTS scope) and department-name resolution as needed.

Request​

Path parameters

NameRequiredNotes
orgIdYesULID
subYesCognito sub of the member

Query/body: none.

Response​

{
sub: string;
displayName: string;
emailNorm: string; // full, unmasked email — this is the single-member admin drawer
department?: { deptId: string; name: string };
status: "ACTIVE" | "SUSPENDED" | "REMOVED";
suspendNote?: string;
role: { roleId: string; name: string; perms: RolePerms; scopeRule: "ALL" | "SCOPED" };
scope: {
kind: "ALL"|"REGION"|"TAG"|"CUSTOMER"|"PLANTS"|"NONE";
targets: Array<{ id: string; label: string; removed?: boolean }>; // "removed" reserved, never populated
plantCountApprox: number;
plantsPreview: Array<{ plantId: string; name: string }>; // <= 10
};
mfa: {
enabled: boolean;
required: boolean; // the EFFECTIVE requirement (explicit flag, PLATFORM org, or any role level FULL)
requiredReason?: "EXPLICIT" | "PLATFORM" | "ROLE_FULL"; // omitted when MFA isn't required (incl. every member of a personal org)
};
lastSignInAt?: string; // never populated today
joinedAt?: string;
invitedAt?: string; // reserved, never populated
warnings: Array<"NO_MFA_WITH_COMMANDS" | "UNRESTRICTED_SCOPE">;
version: number; // also carried as the ETag response header, quoted: "3"
}

Response headers: ETag: "<version>" — use it as the If-Match of a following PATCH or lifecycle action (packages/api/src/handlers/members.ts). Header deployed to dev 2026-10-13; not yet re-verified with a signed-in call.

RolePerms is the 15-category level map (10-key maps are still accepted; the five ADR 0014 keys are derived — see Roles & permissions) (see Architecture → Authorization model).

Successful response — illustrative example​

{
"sub": "01J9Z4A1B2C3D4E5F6G7H8J9K0",
"displayName": "Ayesha Raza",
"emailNorm": "ayesha.raza@example.com",
"status": "ACTIVE",
"role": {
"roleId": "01M3W3PECHZHW97E14E6H8X3MM",
"name": "Administrator",
"scopeRule": "ALL",
"perms": {
"plants": "FULL", "devices": "FULL", "alerts": "FULL", "commands": "MANAGE",
"firmware": "VIEW", "service": "FULL", "reports": "FULL", "customers": "FULL",
"team": "MANAGE", "settings": "EDIT"
}
},
"scope": { "kind": "ALL", "targets": [], "plantCountApprox": 0, "plantsPreview": [] },
"mfa": { "enabled": true, "required": true, "requiredReason": "ROLE_FULL" },
"joinedAt": "2026-08-12T09:00:00.000Z",
"warnings": [],
"version": 4
}

Failure responses​

StatuscodeWhen
401— (gateway)Missing/invalid token
403FORBIDDENteam < VIEW AND sub is not the caller's own
404NOT_FOUNDsub is not a member of this org, or their membership is REMOVED
500 / 503INTERNAL / DEPENDENCY_UNAVAILABLEServer/dependency error

Edge cases​

  • Self-read bypasses the team gate entirely — a Technician or Sales role (team: NONE) can still open their own drawer.
  • lastSignInAt/invitedAt are always absent — no sign-in tracking and no invitation entity exist yet in this feature.
  • requiredReason is omitted whenever MFA isn't required at all, including every member of a personal organisation (always exempt, regardless of role or explicit flag).

PATCH /v1/orgs/{orgId}/members/{sub} — Change role, scope, department or MFA requirement​

Purpose: The only write operation on this page. Changes one or more of a member's role, scope, department, or explicit MFA requirement, in one optimistically-locked call.

  • HTTP method: PATCH
  • Authorization: team ≥ MANAGE, plus the escalation and Super-Admin rules below. Installer path (2026-11-26, owner): an Installer of this Business (no team level) may call it too, but only to change the plants of an End User member: the body may carry scope only, scope.kind must be PLANTS with at least one target, and every target must be a plant of this Business (the Installer reaches all of them, whoever added the plant). Adding and removing plants both work; the End User keeps at least one. Every other change (role, department, MFA, remote control, any non-End-User member) stays with team ≥ MANAGE.
  • Concurrency: versioned — If-Match is required, and the response carries ETag. This is the first versioned route in this API.
  • DynamoDB calls: a GetItem on the member + org META, role resolution for both the current and (if changing) new role, an optional BatchGet to validate PLANTS scope targets, then one TransactWriteCommand (conditional member update on version, an optional Super-Admin-counter ADD, one access-log PutItem, and — only when access narrows — one outbox PutItem for access.revoked.v1).

Request​

Headers

HeaderRequiredNotes
AuthorizationYesBearer <token>
If-MatchYesA strong ("3") or weak (W/"3") ETag from a prior GET/PATCH on this same member. Missing → 428. Present but malformed (*, unquoted, comma-separated) → 400, not 422.
Content-TypeYesapplication/json

Path parameters: orgId, sub (as above).

Request body — at least one field required:

FieldTypeNotes
roleIdULIDNew role. Subject to the escalation/Super-Admin rules below.
scope{ kind, targets[] }A full Scope object — see Types & schemas for the per-kind target caps (≤10 for REGION/TAG/CUSTOMER, ≤500 for PLANTS). For a member on an Installer-type role (a custom SCOPED role in a Business org), a role or scope change stores NONE whatever is sent (Role boundaries, 2026-11-12).
departmentIdULID | nullnull clears the department.
mfaRequiredbooleanThe membership's own explicit flag.

Strict (.strict() Zod): an unknown field is 422.

Response​

Structure: the same shape as GET /v1/orgs/{orgId}/members/{sub} above, plus impact:

{
...MemberDetail, // see GET .../members/{sub} above
impact: { plantsRemovedApprox?: number }; // always {} today — never populated, see Edge cases
}

Response headers: ETag: "<new version>".

Failure responses​

StatuscodeWhenFE action
400VALIDATION_FAILEDMalformed If-Match valueFix the header; this is a client bug, not retryable as-is
401— (gateway)Missing/invalid tokenRe-authenticate
403FORBIDDENteam < MANAGE; OR details.reason: "ESCALATION" — the granted role holds a category level above the caller's own (FR-031), or the caller tried to assign/remove Super Admin without being one themselves (FR-030)Don't retry; the caller isn't allowed to make this change
403FORBIDDENdetails.reason: "ROLE_NOT_ASSIGNABLE" — a role change to a role this kind of org may not grant (Role boundaries, 2026-11-12). A patch that keeps the current role is not checkedOffer only the roles GET …/roles lists; a Business user cannot change a member to End User (Super Admin can)
403FORBIDDENInstaller path only: details.reason: "INSTALLER_END_USER_ONLY" (the member is not an End User), "INSTALLER_SCOPE_ONLY" (the body carries a field other than scope; details.fields lists them) or "INSTALLER_SCOPE" (a target the Installer does not cover; details.invalidTargets)Don't retry; ask a Business member
403FORBIDDENdetails.reason: "PLATFORM_PERSONAL_ORG" — a personal account opened only through the platform fallback; platform staff cannot create lasting access there (revalidation 2026-11-03)Don't retry; the action is not available to platform staff here
404NOT_FOUNDsub is not a member of this org, or is REMOVEDRe-fetch the people list
409VERSION_CONFLICTdetails.currentVersion — someone else changed this member since the ETag was readRe-GET, re-apply the change, retry with the new If-Match
409INVALID_STATEdetails.reason: "LAST_SUPER_ADMIN" — this change would demote/remove the organisation's only ACTIVE Super AdminDon't retry; promote another Super Admin first
422VALIDATION_FAILEDSee the reason list belowDepends on reason — see below
422LIMIT_EXCEEDEDdetails.field: "scope.targets" — the scope's targets exceed its per-kind cap (≤10 REGION/TAG/CUSTOMER, ≤500 PLANTS)Don't retry unmodified; trim the target list
428PRECONDITION_REQUIREDIf-Match header missingGET the member first for its current ETag, then retry
500 / 503INTERNAL / DEPENDENCY_UNAVAILABLEServer/dependency errorRetry with backoff

The 422 reasons, each details.reason unless noted:

  • INSTALLER_SCOPE_PLANTS_ONLY — Installer path: scope is missing, not PLANTS, or has no targets.
  • SCOPE_RULE_FORCES_ALL — the (new or current) role's scopeRule is ALL, but an explicit scope with a kind other than ALL was sent.
  • KIND_NOT_ALLOWED_FOR_ORG — the scope kind isn't one this organisation's kind may use (FR-022 — e.g. a CUSTOMER-kind org may only use ALL/PLANTS/NONE).
  • details.invalidTargets (no reason key on this one — just the offending id list) — one or more PLANTS targets aren't operated by this org.
  • MFA_POLICY_FLOOR — no longer returned since 2026-11-11: the policy floor is always false, so lowering mfaRequired is never refused. Earlier: mfaRequired: false was sent, but the role/org policy floor requires it (FR-036); once the floor applies it can be raised freely but never lowered below it this way. A change that does not send mfaRequired (for example a role change into Super Admin, or any role change in the PLATFORM org) is never refused for this reason: the effective requirement simply rises with the new role (fixed 2026-11-02; before that, such a role change was wrongly refused).
  • No details.reason at all, just the plain message "No changes supplied" — none of the four fields were sent (or all matched the current values).
  • The generic .strict() Zod body-validation failure (unknown field, bad ULID) — details is Zod's flattened { formErrors, fieldErrors }, no reason key.

One 422 case uses a different error.code entirely: scope.targets over its per-kind cap (≤10 REGION/TAG/CUSTOMER, ≤500 PLANTS) is error.code: "LIMIT_EXCEEDED" with details.field: "scope.targets" — remapped from the generic Zod error specifically for this one failure mode. Don't rely on HTTP status alone to tell these apart from the VALIDATION_FAILED cases above.

Edge cases​

  • Escalation (FR-031) is fully enforced: a non-Super-Admin caller can never grant a roleId whose permission map holds ANY category level above their own current level — not just a Super Admin/non-Super-Admin transition. An ACTIVE Super Admin is exempt from this check (they're FULL everywhere, so it can never apply).
  • FR-030's narrower rule is a separate, additional check: assigning or removing the Super Admin role specifically always requires the caller to be an ACTIVE Super Admin, even though that transition would also fail the general FR-031 check for anyone else anyway. Both report the same 403 details.reason: "ESCALATION".
  • Last Super Admin: the organisation's Super Admin count is maintained transactionally — a promotion here and accepting a Super Admin invitation both add to it; demoting the only remaining one is refused with 409 INVALID_STATE (details.reason: "LAST_SUPER_ADMIN"), not silently allowed and not a 422.
  • Widening vs narrowing: widening a scope or raising a role takes effect on the member's next request. Narrowing access (a role whose levels drop in plants/devices/alerts/commands, or a scope that covers fewer plants) additionally publishes one access.revoked.v1 event in the same transaction, so the affected person's live session loses access promptly rather than only on their next full re-authorization.
  • impact.plantsRemovedApprox is always absent. The response always returns impact: {} — this count is never computed yet, even on a genuine narrowing (KI-25).

POST /v1/orgs/{orgId}/members/{sub}:suspend|:restore|:end-sessions|:reset-mfa|:remove — Member lifecycle actions​

Purpose: The five member-lifecycle actions off the drawer's "⋯" menu — suspend, restore, end all sessions in this org, reset two-factor, and permanently remove.

  • HTTP method: POST
  • Endpoint: one wire route, POST /v1/orgs/{orgId}/members/{sub} — API Gateway can't register a {sub}:verb path template (CR-2), so the colon verb travels as part of the sub path value (<sub>:suspend, <sub>:restore, <sub>:end-sessions, <sub>:reset-mfa, <sub>:remove) and the handler itself (packages/api/src/handlers/members.ts memberAction) splits it with parseActionSegment — not the generic family router used elsewhere on this page, because this path has two path parameters (orgId and sub), which that generic splitter can't disambiguate. An unrecognised verb, or a sub segment with no verb at all, is 404 NOT_FOUND.
  • Authentication: Required
  • Authorization: team ≥ MANAGE for every action, plus two target-identity guards that apply regardless of team level (see Edge cases): acting on a Super Admin requires the caller to be one themselves, and :suspend/:remove refuse the caller acting on their own account.
  • Concurrency: versioned, same as PATCH above — If-Match is required on all five actions (including :reset-mfa, even though it only touches the profile/MFA mirror, not the role/scope fields), and the response carries ETag.
  • Idempotency: the contract names Idempotency-Key as accepted, but this route does not process it at all (idempotency: 'none' in lib/routes.ts, the same simplification already made for POST …/invitations/{inviteId}:resend) — a retried POST with the same key is not deduplicated. Rely on If-Match/the resulting version to avoid double-applying an action, not on this header.
  • DynamoDB calls: a strongly-consistent GetItem on the member + org META, then one TransactWriteCommand per action (conditional member update on status + version, an optional Super-Admin-counter ADD, one EMAIL# guard delete on :remove only, one access-log PutItem, and — every action except :restore, which only widens access — one outbox PutItem for access.revoked.v1). :reset-mfa calls IdentityProvider.resetMfa (Cognito AdminSetUserMFAPreference) before its transaction, per data-model.md's own ordering note (Cognito has no transactional join with DynamoDB). None of the five ever calls Cognito's AdminDisableUser or GlobalSignOut — see Edge cases on session revocation below.
  • :remove in a Business returns the user to their personal account (owner, 2026-11-17 — one account per user). After the membership is removed, every plant whose customer they are (brought in, or transferred to them by the Business — ADR 0036, 2026-11-27) moves to their personal org, and the personal org is reopened as their default org. Removing an Installer makes the Business owner the assigned Installer of their plants and the assignee of their open work orders; their End Users stay. Removing the Business owner, an Administrator or a Super Admin who owns plants no End User has is 409 CONFLICT OWNS_UNSHARED_PLANTS (delete or transfer them first). See Account suspension and removal. This holds for every role (End User, Business, Installer) and also when no plant moves. A plant move still running for that user is finished first (409 CONFLICT details.reason: "MOVE_IN_PROGRESS" if it cannot). Outside a Business, :remove only removes the membership. See RBAC v2 · One account per user.

Request​

Headers

HeaderRequiredNotes
AuthorizationYesBearer <token>
If-MatchYesSame rules as PATCH above — missing → 428, malformed → 400.
Content-TypeOnly for :suspend with a bodyapplication/json

Path parameters: orgId, sub (as above — sub carries the colon verb as described).

Request body — one shared, .strict() shape for all five actions (MemberActionInput); an empty object {} is valid everywhere:

FieldTypeUsed by
notestring, ≤500 chars, optional:suspend only — shown on the member drawer as the suspension reason. Accepted (and ignored) on the other four actions.

Response​

Structure: the same MemberDetail shape as GET/PATCH .../members/{sub} above. :suspend's response additionally carries assignedWorkOrdersRemain:

{
...MemberDetail, // see GET .../members/{sub} above
assignedWorkOrdersRemain?: boolean; // `:suspend` response only; always `false` today — see Edge cases
}

Response headers: ETag: "<new version>".

Successful response — illustrative example (:suspend)​

{
"sub": "01J9Z4A1B2C3D4E5F6G7H8J9K0",
"displayName": "Ayesha Raza",
"emailNorm": "ayesha.raza@example.com",
"status": "SUSPENDED",
"suspendNote": "Investigating a safety incident",
"role": { "roleId": "01M3W3PECHZHW97E14E6H8X3MM", "name": "Administrator", "scopeRule": "ALL", "perms": { "...": "..." } },
"scope": { "kind": "ALL", "targets": [], "plantCountApprox": 0, "plantsPreview": [] },
"mfa": { "enabled": true, "required": true, "requiredReason": "ROLE_FULL" },
"joinedAt": "2026-08-12T09:00:00.000Z",
"warnings": [],
"version": 5,
"assignedWorkOrdersRemain": false
}

Failure responses​

StatuscodeWhenFE action
400VALIDATION_FAILEDMalformed If-Match valueFix the header
401— (gateway)Missing/invalid tokenRe-authenticate
403FORBIDDENteam < MANAGE; OR details.reason: "SUPER_ADMIN_TARGET" — the target holds the Super Admin role and the caller doesn't (applies to all five actions); OR details.reason: "SELF" — :suspend/:remove targeting the caller's own account; OR details.reason: "END_USER_CROWN_ONLY" — :suspend/:restore on an End User by a caller who is not a Super Admin or Administrator (owner decision 2026-11-25: a Business never activates or deactivates an End User; it manages plants only); OR (:reset-mfa only) details.reason: "ACCOUNT_WIDE_EFFECT" — see Edge casesDon't retry; the caller isn't allowed to make this change
404NOT_FOUNDsub is not a member of this org (or already REMOVED); or the colon-verb segment isn't one of the five recognised actionsRe-fetch the people list
409VERSION_CONFLICTdetails.currentVersion — someone else changed this member since the ETag was readRe-GET, retry with the new If-Match
409INVALID_STATEThe action's precondition on current status isn't met (see the table in Edge cases) — e.g. :suspend/:end-sessions on a non-ACTIVE member, :restore on a non-SUSPENDED one, or demoting/removing the organisation's only ACTIVE Super Admin via :suspend/:remove. No details.reason key on any of these (unlike PATCH's LAST_SUPER_ADMIN reason)Re-GET to see the current status before retrying
422VALIDATION_FAILEDGeneric .strict() body error (unknown field on the :suspend body)Fix the request
428PRECONDITION_REQUIREDIf-Match missingGET the member first, then retry
500 / 503INTERNAL / DEPENDENCY_UNAVAILABLEServer/dependency errorRetry with backoff

Edge cases​

  • Preconditions and effects, per action:

    ActionPreconditionEffect
    :suspendstatus ACTIVE; not the caller; not the last ACTIVE Super Adminstatus → SUSPENDED; this org's membership tokensValidAfter set to now; access.revoked.v1 published
    :restorestatus SUSPENDEDstatus → ACTIVE; no access.revoked.v1 (restoring widens access)
    :end-sessionsstatus ACTIVEthis org's membership tokensValidAfter set to now; status unchanged; access.revoked.v1 published
    :reset-mfacaller holds an ACTIVE PLATFORM membership with team ≥ MANAGE, or the target has no other ACTIVE non-personal membership anywhereCognito TOTP cleared; the stored profile.mfa mirror (and this membership's own mfaEnabled mirror) set to false; access.revoked.v1 published
    :removenot the caller; not the last ACTIVE Super Adminstatus → REMOVED; member drops out of the People list (GSI2/GSI3 attributes removed); the EMAIL# guard is freed, so the same address can be re-invited; tokensValidAfter set to now; access.revoked.v1 published
  • Session revocation is org-scoped, not account-wide. :suspend and :end-sessions (and :remove) only bump this org's membership tokensValidAfter watermark — never Cognito's GlobalSignOut, and never the account-wide profile.tokensValidAfter. The practical effect: any token the affected person is already holding gets 401 SESSION_REVOKED on their very next request in this org (auth_time on the token is now older than the new watermark), but the same token keeps working unaffected in every other org they belong to. The FE must treat 401 SESSION_REVOKED as "re-authenticate" for that org's session — there is no partial-refresh path; the client needs a fresh sign-in (a new auth_time) before it can call that org's routes again. This is the same check GET /v1/me/context and every other org-scoped route already applies (see Architecture → Authorization model); B06 doesn't add a new mechanism, it's just the first page with UI actions that deliberately trigger it.

  • :reset-mfa's "account-wide effect" guard (FR-035). Two-factor is a per-Cognito-account setting, not a per-org one — clearing it affects every org the person belongs to, not just this one. This route refuses the reset (403 details.reason: "ACCOUNT_WIDE_EFFECT") unless either (a) the target has no OTHER active, non-personal membership anywhere (so this really is the only org affected), or (b) the caller themselves holds an ACTIVE PLATFORM-org membership with team ≥ MANAGE (platform staff are trusted with the account-wide consequence). There is no way to force a reset from a non-platform caller when the target belongs to multiple orgs — direct them to platform support instead.

  • Acting on a Super Admin. Regardless of which of the five actions, a caller who is not themselves an ACTIVE Super Admin in this org gets 403 details.reason: "SUPER_ADMIN_TARGET" when the target holds the Super Admin role — distinct from PATCH's "ESCALATION" reason (that one is about the role being granted; this one is about the role the target already has).

  • Last Super Admin. :suspend and :remove both refuse to act on the organisation's only remaining ACTIVE Super Admin (409 INVALID_STATE, no details.reason — unlike PATCH's "LAST_SUPER_ADMIN" reason on the same underlying guard). :restore and :end-sessions have no such restriction.

  • assignedWorkOrdersRemain is always false today (KI-25). It's meant to warn the admin that a suspended technician still has open work orders assigned — sourced from a facet counter feature 006 (work orders, not yet built) would maintain. The field is present and typed correctly, but nothing populates it above false yet.

  • Never a Cognito account-level action. None of the five calls AdminDisableUser (would lock the person out of every org and the mobile app entirely) or GlobalSignOut (would revoke every refresh token account-wide) — this is a deliberate design boundary: org membership actions never reach outside that org's blast radius, except :reset-mfa, whose account-wide nature is gated by the guard above rather than avoided.


POST /v1/orgs/{orgId}/members:bulk-assign-scope — Bulk-assign one scope to up to 50 members​

Purpose: Apply the same scope (e.g. "these 12 technicians now cover tag north") to many members in one call, from a multi-select on the People screen.

  • HTTP method: POST
  • Endpoint: POST /v1/orgs/{orgId}/members:bulk-assign-scope. API Gateway matches it to the catch-all POST /v1/orgs/{orgId}/{collection} route (OrgCollectionAction), whose handler dispatches it here (audit C1, live from the next deploy). The plain POST /v1/orgs/{orgId}/members (BulkAssignScope) serves the same operation and stays as a backward-compatible alias.
  • Headers: Idempotency-Key required.
  • Authentication: Required
  • Authorization: team ≥ MANAGE
  • Idempotency: Idempotency-Key required — missing → 428.
  • DynamoDB calls: one GetItem on the org META; if the scope is PLANTS, one BatchGet to validate every target plant belongs to this org; then, in parallel, one GetItem + (on an actual change) one TransactWriteCommand per member in subs — this is subs.length independent writes, not one shared transaction, so one member's failure never blocks another's.

Request​

Headers

HeaderRequiredNotes
AuthorizationYesBearer <token>
Idempotency-KeyYes428 PRECONDITION_REQUIRED details.header: "Idempotency-Key" if missing
Content-TypeYesapplication/json

Request body

FieldTypeNotes
subsarray of string, 1–50, uniqueCognito subs. A duplicate is a whole-request 422 VALIDATION_FAILED (the .strict() refine) — not a per-item error. Over 50 is 422 LIMIT_EXCEEDED.
scope{kind, targets[]}One Scope object, applied to every member in subs. Same shape as PATCH .../members/{sub}'s scope field. A member on an Installer-type role gets NONE instead (2026-11-12).

Response​

Always 200 once the body itself validates — per-member outcomes are reported individually, never as a whole-request failure:

{
results: Array<
| { sub: string; ok: true; version: number }
| { sub: string; ok: false; error: { code: string; message: string } }
>;
}

Successful response — illustrative example (mixed outcome)​

{
"results": [
{ "sub": "01J9Z4A1B2C3D4E5F6G7H8J9K0", "ok": true, "version": 3 },
{ "sub": "01J9Z4ZZZZZZZZZZZZZZZZZZZZ", "ok": false, "error": { "code": "NOT_FOUND", "message": "Member not found" } }
]
}

Per-item error.code values (results[].error.code):

CodeWhen
NOT_FOUNDsub is not a member of this org, or is REMOVED
FORBIDDENThe target holds the Super Admin role — bulk-assign refuses to touch a Super Admin's scope at all
VALIDATION_FAILEDThe target's role has scopeRule: "ALL" and the requested scope isn't ALL; or the requested scope shape isn't valid for this org kind; or (for a PLANTS scope) one of the target's plant ids isn't operated by this org

No VERSION_CONFLICT per item, ever — contract's own wording: this route applies "unconditionally on current version per item". There is no If-Match on this route at all; a member changed concurrently by someone else is simply overwritten.

Whole-request failure responses​

StatuscodeWhenFE action
401— (gateway)Missing/invalid tokenRe-authenticate
403FORBIDDENteam < MANAGEDon't retry
422VALIDATION_FAILEDGeneric .strict() body error, including a duplicate sub in subsFix the request
422LIMIT_EXCEEDEDMore than 50 subsSplit into smaller batches
428PRECONDITION_REQUIREDIdempotency-Key missingGenerate a key, retry
500 / 503INTERNAL / DEPENDENCY_UNAVAILABLEServer/dependency errorRetry with backoff

Edge cases​

  • A no-op member is still ok: true. If a member's current scope already equals the requested one, the route reports success with that member's unchanged version — it does not write anything, and does not report it any differently from a real change.
  • A member already on the exact requested scope needs no retry. Combined with the point above: a partial failure (some ok:false) can be retried with the SAME full subs list — the ones that already succeeded report ok:true again harmlessly.
  • Audit: one MEMBER_SCOPE_CHANGED access-log entry per member that actually changed (not per no-op, not per failure). Events: an access.revoked.v1 is published per member whose scope change narrows their effective coverage — same isScopeNarrower rule PATCH .../members/{sub} (B05) uses.
  • Known gap vs the contract (KI-27): Idempotency-Key replay (same key, same body returning the stored response) is not implemented — a retried POST with the same key re-executes rather than replaying. Same documented simplification as POST /v1/orgs/{orgId}/invitations's own gap. Don't rely on replay semantics; rely on the per-member idempotent no-op behaviour described above instead.

GET /v1/orgs/{orgId}/roles — Roles screen​

Purpose: The whole Roles & Permissions screen in one call: the 15 categories, the 5 levels, and every role (the built-in roles first, then this org's custom roles by code; the retired Viewer is not listed) with its full permission map and member count. Since 2026-11-12 a Business org does not list Super Admin or Administrator (Role boundaries).

  • HTTP method: GET
  • Authorization: roles ≥ VIEW (ADR 0014; was team ≥ VIEW)
  • DynamoDB calls: one Query for this org's custom role items, plus one GetItem-per-role member-count facet counter (system roles included — they're code constants, never stored, but still have a stored counter).

Request​

Path parameters: orgId (ULID). Query/body: none — this route takes no query parameters at all.

Response​

{
categories: Array<{ category: string; note?: string }>; // the 15 fixed categories, in order (ADR 0014 added registersRead, registersWrite, sharing, roles, audit)
levels: Array<{ level: string; note?: string }>; // NONE, VIEW, EDIT, MANAGE, FULL, in order
roles: Array<{
roleId: string; code: string; name: string;
system: boolean; // true for the 4 built-in roles; perms are effective (Super-Admin-edited) values
version?: number; // custom roles; built-in roles only in the PLATFORM org (If-Match for the phase-2b edit)
memberCount: number;
approximate: true; // memberCount is a facet counter; always true
scopeRule: "ALL" | "SCOPED";
perms: RolePerms;
auditTrail: boolean;
summary?: string;
note?: string;
version?: number; // custom roles only — a system role has no stored version, so this is omitted for it
}>;
}

Failure responses​

StatuscodeWhen
401— (gateway)Missing/invalid token
403FORBIDDENteam < VIEW
500 / 503INTERNAL / DEPENDENCY_UNAVAILABLEServer/dependency error

GET /v1/orgs/{orgId}/roles/{roleId} — One role's detail​

Purpose: A single role's full detail plus its pending-invitation count.

  • HTTP method: GET
  • Authorization: roles ≥ VIEW (ADR 0014; was team ≥ VIEW)
  • Path parameters: orgId, roleId — either a custom role's ULID or one of the 3 fixed system-role ULIDs (access/system-roles.ts).

Response​

Same shape as one roles[] entry above, plus pendingInvitations:

{ ...RoleSummary, pendingInvitations: number } // pendingInvitations is always 0 today

Failure responses​

StatuscodeWhen
401— (gateway)Missing/invalid token
403FORBIDDENteam < VIEW
404NOT_FOUNDroleId isn't a system role and isn't a custom role of this org
500 / 503INTERNAL / DEPENDENCY_UNAVAILABLEServer/dependency error

Edge cases​

  • pendingInvitations is a live count. It counts this org's PENDING, unexpired invitations for the role with a bounded Query of the org's invitations (up to 10 pages; no counter item involved). Invitations are built — see Invitations API.

POST /v1/orgs/{orgId}/roles — Create a custom role​

Purpose: Add a new custom role to the Roles & Permissions screen, usually as a starting-point copy of an existing one.

  • HTTP method: POST
  • Authentication: Required
  • Authorization: roles ≥ MANAGE (ADR 0014; was team = FULL). Super Admin and Business by default; a 10-key role stored earlier gets roles = FULL only from team = FULL, so older custom roles keep exactly their old access.
  • Idempotency: Idempotency-Key required.
  • DynamoDB calls: resolves the source role (system constant or one GetItem), then one TransactWriteCommand (the new ROLE item, a ROLENAME# uniqueness guard, one access-log PutItem).

Request​

Headers: Idempotency-Key required, Content-Type: application/json.

Request body

FieldRequiredTypeNotes
nameYesstring, 1–60 chars
copyFromRoleIdYes (since 2026-11-03)ULIDA system-role id (Super Admin/Administrator/Business) or a custom role's own id in this org, e.g. the org's Installer role to make "Installer – senior". The retired Viewer is refused.
summaryNostring, ≤200 chars
noteNostring, ≤500 chars

Known gap vs the design: the new role's perms/scopeRule/auditTrail are always an exact copy of the source role — this body has no way to set them directly at create time (no perms/scopeRule/auditTrail fields exist on the real, landed request schema, unlike an earlier draft of this contract). Use PATCH on the newly-created role to adjust its permission map afterward.

Response​

201 — same shape as one roles[] entry from the Roles screen (RoleSummary, see GET /v1/orgs/{orgId}/roles above), system: false, version: 1.

Failure responses​

StatuscodeWhenFE action
401— (gateway)Missing/invalid tokenRe-authenticate
403FORBIDDENroles < MANAGE; or details.reason: "ESCALATION" — copying a role whose perms exceed the caller's own current level (even though no perms field was sent directly — the COPY SOURCE's perms are what's checked; never for a Super Admin)Don't retry
404NOT_FOUNDcopyFromRoleId is not a built-in role or a custom role of this orgPick another source
409ALREADY_EXISTSA role with this name (case/whitespace-normalised) already exists in this orgChoose a different name
422VALIDATION_FAILEDGeneric .strict() body error (copyFromRoleId missing included); details.reason: "ROLE_RETIRED" (field: copyFromRoleId) — the retired Viewer; or details.field: "perms" — FULL on every category, for anyone but a Super AdminFix the request
428PRECONDITION_REQUIREDIdempotency-Key missingGenerate a key, retry
500 / 503INTERNAL / DEPENDENCY_UNAVAILABLEServer/dependency errorRetry with backoff

Audit: ROLE_CREATED.


PATCH/DELETE /v1/orgs/{orgId}/roles/{roleId} — Change or remove a custom role​

Built-in roles (ADR 0014 phase 2b). A Super Admin, in the PLATFORM org, may PATCH only the perms of Administrator or Business, to any level (Viewer is retired); If-Match = the role's version (1 until first edited). The change applies in every organisation; sending the default perms resets it. The response's affectedMembers counts PLATFORM holders only. No revocation event is sent; other users see the change within ~30 s over HTTP and on their next realtime ticket (≤ 600 s). See Roles & permissions.

  • HTTP methods: PATCH, DELETE
  • Authentication: Required
  • Authorization: roles ≥ MANAGE for both (ADR 0014; was team = FULL)
  • Concurrency: both versioned — If-Match required, response carries ETag.
  • DynamoDB calls: a consistent GetItem on the role, then one TransactWriteCommand (conditional role update/delete on version, a ROLENAME# guard swap on a name change, one access-log PutItem). PATCH additionally reads the role's own (approximate) member-count facet counter for affectedMembers; DELETE reads it AND the pending- invitation count to decide whether the delete is allowed at all.

PATCH request​

Path parameters: orgId, roleId (a custom role's ULID — a system role id here is refused, see Failure responses).

Body — at least one field required:

FieldTypeNotes
namestring, 1–60 chars
summarystring, ≤200, or nullnull clears it
notestring, ≤500, or nullnull clears it
permsfull RolePerms map (all 15 categories; a map with only the original 10 is accepted and the other five are derived — see Roles & permissions)A FULL replacement, not a per-category patch. Granting any category above the caller's own current level is 403 (escalation).
scopeRuleALL | SCOPEDSee Edge cases below
auditTrailboolean

PATCH response​

200 — RoleSummary (see GET /v1/orgs/{orgId}/roles) plus affectedMembers (the role's own approximate member count — the same number as memberCount elsewhere, under a different key for this response).

{ ...RoleSummary, affectedMembers: number }

DELETE response​

204 No Content.

Failure responses (both PATCH and DELETE)​

StatuscodeWhenFE action
401— (gateway)Missing/invalid tokenRe-authenticate
403FORBIDDENroles < MANAGE; PATCH only: details.reason: "ESCALATION" (granted perms exceed the caller's own level), or "SUPER_ADMIN_ONLY" (built-in role in the PLATFORM org, caller not Super Admin)Don't retry
404NOT_FOUNDroleId doesn't exist in this org (a SYSTEM role id, see below, is 422 instead — never 404)Re-fetch the roles list
409VERSION_CONFLICTdetails.currentVersionRe-GET, retry with the new If-Match
409INVALID_STATEDELETE only — details.memberCount and details.pendingInvitations (both always present, 0 when not the blocking one) — the role still has a member or pending invitation on itReassign those members/invitations first
422UNSUPPORTED_OPERATIONdetails.reason: "SYSTEM_ROLE" — roleId is a built-in role and this is a DELETE, a PATCH outside the PLATFORM org, a PATCH with any field but perms, or a PATCH of Super AdminDon't retry
422VALIDATION_FAILEDPATCH: generic .strict() body error, or the plain "No changes supplied" message; details.field: "perms" — custom role with FULL on every category; details.field: "perms.roles" — built-in role edit with roles: FULL (Super Admin assignment capability). Built-in Administrator edits apply only to PLATFORM-org AdministratorsFix the request
428PRECONDITION_REQUIREDIf-Match missingGET the role first, then retry
500 / 503INTERNAL / DEPENDENCY_UNAVAILABLEServer/dependency errorRetry with backoff

Edge cases​

  • scopeRule transitions are asymmetric, and SCOPED → ALL is asynchronous. SCOPED → ALL widens every current ACTIVE holder's scope to ALL — but not inline with the PATCH response: the same stream projector that handles perms-lowering revocation (projections/access-revocation.ts's planScopeWidening/ applyScopeWidening) pages holders (≤ 100 per TransactWriteCommand- equivalent batch) and sets their stored scope to ALL a short time after the role change commits — eventually consistent, typically within seconds, not instant. No access.revoked.v1 is published for this (it's a widening, never a revocation). A single PATCH that BOTH lowers a perms category AND flips scopeRule to ALL triggers both fan- outs independently (separate dedup markers, so neither suppresses the other). ALL → SCOPED is NOT fanned out at all — each holder keeps scope ALL until an admin edits their scope individually via PATCH .../members/{sub} or bulk-assign-scope.
  • Lowering a permission level doesn't revoke synchronously. When perms drops a level in alerts/devices/commands/plants, the PATCH transaction only updates the ROLE item itself — a background projector (projections/access-revocation.ts) then pages every ACTIVE member holding this role and publishes one access.revoked.v1 event per member (reason ROLE_CHANGED), in batches of up to 100. This happens asynchronously, not inline with the PATCH response — a client polling for the effect should expect a short delay, not instant propagation.
  • System roles are a hard wall. Any attempt to PATCH or DELETE Super Admin or Viewer (and any built-in role outside the Phase 2b rule above) is 422 UNSUPPORTED_OPERATION, checked before even reading the role — distinguish this from 404 (role doesn't exist at all) in the UI.
  • affectedMembers is approximate, same facet-counter caveat as memberCount on the Roles screen (COUNT#members#roleId#<id>, eventually consistent).

Audit: ROLE_UPDATED / ROLE_DELETED.


GET /v1/orgs/{orgId}/scopes/summary — Who is authorized where​

Purpose: "Who is authorized where" — a member count per scope kind, plus a paged list of every member with their scope.

  • HTTP method: GET
  • Authorization: team ≥ VIEW
  • DynamoDB calls: one BatchGet of 6 facet counters (one per scope kind) for byScopeKind — O(1) regardless of org size — plus a separate, already-bounded (Limit) Query for the items page.

Request​

Query parameters

NameRequiredTypeNotes
scopeKindNoALL|REGION|TAG|CUSTOMER|PLANTS|NONEFilters items only — byScopeKind always covers every kind regardless of this filter.
limitNointeger 1–50, default 25
cursorNoopaque string

Strict: an unknown query parameter is 400 VALIDATION_FAILED.

Response​

{
byScopeKind: Array<{ kind: string; count: number }>; // zero-count kinds omitted; every page, not just the first
items: Array<{
sub: string; displayName: string;
roleId: string; roleName: string;
scopeKind: string; targetsLabel: string; // e.g. "All plants", "3 plants"
approxPlantCount: number;
}>;
cursor?: string;
approximate: true; // byScopeKind is counter-derived; always true
}

Failure responses​

StatuscodeWhen
400VALIDATION_FAILEDUnknown query parameter
400INVALID_CURSORcursor is malformed, or was issued for a different route/org/filter/sort combination
401— (gateway)Missing/invalid token
403FORBIDDENteam < VIEW
500 / 503INTERNAL / DEPENDENCY_UNAVAILABLEServer/dependency error

Edge cases​

  • No design caveats surfaced. The design's two scope-kind caveats (ALL_REVIEW_OFTEN, TAG_SILENT_GRANT) aren't part of this response at all yet (KI-25) — the FE must supply that copy itself if needed, keyed off kind.
  • byScopeKind is returned the same way on every page, not only the first.
  • Members only. Pending invitations never appear in items, and every item has a sub and a displayName (same filtering as GET …/members, so a page can also be shorter than limit while cursor is present). Fixed 2026-11-04 (cse-http-backend#15): before that, a pending invitation appeared here as an item with no sub and no displayName.

Departments (/v1/orgs/{orgId}/departments)​

Purpose: The roster of departments (e.g. "Operations", "Field Service") used to group members and filter the People list. Departments carry no permission effect — assigning someone to a department changes nothing about what they can access; it's organisational labelling only.

  • HTTP methods: GET, POST (both on the collection path); PATCH, DELETE (on /departments/{deptId})
  • Authentication: Required
  • Authorization: GET — team ≥ VIEW. POST/PATCH/DELETE — team ≥ MANAGE.
  • Concurrency: PATCH/DELETE are versioned — If-Match required.
  • Idempotency: POST requires Idempotency-Key.
  • DynamoDB calls: GET — one bounded Query (this org's DEPT# items), plus a BatchGet to resolve each listed department's lead's display name and one facet-counter GetItem per department for memberCount. Writes — a GetItem (when a leadSub needs validating, or for PATCH/DELETE's existing-row read), then one TransactWriteCommand.

GET /v1/orgs/{orgId}/departments — List departments​

Query parameters: limit (1–50; default 15 on the first page, 10 with a cursor (lazy loading)), cursor — no filters.

Response

{
items: Array<{
deptId: string; code: string; // "D-1"
name: string;
leadSub?: string; leadName?: string;
memberCount: number; // approximate (facet counter)
regionNote?: string; note?: string;
version: number;
}>;
nextCursor?: string;
}

Failure responses​

StatuscodeWhen
401— (gateway)Missing/invalid token
403FORBIDDENteam < VIEW
500 / 503INTERNAL / DEPENDENCY_UNAVAILABLEServer/dependency error

POST /v1/orgs/{orgId}/departments — Create a department​

Headers: Idempotency-Key required, Content-Type: application/json.

Body

FieldRequiredTypeNotes
nameYesstring, 1–60 charsMust be unique (case/whitespace-normalised) within this org
leadSubNoCognito subMust be an ACTIVE member of this org — 422 otherwise
regionNoteNostring, ≤120 chars
noteNostring, ≤500 chars

Response: 201, same shape as one items[] entry above, version: 1.

Failure responses​

StatuscodeWhenFE action
401— (gateway)Missing/invalid tokenRe-authenticate
403FORBIDDENteam < MANAGEDon't retry
409ALREADY_EXISTSA department with this name already existsChoose a different name
422VALIDATION_FAILEDdetails.field: "leadSub" — leadSub isn't an ACTIVE member of this org; or a generic .strict() body errorFix the request
428PRECONDITION_REQUIREDIdempotency-Key missingGenerate a key, retry
500 / 503INTERNAL / DEPENDENCY_UNAVAILABLEServer/dependency errorRetry with backoff

Audit: DEPARTMENT_CREATED.

PATCH /v1/orgs/{orgId}/departments/{deptId} — Rename/update a department​

Headers: If-Match required.

Body — at least one field, all optional:

FieldTypeNotes
namestring, 1–60 charsRenaming checks the uniqueness guard again
leadSubCognito sub, or nullnull clears the lead. A non-null value must be an ACTIVE member of this org (same check as create).
regionNotestring, ≤120, or nullnull clears it
notestring, ≤500, or nullnull clears it

Response: 200, same shape as POST's, version bumped by 1.

Failure responses​

StatuscodeWhenFE action
401— (gateway)Missing/invalid tokenRe-authenticate
403FORBIDDENteam < MANAGEDon't retry
404NOT_FOUNDdeptId doesn't exist in this orgRe-fetch the department list
409VERSION_CONFLICTdetails.currentVersionRe-GET, retry with the new If-Match
409ALREADY_EXISTSRenaming to a name already used by another department in this orgChoose a different name
422VALIDATION_FAILEDdetails.field: "leadSub" (not an ACTIVE member), or the generic .strict() body error, or the plain "No changes supplied" messageFix the request
428PRECONDITION_REQUIREDIf-Match missingGET first, then retry
500 / 503INTERNAL / DEPENDENCY_UNAVAILABLEServer/dependency errorRetry with backoff

Audit: DEPARTMENT_UPDATED.

DELETE /v1/orgs/{orgId}/departments/{deptId} — Delete a department​

Headers: If-Match required.

Response: 204 No Content.

Failure responses​

StatuscodeWhenFE action
401— (gateway)Missing/invalid tokenRe-authenticate
403FORBIDDENteam < MANAGEDon't retry
404NOT_FOUNDdeptId doesn't exist in this orgRe-fetch the department list
409VERSION_CONFLICTdetails.currentVersionRe-GET, retry with the new If-Match
409INVALID_STATEdetails.memberCount — one or more members still belong to this departmentReassign those members to a different (or no) department first
428PRECONDITION_REQUIREDIf-Match missingGET first, then retry
500 / 503INTERNAL / DEPENDENCY_UNAVAILABLEServer/dependency errorRetry with backoff

Audit: DEPARTMENT_DELETED.

Edge cases (all four operations)​

  • Departments have zero permission effect. They never appear in any levels/perms computation — assigning or clearing a department only changes the departmentId label on a membership and the People list's department filter/grouping. Don't confuse this with scope (which DOES gate access). memberCount/department assignment is purely organisational. GET /v1/orgs/{orgId}/members/summary's own byDepartment tiles read the same counters this page's memberCount does.
  • leadSub must be an ACTIVE member of the SAME org — not of any parent/related org — on both create and patch. leadName is resolved on read, not stored on the department row, so it's always current with the lead's latest display name (unlike the leadSub reference itself, which only changes when explicitly patched).
  • memberCount is approximate, same facet-counter caveat as everywhere else on this page (eventually consistent, can lag by seconds after a member is moved in/out of a department).
  • POST's Idempotency-Key doesn't replay (KI-27) — same gap as bulk-assign-scope above; a retry after a genuine partial failure can hit 409 ALREADY_EXISTS instead of the original 201.

POST /v1/users/lookup — Display names for user ids​

Added 2026-11-11 for the web console's Engineering screen (request EB-5). The TCP console messages (list_bulk_tasks, get_command, get_operation_log, list_device_files, …) carry bare Cognito subs in requesterSub, approverSub, actorSub, userId and uploadedBy. The console collects the subs on a screen and resolves them with one call here. Names stay in this backend; TCP does not store them.

Unlike the rest of this page, this route has no {orgId} in the path: the org comes from the X-Org-Id header (required).

Authorization​

Any ACTIVE member of the X-Org-Id org at any level, or a Crown platform member reaching it through the platform fallback. The call is never refused because of a sub the caller may not see. Which names come back:

CallerNames returned
AnyoneTheir own (profile displayName)
team ≥ VIEW in the selected orgEvery member of that org, any status — the name on the membership row, as on the People screen
Crown Super Admin or AdministratorEveryone (membership-row name in the selected org, otherwise profile displayName)

Every other sub, and any unknown sub, comes back with name: null. No email or phone number is ever returned.

Request​

PartValue
HeadersAuthorization: Bearer <id token>, X-Org-Id: <orgId>, Content-Type: application/json
Body{ "subs": string[] } — 1 to 100 entries, each 1–128 characters; no other fields (strict)

Response​

200 OK — { "users": [{ "sub": string, "name": string | null }] }, in request order with duplicates removed.

Successful response — illustrative example​

Derived from UserLookupResponse (packages/core/src/schemas.ts) and lookupUserNames (packages/core/src/repositories/users.ts); not a captured execution.

{
"users": [
{ "sub": "1a2b3c4d-0000-0000-0000-000000000001", "name": "Ayesha Khan" },
{ "sub": "1a2b3c4d-0000-0000-0000-000000000002", "name": null }
]
}

Failure responses​

StatuscodeWhen
400ORG_CONTEXT_REQUIREDNo X-Org-Id header
401— (gateway)Missing or invalid token
403FORBIDDEN · ACCOUNT_SUSPENDEDNo ACTIVE membership in the org, or suspended account
422VALIDATION_FAILEDsubs missing, empty, more than 100, or an unknown body field
503DEPENDENCY_UNAVAILABLEDynamoDB BatchGet retries exhausted

Edge cases​

  • One DynamoDB BatchGetItem per call (membership rows and profiles), no Query and no Scan.
  • A user who has never set a display name comes back name: null even when visible.
  • A removed member keeps no membership row, so their name is hidden from Business admins (null); Crown Super Admin / Administrator still see the profile name.

See also​

  • Known issues & gaps — KI-24 (invitations), KI-25 (placeholder fields on this page), KI-27 (bulk-assign-scope/department create idempotency)
  • Architecture → Authorization model — the full level/category/scope/role model these routes enforce
  • API overview — shared conventions (pagination, If-Match/ETag, error envelope) that apply here too

Web console additions​

See Web console additions (N-37 … N-51) for the newer, not-yet-deployed fields and routes on this area.