Preserve selected Google services when setup resumes

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-28 10:53:19 -05:00
1 parent 820c458465
commit 1c31cde0ed
11 files changed
+348 -26

No files matched your search

+14
View File
@@ -14,6 +14,20 @@ permissions; discovery skips services without grants and excludes unsupported
actions. The gateway checks actual grant scopes again before each call, including
after refresh. Requested scopes alone never authorize an action.
Before managed or customer-owned OAuth opens, Paperclip saves the validated
service choice as non-secret setup intent on the draft. It is bound to the
company, connection, initiating actor, grant kind, and credential subject.
Declined or expired authorization and a cold **Finish setup** return restore
that choice, not the new-account write defaults. Historical drafts without a
matching saved intent require an explicit choice. Reconnecting an established
account without a new choice keeps its exact grant request.
An agent can hand setup to its responsible human without choosing services or
creating provider OAuth state. If the agent proposes services, the human can
review and change them in the picker. Saving the human's choice consumes only
that person's pending proposal, so an old proposal cannot replace their choice
after a declined sign-in. Neither draft intent nor a proposal is consent.
Discovery isolates service outages. Healthy services remain usable while the
connection's health message identifies unavailable services and recommends a
catalog refresh. Failed services' cached actions are disabled until rediscovered;
@@ -37,3 +37,21 @@ validation and token gates pass.
The production setup components were checked in a background browser using
simulated Storybook data: one profile, personal access and OAuth method switching.
Full regression checks and PR review are in progress. No live Google proof yet.
## Draft resume follow-up — 2026-10-28
The setup draft now retains its validated service request before either managed
or customer-owned OAuth handoff. This non-secret intent is bound to the company,
connection, initiating actor, grant kind, and credential subject. Denial, expired
OAuth state, and a cold Finish setup return restore that exact request rather
than the new-account write defaults. Historical or differently owned drafts
require an explicit service choice; existing reconnects keep their grant request.
Agent handoffs still open the addressed human's picker without issuing provider
state or inventing service access. A human's reviewed choice consumes only their
own pending service proposal, so an older proposal cannot override that choice
on the next draft resume. Other users' proposals remain unchanged.
This follow-up is local to a fresh checkout of master at `820c458465fa`.
Provider-fixture/database and production-component tests cover the changed
journey; they do not establish live Google consent, merge, or deployment.
@@ -5,11 +5,26 @@ import {
googleWorkspaceGrantedScopes, googleWorkspaceToolTarget, isGoogleWorkspaceToolGranted,
googleWorkspaceServiceGranted, isGoogleWorkspaceScopeGrant,
googleWorkspaceSelectedScopes, googleWorkspaceEffectiveScopes, GOOGLE_WORKSPACE_DEFAULT_SELECTION,
googleWorkspaceDraftRequestedScopes,
} from "./google-workspace-connectors.js";
const scope = (value: string) => `https://www.googleapis.com/auth/${value}`;
describe("combined Google Workspace consent", () => {
it("restores draft intent only for its exact identity and current service scopes", () => {
const binding = { companyId: "company", connectionId: "connection", actorType: "user", actorId: "owner",
grantKind: "user" as const, subjectId: "owner" };
const draft = { version: 1, ...binding, requestedScopes: [scope("gmail.readonly")] };
expect(googleWorkspaceDraftRequestedScopes(draft, binding)).toEqual([scope("gmail.readonly")]);
for (const field of ["companyId", "connectionId", "actorType", "actorId", "grantKind", "subjectId"] as const) {
expect(googleWorkspaceDraftRequestedScopes({ ...draft, [field]: "different" }, binding)).toBeNull();
}
for (const requestedScopes of [[], [scope("chat.messages.readonly")], [scope("contacts.readonly")], [scope("gmail.send")], "gmail.readonly"]) {
expect(googleWorkspaceDraftRequestedScopes({ ...draft, requestedScopes }, binding)).toBeNull();
}
expect(googleWorkspaceDraftRequestedScopes(undefined, binding)).toBeNull();
});
it("defaults to Gmail, combined Drive, and Calendar write scopes without Chat or People", () => {
const selected = googleWorkspaceSelectedScopes(GOOGLE_WORKSPACE_DEFAULT_SELECTION);
expect(selected).toHaveLength(9);
@@ -48,6 +48,31 @@ export function googleWorkspaceSelectionForScopes(scopes: readonly string[]): Go
return selection;
}
export interface GoogleWorkspaceDraftBinding {
companyId: string;
connectionId: string;
actorType: string | null;
actorId: string | null;
grantKind: "user" | "agent" | "organization";
subjectId: string | null;
}
export function googleWorkspaceDraftRequestedScopes(
value: unknown,
binding: GoogleWorkspaceDraftBinding,
): string[] | null {
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
const draft = value as Record<string, unknown>;
if (!binding.actorType || !binding.actorId || draft.version !== 1
|| Object.entries(binding).some(([key, expected]) => draft[key] !== expected)) return null;
const scopes = draft.requestedScopes;
const allowed = new Set(GOOGLE_WORKSPACE_SERVICE_GROUPS.flatMap(group =>
[...group.read, ...group.write].flatMap(profile => GOOGLE_WORKSPACE_CONNECTOR_PROFILES[profile].scopes)));
if (!Array.isArray(scopes) || scopes.length === 0 || scopes.length > allowed.size
|| scopes.some(scope => typeof scope !== "string" || !allowed.has(scope))) return null;
return [...new Set(scopes)].sort();
}
const auth = (scope: string) => `https://www.googleapis.com/auth/${scope}`;
const SERVICE_PROFILES: Readonly<Record<Exclude<GoogleWorkspaceConnectorProfileId, "workspace.all">, {
@@ -785,6 +785,10 @@ describe("connection management with production default agents", () => {
const created = await f.request("POST", `/companies/${f.companyId}/tools/connections`, { name: "Selected Google services", transport: "mcp_remote", authKind: "oauth", credentialPolicy: "per_user", status: "draft",
config: { url: "https://1.1.1.1/mcp", sourceTemplateKey: "google-workspace", connectionMethodKey: "paperclip-workspace" } });
expect(created, JSON.stringify(created)).toMatchObject({ status: 201 });
const handoff = await f.request("POST", `/tools/oauth/${created.body.id}/start`, { asCurrentUser: true });
expect(handoff, JSON.stringify(handoff)).toMatchObject({ status: 200, body: { expiresAt: null, requiredUserAction: { userId: f.userId } } });
const [unselected] = await server.db.select().from(toolConnections).where(eq(toolConnections.id, created.body.id));
expect(unselected.config.workspaceSetup).toBeUndefined();
const services = { gmail: "read" as const };
const started = await f.request("POST", `/tools/oauth/${created.body.id}/start`, { asCurrentUser: true, workspaceServices: services });
expect(started, JSON.stringify(started)).toMatchObject({ status: 200, body: { expiresAt: null, requiredUserAction: { userId: f.userId } } });
@@ -797,6 +801,10 @@ describe("connection management with production default agents", () => {
[f.userId]: { requestedScopes: googleWorkspaceSelectedScopes(services) },
} } } } });
expect(await server.db.select().from(toolOauthStates).where(eq(toolOauthStates.connectionId, saved.id))).toHaveLength(0);
expect(await f.request("POST", `/tools/oauth/${saved.id}/start`, { asCurrentUser: true })).toMatchObject({ status: 200, body: { authorizationUrl: started.body.authorizationUrl } });
const [handedOff] = await server.db.select().from(toolConnections).where(eq(toolConnections.id, saved.id));
expect(handedOff.config.workspaceSetup).toBeUndefined();
expect(handedOff.config.oauth).toEqual(saved.config.oauth);
});
it("discovers and invokes connection APIs through default production native bindings", async () => {
@@ -82,6 +82,9 @@ import {
} from "../services/tool-access.js";
import { accessService } from "../services/access.js";
import { instanceSettingsService } from "../services/instance-settings.js";
import { createOAuthAuthorizationStart } from "../services/tool-access/oauth/authorization-start.js";
import { createPersonalConnectionIdentity } from "../services/tool-access/connections/personal-identity.js";
import { createConnectionSetupPolicy } from "../services/tool-access/connections/setup-policy.js";
import { toolAccessPolicyService } from "../services/tool-access-policy.js";
import { secretService } from "../services/secrets.js";
import {
@@ -2606,6 +2609,63 @@ describeEmbeddedPostgres("tool access service", () => {
expect(reconnected.connection.agentInstructions).toEqual(settings);
});
it.each(["managed", "customer"] as const)("preserves a %s Workspace draft's selection after declined and expired authorization", async (mode) => {
const company = await createCompany(db);
const userId = `workspace-draft-${randomUUID()}`;
await grantBoardUser(db, company.id, userId, [], "owner");
const actor = { actorType: "user" as const, actorId: userId };
const connector = fakeGoogleWorkspaceConnector(company.id, userId, "workspace.all");
const service = createTestToolAccessService(db, { paperclipCloudConnector: connector });
const connected = await service.connectGalleryApp(company.id, {
galleryKey: "google-workspace", grantKind: "user",
connectionMethodKey: mode === "managed" ? "paperclip-workspace" : "customer-workspace-oauth",
...(mode === "customer" ? { oauthClient: { clientId: "fixture-client", clientSecret: "fixture-secret" } } : {}),
}, actor);
const redirectUri = "https://paperclip.example.test/api/tools/oauth/callback";
const [unstarted] = await db.select().from(toolConnections).where(eq(toolConnections.id, connected.connectionId));
const configWithProposals = { ...unstarted.config, oauth: { ...(unstarted.config.oauth as Record<string, unknown>), pendingWorkspaceServiceRequests: {
[userId]: { requestedScopes: googleWorkspaceSelectedScopes({ drive: "write" }), requestedAt: "2026-10-26T10:00:00Z" },
other: { requestedScopes: googleWorkspaceSelectedScopes({ calendar: "write" }), requestedAt: "2026-10-26T10:00:00Z" },
} } };
await db.update(toolConnections).set({ config: configWithProposals, transportConfig: configWithProposals }).where(eq(toolConnections.id, connected.connectionId));
const started = await service.startOAuth(company.id, connected.connectionId, {
redirectUri, actor, workspaceServices: { gmail: "read" },
});
const state = new URL(started.authorizationUrl).searchParams.get("state")!;
if (mode === "managed") {
await expect(service.completePaperclipCloudConnectorCallback({ state, error: "access_denied", actor })).rejects.toMatchObject({ status: 400 });
} else {
await expect(service.completeOAuthCallback({ state, error: "access_denied", redirectUri, actor })).rejects.toMatchObject({ status: 400 });
}
const draft = await service.getConnection(connected.connectionId);
expect(draft.status).toBe("draft");
expect(draft.config.workspaceSetup).toEqual({
version: 1, companyId: company.id, connectionId: draft.id, actorType: "user", actorId: userId,
grantKind: "user", subjectId: userId,
requestedScopes: ["https://www.googleapis.com/auth/gmail.readonly"],
});
expect((draft.config.oauth as typeof configWithProposals.oauth).pendingWorkspaceServiceRequests).toEqual({ other: configWithProposals.oauth.pendingWorkspaceServiceRequests.other });
const retained = await service.connectGalleryApp(company.id, {
galleryKey: "google-workspace", resumeConnectionId: draft.id,
connectionMethodKey: mode === "managed" ? "paperclip-workspace" : "customer-workspace-oauth",
...(mode === "customer" ? { oauthClient: { clientId: "fixture-client" } } : {}),
}, actor);
expect(retained.connectionId).toBe(draft.id);
const resumed = await service.startOAuth(company.id, retained.connectionId, { redirectUri, actor });
const [resumedState] = await db.select().from(toolOauthStates).where(eq(toolOauthStates.state, new URL(resumed.authorizationUrl).searchParams.get("state")!));
expect(resumedState.requestedScopes).toEqual(["https://www.googleapis.com/auth/gmail.readonly"]);
await db.update(toolOauthStates).set({ expiresAt: new Date(Date.now() - 1000) }).where(eq(toolOauthStates.state, resumedState.state));
if (mode === "managed") {
await expect(service.completePaperclipCloudConnectorCallback({ state: resumedState.state, claimId: "expired", actor })).rejects.toMatchObject({ status: 400 });
} else {
await expect(service.completeOAuthCallback({ state: resumedState.state, code: "expired", redirectUri, actor })).rejects.toMatchObject({ status: 400 });
}
const coldService = createTestToolAccessService(db, { paperclipCloudConnector: connector });
const coldResume = await coldService.startOAuth(company.id, draft.id, { redirectUri, actor });
const [coldState] = await db.select().from(toolOauthStates).where(eq(toolOauthStates.state, new URL(coldResume.authorizationUrl).searchParams.get("state")!));
expect(coldState.requestedScopes).toEqual(["https://www.googleapis.com/auth/gmail.readonly"]);
});
it.each(["user", "organization"] as const)("preserves the %s Workspace request when account-page reconnect omits a selection", async (kind) => {
const company = await createCompany(db);
const service = createTestToolAccessService(db);
@@ -2639,6 +2699,69 @@ describeEmbeddedPostgres("tool access service", () => {
expect(new URL(selected.authorizationUrl).searchParams.get("scope")?.split(" ")).toEqual(requestedScopes);
});
it("requires explicit selection for historical Workspace drafts and a different setup owner", async () => {
const company = await createCompany(db);
const userId = `workspace-owner-${randomUUID()}`;
const otherUserId = `workspace-owner-${randomUUID()}`;
await grantBoardUser(db, company.id, userId, [], "owner");
await grantBoardUser(db, company.id, otherUserId, [], "owner");
const actor = { actorType: "user" as const, actorId: userId };
const connector = fakeGoogleWorkspaceConnector(company.id, userId, "workspace.all");
const service = createTestToolAccessService(db, { paperclipCloudConnector: connector });
const connected = await service.connectGalleryApp(company.id, {
galleryKey: "google-workspace", connectionMethodKey: "paperclip-workspace", grantKind: "organization",
}, actor);
const redirectUri = "https://paperclip.example.test/api/tools/oauth/callback";
await expect(service.startOAuth(company.id, connected.connectionId, { redirectUri, actor })).rejects.toMatchObject({ status: 400 });
await service.startOAuth(company.id, connected.connectionId, { redirectUri, actor, workspaceServices: { gmail: "read" } });
await expect(service.startOAuth(company.id, connected.connectionId, {
redirectUri, actor: { actorType: "user", actorId: otherUserId },
})).rejects.toMatchObject({ status: 400 });
expect((await service.getConnection(connected.connectionId)).config.workspaceSetup).toMatchObject({ actorId: userId });
});
it.each(["credentialPolicy", "credentialSource", "authKind", "transport", "createdByUserId", "sourceTemplateKey", "connectionMethodKey"] as const)("rejects a Workspace draft whose %s changes during authorization", async (field) => {
const company = await createCompany(db);
const actor = { actorType: "user" as const, actorId: "board" };
const service = createTestToolAccessService(db);
const connected = await service.connectGalleryApp(company.id, {
galleryKey: "google-workspace", connectionMethodKey: "customer-workspace-oauth", grantKind: "organization",
oauthClient: { clientId: "fixture-client", clientSecret: "fixture-secret" },
}, actor);
const [original] = await db.select().from(toolConnections).where(eq(toolConnections.id, connected.connectionId));
const changed: Partial<typeof toolConnections.$inferInsert> = {};
if (field === "credentialPolicy") changed.credentialPolicy = "per_user";
else if (field === "credentialSource") {
changed.credentialSource = "vercel_connect";
changed.credentialRefs = [];
changed.credentialSecretRefs = [];
changed.externalCredential = { provider: "vercel_connect", connectorId: "fixture", connectorUid: "fixture", service: "google", principalMode: "user" };
}
else if (field === "authKind") changed.authKind = "none";
else if (field === "transport") changed.transport = "rest_api";
else if (field === "createdByUserId") changed.createdByUserId = "another-owner";
else changed.config = { ...original.config, [field]: "different" };
const start = createOAuthAuthorizationStart(db, {
now: () => new Date(),
getConnectionRow: async () => {
await db.update(toolConnections).set(changed).where(eq(toolConnections.id, original.id));
return original;
},
setupPolicy: createConnectionSetupPolicy(db),
fixedPersonalIdentityForReconnect: createPersonalConnectionIdentity(db),
currentCloudConnector: () => null,
vercelConnect: null,
ensureOAuthClient: vi.fn(),
oauthEndpointsForConnection: vi.fn(),
assertOAuthEndpointUrl: vi.fn(),
});
await expect(start(company.id, original.id, {
redirectUri: "https://paperclip.example.test/api/tools/oauth/callback", actor, workspaceServices: { gmail: "read" },
})).rejects.toMatchObject({ status: 409 });
expect((await service.getConnection(original.id)).config.workspaceSetup).toBeUndefined();
expect(await db.select().from(toolOauthStates).where(eq(toolOauthStates.connectionId, original.id))).toHaveLength(0);
});
it("binds selected Workspace service scopes to OAuth state and rejects other providers", async () => {
const company = await createCompany(db);
const service = createTestToolAccessService(db);
@@ -2672,7 +2795,7 @@ describeEmbeddedPostgres("tool access service", () => {
oauthClient: { clientId: "test-workspace-client", clientSecret: "test-workspace-secret" },
}, actor);
const redirectUri = "https://paperclip.example.test/api/tools/oauth/callback";
const started = await service.startOAuth(company.id, connected.connectionId, { redirectUri, actor });
const started = await service.startOAuth(company.id, connected.connectionId, { redirectUri, actor, workspaceServices: GOOGLE_WORKSPACE_DEFAULT_SELECTION });
const authorization = new URL(started.authorizationUrl);
expect(authorization.searchParams.get("scope")?.split(" ")).toEqual(googleWorkspaceSelectedScopes(GOOGLE_WORKSPACE_DEFAULT_SELECTION));
expect(authorization.searchParams.get("enable_granular_consent")).toBe("true");
@@ -2728,7 +2851,9 @@ describeEmbeddedPostgres("tool access service", () => {
const redirectUri = `https://paperclip.example/api/tools/oauth/${mode === "managed" ? "cloud-connector/" : ""}callback`;
for (const reconnect of [false, true]) {
if (reconnect) await service.connectGalleryApp(company.id, { ...input, reconnectConnectionId: connected.connectionId }, actor);
const started = await service.startOAuth(company.id, connected.connectionId, { redirectUri, actor });
const started = await service.startOAuth(company.id, connected.connectionId, { redirectUri, actor,
...(!reconnect ? { workspaceServices: GOOGLE_WORKSPACE_DEFAULT_SELECTION } : {}),
});
const state = new URL(started.authorizationUrl).searchParams.get("state")!;
const completed = mode === "managed"
? await service.completePaperclipCloudConnectorCallback({ state, claimId: "workspace-no-agents", actor })
@@ -7615,6 +7740,7 @@ describeEmbeddedPostgres("tool access service", () => {
expect(workspaceApp.methods.map((method: { key: string }) => method.key)).toContain(methodKey);
const connected = await request(app).post(`/api/companies/${company.id}/tools/apps/connect`).send({
galleryKey: slug, connectionMethodKey: methodKey, grantKind: "user", name: `Personal ${slug}`,
...(profile === "workspace.all" ? { workspaceServices: GOOGLE_WORKSPACE_DEFAULT_SELECTION } : {}),
});
expect(connected.status).toBe(201);
expect(connected.body.connection).toMatchObject({ credentialPolicy: "per_user", ownership: "platform_shared" });
@@ -7677,6 +7803,7 @@ describeEmbeddedPostgres("tool access service", () => {
.map((method: { key: string }) => method.key)).toContain(methodKey);
const result = await request(app).post(`/api/companies/${company.id}/tools/apps/connect`).send({
galleryKey: slug, connectionMethodKey: methodKey, grantKind: "user", name: `Cloud ${slug}`,
...(profile === "workspace.all" ? { workspaceServices: GOOGLE_WORKSPACE_DEFAULT_SELECTION } : {}),
});
expect(result.status, JSON.stringify(result.body)).toBe(201);
expect(result.body.auth.startUrl).toBe("https://my.paperclip.app/connections/confirm?id=test-workspace-session");
@@ -8283,6 +8410,7 @@ describeEmbeddedPostgres("tool access service", () => {
}, actor);
const started = await service.startOAuth(company.id, connected.connectionId, {
redirectUri: "https://paperclip.example/api/tools/oauth/cloud-connector/callback", actor,
workspaceServices: GOOGLE_WORKSPACE_DEFAULT_SELECTION,
});
const completed = await service.completePaperclipCloudConnectorCallback({
state: new URL(started.authorizationUrl).searchParams.get("state")!, claimId: "workspace-claim", actor,
@@ -8350,7 +8478,7 @@ describeEmbeddedPostgres("tool access service", () => {
...(mode === "customer" ? { oauthClient: { clientId: "workspace-client", clientSecret: "workspace-client-secret" } } : {}),
}, actor);
const redirectUri = mode === "managed" ? "https://paperclip.example/api/tools/oauth/cloud-connector/callback" : "https://paperclip.example/api/tools/oauth/callback";
const started = await service.startOAuth(company.id, connected.connectionId, { redirectUri, actor });
const started = await service.startOAuth(company.id, connected.connectionId, { redirectUri, actor, workspaceServices: GOOGLE_WORKSPACE_DEFAULT_SELECTION });
const state = new URL(started.authorizationUrl).searchParams.get("state")!;
const completed = mode === "managed"
? await service.completePaperclipCloudConnectorCallback({ state, claimId: "fixture", actor })
+3
View File
@@ -2112,6 +2112,9 @@ export function toolAccessService(
sourceTemplateKey: galleryEntry.slug,
connectionMethodKey: method?.key,
methodConfig: normalizedMethodConfig?.values ?? {},
...(galleryEntry.slug === "google-workspace" && retainedConnection?.status === "draft"
? { workspaceSetup: retainedConnection.config.workspaceSetup }
: {}),
...(method?.defaults?.mcpSessionRequired === true
? { mcpSessionRequired: true }
: {}),
@@ -4,9 +4,9 @@ import { createOAuthClientRegistration } from "./client-registration.js";
import type { ActorInfo } from "../types.js";
import { createOAuthEndpointPolicy } from "./endpoint-policy.js";
import { createOAuthDiscovery } from "./discovery.js";
import { oauthConfig, normalizeOauthScopes, originOf } from "./metadata.js";
import { asRecord, oauthConfig, normalizeOauthScopes, originOf } from "./metadata.js";
import { connectionMethodForConnection } from "../connection-methods.js";
import { GOOGLE_WORKSPACE_DEFAULT_SELECTION, googleWorkspaceSelectedScopes, type GoogleWorkspaceServiceSelection, isGoogleWorkspaceScopeGrant } from "@paperclipai/shared";
import { googleWorkspaceDraftRequestedScopes, googleWorkspaceSelectedScopes, type GoogleWorkspaceServiceSelection, isGoogleWorkspaceScopeGrant } from "@paperclipai/shared";
import { and, eq, lt } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { companies, agents, connectionGrants, issueThreadInteractions, toolConnections, toolOauthStates } from "@paperclipai/db";
@@ -71,17 +71,37 @@ export function createOAuthAuthorizationStart(db: Db, dependencies: Dependencies
const galleryMethod = galleryEntry
? connectionMethodForConnection(galleryEntry, connection)
: null;
const starterBinding = actorBinding(input.actor);
const fixedPersonalIdentity = await fixedPersonalIdentityForReconnect(
connection,
input.subjectUserId,
input.actor,
);
const authorizationSubjectUserId =
fixedPersonalIdentity?.subjectUserId ?? input.subjectUserId;
const authorizationSubjectAgentId = input.subjectAgentId;
const workspaceDraftBinding = {
companyId, connectionId: connection.id,
actorType: starterBinding.actorType, actorId: starterBinding.actorId,
grantKind: connection.credentialPolicy === "per_user" ? "user" as const
: connection.credentialPolicy === "per_agent" ? "agent" as const : "organization" as const,
subjectId: connection.credentialPolicy === "per_user" ? authorizationSubjectUserId ?? null
: connection.credentialPolicy === "per_agent" ? authorizationSubjectAgentId ?? null : null,
};
const requestedScopes = await (async () => {
if (input.workspaceServices && sourceTemplateKey !== "google-workspace") throw badRequest("Service selection requires Google Workspace");
if (sourceTemplateKey === "google-workspace") {
if (input.workspaceServices && input.scopes) throw badRequest("Choose services or scopes, not both");
const allowed = normalizeOauthScopes(galleryMethod?.defaults?.scopesHint);
let scopes = input.scopes ?? (input.workspaceServices ? googleWorkspaceSelectedScopes(input.workspaceServices) : undefined);
if (!scopes && connection.status !== "draft") {
if (!scopes && connection.status === "draft") {
scopes = googleWorkspaceDraftRequestedScopes(connection.config.workspaceSetup, workspaceDraftBinding) ?? undefined;
}
if (!scopes && input.actor.managementContext?.actor.type === "agent") return null;
if (!scopes) {
// Account-page reconnect has no new service choice. Never replace its
// subject's saved request with the new-account write defaults.
const binding = actorBinding(input.actor);
const subjectUserId = input.subjectUserId ?? (binding.actorType === "user" ? binding.actorId : null);
const subjectUserId = authorizationSubjectUserId ?? (starterBinding.actorType === "user" ? starterBinding.actorId : null);
const kind = connection.credentialPolicy === "per_user" ? "user"
: connection.credentialPolicy === "per_agent" ? "agent" : "organization";
const [grant] = await db.select().from(connectionGrants).where(and(
@@ -93,11 +113,12 @@ export function createOAuthAuthorizationStart(db: Db, dependencies: Dependencies
: eq(connectionGrants.isDefault, true),
)).limit(1);
const saved = grant?.providerTenant?.oauth;
scopes = normalizeOauthScopes(saved?.requestedScopes ?? saved?.scopes)
scopes = normalizeOauthScopes(saved?.requestedScopes ?? (connection.status !== "draft" ? saved?.scopes : undefined))
.filter(scope => allowed.includes(scope));
if (scopes.length === 0) throw badRequest("Choose your Google Workspace services before reconnecting");
if (scopes.length === 0) throw badRequest(connection.status === "draft"
? "Choose your Google Workspace services before continuing setup"
: "Choose your Google Workspace services before reconnecting");
}
scopes ??= googleWorkspaceSelectedScopes(GOOGLE_WORKSPACE_DEFAULT_SELECTION);
if (!isGoogleWorkspaceScopeGrant(scopes) || scopes.some(scope => !allowed.includes(scope))) throw badRequest("Select at least one supported Google service");
return scopes;
}
@@ -117,15 +138,6 @@ export function createOAuthAuthorizationStart(db: Db, dependencies: Dependencies
}
return requested;
})();
const starterBinding = actorBinding(input.actor);
const fixedPersonalIdentity = await fixedPersonalIdentityForReconnect(
connection,
input.subjectUserId,
input.actor,
);
const authorizationSubjectUserId =
fixedPersonalIdentity?.subjectUserId ?? input.subjectUserId;
const authorizationSubjectAgentId = input.subjectAgentId;
if (authorizationSubjectAgentId) {
const [subjectAgent] = await db
.select({ id: agents.id })
@@ -208,6 +220,37 @@ export function createOAuthAuthorizationStart(db: Db, dependencies: Dependencies
return { connectionId: connection.id, provider: sourceTemplateKey ?? "oauth",
authorizationUrl: destination.toString(), expiresAt: null };
}
if (sourceTemplateKey === "google-workspace" && connection.status === "draft") {
const workspaceSetup = { version: 1, ...workspaceDraftBinding, requestedScopes };
const updated = await db.transaction(async tx => {
const [saved] = await tx.select().from(toolConnections).where(and(
eq(toolConnections.id, connection.id), eq(toolConnections.companyId, companyId), eq(toolConnections.status, "draft"),
)).for("no key update");
if (!saved || (["credentialPolicy", "credentialSource", "authKind", "transport", "createdByUserId"] as const)
.some(key => saved[key] !== connection[key])
|| ["sourceTemplateKey", "connectionMethodKey"].some(key => saved.config[key] !== connection.config[key]
|| saved.transportConfig[key] !== connection.transportConfig[key])) {
throw conflict("Connection setup changed. Reload before continuing");
}
const config: Record<string, unknown> = { ...saved.config, workspaceSetup };
const transportConfig: Record<string, unknown> = { ...saved.transportConfig, workspaceSetup };
if (starterBinding.actorType === "user" && starterBinding.actorId) {
for (const target of [config, transportConfig]) {
const oauth = asRecord(target.oauth);
const pending = { ...asRecord(oauth.pendingWorkspaceServiceRequests) };
if (Object.hasOwn(pending, starterBinding.actorId)) {
delete pending[starterBinding.actorId];
target.oauth = { ...oauth, pendingWorkspaceServiceRequests: pending };
}
}
}
const [row] = await tx.update(toolConnections).set({ config, transportConfig, updatedAt: now() })
.where(and(eq(toolConnections.id, saved.id), eq(toolConnections.companyId, companyId), eq(toolConnections.status, "draft"))).returning();
return row;
});
if (!updated) throw conflict("Connection setup changed. Reload before continuing");
connection = updated;
}
if (connection.credentialSource === "vercel_connect") {
if (!vercelConnect)
throw vercelConnectHttpError(
@@ -32,6 +32,7 @@ describe("Workspace service consent", () => {
}
beforeEach(() => {
vi.clearAllMocks();
listGrants.mockResolvedValue({ currentUserId: "me", grants: [] });
container = document.createElement("div");
document.body.append(container);
root = createRoot(container);
@@ -68,6 +69,36 @@ describe("Workspace service consent", () => {
expect(onContinue).toHaveBeenCalledWith({ gmail: "read" });
});
it("restores a cold draft's selected services after declined OAuth", async () => {
await render({ ...existing, companyId: "company-1", status: "draft", config: {
workspaceSetup: {
version: 1, companyId: "company-1", connectionId: existing.id,
actorType: "user", actorId: "me", grantKind: "user", subjectId: "me",
requestedScopes: ["https://www.googleapis.com/auth/gmail.readonly"],
},
oauth: { scopes: ["https://www.googleapis.com/auth/documents"] },
} });
expect([...document.querySelectorAll('[role="switch"]')].map(item => item.getAttribute("aria-checked"))).toEqual(["true", "false", "false"]);
expect(document.querySelector("select")?.value).toBe("read");
await click("Continue");
expect(onContinue).toHaveBeenCalledWith({ gmail: "read" });
});
it.each([undefined, "another-user"])("requires a deliberate choice for an unbound draft (%s)", async (actorId) => {
await render({ ...existing, companyId: "company-1", status: "draft", config: {
...(actorId ? { workspaceSetup: {
version: 1, companyId: "company-1", connectionId: existing.id,
actorType: "user", actorId, grantKind: "user", subjectId: "me",
requestedScopes: ["https://www.googleapis.com/auth/gmail.readonly"],
} } : {}),
oauth: { scopes: ["https://www.googleapis.com/auth/documents"] },
} });
expect([...document.querySelectorAll('[role="switch"]')].map(item => item.getAttribute("aria-checked"))).toEqual(["false", "false", "false"]);
const proceed = [...document.querySelectorAll("button")].find(item => item.textContent === "Continue")!;
expect(proceed.disabled).toBe(true);
expect(onContinue).not.toHaveBeenCalled();
});
it("blocks on grant-load failure and retries without broadening the saved request", async () => {
listGrants.mockRejectedValueOnce(new Error("unavailable"));
await render(existing);
@@ -1,6 +1,6 @@
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { GOOGLE_WORKSPACE_DEFAULT_SELECTION, GOOGLE_WORKSPACE_SERVICE_GROUPS, googleWorkspaceSelectionForScopes, type GoogleWorkspaceServiceSelection, type ToolConnection } from "@paperclipai/shared";
import { GOOGLE_WORKSPACE_DEFAULT_SELECTION, GOOGLE_WORKSPACE_SERVICE_GROUPS, googleWorkspaceDraftRequestedScopes, googleWorkspaceSelectionForScopes, type GoogleWorkspaceServiceSelection, type ToolConnection } from "@paperclipai/shared";
import { toolsApi } from "@/api/tools";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
@@ -43,12 +43,11 @@ type DialogProps = {
};
export function GoogleWorkspaceServicesDialog(props: DialogProps) {
const existing = props.connection && props.connection.status !== "draft" ? props.connection : null;
const existing = props.connection ?? null;
const oauth = props.connection?.config?.oauth as { pendingWorkspaceServiceRequests?: Record<string, { requestedScopes?: unknown; requestedAt?: string }> } | undefined;
const pendingRequests = oauth?.pendingWorkspaceServiceRequests;
const loadConnection = existing ?? (pendingRequests && Object.keys(pendingRequests).length ? props.connection : null);
const grants = useQuery({ queryKey: ["workspace-service-consent", loadConnection?.id], queryFn: () => toolsApi.listConnectionGrants(loadConnection!.id), enabled: Boolean(loadConnection) });
if (loadConnection && !grants.data) return <Dialog open onOpenChange={open => { if (!open) props.onCancel(); }}><DialogContent>
const grants = useQuery({ queryKey: ["workspace-service-consent", existing?.id], queryFn: () => toolsApi.listConnectionGrants(existing!.id), enabled: Boolean(existing) });
if (existing && !grants.data) return <Dialog open onOpenChange={open => { if (!open) props.onCancel(); }}><DialogContent>
<DialogTitle>Connect Google Workspace</DialogTitle><DialogDescription>{grants.isError ? "Could not load your saved service access. Your connection has not changed." : "Loading your saved service access…"}</DialogDescription>
<footer className="flex items-center justify-between gap-3"><Button variant="ghost" onClick={() => props.onCancel()}>Cancel</Button>{grants.isError && <Button onClick={() => void grants.refetch()}>Try again</Button>}</footer>
</DialogContent></Dialog>;
@@ -57,7 +56,15 @@ export function GoogleWorkspaceServicesDialog(props: DialogProps) {
: existing?.credentialPolicy === "per_agent"
? grant.kind === "agent" && grant.subjectAgentId === (existing.config?.oauth as { connectorSubjectAgentId?: string } | undefined)?.connectorSubjectAgentId
: grant.kind === "organization");
const savedScopes = grant?.providerTenant?.oauth?.requestedScopes ?? grant?.providerTenant?.oauth?.scopes ?? [];
const savedScopes = existing?.status === "draft"
? googleWorkspaceDraftRequestedScopes(existing.config?.workspaceSetup, {
companyId: existing.companyId, connectionId: existing.id,
actorType: "user", actorId: grants.data?.currentUserId ?? null,
grantKind: existing.credentialPolicy === "per_user" ? "user" : existing.credentialPolicy === "per_agent" ? "agent" : "organization",
subjectId: existing.credentialPolicy === "per_user" ? grants.data?.currentUserId ?? null
: existing.credentialPolicy === "per_agent" ? (existing.config?.oauth as { connectorSubjectAgentId?: string } | undefined)?.connectorSubjectAgentId ?? null : null,
}) ?? grant?.providerTenant?.oauth?.requestedScopes ?? []
: grant?.providerTenant?.oauth?.requestedScopes ?? grant?.providerTenant?.oauth?.scopes ?? [];
const pending = grants.data?.currentUserId ? pendingRequests?.[grants.data.currentUserId] : undefined;
const pendingTime = Date.parse(pending?.requestedAt ?? "");
// Refresh and lease writes update the grant row without changing consent.
+30
View File
@@ -24,6 +24,7 @@ vi.mock("@/api/instanceSettings", () => ({ instanceSettingsApi: {
} }));
const listApplicationsMock = vi.hoisted(() => vi.fn());
const listConnectionsMock = vi.hoisted(() => vi.fn());
const listConnectionGrantsMock = vi.hoisted(() => vi.fn());
const getConnectionMock = vi.hoisted(() => vi.fn());
const getConnectionInstallsMock = vi.hoisted(() => vi.fn());
const connectAppMock = vi.hoisted(() => vi.fn());
@@ -82,6 +83,7 @@ vi.mock("@/api/tools", () => ({
listGallery: (companyId: string) => listGalleryMock(companyId),
listApplications: (companyId: string) => listApplicationsMock(companyId),
listConnections: (companyId: string) => listConnectionsMock(companyId),
listConnectionGrants: (connectionId: string) => listConnectionGrantsMock(connectionId),
getConnection: (id: string) => getConnectionMock(id),
getConnectionInstalls: (id: string) => getConnectionInstallsMock(id),
connectApp: (companyId: string, input: unknown) => connectAppMock(companyId, input),
@@ -2894,6 +2896,34 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {
);
});
it("keeps Gmail read-only selected when Finish setup resumes a declined Workspace draft", async () => {
const connectionId = "22222222-2222-4222-8222-222222222222";
const workspace = getAppStoreDefinition("google-workspace")!;
mockSearch.value = `source=google-workspace&resume=${connectionId}&oauth=denied`;
listGalleryMock.mockResolvedValue({ apps: [{ ...workspace, ownershipAvailability: { ...workspace.ownershipAvailability, platform_shared: true } }] });
listApplicationsMock.mockResolvedValue({ applications: [{ id: "app-workspace", companyId: "company-1", status: "draft", metadata: { sourceTemplateKey: "google-workspace" } }] });
listConnectionsMock.mockResolvedValue({ connections: [{
...notionConnection(connectionId, "per_user", "draft"), companyId: "company-1", applicationId: "app-workspace",
config: { sourceTemplateKey: "google-workspace", connectionMethodKey: "paperclip-workspace", workspaceSetup: {
version: 1, companyId: "company-1", connectionId, actorType: "user", actorId: "me", grantKind: "user", subjectId: "me",
requestedScopes: ["https://www.googleapis.com/auth/gmail.readonly"],
} },
}] });
listConnectionGrantsMock.mockResolvedValue({ currentUserId: "me", grants: [] });
await render();
await vi.waitFor(() => expect(container.textContent).toContain("Try again"));
await act(async () => buttonByText("Try again")!.click());
await flushReact();
await vi.waitFor(() => expect(document.querySelector('[role="dialog"] select')).not.toBeNull());
const dialog = document.querySelector('[role="dialog"]')!;
expect([...dialog.querySelectorAll('[role="switch"]')].map(item => item.getAttribute("aria-checked"))).toEqual(["true", "false", "false"]);
expect(dialog.querySelector("select")?.value).toBe("read");
await act(async () => buttonByText("Continue")!.click());
await flushReact();
expect(connectAppMock).not.toHaveBeenCalled();
expect(startOAuthMock).toHaveBeenCalledWith(connectionId, { asCurrentUser: true, workspaceServices: { gmail: "read" } });
});
it("resumes a hidden provider draft only after matching its company-visible application", async () => {
const connectionId = "22222222-2222-4222-8222-222222222222";
mockSearch.value = `source=clickup&resume=${connectionId}`;