diff --git a/apps/server/src/provider/antigravityUsageLimits.test.ts b/apps/server/src/provider/antigravityUsageLimits.test.ts index 9defd9df90dce..6582fc2458577 100644 --- a/apps/server/src/provider/antigravityUsageLimits.test.ts +++ b/apps/server/src/provider/antigravityUsageLimits.test.ts @@ -1,5 +1,6 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Layer from "effect/Layer"; import { describe, expect, it } from "@effect/vitest"; import * as Context from "effect/Context"; @@ -10,7 +11,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 { + decodeGoKeyringSecret, + makeAntigravityUsageProbe, + readWindowsCliCredential, +} from "./antigravityUsageLimits.ts"; const summary = { groups: [ @@ -66,6 +71,9 @@ const fixture = Effect.fn("AntigravityUsageTest.fixture")(function* ( userInfoAt?: number; missingToken?: boolean; authMethod?: "oauth-personal" | "oauth-business" | "gemini-api-key"; + keyringSecret?: string; + /** Reads the OS keyring instead of `keyringSecret`. */ + nativeKeyring?: boolean; } = {}, ) { const fs = yield* FileSystem.FileSystem; @@ -111,7 +119,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 +140,7 @@ const fixture = Effect.fn("AntigravityUsageTest.fixture")(function* ( const usage = yield* makeAntigravityUsageProbe({ profileDirectory, authMethod: options.authMethod ?? "oauth-personal", + ...(options.nativeKeyring ? {} : { readKeyringSecret: Effect.succeed(options.keyringSecret) }), }).pipe(Effect.provideService(HttpClient.HttpClient, http)); return { ...usage, requests, writeToken, tokenPath }; }); @@ -654,6 +663,101 @@ describe("Antigravity subscription limits", () => { }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); + it.effect("reads the native CLI's stored sign-in when acp_token.json is absent", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { probe, tokenPath } = yield* fixture({ missingToken: true }); + // The 1.5.x CLI never writes acp_token.json; without a keyring it stores this file instead. + yield* fs.writeFileString( + path.join(path.dirname(tokenPath), "antigravity-oauth-token"), + JSON.stringify({ + token: { + access_token: "access-token", + token_type: "Bearer", + refresh_token: "refresh-a", + expiry: "2099-01-01T00:00:00Z", + expires_in: 3600, + }, + auth_method: "consumer", + id_token_email: "someone@example.com", + }), + ); + const limits = yield* probe; + expect(limits.unavailable?.message).not.toBe( + "Sign in with Google to see Antigravity limits.", + ); + expect(limits.unavailable?.reason).not.toBe("unsupported"); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + + it.effect("reads the native CLI's keyring sign-in and reports when it has expired", () => + Effect.gen(function* () { + yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-09T12:00:00Z"))); + const keyringSecret = (expiry: string) => + JSON.stringify({ token: { access_token: "access-token", refresh_token: "r", expiry } }); + const signedIn = yield* fixture({ + missingToken: true, + userId: "google-user-1", + keyringSecret: keyringSecret("2026-10-09T14:00:00.123456789+01:00"), + }); + const limits = yield* signedIn.probe; + expect(limits.unavailable).toBeUndefined(); + expect(limits.windows).toHaveLength(4); + expect(signedIn.requests.some((request) => request.url.endsWith("/token"))).toBe(false); + + const expired = yield* fixture({ + missingToken: true, + keyringSecret: keyringSecret("2026-10-09T12:00:30Z"), + }); + expect((yield* expired.probe).unavailable?.reason).toBe("probeFailed"); + expect(expired.requests).toEqual([]); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + + it.effect.runIf(HostProcess.Platform.defaultValue() === "win32")( + "reads go-keyring's Windows credential target without changing it", + (ctx) => + Effect.gen(function* () { + // Never overwrite a real sign-in on a developer's machine. + if (readWindowsCliCredential(HostProcess.Architecture.defaultValue())) return ctx.skip(); + yield* TestClock.setTime( + DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-09T12:00:00Z")), + ); + const { AsyncEntry } = yield* Effect.promise(() => import("@napi-rs/keyring")); + // go-keyring writes the UTF-8 JSON at `:`. + const target = AsyncEntry.withTarget("gemini:antigravity", "gemini", "antigravity"); + const stored = new TextEncoder().encode( + JSON.stringify({ + token: { access_token: "access-token", expiry: "2026-10-09T14:00:00Z" }, + }), + ); + yield* Effect.acquireRelease( + Effect.promise(() => target.setSecret(stored)), + () => Effect.promise(() => target.deleteCredential()), + ); + const { probe } = yield* fixture({ missingToken: true, nativeKeyring: true }); + const limits = yield* probe; + expect(limits.unavailable).toBeUndefined(); + expect(limits.windows).toHaveLength(4); + expect(readWindowsCliCredential(HostProcess.Architecture.defaultValue())).toEqual( + Buffer.from(stored), + ); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + + it("decodes go-keyring's macOS encodings", () => { + const value = '{"token":{}}'; + const bytes = (text: string) => new TextEncoder().encode(text); + expect(decodeGoKeyringSecret(bytes(value))).toBe(value); + expect( + decodeGoKeyringSecret(bytes(`go-keyring-base64:${Buffer.from(value).toString("base64")}`)), + ).toBe(value); + expect( + decodeGoKeyringSecret(bytes(`go-keyring-encoded:${Buffer.from(value).toString("hex")}`)), + ).toBe(value); + }); + it.effect("does not make network requests for API keys or missing sign-ins", () => Effect.gen(function* () { for (const options of [{ authMethod: "gemini-api-key" as const }, { missingToken: true }]) { diff --git a/apps/server/src/provider/antigravityUsageLimits.ts b/apps/server/src/provider/antigravityUsageLimits.ts index ede0e5c47d20e..77ac75c7a2f52 100644 --- a/apps/server/src/provider/antigravityUsageLimits.ts +++ b/apps/server/src/provider/antigravityUsageLimits.ts @@ -1,3 +1,5 @@ +import * as NodeModule from "node:module"; + import type { AntigravitySettings, ServerProviderUsageWindow } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Clock from "effect/Clock"; @@ -38,6 +40,15 @@ const TokenFile = Schema.Struct({ refresh_token: Schema.NonEmptyString, project_id: Schema.optional(Schema.String), }); +// The 1.5.x CLI never writes acp_token.json: it keeps its sign-in in the OS keyring, or in +// antigravity-oauth-token without one. It stores no OAuth client, so T3 cannot refresh it. +const CliToken = Schema.Struct({ + token: Schema.Struct({ + access_token: Schema.NonEmptyString, + refresh_token: Schema.optional(Schema.String), + expiry: Schema.optional(Schema.String), + }), +}); const TokenResponse = Schema.Struct({ access_token: Schema.NonEmptyString, expires_in: Schema.Number.check(Schema.isGreaterThan(0)), @@ -78,6 +89,7 @@ const Models = Schema.Struct({ }); const decodeTokenFile = Schema.decodeEffect(Schema.fromJsonString(TokenFile)); +const decodeCliToken = Schema.decodeEffect(Schema.fromJsonString(CliToken)); const decodeTokenResponse = Schema.decodeUnknownEffect(TokenResponse); const decodeUserInfo = Schema.decodeUnknownEffect(UserInfo); const decodeSummary = Schema.decodeUnknownEffect(Summary); @@ -132,6 +144,104 @@ const sha256 = Effect.fnUntraced(function* (text: string) { return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join(""); }); +/** go-keyring stores UTF-8, which it prefixes and encodes on macOS. */ +export function decodeGoKeyringSecret(secret: ArrayLike): string { + // The binding resolves a plain number array at runtime despite its Uint8Array type. + const text = new TextDecoder().decode(Uint8Array.from(secret)); + if (text.startsWith("go-keyring-base64:")) { + return Buffer.from(text.slice("go-keyring-base64:".length), "base64").toString("utf8"); + } + if (text.startsWith("go-keyring-encoded:")) { + return Buffer.from(text.slice("go-keyring-encoded:".length), "hex").toString("utf8"); + } + return text; +} + +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."; + } +} + +// A single-executable server resolves packages on disk only through `require`. +const requireExternal = NodeModule.createRequire(import.meta.url); + +/** + * go-keyring's Windows target is `gemini:antigravity`; @napi-rs/keyring reads `antigravity.gemini`, + * and its `withTarget` overwrites the target with an empty secret before reading. + */ +export function readWindowsCliCredential( + architecture: NodeJS.Architecture, +): Uint8Array | undefined { + // CREDENTIALW offsets and the pointers below are 64-bit. + if (architecture !== "x64" && architecture !== "arm64") { + throw new Error(`no credential access on ${architecture}`); + } + const { DataType, load, open } = requireExternal("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, + // CRED_TYPE_GENERIC + paramsType: [DataType.WString, DataType.U32, DataType.U32, DataType.U8Array], + paramsValue: ["gemini:antigravity", 1, 0, out], + errno: true as const, + }); + if (read.value === 0) { + // ERROR_NOT_FOUND + if (read.errnoCode === 1168) return undefined; + throw new Error(`CredReadW failed with Windows error ${read.errnoCode}`); + } + const credential = out.readBigUInt64LE(); + try { + // CredentialBlobSize is a DWORD at 32 and CredentialBlob a pointer at 40. + const header = Buffer.alloc(48); + 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], + }); + } +} + +// Loaded lazily: a native binding that fails to load must not take the provider down. +const readCliKeyringSecret = (platform: NodeJS.Platform, architecture: NodeJS.Architecture) => + Effect.tryPromise({ + try: async () => { + const secret = + platform === "win32" + ? readWindowsCliCredential(architecture) + : await new ( + requireExternal("@napi-rs/keyring") as typeof import("@napi-rs/keyring") + ).AsyncEntry("gemini", "antigravity").getSecret(); + return secret ? decodeGoKeyringSecret(secret) : undefined; + }, + catch: (cause) => new AntigravityKeyringError({ cause }), + }); + /** Keys an account by its Google ID, which matches across machines and hubs; refresh tokens do not. */ export const antigravityAccountFingerprint = (userInfo: unknown) => decodeUserInfo(userInfo).pipe(Effect.flatMap((info) => sha256(`google-account\0${info.id}`))); @@ -210,6 +320,7 @@ function modelWindows(models: typeof Models.Type) { export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")(function* (input: { readonly profileDirectory: string; readonly authMethod: AntigravitySettings["authMethod"]; + readonly readKeyringSecret?: Effect.Effect; }) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -218,6 +329,12 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")( const platform = yield* HostProcess.Platform; const architecture = yield* HostProcess.Architecture; const tokenPath = path.join(input.profileDirectory, "antigravity-acp", "acp_token.json"); + const cliTokenPath = path.join( + input.profileDirectory, + "antigravity-acp", + "antigravity-oauth-token", + ); + const readKeyringSecret = input.readKeyringSecret ?? readCliKeyringSecret(platform, architecture); let cached: | { fingerprint: string; account: string; accessToken: string; expiresAt: number } | undefined; @@ -236,54 +353,80 @@ 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))) { - cached = undefined; - return makeUnavailableUsageLimits({ - checkedAt, - reason: "unsupported", - 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 ?? ""}`, - ); const now = yield* Clock.currentTimeMillis; let accessToken: string; let account: string; - if (cached?.fingerprint !== fingerprint || cached.expiresAt <= now + 60_000) { + let projectId: string | undefined; + if (!(yield* fs.exists(tokenPath))) { 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; - // Use Google account IDs to merge accounts across environments; refresh tokens differ per machine. + const stored = (yield* fs.exists(cliTokenPath)) + ? yield* fs.readFileString(cliTokenPath) + : yield* readKeyringSecret; + if (stored === undefined) { + return makeUnavailableUsageLimits({ + checkedAt, + reason: "unsupported", + message: "Sign in with Google to see Antigravity limits.", + }); + } + const { token } = yield* decodeCliToken(stored); + if (!(Date.parse(token.expiry ?? "") > now + 60_000)) { + return makeUnavailableUsageLimits({ + checkedAt, + reason: "probeFailed", + message: + "Antigravity's saved sign-in has expired. Start an Antigravity turn to renew it, then refresh limits.", + }); + } + accessToken = token.access_token; account = yield* request( HttpClientRequest.get("https://www.googleapis.com/oauth2/v2/userinfo").pipe( HttpClientRequest.setHeaders({ Authorization: `Bearer ${accessToken}` }), ), ).pipe( Effect.flatMap(antigravityAccountFingerprint), - Effect.orElseSucceed(() => fingerprint), + Effect.catch(() => sha256(`antigravity-cli\0${token.refresh_token || accessToken}`)), ); - if (generation === startedGeneration) { - cached = { - fingerprint, - account, - accessToken, - expiresAt: now + refreshed.expires_in * 1000, - }; - } } else { - accessToken = cached.accessToken; - account = cached.account; + const token = yield* fs.readFileString(tokenPath).pipe(Effect.flatMap(decodeTokenFile)); + projectId = token.project_id; + const fingerprint = yield* sha256( + `${token.client_id}\0${token.refresh_token}\0${token.project_id ?? ""}`, + ); + 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; + // 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( + HttpClientRequest.setHeaders({ Authorization: `Bearer ${accessToken}` }), + ), + ).pipe( + Effect.flatMap(antigravityAccountFingerprint), + Effect.orElseSucceed(() => fingerprint), + ); + if (generation === startedGeneration) { + cached = { + fingerprint, + account, + accessToken, + expiresAt: now + refreshed.expires_in * 1000, + }; + } + } else { + accessToken = cached.accessToken; + account = cached.account; + } } const endpoints = ENDPOINTS[input.authMethod]; // Merge endpoints because quota groups differ; the metered host's reading of a bucket wins. @@ -306,9 +449,7 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")( Authorization: `Bearer ${accessToken}`, "User-Agent": antigravityUserAgent(platform, architecture), }), - HttpClientRequest.bodyJsonUnsafe( - token.project_id ? { project: token.project_id } : {}, - ), + HttpClientRequest.bodyJsonUnsafe(projectId ? { project: projectId } : {}), ), ).pipe( Effect.flatMap((response) => parse(response, requestedAt)),