feat(antigravity): add hosted Google loopback-relay sign-in (#22932)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Google Antigravity supports Google account sign-in through Paperclip
Runner's pinned, isolated `agy_acp_server.par` process.
> - On `authenticated + public` deployments (including hosted Cloud
instances), `supportsLocalAiLogin` returns `false`, and the user's
browser cannot directly reach the server's `127.0.0.1:<ephemeral_port>`
loopback callback listener.
> - Because `client_secret` lives only inside `agy_acp_server.par` and
uses PKCE with a one-shot `127.0.0.1` listener, hosted deployments need
an authenticated relay path instead of an anonymous callback route or
extracted secret.
> - This pull request adds an authenticated loopback-relay flow across
Runner, server policy/routes/redaction, and the UI so users on hosted
deployments can sign in with Google, copy the `127.0.0.1` redirect URL
from their address bar, and paste it to complete authentication.
> - The benefit is that Google Antigravity subscription sign-in works on
hosted public deployments while keeping Claude, OpenAI, and Grok
server-host login disabled and preventing SSRF, secret leakage, or
cross-tenant access.

## Linked Issues or Issue Description

Refs #22923

**Subsystem affected**
Cross-cutting (packages/paperclip-runner, packages/shared, server/, ui/)

**Problem or motivation**
Google Antigravity sign-in launches Paperclip's pinned, isolated
`agy_acp_server.par` closure, which opens a one-shot
`127.0.0.1:<ephemeral_port>` OAuth callback listener. On hosted
`authenticated + public` deployments, server-host login routes are
blocked and the user's browser cannot connect to the server's loopback
interface, so users cannot sign in with a Google account on Cloud or
remote instances.

**Proposed solution**
Add an authenticated loopback-relay flow:
1. Runner exposes a single-use `submitRedirect(rawRedirectUrl)` handler
on `AntigravityBrowserLoginState` that validates the pasted URL (length,
printable ASCII, `http://127.0.0.1:<expectedPort>/`, no
credentials/hash, no duplicate `state`/`code`, no `error` param,
`timingSafeEqual` state check, bounded 5-attempt bad-paste cap, SHA-256
reused-code tracking) and issues an SSRF-proof reconstructed `GET` to
`expectedRedirect.origin` with `redirect: "manual"`.
2. Server adds `supportsHostedGoogleAiLogin` (exposed on `/api/health`
as `hostedGoogleAiLoginSupported`), permits Google through the
authenticated `/api/companies/:companyId/ai-connections/local/*` routes
while keeping `anthropic`/`openai`/`xai` blocked on public deployments,
accepts up to 4096-character redirect URLs on `/code` while preserving
Claude's 512-byte limit, runs the loopback relay outside DB
transactions, falls back cleanly when a stack has no active `local`
environment row, and redacts `browserCode`/`redirectUrl` and marks
`/code` secret-sensitive.
3. UI enables Google sign-in for `antigravity_runtime` on non-local
environments when `hostedGoogleAiLoginSupported` is true, renders the
external Google sign-in link plus plain-language `127.0.0.1` copy/paste
instructions with analytics masking/no-capture markers, and triggers an
immediate status check after submission.

**Alternatives considered**
- Adding an anonymous public OAuth callback route on the server:
rejected because it widens the unauthenticated attack surface and cannot
change the loopback `redirect_uri` bound inside `agy_acp_server.par`.
- Extracting Google OAuth `client_secret` out of `agy_acp_server.par`:
rejected by policy; secrets remain owned solely inside the pinned
closure.

## What Changed

- `packages/paperclip-runner/src/drivers/acpx/antigravity-auth.ts` &
`packages/paperclip-runner/src/index.ts` &
`server/src/vendor/paperclip-runner/index.ts`: add single-use
`submitRedirect` on `AntigravityBrowserLoginState` with strict
validation, `timingSafeEqual` state verification, 5-attempt cap, bounded
SHA-256 reused-code set, and SSRF-proof loopback relay.
- `packages/shared/src/ai-connections.ts`: add
`LOCAL_AI_LOGIN_CODE_MAX_LENGTH` (4096), `localAiLoginCodeSchema`, and
`submitLocalAiLoginCodeSchema` while preserving Claude's 512-byte
`BROWSER_CODE_MAX_LENGTH` and `browserCodeSchema`.
- `server/src/services/local-ai-login-policy.ts` &
`server/src/routes/health.ts`: add `supportsHostedGoogleAiLogin` and
expose `hostedGoogleAiLoginSupported` on `/api/health`.
- `server/src/services/local-ai-browser-login.ts`,
`server/src/services/local-ai-login.ts`,
`server/src/routes/ai-connections.ts`: permit hosted Google sign-in on
authenticated public deployments while keeping Claude/OpenAI/Grok
blocked; enforce `Cache-Control: no-store`, owner/company/active/expiry
checks, and Claude's 512-byte cap; run Google `submitRedirect` outside
any DB transaction; fall back cleanly to an active environment or
savepoint-wrapped `ensureLocalEnvironment` when no active `local`
environment row exists.
- `server/src/middleware/redact-sensitive.ts`,
`server/src/middleware/http-log-redaction.ts`,
`server/src/middleware/http-log-policy.ts`: redact
`browserCode`/`redirectUrl`/`redirect_url` unconditionally and classify
`/api/companies/:companyId/ai-connections/local/attempts/:sessionId/code`
as secret-sensitive (`local_ai_login_code`).
- `ui/src/api/health.ts`,
`ui/src/components/ai-connections/useLocalAiLogin.ts`,
`ui/src/components/AdapterLoginChrome.tsx`,
`ui/src/components/new-agent/AgentProviderConnection.tsx`,
`ui/src/components/ai-connections/AiConnectionCredentialStep.tsx`,
`ui/src/components/OnboardingWizard.tsx`: enable hosted Google sign-in
for `antigravity_runtime` on hosted/non-local environments, render the
hosted `127.0.0.1` redirect paste flow with `ANALYTICS_MASK_CLASS` and
`ANALYTICS_NO_CAPTURE_CLASS`, preserve retryable paste errors inline,
and trigger immediate status re-check on submit.
- `tests/runner-e2e/source-sdk-public-inputs.json`: refreshed for the
updated `packages/shared/src/ai-connections.ts` schema.
- Unit, integration, and UI tests across `antigravity-auth.test.ts`,
`local-ai-login-policy.test.ts`, `health.test.ts`,
`health-dev-server-token.test.ts`, `redact-sensitive.test.ts`,
`http-log-policy.test.ts`, `antigravity-local-ai-login.test.ts`,
`ai-connections.test.ts`, `AdapterLoginChrome.test.tsx`,
`useLocalAiLogin.test.tsx`, and `AgentProviderConnection.test.tsx`.

## Verification

- `pnpm --filter @paperclipai/shared build && pnpm --filter
@paperclipai/shared typecheck && pnpm --filter
@paperclipai/paperclip-runner typecheck && pnpm --filter
@paperclipai/server typecheck && pnpm --filter @paperclipai/ui
typecheck` — passed.
- `pnpm --filter @paperclipai/shared exec vitest run
src/validators/claude-setup-token-session.test.ts` — 15/15 passed.
- `pnpm --filter @paperclipai/paperclip-runner exec vitest run
src/drivers/acpx/antigravity-auth.test.ts
src/drivers/acpx/antigravity-auth-stream-order.test.ts` — 33/33 passed
(including real `127.0.0.1` loopback HTTP relay with fake ACP peer,
bad-paste cap, reused-code rejection, single-use, and non-200 failure).
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/local-ai-login-policy.test.ts src/__tests__/health.test.ts
src/__tests__/health-dev-server-token.test.ts
src/__tests__/redact-sensitive.test.ts
src/__tests__/http-log-policy.test.ts
src/__tests__/antigravity-local-ai-login.test.ts` — all passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/ai-connections.test.ts` — 167/167 passed against embedded
PostgreSQL (including hosted Google end-to-end route test, redaction of
activity and HTTP logs, and continued blocking of Anthropic/OpenAI/xAI
on hosted public deployments).
- `pnpm --filter @paperclipai/ui exec vitest run
src/components/AdapterLoginChrome.test.tsx
src/components/ai-connections/useLocalAiLogin.test.tsx
src/components/new-agent/AgentProviderConnection.test.tsx` — 30/30
passed.
- `pnpm verify --explain` returned exit 2
(`tests/runner-e2e/source-sdk-public-inputs.json` broad input); required
CI supplies full-repo coverage.
- Note: live end-to-end sign-in against real `agy_acp_server.par` and
Google OAuth on a live Cloud stack was not run in this unit/integration
environment and remains a live-staging verification step.

## Risks

- Low-to-moderate risk. All hosted Google sign-in endpoints stay
authenticated, company-scoped, owner-bound, and `Cache-Control:
no-store`; `localAiLoginSupported` remains `false` on `authenticated +
public` deployments so Claude, OpenAI, and Grok server-host login stay
blocked.
- Loopback relay runs strictly against the validated
`127.0.0.1:<ephemeral_port>` origin printed by `agy_acp_server.par` with
`redirect: "manual"` and a 5-second timeout, outside any database
transaction.
- No database migrations are required.

## Model Used

- Google Gemini (Antigravity agent with tool use and code execution)

## 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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-11-25 07:36:36 -06:00
1 parent 07d444a717
commit 57bd302c81
30 files changed
+1055 -58

No files matched your search

@@ -205,4 +205,201 @@ describe("Antigravity setup-only Google authentication", () => {
expect(() => validateAntigravityAuthorizationUrl(url)).toThrow();
}
});
async function loopbackFixture(responseStatus = 200) {
const home = await realpath(await mkdtemp(join(tmpdir(), "paperclip-antigravity-loopback-test-"))); roots.push(home);
const peer = join(home, "loopback-peer.cjs");
await writeFile(peer, `
const fs = require('node:fs');
const http = require('node:http');
const path = require('node:path');
const readline = require('node:readline');
const home = process.argv[2];
const statusCode = Number(process.argv[3] || 200);
const received = [];
const state = 'loopback_state_0123456789_' + Math.random().toString(36).slice(2, 10);
let server;
const reader = readline.createInterface({ input: process.stdin });
reader.on('line', line => {
const request = JSON.parse(line);
if (request.method === 'initialize') {
process.stdout.write(JSON.stringify({
jsonrpc: '2.0', id: request.id,
result: { protocolVersion: 1, agentInfo: { name: 'antigravity-acp', version: '1.5.2' }, agentCapabilities: { _meta: { antigravity: { paperclipAdmission: 1 } } }, authMethods: [{ id: 'oauth-personal' }] },
}) + '\\n');
} else if (request.method === 'authenticate') {
server = http.createServer((req, res) => {
received.push({ method: req.method, url: req.url });
fs.writeFileSync(path.join(home, 'loopback-requests.json'), JSON.stringify(received));
res.statusCode = statusCode;
res.setHeader('Content-Type', 'text/plain');
res.end(statusCode === 200 ? 'Authentication complete.' : 'sensitive-loopback-error-body');
if (statusCode === 200) {
server.close(() => {
fs.mkdirSync(path.join(home, 'antigravity-acp'), { mode: 0o700 });
fs.writeFileSync(path.join(home, 'antigravity-acp/acp_token.json'), ${JSON.stringify(JSON.stringify(credential))}, { mode: 0o600 });
process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: request.id, result: {} }) + '\\n');
});
}
});
server.listen(0, '127.0.0.1', () => {
const port = server.address().port;
const params = new URLSearchParams({
client_id: ${JSON.stringify(CLIENT_ID)},
response_type: 'code',
redirect_uri: 'http://127.0.0.1:' + port + '/',
scope: ${JSON.stringify(credential.scopes.join(" "))},
state,
code_challenge: 'a'.repeat(43),
code_challenge_method: 'S256',
access_type: 'offline',
prompt: 'consent',
});
process.stderr.write('Open the following link to authenticate the ACP server: https://accounts.google.com/o/oauth2/v2/auth?' + params.toString() + '\\n');
});
}
});
reader.on('close', () => {
if (server) server.close(() => process.exit(0));
else process.exit(0);
});
`);
setup.verify.mockResolvedValue({ openCommand: async () => ({ spawn: setup.spawn, close: setup.close }) });
setup.spawn.mockImplementation((_args, options) => {
const child = spawn(process.execPath, [peer, home, String(responseStatus)], { ...options, detached: true }); children.push(child); return child;
});
return home;
}
function stubGoogleAllowLoopback() {
const realFetch = globalThis.fetch;
const googleFetch = googleIdentity();
const wrapped = vi.fn().mockImplementation(async (input: string | URL | Request, init?: RequestInit) => {
const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
if (url.startsWith("http://127.0.0.1:")) return realFetch(input, init);
return googleFetch(url, init ?? {});
});
vi.stubGlobal("fetch", wrapped);
return { wrapped, googleFetch };
}
it("relays a validated loopback redirect URL to the local ACP listener and completes sign-in", async () => {
const home = await loopbackFixture(200);
const { wrapped } = stubGoogleAllowLoopback();
const login = startAntigravityBrowserLogin(home);
await vi.waitFor(() => expect(login.submitRedirect).toBeTypeOf("function"), { timeout: 5_000 });
const parsedAuth = new URL(login.authorizationUrl!);
const redirectUri = parsedAuth.searchParams.get("redirect_uri")!;
const expectedState = parsedAuth.searchParams.get("state")!;
const uniqueCode = `4/0valid-relay-code-${Date.now()}`;
const pasted = `${redirectUri}?state=${encodeURIComponent(expectedState)}&code=${encodeURIComponent(uniqueCode)}&scope=email&extra=ignored`;
await login.submitRedirect!(pasted);
expect(login.submitRedirect).toBeUndefined();
await vi.waitFor(() => expect(login.outcome).toBe("success"), { timeout: 5_000 });
const received = JSON.parse(await readFile(join(home, "loopback-requests.json"), "utf8")) as Array<{ method: string; url: string }>;
expect(received).toEqual([{
method: "GET",
url: `/?state=${encodeURIComponent(expectedState)}&code=${encodeURIComponent(uniqueCode)}`,
}]);
expect(wrapped).toHaveBeenCalledWith(
`${redirectUri}?state=${encodeURIComponent(expectedState)}&code=${encodeURIComponent(uniqueCode)}`,
expect.objectContaining({ method: "GET", redirect: "manual" }),
);
await login.abort();
});
it("rejects bad redirect pastes without burning the loopback listener, and rejects reused codes and second submissions", async () => {
const home = await loopbackFixture(200);
stubGoogleAllowLoopback();
const login = startAntigravityBrowserLogin(home);
await vi.waitFor(() => expect(login.submitRedirect).toBeTypeOf("function"), { timeout: 5_000 });
const parsedAuth = new URL(login.authorizationUrl!);
const redirectUri = parsedAuth.searchParams.get("redirect_uri")!;
const expectedState = parsedAuth.searchParams.get("state")!;
const port = Number(new URL(redirectUri).port);
// Wrong state, wrong port/host/protocol/pathname, duplicate params, error param, oversized, control chars.
const invalidInputs = [
`${redirectUri}?state=wrong_state_canary_999&code=secret-code-canary`,
`http://127.0.0.1:${port === 65535 ? port - 1 : port + 1}/?state=${expectedState}&code=secret-code-canary`,
`http://localhost:${port}/?state=${expectedState}&code=secret-code-canary`,
`https://127.0.0.1:${port}/?state=${expectedState}&code=secret-code-canary`,
`${redirectUri}callback?state=${expectedState}&code=secret-code-canary`,
`http://user:pass@127.0.0.1:${port}/?state=${expectedState}&code=secret-code-canary`,
`${redirectUri}?state=${expectedState}&code=secret-code-canary#frag`,
`${redirectUri}?state=${expectedState}&state=${expectedState}&code=secret-code-canary`,
`${redirectUri}?state=${expectedState}&code=a&code=b`,
`${redirectUri}?error=access_denied&error_description=do-not-echo-canary&state=${expectedState}`,
`${redirectUri}?state=${expectedState}&code=${"c".repeat(2049)}`,
`${redirectUri}?state=${expectedState}&code=bad\ncode`,
`${redirectUri}?state=${expectedState}&code=${"x".repeat(4097)}`,
];
// Check first 4 invalid pastes stay retryable without touching the loopback server or leaking secrets.
for (const bad of invalidInputs.slice(0, 4)) {
const err = await login.submitRedirect!(bad).catch((e: unknown) => e);
expect(err).toBeInstanceOf(Error);
if (!(err instanceof Error)) throw new Error("Expected redirect rejection");
expect(err.message).not.toContain(expectedState);
expect(err.message).not.toContain("secret-code-canary");
expect(err.message).not.toContain("wrong_state_canary");
expect(login.submitRedirect).toBeTypeOf("function");
}
await expect(access(join(home, "loopback-requests.json"))).rejects.toMatchObject({ code: "ENOENT" });
// Valid paste still succeeds after 4 bad pastes.
const usedCode = `4/0single-use-code-${Date.now()}`;
const submitRef = login.submitRedirect!;
await submitRef(`${redirectUri}?state=${expectedState}&code=${usedCode}`);
// Second submission on the consumed handler is rejected immediately.
await expect(submitRef(`${redirectUri}?state=${expectedState}&code=another-code`)).rejects.toThrow("can no longer accept");
await vi.waitFor(() => expect(login.outcome).toBe("success"), { timeout: 5_000 });
await login.abort();
// Check remaining invalid shapes + reused code on a fresh attempt, plus the 5-attempt cap.
const home2 = await loopbackFixture(200);
stubGoogleAllowLoopback();
const login2 = startAntigravityBrowserLogin(home2);
await vi.waitFor(() => expect(login2.submitRedirect).toBeTypeOf("function"), { timeout: 5_000 });
const parsedAuth2 = new URL(login2.authorizationUrl!);
const redirectUri2 = parsedAuth2.searchParams.get("redirect_uri")!;
const expectedState2 = parsedAuth2.searchParams.get("state")!;
const port2 = Number(new URL(redirectUri2).port);
for (const bad of [
`${redirectUri2}?error=access_denied&error_description=do-not-echo-canary&state=${expectedState2}`,
`${redirectUri2}?state=${expectedState2}&code=${usedCode}`,
`${redirectUri2}?state=${expectedState2}&state=${expectedState2}&code=unique-1`,
`http://user:pass@127.0.0.1:${port2}/?state=${expectedState2}&code=unique-2`,
]) {
const err = await login2.submitRedirect!(bad).catch((e: unknown) => e);
expect(err).toBeInstanceOf(Error);
if (!(err instanceof Error)) throw new Error("Expected redirect rejection");
expect(err.message).not.toContain("do-not-echo-canary");
expect(err.message).not.toContain(usedCode);
expect(err.message).not.toContain(expectedState2);
}
// 5th bad paste terminates the attempt cleanly.
await expect(login2.submitRedirect!(`${redirectUri2}?state=${expectedState2}&code=${"c".repeat(2049)}`)).rejects.toThrow("Too many invalid");
expect(login2.submitRedirect).toBeUndefined();
await vi.waitFor(() => expect(login2.outcome).toBe("failure"), { timeout: 5_000 });
await expect(access(join(home2, "loopback-requests.json"))).rejects.toMatchObject({ code: "ENOENT" });
await login2.abort();
});
it("fails cleanly without leaking body when the loopback listener returns non-200", async () => {
const home = await loopbackFixture(500);
stubGoogleAllowLoopback();
const login = startAntigravityBrowserLogin(home);
await vi.waitFor(() => expect(login.submitRedirect).toBeTypeOf("function"), { timeout: 5_000 });
const parsedAuth = new URL(login.authorizationUrl!);
const redirectUri = parsedAuth.searchParams.get("redirect_uri")!;
const expectedState = parsedAuth.searchParams.get("state")!;
const err = await login.submitRedirect!(`${redirectUri}?state=${expectedState}&code=4/0non-200-code-${Date.now()}`).catch((e: unknown) => e);
expect(err).toBeInstanceOf(Error);
if (!(err instanceof Error)) throw new Error("Expected redirect rejection");
expect(err.message).not.toContain("sensitive-loopback-error-body");
await vi.waitFor(() => expect(login.outcome).toBe("failure"), { timeout: 5_000 });
await login.abort();
});
});
@@ -1,7 +1,7 @@
import type { ChildProcessWithoutNullStreams } from "node:child_process";
import { constants } from "node:fs";
import { lstat, open, readlink, rename, rm } from "node:fs/promises";
import { randomUUID } from "node:crypto";
import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
import { join } from "node:path";
import { StringDecoder } from "node:string_decoder";
import { antigravityPrivateEnvironment, checkAntigravityPrivateHome, retireAntigravityProcess } from "./antigravity-process.js";
@@ -14,15 +14,33 @@ const TOKEN_URI = "https://oauth2.googleapis.com/token";
const SCOPES = ["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/aicode"];
const AUTH_PREFIX = "Open the following link to authenticate the ACP server: ";
const MAX_BYTES = 64 * 1024;
const MAX_REDIRECT_URL_LENGTH = 4096;
const MAX_REDIRECT_CODE_LENGTH = 2048;
const MAX_BAD_REDIRECT_ATTEMPTS = 5;
const MAX_USED_CODE_DIGESTS = 1024;
const REDIRECT_LOOPBACK_TIMEOUT_MS = 5_000;
const DISALLOWED_PRINTABLE_ASCII = /[^\x21-\x7E]/;
const LOGIN_ERROR = "Google sign-in did not complete. Start sign-in again.";
const record = (value: unknown): Record<string, unknown> => value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
const verifiedCredentials = new Map<string, { credential: string; accountEmail: string }>();
const activeBrowserHomes = new Set<string>();
const usedRedirectCodeDigests = new Set<string>();
function recordUsedRedirectCodeDigest(digest: string): void {
usedRedirectCodeDigests.add(digest);
while (usedRedirectCodeDigests.size > MAX_USED_CODE_DIGESTS) {
const oldest = usedRedirectCodeDigests.values().next().value;
if (oldest === undefined) break;
usedRedirectCodeDigests.delete(oldest);
}
}
export type AntigravityBrowserLoginState = {
authorizationUrl?: string;
outcome?: "success" | "failure";
error?: string;
/** Relay a user-pasted loopback redirect URL to the local ACP listener. */
submitRedirect?: (rawRedirectUrl: string) => Promise<void>;
/** Resolves only after physical process retirement and lease release. */
abort(): Promise<void>;
};
@@ -157,7 +175,7 @@ export function startAntigravityBrowserLogin(home: string): AntigravityBrowserLo
activeBrowserHomes.add(home);
let resolveStopped: () => void;
const stopped = new Promise<void>(resolve => { resolveStopped = resolve; });
const state: AntigravityBrowserLoginState = { abort() { controller.abort(); activeBrowserHomes.delete(home); verifiedCredentials.delete(home); return stopped; } };
const state: AntigravityBrowserLoginState = { abort() { state.submitRedirect = undefined; controller.abort(); activeBrowserHomes.delete(home); verifiedCredentials.delete(home); return stopped; } };
void (async () => {
let lease: VerifiedAcpxCommandLease | undefined;
let child: ChildProcessWithoutNullStreams | undefined, closed: Promise<void> | undefined;
@@ -174,7 +192,7 @@ export function startAntigravityBrowserLogin(home: string): AntigravityBrowserLo
let phase = 1, stdout = "", stderr = "", total = 0, failure: Error | undefined;
const outputDecoder = new StringDecoder("utf8"), errorDecoder = new StringDecoder("utf8");
const authenticated = new Promise<void>((resolve, reject) => {
const fail = (error = new Error(LOGIN_ERROR)) => { failure ??= error; reject(failure); };
const fail = (error = new Error(LOGIN_ERROR)) => { state.submitRedirect = undefined; failure ??= error; reject(failure); };
failPending = fail;
const send = (id: 1 | 2) => peer.stdin.write(`${JSON.stringify(id === 1
? { jsonrpc: "2.0", id, method: "initialize", params: { protocolVersion: 1, clientInfo: { name: "paperclip-runner", version: "1" }, clientCapabilities: {} } }
@@ -195,7 +213,7 @@ export function startAntigravityBrowserLogin(home: string): AntigravityBrowserLo
|| record(record(record(initialized.agentCapabilities)._meta).antigravity).paperclipAdmission !== 1
|| !Array.isArray(initialized.authMethods) || !initialized.authMethods.some(method => record(method).id === "oauth-personal")) { fail(); return; }
phase = 2; send(2);
} else { phase = 3; resolve(); }
} else { phase = 3; state.submitRedirect = undefined; resolve(); }
}
});
peer.stderr.on("data", (chunk: Buffer) => {
@@ -209,6 +227,104 @@ export function startAntigravityBrowserLogin(home: string): AntigravityBrowserLo
const url = validateAntigravityAuthorizationUrl(line.slice(AUTH_PREFIX.length));
if ((phase !== 2 && phase !== 3) || state.authorizationUrl !== undefined) throw new Error(LOGIN_ERROR);
state.authorizationUrl = url;
if (phase === 2 && !controller.signal.aborted && !failure) {
const parsedAuth = new URL(url);
const expectedRedirect = new URL(parsedAuth.searchParams.get("redirect_uri")!);
const expectedState = parsedAuth.searchParams.get("state")!;
const expectedStateBytes = Buffer.from(expectedState, "utf8");
let badAttempts = 0;
const rejectBadAttempt = (message: string): never => {
badAttempts += 1;
if (badAttempts >= MAX_BAD_REDIRECT_ATTEMPTS) {
fail(new Error(LOGIN_ERROR));
throw new Error("Too many invalid Google redirect URLs. Start sign-in again.");
}
throw new Error(message);
};
const submitRedirect = async (rawRedirectUrl: string): Promise<void> => {
if (controller.signal.aborted || failure || phase !== 2 || state.submitRedirect !== submitRedirect) {
throw new Error("This Google sign-in attempt can no longer accept a redirect URL. Start sign-in again.");
}
if (
typeof rawRedirectUrl !== "string"
|| rawRedirectUrl.length === 0
|| rawRedirectUrl.length > MAX_REDIRECT_URL_LENGTH
|| DISALLOWED_PRINTABLE_ASCII.test(rawRedirectUrl)
) {
rejectBadAttempt("Paste the full http://127.0.0.1 URL from your browser’s address bar.");
}
let parsed: URL;
try {
parsed = new URL(rawRedirectUrl);
} catch {
rejectBadAttempt("Paste the full http://127.0.0.1 URL from your browser’s address bar.");
}
if (
parsed!.protocol !== "http:"
|| parsed!.hostname !== "127.0.0.1"
|| parsed!.port !== expectedRedirect.port
|| parsed!.pathname !== "/"
|| parsed!.username
|| parsed!.password
|| parsed!.hash
) {
rejectBadAttempt("The pasted URL does not match this Google sign-in attempt. Copy the address from the tab opened by this sign-in and try again.");
}
if (parsed!.searchParams.has("error")) {
rejectBadAttempt("Google sign-in was cancelled or denied. Start sign-in again.");
}
const states = parsed!.searchParams.getAll("state");
const codes = parsed!.searchParams.getAll("code");
if (states.length !== 1 || codes.length !== 1) {
rejectBadAttempt("The pasted URL is missing the Google sign-in response parameters. Copy the full address bar URL and try again.");
}
const submittedStateBytes = Buffer.from(states[0]!, "utf8");
if (submittedStateBytes.length !== expectedStateBytes.length || !timingSafeEqual(submittedStateBytes, expectedStateBytes)) {
rejectBadAttempt("The pasted URL does not match this Google sign-in attempt. Copy the address from the tab opened by this sign-in and try again.");
}
const submittedCode = codes[0]!;
if (
submittedCode.length === 0
|| submittedCode.length > MAX_REDIRECT_CODE_LENGTH
|| DISALLOWED_PRINTABLE_ASCII.test(submittedCode)
) {
rejectBadAttempt("The pasted URL does not contain a valid Google authorization code.");
}
const codeDigest = createHash("sha256").update(submittedCode, "utf8").digest("hex");
if (usedRedirectCodeDigests.has(codeDigest)) {
rejectBadAttempt("This Google authorization code has already been used. Start sign-in again.");
}
// Atomically consume single-use slot before contacting the one-shot loopback listener.
recordUsedRedirectCodeDigest(codeDigest);
state.submitRedirect = undefined;
const relayUrl = new URL("/", expectedRedirect.origin);
relayUrl.searchParams.set("state", expectedState);
relayUrl.searchParams.set("code", submittedCode);
let response: Response;
try {
response = await fetch(relayUrl.href, {
method: "GET",
redirect: "manual",
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(REDIRECT_LOOPBACK_TIMEOUT_MS)]),
});
} catch {
fail(new Error(LOGIN_ERROR));
throw new Error(LOGIN_ERROR);
}
try {
await response.body?.cancel();
} catch {
// Ignore body cancellation errors after reading status.
}
if (response.status !== 200) {
fail(new Error(LOGIN_ERROR));
throw new Error(LOGIN_ERROR);
}
};
state.submitRedirect = submitRedirect;
}
} catch { fail(); }
}
if (stderr.length > MAX_BYTES) fail();
@@ -233,6 +349,7 @@ export function startAntigravityBrowserLogin(home: string): AntigravityBrowserLo
} catch {
state.outcome = "failure"; state.error = LOGIN_ERROR;
} finally {
state.submitRedirect = undefined;
if (timeout) clearTimeout(timeout);
let observedClose = child === undefined;
let cleanupWasUncertain = false;
+1 -1
View File
@@ -86,7 +86,7 @@ export * from "./drivers/opencode/opencode-server-driver.js";
export * from "./drivers/opencode/mcp-bridge.js";
export * from "./drivers/acpx/qualified-profiles.js";
export { isAntigravityNativeTarget, parseAcpxCandidateAdmission, type AcpxCandidateAdmission } from "./drivers/acpx/candidate-admission.js";
export { startAntigravityBrowserLogin, verifyAntigravityCredential, sanitizeAntigravityCredential } from "./drivers/acpx/antigravity-auth.js";
export { startAntigravityBrowserLogin, verifyAntigravityCredential, sanitizeAntigravityCredential, type AntigravityBrowserLoginState } from "./drivers/acpx/antigravity-auth.js";
export {
GENERATED_ANTIGRAVITY_SWARM_CHANNELS, GENERATED_ANTIGRAVITY_SWARM_CREDENTIAL_FACTS_FIELD, GENERATED_ANTIGRAVITY_SWARM_DEFAULT_CHANNEL,
readGeneratedAntigravitySwarmCredentialFacts, type GeneratedAntigravitySwarmChannel, type GeneratedAntigravitySwarmCredentialFacts,
+13
View File
@@ -278,6 +278,19 @@ export const localAiConnectionSchema = aiConnectionLoginIntentSchema.extend({
localSessionId: z.string().uuid().optional(),
});
export const localAiLoginStartSchema = aiConnectionLoginIntentSchema.extend({ restart: z.boolean().optional() });
export const LOCAL_AI_LOGIN_CODE_MAX_LENGTH = 4096;
const LOCAL_AI_LOGIN_CODE_DISALLOWED_CHAR = /[^\x21-\x7E]/;
export const localAiLoginCodeSchema = z
.string()
.min(1, "A browser code or redirect URL is required.")
.max(LOCAL_AI_LOGIN_CODE_MAX_LENGTH, "The submitted sign-in input is too long.")
.regex(/^[\x21-\x7E]+$/u, "The submitted sign-in input has an invalid character.")
.refine((value) => !LOCAL_AI_LOGIN_CODE_DISALLOWED_CHAR.test(value), {
message: "The submitted sign-in input has an invalid character.",
});
export const submitLocalAiLoginCodeSchema = z.object({
browserCode: localAiLoginCodeSchema,
}).strict();
export interface LocalAiLoginStatus {
status: "ready" | "sign_in_required" | "expired";
authorizationUrl?: string;
+151 -3
View File
@@ -17,7 +17,7 @@ import { mkdtemp, realpath, rm, access, readFile, writeFile, stat } from "node:f
import os from "node:os";
import path from "node:path";
import { and, eq, sql } from "drizzle-orm";
import { createDb, type Db, companies, agents, agentTaskSessions, heartbeatRuns, companyMemberships, connectionGrants, toolApplications, connectionGrantDelegations, connectionGrantMembers, toolConnections, toolConnectionInstalls, aiConnectionDefaults, aiProviderDefaults, adapterAuthSessions, environments, plugins, issues, issueThreadInteractions, issueRecoveryActions, connectionIntentDeliveries, agentWakeupRequests, companySecrets, companySecretVersions, secretAccessEvents, userSecretDefinitions, principalPermissionGrants } from "@paperclipai/db";
import { createDb, type Db, activityLog, companies, agents, agentTaskSessions, heartbeatRuns, companyMemberships, connectionGrants, toolApplications, connectionGrantDelegations, connectionGrantMembers, toolConnections, toolConnectionInstalls, aiConnectionDefaults, aiProviderDefaults, adapterAuthSessions, environments, plugins, issues, issueThreadInteractions, issueRecoveryActions, connectionIntentDeliveries, agentWakeupRequests, companySecrets, companySecretVersions, secretAccessEvents, userSecretDefinitions, principalPermissionGrants } from "@paperclipai/db";
import { startEmbeddedPostgresTestDatabase } from "@paperclipai/db/test-embedded-postgres";
import { fetchCompanyQuotaWindows } from "../services/quota-windows.js";
import { quotaCredentialRecoveryPath, quotaCredentialRecovery, quotaCredentialHash } from "../services/quota-credential-recovery.js";
@@ -50,8 +50,11 @@ import * as settingsModule from "../services/instance-settings.js";
import { agentRoutes } from "../routes/agents.js";
import type { PluginWorkerManager } from "../services/plugin-worker-manager.js";
import { invalidateInstanceSettingsCache } from "../services/instance-settings-cache.js";
const browserLoginMock = vi.hoisted(() => ({
startLocalBrowserLogin: vi.fn(() => ({ authorizationUrl: "https://auth.openai.com/codex/device", code: "ABCD-EFGHJ", abort: () => {} })),
}));
vi.mock("../services/local-ai-browser-login.js", () => ({
startLocalBrowserLogin: () => ({ authorizationUrl: "https://auth.openai.com/codex/device", code: "ABCD-EFGHJ", abort: () => {} }),
startLocalBrowserLogin: browserLoginMock.startLocalBrowserLogin,
}));
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
@@ -2633,7 +2636,7 @@ console.log(JSON.stringify({ type: "result", subtype: "success", result: "hello"
expect((await request(app).post(url).set("x-local", "yes").send({ ...codex, localSessionId: prepared.body.sessionId })).status).toBe(422);
} finally { reader.mockRestore(); }
});
it.each(["anthropic", "openai"] as const)("blocks server-host %s login on a public deployment without a trusted host", async provider => {
it.each(["anthropic", "openai", "xai"] as const)("blocks server-host %s login on a public deployment without a trusted host", async provider => {
const reader = vi.spyOn(localCredentials, "readVerifiedLocalAiCredentialDetails");
const app = express();
app.use(express.json());
@@ -2654,6 +2657,151 @@ console.log(JSON.stringify({ type: "result", subtype: "success", result: "hello"
expect(reader).not.toHaveBeenCalled();
} finally { reader.mockRestore(); }
});
it("allows hosted Google Antigravity sign-in on an authenticated public deployment with full ownership, redaction, and single-use checks", async () => {
const { errorHandler } = await import("../middleware/error-handler.js");
const { createHttpLogger } = await import("../middleware/logger.js");
const { default: pino } = await import("pino");
const owner = `hosted-google-${randomUUID().slice(0, 8)}`;
await db.insert(companyMemberships).values({ companyId, principalId: owner, principalType: "user", status: "active", membershipRole: "member" });
const reader = vi.spyOn(localCredentials, "readVerifiedLocalAiCredentialDetails").mockResolvedValue({
credential: JSON.stringify({
client_id: "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com",
client_secret: "fixture-hosted-secret",
refresh_token: "fixture-hosted-refresh-token",
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",
],
project_id: "fixture-hosted-project",
}),
accountLabel: "hosted.user@example.test",
});
const usedCodes = new Set<string>();
const expectedState = "hosted_google_state_0123456789";
let googleState: { authorizationUrl?: string; outcome?: "success" | "failure"; error?: string; submitRedirect?: (raw: string) => Promise<void>; abort: () => void };
browserLoginMock.startLocalBrowserLogin.mockImplementationOnce(() => {
googleState = {
authorizationUrl: `https://accounts.google.com/o/oauth2/v2/auth?state=${expectedState}&redirect_uri=${encodeURIComponent("http://127.0.0.1:41999/")}`,
submitRedirect: async (raw: string) => {
const parsed = new URL(raw);
if (parsed.searchParams.get("state") !== expectedState) {
throw new Error("The pasted URL does not match this Google sign-in attempt. Copy the address from the tab opened by this sign-in and try again.");
}
const code = parsed.searchParams.get("code") ?? "";
if (usedCodes.has(code)) {
throw new Error("This Google authorization code has already been used. Start sign-in again.");
}
usedCodes.add(code);
googleState.submitRedirect = undefined;
googleState.outcome = "success";
},
abort: () => {},
};
return googleState as never;
});
const logLines: string[] = [];
const testLogger = pino({ level: "debug" }, { write(chunk: string) { logLines.push(chunk); } });
const app = express();
app.use(express.json());
app.use(createHttpLogger(testLogger));
app.use((req, _res, next) => {
req.actor = { type: "board", source: "session", userId: String(req.headers["x-test-user"] ?? owner), companyIds: [companyId], memberships: [{ companyId, status: "active", membershipRole: "member" }] };
next();
});
app.use("/api", aiConnectionRoutes(db, { deploymentMode: "authenticated", deploymentExposure: "public", trustedLocalStdioRuntimeHost: "" }));
app.use(errorHandler);
const base = `/api/companies/${companyId}/ai-connections/local`;
const intent = { provider: "google" as const, method: "subscription" as const, ownership: "personal" as const, name: "Hosted Google Antigravity", allAgents: false, agentIds: [] };
const secretCode = `4/0hosted-google-code-canary-${"z".repeat(550)}`;
const validRedirect = `http://127.0.0.1:41999/?state=${expectedState}&code=${secretCode}`;
const wrongStateRedirect = `http://127.0.0.1:41999/?state=wrong-state-canary&code=wrong-code-canary`;
try {
// 1. Start hosted Google attempt.
const started = await request(app).post(`${base}/attempts`).send(intent);
expect(started.status).toBe(201);
expect(started.headers["cache-control"]).toBe("no-store");
const sessionId = started.body.sessionId as string;
const codeUrl = `${base}/attempts/${sessionId}/code`;
// 2. Ownership, company scope, and bad-state checks on /code.
const wrongUser = await request(app).post(codeUrl).set("x-test-user", "bob").send({ browserCode: validRedirect });
expect(wrongUser.status).toBe(404);
expect(wrongUser.headers["cache-control"]).toBe("no-store");
const wrongCompany = await request(app).post(codeUrl.replace(companyId, otherCompanyId)).send({ browserCode: validRedirect });
expect(wrongCompany.status).toBe(403);
const wrongState = await request(app).post(codeUrl).send({ browserCode: wrongStateRedirect });
expect(wrongState.status).toBe(422);
expect(wrongState.headers["cache-control"]).toBe("no-store");
expect(JSON.stringify(wrongState.body)).not.toContain("wrong-state-canary");
expect(JSON.stringify(wrongState.body)).not.toContain("wrong-code-canary");
// 3. Valid redirect (> 512 bytes!) succeeds and consumes single-use slot.
const submitted = await request(app).post(codeUrl).send({ browserCode: validRedirect });
expect(submitted.status).toBe(200);
expect(submitted.headers["cache-control"]).toBe("no-store");
// 4. Second submission on the same attempt is rejected.
const replayed = await request(app).post(codeUrl).send({ browserCode: validRedirect });
expect(replayed.status).toBe(422);
// 5. Check returns ready with verified account label, and POST /local saves the connection.
const checked = await request(app).post(`${base}/check`).send({ ...intent, localSessionId: sessionId });
expect(checked.status).toBe(200);
expect(checked.body).toEqual({ status: "ready", accountLabel: "hosted.user@example.test" });
const saved = await request(app).post(base).send({ ...intent, localSessionId: sessionId });
expect(saved.status).toBe(201);
expect(saved.body).toEqual({ connectionId: expect.any(String), grantId: expect.any(String) });
// 6. Saved connection is listed and compatible with antigravity_runtime.
const listed = await service.list(companyId, owner);
const savedConnection = listed.find(c => c.id === saved.body.connectionId);
expect(savedConnection).toMatchObject({
provider: "google",
method: "subscription",
name: "Hosted Google Antigravity",
accountLabel: "hosted.user@example.test",
});
expect(isAiConnectionCompatible({ provider: "google", method: "subscription" }, "antigravity_runtime")).toBe(true);
// 7. Expired attempt cannot accept a redirect URL.
const expiredId = randomUUID();
const [envRow] = await db.select().from(environments).where(eq(environments.status, "active")).limit(1);
await db.insert(adapterAuthSessions).values({
id: expiredId, publicSessionId: expiredId, companyId, environmentId: envRow.id,
startedByUserId: owner, adapterType: "paperclip_runner", aiConnection: intent,
connectionMethod: "local_subscription", status: "waiting_for_user",
expiresAt: new Date(Date.now() - 60_000),
});
expect((await request(app).post(`${base}/attempts/${expiredId}/code`).send({ browserCode: validRedirect })).status).toBe(422);
// 8. Activity log and HTTP logs contain NO pasted redirect URL or authorization code.
const activities = await db.select().from(activityLog).where(eq(activityLog.entityId, sessionId));
expect(activities.some(a => a.action === "ai_connection.local_login_code_submitted" && (a.details as { provider?: string })?.provider === "google")).toBe(true);
const serializedActivities = JSON.stringify(activities);
expect(serializedActivities).not.toContain("hosted-google-code-canary");
expect(serializedActivities).not.toContain(expectedState);
expect(serializedActivities).not.toContain("127.0.0.1");
const serializedHttpLogs = logLines.join("\n");
expect(serializedHttpLogs).not.toContain("hosted-google-code-canary");
expect(serializedHttpLogs).not.toContain("wrong-state-canary");
expect(serializedHttpLogs).not.toContain("wrong-code-canary");
expect(serializedHttpLogs).not.toContain("127.0.0.1:41999");
} finally {
reader.mockRestore();
browserLoginMock.startLocalBrowserLogin.mockImplementation(() => ({ authorizationUrl: "https://auth.openai.com/codex/device", code: "ABCD-EFGHJ", abort: () => {} }));
}
});
it.each(["anthropic", "openai"] as const)("lets authenticated users connect only their own isolated %s login", async provider => {
const owner = `self-hosted-${provider}`;
await db.insert(companyMemberships).values({ companyId, principalId: owner, principalType: "user", status: "active", membershipRole: "member" });
@@ -283,4 +283,80 @@ describe("Google local sign-in service admission", () => {
f.release(); await operation;
await expect(access(f.home)).rejects.toMatchObject({ code: "ENOENT" });
});
it("runs Google submitRedirect outside any database transaction and logs only the provider", async () => {
const f = await fixture();
let releaseRelay!: () => void;
const relayPending = new Promise<void>(resolve => { releaseRelay = resolve; });
const submitRedirect = vi.fn(async (raw: string) => {
expect(f.db.activeTransactions).toBe(0);
expect(raw).toContain("http://127.0.0.1:41234/");
await relayPending;
f.browser.outcome = "success";
});
f.browser.submitRedirect = submitRedirect;
const pastedUrl = `http://127.0.0.1:41234/?state=state-canary&code=${"a".repeat(600)}`;
f.db.selections.push([f.db.session]);
const submitting = f.service.submitCode("company", "user", f.attempt.sessionId, pastedUrl, {
allowLocalProviders: false,
allowHostedGoogle: true,
});
await vi.waitFor(() => expect(submitRedirect).toHaveBeenCalledOnce());
expect(f.db.activeTransactions).toBe(0);
releaseRelay();
await submitting;
expect(mocks.activity).toHaveBeenLastCalledWith(
f.db,
expect.objectContaining({
companyId: "company",
actorType: "user",
actorId: "user",
action: "ai_connection.local_login_code_submitted",
entityId: f.attempt.sessionId,
details: { provider: "google" },
}),
);
expect(JSON.stringify(mocks.activity.mock.calls)).not.toContain("state-canary");
expect(JSON.stringify(mocks.activity.mock.calls)).not.toContain("a".repeat(50));
f.release(); f.db.selections.push([f.db.session], [f.db.session]); await f.service.cancel("company", "user", f.attempt.sessionId);
});
it("falls back to an active non-local environment for hosted Google sign-in when no local environment exists", async () => {
const root = await realpath(await mkdtemp(join(tmpdir(), "paperclip-google-cloud-env-test-"))); roots.push(root);
mocks.root.mockReturnValue(root);
const browser: LocalBrowserLoginState = { authorizationUrl: "https://accounts.google.com/fixture", abort: vi.fn() };
mocks.browser.mockReturnValue(browser);
const db = database(), service = localAiLoginService(db);
// No existing session, no active local environment, active managed sandbox environment.
db.selections.push([], [], [{ id: "sandbox-environment", driver: "sandbox", status: "active" }]);
const attempt = await service.start("company", "user", intent);
expect(db.session.environmentId).toBe("sandbox-environment");
db.selections.push([db.session], [db.session]);
await service.cancel("company", "user", attempt.sessionId);
});
it("blocks Claude code submission when local providers are disabled on a hosted instance, and enforces Claude's 512-byte limit", async () => {
const db = database(), service = localAiLoginService(db);
const claudeSession = {
id: "claude-session",
companyId: "company",
startedByUserId: "user",
connectionMethod: "local_subscription",
adapterType: "claude_local",
aiConnection: { ...intent, provider: "anthropic" as const },
status: "waiting_for_user",
expiresAt: new Date(Date.now() + 60_000),
};
db.selections.push([claudeSession]);
await expect(service.submitCode("company", "user", claudeSession.id, "short-code", {
allowLocalProviders: false,
allowHostedGoogle: true,
})).rejects.toThrow("unavailable on this hosted instance");
db.selections.push([claudeSession]);
await expect(service.submitCode("company", "user", claudeSession.id, "a".repeat(513), {
allowLocalProviders: true,
allowHostedGoogle: true,
})).rejects.toThrow("browser code is invalid");
});
});
@@ -107,6 +107,7 @@ describe("GET /health dev-server supervisor access", () => {
deploymentMode: "authenticated",
deploymentExposure: "private",
localAiLoginSupported: true,
hostedGoogleAiLoginSupported: true,
commit: null,
bootstrapStatus: "ready",
bootstrapInviteActive: false,
+3
View File
@@ -397,6 +397,7 @@ describe("GET /health", () => {
deploymentMode: "authenticated",
deploymentExposure: "public",
localAiLoginSupported: false,
hostedGoogleAiLoginSupported: true,
commit: testServerInfo.git.fullSha,
bootstrapStatus: "ready",
bootstrapInviteActive: false,
@@ -455,6 +456,7 @@ describe("GET /health", () => {
deploymentMode: "authenticated",
deploymentExposure: "public",
localAiLoginSupported: false,
hostedGoogleAiLoginSupported: true,
commit: testServerInfo.git.fullSha,
bootstrapStatus: "ready",
bootstrapInviteActive: false,
@@ -494,6 +496,7 @@ describe("GET /health", () => {
deploymentMode: "authenticated",
deploymentExposure: "public",
localAiLoginSupported: false,
hostedGoogleAiLoginSupported: true,
commit: testServerInfo.git.fullSha,
bootstrapStatus: "ready",
bootstrapInviteActive: false,
@@ -103,6 +103,18 @@ describe("isSecretSensitiveHttpRequest", () => {
),
).toBe(false);
});
it("protects local AI login code and hosted redirect submission endpoints", () => {
for (const method of ["POST", "PUT", "GET"]) {
for (const path of [
"/api/companies/company-1/ai-connections/local/attempts/session-1/code",
"https://paperclip.test/API/COMPANIES/company-1/AI-CONNECTIONS/LOCAL/ATTEMPTS/session-1/CODE?code=canary",
]) {
expect(isSecretSensitiveHttpRequest(method, path)).toBe(true);
}
}
expect(isSecretSensitiveHttpRequest("POST", "/api/companies/company-1/ai-connections/local/attempts")).toBe(false);
});
});
describe("shouldSilenceHttpSuccessLog", () => {
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { supportsLocalAiLogin } from "../services/local-ai-login-policy.js";
import { supportsHostedGoogleAiLogin, supportsLocalAiLogin } from "../services/local-ai-login-policy.js";
describe("server-host subscription login policy", () => {
it("permits private self-hosted instances and explicit trusted hosts", () => {
expect(supportsLocalAiLogin({ deploymentMode: "local_trusted", deploymentExposure: "private" })).toBe(true);
@@ -7,4 +7,9 @@ describe("server-host subscription login policy", () => {
expect(supportsLocalAiLogin({ deploymentMode: "authenticated", deploymentExposure: "public", trustedLocalStdioRuntimeHost: "trusted-host" })).toBe(true);
expect(supportsLocalAiLogin({ deploymentMode: "authenticated", deploymentExposure: "public", trustedLocalStdioRuntimeHost: "" })).toBe(false);
});
it("permits hosted Google Antigravity sign-in even on authenticated public deployments", () => {
expect(supportsHostedGoogleAiLogin({ deploymentMode: "authenticated", deploymentExposure: "public", trustedLocalStdioRuntimeHost: "" })).toBe(true);
expect(supportsHostedGoogleAiLogin({ deploymentMode: "local_trusted", deploymentExposure: "private" })).toBe(true);
});
});
@@ -272,6 +272,23 @@ it("redacts Grok routine URL and key in setup failure logs", () => {
expect(collectSensitiveStringValues(payload)).toContain(payload.webhookKey);
});
it("redacts hosted Google redirect URLs and browser codes unconditionally", () => {
const payload = {
browserCode: "http://127.0.0.1:41234/?state=state-canary&code=code-canary",
redirectUrl: "http://127.0.0.1:41234/?state=state-canary-2&code=code-canary-2",
redirect_url: "http://127.0.0.1:41234/?state=state-canary-3&code=code-canary-3",
};
const redacted = redactSensitive(payload) as Record<string, unknown>;
expect(redacted).toEqual({
browserCode: "[REDACTED]",
redirectUrl: "[REDACTED]",
redirect_url: "[REDACTED]",
});
expect(JSON.stringify(redacted)).not.toContain("canary");
expect(collectSensitiveStringValues(payload)).toContain(payload.browserCode);
expect(collectSensitiveStringValues(payload)).toContain(payload.redirectUrl);
});
describe("invitation bearer URL paths", () => {
it.each([
["/api/invites/invite-bearer-canary/accept?token=query-canary", "/api/invites/[REDACTED]/accept"],
+3 -1
View File
@@ -56,7 +56,8 @@ export type SecretSensitiveRouteFamily =
| "voice_sessions"
| "mcp_oauth"
| "api_mcp"
| "chat_endpoint_setup";
| "chat_endpoint_setup"
| "local_ai_login_code";
const SECRET_SENSITIVE_HTTP_PATHS: ReadonlyArray<readonly [SecretSensitiveRouteFamily, RegExp]> = [
["voice_sessions", /^\/api\/companies\/[^/]+\/voice-sessions(?:\/|$)/],
@@ -185,6 +186,7 @@ export function secretSensitiveRouteFamily(
if (!method || !url) return null;
if (/^\/api\/chat-slack\/(?:managed\/)?oauth(?:\/|$)/i.test(normalizePath(url).replace(/^https?:\/\/[^/]*/i, ""))) return "chat_slack_oauth";
if (/^\/api\/chat-endpoints\/[^/]+\/slack(?:\/|$)/i.test(normalizePath(url).replace(/^https?:\/\/[^/]*/i, ""))) return "chat_endpoint_slack";
if (/^\/api\/companies\/[^/]+\/ai-connections\/local\/attempts\/[^/]+\/code(?:\/|$)/i.test(normalizePath(url).replace(/^https?:\/\/[^/]*/i, ""))) return "local_ai_login_code";
if (!SECRET_SENSITIVE_HTTP_METHODS.has(method.toUpperCase())) return null;
const pathname = normalizePath(url);
return SECRET_SENSITIVE_HTTP_PATHS.find(([, pattern]) => pattern.test(pathname))?.[0] ?? null;
@@ -35,5 +35,7 @@ export const HTTP_LOG_REDACT_PATHS = [
// each. The key names are chosen by the caller, so no fixed list of leaf
// names can cover them. Redact the whole envelope instead.
"reqBody.credentialValues",
"reqBody.browserCode",
"reqBody.redirectUrl",
"errorContext.details.credentials",
] as const;
+6 -3
View File
@@ -85,10 +85,13 @@ const SENSITIVE_KEYS = new Set<string>([
"webhookkey",
"webhookurl",
"paperclip_capability",
// The Claude setup-token login fields. `browserCode` carries the one-time
// sign-in code and `authorization_code` carries the OAuth code; neither may
// reach a log line.
// The Claude setup-token and hosted Google redirect login fields.
// `browserCode` carries a one-time sign-in code or loopback redirect URL,
// `redirectUrl` carries an OAuth callback URL, and `authorization_code`
// carries the OAuth code; none may reach a log line.
"browsercode",
"redirecturl",
"redirect_url",
"authorization_code",
"code_verifier",
"codeverifier",
+21 -11
View File
@@ -2,7 +2,7 @@ import { connectionManagementGuard, connectionRequestActor, connectionRequestCon
import { connectionManagementService } from "../services/connection-management.js";
import { validateAiApiKey } from "../services/ai-api-key-test.js";
export { validateAiApiKey } from "../services/ai-api-key-test.js";
import { supportsLocalAiLogin } from "../services/local-ai-login-policy.js";
import { supportsHostedGoogleAiLogin, supportsLocalAiLogin } from "../services/local-ai-login-policy.js";
import { localAiLoginService } from "../services/local-ai-login.js";
import { z } from "zod";
import { Router, type Request } from "express";
@@ -20,7 +20,8 @@ import {
aiConnectionLoginIntentSchema,
localAiConnectionSchema,
localAiLoginStartSchema,
browserCodeSchema,
localAiLoginCodeSchema,
submitLocalAiLoginCodeSchema,
isAiConnectionCompatible,
type AiConnectionLoginIntent,
type AiProvider,
@@ -149,8 +150,11 @@ export async function canInstallSharedAiConnectionForNewAgent(
export function aiConnectionRoutes(db: Db, options: Parameters<typeof supportsLocalAiLogin>[0] & { pluginWorkerManager?: PluginWorkerManager } = {}) {
function assertLocalLoginAvailable() {
if (!supportsLocalAiLogin(options)) throw unprocessable("Server-host subscription sign-in is unavailable on this hosted instance. Choose a supported sign-in environment or use an API key.");
const localLoginAvailable = () => supportsLocalAiLogin(options);
const hostedGoogleLoginAvailable = () => supportsHostedGoogleAiLogin(options);
function assertLocalLoginAvailable(provider?: AiConnectionLoginIntent["provider"]) {
if (provider === "google" ? (hostedGoogleLoginAvailable() || localLoginAvailable()) : localLoginAvailable()) return;
throw unprocessable("Server-host subscription sign-in is unavailable on this hosted instance. Choose a supported sign-in environment or use an API key.");
}
const router = Router();
const managementGuard = connectionManagementGuard(db, "ai");
@@ -189,7 +193,7 @@ export function aiConnectionRoutes(db: Db, options: Parameters<typeof supportsLo
router.post("/companies/:companyId/ai-connections/local/attempts", managementGuard("connections:configure", "POST /companies/:companyId/ai-connections/local/attempts", { personal: true }), validate(localAiLoginStartSchema), async (req, res) => {
const companyId = req.params.companyId as string;
const { restart, ...intent } = localAiLoginStartSchema.parse(req.body);
assertLocalLoginAvailable();
assertLocalLoginAvailable(intent.provider);
const userId = await assertAiConnectionCreateAccess(db, req, companyId, intent);
res.setHeader("Cache-Control", "no-store");
const attempt = await localLogin.start(companyId, userId, intent, restart, connectionRequestContext(req));
@@ -198,7 +202,7 @@ export function aiConnectionRoutes(db: Db, options: Parameters<typeof supportsLo
router.post("/companies/:companyId/ai-connections/local/check", managementGuard("connections:configure", "POST /companies/:companyId/ai-connections/local/check", { personal: true }), validate(localAiConnectionSchema), async (req, res) => {
const companyId = req.params.companyId as string;
const { localSessionId, ...intent } = localAiConnectionSchema.parse(req.body);
assertLocalLoginAvailable();
assertLocalLoginAvailable(intent.provider);
const userId = await assertAiConnectionCreateAccess(db, req, companyId, intent);
res.setHeader("Cache-Control", "no-store");
res.json(await localLogin.check(companyId, userId, intent, localSessionId));
@@ -210,14 +214,19 @@ export function aiConnectionRoutes(db: Db, options: Parameters<typeof supportsLo
await localLogin.cancel(req.params.companyId as string, responsibleUserForAiRequest(req)!, id, connectionRequestContext(req));
res.json({ ok: true });
});
router.post("/companies/:companyId/ai-connections/local/attempts/:sessionId/code", validate(z.object({ browserCode: browserCodeSchema })), async (req, res) => {
router.post("/companies/:companyId/ai-connections/local/attempts/:sessionId/code", validate(submitLocalAiLoginCodeSchema), async (req, res) => {
const companyId = req.params.companyId as string;
assertLocalLoginAvailable();
res.setHeader("Cache-Control", "no-store");
assertBoard(req);
assertCompanyAccess(req, companyId);
if (!localLoginAvailable() && !hostedGoogleLoginAvailable()) {
throw unprocessable("Server-host subscription sign-in is unavailable on this hosted instance. Choose a supported sign-in environment or use an API key.");
}
const id = z.string().uuid().parse(req.params.sessionId);
await localLogin.submitCode(companyId, getActorInfo(req).actorId, id, browserCodeSchema.parse(req.body.browserCode));
res.setHeader("Cache-Control", "no-store");
await localLogin.submitCode(companyId, getActorInfo(req).actorId, id, localAiLoginCodeSchema.parse(req.body.browserCode), {
allowLocalProviders: localLoginAvailable(),
allowHostedGoogle: hostedGoogleLoginAvailable(),
});
res.json({ ok: true });
});
router.get("/companies/:companyId/ai-connections", managementGuard("connections:read", "GET /companies/:companyId/ai-connections", { personal: true }), async (req, res) => {
@@ -362,8 +371,9 @@ export function aiConnectionRoutes(db: Db, options: Parameters<typeof supportsLo
async (req, res) => {
const companyId = req.params.companyId as string;
const { localSessionId, ...input } = localAiConnectionSchema.parse(req.body);
assertLocalLoginAvailable();
assertLocalLoginAvailable(input.provider);
const userId = await assertAiConnectionCreateAccess(db, req, companyId, input);
res.setHeader("Cache-Control", "no-store");
if (!localSessionId) throw unprocessable(input.provider === "xai"
? "Start local sign-in for this connection before connecting."
: "Start browser sign-in for this connection before connecting.");
+4 -2
View File
@@ -1,4 +1,4 @@
import { supportsLocalAiLogin } from "../services/local-ai-login-policy.js";
import { supportsHostedGoogleAiLogin, supportsLocalAiLogin } from "../services/local-ai-login-policy.js";
import { randomUUID, timingSafeEqual } from "node:crypto";
import { Router } from "express";
import type { Db } from "@paperclipai/db";
@@ -414,6 +414,7 @@ export function healthRoutes(
deploymentMode: opts.deploymentMode,
deploymentExposure: opts.deploymentExposure,
localAiLoginSupported: supportsLocalAiLogin(opts),
hostedGoogleAiLoginSupported: supportsHostedGoogleAiLogin(opts),
commit,
bootstrapStatus,
bootstrapInviteActive,
@@ -437,7 +438,8 @@ export function healthRoutes(
commit,
deploymentMode: opts.deploymentMode,
deploymentExposure: opts.deploymentExposure,
localAiLoginSupported: supportsLocalAiLogin(opts),
localAiLoginSupported: supportsLocalAiLogin(opts),
hostedGoogleAiLoginSupported: supportsHostedGoogleAiLogin(opts),
authReady: opts.authReady,
bootstrapStatus,
bootstrapInviteActive,
@@ -13,7 +13,8 @@ export type LocalBrowserLoginState = {
outcome?: "success" | "failure";
error?: string;
submitCode?: (code: string) => void;
abort: () => void;
submitRedirect?: (rawRedirectUrl: string) => Promise<void>;
abort: () => void | Promise<void>;
};
// Node has no built-in PTY API. Python's standard-library pty module supplies
+15 -3
View File
@@ -1,12 +1,24 @@
import type { DeploymentMode, DeploymentExposure } from "@paperclipai/shared";
/** Same server-host boundary as local stdio runtimes. */
export function supportsLocalAiLogin(options: {
export type LocalAiLoginPolicyOptions = {
deploymentMode?: DeploymentMode;
deploymentExposure?: DeploymentExposure;
trustedLocalStdioRuntimeHost?: string | null;
}) {
};
/** Same server-host boundary as local stdio runtimes. */
export function supportsLocalAiLogin(options: LocalAiLoginPolicyOptions) {
return options.deploymentMode !== "authenticated" || options.deploymentExposure !== "public" || Boolean(
options.trustedLocalStdioRuntimeHost ?? process.env.PAPERCLIP_TRUSTED_MCP_RUNTIME_HOST ?? process.env.PAPERCLIP_TOOL_RUNTIME_TRUSTED_HOST,
);
}
/**
* Antigravity Google sign-in launches Paperclip's pinned, isolated
* `agy_acp_server.par` closure with a private per-attempt home rather than
* touching an ambient host CLI, so authenticated public deployments can safely
* relay the user's pasted loopback redirect.
*/
export function supportsHostedGoogleAiLogin(_options: LocalAiLoginPolicyOptions = {}) {
return true;
}
+67 -4
View File
@@ -6,10 +6,11 @@ import { mkdir, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import { and, eq, inArray, isNotNull, lte, notInArray, sql } from "drizzle-orm";
import { adapterAuthSessions, ADAPTER_AUTH_SESSION_ACTIVE_STATES, databaseWorkScopeKey, environments, type Db } from "@paperclipai/db";
import type { AiConnectionLoginIntent, LocalAiLoginAttempt, LocalAiLoginStatus } from "@paperclipai/shared";
import { browserCodeSchema, type AiConnectionLoginIntent, type LocalAiLoginAttempt, type LocalAiLoginStatus } from "@paperclipai/shared";
import { resolvePaperclipInstanceRoot } from "../home-paths.js";
import { notFound, unprocessable } from "../errors.js";
import { aiConnectionService } from "./ai-connections.js";
import { environmentService } from "./environments.js";
import { readVerifiedLocalAiCredentialDetails } from "./local-ai-credentials.js";
import { logActivity } from "./activity-log.js";
import { startLocalBrowserLogin, type LocalBrowserLoginState } from "./local-ai-browser-login.js";
@@ -240,8 +241,22 @@ export function localAiLoginService(db: Db) {
entityType: "adapter_auth_session", entityId: existing.id, details: { provider: intent.provider },
});
}
const [environment] = await tx.select().from(environments)
let [environment] = await tx.select().from(environments)
.where(and(eq(environments.driver, "local"), eq(environments.status, "active"))).limit(1);
if (!environment && intent.provider === "google") {
// Hosted Google sign-in runs inside Paperclip's pinned ACP closure rather
// than a host CLI, so stacks without an active `local` environment row
// (for example managed-sandbox-only Cloud stacks) still record an owning
// environment FK without mutating unrelated execution routing.
[environment] = await tx.select().from(environments)
.where(eq(environments.status, "active")).limit(1);
if (!environment) {
const ensured = await tx.transaction((savepoint) =>
environmentService(savepoint as unknown as Db).ensureLocalEnvironment(companyId),
);
environment = { id: ensured.id } as typeof environment;
}
}
if (!environment) throw unprocessable("No active local environment is available.");
const id = randomUUID();
const directory = loginHome(id);
@@ -311,7 +326,55 @@ export function localAiLoginService(db: Db) {
}
}
async function submitCode(companyId: string, userId: string, id: string, code: string) {
async function submitCode(
companyId: string,
userId: string,
id: string,
code: string,
policy: { allowLocalProviders?: boolean; allowHostedGoogle?: boolean } = {},
) {
const allowLocalProviders = policy.allowLocalProviders ?? true;
const allowHostedGoogle = policy.allowHostedGoogle ?? true;
const [existing] = await db.select().from(adapterAuthSessions).where(and(
eq(adapterAuthSessions.id, id), eq(adapterAuthSessions.companyId, companyId),
eq(adapterAuthSessions.startedByUserId, userId), eq(adapterAuthSessions.connectionMethod, LOCAL_LOGIN_METHOD),
));
if (!existing) throw notFound("Local sign-in attempt not found.");
const isClaude = existing.adapterType === "claude_local";
const isGoogle = existing.adapterType === "paperclip_runner" && existing.aiConnection?.provider === "google";
if (!isClaude && !isGoogle) throw notFound("Local sign-in attempt not found.");
if (isClaude && !allowLocalProviders) {
throw unprocessable("Server-host subscription sign-in is unavailable on this hosted instance. Choose a supported sign-in environment or use an API key.");
}
if (isGoogle && !allowLocalProviders && !allowHostedGoogle) {
throw unprocessable("Server-host subscription sign-in is unavailable on this hosted instance. Choose a supported sign-in environment or use an API key.");
}
if (isGoogle) {
if (existing.status !== "waiting_for_user" || existing.failureReason === RETIREMENT_PENDING || !existing.expiresAt || existing.expiresAt.getTime() <= Date.now()) {
throw unprocessable("This sign-in attempt has expired or was cancelled. Start sign-in again.");
}
const login = browserLogins.get(id);
if (!login?.authorizationUrl || !login.submitRedirect || login.outcome) {
throw unprocessable("This sign-in attempt cannot accept a redirect URL. Start sign-in again.");
}
// Run the loopback relay outside any database transaction so a slow or
// stalled loopback listener can never hold a PostgreSQL row lock open.
try {
await login.submitRedirect(code);
} catch (error) {
throw unprocessable(error instanceof Error ? error.message : "Google sign-in did not complete. Start sign-in again.");
}
await logActivity(db, {
companyId, actorType: "user", actorId: userId, action: "ai_connection.local_login_code_submitted",
entityType: "adapter_auth_session", entityId: id, details: { provider: "google" },
});
return;
}
if (!browserCodeSchema.safeParse(code).success) {
throw unprocessable("The browser code is invalid.");
}
await db.transaction(async (tx) => {
const [session] = await tx.select().from(adapterAuthSessions).where(and(
eq(adapterAuthSessions.id, id), eq(adapterAuthSessions.companyId, companyId),
@@ -319,7 +382,7 @@ export function localAiLoginService(db: Db) {
eq(adapterAuthSessions.adapterType, "claude_local"),
)).for("update");
if (!session) throw notFound("Local sign-in attempt not found.");
if (session.status !== "waiting_for_user" || !session.expiresAt || session.expiresAt.getTime() <= Date.now())
if (session.status !== "waiting_for_user" || session.failureReason === RETIREMENT_PENDING || !session.expiresAt || session.expiresAt.getTime() <= Date.now())
throw unprocessable("This sign-in attempt has expired or was cancelled. Start sign-in again.");
const login = browserLogins.get(id);
if (!login?.authorizationUrl || !login.submitCode || login.outcome)
+1
View File
@@ -10,6 +10,7 @@
type RunnerModule = typeof import("@paperclipai/paperclip-runner");
export type {
AntigravityBrowserLoginState,
GeneratedAntigravitySwarmChannel,
GeneratedAntigravitySwarmCredentialFacts,
NativeCursorCloudConfig,
@@ -64,7 +64,7 @@
"packages/shared/src/aggregator-apps.ts": "2a69a54ee0cb305170275b6f4e97689c107defb1",
"packages/shared/src/ai-connection-router.ts": "9fbd89c385a4d5827bc68e1c7f6a66e00453d413",
"packages/shared/src/ai-connection-usage.ts": "4b51573ee92f8a2ae0f80dd15288a0e59b4dddc7",
"packages/shared/src/ai-connections.ts": "4192761de2dfc02c2e93342077f03c577e862590",
"packages/shared/src/ai-connections.ts": "f4107ef6a07c070b7ad04d64bf16d50135a3950a",
"packages/shared/src/ai-provider-routing.ts": "8149629b707981f0c90118c019eb9c9a88aa435f",
"packages/shared/src/analytics-consent.test.ts": "0c69d867d4f108cb57c07b4e71633e058cb7506b",
"packages/shared/src/analytics-consent.ts": "00c4bfbd24ac3a288a68caae52468dfcd26df3e7",
+1
View File
@@ -35,6 +35,7 @@ export type HealthStatus = {
deploymentMode?: "local_trusted" | "authenticated";
deploymentExposure?: "private" | "public";
localAiLoginSupported?: boolean;
hostedGoogleAiLoginSupported?: boolean;
authReady?: boolean;
bootstrapStatus?: "ready" | "bootstrap_pending";
bootstrapInviteActive?: boolean;
@@ -278,4 +278,67 @@ describe("session replay", () => {
await render(<LocalProviderLoginInstructions adapterType="claude_local" login={{ ...login, status: "ready", accountLabel: "hollis.brennan@example.test" }} />);
expect(replayLeaks("hollis.brennan@example.test", document.body)).toEqual({ rendered: true, recorded: false });
});
it("blocks hosted Google redirect input from session replay and preserves retryable errors", async () => {
const submitCode = vi.fn().mockRejectedValueOnce(new Error("The pasted URL does not match this Google sign-in attempt.")).mockResolvedValueOnce(undefined);
const container = await render(
<LocalProviderLoginInstructions
adapterType="antigravity_runtime"
hostedRedirect
login={{
...login,
authorizationUrl: "https://accounts.google.com/o/oauth2/v2/auth?state=test-state",
submitCode,
}}
/>,
);
const link = container.querySelector('a[href="https://accounts.google.com/o/oauth2/v2/auth?state=test-state"]') as HTMLAnchorElement | null;
expect(link).not.toBeNull();
expect(link!.getAttribute("target")).toBe("_blank");
expect(link!.getAttribute("rel")).toBe("noreferrer noopener");
expect(container.textContent).toContain("127.0.0.1");
const input = container.querySelector('input[aria-label="Google redirect URL"]') as HTMLInputElement | null;
expect(input).not.toBeNull();
expect(input!.getAttribute("autocomplete")).toBe("off");
expect(input!.getAttribute("spellcheck")).toBe("false");
expect(input!.className).toContain("ph-mask");
expect(input!.className).toContain("ph-no-capture");
await act(async () => {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "http://127.0.0.1:41234/?state=bad&code=abc");
input!.dispatchEvent(new Event("input", { bubbles: true }));
});
const submitButton = Array.from(container.querySelectorAll("button")).find(b => b.textContent === "Submit redirect URL") as HTMLButtonElement;
await act(async () => { submitButton.click(); });
await vi.waitFor(() => expect(container.querySelector('[role="alert"]')?.textContent).toContain("does not match"));
expect(submitCode).toHaveBeenCalledWith("http://127.0.0.1:41234/?state=bad&code=abc");
// Input stays open after a retryable bad paste.
const retryInput = container.querySelector('input[aria-label="Google redirect URL"]') as HTMLInputElement | null;
expect(retryInput).not.toBeNull();
await act(async () => {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(retryInput, "http://127.0.0.1:41234/?state=good&code=xyz");
retryInput!.dispatchEvent(new Event("input", { bubbles: true }));
});
const retrySubmit = Array.from(container.querySelectorAll("button")).find(b => b.textContent === "Submit redirect URL") as HTMLButtonElement;
await act(async () => { retrySubmit.click(); });
await vi.waitFor(() => expect(container.textContent).toContain("Finishing sign-in"));
expect(submitCode).toHaveBeenCalledWith("http://127.0.0.1:41234/?state=good&code=xyz");
});
it("keeps the direct local Google prompt without a paste field when hostedRedirect is false", async () => {
const container = await render(
<LocalProviderLoginInstructions
adapterType="antigravity_runtime"
hostedRedirect={false}
login={{
...login,
authorizationUrl: "https://accounts.google.com/o/oauth2/v2/auth?state=local-state",
}}
/>,
);
expect(container.querySelector('input[aria-label="Google redirect URL"]')).toBeNull();
expect(container.textContent).toContain("Finish signing in in the Google browser window");
});
});
+44 -8
View File
@@ -13,6 +13,7 @@ import {
COPIED_REVEAL_TRAVEL,
} from "./onboarding/onboarding-motion";
import { ANALYTICS_MASK_CLASS, ANALYTICS_NO_CAPTURE_CLASS } from "@/lib/analytics/privacy";
import { describeError } from "@/api/errors";
import { cn } from "@/lib/utils";
/**
@@ -367,6 +368,7 @@ export function OnboardingCardField({
placeholder = "Paste authorization code here",
masked = false,
autoFocus = false,
className,
}: {
value: string;
onChange: (value: string) => void;
@@ -391,6 +393,7 @@ export function OnboardingCardField({
* not where the next action is.
*/
autoFocus?: boolean;
className?: string;
}) {
return (
<input
@@ -411,7 +414,7 @@ export function OnboardingCardField({
onSubmit();
}
}}
className={onboardingCardInputClass}
className={className ? cn(onboardingCardInputClass, className) : onboardingCardInputClass}
/>
);
}
@@ -434,7 +437,7 @@ export function ProviderSubscriptionCard({
failure?: "expired" | "failed";
failureMessage?: string;
onRetry?: () => void;
mode: "submitted_code" | "displayed_code" | "browser_redirect";
mode: "submitted_code" | "displayed_code" | "browser_redirect" | "hosted_redirect";
loading?: boolean;
children: ReactNode;
}) {
@@ -456,7 +459,8 @@ export function ProviderSubscriptionCard({
>
Sign in to {providerName}
</a>
{mode === "browser_redirect" ? " then return here"
{mode === "hosted_redirect" ? " then paste the redirect URL below"
: mode === "browser_redirect" ? " then return here"
: mode === "submitted_code"
? " then come back and enter authorization code"
: " by providing the authorization code below"}
@@ -490,38 +494,48 @@ export function ProviderApiKeyCard({
}
/** Shared instructions for local subscription setup in every authentication host. */
export function LocalProviderLoginInstructions({ adapterType, login }: {
export function LocalProviderLoginInstructions({ adapterType, login, hostedRedirect = false }: {
adapterType: string;
hostedRedirect?: boolean | "optional";
login?: { isolated?: boolean; command?: string; authorizationUrl?: string | null; code?: string | null; accountLabel?: string | null; submitCode?: (code: string) => Promise<void>; preparing: boolean; status?: "ready" | "sign_in_required" | "expired" | null; error: string | null; retry: () => void };
}) {
const [showCommand, setShowCommand] = useState(false);
const [browserCode, setBrowserCode] = useState("");
const [submitting, setSubmitting] = useState(false);
const [codeSubmitted, setCodeSubmitted] = useState(false);
const [submitError, setSubmitError] = useState<string | null>(null);
const codeSubmissionRef = useRef<symbol | null>(null);
useEffect(() => {
codeSubmissionRef.current = null;
setBrowserCode("");
setSubmitting(false);
setCodeSubmitted(false);
setSubmitError(null);
}, [login?.authorizationUrl, login?.preparing]);
const provider = adapterType === "antigravity_runtime" ? "Google Antigravity" : adapterType === "claude_local" ? "Claude Code" : adapterType === "grok_local" ? "Grok CLI" : "Codex CLI";
const isolated = login?.isolated ?? (adapterType === "codex_local" || adapterType === "grok_local");
const command = login?.command;
const browserLogin = adapterType === "claude_local" || adapterType === "codex_local" || adapterType === "antigravity_runtime";
const hostedGoogleRedirect = adapterType === "antigravity_runtime" && Boolean(hostedRedirect);
const optionalHostedGoogleRedirect = adapterType === "antigravity_runtime" && hostedRedirect === "optional";
async function submitBrowserCode(value = browserCode) {
if (!value.trim() || !login?.submitCode || codeSubmissionRef.current) return;
const submission = Symbol();
codeSubmissionRef.current = submission;
setSubmitting(true);
setSubmitError(null);
try {
await login.submitCode(value.trim());
if (codeSubmissionRef.current !== submission) return;
setBrowserCode("");
setCodeSubmitted(true);
} catch {
// The login hook presents the request error beside the sign-in card.
if (codeSubmissionRef.current === submission) codeSubmissionRef.current = null;
} catch (cause) {
// The login hook presents attempt-level errors beside the sign-in card;
// hosted Google redirect keeps the field open for retryable paste errors.
if (codeSubmissionRef.current === submission) {
codeSubmissionRef.current = null;
if (hostedGoogleRedirect) setSubmitError(describeError(cause).body);
}
} finally {
if (codeSubmissionRef.current === submission || codeSubmissionRef.current === null) setSubmitting(false);
}
@@ -534,6 +548,7 @@ export function LocalProviderLoginInstructions({ adapterType, login }: {
const end = input.selectionEnd ?? start;
const value = input.value.slice(0, start) + pasted + input.value.slice(end);
event.preventDefault();
setSubmitError(null);
setBrowserCode(value);
void submitBrowserCode(value);
}
@@ -550,7 +565,7 @@ export function LocalProviderLoginInstructions({ adapterType, login }: {
{browserLogin && !ready && !submitting && !codeSubmitted && !login?.error && login?.authorizationUrl && <ProviderSubscriptionCard
providerName={connectSourceName(adapterType)}
authorizationUrl={login.authorizationUrl}
mode={adapterType === "antigravity_runtime" ? "browser_redirect" : adapterType === "claude_local" ? "submitted_code" : "displayed_code"}
mode={hostedGoogleRedirect && !optionalHostedGoogleRedirect ? "hosted_redirect" : adapterType === "antigravity_runtime" ? "browser_redirect" : adapterType === "claude_local" ? "submitted_code" : "displayed_code"}
>
{adapterType === "claude_local" ? <div className="flex flex-col gap-2">
<OnboardingCardField
@@ -561,6 +576,27 @@ export function LocalProviderLoginInstructions({ adapterType, login }: {
disabled={submitting}
/>
<Button type="button" disabled={!browserCode.trim() || submitting} onClick={() => void submitBrowserCode()}>Submit code</Button>
</div> : hostedGoogleRedirect ? <div className="flex flex-col gap-2">
<p className="px-2 text-xs text-muted-foreground">
{optionalHostedGoogleRedirect
? <>Finish signing in in the Google browser window, then return here. If your browser is on another machine and the <code className="font-mono">127.0.0.1</code> redirect page won’t load, copy the full URL from your address bar and paste it below.</>
: <>After signing in with Google, your browser will redirect to a <code className="font-mono">127.0.0.1</code> page that won’t load. Copy the full URL from your browser’s address bar and paste it below.</>}
</p>
<OnboardingCardField
label="Google redirect URL"
placeholder="Paste http://127.0.0.1:... URL here"
className={cn(ANALYTICS_MASK_CLASS, ANALYTICS_NO_CAPTURE_CLASS)}
value={browserCode}
onChange={(value) => {
setSubmitError(null);
setBrowserCode(value);
}}
onPaste={pasteBrowserCode}
onSubmit={() => void submitBrowserCode()}
disabled={submitting}
/>
<Button type="button" disabled={!browserCode.trim() || submitting} onClick={() => void submitBrowserCode()}>Submit redirect URL</Button>
{submitError && <p role="alert" className="px-2 text-xs text-destructive">{submitError}</p>}
</div> : adapterType === "antigravity_runtime" ? <p>Finish signing in in the Google browser window, then return here.</p> : <OnboardingLoginCodeRow code={login.code ?? ""} />}
</ProviderSubscriptionCard>}
{!browserLogin && (!ready || showCommand) && !login?.error && <>
+12 -3
View File
@@ -726,7 +726,7 @@ function OnboardingWizardInner({
const managedSubscriptionRef = useRef<{ companyId: string; binding: AiConnectionBinding; grantId?: string; sessionId?: string } | null>(null);
const defaultSelectionsRef = useRef(new Map<string, { pending: Promise<unknown>; queued: number; revision: number; grantId?: string | null }>());
const managedProvider = aiProviderForAdapter(adapterType);
const managedSubscriptionProvider = managedProvider === "anthropic" || managedProvider === "openai" || managedProvider === "xai" ? managedProvider : undefined;
const managedSubscriptionProvider = managedProvider === "anthropic" || managedProvider === "openai" || managedProvider === "xai" || (managedProvider === "google" && adapterType === "antigravity_runtime") ? managedProvider : undefined;
function managedBindingForStep(): AiConnectionBinding | undefined {
if (credentialMode === "api" && gatewayConnection?.companyId === createdCompanyId && gatewayConnection.adapterType === adapterType) return gatewayConnection.binding;
const restoredBinding = restoredSetup?.companyId === createdCompanyId
@@ -1078,7 +1078,16 @@ function OnboardingWizardInner({
// input here, so this gate alone only decides whether the login mechanism
// could ever apply to the current adapter and environment.
const localLoginHealth = useQuery({ queryKey: queryKeys.health, queryFn: healthApi.get });
const canUseLocalLogin = Boolean(managedSubscriptionProvider) && resolvedLoginEnvironment?.driver === "local" && (localLoginHealth.data?.localAiLoginSupported ?? localLoginHealth.data?.deploymentMode === "local_trusted");
const localAiLoginSupported = Boolean(localLoginHealth.data?.localAiLoginSupported ?? localLoginHealth.data?.deploymentMode === "local_trusted");
const hostedGoogleAiLoginSupported = Boolean(localLoginHealth.data?.hostedGoogleAiLoginSupported);
const canUseLocalLogin = Boolean(managedSubscriptionProvider) && (
managedSubscriptionProvider === "google"
? (hostedGoogleAiLoginSupported || (resolvedLoginEnvironment?.driver === "local" && localAiLoginSupported))
: (resolvedLoginEnvironment?.driver === "local" && localAiLoginSupported)
);
const googleHostedRedirect: boolean | "optional" = managedSubscriptionProvider === "google" && hostedGoogleAiLoginSupported
? (localAiLoginSupported ? "optional" : true)
: false;
const localLogin = useLocalAiLogin(createdCompanyId, {
provider: managedSubscriptionProvider ?? "anthropic", method: "subscription",
name: `My ${CONNECT_SOURCE_NAMES[adapterType] ?? managedProvider} subscription`,
@@ -3323,7 +3332,7 @@ function OnboardingWizardInner({
/>
) : hasSavedSubscription || localLogin.status === "ready" ? null : connectStepHasNoSandbox ? (
canUseLocalLogin && managedProvider ? (
<LocalProviderLoginInstructions adapterType={adapterType} login={{ ...localLogin, retry: () => { autoConnectStartedRef.current = false; setError(null); localLogin.retry(); } }} />
<LocalProviderLoginInstructions adapterType={adapterType} hostedRedirect={googleHostedRedirect} login={{ ...localLogin, retry: () => { autoConnectStartedRef.current = false; setError(null); localLogin.retry(); } }} />
) : browserSignInUnavailable ? <p role="status" className="text-xs text-muted-foreground">This environment does not support browser sign-in. Go back to use an API key or choose another model.</p> : null
) : null}
</motion.div>
@@ -10,6 +10,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@
import { aiConnectionsApi } from "@/api/ai-connections";
import { describeError } from "@/api/errors";
import { environmentsApi } from "@/api/environments";
import { healthApi } from "@/api/health";
import { QueryErrorState, useQueryView } from "@/components/QueryView";
import { instanceSettingsApi } from "@/api/instanceSettings";
import { queryKeys } from "@/lib/queryKeys";
@@ -52,12 +53,14 @@ function SubscriptionConnectionStep({ companyId, provider, initialMethod, fixedM
const settings = useQuery({ queryKey: queryKeys.instance.settings, queryFn: instanceSettingsApi.get });
const experimental = useQuery({ queryKey: queryKeys.instance.experimentalSettings, queryFn: instanceSettingsApi.getExperimental });
const general = useQuery({ queryKey: queryKeys.instance.generalSettings, queryFn: instanceSettingsApi.getGeneral });
const health = useQuery({ queryKey: queryKeys.health, queryFn: healthApi.get, enabled: provider === "google" });
const envsView = useQueryView(envs);
const capsView = useQueryView(caps);
const settingsView = useQueryView(settings);
const experimentalView = useQueryView(experimental);
const generalView = useQueryView(general);
const views = [envsView, capsView, settingsView, experimentalView, generalView];
const hostedGoogleSignIn = provider === "google" && Boolean(health.data?.hostedGoogleAiLoginSupported);
const forced = resolveForcedKubernetesEnvironment(general.data?.executionMode, envs.data ?? []);
let environmentId: string | null = null;
let environmentError: string | undefined;
@@ -70,7 +73,9 @@ function SubscriptionConnectionStep({ companyId, provider, initialMethod, fixedM
managedSandboxEnvironmentId: resolveManagedSandboxEnvironmentId(envs.data),
visibleEnvironmentIds: envs.data?.map((env) => env.id),
});
} catch (error) { environmentError = describeError(error).body; }
} catch (error) {
if (!hostedGoogleSignIn) environmentError = describeError(error).body;
}
const loginEnvironments = (envs.data ?? []).filter((env) =>
env.status === "active" && (env.driver === "local" || (provider !== "google" && environmentSupportsLoginPty(env, caps.data, provider === "openai" ? "codex_local" : provider === "anthropic" ? "claude_local" : "unsupported"))),
);
@@ -82,7 +87,7 @@ function SubscriptionConnectionStep({ companyId, provider, initialMethod, fixedM
}
const environment = envs.data?.find((env) => env.id === environmentId);
const canLogin = environmentSupportsLoginPty(environment, caps.data, provider === "openai" ? "codex_local" : provider === "anthropic" ? "claude_local" : "unsupported");
const loading = [envs, caps, settings, experimental, general].some((query) => query.isPending) || views.some((view) => view.kind === "reconnecting");
const loading = [envs, caps, settings, experimental, general].some((query) => query.isPending) || (provider === "google" && health.isPending) || views.some((view) => view.kind === "reconnecting");
const loadError = views.find((view) => view.kind === "error");
const intent: AiConnectionLoginIntent = { provider: provider as AiConnectionLoginIntent["provider"], method: "subscription", name, ownership, agentIds, allAgents, connectionId };
return <div className="mx-auto w-full min-w-0 max-w-xl space-y-6">
@@ -20,9 +20,10 @@ beforeEach(() => {
host = document.createElement("div"); document.body.append(host); root = createRoot(host);
});
afterEach(() => { flushSync(() => root.unmount()); host.remove(); });
function Harness({ name = "Account", provider = "openai", enabled = true }: { name?: string; provider?: "anthropic" | "openai"; enabled?: boolean }) {
function Harness({ name = "Account", provider = "openai", enabled = true, hostedRedirect = false }: { name?: string; provider?: "anthropic" | "openai" | "google"; enabled?: boolean; hostedRedirect?: boolean }) {
const login = useLocalAiLogin("company", { provider, method: "subscription", name, ownership: "personal", agentIds: [], allAgents: true }, enabled);
return <><LocalProviderLoginInstructions adapterType={provider === "anthropic" ? "claude_local" : "codex_local"} login={login} /><button onClick={() => void login.connect()}>Connect</button><button onClick={login.cancel}>Back</button></>;
const adapterType = provider === "google" ? "antigravity_runtime" : provider === "anthropic" ? "claude_local" : "codex_local";
return <><LocalProviderLoginInstructions adapterType={adapterType} hostedRedirect={hostedRedirect} login={login} /><button onClick={() => void login.connect()}>Connect</button><button onClick={login.cancel}>Back</button></>;
}
it("checks once under StrictMode, preserves renaming and navigation, and cancels only on explicit retry", async () => {
flushSync(() => root.render(<StrictMode><Harness name="First name" /></StrictMode>));
@@ -179,3 +180,23 @@ it.each(["start", "check"])("cancels a local subscription with a pending %s and
expect(api.checkLocalLogin).toHaveBeenCalledTimes(stage === "start" ? 0 : 1);
expect(api.connectLocal).not.toHaveBeenCalled();
});
it("immediately triggers check after submitting a hosted Google redirect URL", async () => {
api.checkLocalLogin
.mockResolvedValueOnce({ status: "sign_in_required", authorizationUrl: "https://accounts.google.com/o/oauth2/v2/auth?state=hosted" })
.mockResolvedValueOnce({ status: "ready", accountLabel: "hosted.user@example.test" });
flushSync(() => root.render(<Harness provider="google" hostedRedirect />));
await vi.waitFor(() => expect(host.querySelector('input[aria-label="Google redirect URL"]')).not.toBeNull());
expect(api.checkLocalLogin).toHaveBeenCalledTimes(1);
const input = host.querySelector('input[aria-label="Google redirect URL"]') as HTMLInputElement;
flushSync(() => {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "http://127.0.0.1:41234/?state=hosted&code=abc123");
input.dispatchEvent(new Event("input", { bubbles: true }));
});
flushSync(() => Array.from(host.querySelectorAll("button")).find(b => b.textContent === "Submit redirect URL")!.click());
await vi.waitFor(() => expect(api.submitLocalLoginCode).toHaveBeenCalledWith("company", "attempt-1", "http://127.0.0.1:41234/?state=hosted&code=abc123"));
await vi.waitFor(() => expect(api.checkLocalLogin).toHaveBeenCalledTimes(2));
await vi.waitFor(() => expect(host.textContent).toContain("hosted.user@example.test is signed in"));
});
@@ -16,6 +16,8 @@ export function useLocalAiLogin(companyId: string | null, intent: AiConnectionLo
const [generation, setGeneration] = useState(0);
const latestIntent = useRef(intent);
const restartRequested = useRef(false);
const checkRef = useRef<(() => Promise<void>) | null>(null);
const fastPollRemaining = useRef(0);
const pending = useRef<Promise<unknown>>(Promise.resolve());
const current = useRef<{ key: string; companyId: string; request: Promise<LocalAiLoginAttempt> } | null>(null);
function cancelCurrent() {
@@ -67,17 +69,26 @@ export function useLocalAiLogin(companyId: string | null, intent: AiConnectionLo
setError(next.error ?? (next.status === "expired" ? "This sign-in attempt expired. Start sign-in again." : null));
// Stop polling a verified account. Focus rechecks after the provider
// browser visit; sign-in never requires repeated Connect clicks.
if (next.status === "sign_in_required") timer = setTimeout(() => void check(), 5000);
if (next.status === "sign_in_required") {
const delayMs = fastPollRemaining.current > 0 ? 1000 : 5000;
if (fastPollRemaining.current > 0) fastPollRemaining.current -= 1;
timer = setTimeout(() => void check(), delayMs);
} else {
fastPollRemaining.current = 0;
}
} catch (cause) {
if (!cancelled && (!isolated || current.current?.request === request)) setError(describeError(cause).body);
} finally { checking = false; }
}
checkRef.current = check;
const onFocus = () => { if (!document.hidden) void check(); };
void check();
window.addEventListener("focus", onFocus);
document.addEventListener("visibilitychange", onFocus);
return () => {
cancelled = true;
checkRef.current = null;
fastPollRemaining.current = 0;
clearTimeout(timer);
window.removeEventListener("focus", onFocus);
document.removeEventListener("visibilitychange", onFocus);
@@ -107,8 +118,15 @@ export function useLocalAiLogin(companyId: string | null, intent: AiConnectionLo
if (!companyId || !attempt) throw new Error("Start sign-in before submitting a code.");
try {
await aiConnectionsApi.submitLocalLoginCode(companyId, attempt.sessionId, browserCode);
setError(null);
fastPollRemaining.current = 10;
void checkRef.current?.();
} catch (cause) {
setError("Could not submit the authorization code. Start sign-in again.");
if (latestIntent.current.provider === "google") {
void checkRef.current?.();
} else {
setError("Could not submit the authorization code. Start sign-in again.");
}
throw cause;
}
},
@@ -0,0 +1,148 @@
// @vitest-environment jsdom
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { AgentProviderConnection } from "./AgentProviderConnection";
const mocks = vi.hoisted(() => ({
healthGet: vi.fn(),
startLocalLogin: vi.fn(),
checkLocalLogin: vi.fn(),
submitLocalLoginCode: vi.fn(),
cancelLocalLogin: vi.fn(),
connectLocal: vi.fn(),
listConnections: vi.fn(),
}));
vi.mock("@/api/health", () => ({ healthApi: { get: mocks.healthGet } }));
vi.mock("@/api/ai-connections", () => ({
aiConnectionsApi: {
startLocalLogin: mocks.startLocalLogin,
checkLocalLogin: mocks.checkLocalLogin,
submitLocalLoginCode: mocks.submitLocalLoginCode,
cancelLocalLogin: mocks.cancelLocalLogin,
connectLocal: mocks.connectLocal,
list: mocks.listConnections,
create: vi.fn(),
loginResult: vi.fn(),
},
}));
vi.mock("@/api/agents", () => ({
agentsApi: { getAdapterAuthSignal: vi.fn().mockResolvedValue({ status: "absent" }) },
}));
vi.mock("../onboarding/SavedProviderKeySelect", () => ({
SavedProviderKeySelect: () => null,
useSavedProviderKeys: () => ({
options: [],
subscriptions: [],
loading: false,
error: false,
storedLogin: { data: undefined, isPending: false, isError: false, isFetching: false },
}),
}));
let root: Root;
let host: HTMLDivElement;
beforeEach(() => {
vi.resetAllMocks();
mocks.startLocalLogin.mockResolvedValue({ sessionId: "hosted-session-1", expiresAt: "2099-01-01T00:00:00Z" });
mocks.checkLocalLogin.mockResolvedValue({
status: "sign_in_required",
authorizationUrl: "https://accounts.google.com/o/oauth2/v2/auth?state=hosted-ui-state",
});
mocks.submitLocalLoginCode.mockResolvedValue({ ok: true });
mocks.cancelLocalLogin.mockResolvedValue({});
mocks.connectLocal.mockResolvedValue({ connectionId: "conn-1", grantId: "grant-1" });
mocks.listConnections.mockResolvedValue({ currentUserId: "u1", canManageConnections: true, connections: [] });
host = document.createElement("div");
document.body.append(host);
root = createRoot(host);
});
afterEach(() => {
flushSync(() => root.unmount());
host.remove();
});
function renderConnection(adapterType: "antigravity_runtime" | "claude_local" | "codex_local", localEnvironment: boolean) {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const provider = adapterType === "antigravity_runtime" ? "google" : adapterType === "claude_local" ? "anthropic" : "openai";
flushSync(() => {
root.render(
<QueryClientProvider client={client}>
<AgentProviderConnection
companyId="company-1"
adapterType={adapterType}
environmentId="sandbox-env-1"
canLogin={false}
localEnvironment={localEnvironment}
onBack={() => {}}
onConnected={() => {}}
testConnection={async () => true}
managedAccount={{
intent: {
provider,
method: "subscription",
name: "Test Account",
ownership: "personal",
agentIds: [],
allAgents: true,
},
onComplete: () => {},
}}
/>
</QueryClientProvider>,
);
});
}
describe("AgentProviderConnection hosted Google sign-in gating", () => {
it("enables hosted Google redirect sign-in for antigravity_runtime on non-local environments", async () => {
mocks.healthGet.mockResolvedValue({
status: "ok",
deploymentMode: "authenticated",
deploymentExposure: "public",
localAiLoginSupported: false,
hostedGoogleAiLoginSupported: true,
});
renderConnection("antigravity_runtime", false);
await vi.waitFor(() => expect(mocks.startLocalLogin).toHaveBeenCalledTimes(1));
await vi.waitFor(() => expect(host.querySelector('input[aria-label="Google redirect URL"]')).not.toBeNull());
expect(host.querySelector('a[href="https://accounts.google.com/o/oauth2/v2/auth?state=hosted-ui-state"]')).not.toBeNull();
expect(host.textContent).toContain("127.0.0.1");
});
it("still exposes the Google redirect paste field when local login is also supported (remote private/trusted host)", async () => {
mocks.healthGet.mockResolvedValue({
status: "ok",
deploymentMode: "authenticated",
deploymentExposure: "private",
localAiLoginSupported: true,
hostedGoogleAiLoginSupported: true,
});
renderConnection("antigravity_runtime", true);
await vi.waitFor(() => expect(mocks.startLocalLogin).toHaveBeenCalledTimes(1));
await vi.waitFor(() => expect(host.querySelector('input[aria-label="Google redirect URL"]')).not.toBeNull());
expect(host.textContent).toContain("another machine");
expect(host.textContent).toContain("127.0.0.1");
});
it.each(["claude_local", "codex_local"] as const)("keeps local login disabled for %s on hosted instances", async (adapterType) => {
mocks.healthGet.mockResolvedValue({
status: "ok",
deploymentMode: "authenticated",
deploymentExposure: "public",
localAiLoginSupported: false,
hostedGoogleAiLoginSupported: true,
});
renderConnection(adapterType, false);
await new Promise((resolve) => setTimeout(resolve, 25));
expect(mocks.startLocalLogin).not.toHaveBeenCalled();
expect(host.textContent).toContain("does not support browser sign-in");
});
});
@@ -74,12 +74,23 @@ export function AgentProviderConnection({
onComplete: (result: { connectionId: string; grantId: string; method: "subscription" | "api_key" }) => void;
};
}) {
const health = useQuery({ queryKey: queryKeys.health, queryFn: healthApi.get, enabled: localEnvironment });
const needsHealth = localEnvironment || adapterType === "antigravity_runtime";
const health = useQuery({ queryKey: queryKeys.health, queryFn: healthApi.get, enabled: needsHealth });
// Read health through the shared view: a transient failure keeps the saved
// local-login path usable,anda no-data failure shows readable copy.
// local-login path usable, and a no-data failure shows readable copy.
const healthView = useQueryView(health);
const canUseLocalLogin = localEnvironment && (health.data?.localAiLoginSupported ?? health.data?.deploymentMode === "local_trusted");
const localAiLoginSupported = Boolean(health.data?.localAiLoginSupported ?? health.data?.deploymentMode === "local_trusted");
const hostedGoogleAiLoginSupported = Boolean(health.data?.hostedGoogleAiLoginSupported);
const canUseLocalLogin = adapterType === "antigravity_runtime"
? (hostedGoogleAiLoginSupported || (localEnvironment && localAiLoginSupported))
: (localEnvironment && localAiLoginSupported);
// Keep the loopback redirect paste option available whenever relay sign-in is
// supported, including private/trusted-host servers where `localAiLoginSupported`
// is true but the user's browser may be on another machine.
const googleHostedRedirect: boolean | "optional" = adapterType === "antigravity_runtime" && hostedGoogleAiLoginSupported
? (localAiLoginSupported ? "optional" : true)
: false;
const epoch = useRef(0);
useEffect(
() => () => {
@@ -416,7 +427,7 @@ export function AgentProviderConnection({
}}
/>
) : savedSubscription ? null : canUseLocalLogin && !storedLogin.data ? (
<LocalProviderLoginInstructions adapterType={adapterType} login={{ ...localLogin, retry: () => { setError(null); localLogin.retry(); } }} />
<LocalProviderLoginInstructions adapterType={adapterType} hostedRedirect={googleHostedRedirect} login={{ ...localLogin, retry: () => { setError(null); localLogin.retry(); } }} />
) : (
<p className="text-sm text-muted-foreground">
{storedLogin.data
@@ -439,7 +450,7 @@ export function AgentProviderConnection({
{testError ?? error}
</p>
)}
{localEnvironment && healthView.kind === "error" && (
{needsHealth && healthView.kind === "error" && (
<p role="alert" className="mt-4 text-sm text-destructive">Could not prepare sign-in. Reload this page to try again.</p>
)}
<FooterNav
@@ -464,7 +475,7 @@ export function AgentProviderConnection({
primaryDisabled={
managedAccount?.disabled ||
(Boolean(managedAccount) && method === "subscription" && !canLogin && !canUseLocalLogin) ||
(localEnvironment && health.isPending) || localLogin.preparing || Boolean(localLogin.error) ||
(needsHealth && health.isPending) || localLogin.preparing || Boolean(localLogin.error) ||
(method === "subscription" && canUseLocalLogin && !savedSubscription && !storedLogin.data && localLogin.status !== "ready") ||
(!managedAccount && adapterType !== "antigravity_runtime" && auth.isPending) ||
savedKeys.loading ||