fix(ai-connections): delete the saved Google Antigravity sign-in on disconnect (#22931)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - AI connections let a company sign in to a model provider, and Google
Antigravity uses a Google account sign-in with a long-lived refresh
token
> - When a user disconnected that account, or removed its connection,
Paperclip marked the grant revoked but kept the saved sign-in in its
database
> - The obvious fix, revoking the token at Google, is unsafe here: the
sign-in uses the OAuth client of Google's own Antigravity runtime, and
Google revocation removes the grant for that whole client
> - A revoke would sign the person out of their own Antigravity app or
CLI and out of every other Paperclip connection for that Google account
> - This pull request deletes Paperclip's saved sign-in on disconnect
and removal, does not call Google, and says plainly that the sign-in
stays valid at Google until the person removes it there
> - The benefit is that "disconnect" does what the person expects in
Paperclip, never breaks their other tools, and never leaves a usable
token behind in Paperclip

## Linked Issues or Issue Description

No issue exists. This follows the feature request template.

**Subsystem affected**

AI connections: Google Antigravity subscription sign-in, its disconnect
and connection removal paths, the connection removal transaction, and
the disconnect messages in the UI and activity log.

**Problem or motivation**

Disconnecting a Google Antigravity subscription account marked the
connection grant revoked in Paperclip only. The saved sign-in (an
encrypted company secret that holds the refresh token) was not deleted.
Connection removal kept it too, because removal only deletes secrets in
the app-owned key namespace. Separately, connection removal revoked the
grants and then released usage-limit holds in two separate writes, so a
failure between them left the grants revoked while held work kept
waiting.

**Proposed solution**

On disconnect or removal, delete Paperclip's saved sign-in and record
the result in plain words. Do not call Google's token revocation. Keep a
saved sign-in that another grant or target still uses. If the delete
fails, keep the reference and let the next disconnect retry. Never
delete a sign-in that a reconnect saved in the meantime. Commit the
grant revocation and the hold release in one transaction, as the
single-grant revoke already does.

**Alternatives considered**

Revoking the refresh token at `https://oauth2.googleapis.com/revoke`
(the first revision of this pull request). The saved credential always
uses client
`1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com`
(`sanitizeAntigravityCredential` rejects any other), which belongs to
Google's own Antigravity runtime that Paperclip runs for sign-in.
Google's OAuth guide for installed apps ("Token revocation") says
revocation "removes all OAuth 2.0 scopes previously granted to a
project" and invalidates tokens for all clients registered under that
project. So a revoke would sign the person out of every Antigravity
sign-in for that account, not only Paperclip's. Paperclip has no client
of its own for this sign-in, so it cannot revoke only its own access.

**Roadmap alignment**

This is work item 5 of the merged plan
`doc/plans/2026-11-25-antigravity-cloud-rollout.md` (gap G10). This pull
request updates G10, item 5 and the security table there to record the
decision.

## What Changed

- `server/src/services/antigravity-access-removal.ts`: for a Google
Antigravity subscription connection, deletes the grant's own saved
sign-in (the private `ai-<grant>` or `ai_<grant>` slot only). It keeps a
sign-in that a live grant or connection elsewhere, a secret binding or
user-secret declaration on another target, or another consumer (agent
profile, routine trigger, secret proposal) still uses. On connection
removal, other grants of the same connection do not count. The delete
passes the saved version, and the grant must still be revoked, so a
reconnect that saved a new version is never deleted. A failed delete
keeps the grant's reference so the next disconnect retries, and the
retry finds a sign-in that is already marked deleted and finishes the
purge. It also clears the quota-recovery file for that grant.
- New `server/src/services/connection-secret-consumers.ts`: one
`findSecretConsumers` check for "is this secret used elsewhere?".
Connection removal (`classifyConnectionSecrets`), managed Google removal
(`secretsHeldElsewhere`) and this change use it. Removal keeps its rule
that any grant or connection counts; the two Google paths count only
live ones. Managed Google removal now also respects bindings,
declarations and other consumers, which only keeps more secrets.
- `packages/shared`: new `AiSignInRemoval` result (`savedSignIn: deleted
| kept_shared | not_deleted`, `providerSignIn: still_valid`) on the
grant revocation result and the connection removal summary.
- `grants.ts`, `removal.ts`, `routes/tool-access.ts`: return and log the
result. Removal does not clear a grant reference whose delete failed,
and its final reference clear only touches revoked grants, so a
reconnect that lands during removal keeps its sign-in.
- `removal.ts`: the grant revocation and the usage-limit hold release
now commit in one transaction.
- `ai-connections.ts`: a personal reconnect reuses the grant's existing
secret definition only if the owner created it, it is live, and it is a
Paperclip-managed local definition. Otherwise the reconnect is refused
in plain words and no token is written.
- UI: the AI account disconnect shows a toast, and connection removal
and the audit feed show the result in plain words, for example
"Paperclip deleted its saved Google sign-in. The sign-in stays valid at
Google until you remove it in your Google account's third-party
connections. Removing it there also signs this Google account out of
Antigravity everywhere." A failed delete says "Paperclip couldn't delete
its saved Google sign-in. Disconnect again to retry."
- Docs: `doc/connections/AI-CONNECTIONS.md` and the rollout plan.
- The first revision's direct Google call and its retry branch in the
Google revocation queue are removed. `google-pending-revocation.ts` is
unchanged from `master`.
- `tests/runner-e2e/source-sdk-public-inputs.json`: refreshed pins for
the changed shared export.

## Verification

- `npx vitest run src/__tests__/antigravity-disconnect-sign-in.test.ts`
(server, embedded Postgres, network calls fail the test): 17 cases.
Disconnect through the route deletes the sign-in, makes no network call,
logs the result with no token, and the owner can reconnect. Connection
removal deletes it, also when a second grant of the same connection
references it. It is kept when a grant on another live connection, a
binding on another target, a declaration on another target, or a routine
trigger uses it. A failed delete (forced by a database trigger) is
reported, keeps the reference, and the next disconnect deletes it, for
disconnect and removal, and also when the failure comes after the
sign-in was marked deleted. A reconnect during the delete, or during
connection removal, keeps its sign-in. A personal reconnect is refused
when the slot was created by someone else, deleted, or moved to another
provider, and no token is written. A hold-release failure during removal
leaves every grant active and the sign-in saved.
- Red/green: with `master`'s `grants.ts`, `removal.ts`,
`ai-connections.ts` and `routes/tool-access.ts`, the disconnect and
removal cases fail. Each guard was also removed on its own, and its case
failed: the saved-version check, the revoked-only final clear, the
half-deleted retry, the same-connection exclusion, and the definition
ownership check.
- `ui`: `npx vitest run
src/features/connections/googleAccessRemoval.test.ts` (13 pass, 5 new).
- Connection removal and managed Google tests pass:
`tool-connection-removal`, `tool-access-service`,
`google-managed-connection-removal`, `google-pending-revocation`,
`ai-connections`, and the browser-use, client-credentials, generic MCP,
Braintrust, 1Password and remote MCP connection suites.
- Server typecheck passes. UI `tsc` shows no errors in changed files.
`pnpm verify` selects about 1,900 test files for this change (removal is
widely imported), so required CI supplies that broad coverage.

## Risks

- The Google sign-in stays valid at Google after a disconnect. The UI
and activity log say so and link to the Google account page. This is
deliberate; see Alternatives considered.
- A reconnect still keeps older versions of a rotated shared secret, as
before this change.
- Company deletion does not change here.
- No schema change and no migration.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, file edits, test runs, web reading of
Google's OAuth documentation).

## 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:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-25 08:52:03 -06:00
1 parent 917fe1ba29
commit 1bea1eeaed
21 files changed
+810 -117

No files matched your search

+13
View File
@@ -640,6 +640,19 @@ for native onboarding and physical login-process retirement. Cancellation and
expiry await retirement before removing the private home. After a server restart,
start a new Google sign-in attempt.
Disconnecting a Google Antigravity account, or removing its connection, deletes
the sign-in that Paperclip saved for it. Paperclip does not revoke the sign-in at
Google. The sign-in uses the OAuth client of Google's own Antigravity runtime, not
a Paperclip client, and Google revocation removes the grant for the whole client.
A revoke would also sign the person out of their own Antigravity app or CLI and
out of every other Paperclip connection for that Google account. The disconnect
says that the sign-in stays valid at Google until the person removes it in their
Google account. Paperclip keeps a saved sign-in that another connection or target
still uses. If the delete fails, the grant keeps its reference, and disconnecting
again retries the delete. A reconnect that saves a new version first is never
deleted. The disconnect also releases work held by that account's usage limits in
the same transaction as the grant revocation.
Antigravity task execution remains pending acceptance. Its managed subscription
path is local and turn-by-turn: native execution retires before refreshed tokens
are verified and saved with generation checks. Remote and warm OAuth execution
@@ -42,7 +42,7 @@ Copied from the kickoff success criteria. Re-read before saying "done".
campaign: staging first and verified, production after.
5. Credentials: a person's Google token placed in a sandbox is scoped to that
connection and agent, never logged, never visible to other tasks, and
disconnect revokes it.
disconnect deletes Paperclip's saved copy (no revoke at Google, see G10).
6. Every PR: green checks, Greptile 5/5, merged; deploys watched; staging
verified.
7. The ledger records what is and is not proven.
@@ -144,7 +144,7 @@ refreshable file credential with write-back to the plugin path today.
| G7 | Remote sign-in is refused at save, Test and run start (`server/src/services/native-runtime/antigravity-connection-policy.ts:42-45`, `server/src/routes/agents.ts:3292-3302`, `antigravity-runner-credentials.ts:73-74`). | as cited | Core |
| G8 | Warm default conflicts with per-turn only. A plugin environment's `runnerLifecycleMode` wins over the agent's setting (`server/src/services/runner-environment-lifecycle.ts:14-23`, `:92-93`), and the managed Daytona and Unikraft task environments set `warm` (Cloud `src/fleet/materializer.ts:163`, `:175`). Antigravity refuses warm at run start (`antigravity-connection-policy.ts:29-31`), but the save-time check does not pass the lifecycle (`agents.ts:3299`). So an Antigravity agent on those environments would save, then fail every run. | as cited | Core |
| G9 | A Cloud user cannot create a Google sign-in. Hosted instances refuse server-host sign-in (`server/src/services/local-ai-login-policy.ts:4-12`, `server/src/routes/ai-connections.ts:153`). Google sign-in is a PKCE flow whose redirect is `http://127.0.0.1:<port>/` on the server (`packages/paperclip-runner/src/drivers/acpx/antigravity-auth.ts:47-60`), which a remote browser cannot reach. Cloud's other sign-ins use a login terminal on the computer, and only Codex can read a credential back from it (`packages/plugins/sdk/src/protocol.ts:1120`, `:1167-1180`; `server/src/services/plugin-login-credential.ts:13-23`). | as cited | Core (route, UI) |
| G10 | Disconnect does not revoke at Google. AI connection removal marks the grant revoked in Paperclip only; no Google token revocation exists for AI connections (no `revoke` call in `server/src/services/ai-connections.ts` or `antigravity-auth.ts`). | as cited | Core |
| G10 | Disconnect left the saved sign-in in Paperclip. Decision: Paperclip deletes its saved sign-in on disconnect and removal and does not revoke at Google. The sign-in uses the OAuth client of Google's own Antigravity runtime (`antigravity-auth.ts:12`), and Google revocation "removes all OAuth 2.0 scopes previously granted to a project" (Google OAuth native-app guide, "Token revocation"). A revoke would sign the person out of their own Antigravity app or CLI and out of every other connection for that Google account. | as cited | Core |
Closest templates:
@@ -252,7 +252,7 @@ Reuse the Claude delivery for the token and the Codex path for write-back:
| Token never logged | The credential only travels in typed task credentials and private task environment. The Launcher must reject `PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET` (exact name) and the `GEMINI_` and `GOOGLE_` prefixes in any configured or project environment, as it does for Copilot's `COPILOT_` prefix. Add a test that searches the run log and Launcher logs for the token after a run. |
| Scoped to the run | One task credential per task, bound to the account binding and session (Cloud `task_credentials.go:64-70` `credentialBinding`); per-turn only. |
| Not readable by other tasks | Today's mechanism: each agent has its own computer or sandbox (the task drivers declare `requiresAgent: true`, Cloud `extensions/plugin-agent-computer/src/manifest.ts:26-48`), so other agents' tasks never share it. Inside one computer, every task of that agent runs as the **same** UID/GID 1000 on a shared kernel; each task gets its own private mount namespace and user namespace, and `/home/agent` is shared (Cloud `agent-computer/launcher/README.md`, "Namespace isolation" and the task entry row). Same-UID tasks are therefore not a boundary by themselves. The implementation must add: the credential home under the task's private path (`/run/paperclip-runner-tasks/<task-id>`), never `/home/agent` or a profile slot; removal when the task ends; and proof that a concurrent task of the same agent cannot read it, neither the file nor `/proc/<pid>/environ` or memory of the Runner process. If that proof fails, pass the token through a file in the private task mount instead of the environment, or run Antigravity tasks one at a time per computer. Keep the cross-task read test as a regression test. Owner: item 9 alone (the Launcher gives the Runner a runtime root under the private task path, so `agentHomeDirectory` is task-private, and item 9's acceptance carries the cross-task read test). |
| Revoked on disconnect | New: on disconnect or reconnect, call Google's token revocation for the stored refresh token, then retire it. Running tasks fail at their next refresh. Record an activity log entry. |
| Deleted on disconnect | On disconnect or removal, delete the saved sign-in and record an activity entry. Do not call Google's revoke: the client is Google's own Antigravity client, so a revoke would also sign the person out of their Antigravity app or CLI and every other connection for that account. The person removes access in their Google account if they want it ended at Google. Running tasks keep their current turn. |
## 4. The qualification flip
@@ -330,14 +330,14 @@ in that repository.
| 2 | Add Antigravity sign-in task credential with refresh write-back | Core | same files plus `native-session-executor.ts` (write-back sync beside Codex), `antigravity-runner-credentials.ts` | New credential carries only the sanitized sign-in JSON as `PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET`; a rotated refresh token from a task snapshot is saved only after the account check; a different account is refused; a test proves no token in logs | 1 | B |
| 3 | Keep per-turn-only harnesses per-turn on warm plugin environments | Core | `server/src/services/runner-environment-lifecycle.ts`, `server/src/routes/agents.ts` (save check), tests | An Antigravity agent on a plugin environment with `runnerLifecycleMode: "warm"` runs per-turn, or save refuses it in plain words; no run fails with the warm refusal | none | A |
| 4 | Hosted Google sign-in (spike, then route and UI) | Core | `server/src/routes/ai-connections.ts`, `server/src/services/local-ai-login.ts`, `local-ai-browser-login.ts`, Runner `antigravity-auth.ts`, UI connection dialog | Spike answers the loopback question first. Then: on an authenticated public instance, a user completes Google sign-in by pasting the redirect; wrong `state`, reused code and another user's attempt are refused; the connection lists models | none | A |
| 5 | Revoke the Google token on disconnect | Core | AI connection removal and reconnect paths in `server/src/services/ai-connections.ts`, activity log | Disconnect calls Google revocation once (retried on network failure), the secret is retired, an activity entry is written, a later run asks to reconnect | none | A |
| 5 | Delete the saved Google sign-in on disconnect (no revoke at Google, see G10) | Core | AI connection removal and grant revocation paths, activity log | Disconnect deletes the saved sign-in (a shared one is kept; a failed delete keeps a retryable reference), the activity entry says in plain words that the sign-in stays valid at Google until the person removes it there, a later run asks to reconnect | none | A |
| 6 | Allow Antigravity on plugin Runner-task and remote sign-in targets | Core | `antigravity-release.ts`, `antigravity-connection-probe.ts` (use the plugin probe path, `server/src/services/native-runtime/plugin-runner-probe.ts`), `antigravity-connection-policy.ts`, `antigravity-runner-credentials.ts`, `agents.ts` | Tested against a released-profile fixture (the real profile is still pending when this merges): picker offers Antigravity on a plugin environment; Test runs the plugin probe; save and run accept sign-in on remote targets when 2 is present. The Core sandbox path gets the same sign-in support. Re-verified live in item 12 | 1, 2, 3 | C |
| 7 | Qualification runs on a paid key | Core (ledger) | `doc/plans/2026-11-22-antigravity-qualification.md` | All NOT RUN rows in section 4 pass live (24 cells local and Daytona, both lineups, session-load or no claim, attended sign-in journey, image pull time) | paid key (owner) | A (starts when the key exists) |
| 8 | Flip Antigravity from pending to qualified | Core | `packages/paperclip-runner` release declaration and generated profiles, capability profile, docs, UI copy | Ledger rule met; the Core image's provider pack includes the closure without a candidate flag; no operator grant needed | 7, 3 | D |
| 9 | Run Antigravity on agent computers through ACPX | Cloud | `extensions/plugin-agent-computer/src/harnesses.ts`, `agent-computer/harness/harnesses.json`, `harness.go`, Launcher `task_credentials.go`, `configured_environment.go`, `agent-computer/runtime/select-pack.mjs`, `assemble.mjs`, `pack-manifest.mjs`, `verify*.mjs`, tests (copy Cloud #1696) | Row `antigravity`: driver `acpx`, `acpxAgent: "antigravity"`, `projectAuthProvider: "google"`, credential `task-env` with key sets `GEMINI_API_KEY` or the sign-in key, reserved prefixes `GEMINI_` and `GOOGLE_`, reserved exact key `PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET` with a negative test (a configured or project environment that sets it is refused), blocked project settings for `.gemini/settings.json` endpoint and key fields, the Runner's runtime root (so `agentHomeDirectory`) in the private task path, with a test that a concurrent task of the same agent cannot read the staged file, `/proc/<pid>/environ` or Runner memory, per-turn, closure under `provider-assets/antigravity/linux-x64` copied into the ROM. Tests pin the two tables together | 1, 2 (types); ROM content needs 8 | B (code), E (ROM) |
| 10 | Pin the Runner ROM to a Core with the flip | Cloud | `agent-computer/runner-source.lock.json`, `runner-pnpm-lock.yaml` | ROM and fleet sandbox image build; closure verified at build; ROM size, build time, boot and first-token time recorded before and after | 8, 9 | E |
| 11 | Staging policy campaign | Fleet (operator action, no code) | `env_config` campaign with the full array plus `antigravity_runtime`, canary first | Staging `/api/health` lists the exact array; picker shows Google Antigravity | 10 deployed on staging, 6 deployed | F |
| 12 | Staging acceptance (staging is the canary) | none (verification, ledger update) | ledger | First establish which environment kind staging stacks use (fleet environment defaults, `paperclipComputerDefault`). Then finish line 1, 2 and 5 on staging before any production exposure, both credential routes, Flash and Neon, Paperclip Computer and the managed sandbox; Stop; a restart mid-run resumes; disconnect revokes | 11, 4, 5 | F |
| 12 | Staging acceptance (staging is the canary) | none (verification, ledger update) | ledger | First establish which environment kind staging stacks use (fleet environment defaults, `paperclipComputerDefault`). Then finish line 1, 2 and 5 on staging before any production exposure, both credential routes, Flash and Neon, Paperclip Computer and the managed sandbox; Stop; a restart mid-run resumes; disconnect deletes the saved sign-in | 11, 4, 5 | F |
| 13 | Update the Cloud bootstrap default | Cloud | `src/fleet/cloud-harness-availability.ts`, `docs/harness-availability.md` | New stacks born before fleet policy get the same list | 12 | G |
| 14 | Production campaign | Fleet (operator action) | as 11, production | Production `/api/health` lists the array; one production run Done | 12, owner go-ahead | G |
+1
View File
@@ -1648,6 +1648,7 @@ export type {
ToolConnectionRemovalResult,
ToolConnectionRemovalSummary,
ManagedGoogleAccessRemoval,
AiSignInRemoval,
ManagedGoogleRevocationOutcome,
ConnectionGrantRevocationResult,
ToolConnectionStoredContent,
+1
View File
@@ -566,6 +566,7 @@ export type {
ToolConnectionRemovalResult,
ToolConnectionRemovalSummary,
ManagedGoogleAccessRemoval,
AiSignInRemoval,
ManagedGoogleRevocationOutcome,
ConnectionGrantRevocationResult,
ToolConnectionStoredContent,
+8
View File
@@ -429,6 +429,13 @@ export interface ToolConnectionRemovalSummary {
manageUrl: string;
} | null;
providerAccess?: ManagedGoogleAccessRemoval | null;
signInRemoval?: AiSignInRemoval | null;
}
export interface AiSignInRemoval {
provider: "google";
savedSignIn: "deleted" | "kept_shared" | "not_deleted";
providerSignIn: "still_valid";
}
export type ManagedGoogleRevocationOutcome =
@@ -452,6 +459,7 @@ export interface ManagedGoogleAccessRemoval {
export type ConnectionGrantRevocationResult = ConnectionGrant & {
providerAccess?: ManagedGoogleAccessRemoval | null;
signInRemoval?: AiSignInRemoval | null;
};
export interface ToolConnectionRemovalResult {
@@ -0,0 +1,424 @@
import { randomUUID } from "node:crypto";
import { mkdtemp, realpath, rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import express from "express";
import request from "supertest";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { and, eq, isNull, sql } from "drizzle-orm";
import {
activityLog,
companies,
companyMemberships,
companySecretBindings,
companySecrets,
connectionGrants,
routines,
routineTriggers,
createDb,
toolConnections,
userSecretDeclarations,
userSecretDefinitions,
} from "@paperclipai/db";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
const control = vi.hoisted(() => ({ failRelease: false }));
vi.mock("../services/heartbeat/provider-limit-wait.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("../services/heartbeat/provider-limit-wait.js")>();
return {
...actual,
releaseProviderLimitWaits: async (...args: Parameters<typeof actual.releaseProviderLimitWaits>) => {
if (control.failRelease) throw new Error("hold release failed");
return actual.releaseProviderLimitWaits(...args);
},
};
});
vi.mock("../services/subscription-refresh.js", () => ({ refreshSubscriptionConnection: vi.fn().mockResolvedValue(undefined) }));
import { aiConnectionService } from "../services/ai-connections.js";
import { toolAccessService } from "../services/tool-access.js";
import { secretService } from "../services/secrets.js";
import { createAntigravitySignInRemoval } from "../services/antigravity-access-removal.js";
import { toolAccessRoutes } from "../routes/tool-access.js";
import { errorHandler } from "../middleware/index.js";
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
const REFRESH_TOKEN = "antigravity-refresh-token-do-not-log";
const credential = (refreshToken = REFRESH_TOKEN) => JSON.stringify({
client_id: "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com",
client_secret: "fixture-client-secret",
refresh_token: refreshToken,
token_uri: "https://oauth2.googleapis.com/token",
scopes: ["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/aicode"],
});
const STILL_VALID = { provider: "google", savedSignIn: "deleted", providerSignIn: "still_valid" };
describeEmbeddedPostgres("deleting a saved Google Antigravity sign-in on disconnect", () => {
let db!: ReturnType<typeof createDb>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
let home = "";
beforeAll(async () => {
home = await realpath(await mkdtemp(path.join(os.tmpdir(), "paperclip-antigravity-disconnect-")));
vi.stubEnv("PAPERCLIP_HOME", home);
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-antigravity-disconnect-");
db = createDb(tempDb.connectionString, { maxConnections: 4 });
}, 30_000);
afterEach(async () => {
control.failRelease = false;
vi.restoreAllMocks();
await allowDeletion();
});
async function blockDeletion(secretId: string) {
await db.execute(sql.raw(`create or replace function test_block_secret_delete() returns trigger language plpgsql as $$
begin
if old.id = '${secretId}'::uuid and new.deleted_at is not null then raise exception 'vault unavailable'; end if;
return new;
end $$`));
await db.execute(sql.raw("drop trigger if exists test_block_secret_delete on company_secrets"));
await db.execute(sql.raw("create trigger test_block_secret_delete before update on company_secrets for each row execute function test_block_secret_delete()"));
}
async function allowDeletion() {
await db?.execute(sql.raw("drop trigger if exists test_block_secret_delete on company_secrets"));
}
afterAll(async () => {
vi.unstubAllEnvs();
await db?.$client.end({ timeout: 1 });
await tempDb?.cleanup();
if (home) await rm(home, { recursive: true, force: true });
});
function noNetwork() {
return vi.spyOn(globalThis, "fetch").mockImplementation(async (url) => {
throw new Error(`Unexpected request to ${String(url)}`);
});
}
async function company() {
const [row] = await db.insert(companies).values({
name: `Antigravity disconnect ${randomUUID()}`,
issuePrefix: `AD${randomUUID().slice(0, 6).toUpperCase()}`,
}).returning();
const userId = `antigravity-owner-${randomUUID()}`;
await db.insert(companyMemberships).values({
companyId: row!.id, principalType: "user", principalId: userId, status: "active", membershipRole: "owner",
});
return { companyId: row!.id, userId };
}
async function connectGoogle(input: { companyId: string; userId: string; ownership: "personal" | "shared"; account: string; refreshToken?: string; connectionId?: string }) {
const saved = await aiConnectionService(db).save(input.companyId, input.userId, {
provider: "google", method: "subscription", ownership: input.ownership, name: `Google ${input.account}`,
loginSessionId: "fixture", agentIds: [], allAgents: true, ...(input.connectionId ? { connectionId: input.connectionId } : {}),
}, credential(input.refreshToken), undefined, undefined, undefined, input.account);
const [grant] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, saved.grantId));
return { ...saved, secretId: grant!.credentialSecretRefs[0]!.secretId };
}
async function liveSecret(companyId: string, secretId: string) {
return (await db.select({ id: companySecrets.id }).from(companySecrets)
.where(and(eq(companySecrets.companyId, companyId), eq(companySecrets.id, secretId), isNull(companySecrets.deletedAt)))).length > 0;
}
async function grantRow(grantId: string) {
const [grant] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, grantId));
return grant!;
}
function app(companyId: string, userId: string) {
const server = express();
server.use(express.json());
server.use((req, _res, next) => {
req.actor = {
type: "board", userId, sessionId: `session-${randomUUID()}`, userName: "Owner", userEmail: null,
isInstanceAdmin: false, source: "session", companyIds: [companyId],
memberships: [{ companyId, membershipRole: "owner", status: "active" }],
};
next();
});
server.use("/api", toolAccessRoutes(db, {}));
server.use(errorHandler);
return server;
}
it("deletes the saved sign-in without calling Google, records it in plain words, and lets the owner reconnect", async () => {
const { companyId, userId } = await company();
const account = await connectGoogle({ companyId, userId, ownership: "personal", account: "alice@example.test" });
const network = noNetwork();
const response = await request(app(companyId, userId)).delete(`/api/tool-connections/${account.connectionId}/grants/${account.grantId}`);
expect(response.status).toBe(200);
expect(response.body.signInRemoval).toEqual(STILL_VALID);
expect(network).not.toHaveBeenCalled();
expect(await liveSecret(companyId, account.secretId)).toBe(false);
expect(await grantRow(account.grantId)).toMatchObject({ status: "revoked", credentialSecretRefs: [] });
const [entry] = await db.select().from(activityLog)
.where(and(eq(activityLog.companyId, companyId), eq(activityLog.action, "tool_connection.grant_revoked")));
expect(entry?.details).toMatchObject({ signInRemoval: STILL_VALID });
expect(JSON.stringify(entry?.details)).not.toContain(REFRESH_TOKEN);
const reconnected = await connectGoogle({ companyId, userId, ownership: "personal", account: "alice@example.test",
refreshToken: "alice-new-refresh-do-not-log", connectionId: account.connectionId });
expect(reconnected.grantId).toBe(account.grantId);
expect((await grantRow(account.grantId)).status).toBe("active");
expect(await liveSecret(companyId, reconnected.secretId)).toBe(true);
});
it.each([
["created by someone else", { createdByUserId: "company-admin" }],
["deleted", { deletedAt: new Date(), status: "deleted" }],
["moved to another provider", { provider: "aws_secrets_manager" }],
] as const)("refuses a personal reconnect when the saved sign-in slot was %s", async (_label, change) => {
const { companyId, userId } = await company();
const account = await connectGoogle({ companyId, userId, ownership: "personal", account: "olga@example.test" });
await toolAccessService(db).revokeConnectionGrant(account.connectionId, account.grantId, { actorType: "user", actorId: userId });
const key = `ai_${account.grantId.replaceAll("-", "_")}`;
await db.update(userSecretDefinitions).set(change).where(and(eq(userSecretDefinitions.companyId, companyId), eq(userSecretDefinitions.key, key)));
const [definition] = await db.select().from(userSecretDefinitions)
.where(and(eq(userSecretDefinitions.companyId, companyId), eq(userSecretDefinitions.key, key)));
await expect(connectGoogle({ companyId, userId, ownership: "personal", account: "olga@example.test",
refreshToken: "olga-new-refresh-do-not-log", connectionId: account.connectionId }))
.rejects.toThrow("This account's saved sign-in slot was changed outside this connection");
const values = await db.select().from(companySecrets)
.where(and(eq(companySecrets.companyId, companyId), eq(companySecrets.userSecretDefinitionId, definition!.id)));
expect(values).toEqual([]);
expect((await grantRow(account.grantId)).status).toBe("revoked");
});
it("deletes the saved sign-in when the whole connection is removed", async () => {
const { companyId, userId } = await company();
const account = await connectGoogle({ companyId, userId, ownership: "shared", account: "bob@example.test" });
const network = noNetwork();
const removed = await toolAccessService(db).archiveConnection(account.connectionId, companyId, { actorType: "user", actorId: userId });
expect(removed.removal.signInRemoval).toEqual(STILL_VALID);
expect(removed.connection.status).toBe("archived");
expect(network).not.toHaveBeenCalled();
expect(await liveSecret(companyId, account.secretId)).toBe(false);
});
it("keeps a saved sign-in that another grant still references", async () => {
const { companyId, userId } = await company();
const account = await connectGoogle({ companyId, userId, ownership: "shared", account: "carol@example.test" });
const other = await connectGoogle({ companyId, userId, ownership: "shared", account: "carol-two@example.test" });
const ref = { secretId: account.secretId, configPath: "ai.credential", required: true, versionSelector: "latest" as const };
await db.update(connectionGrants).set({ credentialSecretRefs: [ref] }).where(eq(connectionGrants.id, other.grantId));
const revoked = await toolAccessService(db).revokeConnectionGrant(account.connectionId, account.grantId, { actorType: "user", actorId: userId });
expect(revoked.signInRemoval).toEqual({ ...STILL_VALID, savedSignIn: "kept_shared" });
expect(await liveSecret(companyId, account.secretId)).toBe(true);
expect((await grantRow(other.grantId)).credentialSecretRefs).toEqual([ref]);
expect((await grantRow(account.grantId)).credentialSecretRefs).toEqual([]);
});
it("deletes the saved sign-in on connection removal when only grants of that connection reference it", async () => {
const { companyId, userId } = await company();
const account = await connectGoogle({ companyId, userId, ownership: "shared", account: "mia@example.test" });
const ref = { secretId: account.secretId, configPath: "ai.credential", required: true, versionSelector: "latest" as const };
const [second] = await db.insert(connectionGrants).values({
companyId, connectionId: account.connectionId, kind: "organization", credentialSecretRefs: [ref], createdByUserId: userId,
}).returning();
const removed = await toolAccessService(db).archiveConnection(account.connectionId, companyId, { actorType: "user", actorId: userId });
expect(removed.removal.signInRemoval).toEqual(STILL_VALID);
expect(await liveSecret(companyId, account.secretId)).toBe(false);
expect((await grantRow(second!.id)).status).toBe("revoked");
});
it("keeps the saved sign-in when a grant on another, still active connection references it", async () => {
const { companyId, userId } = await company();
const account = await connectGoogle({ companyId, userId, ownership: "shared", account: "nia@example.test" });
const other = await connectGoogle({ companyId, userId, ownership: "shared", account: "nia-two@example.test" });
const ref = { secretId: account.secretId, configPath: "ai.credential", required: true, versionSelector: "latest" as const };
await db.update(connectionGrants).set({ credentialSecretRefs: [ref] }).where(eq(connectionGrants.id, other.grantId));
const removed = await toolAccessService(db).archiveConnection(account.connectionId, companyId, { actorType: "user", actorId: userId });
expect(removed.removal.signInRemoval).toEqual({ ...STILL_VALID, savedSignIn: "kept_shared" });
expect(await liveSecret(companyId, account.secretId)).toBe(true);
});
it("reports a failed delete, keeps a retryable reference, and deletes on the next disconnect", async () => {
const { companyId, userId } = await company();
const account = await connectGoogle({ companyId, userId, ownership: "shared", account: "dana@example.test" });
await blockDeletion(account.secretId);
const failed = await toolAccessService(db).revokeConnectionGrant(account.connectionId, account.grantId, { actorType: "user", actorId: userId });
expect(failed.signInRemoval).toEqual({ ...STILL_VALID, savedSignIn: "not_deleted" });
expect(await liveSecret(companyId, account.secretId)).toBe(true);
expect((await grantRow(account.grantId)).credentialSecretRefs.map((entry) => entry.secretId)).toEqual([account.secretId]);
await allowDeletion();
const retried = await toolAccessService(db).revokeConnectionGrant(account.connectionId, account.grantId, { actorType: "user", actorId: userId });
expect(retried.signInRemoval).toEqual(STILL_VALID);
expect(await liveSecret(companyId, account.secretId)).toBe(false);
});
it("finishes a delete that failed after the sign-in was already marked deleted", async () => {
const { companyId, userId } = await company();
const account = await connectGoogle({ companyId, userId, ownership: "shared", account: "ivy@example.test" });
await db.execute(sql.raw(`create or replace function test_block_secret_purge() returns trigger language plpgsql as $$
begin
if old.id = '${account.secretId}'::uuid then raise exception 'vault unavailable'; end if;
return old;
end $$`));
await db.execute(sql.raw("create trigger test_block_secret_purge before delete on company_secrets for each row execute function test_block_secret_purge()"));
let failed;
try {
failed = await toolAccessService(db).revokeConnectionGrant(account.connectionId, account.grantId, { actorType: "user", actorId: userId });
} finally {
await db.execute(sql.raw("drop trigger if exists test_block_secret_purge on company_secrets"));
}
expect(failed.signInRemoval).toEqual({ ...STILL_VALID, savedSignIn: "not_deleted" });
const [halfDeleted] = await db.select().from(companySecrets).where(eq(companySecrets.id, account.secretId));
expect(halfDeleted?.deletedAt).not.toBeNull();
expect((await grantRow(account.grantId)).credentialSecretRefs.map((entry) => entry.secretId)).toEqual([account.secretId]);
const retried = await toolAccessService(db).revokeConnectionGrant(account.connectionId, account.grantId, { actorType: "user", actorId: userId });
expect(retried.signInRemoval).toEqual(STILL_VALID);
expect(await db.select().from(companySecrets).where(eq(companySecrets.id, account.secretId))).toEqual([]);
expect((await grantRow(account.grantId)).credentialSecretRefs).toEqual([]);
});
it("keeps a saved sign-in that another target binds", async () => {
const { companyId, userId } = await company();
const account = await connectGoogle({ companyId, userId, ownership: "shared", account: "jade@example.test" });
await db.insert(companySecretBindings).values({
companyId, secretId: account.secretId, targetType: "agent", targetId: randomUUID(), configPath: "env.GEMINI_HOME",
});
const revoked = await toolAccessService(db).revokeConnectionGrant(account.connectionId, account.grantId, { actorType: "user", actorId: userId });
expect(revoked.signInRemoval).toEqual({ ...STILL_VALID, savedSignIn: "kept_shared" });
expect(await liveSecret(companyId, account.secretId)).toBe(true);
});
it("keeps a personal saved sign-in that another target declares", async () => {
const { companyId, userId } = await company();
const account = await connectGoogle({ companyId, userId, ownership: "personal", account: "kim@example.test" });
const [secret] = await db.select().from(companySecrets).where(eq(companySecrets.id, account.secretId));
await db.insert(userSecretDeclarations).values({
companyId, userSecretDefinitionId: secret!.userSecretDefinitionId!, targetType: "agent", targetId: randomUUID(),
configPath: "env.GEMINI_HOME", envKey: "GEMINI_HOME",
});
const revoked = await toolAccessService(db).revokeConnectionGrant(account.connectionId, account.grantId, { actorType: "user", actorId: userId });
expect(revoked.signInRemoval).toEqual({ ...STILL_VALID, savedSignIn: "kept_shared" });
expect(await liveSecret(companyId, account.secretId)).toBe(true);
});
it("keeps a saved sign-in that a routine trigger uses", async () => {
const { companyId, userId } = await company();
const account = await connectGoogle({ companyId, userId, ownership: "shared", account: "lee@example.test" });
const [routine] = await db.insert(routines).values({ companyId, title: "Uses the sign-in" }).returning();
await db.insert(routineTriggers).values({ companyId, routineId: routine!.id, kind: "webhook", secretId: account.secretId });
const revoked = await toolAccessService(db).revokeConnectionGrant(account.connectionId, account.grantId, { actorType: "user", actorId: userId });
expect(revoked.signInRemoval).toEqual({ ...STILL_VALID, savedSignIn: "kept_shared" });
expect(await liveSecret(companyId, account.secretId)).toBe(true);
});
it("keeps the reference after a failed delete during connection removal so removing it again finishes", async () => {
const { companyId, userId } = await company();
const account = await connectGoogle({ companyId, userId, ownership: "shared", account: "erin@example.test" });
await blockDeletion(account.secretId);
const failed = await toolAccessService(db).archiveConnection(account.connectionId, companyId, { actorType: "user", actorId: userId });
expect(failed.removal.signInRemoval?.savedSignIn).toBe("not_deleted");
expect(await liveSecret(companyId, account.secretId)).toBe(true);
expect((await grantRow(account.grantId)).credentialSecretRefs.map((entry) => entry.secretId)).toEqual([account.secretId]);
await allowDeletion();
const retried = await toolAccessService(db).archiveConnection(account.connectionId, companyId, { actorType: "user", actorId: userId });
expect(retried.removal.signInRemoval).toEqual(STILL_VALID);
expect(await liveSecret(companyId, account.secretId)).toBe(false);
});
it("never deletes a reconnect that saved a new sign-in while the disconnect was finishing", async () => {
const { companyId, userId } = await company();
const account = await connectGoogle({ companyId, userId, ownership: "shared", account: "faye@example.test" });
const [connection] = await db.select().from(toolConnections).where(eq(toolConnections.id, account.connectionId));
const vault = secretService(db);
const removal = createAntigravitySignInRemoval(db, {
secrets: {
remove: async (...args: Parameters<typeof vault.remove>) => {
await connectGoogle({ companyId, userId, ownership: "shared", account: "faye@example.test",
refreshToken: "faye-new-refresh-do-not-log", connectionId: account.connectionId });
return vault.remove(...args);
},
},
});
const prepared = await removal.prepare(connection!, [await grantRow(account.grantId)], { removingConnection: false });
await db.update(connectionGrants).set({ status: "revoked", revokedAt: new Date(), updatedAt: new Date(Date.now() - 1_000) })
.where(eq(connectionGrants.id, account.grantId));
const result = await prepared!.send();
expect(result).toBeNull();
const grant = await grantRow(account.grantId);
expect(grant.status).toBe("active");
expect(grant.credentialSecretRefs.map((entry) => entry.secretId)).toEqual([account.secretId]);
expect(await liveSecret(companyId, account.secretId)).toBe(true);
expect(await vault.resolveSecretValue(companyId, account.secretId, "latest")).toBe(credential("faye-new-refresh-do-not-log"));
});
it("keeps the reference of a reconnect that lands while the connection is being removed", async () => {
const { companyId, userId } = await company();
const account = await connectGoogle({ companyId, userId, ownership: "shared", account: "hana@example.test" });
const replacement = await secretService(db).create(companyId, { name: `replacement-${randomUUID()}`, provider: "local_encrypted", value: credential("hana-new-refresh-do-not-log") }, { userId });
const ref = { secretId: replacement.id, configPath: "ai.credential", required: true, versionSelector: "latest" };
await db.execute(sql.raw(`create or replace function test_reconnect_on_delete() returns trigger language plpgsql as $$
begin
if old.id = '${account.secretId}'::uuid then
update connection_grants set status = 'active', revoked_at = null, credential_secret_refs = '${JSON.stringify([ref])}'::jsonb
where id = '${account.grantId}'::uuid;
end if;
return old;
end $$`));
await db.execute(sql.raw("create trigger test_reconnect_on_delete after delete on company_secrets for each row execute function test_reconnect_on_delete()"));
try {
await toolAccessService(db).archiveConnection(account.connectionId, companyId, { actorType: "user", actorId: userId });
} finally {
await db.execute(sql.raw("drop trigger if exists test_reconnect_on_delete on company_secrets"));
}
const grant = await grantRow(account.grantId);
expect(grant.status).toBe("active");
expect(grant.credentialSecretRefs).toEqual([ref]);
expect(await liveSecret(companyId, account.secretId)).toBe(false);
});
it("leaves every grant active and the sign-in saved when releasing held work fails during removal", async () => {
const { companyId, userId } = await company();
const account = await connectGoogle({ companyId, userId, ownership: "shared", account: "gail@example.test" });
control.failRelease = true;
await expect(toolAccessService(db).archiveConnection(account.connectionId, companyId, { actorType: "user", actorId: userId }))
.rejects.toThrow("hold release failed");
expect((await grantRow(account.grantId)).status).toBe("active");
expect(await liveSecret(companyId, account.secretId)).toBe(true);
control.failRelease = false;
const removed = await toolAccessService(db).archiveConnection(account.connectionId, companyId, { actorType: "user", actorId: userId });
expect(removed.removal.signInRemoval).toEqual(STILL_VALID);
expect(await liveSecret(companyId, account.secretId)).toBe(false);
});
});
@@ -260,15 +260,20 @@ describeEmbeddedPostgres("removing a Paperclip-managed Google connection", () =>
it("makes no broker call when removal fails before the grants are revoked, and the retry sends them", async () => {
const fixture = await connectManagedGmail();
const update = db.update.bind(db);
const transaction = db.transaction.bind(db);
let failedOnce = false;
vi.spyOn(db, "update").mockImplementation(((table: unknown) => {
if (table === connectionGrants && !failedOnce) {
failedOnce = true;
throw new Error("grant revocation failed");
}
return update(table as never);
}) as never);
vi.spyOn(db, "transaction").mockImplementation(((work: (tx: typeof db) => Promise<unknown>, ...rest: unknown[]) =>
transaction(async (tx) => {
const update = tx.update.bind(tx);
tx.update = ((table: unknown) => {
if (table === connectionGrants && !failedOnce) {
failedOnce = true;
throw new Error("grant revocation failed");
}
return update(table as never);
}) as never;
return work(tx as unknown as typeof db);
}, ...(rest as []))) as never);
const failed = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`);
expect(failed.status).toBe(500);
+1 -1
View File
@@ -2113,7 +2113,7 @@ function connectorEnrollmentPrincipal(req: Request): string {
action: "tool_connection.grant_revoked",
entityType: "connection_grant",
entityId: grant.id,
details: { connectionId: connection.id, kind: grant.kind, ...(grant.providerAccess ? { providerAccess: grant.providerAccess } : {}) },
details: { connectionId: connection.id, kind: grant.kind, ...(grant.providerAccess ? { providerAccess: grant.providerAccess } : {}), ...(grant.signInRemoval ? { signInRemoval: grant.signInRemoval } : {}) },
});
res.json(grant);
});
+8 -2
View File
@@ -40,7 +40,7 @@ import {
type CreateAiConnection,
type AiConnectionLoginIntent,
} from "@paperclipai/shared";
import { forbidden, notFound, unprocessable } from "../errors.js";
import { conflict, forbidden, notFound, unprocessable } from "../errors.js";
import { aiConnectionConfigurationFailure, aiConnectionCredentialNotSharedFailure } from "./ai-connection-configuration-failure.js";
import { quotaCredentialRecovery, quotaCredentialHash } from "./quota-credential-recovery.js";
import { prepareAntigravityCredentialRecovery } from "./native-runtime/antigravity-runner-credentials.js";
@@ -754,7 +754,13 @@ export function aiConnectionService(db: Db) {
{ userId },
);
else if (input.ownership === "personal") {
const definition = await secrets.createUserSecretDefinition(
const [existingDefinition] = await tx.select().from(userSecretDefinitions)
.where(and(eq(userSecretDefinitions.companyId, companyId), eq(userSecretDefinitions.key, `ai_${grantId.replaceAll("-", "_")}`)));
if (existingDefinition && (existingDefinition.createdByUserId !== userId || existingDefinition.deletedAt
|| existingDefinition.status !== "active" || existingDefinition.provider !== "local_encrypted"
|| existingDefinition.providerConfigId || existingDefinition.managedMode !== "paperclip_managed"))
throw conflict("This account's saved sign-in slot was changed outside this connection. Add the account as a new connection.");
const definition = existingDefinition ?? await secrets.createUserSecretDefinition(
companyId,
{
key: `ai_${grantId.replaceAll("-", "_")}`,
@@ -0,0 +1,156 @@
import { and, eq } from "drizzle-orm";
import {
companySecrets,
connectionGrants,
userSecretDefinitions,
type Db,
type toolConnections,
} from "@paperclipai/db";
import { aiConnectionMetadataSchema, type AiSignInRemoval } from "@paperclipai/shared";
import { logger } from "../middleware/logger.js";
import { findSecretConsumers } from "./connection-secret-consumers.js";
import { quotaCredentialRecovery } from "./quota-credential-recovery.js";
import type { secretService } from "./secrets.js";
type RemovedGrant = Pick<typeof connectionGrants.$inferSelect, "id" | "kind" | "credentialSecretRefs">;
type Connection = typeof toolConnections.$inferSelect;
type Target = { grantId: string; secretId: string; expectedVersion: number; definitionId: string | null; state: "live" | "claimed" | "gone" };
type CredentialResult = AiSignInRemoval["savedSignIn"] | "reconnected";
export type PreparedAiSignInRemoval = {
send(): Promise<AiSignInRemoval | null>;
retainedGrantIds(): string[];
};
export function isAntigravitySubscriptionConnection(connection: Pick<Connection, "connectionPurpose" | "config">): boolean {
if (connection.connectionPurpose !== "ai") return false;
const metadata = aiConnectionMetadataSchema.safeParse(connection.config?.ai);
return metadata.success && metadata.data.provider === "google" && metadata.data.method === "subscription";
}
export function summarizeAiSignInRemoval(results: AiSignInRemoval["savedSignIn"][]): AiSignInRemoval {
const savedSignIn = results.includes("not_deleted") ? "not_deleted"
: results.includes("kept_shared") ? "kept_shared"
: "deleted";
return { provider: "google", savedSignIn, providerSignIn: "still_valid" };
}
export function createAntigravitySignInRemoval(db: Db, deps: {
secrets: Pick<ReturnType<typeof secretService>, "remove">;
}) {
async function privateSlot(connection: Connection, grant: RemovedGrant, secretId: string): Promise<Target | null> {
const [row] = await db
.select({
id: companySecrets.id,
name: companySecrets.name,
scope: companySecrets.scope,
latestVersion: companySecrets.latestVersion,
deletedAt: companySecrets.deletedAt,
definitionId: userSecretDefinitions.id,
definitionKey: userSecretDefinitions.key,
})
.from(companySecrets)
.leftJoin(userSecretDefinitions, eq(userSecretDefinitions.id, companySecrets.userSecretDefinitionId))
.where(and(eq(companySecrets.companyId, connection.companyId), eq(companySecrets.id, secretId)));
if (!row) return { grantId: grant.id, secretId, expectedVersion: 0, definitionId: null, state: "gone" };
const personal = grant.kind === "user";
const claimed = row.deletedAt !== null;
const name = `ai-${grant.id}`;
const owned = personal
? row.scope === "user" && row.definitionKey === `ai_${grant.id.replaceAll("-", "_")}`
: row.scope === "company" && (row.name === name || (claimed && row.name === `${name}__deleted__${row.id}`));
if (!owned) return null;
return {
grantId: grant.id, secretId: row.id, expectedVersion: row.latestVersion,
definitionId: personal ? row.definitionId : null, state: claimed ? "claimed" : "live",
};
}
async function usedElsewhere(connection: Connection, target: Target, removingConnection: boolean): Promise<boolean> {
const held = await findSecretConsumers(db, {
companyId: connection.companyId, connectionId: connection.id, secretIds: [target.secretId],
excludeGrantIds: [target.grantId], removingConnection, liveOnly: true,
});
return held.has(target.secretId);
}
async function clearRevokedRef(connection: Connection, target: Target) {
const [grant] = await db.select({ refs: connectionGrants.credentialSecretRefs }).from(connectionGrants)
.where(and(eq(connectionGrants.id, target.grantId), eq(connectionGrants.companyId, connection.companyId), eq(connectionGrants.status, "revoked")));
if (!grant) return;
const refs = (grant.refs ?? []).filter((ref) => ref.secretId !== target.secretId);
await db.update(connectionGrants)
.set({ credentialSecretRefs: refs, updatedAt: new Date() })
.where(and(eq(connectionGrants.id, target.grantId), eq(connectionGrants.companyId, connection.companyId), eq(connectionGrants.status, "revoked")));
}
async function stillRevoked(connection: Connection, target: Target) {
const [grant] = await db.select({ status: connectionGrants.status }).from(connectionGrants)
.where(and(eq(connectionGrants.id, target.grantId), eq(connectionGrants.companyId, connection.companyId)));
return grant?.status === "revoked";
}
async function secretStillStored(connection: Connection, target: Target) {
const rows = await db.select({ id: companySecrets.id }).from(companySecrets)
.where(and(eq(companySecrets.companyId, connection.companyId), eq(companySecrets.id, target.secretId)));
return rows.length > 0;
}
async function retire(connection: Connection, target: Target, removingConnection: boolean): Promise<CredentialResult> {
if (!(await stillRevoked(connection, target))) return "reconnected";
if (await usedElsewhere(connection, target, removingConnection)) {
await clearRevokedRef(connection, target);
return "kept_shared";
}
if (target.state === "gone") {
await clearRevokedRef(connection, target);
return "deleted";
}
const removed = target.state === "claimed"
? await deps.secrets.remove(target.secretId)
: await deps.secrets.remove(target.secretId, { expectedVersion: target.expectedVersion });
if (!removed && await secretStillStored(connection, target)) {
return (await stillRevoked(connection, target)) ? "not_deleted" : "reconnected";
}
await clearRevokedRef(connection, target);
await quotaCredentialRecovery(connection.companyId, target.grantId).clear().catch(() => undefined);
return "deleted";
}
async function prepare(connection: Connection, grants: RemovedGrant[], scope: { removingConnection: boolean }): Promise<PreparedAiSignInRemoval | null> {
if (!isAntigravitySubscriptionConnection(connection)) return null;
const targets: Target[] = [];
for (const grant of grants) {
const ref = (grant.credentialSecretRefs ?? []).find((entry) => entry.configPath === "ai.credential");
if (!ref) continue;
const target = await privateSlot(connection, grant, ref.secretId);
if (target) targets.push(target);
}
if (targets.length === 0) return null;
const retained: string[] = [];
return {
retainedGrantIds: () => [...retained],
send: async () => {
const results: AiSignInRemoval["savedSignIn"][] = [];
for (const target of targets) {
let result: CredentialResult;
try {
result = await retire(connection, target, scope.removingConnection);
} catch (error) {
logger.warn(
{ companyId: connection.companyId, connectionId: connection.id, errorName: error instanceof Error ? error.name : typeof error },
"Could not delete a disconnected Google sign-in",
);
result = "not_deleted";
}
if (result === "reconnected") continue;
if (result === "not_deleted") retained.push(target.grantId);
results.push(result);
}
return results.length > 0 ? summarizeAiSignInRemoval(results) : null;
},
};
}
return { prepare };
}
@@ -0,0 +1,69 @@
import { and, eq, inArray, ne, sql, type SQL } from "drizzle-orm";
import {
companySecretBindings,
companySecrets,
connectionGrants,
toolConnections,
userSecretDeclarations,
type Db,
} from "@paperclipai/db";
import { connectionSecretsUsedByOtherConsumers } from "./connection-credentials.js";
export type SecretConsumerScope = {
companyId: string;
connectionId: string;
secretIds: readonly string[];
excludeGrantIds?: readonly string[];
removingConnection: boolean;
liveOnly: boolean;
};
export async function findSecretConsumers(db: Db, scope: SecretConsumerScope): Promise<Set<string>> {
const wanted = [...new Set(scope.secretIds.filter((id) => typeof id === "string" && id.length > 0))];
if (wanted.length === 0) return new Set();
const wantedSet = new Set(wanted);
const held = await connectionSecretsUsedByOtherConsumers(db, wanted);
const excludedGrants = new Set(scope.excludeGrantIds ?? []);
const grantFilters: SQL[] = [eq(connectionGrants.companyId, scope.companyId)];
if (scope.liveOnly) grantFilters.push(ne(connectionGrants.status, "revoked"));
if (scope.removingConnection) grantFilters.push(ne(connectionGrants.connectionId, scope.connectionId));
const grants = await db.select({ id: connectionGrants.id, refs: connectionGrants.credentialSecretRefs })
.from(connectionGrants).where(and(...grantFilters));
for (const row of grants) {
if (excludedGrants.has(row.id)) continue;
for (const ref of row.refs ?? []) if (wantedSet.has(ref.secretId)) held.add(ref.secretId);
}
const connectionFilters: SQL[] = [eq(toolConnections.companyId, scope.companyId)];
if (scope.liveOnly) connectionFilters.push(ne(toolConnections.status, "archived"));
if (scope.removingConnection) connectionFilters.push(ne(toolConnections.id, scope.connectionId));
const connections = await db.select({ refs: toolConnections.credentialRefs, secretRefs: toolConnections.credentialSecretRefs })
.from(toolConnections).where(and(...connectionFilters));
for (const row of connections) {
for (const ref of [...(row.refs ?? []), ...(row.secretRefs ?? [])]) if (wantedSet.has(ref.secretId)) held.add(ref.secretId);
}
const bindings = await db.select({ secretId: companySecretBindings.secretId }).from(companySecretBindings)
.where(and(
eq(companySecretBindings.companyId, scope.companyId),
inArray(companySecretBindings.secretId, wanted),
sql`not (${companySecretBindings.targetType} = 'tool_connection' and ${companySecretBindings.targetId} = ${scope.connectionId})`,
));
for (const row of bindings) held.add(row.secretId);
const definitions = await db.select({ id: companySecrets.id, definitionId: companySecrets.userSecretDefinitionId })
.from(companySecrets)
.where(and(eq(companySecrets.companyId, scope.companyId), inArray(companySecrets.id, wanted)));
const definitionIds = [...new Set(definitions.flatMap((row) => row.definitionId ? [row.definitionId] : []))];
if (definitionIds.length > 0) {
const declared = await db.select({ definitionId: userSecretDeclarations.userSecretDefinitionId }).from(userSecretDeclarations)
.where(and(
inArray(userSecretDeclarations.userSecretDefinitionId, definitionIds),
sql`not (${userSecretDeclarations.targetType} = 'tool_connection' and ${userSecretDeclarations.targetId} = ${scope.connectionId})`,
));
const shared = new Set(declared.map((row) => row.definitionId));
for (const row of definitions) if (row.definitionId && shared.has(row.definitionId)) held.add(row.id);
}
return held;
}
@@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import type { Db } from "@paperclipai/db";
const resolveConnectionGrantSecret = vi.hoisted(() => vi.fn());
vi.mock("../../connection-credentials.js", () => ({ resolveConnectionGrantSecret }));
vi.mock("../../connection-credentials.js", () => ({ resolveConnectionGrantSecret, connectionSecretsUsedByOtherConsumers: async () => new Set<string>() }));
import { createManagedGoogleAccessRemoval, summarizeManagedGoogleAccess } from "./google-access-removal.js";
import type { PaperclipCloudConnector } from "../../paperclip-cloud-connector.js";
@@ -1,9 +1,10 @@
import type { Db } from "@paperclipai/db";
import { companySecrets, connectionGrants, googlePendingRevocations, toolAccessAuditEvents, toolConnections } from "@paperclipai/db";
import { and, eq, inArray, isNull, ne } from "drizzle-orm";
import { and, eq, inArray, isNull } from "drizzle-orm";
import type { ManagedGoogleAccessRemoval, ManagedGoogleRevocationOutcome } from "@paperclipai/shared";
import { logger } from "../../../middleware/logger.js";
import { resolveConnectionGrantSecret } from "../../connection-credentials.js";
import { findSecretConsumers } from "../../connection-secret-consumers.js";
import { isPaperclipCloudConnectorStrategy, type PaperclipCloudConnector } from "../../paperclip-cloud-connector.js";
import { managedConnectorConsentSubject, managedConnectorProfile } from "../oauth/client-settings.js";
import { oauthConfig } from "../oauth/metadata.js";
@@ -189,25 +190,10 @@ export function createManagedGoogleAccessRemoval(db: Db, deps: {
secretIds: string[],
removingConnection: boolean,
): Promise<Set<string>> {
if (secretIds.length === 0) return new Set();
const wanted = new Set(secretIds);
const removedGrantIds = new Set(grants.map((grant) => grant.id));
const held = new Set<string>();
const liveGrants = await db.select({ id: connectionGrants.id, connectionId: connectionGrants.connectionId, refs: connectionGrants.credentialSecretRefs })
.from(connectionGrants)
.where(and(eq(connectionGrants.companyId, connection.companyId), ne(connectionGrants.status, "revoked")));
for (const row of liveGrants) {
if (removedGrantIds.has(row.id) || (removingConnection && row.connectionId === connection.id)) continue;
for (const ref of row.refs ?? []) if (wanted.has(ref.secretId)) held.add(ref.secretId);
}
const liveConnections = await db.select({ id: toolConnections.id, refs: toolConnections.credentialRefs, secretRefs: toolConnections.credentialSecretRefs })
.from(toolConnections)
.where(and(eq(toolConnections.companyId, connection.companyId), ne(toolConnections.status, "archived")));
for (const row of liveConnections) {
if (removingConnection && row.id === connection.id) continue;
for (const ref of [...(row.refs ?? []), ...(row.secretRefs ?? [])]) if (wanted.has(ref.secretId)) held.add(ref.secretId);
}
return held;
return findSecretConsumers(db, {
companyId: connection.companyId, connectionId: connection.id, secretIds,
excludeGrantIds: grants.map((grant) => grant.id), removingConnection, liveOnly: true,
});
}
async function deleteSentSecrets(
@@ -12,6 +12,7 @@ import { agents, connectionGrantMembers, connectionGrantDelegations, connectionG
import { badRequest, conflict, forbidden, notFound, unprocessable } from "../../../errors.js";
import type { PaperclipCloudConnector } from "../../paperclip-cloud-connector.js";
import { createManagedGoogleAccessRemoval } from "./google-access-removal.js";
import { createAntigravitySignInRemoval } from "../../antigravity-access-removal.js";
import { contentDeletionActor, deleteGoogleContentWhenAccessEnds } from "./google-content-retention.js";
import type { ConnectionGrantRevocationResult } from "@paperclipai/shared";
import { vercelTokenRequest, type VercelConnectClient } from "../../vercel-connect.js";
@@ -30,6 +31,7 @@ type GrantDependencies = {
export function createConnectionGrants(db: Db, { getConnectionRow, assertSecretRefs, vercelConnect, currentCloudConnector, secrets }: GrantDependencies) {
const managedGoogleAccess = createManagedGoogleAccessRemoval(db, { currentCloudConnector });
const antigravitySignIn = createAntigravitySignInRemoval(db, { secrets });
return {
listConnectionGrants: async (idOrUid: string, companyId?: string) => {
const connection = await getConnectionRow(idOrUid, companyId);
@@ -518,6 +520,7 @@ replaceConnectionGrantMembers: async (
removingConnection: false,
removeSecret: (secretId, expectedVersion) => secrets.remove(secretId, { expectedVersion }),
});
const signInRemoval = await antigravitySignIn.prepare(connection, [currentGrant], { removingConnection: false });
if (
connection.credentialSource === "vercel_connect" &&
connection.externalCredential
@@ -612,6 +615,7 @@ replaceConnectionGrantMembers: async (
});
if (!grant) throw notFound("Connection grant not found");
const providerAccess = providerAccessRemoval ? await providerAccessRemoval.send() : null;
const signIn = signInRemoval ? await signInRemoval.send() : null;
await db.insert(toolAccessAuditEvents).values({
companyId: connection.companyId,
connectionId: connection.id,
@@ -623,7 +627,7 @@ replaceConnectionGrantMembers: async (
details: { grantId: grant.id, kind: grant.kind, providerRevocation },
});
releasedWaitPublications.forEach(publishActivity);
return { ...toConnectionGrant(grant), ...(providerAccess ? { providerAccess } : {}) };
return { ...toConnectionGrant(grant), ...(providerAccess ? { providerAccess } : {}), ...(signIn ? { signInRemoval: signIn } : {}) };
}
};
}
@@ -4,6 +4,9 @@ import { notifyChatEndpointWork } from "../../chat-work-notifications.js";
import { notifyToolConnectionHealth } from "../../tool-connection-health-notifications.js";
import { toConnection } from "./projection.js";
import { createManagedGoogleAccessRemoval } from "./google-access-removal.js";
import { createAntigravitySignInRemoval } from "../../antigravity-access-removal.js";
import { publishActivity } from "../../activity-log.js";
import type { ActivityPublication } from "../../../types/activity-publication.js";
import { contentDeletionActor, deleteGoogleContentWhenAccessEnds } from "./google-content-retention.js";
import type { PaperclipCloudConnector } from "../../paperclip-cloud-connector.js";
import { actorBinding, connectionActorUserId } from "../actor.js";
@@ -16,16 +19,16 @@ import { chatEndpoints } from "@paperclipai/db";
import { isBrowserUseConnection } from "../../browser-use-client.js";
import { browserUseService } from "../../browser-use.js";
import { emitConnectionUpdated } from "../../connector-telemetry.js";
import { and, eq, inArray, isNull, ne, sql } from "drizzle-orm";
import { and, eq, inArray, isNull, ne, notInArray, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { connectionGrants, connectionTokenIssuances, companySecretBindings, companySecrets, userSecretDefinitions, userSecretDeclarations, toolApplications, toolCatalogEntries, toolConnectionInstalls, toolConnections, toolOauthStates, toolGatewaySessions, toolMcpGateways, toolMcpGatewayTokens, toolProfileBindings, toolProfileEntries, toolProfiles, toolRuntimeSlots } from "@paperclipai/db";
import { connectionGrants, connectionTokenIssuances, companySecretBindings, companySecrets, userSecretDefinitions, toolApplications, toolCatalogEntries, toolConnectionInstalls, toolConnections, toolOauthStates, toolGatewaySessions, toolMcpGateways, toolMcpGatewayTokens, toolProfileBindings, toolProfileEntries, toolProfiles, toolRuntimeSlots } from "@paperclipai/db";
import type { ToolConnectionRemovalResult, ToolConnectionRemovalSummary } from "@paperclipai/shared";
import { notFound } from "../../../errors.js";
import { logger } from "../../../middleware/logger.js";
import { releaseProviderLimitWaits } from "../../heartbeat/provider-limit-wait.js";
import { forgetMcpHttpSessions } from "../../mcp-http.js";
import { secretService } from "../../secrets.js";
import { connectionSecretsUsedByOtherConsumers } from "../../connection-credentials.js";
import { findSecretConsumers } from "../../connection-secret-consumers.js";
import { createToolRuntimeSupervisor } from "../../tool-runtime-supervisor.js";
import { vercelConnectIntegrationStatus, vercelTokenRequest, type VercelConnectClient } from "../../vercel-connect.js";
@@ -91,6 +94,7 @@ type RemovalDependencies = {
export function createConnectionRemoval(db: Db, { options, secrets, runtimeSupervisor, vercelConnect, currentCloudConnector, getConnectionRow }: RemovalDependencies) {
const managedGoogleAccess = createManagedGoogleAccessRemoval(db, { currentCloudConnector });
const antigravitySignIn = createAntigravitySignInRemoval(db, { secrets });
/**
* Split the secrets a connection points at into the ones it owns outright and
* the ones another consumer still depends on.
@@ -139,63 +143,15 @@ async function classifyConnectionSecrets(
);
const byId = new Map(secretRows.map((row) => [row.id, row]));
const referencedElsewhere = await connectionSecretsUsedByOtherConsumers(db, unique);
const foreignBindings = await db
.select({ secretId: companySecretBindings.secretId })
.from(companySecretBindings)
.where(
and(
eq(companySecretBindings.companyId, connection.companyId),
inArray(companySecretBindings.secretId, unique),
sql`not (${companySecretBindings.targetType} = 'tool_connection' and ${companySecretBindings.targetId} = ${connection.id})`,
),
);
for (const row of foreignBindings) referencedElsewhere.add(row.secretId);
// Bindings are the authority, but read the sibling refs too: a row written
// before `syncCredentialBindings` existed — or by hand — can reference a
// secret with no binding to prove it.
const siblingConnections = await db
.select({
credentialRefs: toolConnections.credentialRefs,
credentialSecretRefs: toolConnections.credentialSecretRefs,
})
.from(toolConnections)
.where(
and(
eq(toolConnections.companyId, connection.companyId),
ne(toolConnections.id, connection.id),
),
);
for (const row of siblingConnections) {
for (const ref of row.credentialRefs ?? [])
referencedElsewhere.add(ref.secretId);
for (const ref of row.credentialSecretRefs ?? [])
referencedElsewhere.add(ref.secretId);
}
const siblingGrants = await db
.select({ credentialSecretRefs: connectionGrants.credentialSecretRefs })
.from(connectionGrants)
.where(
and(
eq(connectionGrants.companyId, connection.companyId),
ne(connectionGrants.connectionId, connection.id),
),
);
for (const row of siblingGrants) {
for (const ref of row.credentialSecretRefs ?? [])
referencedElsewhere.add(ref.secretId);
}
const referencedElsewhere = await findSecretConsumers(db, {
companyId: connection.companyId, connectionId: connection.id, secretIds: unique,
removingConnection: true, liveOnly: false,
});
const definitionIds = secretRows.flatMap((row) => row.userSecretDefinitionId ? [row.userSecretDefinitionId] : []);
const definitions = definitionIds.length ? await db.select().from(userSecretDefinitions)
.where(and(eq(userSecretDefinitions.companyId, connection.companyId), inArray(userSecretDefinitions.id, definitionIds))) : [];
const dedicatedDefinitions = new Set(definitions.filter((row) => row.key.startsWith(CONNECTION_OWNED_SECRET_KEY_PREFIX) || row.key.startsWith(`tool_oauth.${connection.id}.`)).map((row) => row.id));
const foreignDeclarations = definitionIds.length ? await db.select().from(userSecretDeclarations).where(and(
inArray(userSecretDeclarations.userSecretDefinitionId, definitionIds),
sql`not (${userSecretDeclarations.targetType} = 'tool_connection' and ${userSecretDeclarations.targetId} = ${connection.id})`,
)) : [];
const sharedDefinitions = new Set(foreignDeclarations.map((row) => row.userSecretDefinitionId));
const owned: string[] = [];
const retained: string[] = [];
for (const secretId of unique) {
@@ -208,7 +164,7 @@ async function classifyConnectionSecrets(
continue;
}
const dedicated = row.scope === "user" && row.userSecretDefinitionId
? dedicatedDefinitions.has(row.userSecretDefinitionId) && !sharedDefinitions.has(row.userSecretDefinitionId)
? dedicatedDefinitions.has(row.userSecretDefinitionId)
: row.scope === "company" && row.userSecretDefinitionId === null
&& row.key.startsWith(CONNECTION_OWNED_SECRET_KEY_PREFIX);
if (dedicated && !referencedElsewhere.has(secretId)) owned.push(secretId);
@@ -294,8 +250,10 @@ async function removeConnection(
if (await secrets.remove(secretId, { expectedVersion })) secretsRevoked += 1;
},
});
if (grantsToRevoke.length > 0) {
await db
const signInRemoval = await antigravitySignIn.prepare(connection, grantRows, { removingConnection: true });
const releasedWaitPublications: ActivityPublication[] = [];
await db.transaction(async (tx) => {
if (grantsToRevoke.length > 0) await tx
.update(connectionGrants)
.set({
status: "revoked",
@@ -313,16 +271,16 @@ async function removeConnection(
grantsToRevoke.map((row) => row.id),
),
);
}
// Usage limits reported on a removed account no longer hold work. This
// runs before any provider call and covers grants an earlier attempt
// already revoked, so a failed release fails the removal and its retry
// releases them.
await releaseProviderLimitWaits(db, {
companyId: connection.companyId, reason: "ai_connection_revoked",
grantIds: grantRows.map((row) => row.id),
...(binding.actorType && binding.actorId ? { actor: { actorType: binding.actorType, actorId: binding.actorId } } : {}),
// Usage limits reported on a removed account no longer hold work. The
// release commits with the revocation, so waiting work never outlives it.
await releaseProviderLimitWaits(tx as unknown as Db, {
companyId: connection.companyId, reason: "ai_connection_revoked",
grantIds: grantRows.map((row) => row.id),
publications: releasedWaitPublications,
...(binding.actorType && binding.actorId ? { actor: { actorType: binding.actorType, actorId: binding.actorId } } : {}),
});
});
releasedWaitPublications.forEach(publishActivity);
let externalCredentialCleanup: ToolConnectionRemovalSummary["externalCredentialCleanup"] =
null;
if (
@@ -624,6 +582,8 @@ async function removeConnection(
}
const providerAccess = providerAccessRemoval ? await providerAccessRemoval.send() : null;
const signIn = signInRemoval ? await signInRemoval.send() : null;
const retainedGrantIds = signInRemoval?.retainedGrantIds() ?? [];
// Only now, with every access path closed, revoke the credentials. Each
// `secrets.remove` marks the row deleted before it calls the provider, so a
@@ -669,6 +629,8 @@ async function removeConnection(
and(
eq(connectionGrants.companyId, connection.companyId),
eq(connectionGrants.connectionId, connection.id),
eq(connectionGrants.status, "revoked"),
...(retainedGrantIds.length > 0 ? [notInArray(connectionGrants.id, retainedGrantIds)] : []),
),
);
}
@@ -694,6 +656,7 @@ async function removeConnection(
applicationArchived: archived.applicationArchived,
externalCredentialCleanup,
...(providerAccess ? { providerAccess } : {}),
...(signIn ? { signInRemoval: signIn } : {}),
},
};
}
@@ -278,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": "87b4a095d07b2eace7cc8dfc44d6db9631012dd6",
"packages/shared/src/index.ts": "f0c8e72ac411fad0f9c090f68ea9590d15316d94",
"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",
@@ -438,7 +438,7 @@
"packages/shared/src/types/inbox-agent-policy.ts": "cb9d41d9681e80b834889268ad96015a39df92f6",
"packages/shared/src/types/inbox-dismissal.ts": "58fb7013847396ac9971eb5799dd0bf0486e0371",
"packages/shared/src/types/inbox-mine.ts": "1d302b531d34842189704abd2f75f8743d09490d",
"packages/shared/src/types/index.ts": "60366f789182ba3a4fb6895f91454ec386988496",
"packages/shared/src/types/index.ts": "e566109a838995a8b14cb2a4d47394aea0b9a752",
"packages/shared/src/types/instance.ts": "ddfef2455723757a5ecffaf3bab56ec47c287267",
"packages/shared/src/types/issue-tree-control.ts": "75489fffd491b8350b05caf57d7796419797d9df",
"packages/shared/src/types/issue.ts": "fe78765782a50faf24e91e76e39846a4ace2cfc5",
@@ -462,7 +462,7 @@
"packages/shared/src/types/tailscale.ts": "d02a917945d7779009a2dea4c4b535e9478e0680",
"packages/shared/src/types/task-workspace.ts": "a23afa13d2cb58dc2eb72692ed28c16ed6fb84fb",
"packages/shared/src/types/teams-catalog.ts": "632fe75f8e5a4cfc455843c2a1a2daff28a022be",
"packages/shared/src/types/tool-access.ts": "f1f8dfb778e19835c79b808bfc9730663aa411ee",
"packages/shared/src/types/tool-access.ts": "e517c0282ce65664eb281eafa8534c642a5943a8",
"packages/shared/src/types/user-profile.ts": "1ac26e033a79fab21dc267fd983959814c8b680f",
"packages/shared/src/types/voice-sessions.ts": "95e3b62cdd51f62290e68536728ddd7297bc0459",
"packages/shared/src/types/work-product.ts": "26f9129f606a207ce7a218ccef40f96747283086",
@@ -1,4 +1,6 @@
import { heartbeatsApi } from "@/api/heartbeats";
import { useToastActions } from "@/context/ToastContext";
import { aiSignInRemovalNotice } from "@/features/connections/googleAccessRemoval";
import { Button } from "@/components/ui/button";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { aiConnectionsApi } from "@/api/ai-connections";
@@ -62,10 +64,15 @@ export function ManagedAiConnectionDetails({
const accountsView = useQueryView(accounts);
const grantsView = useQueryView(grants);
const refresh = () => client.invalidateQueries();
const { pushToast } = useToastActions();
const revoke = useMutation({
mutationFn: (id: string) =>
toolsApi.revokeConnectionGrant(connection.id, id),
onSuccess: refresh,
onSuccess: (revoked) => {
const notice = aiSignInRemovalNotice(revoked.signInRemoval);
if (notice) pushToast({ title: "Account disconnected", body: notice.body, tone: notice.tone, ...(notice.action ? { action: notice.action } : {}) });
return refresh();
},
});
const stop = useMutation({
mutationFn: (id: string) => heartbeatsApi.cancel(id),
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { connectionRemovalToast, GOOGLE_THIRD_PARTY_ACCESS_URL, googleAccessRemovalNotice, googleAccessRetrySummary } from "./googleAccessRemoval";
import { aiSignInRemovalNotice, connectionRemovalToast, GOOGLE_THIRD_PARTY_ACCESS_URL, googleAccessRemovalNotice, googleAccessRetrySummary } from "./googleAccessRemoval";
describe("googleAccessRemovalNotice", () => {
afterEach(() => vi.unstubAllGlobals());
@@ -65,3 +65,37 @@ describe("googleAccessRemovalNotice", () => {
expect(googleAccessRetrySummary("google_access_not_ended", { result: "gave_up" })).toBe("Paperclip stopped trying to end its access at Google without a confirmation");
});
});
describe("aiSignInRemovalNotice", () => {
it("says nothing when no saved Google sign-in was involved", () => {
expect(aiSignInRemovalNotice(undefined)).toBeNull();
expect(aiSignInRemovalNotice(null)).toBeNull();
});
it("says the saved sign-in was deleted and stays valid at Google", () => {
const notice = aiSignInRemovalNotice({ provider: "google", savedSignIn: "deleted", providerSignIn: "still_valid" });
expect(notice?.tone).toBe("info");
expect(notice?.body).toBe("Paperclip deleted its saved Google sign-in. The sign-in stays valid at Google until you remove it in your Google account's third-party connections. Removing it there also signs this Google account out of Antigravity everywhere.");
expect(notice?.action?.label).toBe("Open Google account connections");
});
it("says a shared sign-in was kept", () => {
expect(aiSignInRemovalNotice({ provider: "google", savedSignIn: "kept_shared", providerSignIn: "still_valid" })?.body)
.toMatch(/^Another connection still uses this saved Google sign-in, so Paperclip kept it\./);
});
it("warns when the saved sign-in could not be deleted", () => {
expect(aiSignInRemovalNotice({ provider: "google", savedSignIn: "not_deleted", providerSignIn: "still_valid" })).toEqual({
tone: "warn",
body: "Paperclip couldn't delete its saved Google sign-in. Disconnect again to retry.",
});
});
it("adds the notice to a connection removal toast", () => {
const toast = connectionRemovalToast({
title: "Connection deleted", body: "Google is no longer available to agents.", providerAccess: null,
signInRemoval: { provider: "google", savedSignIn: "not_deleted", providerSignIn: "still_valid" },
});
expect(toast).toMatchObject({ tone: "warn", body: "Google is no longer available to agents. Paperclip couldn't delete its saved Google sign-in. Disconnect again to retry." });
});
});
@@ -1,4 +1,4 @@
import type { ManagedGoogleAccessRemoval } from "@paperclipai/shared";
import type { AiSignInRemoval, ManagedGoogleAccessRemoval } from "@paperclipai/shared";
import type { ToastAction, ToastInput, ToastTone } from "../../context/ToastContext";
export const GOOGLE_THIRD_PARTY_ACCESS_URL = "https://myaccount.google.com/connections";
@@ -51,12 +51,28 @@ export function googleAccessRemovalNotice(
};
}
export function aiSignInRemovalNotice(removal: AiSignInRemoval | null | undefined): GoogleAccessRemovalNotice | null {
if (removal?.provider !== "google") return null;
if (removal.savedSignIn === "not_deleted") {
return { tone: "warn", body: "Paperclip couldn't delete its saved Google sign-in. Disconnect again to retry." };
}
const kept = removal.savedSignIn === "kept_shared"
? "Another connection still uses this saved Google sign-in, so Paperclip kept it."
: "Paperclip deleted its saved Google sign-in.";
return {
tone: "info",
body: `${kept} The sign-in stays valid at Google until you remove it in your Google account's third-party connections. Removing it there also signs this Google account out of Antigravity everywhere.`,
action: openGoogleAccountConnections,
};
}
export function connectionRemovalToast(input: {
title: string;
body: string;
providerAccess: ManagedGoogleAccessRemoval | null | undefined;
signInRemoval?: AiSignInRemoval | null;
}): ToastInput {
const notice = googleAccessRemovalNotice(input.providerAccess);
const notice = googleAccessRemovalNotice(input.providerAccess) ?? aiSignInRemovalNotice(input.signInRemoval);
return {
title: input.title,
body: notice ? `${input.body} ${notice.body}` : input.body,
+1 -1
View File
@@ -202,7 +202,7 @@ export function Connections() {
const body = target.remainingConnectionCount > 0
? `${target.appName} still has ${target.remainingConnectionCount} active ${target.remainingConnectionCount === 1 ? "connection" : "connections"} available to agents.`
: `${target.appName} is no longer available to agents and its credentials are deleted. Connecting it again needs a new sign-in or key.`;
pushToast(connectionRemovalToast({ title: "Connection deleted", body, providerAccess: removed?.removal?.providerAccess }));
pushToast(connectionRemovalToast({ title: "Connection deleted", body, providerAccess: removed?.removal?.providerAccess, signInRemoval: removed?.removal?.signInRemoval }));
setConnectionToDelete(null);
},
onError: (error) =>
+4 -4
View File
@@ -2,7 +2,7 @@ import { AgentAvatar } from "@/components/AgentAvatar";
import { useEffect, useMemo, useState } from "react";
import { useInfiniteQuery, useQuery } from "@tanstack/react-query";
import { Download, ScrollText, ShieldAlert } from "lucide-react";
import type { Agent, CaseWorkflowTransition, ManagedGoogleAccessRemoval } from "@paperclipai/shared";
import type { Agent, AiSignInRemoval, CaseWorkflowTransition, ManagedGoogleAccessRemoval } from "@paperclipai/shared";
import { Link, useCaseHref } from "@/lib/router";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
@@ -28,7 +28,7 @@ import { describeError } from "@/api/errors";
import { QueryErrorState, useQueryView } from "@/components/QueryView";
import { useToastActions } from "@/context/ToastContext";
import { instanceSettingsApi } from "@/api/instanceSettings";
import { googleAccessRemovalNotice } from "@/features/connections/googleAccessRemoval";
import { aiSignInRemovalNotice, googleAccessRemovalNotice } from "@/features/connections/googleAccessRemoval";
const PAGE_SIZE = 50;
const ALL = "__all";
@@ -211,10 +211,10 @@ function AuditEntityNode({ record }: { record: AuditActionRecord }) {
function auditOutcome(record: AuditActionRecord): string | null {
if (record.action === "tool_connection.archived" || record.action === "tool_connection.grant_revoked") {
return googleAccessRemovalNotice(
return (googleAccessRemovalNotice(
record.details?.providerAccess as ManagedGoogleAccessRemoval | undefined,
record.action === "tool_connection.grant_revoked" ? "credentials" : "connection",
)?.body ?? null;
) ?? aiSignInRemovalNotice(record.details?.signInRemoval as AiSignInRemoval | undefined))?.body ?? null;
}
return formatActivityOutcome(record.action, record.details);
}