mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-25 16:14:26 +01:00
fix(connections): offer Paperclip's Google sign-in on Paperclip Cloud only (#22699)
<!-- Write all pull request text in Simplified Technical English
(ASD-STE100): short sentences, one instruction per sentence, simple
approved vocabulary, and the active voice. -->
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents use Google Workspace through a connection. A connection can
use Paperclip's own Google sign-in ("Connect with Paperclip") or the
customer's own Google OAuth client
> - Paperclip's own Google sign-in goes through the Paperclip Cloud
broker with Paperclip's verified Google client
> - Google's restricted-scope verification and security assessment cover
only the servers that Paperclip operates
> - The owner decided on 2026-11-23: Paperclip's own Google sign-in is
for Paperclip Cloud workspaces only. Self-hosted instances use their own
Google OAuth client
> - This pull request hides and refuses Paperclip's own Google sign-in
on self-hosted instances, keeps saved connections working, and gives
clear guidance
> - The benefit is that restricted-scope Google tokens stay on servers
that Paperclip operates, and self-hosted users always see a path that
works
## Linked Issues or Issue Description
Refs #22635
**What happened?**
A self-hosted Paperclip instance offered "Connect with Paperclip" for
Google Workspace and other Google apps. That sign-in uses Paperclip's
verified Google client. It sends restricted-scope Google tokens to a
server that Paperclip does not operate. A self-hosted instance also
offered Paperclip Cloud enrollment only to use that sign-in.
**What did you expect to happen?**
Paperclip's own Google sign-in is available only on Paperclip Cloud
workspaces. A self-hosted instance shows only "Use your own Google OAuth
app", with a short reason and a link to a setup guide. Saved Google
connections on a self-hosted instance keep working until a sunset date
that the owner sets on the Paperclip Cloud broker. After that date, the
connection tells the user to reconnect with their own Google client.
Paperclip Cloud workspaces do not change.
**Steps to reproduce**
1. Run Paperclip without Paperclip Cloud markers (self-hosted).
2. Turn on the Google Workspace connector in **Settings →
Experimental**.
3. Open **Apps** and choose **Google Workspace** or **Gmail**.
4. Before this change: setup offers "Connect with Paperclip" or asks to
connect the instance to Paperclip Cloud first.
## What Changed
- `packages/shared/src/google-sign-in-deployment.ts`: new
`appDefinitionForDeployment` and `isCloudOnlyConnectionMethod`. On a
self-hosted instance they remove every Paperclip-managed Google method.
Other providers do not change. New shared message
`GOOGLE_SIGN_IN_CLOUD_ONLY_MESSAGE`.
- `server/src/services/google-sign-in-availability.ts`:
`paperclipGoogleSignInAvailable()` returns `isCloudManagedInstance()`.
This is the existing single Cloud check. No new environment variable.
- `appWithPaperclipCloudConnectorAvailability` (gallery and setup
validation) uses that check. A self-hosted gallery and setup do not show
managed Google methods.
- `authorization-start.ts`: a self-hosted instance refuses to start a
managed Google authorization before it calls Paperclip Cloud (`422`,
code `google_sign_in_cloud_only`). A broker refusal with
`PROVIDER_CLOUD_ONLY` maps to the same message, also on a Cloud
instance.
- `paperclip-cloud-connector.ts`: `PROVIDER_CLOUD_ONLY` is a known
broker reason.
- `grant-refresh.ts`: when the broker refuses a refresh with
`PROVIDER_CLOUD_ONLY` (after the sunset), the grant is marked for
reconnection. The error keeps code `oauth_reauthorization_required`,
adds reason `google_sign_in_cloud_only`, and tells the user to reconnect
with their own Google OAuth client.
- `ConnectionSetupFlow.tsx`: on a self-hosted instance (no `cloud` block
in health), Google setup uses the filtered definition. It never shows
Cloud enrollment for Google. The customer-owned Google client step shows
this note and a link to Google's client guide.
- Docs: `doc/connections/GOOGLE-WORKSPACE.md` ("Who can use Paperclip's
Google sign-in", "Self-hosted instances: use your own Google client")
and a dated decision row in `doc/memory/google-connector-memory.md`.
- `tests/runner-e2e/source-sdk-public-inputs.json`: pins the new shared
files (generated).
## Verification
- Red first, then green:
- `packages/shared/src/google-sign-in-deployment.test.ts` fails without
the new module and passes with it (4 tests).
- With the source files from `origin/master`, these new tests fail: 2 in
`server/src/__tests__/tool-access-service.test.ts` (self-hosted refusal,
refresh guidance and saved-connection refresh; broker refusal mapping),
3 in `server/src/services/paperclip-cloud-connector.test.ts`, and the
self-hosted test in `ui/src/pages/apps/AppsConnect.test.tsx`. With the
change they pass.
- Cloud path proof: "never shows the self-hosted Google notice on
Paperclip Cloud" (UI), "leaves every app unchanged on Paperclip Cloud"
(shared, identity check on every definition), "decides Cloud or
self-hosted from the instance's Cloud markers" (server). All existing
managed Google service tests (515) pass in a Cloud context.
- `npx vitest run src/__tests__/tool-access-service.test.ts` (server):
517 passed.
- `npx vitest run src/services/paperclip-cloud-connector.test.ts`
(server): 71 passed.
- `npx vitest run src/pages/apps/AppsConnect.test.tsx
src/features/connections` (ui): all passed.
- `npx vitest run` for `agent-connection-catalog.integration`,
`tool-gateway-service`, `google-access-removal`,
`connection-management.integration`, `generic-mcp-connection`,
`remote-mcp-connectors` and `plugin-connectors-circleback-parity`
(server): 446 passed, 1 skipped.
- `npx vitest run` in `packages/shared`: 1383 passed.
- `pnpm verify` exits 2 because `doc/connections/GOOGLE-WORKSPACE.md` is
a global CI input. Required CI supplies the broad coverage.
- Not run: no requests to staging, production, or Google. The reconnect
of a saved managed Google connection on a self-hosted instance after the
sunset was not run end to end in a browser.
## Risks
- Behavior change for self-hosted instances: new Paperclip-managed
Google connections stop. Saved ones keep refreshing until the broker
sunset (not set yet).
- The decision uses `isCloudManagedInstance()`. If a Cloud workspace
does not have its Cloud markers, it shows the self-hosted path. Cloud
stacks always have the tenant token, so the risk is low.
- Works with old and new brokers. An old broker does not refuse. The app
check still hides and refuses the method. A new broker refuses
self-hosted instances, and the app maps the refusal to the same
guidance.
- Deploy order: the broker change (paperclip-cloud) and this change can
deploy in any order.
> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, test runs).
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
980caf1167
commit
8c6e5cbbb8
20 files changed
+397
-37
No files matched your search
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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.";
|
||||
@@ -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 {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<unknown>) => {
|
||||
await onRemoved?.();
|
||||
|
||||
@@ -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();
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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()],
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
import { isCloudManagedInstance } from "./cloud-instance.js";
|
||||
|
||||
export function paperclipGoogleSignInAvailable(): boolean {
|
||||
return isCloudManagedInstance();
|
||||
}
|
||||
@@ -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"];
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<typeof createOAuthEndpointPolicy>["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())
|
||||
|
||||
@@ -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),
|
||||
},
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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({
|
||||
<KeyStep
|
||||
settingsValid={additionalSettingsValid && instructionsValid && !dedicatedAgentMissing}
|
||||
entry={entry}
|
||||
selfHostedGoogleApp={!cloudInstance && Boolean(getConnectableAppDefinition(entry.slug)?.methods.some(isCloudOnlyConnectionMethod))}
|
||||
error={connectMutation.error ? describeError(connectMutation.error).body : null}
|
||||
values={credentials}
|
||||
onChange={setCredentials}
|
||||
@@ -3483,6 +3492,7 @@ function normalizeAppLink(value: string): string | null {
|
||||
function KeyStep({
|
||||
settingsValid = true,
|
||||
entry,
|
||||
selfHostedGoogleApp = false,
|
||||
error,
|
||||
values,
|
||||
onChange,
|
||||
@@ -3512,6 +3522,7 @@ function KeyStep({
|
||||
}: {
|
||||
settingsValid?: boolean;
|
||||
entry: AppDefinition;
|
||||
selfHostedGoogleApp?: boolean;
|
||||
error?: string | null;
|
||||
values: Record<string, string>;
|
||||
onChange: (next: Record<string, string>) => 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 (
|
||||
<div className="mx-auto max-w-xl">
|
||||
@@ -3832,6 +3845,25 @@ function KeyStep({
|
||||
{managedAsana ? (
|
||||
<p className="text-sm text-muted-foreground">Sign in with Asana to choose your workspace and connect it to Paperclip.</p>
|
||||
) : null}
|
||||
{selfHostedGoogleClient ? (
|
||||
<InlineBanner tone="info">
|
||||
{GOOGLE_SIGN_IN_CLOUD_ONLY_MESSAGE}
|
||||
{selfHostedGoogleClientGuide ? (
|
||||
<>
|
||||
{" "}
|
||||
<a
|
||||
href={selfHostedGoogleClientGuide}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="inline-flex items-center gap-1 font-medium text-foreground underline underline-offset-2"
|
||||
>
|
||||
How to set up a Google OAuth client
|
||||
<ArrowUpRight className="h-3 w-3" />
|
||||
</a>
|
||||
</>
|
||||
) : null}
|
||||
</InlineBanner>
|
||||
) : null}
|
||||
{method?.capabilityProfile && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{method.capabilityProfile.label}: {method.capabilityProfile.description}
|
||||
|
||||
@@ -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<HTMLAnchorElement>("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, <ConnectionSetupFlow host="dialog" serviceSlug="gmail" interactionId="intent-1" requestedAgentId="agent-1" />);
|
||||
await render(cloudQueryClient(), false, <ConnectionSetupFlow host="dialog" serviceSlug="gmail" interactionId="intent-1" requestedAgentId="agent-1" />);
|
||||
await passAccessStep();
|
||||
await act(async () => buttonByText("Connect with Paperclip")?.click());
|
||||
await flushReact();
|
||||
|
||||
Reference in new issue
Block a user