diff --git a/api/openapi-desktop-installations.test.ts b/api/openapi-desktop-installations.test.ts new file mode 100644 index 0000000000..61952e9ced --- /dev/null +++ b/api/openapi-desktop-installations.test.ts @@ -0,0 +1,213 @@ +import { expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { parse } from "yaml"; +import { RecordDesktopInstallationBody } from "../app/src/lib/api/generated/product-events/product-events.zod"; + +/** + * recordDesktopInstallation, as the spec sets it out for both ways OpenBot Desktop signs in: the + * window's page sends it with its own session once it has traded the sign-in's code, and Desktop + * sends it with its own sign-in when it signs in itself. One address, outside any organization, + * an Idempotency-Key, and a body of one random (version 4) UUID and nothing else, which the server + * reads with the same generated schema, made strict. + */ + +type Schema = { + $ref?: string; + type?: string; + format?: string; + pattern?: string; + additionalProperties?: boolean; + required?: string[]; + properties?: Record; +}; +type Operation = { + operationId: string; + description?: string; + security?: Record[]; + parameters?: { $ref: string }[]; + requestBody?: { + required?: boolean; + content: Record< + string, + { schema: Schema; examples?: Record } + >; + }; + responses: Record; +}; + +const spec = parse( + readFileSync(join(import.meta.dir, "openapi.yaml"), "utf8"), +) as { + paths: Record>; + components: { + securitySchemes: Record< + string, + { flows?: { authorizationCode?: { scopes?: Record } } } + >; + schemas: Record; + parameters: Record< + string, + { name: string; in: string; required?: boolean } + >; + examples: Record; + }; +}; + +const PATH = "/api/v2/people/me/desktop-installations"; +const item = spec.paths[PATH] ?? {}; +const operation = item.post as Operation; + +test("the address takes only POST, with an Idempotency-Key, and answers 204", () => { + const methods = [ + "get", + "put", + "post", + "delete", + "patch", + "head", + "options", + "trace", + ]; + expect(Object.keys(item).filter((key) => methods.includes(key))).toEqual([ + "post", + ]); + expect(operation.operationId).toBe("recordDesktopInstallation"); + const parameters = (operation.parameters ?? []).map( + (parameter) => + spec.components.parameters[parameter.$ref.split("/").pop() as string], + ); + expect(parameters).toContainEqual( + expect.objectContaining({ + name: "Idempotency-Key", + in: "header", + required: true, + }), + ); + // The one success, also the answer where product telemetry is off and the report is dropped. + expect( + Object.keys(operation.responses).filter((code) => code.startsWith("2")), + ).toEqual(["204"]); + // Nothing comes back with the 204. + expect( + (operation.responses["204"] as { content?: unknown }).content, + ).toBeUndefined(); + // Outside an organization, so no organization can be not found. + expect(item.parameters).toBeUndefined(); + expect(Object.keys(operation.responses)).not.toContain("404"); +}); + +test("the window's page sends it with its session, and Desktop with its own sign-in; nothing else may", () => { + // The page in Desktop's window holds a web session; Desktop's own sign-in is an appOAuth token. + // An API key is automation, not a sign-in from an installation, so it is not offered. + expect(operation.security).toEqual([ + { webSession: [] }, + { appOAuth: ["conversations:write"] }, + ]); + // The scope is the one the other product events ask for. + const nudge = spec.paths[ + "/api/v2/organizations/{organizationId}/nudge-events" + ]?.post as Operation; + expect(nudge.security).toContainEqual({ appOAuth: ["conversations:write"] }); +}); + +test("Desktop's one scope, openbot, stands for the scope the operation needs", () => { + // Desktop asks for `openbot` and offline_access alone (connected/address.rs), and `openbot` is + // every other scope of appOAuth, so a sign-in that holds only `openbot` may send it. + const scopes = Object.keys( + spec.components.securitySchemes.appOAuth?.flows?.authorizationCode + ?.scopes ?? {}, + ); + expect(scopes).toContain("openbot"); + const needed = (operation.security ?? []).flatMap( + (entry) => entry.appOAuth ?? [], + ); + expect(needed.length).toBeGreaterThan(0); + for (const scope of needed) expect(scopes).toContain(scope); + const address = readFileSync( + join(import.meta.dir, "../desktop/src-tauri/src/connected/address.rs"), + "utf8", + ); + expect(address).toContain('const OPENBOT: &str = "openbot";'); +}); + +test("the body is one random (version 4) UUID named installationId and nothing else", () => { + expect(operation.requestBody?.required).toBe(true); + const media = operation.requestBody?.content["application/json"]; + const ref = media?.schema.$ref?.split("/").pop() as string; + const schema = spec.components.schemas[ref] as Schema; + expect(schema.additionalProperties).toBe(false); + expect(schema.required).toEqual(["installationId"]); + expect(Object.keys(schema.properties ?? {})).toEqual(["installationId"]); + expect(schema.properties?.installationId).toMatchObject({ + type: "string", + format: "uuid", + pattern: + "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$", + }); + + // The spec's own example is one the generated schema accepts. + const example = + spec.components.examples[ + media?.examples?.signedIn?.$ref.split("/").pop() as string + ]; + expect(RecordDesktopInstallationBody.safeParse(example?.value).success).toBe( + true, + ); + // Upper-case hex is still a version 4 UUID. + expect( + RecordDesktopInstallationBody.safeParse({ + installationId: "3F2C9A64-8E1B-4C7D-9A35-0B6E2D4F1C88", + }).success, + ).toBe(true); + expect( + RecordDesktopInstallationBody.safeParse({ installationId: "not-a-uuid" }) + .success, + ).toBe(false); + expect(RecordDesktopInstallationBody.safeParse({}).success).toBe(false); + // A UUID of any other version is refused: v1 carries a time and a hardware address, v7 a time, + // and the nil UUID is no installation's. + for (const other of [ + "6ba7b810-9dad-11d1-80b4-00c04fd430c8", + "01890a5d-ac96-774b-bcce-b302099a8057", + "00000000-0000-0000-0000-000000000000", + ]) { + expect( + RecordDesktopInstallationBody.safeParse({ installationId: other }) + .success, + ).toBe(false); + } + // Read strictly, as the server reads it (the spec's additionalProperties: false, checked above), + // anything beside the UUID is refused. + expect( + RecordDesktopInstallationBody.strict().safeParse(example?.value).success, + ).toBe(true); + for (const extra of [ + { email: "a@b.example" }, + { organizationId: "org_1" }, + { signInPath: "window" }, + ]) { + expect( + RecordDesktopInstallationBody.strict().safeParse({ + ...(example?.value as object), + ...extra, + }).success, + ).toBe(false); + } +}); + +test("the description says which servers may receive the id, every caller, and the dedupe key", () => { + // One line of prose each, so a reader of the spec alone knows who may receive the id: OpenBot + // Cloud only, never a self-hosted OpenBot; that Move to Cloud's sign-in is a caller beside the + // window's page; and what makes two sends count once. + const text = (operation.description ?? "").replace(/\s+/g, " "); + expect(text).toContain("OpenBot Cloud only"); + expect(text).toContain( + "A self-hosted OpenBot never receives it from Desktop.", + ); + expect(text).toContain("Move to Cloud's sign-in"); + expect(text).toContain( + "Its event id is made from the deployment, the caller's pseudonym and the installation id in lower case", + ); + expect(text).toContain("accepted and dropped, whoever sends it"); +}); diff --git a/api/openapi.yaml b/api/openapi.yaml index 0e2470c3a0..652156c914 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -13944,6 +13944,50 @@ paths: $ref: '#/components/responses/ServerError' default: $ref: '#/components/responses/UnexpectedError' + /api/v2/people/me/desktop-installations: + post: + tags: + - Product events + operationId: recordDesktopInstallation + summary: Record the OpenBot Desktop installation the caller signed in from + description: 'Tell OpenBot that the caller signed in from this OpenBot Desktop installation, by the random id its usage data is sent under at the sign-in, so usage data can join what the installation did before the sign-in with what the caller does after it. OpenBot Cloud only: Desktop''s usage-data switch is consent to CopilotKit, not to a company''s own server, so Desktop hands the id over, or sends it itself, only when the address it signed in to is OpenBot Cloud. A self-hosted OpenBot never receives it from Desktop. One operation serves every way Desktop signs in to OpenBot Cloud. Where Desktop''s window holds the sign-in, Desktop hands the window''s page the id with the sign-in''s code, and the page sends it with its own session once it has traded the code, with keepalive, so it still leaves when the page goes on. Where Desktop signs in itself, as Move to Cloud''s sign-in does, Desktop sends it with that sign-in. Desktop hands the id over only while the person shares usage data, and nothing is sent without that. An installation is the person''s, not an organization''s, and the page has just signed in and names none, so the address names none either. The id is a random (version 4) UUID, made by the installation, and names nothing about the person or the computer; any other version, which could carry a time or a hardware address, is refused. It is best effort: a client sends it once per sign-in with a new Idempotency-Key, waits on nothing, and treats any answer but 204 alike, never retrying, so a server without the operation, which answers 404, changes nothing. Each accepted report goes out with the rest of OpenBot''s product telemetry, beside the caller''s pseudonym, never their email or account id. Its event id is made from the deployment, the caller''s pseudonym and the installation id in lower case, so it repeats for the same caller and installation: when the window and Move to Cloud both send it for one person, distinct ids still count the link once. It joins the two; it merges no one. Where this OpenBot has product telemetry switched off, a valid report is accepted and dropped, whoever sends it.' + security: + - webSession: [] + - appOAuth: + - conversations:write + parameters: + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/DesktopInstallation' + examples: + signedIn: + $ref: '#/components/examples/DesktopInstallationSignedIn' + responses: + '204': + description: The report is accepted, including where product telemetry is switched off and it is dropped. + headers: + X-Request-Id: + $ref: '#/components/headers/RequestId' + '400': + $ref: '#/components/responses/InvalidRequest' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + '409': + $ref: '#/components/responses/IdempotencyConflict' + '413': + $ref: '#/components/responses/PayloadTooLarge' + '429': + $ref: '#/components/responses/TooManyRequests' + '500': + $ref: '#/components/responses/ServerError' + default: + $ref: '#/components/responses/UnexpectedError' /api/v2/organizations/{organizationId}/teams: parameters: - $ref: '#/components/parameters/OrganizationId' @@ -41279,6 +41323,18 @@ components: description: The organizations to deal with first, as getAccountDeletion lists them. items: $ref: '#/components/schemas/AccountDeletionBlocker' + DesktopInstallation: + type: object + description: The OpenBot Desktop installation the caller signed in from, by the random (version 4) UUID it keeps for its usage data. Names nothing about the computer, or about the person, who is the caller. + additionalProperties: false + required: + - installationId + properties: + installationId: + type: string + format: uuid + pattern: ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$ + description: The random (version 4) UUID OpenBot Desktop sends its usage data under at the sign-in; Desktop's own events carry it as their `deployment_id`. Desktop makes a new one when usage data is turned off and on again, or when the account it is tied to changes or signs out. Any other UUID version is refused. TeamSource: type: string description: 'Where a team comes from. openbot is a team made here. directory is a group of the company''s directory, kept in step with it: its name and its people are the directory''s and can''t be changed here.' @@ -63509,6 +63565,10 @@ components: value: status: deleting blockers: [] + DesktopInstallationSignedIn: + summary: The caller signed in to OpenBot Cloud from OpenBot Desktop. + value: + installationId: 3f2c9a64-8e1b-4c7d-9a35-0b6e2d4f1c88 TeamPageLast: summary: An organization's teams, on one page. value: diff --git a/api/openapi/common.yaml b/api/openapi/common.yaml index f4e606bb15..ab81ffe004 100644 --- a/api/openapi/common.yaml +++ b/api/openapi/common.yaml @@ -399,6 +399,7 @@ paths: /api/v2/people/me/invitations/{invitationId}/decline: { $ref: './organizations.yaml#/paths/~1api~1v2~1people~1me~1invitations~1{invitationId}~1decline' } /api/v2/people/me/account-deletion: { $ref: './accounts.yaml#/paths/~1api~1v2~1people~1me~1account-deletion' } /api/v2/people/me/account-deletion/cancel: { $ref: './accounts.yaml#/paths/~1api~1v2~1people~1me~1account-deletion~1cancel' } + /api/v2/people/me/desktop-installations: { $ref: './conversations.yaml#/paths/~1api~1v2~1people~1me~1desktop-installations' } /api/v2/organizations/{organizationId}/teams: { $ref: './teams.yaml#/paths/~1api~1v2~1organizations~1{organizationId}~1teams' } /api/v2/organizations/{organizationId}/teams/{teamId}: { $ref: './teams.yaml#/paths/~1api~1v2~1organizations~1{organizationId}~1teams~1{teamId}' } /api/v2/organizations/{organizationId}/teams/{teamId}/members: { $ref: './teams.yaml#/paths/~1api~1v2~1organizations~1{organizationId}~1teams~1{teamId}~1members' } diff --git a/api/openapi/conversations.yaml b/api/openapi/conversations.yaml index f31c723e12..c6baea3886 100644 --- a/api/openapi/conversations.yaml +++ b/api/openapi/conversations.yaml @@ -2223,6 +2223,84 @@ paths: $ref: './common.yaml#/components/responses/ServerError' default: $ref: './common.yaml#/components/responses/UnexpectedError' + /api/v2/people/me/desktop-installations: + post: + tags: + - Product events + operationId: recordDesktopInstallation + summary: Record the OpenBot Desktop installation the caller signed in from + description: >- + Tell OpenBot that the caller signed in from this OpenBot Desktop + installation, by the random id its usage data is sent under at the + sign-in, so usage data can join what the installation did before the + sign-in with what the caller does after it. OpenBot Cloud only: + Desktop's usage-data switch is consent to CopilotKit, not to a + company's own server, so Desktop hands the id over, or sends it + itself, only when the address it signed in to is OpenBot Cloud. A + self-hosted OpenBot never receives it from Desktop. One operation + serves every way Desktop signs in to OpenBot Cloud. Where Desktop's + window holds the sign-in, Desktop hands the window's page the id with + the sign-in's code, and the page sends it with its own session once + it has traded the code, with keepalive, so it still leaves when the + page goes on. Where Desktop signs in itself, as Move to Cloud's + sign-in does, Desktop sends it with that sign-in. Desktop hands the id + over only while the person shares usage data, and nothing is sent + without that. An installation is the person's, not an + organization's, and the page has just signed in and names none, so + the address names none either. The id is a random (version 4) UUID, + made by the installation, and names nothing about the person or the + computer; any other version, which could carry a time or a hardware + address, is refused. It is best effort: a client sends it once per + sign-in with a new Idempotency-Key, waits on nothing, and treats any + answer but 204 alike, never retrying, so a server without the + operation, which answers 404, changes nothing. Each accepted report + goes out with the rest of OpenBot's product telemetry, beside the + caller's pseudonym, never their email or account id. Its event id is + made from the deployment, the caller's pseudonym and the installation + id in lower case, so it repeats for the same caller and installation: + when the window and Move to Cloud both send it for one person, + distinct ids still count the link once. It joins the two; it merges + no one. Where this OpenBot has product telemetry switched off, a valid + report is accepted and dropped, whoever sends it. + security: + - webSession: [] + - appOAuth: + - conversations:write + parameters: + - $ref: './common.yaml#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/DesktopInstallation' + examples: + signedIn: + $ref: '#/components/examples/DesktopInstallationSignedIn' + responses: + '204': + description: >- + The report is accepted, including where product telemetry is + switched off and it is dropped. + headers: + X-Request-Id: + $ref: './common.yaml#/components/headers/RequestId' + '400': + $ref: './common.yaml#/components/responses/InvalidRequest' + '401': + $ref: './common.yaml#/components/responses/Unauthenticated' + '403': + $ref: './common.yaml#/components/responses/Forbidden' + '409': + $ref: './common.yaml#/components/responses/IdempotencyConflict' + '413': + $ref: './common.yaml#/components/responses/PayloadTooLarge' + '429': + $ref: './common.yaml#/components/responses/TooManyRequests' + '500': + $ref: './common.yaml#/components/responses/ServerError' + default: + $ref: './common.yaml#/components/responses/UnexpectedError' components: parameters: ConversationLimit: @@ -2797,6 +2875,26 @@ components: - web - desktop description: Where the caller saw or answered it. + DesktopInstallation: + type: object + description: >- + The OpenBot Desktop installation the caller signed in from, by the + random (version 4) UUID it keeps for its usage data. Names nothing + about the computer, or about the person, who is the caller. + additionalProperties: false + required: + - installationId + properties: + installationId: + type: string + format: uuid + pattern: '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$' + description: >- + The random (version 4) UUID OpenBot Desktop sends its usage data + under at the sign-in; Desktop's own events carry it as their + `deployment_id`. Desktop makes a new one when usage data is turned + off and on again, or when the account it is tied to changes or + signs out. Any other UUID version is refused. AppError: type: object description: An error the app hit and did not handle, as the app saw it. @@ -4221,6 +4319,9 @@ components: ProductEventViewed: summary: "An answer the caller saw in the web app." value: {"kind": "result_viewed", "threadId": "6f3d6b1f-6f10-4a53-9d51-5f0d6c0e2f1a", "messageId": "msg_0b1c6f0e", "surface": "web"} + DesktopInstallationSignedIn: + summary: "The caller signed in to OpenBot Cloud from OpenBot Desktop." + value: {"installationId": "3f2c9a64-8e1b-4c7d-9a35-0b6e2d4f1c88"} NudgeClicked: summary: "The caller opened OpenBot's repository from the star card, in OpenBot Desktop." value: {"nudge": "star-on-github", "action": "clicked", "place": "card", "surface": "desktop"} diff --git a/api/redocly/rules.mjs b/api/redocly/rules.mjs index 8037bce3c3..760b4afcfa 100644 --- a/api/redocly/rules.mjs +++ b/api/redocly/rules.mjs @@ -33,6 +33,9 @@ const OUTSIDE_AN_ORGANIZATION = [ "/api/v2/artifact-invites/redeem", // An error the app hit before anyone is signed in to an organization (signing in): there is none to name. "/api/v2/app-errors", + // The OpenBot Desktop installation the caller signed in from: it is the person's, not an + // organization's, and the page that sends it has just signed in and names none. + "/api/v2/people/me/desktop-installations", ]; const WRITE_METHODS = ["post", "put", "patch", "delete"]; const METHODS = ["get", "head", "options", "trace", ...WRITE_METHODS]; diff --git a/api/redocly/rules.test.ts b/api/redocly/rules.test.ts index 8a108c8a41..443d55e1f1 100644 --- a/api/redocly/rules.test.ts +++ b/api/redocly/rules.test.ts @@ -111,6 +111,10 @@ test("only the caller's own organizations, invitations and account deletion sit ); // An error the app hit before anyone is signed in to an organization. expect(Object.keys(spec().paths)).toContain("/api/v2/app-errors"); + // The OpenBot Desktop installation the caller signed in from, which is the person's. + expect(Object.keys(spec().paths)).toContain( + "/api/v2/people/me/desktop-installations", + ); const broken = spec(); // Nothing beside it is: not another of the person's own resources, and not the address under it. broken.paths["/api/v2/people/me/bots"] = broken.paths[BOTS]; diff --git a/app/src/lib/api/generated/model/desktopInstallation.ts b/app/src/lib/api/generated/model/desktopInstallation.ts new file mode 100644 index 0000000000..2908da5e99 --- /dev/null +++ b/app/src/lib/api/generated/model/desktopInstallation.ts @@ -0,0 +1,14 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ + +/** + * The OpenBot Desktop installation the caller signed in from, by the random (version 4) UUID it keeps for its usage data. Names nothing about the computer, or about the person, who is the caller. + */ +export interface DesktopInstallation { + /** + * The random (version 4) UUID OpenBot Desktop sends its usage data under at the sign-in; Desktop's own events carry it as their `deployment_id`. Desktop makes a new one when usage data is turned off and on again, or when the account it is tied to changes or signs out. Any other UUID version is refused. + * @pattern ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$ + */ + installationId: string; +} diff --git a/app/src/lib/api/generated/model/index.ts b/app/src/lib/api/generated/model/index.ts index cc27f954a9..88cdc26459 100644 --- a/app/src/lib/api/generated/model/index.ts +++ b/app/src/lib/api/generated/model/index.ts @@ -932,6 +932,7 @@ export * from "./deliveryState"; export * from "./deployment"; export * from "./deploymentAuthProvidersItem"; export * from "./deploymentEdition"; +export * from "./desktopInstallation"; export * from "./destination"; export * from "./destinationBotId"; export * from "./destinationConversationId"; @@ -1499,6 +1500,7 @@ export * from "./recheckSharedConnectionHeaders"; export * from "./reconnectApp"; export * from "./recordAppErrorHeaders"; export * from "./recordConversationActivityHeaders"; +export * from "./recordDesktopInstallationHeaders"; export * from "./recorderActivity"; export * from "./recorderActivityPhase"; export * from "./recorderAuthorityUnavailableResponse"; diff --git a/app/src/lib/api/generated/model/recordDesktopInstallationHeaders.ts b/app/src/lib/api/generated/model/recordDesktopInstallationHeaders.ts new file mode 100644 index 0000000000..f9d8acb0fb --- /dev/null +++ b/app/src/lib/api/generated/model/recordDesktopInstallationHeaders.ts @@ -0,0 +1,13 @@ +/** + * Generated by Orval from api/openapi.yaml. Do not edit: change the spec and run `bun run api:generate`. + */ +import type { IdempotencyKeyParameter } from "./idempotencyKeyParameter"; + +export type RecordDesktopInstallationHeaders = { + /** + * Generated by the caller for each write it means to make once. Reuse the same key and the same request for 24 hours after an uncertain response; the same key with a different request is a conflict. + * @minLength 1 + * @maxLength 128 + */ + "Idempotency-Key": IdempotencyKeyParameter; +}; diff --git a/app/src/lib/api/generated/product-events/product-events.msw.ts b/app/src/lib/api/generated/product-events/product-events.msw.ts index 889c6e6a9f..190afd6b50 100644 --- a/app/src/lib/api/generated/product-events/product-events.msw.ts +++ b/app/src/lib/api/generated/product-events/product-events.msw.ts @@ -8,7 +8,39 @@ import type { RequestHandlerOptions, } from "msw"; -import type { AppError, NudgeEvent, ProductEvent } from "../model"; +import type { + AppError, + DesktopInstallation, + NudgeEvent, + ProductEvent, +} from "../model"; + +export const getRecordDesktopInstallationMockHandler = ( + overrideResponse?: + | void + | (( + info: Parameters< + HttpResponseResolver + >[0], + ) => Promise | void), + options?: RequestHandlerOptions, +) => { + return http.post( + "*/api/v2/people/me/desktop-installations", + async ( + info: Parameters< + HttpResponseResolver + >[0], + ) => { + if (typeof overrideResponse === "function") { + await overrideResponse(info); + } + + return new HttpResponse(null, { status: 204 }); + }, + options, + ); +}; export const getRecordProductEventMockHandler = ( overrideResponse?: @@ -112,6 +144,7 @@ export const getRecordNudgeEventMockHandler = ( ); }; export const getProductEventsMock = () => [ + getRecordDesktopInstallationMockHandler(), getRecordProductEventMockHandler(), getRecordAppErrorMockHandler(), getRecordSignedOutAppErrorMockHandler(), diff --git a/app/src/lib/api/generated/product-events/product-events.ts b/app/src/lib/api/generated/product-events/product-events.ts index 99a4c08d8f..205084fa93 100644 --- a/app/src/lib/api/generated/product-events/product-events.ts +++ b/app/src/lib/api/generated/product-events/product-events.ts @@ -11,6 +11,7 @@ import type { import type { AppError, + DesktopInstallation, ForbiddenResponse, IdempotencyConflictResponse, InvalidRequestResponse, @@ -19,6 +20,7 @@ import type { PayloadTooLargeResponse, ProductEvent, RecordAppErrorHeaders, + RecordDesktopInstallationHeaders, RecordNudgeEventHeaders, RecordProductEventHeaders, RecordSignedOutAppErrorHeaders, @@ -36,6 +38,155 @@ type Awaited = O extends AwaitedInput ? T : never; type SecondParameter unknown> = Parameters[1]; +export const getRecordDesktopInstallationUrl = () => { + return `/api/v2/people/me/desktop-installations`; +}; + +/** + * Tell OpenBot that the caller signed in from this OpenBot Desktop installation, by the random id its usage data is sent under at the sign-in, so usage data can join what the installation did before the sign-in with what the caller does after it. OpenBot Cloud only: Desktop's usage-data switch is consent to CopilotKit, not to a company's own server, so Desktop hands the id over, or sends it itself, only when the address it signed in to is OpenBot Cloud. A self-hosted OpenBot never receives it from Desktop. One operation serves every way Desktop signs in to OpenBot Cloud. Where Desktop's window holds the sign-in, Desktop hands the window's page the id with the sign-in's code, and the page sends it with its own session once it has traded the code, with keepalive, so it still leaves when the page goes on. Where Desktop signs in itself, as Move to Cloud's sign-in does, Desktop sends it with that sign-in. Desktop hands the id over only while the person shares usage data, and nothing is sent without that. An installation is the person's, not an organization's, and the page has just signed in and names none, so the address names none either. The id is a random (version 4) UUID, made by the installation, and names nothing about the person or the computer; any other version, which could carry a time or a hardware address, is refused. It is best effort: a client sends it once per sign-in with a new Idempotency-Key, waits on nothing, and treats any answer but 204 alike, never retrying, so a server without the operation, which answers 404, changes nothing. Each accepted report goes out with the rest of OpenBot's product telemetry, beside the caller's pseudonym, never their email or account id. Its event id is made from the deployment, the caller's pseudonym and the installation id in lower case, so it repeats for the same caller and installation: when the window and Move to Cloud both send it for one person, distinct ids still count the link once. It joins the two; it merges no one. Where this OpenBot has product telemetry switched off, a valid report is accepted and dropped, whoever sends it. + * @summary Record the OpenBot Desktop installation the caller signed in from + */ +export const recordDesktopInstallation = async ( + desktopInstallation: DesktopInstallation, + headers: RecordDesktopInstallationHeaders, + options?: Parameters[1], +): Promise => { + const getHeaders = ( + h?: NonNullable, + ): Record => { + if (!h) return {}; + if (h instanceof Headers) return Object.fromEntries(h.entries()); + if (Symbol.iterator in h) { + return Object.fromEntries( + Array.from( + h as Iterable>, + (entry) => Array.from(entry) as [string, string], + ), + ); + } + const headers: Record = {}; + for (const [name, value] of Object.entries< + string | readonly string[] | undefined + >(h)) { + if (value !== undefined) headers[name] = value; + } + return headers; + }; + return apiRequest(getRecordDesktopInstallationUrl(), { + ...options, + method: "POST", + headers: { + "Content-Type": "application/json", + ...headers, + ...getHeaders(options?.headers), + }, + body: JSON.stringify(desktopInstallation), + }); +}; + +export const getRecordDesktopInstallationMutationKey = () => + ["recordDesktopInstallation"] as const; + +export const getRecordDesktopInstallationMutationOptions = < + TError = + | InvalidRequestResponse + | UnauthenticatedResponse + | ForbiddenResponse + | IdempotencyConflictResponse + | PayloadTooLargeResponse + | TooManyRequestsResponse + | ServerErrorResponse + | UnexpectedErrorResponse, + TContext = unknown, +>(options?: { + mutation?: UseMutationOptions< + Awaited>, + TError, + RecordDesktopInstallationMutationVariables, + TContext + >; + request?: SecondParameter; +}): UseMutationOptions< + Awaited>, + TError, + RecordDesktopInstallationMutationVariables, + TContext +> => { + const mutationKey = getRecordDesktopInstallationMutationKey(); + const { mutation: mutationOptions, request: requestOptions } = options + ? options.mutation && + "mutationKey" in options.mutation && + options.mutation.mutationKey + ? options + : { ...options, mutation: { ...options.mutation, mutationKey } } + : { mutation: { mutationKey }, request: undefined }; + + const mutationFn: MutationFunction< + Awaited>, + RecordDesktopInstallationMutationVariables + > = (props) => { + const { data, headers } = props ?? {}; + + return recordDesktopInstallation(data, headers, requestOptions); + }; + + return { mutationFn, ...mutationOptions }; +}; + +export type RecordDesktopInstallationMutationResult = NonNullable< + Awaited> +>; +export type RecordDesktopInstallationMutationBody = DesktopInstallation; +export type RecordDesktopInstallationMutationError = + | InvalidRequestResponse + | UnauthenticatedResponse + | ForbiddenResponse + | IdempotencyConflictResponse + | PayloadTooLargeResponse + | TooManyRequestsResponse + | ServerErrorResponse + | UnexpectedErrorResponse; +export type RecordDesktopInstallationMutationVariables = { + data: DesktopInstallation; + headers: RecordDesktopInstallationHeaders; +}; + +/** + * @summary Record the OpenBot Desktop installation the caller signed in from + */ +export const useRecordDesktopInstallation = < + TError = + | InvalidRequestResponse + | UnauthenticatedResponse + | ForbiddenResponse + | IdempotencyConflictResponse + | PayloadTooLargeResponse + | TooManyRequestsResponse + | ServerErrorResponse + | UnexpectedErrorResponse, + TContext = unknown, +>( + options?: { + mutation?: UseMutationOptions< + Awaited>, + TError, + RecordDesktopInstallationMutationVariables, + TContext + >; + request?: SecondParameter; + }, + queryClient?: QueryClient, +): UseMutationResult< + Awaited>, + TError, + RecordDesktopInstallationMutationVariables, + TContext +> => { + return useMutation( + getRecordDesktopInstallationMutationOptions(options), + queryClient, + ); +}; export const getRecordProductEventUrl = (organizationId: string) => { return `/api/v2/organizations/${encodeURIComponent(String(organizationId))}/product-events`; }; diff --git a/app/src/lib/api/generated/product-events/product-events.zod.ts b/app/src/lib/api/generated/product-events/product-events.zod.ts index 96e7e21885..620e2a8d87 100644 --- a/app/src/lib/api/generated/product-events/product-events.zod.ts +++ b/app/src/lib/api/generated/product-events/product-events.zod.ts @@ -3,6 +3,41 @@ */ import * as zod from "zod"; +/** + * Tell OpenBot that the caller signed in from this OpenBot Desktop installation, by the random id its usage data is sent under at the sign-in, so usage data can join what the installation did before the sign-in with what the caller does after it. OpenBot Cloud only: Desktop's usage-data switch is consent to CopilotKit, not to a company's own server, so Desktop hands the id over, or sends it itself, only when the address it signed in to is OpenBot Cloud. A self-hosted OpenBot never receives it from Desktop. One operation serves every way Desktop signs in to OpenBot Cloud. Where Desktop's window holds the sign-in, Desktop hands the window's page the id with the sign-in's code, and the page sends it with its own session once it has traded the code, with keepalive, so it still leaves when the page goes on. Where Desktop signs in itself, as Move to Cloud's sign-in does, Desktop sends it with that sign-in. Desktop hands the id over only while the person shares usage data, and nothing is sent without that. An installation is the person's, not an organization's, and the page has just signed in and names none, so the address names none either. The id is a random (version 4) UUID, made by the installation, and names nothing about the person or the computer; any other version, which could carry a time or a hardware address, is refused. It is best effort: a client sends it once per sign-in with a new Idempotency-Key, waits on nothing, and treats any answer but 204 alike, never retrying, so a server without the operation, which answers 404, changes nothing. Each accepted report goes out with the rest of OpenBot's product telemetry, beside the caller's pseudonym, never their email or account id. Its event id is made from the deployment, the caller's pseudonym and the installation id in lower case, so it repeats for the same caller and installation: when the window and Move to Cloud both send it for one person, distinct ids still count the link once. It joins the two; it merges no one. Where this OpenBot has product telemetry switched off, a valid report is accepted and dropped, whoever sends it. + * @summary Record the OpenBot Desktop installation the caller signed in from + */ +export const recordDesktopInstallationHeaderIdempotencyKeyMax = 128; + +export const RecordDesktopInstallationHeader = zod.object({ + "Idempotency-Key": zod + .string() + .min(1) + .max(recordDesktopInstallationHeaderIdempotencyKeyMax) + .describe( + "Generated by the caller for each write it means to make once. Reuse the same key and the same request for 24 hours after an uncertain response; the same key with a different request is a conflict.", + ), +}); + +export const recordDesktopInstallationBodyInstallationIdRegExp = new RegExp( + "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$", +); + +export const RecordDesktopInstallationBody = zod + .object({ + installationId: zod + .uuid() + .regex(recordDesktopInstallationBodyInstallationIdRegExp) + .describe( + "The random (version 4) UUID OpenBot Desktop sends its usage data under at the sign-in; Desktop's own events carry it as their `deployment_id`. Desktop makes a new one when usage data is turned off and on again, or when the account it is tied to changes or signs out. Any other UUID version is refused.", + ), + }) + .describe( + "The OpenBot Desktop installation the caller signed in from, by the random (version 4) UUID it keeps for its usage data. Names nothing about the computer, or about the person, who is the caller.", + ); + +export const RecordDesktopInstallationResponse = zod.void(); + /** * Tell OpenBot that the caller saw a Bot's answer on screen, or copied it, so OpenBot can count which answers people use. It is best effort: a client sends one for each answer it shows or copies, waits on nothing, and sends it with keepalive so it still leaves when the page closes. The event counts for the caller, and names only the answer. Where this OpenBot has product telemetry switched off, it is accepted and dropped. * @summary Record that the caller saw or copied a Bot's answer