diff --git a/doc/connections/GMAIL.md b/doc/connections/GMAIL.md index 58050d11640..c9700ab52dc 100644 --- a/doc/connections/GMAIL.md +++ b/doc/connections/GMAIL.md @@ -257,6 +257,11 @@ the local result. See "Removing a managed Google connection" in ### Configure each originating Paperclip instance +These steps apply to Paperclip Cloud workspaces. Paperclip's own Google +sign-in is not available on a self-hosted Paperclip; a self-hosted instance +connects Gmail with its own Google OAuth client. See +[Self-hosted instances: use your own Google client](GOOGLE-WORKSPACE.md#self-hosted-instances-use-your-own-google-client). + Generate the two long-lived instance keys once. PEM-encoded PKCS#8 keys work directly with Paperclip: @@ -286,17 +291,22 @@ HTTP is accepted only for a loopback Paperclip Cloud URL; staging and production must use HTTPS. Cloud-hosted stacks receive these values automatically through the existing -per-stack secret-reference delivery path. Self-hosted instances normally use -the Apps enrollment action instead of running the OpenSSL commands manually; -it generates the keys and writes them to the ignored instance secret directory -with owner-only permissions. +per-stack secret-reference delivery path. A self-hosted instance does not use +these keys for Google. Its Apps enrollment action still serves other +Paperclip-managed providers, such as GitHub and Asana: it generates the keys +and writes them to the ignored instance secret directory with owner-only +permissions. `PAPERCLIP_ID_CONNECTOR_*` values are not aliases for this protocol. Paperclip ID used different endpoints, signing metadata, envelope purposes, and Google client credentials. An instance with only those legacy values fails with -`CONNECTOR_MIGRATION_REQUIRED`. Enroll it with Paperclip Cloud and reconnect -each legacy Google grant. Cloud-hosted fleets must deliver the new enrollment -keys before they deploy a binary that enables the Cloud connector. +`CONNECTOR_MIGRATION_REQUIRED`. On Paperclip Cloud, deliver the new enrollment +keys and reconnect each legacy Google grant. On a self-hosted instance, reconnect +Gmail with your own Google OAuth client. A Google grant that a self-hosted +instance already holds through Paperclip keeps refreshing until the Paperclip +Cloud sunset date; after that date, Paperclip asks the user to reconnect with +their own Google OAuth client. Cloud-hosted fleets must deliver the new +enrollment keys before they deploy a binary that enables the Cloud connector. ## Paperclip access defaults diff --git a/doc/connections/GOOGLE-WORKSPACE.md b/doc/connections/GOOGLE-WORKSPACE.md index 0825c7bdecc..d515c78b9ab 100644 --- a/doc/connections/GOOGLE-WORKSPACE.md +++ b/doc/connections/GOOGLE-WORKSPACE.md @@ -100,6 +100,44 @@ The catalog reuses the existing reviewed Google mark (`google-people.svg`), registered under its own `google-workspace` brand identity. No new artwork is downloaded or substituted for a product logo. +## Who can use Paperclip's Google sign-in + +Paperclip's own Google sign-in ("Connect with Paperclip") is available only on +Paperclip Cloud workspaces. Google's restricted-scope verification and security +assessment cover Paperclip's infrastructure, so Paperclip does not give +restricted-scope Google tokens to servers it does not run. + +A self-hosted Paperclip connects Google with its own Google OAuth client (the +"Use your own Google OAuth app" method). See +[Self-hosted instances: use your own Google client](#self-hosted-instances-use-your-own-google-client). + +The app decides Cloud or self-hosted with `isCloudManagedInstance()` +(`server/src/services/cloud-instance.ts`), the same check every other Cloud +behavior uses, through `paperclipGoogleSignInAvailable()` +(`server/src/services/google-sign-in-availability.ts`). The board UI uses the +health response's `cloud` block (`useCloudInstance`), which the server fills +from the same check. On a self-hosted instance: + +- The gallery and setup validation leave out every Paperclip-managed Google + method (`appDefinitionForDeployment` in + `packages/shared/src/google-sign-in-deployment.ts`). Setup shows only the + customer-owned Google client, with a short explanation and a link to + Google's client setup guide. It never offers instance enrollment for Google. +- Starting a Paperclip-managed Google authorization fails with + `google_sign_in_cloud_only` before any call to Paperclip Cloud. +- A broker refusal with `PROVIDER_CLOUD_ONLY` (for example a broker that + sees the instance as self-hosted) maps to the same message on start. + +Google connections that a self-hosted instance already made through +Paperclip keep refreshing until a sunset date the owner sets on the broker. +After it, a refresh fails with `oauth_reauthorization_required` and reason +`google_sign_in_cloud_only`, the grant is marked for reconnection, and the +message tells the user to reconnect with their own Google OAuth client. +Removing the connection still works. Cloud workspaces are not affected. + +The app works with brokers from before and after this change: an older broker +never refuses, and the app's own check already hides and refuses the method. + ## Combined profile deployment and verification Deploy the companion Cloud broker registry before enabling `workspace.all` in @@ -395,7 +433,9 @@ whose provider, profile, or exact scope set does not match its closed registry. ## Instance configuration -All Paperclip-managed Google methods use the existing enrolled-instance keys: +All Paperclip-managed Google methods use the existing enrolled-instance keys. +Only Paperclip Cloud workspaces use them for Google; see +[Who can use Paperclip's Google sign-in](#who-can-use-paperclips-google-sign-in). ```dotenv PAPERCLIP_CLOUD_CONNECTOR_BASE_URL=https://my.paperclip.app @@ -411,14 +451,12 @@ OAuth client ID and secret and stores them through the normal instance-vault path. Cloud-hosted stacks receive these values through the existing per-stack secret -delivery path. A self-hosted instance creates its keys during enrollment and -stores them with owner-only permissions in the instance's ignored secret -directory. The setup page supplies its authenticated same-origin HTTPS address -to enrollment, so a normal Tailscale-hosted self-hoster does not need to edit -`config.json` or set `PAPERCLIP_PUBLIC_URL`; the enrolled origin becomes the -durable callback binding. The former `PAPERCLIP_ID_CONNECTOR_*` values use an incompatible -Paperclip ID protocol and are not read aliases. Enroll with Paperclip Cloud and -reconnect legacy grants before their old access tokens expire. +delivery path. A self-hosted instance does not enroll with Paperclip Cloud +for Google: it uses its own Google OAuth client (see +[Self-hosted instances: use your own Google client](#self-hosted-instances-use-your-own-google-client)). +Enrollment of a self-hosted instance still serves other Paperclip-managed +providers, such as GitHub and Asana. The former `PAPERCLIP_ID_CONNECTOR_*` +values use an incompatible Paperclip ID protocol and are not read aliases. The gallery requests the broker capability document with a short cache. A Paperclip-managed method is omitted unless its exact profile is enabled at the @@ -430,6 +468,24 @@ See [Gmail connection](./GMAIL.md) for the detailed enrollment, signing, encryption, environment-isolation, and security review runbook inherited by all profiles. +## Self-hosted instances: use your own Google client + +1. In the Google Cloud console, create or choose a project and enable the APIs + for the services you want (Gmail, Drive, Docs, Sheets, Slides, Calendar). +2. Configure the OAuth consent screen. Add the scopes for the services you + will select. Paperclip asks only for the services you choose. +3. Create an OAuth client of type "Web application". Add Paperclip's callback + URL as an authorized redirect URI. The setup screen shows the exact URL to + copy. +4. In Paperclip, open **Apps**, choose **Google Workspace**, and enter the + client ID and client secret. Paperclip stores them in the instance vault. +5. Choose the services and sign in with Google. + +Google's guide: +[Configure Google Workspace MCP servers](https://developers.google.com/workspace/guides/configure-mcp-servers). +An unverified Google app shows a warning screen and has a user cap; only you +can decide whether to submit your own app for Google's verification. + ## Safety boundary Every Google profile has an explicit MCP tool allowlist. Unknown Developer diff --git a/doc/memory/google-connector-memory.md b/doc/memory/google-connector-memory.md index 68050f42ce8..51c28b581d8 100644 --- a/doc/memory/google-connector-memory.md +++ b/doc/memory/google-connector-memory.md @@ -44,6 +44,7 @@ Last updated: November 23, 2026. | Nov 23 | **Write actions default to "Allowed"** | No approval step by default, including actions labelled destructive. Operators can still set Ask first per action. | | Nov 23 | **Images by public web address are allowed in Docs and Slides** | `insertInlineImage`, `replaceImage`, `createImage` and `replaceAllShapesWithImage` may use any public link. Links to Drive or Docs files stay refused (Nov 17 rule). Accepted risk: Google, not Paperclip, fetches the address, and Paperclip's own requests still go only to the allowed Google hosts. What remains is that an agent could put data in the address it chooses. Owner decision; do not restrict it. | | Nov 23 | **Unconfirmed Google revocation is retried by the app, not Cloud** | When access must end and Google cannot be reached or confirm, the app keeps the token in `google_pending_revocations` and retries (1 minute up to 6 hours backoff, 30-day hard stop). Cloud still never stores provider tokens. Company deletion and a Cloud-removed instance queue the same way. The broker lets a removed instance sign a Google revoke (Cloud broker change, November 23). See [connector doc](../connections/GOOGLE-WORKSPACE.md), "Pending revocation". | +| Nov 23 | **Paperclip's Google sign-in is for Paperclip Cloud only** | Self-hosted instances bring their own Google OAuth client. Google's restricted-scope verification and security assessment cover Paperclip's infrastructure, so the broker does not give restricted-scope Google tokens to servers Paperclip does not run. The app hides the method on self-hosted instances and refuses to start it; the broker refuses it too (`PROVIDER_CLOUD_ONLY`). Google connections a self-hosted instance already has keep refreshing until a sunset date the owner will set on the broker; after it, the app asks the user to reconnect with their own Google client. | ## What has shipped diff --git a/packages/shared/src/google-sign-in-deployment.test.ts b/packages/shared/src/google-sign-in-deployment.test.ts new file mode 100644 index 00000000000..7f0ee05e9ad --- /dev/null +++ b/packages/shared/src/google-sign-in-deployment.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from "vitest"; +import { CONNECTABLE_APP_DEFINITIONS, getConnectableAppDefinition } from "./app-definitions.js"; +import { appDefinitionForDeployment, isCloudOnlyConnectionMethod } from "./google-sign-in-deployment.js"; + +const googleApps = CONNECTABLE_APP_DEFINITIONS.filter((app) => + app.methods.some((method) => method.connectorProfile && isCloudOnlyConnectionMethod(method))); + +describe("Paperclip's Google sign-in by deployment", () => { + it("finds every Google app that offers Paperclip's Google sign-in", () => { + expect(googleApps.map((app) => app.slug).sort()).toEqual([ + "gmail", "google-calendar", "google-chat", "google-docs", "google-drive", "google-people", + "google-sheets", "google-slides", "google-workspace", "google-workspace-search", + ]); + }); + + it("offers only the customer-owned Google client on a self-hosted instance", () => { + for (const app of googleApps) { + const selfHosted = appDefinitionForDeployment(app, { cloudHosted: false }); + expect(selfHosted.methods.some(isCloudOnlyConnectionMethod), app.slug).toBe(false); + expect(selfHosted.methods.length, app.slug).toBeGreaterThan(0); + expect(selfHosted.methods.every((method) => !method.oauthStrategy), app.slug).toBe(true); + } + expect(appDefinitionForDeployment(getConnectableAppDefinition("google-workspace")!, { cloudHosted: false }).methods + .map((method) => method.key)).toEqual(["customer-workspace-oauth"]); + }); + + it("leaves every app unchanged on Paperclip Cloud", () => { + for (const app of CONNECTABLE_APP_DEFINITIONS) { + expect(appDefinitionForDeployment(app, { cloudHosted: true })).toBe(app); + } + }); + + it("leaves other providers' Paperclip sign-in on a self-hosted instance", () => { + for (const app of CONNECTABLE_APP_DEFINITIONS.filter((candidate) => !googleApps.includes(candidate))) { + expect(appDefinitionForDeployment(app, { cloudHosted: false }), app.slug).toBe(app); + } + }); +}); diff --git a/packages/shared/src/google-sign-in-deployment.ts b/packages/shared/src/google-sign-in-deployment.ts new file mode 100644 index 00000000000..2e4e4cc3c24 --- /dev/null +++ b/packages/shared/src/google-sign-in-deployment.ts @@ -0,0 +1,15 @@ +import { isGoogleWorkspaceConnectorProfileId } from "./google-workspace-connectors.js"; +import type { AppDefinition, ConnectionMethodDef } from "./types/app-definition.js"; + +export function isCloudOnlyConnectionMethod(method: ConnectionMethodDef): boolean { + return (method.oauthStrategy === "paperclip_cloud_connector" || method.oauthStrategy === "paperclip_id_connector") + && isGoogleWorkspaceConnectorProfileId(method.connectorProfile ?? ""); +} + +export function appDefinitionForDeployment(app: AppDefinition, deployment: { cloudHosted: boolean }): AppDefinition { + if (deployment.cloudHosted || !app.methods.some(isCloudOnlyConnectionMethod)) return app; + return { ...app, methods: app.methods.filter((method) => !isCloudOnlyConnectionMethod(method)) }; +} + +export const GOOGLE_SIGN_IN_CLOUD_ONLY_MESSAGE = + "Connecting Google through Paperclip works only on Paperclip Cloud. On your own Paperclip server, connect Google with your own Google OAuth client."; diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 583f640ffdc..3fa6eb48ed1 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -364,6 +364,7 @@ export { } from "./connection-setup-state.js"; export { APP_DEFINITIONS } from "./app-definitions.generated.js"; export * from "./google-workspace-connectors.js"; +export * from "./google-sign-in-deployment.js"; export * from "./github-connectors.js"; export * from "./asana-connectors.js"; export { diff --git a/server/src/__tests__/google-managed-connection-removal.test.ts b/server/src/__tests__/google-managed-connection-removal.test.ts index f0f3636d0c0..dff12601b65 100644 --- a/server/src/__tests__/google-managed-connection-removal.test.ts +++ b/server/src/__tests__/google-managed-connection-removal.test.ts @@ -28,6 +28,8 @@ import { REFRESH_TOKEN, } from "./helpers/managed-google-connection.js"; +vi.mock("../services/google-sign-in-availability.js", () => ({ paperclipGoogleSignInAvailable: () => true })); + const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; diff --git a/server/src/__tests__/google-pending-revocation.test.ts b/server/src/__tests__/google-pending-revocation.test.ts index 0300ca6de0f..fd20890125f 100644 --- a/server/src/__tests__/google-pending-revocation.test.ts +++ b/server/src/__tests__/google-pending-revocation.test.ts @@ -36,6 +36,8 @@ import { secretService } from "../services/secrets.js"; import { deleteCompany } from "../services/company-deletion.js"; import { listConnectionLifecycleEvents } from "../services/tool-connection-activity.js"; +vi.mock("../services/google-sign-in-availability.js", () => ({ paperclipGoogleSignInAvailable: () => true })); + vi.mock("../services/paperclip-cloud-connector-status.js", () => ({ reconcilePaperclipCloudConnectorEnrollmentStatus: async (_env: unknown, _request: unknown, onRemoved?: () => Promise) => { await onRemoved?.(); diff --git a/server/src/__tests__/google-workspace-rest-transport.test.ts b/server/src/__tests__/google-workspace-rest-transport.test.ts index 590ddfbc08b..6924f387d8c 100644 --- a/server/src/__tests__/google-workspace-rest-transport.test.ts +++ b/server/src/__tests__/google-workspace-rest-transport.test.ts @@ -18,6 +18,8 @@ import { initializeRunIdentity } from "../services/run-identity.js"; import type { PaperclipCloudConnector } from "../services/paperclip-cloud-connector.js"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +vi.mock("../services/google-sign-in-availability.js", () => ({ paperclipGoogleSignInAvailable: () => true })); + const gmailCatalog = (write: boolean) => ["docs__read_doc", ...googleWorkspaceServiceToolNames("gmail") .filter((name) => write || name !== "create_draft").map((name) => `gmail__${name}`)].sort(); diff --git a/server/src/__tests__/tool-access-service.test.ts b/server/src/__tests__/tool-access-service.test.ts index 15dd9b5afaa..0411faeddd8 100644 --- a/server/src/__tests__/tool-access-service.test.ts +++ b/server/src/__tests__/tool-access-service.test.ts @@ -1,4 +1,6 @@ import { DELIVERY_QUEUES, subscribeDeliveryWork } from "../services/delivery-work-notifications.js"; +const googleSignIn = vi.hoisted(() => ({ cloudHosted: true })); +vi.mock("../services/google-sign-in-availability.js", () => ({ paperclipGoogleSignInAvailable: () => googleSignIn.cloudHosted })); import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; import * as fs from "node:fs/promises"; import { createHash, generateKeyPairSync, randomUUID } from "node:crypto"; @@ -69,6 +71,7 @@ import { googleWorkspaceSelectedScopes, googleWorkspaceGrantedScopes, googleWorkspaceSelectionForScopes, + GOOGLE_SIGN_IN_CLOUD_ONLY_MESSAGE, GOOGLE_WORKSPACE_DEFAULT_SELECTION, getAvailableConnectionMethod, getConnectableAppDefinition, @@ -8185,6 +8188,76 @@ describeEmbeddedPostgres("tool access service", () => { expect(connector.startAuthorization).not.toHaveBeenCalled(); }); + it("keeps a saved Paperclip Google connection working on a self-hosted instance and guides a reconnect with its own client", async () => { + const company = await createCompany(db); + const userId = `google-self-hosted-${randomUUID()}`; + await grantBoardUser(db, company.id, userId, [], "owner"); + const connector = fakeGoogleWorkspaceConnector(company.id, userId, "gmail.draft"); + const service = createTestToolAccessService(db, { paperclipCloudConnector: connector }); + const actor = { actorType: "user" as const, actorId: userId }; + const redirectUri = "https://paperclip.example/api/tools/oauth/cloud-connector/callback"; + mockToolsList([]); + const connected = await service.connectGalleryApp(company.id, { + galleryKey: "gmail", connectionMethodKey: "paperclip-draft", grantKind: "user", name: "Saved Gmail", + }, actor); + const started = await service.startOAuth(company.id, connected.connectionId, { redirectUri, actor }); + await service.completePaperclipCloudConnectorCallback({ + state: new URL(started.authorizationUrl).searchParams.get("state")!, claimId: "saved-claim", actor, + }); + const [grant] = await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, connected.connectionId)); + vi.mocked(connector.startAuthorization).mockClear(); + googleSignIn.cloudHosted = false; + try { + await service.refreshOAuthGrantCredentials({ companyId: company.id, connectionId: connected.connectionId, grantId: grant.id, forceRefresh: true, actor }); + expect(connector.refresh).toHaveBeenCalledWith(expect.objectContaining({ profile: "gmail.draft" })); + + await expect(service.startOAuth(company.id, connected.connectionId, { redirectUri, actor })).rejects.toMatchObject({ + status: 422, message: GOOGLE_SIGN_IN_CLOUD_ONLY_MESSAGE, details: { code: "google_sign_in_cloud_only" }, + }); + await expect(service.connectGalleryApp(company.id, { + galleryKey: "gmail", connectionMethodKey: "paperclip-draft", grantKind: "user", name: "New Gmail", + }, actor)).rejects.toMatchObject({ status: 422 }); + expect(connector.startAuthorization).not.toHaveBeenCalled(); + + for (const status of [409, 403]) { + await db.update(connectionGrants).set({ status: "active" }).where(eq(connectionGrants.id, grant.id)); + vi.mocked(connector.refresh).mockRejectedValueOnce(new PaperclipCloudConnectorError( + `Paperclip Cloud connector rejected the request (operation=refresh, status=${status}, reason=PROVIDER_CLOUD_ONLY)`, + status === 409 ? "REAUTHORIZATION_REQUIRED" : "CONNECTOR_REQUEST_FAILED", status, undefined, "PROVIDER_CLOUD_ONLY", + )); + await expect(service.refreshOAuthGrantCredentials({ companyId: company.id, connectionId: connected.connectionId, grantId: grant.id, forceRefresh: true, actor })) + .rejects.toMatchObject({ + status: 422, + message: `Reconnect required. ${GOOGLE_SIGN_IN_CLOUD_ONLY_MESSAGE}`, + details: { code: "oauth_reauthorization_required", reason: "google_sign_in_cloud_only" }, + }); + expect((await db.select().from(connectionGrants).where(eq(connectionGrants.id, grant.id)))[0].status).toBe("needs_reauthorization"); + } + } finally { + googleSignIn.cloudHosted = true; + } + }); + + it("turns the broker's cloud-only refusal into the same guidance on a Cloud instance", async () => { + const company = await createCompany(db); + const userId = `google-cloud-refused-${randomUUID()}`; + await grantBoardUser(db, company.id, userId, [], "owner"); + const connector = fakeGoogleWorkspaceConnector(company.id, userId, "gmail.draft"); + const service = createTestToolAccessService(db, { paperclipCloudConnector: connector }); + const actor = { actorType: "user" as const, actorId: userId }; + mockToolsList([]); + const connected = await service.connectGalleryApp(company.id, { + galleryKey: "gmail", connectionMethodKey: "paperclip-draft", grantKind: "user", name: "Refused Gmail", + }, actor); + vi.mocked(connector.startAuthorization).mockRejectedValueOnce(new PaperclipCloudConnectorError( + "Paperclip Cloud connector rejected the request (operation=session, status=403, reason=PROVIDER_CLOUD_ONLY)", + "CONNECTOR_REQUEST_FAILED", 403, undefined, "PROVIDER_CLOUD_ONLY", + )); + await expect(service.startOAuth(company.id, connected.connectionId, { + redirectUri: "https://paperclip.example/api/tools/oauth/cloud-connector/callback", actor, + })).rejects.toMatchObject({ status: 422, message: GOOGLE_SIGN_IN_CLOUD_ONLY_MESSAGE, details: { code: "google_sign_in_cloud_only" } }); + }); + it("completes brokered Gmail OAuth with a single database connection", async () => { const company = await createCompany(db); const userId = `gmail-member-${randomUUID()}`; @@ -8848,6 +8921,35 @@ describeEmbeddedPostgres("tool access service", () => { } }); + it("never turns a cloud-only refusal for another provider into Google guidance", async () => { + const company = await createCompany(db); + const userId = `github-cloud-only-${randomUUID()}`; + await grantBoardUser(db, company.id, userId, [], "owner"); + const connector = fakeGitHubConnector(company.id, userId); + connector.startAuthorization = vi.fn(async () => { + throw new PaperclipCloudConnectorError( + "Paperclip Cloud connector rejected the request (operation=session, status=403, reason=PROVIDER_CLOUD_ONLY)", + "CONNECTOR_REQUEST_FAILED", 403, undefined, "PROVIDER_CLOUD_ONLY", + ); + }); + const githubDefinition = getConnectableAppDefinition("github")!; + const previousOwnershipAvailability = githubDefinition.ownershipAvailability; + githubDefinition.ownershipAvailability = { ...previousOwnershipAvailability, platform_shared: true }; + googleSignIn.cloudHosted = false; + try { + const app = createRouteApp(db, boardSessionActor(company.id, "owner", userId), undefined, { paperclipCloudConnector: connector }); + const connected = await request(app) + .post(`/api/companies/${company.id}/tools/apps/connect`) + .send({ galleryKey: "github", connectionMethodKey: "managed", grantKind: "user", name: "GitHub" }); + expect(connector.startAuthorization).toHaveBeenCalled(); + expect(connected.body.code).not.toBe("google_sign_in_cloud_only"); + expect(JSON.stringify(connected.body)).not.toContain(GOOGLE_SIGN_IN_CLOUD_ONLY_MESSAGE); + } finally { + googleSignIn.cloudHosted = true; + githubDefinition.ownershipAvailability = previousOwnershipAvailability; + } + }); + it.each(["user", "organization"] as const)("builds one Workspace catalog from actual partial consent for a %s grant", async (grantKind) => { useGoogleMcpTransport(); const company = await createCompany(db); diff --git a/server/src/routes/tool-access.ts b/server/src/routes/tool-access.ts index 95334752460..6179917689d 100644 --- a/server/src/routes/tool-access.ts +++ b/server/src/routes/tool-access.ts @@ -88,6 +88,7 @@ import { type PaperclipCloudConnector, paperclipCloudConnectorCapabilitiesFromEnv, } from "../services/paperclip-cloud-connector.js"; +import { paperclipGoogleSignInAvailable } from "../services/google-sign-in-availability.js"; import { runtimeCanonicalOrigin } from "../services/cloud-runtime-identity.js"; import { instanceSettingsService } from "../services/instance-settings.js"; import { @@ -951,6 +952,7 @@ function connectorEnrollmentPrincipal(req: Request): string { if (details?.code !== "oauth_redirect_origin_unsupported") throw error; } const pluginApps = (await loadPluginAppCatalog(db)).definitions; + const cloudHosted = paperclipGoogleSignInAvailable(); res.json({ ...(oauthCallbackUrl ? { oauthCallbackUrl } : {}), // Full definitions of plugin-provided connectors. Like the built-in @@ -973,9 +975,9 @@ function connectorEnrollmentPrincipal(req: Request): string { }, apps: [...APP_STORE_DEFINITIONS.filter((app) => (settings.enableMemoryConnectors || !isMemoryConnectorId(app.slug)) && isConnectorFeatureEnabled(app, settings)).map((app) => - appWithPaperclipCloudConnectorAvailability(app, advertisedProfiles) + appWithPaperclipCloudConnectorAvailability(app, advertisedProfiles, cloudHosted) ), ...pluginApps.map((app) => - appWithPaperclipCloudConnectorAvailability(app, advertisedProfiles) + appWithPaperclipCloudConnectorAvailability(app, advertisedProfiles, cloudHosted) ), ...await aiConnectionRouterService(db).catalog()], }); }); diff --git a/server/src/services/google-sign-in-availability.ts b/server/src/services/google-sign-in-availability.ts new file mode 100644 index 00000000000..c01e91239e0 --- /dev/null +++ b/server/src/services/google-sign-in-availability.ts @@ -0,0 +1,5 @@ +import { isCloudManagedInstance } from "./cloud-instance.js"; + +export function paperclipGoogleSignInAvailable(): boolean { + return isCloudManagedInstance(); +} diff --git a/server/src/services/paperclip-cloud-connector.test.ts b/server/src/services/paperclip-cloud-connector.test.ts index c757b3dda2c..43912d96379 100644 --- a/server/src/services/paperclip-cloud-connector.test.ts +++ b/server/src/services/paperclip-cloud-connector.test.ts @@ -16,6 +16,7 @@ import { } from "@paperclipai/shared"; import { describe, expect, it, vi } from "vitest"; import { readFileSync } from "node:fs"; +import { paperclipGoogleSignInAvailable } from "./google-sign-in-availability.js"; import { appWithPaperclipCloudConnectorAvailability, @@ -316,20 +317,57 @@ describe("Paperclip Cloud connector", () => { expect(managedGoogle.filter(({ method }) => (method.defaults?.scopesHint ?? []).some((value) => !submitted.has(value))) .map(({ id }) => id)).toEqual(savedConnectionsOnly); for (const app of APP_DEFINITIONS) { - const offered = appWithPaperclipCloudConnectorAvailability(app, [...GOOGLE_WORKSPACE_CONNECTOR_PROFILE_IDS]); + const offered = appWithPaperclipCloudConnectorAvailability(app, [...GOOGLE_WORKSPACE_CONNECTOR_PROFILE_IDS], true); for (const method of offered.methods.filter((candidate) => candidate.oauthStrategy === "paperclip_cloud_connector")) { expect(savedConnectionsOnly).not.toContain(`${app.slug}/${method.key}`); for (const value of method.defaults?.scopesHint ?? []) expect(submitted, `${app.slug}/${method.key}`).toContain(value); } } - const gmail = appWithPaperclipCloudConnectorAvailability(APP_DEFINITIONS.find((app) => app.slug === "gmail")!, [...GOOGLE_WORKSPACE_CONNECTOR_PROFILE_IDS]); + const gmail = appWithPaperclipCloudConnectorAvailability(APP_DEFINITIONS.find((app) => app.slug === "gmail")!, [...GOOGLE_WORKSPACE_CONNECTOR_PROFILE_IDS], true); expect(gmail.methods.map((method) => method.key)).toEqual([ "paperclip-read", "customer-read-oauth", "paperclip-draft", "customer-draft-oauth", "customer-archive-oauth", ]); - const chat = appWithPaperclipCloudConnectorAvailability(APP_DEFINITIONS.find((app) => app.slug === "google-chat")!, [...GOOGLE_WORKSPACE_CONNECTOR_PROFILE_IDS]); + const chat = appWithPaperclipCloudConnectorAvailability(APP_DEFINITIONS.find((app) => app.slug === "google-chat")!, [...GOOGLE_WORKSPACE_CONNECTOR_PROFILE_IDS], true); expect(chat.ownershipAvailability?.platform_shared).toBe(false); }); + it("offers Paperclip's Google sign-in only on Paperclip Cloud and keeps other managed methods", () => { + const workspace = APP_DEFINITIONS.find((app) => app.slug === "google-workspace")!; + const asana = APP_DEFINITIONS.find((app) => app.methods.some((method) => method.connectorProfile === "asana.mcp"))!; + const advertised = [...GOOGLE_WORKSPACE_CONNECTOR_PROFILE_IDS, "asana.mcp"]; + const cloud = appWithPaperclipCloudConnectorAvailability(workspace, advertised, true); + expect(cloud.methods.map((method) => method.key)).toEqual(["paperclip-workspace", "customer-workspace-oauth"]); + expect(cloud.ownershipAvailability?.platform_shared).toBe(true); + const selfHosted = appWithPaperclipCloudConnectorAvailability(workspace, advertised, false); + expect(selfHosted.methods.map((method) => method.key)).toEqual(["customer-workspace-oauth"]); + expect(selfHosted.ownershipAvailability?.platform_shared).toBe(false); + expect(appWithPaperclipCloudConnectorAvailability(asana, advertised, false).methods) + .toEqual(appWithPaperclipCloudConnectorAvailability(asana, advertised, true).methods); + }); + + it("decides Cloud or self-hosted from the instance's Cloud markers", () => { + vi.stubEnv("PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN", ""); + vi.stubEnv("PAPERCLIP_MANAGED_CONFIG", undefined); + try { + expect(paperclipGoogleSignInAvailable()).toBe(false); + vi.stubEnv("PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN", "tenant-token-fixture"); + expect(paperclipGoogleSignInAvailable()).toBe(true); + } finally { + vi.unstubAllEnvs(); + } + }); + + it("keeps the broker's cloud-only refusal as a known reason", async () => { + const connector = createPaperclipCloudConnector({ + config: config().config, + request: vi.fn(async () => Response.json({ error: "PROVIDER_CLOUD_ONLY" }, { status: 409 })) as typeof fetch, + }); + await expect(connector.refresh({ subject, companyId, profile: "workspace.all", refreshToken: "refresh-fixture" })) + .rejects.toMatchObject({ code: "REAUTHORIZATION_REQUIRED", brokerReason: "PROVIDER_CLOUD_ONLY" }); + expect(await rejection(Response.json({ error: "PROVIDER_CLOUD_ONLY" }, { status: 403 }))) + .toMatchObject({ code: "CONNECTOR_REQUEST_FAILED", status: 403, brokerReason: "PROVIDER_CLOUD_ONLY" }); + }); + it("signs selected Workspace scopes without substituting the full profile", async () => { const keys = config(); const scopes = ["https://www.googleapis.com/auth/gmail.readonly"]; diff --git a/server/src/services/paperclip-cloud-connector.ts b/server/src/services/paperclip-cloud-connector.ts index baf6181cc8b..923ed2301d8 100644 --- a/server/src/services/paperclip-cloud-connector.ts +++ b/server/src/services/paperclip-cloud-connector.ts @@ -1,6 +1,6 @@ import { assertMcpClientMirrorEnvelope } from "./public-mcp/client-mirror-wire.js"; import { providerRetryAt } from "./provider-retry-after.js"; -import { SLACK_MANAGER_SCOPES, ASANA_CONNECTOR_SCOPES, isAsanaConnectorProfileId, type AsanaConnectorProfileId } from "@paperclipai/shared"; +import { SLACK_MANAGER_SCOPES, ASANA_CONNECTOR_SCOPES, appDefinitionForDeployment, isAsanaConnectorProfileId, type AsanaConnectorProfileId } from "@paperclipai/shared"; import { createDecipheriv, createHash, @@ -160,7 +160,7 @@ const BROKER_REJECTION_REASONS = new Set([ "REQUEST_EXPIRED", "REQUEST_REPLAYED", "SIGNATURE_REJECTED", "AUDIENCE_MISMATCH", "OPERATION_MISMATCH", "PAYLOAD_MISMATCH", "MALFORMED_REQUEST", "UNSUPPORTED_ALGORITHM", "RATE_LIMITED", - "PROVIDER_OPERATION_FAILED", "PROVIDER_REAUTHORIZATION_REQUIRED", "REVOCATION_NOT_AVAILABLE", + "PROVIDER_OPERATION_FAILED", "PROVIDER_REAUTHORIZATION_REQUIRED", "REVOCATION_NOT_AVAILABLE", "PROVIDER_CLOUD_ONLY", "SLACK_ENROLLMENT_GENERATION_CHANGED", "SLACK_ENROLLMENT_IDENTITY_CHANGED", "SLACK_ENROLLMENT_CHANGED", "SLACK_ENROLLMENT_UNSETTLED", "SLACK_ENROLLMENT_DISABLED", "SLACK_COMPANY_MISMATCH", "SLACK_EVENTS_UNAVAILABLE", @@ -836,9 +836,10 @@ export function isPaperclipCloudConnectorStrategy(value: unknown): boolean { export function appWithPaperclipCloudConnectorAvailability( app: AppDefinition, profiles: readonly string[], + cloudHosted: boolean, ): AppDefinition { const enabledProfiles = new Set(profiles); - const methods = app.methods.filter((method) => + const methods = appDefinitionForDeployment(app, { cloudHosted }).methods.filter((method) => !isPaperclipCloudConnectorStrategy(method.oauthStrategy) || Boolean(method.connectorProfile && enabledProfiles.has(method.connectorProfile) && paperclipCloudConnectorConsentAllowed(method.connectorProfile)) diff --git a/server/src/services/tool-access.ts b/server/src/services/tool-access.ts index abf05c53451..4a3ab8874bb 100644 --- a/server/src/services/tool-access.ts +++ b/server/src/services/tool-access.ts @@ -155,6 +155,7 @@ import { googleWorkspaceCatalogToolTitle } from "./google-workspace-rest-dispatc import { createToolRuntimeSupervisor } from "./tool-runtime-supervisor.js"; +import { paperclipGoogleSignInAvailable } from "./google-sign-in-availability.js"; import { appWithPaperclipCloudConnectorAvailability, paperclipCloudConnectorCapabilitiesFromEnv, createPaperclipCloudConnector, isPaperclipCloudConnectorStrategy, paperclipCloudConnectorConfigFromEnv, type PaperclipCloudConnector } from "./paperclip-cloud-connector.js"; import { createVercelConnectClient, deriveVercelConnectSubject, vercelConnectIntegrationStatus, type VercelConnectClient } from "./vercel-connect.js"; @@ -781,7 +782,7 @@ export function toolAccessService( const profiles = connectorWasProvided ? (await currentCloudConnector()?.getCapabilities() ?? []) : await paperclipCloudConnectorCapabilitiesFromEnv(); - return appWithPaperclipCloudConnectorAvailability(app, profiles); + return appWithPaperclipCloudConnectorAvailability(app, profiles, paperclipGoogleSignInAvailable()); } const vercelConnect = options.vercelConnectClient === undefined diff --git a/server/src/services/tool-access/oauth/authorization-start.ts b/server/src/services/tool-access/oauth/authorization-start.ts index aae8a71d8cd..c71cc3f100e 100644 --- a/server/src/services/tool-access/oauth/authorization-start.ts +++ b/server/src/services/tool-access/oauth/authorization-start.ts @@ -7,7 +7,8 @@ import { createOAuthEndpointPolicy } from "./endpoint-policy.js"; import { createOAuthDiscovery } from "./discovery.js"; import { asRecord, oauthConfig, normalizeOauthScopes, originOf } from "./metadata.js"; import { connectionMethodForConnection } from "../connection-methods.js"; -import { googleWorkspaceDraftRequestedScopes, googleWorkspaceSelectedScopes, type GoogleWorkspaceServiceSelection, isGoogleWorkspaceScopeGrant } from "@paperclipai/shared"; +import { GOOGLE_SIGN_IN_CLOUD_ONLY_MESSAGE, googleWorkspaceDraftRequestedScopes, googleWorkspaceSelectedScopes, type GoogleWorkspaceServiceSelection, isGoogleWorkspaceScopeGrant } from "@paperclipai/shared"; +import { paperclipGoogleSignInAvailable } from "../../google-sign-in-availability.js"; import { and, eq, lt } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { companies, agents, connectionGrants, issueThreadInteractions, toolConnections, toolOauthStates } from "@paperclipai/db"; @@ -36,8 +37,13 @@ type Dependencies = { assertOAuthEndpointUrl: ReturnType["assertOAuthEndpointUrl"]; }; -function cloudConnectorStartHttpError(error: unknown, providerName: string, at: Date): unknown { +function googleSignInCloudOnlyError() { + return unprocessable(GOOGLE_SIGN_IN_CLOUD_ONLY_MESSAGE, { code: "google_sign_in_cloud_only" }); +} + +function cloudConnectorStartHttpError(error: unknown, provider: string, providerName: string, at: Date): unknown { if (!(error instanceof PaperclipCloudConnectorError)) return error; + if (provider === "google" && error.brokerReason === "PROVIDER_CLOUD_ONLY") return googleSignInCloudOnlyError(); if (error.status !== 429 && error.brokerReason !== "RATE_LIMITED") return error; const retryAfterSeconds = error.retryAt === undefined ? undefined @@ -360,6 +366,7 @@ export function createOAuthAuthorizationStart(db: Db, dependencies: Dependencies if (!managedProfile) throw badRequest("This app has an invalid managed connector profile"); const providerName = galleryEntry?.name ?? "Google Workspace"; + if (managedProfile.provider === "google" && !paperclipGoogleSignInAvailable()) throw googleSignInCloudOnlyError(); if (!paperclipCloudConnectorConsentAllowed(managedProfile.id)) { throw unprocessable( `${providerName} can no longer be connected through Paperclip with these permissions. Connect Google Workspace, or set up ${providerName} with your own Google OAuth app.`, @@ -420,7 +427,7 @@ export function createOAuthAuthorizationStart(db: Db, dependencies: Dependencies returnState: state, }); } catch (error) { - throw cloudConnectorStartHttpError(error, providerName, now()); + throw cloudConnectorStartHttpError(error, managedProfile.provider, providerName, now()); } const remoteExpiry = new Date(session.expiresAt); const expiresAt = Number.isFinite(remoteExpiry.getTime()) diff --git a/server/src/services/tool-access/oauth/grant-refresh.ts b/server/src/services/tool-access/oauth/grant-refresh.ts index 3f3981411bc..f6b3f199804 100644 --- a/server/src/services/tool-access/oauth/grant-refresh.ts +++ b/server/src/services/tool-access/oauth/grant-refresh.ts @@ -4,7 +4,7 @@ import type { ActorInfo, DbTransaction } from "../types.js"; import { withAccountHomeSecretMutationLock } from "@paperclipai/adapter-codex-local/server"; import { createOAuthClientProtocol, storedOAuthTokenEndpointAuthMethod } from "./client.js"; import { oauthConfig, normalizeOauthScopes, resolveGrantedOauthScopes } from "./metadata.js"; -import { googleWorkspaceEffectiveScopes, googleWorkspaceSubmittedScopesIn, isGoogleWorkspaceScopeGrant } from "@paperclipai/shared"; +import { GOOGLE_SIGN_IN_CLOUD_ONLY_MESSAGE, googleWorkspaceEffectiveScopes, googleWorkspaceSubmittedScopesIn, isGoogleWorkspaceScopeGrant } from "@paperclipai/shared"; import { emitConnectionUpdated } from "../../connector-telemetry.js"; import { and, eq, sql } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; @@ -149,9 +149,12 @@ export function createOAuthGrantRefresh(db: Db, { now, store, leases, currentClo throw new PaperclipCloudConnectorError("Google did not return verifiable permissions", "REAUTHORIZATION_REQUIRED"); } } catch (error) { + const cloudOnly = error instanceof PaperclipCloudConnectorError + && profile.provider === "google" + && error.brokerReason === "PROVIDER_CLOUD_ONLY"; if ( error instanceof PaperclipCloudConnectorError && - error.code === "REAUTHORIZATION_REQUIRED" + (error.code === "REAUTHORIZATION_REQUIRED" || cloudOnly) ) { await db .update(connectionGrants) @@ -163,9 +166,10 @@ export function createOAuthGrantRefresh(db: Db, { now, store, leases, currentClo ), ); throw unprocessable( - "Managed authorization must be reconnected", + cloudOnly ? `Reconnect required. ${GOOGLE_SIGN_IN_CLOUD_ONLY_MESSAGE}` : "Managed authorization must be reconnected", { code: "oauth_reauthorization_required", + ...(cloudOnly ? { reason: "google_sign_in_cloud_only" } : {}), setupUrl: connectionSetupUrl(connection), reconnectUrl: connectionReconnectUrl(connection), }, diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index a207f34e35b..07bdf0d2e4b 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -268,6 +268,8 @@ "packages/shared/src/github-connectors.ts": "b8448b1eddac9a9d1308b94e4d136c761cbd4a00", "packages/shared/src/github-skill-repository.ts": "b00a9963472723bcb7fcd433aae442f75d7a138b", "packages/shared/src/gitignore-runtime.test.ts": "e334ab0eca8faeab5807171983ec9102a3f1c734", + "packages/shared/src/google-sign-in-deployment.test.ts": "7f0ee05e9adaec48ed71c67e2b0e8364b0d1bdb2", + "packages/shared/src/google-sign-in-deployment.ts": "2e4e4cc3c24347642e20c91186581e1dce81d740", "packages/shared/src/google-workspace-connectors.test.ts": "26316900a50e5ab384e0dcf9c45a2bb4abc0830d", "packages/shared/src/google-workspace-connectors.ts": "88d942d1e66d7facc68cf8645f665cdc80c8c005", "packages/shared/src/grok-bot.ts": "9de68f00e7926c397729ff62bf8e277f5a41c525", @@ -276,7 +278,7 @@ "packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d", "packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca", "packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699", - "packages/shared/src/index.ts": "583f640ffdcccf38972edd8e3e3b148111c7a00d", + "packages/shared/src/index.ts": "3fa6eb48ed1e6ccf989a35e1449da40f1975bf05", "packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca", "packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075", "packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9", diff --git a/ui/src/features/connections/ConnectionSetupFlow.tsx b/ui/src/features/connections/ConnectionSetupFlow.tsx index 7b482da544c..fe402e9901c 100644 --- a/ui/src/features/connections/ConnectionSetupFlow.tsx +++ b/ui/src/features/connections/ConnectionSetupFlow.tsx @@ -61,7 +61,11 @@ import { getAvailableConnectionMethods, getRecommendedConnectionMethod, isGoogleWorkspaceConnectorProfileId, + appDefinitionForDeployment, + isCloudOnlyConnectionMethod, + GOOGLE_SIGN_IN_CLOUD_ONLY_MESSAGE, } from "@paperclipai/shared"; +import { useCloudInstance } from "@/hooks/useCloudInstance"; import { useNavigate, useParams, useSearchParams } from "@/lib/router"; import { useCompany } from "@/context/CompanyContext"; import { useBreadcrumbs } from "@/context/BreadcrumbContext"; @@ -1188,9 +1192,13 @@ function StandardConnectionSetupFlow({ ), [galleryQuery.data, chatConnectorsEnabled, githubEnabled, memoryConnectorsEnabled, connectorAvailability.enabled], ); - const fullRequestedDefinition = requestedAppKey + const cloudInstance = useCloudInstance(); + const bundledRequestedDefinition = requestedAppKey ? getConnectableAppDefinition(requestedAppKey) : null; + const fullRequestedDefinition = bundledRequestedDefinition + ? appDefinitionForDeployment(bundledRequestedDefinition, { cloudHosted: Boolean(cloudInstance) }) + : null; const customOAuthMethod = fullRequestedDefinition?.methods.find((candidate) => connectionMethodAcceptsCustomerOAuthClient(candidate) && !connectionMethodSupportsAutomaticOAuth(candidate), @@ -2815,6 +2823,7 @@ function StandardConnectionSetupFlow({ ; onChange: (next: Record) => void; @@ -3811,6 +3822,8 @@ function KeyStep({ const managedAsana = method?.connectorProfile === "asana.mcp"; const requirementsUrl = managedAsana ? null : method?.consoleLinks?.docs ?? entry.docsUrl; + const selfHostedGoogleClient = selfHostedGoogleApp && connectionMethodAcceptsCustomerOAuthClient(method); + const selfHostedGoogleClientGuide = method?.consoleLinks?.docs ?? entry.docsUrl ?? null; return (
@@ -3832,6 +3845,25 @@ function KeyStep({ {managedAsana ? (

Sign in with Asana to choose your workspace and connect it to Paperclip.

) : null} + {selfHostedGoogleClient ? ( + + {GOOGLE_SIGN_IN_CLOUD_ONLY_MESSAGE} + {selfHostedGoogleClientGuide ? ( + <> + {" "} + + How to set up a Google OAuth client + + + + ) : null} + + ) : null} {method?.capabilityProfile && (

{method.capabilityProfile.label}: {method.capabilityProfile.description} diff --git a/ui/src/pages/apps/AppsConnect.test.tsx b/ui/src/pages/apps/AppsConnect.test.tsx index 9bae807e0ed..9ced25c9813 100644 --- a/ui/src/pages/apps/AppsConnect.test.tsx +++ b/ui/src/pages/apps/AppsConnect.test.tsx @@ -3,7 +3,7 @@ import { act, type ReactNode } from "react"; import { createRoot, type Root } from "react-dom/client"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { CONNECTABLE_APP_DEFINITIONS, GOOGLE_WORKSPACE_CONNECTOR_PROFILES, getAppStoreDefinition, pluginAppDefinition, pluginAppSlug, setPluginAppDefinitions } from "@paperclipai/shared"; +import { CONNECTABLE_APP_DEFINITIONS, GOOGLE_SIGN_IN_CLOUD_ONLY_MESSAGE, GOOGLE_WORKSPACE_CONNECTOR_PROFILES, getAppStoreDefinition, pluginAppDefinition, pluginAppSlug, setPluginAppDefinitions } from "@paperclipai/shared"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { ApiError, type RequestOptions } from "@/api/client"; import { aiConnectionsApi } from "@/api/ai-connections"; @@ -351,6 +351,14 @@ function unconfiguredConnectorEnrollment() { }; } +function cloudQueryClient(client = new QueryClient({ defaultOptions: { queries: { retry: false } } })) { + client.setQueryData(queryKeys.health, { + deploymentMode: "authenticated", + cloud: { managed: true, managedBy: "paperclip-cloud", stackSlug: "stack-fixture", cloudBaseUrl: "https://my-staging.paperclip.app" }, + }); + return client; +} + function customerOwnedApp(app: typeof GMAIL) { return { ...app, @@ -1803,7 +1811,7 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => { }); getCloudConnectorEnrollmentMock.mockResolvedValueOnce(unconfiguredConnectorEnrollment()); - await render(); + await render(cloudQueryClient()); await passAccessStep(); expect(container.textContent).toContain("Connect with Paperclip"); @@ -1829,8 +1837,39 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => { ); }); + it("offers only the customer's own Google client on a self-hosted instance and explains why", async () => { + mockParams.appKey = "gmail"; + listGalleryMock.mockResolvedValue({ apps: [customerOwnedApp(GMAIL)] }); + getCloudConnectorEnrollmentMock.mockResolvedValue(unconfiguredConnectorEnrollment()); + + await render(); + await passAccessStep(); + + expect(container.textContent).not.toContain("Connect with Paperclip"); + expect(container.textContent).not.toContain("You must connect this instance to Paperclip"); + expect(getCloudConnectorEnrollmentMock).not.toHaveBeenCalled(); + const notice = Array.from(container.querySelectorAll('[role="note"]')) + .find((element) => element.textContent?.includes(GOOGLE_SIGN_IN_CLOUD_ONLY_MESSAGE)); + expect(notice).toBeDefined(); + const guide = notice!.querySelector("a"); + expect(guide?.textContent).toBe("How to set up a Google OAuth client"); + expect(guide?.href).toMatch(/^https:\/\/developers\.google\.com\//); + expect(container.textContent).toContain("Client ID"); + }); + + it("never shows the self-hosted Google notice on Paperclip Cloud", async () => { + mockParams.appKey = "gmail"; + listGalleryMock.mockResolvedValue({ apps: [{ ...GMAIL, ownershipAvailability: { ...GMAIL.ownershipAvailability, platform_shared: true } }] }); + + await render(cloudQueryClient()); + await passAccessStep(); + + expect(container.textContent).not.toContain(GOOGLE_SIGN_IN_CLOUD_ONLY_MESSAGE); + expect(buttonByText("Continue to sign in")).toBeDefined(); + }); + it.each([false, true])("retains task access and interaction through enrollment (popup blocked: %s)", async (popupBlocked) => { - const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + const client = cloudQueryClient(); const popup = { closed: false, location: { assign: vi.fn() }, focus: vi.fn(), close: vi.fn() }; const open = vi.spyOn(window, "open").mockReturnValue(popupBlocked ? null : popup as unknown as Window); listGalleryMock.mockResolvedValue({ apps: [customerOwnedApp(GMAIL)] }); @@ -1880,7 +1919,7 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => { verificationUrl: failure === "missing-url" ? undefined : "javascript:alert(1)", }); } - await render(undefined, false, ); + await render(cloudQueryClient(), false, ); await passAccessStep(); await act(async () => buttonByText("Connect with Paperclip")?.click()); await flushReact();