@devries-cameron20 / t3code-1 / commits / 5283f33ca9
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(server): Antigravity limits read the 1.5.x CLI's stored sign-in (#38957)

Julius Marminge committed Nov 19, 2026 at 15:30 UTC 5283f33ca9d3515058a5686ea9a4e40a57ef23da
2 files changed +286 -41
apps/server/src/provider/antigravityUsageLimits.test.ts
+106 -2
@@ -1,5 +1,6 @@
1 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 +import * as HostProcess from "@t3tools/shared/HostProcess";
4 import * as Layer from "effect/Layer";
5 import { describe, expect, it } from "@effect/vitest";
6 import * as Context from "effect/Context";
@@ -10,7 +11,11 @@ import * as Path from "effect/Path";
11 import * as TestClock from "effect/testing/TestClock";
12 import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http";
13
13 -import { makeAntigravityUsageProbe } from "./antigravityUsageLimits.ts";
14 +import {
15 + decodeGoKeyringSecret,
16 + makeAntigravityUsageProbe,
17 + readWindowsCliCredential,
18 +} from "./antigravityUsageLimits.ts";
19
20 const summary = {
21 groups: [
@@ -66,6 +71,9 @@ const fixture = Effect.fn("AntigravityUsageTest.fixture")(function* (
71 userInfoAt?: number;
72 missingToken?: boolean;
73 authMethod?: "oauth-personal" | "oauth-business" | "gemini-api-key";
74 + keyringSecret?: string;
75 + /** Reads the OS keyring instead of `keyringSecret`. */
76 + nativeKeyring?: boolean;
77 } = {},
78 ) {
79 const fs = yield* FileSystem.FileSystem;
@@ -111,7 +119,7 @@ const fixture = Effect.fn("AntigravityUsageTest.fixture")(function* (
119 : Response.json({}, { status: 403 }),
120 );
121 }
114 - expect(JSON.parse(body)).toEqual({ project: "project-id" });
122 + expect(JSON.parse(body)).toEqual(options.missingToken ? {} : { project: "project-id" });
123 expect(request.headers["user-agent"]).toMatch(/^antigravity\/hub\/2\.24\.0 /);
124 return HttpClientResponse.fromWeb(
125 request,
@@ -132,6 +140,7 @@ const fixture = Effect.fn("AntigravityUsageTest.fixture")(function* (
140 const usage = yield* makeAntigravityUsageProbe({
141 profileDirectory,
142 authMethod: options.authMethod ?? "oauth-personal",
143 + ...(options.nativeKeyring ? {} : { readKeyringSecret: Effect.succeed(options.keyringSecret) }),
144 }).pipe(Effect.provideService(HttpClient.HttpClient, http));
145 return { ...usage, requests, writeToken, tokenPath };
146 });
@@ -654,6 +663,101 @@ describe("Antigravity subscription limits", () => {
663 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
664 );
665
666 + it.effect("reads the native CLI's stored sign-in when acp_token.json is absent", () =>
667 + Effect.gen(function* () {
668 + const fs = yield* FileSystem.FileSystem;
669 + const path = yield* Path.Path;
670 + const { probe, tokenPath } = yield* fixture({ missingToken: true });
671 + // The 1.5.x CLI never writes acp_token.json; without a keyring it stores this file instead.
672 + yield* fs.writeFileString(
673 + path.join(path.dirname(tokenPath), "antigravity-oauth-token"),
674 + JSON.stringify({
675 + token: {
676 + access_token: "access-token",
677 + token_type: "Bearer",
678 + refresh_token: "refresh-a",
679 + expiry: "2099-01-01T00:00:00Z",
680 + expires_in: 3600,
681 + },
682 + auth_method: "consumer",
683 + id_token_email: "someone@example.com",
684 + }),
685 + );
686 + const limits = yield* probe;
687 + expect(limits.unavailable?.message).not.toBe(
688 + "Sign in with Google to see Antigravity limits.",
689 + );
690 + expect(limits.unavailable?.reason).not.toBe("unsupported");
691 + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
692 + );
693 +
694 + it.effect("reads the native CLI's keyring sign-in and reports when it has expired", () =>
695 + Effect.gen(function* () {
696 + yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-09T12:00:00Z")));
697 + const keyringSecret = (expiry: string) =>
698 + JSON.stringify({ token: { access_token: "access-token", refresh_token: "r", expiry } });
699 + const signedIn = yield* fixture({
700 + missingToken: true,
701 + userId: "google-user-1",
702 + keyringSecret: keyringSecret("2026-10-09T14:00:00.123456789+01:00"),
703 + });
704 + const limits = yield* signedIn.probe;
705 + expect(limits.unavailable).toBeUndefined();
706 + expect(limits.windows).toHaveLength(4);
707 + expect(signedIn.requests.some((request) => request.url.endsWith("/token"))).toBe(false);
708 +
709 + const expired = yield* fixture({
710 + missingToken: true,
711 + keyringSecret: keyringSecret("2026-10-09T12:00:30Z"),
712 + });
713 + expect((yield* expired.probe).unavailable?.reason).toBe("probeFailed");
714 + expect(expired.requests).toEqual([]);
715 + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
716 + );
717 +
718 + it.effect.runIf(HostProcess.Platform.defaultValue() === "win32")(
719 + "reads go-keyring's Windows credential target without changing it",
720 + (ctx) =>
721 + Effect.gen(function* () {
722 + // Never overwrite a real sign-in on a developer's machine.
723 + if (readWindowsCliCredential(HostProcess.Architecture.defaultValue())) return ctx.skip();
724 + yield* TestClock.setTime(
725 + DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-09T12:00:00Z")),
726 + );
727 + const { AsyncEntry } = yield* Effect.promise(() => import("@napi-rs/keyring"));
728 + // go-keyring writes the UTF-8 JSON at `<service>:<user>`.
729 + const target = AsyncEntry.withTarget("gemini:antigravity", "gemini", "antigravity");
730 + const stored = new TextEncoder().encode(
731 + JSON.stringify({
732 + token: { access_token: "access-token", expiry: "2026-10-09T14:00:00Z" },
733 + }),
734 + );
735 + yield* Effect.acquireRelease(
736 + Effect.promise(() => target.setSecret(stored)),
737 + () => Effect.promise(() => target.deleteCredential()),
738 + );
739 + const { probe } = yield* fixture({ missingToken: true, nativeKeyring: true });
740 + const limits = yield* probe;
741 + expect(limits.unavailable).toBeUndefined();
742 + expect(limits.windows).toHaveLength(4);
743 + expect(readWindowsCliCredential(HostProcess.Architecture.defaultValue())).toEqual(
744 + Buffer.from(stored),
745 + );
746 + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
747 + );
748 +
749 + it("decodes go-keyring's macOS encodings", () => {
750 + const value = '{"token":{}}';
751 + const bytes = (text: string) => new TextEncoder().encode(text);
752 + expect(decodeGoKeyringSecret(bytes(value))).toBe(value);
753 + expect(
754 + decodeGoKeyringSecret(bytes(`go-keyring-base64:${Buffer.from(value).toString("base64")}`)),
755 + ).toBe(value);
756 + expect(
757 + decodeGoKeyringSecret(bytes(`go-keyring-encoded:${Buffer.from(value).toString("hex")}`)),
758 + ).toBe(value);
759 + });
760 +
761 it.effect("does not make network requests for API keys or missing sign-ins", () =>
762 Effect.gen(function* () {
763 for (const options of [{ authMethod: "gemini-api-key" as const }, { missingToken: true }]) {
apps/server/src/provider/antigravityUsageLimits.ts
+180 -39
@@ -1,3 +1,5 @@
1 +import * as NodeModule from "node:module";
2 +
3 import type { AntigravitySettings, ServerProviderUsageWindow } from "@t3tools/contracts";
4 import * as HostProcess from "@t3tools/shared/HostProcess";
5 import * as Clock from "effect/Clock";
@@ -38,6 +40,15 @@ const TokenFile = Schema.Struct({
40 refresh_token: Schema.NonEmptyString,
41 project_id: Schema.optional(Schema.String),
42 });
43 +// The 1.5.x CLI never writes acp_token.json: it keeps its sign-in in the OS keyring, or in
44 +// antigravity-oauth-token without one. It stores no OAuth client, so T3 cannot refresh it.
45 +const CliToken = Schema.Struct({
46 + token: Schema.Struct({
47 + access_token: Schema.NonEmptyString,
48 + refresh_token: Schema.optional(Schema.String),
49 + expiry: Schema.optional(Schema.String),
50 + }),
51 +});
52 const TokenResponse = Schema.Struct({
53 access_token: Schema.NonEmptyString,
54 expires_in: Schema.Number.check(Schema.isGreaterThan(0)),
@@ -78,6 +89,7 @@ const Models = Schema.Struct({
89 });
90
91 const decodeTokenFile = Schema.decodeEffect(Schema.fromJsonString(TokenFile));
92 +const decodeCliToken = Schema.decodeEffect(Schema.fromJsonString(CliToken));
93 const decodeTokenResponse = Schema.decodeUnknownEffect(TokenResponse);
94 const decodeUserInfo = Schema.decodeUnknownEffect(UserInfo);
95 const decodeSummary = Schema.decodeUnknownEffect(Summary);
@@ -132,6 +144,104 @@ const sha256 = Effect.fnUntraced(function* (text: string) {
144 return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
145 });
146
147 +/** go-keyring stores UTF-8, which it prefixes and encodes on macOS. */
148 +export function decodeGoKeyringSecret(secret: ArrayLike<number>): string {
149 + // The binding resolves a plain number array at runtime despite its Uint8Array type.
150 + const text = new TextDecoder().decode(Uint8Array.from(secret));
151 + if (text.startsWith("go-keyring-base64:")) {
152 + return Buffer.from(text.slice("go-keyring-base64:".length), "base64").toString("utf8");
153 + }
154 + if (text.startsWith("go-keyring-encoded:")) {
155 + return Buffer.from(text.slice("go-keyring-encoded:".length), "hex").toString("utf8");
156 + }
157 + return text;
158 +}
159 +
160 +class AntigravityKeyringError extends Schema.TaggedError<AntigravityKeyringError>()(
161 + "AntigravityKeyringError",
162 + { cause: Schema.Defect() },
163 +) {
164 + override get message(): string {
165 + return "Could not read the Antigravity sign-in from the system keyring.";
166 + }
167 +}
168 +
169 +// A single-executable server resolves packages on disk only through `require`.
170 +const requireExternal = NodeModule.createRequire(import.meta.url);
171 +
172 +/**
173 + * go-keyring's Windows target is `gemini:antigravity`; @napi-rs/keyring reads `antigravity.gemini`,
174 + * and its `withTarget` overwrites the target with an empty secret before reading.
175 + */
176 +export function readWindowsCliCredential(
177 + architecture: NodeJS.Architecture,
178 +): Uint8Array | undefined {
179 + // CREDENTIALW offsets and the pointers below are 64-bit.
180 + if (architecture !== "x64" && architecture !== "arm64") {
181 + throw new Error(`no credential access on ${architecture}`);
182 + }
183 + const { DataType, load, open } = requireExternal("ffi-rs") as typeof import("ffi-rs");
184 + open({ library: "t3-advapi32", path: "advapi32.dll" });
185 + open({ library: "t3-kernel32", path: "kernel32.dll" });
186 + const copy = (into: Buffer, from: bigint) =>
187 + load({
188 + library: "t3-kernel32",
189 + funcName: "RtlMoveMemory",
190 + retType: DataType.Void,
191 + paramsType: [DataType.U8Array, DataType.BigInt, DataType.BigInt],
192 + paramsValue: [into, from, BigInt(into.length)],
193 + });
194 + const out = Buffer.alloc(8);
195 + const read = load({
196 + library: "t3-advapi32",
197 + funcName: "CredReadW",
198 + retType: DataType.I32,
199 + // CRED_TYPE_GENERIC
200 + paramsType: [DataType.WString, DataType.U32, DataType.U32, DataType.U8Array],
201 + paramsValue: ["gemini:antigravity", 1, 0, out],
202 + errno: true as const,
203 + });
204 + if (read.value === 0) {
205 + // ERROR_NOT_FOUND
206 + if (read.errnoCode === 1168) return undefined;
207 + throw new Error(`CredReadW failed with Windows error ${read.errnoCode}`);
208 + }
209 + const credential = out.readBigUInt64LE();
210 + try {
211 + // CredentialBlobSize is a DWORD at 32 and CredentialBlob a pointer at 40.
212 + const header = Buffer.alloc(48);
213 + copy(header, credential);
214 + const size = header.readUInt32LE(32);
215 + if (size === 0) return undefined;
216 + const blob = Buffer.alloc(size);
217 + copy(blob, header.readBigUInt64LE(40));
218 + return blob;
219 + } finally {
220 + load({
221 + library: "t3-advapi32",
222 + funcName: "CredFree",
223 + retType: DataType.Void,
224 + paramsType: [DataType.BigInt],
225 + paramsValue: [credential],
226 + });
227 + }
228 +}
229 +
230 +// Loaded lazily: a native binding that fails to load must not take the provider down.
231 +const readCliKeyringSecret = (platform: NodeJS.Platform, architecture: NodeJS.Architecture) =>
232 + Effect.tryPromise({
233 + try: async () => {
234 + const secret =
235 + platform === "win32"
236 + ? readWindowsCliCredential(architecture)
237 + : await new (
238 + requireExternal("@napi-rs/keyring") as typeof import("@napi-rs/keyring")
239 + ).AsyncEntry("gemini", "antigravity").getSecret();
240 + return secret ? decodeGoKeyringSecret(secret) : undefined;
241 + },
242 + catch: (cause) => new AntigravityKeyringError({ cause }),
243 + });
244 +
245 /** Keys an account by its Google ID, which matches across machines and hubs; refresh tokens do not. */
246 export const antigravityAccountFingerprint = (userInfo: unknown) =>
247 decodeUserInfo(userInfo).pipe(Effect.flatMap((info) => sha256(`google-account\0${info.id}`)));
@@ -210,6 +320,7 @@ function modelWindows(models: typeof Models.Type) {
320 export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")(function* (input: {
321 readonly profileDirectory: string;
322 readonly authMethod: AntigravitySettings["authMethod"];
323 + readonly readKeyringSecret?: Effect.Effect<string | undefined, AntigravityKeyringError>;
324 }) {
325 const fs = yield* FileSystem.FileSystem;
326 const path = yield* Path.Path;
@@ -218,6 +329,12 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")(
329 const platform = yield* HostProcess.Platform;
330 const architecture = yield* HostProcess.Architecture;
331 const tokenPath = path.join(input.profileDirectory, "antigravity-acp", "acp_token.json");
332 + const cliTokenPath = path.join(
333 + input.profileDirectory,
334 + "antigravity-acp",
335 + "antigravity-oauth-token",
336 + );
337 + const readKeyringSecret = input.readKeyringSecret ?? readCliKeyringSecret(platform, architecture);
338 let cached:
339 | { fingerprint: string; account: string; accessToken: string; expiresAt: number }
340 | undefined;
@@ -236,54 +353,80 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")(
353 if (input.authMethod !== "oauth-personal" && input.authMethod !== "oauth-business") {
354 return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" });
355 }
239 - if (!(yield* fs.exists(tokenPath))) {
240 - cached = undefined;
241 - return makeUnavailableUsageLimits({
242 - checkedAt,
243 - reason: "unsupported",
244 - message: "Sign in with Google to see Antigravity limits.",
245 - });
246 - }
247 - const token = yield* fs.readFileString(tokenPath).pipe(Effect.flatMap(decodeTokenFile));
248 - const fingerprint = yield* sha256(
249 - `${token.client_id}\0${token.refresh_token}\0${token.project_id ?? ""}`,
250 - );
356 const now = yield* Clock.currentTimeMillis;
357 let accessToken: string;
358 let account: string;
254 - if (cached?.fingerprint !== fingerprint || cached.expiresAt <= now + 60_000) {
359 + let projectId: string | undefined;
360 + if (!(yield* fs.exists(tokenPath))) {
361 cached = undefined;
256 - const refreshed = yield* request(
257 - HttpClientRequest.post("https://oauth2.googleapis.com/token").pipe(
258 - HttpClientRequest.bodyUrlParams({
259 - client_id: token.client_id,
260 - client_secret: token.client_secret,
261 - refresh_token: token.refresh_token,
262 - grant_type: "refresh_token",
263 - }),
264 - ),
265 - ).pipe(Effect.flatMap(decodeTokenResponse));
266 - accessToken = refreshed.access_token;
267 - // Use Google account IDs to merge accounts across environments; refresh tokens differ per machine.
362 + const stored = (yield* fs.exists(cliTokenPath))
363 + ? yield* fs.readFileString(cliTokenPath)
364 + : yield* readKeyringSecret;
365 + if (stored === undefined) {
366 + return makeUnavailableUsageLimits({
367 + checkedAt,
368 + reason: "unsupported",
369 + message: "Sign in with Google to see Antigravity limits.",
370 + });
371 + }
372 + const { token } = yield* decodeCliToken(stored);
373 + if (!(Date.parse(token.expiry ?? "") > now + 60_000)) {
374 + return makeUnavailableUsageLimits({
375 + checkedAt,
376 + reason: "probeFailed",
377 + message:
378 + "Antigravity's saved sign-in has expired. Start an Antigravity turn to renew it, then refresh limits.",
379 + });
380 + }
381 + accessToken = token.access_token;
382 account = yield* request(
383 HttpClientRequest.get("https://www.googleapis.com/oauth2/v2/userinfo").pipe(
384 HttpClientRequest.setHeaders({ Authorization: `Bearer ${accessToken}` }),
385 ),
386 ).pipe(
387 Effect.flatMap(antigravityAccountFingerprint),
274 - Effect.orElseSucceed(() => fingerprint),
388 + Effect.catch(() => sha256(`antigravity-cli\0${token.refresh_token || accessToken}`)),
389 );
276 - if (generation === startedGeneration) {
277 - cached = {
278 - fingerprint,
279 - account,
280 - accessToken,
281 - expiresAt: now + refreshed.expires_in * 1000,
282 - };
283 - }
390 } else {
285 - accessToken = cached.accessToken;
286 - account = cached.account;
391 + const token = yield* fs.readFileString(tokenPath).pipe(Effect.flatMap(decodeTokenFile));
392 + projectId = token.project_id;
393 + const fingerprint = yield* sha256(
394 + `${token.client_id}\0${token.refresh_token}\0${token.project_id ?? ""}`,
395 + );
396 + if (cached?.fingerprint !== fingerprint || cached.expiresAt <= now + 60_000) {
397 + cached = undefined;
398 + const refreshed = yield* request(
399 + HttpClientRequest.post("https://oauth2.googleapis.com/token").pipe(
400 + HttpClientRequest.bodyUrlParams({
401 + client_id: token.client_id,
402 + client_secret: token.client_secret,
403 + refresh_token: token.refresh_token,
404 + grant_type: "refresh_token",
405 + }),
406 + ),
407 + ).pipe(Effect.flatMap(decodeTokenResponse));
408 + accessToken = refreshed.access_token;
409 + // Use Google account IDs to merge accounts across environments; refresh tokens differ per machine.
410 + account = yield* request(
411 + HttpClientRequest.get("https://www.googleapis.com/oauth2/v2/userinfo").pipe(
412 + HttpClientRequest.setHeaders({ Authorization: `Bearer ${accessToken}` }),
413 + ),
414 + ).pipe(
415 + Effect.flatMap(antigravityAccountFingerprint),
416 + Effect.orElseSucceed(() => fingerprint),
417 + );
418 + if (generation === startedGeneration) {
419 + cached = {
420 + fingerprint,
421 + account,
422 + accessToken,
423 + expiresAt: now + refreshed.expires_in * 1000,
424 + };
425 + }
426 + } else {
427 + accessToken = cached.accessToken;
428 + account = cached.account;
429 + }
430 }
431 const endpoints = ENDPOINTS[input.authMethod];
432 // 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")(
449 Authorization: `Bearer ${accessToken}`,
450 "User-Agent": antigravityUserAgent(platform, architecture),
451 }),
309 - HttpClientRequest.bodyJsonUnsafe(
310 - token.project_id ? { project: token.project_id } : {},
311 - ),
452 + HttpClientRequest.bodyJsonUnsafe(projectId ? { project: projectId } : {}),
453 ),
454 ).pipe(
455 Effect.flatMap((response) => parse(response, requestedAt)),