Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

antigravityAuthSupport.ts

562 lines21.0 KB

1import * as NodeCrypto from "node:crypto";
2// @effect-diagnostics-next-line nodeBuiltinImport:off - Effect's symlink has no type argument, and Windows needs a junction to link without elevation.
3import * as NodeFSP from "node:fs/promises";
4// @effect-diagnostics-next-line nodeBuiltinImport:off - resolveAntigravityProfileDirectory is a pure sync helper, so it cannot use the Path service.
5import * as NodePath from "node:path";
6​
7import type { AntigravityAuthMethod, ProviderInstanceId } from "@t3tools/contracts";
8import { HostProcessExecutablePath, HostProcessPlatform } from "@t3tools/shared/hostProcess";
9import * as Effect from "effect/Effect";
10import * as FileSystem from "effect/FileSystem";
11import * as Path from "effect/Path";
12import type * as PlatformError from "effect/PlatformError";
13import * as Schema from "effect/Schema";
14import * as Stream from "effect/Stream";
15import * as ChildProcess from "effect/unstable/process/ChildProcess";
16import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
17import * as AcpErrors from "effect-acp/errors";
18​
19import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
20import type { AcpSpawnInput } from "./acp/AcpSessionRuntime.ts";
21import {
22 antigravityUserSkillDirectories,
23 resolveAntigravityUserHome,
24} from "./Drivers/AntigravitySkills.ts";
25​
26export const ANTIGRAVITY_AUTH_STDOUT_PREFIX =
27 "Open the following link to authenticate the ACP server: ";
28export const ANTIGRAVITY_AUTH_BROWSER_MARKER = "__T3_ANTIGRAVITY_AUTH_URL__";
29export const ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE =
30 "Sign in to Antigravity in Settings before you continue.";
31​
32const maxAuthorizationUrlLength = 16_384;
33const maxBrowserHelperLineLength =
34 Math.max(ANTIGRAVITY_AUTH_BROWSER_MARKER.length, ANTIGRAVITY_AUTH_STDOUT_PREFIX.length) +
35 maxAuthorizationUrlLength +
36 2;
37const maxStdoutLineBytes = 16 * 1024 * 1024;
38const authPrefixBytes = new TextEncoder().encode(ANTIGRAVITY_AUTH_STDOUT_PREFIX);
39const decodeUrl = Schema.decodeUnknownEffect(Schema.URLFromString);
40const decodeBrowserHelperUrl = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.String));
41const ProfileSettingsFile = Schema.Struct({
42 auth: Schema.Struct({ type: Schema.String }),
43 gcp: Schema.optional(
44 Schema.Struct({
45 project: Schema.optional(Schema.String),
46 location: Schema.optional(Schema.String),
47 }),
48 ),
49});
50const encodeProfileSettings = Schema.encodeSync(Schema.fromJsonString(ProfileSettingsFile));
51const isAcpRequestError = Schema.is(AcpErrors.AcpRequestError);
52const isAcpTransportError = Schema.is(AcpErrors.AcpTransportError);
53​
54// Python splits BROWSER on the platform path separator before it parses quotes.
55// Keep this source free of both colons and semicolons. EPIPE must still exit 0
56// so Python does not fall back to an OS browser after cancellation.
57const browserHelperSource =
58 `process.stderr.on("error",()=>process.exit(0)).write(` +
59 `"${ANTIGRAVITY_AUTH_BROWSER_MARKER}"+JSON.stringify(process.argv[1])+"\\n",` +
60 `()=>process.exit(0))`;
61const browserPreflightUrl = "https://example.invalid/t3-antigravity-browser-preflight";
62​
63const removedEnvironmentKeys = new Set([
64 "GEMINI_API_KEY",
65 "GOOGLE_API_KEY",
66 "GOOGLE_APPLICATION_CREDENTIALS",
67 "GOOGLE_CLOUD_PROJECT",
68 "GOOGLE_CLOUD_LOCATION",
69 "GOOGLE_CLOUD_QUOTA_PROJECT",
70 "GOOGLE_GENAI_USE_VERTEXAI",
71 "GCLOUD_PROJECT",
72 "CLOUDSDK_CORE_PROJECT",
73 "AGY_ACP_CCPA_PROJECT",
74 "AGY_ACP_ENABLE_OAUTH",
75 "GEMINI_HOME",
76 "AGY_ACP_FORCE_FILE_STORAGE",
77 "ANTIGRAVITY_HARNESS_PATH",
78 "BROWSER",
79 "PYTHONUNBUFFERED",
80 "ELECTRON_RUN_AS_NODE",
81]);
82​
83export interface AntigravityProfile {
84 readonly platform: NodeJS.Platform;
85 readonly geminiHome: string;
86 readonly acpDirectory: string;
87 readonly tokenPath: string;
88 readonly browserCommand: string;
90​
91/**
92 * Credentials for the non-personal ACP auth methods. The agent reads the API
93 * key from its environment and the GCP project and location from
94 * `settings.json` in the profile. Empty strings mean "not set".
95 */
96export interface AntigravityAuthConfig {
97 readonly authMethod: AntigravityAuthMethod;
98 readonly apiKey: string;
99 readonly gcpProject: string;
100 readonly gcpLocation: string;
102​
103export const ANTIGRAVITY_PERSONAL_AUTH: AntigravityAuthConfig = {
104 authMethod: "oauth-personal",
105 apiKey: "",
106 gcpProject: "",
107 gcpLocation: "",
108};
109​
110/** True for the two methods that open a Google sign-in page. */
111export function antigravityAuthUsesBrowser(authMethod: AntigravityAuthMethod): boolean {
112 return authMethod === "oauth-personal" || authMethod === "oauth-business";
114​
115/** Label shown on the provider card once the method has authenticated. */
116export function antigravityAuthLabel(authMethod: AntigravityAuthMethod): string {
117 switch (authMethod) {
118 case "oauth-personal":
119 return "Google account";
120 case "oauth-business":
121 return "Gemini Enterprise";
122 case "gemini-api-key":
123 return "Gemini API key";
124 case "agent-platform":
125 return "Agent Platform";
126 }
128​
129/**
130 * Explains what is missing before a non-personal method can authenticate, or
131 * null when the config is complete. Personal sign-in never needs config.
132 */
133export function antigravityAuthConfigIssue(auth: AntigravityAuthConfig): string | null {
134 switch (auth.authMethod) {
135 case "oauth-personal":
136 return null;
137 case "oauth-business":
138 return auth.gcpProject && auth.gcpLocation
139 ? null
140 : "Gemini Enterprise needs a GCP project and location in the Antigravity provider settings.";
141 case "gemini-api-key":
142 return auth.apiKey ? null : "Enter a Gemini API key in the Antigravity provider settings.";
143 case "agent-platform":
144 return auth.apiKey || (auth.gcpProject && auth.gcpLocation)
145 ? null
146 : "Agent Platform needs an API key, or a GCP project and location, in the Antigravity provider settings.";
147 }
149​
150/**
151 * `settings.json` content for the agent's profile. `auth.type` names the
152 * selected method so a native logout clears only that method's credentials
153 * instead of every stored token. The GCP block feeds Enterprise and Agent
154 * Platform. Never holds a credential.
155 */
156export function antigravityProfileSettings(auth: AntigravityAuthConfig): string {
157 const gcp = {
158 ...(auth.gcpProject ? { project: auth.gcpProject } : {}),
159 ...(auth.gcpLocation ? { location: auth.gcpLocation } : {}),
160 };
161 return `${encodeProfileSettings({
162 auth: { type: auth.authMethod },
163 ...(Object.keys(gcp).length > 0 ? { gcp } : {}),
164 })}\n`;
166​
167export interface AntigravityAuthorizationUrl {
168 readonly authorizationUrl: string;
169 readonly redirectUri: string;
170 readonly state: string;
172​
173function authSupportError(detail: string) {
174 return new AcpErrors.AcpTransportError({ detail, cause: undefined });
176​
177/** Recognizes native auth failures and interactive login blocked by T3. */
178export function isAntigravitySignInRequiredError(error: unknown): boolean {
179 return (
180 (isAcpRequestError(error) && error.code === -32000) ||
181 (isAcpTransportError(error) && error.detail === ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE)
182 );
184​
185/** Keeps case-sensitive instance IDs separate on case-insensitive filesystems. */
186export function resolveAntigravityProfileDirectory(
187 stateDir: string,
188 instanceId: ProviderInstanceId,
189): string {
190 const directoryName = NodeCrypto.createHash("sha256").update(instanceId).digest("hex");
191 return NodePath.join(stateDir, "providers", "antigravity", directoryName);
193​
194function quoteBrowserArgument(value: string): string {
195 return `'${value.replaceAll("'", `'"'"'`)}'`;
197​
198function antigravityEnvironment(
199 profile: AntigravityProfile,
200 baseEnv: NodeJS.ProcessEnv,
201 auth: AntigravityAuthConfig,
202) {
203 const environment: NodeJS.ProcessEnv = {};
204 for (const [key, value] of Object.entries(baseEnv)) {
205 // Windows treats environment keys as case-insensitive. Remove aliases too.
206 if (!removedEnvironmentKeys.has(key.toUpperCase())) environment[key] = value;
207 }
208 // Only the configured method's credential reaches the agent. The agent
209 // prefers GOOGLE_API_KEY over the GCP pair for Agent Platform, so the pair
210 // goes through settings.json instead of the environment.
211 const credential =
212 auth.authMethod === "gemini-api-key" && auth.apiKey
213 ? { GEMINI_API_KEY: auth.apiKey }
214 : auth.authMethod === "agent-platform" && auth.apiKey
215 ? { GOOGLE_API_KEY: auth.apiKey }
216 : {};
217 return {
218 ...environment,
219 ...credential,
220 GEMINI_HOME: profile.geminiHome,
221 AGY_ACP_FORCE_FILE_STORAGE: "1",
222 BROWSER: profile.browserCommand,
223 PYTHONUNBUFFERED: "1",
224 ELECTRON_RUN_AS_NODE: "1",
225 };
227​
228/**
229 * The agent reads its user-global skills under `GEMINI_HOME`, which T3 points
230 * at the private profile. Link the two skill directories back to the user's
231 * real `~/.gemini` so global skills load, while MCP servers, hooks, and
232 * credentials stay isolated. Best effort: a link that cannot be made only
233 * costs global skills, never the session. A real directory at the link path
234 * is the user's own content and is left alone.
235 */
236const linkAntigravityUserSkills = Effect.fn("linkAntigravityUserSkills")(function* (input: {
237 readonly profileDirectory: string;
238 readonly userHome: string;
239 readonly platform: NodeJS.Platform;
240}): Effect.fn.Return<void, never, FileSystem.FileSystem | Path.Path> {
241 const fs = yield* FileSystem.FileSystem;
242 const path = yield* Path.Path;
243 const links = antigravityUserSkillDirectories(path, input.profileDirectory);
244 const targets = antigravityUserSkillDirectories(path, path.join(input.userHome, ".gemini"));
245 for (const [link, target] of [
246 [links[0], targets[0]],
247 [links[1], targets[1]],
248 ] as const) {
249 yield* Effect.gen(function* () {
250 const existing = yield* fs.readLink(link).pipe(
251 Effect.map((value): string | undefined => path.resolve(path.dirname(link), value)),
252 Effect.catch((error) =>
253 error.reason._tag === "NotFound" ? Effect.succeed(undefined) : Effect.fail(error),
254 ),
255 );
256 if (existing === target) return;
257 if (existing !== undefined) {
258 yield* fs.remove(link);
259 }
260 yield* fs.makeDirectory(path.dirname(link), { recursive: true });
261 yield* Effect.tryPromise(() =>
262 NodeFSP.symlink(target, link, input.platform === "win32" ? "junction" : "dir"),
263 );
264 }).pipe(
265 // A non-symlink at the link path fails `readLink`; anything else is a
266 // filesystem refusal. Both leave the profile usable.
267 Effect.catch((error) =>
268 Effect.logWarning("Antigravity user skills are not linked into the profile.", {
269 link,
270 target,
271 error,
272 }),
273 ),
274 );
275 }
276});
277​
278/** Prepares a private profile without reading or copying Google credentials. */
279export const prepareAntigravityProfile = Effect.fn("prepareAntigravityProfile")(function* (input: {
280 readonly profileDirectory: string;
281 readonly baseEnv?: NodeJS.ProcessEnv;
282 readonly runtimeExecutablePath?: string;
283 readonly platform?: NodeJS.Platform;
284 readonly auth?: AntigravityAuthConfig;
285 /** Home the agent expands `~` against. Defaults to the launch environment's. */
286 readonly userHome?: string;
287}) {
288 const auth = input.auth ?? ANTIGRAVITY_PERSONAL_AUTH;
289 const fs = yield* FileSystem.FileSystem;
290 const path = yield* Path.Path;
291 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
292 const platform = input.platform ?? (yield* HostProcessPlatform);
293 const userHome =
294 input.userHome ?? resolveAntigravityUserHome(platform, input.baseEnv ?? process.env);
295 const runtimeExecutablePath = input.runtimeExecutablePath ?? (yield* HostProcessExecutablePath);
296 const helperExecutable =
297 platform === "win32" ? runtimeExecutablePath.replaceAll("\\", "/") : runtimeExecutablePath;
298 const browserArguments = [helperExecutable, "-e", browserHelperSource, "--", "%s"];
299 const browserCommand = browserArguments.map(quoteBrowserArgument).join(" ");
300 if (
301 browserCommand.includes(platform === "win32" ? ";" : ":") ||
302 helperExecutable.includes("\r") ||
303 helperExecutable.includes("\n") ||
304 helperExecutable.includes("\0") ||
305 helperExecutable.includes("%s")
306 ) {
307 return yield* authSupportError(
308 "The T3 runtime path cannot be used to suppress Antigravity browser launches.",
309 );
310 }
311​
312 const geminiHome = path.resolve(input.profileDirectory);
313 const acpDirectory = path.join(geminiHome, "antigravity-acp");
314 const profile: AntigravityProfile = {
315 platform,
316 geminiHome,
317 acpDirectory,
318 tokenPath: path.join(acpDirectory, "acp_token.json"),
319 browserCommand,
320 };
321 const environment = antigravityEnvironment(profile, input.baseEnv ?? process.env, auth);
322 yield* Effect.gen(function* () {
323 const child = yield* spawner.spawn(
324 ChildProcess.make(helperExecutable, ["-e", browserHelperSource, "--", browserPreflightUrl], {
325 env: environment,
326 extendEnv: false,
327 shell: false,
328 }),
329 );
330 const [stdout, stderr, exitCode] = yield* Effect.all(
331 [
332 collectUint8StreamText({ stream: child.stdout, maxBytes: 4_096 }),
333 collectUint8StreamText({ stream: child.stderr, maxBytes: 4_096 }),
334 child.exitCode,
335 ],
336 { concurrency: "unbounded" },
337 );
338 if (
339 Number(exitCode) !== 0 ||
340 stdout.bytes !== 0 ||
341 stdout.truncated ||
342 stderr.truncated ||
343 stderr.text !== `${ANTIGRAVITY_AUTH_BROWSER_MARKER}"${browserPreflightUrl}"\n`
344 ) {
345 return yield* authSupportError("Antigravity browser suppression could not be verified.");
346 }
347 }).pipe(
348 Effect.scoped,
349 Effect.timeoutOrElse({
350 duration: "5 seconds",
351 orElse: () =>
352 Effect.fail(authSupportError("Antigravity browser suppression verification timed out.")),
353 }),
354 Effect.mapError((error) =>
355 error._tag === "AcpTransportError"
356 ? error
357 : authSupportError("Antigravity browser suppression could not be verified."),
358 ),
359 );
360​
361 for (const directory of [geminiHome, acpDirectory]) {
362 yield* fs
363 .makeDirectory(directory, { recursive: true, mode: 0o700 })
364 .pipe(
365 Effect.mapError(() =>
366 authSupportError("The Antigravity profile directory could not be created."),
367 ),
368 );
369 if (platform !== "win32") {
370 yield* fs
371 .chmod(directory, 0o700)
372 .pipe(
373 Effect.mapError(() =>
374 authSupportError("The Antigravity profile directory permissions could not be set."),
375 ),
376 );
377 }
378 }
379 // Rewriting on every launch keeps a method, project, or location edit in
380 // Settings effective. The agent also records auth.type here after a
381 // sign-in, which matches the value written below.
382 yield* fs
383 .writeFileString(path.join(acpDirectory, "settings.json"), antigravityProfileSettings(auth))
384 .pipe(
385 Effect.mapError(() =>
386 authSupportError("The Antigravity profile settings could not be written."),
387 ),
388 );
389 yield* linkAntigravityUserSkills({ profileDirectory: geminiHome, userHome, platform });
390 return profile;
391});
392​
393/** Applies the same subscription-only launch settings to every ACP process. */
394export function buildAntigravityAcpSpawnInput(input: {
395 readonly installation: {
396 readonly executablePath: string;
397 readonly harnessPath: string;
398 };
399 readonly profile: AntigravityProfile;
400 readonly cwd: string;
401 readonly baseEnv?: NodeJS.ProcessEnv;
402 readonly auth?: AntigravityAuthConfig;
403}): AcpSpawnInput {
404 return {
405 command: input.installation.executablePath,
406 args: input.profile.platform === "linux" ? ["--uid="] : [],
407 cwd: input.cwd,
408 env: {
409 ...antigravityEnvironment(
410 input.profile,
411 input.baseEnv ?? process.env,
412 input.auth ?? ANTIGRAVITY_PERSONAL_AUTH,
413 ),
414 ANTIGRAVITY_HARNESS_PATH: input.installation.harnessPath,
415 },
416 extendEnv: false,
417 };
419​
420/** Reads only the public authorization request, never an OAuth token file. */
421export const parseAntigravityAuthorizationUrl = Effect.fn("parseAntigravityAuthorizationUrl")(
422 function* (
423 authorizationUrl: string,
424 ): Effect.fn.Return<AntigravityAuthorizationUrl, AcpErrors.AcpError> {
425 const invalidUrl = () =>
426 authSupportError("Antigravity returned an invalid Google sign-in URL.");
427 if (authorizationUrl.length > maxAuthorizationUrlLength || /\s/.test(authorizationUrl)) {
428 return yield* invalidUrl();
429 }
430 const url = yield* decodeUrl(authorizationUrl).pipe(Effect.mapError(invalidUrl));
431 const state = url.searchParams.get("state");
432 const redirectUri = url.searchParams.get("redirect_uri");
433 if (
434 url.origin !== "https://accounts.google.com" ||
435 url.pathname !== "/o/oauth2/v2/auth" ||
436 url.username !== "" ||
437 url.password !== "" ||
438 url.hash !== "" ||
439 url.searchParams.getAll("state").length !== 1 ||
440 url.searchParams.getAll("redirect_uri").length !== 1 ||
441 url.searchParams.getAll("response_type").length !== 1 ||
442 url.searchParams.get("response_type") !== "code" ||
443 state === null ||
444 state.length === 0 ||
445 state.length > 512 ||
446 /\s/.test(state) ||
447 redirectUri === null ||
448 !/^http:\/\/127\.0\.0\.1:[1-9][0-9]{0,4}\/$/.test(redirectUri)
449 ) {
450 return yield* invalidUrl();
451 }
452 const redirect = yield* decodeUrl(redirectUri).pipe(Effect.mapError(invalidUrl));
453 if (Number(redirect.port) < 1_024) return yield* invalidUrl();
454 return { authorizationUrl, redirectUri, state };
455 },
456);
457​
458export function makeAntigravityStdoutTransform(
459 input: {
460 readonly onAuthorizationUrl?: (
461 authorizationUrl: string,
462 ) => Effect.Effect<void, AcpErrors.AcpError>;
463 } = {},
464) {
465 const handleLine = Effect.fn("antigravityAuthSupport.handleStdoutLine")(function* (
466 line: Uint8Array,
467 ) {
468 if (!authPrefixBytes.every((byte, index) => line[index] === byte)) return [line];
469 const message = new TextDecoder().decode(line).replace(/\r?\n$/, "");
470 const request = yield* parseAntigravityAuthorizationUrl(
471 message.slice(ANTIGRAVITY_AUTH_STDOUT_PREFIX.length),
472 );
473 if (!input.onAuthorizationUrl) {
474 return yield* authSupportError(ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE);
475 }
476 yield* input.onAuthorizationUrl(request.authorizationUrl);
477 return [];
478 });
479​
480 return (
481 stdout: ChildProcessSpawner.ChildProcessHandle["stdout"],
482 ): Stream.Stream<Uint8Array, PlatformError.PlatformError | AcpErrors.AcpError> =>
483 Stream.suspend(() => {
484 let pending: Uint8Array[] = [];
485 let pendingBytes = 0;
486 const finishLine = () => {
487 const line = Buffer.concat(pending, pendingBytes);
488 pending = [];
489 pendingBytes = 0;
490 return line;
491 };
492 return stdout.pipe(
493 Stream.mapEffect(
494 Effect.fn("antigravityAuthSupport.splitStdoutLines")(function* (chunk: Uint8Array) {
495 const lines: Uint8Array[] = [];
496 let offset = 0;
497 while (offset < chunk.byteLength) {
498 const newline = chunk.indexOf(10, offset);
499 const end = newline === -1 ? chunk.byteLength : newline + 1;
500 const part = chunk.subarray(offset, end);
501 if (pendingBytes + part.byteLength > maxStdoutLineBytes) {
502 return yield* authSupportError(
503 "Antigravity sent a protocol line that is too large.",
504 );
505 }
506 pending.push(part);
507 pendingBytes += part.byteLength;
508 if (newline !== -1) lines.push(finishLine());
509 offset = end;
510 }
511 return lines;
512 }),
513 ),
514 Stream.flatMap(Stream.fromIterable),
515 Stream.concat(
516 Stream.suspend(() => (pendingBytes > 0 ? Stream.succeed(finishLine()) : Stream.empty)),
517 ),
518 Stream.mapEffect(handleLine),
519 Stream.flatMap(Stream.fromIterable),
520 );
521 });
523​
524/** Receives native 1.1.1 sign-in URLs and T3 browser-helper URLs without logging stderr. */
525export function makeAntigravityStderrHandler(
526 input: {
527 readonly onAuthorizationUrl?: (
528 authorizationUrl: string,
529 ) => Effect.Effect<void, AcpErrors.AcpError>;
530 } = {},
531) {
532 let pending = "";
533 const handleLine = (line: string) => {
534 const message = line.endsWith("\r") ? line.slice(0, -1) : line;
535 if (message.length > maxBrowserHelperLineLength) {
536 return Effect.void;
537 }
538 const url = message.startsWith(ANTIGRAVITY_AUTH_STDOUT_PREFIX)
539 ? Effect.succeed(message.slice(ANTIGRAVITY_AUTH_STDOUT_PREFIX.length))
540 : message.startsWith(ANTIGRAVITY_AUTH_BROWSER_MARKER)
541 ? decodeBrowserHelperUrl(message.slice(ANTIGRAVITY_AUTH_BROWSER_MARKER.length))
542 : undefined;
543 if (url === undefined) return Effect.void;
544 return url.pipe(
545 Effect.flatMap(parseAntigravityAuthorizationUrl),
546 Effect.matchEffect({
547 onFailure: () => Effect.void,
548 onSuccess: (request) =>
549 input.onAuthorizationUrl
550 ? input.onAuthorizationUrl(request.authorizationUrl)
551 : Effect.fail(authSupportError(ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE)),
552 }),
553 );
554 };
555​
556 return Effect.fn("antigravityAuthSupport.handleStderr")(function* (text: string) {
557 const lines = `${pending}${text}`.split("\n");
558 pending = lines.pop() ?? "";
559 if (pending.length > maxBrowserHelperLineLength) pending = "";
560 yield* Effect.forEach(lines, handleLine, { discard: true });
561 });