diff --git a/.github/workflows/desktop.yml b/.github/workflows/desktop.yml index b492ff884b..2e047eb6e4 100644 --- a/.github/workflows/desktop.yml +++ b/.github/workflows/desktop.yml @@ -9,10 +9,10 @@ name: Desktop # it at runtime with an `expect`, so a bad row panics the window rather than failing a type check. on: pull_request: - paths: ["desktop/**", "shared/harnesses.json", "shared/marks/**", "shared/recorder-extension.json", "package.json", ".github/workflows/desktop.yml", ".github/workflows/desktop-build.yml"] + paths: ["desktop/**", "shared/harnesses.json", "shared/marks/**", "shared/recorder-extension.json", "shared/fixtures/client-version/**", "package.json", ".github/workflows/desktop.yml", ".github/workflows/desktop-build.yml"] push: branches: [main] - paths: ["desktop/**", "shared/harnesses.json", "shared/marks/**", "shared/recorder-extension.json", "package.json", ".github/workflows/desktop.yml", ".github/workflows/desktop-build.yml"] + paths: ["desktop/**", "shared/harnesses.json", "shared/marks/**", "shared/recorder-extension.json", "shared/fixtures/client-version/**", "package.json", ".github/workflows/desktop.yml", ".github/workflows/desktop-build.yml"] workflow_call: secrets: OPENBOT_GOOGLE_MODEL_OAUTH_CLIENT_SECRET: diff --git a/api/openapi.yaml b/api/openapi.yaml index 7df444d945..e1ae678b31 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -14,6 +14,8 @@ info: 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. + OpenBot's own apps name themselves on every request in the header `OpenBot-Client`: `/`, where kind is web, desktop, mobile or recorder, such as `OpenBot-Client: desktop/1.1.0`. A header may name more than one, separated by spaces: OpenBot Desktop adds its own to the one its window's page sent. getDeployment says which API versions this OpenBot serves and the oldest release of each app it serves (minimumClients). Every other operation under /api/v2 refuses an app older than that with 400 and the code CLIENT_UPDATE_REQUIRED, whose problem names the app (client) and its minimum (minimumVersion) and whose detail tells the person to update OpenBot. When that minimum was raised because of a security problem in older releases, the problem also says security: true, and getDeployment lists it under securityMinimumClients. A program of your own need not send the header; without it nothing is refused for a version. + This file is the single source of truth: the clients, the server's types, the docs and the contract tests are all generated from it or checked against it. A change that breaks an existing client fails the pull request. servers: - url: http://127.0.0.1:3001 @@ -1690,7 +1692,7 @@ paths: - Organization settings operationId: getDeployment summary: Read what this OpenBot offers - description: 'Return what this OpenBot offers and how people sign in to it: the edition, the features the apps draw, how large an attached file may be, and the sign-in options. Anybody may read it, signed in or not, because the sign-in screen reads it first. Signed in, it is answered in an organization the caller is a member of, and an organization they are not in, the organization `default` included, answers exactly as one that does not exist. Nobody signed in reads it in the organization `default`. It names no identity provider and no version: only whether single sign-on is set up and required.' + description: 'Return what this OpenBot offers and how people sign in to it: the edition, the features the apps draw, how large an attached file may be, and the sign-in options. Anybody may read it, signed in or not, because the sign-in screen reads it first. Signed in, it is answered in an organization the caller is a member of, and an organization they are not in, the organization `default` included, answers exactly as one that does not exist. Nobody signed in reads it in the organization `default`. It names no identity provider and no build: only whether single sign-on is set up and required, and which API versions and which releases of each OpenBot app it serves. It is never refused for the app''s version, so an app reads it first to learn whether it, or the OpenBot, needs an update.' x-openbot-singleton: true security: - {} @@ -22292,6 +22294,26 @@ components: description: 'Whether this OpenBot has computers for Bots at all. False, a Bot has no computer, browser or sign-in to a website, and the computers answer 503 to every call. Not isolatedBots: an OpenBot whose Bots share one computer has computers (true) and cannot give a Bot one of its own (isolatedBots false).' attachmentLimits: $ref: '#/components/schemas/AttachmentLimits' + api: + type: array + description: 'The API versions this OpenBot serves, by major, such as v2. An app that speaks none of them can''t use it: when they are all newer than the app''s, the app needs an update; when they are all older, this OpenBot does. Absent from a release before it was published, which serves v2.' + minItems: 1 + items: + type: string + pattern: ^v[1-9][0-9]{0,3}$ + minimumClients: + $ref: '#/components/schemas/MinimumClients' + securityMinimumClients: + $ref: '#/components/schemas/MinimumClients' + description: 'The part of minimumClients raised because of a security problem in older releases: for each app named, the minimum is there for security. Absent or empty when none is.' + launcherApi: + type: integer + minimum: 1 + description: The version of what OpenBot Desktop supplies when it starts this OpenBot on its own computer. It changes when Desktop must supply something new. + extensionApi: + type: integer + minimum: 1 + description: The version of what the OpenBot Recorder and this OpenBot exchange. AllowlistEntry: type: string minLength: 1 @@ -23467,6 +23489,20 @@ components: description: 'What is wrong, item by item, when a refusal has more than one reason: each entry names the item and says what is wrong with it.' items: type: object + client: + type: string + x-extensible-enum: + - web + - desktop + - mobile + - recorder + description: On CLIENT_UPDATE_REQUIRED, the app the OpenBot-Client header named that is older than this OpenBot serves. A later OpenBot may name another app; read one you don't know as other. + minimumVersion: + type: string + description: On CLIENT_UPDATE_REQUIRED, the oldest release of that app this OpenBot serves. + security: + type: boolean + description: On CLIENT_UPDATE_REQUIRED, true when the minimum the app is below was raised because of a security problem in older releases. ConversationJoinToken: type: object description: 'What a client needs to watch a conversation live: a token, and the socket and topic to use it on (the threadStream channel of api/asyncapi.yaml).' @@ -23835,6 +23871,24 @@ components: type: integer minimum: 1 description: The largest text file, or a file of any other kind. + ClientRelease: + type: string + description: An OpenBot release, such as 1.1.0. + pattern: ^\d{1,6}\.\d{1,6}\.\d{1,6}(-[0-9A-Za-z.-]{1,64})?$ + examples: + - 1.1.0 + MinimumClients: + type: object + description: The oldest release of each OpenBot app this OpenBot serves. An app names itself in the OpenBot-Client header, and one older than its minimum here is refused with CLIENT_UPDATE_REQUIRED, everywhere but this deployment answer. An app not listed has no minimum. An OpenBot serves every app released in the last 12 months, so it names one only where its administrator raised it. Absent from a release before it was published. + properties: + web: + $ref: '#/components/schemas/ClientRelease' + desktop: + $ref: '#/components/schemas/ClientRelease' + mobile: + $ref: '#/components/schemas/ClientRelease' + recorder: + $ref: '#/components/schemas/ClientRelease' ConversationWork: type: object description: 'Something still owed an answer in a conversation: another Bot that was asked and has not answered (handoff), or a routine running into it (routine).' @@ -37111,6 +37165,33 @@ components: retryable: true requestId: req_example traceId: trace_example + clientUpdateRequired: + value: + type: https://open.bot/errors/client-update-required + title: This app is too old for this OpenBot. + status: 400 + detail: This OpenBot needs OpenBot Desktop 1.2.0 or later. Update OpenBot, then try again. + code: CLIENT_UPDATE_REQUIRED + category: validation + retryable: false + requestId: req_example + traceId: trace_example + client: desktop + minimumVersion: 1.2.0 + clientUpdateRequiredSecurity: + value: + type: https://open.bot/errors/client-update-required + title: This app is too old for this OpenBot. + status: 400 + detail: This version of OpenBot has a security problem. Update to keep using it. + code: CLIENT_UPDATE_REQUIRED + category: validation + retryable: false + requestId: req_example + traceId: trace_example + client: desktop + minimumVersion: 1.2.0 + security: true ConversationNotFound: description: The conversation does not exist, was removed, or the caller is not in it, or the organization does not exist. content: @@ -41899,6 +41980,12 @@ components: imageBytes: 104857600 documentBytes: 104857600 fileBytes: 104857600 + api: + - v2 + minimumClients: + desktop: 1.2.0 + launcherApi: 1 + extensionApi: 1 OrganizationSettingsExample: summary: The settings, with what an administrator needs beside them. value: diff --git a/api/openapi/admin-settings.yaml b/api/openapi/admin-settings.yaml index 45fd09f3f0..ef11f29e05 100644 --- a/api/openapi/admin-settings.yaml +++ b/api/openapi/admin-settings.yaml @@ -19,8 +19,11 @@ paths: member of, and an organization they are not in, the organization `default` included, answers exactly as one that does not exist. Nobody signed in reads it in the organization `default`. It names no identity - provider and no version: only whether - single sign-on is set up and required. + provider and no build: only whether + single sign-on is set up and required, and which API versions and + which releases of each OpenBot app it serves. It is never refused for + the app's version, so an app reads it first to learn whether it, or + the OpenBot, needs an update. x-openbot-singleton: true security: - {} @@ -1086,6 +1089,61 @@ components: a Bot one of its own (isolatedBots false). attachmentLimits: $ref: '#/components/schemas/AttachmentLimits' + api: + type: array + description: >- + The API versions this OpenBot serves, by major, such as v2. An app + that speaks none of them can't use it: when they are all newer than + the app's, the app needs an update; when they are all older, this + OpenBot does. Absent from a release before it was published, which + serves v2. + minItems: 1 + items: + type: string + pattern: ^v[1-9][0-9]{0,3}$ + minimumClients: + $ref: '#/components/schemas/MinimumClients' + securityMinimumClients: + $ref: '#/components/schemas/MinimumClients' + description: >- + The part of minimumClients raised because of a security problem in + older releases: for each app named, the minimum is there for + security. Absent or empty when none is. + launcherApi: + type: integer + minimum: 1 + description: >- + The version of what OpenBot Desktop supplies when it starts this + OpenBot on its own computer. It changes when Desktop must supply + something new. + extensionApi: + type: integer + minimum: 1 + description: The version of what the OpenBot Recorder and this OpenBot exchange. + MinimumClients: + type: object + description: >- + The oldest release of each OpenBot app this OpenBot serves. An app + names itself in the OpenBot-Client header, and one older than its + minimum here is refused with CLIENT_UPDATE_REQUIRED, everywhere but + this deployment answer. An app not listed has no minimum. An OpenBot + serves every app released in the last 12 months, so it names one only + where its administrator raised it. Absent from a release before it was + published. + properties: + web: + $ref: '#/components/schemas/ClientRelease' + desktop: + $ref: '#/components/schemas/ClientRelease' + mobile: + $ref: '#/components/schemas/ClientRelease' + recorder: + $ref: '#/components/schemas/ClientRelease' + ClientRelease: + type: string + description: An OpenBot release, such as 1.1.0. + pattern: ^\d{1,6}\.\d{1,6}\.\d{1,6}(-[0-9A-Za-z.-]{1,64})?$ + examples: [1.1.0] AttachmentLimits: type: object description: >- @@ -2179,6 +2237,11 @@ components: imageBytes: 104857600 documentBytes: 104857600 fileBytes: 104857600 + api: [v2] + minimumClients: + desktop: 1.2.0 + launcherApi: 1 + extensionApi: 1 OrganizationSettingsExample: summary: The settings, with what an administrator needs beside them. value: diff --git a/api/openapi/common.yaml b/api/openapi/common.yaml index 0b84e355c6..38d088e3fa 100644 --- a/api/openapi/common.yaml +++ b/api/openapi/common.yaml @@ -57,6 +57,22 @@ info: SIGN_IN_UNAVAILABLE. + OpenBot's own apps name themselves on every request in the header + `OpenBot-Client`: `/`, where kind is web, desktop, + mobile or recorder, such as `OpenBot-Client: desktop/1.1.0`. A header + may name more than one, separated by spaces: OpenBot Desktop adds its + own to the one its window's page sent. getDeployment says which API + versions this OpenBot serves and the oldest release of each app it + serves (minimumClients). Every other operation under /api/v2 refuses + an app older than that with 400 and the code CLIENT_UPDATE_REQUIRED, whose problem + names the app (client) and its minimum (minimumVersion) and whose + detail tells the person to update OpenBot. When that minimum was raised + because of a security problem in older releases, the problem also says + security: true, and getDeployment lists it under securityMinimumClients. + A program of your own need not send the header; without it nothing is + refused for a version. + + This file is the single source of truth: the clients, the server's types, the docs and the contract tests are all generated from it or checked against it. A change that breaks an existing client fails the pull request. @@ -993,6 +1009,21 @@ components: reason: each entry names the item and says what is wrong with it. items: type: object + client: + type: string + x-extensible-enum: [web, desktop, mobile, recorder] + description: >- + On CLIENT_UPDATE_REQUIRED, the app the OpenBot-Client header named + that is older than this OpenBot serves. A later OpenBot may name + another app; read one you don't know as other. + minimumVersion: + type: string + description: On CLIENT_UPDATE_REQUIRED, the oldest release of that app this OpenBot serves. + security: + type: boolean + description: >- + On CLIENT_UPDATE_REQUIRED, true when the minimum the app is below + was raised because of a security problem in older releases. ConversationJoinToken: { $ref: './conversations.yaml#/components/schemas/ConversationJoinToken' } CredentialKind: { $ref: './model-connections.yaml#/components/schemas/CredentialKind' } Credential: { $ref: './model-connections.yaml#/components/schemas/Credential' } @@ -1310,6 +1341,33 @@ components: retryable: true requestId: req_example traceId: trace_example + clientUpdateRequired: + value: + type: https://open.bot/errors/client-update-required + title: This app is too old for this OpenBot. + status: 400 + detail: This OpenBot needs OpenBot Desktop 1.2.0 or later. Update OpenBot, then try again. + code: CLIENT_UPDATE_REQUIRED + category: validation + retryable: false + requestId: req_example + traceId: trace_example + client: desktop + minimumVersion: 1.2.0 + clientUpdateRequiredSecurity: + value: + type: https://open.bot/errors/client-update-required + title: This app is too old for this OpenBot. + status: 400 + detail: This version of OpenBot has a security problem. Update to keep using it. + code: CLIENT_UPDATE_REQUIRED + category: validation + retryable: false + requestId: req_example + traceId: trace_example + client: desktop + minimumVersion: 1.2.0 + security: true ConversationNotFound: description: >- The conversation does not exist, was removed, or the caller is not in diff --git a/app/src/components/layout/client-version-gate.tsx b/app/src/components/layout/client-version-gate.tsx new file mode 100644 index 0000000000..cc56a430d4 --- /dev/null +++ b/app/src/components/layout/client-version-gate.tsx @@ -0,0 +1,236 @@ +import { + APP_UPDATE_SENTENCE, + type Compatibility, + SECURITY_UPDATE_SENTENCE, + SERVER_UPDATE_SENTENCE, +} from "@openbot/shared/client-version"; +import { DOESNT_UPDATE_ITSELF } from "@openbot/shared/desktop-updates"; +import { useMutation, useQuery } from "@tanstack/react-query"; +import { type ReactNode, useSyncExternalStore } from "react"; +import AgentOrb from "@/components/agents/orb/agent-orb"; +import { describe } from "@/components/layout/update-banner"; +import { Button } from "@/components/ui/button"; +import { + type ClientRefusal, + clientRefusal, + subscribeClientRefusal, +} from "@/lib/client-version/refusal"; +import { + type CompatibleApp, + deploymentCompatibilityQueryOptions, + THIS_APP, +} from "@/lib/deployment/queries"; +import { installAppUpdateMutationOptions } from "@/lib/desktop/mutations"; +import { desktopAppUpdateQueryOptions } from "@/lib/desktop/queries"; +import { desktopShell } from "@/lib/desktop/shell"; +import { queryClient } from "@/query-client"; + +/** + * What has to be updated before this app and its OpenBot can work together. + * + * - `page`: this page is older than the OpenBot serves. Loading the page again loads the new one. + * - `desktop`: OpenBot Desktop, around this page, is older than the OpenBot serves. Only its own + * update fixes that, so the screen offers OpenBot Desktop's Update and restart. + * - `server`: the OpenBot is older than this page can use. Only whoever runs it can update it. + * + * `security` on the first two: the minimum was raised because of a security problem in older + * releases, and the screen says so in place of "Update OpenBot". + */ +export type UpdateVerdict = + | { update: "page"; security?: true } + | { update: "desktop"; minimum?: string; security?: true } + | { update: "server" }; + +/** + * The verdict, from a refusal this page met and from what the OpenBot's `deployment` says. A refusal + * comes first: it names the app the OpenBot refused, which inside OpenBot Desktop's window can be + * OpenBot Desktop itself (its relay adds its own name to every request the page makes). + */ +export function updateVerdict( + refusal: ClientRefusal | null, + fit: Compatibility | undefined, + inDesktop: boolean, +): UpdateVerdict | null { + if (refusal) { + const security = refusal.security ? { security: true as const } : {}; + return refusal.client === "desktop" && inDesktop + ? { update: "desktop", minimum: refusal.minimumVersion, ...security } + : { update: "page", ...security }; + } + if (fit?.fit === "app") + return fit.security + ? { update: "page", security: true } + : { update: "page" }; + if (fit?.fit === "server") return { update: "server" }; + return null; +} + +/** + * The app, unless it and its OpenBot can't work together; then one screen that says what to update, + * in place of the app. + * + * At the root, around every route, so it shows before sign-in as well as after, and so nothing that + * would fail is drawn behind it. Two things decide it: the OpenBot's `deployment`, which it never + * refuses for the app's version and which the app reads first, and a refusal of any request for + * being too old an app (`lib/client-version/refusal.ts`), which is how a tab left open across an + * upgrade finds out. While neither has said anything, or the `deployment` could not be read, the app + * draws as it always did. + * + * `app` is this app; a test names another to see the other verdicts drawn. + */ +export function ClientVersionGate({ + children, + app = THIS_APP, +}: { + children: ReactNode; + app?: CompatibleApp; +}) { + const refusal = useSyncExternalStore( + subscribeClientRefusal, + clientRefusal, + () => null, + ); + const fit = useQuery(deploymentCompatibilityQueryOptions(app)); + const verdict = updateVerdict(refusal, fit.data, desktopShell() !== null); + return verdict ? : children; +} + +/** + * The screen itself: the sign-in screen's frame (the orb, the heading, the column), so it reads as + * OpenBot's own, with one sentence for a heading and one way forward. + * + * No "Reload the page": the same screen shows in OpenBot Desktop's window, which has no reload + * button. The buttons load the page again themselves. + */ +export function UpdateScreen({ verdict }: { verdict: UpdateVerdict }) { + return ( +
+
+ + {verdict.update === "server" ? ( + + ) : verdict.update === "desktop" ? ( + + ) : ( + + )} +
+
+ ); +} + +function Heading({ children }: { children: ReactNode }) { + return ( +

+ {children} +

+ ); +} + +function Line({ children }: { children: ReactNode }) { + return ( +

+ {children} +

+ ); +} + +function loadAgain() { + window.location.reload(); +} + +/** + * This page is older than the OpenBot serves: the OpenBot serves the new one on the next load. For a + * security problem the heading says so and already says what to do, so no line repeats it. + */ +function PageUpdate({ security }: { security: boolean }) { + return ( + <> + {security ? ( + {SECURITY_UPDATE_SENTENCE} + ) : ( + <> + {APP_UPDATE_SENTENCE} + This page is from an older version of OpenBot. + + )} + + + ); +} + +/** The OpenBot is older than this page can use. Loading again shows whether it has been updated. */ +function ServerUpdate() { + return ( + <> + {SERVER_UPDATE_SENTENCE} + This OpenBot is on a release this page can't use yet. + + + ); +} + +/** + * OpenBot Desktop is older than the OpenBot serves. Its own Update and restart, as the update banner + * offers it, with how far the download has got; or, on a build that never updates itself, what to + * do instead. + */ +function DesktopUpdate({ + minimum, + security, +}: { + minimum?: string; + security: boolean; +}) { + const offer = useQuery(desktopAppUpdateQueryOptions()); + const install = useMutation(installAppUpdateMutationOptions(queryClient)); + const updatesItself = offer.data?.updatesItself !== false; + const progress = offer.data?.installing ?? null; + const busy = install.isPending || progress !== null; + return ( + <> + + {security ? SECURITY_UPDATE_SENTENCE : APP_UPDATE_SENTENCE} + + + {minimum + ? `This OpenBot needs OpenBot Desktop ${minimum} or later.` + : "This OpenBot needs a newer OpenBot Desktop."} + + {offer.isLoading ? null : updatesItself ? ( + + ) : ( + {DOESNT_UPDATE_ITSELF} + )} + {install.error && !busy ? ( +

+ Couldn't install the update: {reason(install.error)} +

+ ) : null} + + ); +} + +/** The desktop app refuses with its own sentence, as a plain string. */ +function reason(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} diff --git a/app/src/lib/api/generated/model/clientRelease.ts b/app/src/lib/api/generated/model/clientRelease.ts new file mode 100644 index 0000000000..45b5f0897a --- /dev/null +++ b/app/src/lib/api/generated/model/clientRelease.ts @@ -0,0 +1,9 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ + +/** + * An OpenBot release, such as 1.1.0. + * @pattern ^\d{1,6}\.\d{1,6}\.\d{1,6}(-[0-9A-Za-z.-]{1,64})?$ + */ +export type ClientRelease = string; diff --git a/app/src/lib/api/generated/model/deployment.ts b/app/src/lib/api/generated/model/deployment.ts index 30fdbaebc1..b113d710fb 100644 --- a/app/src/lib/api/generated/model/deployment.ts +++ b/app/src/lib/api/generated/model/deployment.ts @@ -4,6 +4,7 @@ import type { AttachmentLimits } from "./attachmentLimits"; import type { DeploymentAuthProvidersItem } from "./deploymentAuthProvidersItem"; import type { DeploymentEdition } from "./deploymentEdition"; +import type { MinimumClients } from "./minimumClients"; /** * What this OpenBot offers and how people sign in to it. @@ -36,4 +37,23 @@ export interface Deployment { /** Whether this OpenBot has computers for Bots at all. False, a Bot has no computer, browser or sign-in to a website, and the computers answer 503 to every call. Not isolatedBots: an OpenBot whose Bots share one computer has computers (true) and cannot give a Bot one of its own (isolatedBots false). */ botComputers: boolean; attachmentLimits?: AttachmentLimits; + /** + * The API versions this OpenBot serves, by major, such as v2. An app that speaks none of them can't use it: when they are all newer than the app's, the app needs an update; when they are all older, this OpenBot does. Absent from a release before it was published, which serves v2. + * @minItems 1 + * @items.pattern ^v[1-9][0-9]{0,3}$ + */ + api?: string[]; + minimumClients?: MinimumClients; + /** The part of minimumClients raised because of a security problem in older releases: for each app named, the minimum is there for security. Absent or empty when none is. */ + securityMinimumClients?: MinimumClients; + /** + * The version of what OpenBot Desktop supplies when it starts this OpenBot on its own computer. It changes when Desktop must supply something new. + * @minimum 1 + */ + launcherApi?: number; + /** + * The version of what the OpenBot Recorder and this OpenBot exchange. + * @minimum 1 + */ + extensionApi?: number; } diff --git a/app/src/lib/api/generated/model/index.ts b/app/src/lib/api/generated/model/index.ts index f23cd5219d..a4de03da27 100644 --- a/app/src/lib/api/generated/model/index.ts +++ b/app/src/lib/api/generated/model/index.ts @@ -418,6 +418,7 @@ export * from "./clearBotBrowserHeaders"; export * from "./clearPersonBrowserHeaders"; export * from "./clearTeamBotConsentsHeaders"; export * from "./clickComputerHeaders"; +export * from "./clientRelease"; export * from "./completeGoalHeaders"; export * from "./completeOnboardingHeaders"; export * from "./component"; @@ -998,6 +999,7 @@ export * from "./memorySourceToolInputSchema"; export * from "./memorySourceToolPage"; export * from "./memoryUnavailableResponse"; export * from "./messageListEmphasis"; +export * from "./minimumClients"; export * from "./modelCatalogue"; export * from "./modelCatalogueExposure"; export * from "./modelCatalogueProvider"; diff --git a/app/src/lib/api/generated/model/minimumClients.ts b/app/src/lib/api/generated/model/minimumClients.ts new file mode 100644 index 0000000000..bedba5d4b8 --- /dev/null +++ b/app/src/lib/api/generated/model/minimumClients.ts @@ -0,0 +1,14 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ +import type { ClientRelease } from "./clientRelease"; + +/** + * The oldest release of each OpenBot app this OpenBot serves. An app names itself in the OpenBot-Client header, and one older than its minimum here is refused with CLIENT_UPDATE_REQUIRED, everywhere but this deployment answer. An app not listed has no minimum. An OpenBot serves every app released in the last 12 months, so it names one only where its administrator raised it. Absent from a release before it was published. + */ +export interface MinimumClients { + web?: ClientRelease; + desktop?: ClientRelease; + mobile?: ClientRelease; + recorder?: ClientRelease; +} diff --git a/app/src/lib/api/generated/model/problem.ts b/app/src/lib/api/generated/model/problem.ts index 703b301dfb..2dc1292f00 100644 --- a/app/src/lib/api/generated/model/problem.ts +++ b/app/src/lib/api/generated/model/problem.ts @@ -31,4 +31,10 @@ export interface Problem { capability?: string; /** What is wrong, item by item, when a refusal has more than one reason: each entry names the item and says what is wrong with it. */ problems?: ProblemProblemsItem[]; + /** On CLIENT_UPDATE_REQUIRED, the app the OpenBot-Client header named that is older than this OpenBot serves. A later OpenBot may name another app; read one you don't know as other. */ + client?: string; + /** On CLIENT_UPDATE_REQUIRED, the oldest release of that app this OpenBot serves. */ + minimumVersion?: string; + /** On CLIENT_UPDATE_REQUIRED, true when the minimum the app is below was raised because of a security problem in older releases. */ + security?: boolean; } diff --git a/app/src/lib/api/generated/organization-settings/organization-settings.msw.ts b/app/src/lib/api/generated/organization-settings/organization-settings.msw.ts index e5d623fe6f..c97029e75a 100644 --- a/app/src/lib/api/generated/organization-settings/organization-settings.msw.ts +++ b/app/src/lib/api/generated/organization-settings/organization-settings.msw.ts @@ -33,6 +33,10 @@ export const getGetDeploymentResponseMock = (): Deployment => ({ documentBytes: 104857600, fileBytes: 104857600, }, + api: ["v2"], + minimumClients: { desktop: "1.2.0" }, + launcherApi: 1, + extensionApi: 1, }); export const getGetOrganizationSettingsResponseMock = diff --git a/app/src/lib/api/generated/organization-settings/organization-settings.ts b/app/src/lib/api/generated/organization-settings/organization-settings.ts index 3aeaebb45d..b0029d371d 100644 --- a/app/src/lib/api/generated/organization-settings/organization-settings.ts +++ b/app/src/lib/api/generated/organization-settings/organization-settings.ts @@ -101,7 +101,7 @@ export const getGetDeploymentUrl = (organizationId: string) => { }; /** - * Return what this OpenBot offers and how people sign in to it: the edition, the features the apps draw, how large an attached file may be, and the sign-in options. Anybody may read it, signed in or not, because the sign-in screen reads it first. Signed in, it is answered in an organization the caller is a member of, and an organization they are not in, the organization `default` included, answers exactly as one that does not exist. Nobody signed in reads it in the organization `default`. It names no identity provider and no version: only whether single sign-on is set up and required. + * Return what this OpenBot offers and how people sign in to it: the edition, the features the apps draw, how large an attached file may be, and the sign-in options. Anybody may read it, signed in or not, because the sign-in screen reads it first. Signed in, it is answered in an organization the caller is a member of, and an organization they are not in, the organization `default` included, answers exactly as one that does not exist. Nobody signed in reads it in the organization `default`. It names no identity provider and no build: only whether single sign-on is set up and required, and which API versions and which releases of each OpenBot app it serves. It is never refused for the app's version, so an app reads it first to learn whether it, or the OpenBot, needs an update. * @summary Read what this OpenBot offers */ export const getDeployment = async ( diff --git a/app/src/lib/api/generated/organization-settings/organization-settings.zod.ts b/app/src/lib/api/generated/organization-settings/organization-settings.zod.ts index f31b5b622f..9b33285388 100644 --- a/app/src/lib/api/generated/organization-settings/organization-settings.zod.ts +++ b/app/src/lib/api/generated/organization-settings/organization-settings.zod.ts @@ -4,7 +4,7 @@ import * as zod from "zod"; /** - * Return what this OpenBot offers and how people sign in to it: the edition, the features the apps draw, how large an attached file may be, and the sign-in options. Anybody may read it, signed in or not, because the sign-in screen reads it first. Signed in, it is answered in an organization the caller is a member of, and an organization they are not in, the organization `default` included, answers exactly as one that does not exist. Nobody signed in reads it in the organization `default`. It names no identity provider and no version: only whether single sign-on is set up and required. + * Return what this OpenBot offers and how people sign in to it: the edition, the features the apps draw, how large an attached file may be, and the sign-in options. Anybody may read it, signed in or not, because the sign-in screen reads it first. Signed in, it is answered in an organization the caller is a member of, and an organization they are not in, the organization `default` included, answers exactly as one that does not exist. Nobody signed in reads it in the organization `default`. It names no identity provider and no build: only whether single sign-on is set up and required, and which API versions and which releases of each OpenBot app it serves. It is never refused for the app's version, so an app reads it first to learn whether it, or the OpenBot, needs an update. * @summary Read what this OpenBot offers */ @@ -17,6 +17,32 @@ export const GetDeploymentParams = zod.object({ ), }); +export const getDeploymentResponseApiItemRegExp = new RegExp( + "^v[1-9][0-9]{0,3}$", +); + +export const getDeploymentResponseMinimumClientsWebRegExp = new RegExp( + "^\\d{1,6}\\.\\d{1,6}\\.\\d{1,6}(-[0-9A-Za-z.-]{1,64})?$", +); +export const getDeploymentResponseMinimumClientsDesktopRegExp = new RegExp( + "^\\d{1,6}\\.\\d{1,6}\\.\\d{1,6}(-[0-9A-Za-z.-]{1,64})?$", +); +export const getDeploymentResponseMinimumClientsMobileRegExp = new RegExp( + "^\\d{1,6}\\.\\d{1,6}\\.\\d{1,6}(-[0-9A-Za-z.-]{1,64})?$", +); +export const getDeploymentResponseMinimumClientsRecorderRegExp = new RegExp( + "^\\d{1,6}\\.\\d{1,6}\\.\\d{1,6}(-[0-9A-Za-z.-]{1,64})?$", +); +export const getDeploymentResponseSecurityMinimumClientsWebRegExp = new RegExp( + "^\\d{1,6}\\.\\d{1,6}\\.\\d{1,6}(-[0-9A-Za-z.-]{1,64})?$", +); +export const getDeploymentResponseSecurityMinimumClientsDesktopRegExp = + new RegExp("^\\d{1,6}\\.\\d{1,6}\\.\\d{1,6}(-[0-9A-Za-z.-]{1,64})?$"); +export const getDeploymentResponseSecurityMinimumClientsMobileRegExp = + new RegExp("^\\d{1,6}\\.\\d{1,6}\\.\\d{1,6}(-[0-9A-Za-z.-]{1,64})?$"); +export const getDeploymentResponseSecurityMinimumClientsRecorderRegExp = + new RegExp("^\\d{1,6}\\.\\d{1,6}\\.\\d{1,6}(-[0-9A-Za-z.-]{1,64})?$"); + export const GetDeploymentResponse = zod .object({ edition: zod @@ -88,6 +114,81 @@ export const GetDeploymentResponse = zod .describe( "How large a file attached to a message may be, by kind, in bytes. An upload over its kind's limit is refused. Absent, as from an older OpenBot, the limits are 8388608 for an image or a document (a PDF, or a Word, Excel or PowerPoint file) and 1048576 for any other file. The limits can rise while OpenBot runs, so a client reads them again rather than keeping them for good. What a Bot's model is shown of a large file is a separate matter: the file is kept and can be downloaded whatever the model can read of it.", ), + api: zod + .array(zod.string().regex(getDeploymentResponseApiItemRegExp)) + .min(1) + .optional() + .describe( + "The API versions this OpenBot serves, by major, such as v2. An app that speaks none of them can't use it: when they are all newer than the app's, the app needs an update; when they are all older, this OpenBot does. Absent from a release before it was published, which serves v2.", + ), + minimumClients: zod + .object({ + web: zod + .string() + .regex(getDeploymentResponseMinimumClientsWebRegExp) + .optional() + .describe("An OpenBot release, such as 1.1.0."), + desktop: zod + .string() + .regex(getDeploymentResponseMinimumClientsDesktopRegExp) + .optional() + .describe("An OpenBot release, such as 1.1.0."), + mobile: zod + .string() + .regex(getDeploymentResponseMinimumClientsMobileRegExp) + .optional() + .describe("An OpenBot release, such as 1.1.0."), + recorder: zod + .string() + .regex(getDeploymentResponseMinimumClientsRecorderRegExp) + .optional() + .describe("An OpenBot release, such as 1.1.0."), + }) + .optional() + .describe( + "The oldest release of each OpenBot app this OpenBot serves. An app names itself in the OpenBot-Client header, and one older than its minimum here is refused with CLIENT_UPDATE_REQUIRED, everywhere but this deployment answer. An app not listed has no minimum. An OpenBot serves every app released in the last 12 months, so it names one only where its administrator raised it. Absent from a release before it was published.", + ), + securityMinimumClients: zod + .object({ + web: zod + .string() + .regex(getDeploymentResponseSecurityMinimumClientsWebRegExp) + .optional() + .describe("An OpenBot release, such as 1.1.0."), + desktop: zod + .string() + .regex(getDeploymentResponseSecurityMinimumClientsDesktopRegExp) + .optional() + .describe("An OpenBot release, such as 1.1.0."), + mobile: zod + .string() + .regex(getDeploymentResponseSecurityMinimumClientsMobileRegExp) + .optional() + .describe("An OpenBot release, such as 1.1.0."), + recorder: zod + .string() + .regex(getDeploymentResponseSecurityMinimumClientsRecorderRegExp) + .optional() + .describe("An OpenBot release, such as 1.1.0."), + }) + .optional() + .describe( + "The part of minimumClients raised because of a security problem in older releases: for each app named, the minimum is there for security. Absent or empty when none is.", + ), + launcherApi: zod + .int() + .min(1) + .optional() + .describe( + "The version of what OpenBot Desktop supplies when it starts this OpenBot on its own computer. It changes when Desktop must supply something new.", + ), + extensionApi: zod + .int() + .min(1) + .optional() + .describe( + "The version of what the OpenBot Recorder and this OpenBot exchange.", + ), }) .describe("What this OpenBot offers and how people sign in to it."); diff --git a/app/src/lib/auth/client.ts b/app/src/lib/auth/client.ts index 90c438cb54..b656e31fef 100644 --- a/app/src/lib/auth/client.ts +++ b/app/src/lib/auth/client.ts @@ -1,13 +1,15 @@ import { ssoClient } from "@better-auth/sso/client"; import { createAuthClient } from "better-auth/react"; +import { withClientName } from "@/lib/client"; import type { AuthProviderId } from "./queries"; export const authClient = createAuthClient({ plugins: [ssoClient()], fetchOptions: { // The page's fetch at the time of each call, as every other request in the app uses it, rather - // than the one there was when this module loaded. - customFetchImpl: (input, init) => fetch(input, init), + // than the one there was when this module loaded. Naming this app, as every request does. + customFetchImpl: (input, init) => + fetch(input, { ...init, headers: withClientName(init?.headers) }), }, }); diff --git a/app/src/lib/client-version/refusal.ts b/app/src/lib/client-version/refusal.ts new file mode 100644 index 0000000000..59ef6a1b92 --- /dev/null +++ b/app/src/lib/client-version/refusal.ts @@ -0,0 +1,98 @@ +/** + * Whether the OpenBot this page talks to refused it for being too old an app. + * + * Every request names this app in the `OpenBot-Client` header (`lib/client.ts`). An OpenBot whose + * oldest served release of that app is newer than it refuses every request except its `deployment` + * with a 400 problem whose code is CLIENT_UPDATE_REQUIRED, naming the app (`client`) and the oldest + * release it serves (`minimumVersion`), and `security: true` when that minimum was raised because of a + * security problem in older releases. Inside OpenBot Desktop's window the desktop app adds its own + * name to the page's header, so there the app named can be OpenBot Desktop rather than this page. + * + * `lib/client.ts` hands every 400 here before the caller sees it. The first refusal is kept until the + * page is loaded again, and the update screen reads it (`components/layout/client-version-gate.tsx`), + * so a tab left open across an upgrade shows "Update OpenBot" in place of a screen whose read failed. + * + * No imports from the app, so the transport can report to it without a cycle. + */ +import { + CLIENT_KINDS, + CLIENT_UPDATE_REQUIRED, + type ClientKind, + isVersion, +} from "@openbot/shared/client-version"; + +/** + * The app the OpenBot refused, the oldest release of it that OpenBot serves, and `security` when that + * minimum is there for a security problem. + */ +export type ClientRefusal = { + client: ClientKind; + minimumVersion?: string; + security?: true; +}; + +let refused: ClientRefusal | null = null; +const listeners = new Set<() => void>(); + +/** The refusal a problem body is, or null when it is some other answer. */ +export function clientRefusalOf(body: unknown): ClientRefusal | null { + if (!body || typeof body !== "object" || Array.isArray(body)) return null; + const problem = body as { + code?: unknown; + client?: unknown; + minimumVersion?: unknown; + security?: unknown; + }; + if (problem.code !== CLIENT_UPDATE_REQUIRED) return null; + // A refusal that names no app we know is still this page's to act on: it is the page that asked. + const client = (CLIENT_KINDS as readonly unknown[]).includes(problem.client) + ? (problem.client as ClientKind) + : "web"; + return { + client, + ...(isVersion(problem.minimumVersion) + ? { minimumVersion: problem.minimumVersion } + : {}), + ...(problem.security === true ? { security: true as const } : {}), + }; +} + +/** + * A request was answered 400. Its body is read from a copy, so the caller still reads its own; the + * promise settles once it has been, so the caller can fail knowing whether this was the reason. + */ +export function noteRefusal(response: Response): Promise { + if (response.status !== 400 || refused !== null) return Promise.resolve(); + const type = response.headers.get("content-type") ?? ""; + if (!type.includes("json")) return Promise.resolve(); + return response + .clone() + .json() + .then( + (body: unknown) => { + const refusal = clientRefusalOf(body); + if (refusal === null || refused !== null) return; + refused = refusal; + for (const listener of listeners) listener(); + }, + () => undefined, + ); +} + +/** For `useSyncExternalStore`. */ +export function subscribeClientRefusal(listener: () => void): () => void { + listeners.add(listener); + return () => listeners.delete(listener); +} + +/** The refusal this page met, or null while it has met none. */ +export function clientRefusal(): ClientRefusal | null { + return refused; +} + +/** Forget the refusal, as loading the page again does. For tests, which share one module. */ +export function forgetClientRefusal(): void { + if (refused === null) return; + refused = null; + for (const listener of listeners) listener(); +} diff --git a/app/src/lib/client.ts b/app/src/lib/client.ts index 21e481ce2f..0fcbd820f8 100644 --- a/app/src/lib/client.ts +++ b/app/src/lib/client.ts @@ -12,8 +12,47 @@ * guessed the envelope would be a client that had to be argued with. */ +import { CLIENT_HEADER, clientToken } from "@openbot/shared/client-version"; +import { noteRefusal } from "@/lib/client-version/refusal"; import { noteAnswer, noteNoAnswer } from "@/lib/desktop/reachability"; +/** + * This app as it names itself to its OpenBot: `web/`, the release it was built from + * (shared/client-version.ts). The server refuses an app older than the oldest it serves. + */ +export const CLIENT_NAME = clientToken("web"); + +/** + * `headers` with this app named in them, in the same shape they were given: a record, a `Headers`, + * or a list of pairs. For the few requests the app makes to OpenBot without the client: the + * runtime's, sign-in's and finishing a consent. A file's own address is read like a picture's, + * which carries no header either, and can be sent on to wherever the file is kept. + */ +export function withClientName( + headers: Record, +): Record; +export function withClientName(headers?: HeadersInit): HeadersInit; +export function withClientName(headers?: HeadersInit): HeadersInit { + const header = CLIENT_HEADER.toLowerCase(); + if (headers instanceof Headers) { + const named = new Headers(headers); + named.set(CLIENT_HEADER, CLIENT_NAME); + return named; + } + if (Array.isArray(headers)) { + return [ + ...headers.filter(([name]) => name.toLowerCase() !== header), + [CLIENT_HEADER, CLIENT_NAME], + ]; + } + const named: Record = {}; + for (const [name, value] of Object.entries(headers ?? {})) { + if (name.toLowerCase() !== header) named[name] = value; + } + named[CLIENT_HEADER] = CLIENT_NAME; + return named; +} + export type ClientOptions = { /** Absent means GET. */ method?: string; @@ -41,17 +80,26 @@ export type ClientOptions = { * * A 502 is read before it is handed back, so a read failing on the relay's own answer fails with * the connection already known to be lost, and waits for OpenBot (`connection-lost.ts`). + * + * Every request names this app ({@link CLIENT_NAME}). A 400 is read before it is handed back too, so + * a refusal for being too old an app is known before the request fails, and the update screen shows + * in place of whatever failed (`lib/client-version/refusal.ts`). */ async function request(path: string, init: RequestInit): Promise { let response: Response; try { - response = await fetch(path, { ...init, credentials: "include" }); + response = await fetch(path, { + ...init, + headers: withClientName(init.headers), + credentials: "include", + }); } catch (error) { noteNoAnswer(error); throw error; } const noted = noteAnswer(response); if (response.status === 502) await noted; + if (response.status === 400) await noteRefusal(response); return response; } diff --git a/app/src/lib/copilot/provider.tsx b/app/src/lib/copilot/provider.tsx index 91b1533755..8e0b797814 100644 --- a/app/src/lib/copilot/provider.tsx +++ b/app/src/lib/copilot/provider.tsx @@ -5,6 +5,7 @@ import { } from "@openbot/shared/person-time-zone"; import { useQuery } from "@tanstack/react-query"; import { type ReactNode, useMemo } from "react"; +import { withClientName } from "@/lib/client"; import { deploymentCapabilitiesQueryOptions } from "@/lib/deployment/queries"; import { organizationHeaders, @@ -50,8 +51,9 @@ export function CopilotProvider({ children }: { children: ReactNode }) { * it in the one named, when the person is a member of it. */ const organization = useCurrentOrganizationId(); + // And this app, as every request to OpenBot names it (lib/client.ts). const headers = useMemo( - () => organizationHeaders(organization), + () => withClientName(organizationHeaders(organization)), [organization], ); diff --git a/app/src/lib/deployment/queries.ts b/app/src/lib/deployment/queries.ts index eb6dc99e5a..f8a35f8a60 100644 --- a/app/src/lib/deployment/queries.ts +++ b/app/src/lib/deployment/queries.ts @@ -1,3 +1,9 @@ +import { + type ClientKind, + type Compatibility, + compatibility, + RELEASE, +} from "@openbot/shared/client-version"; import { type QueryClient, queryOptions, @@ -103,12 +109,59 @@ export async function readDeployment(options: { } } +/** An app as `compatibility` reads it: its kind, its release, and the API versions it speaks. */ +export type CompatibleApp = { + kind: ClientKind; + version: string; + speaks?: readonly string[]; +}; + +/** This app: the web app, the release it was built from, speaking this release's API versions. */ +export const THIS_APP: CompatibleApp = { kind: "web", version: RELEASE }; + export const deploymentKeys = { all: ["deployment"] as const, capabilities: () => ["deployment", "capabilities"] as const, attachmentLimits: () => ["deployment", "attachment-limits"] as const, + compatibility: (app: CompatibleApp) => + [ + "deployment", + "compatibility", + { kind: app.kind, version: app.version, speaks: app.speaks ?? null }, + ] as const, }; +/** + * Whether this app and the OpenBot it talks to can work together, as that OpenBot's `deployment` + * says: the API versions it serves and the oldest release of each app it serves + * (`compatibility` in shared/client-version.ts, which every OpenBot app decides by). + * + * `deployment` is the one read an OpenBot never refuses for the app's version, so this is how a page + * finds out before anything else fails. Read again every so often and when the tab is looked at + * again, like the attachment limits, because the OpenBot can be upgraded while the tab stays open. + * Not answered (an OpenBot from before the v2 API, or one that failed to answer) is not a verdict: + * the screens say their own failures as they always did. + * + * `app` is this app; a test names another to see the other verdicts drawn. + */ +export function deploymentCompatibilityQueryOptions( + app: CompatibleApp = THIS_APP, +) { + return queryOptions({ + queryKey: deploymentKeys.compatibility(app), + staleTime: 60_000, + refetchOnWindowFocus: true, + queryFn: async ({ signal }): Promise => + compatibility( + await readDeployment({ + signal, + fallback: "Couldn't load which apps OpenBot serves.", + }), + app, + ), + }); +} + /** * How large an attached file may be, as this server says, read again every so often. * diff --git a/app/src/lib/plugins/finish-on-return.ts b/app/src/lib/plugins/finish-on-return.ts index 24bf46dc21..cb83b38e1f 100644 --- a/app/src/lib/plugins/finish-on-return.ts +++ b/app/src/lib/plugins/finish-on-return.ts @@ -1,4 +1,5 @@ import { VERIFIER_PATH } from "@/lib/auth/resume"; +import { withClientName } from "@/lib/client"; import { desktopShell } from "@/lib/desktop/shell"; /** The step waiting for the window to be back in front, while there is one. */ @@ -45,6 +46,7 @@ export async function finishInBackground(): Promise { await fetch(VERIFIER_PATH, { credentials: "same-origin", redirect: "manual", + headers: withClientName(), }); } catch { // Nothing to tell anybody: the connections read that follows says whether it was finished. diff --git a/app/src/routes/__root.tsx b/app/src/routes/__root.tsx index 7293d47cbd..90b7b76c64 100644 --- a/app/src/routes/__root.tsx +++ b/app/src/routes/__root.tsx @@ -4,6 +4,7 @@ import { Outlet, } from "@tanstack/react-router"; import { useEffect } from "react"; +import { ClientVersionGate } from "@/components/layout/client-version-gate"; import { ThemeProvider } from "@/components/theme-provider"; import { Toaster } from "@/components/ui/toast"; import { TooltipProvider } from "@/components/ui/tooltip"; @@ -126,7 +127,10 @@ function RootComponent() {
- + {/* In place of every route when this app and its OpenBot can't work together. */} + + + diff --git a/app/tests/client-name-header.test.ts b/app/tests/client-name-header.test.ts new file mode 100644 index 0000000000..f480e0e709 --- /dev/null +++ b/app/tests/client-name-header.test.ts @@ -0,0 +1,99 @@ +/** + * Every request this app makes to its OpenBot names the app: `OpenBot-Client: web/`. + * + * The server reads the header to refuse an app older than it serves (CLIENT_UPDATE_REQUIRED) and to + * count which apps still call what. These requests leave through the app's real transport + * (`lib/client.ts`, and the generated client's mutator on top of it) and reach a real HTTP server on + * this computer, which records what arrived. The page is addressed at that server, as a page is at + * the OpenBot that served it. + */ +import { afterAll, beforeAll, beforeEach, expect, test } from "bun:test"; +import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import { + CLIENT_HEADER, + clientToken, + RELEASE, +} from "@openbot/shared/client-version"; +import { getDeployment } from "@/lib/api/generated/organization-settings/organization-settings"; +import { listOrganizations } from "@/lib/api/generated/organizations/organizations"; +import { client, tryClient } from "@/lib/client"; +import { nativeFetch, pageFetch } from "./page-fetch"; +import { settleReactWork } from "./settle-react-work"; + +type Seen = { path: string; headers: Headers }; +let seen: Seen[] = []; +let openbot: ReturnType; +// The server answers in the runtime's own Response, not the page's. +const NativeResponse = globalThis.Response; + +beforeAll(() => { + openbot = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + fetch(request) { + const path = new URL(request.url).pathname; + seen.push({ path, headers: request.headers }); + if (path.endsWith("/deployment")) + return NativeResponse.json({ edition: "team", api: ["v2"] }); + if (path === "/api/v2/people/me/organizations") + return NativeResponse.json({ organizations: [], nextCursor: null }); + return NativeResponse.json({ thing: { id: "one" } }); + }, + }); + GlobalRegistrator.register({ url: `http://127.0.0.1:${openbot.port}/` }); + // The page is at the server. + globalThis.fetch = pageFetch(); +}); +beforeEach(() => { + seen = []; +}); +afterAll(async () => { + globalThis.fetch = nativeFetch; + await settleReactWork(); + await GlobalRegistrator.unregister(); + openbot.stop(true); +}); + +const NAMED = clientToken("web", RELEASE); + +function headerAt(path: string): string | null { + const request = seen.find((one) => one.path === path); + if (!request) throw new Error(`nothing reached ${path}`); + return request.headers.get(CLIENT_HEADER); +} + +test(`a request through the client says ${NAMED}`, async () => { + expect(NAMED).toBe(`web/${RELEASE}`); + await client("/api/things/one", "thing"); + expect(headerAt("/api/things/one")).toBe(NAMED); +}); + +test("a generated operation says it too", async () => { + await getDeployment("default", { fallback: "Couldn't load OpenBot." }); + expect(headerAt("/api/v2/organizations/default/deployment")).toBe(NAMED); +}); + +test("beside the headers a caller gives, as a record or as Headers", async () => { + await tryClient("/api/things/record", { + method: "POST", + body: { a: 1 }, + headers: { "OpenBot-Organization": "default" }, + }); + const record = seen.find((one) => one.path === "/api/things/record"); + expect(record?.headers.get(CLIENT_HEADER)).toBe(NAMED); + expect(record?.headers.get("OpenBot-Organization")).toBe("default"); + expect(record?.headers.get("content-type")).toBe("application/json"); + + // getDeployment hands its options' headers to the transport as they were given: here, Headers. + await getDeployment("given", { + headers: new Headers({ "OpenBot-Organization": "default" }), + }); + const given = seen.find( + (one) => one.path === "/api/v2/organizations/given/deployment", + ); + expect(given?.headers.get(CLIENT_HEADER)).toBe(NAMED); + expect(given?.headers.get("OpenBot-Organization")).toBe("default"); + + await listOrganizations({ limit: 1 }); + expect(headerAt("/api/v2/people/me/organizations")).toBe(NAMED); +}); diff --git a/app/tests/client-version-gate.test.tsx b/app/tests/client-version-gate.test.tsx new file mode 100644 index 0000000000..fd7be15e9f --- /dev/null +++ b/app/tests/client-version-gate.test.tsx @@ -0,0 +1,454 @@ +/** + * When this app and the OpenBot it talks to can't work together, the person reads one sentence in + * place of the app: "Update OpenBot" when the app is too old, "Ask whoever runs your OpenBot to + * update it" when the OpenBot is. Before sign-in as well as after, and nothing that fails behind it. + * + * The app is the real one at its root: the root route's own component, the sign-in screen and the + * sign-in gate, the app's query client and its transport. The OpenBot is a real HTTP server on this + * computer answering `deployment` with the real answers in shared/fixtures/client-version/cases.json, + * and refusing every other v2 operation the way an OpenBot does: an app the header names below the + * minimum its `deployment` publishes gets 400 CLIENT_UPDATE_REQUIRED, with the rules the server uses + * (shared/client-version.ts). A tab left open across an upgrade meets that refusal on any request, + * and the screen comes up the same; the spec's own example of the refusal is served for that. + */ +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + expect, + test, +} from "bun:test"; +import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import { + APP_UPDATE_SENTENCE, + belowMinimum, + CLIENT_HEADER, + CLIENT_UPDATE_REQUIRED, + type ClientKind, + clientUpdateDetail, + compatibility, + parseClientHeader, + RELEASE, + SECURITY_UPDATE_SENTENCE, + SERVER_UPDATE_SENTENCE, +} from "@openbot/shared/client-version"; +import { DOESNT_UPDATE_ITSELF } from "@openbot/shared/desktop-updates"; +import { QueryClientProvider } from "@tanstack/react-query"; +import { + type AnyRoute, + createMemoryHistory, + createRootRouteWithContext, + createRoute, + createRouter, + Outlet, + RouterProvider, +} from "@tanstack/react-router"; +import { cleanup, render, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { ClientVersionGate } from "@/components/layout/client-version-gate"; +import { forgetClientRefusal } from "@/lib/client-version/refusal"; +import type { CompatibleApp } from "@/lib/deployment/queries"; +import { queryClient } from "@/query-client"; +import type { RouterContext } from "@/router-context"; +import { Route as RootRoute } from "@/routes/__root"; +import { Route as AuthedRoute } from "@/routes/_authed"; +import { Route as SignRoute } from "@/routes/sign"; +import cases from "../../shared/fixtures/client-version/cases.json"; +import { nativeFetch, pageFetch } from "./page-fetch"; +import { settleReactWork } from "./settle-react-work"; + +type DeploymentName = keyof typeof cases.deployments; + +/** This app, as it names itself. */ +const THIS_WEB = { kind: "web" as const, version: RELEASE }; + +/** The spec's example of the refusal (api/openapi/common.yaml, `clientUpdateRequired`), as is. */ +const SPEC_REFUSAL = { + type: "https://open.bot/errors/client-update-required", + title: "This app is too old for this OpenBot.", + status: 400, + detail: + "This OpenBot needs OpenBot Desktop 1.2.0 or later. Update OpenBot, then try again.", + code: "CLIENT_UPDATE_REQUIRED", + category: "validation", + retryable: false, + requestId: "req_example", + traceId: "trace_example", + client: "desktop", + minimumVersion: "1.2.0", +}; + +/** The spec's example of a refusal for a security problem (`clientUpdateRequiredSecurity`), as is. */ +const SPEC_SECURITY_REFUSAL = { + ...SPEC_REFUSAL, + detail: + "This version of OpenBot has a security problem. Update to keep using it.", + security: true, +}; + +/** What the OpenBot answers: its `deployment`, and whether it refuses every other v2 operation. */ +let deployment: DeploymentName; +let refuseEverything: boolean; +/** What it refuses every other v2 operation with, when it does. */ +let refusalBody: Record; +const NativeResponse = globalThis.Response; +let openbot: ReturnType; + +function problem(status: number, body: Record): Response { + return new NativeResponse(JSON.stringify({ status, ...body }), { + status, + headers: { "content-type": "application/problem+json" }, + }); +} + +function answer(request: Request): Response { + const path = new URL(request.url).pathname; + const published = cases.deployments[deployment]; + if (/^\/api\/v2\/organizations\/[^/]+\/deployment$/.test(path)) + return NativeResponse.json(published); + if (refuseEverything) return problem(400, refusalBody); + // A later OpenBot that serves only v3 no longer answers at v2. One that names no API serves v2. + if ("api" in published && !published.api.includes("v2")) + return problem(404, { code: "NOT_FOUND" }); + // The server's own rule: an app below the minimum the deployment publishes is refused. + const minimums = + "minimumClients" in published + ? (published.minimumClients as Partial>) + : {}; + const below = belowMinimum( + parseClientHeader(request.headers.get(CLIENT_HEADER)), + minimums, + ); + if (below) + return problem(400, { + code: CLIENT_UPDATE_REQUIRED, + detail: clientUpdateDetail(below.kind, below.minimum), + client: below.kind, + minimumVersion: below.minimum, + }); + // Nobody is signed in. + return problem(401, { + code: "UNAUTHENTICATED", + detail: "Sign in to OpenBot.", + }); +} + +beforeAll(() => { + openbot = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: answer }); + GlobalRegistrator.register({ url: `http://127.0.0.1:${openbot.port}/` }); +}); +beforeEach(() => { + deployment = "current"; + refuseEverything = false; + refusalBody = SPEC_REFUSAL; + queryClient.clear(); + // The page is at the server. + globalThis.fetch = pageFetch(); +}); +afterEach(async () => { + cleanup(); + await settleReactWork(); + queryClient.clear(); + forgetClientRefusal(); + delete (window as unknown as Record).__TAURI_INTERNALS__; + globalThis.fetch = nativeFetch; +}); +afterAll(async () => { + await settleReactWork(); + await GlobalRegistrator.unregister(); + openbot.stop(true); +}); + +/** + * The app at `/`: the root route's own component around the real sign-in gate and sign-in screen, + * on routes of this test's own (re-parenting the app's route objects would take them out of the + * app's tree for every test after this one). `app` replaces the root with the gate for another app. + */ +function openApp(app?: CompatibleApp) { + const root = createRootRouteWithContext()({ + component: app + ? () => ( + + + + ) + : (RootRoute.options.component as () => React.JSX.Element), + }); + const gate = AuthedRoute.options as unknown as Record; + const authed = createRoute({ + id: "_authed", + getParentRoute: () => root, + component: Outlet, + ...{ beforeLoad: gate.beforeLoad, errorComponent: gate.errorComponent }, + } as never) as unknown as AnyRoute; + const home = createRoute({ + getParentRoute: () => authed, + path: "/", + component: () =>

The app

, + } as never) as unknown as AnyRoute; + const sign = SignRoute.options as unknown as Record; + const signIn = createRoute({ + getParentRoute: () => root, + path: "/sign", + ...{ + validateSearch: sign.validateSearch, + beforeLoad: sign.beforeLoad, + component: sign.component, + }, + } as never) as unknown as AnyRoute; + const router = createRouter({ + routeTree: root.addChildren([authed.addChildren([home]), signIn]), + history: createMemoryHistory({ initialEntries: ["/"] }), + context: { queryClient }, + }); + return render( + + + , + ); +} + +/** A deployment answer, as `compatibility` reads one. */ +function publishedBy(name: DeploymentName): { + api?: unknown; + minimumClients?: unknown; +} { + const answer: Record = cases.deployments[name]; + return answer; +} + +/** The fixture's verdict for an app, so the screen is held to the same cases as every other app. */ +function expected( + name: DeploymentName, + client: { kind: ClientKind; version: string; speaks?: string[] }, +) { + const listed = cases.cases.find( + (one) => + one.deployment === name && + one.client.kind === client.kind && + one.client.version === client.version && + JSON.stringify(one.client.speaks ?? null) === + JSON.stringify(client.speaks ?? null), + ); + return listed?.fit ?? compatibility(publishedBy(name), client).fit; +} + +test("an OpenBot of today: the sign-in screen, and no update screen", async () => { + expect(RELEASE).toBe("1.1.0"); + expect(expected("current", THIS_WEB)).toBe("ok"); + const view = openApp(); + expect( + await view.findByRole( + "heading", + { name: /Sign in to/ }, + { timeout: 5_000 }, + ), + ).toBeTruthy(); + expect(view.queryByText(APP_UPDATE_SENTENCE)).toBeNull(); + expect(view.queryByText(SERVER_UPDATE_SENTENCE)).toBeNull(); +}, 15_000); + +test("an OpenBot whose oldest web app is newer than this one: Update OpenBot, before sign-in", async () => { + deployment = "next"; + expect(expected("next", THIS_WEB)).toBe("app"); + const view = openApp(); + expect( + await view.findByRole( + "heading", + { name: APP_UPDATE_SENTENCE }, + { timeout: 5_000 }, + ), + ).toBeTruthy(); + expect( + view.getByText("This page is from an older version of OpenBot."), + ).toBeTruthy(); + expect(view.getByRole("button", { name: "Update" })).toBeTruthy(); + // Nothing behind it: no sign-in screen, no error screen. + expect(view.queryByRole("heading", { name: /Sign in to/ })).toBeNull(); + expect(view.queryByRole("alert")).toBeNull(); +}, 15_000); + +test("an OpenBot that serves only a newer API: Update OpenBot", async () => { + deployment = "v3-only"; + expect(compatibility(cases.deployments["v3-only"], THIS_WEB).fit).toBe("app"); + const view = openApp(); + expect( + await view.findByRole( + "heading", + { name: APP_UPDATE_SENTENCE }, + { timeout: 5_000 }, + ), + ).toBeTruthy(); + expect(view.queryByRole("heading", { name: /Sign in to/ })).toBeNull(); +}, 15_000); + +test("an app that speaks only a newer API than the OpenBot serves: ask whoever runs it", async () => { + const app = { kind: "web" as const, version: "2.0.0", speaks: ["v3"] }; + expect( + expected("current", { kind: "desktop", version: "2.0.0", speaks: ["v3"] }), + ).toBe("server"); + const view = openApp(app); + expect( + await view.findByRole( + "heading", + { name: SERVER_UPDATE_SENTENCE }, + { timeout: 5_000 }, + ), + ).toBeTruthy(); + expect( + view.getByText("This OpenBot is on a release this page can't use yet."), + ).toBeTruthy(); + expect(view.getByRole("button", { name: "Try again" })).toBeTruthy(); + expect(view.queryByRole("heading", { name: /Sign in to/ })).toBeNull(); +}, 15_000); + +test("any request refused with CLIENT_UPDATE_REQUIRED brings up Update OpenBot, in place of what failed", async () => { + refuseEverything = true; + const view = openApp(); + expect( + await view.findByRole( + "heading", + { name: APP_UPDATE_SENTENCE }, + { timeout: 5_000 }, + ), + ).toBeTruthy(); + expect(view.getByRole("button", { name: "Update" })).toBeTruthy(); + expect(view.queryByText(SPEC_REFUSAL.detail)).toBeNull(); + // A plain raise is not a security problem. + expect(view.queryByText(SECURITY_UPDATE_SENTENCE)).toBeNull(); + expect(view.queryByRole("heading", { name: /Sign in to/ })).toBeNull(); +}, 15_000); + +test("a refusal for a security problem says so in place of Update OpenBot, with the same Update", async () => { + refuseEverything = true; + refusalBody = SPEC_SECURITY_REFUSAL; + const view = openApp(); + expect( + await view.findByRole( + "heading", + { name: SECURITY_UPDATE_SENTENCE }, + { timeout: 5_000 }, + ), + ).toBeTruthy(); + expect(view.queryByText(APP_UPDATE_SENTENCE)).toBeNull(); + expect(view.getByRole("button", { name: "Update" })).toBeTruthy(); + expect(view.queryByRole("heading", { name: /Sign in to/ })).toBeNull(); +}, 15_000); + +test("an OpenBot whose deployment raised an app's minimum for a security problem: that app reads the security sentence", async () => { + deployment = "security"; + const app = { kind: "recorder" as const, version: "1.1.0" }; + expect(compatibility(cases.deployments.security, app)).toEqual({ + fit: "app", + minimum: "1.2.0", + security: true, + }); + const view = openApp(app); + expect( + await view.findByRole( + "heading", + { name: SECURITY_UPDATE_SENTENCE }, + { timeout: 5_000 }, + ), + ).toBeTruthy(); + expect(view.getByRole("button", { name: "Update" })).toBeTruthy(); + cleanup(); + // The same OpenBot's plain raise, for an app it raised for no security problem, reads as before. + deployment = "raised"; + queryClient.clear(); + const plain = openApp(app); + expect( + await plain.findByRole( + "heading", + { name: APP_UPDATE_SENTENCE }, + { timeout: 5_000 }, + ), + ).toBeTruthy(); + expect(plain.queryByText(SECURITY_UPDATE_SENTENCE)).toBeNull(); +}, 15_000); + +/** OpenBot Desktop's window around the page, answering its plugin's update commands. */ +function insideDesktop(updatesItself: boolean, installed: string[]) { + (window as unknown as Record).__TAURI_INTERNALS__ = { + invoke: async (command: string) => { + if (command === "plugin:openbot-desktop|connection") + return { mode: "connected", address: openbot.url.origin }; + if (command === "plugin:openbot-desktop|update_offer") + return { + version: null, + current: "1.0.1", + installing: null, + updatesItself, + ready: null, + }; + if (command === "plugin:openbot-desktop|install_update") { + installed.push(command); + throw "No update is available right now."; + } + throw `command ${command} not found`; + }, + transformCallback: () => 0, + }; +} + +test("inside OpenBot Desktop, a refusal naming OpenBot Desktop offers its own Update and restart", async () => { + refuseEverything = true; + const installed: string[] = []; + insideDesktop(true, installed); + const view = openApp(); + expect( + await view.findByRole( + "heading", + { name: APP_UPDATE_SENTENCE }, + { timeout: 5_000 }, + ), + ).toBeTruthy(); + expect( + view.getByText("This OpenBot needs OpenBot Desktop 1.2.0 or later."), + ).toBeTruthy(); + const update = await view.findByRole( + "button", + { name: "Update and restart" }, + { timeout: 5_000 }, + ); + await userEvent.click(update); + await waitFor(() => expect(installed).toHaveLength(1)); + expect( + (await view.findByRole("alert", {}, { timeout: 5_000 })).textContent, + ).toBe("Couldn't install the update: No update is available right now."); +}, 15_000); + +test("inside OpenBot Desktop, a refusal of it for a security problem says so, with its own Update and restart", async () => { + refuseEverything = true; + refusalBody = SPEC_SECURITY_REFUSAL; + insideDesktop(true, []); + const view = openApp(); + expect( + await view.findByRole( + "heading", + { name: SECURITY_UPDATE_SENTENCE }, + { timeout: 5_000 }, + ), + ).toBeTruthy(); + expect( + view.getByText("This OpenBot needs OpenBot Desktop 1.2.0 or later."), + ).toBeTruthy(); + expect( + await view.findByRole( + "button", + { name: "Update and restart" }, + { timeout: 5_000 }, + ), + ).toBeTruthy(); +}, 15_000); + +test("inside an OpenBot Desktop that never updates itself, it says what to do instead", async () => { + refuseEverything = true; + insideDesktop(false, []); + const view = openApp(); + expect( + await view.findByText(DOESNT_UPDATE_ITSELF, {}, { timeout: 5_000 }), + ).toBeTruthy(); + expect(view.queryByRole("button", { name: "Update and restart" })).toBeNull(); +}, 15_000); diff --git a/app/tests/connect-app-card.test.tsx b/app/tests/connect-app-card.test.tsx index abf2736d66..a6b24b230b 100644 --- a/app/tests/connect-app-card.test.tsx +++ b/app/tests/connect-app-card.test.tsx @@ -1,5 +1,6 @@ import { afterAll, afterEach, beforeAll, expect, test } from "bun:test"; import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import { CLIENT_HEADER } from "@openbot/shared/client-version"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { createMemoryHistory, @@ -11,6 +12,7 @@ import { } from "@tanstack/react-router"; import { cleanup, fireEvent, render, waitFor } from "@testing-library/react"; import { ConnectAppCard } from "@/components/channels/connect-app-card"; +import { CLIENT_NAME } from "@/lib/client"; import { carryOnMessage } from "@/lib/copilot/carry-on"; import { ConversationProvider } from "@/lib/copilot/conversation"; import { settleReactWork } from "./settle-react-work"; @@ -402,7 +404,12 @@ test("in OpenBot Desktop, coming back finishes a held consent in the background, await comeBack(card); expect(card.verifierCalls).toEqual([ - { credentials: "same-origin", redirect: "manual" }, + { + credentials: "same-origin", + redirect: "manual", + // Naming this app, as every request to OpenBot does. + headers: { [CLIENT_HEADER]: CLIENT_NAME }, + }, ]); expect(window.location.href).toBe(before); } finally { diff --git a/app/tests/page-fetch.ts b/app/tests/page-fetch.ts new file mode 100644 index 0000000000..d7ce6369a7 --- /dev/null +++ b/app/tests/page-fetch.ts @@ -0,0 +1,33 @@ +/** + * The page's `fetch`, for a test whose page is addressed at a real HTTP server on this computer. + * + * A browser resolves a request's path against the page's address and aborts it on the page's own + * signal. Under happy-dom the page's `AbortSignal` is happy-dom's, which the runtime's `fetch` + * refuses, so the abort is carried over to one of the runtime's own. Everything else is the + * runtime's real request, on the real network stack. + * + * Captured when this module loads, before a test file registers happy-dom. + */ +const nativeFetch = globalThis.fetch; +const NativeAbortController = globalThis.AbortController; + +export function pageFetch(): typeof fetch { + return Object.assign( + (input: RequestInfo | URL, init?: RequestInit) => { + const target = + typeof input === "string" ? new URL(input, location.href) : input; + const given = init?.signal; + if (!given) return nativeFetch(target, init); + const controller = new NativeAbortController(); + if (given.aborted) controller.abort(); + else + given.addEventListener("abort", () => controller.abort(), { + once: true, + }); + return nativeFetch(target, { ...init, signal: controller.signal }); + }, + { preconnect: nativeFetch.preconnect }, + ) as typeof fetch; +} + +export { nativeFetch }; diff --git a/desktop/src-tauri/src/client_version.rs b/desktop/src-tauri/src/client_version.rs new file mode 100644 index 0000000000..b77ab64e5a --- /dev/null +++ b/desktop/src-tauri/src/client_version.rs @@ -0,0 +1,497 @@ +/*! +Which OpenBot app this is, said on every request the shell makes to an OpenBot, and whether this app +and the OpenBot it talks to can work together. + +Every OpenBot app names itself in `OpenBot-Client: /`, and every OpenBot says on its +`deployment` which API versions it serves and the oldest release of each app it still serves. When +this app is too old for that OpenBot, the person reads "Update OpenBot" and is offered this app's +update. An OpenBot too old for this app is told as it always was (`connected::Kind::TooOld`). + +The rules are `shared/client-version.ts`'s, carried here in Rust. The tests hold them to every case +in `shared/fixtures/client-version/cases.json`, the same cases the web app, the Recorder and the +phone app run. +*/ + +use crate::problem::Problem; +use reqwest::header::{HeaderMap, HeaderName, HeaderValue}; +use std::sync::OnceLock; + +/// The request header an app names itself in. +pub const HEADER: &str = "OpenBot-Client"; + +/// What this app is called in that header. +pub const KIND: &str = "desktop"; + +/// The API versions this app speaks. +pub const API_VERSIONS: &[&str] = &["v2"]; + +/// The `kind` a problem carries when this app is too old for the OpenBot it talks to. The window +/// offers this app's own update for it, wherever it shows. +pub const APP_TOO_OLD: &str = "app-too-old"; + +/// The `kind` for the same when the minimum this app is below was raised because of a security +/// problem in older releases. The window offers the same update and says [`SECURITY_UPDATE`]. +pub const APP_TOO_OLD_SECURITY: &str = "app-too-old-security"; + +/// What the person reads in place of "Update OpenBot" when the minimum was raised for a security +/// problem (`shared/client-version.ts` `SECURITY_UPDATE_SENTENCE`). +pub const SECURITY_UPDATE: &str = + "This version of OpenBot has a security problem. Update to keep using it."; + +static VERSION: OnceLock = OnceLock::new(); + +/** +The version this app was packaged as: the one the installer, the update check and About name. Set +once at launch from the Tauri configuration (`package_info`), which is the root package.json's +version, or an internal build's own. Until then, and in a process that never starts the app (the +Recorder's native host), Cargo's, which names the same release for every released build. +*/ +pub fn set_app_version(version: impl Into) { + let _ = VERSION.set(version.into()); +} + +/// This app's version, as it names itself. +pub fn app_version() -> String { + #[cfg(test)] + if let Some(version) = TEST_VERSION.with(|version| version.borrow().clone()) { + return version; + } + VERSION + .get() + .cloned() + .unwrap_or_else(|| env!("CARGO_PKG_VERSION").to_owned()) +} + +/// `desktop/`, as this app sends it. +pub fn token() -> String { + format!("{KIND}/{}", app_version()) +} + +fn header_name() -> HeaderName { + HeaderName::from_static("openbot-client") +} + +/// The header, for a client every request of which goes to an OpenBot. +pub fn headers() -> HeaderMap { + let mut headers = HeaderMap::new(); + if let Ok(value) = HeaderValue::from_str(&token()) { + headers.insert(header_name(), value); + } + headers +} + +/** +The header the relay passes on: the one the window's page sent, with this app added after it, as a +User-Agent lists the programs a request went through. `shared/client-version.ts` reads every name in +it. When the page sent none, this app alone. +*/ +pub fn added_to(sent: &HeaderMap) -> Option { + let page: Vec<&str> = sent + .get_all(header_name()) + .iter() + .filter_map(|value| value.to_str().ok()) + .map(str::trim) + .filter(|value| !value.is_empty()) + .collect(); + let mine = token(); + let joined = if page.is_empty() { + mine + } else { + format!("{} {mine}", page.join(" ")) + }; + HeaderValue::from_str(&joined).ok() +} + +/// Whether an app and the OpenBot it talks to can work together. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Fit { + /// They can. Features that OpenBot lacks are hidden by the fields that offer them. + Ok, + /// The app is too old: that OpenBot serves only newer API versions, or names a minimum for + /// this app above its version (`minimum`). "Update OpenBot". `security` when it also names this + /// app in `securityMinimumClients` above its version: the minimum is there for a security + /// problem, and the person reads [`SECURITY_UPDATE`] instead. + App { + minimum: Option, + security: bool, + }, + /// That OpenBot is too old: it serves only API versions older than any the app speaks. + Server, +} + +/// An OpenBot's `deployment`, as it answered it. +pub type Deployment = serde_json::Map; + +/// The major of an API version, `v2` as 2. +fn major(version: &str) -> Option { + let digits = version.strip_prefix('v')?; + (!digits.is_empty() && digits.len() <= 4 && digits.bytes().all(|b| b.is_ascii_digit())) + .then(|| digits.parse().ok()) + .flatten() +} + +/// A release number's parts: `1.2.0-rc.1` as (1, 2, 0) and `rc.1`, with or without a leading v. +fn release(value: &str) -> Option<([u64; 3], Option<&str>)> { + let value = value.strip_prefix('v').unwrap_or(value); + let (core, pre) = match value.split_once('-') { + Some((core, pre)) => (core, Some(pre)), + None => (value, None), + }; + if let Some(pre) = pre { + let allowed = |b: u8| b.is_ascii_alphanumeric() || b == b'.' || b == b'-'; + if pre.is_empty() || pre.len() > 64 || !pre.bytes().all(allowed) { + return None; + } + } + let mut parts = [0u64; 3]; + let mut pieces = core.split('.'); + for part in &mut parts { + let piece = pieces.next()?; + if piece.is_empty() || piece.len() > 6 || !piece.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + *part = piece.parse().ok()?; + } + pieces.next().is_none().then_some((parts, pre)) +} + +/// Whether `value` is a release number: `1.2.0`, `1.2.0-rc.1`, with or without a leading v. +pub fn is_version(value: &str) -> bool { + release(value).is_some() +} + +/** +Release order, by semantic versioning's rules (semver.org, section 11): numbers first, and a +pre-release (`1.2.0-rc.1`) before its release. None when either is not a release number. +*/ +pub fn compare_versions(a: &str, b: &str) -> Option { + use std::cmp::Ordering; + let (left, left_pre) = release(a)?; + let (right, right_pre) = release(b)?; + let order = left.cmp(&right); + if order != Ordering::Equal { + return Some(order); + } + Some(match (left_pre, right_pre) { + (None, None) => Ordering::Equal, + (None, Some(_)) => Ordering::Greater, + (Some(_), None) => Ordering::Less, + (Some(left), Some(right)) => { + let (mut left, mut right) = (left.split('.'), right.split('.')); + loop { + match (left.next(), right.next()) { + (None, None) => break Ordering::Equal, + (None, Some(_)) => break Ordering::Less, + (Some(_), None) => break Ordering::Greater, + (Some(l), Some(r)) => { + let number = |s: &str| { + (!s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())) + .then(|| s.parse::().ok()) + .flatten() + }; + let order = match (number(l), number(r)) { + (Some(l), Some(r)) => l.cmp(&r), + (Some(_), None) => Ordering::Less, + (None, Some(_)) => Ordering::Greater, + (None, None) => l.cmp(r), + }; + if order != Ordering::Equal { + break order; + } + } + } + } + } + }) +} + +/** +Whether an app of `kind` at `version`, speaking `speaks`, and the OpenBot that answered `deployment` +can work together. A `deployment` that publishes no `api` is from a release before it was +published, and every such release that answers `deployment` serves v2. +*/ +pub fn compatibility(deployment: &Deployment, kind: &str, version: &str, speaks: &[&str]) -> Fit { + let served: Vec<&str> = match deployment.get("api") { + Some(serde_json::Value::Array(api)) => { + api.iter().filter_map(serde_json::Value::as_str).collect() + } + _ => vec!["v2"], + }; + if !served.iter().any(|version| speaks.contains(version)) { + // None is below every major, as an empty list's largest is. + let newest_served = served.iter().filter_map(|v| major(v)).max(); + let newest_spoken = speaks.iter().filter_map(|v| major(v)).max(); + // Only newer versions than any the app speaks: the app is behind. Otherwise the server is. + return if newest_served > newest_spoken { + Fit::App { + minimum: None, + security: false, + } + } else { + Fit::Server + }; + } + let below = |field: &str| { + deployment + .get(field) + .and_then(serde_json::Value::as_object) + .and_then(|minimums| minimums.get(kind)) + .and_then(serde_json::Value::as_str) + .filter(|minimum| is_version(minimum)) + .filter(|minimum| compare_versions(version, minimum) == Some(std::cmp::Ordering::Less)) + }; + match below("minimumClients") { + Some(minimum) => Fit::App { + minimum: Some(minimum.to_owned()), + security: below("securityMinimumClients").is_some(), + }, + None => Fit::Ok, + } +} + +/// [`compatibility`] for this app. +pub fn fit(deployment: &Deployment) -> Fit { + compatibility(deployment, KIND, &app_version(), API_VERSIONS) +} + +/// Why it doesn't fit, for the log: what that OpenBot said, against this app. +pub fn why(deployment: &Deployment, fit: &Fit) -> String { + let this = format!( + "this app is {} and speaks {}", + token(), + API_VERSIONS.join(", ") + ); + let served = deployment + .get("api") + .map_or_else(|| "no api (v2)".to_owned(), |api| format!("api {api}")); + match fit { + Fit::App { + minimum: Some(minimum), + security: true, + } => format!( + "the deployment's minimumClients.{KIND} is {minimum}, raised for a security problem \ + (securityMinimumClients); {this}" + ), + Fit::App { + minimum: Some(minimum), + .. + } => format!("the deployment's minimumClients.{KIND} is {minimum}; {this}"), + _ => format!("the deployment says {served}; {this}"), + } +} + +/// What the person reads when the OpenBot on this computer needs a newer version of this app. +pub const LOCAL_APP_TOO_OLD: &str = + "The OpenBot on this computer needs a newer version of this app. Update OpenBot to keep going."; + +/** +Whether the OpenBot on this computer, at `base` (`http://127.0.0.1:` of its server), needs a +newer version of this app: its `deployment` read the way every app reads it, with the install's +token when it has one. Only that is a problem. An OpenBot from an older release, one that answers +no `deployment`, or one that does not answer at all, starts and opens exactly as before: Start +upgrades an older one, and a missing answer is the readiness check's to report, not this one's. +*/ +pub fn local_problem(base: &str, install_token: Option<&str>) -> Option { + let client = reqwest::blocking::Client::builder() + .timeout(std::time::Duration::from_secs(3)) + .redirect(reqwest::redirect::Policy::none()) + .default_headers(headers()) + .build() + .ok()?; + let mut request = client + .get(format!( + "{}{}", + base.trim_end_matches('/'), + crate::connected::address::DEPLOYMENT + )) + .header(reqwest::header::ACCEPT, "application/json"); + if let Some(token) = install_token.filter(|token| !token.trim().is_empty()) { + request = request.header(crate::install_token::HEADER, token); + } + let answered = request.send().ok()?; + if !answered.status().is_success() { + return None; + } + let serde_json::Value::Object(deployment) = answered.json::().ok()? else { + return None; + }; + let decided = fit(&deployment); + let Fit::App { security, .. } = decided else { + return None; + }; + let (said, kind) = if security { + (SECURITY_UPDATE, APP_TOO_OLD_SECURITY) + } else { + (LOCAL_APP_TOO_OLD, APP_TOO_OLD) + }; + let mut problem = Problem::with(said, why(&deployment, &decided)); + problem.kind = Some(kind); + Some(problem) +} + +#[cfg(test)] +thread_local! { + static TEST_VERSION: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +/// This app is `version` on this thread until the guard goes, so a test reads the fixture's real +/// answers against the release they were written for, whatever this build's version is. +#[cfg(test)] +pub(crate) fn as_version(version: &str) -> impl Drop { + struct Restore(Option); + impl Drop for Restore { + fn drop(&mut self) { + let earlier = self.0.take(); + TEST_VERSION.with(|version| *version.borrow_mut() = earlier); + } + } + let earlier = TEST_VERSION.with(|current| current.borrow_mut().replace(version.to_owned())); + Restore(earlier) +} + +/// The shared fixture: real deployment answers, and what each app decides from them. +#[cfg(test)] +pub(crate) const CASES: &str = include_str!("../../../shared/fixtures/client-version/cases.json"); + +/// One of the fixture's real deployment answers, by name. +#[cfg(test)] +pub(crate) fn fixture_deployment(name: &str) -> serde_json::Value { + let cases: serde_json::Value = serde_json::from_str(CASES).unwrap(); + let found = cases["deployments"][name].clone(); + assert!(found.is_object(), "the fixture has no deployment {name}"); + found +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Every case the shared fixture lists, decided as `shared/client-version.ts` decides it. + #[test] + fn every_case_in_the_shared_fixture_is_decided_as_the_contract_says() { + let cases: serde_json::Value = serde_json::from_str(CASES).unwrap(); + let list = cases["cases"].as_array().unwrap(); + assert!(list.len() >= 19, "the fixture lost its cases"); + for case in list { + let name = case["deployment"].as_str().unwrap(); + let client = &case["client"]; + let speaks: Vec<&str> = client["speaks"] + .as_array() + .map(|speaks| speaks.iter().filter_map(|v| v.as_str()).collect()) + .unwrap_or_else(|| API_VERSIONS.to_vec()); + let deployment = cases["deployments"][name].as_object().unwrap(); + let decided = compatibility( + deployment, + client["kind"].as_str().unwrap(), + client["version"].as_str().unwrap(), + &speaks, + ); + let expected = match case["fit"].as_str().unwrap() { + "ok" => Fit::Ok, + "server" => Fit::Server, + "app" => Fit::App { + minimum: case["minimum"].as_str().map(str::to_owned), + security: case["security"].as_bool().unwrap_or(false), + }, + other => panic!("an unknown fit {other}"), + }; + assert_eq!(decided, expected, "{case}"); + } + } + + /// Release order as semver.org section 11 has it, which the TypeScript rule follows. + #[test] + fn releases_are_ordered_as_semantic_versioning_orders_them() { + use std::cmp::Ordering::*; + for (a, b, order) in [ + ("1.0.2", "1.0.2", Equal), + ("v1.0.2", "1.0.2", Equal), + ("1.0.1", "1.0.2", Less), + ("1.10.0", "1.9.9", Greater), + ("1.0.2-rc.3", "1.0.2", Less), + ("1.0.0-alpha", "1.0.0-alpha.1", Less), + ("1.0.0-alpha.1", "1.0.0-alpha.beta", Less), + ("1.0.0-alpha.beta", "1.0.0-beta", Less), + ("1.0.0-beta.2", "1.0.0-beta.11", Less), + ("1.0.0-rc.1", "1.0.0", Less), + ("1.1.0-internal.892.g0c140734ecf0", "1.1.0", Less), + ] { + assert_eq!(compare_versions(a, b), Some(order), "{a} {b}"); + } + for not_a_release in [ + "", + "1.2", + "1.2.3.4", + "1.2.x", + "1.2.3-", + "1234567.0.0", + "1.2.3-a b", + ] { + assert!(!is_version(not_a_release), "{not_a_release}"); + assert_eq!(compare_versions(not_a_release, "1.0.0"), None); + } + } + + /// The OpenBot on this computer, read as every app reads it, through the real HTTP path with + /// the fixture's real answers. Only an OpenBot that needs a newer app is a problem: one of this + /// release, one left at 1.1.0 (no version fields) and one that is not answering all start and + /// open as before, with no sentence. + #[test] + fn the_openbot_on_this_computer_says_update_openbot_only_when_it_needs_a_newer_app() { + use crate::connected::fake_openbot::{FakeOpenBot, Shape}; + let _version = as_version("1.1.0"); + let plain = Some(( + APP_TOO_OLD, + "The OpenBot on this computer needs a newer version of this app. Update OpenBot to keep going.", + )); + let security = Some(( + APP_TOO_OLD_SECURITY, + "This version of OpenBot has a security problem. Update to keep using it.", + )); + for (shape, said) in [ + (Shape::Answers("raised"), plain), + (Shape::Answers("v3-only"), plain), + (Shape::Answers("security"), security), + (Shape::Answers("current"), None), + (Shape::Answers("v1.1.0"), None), + ] { + let server = FakeOpenBot::start(shape.clone()); + let problem = local_problem(&server.address(), Some("install-token-abc")); + assert_eq!( + problem + .as_ref() + .map(|problem| (problem.kind.unwrap(), problem.said.as_str())), + said, + "{shape:?}: {problem:?}" + ); + let asked = server.seen_at(crate::connected::address::DEPLOYMENT); + assert_eq!(asked.len(), 1, "{shape:?}"); + assert_eq!(asked[0].header("openbot-client"), Some("desktop/1.1.0")); + assert_eq!( + asked[0].header(crate::install_token::HEADER), + Some("install-token-abc") + ); + } + // Nothing listening: the readiness check says that, not this. + let port = std::net::TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port(); + assert!(local_problem(&format!("http://127.0.0.1:{port}"), None).is_none()); + } + + /// The relay names this app after whatever the page named, and only this app when it named none. + #[test] + fn the_header_names_this_app_after_the_page() { + let _version = as_version("1.1.0"); + assert_eq!(token(), "desktop/1.1.0"); + assert_eq!(headers()["openbot-client"], "desktop/1.1.0"); + let mut sent = HeaderMap::new(); + assert_eq!(added_to(&sent).unwrap(), "desktop/1.1.0"); + sent.insert(header_name(), HeaderValue::from_static("web/1.1.0")); + assert_eq!(added_to(&sent).unwrap(), "web/1.1.0 desktop/1.1.0"); + sent.insert(header_name(), HeaderValue::from_static(" ")); + assert_eq!(added_to(&sent).unwrap(), "desktop/1.1.0"); + } +} diff --git a/desktop/src-tauri/src/connected/address.rs b/desktop/src-tauri/src/connected/address.rs index 0782f5542d..0c6bbb4a6d 100644 --- a/desktop/src-tauri/src/connected/address.rs +++ b/desktop/src-tauri/src/connected/address.rs @@ -3,13 +3,17 @@ //! //! Two questions are asked of the address, both public: what it offers //! (`/api/v2/organizations/default/deployment`, which every OpenBot answers before sign-in) and -//! how an app signs in to it (its authorization server metadata, RFC 8414). Each way that can go -//! wrong is one `Kind`, so the window can say what to do next. +//! how an app signs in to it (its authorization server metadata, RFC 8414). What it offers says +//! whether this app is new enough for that OpenBot (`client_version`). Each way that can go wrong +//! is one `Kind`, so the window can say what to do next. use super::{host_of, http, transport, Kind}; +use crate::client_version; use crate::problem::Problem; -const DEPLOYMENT: &str = "/api/v2/organizations/default/deployment"; +/// What an OpenBot offers, which every OpenBot answers before sign-in. Read here, and of the OpenBot +/// on this computer (`client_version::local_problem`). +pub const DEPLOYMENT: &str = "/api/v2/organizations/default/deployment"; const METADATA: &str = "/.well-known/oauth-authorization-server/api/auth"; /// What keeps a sign-in going after its first hour: a refresh token. const OFFLINE_ACCESS: &str = "offline_access"; @@ -90,21 +94,39 @@ pub fn probe(address: &str) -> Result { .as_ref() .and_then(|deployment| deployment.get("edition")) .and_then(serde_json::Value::as_str); - let Some(edition) = edition else { + let (Some(deployment), Some(edition)) = (deployment.as_ref(), edition) else { return Err(Kind::NotOpenBot.problem( &host, format!("GET {DEPLOYMENT} answered {status}, not as an OpenBot does"), )); }; let on_its_own_computer = deployment - .as_ref() - .and_then(|deployment| deployment.get("localEvaluation")) + .get("localEvaluation") .and_then(serde_json::Value::as_bool) .unwrap_or(false); if on_its_own_computer { return Err(Kind::SinglePerson.problem(&host, "the deployment says localEvaluation")); } + // Which API versions it serves and the oldest release of this app it serves, decided as every + // OpenBot app decides it (`client_version`): asked when the person connects and on every + // launch, so an OpenBot that raised its minimum past this app since is caught. One that serves + // only an older API is told as an OpenBot this app can't connect to always was. + match client_version::fit(deployment) { + client_version::Fit::Ok => {} + fit @ client_version::Fit::App { security, .. } => { + let kind = if security { + Kind::AppTooOldSecurity + } else { + Kind::AppTooOld + }; + return Err(kind.problem(&host, client_version::why(deployment, &fit))); + } + fit @ client_version::Fit::Server => { + return Err(Kind::TooOld.problem(&host, client_version::why(deployment, &fit))); + } + } + let answered = get(METADATA)?; let status = answered.status(); let Some(document) = json_object(answered).filter(|_| status.is_success()) else { @@ -315,6 +337,79 @@ mod tests { assert_eq!(kind(&server.address()), Some(Kind::TooOld)); } + /// The fixture's real answers (`shared/fixtures/client-version/cases.json`), as this release's + /// app reads them through the real HTTP path. An OpenBot of this release, and one of 1.1.0 + /// (which publishes no version fields), connect. One whose admin raised the oldest app it + /// serves above this one, and one that serves only a newer API, say "Update OpenBot", and the + /// app asks nothing more of them. + #[test] + fn an_openbot_this_app_is_too_old_for_says_update_openbot_and_the_rest_connect() { + let _version = crate::client_version::as_version("1.1.0"); + for name in ["current", "v1.1.0"] { + let server = FakeOpenBot::start(Shape::Answers(name)); + let (address, metadata) = check(&server.address()).unwrap_or_else(|problem| { + panic!("{name}: {problem:?}"); + }); + assert_eq!(address, server.address(), "{name}"); + assert!(metadata + .scopes + .iter() + .any(|scope| scope == "offline_access")); + } + for name in ["raised", "v3-only"] { + let server = FakeOpenBot::start(Shape::Answers(name)); + let problem = check(&server.address()).expect_err(name); + assert_eq!(kind_of(&problem), Some(Kind::AppTooOld), "{name}"); + assert_eq!( + problem.said, + format!( + "The OpenBot at {} needs a newer version of this app. Update OpenBot, then connect again.", + host_of(&server.address()) + ), + "{name}" + ); + assert!(server.seen_at(METADATA).is_empty(), "{name}"); + } + // One that raised this app's minimum for a security problem says so instead, and offers the + // same update. + let security = FakeOpenBot::start(Shape::Answers("security")); + let problem = check(&security.address()).expect_err("security"); + assert_eq!(kind_of(&problem), Some(Kind::AppTooOldSecurity)); + assert_eq!( + problem.said, + "This version of OpenBot has a security problem. Update to keep using it." + ); + assert_eq!( + problem.detail.as_deref(), + Some("the deployment's minimumClients.desktop is 1.2.0, raised for a security problem (securityMinimumClients); this app is desktop/1.1.0 and speaks v2") + ); + assert!(security.seen_at(METADATA).is_empty()); + // What the log says beside the sentence: what that OpenBot asked for, against this app. + let raised = FakeOpenBot::start(Shape::Answers("raised")); + let problem = check(&raised.address()).expect_err("raised"); + assert_eq!( + problem.detail.as_deref(), + Some("the deployment's minimumClients.desktop is 1.2.0; this app is desktop/1.1.0 and speaks v2") + ); + } + + /// The check runs on every launch while connected (`probe`, before the saved sign-in is used), + /// not only when the person connects: an OpenBot that raised its minimum past the app since, + /// as OpenBot Cloud does, is caught the next time the app opens. + #[test] + fn the_launch_check_catches_an_openbot_that_moved_since_the_app_connected() { + let _version = crate::client_version::as_version("1.1.0"); + for (name, kind) in [ + ("raised", Kind::AppTooOld), + ("v3-only", Kind::AppTooOld), + ("security", Kind::AppTooOldSecurity), + ] { + let server = FakeOpenBot::start(Shape::Answers(name)); + let problem = probe(&server.address()).expect_err(name); + assert_eq!(kind_of(&problem), Some(kind), "{name}"); + } + } + /// The browser is sent to the authorization endpoint and the code is posted to the token /// endpoint. Metadata that names another host for either is not followed there. #[test] diff --git a/desktop/src-tauri/src/connected/fake_openbot_tests.rs b/desktop/src-tauri/src/connected/fake_openbot_tests.rs index 7f25660f84..a0be752470 100644 --- a/desktop/src-tauri/src/connected/fake_openbot_tests.rs +++ b/desktop/src-tauri/src/connected/fake_openbot_tests.rs @@ -2,7 +2,9 @@ A stand-in for an OpenBot that runs elsewhere, for this module's tests: a real HTTP server on a loopback port that answers the addresses the app uses as the real one does. -- the public deployment answer and the authorization server metadata (RFC 8414), at the real paths; +- the public deployment answer and the authorization server metadata (RFC 8414), at the real paths, + the deployment as one of the real answers in `shared/fixtures/client-version/cases.json` when + asked (`Shape::Answers`); - the authorization endpoint, which accepts only the public client, `response_type=code`, an S256 challenge and a redirect of exactly `http://127.0.0.1:/callback`, and sends the browser back with a code or with `error=access_denied`; @@ -60,6 +62,10 @@ pub enum Shape { InfoAnswers(u16), /// Its revocation endpoint fails with a 500 whatever it is sent. RevokeBroken, + /// Signs in as `Current` does, and answers `deployment` with one of the real answers in + /// `shared/fixtures/client-version/cases.json`, by name: `current`, `v1.1.0`, `raised`, + /// `security` or `v3-only`. + Answers(&'static str), } const SCOPES: [&str; 4] = ["openid", "profile", "offline_access", "openbot"]; @@ -416,17 +422,23 @@ async fn answer( ) }; Ok(match (method.as_str(), path.as_str()) { - ("GET", "/api/v2/organizations/default/deployment") => json( - StatusCode::OK, - serde_json::json!({ - "edition": if shape == Shape::Personal { "personal" } else { "team" }, - "localEvaluation": shape == Shape::LocalEvaluation, - "generativeUi": true, - "authProviders": ["google"], - "ssoConfigured": false, - "ssoRequired": false, - }), - ), + ("GET", "/api/v2/organizations/default/deployment") => match &shape { + Shape::Answers(name) => json( + StatusCode::OK, + crate::client_version::fixture_deployment(name), + ), + _ => json( + StatusCode::OK, + serde_json::json!({ + "edition": if shape == Shape::Personal { "personal" } else { "team" }, + "localEvaluation": shape == Shape::LocalEvaluation, + "generativeUi": true, + "authProviders": ["google"], + "ssoConfigured": false, + "ssoRequired": false, + }), + ), + }, ("GET", "/.well-known/oauth-authorization-server/api/auth") => { if matches!( shape, diff --git a/desktop/src-tauri/src/connected/mod.rs b/desktop/src-tauri/src/connected/mod.rs index 2af37736c4..44ff280019 100644 --- a/desktop/src-tauri/src/connected/mod.rs +++ b/desktop/src-tauri/src/connected/mod.rs @@ -41,6 +41,10 @@ pub enum Kind { NotOpenBot, SinglePerson, TooOld, + /// This app is older than that OpenBot serves: the window offers this app's own update. + AppTooOld, + /// The same, for a minimum that OpenBot raised because of a security problem. + AppTooOldSecurity, SignInCancelled, SignInFailed, /// Signed in, and then the OpenBot refused the new sign-in on the app's screens (401 or 403). @@ -57,6 +61,8 @@ impl Kind { Kind::NotOpenBot => "not-openbot", Kind::SinglePerson => "single-person", Kind::TooOld => "too-old", + Kind::AppTooOld => crate::client_version::APP_TOO_OLD, + Kind::AppTooOldSecurity => crate::client_version::APP_TOO_OLD_SECURITY, Kind::SignInCancelled => "sign-in-cancelled", Kind::SignInFailed => "sign-in-failed", Kind::AccessRefused => "access-refused", @@ -85,6 +91,11 @@ impl Kind { "The OpenBot at {host} is on a release this app can't connect to yet. Ask whoever \ runs it to update OpenBot, or open it in your browser." ), + Kind::AppTooOld => format!( + "The OpenBot at {host} needs a newer version of this app. Update OpenBot, then \ + connect again." + ), + Kind::AppTooOldSecurity => crate::client_version::SECURITY_UPDATE.into(), Kind::SignInCancelled => "Sign-in didn't finish. Try again when you're ready.".into(), Kind::SignInFailed => format!( "OpenBot couldn't sign you in at {host}. Try again, or ask whoever runs your OpenBot." @@ -124,6 +135,8 @@ pub fn kind_of(problem: &Problem) -> Option { Kind::NotOpenBot, Kind::SinglePerson, Kind::TooOld, + Kind::AppTooOld, + Kind::AppTooOldSecurity, Kind::SignInCancelled, Kind::SignInFailed, Kind::AccessRefused, @@ -149,8 +162,9 @@ pub fn host_of(address: &str) -> String { .unwrap_or_else(|| address.to_owned()) } -/// A client for the few requests the shell itself makes to that OpenBot: short timeouts, and a -/// redirect followed only while it stays on the same host. +/// A client for the few requests the shell itself makes to that OpenBot: short timeouts, a +/// redirect followed only while it stays on the same host, and this app named on every one +/// (`client_version`). pub(crate) fn http() -> Result { reqwest::blocking::Client::builder() .connect_timeout(std::time::Duration::from_secs(10)) @@ -168,6 +182,7 @@ pub(crate) fn http() -> Result { } })) .user_agent("OpenBot/desktop") + .default_headers(crate::client_version::headers()) .build() .map_err(|error| error.to_string()) } @@ -212,6 +227,27 @@ mod tests { Kind::TooOld.said("127.0.0.1:4000"), "The OpenBot at 127.0.0.1:4000 is on a release this app can't connect to yet. Ask whoever runs it to update OpenBot, or open it in your browser." ); + // This app too old for that OpenBot, as every OpenBot app says it (`shared/client-version.ts`). + assert_eq!( + Kind::AppTooOld.said("openbot.example.com"), + "The OpenBot at openbot.example.com needs a newer version of this app. Update OpenBot, then connect again." + ); + assert_eq!( + Kind::AppTooOldSecurity.said("openbot.example.com"), + "This version of OpenBot has a security problem. Update to keep using it." + ); + let insecure = Kind::AppTooOldSecurity.problem("openbot.example.com", "security"); + assert_eq!(kind_of(&insecure), Some(Kind::AppTooOldSecurity)); + assert_eq!( + serde_json::to_value(&insecure).unwrap()["kind"], + "app-too-old-security" + ); + let too_old = Kind::AppTooOld.problem("openbot.example.com", "minimum 1.2.0"); + assert_eq!(kind_of(&too_old), Some(Kind::AppTooOld)); + assert_eq!( + serde_json::to_value(&too_old).unwrap()["kind"], + "app-too-old" + ); let refused = Kind::AccessRefused.problem("openbot.example.com", "answered 403"); assert_eq!(kind_of(&refused), Some(Kind::AccessRefused)); assert_eq!( diff --git a/desktop/src-tauri/src/connected/relay.rs b/desktop/src-tauri/src/connected/relay.rs index 1caf8215ae..9d1289f759 100644 --- a/desktop/src-tauri/src/connected/relay.rs +++ b/desktop/src-tauri/src/connected/relay.rs @@ -25,6 +25,9 @@ What keeps it to that: - On the way out it drops `Origin`, `Cookie`, `Referer`, `Forwarded` and `X-Forwarded-*`, and any `Authorization` the page sent. On the way back it drops `Set-Cookie`. +It adds this app to the `OpenBot-Client` header the page sent, or sends this app's alone, so the +OpenBot knows which apps a request came through (`client_version`). + Bodies are passed on as they arrive, both ways, so a chat answer streams. A WebSocket upgrade is passed on and the two connections are joined. @@ -317,6 +320,8 @@ fn dropped_on_the_way_out(name: &HeaderName) -> bool { || name.starts_with("sec-fetch-") // The shell names the organisation, not the page. || name.eq_ignore_ascii_case(ORGANIZATION_HEADER) + // Passed on with this app added after it (`client_version::added_to`). + || name.eq_ignore_ascii_case(crate::client_version::HEADER) } /// Whether a request for `path` is one of OpenBot's own that takes the person's sign-in: its API, @@ -431,6 +436,14 @@ async fn answer(mut request: Request, shared: Arc) -> Response } headers.append(name.clone(), value.clone()); } + // Which apps the request came through: the page's own name, then this app's. On everything it + // passes on, so OpenBot knows this app is asking whatever the page is. + if let (Ok(name), Some(named)) = ( + HeaderName::from_bytes(crate::client_version::HEADER.as_bytes()), + crate::client_version::added_to(request.headers()), + ) { + headers.insert(name, named); + } // The person's sign-in and their organisation, for OpenBot's own API only. let signed_in = carries_the_sign_in(request.uri().path()); let organization = shared @@ -1004,6 +1017,32 @@ mod tests { assert!(!sent.to_string().contains(&window.cookie)); } + /// OpenBot hears which apps a request came through: the name the window's page gave, then this + /// app's, on OpenBot's API and on its pages alike. A page that names none is this app alone. + #[test] + fn openbot_hears_the_pages_app_and_then_this_one() { + let rig = rig(); + let window = rig.window(); + let mine = format!("desktop/{}", crate::client_version::app_version()); + let sent = window.echo(window.get(ECHO).header("openbot-client", "web/1.1.0")); + assert_eq!( + sent["headers"]["openbot-client"], + format!("web/1.1.0 {mine}") + ); + let sent = window.echo(window.get(ECHO)); + assert_eq!(sent["headers"]["openbot-client"], mine.as_str()); + let page = window + .get("/landing") + .header("openbot-client", "web/1.1.0") + .send() + .unwrap(); + assert_eq!(page.status(), 200); + assert_eq!( + rig.openbot.seen_at("/landing")[0].header("openbot-client"), + Some(format!("web/1.1.0 {mine}").as_str()) + ); + } + #[test] fn a_cookie_openbot_sets_does_not_come_back() { let rig = rig(); diff --git a/desktop/src-tauri/src/connected/sign_in.rs b/desktop/src-tauri/src/connected/sign_in.rs index 8b4bf83b76..567fd41e2d 100644 --- a/desktop/src-tauri/src/connected/sign_in.rs +++ b/desktop/src-tauri/src/connected/sign_in.rs @@ -1279,6 +1279,49 @@ mod tests { assert!(session.access().is_err()); } + /// Every request the shell itself makes to the OpenBot names this app, `OpenBot-Client: + /// desktop/`: the two questions before sign-in, the code exchange, the first call + /// after it, a refresh, and sign-out's revocations. Only the person's browser, which opens the + /// authorization address, is not the app. + #[test] + fn every_request_the_shell_makes_names_this_app() { + let openbot = FakeOpenBot::start(Shape::Current); + let session = openbot.sign_in(in_memory()); + let access = session.access().unwrap(); + openbot.expire_access_tokens(); + session.after_refused(&access).unwrap(); + session.sign_out().unwrap(); + + let named = format!("desktop/{}", crate::client_version::app_version()); + let shells: Vec<_> = openbot + .seen() + .into_iter() + .filter(|seen| seen.path != "/api/auth/oauth2/authorize") + .collect(); + let asked: Vec = shells + .iter() + .map(|seen| format!("{} {}", seen.method, seen.path)) + .collect(); + for path in [ + "GET /api/v2/organizations/default/deployment", + "GET /.well-known/oauth-authorization-server/api/auth", + "POST /api/auth/oauth2/token", + "GET /api/copilotkit/info", + "POST /api/auth/oauth2/revoke", + ] { + assert!(asked.iter().any(|seen| seen == path), "{path}: {asked:?}"); + } + for seen in &shells { + assert_eq!( + seen.header("openbot-client"), + Some(named.as_str()), + "{} {}", + seen.method, + seen.path + ); + } + } + /// Nothing shaped like a token reaches a file under the app's configuration folder or a line /// of the log, through a sign-in, a refresh, a refused refresh and a sign-out. #[test] diff --git a/desktop/src-tauri/src/desktop_connection.rs b/desktop/src-tauri/src/desktop_connection.rs index 313ccc2521..84e2d79272 100644 --- a/desktop/src-tauri/src/desktop_connection.rs +++ b/desktop/src-tauri/src/desktop_connection.rs @@ -14,6 +14,7 @@ pub fn client() -> Result { Client::builder() .timeout(std::time::Duration::from_secs(1)) .redirect(reqwest::redirect::Policy::none()) + .default_headers(openbot_desktop_lib::client_version::headers()) .build() .map_err(|error| format!("Could not create connection status client: {error}")) } diff --git a/desktop/src-tauri/src/host_access.rs b/desktop/src-tauri/src/host_access.rs index 8f4c1fe6b6..eca969fa51 100644 --- a/desktop/src-tauri/src/host_access.rs +++ b/desktop/src-tauri/src/host_access.rs @@ -611,7 +611,11 @@ impl Drop for HostAccess { } fn broker_loop(inner: Arc) { - let client = match Client::builder().timeout(Duration::from_secs(15)).build() { + let client = match Client::builder() + .timeout(Duration::from_secs(15)) + .default_headers(crate::client_version::headers()) + .build() + { Ok(client) => client, Err(error) => { log::error!("[host access] could not create its HTTP client: {error}"); @@ -1225,6 +1229,7 @@ impl Inner { .spawn(move || { let sent = Client::builder() .timeout(Duration::from_secs(5)) + .default_headers(crate::client_version::headers()) .build() .and_then(|client| { client diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rs index 97d557944b..45e2dea865 100644 --- a/desktop/src-tauri/src/lib.rs +++ b/desktop/src-tauri/src/lib.rs @@ -3,6 +3,7 @@ pub mod acquire; pub mod ai_connection; pub mod app_update; pub mod cli_release; +pub mod client_version; pub mod composio; pub mod connected; pub mod deployment; diff --git a/desktop/src-tauri/src/main.rs b/desktop/src-tauri/src/main.rs index a2e17a45a8..36ac8d156f 100644 --- a/desktop/src-tauri/src/main.rs +++ b/desktop/src-tauri/src/main.rs @@ -7170,8 +7170,15 @@ fn show_openbot_on( let (url, address) = owned_app(&shell, &root, ports).ok_or_else(|| { format!("OpenBot could not verify its app on port {port} belongs to this installation. Try starting OpenBot again.") })?; + // Held either way: it is running, and this session's from now on, as one Start raised is. A + // launch that found it running and needs a newer app said "Not running" in the tray otherwise. hold_shown_deployment(&app, &shell, &root, address.clone(), ports.server); refresh_menus(&app); + // An OpenBot that needs a newer app is not shown: the window says "Update OpenBot" instead. + if let Some(problem) = local_app_too_old(&shell, &root, &address, ports) { + log::warn!("[show] {}", logging::Failure::described(&problem)); + return Err(problem); + } // Only the owned app itself. trust_owned_app(&app, &url); // A debug build may show a developer's own app in its place, on this installation's back end. @@ -9300,6 +9307,7 @@ fn show_setup_and_focus(app: tauri::AppHandle) -> Result<( fn server_capabilities_answer(port: u16) -> bool { reqwest::blocking::Client::builder() .timeout(std::time::Duration::from_secs(2)) + .default_headers(openbot_desktop_lib::client_version::headers()) .build() .ok() .and_then(|client| { @@ -9360,6 +9368,26 @@ fn owned_app_url(shell: &Shell, root: &Path, ports: &openbot_env::Ports) -> Opti owned_app(shell, root, ports).map(|(url, _)| url) } +/** +Whether this app is too old for the OpenBot `root`'s server runs, read from its `deployment` as every +OpenBot app reads it (`client_version::local_problem`), with the install's token. "Update OpenBot", +with this app's update, is the only thing that stops the window from opening it: an OpenBot from an +older release opens exactly as before (Start upgrades it), and one that does not answer is the +readiness check's to report. +*/ +fn local_app_too_old( + shell: &Shell, + root: &Path, + address: &engine::Address, + ports: &openbot_env::Ports, +) -> Option { + let token = install_token_for(shell, root, address); + openbot_desktop_lib::client_version::local_problem( + &format!("http://127.0.0.1:{}", ports.server), + token.as_deref(), + ) +} + /// [`owned_app_url`], with the engine whose `server` container publishes it. fn owned_app( shell: &Shell, @@ -11710,6 +11738,8 @@ fn restore_window_on(app: &tauri::AppHandle, ports: &openb if let Some((url, address)) = (!recovery_required_or_pending_quit_notice(&shell, &root)) .then(|| owned_app(&shell, &root, ports)) .flatten() + // One that needs a newer app stays on setup, which says so. + .filter(|(_, address)| local_app_too_old(&shell, &root, address, ports).is_none()) { hold_shown_deployment(app, &shell, &root, address.clone(), ports.server); refresh_menus(app); @@ -13029,6 +13059,11 @@ fn main() { // After an in-app update, or from the installer's last page: in front as the window first shows. let from_installer = started_by_installer(&args); let context = side_by_side(tauri::generate_context!()); + // The version every request to an OpenBot names this app with (`client_version`): the one the + // installer, the update check and About name. + openbot_desktop_lib::client_version::set_app_version( + context.package_info().version.to_string(), + ); // A `shell-updater` build with compiled trust supplies `plugins.updater` when no bundled block // (such as the signed Mac overlay) already does. Registration itself happens once, in `setup`. #[cfg(feature = "shell-updater")] @@ -24629,6 +24664,16 @@ fn serve(listener: TcpListener) { // token it was started with (`server-host-token`), and each request recorded as one or the other. fn desktop_answer(request: &str) -> Option<(&'static str, String)> { let path = request.split_whitespace().nth(1)?; + // Which app asked for what, as the OpenBot-Client header named it. + let named = request.lines().filter_map(|line| line.split_once(':')).find_map(|(name, value)| { + name.eq_ignore_ascii_case("openbot-client").then(|| value.trim().to_owned()) + }).unwrap_or_else(|| "-".into()); + let mut asked = std::fs::OpenOptions::new().create(true).append(true).open("client-headers.log").unwrap(); + writeln!(asked, "{path} {named}").unwrap(); + // What it offers, when the test gave it a deployment answer to give. + if path == "/api/v2/organizations/default/deployment" { + return std::fs::read_to_string("deployment.json").ok().map(|body| ("200 OK", body)); + } let empty = match path { "/api/host-access/desktop/next" => "{\"operations\":[],\"leaseMs\":30000}", "/api/desktop/connection-failure" => "null", @@ -25057,6 +25102,103 @@ fn main() { assert_eq!(window_url(&app), shown); } + /// The OpenBot on this computer is read as every app reads it before the window opens it + /// (API versioning design, 7.1). One whose admin raised the oldest app it serves above this + /// one, or one that serves only a newer API, is not shown: the window says "Update OpenBot", or + /// that this version has a security problem when the minimum was raised for one, + /// and offers this app's update, and Show Window keeps it on setup. One left at 1.1.0, which + /// publishes no version fields, opens exactly as before. Every request names this app. + #[test] + fn the_openbot_on_this_computer_opens_only_when_this_app_is_new_enough_for_it() { + let f = RestoreFixture::new(); + openbot_env::write( + &f.owned.join(".env"), + &f.ports.settings(), + &std::collections::BTreeMap::new(), + ) + .unwrap(); + let root = f.owned.to_string_lossy().into_owned(); + let shown = format!("http://127.0.0.1:{}/", f.ports.app); + let version = openbot_desktop_lib::client_version::app_version(); + let window_url = |app: &tauri::App| { + app.get_webview_window("main") + .unwrap() + .url() + .unwrap() + .to_string() + }; + let cases: serde_json::Value = serde_json::from_str(include_str!( + "../../../shared/fixtures/client-version/cases.json" + )) + .unwrap(); + let answer = |name: &str| cases["deployments"][name].clone(); + // The fixture's `raised`, its minimum for this app above whatever this build is. + let mut raised = answer("raised"); + let major: u64 = version.split('.').next().unwrap().parse().unwrap(); + raised["minimumClients"]["desktop"] = format!("{}.0.0", major + 1).into(); + // The fixture's `security`, the same minimum raised for a security problem. + let mut security = answer("security"); + security["minimumClients"]["desktop"] = format!("{}.0.0", major + 1).into(); + security["securityMinimumClients"]["desktop"] = format!("{}.0.0", major + 1).into(); + let plain = ( + "app-too-old", + "The OpenBot on this computer needs a newer version of this app. Update OpenBot to keep going.", + ); + + for (too_new, (kind, said)) in [ + (raised, plain), + (answer("v3-only"), plain), + ( + security, + ( + "app-too-old-security", + "This version of OpenBot has a security problem. Update to keep using it.", + ), + ), + ] { + std::fs::write(f.owned.join("deployment.json"), too_new.to_string()).unwrap(); + let app = f.app(&f.owned, "tauri://localhost/"); + assert!(already_running_now(app.handle(), &root)); + let problem = show_openbot_on(app.handle().clone(), &f.ports).unwrap_err(); + assert_eq!(problem.kind, Some(kind), "{too_new}"); + assert_eq!(problem.said, said); + assert_eq!(window_url(&app), "http://127.0.0.1:9/stale-page"); + // Found running by a launch that did not start it, it is still running: held as this + // session's, as Start holds the one it raised, so the tray says "Running" and Stop and + // Quit act on it. Not held, the tray said "Not running" while the server answered. + assert_eq!( + app.state::().root.lock().unwrap().as_deref(), + Some(f.owned.as_path()), + "{too_new}" + ); + restore_window_on(app.handle(), &f.ports); + assert_eq!(window_url(&app), "tauri://localhost/"); + } + + // Left at 1.1.0: the server left at an older version, which starts and opens as today. + std::fs::write( + f.owned.join("deployment.json"), + answer("v1.1.0").to_string(), + ) + .unwrap(); + let app = f.app(&f.owned, "tauri://localhost/"); + show_openbot_on(app.handle().clone(), &f.ports).unwrap(); + assert_eq!(window_url(&app), shown); + + let asked = std::fs::read_to_string(f.owned.join("client-headers.log")).unwrap(); + for path in [ + "/api/capabilities", + "/api/v2/organizations/default/deployment", + ] { + assert!( + asked + .lines() + .any(|line| line == format!("{path} desktop/{version}")), + "{path}: {asked}" + ); + } + } + /// A deployment shown as the window's own is this session's, as one Start raised is: the menus /// say it is running, local folder access and the connection watcher answer to its server, and /// Quit takes its containers down. Shown and not held, the tray said "Not running", Quit left diff --git a/desktop/src-tauri/src/recorder_host.rs b/desktop/src-tauri/src/recorder_host.rs index 7107041802..d0f068d0aa 100644 --- a/desktop/src-tauri/src/recorder_host.rs +++ b/desktop/src-tauri/src/recorder_host.rs @@ -448,6 +448,7 @@ fn client() -> reqwest::Result { Client::builder() .timeout(DEADLINES.handoff) .redirect(reqwest::redirect::Policy::none()) + .default_headers(crate::client_version::headers()) .build() } diff --git a/desktop/src-tauri/src/stack.rs b/desktop/src-tauri/src/stack.rs index 9504a1d7b5..1faa6e32bd 100644 --- a/desktop/src-tauri/src/stack.rs +++ b/desktop/src-tauri/src/stack.rs @@ -4444,6 +4444,7 @@ pub fn answering_at(port: u16, path: &str) -> Option { pub fn answering_within(port: u16, path: &str, patience: std::time::Duration) -> Option { let client = reqwest::blocking::Client::builder() .timeout(patience) + .default_headers(crate::client_version::headers()) .build() .ok()?; LOOPBACKS.iter().find_map(|host| { @@ -4524,6 +4525,7 @@ pub fn wait_until_healthy_saying( ); let client = reqwest::blocking::Client::builder() .timeout(std::time::Duration::from_secs(3)) + .default_headers(crate::client_version::headers()) .build() .map_err(|error| { NotReady::NotAnswering(format!("could not ask OpenBot's services: {error}")) diff --git a/desktop/src/App.test.tsx b/desktop/src/App.test.tsx index 78a560b665..ae0383a432 100644 --- a/desktop/src/App.test.tsx +++ b/desktop/src/App.test.tsx @@ -12,6 +12,7 @@ import { GlobalRegistrator } from "@happy-dom/global-registrator"; import { act, cleanup, render, waitFor, within } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { StrictMode } from "react"; +import { DOESNT_UPDATE_ITSELF } from "../../shared/desktop-updates"; import { DEFAULT_HARNESS } from "./harness"; type Invoke = (command: string, args?: unknown) => Promise; @@ -887,7 +888,12 @@ const CONNECT_PROBLEMS: Array<{ kind: string; said: string; at: "check" | "connect"; - offer: "field" | "Try again" | "Sign in again" | "Open in browser"; + offer: + | "field" + | "Try again" + | "Sign in again" + | "Open in browser" + | "Update and restart"; }> = [ { kind: "address-invalid", @@ -919,6 +925,18 @@ const CONNECT_PROBLEMS: Array<{ offer: "Open in browser", said: "The OpenBot at openbot.example.com is on a release this app can't connect to yet. Ask whoever runs it to update OpenBot, or open it in your browser.", }, + { + kind: "app-too-old", + at: "check", + offer: "Update and restart", + said: "The OpenBot at openbot.example.com needs a newer version of this app. Update OpenBot, then connect again.", + }, + { + kind: "app-too-old-security", + at: "check", + offer: "Update and restart", + said: "This version of OpenBot has a security problem. Update to keep using it.", + }, { kind: "sign-in-cancelled", at: "connect", @@ -1116,6 +1134,19 @@ for (const { kind, said, at, offer } of CONNECT_PROBLEMS) { throw { said, kind }; }, "plugin:opener|open_url": null, + // This app's own update, as the shell offers it. + app_update_offer: { + version: null, + current: "1.1.0", + installing: null, + updatesItself: true, + }, + check_app_update: { + found: "available", + version: "1.2.0", + current: "1.1.0", + }, + install_app_update: () => new Promise(() => {}), }); const field = view.getByLabelText("OpenBot address") as HTMLInputElement; await userEvent.type(field, `${ELSEWHERE}{Enter}`); @@ -1152,6 +1183,22 @@ for (const { kind, said, at, offer } of CONNECT_PROBLEMS) { args: { url: ELSEWHERE }, }); expect(view.getByRole("button", { name: "Connect" })).toBeTruthy(); + } else if (offer === "Update and restart") { + // This app is what is too old: the way on is its own update, not another try. + expect(alert.textContent).toBe(said); + expect(view.queryByRole("button", { name: "Connect" })).toBeNull(); + const update = view.getByRole("button", { name: offer }); + await waitFor(() => expect(update).toHaveProperty("disabled", false)); + await userEvent.click(update); + await waitFor(() => + expect(invokeCalls.map((call) => call.command)).toContain( + "install_app_update", + ), + ); + expect(checks).toBe(1); + // Another address is another OpenBot: Connect is back once it changes. + await userEvent.type(field, "x"); + expect(view.getByRole("button", { name: "Connect" })).toBeTruthy(); } else { // One way on, and it says what it does. expect(alert.textContent).toBe(said); @@ -1162,6 +1209,35 @@ for (const { kind, said, at, offer } of CONNECT_PROBLEMS) { }); } +/* + * On a build that never updates itself, the line that says so is part of the notice, as on the + * screen for the OpenBot on this computer. Seen on a Mac: it sat under the notice in body type, a + * second message about the same thing. + */ +test("an OpenBot this build is too old for says in its notice that this build doesn't update itself", async () => { + const said = + "The OpenBot at openbot.example.com needs a newer version of this app. Update OpenBot, then connect again."; + const view = await chooseConnect({ + check_openbot_address: () => { + throw { said, kind: "app-too-old" }; + }, + app_update_offer: { + version: null, + current: "1.1.0", + installing: null, + updatesItself: false, + }, + }); + const field = view.getByLabelText("OpenBot address") as HTMLInputElement; + await userEvent.type(field, `${ELSEWHERE}{Enter}`); + const line = await view.findByText(DOESNT_UPDATE_ITSELF); + const notice = view.getByRole("alert"); + expect(notice.textContent).toContain(said); + expect(notice.contains(line)).toBe(true); + expect(view.queryByRole("button", { name: "Update and restart" })).toBeNull(); + expect(view.queryByRole("button", { name: "Connect" })).toBeNull(); +}); + test("Cancel while the browser is waited on stops the sign-in and gives the form back", async () => { const signIn = deferred(); const view = await chooseConnect({ @@ -3891,6 +3967,138 @@ test("the running screen opens on its heading, with Updates under the buttons, w ); }); +/* + * The OpenBot on this computer started, and needs a newer version of this app (its admin's minimum, + * or only a newer API). The window does not open it, and does not say it stopped or failed: it says + * "Update OpenBot" with the shell's sentence and Update and restart. Stop is still there. + */ +test("an OpenBot on this computer that needs a newer app says Update OpenBot, not that it stopped", async () => { + setupConnectedLocalStack( + "/tmp/local-eval-app-too-old", + localStatus("ready", "valid"), + ); + const said = + "The OpenBot on this computer needs a newer version of this app. Update OpenBot to keep going."; + const previous = invokeHandler; + invokeHandler = async (command, args) => { + if (command === "show_openbot") + throw { + said, + detail: + "the deployment's minimumClients.desktop is 1.2.0; this app is desktop/1.1.0 and speaks v2", + kind: "app-too-old", + }; + if (command === "app_update_offer") + return { + version: null, + current: "1.1.0", + installing: null, + updatesItself: true, + }; + return previous(command, args); + }; + const view = await renderApp(); + await waitFor(() => expect(localSequence()).toContain("start_stack")); + const heading = await view.findByRole("heading", { + level: 1, + name: "Update OpenBot", + }); + expect(view.queryByRole("heading", { name: "OpenBot stopped" })).toBeNull(); + expect(view.queryByText("That didn’t finish")).toBeNull(); + expect(view.queryByRole("list", { name: "Setup progress" })).toBeNull(); + const card = view.getByRole("alert"); + expect(card.textContent).toContain(said); + // One heading says it: the card under it does not say it again. + expect(within(card).queryByRole("heading")).toBeNull(); + expect(heading.closest(".sheet")?.contains(card)).toBe(true); + expect(view.getByRole("button", { name: "Update and restart" })).toBeTruthy(); + expect(view.getByRole("button", { name: "Stop OpenBot" })).toBeTruthy(); +}); + +// The same, for a minimum raised because of a security problem: the security sentence is the heading, +// in place of Update OpenBot, and the card under it offers the update without saying it again. +test("an OpenBot on this computer that raised this app's minimum for a security problem says so as the heading", async () => { + setupConnectedLocalStack( + "/tmp/local-eval-app-too-old-security", + localStatus("ready", "valid"), + ); + const said = + "This version of OpenBot has a security problem. Update to keep using it."; + const previous = invokeHandler; + invokeHandler = async (command, args) => { + if (command === "show_openbot") + throw { + said, + detail: + "the deployment's minimumClients.desktop is 1.2.0, raised for a security problem (securityMinimumClients); this app is desktop/1.1.0 and speaks v2", + kind: "app-too-old-security", + }; + if (command === "app_update_offer") + return { + version: null, + current: "1.1.0", + installing: null, + updatesItself: true, + }; + return previous(command, args); + }; + const view = await renderApp(); + await waitFor(() => expect(localSequence()).toContain("start_stack")); + await view.findByRole("heading", { level: 1, name: said }); + expect(view.queryByRole("heading", { name: "Update OpenBot" })).toBeNull(); + expect(view.queryByRole("heading", { name: "OpenBot stopped" })).toBeNull(); + expect(view.getAllByText(said)).toHaveLength(1); + expect(view.getByRole("button", { name: "Update and restart" })).toBeTruthy(); + expect(view.getByRole("button", { name: "Stop OpenBot" })).toBeTruthy(); +}); + +/* + * The same OpenBot, found already running by a launch that did not start it: the app was quit or + * killed and opened again while OpenBot kept running. Seen on a Mac and on Windows: the window said + * "OpenBot is stopped" with Start OpenBot, the Update OpenBot card under it, while the server was up + * and answering. It is the screen Start shows when it finds the same: Update OpenBot, running, with + * Show OpenBot and Stop OpenBot, and nothing starts. + */ +test("a launch that finds this computer's OpenBot running and needing a newer app says Update OpenBot, never that it stopped", async () => { + setupConnectedLocalStack( + "/tmp/local-eval-app-too-old-found-running", + localStatus("ready", "valid"), + ); + const said = + "The OpenBot on this computer needs a newer version of this app. Update OpenBot to keep going."; + const previous = invokeHandler; + invokeHandler = async (command, args) => { + if (command === "already_running") return true; + if (command === "show_openbot") + throw { + said, + detail: + "the deployment's minimumClients.desktop is 1.2.0; this app is desktop/1.1.0 and speaks v2", + kind: "app-too-old", + }; + if (command === "app_update_offer") + return { + version: null, + current: "1.1.0", + installing: null, + updatesItself: true, + }; + return previous(command, args); + }; + const view = await renderApp(); + await view.findByRole("heading", { level: 1, name: "Update OpenBot" }); + const card = view.getByRole("alert"); + expect(card.textContent).toContain(said); + expect(within(card).queryByRole("heading")).toBeNull(); + expect(view.queryByText("OpenBot is stopped")).toBeNull(); + expect(view.queryByRole("button", { name: "Start OpenBot" })).toBeNull(); + expect(view.getByRole("button", { name: "Update and restart" })).toBeTruthy(); + expect(view.getByRole("button", { name: "Show OpenBot" })).toBeTruthy(); + expect(view.getByRole("button", { name: "Stop OpenBot" })).toBeTruthy(); + // Running already: nothing is started again. + expect(localSequence()).toEqual(["show_openbot"]); +}); + test("relaunch says when Docker Desktop did not start, and Retry opens it again", async () => { setupConnectedLocalStack( "/tmp/local-eval-docker-never", diff --git a/desktop/src/App.tsx b/desktop/src/App.tsx index 1c95518b42..ad0d584fa9 100644 --- a/desktop/src/App.tsx +++ b/desktop/src/App.tsx @@ -63,6 +63,7 @@ import { type SetupStep, } from "./telemetry"; import { choseThisComputer, rememberThisComputer } from "./thisComputer"; +import { AppTooOld, appTooOld, forSecurity } from "./UpdateOpenBot"; import { UsageDataChoice } from "./UsageDataChoice"; import { type Hosting, Welcome } from "./Welcome"; import { @@ -743,7 +744,19 @@ function LocalSetup({ address, choose }: { address: string; choose: boolean }) { ) ) { // Already up from a previous window: show it, rather than a screen about it. - await invoke("show_openbot"); + try { + await invoke("show_openbot"); + } catch (error) { + /* + * Up, and needing a newer version of this app: the shell holds it as this session's + * and does not show it. It is running, so the window says so as when Start finds the + * same (Update OpenBot, with Show OpenBot and Stop OpenBot), never that it stopped. + */ + if (!appTooOld(asProblem(error))) throw error; + setRunning(true); + recoverFromStart(error); + return; + } setRunning(true); return; } @@ -1753,7 +1766,17 @@ function LocalSetup({ address, choose }: { address: string; choose: boolean }) { {/* A failure outranks `running`. The supervisor gives up on a process and sends the window back here, and a heading that still says everything is running while the box underneath names the process that stopped is a screen arguing with itself. */} -

{displayedFailure ? "OpenBot stopped" : "OpenBot is running"}

+ {/* Running, and needing a newer version of this app: nothing stopped, so the heading says + what to do and the card under it offers the update. */} +

+ {forSecurity(displayedFailure) && displayedFailure + ? displayedFailure.said + : appTooOld(displayedFailure) + ? "Update OpenBot" + : displayedFailure + ? "OpenBot stopped" + : "OpenBot is running"} +

{/* The back end runs the release it had: information, said where the lede goes. Nothing failed, so it is not drawn as a failure and offers no help. */} {!displayedFailure && backEndNotice && ( @@ -1774,8 +1797,14 @@ function LocalSetup({ address, choose }: { address: string; choose: boolean }) { {/* The start's rows only when something failed, to show where. Once OpenBot runs they are all done, and they flashed for the moment before it opened with the native side's own words ("settings written, credentials stored"). */} - {displayedFailure && } - {displayedFailure && } + {appTooOld(displayedFailure) && displayedFailure ? ( + + ) : ( + <> + {displayedFailure && } + {displayedFailure && } + + )} {stopping && Stopping OpenBot…} {showing && Loading OpenBot…}
diff --git a/desktop/src/ConnectToOpenBot.tsx b/desktop/src/ConnectToOpenBot.tsx index 8f0dec1971..bcbf194b22 100644 --- a/desktop/src/ConnectToOpenBot.tsx +++ b/desktop/src/ConnectToOpenBot.tsx @@ -3,6 +3,11 @@ import { useEffect, useId, useRef, useState } from "react"; import { ExternalLink } from "./ExternalLink"; import { asProblem, type Problem } from "./Problem"; import { StatusLine } from "./SetupProgress"; +import { + APP_TOO_OLD, + APP_TOO_OLD_SECURITY, + UpdateOpenBot, +} from "./UpdateOpenBot"; /** * What the screen offers after something went wrong, chosen by the problem's `kind`. The sentence @@ -10,10 +15,11 @@ import { StatusLine } from "./SetupProgress"; * * `field`: the address is what to fix, so the sentence sits under the field and the field has the * focus. `sign-in` and `retry`: the screen's one button says Sign in again or Try again. `browser`: - * this app can't connect to that OpenBot, and a link opens it in the browser. A kind this app does - * not know is offered Try again. + * this app can't connect to that OpenBot, and a link opens it in the browser. `update`: this app is + * too old for that OpenBot, and the way on is this app's own update. A kind this app does not know + * is offered Try again. */ -type Offer = "field" | "retry" | "sign-in" | "browser"; +type Offer = "field" | "retry" | "sign-in" | "browser" | "update"; function offerFor(kind: string | null | undefined): Offer { switch (kind) { @@ -23,6 +29,9 @@ function offerFor(kind: string | null | undefined): Offer { return "field"; case "too-old": return "browser"; + case APP_TOO_OLD: + case APP_TOO_OLD_SECURITY: + return "update"; case "sign-in-cancelled": case "sign-in-failed": case "access-refused": @@ -142,7 +151,7 @@ export function useConnectToOpenBot({ if (offer !== "retry") setReopens(false); setPhase("idle"); // To the field when the address is what to fix, to the button when it is the way on. - if (offer !== "browser") + if (offer !== "browser" && offer !== "update") setFocus({ on: offer === "field" ? "field" : "action" }); } } @@ -256,28 +265,37 @@ export function ConnectToOpenBot({ connecting }: { connecting: Connecting }) { You'll sign in to it in your browser. Nothing is installed on this computer.

- {trouble && !underField && } -
- - {trouble?.offer === "browser" && address.trim() && ( - + )} + {/* This app is too old for that OpenBot: its own update is the way on, and Connect + comes back once the address is another. The update draws the notice, so a build + that never updates itself says so in it. */} + {trouble?.offer === "update" ? ( + + ) : ( +
+
+ {trouble?.offer === "sign-in" + ? "Sign in again" + : trouble?.offer === "retry" + ? "Try again" + : "Connect"} + + {trouble?.offer === "browser" && address.trim() && ( + + Open in browser + + )} +
+ )} {phase === "checking" && ( Checking the address… )} diff --git a/desktop/src/Problem.test.tsx b/desktop/src/Problem.test.tsx index 2050df2af1..c818c64c3a 100644 --- a/desktop/src/Problem.test.tsx +++ b/desktop/src/Problem.test.tsx @@ -4,12 +4,14 @@ import { cleanup, fireEvent, render, waitFor } from "@testing-library/react"; let invokeCalls: Array<{ command: string; args?: unknown }> = []; let invokeFailure: string | null = null; +/** What the shell answers a command, where a test needs more than nothing. */ +let answers: Record = {}; mock.module("@tauri-apps/api/core", () => ({ invoke: (command: string, args?: unknown) => { invokeCalls.push({ command, args }); if (invokeFailure) return Promise.reject(invokeFailure); - return Promise.resolve(null); + return Promise.resolve(answers[command] ?? null); }, })); @@ -27,6 +29,7 @@ beforeAll(() => afterEach(() => { invokeCalls = []; invokeFailure = null; + answers = {}; if (previousSupportUrl === undefined) delete process.env.VITE_OPENBOT_SUPPORT_URL; else process.env.VITE_OPENBOT_SUPPORT_URL = previousSupportUrl; @@ -34,6 +37,106 @@ afterEach(() => { }); afterAll(() => GlobalRegistrator.unregister()); +/** What the shell says when the OpenBot on this computer needs a newer app (`client_version.rs`). */ +const LOCAL_APP_TOO_OLD = { + said: "The OpenBot on this computer needs a newer version of this app. Update OpenBot to keep going.", + detail: + "the deployment's minimumClients.desktop is 1.2.0; this app is desktop/1.1.0 and speaks v2", + kind: "app-too-old", +}; + +/* + * An OpenBot that needs a newer version of this app is not a failure. Wherever setup shows a + * problem, it says "Update OpenBot" with the shell's sentence, and Update and restart reads the + * update feed and installs what it finds: no failure heading, no technical details, no logs. + */ +test("an OpenBot that needs a newer app says Update OpenBot and Update and restart installs the update", async () => { + answers = { + app_update_offer: { + version: null, + current: "1.1.0", + installing: null, + updatesItself: true, + }, + check_app_update: { + found: "available", + version: "1.2.0", + current: "1.1.0", + }, + // On success the app restarts into the new version, and never answers. + install_app_update: new Promise(() => {}), + }; + const view = render(); + const card = view.getByRole("alert"); + expect(view.getByRole("heading", { name: "Update OpenBot" })).toBeTruthy(); + expect(card.textContent).toContain(LOCAL_APP_TOO_OLD.said); + expect(view.queryByText("That didn’t finish")).toBeNull(); + expect(view.queryByText("Technical details")).toBeNull(); + expect(view.queryByRole("button", { name: "Copy logs" })).toBeNull(); + // Drawn as a notice, not as the failure card. + expect(card.classList.contains("blocker")).toBe(false); + const update = view.getByRole("button", { name: "Update and restart" }); + await waitFor(() => expect(update).toHaveProperty("disabled", false)); + fireEvent.click(update); + await waitFor(() => + expect(invokeCalls.map((call) => call.command)).toEqual([ + "app_update_offer", + "check_app_update", + "install_app_update", + ]), + ); + await waitFor(() => expect(update.textContent).toBe("Downloading…")); +}); + +/** The same, for a minimum the OpenBot on this computer raised because of a security problem. */ +const LOCAL_APP_TOO_OLD_SECURITY = { + said: "This version of OpenBot has a security problem. Update to keep using it.", + detail: + "the deployment's minimumClients.desktop is 1.2.0, raised for a security problem (securityMinimumClients); this app is desktop/1.1.0 and speaks v2", + kind: "app-too-old-security", +}; + +// For a security problem, the security sentence is the heading, in place of Update OpenBot, with the +// same update and nothing repeating it below. +test("an OpenBot that raised this app's minimum for a security problem says so in place of Update OpenBot, with the same update", async () => { + answers = { + app_update_offer: { + version: null, + current: "1.1.0", + installing: null, + updatesItself: true, + }, + }; + const view = render(); + expect( + view.getByRole("heading", { name: LOCAL_APP_TOO_OLD_SECURITY.said }), + ).toBeTruthy(); + expect(view.queryByRole("heading", { name: "Update OpenBot" })).toBeNull(); + expect(view.getAllByText(LOCAL_APP_TOO_OLD_SECURITY.said)).toHaveLength(1); + expect(view.queryByText("That didn’t finish")).toBeNull(); + const update = view.getByRole("button", { name: "Update and restart" }); + await waitFor(() => expect(update).toHaveProperty("disabled", false)); +}); + +// A build that never updates itself has nothing to press: it says how to get one that does. +test("an OpenBot that needs a newer app, on a build that doesn't update itself, says how to get one", async () => { + answers = { + app_update_offer: { + version: null, + current: "1.1.0-internal.12.gabc", + installing: null, + updatesItself: false, + }, + }; + const view = render(); + await waitFor(() => + expect(view.getByRole("alert").textContent).toContain( + "This version of OpenBot doesn't update itself. Install a released version of OpenBot to get updates.", + ), + ); + expect(view.queryByRole("button", { name: "Update and restart" })).toBeNull(); +}); + /* * The card a Mac showed when its disk filled mid-update: containerd's input/output errors and * nothing about disk space. The native side recognises the full disk in that output diff --git a/desktop/src/Problem.tsx b/desktop/src/Problem.tsx index 63cfc899f4..d21facf47e 100644 --- a/desktop/src/Problem.tsx +++ b/desktop/src/Problem.tsx @@ -3,6 +3,7 @@ import { useState } from "react"; import { ExternalLink } from "./ExternalLink"; import type { Shortfall } from "./localEvalCli"; import { resourcesShortSaid } from "./localReadiness"; +import { AppTooOld, appTooOld } from "./UpdateOpenBot"; /** * A failure, in both registers, wherever one happens. @@ -179,6 +180,9 @@ export function TroubleshootingLogs({ /** * `onRetry`, where the screen has no other way to run what failed again: Try again, in the card. * The install behind the account step had none, and its failure sat there with nothing to press. + * + * An OpenBot that needs a newer version of this app is not a failure: wherever one shows, it says + * "Update OpenBot" with this app's update (`AppTooOld`). */ export function Failure({ problem, @@ -187,6 +191,7 @@ export function Failure({ problem: Problem; onRetry?: () => void; }) { + if (appTooOld(problem)) return ; return (

That didn’t finish

diff --git a/desktop/src/UpdateOffer.tsx b/desktop/src/UpdateOffer.tsx index a4d611655f..6a2572b826 100644 --- a/desktop/src/UpdateOffer.tsx +++ b/desktop/src/UpdateOffer.tsx @@ -2,6 +2,7 @@ import { invoke } from "@tauri-apps/api/core"; import { useCallback, useEffect, useState } from "react"; import type { UpdateReadiness } from "../../shared/desktop-updates"; import { asProblem } from "./Problem"; +import { useUpdateOpenBotShowing } from "./UpdateOpenBot"; /** * What the shell offers. The same answer OpenBot's own page reads for its update banner, so the @@ -54,6 +55,7 @@ export function UpdateOffer() { const [declined, setDeclined] = useState(null); const [installing, setInstalling] = useState(false); const [failure, setFailure] = useState(null); + const standingBack = useUpdateOpenBotShowing(); useEffect(() => { let current = true; @@ -101,6 +103,8 @@ export function UpdateOffer() { }, []); const version = offer?.version; + // The window says an OpenBot needs this update, with its own Update and restart: one is enough. + if (standingBack) return null; if (!offer || !version || version === declined) return null; const progress = offer.installing; const ready = offer.ready; diff --git a/desktop/src/UpdateOpenBot.tsx b/desktop/src/UpdateOpenBot.tsx new file mode 100644 index 0000000000..1f92d6afd0 --- /dev/null +++ b/desktop/src/UpdateOpenBot.tsx @@ -0,0 +1,218 @@ +import { invoke } from "@tauri-apps/api/core"; +import { useEffect, useState, useSyncExternalStore } from "react"; +import { DOESNT_UPDATE_ITSELF } from "../../shared/desktop-updates"; +import type { Checked } from "./CheckForUpdates"; +import { asProblem, InlineFailure, type Problem } from "./Problem"; +import { type AppUpdate, describe } from "./UpdateOffer"; + +/** + * The `kind` the shell gives a problem when this app is older than the OpenBot it talks to serves + * (`client_version::APP_TOO_OLD`): connected to an OpenBot, such as OpenBot Cloud, that raised the + * oldest app it serves, or with an OpenBot on this computer that needs a newer app. + */ +export const APP_TOO_OLD = "app-too-old"; + +/** + * The same, when the minimum this app is below was raised because of a security problem in older + * releases (`client_version::APP_TOO_OLD_SECURITY`). The shell's sentence says so, and the window + * puts it where "Update OpenBot" would be. + */ +export const APP_TOO_OLD_SECURITY = "app-too-old-security"; + +/** Whether a problem is this app being too old for its OpenBot, for a security problem or not. */ +export function appTooOld(problem: Problem | null | undefined): boolean { + return problem?.kind === APP_TOO_OLD || forSecurity(problem); +} + +/** Whether this app is too old for its OpenBot because of a security problem. */ +export function forSecurity(problem: Problem | null | undefined): boolean { + return problem?.kind === APP_TOO_OLD_SECURITY; +} + +/** How often to ask the shell how an install is going, as Check for updates does. */ +const PROGRESS_EVERY_MS = 500; + +/** How many Update and restart buttons of this kind are on screen, and who wants to know. */ +let showing = 0; +const watchers = new Set<() => void>(); +function told() { + for (const watcher of watchers) watcher(); +} + +/** + * Whether an OpenBot that needs a newer app is being said on screen with its Update and restart. + * The offer at the top of the window stands back while it is, so the window offers the update + * once, in the card that says why. + */ +export function useUpdateOpenBotShowing(): boolean { + return useSyncExternalStore( + (changed) => { + watchers.add(changed); + return () => { + watchers.delete(changed); + }; + }, + () => showing > 0, + ); +} + +/** + * Update and restart, for an OpenBot that needs a newer version of this app. The same feed and the + * same install as the update offer at the top of this window and Check for updates: the feed is read + * now, and a newer version found is installed, and OpenBot restarts into it. A version the person + * closed the offer on before is still installed: they asked. + * + * A build that never updates itself (internal, candidate, or without the updater) says so, with + * nothing to press. When the feed has nothing newer, it says so and the button stays to try later. + * + * `said`: the sentence about the OpenBot, for a screen whose notice for it this draws (the connect + * screen): the notice, then Update and restart under it. + */ +export function UpdateOpenBot({ said }: { said?: string } = {}) { + const [updatesItself, setUpdatesItself] = useState(null); + const [phase, setPhase] = useState<"idle" | "checking" | "installing">( + "idle", + ); + const [progress, setProgress] = useState(null); + const [found, setFound] = useState(null); + const [failure, setFailure] = useState(null); + const [installFailure, setInstallFailure] = useState(null); + + useEffect(() => { + showing += 1; + told(); + return () => { + showing -= 1; + told(); + }; + }, []); + + useEffect(() => { + let current = true; + invoke("app_update_offer") + .then((offer) => { + if (current) setUpdatesItself(offer.updatesItself !== false); + }) + // A shell that doesn't say still offers the update: the install says what it can't do. + .catch(() => { + if (current) setUpdatesItself(true); + }); + return () => { + current = false; + }; + }, []); + + useEffect(() => { + if (phase !== "installing") return; + let current = true; + const timer = setInterval(async () => { + try { + const offer = await invoke("app_update_offer"); + if (current) setProgress(offer.installing); + } catch { + // Progress is a courtesy. The button already says it is downloading. + } + }, PROGRESS_EVERY_MS); + return () => { + current = false; + clearInterval(timer); + }; + }, [phase]); + + async function update() { + setFailure(null); + setInstallFailure(null); + setFound(null); + setPhase("checking"); + let checked: Checked; + try { + checked = await invoke("check_app_update"); + } catch (error) { + setFailure(asProblem(error)); + setPhase("idle"); + return; + } + setFound(checked); + if (checked.found !== "available" && checked.found !== "installing") { + setPhase("idle"); + return; + } + setPhase("installing"); + try { + // Returns only when it failed: on success the app restarts into the new version. + await invoke("install_app_update"); + } catch (error) { + setInstallFailure(asProblem(error).said); + setPhase("idle"); + setProgress(null); + } + } + + const doesntUpdate = updatesItself === false || found?.found === "notOffered"; + const line = doesntUpdate &&

{DOESNT_UPDATE_ITSELF}

; + // Given the sentence, the calm notice is drawn here, so a build that never updates itself says + // so in it, in its type, as the card for the OpenBot on this computer does (`AppTooOld`). + const notice = said !== undefined && ( +
+

{said}

+ {line} +
+ ); + if (doesntUpdate) return notice || line; + return ( + <> + {notice} +
+ +
+ {found?.found === "upToDate" && ( +

+ OpenBot {found.current} is the newest version available. Check again + later. +

+ )} + {installFailure && ( +

+ OpenBot could not install the update: {installFailure} +

+ )} + {failure && } + + ); +} + +/** + * An OpenBot that needs a newer version of this app, wherever setup shows a problem: the shell's + * sentence, which says "Update OpenBot", and Update and restart. Nothing failed, so it is not drawn as + * a failure: no "That didn't finish", no technical details, no troubleshooting logs. For a security + * problem the shell's sentence is the heading, in place of "Update OpenBot", and is not said twice. + */ +export function AppTooOld({ + problem, + headed = true, +}: { + problem: Problem; + /** False where the screen's own heading already says it. */ + headed?: boolean; +}) { + const security = forSecurity(problem); + return ( + // The calm notice the connect screen uses for a connection that didn't work, not the failure + // card: nothing failed. +
+ {headed &&

{security ? problem.said : "Update OpenBot"}

} + {!security &&

{problem.said}

} + +
+ ); +} diff --git a/desktop/src/setupLayout.browser.test.ts b/desktop/src/setupLayout.browser.test.ts index b73c5aba14..321877838b 100644 --- a/desktop/src/setupLayout.browser.test.ts +++ b/desktop/src/setupLayout.browser.test.ts @@ -87,7 +87,28 @@ fake.emit = emit; // the back end's, which the window runs first (a Mac at 8.2 GB). const updateShort = location.hash === "#update-short"; const backEndShort = location.hash === "#backend-short"; -const relaunch = location.hash === "#start" || updateShort || backEndShort; +// This app too old for its OpenBot, as the shell says it: connected to an OpenBot (such as OpenBot +// Cloud) that needs a newer app; one whose sign-in ended, as it always was; and the OpenBot on +// this computer needing a newer app once Start has it running. +const CONNECTED_PROBLEMS = { + "#connect-app-too-old": { said: "The OpenBot at openbot.example.com needs a newer version of this app. Update OpenBot, then connect again.", kind: "app-too-old" }, + "#connect-app-too-old-security": { said: "This version of OpenBot has a security problem. Update to keep using it.", kind: "app-too-old-security" }, + "#connect-session-ended": { said: "Your sign-in to openbot.example.com has ended. Sign in again to keep going.", kind: "session-ended" }, +}; +const connectedProblem = CONNECTED_PROBLEMS[location.hash]; +// The same, for a minimum raised because of a security problem. +const localSecurity = location.hash === "#local-app-too-old-security"; +const localTooOld = location.hash === "#local-app-too-old" || localSecurity; +// A launch that finds this computer's OpenBot already running, and that it needs a newer app. +const runningTooOld = location.hash === "#local-app-too-old-running"; +// The same launch, where showing it fails as it could before: the slot the card above lands in. +const runningFails = location.hash === "#local-running-fails"; +// The update feed has a newer version, so the offer at the top shows too. +const offered = location.search === "?offer"; +// A build that never updates itself (internal, candidate, or without the updater). +const internal = location.search === "?internal"; +// Found running by the launch is a relaunch too: an installation set up and started before. +const relaunch = location.hash === "#start" || updateShort || backEndShort || localTooOld || runningTooOld; const signingIn = location.hash === "#signin"; const installing = location.hash === "#licence-installing"; const pausing = location.hash === "#pause-podman"; @@ -123,6 +144,26 @@ fake.opened = []; export async function invoke(command, args) { fake.calls.push(command); if (command === "plugin:opener|open_url") fake.opened.push(args.url); + if (connectedProblem && command === "connection") + return { mode: "connected", address: "https://openbot.example.com", signedIn: true }; + if (connectedProblem && command === "show_connected") throw connectedProblem; + if ((runningTooOld || runningFails) && command === "already_running") return true; + if (runningFails && command === "show_openbot") + throw { said: "Part of OpenBot needs recovery. Try starting OpenBot once more." }; + if (localSecurity && command === "show_openbot") + throw { + said: "This version of OpenBot has a security problem. Update to keep using it.", + detail: "the deployment's minimumClients.desktop is 1.2.0, raised for a security problem (securityMinimumClients); this app is desktop/1.1.0 and speaks v2", + kind: "app-too-old-security", + }; + if ((localTooOld || runningTooOld) && command === "show_openbot") + throw { + said: "The OpenBot on this computer needs a newer version of this app. Update OpenBot to keep going.", + detail: "the deployment's minimumClients.desktop is 1.2.0; this app is desktop/1.1.0 and speaks v2", + kind: "app-too-old", + }; + if ((connectedProblem || localTooOld || runningTooOld) && command === "app_update_offer") + return { version: offered ? "1.2.0" : null, current: "1.1.0", installing: null, updatesItself: !internal, ready: null }; switch (command) { case "windows_restart_pending": case "take_ai_connection_change": @@ -140,7 +181,7 @@ export async function invoke(command, args) { } : { values: {}, saved: { modelApiKeys: none, modelSessions: none } }; case "upgrade_due": - return relaunch ? { from: "1.0.0", to: "1.0.1" } : null; + return relaunch && !localTooOld && !runningTooOld ? { from: "1.0.0", to: "1.0.1" } : null; case "upgrade_and_start": if (updateShort) throw { @@ -194,9 +235,10 @@ export async function invoke(command, args) { }; if (backEndShort) return { ...status("ready", "valid"), updateTo: "0.16.0-rc.13" }; return status("ready", "valid"); - // OpenBot's own start, the step's last row: it stays there for the test to look at. + // OpenBot's own start, the step's last row: it stays there for the test to look at. Running, + // when the window is about to find it needs a newer app. case "start_stack": - return new Promise(() => {}); + return localTooOld ? null : new Promise(() => {}); // Usage data as a first run finds it: shared until the person says otherwise. case "plugin:openbot-desktop|usage_data": return { shared: true, offByEnvironment: false }; @@ -2136,3 +2178,237 @@ describe.skipIf(!asked)( }, 30_000); }, ); + +/* + * When this app is too old for its OpenBot (`client_version.rs`), the window says the shell's + * sentence and offers its one way on, Update and restart, in view and uncovered, without outgrowing + * the window. Beside them problems the screen always had, a sign-in that ended and a found-running + * OpenBot that fails to show, for comparison. With `OPENBOT_SHOTS_DIR` set, each is + * saved there in light and dark, at the window's default size. + */ +describe.skipIf(!asked)("an OpenBot this app is too old for", () => { + const shots = process.env.OPENBOT_SHOTS_DIR; + const states: { + name: string; + at: string; + said: string; + way: { role: "button" | "link"; name: string }; + /** The window's heading, where the state's screen is OpenBot on this computer running. */ + heading?: string; + }[] = [ + { + name: "connected-app-too-old", + at: "#connect-app-too-old", + said: "needs a newer version of this app. Update OpenBot, then connect again.", + way: { role: "button", name: "Update and restart" }, + }, + { + name: "connected-app-too-old-with-offer", + at: "?offer#connect-app-too-old", + said: "needs a newer version of this app. Update OpenBot, then connect again.", + way: { role: "button", name: "Update and restart" }, + }, + { + name: "connected-app-too-old-security", + at: "#connect-app-too-old-security", + said: "This version of OpenBot has a security problem. Update to keep using it.", + way: { role: "button", name: "Update and restart" }, + }, + { + name: "local-app-too-old-security", + at: "#local-app-too-old-security", + said: "This version of OpenBot has a security problem. Update to keep using it.", + way: { role: "button", name: "Update and restart" }, + }, + { + name: "local-app-too-old", + at: "#local-app-too-old", + said: "The OpenBot on this computer needs a newer version of this app. Update OpenBot to keep going.", + way: { role: "button", name: "Update and restart" }, + heading: "Update OpenBot", + }, + // Found running by a launch that did not start it: the same screen as when Start finds it. + { + name: "local-app-too-old-found-running", + at: "?offer#local-app-too-old-running", + said: "The OpenBot on this computer needs a newer version of this app. Update OpenBot to keep going.", + way: { role: "button", name: "Update and restart" }, + heading: "Update OpenBot", + }, + { + name: "existing-found-running-fails", + at: "#local-running-fails", + said: "Part of OpenBot needs recovery. Try starting OpenBot once more.", + way: { role: "button", name: "Install" }, + }, + { + name: "existing-session-ended", + at: "#connect-session-ended", + said: "Your sign-in to openbot.example.com has ended.", + way: { role: "button", name: "Sign in again" }, + }, + ]; + for (const state of states) { + for (const [width, height] of [ + [1000, 800], + [720, 560], + ] as const) { + test(`${state.name} at ${width}x${height}: the sentence and its way on are in view`, async () => { + for (const colorScheme of ["light", "dark"] as const) { + const page = await browser.newPage({ + viewport: { width, height }, + colorScheme, + }); + try { + await open(page, state.at); + await page.getByText(state.said, { exact: false }).waitFor(); + // The card's entrance, and the update offer's first answer, settled. + await page.waitForTimeout(1200); + // The card's own way on: the last of its name, under the offer at the top when there is one. + const way = await page.evaluate(({ role, name }) => { + const found = [ + ...document.querySelectorAll(role === "link" ? "a" : "button"), + ].filter((element) => element.textContent?.trim() === name); + const element = found.at(-1); + if (!element) return null; + // A step taller than the window scrolls inside its card: there, it is reached so. + element.scrollIntoView({ block: "nearest" }); + const box = element.getBoundingClientRect(); + const top = document.elementFromPoint( + box.left + box.width / 2, + box.top + box.height / 2, + ); + return { + y: box.top, + bottom: box.bottom, + covered: !(top && (top === element || element.contains(top))), + enabled: !(element as HTMLButtonElement).disabled, + }; + }, state.way); + expect({ state: state.name, found: way !== null }).toEqual({ + state: state.name, + found: true, + }); + expect(way?.y ?? -1).toBeGreaterThanOrEqual(0); + expect(way?.bottom ?? height + 1).toBeLessThanOrEqual(height); + expect({ state: state.name, covered: way?.covered }).toEqual({ + state: state.name, + covered: false, + }); + expect(way?.enabled).toBe(true); + // Running, so never "OpenBot is stopped" with a Start: Show OpenBot and Stop OpenBot. + if (state.heading) { + const screen = await page.evaluate(() => ({ + heading: document.querySelector("h1")?.textContent?.trim(), + buttons: [...document.querySelectorAll("button")].map( + (button) => button.textContent?.trim(), + ), + })); + expect(screen.heading).toBe(state.heading); + expect(screen.buttons).not.toContain("Start OpenBot"); + expect(screen.buttons).toContain("Show OpenBot"); + expect(screen.buttons).toContain("Stop OpenBot"); + } + // One Update and restart: the offer at the top stands back while the card says why. + if (state.way.name === "Update and restart") + expect( + await page.evaluate( + () => + [...document.querySelectorAll("button")].filter( + (button) => + button.textContent?.trim() === "Update and restart", + ).length, + ), + ).toBe(1); + const fits = await page.evaluate(() => ({ + page: document.documentElement.scrollHeight, + window: window.innerHeight, + wide: document.documentElement.scrollWidth, + across: window.innerWidth, + })); + expect(fits.page).toBeLessThanOrEqual(fits.window); + expect(fits.wide).toBeLessThanOrEqual(fits.across); + if (shots && width === 1000) + await page.screenshot({ + path: `${shots}/${state.name}-${colorScheme}.png`, + }); + } finally { + await page.close(); + } + } + }, 30_000); + } + } + + /* + * On a build that never updates itself, the line that says so is part of the notice, in the + * notice's type, on the connect screen as on the screen for the OpenBot on this computer. Seen on + * a Mac: on the connect screen it sat under the notice in body type. + */ + for (const state of [ + { + name: "connected-app-too-old-internal", + at: "?internal#connect-app-too-old", + said: "needs a newer version of this app. Update OpenBot, then connect again.", + }, + { + name: "local-app-too-old-internal", + at: "?internal#local-app-too-old", + said: "The OpenBot on this computer needs a newer version of this app. Update OpenBot to keep going.", + }, + ]) { + test(`${state.name}: "doesn't update itself" is in the notice, in the notice's type`, async () => { + for (const colorScheme of ["light", "dark"] as const) { + const page = await browser.newPage({ + viewport: { width: 1000, height: 800 }, + colorScheme, + }); + try { + await open(page, state.at); + await page.getByText(state.said, { exact: false }).waitFor(); + // The update's own line (Updates, folded under the buttons, says it too). + await page + .locator('p[role="status"]', { hasText: "doesn't update itself" }) + .waitFor(); + await page.waitForTimeout(1200); + const placed = await page.evaluate((said) => { + const notice = [...document.querySelectorAll(".local-alert")].find( + (element) => element.textContent?.includes(said), + ); + const sentence = [...(notice?.querySelectorAll("p") ?? [])].find( + (element) => element.textContent?.includes(said), + ); + const line = [ + ...document.querySelectorAll('p[role="status"]'), + ].find((element) => + element.textContent?.includes("doesn't update itself"), + ); + const size = (element: Element | undefined) => + element ? getComputedStyle(element).fontSize : null; + return { + inside: Boolean(notice && line && notice.contains(line)), + line: size(line), + notice: size(sentence), + updates: [...document.querySelectorAll("button")].filter( + (button) => button.textContent?.trim() === "Update and restart", + ).length, + }; + }, state.said); + expect(placed.notice).not.toBeNull(); + expect(placed).toEqual({ + inside: true, + line: placed.notice, + notice: placed.notice, + updates: 0, + }); + if (shots) + await page.screenshot({ + path: `${shots}/${state.name}-${colorScheme}.png`, + }); + } finally { + await page.close(); + } + } + }, 30_000); + } +}); diff --git a/desktop/src/styles.css b/desktop/src/styles.css index 2e3e139b28..02c09bb3a2 100644 --- a/desktop/src/styles.css +++ b/desktop/src/styles.css @@ -456,6 +456,12 @@ button.text-link:hover:not(:disabled) { background: color-mix(in srgb, var(--ring) 7%, var(--card)); } +/* "Update OpenBot" sits where a failure card would, so it keeps that card's place: apart from what + is above it, and the next row's own gap below. */ +.local-alert.app-too-old { + margin: 20px 0 0; +} + .local-alert h2 { display: flex; align-items: center; @@ -486,6 +492,11 @@ button.text-link:hover:not(:disabled) { margin-top: 12px; } +/* A card with nothing said above its button (the heading over it already says why): no gap above. */ +.local-alert.app-too-old > .row:first-child { + margin-top: 0; +} + /* Under its button, a line keeps the row's gap rather than touching the button. */ .local-alert .row + .footnote { margin-top: 12px; diff --git a/extension/src/background/connection.ts b/extension/src/background/connection.ts index 60ded7e0e6..52344d8502 100644 --- a/extension/src/background/connection.ts +++ b/extension/src/background/connection.ts @@ -15,7 +15,11 @@ import { getRecorderIdentity, type RecorderConnectionGrant, } from "../shared/generated/recorder"; -import { OpenBotError, ORGANIZATION_ID } from "../shared/openbot-client"; +import { + OpenBotError, + ORGANIZATION_ID, + updateRequiredSentence, +} from "../shared/openbot-client"; import { normaliseOpenBotOrigin } from "../shared/origin"; import { allowsOpenBot, @@ -361,13 +365,14 @@ async function approve( ); } catch (error) { // The Recorder's own sentence for what OpenBot answered (EXCHANGE_REFUSED), or a plain one: a network failure's - // message ("Failed to fetch") means nothing here. + // message ("Failed to fetch") means nothing here. An OpenBot that serves only newer Recorders says to update. return { ok: false, error: - error instanceof OpenBotError + updateRequiredSentence(error) ?? + (error instanceof OpenBotError ? (EXCHANGE_REFUSED[error.status] ?? EXCHANGE_FAILED) - : UNREACHABLE, + : UNREACHABLE), }; } const connection: ConnectionRecord = { @@ -894,7 +899,11 @@ async function desktopConnect( } catch (error) { return refused( error instanceof OpenBotError - ? "exchange-refused" + ? error.updateRequired + ? error.securityUpdateRequired + ? "client-security-update-required" + : "client-update-required" + : "exchange-refused" : "openbot-unreachable", ); } diff --git a/extension/src/background/recording.ts b/extension/src/background/recording.ts index 98f6dd9db9..9633aae797 100644 --- a/extension/src/background/recording.ts +++ b/extension/src/background/recording.ts @@ -46,7 +46,11 @@ import { KEPT_FOR_PERSON_MS, RECORDER_ACTION_NOTICE_AT, } from "../shared/limits"; -import { OpenBotError, ORGANIZATION_ID } from "../shared/openbot-client"; +import { + OpenBotError, + ORGANIZATION_ID, + updateRequiredSentence, +} from "../shared/openbot-client"; import { isRecordablePage } from "../shared/origin"; import { allowsOpenBot, @@ -573,6 +577,8 @@ const signedOutReason = (error: unknown): SignedOutReason | null => * text in its answer, which the popup would show in the Recorder's own voice. */ const sentenceFor = (error: unknown, fallback: string): string => { if (!(error instanceof OpenBotError)) return fallback; + const update = updateRequiredSentence(error); + if (update) return update; if (error.body?.code === RECORDER_AUTHORITY_UNAVAILABLE) return SENTENCES.authorityUnavailable; return error.status === 403 ? SENTENCES.forbidden : fallback; diff --git a/extension/src/pages/popup/desktop-sentence.ts b/extension/src/pages/popup/desktop-sentence.ts index 8be4805c07..f69398946f 100644 --- a/extension/src/pages/popup/desktop-sentence.ts +++ b/extension/src/pages/popup/desktop-sentence.ts @@ -1,5 +1,6 @@ /** Why Connect with OpenBot Desktop did not connect this browser, one plain sentence per code: OpenBot Desktop's own - * error codes, and the Recorder's (no answer, the policy, an address it cannot use, OpenBot not taking Desktop's code). */ + * error codes, and the Recorder's (no answer, the policy, an address it cannot use, OpenBot not taking Desktop's code, + * OpenBot serving only newer Recorders, for a security problem or not). */ const SENTENCES: Record = { "origin-not-allowed": "OpenBot Desktop does not recognise this copy of the Recorder. Connect from OpenBot in your browser instead.", @@ -27,6 +28,10 @@ const SENTENCES: Record = { "OpenBot Desktop answered with an address the Recorder cannot use. Connect from OpenBot in your browser instead.", "exchange-refused": "OpenBot did not accept the code OpenBot Desktop gave the Recorder. Try again.", + "client-update-required": + "This OpenBot needs a newer OpenBot Recorder. Update OpenBot, then try again.", + "client-security-update-required": + "This version of OpenBot has a security problem. Update to keep using it.", "openbot-unreachable": "OpenBot did not answer. Make sure OpenBot is running in OpenBot Desktop, then try again.", }; diff --git a/extension/src/shared/generated/recorder.ts b/extension/src/shared/generated/recorder.ts index e7929d0e5a..2d0d0bd092 100644 --- a/extension/src/shared/generated/recorder.ts +++ b/extension/src/shared/generated/recorder.ts @@ -289,6 +289,12 @@ export interface Problem { capability?: string; /** What is wrong, item by item, when a refusal has more than one reason: each entry names the item and says what is wrong with it. */ problems?: ProblemProblemsItem[]; + /** On CLIENT_UPDATE_REQUIRED, the app the OpenBot-Client header named that is older than this OpenBot serves. A later OpenBot may name another app; read one you don't know as other. */ + client?: string; + /** On CLIENT_UPDATE_REQUIRED, the oldest release of that app this OpenBot serves. */ + minimumVersion?: string; + /** On CLIENT_UPDATE_REQUIRED, true when the minimum the app is below was raised because of a security problem in older releases. */ + security?: boolean; } /** diff --git a/extension/src/shared/openbot-client.ts b/extension/src/shared/openbot-client.ts index c24220e1a9..a9566cfd4e 100644 --- a/extension/src/shared/openbot-client.ts +++ b/extension/src/shared/openbot-client.ts @@ -1,3 +1,13 @@ +import { + CLIENT_HEADER, + CLIENT_KINDS, + CLIENT_UPDATE_REQUIRED, + type ClientKind, + clientToken, + clientUpdateDetail, + isVersion, + SECURITY_UPDATE_SENTENCE, +} from "@openbot/shared/client-version"; import { RECORDER_SIGNED_OUT, type RecorderErrorBody, @@ -17,11 +27,54 @@ export class OpenBotError extends Error { get signedOut(): boolean { return this.status === 401 && this.body?.code === RECORDER_SIGNED_OUT; } + + /** True when OpenBot refused this Recorder as older than it serves (CLIENT_UPDATE_REQUIRED). */ + get updateRequired(): boolean { + return this.body?.code === CLIENT_UPDATE_REQUIRED; + } + + /** True when that refusal's minimum was raised because of a security problem in older releases. */ + get securityUpdateRequired(): boolean { + return ( + this.updateRequired && + (this.body as Record | null)?.security === true + ); + } +} + +/** What the person reads when OpenBot serves only newer Recorders and its answer names no release we can use. */ +export const RECORDER_UPDATE_REQUIRED = + "This OpenBot needs a newer OpenBot Recorder. Update OpenBot, then try again."; + +/** + * The sentence for OpenBot refusing this Recorder as too old, or null for any other failure. It is the Recorder's own + * sentence, the same one OpenBot words its refusal with (`clientUpdateDetail`), built from the app and release the + * answer names, or the security sentence when the minimum was raised for a security problem. The text of the answer + * itself is never shown: any site can answer as OpenBot, and only a known app, a release number and the security flag + * pass through. + */ +export function updateRequiredSentence(error: unknown): string | null { + if (!(error instanceof OpenBotError) || !error.updateRequired) return null; + if (error.securityUpdateRequired) return SECURITY_UPDATE_SENTENCE; + const body = error.body as Record | null; + const named = body?.client; + const kind: ClientKind = (CLIENT_KINDS as readonly unknown[]).includes(named) + ? (named as ClientKind) + : "recorder"; + const minimum = body?.minimumVersion; + return isVersion(minimum) + ? clientUpdateDetail(kind, minimum) + : RECORDER_UPDATE_REQUIRED; } type OpenBotTarget = { openbotUrl: string; token?: string }; -/** Sends the request with the bearer when there is one, never with cookies, and never follows a redirect. */ +/** + * Sends the request with the bearer when there is one, never with cookies, and never follows a redirect. Every request + * names the Recorder and the OpenBot release it was built from (`OpenBot-Client: recorder/`), so OpenBot can + * refuse a Recorder older than it serves with a sentence. These requests run in the service worker and the offscreen + * document, which the install's host access lets reach any OpenBot without a CORS preflight; never from a content script. + */ export async function openbotRaw( target: OpenBotTarget, path: string, @@ -29,6 +82,7 @@ export async function openbotRaw( ): Promise { const headers = new Headers(init.headers); if (target.token) headers.set("Authorization", `Bearer ${target.token}`); + headers.set(CLIENT_HEADER, clientToken("recorder")); const url = new URL(path, target.openbotUrl); if (url.origin !== new URL(target.openbotUrl).origin) { throw new Error( diff --git a/extension/tests/connection.test.ts b/extension/tests/connection.test.ts index c9d48745df..8de027289a 100644 --- a/extension/tests/connection.test.ts +++ b/extension/tests/connection.test.ts @@ -17,6 +17,7 @@ import { installConnection, trustedConnectRule, } from "../src/background/connection"; +import { desktopSentence } from "../src/pages/popup/desktop-sentence"; import type { RecorderPolicy } from "../src/shared/policy"; import { installIdFor, @@ -35,6 +36,31 @@ const bea = { id: "u2", name: "Bea", email: "bea@example.test" }; const HOSTILE = "Your Recorder is out of date. Install the new one from https://evil.example.test/recorder.crx."; +/** OpenBot's refusal of a Recorder older than it serves, in the shape of api/openapi/common.yaml's clientUpdateRequired + * example, for the Recorder. */ +const TOO_OLD = { + type: "https://open.bot/errors/client-update-required", + title: "This app is too old for this OpenBot.", + status: 400, + detail: + "This OpenBot needs the OpenBot Recorder 1.2.0 or later. Update OpenBot, then try again.", + code: "CLIENT_UPDATE_REQUIRED", + category: "validation", + retryable: false, + requestId: "req_example", + traceId: "trace_example", + client: "recorder", + minimumVersion: "1.2.0", +}; + +/** The same refusal for a minimum raised because of a security problem (the spec's clientUpdateRequiredSecurity). */ +const INSECURE = { + ...TOO_OLD, + detail: + "This version of OpenBot has a security problem. Update to keep using it.", + security: true, +}; + let server: ReturnType; /** * The web OpenBot most tests connect: an https site, as a hosted OpenBot is. The Recorder takes a connect from OpenBot @@ -95,6 +121,16 @@ async function openbot(request: Request): Promise { await holdIfAsked(url.pathname); if (body.code === "obc_expired") return Response.json({ error: HOSTILE }, { status: 400 }); + if (body.code === "obc_insecure") + return Response.json(INSECURE, { + status: 400, + headers: { "content-type": "application/problem+json" }, + }); + if (body.code === "obc_too_old") + return Response.json(TOO_OLD, { + status: 400, + headers: { "content-type": "application/problem+json" }, + }); const refused = /^obc_refused_(\d{3})$/.exec(body.code); if (refused) return Response.json({ error: HOSTILE }, { status: Number(refused[1]) }); @@ -361,6 +397,36 @@ test("a code OpenBot refuses shows the Recorder's own sentence on the Connect pa expect(await readLocal("connection")).toBeUndefined(); }); +test("an OpenBot that serves only newer Recorders says so on the Connect page, Update OpenBot, and stores nothing", async () => { + await connect("obc_too_old"); + expect( + await handleConnectionMessage({ + type: "page.connect.decide", + approve: true, + label: "x", + origin, + }), + ).toEqual({ ok: false, error: TOO_OLD.detail }); + expect(await readLocal("connection")).toBeUndefined(); +}); + +test("an OpenBot that raised the Recorder's minimum for a security problem says so on the Connect page, and stores nothing", async () => { + await connect("obc_insecure"); + expect( + await handleConnectionMessage({ + type: "page.connect.decide", + approve: true, + label: "x", + origin, + }), + ).toEqual({ + ok: false, + error: + "This version of OpenBot has a security problem. Update to keep using it.", + }); + expect(await readLocal("connection")).toBeUndefined(); +}); + test("an approve that cannot reach OpenBot shows a plain sentence, not the browser's error, and stores nothing", async () => { await connect("obc_abc"); const unreachable = spyOn(globalThis, "fetch").mockImplementation( @@ -894,6 +960,32 @@ test("a code OpenBot refuses, or an OpenBot that does not answer, stores nothing expect(await readSession("pendingConnect")).toBeUndefined(); }); +test("an OpenBot that serves only newer Recorders refuses Desktop's code with its own reason, which the popup says as Update OpenBot", async () => { + expect( + await connectThroughDesktop({ + askDesktop: async () => ({ openbotUrl: loopback, code: "obc_too_old" }), + openTab, + readPolicy: async () => policy, + }), + ).toEqual({ connected: false, reason: "client-update-required" }); + expect(desktopSentence("client-update-required")).toBe( + "This OpenBot needs a newer OpenBot Recorder. Update OpenBot, then try again.", + ); + expect(await currentConnection()).toBeNull(); + // One raised for a security problem has its own reason, which the popup says as that. + expect( + await connectThroughDesktop({ + askDesktop: async () => ({ openbotUrl: loopback, code: "obc_insecure" }), + openTab, + readPolicy: async () => policy, + }), + ).toEqual({ connected: false, reason: "client-security-update-required" }); + expect(desktopSentence("client-security-update-required")).toBe( + "This version of OpenBot has a security problem. Update to keep using it.", + ); + expect(await currentConnection()).toBeNull(); +}); + test("a pin elsewhere that lands while Desktop's code is exchanged keeps the connection out and revokes its new token", async () => { const exchange = holdAnswer( "/api/v2/organizations/default/recorder-connections", diff --git a/extension/tests/openbot-client.test.ts b/extension/tests/openbot-client.test.ts index 14944caec4..6dae1ee9cd 100644 --- a/extension/tests/openbot-client.test.ts +++ b/extension/tests/openbot-client.test.ts @@ -1,4 +1,6 @@ import { afterAll, beforeAll, expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; import { deleteCurrentRecorderConnection, exchangeRecorderConnectCode, @@ -27,8 +29,17 @@ type Seen = { key: string | null; contentType: string | null; body: unknown; + /** The OpenBot-Client header: which app is asking. */ + client: string | null; }; +/** The OpenBot release this Recorder is built from: the root package.json's version, read here on its own. */ +const RELEASE = ( + JSON.parse( + readFileSync(join(import.meta.dir, "../../package.json"), "utf8"), + ) as { version: string } +).version; + /** A refusal as OpenBot's API answers one: problem details (RFC 9457). */ function problem( status: number, @@ -99,6 +110,7 @@ beforeAll(() => { key: request.headers.get("idempotency-key"), contentType: request.headers.get("content-type"), body: text ? JSON.parse(text) : null, + client: request.headers.get("openbot-client"), }; const route = `${request.method} ${url.pathname}`; // OpenBot's API, at its addresses and in its shapes, for the Recorder's own operations. @@ -251,6 +263,31 @@ test("each of the Recorder's operations goes out through the mutator: its addres expect(seen?.key).toMatch(/^[0-9a-f]{32}$/); }); +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 }); + expect(seen).toMatchObject({ path: API.me, client: named }); + await reportRecorderActivity( + ORGANIZATION_ID, + { phase: "recording", actions: 1 }, + { target }, + ); + expect(seen).toMatchObject({ path: API.activity, client: named }); + await exchangeRecorderConnectCode( + ORGANIZATION_ID, + { + code: "obc_abc", + label: "Work laptop", + installId: "0123456789abcdef0123456789abcdef", + }, + { target: { openbotUrl } }, + ); + expect(seen).toMatchObject({ path: API.connections, client: named }); + await openbotRaw(target, "/ok", { method: "POST", body: "{}" }); + expect(seen).toMatchObject({ path: "/ok", client: named }); +}); + 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( diff --git a/extension/tests/recording.test.ts b/extension/tests/recording.test.ts index fec3e83849..dfe739c25a 100644 --- a/extension/tests/recording.test.ts +++ b/extension/tests/recording.test.ts @@ -3946,6 +3946,66 @@ test("a refusal from OpenBot reaches the popup in the Recorder's own sentence, n } }); +/** OpenBot's refusal of an app older than it serves, exactly as api/openapi/common.yaml's clientUpdateRequired example + * gives it. */ +const CLIENT_UPDATE_REQUIRED_EXAMPLE = { + type: "https://open.bot/errors/client-update-required", + title: "This app is too old for this OpenBot.", + status: 400, + detail: + "This OpenBot needs OpenBot Desktop 1.2.0 or later. Update OpenBot, then try again.", + code: "CLIENT_UPDATE_REQUIRED", + category: "validation", + retryable: false, + requestId: "req_example", + traceId: "trace_example", + client: "desktop", + minimumVersion: "1.2.0", +}; + +test("an OpenBot that serves only newer Recorders reaches the popup as its sentence: Update OpenBot, never a plain failure and never text the server made up", async () => { + for (const [body, sentence] of [ + [CLIENT_UPDATE_REQUIRED_EXAMPLE, CLIENT_UPDATE_REQUIRED_EXAMPLE.detail], + [ + { + ...CLIENT_UPDATE_REQUIRED_EXAMPLE, + detail: + "This OpenBot needs the OpenBot Recorder 1.2.0 or later. Update OpenBot, then try again.", + client: "recorder", + minimumVersion: "1.2.0", + }, + "This OpenBot needs the OpenBot Recorder 1.2.0 or later. Update OpenBot, then try again.", + ], + [ + { + ...CLIENT_UPDATE_REQUIRED_EXAMPLE, + detail: + "Your Recorder is out of date. Install the new one from https://evil.example.test.", + client: "evil", + minimumVersion: "see https://evil.example.test", + }, + "This OpenBot needs a newer OpenBot Recorder. Update OpenBot, then try again.", + ], + // A minimum raised for a security problem (the spec's clientUpdateRequiredSecurity), said in the Recorder's own + // words for it, whatever detail came with it. + [ + { + ...CLIENT_UPDATE_REQUIRED_EXAMPLE, + detail: "Install the fix from https://evil.example.test.", + client: "recorder", + minimumVersion: "1.2.0", + security: true, + }, + "This version of OpenBot has a security problem. Update to keep using it.", + ], + ] as const) { + openbot.learningRefusal = { status: 400, body }; + const answer = await page({ type: "page.learning" }); + expect(answer).toEqual({ ok: false, error: sentence }); + expect(JSON.stringify(answer)).not.toContain("evil"); + } +}); + test("page.learning reads the person's own Learning space", async () => { expect(await page({ type: "page.learning" })).toEqual({ ok: true, diff --git a/mobile/app/_layout.tsx b/mobile/app/_layout.tsx index bc2cd4af09..11b69e5ec0 100644 --- a/mobile/app/_layout.tsx +++ b/mobile/app/_layout.tsx @@ -1,9 +1,11 @@ import * as Notifications from "expo-notifications"; import { router, Stack } from "expo-router"; import { useEffect, useRef } from "react"; +import { View } from "react-native"; import { authClient } from "../src/auth"; import { withSecurityFloor } from "../src/floor-gate"; import { notificationDestination } from "../src/links"; +import { useVersionVerdict, VersionGate } from "../src/version-gate"; Notifications.setNotificationHandler({ handleNotification: async () => ({ @@ -15,6 +17,9 @@ Notifications.setNotificationHandler({ }); function Layout() { const { data: session } = authClient.useSession(); + // Asked before sign-in: whether this app and its OpenBot can work together. When they can't, one sentence covers + // the app, so no screen behind it is seen failing. + const { verdict, check } = useVersionVerdict(); const pending = useRef(null); const handled = useRef(null); useEffect(() => { @@ -36,19 +41,22 @@ function Layout() { return () => subscription.remove(); }, [session]); return ( - - - - - - - - - - - - - + + + + + + + + + + + + + + + void check()} /> + ); } export default withSecurityFloor(Layout); diff --git a/mobile/app/computer.tsx b/mobile/app/computer.tsx index fac9383fd5..89769c4ecd 100644 --- a/mobile/app/computer.tsx +++ b/mobile/app/computer.tsx @@ -25,6 +25,7 @@ import { } from "../src/api/generated/computers/computers"; import type { ComputerHumanInput } from "../src/api/generated/model"; import { authClient, serverUrl } from "../src/auth"; +import { clientHeaders } from "../src/release"; import { colors, input, muted, Problem, Screen, useAction } from "../src/ui"; type Frame = { uri: string; width: number; height: number }; @@ -59,7 +60,7 @@ function useLiveFrame(botId: string, enabled: boolean) { options: { headers: Record }, ) => WebSocket; socket = new Native(url, null, { - headers: cookie ? { Cookie: cookie } : {}, + headers: { ...clientHeaders(), ...(cookie ? { Cookie: cookie } : {}) }, }); socket.onmessage = (event) => { let message: unknown; diff --git a/mobile/src/api/generated/model/clientRelease.ts b/mobile/src/api/generated/model/clientRelease.ts new file mode 100644 index 0000000000..45b5f0897a --- /dev/null +++ b/mobile/src/api/generated/model/clientRelease.ts @@ -0,0 +1,9 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ + +/** + * An OpenBot release, such as 1.1.0. + * @pattern ^\d{1,6}\.\d{1,6}\.\d{1,6}(-[0-9A-Za-z.-]{1,64})?$ + */ +export type ClientRelease = string; diff --git a/mobile/src/api/generated/model/deployment.ts b/mobile/src/api/generated/model/deployment.ts index 30fdbaebc1..b113d710fb 100644 --- a/mobile/src/api/generated/model/deployment.ts +++ b/mobile/src/api/generated/model/deployment.ts @@ -4,6 +4,7 @@ import type { AttachmentLimits } from "./attachmentLimits"; import type { DeploymentAuthProvidersItem } from "./deploymentAuthProvidersItem"; import type { DeploymentEdition } from "./deploymentEdition"; +import type { MinimumClients } from "./minimumClients"; /** * What this OpenBot offers and how people sign in to it. @@ -36,4 +37,23 @@ export interface Deployment { /** Whether this OpenBot has computers for Bots at all. False, a Bot has no computer, browser or sign-in to a website, and the computers answer 503 to every call. Not isolatedBots: an OpenBot whose Bots share one computer has computers (true) and cannot give a Bot one of its own (isolatedBots false). */ botComputers: boolean; attachmentLimits?: AttachmentLimits; + /** + * The API versions this OpenBot serves, by major, such as v2. An app that speaks none of them can't use it: when they are all newer than the app's, the app needs an update; when they are all older, this OpenBot does. Absent from a release before it was published, which serves v2. + * @minItems 1 + * @items.pattern ^v[1-9][0-9]{0,3}$ + */ + api?: string[]; + minimumClients?: MinimumClients; + /** The part of minimumClients raised because of a security problem in older releases: for each app named, the minimum is there for security. Absent or empty when none is. */ + securityMinimumClients?: MinimumClients; + /** + * The version of what OpenBot Desktop supplies when it starts this OpenBot on its own computer. It changes when Desktop must supply something new. + * @minimum 1 + */ + launcherApi?: number; + /** + * The version of what the OpenBot Recorder and this OpenBot exchange. + * @minimum 1 + */ + extensionApi?: number; } diff --git a/mobile/src/api/generated/model/index.ts b/mobile/src/api/generated/model/index.ts index 991f2f4fcc..00e9c06ad1 100644 --- a/mobile/src/api/generated/model/index.ts +++ b/mobile/src/api/generated/model/index.ts @@ -162,6 +162,7 @@ export * from "./checkInSkipReason"; export * from "./checkInUsage"; export * from "./checkInUsageDays"; export * from "./checkInUsagePings"; +export * from "./clientRelease"; export * from "./computer"; export * from "./computerAction"; export * from "./computerActionConflictResponse"; @@ -371,6 +372,7 @@ export * from "./memorySourceTool"; export * from "./memorySourceToolInputSchema"; export * from "./memorySourceToolPage"; export * from "./memoryUnavailableResponse"; +export * from "./minimumClients"; export * from "./modelFailedResponse"; export * from "./modelNotConfiguredResponse"; export * from "./modelUsage"; diff --git a/mobile/src/api/generated/model/minimumClients.ts b/mobile/src/api/generated/model/minimumClients.ts new file mode 100644 index 0000000000..bedba5d4b8 --- /dev/null +++ b/mobile/src/api/generated/model/minimumClients.ts @@ -0,0 +1,14 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ +import type { ClientRelease } from "./clientRelease"; + +/** + * The oldest release of each OpenBot app this OpenBot serves. An app names itself in the OpenBot-Client header, and one older than its minimum here is refused with CLIENT_UPDATE_REQUIRED, everywhere but this deployment answer. An app not listed has no minimum. An OpenBot serves every app released in the last 12 months, so it names one only where its administrator raised it. Absent from a release before it was published. + */ +export interface MinimumClients { + web?: ClientRelease; + desktop?: ClientRelease; + mobile?: ClientRelease; + recorder?: ClientRelease; +} diff --git a/mobile/src/api/generated/model/problem.ts b/mobile/src/api/generated/model/problem.ts index 703b301dfb..2dc1292f00 100644 --- a/mobile/src/api/generated/model/problem.ts +++ b/mobile/src/api/generated/model/problem.ts @@ -31,4 +31,10 @@ export interface Problem { capability?: string; /** What is wrong, item by item, when a refusal has more than one reason: each entry names the item and says what is wrong with it. */ problems?: ProblemProblemsItem[]; + /** On CLIENT_UPDATE_REQUIRED, the app the OpenBot-Client header named that is older than this OpenBot serves. A later OpenBot may name another app; read one you don't know as other. */ + client?: string; + /** On CLIENT_UPDATE_REQUIRED, the oldest release of that app this OpenBot serves. */ + minimumVersion?: string; + /** On CLIENT_UPDATE_REQUIRED, true when the minimum the app is below was raised because of a security problem in older releases. */ + security?: boolean; } diff --git a/mobile/src/api/generated/organization-settings/organization-settings.ts b/mobile/src/api/generated/organization-settings/organization-settings.ts index afb6ea6047..13a9cd80ad 100644 --- a/mobile/src/api/generated/organization-settings/organization-settings.ts +++ b/mobile/src/api/generated/organization-settings/organization-settings.ts @@ -48,7 +48,7 @@ export const getGetDeploymentUrl = (organizationId: string) => { }; /** - * Return what this OpenBot offers and how people sign in to it: the edition, the features the apps draw, how large an attached file may be, and the sign-in options. Anybody may read it, signed in or not, because the sign-in screen reads it first. Signed in, it is answered in an organization the caller is a member of, and an organization they are not in, the organization `default` included, answers exactly as one that does not exist. Nobody signed in reads it in the organization `default`. It names no identity provider and no version: only whether single sign-on is set up and required. + * Return what this OpenBot offers and how people sign in to it: the edition, the features the apps draw, how large an attached file may be, and the sign-in options. Anybody may read it, signed in or not, because the sign-in screen reads it first. Signed in, it is answered in an organization the caller is a member of, and an organization they are not in, the organization `default` included, answers exactly as one that does not exist. Nobody signed in reads it in the organization `default`. It names no identity provider and no build: only whether single sign-on is set up and required, and which API versions and which releases of each OpenBot app it serves. It is never refused for the app's version, so an app reads it first to learn whether it, or the OpenBot, needs an update. * @summary Read what this OpenBot offers */ export const getDeployment = async ( diff --git a/mobile/src/api/request.ts b/mobile/src/api/request.ts index 82cebafccf..f8c37d4a1d 100644 --- a/mobile/src/api/request.ts +++ b/mobile/src/api/request.ts @@ -4,22 +4,34 @@ * Every operation the app uses calls this with the address, method, headers and serialised body the spec gives it. It * goes to the deployment the app was built for, in the organization the signed-in person is working in, with the * session's cookie and never the platform's own cookie jar, and a refusal is thrown as an {@link ApiError} in the server's own sentence. + * Every request names the app and the OpenBot release it was built from (`OpenBot-Client: mobile/`), and a + * refusal of this app as too old (CLIENT_UPDATE_REQUIRED) is also told to the root layout, which shows Update OpenBot. */ import * as Crypto from "expo-crypto"; import { authClient, serverUrl } from "../auth"; +import { + CLIENT_UPDATE_REQUIRED, + phoneUpdateDetail, + reportUpdateRequired, +} from "../client-version"; import { createOrganizationAddress, type ListedOrganization, ORGANIZATION, } from "../organization"; +import { clientHeaders } from "../release"; import { listOrganizations } from "./generated/organizations/organizations"; -/** A refusal from the server, with its status and the API's problem code when it gave one. */ +/** + * A refusal from the server, with its status and the API's problem code when it gave one, and whether a refusal of + * this app as too old was for a security problem. + */ export class ApiError extends Error { constructor( message: string, readonly status: number, readonly code?: string, + readonly security = false, ) { super(message); this.name = "ApiError"; @@ -92,13 +104,23 @@ const apiWrite = (url: string, method: string) => url.startsWith("/api/v2/") && method !== "GET"; /** The server's sentence for a refusal: the API's problems say it in `detail`, older routes in `error`. */ -function refusal(body: unknown): { said?: string; code?: string } { +function refusal(body: unknown): { + said?: string; + code?: string; + minimumVersion?: string; + security?: boolean; +} { if (!body || typeof body !== "object") return {}; const field = (name: string) => { const value = (body as Record)[name]; return typeof value === "string" ? value : undefined; }; - return { said: field("detail") ?? field("error"), code: field("code") }; + return { + said: field("detail") ?? field("error"), + code: field("code"), + minimumVersion: field("minimumVersion"), + security: (body as Record).security === true, + }; } export async function apiRequest( @@ -114,6 +136,7 @@ export async function apiRequest( // A new key for each write, unless the caller sends its own to retry with. if (apiWrite(url, method) && !headers["idempotency-key"]) headers["idempotency-key"] = Crypto.randomUUID(); + Object.assign(headers, clientHeaders()); const cookie = await authClient.getCookie(); if (cookie) headers.cookie = cookie; const address = await inOrganization(url, cookie); @@ -126,7 +149,15 @@ export async function apiRequest( if (response.status === 204) return undefined as T; const body: unknown = await response.json().catch(() => null); if (!response.ok) { - const { said, code } = refusal(body); + const { said, code, minimumVersion, security } = refusal(body); + if (code === CLIENT_UPDATE_REQUIRED) { + // A minimum raised for a security problem is always said in the app's own words for it. + const detail = security + ? phoneUpdateDetail(minimumVersion, true) + : (said ?? phoneUpdateDetail(minimumVersion)); + reportUpdateRequired(detail, security); + throw new ApiError(detail, response.status, code, security); + } throw new ApiError( said ?? `Request failed (${response.status}).`, response.status, diff --git a/mobile/src/auth.ts b/mobile/src/auth.ts index ce7ceefa76..2ead6e5de2 100644 --- a/mobile/src/auth.ts +++ b/mobile/src/auth.ts @@ -2,6 +2,7 @@ import { expoClient } from "@better-auth/expo/client"; import { ssoClient } from "@better-auth/sso/client"; import { createAuthClient } from "better-auth/react"; import * as SecureStore from "expo-secure-store"; +import { clientHeaders } from "./release"; const configured = process.env.EXPO_PUBLIC_SERVER_URL; if (!configured) @@ -21,6 +22,8 @@ if (endpoint.username || endpoint.password || endpoint.search || endpoint.hash) export const serverUrl = endpoint.origin; export const authClient = createAuthClient({ baseURL: serverUrl, + // Sign-in's own requests name the app too; the Expo plugin keeps these and adds the session's cookie. + fetchOptions: { headers: clientHeaders() }, plugins: [ expoClient({ scheme: "openbotmobile", diff --git a/mobile/src/client-version.ts b/mobile/src/client-version.ts new file mode 100644 index 0000000000..f286dcb2e7 --- /dev/null +++ b/mobile/src/client-version.ts @@ -0,0 +1,177 @@ +/** + * Whether this phone app and the OpenBot it talks to can work together, and the header it names itself in. + * + * The phone app is bundled on its own (Metro serves only mobile/), so it carries its own copy of the few rules in + * shared/client-version.ts. tests/client-version.test.ts holds this copy to every case in + * shared/fixtures/client-version/cases.json, the same cases the web app, the Recorder and OpenBot Desktop run. It + * imports nothing, so it can be tested without a phone. + */ + +/** The request header an app names itself in: `OpenBot-Client: mobile/`. */ +export const CLIENT_HEADER = "OpenBot-Client"; + +/** The problem code an OpenBot answers an app below its minimum with. */ +export const CLIENT_UPDATE_REQUIRED = "CLIENT_UPDATE_REQUIRED"; + +/** The API versions this app speaks. */ +export const API_VERSIONS: readonly string[] = ["v2"]; + +/** What a person reads when the app is older than the OpenBot it talks to serves. */ +export const APP_UPDATE_SENTENCE = "Update OpenBot"; +/** What a person reads in its place when the minimum the app is below was raised for a security problem. */ +export const SECURITY_UPDATE_SENTENCE = + "This version of OpenBot has a security problem. Update to keep using it."; + +/** The apps that name themselves, as the server's minimums list them. */ +type ClientKind = "web" | "desktop" | "mobile" | "recorder"; + +const VERSION = + /^v?(\d{1,6})\.(\d{1,6})\.(\d{1,6})(?:-([0-9A-Za-z.-]{1,64}))?$/; + +/** Whether `value` is a release number: `1.2.0`, `1.2.0-rc.1`, with or without a leading v. */ +export function isVersion(value: unknown): value is string { + return typeof value === "string" && VERSION.test(value); +} + +/** `/`, as an app sends it. */ +export function clientToken(kind: ClientKind, version: string) { + return `${kind}/${version}`; +} + +/** + * Release order, by semantic versioning's rules (semver.org, section 11): numbers first, and a pre-release + * (`1.2.0-rc.1`) before its release. Undefined when either is not a release number. + */ +export function compareVersions(a: string, b: string): number | undefined { + const left = VERSION.exec(a); + const right = VERSION.exec(b); + if (!left || !right) return undefined; + for (const index of [1, 2, 3]) { + const difference = Number(left[index]) - Number(right[index]); + if (difference !== 0) return Math.sign(difference); + } + const [leftPre, rightPre] = [left[4], right[4]]; + if (leftPre === rightPre) return 0; + if (leftPre === undefined) return 1; + if (rightPre === undefined) return -1; + const leftParts = leftPre.split("."); + const rightParts = rightPre.split("."); + for (let i = 0; i < Math.max(leftParts.length, rightParts.length); i++) { + const l = leftParts[i]; + const r = rightParts[i]; + if (l === undefined) return -1; + if (r === undefined) return 1; + const ln = /^\d+$/.test(l) ? Number(l) : undefined; + const rn = /^\d+$/.test(r) ? Number(r) : undefined; + if (ln !== undefined && rn !== undefined) { + if (ln !== rn) return Math.sign(ln - rn); + } else if (ln !== undefined) return -1; + else if (rn !== undefined) return 1; + else if (l !== r) return l < r ? -1 : 1; + } + return 0; +} + +/** The major of an API version, `v2` as 2. */ +function major(version: string): number | undefined { + const match = /^v(\d{1,4})$/.exec(version); + return match ? Number(match[1]) : undefined; +} + +/** + * - `ok`: they can. Features the server lacks are hidden by the fields that offer them, never by a version. + * - `app`: the app is too old. "Update OpenBot". `security` when the minimum it is below was raised for a security + * problem in older releases (the server names the app in `securityMinimumClients` above its version too). + * - `server`: the server serves only API versions older than any the app speaks. The phone app adds nothing for it: + * whoever runs that OpenBot keeps it and their apps matched, and the screens say what failed, as they always have. + */ +export type Compatibility = + | { fit: "ok" } + | { fit: "app"; minimum?: string; security?: true } + | { fit: "server" }; + +/** + * Whether an app and the OpenBot it talks to can work together, from that OpenBot's `deployment`. A `deployment` that + * publishes no `api` is from a release before this check, and every such release serves v2. + */ +export function compatibility( + deployment: { + api?: unknown; + minimumClients?: unknown; + securityMinimumClients?: unknown; + }, + client: { kind: ClientKind; version: string; speaks?: readonly string[] }, +): Compatibility { + const speaks = client.speaks ?? API_VERSIONS; + const served = Array.isArray(deployment.api) + ? deployment.api.filter( + (entry): entry is string => typeof entry === "string", + ) + : ["v2"]; + if (!served.some((version) => speaks.includes(version))) { + const newestServed = Math.max( + ...served.map(major).filter((n): n is number => n !== undefined), + ); + const newestSpoken = Math.max( + ...speaks.map(major).filter((n): n is number => n !== undefined), + ); + return newestServed > newestSpoken ? { fit: "app" } : { fit: "server" }; + } + const minimum = minimumFor(deployment.minimumClients, client.kind); + if (minimum && below(client.version, minimum)) { + const floor = minimumFor(deployment.securityMinimumClients, client.kind); + return floor && below(client.version, floor) + ? { fit: "app", minimum, security: true } + : { fit: "app", minimum }; + } + return { fit: "ok" }; +} + +/** The release `minimums` names for `kind`, when it names one. */ +function minimumFor(minimums: unknown, kind: ClientKind): string | undefined { + if (!minimums || typeof minimums !== "object") return undefined; + const minimum = (minimums as Record)[kind]; + return isVersion(minimum) ? minimum : undefined; +} + +/** Whether `version` is a release before `minimum`. */ +function below(version: string, minimum: string): boolean { + const order = compareVersions(version, minimum); + return order !== undefined && order < 0; +} + +/** + * What the update screen says under "Update OpenBot": OpenBot's own sentence for refusing this app (as + * shared/client-version.ts `clientUpdateDetail` words it for the phone app), with the release it needs when known, or + * the security sentence when the minimum was raised for a security problem. + */ +export function phoneUpdateDetail( + minimum?: string, + security?: boolean, +): string { + if (security) return SECURITY_UPDATE_SENTENCE; + return isVersion(minimum) + ? `This OpenBot needs the OpenBot phone app ${minimum.replace(/^v/, "")} or later. Update OpenBot, then try again.` + : "This OpenBot needs a newer OpenBot phone app. Update OpenBot, then try again."; +} + +/** What the root layout shows: the app, or "Update OpenBot" (`security` when it is for a security problem). */ +export type VersionVerdict = + | { kind: "ok" } + | { kind: "app"; detail: string; security?: true }; + +/** + * Anything that learns OpenBot refused this app as too old (a request's CLIENT_UPDATE_REQUIRED) says so here, and the + * root layout, which listens, shows the update screen in place of whatever was open. + */ +type UpdateRequired = (detail: string, security: boolean) => void; +const listeners = new Set(); +export function reportUpdateRequired(detail: string, security = false): void { + for (const listener of listeners) listener(detail, security); +} +export function onUpdateRequired(listener: UpdateRequired): () => void { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} diff --git a/mobile/src/release.ts b/mobile/src/release.ts new file mode 100644 index 0000000000..c09e422d93 --- /dev/null +++ b/mobile/src/release.ts @@ -0,0 +1,19 @@ +/** + * The OpenBot release this app was built from, and the header that names it on every request to OpenBot. + * + * It is the version in the repository's root package.json, which app.config.ts reads as the app is built into + * `extra.openbotRelease`. Expo's own app version is a store number and says nothing about which OpenBot this is. + */ +import Constants from "expo-constants"; +import { CLIENT_HEADER, clientToken, isVersion } from "./client-version"; + +const built = (Constants.expoConfig?.extra as { openbotRelease?: unknown }) + ?.openbotRelease; + +/** Undefined only for a build whose config was not read from this repository; such a build names no release. */ +export const RELEASE: string | undefined = isVersion(built) ? built : undefined; + +/** `OpenBot-Client: mobile/`, for every request this app sends to OpenBot. */ +export function clientHeaders(): Record { + return RELEASE ? { [CLIENT_HEADER]: clientToken("mobile", RELEASE) } : {}; +} diff --git a/mobile/src/version-check.ts b/mobile/src/version-check.ts new file mode 100644 index 0000000000..06a273f20b --- /dev/null +++ b/mobile/src/version-check.ts @@ -0,0 +1,43 @@ +/** + * Whether this phone app is new enough for the OpenBot it was built for, asked before anybody signs in. + * + * The app reads the OpenBot's `deployment` (which answers before sign-in) and decides by the rule in ./client-version. + * Only an app too old for its OpenBot is stopped, with "Update OpenBot". Anything else decides nothing: the screens say + * what failed, as they always have. + */ +import { ApiError, DEPLOYMENT_ORGANIZATION_ID } from "./api/request"; +import { getDeployment } from "./api/generated/organization-settings/organization-settings"; +import { + CLIENT_UPDATE_REQUIRED, + compatibility, + phoneUpdateDetail, + type VersionVerdict, +} from "./client-version"; +import { RELEASE } from "./release"; + +export async function checkVersion(): Promise { + let deployment: Awaited>; + try { + deployment = await getDeployment(DEPLOYMENT_ORGANIZATION_ID); + } catch (error) { + if (error instanceof ApiError && error.code === CLIENT_UPDATE_REQUIRED) + return error.security + ? { kind: "app", detail: error.message, security: true } + : { kind: "app", detail: error.message }; + return { kind: "ok" }; + } + // A build that names no release can still tell an API it doesn't speak; it is never refused for a version. + const fit = compatibility(RELEASE ? deployment : { api: deployment.api }, { + kind: "mobile", + version: RELEASE ?? "0.0.0", + }); + if (fit.fit === "app") + return fit.security + ? { + kind: "app", + detail: phoneUpdateDetail(fit.minimum, true), + security: true, + } + : { kind: "app", detail: phoneUpdateDetail(fit.minimum) }; + return { kind: "ok" }; +} diff --git a/mobile/src/version-gate.tsx b/mobile/src/version-gate.tsx new file mode 100644 index 0000000000..7c10181676 --- /dev/null +++ b/mobile/src/version-gate.tsx @@ -0,0 +1,110 @@ +/** + * The screen the root layout shows in place of the app when the app is too old for its OpenBot ("Update OpenBot", or + * the security sentence when the minimum was raised for a security problem). It covers everything, headers included, + * so nothing behind it is shown failing. + */ +import { useCallback, useEffect, useState } from "react"; +import { + ActivityIndicator, + AppState, + Button, + StyleSheet, + Text, + View, +} from "react-native"; +import { serverUrl } from "./auth"; +import { + APP_UPDATE_SENTENCE, + onUpdateRequired, + SECURITY_UPDATE_SENTENCE, + type VersionVerdict, +} from "./client-version"; +import { heading, muted } from "./ui"; +import { checkVersion } from "./version-check"; + +/** How long the check may hold the app before it opens anyway: a slow network decides nothing. */ +const CHECK_WAIT_MS = 8_000; + +/** The decision, asked as the app opens and each time it comes back to the front, and changed by any refusal. */ +export function useVersionVerdict() { + const [verdict, setVerdict] = useState( + "checking", + ); + const check = useCallback(async () => { + let timer: ReturnType | undefined; + const waited = new Promise((resolve) => { + timer = setTimeout(() => resolve({ kind: "ok" }), CHECK_WAIT_MS); + }); + const decided = await Promise.race([checkVersion(), waited]); + clearTimeout(timer); + setVerdict(decided); + }, []); + useEffect(() => { + void check(); + const subscription = AppState.addEventListener("change", (state) => { + if (state === "active") void check(); + }); + const stop = onUpdateRequired((detail, security) => + setVerdict( + security + ? { kind: "app", detail, security: true } + : { kind: "app", detail }, + ), + ); + return () => { + subscription.remove(); + stop(); + }; + }, [check]); + return { verdict, check }; +} + +export function VersionGate({ + verdict, + onRetry, +}: { + verdict: VersionVerdict | "checking"; + onRetry: () => void; +}) { + if (verdict !== "checking" && verdict.kind === "ok") return null; + return ( + + {verdict === "checking" ? ( + + ) : ( + + {verdict.security ? ( + // The security sentence is the heading, and says what to do: nothing repeats it below. + + {SECURITY_UPDATE_SENTENCE} + + ) : ( + <> + + {APP_UPDATE_SENTENCE} + + {verdict.detail} + + )} + {serverUrl} + +