From 5da43ba6163a3606f6b5d1ec8aff11b1a9cdfee9 Mon Sep 17 00:00:00 2001 From: David McKay Date: Thu, 19 Nov 2026 13:24:14 -0800 Subject: [PATCH 1/4] API: organizations can be deleted, API keys and the realtime socket can be held to one organization Adds deleteOrganization (DELETE .../profile), refusing a person's own organization and default; organizationOnly on a new API key and organizationId on a key; organizationId on conversation events and on a Recorder connection; the realtime socket relayed at /api/v2/organizations/{organizationId}/realtime/websocket; and says a push device is registered per organization. Deprecates the role property of updatePerson in favour of updateOrganizationMember, sunset 2028-05-19, and reserves Intelligence's /api/v2/platform root. --- CHANGELOG.md | 23 +++ api/asyncapi.yaml | 167 +++++++++++++++++- api/intelligence-reserved.yaml | 1 + api/openapi.yaml | 146 ++++++++++++++- api/openapi/accounts.yaml | 31 +++- api/openapi/common.yaml | 16 +- api/openapi/notifications.yaml | 18 +- api/openapi/organizations.yaml | 123 +++++++++++++ api/openapi/passwords-and-recorder.yaml | 8 + .../api/generated/api-keys/api-keys.msw.ts | 2 + .../lib/api/generated/api-keys/api-keys.ts | 2 +- .../api/generated/api-keys/api-keys.zod.ts | 20 ++- app/src/lib/api/generated/devices/devices.ts | 6 +- .../lib/api/generated/devices/devices.zod.ts | 10 +- app/src/lib/api/generated/model/apiKey.ts | 5 + .../generated/model/createApiKeyRequest.ts | 2 + .../model/deleteOrganizationHeaders.ts | 13 ++ app/src/lib/api/generated/model/device.ts | 2 +- app/src/lib/api/generated/model/index.ts | 4 + .../model/organizationNotDeletedResponse.ts | 9 + .../model/organizationStaysResponse.ts | 9 + .../api/generated/model/ownerOnlyResponse.ts | 9 + .../model/recorderConnectionGrant.ts | 2 + .../generated/model/updatePersonRequest.ts | 4 + .../organizations/organizations.msw.ts | 24 +++ .../generated/organizations/organizations.ts | 148 ++++++++++++++++ .../organizations/organizations.zod.ts | 28 +++ app/src/lib/api/generated/people/people.ts | 2 +- .../lib/api/generated/people/people.zod.ts | 6 +- .../api/generated/recorder/recorder.msw.ts | 1 + .../api/generated/recorder/recorder.zod.ts | 6 + extension/src/shared/generated/recorder.ts | 2 + mobile/src/api/generated/devices/devices.ts | 6 +- mobile/src/api/generated/model/device.ts | 2 +- mobile/src/api/generated/model/index.ts | 3 + .../model/organizationNotDeletedResponse.ts | 9 + .../model/organizationStaysResponse.ts | 9 + .../api/generated/model/ownerOnlyResponse.ts | 9 + .../generated/organizations/organizations.ts | 18 ++ 39 files changed, 866 insertions(+), 39 deletions(-) create mode 100644 app/src/lib/api/generated/model/deleteOrganizationHeaders.ts create mode 100644 app/src/lib/api/generated/model/organizationNotDeletedResponse.ts create mode 100644 app/src/lib/api/generated/model/organizationStaysResponse.ts create mode 100644 app/src/lib/api/generated/model/ownerOnlyResponse.ts create mode 100644 mobile/src/api/generated/model/organizationNotDeletedResponse.ts create mode 100644 mobile/src/api/generated/model/organizationStaysResponse.ts create mode 100644 mobile/src/api/generated/model/ownerOnlyResponse.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 1b521e1877..4f36156649 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,29 @@ Newest first. `Unreleased` is what is on `main` and not yet tagged. ## Unreleased +**Before upgrading.** + +- **Deprecated.** Each still works, answers with `Deprecation` and `Sunset` headers, and is + removed no earlier than its sunset, and only once nothing uses it. + - `PATCH /api/v2/organizations/{organizationId}/people/{personId} body role`: Sunset 2028-05-19. + Change a member's role with `PATCH /api/v2/organizations/{organizationId}/members/{personId}` + (`updateOrganizationMember`) instead. + +### API + +- **Delete an organization.** `DELETE /api/v2/organizations/{organizationId}/profile` + (`deleteOrganization`) deletes an organization and what is in it, for an owner of it. A person's + own organization and `default` stay, refused with 409 `CONFLICT`. +- **API keys for one organization.** `organizationOnly` on a new API key makes it work only in the + organization the address names; without it a key works in every organization its person is in, + as before. A key in an answer carries `organizationId`, null for a key that works everywhere. +- **The realtime socket at an address that names the organization.** + `/api/v2/organizations/{organizationId}/realtime/websocket` relays the same socket as + `/api/intelligence/client/websocket`, for a caller who is a member of that organization. +- **Push notifications per organization.** A phone registered under an organization's address gets + push notifications from the person's Bots in that organization only. +- New optional fields: `organizationId` on a conversation event and on a Recorder connection. + ### Bots and models - **A Bot asks for the app a request needs instead of searching around it.** Asked about what is diff --git a/api/asyncapi.yaml b/api/asyncapi.yaml index d3b64aff46..d3bb1ab1f2 100644 --- a/api/asyncapi.yaml +++ b/api/asyncapi.yaml @@ -62,7 +62,9 @@ servers: Where Intelligence runs beside an OpenBot, that address is OpenBot's own, so a client dials one host: either /api/intelligence/client, which OpenBot relays, or /client, which the deployment's edge sends straight - to the gateway. The relayed address also asks who is connecting, with + to the gateway. OpenBot also relays it at an address that names the + organization, /api/v2/organizations/{organizationId}/realtime, which + the channels that start with "organization" describe. The relayed address also asks who is connecting, with the same credential that made the join token: the web app's session, an app's access token (conversations:read) or an API key, the last two as Authorization: Bearer on the request that opens the socket, or a key in @@ -299,6 +301,111 @@ channels: $ref: "#/components/messages/TrajectoryEvents" trajectoryReply: $ref: "#/components/messages/TrajectoryReply" + organizationThreadStream: + address: /api/v2/organizations/{organizationId}/realtime/websocket + title: A conversation's runs, at the organization's address + description: >- + The gateway's socket for clients, relayed by OpenBot at an address that + names the organization, like every other address under /api/v2. It + carries exactly what a conversation's runs carry on the gateway's own + address: the same Phoenix Channels frames, topics, join tokens and + replay. A REST answer whose realtime.clientUrl is + /api/v2/organizations/{organizationId}/realtime on this server is + dialled here, with /websocket added as on the gateway. It is opened as + the relayed address is, by the web app's session, an app's access + token (conversations:read) or an API key, and the caller must be a + member of the organization the address names. One they are not in is + refused before the socket opens, as one that does not exist. The + organization's gateway is the one the socket reaches. + servers: + - $ref: "#/servers/openbot" + parameters: + organizationId: + $ref: "#/components/parameters/organizationId" + bindings: + ws: + method: GET + query: + type: object + required: + - join_token + - vsn + properties: + join_token: + type: string + description: >- + The join token from the REST answer. It works once and for + about half a minute, so every connection, and every + reconnection, starts with a new one. + vsn: + type: string + const: 2.0.0 + description: The Phoenix Channels protocol version. + bindingVersion: 0.1.0 + messages: + threadJoin: + $ref: "#/components/messages/ThreadJoin" + threadReply: + $ref: "#/components/messages/ThreadReply" + threadHeartbeat: + $ref: "#/components/messages/ThreadHeartbeat" + threadConnected: + $ref: "#/components/messages/ThreadConnected" + threadAgUiEvent: + $ref: "#/components/messages/ThreadAgUiEvent" + threadReplayComplete: + $ref: "#/components/messages/ThreadReplayComplete" + threadStreamIdle: + $ref: "#/components/messages/ThreadStreamIdle" + threadReplayFailed: + $ref: "#/components/messages/ThreadReplayFailed" + threadExpired: + $ref: "#/components/messages/ThreadExpired" + threadStopRun: + $ref: "#/components/messages/ThreadStopRun" + threadLeave: + $ref: "#/components/messages/ThreadLeave" + threadClose: + $ref: "#/components/messages/ThreadClose" + threadError: + $ref: "#/components/messages/ThreadError" + organizationTrajectoryCapture: + address: /api/v2/organizations/{organizationId}/realtime/websocket + title: What the Recorder captures, at the organization's address + description: >- + The same socket as a conversation's runs at the organization's address, + on the topic trajectory:{trajectoryId}: what the Recorder captures, + exactly as it travels on the gateway's own address. The Recorder dials + it when its pass's realtime.clientUrl names this address. + servers: + - $ref: "#/servers/openbot" + parameters: + organizationId: + $ref: "#/components/parameters/organizationId" + bindings: + ws: + method: GET + query: + type: object + required: + - join_token + - vsn + properties: + join_token: + type: string + description: The join token from the Recorder's pass. It works once. + vsn: + type: string + const: 2.0.0 + description: The Phoenix Channels protocol version. + bindingVersion: 0.1.0 + messages: + trajectoryJoin: + $ref: "#/components/messages/TrajectoryJoin" + trajectoryEvents: + $ref: "#/components/messages/TrajectoryEvents" + trajectoryReply: + $ref: "#/components/messages/TrajectoryReply" voiceCall: address: / title: A voice call @@ -452,6 +559,58 @@ operations: $ref: "#/channels/trajectoryCapture" messages: - $ref: "#/channels/trajectoryCapture/messages/trajectoryReply" + sendOrganizationThreadStream: + action: send + title: Stream a conversation's runs, at the organization's address + summary: The thread's AG-UI events, replayed and then live, with the markers between. + security: + - $ref: "#/components/securitySchemes/webSession" + - $ref: "#/components/securitySchemes/apiKey" + - $ref: "#/components/securitySchemes/conversationsRead" + channel: + $ref: "#/channels/organizationThreadStream" + messages: + - $ref: "#/channels/organizationThreadStream/messages/threadReply" + - $ref: "#/channels/organizationThreadStream/messages/threadConnected" + - $ref: "#/channels/organizationThreadStream/messages/threadAgUiEvent" + - $ref: "#/channels/organizationThreadStream/messages/threadReplayComplete" + - $ref: "#/channels/organizationThreadStream/messages/threadStreamIdle" + - $ref: "#/channels/organizationThreadStream/messages/threadReplayFailed" + - $ref: "#/channels/organizationThreadStream/messages/threadExpired" + - $ref: "#/channels/organizationThreadStream/messages/threadClose" + - $ref: "#/channels/organizationThreadStream/messages/threadError" + receiveOrganizationThreadCommands: + action: receive + title: Join a thread, keep the socket alive, stop a run, leave, at the organization's address + summary: What a client sends on the organization's relayed socket. + security: + - $ref: "#/components/securitySchemes/webSession" + - $ref: "#/components/securitySchemes/apiKey" + - $ref: "#/components/securitySchemes/conversationsRead" + channel: + $ref: "#/channels/organizationThreadStream" + messages: + - $ref: "#/channels/organizationThreadStream/messages/threadJoin" + - $ref: "#/channels/organizationThreadStream/messages/threadHeartbeat" + - $ref: "#/channels/organizationThreadStream/messages/threadStopRun" + - $ref: "#/channels/organizationThreadStream/messages/threadLeave" + receiveOrganizationTrajectoryEvents: + action: receive + title: Take what the Recorder captured, at the organization's address + summary: The Recorder joins a trajectory's topic and sends its events in batches. + channel: + $ref: "#/channels/organizationTrajectoryCapture" + messages: + - $ref: "#/channels/organizationTrajectoryCapture/messages/trajectoryJoin" + - $ref: "#/channels/organizationTrajectoryCapture/messages/trajectoryEvents" + sendOrganizationTrajectoryReplies: + action: send + title: Answer the Recorder, at the organization's address + summary: The gateway's answer to a join and to each batch. + channel: + $ref: "#/channels/organizationTrajectoryCapture" + messages: + - $ref: "#/channels/organizationTrajectoryCapture/messages/trajectoryReply" receiveVoiceCall: action: receive title: Take a person's side of a call @@ -796,6 +955,12 @@ components: channelId: type: string description: The conversation. + organizationId: + type: string + description: >- + The organization the conversation is in. A client ignores a + message for an organization other than the one it shows. Absent + from a server that sends only the socket's own organization's. memberIds: type: array description: The people this message was sent to. diff --git a/api/intelligence-reserved.yaml b/api/intelligence-reserved.yaml index 035d335bc9..1ad491f4bf 100644 --- a/api/intelligence-reserved.yaml +++ b/api/intelligence-reserved.yaml @@ -41,6 +41,7 @@ roots: - me - oauth - organization-slugs + - platform - runtime # Exactly these, which Intelligence answers itself. diff --git a/api/openapi.yaml b/api/openapi.yaml index 058774ef9c..fa8a404a78 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -739,7 +739,7 @@ paths: - People operationId: updatePerson summary: Change a person - description: Change what is sent and leave the rest. A person changes their own name, and nobody else's. An administrator changes anybody's role, but not their own away from administrator, and not the role of somebody the deployment's configuration names as an administrator. Asking for the role a person already has changes nothing and records nothing. + description: 'Change what is sent and leave the rest. A person changes their own name, and nobody else''s. An administrator changes anybody''s role, but not their own away from administrator, and not the role of somebody the deployment''s configuration names as an administrator. Asking for the role a person already has changes nothing and records nothing. role is deprecated: change a member''s role with updateOrganizationMember instead.' security: - webSession: [] - appOAuth: @@ -1207,7 +1207,7 @@ paths: - API keys operationId: createApiKey summary: Make an API key - description: 'Make an API key that acts as the person, in every organization they are a member of, on the API. The key itself is in this answer and never again: OpenBot keeps only a hash of it. Only the person themselves may make one, signed in to OpenBot: a key can never make another key, and neither can an app''s sign-in. A key ends when it expires, when it is deleted, or when an administrator removes the person.' + description: 'Make an API key that acts as the person on the API: in this organization only when organizationOnly is true, otherwise in every organization they are a member of. The key itself is in this answer and never again: OpenBot keeps only a hash of it. Only the person themselves may make one, signed in to OpenBot: a key can never make another key, and neither can an app''s sign-in. A key ends when it expires, when it is deleted, or when an administrator removes the person.' security: - webSession: [] parameters: @@ -1223,6 +1223,7 @@ paths: value: name: Nightly report expiresInDays: 90 + organizationOnly: true responses: '201': description: The key, shown this once. @@ -7921,7 +7922,7 @@ paths: - Devices operationId: listDevices summary: List a person's devices - description: Return one page of the phones a person registered for push notifications, the first registered first. Never a device's push token. Only the person themselves may list them; there is no administrator view. A missing cursor starts at the first page and nextCursor null ends the list. + description: Return one page of the phones a person registered for push notifications in this organization, the first registered first. Never a device's push token. Only the person themselves may list them; there is no administrator view. A missing cursor starts at the first page and nextCursor null ends the list. security: - webSession: [] - appOAuth: @@ -7965,7 +7966,7 @@ paths: - Devices operationId: registerDevice summary: Register a device for push notifications - description: Register one of the person's phones for push notifications under the id the app made for it, or replace what that id holds. The app sends its current push token every time it starts, so a token that changed replaces the old one and the device is never registered twice. Answers 200 whether the id was new or held a registration already. A token another account holds moves only once that account signed out on the phone. Only the person themselves may register their devices, and only where this deployment sends push notifications (listNotificationTransports). + description: Register one of the person's phones for push notifications under the id the app made for it, or replace what that id holds. A device is registered in one organization, the one the address names, and gets push notifications only from the person's Bots there. A person in several organizations registers the phone in each one they want notifications from, under the same id. The app sends its current push token every time it starts, so a token that changed replaces the old one and the device is never registered twice. Answers 200 whether the id was new or held a registration already. A token another account holds moves only once that account signed out on the phone. Only the person themselves may register their devices, and only where this deployment sends push notifications (listNotificationTransports). security: - webSession: [] - appOAuth: @@ -8017,7 +8018,7 @@ paths: - Devices operationId: deleteDevice summary: Stop push notifications to a device - description: Stop sending push notifications to one of the person's phones. The app does this when the person signs out on it, so another account can register the phone after them. Only the person themselves may remove their devices. A device already removed is not found, which a client can read as done. + description: Stop sending push notifications to one of the person's phones from this organization. Its registrations in the person's other organizations stay. The app does this in each organization when the person signs out on it, so another account can register the phone after them. Only the person themselves may remove their devices. A device already removed is not found, which a client can read as done. security: - webSession: [] - appOAuth: @@ -10467,6 +10468,41 @@ paths: $ref: '#/components/responses/ServerError' default: $ref: '#/components/responses/UnexpectedError' + delete: + tags: + - Organizations + operationId: deleteOrganization + summary: Delete an organization + description: 'Delete the organization and what is in it. Nobody can work in it again: its Bots stop, its computers are removed, an API key made for it alone stops working, and it leaves every member''s list of organizations. Its members keep their accounts and their other organizations. Only an owner of this organization can. A person''s own organization and `default` stay, and are refused. A repeated request with the same Idempotency-Key returns the first result.' + security: + - webSession: [] + - appOAuth: + - organizations:write + - apiKey: [] + parameters: + - $ref: '#/components/parameters/IdempotencyKey' + responses: + '204': + description: The organization is deleted. + headers: + Cache-Control: + $ref: '#/components/headers/PrivateNoStore' + '400': + $ref: '#/components/responses/InvalidRequest' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/OwnerOnly' + '404': + $ref: '#/components/responses/OrganizationNotFound' + '409': + $ref: '#/components/responses/OrganizationStays' + '500': + $ref: '#/components/responses/ServerError' + '503': + $ref: '#/components/responses/OrganizationNotDeleted' + default: + $ref: '#/components/responses/UnexpectedError' /api/v2/organizations/{organizationId}/members/{personId}: parameters: - $ref: '#/components/parameters/OrganizationId' @@ -20215,7 +20251,7 @@ components: Endpoints. The authorization server's metadata (RFC 8414) is at `/.well-known/oauth-authorization-server/api/auth`. The person is sent to `/api/auth/oauth2/authorize`. The code is exchanged, and a token refreshed, at `/api/auth/oauth2/token`, with a form-encoded body (`application/x-www-form-urlencoded`) that carries `client_id` and no secret: the token and revocation endpoints take no client authentication (`none` in the metadata's `token_endpoint_auth_methods_supported`). A wrong `code_verifier` is answered 400 `invalid_grant`, and the code cannot be used again. A token is revoked (RFC 7009) at `/api/auth/oauth2/revoke`; revoking a token the server does not know, or one already revoked, answers 200. - Tokens. An access token starts `oba_` and lasts one hour. A refresh token starts `obr_`, is issued only when the `offline_access` scope is asked for, and rotates on every use: each refresh answers a new refresh token and ends the one it was given. Access tokens work on /api/v2, and on four addresses outside it that an app's screens need, each with the scope given: `GET /api/me`, who is signed in (people:read); the chat runtime at `/api/copilotkit` and everything under it (conversations:write); a file's download at `GET /api/attachments/{attachmentId}`, the address a sent message keeps (conversations:read); and the relayed realtime socket at `/api/intelligence/client/websocket` (conversations:read). They work nowhere else. + Tokens. An access token starts `oba_` and lasts one hour. A refresh token starts `obr_`, is issued only when the `offline_access` scope is asked for, and rotates on every use: each refresh answers a new refresh token and ends the one it was given. Access tokens work on /api/v2, and on four addresses outside it that an app's screens need, each with the scope given: `GET /api/me`, who is signed in (people:read); the chat runtime at `/api/copilotkit` and everything under it (conversations:write); a file's download at `GET /api/attachments/{attachmentId}`, the address a sent message keeps (conversations:read); and the relayed realtime socket at `/api/intelligence/client/websocket` (conversations:read), which is also on /api/v2 at `/api/v2/organizations/{organizationId}/realtime/websocket`. They work nowhere else. Organization. An access token carries no memory of which organization the person is working in. An address under `/api/v2/organizations/{organizationId}` names it. Where an address names none, such as the list of the person's own organizations, an app sends the header `OpenBot-Organization` with the organization's id. It is checked against the person's membership on every request, and an organization they are not in answers not found. With no header, the app works in the person's own organization. @@ -20315,7 +20351,7 @@ components: type: http scheme: bearer bearerFormat: OpenBot API key - description: 'Automation. An API key acts as the person who created it, in every organization they are a member of, like a personal access token: the address of each request names the organization, and one the person is not in answers not found. A key starts `obk_` and is sent as `Authorization: Bearer ` or in an `x-api-key` header, on /api/v2 and on the relayed realtime socket at `/api/intelligence/client/websocket`, where a join token the key made is spent (createConversationJoinToken). A person makes one in the web app, signed in, under Settings, then API keys (createApiKey).' + description: 'Automation. An API key acts as the person who created it, like a personal access token: in every organization they are a member of, or in one organization only when it was made for that one (organizationOnly). The address of each request names the organization, and one the key does not work in answers not found. A key starts `obk_` and is sent as `Authorization: Bearer ` or in an `x-api-key` header, on /api/v2 (the relayed realtime socket at `/api/v2/organizations/{organizationId}/realtime/websocket` included) and on the relayed realtime socket at `/api/intelligence/client/websocket`, where a join token the key made is spent (createConversationJoinToken). A person makes one in the web app, signed in, under Settings, then API keys (createApiKey).' recorderConnection: type: http scheme: bearer @@ -21811,6 +21847,10 @@ components: description: What OpenBot calls the person, 1 to 100 characters once trimmed. Only the person themselves may change it. role: $ref: '#/components/schemas/AssignableRole' + deprecated: true + x-deprecation-date: '2026-11-19' + x-sunset: '2028-05-19' + description: Deprecated. Change a member's role with updateOrganizationMember (PATCH /api/v2/organizations/{organizationId}/members/{personId}) instead. AdvanceOnboardingRequest: type: object additionalProperties: false @@ -21968,6 +22008,11 @@ components: - 'null' format: date-time description: When it last signed a request. Null if never. + organizationId: + type: + - string + - 'null' + description: The organization the key works in, when it was made for that one only (organizationOnly). Null when it works in every organization the person is a member of. Absent from a server that makes every key for every organization. ApiKeyPage: type: object required: @@ -22003,6 +22048,9 @@ components: minimum: 1 maximum: 365 description: Days until the key stops working. Absent, it never expires. + organizationOnly: + type: boolean + description: Whether the key works only in this organization, the one the address names. In any other organization it is refused as if the organization did not exist. Absent or false, the key works in every organization the person is a member of. CreatedApiKey: type: object required: @@ -27638,7 +27686,7 @@ components: description: The phone's operating system. Device: type: object - description: A phone that gets push notifications for the person, from every one of their Bots. Never its push token. + description: A phone that gets push notifications for the person, from every one of their Bots in the organization it is registered in. Never its push token. required: - id - platform @@ -34837,6 +34885,9 @@ components: $ref: '#/components/schemas/RecorderConnection' user: $ref: '#/components/schemas/RecorderUser' + organizationId: + type: string + description: The organization the connection works in, the one the connect code was made in. The Recorder names it in every address it calls from now on. Absent from a server that keeps every connection in `default`. RecorderProblem: description: 'A problem for the OpenBot Recorder: the shared problem details, with why its connection ended.' allOf: @@ -39512,6 +39563,82 @@ components: retryable: true requestId: req_example traceId: trace_example + OwnerOnly: + description: The caller is not an owner of the organization, or holds no role in it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + notOwner: + value: + type: https://open.bot/errors/permission-denied + title: Permission denied. + status: 403 + detail: Only an owner can delete this organization. + code: PERMISSION_DENIED + category: permission + retryable: false + requestId: req_example + traceId: trace_example + OrganizationStays: + description: 'The organization can''t be deleted: it is a person''s own organization, or it is `default`. Or the Idempotency-Key was used for a different request.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + personal: + value: + type: https://open.bot/errors/conflict + title: The request conflicts with the current state. + status: 409 + detail: This is your own organization, so it stays. You can delete organizations you created. + code: CONFLICT + category: conflict + retryable: false + requestId: req_example + traceId: trace_example + default: + value: + type: https://open.bot/errors/conflict + title: The request conflicts with the current state. + status: 409 + detail: This organization comes with OpenBot, so it stays. + code: CONFLICT + category: conflict + retryable: false + requestId: req_example + traceId: trace_example + reused: + value: + type: https://open.bot/errors/idempotency-key-conflict + title: That Idempotency-Key was used for a different request. + status: 409 + detail: That Idempotency-Key was used for a different request. + code: IDEMPOTENCY_KEY_CONFLICT + category: conflict + retryable: false + requestId: req_example + traceId: trace_example + OrganizationNotDeleted: + description: This OpenBot could not finish deleting the organization, so it was not deleted. Asking again may work. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + unfinished: + value: + type: https://open.bot/errors/service-unavailable + title: A service OpenBot depends on is unavailable. + status: 503 + detail: The organization couldn't be deleted. Try again. + code: SERVICE_UNAVAILABLE + category: dependency + retryable: true + requestId: req_example + traceId: trace_example OwnerStays: description: 'The person stays in the organization: they own it, or this OpenBot''s settings keep them as an admin of it. The members list says who, as removable.' content: @@ -42261,6 +42388,7 @@ components: createdAt: '2026-11-14T09:00:00.000Z' expiresAt: '2027-02-12T09:00:00.000Z' lastUsedAt: '2026-11-14T09:05:12.000Z' + organizationId: Jq3xT9mLw2Vb8RnC5sYd0fKe nextCursor: null CreatedApiKeyExample: summary: A key, made. @@ -42272,6 +42400,7 @@ components: createdAt: '2026-11-14T09:00:00.000Z' expiresAt: '2027-02-12T09:00:00.000Z' lastUsedAt: null + organizationId: Jq3xT9mLw2Vb8RnC5sYd0fKe key: obk_XyR2f8Lq0mVt5WcN1pZa7KdJ3hUe9sBg SessionPageLast: summary: Signed in on a laptop and a phone. @@ -45621,6 +45750,7 @@ components: id: 9f8e7d6c-5b4a-4321-8fed-cba987654321 name: Sam Ortiz email: sam@example.com + organizationId: Jq3xT9mLw2Vb8RnC5sYd0fKe RecorderIdentityExample: summary: Who this Recorder acts as. value: diff --git a/api/openapi/accounts.yaml b/api/openapi/accounts.yaml index 3a2ec3ef48..19c5ab4796 100644 --- a/api/openapi/accounts.yaml +++ b/api/openapi/accounts.yaml @@ -110,6 +110,8 @@ paths: not their own away from administrator, and not the role of somebody the deployment's configuration names as an administrator. Asking for the role a person already has changes nothing and records nothing. + role is deprecated: change a member's role with + updateOrganizationMember instead. security: - webSession: [] - appOAuth: [people:write] @@ -609,8 +611,9 @@ paths: operationId: createApiKey summary: Make an API key description: >- - Make an API key that acts as the person, in every organization they - are a member of, on the API. The key itself is in this answer and never again: + Make an API key that acts as the person on the API: in this + organization only when organizationOnly is true, otherwise in every + organization they are a member of. The key itself is in this answer and never again: OpenBot keeps only a hash of it. Only the person themselves may make one, signed in to OpenBot: a key can never make another key, and neither can an app's sign-in. A key ends when it expires, when it is @@ -630,6 +633,7 @@ paths: value: name: Nightly report expiresInDays: 90 + organizationOnly: true responses: '201': description: The key, shown this once. @@ -1306,6 +1310,13 @@ components: Only the person themselves may change it. role: $ref: '#/components/schemas/AssignableRole' + deprecated: true + x-deprecation-date: 2026-11-19 + x-sunset: 2028-05-19 + description: >- + Deprecated. Change a member's role with updateOrganizationMember + (PATCH /api/v2/organizations/{organizationId}/members/{personId}) + instead. AdvanceOnboardingRequest: type: object additionalProperties: false @@ -1456,6 +1467,13 @@ components: type: [string, 'null'] format: date-time description: When it last signed a request. Null if never. + organizationId: + type: [string, 'null'] + description: >- + The organization the key works in, when it was made for that one + only (organizationOnly). Null when it works in every organization + the person is a member of. Absent from a server that makes every + key for every organization. ApiKeyPage: type: object required: [apiKeys, nextCursor] @@ -1488,6 +1506,13 @@ components: minimum: 1 maximum: 365 description: Days until the key stops working. Absent, it never expires. + organizationOnly: + type: boolean + description: >- + Whether the key works only in this organization, the one the + address names. In any other organization it is refused as if the + organization did not exist. Absent or false, the key works in + every organization the person is a member of. CreatedApiKey: type: object required: [apiKey, key] @@ -2155,6 +2180,7 @@ components: createdAt: '2026-11-14T09:00:00.000Z' expiresAt: '2027-02-12T09:00:00.000Z' lastUsedAt: '2026-11-14T09:05:12.000Z' + organizationId: Jq3xT9mLw2Vb8RnC5sYd0fKe nextCursor: null CreatedApiKeyExample: summary: A key, made. @@ -2166,6 +2192,7 @@ components: createdAt: '2026-11-14T09:00:00.000Z' expiresAt: '2027-02-12T09:00:00.000Z' lastUsedAt: null + organizationId: Jq3xT9mLw2Vb8RnC5sYd0fKe key: obk_XyR2f8Lq0mVt5WcN1pZa7KdJ3hUe9sBg SessionPageLast: summary: Signed in on a laptop and a phone. diff --git a/api/openapi/common.yaml b/api/openapi/common.yaml index c05d3a9f6a..8845be7b05 100644 --- a/api/openapi/common.yaml +++ b/api/openapi/common.yaml @@ -527,7 +527,9 @@ components: under it (conversations:write); a file's download at `GET /api/attachments/{attachmentId}`, the address a sent message keeps (conversations:read); and the relayed realtime socket at - `/api/intelligence/client/websocket` (conversations:read). They work + `/api/intelligence/client/websocket` (conversations:read), which is + also on /api/v2 at + `/api/v2/organizations/{organizationId}/realtime/websocket`. They work nowhere else. @@ -641,11 +643,15 @@ components: scheme: bearer bearerFormat: OpenBot API key description: >- - Automation. An API key acts as the person who created it, in every - organization they are a member of, like a personal access token: the - address of each request names the organization, and one the person - is not in answers not found. A key starts `obk_` and is sent as + Automation. An API key acts as the person who created it, like a + personal access token: in every organization they are a member of, + or in one organization only when it was made for that one + (organizationOnly). The address of each request names the + organization, and one the key does not work in answers not found. A + key starts `obk_` and is sent as `Authorization: Bearer ` or in an `x-api-key` header, on /api/v2 + (the relayed realtime socket at + `/api/v2/organizations/{organizationId}/realtime/websocket` included) and on the relayed realtime socket at `/api/intelligence/client/websocket`, where a join token the key made is spent (createConversationJoinToken). A person makes one in the web diff --git a/api/openapi/notifications.yaml b/api/openapi/notifications.yaml index 6dc68a87f7..4f943a7d10 100644 --- a/api/openapi/notifications.yaml +++ b/api/openapi/notifications.yaml @@ -15,7 +15,8 @@ paths: summary: List a person's devices description: >- Return one page of the phones a person registered for push - notifications, the first registered first. Never a device's push + notifications in this organization, the first registered first. + Never a device's push token. Only the person themselves may list them; there is no administrator view. A missing cursor starts at the first page and nextCursor null ends the list. @@ -62,7 +63,11 @@ paths: summary: Register a device for push notifications description: >- Register one of the person's phones for push notifications under the - id the app made for it, or replace what that id holds. The app sends + id the app made for it, or replace what that id holds. A device is + registered in one organization, the one the address names, and gets + push notifications only from the person's Bots there. A person in + several organizations registers the phone in each one they want + notifications from, under the same id. The app sends its current push token every time it starts, so a token that changed replaces the old one and the device is never registered twice. Answers 200 whether the id was new or held a registration already. @@ -120,8 +125,10 @@ paths: operationId: deleteDevice summary: Stop push notifications to a device description: >- - Stop sending push notifications to one of the person's phones. The - app does this when the person signs out on it, so another account + Stop sending push notifications to one of the person's phones from + this organization. Its registrations in the person's other + organizations stay. The app does this in each organization when the + person signs out on it, so another account can register the phone after them. Only the person themselves may remove their devices. A device already removed is not found, which a client can read as done. @@ -736,7 +743,8 @@ components: type: object description: >- A phone that gets push notifications for the person, from every one - of their Bots. Never its push token. + of their Bots in the organization it is registered in. Never its + push token. required: [id, platform, createdAt] properties: id: diff --git a/api/openapi/organizations.yaml b/api/openapi/organizations.yaml index 09bc89ed9a..11c4adf40a 100644 --- a/api/openapi/organizations.yaml +++ b/api/openapi/organizations.yaml @@ -184,6 +184,46 @@ paths: $ref: './common.yaml#/components/responses/ServerError' default: $ref: './common.yaml#/components/responses/UnexpectedError' + delete: + tags: [Organizations] + operationId: deleteOrganization + summary: Delete an organization + description: >- + Delete the organization and what is in it. Nobody can work in it + again: its Bots stop, its computers are removed, an API key made for + it alone stops working, and it leaves every member's list of + organizations. Its members keep their accounts and their other + organizations. Only an owner of this organization can. A person's own + organization and `default` stay, and are refused. A repeated request + with the same Idempotency-Key returns the first result. + security: + - webSession: [] + - appOAuth: [organizations:write] + - apiKey: [] + parameters: + - $ref: './common.yaml#/components/parameters/IdempotencyKey' + responses: + '204': + description: The organization is deleted. + headers: + Cache-Control: + $ref: './common.yaml#/components/headers/PrivateNoStore' + '400': + $ref: './common.yaml#/components/responses/InvalidRequest' + '401': + $ref: './common.yaml#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/OwnerOnly' + '404': + $ref: './common.yaml#/components/responses/OrganizationNotFound' + '409': + $ref: '#/components/responses/OrganizationStays' + '500': + $ref: './common.yaml#/components/responses/ServerError' + '503': + $ref: '#/components/responses/OrganizationNotDeleted' + default: + $ref: './common.yaml#/components/responses/UnexpectedError' /api/v2/organizations/{organizationId}/members: parameters: - $ref: './common.yaml#/components/parameters/OrganizationId' @@ -1022,6 +1062,89 @@ components: retryable: true requestId: req_example traceId: trace_example + OwnerOnly: + description: >- + The caller is not an owner of the organization, or holds no role in + it. + content: + application/problem+json: + schema: + $ref: './common.yaml#/components/schemas/Problem' + examples: + notOwner: + value: + type: https://open.bot/errors/permission-denied + title: Permission denied. + status: 403 + detail: Only an owner can delete this organization. + code: PERMISSION_DENIED + category: permission + retryable: false + requestId: req_example + traceId: trace_example + OrganizationStays: + description: >- + The organization can't be deleted: it is a person's own organization, + or it is `default`. Or the Idempotency-Key was used for a different + request. + content: + application/problem+json: + schema: + $ref: './common.yaml#/components/schemas/Problem' + examples: + personal: + value: + type: https://open.bot/errors/conflict + title: The request conflicts with the current state. + status: 409 + detail: This is your own organization, so it stays. You can delete organizations you created. + code: CONFLICT + category: conflict + retryable: false + requestId: req_example + traceId: trace_example + default: + value: + type: https://open.bot/errors/conflict + title: The request conflicts with the current state. + status: 409 + detail: This organization comes with OpenBot, so it stays. + code: CONFLICT + category: conflict + retryable: false + requestId: req_example + traceId: trace_example + reused: + value: + type: https://open.bot/errors/idempotency-key-conflict + title: That Idempotency-Key was used for a different request. + status: 409 + detail: That Idempotency-Key was used for a different request. + code: IDEMPOTENCY_KEY_CONFLICT + category: conflict + retryable: false + requestId: req_example + traceId: trace_example + OrganizationNotDeleted: + description: >- + This OpenBot could not finish deleting the organization, so it was + not deleted. Asking again may work. + content: + application/problem+json: + schema: + $ref: './common.yaml#/components/schemas/Problem' + examples: + unfinished: + value: + type: https://open.bot/errors/service-unavailable + title: A service OpenBot depends on is unavailable. + status: 503 + detail: The organization couldn't be deleted. Try again. + code: SERVICE_UNAVAILABLE + category: dependency + retryable: true + requestId: req_example + traceId: trace_example OwnerStays: description: >- The person stays in the organization: they own it, or this OpenBot's diff --git a/api/openapi/passwords-and-recorder.yaml b/api/openapi/passwords-and-recorder.yaml index ec0acf2dc4..0b6a3aaad4 100644 --- a/api/openapi/passwords-and-recorder.yaml +++ b/api/openapi/passwords-and-recorder.yaml @@ -1429,6 +1429,13 @@ components: $ref: '#/components/schemas/RecorderConnection' user: $ref: '#/components/schemas/RecorderUser' + organizationId: + type: string + description: >- + The organization the connection works in, the one the connect + code was made in. The Recorder names it in every address it calls + from now on. Absent from a server that keeps every connection in + `default`. RecorderIdentity: type: object required: [user, connectionId] @@ -1986,6 +1993,7 @@ components: id: 9f8e7d6c-5b4a-4321-8fed-cba987654321 name: Sam Ortiz email: sam@example.com + organizationId: Jq3xT9mLw2Vb8RnC5sYd0fKe RecorderIdentityExample: summary: Who this Recorder acts as. value: diff --git a/app/src/lib/api/generated/api-keys/api-keys.msw.ts b/app/src/lib/api/generated/api-keys/api-keys.msw.ts index 01f964e6ec..f3ce0c33ca 100644 --- a/app/src/lib/api/generated/api-keys/api-keys.msw.ts +++ b/app/src/lib/api/generated/api-keys/api-keys.msw.ts @@ -15,6 +15,7 @@ export const getListApiKeysResponseMock = (): ApiKeyPage => ({ createdAt: "2026-11-14T09:00:00.000Z", expiresAt: "2027-02-12T09:00:00.000Z", lastUsedAt: "2026-11-14T09:05:12.000Z", + organizationId: "Jq3xT9mLw2Vb8RnC5sYd0fKe", }, ], nextCursor: null, @@ -28,6 +29,7 @@ export const getCreateApiKeyResponseMock = (): CreatedApiKey => ({ createdAt: "2026-11-14T09:00:00.000Z", expiresAt: "2027-02-12T09:00:00.000Z", lastUsedAt: null, + organizationId: "Jq3xT9mLw2Vb8RnC5sYd0fKe", }, key: "obk_XyR2f8Lq0mVt5WcN1pZa7KdJ3hUe9sBg", }); diff --git a/app/src/lib/api/generated/api-keys/api-keys.ts b/app/src/lib/api/generated/api-keys/api-keys.ts index 44b1e40d6c..2725f26fa0 100644 --- a/app/src/lib/api/generated/api-keys/api-keys.ts +++ b/app/src/lib/api/generated/api-keys/api-keys.ts @@ -313,7 +313,7 @@ export const getCreateApiKeyUrl = ( }; /** - * Make an API key that acts as the person, in every organization they are a member of, on the API. The key itself is in this answer and never again: OpenBot keeps only a hash of it. Only the person themselves may make one, signed in to OpenBot: a key can never make another key, and neither can an app's sign-in. A key ends when it expires, when it is deleted, or when an administrator removes the person. + * Make an API key that acts as the person on the API: in this organization only when organizationOnly is true, otherwise in every organization they are a member of. The key itself is in this answer and never again: OpenBot keeps only a hash of it. Only the person themselves may make one, signed in to OpenBot: a key can never make another key, and neither can an app's sign-in. A key ends when it expires, when it is deleted, or when an administrator removes the person. * @summary Make an API key */ export const createApiKey = async ( diff --git a/app/src/lib/api/generated/api-keys/api-keys.zod.ts b/app/src/lib/api/generated/api-keys/api-keys.zod.ts index 3b5182e73f..f26f16781e 100644 --- a/app/src/lib/api/generated/api-keys/api-keys.zod.ts +++ b/app/src/lib/api/generated/api-keys/api-keys.zod.ts @@ -80,6 +80,12 @@ export const ListApiKeysResponse = zod.object({ .datetime({ offset: true }) .nullable() .describe("When it last signed a request. Null if never."), + organizationId: zod + .string() + .nullish() + .describe( + "The organization the key works in, when it was made for that one only (organizationOnly). Null when it works in every organization the person is a member of. Absent from a server that makes every key for every organization.", + ), }) .describe("An API key a person made. Never the key itself."), ) @@ -95,7 +101,7 @@ export const ListApiKeysResponse = zod.object({ }); /** - * Make an API key that acts as the person, in every organization they are a member of, on the API. The key itself is in this answer and never again: OpenBot keeps only a hash of it. Only the person themselves may make one, signed in to OpenBot: a key can never make another key, and neither can an app's sign-in. A key ends when it expires, when it is deleted, or when an administrator removes the person. + * Make an API key that acts as the person on the API: in this organization only when organizationOnly is true, otherwise in every organization they are a member of. The key itself is in this answer and never again: OpenBot keeps only a hash of it. Only the person themselves may make one, signed in to OpenBot: a key can never make another key, and neither can an app's sign-in. A key ends when it expires, when it is deleted, or when an administrator removes the person. * @summary Make an API key */ @@ -150,6 +156,12 @@ export const CreateApiKeyBody = zod.object({ .max(createApiKeyBodyExpiresInDaysMax) .optional() .describe("Days until the key stops working. Absent, it never expires."), + organizationOnly: zod + .boolean() + .optional() + .describe( + "Whether the key works only in this organization, the one the address names. In any other organization it is refused as if the organization did not exist. Absent or false, the key works in every organization the person is a member of.", + ), }); export const CreateApiKeyResponse = zod.object({ @@ -170,6 +182,12 @@ export const CreateApiKeyResponse = zod.object({ .datetime({ offset: true }) .nullable() .describe("When it last signed a request. Null if never."), + organizationId: zod + .string() + .nullish() + .describe( + "The organization the key works in, when it was made for that one only (organizationOnly). Null when it works in every organization the person is a member of. Absent from a server that makes every key for every organization.", + ), }) .describe("An API key a person made. Never the key itself."), key: zod diff --git a/app/src/lib/api/generated/devices/devices.ts b/app/src/lib/api/generated/devices/devices.ts index 4182c789e0..2c5c9e9c9d 100644 --- a/app/src/lib/api/generated/devices/devices.ts +++ b/app/src/lib/api/generated/devices/devices.ts @@ -83,7 +83,7 @@ export const getListDevicesUrl = ( }; /** - * Return one page of the phones a person registered for push notifications, the first registered first. Never a device's push token. Only the person themselves may list them; there is no administrator view. A missing cursor starts at the first page and nextCursor null ends the list. + * Return one page of the phones a person registered for push notifications in this organization, the first registered first. Never a device's push token. Only the person themselves may list them; there is no administrator view. A missing cursor starts at the first page and nextCursor null ends the list. * @summary List a person's devices */ export const listDevices = async ( @@ -309,7 +309,7 @@ export const getRegisterDeviceUrl = ( }; /** - * Register one of the person's phones for push notifications under the id the app made for it, or replace what that id holds. The app sends its current push token every time it starts, so a token that changed replaces the old one and the device is never registered twice. Answers 200 whether the id was new or held a registration already. A token another account holds moves only once that account signed out on the phone. Only the person themselves may register their devices, and only where this deployment sends push notifications (listNotificationTransports). + * Register one of the person's phones for push notifications under the id the app made for it, or replace what that id holds. A device is registered in one organization, the one the address names, and gets push notifications only from the person's Bots there. A person in several organizations registers the phone in each one they want notifications from, under the same id. The app sends its current push token every time it starts, so a token that changed replaces the old one and the device is never registered twice. Answers 200 whether the id was new or held a registration already. A token another account holds moves only once that account signed out on the phone. Only the person themselves may register their devices, and only where this deployment sends push notifications (listNotificationTransports). * @summary Register a device for push notifications */ export const registerDevice = async ( @@ -471,7 +471,7 @@ export const getDeleteDeviceUrl = ( }; /** - * Stop sending push notifications to one of the person's phones. The app does this when the person signs out on it, so another account can register the phone after them. Only the person themselves may remove their devices. A device already removed is not found, which a client can read as done. + * Stop sending push notifications to one of the person's phones from this organization. Its registrations in the person's other organizations stay. The app does this in each organization when the person signs out on it, so another account can register the phone after them. Only the person themselves may remove their devices. A device already removed is not found, which a client can read as done. * @summary Stop push notifications to a device */ export const deleteDevice = async ( diff --git a/app/src/lib/api/generated/devices/devices.zod.ts b/app/src/lib/api/generated/devices/devices.zod.ts index a33721f722..1b4e1195fa 100644 --- a/app/src/lib/api/generated/devices/devices.zod.ts +++ b/app/src/lib/api/generated/devices/devices.zod.ts @@ -4,7 +4,7 @@ import * as zod from "zod"; /** - * Return one page of the phones a person registered for push notifications, the first registered first. Never a device's push token. Only the person themselves may list them; there is no administrator view. A missing cursor starts at the first page and nextCursor null ends the list. + * Return one page of the phones a person registered for push notifications in this organization, the first registered first. Never a device's push token. Only the person themselves may list them; there is no administrator view. A missing cursor starts at the first page and nextCursor null ends the list. * @summary List a person's devices */ @@ -74,7 +74,7 @@ export const ListDevicesResponse = zod.object({ .describe("When OpenBot first registered the phone."), }) .describe( - "A phone that gets push notifications for the person, from every one of their Bots. Never its push token.", + "A phone that gets push notifications for the person, from every one of their Bots in the organization it is registered in. Never its push token.", ), ) .describe("The first registered first, then by id."), @@ -89,7 +89,7 @@ export const ListDevicesResponse = zod.object({ }); /** - * Register one of the person's phones for push notifications under the id the app made for it, or replace what that id holds. The app sends its current push token every time it starts, so a token that changed replaces the old one and the device is never registered twice. Answers 200 whether the id was new or held a registration already. A token another account holds moves only once that account signed out on the phone. Only the person themselves may register their devices, and only where this deployment sends push notifications (listNotificationTransports). + * Register one of the person's phones for push notifications under the id the app made for it, or replace what that id holds. A device is registered in one organization, the one the address names, and gets push notifications only from the person's Bots there. A person in several organizations registers the phone in each one they want notifications from, under the same id. The app sends its current push token every time it starts, so a token that changed replaces the old one and the device is never registered twice. Answers 200 whether the id was new or held a registration already. A token another account holds moves only once that account signed out on the phone. Only the person themselves may register their devices, and only where this deployment sends push notifications (listNotificationTransports). * @summary Register a device for push notifications */ @@ -167,12 +167,12 @@ export const RegisterDeviceResponse = zod.object({ .describe("When OpenBot first registered the phone."), }) .describe( - "A phone that gets push notifications for the person, from every one of their Bots. Never its push token.", + "A phone that gets push notifications for the person, from every one of their Bots in the organization it is registered in. Never its push token.", ), }); /** - * Stop sending push notifications to one of the person's phones. The app does this when the person signs out on it, so another account can register the phone after them. Only the person themselves may remove their devices. A device already removed is not found, which a client can read as done. + * Stop sending push notifications to one of the person's phones from this organization. Its registrations in the person's other organizations stay. The app does this in each organization when the person signs out on it, so another account can register the phone after them. Only the person themselves may remove their devices. A device already removed is not found, which a client can read as done. * @summary Stop push notifications to a device */ diff --git a/app/src/lib/api/generated/model/apiKey.ts b/app/src/lib/api/generated/model/apiKey.ts index 64d58babf1..cc48b81925 100644 --- a/app/src/lib/api/generated/model/apiKey.ts +++ b/app/src/lib/api/generated/model/apiKey.ts @@ -29,4 +29,9 @@ export interface ApiKey { * @nullable */ lastUsedAt: string | null; + /** + * The organization the key works in, when it was made for that one only (organizationOnly). Null when it works in every organization the person is a member of. Absent from a server that makes every key for every organization. + * @nullable + */ + organizationId?: string | null; } diff --git a/app/src/lib/api/generated/model/createApiKeyRequest.ts b/app/src/lib/api/generated/model/createApiKeyRequest.ts index ea6f3f7c9c..c5e51c6429 100644 --- a/app/src/lib/api/generated/model/createApiKeyRequest.ts +++ b/app/src/lib/api/generated/model/createApiKeyRequest.ts @@ -16,4 +16,6 @@ export interface CreateApiKeyRequest { * @maximum 365 */ expiresInDays?: number; + /** Whether the key works only in this organization, the one the address names. In any other organization it is refused as if the organization did not exist. Absent or false, the key works in every organization the person is a member of. */ + organizationOnly?: boolean; } diff --git a/app/src/lib/api/generated/model/deleteOrganizationHeaders.ts b/app/src/lib/api/generated/model/deleteOrganizationHeaders.ts new file mode 100644 index 0000000000..4231ef5968 --- /dev/null +++ b/app/src/lib/api/generated/model/deleteOrganizationHeaders.ts @@ -0,0 +1,13 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ +import type { IdempotencyKeyParameter } from "./idempotencyKeyParameter"; + +export type DeleteOrganizationHeaders = { + /** + * Generated by the caller for each write it means to make once. Reuse the same key and the same request for 24 hours after an uncertain response; the same key with a different request is a conflict. + * @minLength 1 + * @maxLength 128 + */ + "Idempotency-Key": IdempotencyKeyParameter; +}; diff --git a/app/src/lib/api/generated/model/device.ts b/app/src/lib/api/generated/model/device.ts index fdc5e0f8a3..ab936893cc 100644 --- a/app/src/lib/api/generated/model/device.ts +++ b/app/src/lib/api/generated/model/device.ts @@ -4,7 +4,7 @@ import type { DevicePlatform } from "./devicePlatform"; /** - * A phone that gets push notifications for the person, from every one of their Bots. Never its push token. + * A phone that gets push notifications for the person, from every one of their Bots in the organization it is registered in. Never its push token. */ export interface Device { /** The id the OpenBot app made for the phone. */ diff --git a/app/src/lib/api/generated/model/index.ts b/app/src/lib/api/generated/model/index.ts index eeb2253209..1d9ddc1430 100644 --- a/app/src/lib/api/generated/model/index.ts +++ b/app/src/lib/api/generated/model/index.ts @@ -675,6 +675,7 @@ export * from "./deleteLinkedAccountHeaders"; export * from "./deleteMemoryHeaders"; export * from "./deleteMemorySourceHeaders"; export * from "./deleteNetworkPolicyHeaders"; +export * from "./deleteOrganizationHeaders"; export * from "./deletePersonApprovalRuleHeaders"; export * from "./deleteRecorderConnectionHeaders"; export * from "./deleteReviewerGuidanceHeaders"; @@ -1074,6 +1075,7 @@ export * from "./organizationMember"; export * from "./organizationMemberPage"; export * from "./organizationMemberResponse"; export * from "./organizationNotCreatedResponse"; +export * from "./organizationNotDeletedResponse"; export * from "./organizationNotFoundResponse"; export * from "./organizationOrInvitationNotFoundResponse"; export * from "./organizationPage"; @@ -1087,6 +1089,8 @@ export * from "./organizationSettingsContextScim"; export * from "./organizationSettingValues"; export * from "./organizationSettingValuesMcpAllowlist"; export * from "./organizationSettingValuesModelAllowlist"; +export * from "./organizationStaysResponse"; +export * from "./ownerOnlyResponse"; export * from "./ownerStaysResponse"; export * from "./ownOnlyResponse"; export * from "./pagerdutyTriggerConfig"; diff --git a/app/src/lib/api/generated/model/organizationNotDeletedResponse.ts b/app/src/lib/api/generated/model/organizationNotDeletedResponse.ts new file mode 100644 index 0000000000..df75531c85 --- /dev/null +++ b/app/src/lib/api/generated/model/organizationNotDeletedResponse.ts @@ -0,0 +1,9 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ +import type { Problem } from "./problem"; + +/** + * This OpenBot could not finish deleting the organization, so it was not deleted. Asking again may work. + */ +export type OrganizationNotDeletedResponse = Problem; diff --git a/app/src/lib/api/generated/model/organizationStaysResponse.ts b/app/src/lib/api/generated/model/organizationStaysResponse.ts new file mode 100644 index 0000000000..77cb486b2b --- /dev/null +++ b/app/src/lib/api/generated/model/organizationStaysResponse.ts @@ -0,0 +1,9 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ +import type { Problem } from "./problem"; + +/** + * The organization can't be deleted: it is a person's own organization, or it is `default`. Or the Idempotency-Key was used for a different request. + */ +export type OrganizationStaysResponse = Problem; diff --git a/app/src/lib/api/generated/model/ownerOnlyResponse.ts b/app/src/lib/api/generated/model/ownerOnlyResponse.ts new file mode 100644 index 0000000000..78b2fff6a3 --- /dev/null +++ b/app/src/lib/api/generated/model/ownerOnlyResponse.ts @@ -0,0 +1,9 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ +import type { Problem } from "./problem"; + +/** + * The caller is not an owner of the organization, or holds no role in it. + */ +export type OwnerOnlyResponse = Problem; diff --git a/app/src/lib/api/generated/model/recorderConnectionGrant.ts b/app/src/lib/api/generated/model/recorderConnectionGrant.ts index 56f43e39f9..8ae974ede9 100644 --- a/app/src/lib/api/generated/model/recorderConnectionGrant.ts +++ b/app/src/lib/api/generated/model/recorderConnectionGrant.ts @@ -9,4 +9,6 @@ export interface RecorderConnectionGrant { token: string; connection: RecorderConnection; user: RecorderUser; + /** The organization the connection works in, the one the connect code was made in. The Recorder names it in every address it calls from now on. Absent from a server that keeps every connection in `default`. */ + organizationId?: string; } diff --git a/app/src/lib/api/generated/model/updatePersonRequest.ts b/app/src/lib/api/generated/model/updatePersonRequest.ts index b51f02da6d..8365e1546a 100644 --- a/app/src/lib/api/generated/model/updatePersonRequest.ts +++ b/app/src/lib/api/generated/model/updatePersonRequest.ts @@ -14,5 +14,9 @@ export interface UpdatePersonRequest { * @pattern ^[^\x00]*$ */ name?: string; + /** + * Deprecated. Change a member's role with updateOrganizationMember (PATCH /api/v2/organizations/{organizationId}/members/{personId}) instead. + * @deprecated + */ role?: AssignableRole; } diff --git a/app/src/lib/api/generated/organizations/organizations.msw.ts b/app/src/lib/api/generated/organizations/organizations.msw.ts index 4fa14fe838..48c0ba664b 100644 --- a/app/src/lib/api/generated/organizations/organizations.msw.ts +++ b/app/src/lib/api/generated/organizations/organizations.msw.ts @@ -310,6 +310,29 @@ export const getUpdateOrganizationMockHandler = ( ); }; +export const getDeleteOrganizationMockHandler = ( + overrideResponse?: + | void + | (( + info: Parameters>[0], + ) => Promise | void), + options?: RequestHandlerOptions, +) => { + return http.delete<{ organizationId: string }>( + "*/api/v2/organizations/:organizationId/profile", + async ( + info: Parameters>[0], + ) => { + if (typeof overrideResponse === "function") { + await overrideResponse(info); + } + + return new HttpResponse(null, { status: 204 }); + }, + options, + ); +}; + export const getUpdateOrganizationMemberMockHandler = ( overrideResponse?: | OrganizationMemberResponse @@ -573,6 +596,7 @@ export const getOrganizationsMock = () => [ getCreateOrganizationMockHandler(), getListOrganizationMembersMockHandler(), getUpdateOrganizationMockHandler(), + getDeleteOrganizationMockHandler(), getUpdateOrganizationMemberMockHandler(), getRemoveOrganizationMemberMockHandler(), getListOrganizationInvitationsMockHandler(), diff --git a/app/src/lib/api/generated/organizations/organizations.ts b/app/src/lib/api/generated/organizations/organizations.ts index 8101e539f0..0c718b38be 100644 --- a/app/src/lib/api/generated/organizations/organizations.ts +++ b/app/src/lib/api/generated/organizations/organizations.ts @@ -26,6 +26,7 @@ import type { CreateOrganizationInvitationRequest, CreateOrganizationRequest, DeclineInvitationHeaders, + DeleteOrganizationHeaders, ForbiddenResponse, IdempotencyConflictResponse, InvalidOrganizationInvitationResponse, @@ -47,10 +48,13 @@ import type { OrganizationMemberPage, OrganizationMemberResponse, OrganizationNotCreatedResponse, + OrganizationNotDeletedResponse, OrganizationNotFoundResponse, OrganizationOrInvitationNotFoundResponse, OrganizationPage, OrganizationResponse, + OrganizationStaysResponse, + OwnerOnlyResponse, OwnerStaysResponse, PersonNotFoundResponse, RemoveOrganizationMemberHeaders, @@ -882,6 +886,150 @@ export const useUpdateOrganization = < queryClient, ); }; +export const getDeleteOrganizationUrl = (organizationId: string) => { + return `/api/v2/organizations/${encodeURIComponent(String(organizationId))}/profile`; +}; + +/** + * Delete the organization and what is in it. Nobody can work in it again: its Bots stop, its computers are removed, an API key made for it alone stops working, and it leaves every member's list of organizations. Its members keep their accounts and their other organizations. Only an owner of this organization can. A person's own organization and `default` stay, and are refused. A repeated request with the same Idempotency-Key returns the first result. + * @summary Delete an organization + */ +export const deleteOrganization = async ( + organizationId: string, + headers: DeleteOrganizationHeaders, + options?: Parameters[1], +): Promise => { + const getHeaders = ( + h?: NonNullable, + ): Record => { + if (!h) return {}; + if (h instanceof Headers) return Object.fromEntries(h.entries()); + if (Symbol.iterator in h) { + return Object.fromEntries( + Array.from( + h as Iterable>, + (entry) => Array.from(entry) as [string, string], + ), + ); + } + const headers: Record = {}; + for (const [name, value] of Object.entries< + string | readonly string[] | undefined + >(h)) { + if (value !== undefined) headers[name] = value; + } + return headers; + }; + return apiRequest(getDeleteOrganizationUrl(organizationId), { + ...options, + method: "DELETE", + headers: { ...headers, ...getHeaders(options?.headers) }, + }); +}; + +export const getDeleteOrganizationMutationKey = () => + ["deleteOrganization"] as const; + +export const getDeleteOrganizationMutationOptions = < + TError = + | InvalidRequestResponse + | UnauthenticatedResponse + | OwnerOnlyResponse + | OrganizationNotFoundResponse + | OrganizationStaysResponse + | ServerErrorResponse + | OrganizationNotDeletedResponse + | UnexpectedErrorResponse, + TContext = unknown, +>(options?: { + mutation?: UseMutationOptions< + Awaited>, + TError, + DeleteOrganizationMutationVariables, + TContext + >; + request?: SecondParameter; +}): UseMutationOptions< + Awaited>, + TError, + DeleteOrganizationMutationVariables, + TContext +> => { + const mutationKey = getDeleteOrganizationMutationKey(); + const { mutation: mutationOptions, request: requestOptions } = options + ? options.mutation && + "mutationKey" in options.mutation && + options.mutation.mutationKey + ? options + : { ...options, mutation: { ...options.mutation, mutationKey } } + : { mutation: { mutationKey }, request: undefined }; + + const mutationFn: MutationFunction< + Awaited>, + DeleteOrganizationMutationVariables + > = (props) => { + const { organizationId, headers } = props ?? {}; + + return deleteOrganization(organizationId, headers, requestOptions); + }; + + return { mutationFn, ...mutationOptions }; +}; + +export type DeleteOrganizationMutationResult = NonNullable< + Awaited> +>; + +export type DeleteOrganizationMutationError = + | InvalidRequestResponse + | UnauthenticatedResponse + | OwnerOnlyResponse + | OrganizationNotFoundResponse + | OrganizationStaysResponse + | ServerErrorResponse + | OrganizationNotDeletedResponse + | UnexpectedErrorResponse; +export type DeleteOrganizationMutationVariables = { + organizationId: string; + headers: DeleteOrganizationHeaders; +}; + +/** + * @summary Delete an organization + */ +export const useDeleteOrganization = < + TError = + | InvalidRequestResponse + | UnauthenticatedResponse + | OwnerOnlyResponse + | OrganizationNotFoundResponse + | OrganizationStaysResponse + | ServerErrorResponse + | OrganizationNotDeletedResponse + | UnexpectedErrorResponse, + TContext = unknown, +>( + options?: { + mutation?: UseMutationOptions< + Awaited>, + TError, + DeleteOrganizationMutationVariables, + TContext + >; + request?: SecondParameter; + }, + queryClient?: QueryClient, +): UseMutationResult< + Awaited>, + TError, + DeleteOrganizationMutationVariables, + TContext +> => { + return useMutation( + getDeleteOrganizationMutationOptions(options), + queryClient, + ); +}; export const getUpdateOrganizationMemberUrl = ( organizationId: string, personId: string, diff --git a/app/src/lib/api/generated/organizations/organizations.zod.ts b/app/src/lib/api/generated/organizations/organizations.zod.ts index 946cd36f25..9ef0ab597b 100644 --- a/app/src/lib/api/generated/organizations/organizations.zod.ts +++ b/app/src/lib/api/generated/organizations/organizations.zod.ts @@ -340,6 +340,34 @@ export const UpdateOrganizationResponse = zod.object({ ), }); +/** + * Delete the organization and what is in it. Nobody can work in it again: its Bots stop, its computers are removed, an API key made for it alone stops working, and it leaves every member's list of organizations. Its members keep their accounts and their other organizations. Only an owner of this organization can. A person's own organization and `default` stay, and are refused. A repeated request with the same Idempotency-Key returns the first result. + * @summary Delete an organization + */ + +export const DeleteOrganizationParams = zod.object({ + organizationId: zod + .string() + .min(1) + .describe( + "The organization, by its id or its slug. One the caller is not a member of answers as one that does not exist, `default` included.", + ), +}); + +export const deleteOrganizationHeaderIdempotencyKeyMax = 128; + +export const DeleteOrganizationHeader = zod.object({ + "Idempotency-Key": zod + .string() + .min(1) + .max(deleteOrganizationHeaderIdempotencyKeyMax) + .describe( + "Generated by the caller for each write it means to make once. Reuse the same key and the same request for 24 hours after an uncertain response; the same key with a different request is a conflict.", + ), +}); + +export const DeleteOrganizationResponse = zod.void(); + /** * Give a member of the organization another role. An owner or an admin changes anybody between admin and member. Only an owner makes somebody an owner, or changes an owner's role, their own included, and the organization always keeps an owner: the last one cannot step down. A person's own organization keeps exactly its one owner. The members list says which roles the caller may give each member, as assignableRoles. A repeated request with the same Idempotency-Key and body returns the first result. * @summary Change a member's role diff --git a/app/src/lib/api/generated/people/people.ts b/app/src/lib/api/generated/people/people.ts index 186bb0bcc9..081ca7ba7d 100644 --- a/app/src/lib/api/generated/people/people.ts +++ b/app/src/lib/api/generated/people/people.ts @@ -507,7 +507,7 @@ export const getUpdatePersonUrl = ( }; /** - * Change what is sent and leave the rest. A person changes their own name, and nobody else's. An administrator changes anybody's role, but not their own away from administrator, and not the role of somebody the deployment's configuration names as an administrator. Asking for the role a person already has changes nothing and records nothing. + * Change what is sent and leave the rest. A person changes their own name, and nobody else's. An administrator changes anybody's role, but not their own away from administrator, and not the role of somebody the deployment's configuration names as an administrator. Asking for the role a person already has changes nothing and records nothing. role is deprecated: change a member's role with updateOrganizationMember instead. * @summary Change a person */ export const updatePerson = async ( diff --git a/app/src/lib/api/generated/people/people.zod.ts b/app/src/lib/api/generated/people/people.zod.ts index 5eed7d2e1d..43f0dccb2e 100644 --- a/app/src/lib/api/generated/people/people.zod.ts +++ b/app/src/lib/api/generated/people/people.zod.ts @@ -258,7 +258,7 @@ export const GetPersonResponse = zod.object({ }); /** - * Change what is sent and leave the rest. A person changes their own name, and nobody else's. An administrator changes anybody's role, but not their own away from administrator, and not the role of somebody the deployment's configuration names as an administrator. Asking for the role a person already has changes nothing and records nothing. + * Change what is sent and leave the rest. A person changes their own name, and nobody else's. An administrator changes anybody's role, but not their own away from administrator, and not the role of somebody the deployment's configuration names as an administrator. Asking for the role a person already has changes nothing and records nothing. role is deprecated: change a member's role with updateOrganizationMember instead. * @summary Change a person */ @@ -313,7 +313,9 @@ export const UpdatePersonBody = zod role: zod .enum(["admin", "member"]) .optional() - .describe("A role an admin can give a person."), + .describe( + "Deprecated. Change a member's role with updateOrganizationMember (PATCH /api/v2/organizations/{organizationId}/members/{personId}) instead.", + ), }) .describe("The changes to make. At least one."); diff --git a/app/src/lib/api/generated/recorder/recorder.msw.ts b/app/src/lib/api/generated/recorder/recorder.msw.ts index 866693a981..8f42abf2b9 100644 --- a/app/src/lib/api/generated/recorder/recorder.msw.ts +++ b/app/src/lib/api/generated/recorder/recorder.msw.ts @@ -77,6 +77,7 @@ export const getExchangeRecorderConnectCodeResponseMock = name: "Sam Ortiz", email: "sam@example.com", }, + organizationId: "Jq3xT9mLw2Vb8RnC5sYd0fKe", }); export const getGetRecorderIdentityResponseMock = (): RecorderIdentity => ({ diff --git a/app/src/lib/api/generated/recorder/recorder.zod.ts b/app/src/lib/api/generated/recorder/recorder.zod.ts index cc55c25e49..c2a36017e9 100644 --- a/app/src/lib/api/generated/recorder/recorder.zod.ts +++ b/app/src/lib/api/generated/recorder/recorder.zod.ts @@ -399,6 +399,12 @@ export const ExchangeRecorderConnectCodeResponse = zod.object({ .describe("Their name, or their email where they have none."), email: zod.string(), }), + organizationId: zod + .string() + .optional() + .describe( + "The organization the connection works in, the one the connect code was made in. The Recorder names it in every address it calls from now on. Absent from a server that keeps every connection in `default`.", + ), }); /** diff --git a/extension/src/shared/generated/recorder.ts b/extension/src/shared/generated/recorder.ts index 2d0d0bd092..09e87cd3b9 100644 --- a/extension/src/shared/generated/recorder.ts +++ b/extension/src/shared/generated/recorder.ts @@ -160,6 +160,8 @@ export interface RecorderConnectionGrant { token: string; connection: RecorderConnection; user: RecorderUser; + /** The organization the connection works in, the one the connect code was made in. The Recorder names it in every address it calls from now on. Absent from a server that keeps every connection in `default`. */ + organizationId?: string; } export interface RecorderIdentity { diff --git a/mobile/src/api/generated/devices/devices.ts b/mobile/src/api/generated/devices/devices.ts index bc83f2e218..a4dd8db64d 100644 --- a/mobile/src/api/generated/devices/devices.ts +++ b/mobile/src/api/generated/devices/devices.ts @@ -31,7 +31,7 @@ export const getListDevicesUrl = ( }; /** - * Return one page of the phones a person registered for push notifications, the first registered first. Never a device's push token. Only the person themselves may list them; there is no administrator view. A missing cursor starts at the first page and nextCursor null ends the list. + * Return one page of the phones a person registered for push notifications in this organization, the first registered first. Never a device's push token. Only the person themselves may list them; there is no administrator view. A missing cursor starts at the first page and nextCursor null ends the list. * @summary List a person's devices */ export const listDevices = async ( @@ -58,7 +58,7 @@ export const getRegisterDeviceUrl = ( }; /** - * Register one of the person's phones for push notifications under the id the app made for it, or replace what that id holds. The app sends its current push token every time it starts, so a token that changed replaces the old one and the device is never registered twice. Answers 200 whether the id was new or held a registration already. A token another account holds moves only once that account signed out on the phone. Only the person themselves may register their devices, and only where this deployment sends push notifications (listNotificationTransports). + * Register one of the person's phones for push notifications under the id the app made for it, or replace what that id holds. A device is registered in one organization, the one the address names, and gets push notifications only from the person's Bots there. A person in several organizations registers the phone in each one they want notifications from, under the same id. The app sends its current push token every time it starts, so a token that changed replaces the old one and the device is never registered twice. Answers 200 whether the id was new or held a registration already. A token another account holds moves only once that account signed out on the phone. Only the person themselves may register their devices, and only where this deployment sends push notifications (listNotificationTransports). * @summary Register a device for push notifications */ export const registerDevice = async ( @@ -112,7 +112,7 @@ export const getDeleteDeviceUrl = ( }; /** - * Stop sending push notifications to one of the person's phones. The app does this when the person signs out on it, so another account can register the phone after them. Only the person themselves may remove their devices. A device already removed is not found, which a client can read as done. + * Stop sending push notifications to one of the person's phones from this organization. Its registrations in the person's other organizations stay. The app does this in each organization when the person signs out on it, so another account can register the phone after them. Only the person themselves may remove their devices. A device already removed is not found, which a client can read as done. * @summary Stop push notifications to a device */ export const deleteDevice = async ( diff --git a/mobile/src/api/generated/model/device.ts b/mobile/src/api/generated/model/device.ts index fdc5e0f8a3..ab936893cc 100644 --- a/mobile/src/api/generated/model/device.ts +++ b/mobile/src/api/generated/model/device.ts @@ -4,7 +4,7 @@ import type { DevicePlatform } from "./devicePlatform"; /** - * A phone that gets push notifications for the person, from every one of their Bots. Never its push token. + * A phone that gets push notifications for the person, from every one of their Bots in the organization it is registered in. Never its push token. */ export interface Device { /** The id the OpenBot app made for the phone. */ diff --git a/mobile/src/api/generated/model/index.ts b/mobile/src/api/generated/model/index.ts index 00e9c06ad1..c47e5deec2 100644 --- a/mobile/src/api/generated/model/index.ts +++ b/mobile/src/api/generated/model/index.ts @@ -393,6 +393,7 @@ export * from "./organizationMember"; export * from "./organizationMemberPage"; export * from "./organizationMemberResponse"; export * from "./organizationNotCreatedResponse"; +export * from "./organizationNotDeletedResponse"; export * from "./organizationNotFoundResponse"; export * from "./organizationOrInvitationNotFoundResponse"; export * from "./organizationPage"; @@ -406,6 +407,8 @@ export * from "./organizationSettingsContextScim"; export * from "./organizationSettingValues"; export * from "./organizationSettingValuesMcpAllowlist"; export * from "./organizationSettingValuesModelAllowlist"; +export * from "./organizationStaysResponse"; +export * from "./ownerOnlyResponse"; export * from "./ownerStaysResponse"; export * from "./ownOnlyResponse"; export * from "./payloadTooLargeResponse"; diff --git a/mobile/src/api/generated/model/organizationNotDeletedResponse.ts b/mobile/src/api/generated/model/organizationNotDeletedResponse.ts new file mode 100644 index 0000000000..df75531c85 --- /dev/null +++ b/mobile/src/api/generated/model/organizationNotDeletedResponse.ts @@ -0,0 +1,9 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ +import type { Problem } from "./problem"; + +/** + * This OpenBot could not finish deleting the organization, so it was not deleted. Asking again may work. + */ +export type OrganizationNotDeletedResponse = Problem; diff --git a/mobile/src/api/generated/model/organizationStaysResponse.ts b/mobile/src/api/generated/model/organizationStaysResponse.ts new file mode 100644 index 0000000000..77cb486b2b --- /dev/null +++ b/mobile/src/api/generated/model/organizationStaysResponse.ts @@ -0,0 +1,9 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ +import type { Problem } from "./problem"; + +/** + * The organization can't be deleted: it is a person's own organization, or it is `default`. Or the Idempotency-Key was used for a different request. + */ +export type OrganizationStaysResponse = Problem; diff --git a/mobile/src/api/generated/model/ownerOnlyResponse.ts b/mobile/src/api/generated/model/ownerOnlyResponse.ts new file mode 100644 index 0000000000..78b2fff6a3 --- /dev/null +++ b/mobile/src/api/generated/model/ownerOnlyResponse.ts @@ -0,0 +1,9 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ +import type { Problem } from "./problem"; + +/** + * The caller is not an owner of the organization, or holds no role in it. + */ +export type OwnerOnlyResponse = Problem; diff --git a/mobile/src/api/generated/organizations/organizations.ts b/mobile/src/api/generated/organizations/organizations.ts index 9b3d040be9..d00d81415a 100644 --- a/mobile/src/api/generated/organizations/organizations.ts +++ b/mobile/src/api/generated/organizations/organizations.ts @@ -181,6 +181,24 @@ export const updateOrganization = async ( ); }; +export const getDeleteOrganizationUrl = (organizationId: string) => { + return `/api/v2/organizations/${encodeURIComponent(String(organizationId))}/profile`; +}; + +/** + * Delete the organization and what is in it. Nobody can work in it again: its Bots stop, its computers are removed, an API key made for it alone stops working, and it leaves every member's list of organizations. Its members keep their accounts and their other organizations. Only an owner of this organization can. A person's own organization and `default` stay, and are refused. A repeated request with the same Idempotency-Key returns the first result. + * @summary Delete an organization + */ +export const deleteOrganization = async ( + organizationId: string, + options?: Parameters[1], +): Promise => { + return apiRequest(getDeleteOrganizationUrl(organizationId), { + ...options, + method: "DELETE", + }); +}; + export const getUpdateOrganizationMemberUrl = ( organizationId: string, personId: string, From ad899e996dc4e99915d52417d17e4ed8bbc96779 Mon Sep 17 00:00:00 2001 From: David McKay Date: Thu, 19 Nov 2026 13:25:48 -0800 Subject: [PATCH 2/4] API: an API key acts only in the organization it was made in Drops organizationOnly from a new key: every key is bound to the organization it was made in, and a key with no binding acts in default. ApiKey.organizationId says which, and createApiKey, the apiKey scheme and the changelog say so. --- CHANGELOG.md | 6 +++--- api/openapi.yaml | 16 ++++++-------- api/openapi/accounts.yaml | 21 ++++++------------- api/openapi/common.yaml | 15 +++++++------ api/openapi/organizations.yaml | 4 ++-- .../lib/api/generated/api-keys/api-keys.ts | 2 +- .../api/generated/api-keys/api-keys.zod.ts | 12 +++-------- app/src/lib/api/generated/model/apiKey.ts | 2 +- .../generated/model/createApiKeyRequest.ts | 2 -- .../generated/organizations/organizations.ts | 2 +- .../organizations/organizations.zod.ts | 2 +- .../generated/organizations/organizations.ts | 2 +- 12 files changed, 32 insertions(+), 54 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f36156649..92d2a8c0cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,9 +21,9 @@ Newest first. `Unreleased` is what is on `main` and not yet tagged. - **Delete an organization.** `DELETE /api/v2/organizations/{organizationId}/profile` (`deleteOrganization`) deletes an organization and what is in it, for an owner of it. A person's own organization and `default` stay, refused with 409 `CONFLICT`. -- **API keys for one organization.** `organizationOnly` on a new API key makes it work only in the - organization the address names; without it a key works in every organization its person is in, - as before. A key in an answer carries `organizationId`, null for a key that works everywhere. +- **An API key acts in the organization it was made in.** A key made in one organization is refused + in any other, as if that organization did not exist. A key in an answer carries `organizationId`. + A key made before this release acts in `default`. - **The realtime socket at an address that names the organization.** `/api/v2/organizations/{organizationId}/realtime/websocket` relays the same socket as `/api/intelligence/client/websocket`, for a caller who is a member of that organization. diff --git a/api/openapi.yaml b/api/openapi.yaml index fa8a404a78..6c045ae0b0 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -10,7 +10,7 @@ info: An OpenBot install holds one or more organizations, and a person may be a member of several. Where an install allows more than one, everybody has an organization of their own, made for them when they first sign in, and joins others by invitation. Otherwise, and on an install for one person with no sign-in, everybody works in the organization `default`. organizationId is an organization's id or its slug, and the caller must be a member of it: an organization the caller is not in answers exactly as one that does not exist, `default` included. - A program of your own signs its requests in one of two ways. An API key acts as the person who made it, in every organization they are a member of, like a personal access token: the address names the organization each request is for. Keys start `obk_` and are sent as `Authorization: Bearer ` or in an `x-api-key` header, on /api/v2 and on the socket a join token is spent on (createConversationJoinToken). To get a first key, sign in to OpenBot's web app, open Settings, then API keys, and create one. The key is shown once. Only a person signed in to the web app can make or delete keys: a key or an app's sign-in cannot. An app that signs people in uses OAuth 2.1 instead, described under the appOAuth security scheme: its client ids, redirect addresses, endpoints, how long tokens last and the four addresses outside /api/v2 a token also works at. + A program of your own signs its requests in one of two ways. An API key acts as the person who made it, in the organization it was made in, like a personal access token: the address names the organization each request is for. Keys start `obk_` and are sent as `Authorization: Bearer ` or in an `x-api-key` header, on /api/v2 and on the socket a join token is spent on (createConversationJoinToken). To get a first key, sign in to OpenBot's web app, open Settings, then API keys, and create one. The key is shown once. Only a person signed in to the web app can make or delete keys: a key or an app's sign-in cannot. An app that signs people in uses OAuth 2.1 instead, described under the appOAuth security scheme: its client ids, redirect addresses, endpoints, how long tokens last and the four addresses outside /api/v2 a token also works at. An install for one person on one computer has no sign-in. It signs nobody in, so it has neither OAuth nor API keys, and the operations that manage keys and sessions answer 503 with the code SIGN_IN_UNAVAILABLE. @@ -36,7 +36,7 @@ tags: - name: Identity providers description: The companies' own identity providers registered for single sign-on, by email domain. Only an administrator manages them. - name: API keys - description: The keys a person makes for automation. A key acts as them, in every organization they are a member of, on the API, and only a person signed in to OpenBot can make or manage one. + description: The keys a person makes for automation. A key acts as them, in the organization it was made in, on the API, and only a person signed in to OpenBot can make or manage one. - name: Sessions description: Where a person is signed in to OpenBot, so they can see each browser and device and sign one out. - name: Organization settings @@ -1207,7 +1207,7 @@ paths: - API keys operationId: createApiKey summary: Make an API key - description: 'Make an API key that acts as the person on the API: in this organization only when organizationOnly is true, otherwise in every organization they are a member of. The key itself is in this answer and never again: OpenBot keeps only a hash of it. Only the person themselves may make one, signed in to OpenBot: a key can never make another key, and neither can an app''s sign-in. A key ends when it expires, when it is deleted, or when an administrator removes the person.' + description: 'Make an API key that acts as the person on the API, in this organization only: the one it was made in. In any other organization it is refused as if the organization did not exist. The key itself is in this answer and never again: OpenBot keeps only a hash of it. Only the person themselves may make one, signed in to OpenBot: a key can never make another key, and neither can an app''s sign-in. A key ends when it expires, when it is deleted, or when an administrator removes the person.' security: - webSession: [] parameters: @@ -1223,7 +1223,6 @@ paths: value: name: Nightly report expiresInDays: 90 - organizationOnly: true responses: '201': description: The key, shown this once. @@ -10473,7 +10472,7 @@ paths: - Organizations operationId: deleteOrganization summary: Delete an organization - description: 'Delete the organization and what is in it. Nobody can work in it again: its Bots stop, its computers are removed, an API key made for it alone stops working, and it leaves every member''s list of organizations. Its members keep their accounts and their other organizations. Only an owner of this organization can. A person''s own organization and `default` stay, and are refused. A repeated request with the same Idempotency-Key returns the first result.' + description: 'Delete the organization and what is in it. Nobody can work in it again: its Bots stop, its computers are removed, the API keys made in it stop working, and it leaves every member''s list of organizations. Its members keep their accounts and their other organizations. Only an owner of this organization can. A person''s own organization and `default` stay, and are refused. A repeated request with the same Idempotency-Key returns the first result.' security: - webSession: [] - appOAuth: @@ -20351,7 +20350,7 @@ components: type: http scheme: bearer bearerFormat: OpenBot API key - description: 'Automation. An API key acts as the person who created it, like a personal access token: in every organization they are a member of, or in one organization only when it was made for that one (organizationOnly). The address of each request names the organization, and one the key does not work in answers not found. A key starts `obk_` and is sent as `Authorization: Bearer ` or in an `x-api-key` header, on /api/v2 (the relayed realtime socket at `/api/v2/organizations/{organizationId}/realtime/websocket` included) and on the relayed realtime socket at `/api/intelligence/client/websocket`, where a join token the key made is spent (createConversationJoinToken). A person makes one in the web app, signed in, under Settings, then API keys (createApiKey).' + description: 'Automation. An API key acts as the person who created it, like a personal access token, in the one organization it was made in. The address of each request names the organization, and any other answers not found. A key starts `obk_` and is sent as `Authorization: Bearer ` or in an `x-api-key` header, on /api/v2 (the relayed realtime socket at `/api/v2/organizations/{organizationId}/realtime/websocket` included) and on the relayed realtime socket at `/api/intelligence/client/websocket`, where a join token the key made is spent (createConversationJoinToken). A person makes one in the web app, signed in, under Settings, then API keys (createApiKey).' recorderConnection: type: http scheme: bearer @@ -22012,7 +22011,7 @@ components: type: - string - 'null' - description: The organization the key works in, when it was made for that one only (organizationOnly). Null when it works in every organization the person is a member of. Absent from a server that makes every key for every organization. + description: 'The organization this key acts in: the one it was made in. Null for a key made before keys were bound to an organization, which acts in `default`. Absent from an older server.' ApiKeyPage: type: object required: @@ -22048,9 +22047,6 @@ components: minimum: 1 maximum: 365 description: Days until the key stops working. Absent, it never expires. - organizationOnly: - type: boolean - description: Whether the key works only in this organization, the one the address names. In any other organization it is refused as if the organization did not exist. Absent or false, the key works in every organization the person is a member of. CreatedApiKey: type: object required: diff --git a/api/openapi/accounts.yaml b/api/openapi/accounts.yaml index 19c5ab4796..bb402e3272 100644 --- a/api/openapi/accounts.yaml +++ b/api/openapi/accounts.yaml @@ -611,9 +611,9 @@ paths: operationId: createApiKey summary: Make an API key description: >- - Make an API key that acts as the person on the API: in this - organization only when organizationOnly is true, otherwise in every - organization they are a member of. The key itself is in this answer and never again: + Make an API key that acts as the person on the API, in this + organization only: the one it was made in. In any other organization + it is refused as if the organization did not exist. The key itself is in this answer and never again: OpenBot keeps only a hash of it. Only the person themselves may make one, signed in to OpenBot: a key can never make another key, and neither can an app's sign-in. A key ends when it expires, when it is @@ -633,7 +633,6 @@ paths: value: name: Nightly report expiresInDays: 90 - organizationOnly: true responses: '201': description: The key, shown this once. @@ -1470,10 +1469,9 @@ components: organizationId: type: [string, 'null'] description: >- - The organization the key works in, when it was made for that one - only (organizationOnly). Null when it works in every organization - the person is a member of. Absent from a server that makes every - key for every organization. + The organization this key acts in: the one it was made in. Null + for a key made before keys were bound to an organization, which + acts in `default`. Absent from an older server. ApiKeyPage: type: object required: [apiKeys, nextCursor] @@ -1506,13 +1504,6 @@ components: minimum: 1 maximum: 365 description: Days until the key stops working. Absent, it never expires. - organizationOnly: - type: boolean - description: >- - Whether the key works only in this organization, the one the - address names. In any other organization it is refused as if the - organization did not exist. Absent or false, the key works in - every organization the person is a member of. CreatedApiKey: type: object required: [apiKey, key] diff --git a/api/openapi/common.yaml b/api/openapi/common.yaml index 8845be7b05..39214a7ffb 100644 --- a/api/openapi/common.yaml +++ b/api/openapi/common.yaml @@ -37,9 +37,9 @@ info: A program of your own signs its requests in one of two ways. An API key - acts as the person who made it, in every organization they are a member - of, like a personal access token: the address names the organization - each request is for. Keys start `obk_` and are sent as + acts as the person who made it, in the organization it was made in, like + a personal access token: the address names the organization each + request is for. Keys start `obk_` and are sent as `Authorization: Bearer ` or in an `x-api-key` header, on /api/v2 and on the socket a join token is spent on (createConversationJoinToken). To get a first key, sign in to OpenBot's web app, open Settings, then API @@ -87,7 +87,7 @@ tags: - { name: People, description: "The people in the organization: who they are, what they may do, and what is theirs alone (their standing instructions, preferences and first-run onboarding). An administrator sees everybody; anybody else sees themselves, as me." } - { name: Linked accounts, description: "A person's accounts at other services, such as Slack and GitHub, that OpenBot knows are theirs, so a Bot answering there knows who it is talking to." } - { name: Identity providers, description: "The companies' own identity providers registered for single sign-on, by email domain. Only an administrator manages them." } - - { name: API keys, description: "The keys a person makes for automation. A key acts as them, in every organization they are a member of, on the API, and only a person signed in to OpenBot can make or manage one." } + - { name: API keys, description: "The keys a person makes for automation. A key acts as them, in the organization it was made in, on the API, and only a person signed in to OpenBot can make or manage one." } - { name: Sessions, description: "Where a person is signed in to OpenBot, so they can see each browser and device and sign one out." } - { name: Organization settings, description: "What an administrator sets for everybody, and what this OpenBot offers: sign-in, recording, idle computers, allowlists, the setup checklist, and which models Bots ran on." } - { name: Capabilities, description: "The permission switches that decide what people may do, set for the organization, a role or a directory group, and each person's answer." } @@ -644,10 +644,9 @@ components: bearerFormat: OpenBot API key description: >- Automation. An API key acts as the person who created it, like a - personal access token: in every organization they are a member of, - or in one organization only when it was made for that one - (organizationOnly). The address of each request names the - organization, and one the key does not work in answers not found. A + personal access token, in the one organization it was made in. The + address of each request names the organization, and any other + answers not found. A key starts `obk_` and is sent as `Authorization: Bearer ` or in an `x-api-key` header, on /api/v2 (the relayed realtime socket at diff --git a/api/openapi/organizations.yaml b/api/openapi/organizations.yaml index 11c4adf40a..abf4cb34d5 100644 --- a/api/openapi/organizations.yaml +++ b/api/openapi/organizations.yaml @@ -190,8 +190,8 @@ paths: summary: Delete an organization description: >- Delete the organization and what is in it. Nobody can work in it - again: its Bots stop, its computers are removed, an API key made for - it alone stops working, and it leaves every member's list of + again: its Bots stop, its computers are removed, the API keys made + in it stop working, and it leaves every member's list of organizations. Its members keep their accounts and their other organizations. Only an owner of this organization can. A person's own organization and `default` stay, and are refused. A repeated request diff --git a/app/src/lib/api/generated/api-keys/api-keys.ts b/app/src/lib/api/generated/api-keys/api-keys.ts index 2725f26fa0..261e253c43 100644 --- a/app/src/lib/api/generated/api-keys/api-keys.ts +++ b/app/src/lib/api/generated/api-keys/api-keys.ts @@ -313,7 +313,7 @@ export const getCreateApiKeyUrl = ( }; /** - * Make an API key that acts as the person on the API: in this organization only when organizationOnly is true, otherwise in every organization they are a member of. The key itself is in this answer and never again: OpenBot keeps only a hash of it. Only the person themselves may make one, signed in to OpenBot: a key can never make another key, and neither can an app's sign-in. A key ends when it expires, when it is deleted, or when an administrator removes the person. + * Make an API key that acts as the person on the API, in this organization only: the one it was made in. In any other organization it is refused as if the organization did not exist. The key itself is in this answer and never again: OpenBot keeps only a hash of it. Only the person themselves may make one, signed in to OpenBot: a key can never make another key, and neither can an app's sign-in. A key ends when it expires, when it is deleted, or when an administrator removes the person. * @summary Make an API key */ export const createApiKey = async ( diff --git a/app/src/lib/api/generated/api-keys/api-keys.zod.ts b/app/src/lib/api/generated/api-keys/api-keys.zod.ts index f26f16781e..4cd9a89864 100644 --- a/app/src/lib/api/generated/api-keys/api-keys.zod.ts +++ b/app/src/lib/api/generated/api-keys/api-keys.zod.ts @@ -84,7 +84,7 @@ export const ListApiKeysResponse = zod.object({ .string() .nullish() .describe( - "The organization the key works in, when it was made for that one only (organizationOnly). Null when it works in every organization the person is a member of. Absent from a server that makes every key for every organization.", + "The organization this key acts in: the one it was made in. Null for a key made before keys were bound to an organization, which acts in `default`. Absent from an older server.", ), }) .describe("An API key a person made. Never the key itself."), @@ -101,7 +101,7 @@ export const ListApiKeysResponse = zod.object({ }); /** - * Make an API key that acts as the person on the API: in this organization only when organizationOnly is true, otherwise in every organization they are a member of. The key itself is in this answer and never again: OpenBot keeps only a hash of it. Only the person themselves may make one, signed in to OpenBot: a key can never make another key, and neither can an app's sign-in. A key ends when it expires, when it is deleted, or when an administrator removes the person. + * Make an API key that acts as the person on the API, in this organization only: the one it was made in. In any other organization it is refused as if the organization did not exist. The key itself is in this answer and never again: OpenBot keeps only a hash of it. Only the person themselves may make one, signed in to OpenBot: a key can never make another key, and neither can an app's sign-in. A key ends when it expires, when it is deleted, or when an administrator removes the person. * @summary Make an API key */ @@ -156,12 +156,6 @@ export const CreateApiKeyBody = zod.object({ .max(createApiKeyBodyExpiresInDaysMax) .optional() .describe("Days until the key stops working. Absent, it never expires."), - organizationOnly: zod - .boolean() - .optional() - .describe( - "Whether the key works only in this organization, the one the address names. In any other organization it is refused as if the organization did not exist. Absent or false, the key works in every organization the person is a member of.", - ), }); export const CreateApiKeyResponse = zod.object({ @@ -186,7 +180,7 @@ export const CreateApiKeyResponse = zod.object({ .string() .nullish() .describe( - "The organization the key works in, when it was made for that one only (organizationOnly). Null when it works in every organization the person is a member of. Absent from a server that makes every key for every organization.", + "The organization this key acts in: the one it was made in. Null for a key made before keys were bound to an organization, which acts in `default`. Absent from an older server.", ), }) .describe("An API key a person made. Never the key itself."), diff --git a/app/src/lib/api/generated/model/apiKey.ts b/app/src/lib/api/generated/model/apiKey.ts index cc48b81925..db56d103ba 100644 --- a/app/src/lib/api/generated/model/apiKey.ts +++ b/app/src/lib/api/generated/model/apiKey.ts @@ -30,7 +30,7 @@ export interface ApiKey { */ lastUsedAt: string | null; /** - * The organization the key works in, when it was made for that one only (organizationOnly). Null when it works in every organization the person is a member of. Absent from a server that makes every key for every organization. + * The organization this key acts in: the one it was made in. Null for a key made before keys were bound to an organization, which acts in `default`. Absent from an older server. * @nullable */ organizationId?: string | null; diff --git a/app/src/lib/api/generated/model/createApiKeyRequest.ts b/app/src/lib/api/generated/model/createApiKeyRequest.ts index c5e51c6429..ea6f3f7c9c 100644 --- a/app/src/lib/api/generated/model/createApiKeyRequest.ts +++ b/app/src/lib/api/generated/model/createApiKeyRequest.ts @@ -16,6 +16,4 @@ export interface CreateApiKeyRequest { * @maximum 365 */ expiresInDays?: number; - /** Whether the key works only in this organization, the one the address names. In any other organization it is refused as if the organization did not exist. Absent or false, the key works in every organization the person is a member of. */ - organizationOnly?: boolean; } diff --git a/app/src/lib/api/generated/organizations/organizations.ts b/app/src/lib/api/generated/organizations/organizations.ts index 0c718b38be..14b4d5227e 100644 --- a/app/src/lib/api/generated/organizations/organizations.ts +++ b/app/src/lib/api/generated/organizations/organizations.ts @@ -891,7 +891,7 @@ export const getDeleteOrganizationUrl = (organizationId: string) => { }; /** - * Delete the organization and what is in it. Nobody can work in it again: its Bots stop, its computers are removed, an API key made for it alone stops working, and it leaves every member's list of organizations. Its members keep their accounts and their other organizations. Only an owner of this organization can. A person's own organization and `default` stay, and are refused. A repeated request with the same Idempotency-Key returns the first result. + * Delete the organization and what is in it. Nobody can work in it again: its Bots stop, its computers are removed, the API keys made in it stop working, and it leaves every member's list of organizations. Its members keep their accounts and their other organizations. Only an owner of this organization can. A person's own organization and `default` stay, and are refused. A repeated request with the same Idempotency-Key returns the first result. * @summary Delete an organization */ export const deleteOrganization = async ( diff --git a/app/src/lib/api/generated/organizations/organizations.zod.ts b/app/src/lib/api/generated/organizations/organizations.zod.ts index 9ef0ab597b..291bfcf16a 100644 --- a/app/src/lib/api/generated/organizations/organizations.zod.ts +++ b/app/src/lib/api/generated/organizations/organizations.zod.ts @@ -341,7 +341,7 @@ export const UpdateOrganizationResponse = zod.object({ }); /** - * Delete the organization and what is in it. Nobody can work in it again: its Bots stop, its computers are removed, an API key made for it alone stops working, and it leaves every member's list of organizations. Its members keep their accounts and their other organizations. Only an owner of this organization can. A person's own organization and `default` stay, and are refused. A repeated request with the same Idempotency-Key returns the first result. + * Delete the organization and what is in it. Nobody can work in it again: its Bots stop, its computers are removed, the API keys made in it stop working, and it leaves every member's list of organizations. Its members keep their accounts and their other organizations. Only an owner of this organization can. A person's own organization and `default` stay, and are refused. A repeated request with the same Idempotency-Key returns the first result. * @summary Delete an organization */ diff --git a/mobile/src/api/generated/organizations/organizations.ts b/mobile/src/api/generated/organizations/organizations.ts index d00d81415a..9b896fd8b8 100644 --- a/mobile/src/api/generated/organizations/organizations.ts +++ b/mobile/src/api/generated/organizations/organizations.ts @@ -186,7 +186,7 @@ export const getDeleteOrganizationUrl = (organizationId: string) => { }; /** - * Delete the organization and what is in it. Nobody can work in it again: its Bots stop, its computers are removed, an API key made for it alone stops working, and it leaves every member's list of organizations. Its members keep their accounts and their other organizations. Only an owner of this organization can. A person's own organization and `default` stay, and are refused. A repeated request with the same Idempotency-Key returns the first result. + * Delete the organization and what is in it. Nobody can work in it again: its Bots stop, its computers are removed, the API keys made in it stop working, and it leaves every member's list of organizations. Its members keep their accounts and their other organizations. Only an owner of this organization can. A person's own organization and `default` stay, and are refused. A repeated request with the same Idempotency-Key returns the first result. * @summary Delete an organization */ export const deleteOrganization = async ( From 1a77b372483464044c825baf37820770b768de50 Mon Sep 17 00:00:00 2001 From: David McKay Date: Thu, 19 Nov 2026 13:41:17 -0800 Subject: [PATCH 3/4] Support window: hold the tree's first real deprecation without reaching the network in tests The support-window tests assumed the spec deprecates nothing, and their run of the check looked every release's spec up by tag, fetching each from GitHub once the spec marks something deprecated: it timed out in CI. SUPPORT_WINDOW_RELEASE_SPECS reads release specs from a directory instead, which the test points at its fixtures, and the tests now find the real deprecation of updatePerson's role. --- scripts/support-window.ts | 15 ++++++++++++++- tests/support-window.test.ts | 33 +++++++++++++++++++++++++++------ 2 files changed, 41 insertions(+), 7 deletions(-) diff --git a/scripts/support-window.ts b/scripts/support-window.ts index c5458ee5af..3ee1f94756 100644 --- a/scripts/support-window.ts +++ b/scripts/support-window.ts @@ -297,8 +297,21 @@ async function publishedMinimums(root: string): Promise< : undefined; } -/** A release's spec, fetched by its tag when this checkout lacks it. Undefined if it has none. */ +/** + * A release's spec, fetched by its tag when this checkout lacks it. Undefined if it has none. + * + * With `SUPPORT_WINDOW_RELEASE_SPECS` set to a directory, each release's spec is read from + * `/.yaml` instead, and a release with no file there has none: the tests hold this + * tree to a fixed set of releases without reaching the network. + */ function releaseSpec(root: string, tag: string): unknown | undefined { + const specs = process.env.SUPPORT_WINDOW_RELEASE_SPECS; + if (specs) { + const file = join(specs, `${tag}.yaml`); + return existsSync(file) + ? parse(readFileSync(file, "utf8"), { maxAliasCount: -1 }) + : undefined; + } const git = (...args: string[]) => execFileSync("git", ["-C", root, ...args], { encoding: "utf8", diff --git a/tests/support-window.test.ts b/tests/support-window.test.ts index 746bf80ea9..f66232a9ba 100644 --- a/tests/support-window.test.ts +++ b/tests/support-window.test.ts @@ -180,14 +180,23 @@ describe("a deprecation's sunset", () => { return copy; }; - test("today's spec deprecates nothing, so nothing is held", () => { - expect(deprecations(spec)).toEqual([]); + test("is found on each element today's spec marks, a request body's property included, each with a sunset date", () => { + const today = deprecations(spec); + expect(today.map((found) => found.where)).toContain( + "/components/schemas/UpdatePersonRequest/properties/role", + ); + for (const { sunset } of today) + expect(String(sunset)).toMatch(/^\d{4}-\d{2}-\d{2}$/); }); test("is found on the operation that names it", () => { - expect(deprecations(deprecated("2027-12-01"))).toEqual([ - { where, sunset: "2027-12-01" }, - ]); + expect(deprecations(spec)).not.toContainEqual( + expect.objectContaining({ where }), + ); + expect(deprecations(deprecated("2027-12-01"))).toContainEqual({ + where, + sunset: "2027-12-01", + }); }); test("is required, and must be a date", () => { @@ -263,7 +272,19 @@ test("this tree holds the window", () => { ), ], { - env: { ...process.env, SUPPORT_WINDOW_NOW: RELEASE_DAY.toISOString() }, + env: { + ...process.env, + SUPPORT_WINDOW_NOW: RELEASE_DAY.toISOString(), + // The releases' specs are read from the fixtures, never fetched: a deprecation in this + // tree's spec makes the check look each release's spec up, and a test never reaches the + // network. No release spec is kept there, so a deprecation is served from the release + // being prepared. + SUPPORT_WINDOW_RELEASE_SPECS: join( + import.meta.dir, + "fixtures", + "support-window", + ), + }, stdout: "pipe", stderr: "pipe", }, From a0bfbd7b53e170803b05dfd29798ffe6d1540889 Mon Sep 17 00:00:00 2001 From: David McKay Date: Thu, 19 Nov 2026 13:42:55 -0800 Subject: [PATCH 4/4] Apps work in one organization at a time: delete an organization, keys and events by organization, the phone's switcher, the Recorder's organization Web: an owner deletes an organization from its settings after typing its name; the server's refusal (a person's own organization, default, an unfinished delete) is shown in its own words, and the person moves to another of their organizations. Each API key's row names the organization it acts in (a key from before binding acts in default), and Create says where the key will work. Conversation events about another organization are ignored; events that name none are taken as before. Phone: a switcher on Home for a person in several organizations. The pick is kept on the phone and used while it is still one of theirs. Every signed-in request names its organization in OpenBot-Organization, the deployment is read in the person's organization once signed in rather than default, and signing out removes the device from each organization. Recorder: the connection keeps the organization its grant names and every request after the connect goes there, falling back to default when the grant names none. --- .../organization-settings-page.tsx | 130 ++++++ app/src/components/settings/api-keys.tsx | 47 +- app/src/lib/channels/use-channel-events.ts | 32 +- app/src/lib/organizations/mutations.ts | 77 ++- app/tests/api-keys-screen.test.tsx | 100 ++++ .../conversation-events-organization.test.tsx | 211 +++++++++ app/tests/organization-delete.test.tsx | 438 ++++++++++++++++++ extension/src/background/activity.ts | 16 +- extension/src/background/connection.ts | 29 +- extension/src/background/launcher.ts | 13 +- extension/src/background/recording.ts | 35 +- extension/src/shared/openbot-client.ts | 26 +- extension/src/shared/storage.ts | 3 + extension/tests/openbot-client.test.ts | 36 +- extension/tests/recorder-organization.test.ts | 147 ++++++ mobile/app/index.tsx | 39 +- mobile/src/api/index.ts | 3 + mobile/src/api/request.ts | 80 +++- mobile/src/auth.ts | 11 + mobile/src/notifications.ts | 22 +- mobile/src/organization.ts | 124 ++++- mobile/src/version-check.ts | 4 +- mobile/tests/generated-client.test.ts | 122 ++++- shared/openbot-browser.ts | 2 + tests/mobile-organization.test.ts | 25 + 25 files changed, 1653 insertions(+), 119 deletions(-) create mode 100644 app/tests/conversation-events-organization.test.tsx create mode 100644 app/tests/organization-delete.test.tsx create mode 100644 extension/tests/recorder-organization.test.ts diff --git a/app/src/components/organizations/organization-settings-page.tsx b/app/src/components/organizations/organization-settings-page.tsx index 4d76a6e073..da3aab8dd0 100644 --- a/app/src/components/organizations/organization-settings-page.tsx +++ b/app/src/components/organizations/organization-settings-page.tsx @@ -42,6 +42,7 @@ import { currentUserQueryOptions } from "@/lib/auth/queries"; import { isOrganizationAdmin, type KnownRole } from "@/lib/auth/roles"; import { changeMemberRoleMutationOptions, + deleteOrganizationMutationOptions, leaveOrganizationMutationOptions, removeOrganizationMemberMutationOptions, renameOrganizationMutationOptions, @@ -102,6 +103,9 @@ export function OrganizationSettingsPage() { {canManage ? ( ) : null} + {organization.role === "owner" ? ( + + ) : null} ); } @@ -653,3 +657,129 @@ function LeaveOrganizationDialog({ ); } + +/** + * Delete the organization, for its owner. Asked in a dialog that wants the organization's name typed, + * because everything in it goes for everybody and can't come back. The server decides whether it can + * go: a person's own organization and the one that comes with OpenBot stay, and its refusal is said + * in its own words in the dialog. + */ +function DeleteOrganizationSection({ + organization, +}: { + organization: OrganizationSummary; +}) { + const [open, setOpen] = useState(false); + return ( + + + + + ); +} + +function DeleteOrganizationDialog({ + onOpenChange, + open, + organization, +}: { + onOpenChange: (open: boolean) => void; + open: boolean; + organization: OrganizationSummary; +}) { + const formId = useId(); + const navigate = useNavigate(); + const remove = useMutation( + deleteOrganizationMutationOptions(queryClient, async () => { + await navigate({ to: "/" }); + }), + ); + const { reset } = remove; + const [typed, setTyped] = useState(""); + const confirmed = typed.trim() === organization.name.trim(); + + // Each opening starts empty, and a refusal from the last one is not news about this one. + useEffect(() => { + if (open) { + setTyped(""); + reset(); + } + }, [open, reset]); + + const confirm = () => { + if (!confirmed || remove.isPending) return; + remove.mutate(organization.id, { onSuccess: () => onOpenChange(false) }); + }; + + return ( + + + + Delete {organization.name}? + + Its Bots stop, and its conversations and computers are deleted for + everyone in it. You can't undo this. + + + +
{ + event.preventDefault(); + confirm(); + }} + > + + + Type {organization.name} to confirm + + { + setTyped(event.target.value); + reset(); + }} + value={typed} + /> + +
+ {remove.error ? ( +

+ {remove.error.message} +

+ ) : null} +
+ + + + +
+
+ ); +} diff --git a/app/src/components/settings/api-keys.tsx b/app/src/components/settings/api-keys.tsx index 6ba328092a..7fc1059699 100644 --- a/app/src/components/settings/api-keys.tsx +++ b/app/src/components/settings/api-keys.tsx @@ -12,6 +12,7 @@ import { Dialog, DialogBody, DialogContent, + DialogDescription, DialogFooter, DialogHeader, DialogTitle, @@ -35,6 +36,7 @@ import { import { type ApiKey, apiKeyListQueryOptions } from "@/lib/api-keys/queries"; import { desktopConnectionQueryOptions } from "@/lib/desktop/queries"; import { desktopShell } from "@/lib/desktop/shell"; +import { useOrganizationChoices } from "@/lib/organizations/queries"; import { relativeTime } from "@/lib/relative-time"; import { queryClient } from "@/query-client"; import { copyText } from "./linked-accounts"; @@ -42,6 +44,9 @@ import { copyText } from "./linked-accounts"; /** The longest name the API takes (`CreateApiKeyRequest.name`). */ const NAME_LIMIT = 32; +/** The organization every install has, where a key made before keys were bound to one acts. */ +const DEFAULT_ORGANIZATION_ID = "default"; + const day = new Intl.DateTimeFormat(undefined, { dateStyle: "medium" }); /** What a key is called on screen. The API allows a key with no name; the screen never makes one. */ @@ -49,6 +54,22 @@ function keyName(apiKey: ApiKey): string { return apiKey.name?.trim() || "Unnamed key"; } +/** + * The organization a key acts in, by name, for its row: the one it was made in (`organizationId`), or `default` for a + * key made before keys were bound to one (null). Null when there is nothing to say: the server names no organization + * (one older than organizations), the person's organizations are not listed (the personal edition has one), or the + * key's is not among them. + */ +export function apiKeyOrganization( + apiKey: ApiKey, + organizations: readonly { id: string; name: string }[] | undefined, +): string | null { + if (apiKey.organizationId === undefined || !organizations) return null; + // A key made before keys were bound to an organization acts in `default`. + const id = apiKey.organizationId ?? DEFAULT_ORGANIZATION_ID; + return organizations.find((one) => one.id === id)?.name ?? null; +} + /** A key's row, under its name: how it starts, when it was made, its last use, and its end if it has one. */ export function apiKeyDescription(apiKey: ApiKey, now = Date.now()): string { const parts = [ @@ -194,14 +215,26 @@ function ApiKeyRow({ apiKey }: { apiKey: ApiKey }) { const [asking, setAsking] = useState(false); const revoke = useMutation(revokeApiKeyMutationOptions(queryClient)); const name = keyName(apiKey); + // Beside its name, as a member's row says You: the organization it acts in, where the person is in several. + const organization = apiKeyOrganization( + apiKey, + useOrganizationChoices()?.organizations, + ); return ( <> - - {name} + + + {name} + {organization ? ( + + {organization} + + ) : null} + {apiKeyDescription(apiKey)} @@ -268,6 +301,11 @@ function CreateApiKeyDialog({ }) { const [name, setName] = useState(""); const create = useMutation(createApiKeyMutationOptions(queryClient)); + // Where the person works now: a key is made in that organization and works there only. + const choices = useOrganizationChoices(); + const organization = choices?.organizations.find( + (one) => one.id === choices.currentId, + ); const trimmed = name.trim(); const close = (next: boolean) => { if (!next) { @@ -299,6 +337,11 @@ function CreateApiKeyDialog({ > Create API key + {organization ? ( + + It works in {organization.name} only. + + ) : null} diff --git a/app/src/lib/channels/use-channel-events.ts b/app/src/lib/channels/use-channel-events.ts index 692ec814aa..e0b148663a 100644 --- a/app/src/lib/channels/use-channel-events.ts +++ b/app/src/lib/channels/use-channel-events.ts @@ -6,6 +6,7 @@ import { import { useRouter } from "@tanstack/react-router"; import { useEffect } from "react"; import { nudgeMoment } from "@/lib/notices"; +import { currentOrganizationId } from "@/lib/organizations/current"; import { isBotReply, noticeChannelEvent, @@ -61,15 +62,36 @@ export function isChannelSocketMessage( return typeof value === "object" && value !== null && !Array.isArray(value); } +/** + * Whether an activity event is about the organization the person is working in. + * + * A person can be in several organizations, and the socket is theirs, not one organization's. An event that names + * another organization (`organizationId`) is about a conversation this screen does not hold, and patching it in would + * put that organization's preview in this one's sidebar, or refetch for a row that will never be here. An event that + * names none, from a server older than this, is taken as it always was. + */ +function inOrganization( + activity: { organizationId?: unknown }, + organization: string | undefined, +): boolean { + return ( + typeof activity.organizationId !== "string" || + organization === undefined || + activity.organizationId === organization + ); +} + /** * Parse one socket frame into something the roster can act on, or `null` to drop it. * * Pure and exported so the drop rules are provable without a socket: unparseable - * text, non-object JSON (`null`, numbers, strings, arrays) and activity events with - * no string channel id are all ignored rather than crashing or refetching the roster. + * text, non-object JSON (`null`, numbers, strings, arrays), activity events with + * no string channel id, and activity events about another organization than + * `organization` are all ignored rather than crashing or refetching the roster. */ export function parseChannelSocketMessage( data: unknown, + organization: string | undefined = currentOrganizationId(), ): ChannelSocketMessage | null { if (typeof data !== "string") return null; let parsed: unknown; @@ -81,11 +103,17 @@ export function parseChannelSocketMessage( if (!isChannelSocketMessage(parsed)) return null; if (isResync(parsed)) return parsed; if (typeof parsed.channelId !== "string") return null; + if (!inOrganization(parsed, organization)) return null; return parsed; } export type ChannelActivityEvent = { channelId: string; + /** + * The organization the conversation is in. Absent from a server older than this, and then the event is taken + * whatever organization the person is working in (`inOrganization`). + */ + organizationId?: string; lastMessage: string | null; lastMessageAt: string | null; lastMessageAgentId: string | null; diff --git a/app/src/lib/organizations/mutations.ts b/app/src/lib/organizations/mutations.ts index 3ce6f1b640..180152d514 100644 --- a/app/src/lib/organizations/mutations.ts +++ b/app/src/lib/organizations/mutations.ts @@ -9,6 +9,7 @@ import { createOrganization, createOrganizationInvitation, declineInvitation, + deleteOrganization, removeOrganizationMember, updateOrganization, updateOrganizationMember, @@ -33,6 +34,7 @@ const CHANGE_ROLE_FALLBACK = "Couldn't change their role. Try again."; const LEAVE_FALLBACK = "Couldn't leave the organization. Try again."; const ACCEPT_FALLBACK = "Couldn't accept the invitation. Try again."; const DECLINE_FALLBACK = "Couldn't decline the invitation. Try again."; +const DELETE_FALLBACK = "Couldn't delete the organization. Try again."; /** Everything read about organizations is read again: the list, members and invitations alike. */ function invalidateOrganizations(queryClient: QueryClient) { @@ -183,13 +185,8 @@ export function changeMemberRoleMutationOptions(queryClient: QueryClient) { } /** - * Leave an organization, as the person signed in. - * - * Somebody who leaves the one they are working in is moved to another of theirs the way a switch - * moves them: the session first, then `leave` (the caller takes them home), then the app changes - * over. Nothing is read again before that, so no screen asks the organization just left for - * anything. Should the session not move, the list of their organizations moves it when it is read - * (./queries.ts). + * Leave an organization, as the person signed in. Somebody who leaves the one they are working in + * is moved to another of theirs (`moveOffGone`). */ export function leaveOrganizationMutationOptions( queryClient: QueryClient, @@ -203,22 +200,56 @@ export function leaveOrganizationMutationOptions( { "Idempotency-Key": idempotencyKey() }, { fallback: LEAVE_FALLBACK }, ), - onSuccess: async (_done, organizationId) => { - const next = queryClient - .getQueryData(organizationKeys.mine()) - ?.organizations.find((one) => one.id !== organizationId); - if (next && currentOrganizationId() === organizationId) { - const moved = await workIn(next.id).then( - () => true, - () => false, - ); - if (moved) { - await leave(); - setCurrentOrganization(next.id); - } - } - await invalidateOrganizations(queryClient); - }, + onSuccess: (_done, organizationId) => + moveOffGone(queryClient, organizationId, leave), + }); +} + +/** + * After the person is no longer in `organizationId` (they left it, or deleted it): somebody working in it is moved to + * another of theirs the way a switch moves them, the session first, then `leave` (the caller takes them home), then the + * app changes over. Nothing is read again before that, so no screen asks the organization that is gone for anything. + * Should the session not move, the list of their organizations moves it when it is read (./queries.ts). + */ +async function moveOffGone( + queryClient: QueryClient, + organizationId: string, + leave: () => Promise, +): Promise { + const next = queryClient + .getQueryData(organizationKeys.mine()) + ?.organizations.find((one) => one.id !== organizationId); + if (next && currentOrganizationId() === organizationId) { + const moved = await workIn(next.id).then( + () => true, + () => false, + ); + if (moved) { + await leave(); + setCurrentOrganization(next.id); + } + } + await invalidateOrganizations(queryClient); +} + +/** + * Delete an organization and what is in it. Only an owner can, and a person's own organization and `default` stay: + * the server refuses those in its own words, which the caller shows. Somebody working in it is moved to another of + * their organizations, as after leaving one. + */ +export function deleteOrganizationMutationOptions( + queryClient: QueryClient, + leave: () => Promise = async () => {}, +) { + return mutationOptions({ + mutationFn: (organizationId: string): Promise => + deleteOrganization( + organizationId, + { "Idempotency-Key": idempotencyKey() }, + { fallback: DELETE_FALLBACK }, + ), + onSuccess: (_done, organizationId) => + moveOffGone(queryClient, organizationId, leave), }); } diff --git a/app/tests/api-keys-screen.test.tsx b/app/tests/api-keys-screen.test.tsx index d0ff40ab1e..f4b815e6a3 100644 --- a/app/tests/api-keys-screen.test.tsx +++ b/app/tests/api-keys-screen.test.tsx @@ -27,6 +27,15 @@ import { getListApiKeysMockHandler, getListApiKeysResponseMock, } from "@/lib/api/generated/api-keys/api-keys.msw"; +import { + CreateApiKeyBody, + ListApiKeysResponse, +} from "@/lib/api/generated/api-keys/api-keys.zod"; +import { + getGetDeploymentMockHandler, + getGetDeploymentResponseMock, +} from "@/lib/api/generated/organization-settings/organization-settings.msw"; +import { getListOrganizationsMockHandler } from "@/lib/api/generated/organizations/organizations.msw"; import type { ApiKey } from "@/lib/api/generated/model"; import { queryClient as appQueryClient } from "@/query-client"; import { settleReactWork } from "./settle-react-work"; @@ -407,3 +416,94 @@ test("refused in OpenBot Desktop, a link opens this page at the OpenBot it is co ); expect(link.getAttribute("target")).toBe("_blank"); }); + +/** + * A person in several organizations: a key acts only in the organization it was made in (`ApiKey.organizationId`), + * so each row names it, and a key made before keys were bound to one (null) acts in `default` and is shown as that + * one. Creating a key says where it will work, and sends only its name: the address names the organization. + */ +function inSeveralOrganizations() { + server.use( + getGetDeploymentMockHandler({ + ...getGetDeploymentResponseMock(), + edition: "team", + }), + getListOrganizationsMockHandler({ + organizations: [ + { + id: "default", + slug: "acme", + name: "Acme", + role: "owner", + active: true, + personal: false, + }, + { + id: "org_research", + slug: "acme-research", + name: "Acme Research", + role: "member", + active: false, + personal: false, + }, + ], + canCreate: true, + nextCursor: null, + }), + ); +} + +test("in several organizations each key's row names the organization it acts in, a key from before binding as default's", async () => { + inSeveralOrganizations(); + const [example] = getListApiKeysResponseMock().apiKeys; + const keys: ApiKey[] = [ + { + ...example, + id: "k1", + name: "Research export", + organizationId: "org_research", + }, + { ...example, id: "k2", name: "Old script", organizationId: null }, + { ...example, id: "k3", name: "Acme sync", organizationId: "default" }, + ]; + // The fake answers as the spec says it may: checked against the generated schema. + const page = ListApiKeysResponse.parse({ apiKeys: keys, nextCursor: null }); + server.use(getListApiKeysMockHandler(page)); + const view = draw(); + + // The organization reads beside the key's name, in its title. + const title = (name: string) => + view.getByText(name).closest('[data-slot="item-title"]')?.textContent ?? ""; + await view.findByText("Research export"); + await waitFor(() => + expect(title("Research export")).toBe("Research exportAcme Research"), + ); + expect(title("Old script")).toBe("Old scriptAcme"); + expect(title("Acme sync")).toBe("Acme syncAcme"); +}); + +test("creating a key in one of several organizations says it works there only, and sends only its name", async () => { + inSeveralOrganizations(); + const bodies: unknown[] = []; + server.use( + getCreateApiKeyMockHandler(async ({ request }) => { + bodies.push(await request.json()); + return getCreateApiKeyResponseMock(); + }), + ); + const view = draw(); + await view.findByText("Nightly report"); + + fireEvent.click(view.getByRole("button", { name: "Create key" })); + const dialog = await view.findByRole("dialog"); + await waitFor(() => + expect(dialog.textContent).toContain("It works in Acme only."), + ); + const name = await view.findByLabelText("Name"); + await userEvent.type(name, "Deploy script"); + fireEvent.submit(name.closest("form") as HTMLFormElement); + await view.findByText(getCreateApiKeyResponseMock().key); + expect(bodies).toEqual([{ name: "Deploy script" }]); + expect(CreateApiKeyBody.parse(bodies[0])).toEqual({ name: "Deploy script" }); + expect(requests).toContain(`POST ${KEYS}`); +}); diff --git a/app/tests/conversation-events-organization.test.tsx b/app/tests/conversation-events-organization.test.tsx new file mode 100644 index 0000000000..58f6668c61 --- /dev/null +++ b/app/tests/conversation-events-organization.test.tsx @@ -0,0 +1,211 @@ +import { afterAll, afterEach, beforeAll, expect, test } from "bun:test"; +import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import { + QueryClient, + QueryClientProvider, + useInfiniteQuery, +} from "@tanstack/react-query"; +import { + createMemoryHistory, + createRootRoute, + createRouter, + RouterProvider, +} from "@tanstack/react-router"; +import { act, cleanup, render, waitFor } from "@testing-library/react"; +import { conversationTitle } from "@/lib/channels/label"; +import { channelListQueryOptions } from "@/lib/channels/queries"; +import { + type ChannelActivityEvent, + useChannelEvents, +} from "@/lib/channels/use-channel-events"; +import { + currentOrganizationId, + setCurrentOrganization, +} from "@/lib/organizations/current"; +import { + CONVERSATIONS_PATH, + conversationPage, + ORGANIZATION_PATH, +} from "./conversations-api"; +import { settleReactWork } from "./settle-react-work"; + +/** + * A person can be in several organizations, and the conversation events socket is theirs, not one organization's: the + * server says which organization each event is about (`ChannelActivityEvent.organizationId`, api/asyncapi.yaml). The + * sidebar takes only the events about the organization the person is working in. An event about another organization + * changes nothing on screen and reads nothing again, and an event that names no organization (a server older than + * this) is taken as it always was. + * + * Driven through the real hook and the real list query, with the server speaking on the socket. + */ + +/** The browser's socket, held so the test can speak as the server. */ +class ServerSocket extends EventTarget implements WebSocket { + static readonly CONNECTING = 0; + static readonly OPEN = 1; + static readonly CLOSING = 2; + static readonly CLOSED = 3; + static opened: ServerSocket[] = []; + readonly CONNECTING = 0; + readonly OPEN = 1; + readonly CLOSING = 2; + readonly CLOSED = 3; + binaryType: BinaryType = "blob"; + bufferedAmount = 0; + extensions = ""; + protocol = ""; + readyState = 1; + onclose: WebSocket["onclose"] = null; + onerror: WebSocket["onerror"] = null; + onmessage: WebSocket["onmessage"] = null; + onopen: WebSocket["onopen"] = null; + readonly url: string; + constructor(url: string | URL) { + super(); + this.url = String(url); + ServerSocket.opened.push(this); + } + close() {} + send() {} + /** One frame from the server, as the conversation events socket sends it. */ + say(event: ChannelActivityEvent) { + this.onmessage?.( + new MessageEvent("message", { data: JSON.stringify(event) }), + ); + } +} + +/** The organization the person is working in: the one the conversations API is asked under here. */ +const HERE = ORGANIZATION_PATH.split("/").at(-1) as string; +const ELSEWHERE = "org_elsewhere"; +const OPENING = "Plan the launch"; + +function row(id: string) { + return { + id, + name: "Researcher", + agentIds: ["researcher"], + threadId: id, + active: true, + lastMessageAt: "2026-11-19T09:00:00.000Z", + summary: null, + opening: OPENING, + lastMessage: OPENING, + lastMessageAgentId: null, + createdAt: "2026-11-19T09:00:00.000Z", + pinned: false, + lastReadAt: null, + }; +} + +let listReads = 0; +const NativeResponse = globalThis.Response; +const originalFetch = globalThis.fetch; +let originalWebSocket: typeof WebSocket; +let originalOrganization: string | undefined; +type Globals = { WebSocket: typeof WebSocket }; +const globals = globalThis as unknown as Globals; + +const serve = (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = new URL(String(input), "http://127.0.0.1:3010"); + if ( + url.pathname === CONVERSATIONS_PATH && + (init?.method ?? "GET").toUpperCase() === "GET" + ) { + listReads++; + return NativeResponse.json(conversationPage([row("plan")])); + } + return NativeResponse.json({ error: "not served" }, { status: 404 }); +}) as unknown as typeof fetch; + +beforeAll(() => { + GlobalRegistrator.register({ url: "http://127.0.0.1:3010" }); + originalWebSocket = globals.WebSocket; + globals.WebSocket = ServerSocket; + globalThis.fetch = serve; + originalOrganization = currentOrganizationId(); + setCurrentOrganization(HERE); +}); +afterEach(() => { + cleanup(); +}); +afterAll(async () => { + await settleReactWork(); + globalThis.fetch = originalFetch; + globals.WebSocket = originalWebSocket; + setCurrentOrganization(originalOrganization); + GlobalRegistrator.unregister(); +}); + +function Sidebar() { + useChannelEvents(); + const { data } = useInfiniteQuery(channelListQueryOptions()); + return ( +
    + {(data ?? []).map((channel) => ( +
  • + {conversationTitle(channel)} +
  • + ))} +
+ ); +} + +const named = ( + channelId: string, + summary: string, + organizationId?: string, +): ChannelActivityEvent => ({ + channelId, + ...(organizationId ? { organizationId } : {}), + lastMessage: null, + lastMessageAt: null, + lastMessageAgentId: null, + summary, +}); + +test("an event about another organization changes nothing and reads nothing again; one about this organization, or naming none, is taken", async () => { + const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false, staleTime: Infinity } }, + }); + const router = createRouter({ + routeTree: createRootRoute({ component: Sidebar }), + history: createMemoryHistory({ initialEntries: ["/"] }), + }); + const view = render( + + + , + ); + await waitFor(() => expect(ServerSocket.opened).toHaveLength(1)); + const socket = ServerSocket.opened[0] as ServerSocket; + act(() => socket.onopen?.(new Event("open"))); + await waitFor(() => + expect(view.getByTestId("plan").textContent).toBe(OPENING), + ); + await act(settleReactWork); + const readsBefore = listReads; + + // Another organization's conversation with the same id, and one this sidebar has never seen: neither is here. + act(() => { + socket.say(named("plan", "Their launch", ELSEWHERE)); + socket.say(named("theirs", "Their offsite", ELSEWHERE)); + }); + await act(settleReactWork); + expect(view.getByTestId("plan").textContent).toBe(OPENING); + expect(view.queryByTestId("theirs")).toBeNull(); + expect(listReads).toBe(readsBefore); + + // This organization's own event is taken. + act(() => socket.say(named("plan", "Launch plan", HERE))); + await waitFor(() => + expect(view.getByTestId("plan").textContent).toBe("Launch plan"), + ); + + // So is one that names no organization, as every event did before organizations were named. + act(() => socket.say(named("plan", "Launch plan, v2"))); + await waitFor(() => + expect(view.getByTestId("plan").textContent).toBe("Launch plan, v2"), + ); + expect(listReads).toBe(readsBefore); +}); diff --git a/app/tests/organization-delete.test.tsx b/app/tests/organization-delete.test.tsx new file mode 100644 index 0000000000..bf7b76d47f --- /dev/null +++ b/app/tests/organization-delete.test.tsx @@ -0,0 +1,438 @@ +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + expect, + test, +} from "bun:test"; +import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import { QueryClientProvider } from "@tanstack/react-query"; +import { + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + Outlet, + RouterProvider, +} from "@tanstack/react-router"; +import { cleanup, render, waitFor, within } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import type { ReactNode } from "react"; +import { AppSidebar } from "@/components/app-sidebar/app-sidebar"; +import { OrganizationBoundary } from "@/components/organizations/organization-boundary"; +import { OrganizationSettingsPage } from "@/components/organizations/organization-settings-page"; +import { SidebarProvider } from "@/components/ui/sidebar"; +import { Toaster } from "@/components/ui/toast"; +import type { Organization } from "@/lib/api/generated/model"; +import { + DeleteOrganizationHeader, + ListOrganizationMembersResponse, + ListOrganizationsResponse, +} from "@/lib/api/generated/organizations/organizations.zod"; +import { signedInUser } from "@/lib/auth/queries"; +import { + currentOrganizationId, + setCurrentOrganization, +} from "@/lib/organizations/current"; +import { queryClient } from "@/query-client"; +import { settleReactWork } from "./settle-react-work"; + +/** + * An organization's owner can delete it from its settings (deleteOrganization, api/openapi/organizations.yaml). It asks + * first, with the organization's name typed, then deletes it, and the person is then working in another of their + * organizations, from home. The server keeps a person's own organization and `default`, and refuses deleting them in + * its own words, which the dialog shows. Only an owner is offered it. + * + * The server here answers at the API's addresses, in the API's shapes, each answer checked against the schemas + * generated from the spec. The app is the real sidebar and the real settings screen, on the app's one query client. + */ + +class OfflineWebSocket extends EventTarget { + static readonly CONNECTING = 0; + static readonly OPEN = 1; + static readonly CLOSING = 2; + static readonly CLOSED = 3; + readyState = 0; + onclose = null; + onerror = null; + onmessage = null; + onopen = null; + close() {} + send() {} +} + +type Listed = Omit; + +const OWN: Listed = { + id: "org_dana", + slug: "dana", + name: "Dana's organization", + role: "owner", + personal: true, +}; +const ACME: Listed = { + id: "org_acme", + slug: "acme", + name: "Acme", + role: "owner", + personal: false, +}; +const DEFAULT: Listed = { + id: "default", + slug: "default", + name: "Example Inc", + role: "owner", + personal: false, +}; + +/** The refusals the spec gives for deleteOrganization, in its own words. */ +const REFUSALS = { + personal: { + status: 409, + code: "CONFLICT", + detail: + "This is your own organization, so it stays. You can delete organizations you created.", + }, + default: { + status: 409, + code: "CONFLICT", + detail: "This organization comes with OpenBot, so it stays.", + }, + unfinished: { + status: 503, + code: "SERVICE_UNAVAILABLE", + detail: "The organization couldn't be deleted. Try again.", + }, + notOwner: { + status: 403, + code: "PERMISSION_DENIED", + detail: "Only an owner can delete this organization.", + }, +} as const; + +let server: { + organizations: Listed[]; + active: string; + /** What the next delete is refused with, when it is. */ + refusal: keyof typeof REFUSALS | null; +}; +let requests: string[] = []; +let deletes: { path: string; key: string | null }[] = []; +const DEPLOYMENT = "/api/v2/organizations/default/deployment"; + +function problem({ + status, + code, + detail, +}: { + status: number; + code: string; + detail: string; +}): Response { + return new Response( + JSON.stringify({ + type: "https://open.bot/errors/example", + title: detail, + status, + detail, + code, + category: "conflict", + retryable: false, + requestId: "req_example", + traceId: "trace_example", + }), + { status, headers: { "content-type": "application/problem+json" } }, + ); +} + +/** An answer, checked against the schema the spec generates for it. */ +function checked(schema: { parse(value: unknown): unknown }, body: unknown) { + return Response.json(schema.parse(body)); +} + +async function answer( + input: Parameters[0], + init?: RequestInit, +): Promise { + const url = new URL(String(input), "http://openbot.invalid"); + const method = (init?.method ?? "GET").toUpperCase(); + const path = url.pathname; + requests.push(`${method} ${path}`); + const body = init?.body ? (JSON.parse(String(init.body)) as unknown) : null; + + if (path === DEPLOYMENT) + return Response.json({ + generativeUi: true, + selfHostBanner: false, + localEvaluation: false, + edition: "team", + }); + if (path === "/api/v2/people/me/organizations" && method === "GET") + return checked(ListOrganizationsResponse, { + organizations: server.organizations.map((one) => ({ + ...one, + active: one.id === server.active, + })), + canCreate: true, + nextCursor: null, + }); + if (path === "/api/auth/organization/set-active" && method === "POST") { + const wanted = (body as { organizationId: string }).organizationId; + if (!server.organizations.some((one) => one.id === wanted)) + return Response.json({ message: "Not a member." }, { status: 403 }); + server.active = wanted; + return Response.json({ id: wanted }); + } + if (path === "/api/v2/people/me/invitations") + return Response.json({ invitations: [], nextCursor: null }); + + const addressed = /^\/api\/v2\/organizations\/([^/]+)\/(.+)$/.exec(path); + if (addressed) { + const [, organization, rest] = addressed; + const here = server.organizations.find((one) => one.id === organization); + if (!here) + return problem({ + status: 404, + code: "ORGANIZATION_NOT_FOUND", + detail: "Couldn't find that organization.", + }); + if (rest === "profile" && method === "DELETE") { + const key = new Headers(init?.headers).get("idempotency-key"); + DeleteOrganizationHeader.parse({ "Idempotency-Key": key }); + deletes.push({ path, key }); + if (here.role !== "owner") return problem(REFUSALS.notOwner); + if (server.refusal) { + const refusal = REFUSALS[server.refusal]; + server.refusal = null; + return problem(refusal); + } + if (here.personal) return problem(REFUSALS.personal); + if (here.id === "default") return problem(REFUSALS.default); + server.organizations = server.organizations.filter( + (one) => one.id !== organization, + ); + return new Response(null, { status: 204 }); + } + if (rest === "people/me") + return Response.json({ + person: { + id: "dana", + email: "dana@example.com", + name: "Dana Fresh", + needsName: false, + image: null, + role: here.role, + onboarding: null, + }, + openbotVersion: null, + }); + if (rest === "members") + return checked(ListOrganizationMembersResponse, { + members: [ + { + id: "dana", + email: "dana@example.com", + name: "Dana Fresh", + image: null, + role: here.role, + joinedAt: "2026-11-01T09:00:00.000Z", + removable: false, + assignableRoles: [], + }, + ], + nextCursor: null, + }); + if (rest === "invitations") + return Response.json({ invitations: [], nextCursor: null }); + if (rest === "conversations") + return Response.json({ conversations: [], nextCursor: null }); + if (rest === "bots") return Response.json({ bots: [], nextCursor: null }); + } + return Response.json({ error: "not served" }, { status: 404 }); +} + +const originalFetch = globalThis.fetch; +const originalWebSocket = globalThis.WebSocket; + +beforeAll(() => { + GlobalRegistrator.register({ url: "http://openbot.invalid/" }); + globalThis.WebSocket = OfflineWebSocket as unknown as typeof WebSocket; +}); +beforeEach(() => { + server = { + organizations: [{ ...OWN }, { ...ACME }], + active: ACME.id, + refusal: null, + }; + requests = []; + deletes = []; + setCurrentOrganization(undefined); + queryClient.clear(); + globalThis.fetch = Object.assign(answer, { + preconnect: originalFetch.preconnect, + }); +}); +afterEach(() => { + cleanup(); + queryClient.clear(); + globalThis.fetch = originalFetch; +}); +afterAll(async () => { + await settleReactWork(); + globalThis.WebSocket = originalWebSocket; + GlobalRegistrator.unregister(); + setCurrentOrganization("default"); +}); + +async function open(start = "/settings/organization") { + await signedInUser(queryClient); + const rootRoute = createRootRoute({ + component: () => ( + + + +
+ +
+ +
+
+ ), + }); + const at = (path: string, component: () => ReactNode) => + createRoute({ getParentRoute: () => rootRoute, path, component }); + const router = createRouter({ + history: createMemoryHistory({ initialEntries: [start] }), + routeTree: rootRoute.addChildren([ + at("/", () =>

Home

), + at("/settings/organization", OrganizationSettingsPage), + ]), + }); + const view = render( + + + , + ); + const person = userEvent.setup({ document }); + const page = within(await view.findByRole("main")); + return { view, router, person, page }; +} + +/** Opens the Delete dialog and types `typed` into its confirmation. */ +async function askToDelete( + app: Awaited>, + name: string, + typed = name, +) { + await app.person.click( + await app.page.findByRole("button", { name: "Delete organization" }), + ); + const dialog = await app.view.findByRole("dialog", { + name: `Delete ${name}?`, + }); + const confirm = within(dialog).getByRole("button", { + name: "Delete organization", + }); + expect(confirm.hasAttribute("disabled")).toBe(true); + await app.person.type( + within(dialog).getByLabelText(`Type ${name} to confirm`), + typed, + ); + return { dialog, confirm }; +} + +describe("deleting an organization", () => { + test("its owner deletes it after typing its name, and is then working in another of their organizations, from home", async () => { + const app = await open(); + const { confirm } = await askToDelete(app, "Acme", "Acm"); + // Not the name yet: nothing to press. + expect(confirm.hasAttribute("disabled")).toBe(true); + expect(deletes).toEqual([]); + await app.person.type( + within(await app.view.findByRole("dialog")).getByLabelText( + "Type Acme to confirm", + ), + "e", + ); + await waitFor(() => expect(confirm.hasAttribute("disabled")).toBe(false)); + requests = []; + await app.person.click(confirm); + + await waitFor(() => expect(currentOrganizationId()).toBe(OWN.id)); + expect(app.router.state.location.pathname).toBe("/"); + expect(deletes).toHaveLength(1); + expect(deletes[0]?.path).toBe(`/api/v2/organizations/${ACME.id}/profile`); + expect(deletes[0]?.key).toMatch(/^[0-9a-f]{32}$/); + expect(server.active).toBe(OWN.id); + expect(server.organizations.map((one) => one.id)).toEqual([OWN.id]); + // Nothing more was asked of the organization once it was gone. + const gone = requests.indexOf( + `DELETE /api/v2/organizations/${ACME.id}/profile`, + ); + expect( + requests.slice(gone + 1).filter((request) => request.includes(ACME.id)), + ).toEqual([]); + await waitFor(() => expect(app.view.queryByRole("dialog")).toBeNull()); + }); + + test("a person's own organization stays: the server's refusal is said in the dialog and nothing changes", async () => { + server.active = OWN.id; + const app = await open(); + const { dialog, confirm } = await askToDelete(app, OWN.name); + await app.person.click(confirm); + expect((await within(dialog).findByRole("alert")).textContent).toBe( + REFUSALS.personal.detail, + ); + expect(currentOrganizationId()).toBe(OWN.id); + expect(app.router.state.location.pathname).toBe("/settings/organization"); + expect(server.organizations.map((one) => one.id)).toEqual([ + OWN.id, + ACME.id, + ]); + }); + + test("the organization that comes with OpenBot stays, in the server's words", async () => { + server.organizations = [{ ...OWN }, { ...DEFAULT }]; + server.active = DEFAULT.id; + const app = await open(); + const { dialog, confirm } = await askToDelete(app, DEFAULT.name); + await app.person.click(confirm); + expect((await within(dialog).findByRole("alert")).textContent).toBe( + REFUSALS.default.detail, + ); + expect(currentOrganizationId()).toBe(DEFAULT.id); + }); + + test("a delete the server could not finish is said, and asking again deletes it", async () => { + server.refusal = "unfinished"; + const app = await open(); + const { dialog, confirm } = await askToDelete(app, "Acme"); + await app.person.click(confirm); + expect((await within(dialog).findByRole("alert")).textContent).toBe( + REFUSALS.unfinished.detail, + ); + expect(currentOrganizationId()).toBe(ACME.id); + + await app.person.click(confirm); + await waitFor(() => expect(currentOrganizationId()).toBe(OWN.id)); + expect(deletes).toHaveLength(2); + // Each request a person asks for is its own write, with its own key. + expect(deletes[0]?.key).not.toBe(deletes[1]?.key); + }); + + test("an admin or a member is not offered it", async () => { + for (const role of ["admin", "member"] as const) { + server.organizations = [{ ...OWN }, { ...ACME, role }]; + const app = await open(); + await app.page.findByText("Members"); + expect( + app.page.queryByRole("button", { name: "Delete organization" }), + ).toBeNull(); + cleanup(); + queryClient.clear(); + setCurrentOrganization(undefined); + } + }); +}); diff --git a/extension/src/background/activity.ts b/extension/src/background/activity.ts index 48758d8a5b..23cc9edbca 100644 --- a/extension/src/background/activity.ts +++ b/extension/src/background/activity.ts @@ -10,7 +10,7 @@ import type { RecorderActivity } from "@openbot/shared/recorder-api"; import type { RecorderState } from "../protocol/messages"; import { reportRecorderActivity } from "../shared/generated/recorder"; -import { OpenBotError, ORGANIZATION_ID } from "../shared/openbot-client"; +import { OpenBotError, organizationOf } from "../shared/openbot-client"; /** How often a running recording reports, well inside the 90 s after which OpenBot treats a report as stale. */ export const ACTIVITY_REPORT_MS = 30_000; @@ -24,6 +24,8 @@ export type ActivityTarget = { openbotUrl: string; token: string; userId: string; + /** The organization the connection was made in (`organizationOf`). */ + organizationId?: string; }; type Timers = { @@ -70,10 +72,14 @@ export function createActivityReport(deps: ActivityDeps): ActivityReport { const target = await deps.target(); if (!target) return; try { - await reportRecorderActivity(ORGANIZATION_ID, activityOf(deps.state()), { - target, - signal: AbortSignal.timeout(REPORT_WAIT_MS), - }); + await reportRecorderActivity( + organizationOf(target), + activityOf(deps.state()), + { + target, + signal: AbortSignal.timeout(REPORT_WAIT_MS), + }, + ); } catch (error) { if (error instanceof OpenBotError && error.signedOut) await deps.signedOut(error.body?.reason ?? "revoked", target); diff --git a/extension/src/background/connection.ts b/extension/src/background/connection.ts index 52344d8502..8a0d2a4f26 100644 --- a/extension/src/background/connection.ts +++ b/extension/src/background/connection.ts @@ -17,7 +17,8 @@ import { } from "../shared/generated/recorder"; import { OpenBotError, - ORGANIZATION_ID, + DEFAULT_ORGANIZATION_ID, + organizationOf, updateRequiredSentence, } from "../shared/openbot-client"; import { normaliseOpenBotOrigin } from "../shared/origin"; @@ -80,6 +81,17 @@ type ConnectionDeps = { connected: () => Promise; }; +/** + * The organization a grant says the connection was made in, kept on the stored connection so every later request goes + * there. A code is exchanged at `default`, because the code itself names the organization it was made for. A grant that + * names none (an OpenBot older than organizations) keeps nothing, and the connection works in `default` as before. + */ +function grantOrganization( + grant: RecorderConnectionGrant, +): Pick { + return grant.organizationId ? { organizationId: grant.organizationId } : {}; +} + const PENDING_MAX_AGE_MS = 5 * 60 * 1000; const OUT_OF_DATE = "This page is out of date. Close it and choose Connect this browser in OpenBot again."; @@ -190,7 +202,9 @@ async function keepAlive(deps: ConnectionDeps): Promise { const connection = await currentConnection(); if (!connection) return; try { - await getRecorderIdentity(ORGANIZATION_ID, { target: connection }); + await getRecorderIdentity(organizationOf(connection), { + target: connection, + }); } catch (error) { if (error instanceof OpenBotError && error.signedOut) await deps.connectionLost({ @@ -355,7 +369,7 @@ async function approve( let exchanged: RecorderConnectionGrant; try { exchanged = await exchangeRecorderConnectCode( - ORGANIZATION_ID, + DEFAULT_ORGANIZATION_ID, { code: pending.code, label, @@ -382,6 +396,7 @@ async function approve( user: exchanged.user, via: pending.via, connectedAt: Date.now(), + ...grantOrganization(exchanged), }; // Checked again in the job that stores it: a pin that landed during the exchange keeps it out, and the token OpenBot // just made is revoked there. The connection it replaces is read in the same job. @@ -634,7 +649,7 @@ async function trustedConnect( let exchanged: RecorderConnectionGrant; try { exchanged = await exchangeRecorderConnectCode( - ORGANIZATION_ID, + DEFAULT_ORGANIZATION_ID, { code, label: defaultBrowserName(), @@ -661,6 +676,7 @@ async function trustedConnect( user: exchanged.user, via: "web", connectedAt: Date.now(), + ...grantOrganization(exchanged), }; const kept = await serially(async (): Promise => { if (!allowsOpenBot(await deps.readPolicy(), origin)) @@ -798,7 +814,7 @@ function sameOrigin(raw: string, origin: string): boolean { /** Best effort: OpenBot revokes the token (the person can also revoke it in OpenBot). */ async function revoke(connection: ConnectionRecord): Promise { try { - await deleteCurrentRecorderConnection(ORGANIZATION_ID, { + await deleteCurrentRecorderConnection(organizationOf(connection), { target: connection, }); } catch { @@ -885,7 +901,7 @@ async function desktopConnect( let exchanged: RecorderConnectionGrant; try { exchanged = await exchangeRecorderConnectCode( - ORGANIZATION_ID, + DEFAULT_ORGANIZATION_ID, { code: handoff.code, label: defaultBrowserName(), @@ -914,6 +930,7 @@ async function desktopConnect( user: exchanged.user, via: "desktop", connectedAt: Date.now(), + ...grantOrganization(exchanged), }; // This job is the queued one that stores it: the launcher's connection, or a pin elsewhere, that came while OpenBot // answered keeps it out, and the token OpenBot just made is revoked. diff --git a/extension/src/background/launcher.ts b/extension/src/background/launcher.ts index 09c217df21..868d455362 100644 --- a/extension/src/background/launcher.ts +++ b/extension/src/background/launcher.ts @@ -22,7 +22,7 @@ import { } from "@openbot/shared/recorder-api"; import type { PageResponse, RecorderState } from "../protocol/messages"; import { getRecorderIdentity } from "../shared/generated/recorder"; -import { OpenBotError, ORGANIZATION_ID } from "../shared/openbot-client"; +import { OpenBotError, organizationOf } from "../shared/openbot-client"; import { normaliseOpenBotOrigin } from "../shared/origin"; import { allowsOpenBot, readPolicy } from "../shared/policy"; import { narrationLanguage } from "../shared/speech-language"; @@ -92,7 +92,7 @@ const isTime = (value: unknown): value is number => /** The launcher's connection, read as the contract types it: anything else is refused, whatever sent it. */ function connectionFrom(value: unknown): LauncherConnection | null { if (!isRecord(value)) return null; - const { openbotUrl, token, connectionId, user } = value; + const { openbotUrl, token, connectionId, user, organizationId } = value; if ( !isText(openbotUrl, 2000) || !isText(token, 200) || @@ -101,7 +101,8 @@ function connectionFrom(value: unknown): LauncherConnection | null { !isRecord(user) || !isText(user.id, 200) || typeof user.name !== "string" || - typeof user.email !== "string" + typeof user.email !== "string" || + (organizationId !== undefined && !isText(organizationId, 200)) ) return null; return { @@ -109,6 +110,7 @@ function connectionFrom(value: unknown): LauncherConnection | null { token, connectionId, user: { id: user.id, name: user.name, email: user.email }, + ...(organizationId ? { organizationId } : {}), }; } @@ -286,7 +288,7 @@ export function createLauncher( | { kind: "unknown" } > { try { - const value = await getRecorderIdentity(ORGANIZATION_ID, { + const value = await getRecorderIdentity(organizationOf(connection), { target: connection, signal: AbortSignal.timeout(ME_WAIT_MS), }); @@ -343,6 +345,9 @@ export function createLauncher( via: "openbot-browser", connectedAt: deps.now(), narration: narration as Narration, + ...(connection.organizationId + ? { organizationId: connection.organizationId } + : {}), }; const current = await currentConnection(); if (sameConnection(current, record)) return { ok: true }; diff --git a/extension/src/background/recording.ts b/extension/src/background/recording.ts index 9633aae797..a386409da9 100644 --- a/extension/src/background/recording.ts +++ b/extension/src/background/recording.ts @@ -48,7 +48,7 @@ import { } from "../shared/limits"; import { OpenBotError, - ORGANIZATION_ID, + organizationOf, updateRequiredSentence, } from "../shared/openbot-client"; import { isRecordablePage } from "../shared/origin"; @@ -560,6 +560,8 @@ type Live = { openbotUrl: string; token: string; userId: string; + /** The organization of the connection it records with (`organizationOf`). */ + organizationId?: string; }; type StopMode = @@ -592,12 +594,18 @@ function report(what: string): (error: unknown) => void { return (error) => console.error(`Recorder: ${what} failed`, error); } -function liveFrom(record: DrainRecord, token: string): Live { +function liveFrom( + record: DrainRecord, + connection: Pick, +): Live { return { recordingId: record.recordingId, openbotUrl: record.openbotUrl, - token, + token: connection.token, userId: record.userId, + ...(connection.organizationId + ? { organizationId: connection.organizationId } + : {}), }; } @@ -704,6 +712,7 @@ export function installRecording( openbotUrl: live.openbotUrl, token: live.token, userId: live.userId, + organizationId: live.organizationId, }; const connection = await currentConnection(); return connection @@ -711,6 +720,7 @@ export function installRecording( openbotUrl: connection.openbotUrl, token: connection.token, userId: connection.user.id, + organizationId: connection.organizationId, } : null; }, @@ -830,7 +840,7 @@ export function installRecording( if (narration) external = { language: narration.language, before: "" }; const connection = await currentConnection(); if (!record || !connection || !ownedBy(record, connection)) return; - live = liveFrom(record, connection.token); + live = liveFrom(record, connection); openSteps(live.recordingId, takeRestored(live.recordingId)); })(); ready.catch(report("loading the recorder state")); @@ -1719,6 +1729,9 @@ export function installRecording( openbotUrl: connection.openbotUrl, token: connection.token, userId: connection.user.id, + ...(connection.organizationId + ? { organizationId: connection.organizationId } + : {}), }; watchConnection(); external = session.narration @@ -2053,7 +2066,7 @@ export function installRecording( const current = live; if (!current || state.phase !== "recording") return; try { - await getRecorderIdentity(ORGANIZATION_ID, { + await getRecorderIdentity(organizationOf(current), { target: { openbotUrl: current.openbotUrl, token: current.token }, }); } catch (error) { @@ -2507,10 +2520,10 @@ export function installRecording( return null; } const connection = await currentConnection(); - const token = - connection && ownedBy(record, connection) ? connection.token : ""; + const owner = + connection && ownedBy(record, connection) ? connection : { token: "" }; await trackStop( - endRecording(liveFrom(record, token), { kind: "person" }, stopping), + endRecording(liveFrom(record, owner), { kind: "person" }, stopping), ); return record.recordingId; } @@ -2560,7 +2573,7 @@ export function installRecording( return; } await trackStop( - endRecording(liveFrom(record, ""), { + endRecording(liveFrom(record, { token: "" }), { kind: "signed-out", reason: await waitingReason(), forgot: true, @@ -2623,7 +2636,7 @@ export function installRecording( ) return cached.value; try { - const value = await getRecorderIdentity(ORGANIZATION_ID, { + const value = await getRecorderIdentity(organizationOf(connection), { target: connection, }); await writeSession("me", { value, fetchedAt: deps.now() }); @@ -2685,7 +2698,7 @@ export function installRecording( const connection = await currentConnection(); if (!connection) return { ok: false, error: SENTENCES.noConnection }; try { - const answer = await getRecorderLearning(ORGANIZATION_ID, { + const answer = await getRecorderLearning(organizationOf(connection), { target: connection, }); learningSpace = answer.learning; diff --git a/extension/src/shared/openbot-client.ts b/extension/src/shared/openbot-client.ts index a9566cfd4e..f5ea3f4360 100644 --- a/extension/src/shared/openbot-client.ts +++ b/extension/src/shared/openbot-client.ts @@ -67,7 +67,12 @@ export function updateRequiredSentence(error: unknown): string | null { : RECORDER_UPDATE_REQUIRED; } -type OpenBotTarget = { openbotUrl: string; token?: string }; +type OpenBotTarget = { + openbotUrl: string; + token?: string; + /** The organization the connection was made in, as its grant named it. Absent: {@link DEFAULT_ORGANIZATION_ID}. */ + organizationId?: string; +}; /** * Sends the request with the bearer when there is one, never with cookies, and never follows a redirect. Every request @@ -127,8 +132,23 @@ function idempotencyKey(): string { ); } -/** The organization the Recorder works in: an install has one, and the API addresses it as `default`. */ -export const ORGANIZATION_ID = "default"; +/** + * The organization every install has, which the API addresses as `default`. A connection is made there (the code it + * exchanges names the organization it is for), and a connection whose grant named no organization works there too: that + * is every connection an OpenBot older than organizations made. + */ +export const DEFAULT_ORGANIZATION_ID = "default"; + +/** + * The organization a connection's requests go to: the one its grant named (`RecorderConnectionGrant.organizationId`), + * else {@link DEFAULT_ORGANIZATION_ID}. A person can be in several organizations, and a Recorder connected in one records + * into that one only. + */ +export function organizationOf(connection: { + organizationId?: string | null; +}): string { + return connection.organizationId || DEFAULT_ORGANIZATION_ID; +} /** What a caller of a generated function (src/shared/generated) adds to the request it makes. */ export type OpenBotRequestInit = RequestInit & { diff --git a/extension/src/shared/storage.ts b/extension/src/shared/storage.ts index b7f94bba48..2e40035489 100644 --- a/extension/src/shared/storage.ts +++ b/extension/src/shared/storage.ts @@ -17,6 +17,9 @@ export type ConnectionRecord = { user: RecorderUser; via: RecorderConnectVia; connectedAt: number; + /** The organization OpenBot made the connection in, as its grant named it: every request of this connection goes + * there (`organizationOf`). Absent from a grant of an OpenBot older than organizations, which means `default`. */ + organizationId?: string; /** Who hears the person, for a connection the Recorder's launcher made (launcher.ts): `external` when the browser has * no microphone and OpenBot passes each phrase in. Absent: the Recorder hears the microphone itself, as always. */ narration?: Narration; diff --git a/extension/tests/openbot-client.test.ts b/extension/tests/openbot-client.test.ts index 6dae1ee9cd..c880b33896 100644 --- a/extension/tests/openbot-client.test.ts +++ b/extension/tests/openbot-client.test.ts @@ -16,7 +16,7 @@ import { import { OpenBotError, type OpenBotRequestInit, - ORGANIZATION_ID, + DEFAULT_ORGANIZATION_ID, openbotRaw, openbotRequest, } from "../src/shared/openbot-client"; @@ -187,11 +187,13 @@ afterAll(() => { test("the generated client reaches OpenBot only at the API's addresses, in its one organization", () => { expect({ - connections: getExchangeRecorderConnectCodeUrl(ORGANIZATION_ID), - currentConnection: getDeleteCurrentRecorderConnectionUrl(ORGANIZATION_ID), - me: getGetRecorderIdentityUrl(ORGANIZATION_ID), - learning: getGetRecorderLearningUrl(ORGANIZATION_ID), - activity: getReportRecorderActivityUrl(ORGANIZATION_ID), + connections: getExchangeRecorderConnectCodeUrl(DEFAULT_ORGANIZATION_ID), + currentConnection: getDeleteCurrentRecorderConnectionUrl( + DEFAULT_ORGANIZATION_ID, + ), + me: getGetRecorderIdentityUrl(DEFAULT_ORGANIZATION_ID), + learning: getGetRecorderLearningUrl(DEFAULT_ORGANIZATION_ID), + activity: getReportRecorderActivityUrl(DEFAULT_ORGANIZATION_ID), }).toEqual(API); }); @@ -199,7 +201,7 @@ test("each of the Recorder's operations goes out through the mutator: its addres const target = { openbotUrl, token: "obr_t" }; const grant = await exchangeRecorderConnectCode( - ORGANIZATION_ID, + DEFAULT_ORGANIZATION_ID, { code: "obc_abc", label: "Work laptop", @@ -224,7 +226,9 @@ test("each of the Recorder's operations goes out through the mutator: its addres }); expect(seen?.key).toMatch(/^[0-9a-f]{32}$/); - expect(await getRecorderIdentity(ORGANIZATION_ID, { target })).toEqual({ + expect( + await getRecorderIdentity(DEFAULT_ORGANIZATION_ID, { target }), + ).toEqual({ user: ada, connectionId: "c1", }); @@ -235,14 +239,16 @@ test("each of the Recorder's operations goes out through the mutator: its addres key: null, }); - expect(await getRecorderLearning(ORGANIZATION_ID, { target })).toEqual({ + expect( + await getRecorderLearning(DEFAULT_ORGANIZATION_ID, { target }), + ).toEqual({ learning: { state: "assigned", containerId: "space-1" }, }); expect(seen).toMatchObject({ method: "GET", path: API.learning }); const activity = { phase: "recording" as const, actions: 3 }; expect( - await reportRecorderActivity(ORGANIZATION_ID, activity, { target }), + await reportRecorderActivity(DEFAULT_ORGANIZATION_ID, activity, { target }), ).toBeUndefined(); expect(seen).toMatchObject({ method: "POST", @@ -253,7 +259,7 @@ test("each of the Recorder's operations goes out through the mutator: its addres expect(seen?.key).toMatch(/^[0-9a-f]{32}$/); expect( - await deleteCurrentRecorderConnection(ORGANIZATION_ID, { target }), + await deleteCurrentRecorderConnection(DEFAULT_ORGANIZATION_ID, { target }), ).toBeUndefined(); expect(seen).toMatchObject({ method: "DELETE", @@ -266,16 +272,16 @@ test("each of the Recorder's operations goes out through the mutator: its addres test("every request names the Recorder and the OpenBot release it was built from, a read and a write, through the generated client and openbotRaw", async () => { const target = { openbotUrl, token: "obr_t" }; const named = `recorder/${RELEASE}`; - await getRecorderIdentity(ORGANIZATION_ID, { target }); + await getRecorderIdentity(DEFAULT_ORGANIZATION_ID, { target }); expect(seen).toMatchObject({ path: API.me, client: named }); await reportRecorderActivity( - ORGANIZATION_ID, + DEFAULT_ORGANIZATION_ID, { phase: "recording", actions: 1 }, { target }, ); expect(seen).toMatchObject({ path: API.activity, client: named }); await exchangeRecorderConnectCode( - ORGANIZATION_ID, + DEFAULT_ORGANIZATION_ID, { code: "obc_abc", label: "Work laptop", @@ -290,7 +296,7 @@ test("every request names the Recorder and the OpenBot release it was built from test("a call that names no OpenBot is refused before any request is made", async () => { const { urls } = await recordFetch(async () => { - await expect(getRecorderIdentity(ORGANIZATION_ID)).rejects.toThrow( + await expect(getRecorderIdentity(DEFAULT_ORGANIZATION_ID)).rejects.toThrow( "Name the OpenBot", ); }); diff --git a/extension/tests/recorder-organization.test.ts b/extension/tests/recorder-organization.test.ts new file mode 100644 index 0000000000..34a16e4e81 --- /dev/null +++ b/extension/tests/recorder-organization.test.ts @@ -0,0 +1,147 @@ +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + expect, + test, +} from "bun:test"; +import { + connectThroughDesktop, + currentConnection, + handleConnectionMessage, + handleExternalConnect, + installConnection, +} from "../src/background/connection"; +import type { RecorderPolicy } from "../src/shared/policy"; +import { type ChromeFake, installChromeFake } from "./support/chrome-fake"; + +/** + * A person can be in several organizations, and a Recorder connected in one of them records into that one: the grant + * OpenBot answers a connect with names the organization (`RecorderConnectionGrant.organizationId`), the Recorder keeps + * it with the connection, and every later request of that connection goes to that organization's addresses. A grant + * that names none, as from an OpenBot older than organizations, keeps the connection in `default`, as before. + * + * The OpenBot here is a real server on this computer that answers the Recorder's addresses as api/openapi.yaml gives + * them, under whichever organization the address names, and records every request. + */ + +const user = { id: "u1", name: "Ada", email: "ada@example.test" }; +/** The organization a code ending `_two` was made in. */ +const TWO = "org_two"; + +const hits: string[] = []; +let server: ReturnType; +let loopback = ""; + +async function openbot(request: Request): Promise { + const url = new URL(request.url); + hits.push(`${request.method} ${url.pathname}`); + // A code is exchanged at `default`: the code names the organization it was made for. + if ( + request.method === "POST" && + url.pathname === "/api/v2/organizations/default/recorder-connections" + ) { + const { code } = (await request.json()) as { code: string }; + return Response.json({ + token: "obr_fixture", + connection: { id: "c1" }, + user, + ...(code.endsWith("_two") ? { organizationId: TWO } : {}), + }); + } + const addressed = + /^\/api\/v2\/organizations\/([^/]+)\/(recorder\/me|recorder-connections\/current)$/.exec( + url.pathname, + ); + if (addressed?.[2] === "recorder/me") + return Response.json({ user, connectionId: "c1" }); + if (addressed && request.method === "DELETE") + return new Response(null, { status: 204 }); + return new Response("nope", { status: 404 }); +} + +beforeAll(() => { + server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: openbot }); + loopback = server.url.origin; +}); +afterAll(() => server.stop(true)); + +let fake: ChromeFake; +const policy: RecorderPolicy = { + openbotUrl: null, + openbotUrlInvalid: false, + allowedIntelligenceUrls: null, +}; +const deps = { + openTab: async () => 41, + readPolicy: async () => policy, +}; +const settle = () => new Promise((resolve) => setTimeout(resolve, 20)); + +beforeEach(() => { + fake = installChromeFake({ manifestVersion: "0.2.0" }); + hits.length = 0; +}); +afterEach(() => { + fake.uninstall(); +}); + +/** The requests after the connect: the keep-alive's identity check, then the person's Disconnect. */ +async function keepAliveThenDisconnect(): Promise { + hits.length = 0; + installConnection(deps); + await settle(); + fake.alarms.fire("recorder-session-keepalive"); + await settle(); + await handleConnectionMessage({ type: "page.disconnect" }); + return hits.filter((hit) => !hit.endsWith("/recorder-connections")); +} + +test("a connection made in another organization keeps it, and every request after the connect goes there", async () => { + const answer = await connectThroughDesktop({ + askDesktop: async () => ({ openbotUrl: loopback, code: "obc_two" }), + ...deps, + }); + expect(answer).toEqual({ connected: true }); + expect(hits).toEqual([ + "POST /api/v2/organizations/default/recorder-connections", + ]); + expect(await currentConnection()).toMatchObject({ + token: "obr_fixture", + organizationId: TWO, + }); + + const after = await keepAliveThenDisconnect(); + expect(after.length).toBeGreaterThanOrEqual(2); + for (const hit of after) expect(hit).toContain(`/organizations/${TWO}/`); + expect(after).toContain(`GET /api/v2/organizations/${TWO}/recorder/me`); + expect(after).toContain( + `DELETE /api/v2/organizations/${TWO}/recorder-connections/current`, + ); + expect(await currentConnection()).toBeNull(); +}); + +test("a grant that names no organization keeps the connection in default, as before organizations", async () => { + // An approved web connect, from an OpenBot that answers no organization. + const origin = loopback; + await handleExternalConnect( + { type: "openbot.connect", code: "obc_plain" }, + { origin }, + deps, + ); + await handleConnectionMessage( + { type: "page.connect.decide", approve: true, label: "Chrome", origin }, + deps, + ); + const stored = await currentConnection(); + expect(stored?.token).toBe("obr_fixture"); + expect(stored?.organizationId).toBeUndefined(); + + const after = await keepAliveThenDisconnect(); + for (const hit of after) expect(hit).toContain("/organizations/default/"); + expect(after).toContain("GET /api/v2/organizations/default/recorder/me"); + expect(after).toContain( + "DELETE /api/v2/organizations/default/recorder-connections/current", + ); +}); diff --git a/mobile/app/index.tsx b/mobile/app/index.tsx index b8f7409995..4b7006a789 100644 --- a/mobile/app/index.tsx +++ b/mobile/app/index.tsx @@ -10,8 +10,10 @@ import { } from "react-native"; import { type ConversationSummary, - DEPLOYMENT_ORGANIZATION_ID, + chooseOrganization, + deploymentOrganization, ORGANIZATION_ID, + organizationChoices, } from "../src/api"; import { listConversations } from "../src/api/generated/conversations/conversations"; import { getDeployment } from "../src/api/generated/organization-settings/organization-settings"; @@ -34,14 +36,18 @@ export default function Home() { }, [session?.user.id]); const loadOptions = useCallback( // The API's `deployment`, which answers before anybody has signed in: asked of the organization every install has. - () => getDeployment(DEPLOYMENT_ORGANIZATION_ID), + async () => getDeployment(await deploymentOrganization()), [], ); const options = useLoad(loadOptions, !session); - // biome-ignore lint/correctness/useExhaustiveDependencies: reload for whoever is signed in now, not the previous person + // The person's organizations and the one they work in; picking another reads everything below again. + const loadOrganizations = useCallback(() => organizationChoices(), []); + const organizations = useLoad(loadOrganizations, Boolean(session)); + const workingIn = organizations.data?.currentId; + // biome-ignore lint/correctness/useExhaustiveDependencies: reload for whoever is signed in now, and wherever they work now const loadConversations = useCallback( () => listConversations(ORGANIZATION_ID, { limit: 100 }), - [session?.user.id], + [session?.user.id, workingIn], ); const conversations = useLoad(loadConversations, Boolean(session)); const nextCursor = @@ -87,6 +93,31 @@ export default function Home() { : "Sign in to OpenBot"} {serverUrl} + {session && (organizations.data?.organizations.length ?? 0) > 1 && ( + + Organization + {organizations.data?.organizations.map((organization) => { + const current = organization.id === workingIn; + return ( +