Skip to content

Commit 7ad9a7b

Browse files
committed
fix(server): deliver Antigravity sign-in URLs without stderr
1 parent 7d62050 commit 7ad9a7b

3 files changed

Lines changed: 200 additions & 0 deletions

File tree

‎apps/server/src/provider/Drivers/AntigravityDriver.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import {
2929
isAntigravitySignInRequiredError,
3030
prepareAntigravityProfile,
3131
resolveAntigravityProfileDirectory,
32+
serveAntigravityAuthorizationUrlSink,
3233
type AntigravityAuthConfig,
3334
} from "../antigravityAuthSupport.ts";
3435
import {
@@ -154,6 +155,9 @@ export const AntigravityDriver: ProviderDriver<AntigravitySettings, AntigravityD
154155
Effect.provideService(Path.Path, path),
155156
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
156157
);
158+
const authorizationUrlSink = input.onAuthorizationUrl
159+
? yield* serveAntigravityAuthorizationUrlSink(input.onAuthorizationUrl)
160+
: undefined;
157161
const runtime = yield* makeAntigravityAcpRuntime({
158162
...input,
159163
authMethod: auth.authMethod,
@@ -164,6 +168,7 @@ export const AntigravityDriver: ProviderDriver<AntigravitySettings, AntigravityD
164168
cwd: input.cwd,
165169
baseEnv: processEnvironment,
166170
auth,
171+
...(authorizationUrlSink ? { authorizationUrlSink } : {}),
167172
}),
168173
}).pipe(Effect.provideService(Crypto.Crypto, crypto));
169174
return {

‎apps/server/src/provider/antigravityAuthSupport.test.ts‎

Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import * as Result from "effect/Result";
1212
import * as Schema from "effect/Schema";
1313
import * as Stream from "effect/Stream";
1414
import * as Ndjson from "effect/unstable/encoding/Ndjson";
15+
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http";
1516
import * as ChildProcess from "effect/unstable/process/ChildProcess";
1617
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
1718
import * as AcpErrors from "effect-acp/errors";
@@ -33,6 +34,7 @@ import {
3334
parseAntigravityAuthorizationUrl,
3435
prepareAntigravityProfile,
3536
resolveAntigravityProfileDirectory,
37+
serveAntigravityAuthorizationUrlSink,
3638
} from "./antigravityAuthSupport.ts";
3739

3840
const authorizationUrl =
@@ -75,6 +77,8 @@ describe("Antigravity process environment", () => {
7577
browser: "another-real-browser",
7678
PYTHONUNBUFFERED: "0",
7779
ELECTRON_RUN_AS_NODE: "0",
80+
T3_ANTIGRAVITY_AUTH_SINK: "http://127.0.0.1:1/stale",
81+
t3_antigravity_auth_sink: "http://127.0.0.1:2/stale-alias",
7882
CUSTOM_SETTING: "keep-this",
7983
};
8084
const original = { ...baseEnv };
@@ -105,6 +109,19 @@ describe("Antigravity process environment", () => {
105109
});
106110
});
107111

