diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.ts index 2491b5ef46442..1291a908a6204 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts @@ -443,6 +443,7 @@ export const AntigravityDriver: ProviderDriver< Effect.provideService(Path.Path, path), Effect.provideService(Digest.Digest, digest), Effect.provideService(HttpClient.HttpClient, httpClient), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), ); const provider = yield* makeAntigravityProvider(settings, { environment: processEnvironment, diff --git a/apps/server/src/provider/antigravityUsageLimits.test.ts b/apps/server/src/provider/antigravityUsageLimits.test.ts index 9defd9df90dce..3bf3c6d30ab7f 100644 --- a/apps/server/src/provider/antigravityUsageLimits.test.ts +++ b/apps/server/src/provider/antigravityUsageLimits.test.ts @@ -10,7 +10,11 @@ import * as Path from "effect/Path"; import * as TestClock from "effect/testing/TestClock"; import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http"; -import { makeAntigravityUsageProbe } from "./antigravityUsageLimits.ts"; +import { + AntigravityKeyringError, + decodeGoKeyringSecret, + makeAntigravityUsageProbe, +} from "./antigravityUsageLimits.ts"; const summary = { groups: [ @@ -66,6 +70,9 @@ const fixture = Effect.fn("AntigravityUsageTest.fixture")(function* ( userInfoAt?: number; missingToken?: boolean; authMethod?: "oauth-personal" | "oauth-business" | "gemini-api-key"; + /** The 1.5.x CLI's stored sign-in, from the OS keyring or its fallback file. */ + storedToken?: { readonly expiry: string; readonly in: "keyring" | "file" }; + readKeyringSecret?: Effect.Effect; } = {}, ) { const fs = yield* FileSystem.FileSystem; @@ -84,6 +91,25 @@ const fixture = Effect.fn("AntigravityUsageTest.fixture")(function* ( }), ); if (!options.missingToken) yield* writeToken(options.refreshToken ?? "refresh-a"); + const storedToken = options.storedToken + ? JSON.stringify({ + token: { + access_token: "access-token", + token_type: "Bearer", + refresh_token: "cli-refresh", + expiry: options.storedToken.expiry, + expires_in: 3599, + }, + auth_method: "consumer", + id_token_email: "someone@example.com", + }) + : undefined; + if (storedToken && options.storedToken?.in === "file") { + yield* fs.writeFileString( + path.join(profileDirectory, "antigravity-acp", "antigravity-oauth-token"), + storedToken, + ); + } const requests: Array<{ url: string; body: string }> = []; const http = HttpClient.make((request, url, _signal, fiber) => Effect.sync(() => { @@ -111,7 +137,7 @@ const fixture = Effect.fn("AntigravityUsageTest.fixture")(function* ( : Response.json({}, { status: 403 }), ); } - expect(JSON.parse(body)).toEqual({ project: "project-id" }); + expect(JSON.parse(body)).toEqual(options.missingToken ? {} : { project: "project-id" }); expect(request.headers["user-agent"]).toMatch(/^antigravity\/hub\/2\.24\.0 /); return HttpClientResponse.fromWeb( request, @@ -132,6 +158,9 @@ const fixture = Effect.fn("AntigravityUsageTest.fixture")(function* ( const usage = yield* makeAntigravityUsageProbe({ profileDirectory, authMethod: options.authMethod ?? "oauth-personal", + readKeyringSecret: + options.readKeyringSecret ?? + Effect.succeed(options.storedToken?.in === "keyring" ? storedToken : undefined), }).pipe(Effect.provideService(HttpClient.HttpClient, http)); return { ...usage, requests, writeToken, tokenPath }; }); @@ -663,4 +692,68 @@ describe("Antigravity subscription limits", () => { } }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); + it.effect("reads the Antigravity CLI's keyring sign-in without refreshing it", () => + Effect.gen(function* () { + const { probe, requests } = yield* fixture({ + missingToken: true, + userId: "google-user-1", + storedToken: { expiry: "2026-10-09T12:00:00.123456789+11:00", in: "keyring" }, + }); + const limits = yield* probe; + expect(limits.unavailable).toBeUndefined(); + expect(limits.windows).toHaveLength(4); + expect(limits.credentialFingerprint).toMatch(/^[0-9a-f]{64}$/); + expect(requests.some((request) => request.url.endsWith("/token"))).toBe(false); + expect(JSON.stringify(limits)).not.toMatch(/cli-refresh|access-token|someone@example.com/); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + + it.effect("reads the CLI's token file before the keyring", () => + Effect.gen(function* () { + const { probe } = yield* fixture({ + missingToken: true, + storedToken: { expiry: "2026-10-09T12:00:00Z", in: "file" }, + readKeyringSecret: Effect.die("the keyring must not be read"), + }); + expect((yield* probe).windows).toHaveLength(4); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + + it.effect("waits for the CLI to refresh an expired stored sign-in", () => + Effect.gen(function* () { + yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-09T12:00:00Z"))); + const { probe, requests } = yield* fixture({ + missingToken: true, + storedToken: { expiry: "2026-10-09T12:00:30Z", in: "keyring" }, + }); + const limits = yield* probe; + expect(limits.unavailable).toEqual({ + reason: "probeFailed", + message: "Antigravity limits update when an Antigravity session starts.", + }); + expect(requests).toEqual([]); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + + it.effect("returns a safe failure when the keyring cannot be read", () => + Effect.gen(function* () { + const { probe, requests } = yield* fixture({ + missingToken: true, + readKeyringSecret: Effect.fail(new AntigravityKeyringError({ cause: "keyring locked" })), + }); + expect((yield* probe).unavailable?.reason).toBe("probeFailed"); + expect(requests).toEqual([]); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + + it("decodes go-keyring's macOS encodings and leaves plain values alone", () => { + const bytes = (text: string) => Array.from(new TextEncoder().encode(text)); + const value = '{"token":{}}'; + expect(decodeGoKeyringSecret(bytes(value))).toBe(value); + expect(decodeGoKeyringSecret(bytes(`go-keyring-base64:${btoa(value)}`))).toBe(value); + const hex = Array.from(new TextEncoder().encode(value), (byte) => + byte.toString(16).padStart(2, "0"), + ).join(""); + expect(decodeGoKeyringSecret(bytes(`go-keyring-encoded:${hex}`))).toBe(value); + }); }); diff --git a/apps/server/src/provider/antigravityUsageLimits.ts b/apps/server/src/provider/antigravityUsageLimits.ts index ede0e5c47d20e..2d07073e1c7ce 100644 --- a/apps/server/src/provider/antigravityUsageLimits.ts +++ b/apps/server/src/provider/antigravityUsageLimits.ts @@ -8,6 +8,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; import { @@ -15,6 +16,9 @@ import { makeUsageLimits, } from "@t3tools/provider-core/server/usageLimits"; +import * as ProcessRunner from "../processRunner.ts"; +import { readWindowsGenericCredential } from "./windowsCredential.ts"; + export function antigravityUserAgent(platform: NodeJS.Platform, architecture: NodeJS.Architecture) { return `antigravity/hub/2.24.0 (aidev_client; os_type=${platform}; arch=${architecture}; cl=963137146)`; } @@ -38,6 +42,18 @@ const TokenFile = Schema.Struct({ refresh_token: Schema.NonEmptyString, project_id: Schema.optional(Schema.String), }); +// The 1.5.x CLI keeps its sign-in in the OS keyring (go-keyring), or in a 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, + }), +}); const TokenResponse = Schema.Struct({ access_token: Schema.NonEmptyString, expires_in: Schema.Number.check(Schema.isGreaterThan(0)), @@ -78,6 +94,7 @@ const Models = Schema.Struct({ }); const decodeTokenFile = Schema.decodeEffect(Schema.fromJsonString(TokenFile)); +const decodeStoredToken = Schema.decodeEffect(Schema.fromJsonString(StoredToken)); const decodeTokenResponse = Schema.decodeUnknownEffect(TokenResponse); const decodeUserInfo = Schema.decodeUnknownEffect(UserInfo); const decodeSummary = Schema.decodeUnknownEffect(Summary); @@ -124,6 +141,98 @@ function summaryResetTime( return untouched ? undefined : bucket.resetTime; } +/** 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 }), + }); +}); + const sha256 = Effect.fnUntraced(function* (text: string) { const digest = yield* (yield* Digest.Digest).digest( Digest.sha256, @@ -210,6 +319,8 @@ function modelWindows(models: typeof Models.Type) { export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")(function* (input: { readonly profileDirectory: string; readonly authMethod: AntigravitySettings["authMethod"]; + /** 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; @@ -217,7 +328,20 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")( const crypto = yield* Digest.Digest; const platform = yield* HostProcess.Platform; const architecture = yield* HostProcess.Architecture; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const tokenPath = path.join(input.profileDirectory, "antigravity-acp", "acp_token.json"); + const storedTokenPath = path.join(input.profileDirectory, "antigravity-acp", STORED_TOKEN_FILE); + const readKeyringSecret = + input.readKeyringSecret ?? + readAntigravityKeyringSecret(platform, architecture).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + const readStoredToken = Effect.gen(function* () { + const secret = (yield* fs.exists(storedTokenPath)) + ? yield* fs.readFileString(storedTokenPath) + : yield* readKeyringSecret; + return secret === undefined ? undefined : yield* decodeStoredToken(secret); + }); let cached: | { fingerprint: string; account: string; accessToken: string; expiresAt: number } | undefined; @@ -236,7 +360,12 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")( if (input.authMethod !== "oauth-personal" && input.authMethod !== "oauth-business") { return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" }); } - if (!(yield* fs.exists(tokenPath))) { + // The 1.4.5 runtime's token file can be refreshed here; the 1.5.x CLI's stored token cannot. + const token = (yield* fs.exists(tokenPath)) + ? yield* fs.readFileString(tokenPath).pipe(Effect.flatMap(decodeTokenFile)) + : undefined; + const stored = token ? undefined : yield* readStoredToken; + if (!token && !stored) { cached = undefined; return makeUnavailableUsageLimits({ checkedAt, @@ -244,26 +373,43 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")( message: "Sign in with Google to see Antigravity limits.", }); } - const token = yield* fs.readFileString(tokenPath).pipe(Effect.flatMap(decodeTokenFile)); const fingerprint = yield* sha256( - `${token.client_id}\0${token.refresh_token}\0${token.project_id ?? ""}`, + token + ? `${token.client_id}\0${token.refresh_token}\0${token.project_id ?? ""}` + : `cli\0${stored?.token.refresh_token || stored?.token.access_token}`, ); const now = yield* Clock.currentTimeMillis; + const storedExpiresAt = stored ? Date.parse(stored.token.expiry) : Number.NaN; + if (stored && !(storedExpiresAt > now + 60_000)) { + return makeUnavailableUsageLimits({ + checkedAt, + reason: "probeFailed", + message: "Antigravity limits update when an Antigravity session starts.", + }); + } let accessToken: string; let account: string; if (cached?.fingerprint !== fingerprint || cached.expiresAt <= now + 60_000) { cached = undefined; - const refreshed = yield* request( - HttpClientRequest.post("https://oauth2.googleapis.com/token").pipe( - HttpClientRequest.bodyUrlParams({ - client_id: token.client_id, - client_secret: token.client_secret, - refresh_token: token.refresh_token, - grant_type: "refresh_token", - }), - ), - ).pipe(Effect.flatMap(decodeTokenResponse)); - accessToken = refreshed.access_token; + const refreshed = token + ? yield* request( + HttpClientRequest.post("https://oauth2.googleapis.com/token").pipe( + HttpClientRequest.bodyUrlParams({ + client_id: token.client_id, + client_secret: token.client_secret, + refresh_token: token.refresh_token, + grant_type: "refresh_token", + }), + ), + ).pipe( + Effect.flatMap(decodeTokenResponse), + Effect.map((response) => ({ + accessToken: response.access_token, + expiresAt: now + response.expires_in * 1000, + })), + ) + : { accessToken: stored?.token.access_token ?? "", expiresAt: storedExpiresAt }; + accessToken = refreshed.accessToken; // Use Google account IDs to merge accounts across environments; refresh tokens differ per machine. account = yield* request( HttpClientRequest.get("https://www.googleapis.com/oauth2/v2/userinfo").pipe( @@ -278,7 +424,7 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")( fingerprint, account, accessToken, - expiresAt: now + refreshed.expires_in * 1000, + expiresAt: refreshed.expiresAt, }; } } else { @@ -307,7 +453,7 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")( "User-Agent": antigravityUserAgent(platform, architecture), }), HttpClientRequest.bodyJsonUnsafe( - token.project_id ? { project: token.project_id } : {}, + token?.project_id ? { project: token.project_id } : {}, ), ), ).pipe( diff --git a/apps/server/src/provider/windowsCredential.ts b/apps/server/src/provider/windowsCredential.ts new file mode 100644 index 0000000000000..ddc0a55f3e1b9 --- /dev/null +++ b/apps/server/src/provider/windowsCredential.ts @@ -0,0 +1,65 @@ +import * as NodeModule from "node:module"; + +// A single-executable server resolves packages on disk only through `require`. +const requireForFfi = NodeModule.createRequire(import.meta.url); + +const CRED_TYPE_GENERIC = 1; +const ERROR_NOT_FOUND = 1168; +// x64 and arm64 CREDENTIALW: CredentialBlobSize is a DWORD at 32, CredentialBlob a pointer at 40. +const CREDENTIAL_SIZE = 48; + +/** + * Reads a generic Credential Manager entry's raw blob, or `undefined` when it does not exist. + * Read-only: @napi-rs/keyring's `withTarget` writes an empty secret before it reads. + */ +export function readWindowsGenericCredential( + target: string, + architecture: string, +): Uint8Array | undefined { + if (architecture !== "x64" && architecture !== "arm64") { + throw new Error(`no credential access on ${architecture}`); + } + const { DataType, load, open } = requireForFfi("ffi-rs") as typeof import("ffi-rs"); + open({ library: "t3-advapi32", path: "advapi32.dll" }); + open({ library: "t3-kernel32", path: "kernel32.dll" }); + const copy = (into: Buffer, from: bigint) => + load({ + library: "t3-kernel32", + funcName: "RtlMoveMemory", + retType: DataType.Void, + paramsType: [DataType.U8Array, DataType.BigInt, DataType.BigInt], + paramsValue: [into, from, BigInt(into.length)], + }); + + const out = Buffer.alloc(8); + const read = load({ + library: "t3-advapi32", + funcName: "CredReadW", + retType: DataType.I32, + paramsType: [DataType.WString, DataType.U32, DataType.U32, DataType.U8Array], + paramsValue: [target, CRED_TYPE_GENERIC, 0, out], + errno: true as const, + }); + if (read.value === 0) { + if (read.errnoCode === ERROR_NOT_FOUND) return undefined; + throw new Error(`CredReadW failed: Windows error ${read.errnoCode}`); + } + const credential = out.readBigUInt64LE(); + try { + const header = Buffer.alloc(CREDENTIAL_SIZE); + copy(header, credential); + const size = header.readUInt32LE(32); + if (size === 0) return undefined; + const blob = Buffer.alloc(size); + copy(blob, header.readBigUInt64LE(40)); + return blob; + } finally { + load({ + library: "t3-advapi32", + funcName: "CredFree", + retType: DataType.Void, + paramsType: [DataType.BigInt], + paramsValue: [credential], + }); + } +} diff --git a/docs/user/providers-antigravity.md b/docs/user/providers-antigravity.md index c62cc56b310d6..ba40ae9acd018 100644 --- a/docs/user/providers-antigravity.md +++ b/docs/user/providers-antigravity.md @@ -161,6 +161,11 @@ Open **Usage > Limits** to see the remaining Gemini and shared Claude/GPT allowa for Google sign-ins. Each group has separate five-hour and weekly limits and reset times. Limits refresh with provider status and include usage outside T3 Code. +Antigravity 1.5 and later keeps its Google sign-in in your system keyring (Keychain on +macOS, Credential Manager on Windows, Secret Service on Linux). T3 Code reads that sign-in +to check limits, so your keyring may ask you to allow access the first time. Antigravity +renews the sign-in only while it runs, so limits update when an Antigravity session starts. + A server restart keeps your Google sign-in. The provider shows the saved account until a session, a refresh, or a sign-out reports something new.