import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as ProcessRunner from "../processRunner.ts"; import { readWindowsGenericCredential } from "./windowsCredential.ts"; // The 1.5.x CLI keeps its sign-in in one OS keyring entry (go-keyring) shared by every profile on // the machine, or in the profile's own file when no keyring is usable. It stores no OAuth client, // so its access token is used until the CLI refreshes it. const KEYRING_SERVICE = "gemini"; const KEYRING_ACCOUNT = "antigravity"; const STORED_TOKEN_FILE = "antigravity-oauth-token"; const StoredToken = Schema.Struct({ token: Schema.Struct({ access_token: Schema.NonEmptyString, refresh_token: Schema.optional(Schema.String), expiry: Schema.String, }), id_token_email: Schema.optional(Schema.String), }); const decodeStoredToken = Schema.decodeEffect(Schema.fromJsonString(StoredToken)); export interface AntigravityStoredSignIn { readonly token: typeof StoredToken.Type.token; readonly email: string | undefined; /** Read from the machine-wide keyring entry, so other profiles and the Antigravity app use it too. */ readonly shared: boolean; } /** go-keyring writes UTF-8, prefixed and encoded on macOS. */ export function decodeGoKeyringSecret(secret: ArrayLike): string { const text = new TextDecoder().decode(Uint8Array.from(secret)); if (text.startsWith("go-keyring-base64:")) { return new TextDecoder().decode( Uint8Array.from(atob(text.slice("go-keyring-base64:".length)), (char) => char.charCodeAt(0)), ); } if (text.startsWith("go-keyring-encoded:")) { const hex = text.slice("go-keyring-encoded:".length); return new TextDecoder().decode( Uint8Array.from({ length: hex.length / 2 }, (_, index) => Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16), ), ); } return text; } export class AntigravityKeyringError extends Schema.TaggedError()( "AntigravityKeyringError", { cause: Schema.Defect() }, ) { override get message(): string { return "Could not read the Antigravity sign-in from the system keyring."; } } /** Reads the CLI's keyring entry; `undefined` when there is none. */ const readAntigravityKeyringSecret = Effect.fn("readAntigravityKeyringSecret")(function* ( platform: NodeJS.Platform, architecture: string, ) { let secret: ArrayLike | undefined; if (platform === "win32") { // go-keyring writes the Windows target `service:account`, which @napi-rs/keyring cannot read. secret = yield* Effect.try({ try: () => readWindowsGenericCredential(`${KEYRING_SERVICE}:${KEYRING_ACCOUNT}`, architecture), catch: (cause) => new AntigravityKeyringError({ cause }), }); } else if (platform === "darwin") { // The binding's Keychain reads drop errors, so a denied prompt would look like a sign-out. // This is go-keyring's own read; exit 44 is errSecItemNotFound. const runner = yield* ProcessRunner.make(); const result = yield* runner .run({ command: "/usr/bin/security", args: ["find-generic-password", "-s", KEYRING_SERVICE, "-wa", KEYRING_ACCOUNT], }) .pipe(Effect.mapError((cause) => new AntigravityKeyringError({ cause }))); if (result.code === 44) return undefined; if (result.code !== 0) { return yield* new AntigravityKeyringError({ cause: `security exited with ${result.code}` }); } secret = new TextEncoder().encode(result.stdout.trim()); } else { // Loading the native binding lazily keeps a broken binding from blocking server startup. const Keyring = yield* Effect.tryPromise({ try: () => import("@napi-rs/keyring"), catch: (cause) => new AntigravityKeyringError({ cause }), }); const entry = yield* Effect.try({ try: () => new Keyring.AsyncEntry(KEYRING_SERVICE, KEYRING_ACCOUNT), catch: (cause) => new AntigravityKeyringError({ cause }), }); // Typed `Uint8Array | undefined`, but the binding returns a plain byte array or `null`. secret = (yield* Effect.tryPromise({ try: () => entry.getSecret(), catch: (cause) => new AntigravityKeyringError({ cause }), })) ?? undefined; if (!secret) { // `getSecret` also resolves empty when the Secret Service is locked or unreachable, so // confirm the absence with a search, which rejects on those failures. const credentials = yield* Effect.tryPromise({ try: () => Keyring.findCredentialsAsync(KEYRING_SERVICE), catch: (cause) => new AntigravityKeyringError({ cause }), }); const password = credentials.find( (credential) => credential.account === KEYRING_ACCOUNT, )?.password; secret = password === undefined ? undefined : new TextEncoder().encode(password); } } if (!secret) return undefined; return yield* Effect.try({ try: () => decodeGoKeyringSecret(secret), catch: (cause) => new AntigravityKeyringError({ cause }), }); }); /** Reads the sign-in the 1.5.x CLI uses for a profile; `undefined` when it has none. */ export const makeAntigravityStoredSignInReader = Effect.fn("makeAntigravityStoredSignInReader")( function* (input: { readonly profileDirectory: string; /** Overrides the OS keyring read; tests must not touch the real keyring. */ readonly readKeyringSecret?: Effect.Effect; }) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const storedTokenPath = path.join(input.profileDirectory, "antigravity-acp", STORED_TOKEN_FILE); const readKeyringSecret = input.readKeyringSecret ?? readAntigravityKeyringSecret( yield* HostProcess.Platform, yield* HostProcess.Architecture, ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)); return Effect.gen(function* () { const inProfile = yield* fs.exists(storedTokenPath); const secret = inProfile ? yield* fs.readFileString(storedTokenPath) : yield* readKeyringSecret; if (secret === undefined) return undefined; const stored = yield* decodeStoredToken(secret); return { token: stored.token, email: stored.id_token_email?.trim() || undefined, shared: !inProfile, } satisfies AntigravityStoredSignIn; }); }, );