112+
it("passes only the current sign-in listener to the agent", () => {
113+
const sink = "http://127.0.0.1:46354/current-flow";
114+
const spawn = buildAntigravityAcpSpawnInput({
115+
installation: { executablePath: "/release/acp", harnessPath: "/release/harness" },
116+
profile,
117+
cwd: "/project",
118+
baseEnv: { t3_antigravity_auth_sink: "http://127.0.0.1:1/stale" },
119+
authorizationUrlSink: sink,
120+
});
121+
expect(spawn.env?.T3_ANTIGRAVITY_AUTH_SINK).toBe(sink);
122+
expect(spawn.env?.t3_antigravity_auth_sink).toBeUndefined();
123+
});
124+
108125
it("passes only the configured method's credential and keeps the GCP pair out of the environment", () => {
109126
const baseEnv = { PATH: "/usr/bin", GOOGLE_API_KEY: "ambient-key" };
110127
const spawnFor = (auth: AntigravityAuthConfig) =>
@@ -260,6 +277,69 @@ describe("Antigravity authorization URL", () => {
260277
);
261278
});
262279

280+
it.layer(FetchHttpClient.layer)("Antigravity authorization URL listener", (it) => {
281+
it.effect(
282+
"accepts only valid URLs on the current flow's POST endpoint and closes with its scope",
283+
() =>
284+
Effect.gen(function* () {
285+
const urls: string[] = [];
286+
const sink = yield* Effect.gen(function* () {
287+
const sink = yield* serveAntigravityAuthorizationUrlSink((url) =>
288+
Effect.sync(() => void urls.push(url)),
289+
);
290+
expect(new URL(sink).hostname).toBe("127.0.0.1");
291+
for (const [target, method, body, status] of [
292+
[sink, "GET", undefined, 404],
293+
[new URL("/wrong-flow", sink).href, "POST", authorizationUrl, 404],
294+
[sink, "POST", "not a Google authorization URL", 400],
295+
] as const) {
296+
const request = HttpClientRequest.make(method)(target);
297+
const response = yield* HttpClient.execute(
298+
body === undefined ? request : HttpClientRequest.bodyText(request, body),
299+
);
300+
expect(response.status).toBe(status);
301+
yield* response.arrayBuffer;
302+
}
303+
// The body limit can close the connection before an HTTP response is sent.
304+
const oversized = yield* HttpClient.execute(
305+
HttpClientRequest.post(sink).pipe(
306+
HttpClientRequest.bodyText(`${authorizationUrl}&scope=${"a".repeat(16_384)}`),
307+
),
308+
).pipe(Effect.result);
309+
if (Result.isSuccess(oversized)) {
310+
expect(oversized.success.status).toBe(400);
311+
yield* oversized.success.arrayBuffer;
312+
}
313+
expect(urls).toEqual([]);
314+
const response = yield* HttpClient.execute(
315+
HttpClientRequest.post(sink).pipe(HttpClientRequest.bodyText(authorizationUrl)),
316+
);
317+
expect(response.status).toBe(204);
318+
expect(urls).toEqual([authorizationUrl]);
319+
return sink;
320+
}).pipe(Effect.scoped);
321+
const closed = yield* HttpClient.execute(
322+
HttpClientRequest.post(sink).pipe(HttpClientRequest.bodyText(authorizationUrl)),
323+
).pipe(Effect.result);
324+
expect(Result.isFailure(closed)).toBe(true);
325+
expect(urls).toEqual([authorizationUrl]);
326+
}),
327+
);
328+
329+
it.effect("does not expose flow-owner failures in the HTTP response", () =>
330+
Effect.gen(function* () {
331+
const sink = yield* serveAntigravityAuthorizationUrlSink(() =>
332+
Effect.fail(AcpErrors.AcpRequestError.internalError("private flow details")),
333+
);
334+
const response = yield* HttpClient.execute(
335+
HttpClientRequest.post(sink).pipe(HttpClientRequest.bodyText(authorizationUrl)),
336+
);
337+
expect(response.status).toBe(400);
338+
expect(yield* response.text).toBe("");
339+
}).pipe(Effect.scoped),
340+
);
341+
});
342+
263343
describe("Antigravity sign-in errors", () => {
264344
it("recognizes native auth-required errors and the blocked-login transport error", () => {
265345
expect(isAntigravitySignInRequiredError(AcpErrors.AcpRequestError.authRequired())).toBe(true);
@@ -615,6 +695,65 @@ it.layer(NodeServices.layer)("Antigravity profile preparation", (it) => {
615695
}),
616696
);
617697

698+
it.effect(
699+
"delivers the helper URL without stdio and exits successfully after the listener closes",
700+
() =>
701+
Effect.gen(function* () {
702+
const fs = yield* FileSystem.FileSystem;
703+
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
704+
const temporaryDirectory = yield* fs.makeTempDirectoryScoped();
705+
let helperCommand: ChildProcess.StandardCommand | undefined;
706+
yield* prepareAntigravityProfile({ profileDirectory: temporaryDirectory }).pipe(
707+
Effect.provideService(
708+
ChildProcessSpawner.ChildProcessSpawner,
709+
ChildProcessSpawner.make((command) => {
710+
if (ChildProcess.isStandardCommand(command)) helperCommand = command;
711+
return spawner.spawn(command);
712+
}),
713+
),
714+
);
715+
expect(helperCommand).toBeDefined();
716+
if (!helperCommand) return;
717+
const command = helperCommand;
718+
const runHelper = (sink: string) =>
719+
Effect.gen(function* () {
720+
// Reproduce a Windows browser launch that loses the helper's stderr.
721+
const child = yield* Effect.acquireRelease(
722+
Effect.sync(() =>
723+
NodeChildProcess.spawn(
724+
command.command,
725+
[...command.args.slice(0, -1), authorizationUrl],
726+
{
727+
env: { ...command.options.env, T3_ANTIGRAVITY_AUTH_SINK: sink },
728+
stdio: "ignore",
729+
},
730+
),
731+
),
732+
(process) => Effect.sync(() => void process.kill()),
733+
);
734+
return yield* Effect.promise(
735+
() =>
736+
new Promise<number | null>((resolve, reject) => {
737+
child.once("error", reject);
738+
child.once("exit", resolve);
739+
}),
740+
);
741+
}).pipe(Effect.scoped);
742+
const urls: string[] = [];
743+
const sink = yield* Effect.gen(function* () {
744+
const sink = yield* serveAntigravityAuthorizationUrlSink((url) =>
745+
Effect.sync(() => void urls.push(url)),
746+
);
747+
expect(yield* runHelper(sink)).toBe(0);
748+
expect(urls).toEqual([authorizationUrl]);
749+
return sink;
750+
}).pipe(Effect.scoped);
751+
// Success prevents Python from falling back to a browser on the server after cancellation.
752+
expect(yield* runHelper(sink)).toBe(0);
753+
expect(urls).toEqual([authorizationUrl]);
754+
}),
755+
);
756+
618757
it.effect("fails before creating a profile when the helper cannot start", () =>
619758
Effect.gen(function* () {
620759
const fs = yield* FileSystem.FileSystem;

‎apps/server/src/provider/antigravityAuthSupport.ts‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,27 @@
11
import * as NodeCrypto from "node:crypto";
22
// @effect-diagnostics-next-line nodeBuiltinImport:off - Effect's symlink has no type argument, and Windows needs a junction to link without elevation.
33
import * as NodeFSP from "node:fs/promises";
4+
// @effect-diagnostics-next-line nodeBuiltinImport:off - The browser helper hands off URLs through a scoped Node loopback listener.
5+
import * as NodeHttp from "node:http";
46
// @effect-diagnostics-next-line nodeBuiltinImport:off - resolveAntigravityProfileDirectory is a pure sync helper, so it cannot use the Path service.
57
import * as NodePath from "node:path";
68

9+
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
710
import type { AntigravityAuthMethod, ProviderInstanceId } from "@t3tools/contracts";
811
import { HostProcessExecutablePath, HostProcessPlatform } from "@t3tools/shared/hostProcess";
912
import * as Effect from "effect/Effect";
1013
import * as FileSystem from "effect/FileSystem";
14+
import * as Layer from "effect/Layer";
1115
import * as Path from "effect/Path";
1216
import type * as PlatformError from "effect/PlatformError";
1317
import * as Schema from "effect/Schema";
1418
import * as Stream from "effect/Stream";
19+
import {
20+
HttpIncomingMessage,
21+
HttpServer,
22+
HttpServerRequest,
23+
HttpServerResponse,
24+
} from "effect/unstable/http";
1525
import * as ChildProcess from "effect/unstable/process/ChildProcess";
1626
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
1727
import * as AcpErrors from "effect-acp/errors";
@@ -55,6 +65,9 @@ const isAcpTransportError = Schema.is(AcpErrors.AcpTransportError);
5565
// Keep this source free of both colons and semicolons. EPIPE must still exit 0
5666
// so Python does not fall back to an OS browser after cancellation.
5767
const browserHelperSource =
68+
`(process.env.T3_ANTIGRAVITY_AUTH_SINK&&fetch(process.env.T3_ANTIGRAVITY_AUTH_SINK,` +
69+
`Object.fromEntries([["method","POST"],["body",process.argv[1]],` +
70+
`["signal",AbortSignal.timeout(5000)]])).then(()=>process.exit(0),()=>process.exit(0)))||` +
5871
`process.stderr.on("error",()=>process.exit(0)).write(` +
5972
`"${ANTIGRAVITY_AUTH_BROWSER_MARKER}"+JSON.stringify(process.argv[1])+"\\n",` +
6073
`()=>process.exit(0))`;
@@ -78,6 +91,7 @@ const removedEnvironmentKeys = new Set([
7891
"BROWSER",
7992
"PYTHONUNBUFFERED",
8093
"ELECTRON_RUN_AS_NODE",
94+
"T3_ANTIGRAVITY_AUTH_SINK",
8195
]);
8296

8397
export interface AntigravityProfile {
@@ -400,6 +414,7 @@ export function buildAntigravityAcpSpawnInput(input: {
400414
readonly cwd: string;
401415
readonly baseEnv?: NodeJS.ProcessEnv;
402416
readonly auth?: AntigravityAuthConfig;
417+
readonly authorizationUrlSink?: string;
403418
}): AcpSpawnInput {
404419
return {
405420
command: input.installation.executablePath,
@@ -412,11 +427,52 @@ export function buildAntigravityAcpSpawnInput(input: {
412427
input.auth ?? ANTIGRAVITY_PERSONAL_AUTH,
413428
),
414429
ANTIGRAVITY_HARNESS_PATH: input.installation.harnessPath,
430+
...(input.authorizationUrlSink
431+
? { T3_ANTIGRAVITY_AUTH_SINK: input.authorizationUrlSink }
432+
: {}),
415433
},
416434
extendEnv: false,
417435
};
418436
}
419437

438+
/** Python's Windows browser subprocess can lose stderr; receive the URL independently of stdio. */
439+
export const serveAntigravityAuthorizationUrlSink = Effect.fn(
440+
"serveAntigravityAuthorizationUrlSink",
441+
)(function* (onAuthorizationUrl: (url: string) => Effect.Effect<void, AcpErrors.AcpError>) {
442+
const token = NodeCrypto.randomBytes(32).toString("hex");
443+
const context = yield* Layer.build(
444+
NodeHttpServer.layer(NodeHttp.createServer, {
445+
host: "127.0.0.1",
446+
port: 0,
447+
disablePreemptiveShutdown: true,
448+
}),
449+
).pipe(
450+
Effect.mapError(() =>
451+
authSupportError("The Antigravity sign-in URL listener could not start."),
452+
),
453+
);
454+
const server = yield* Effect.service(HttpServer.HttpServer).pipe(Effect.provide(context));
455+
yield* server.serve(
456+
Effect.gen(function* () {
457+
const request = yield* HttpServerRequest.HttpServerRequest;
458+
if (request.method !== "POST" || request.url !== `/${token}`) {
459+
return HttpServerResponse.empty({ status: 404 });
460+
}
461+
const url = yield* request.text;
462+
const parsed = yield* parseAntigravityAuthorizationUrl(url);
463+
yield* onAuthorizationUrl(parsed.authorizationUrl);
464+
return HttpServerResponse.empty({ status: 204 });
465+
}).pipe(
466+
Effect.provideService(
467+
HttpIncomingMessage.MaxBodySize,
468+
FileSystem.Size(maxAuthorizationUrlLength),
469+
),
470+
Effect.catch(() => Effect.succeed(HttpServerResponse.empty({ status: 400 }))),
471+
),
472+
);
473+
return `${HttpServer.formatAddress(server.address)}/${token}`;
474+
});
475+
420476
/** Reads only the public authorization request, never an OAuth token file. */
421477
export const parseAntigravityAuthorizationUrl = Effect.fn("parseAntigravityAuthorizationUrl")(
422478
function* (

0 commit comments

Comments
 (0)