Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AntigravityAuth.ts

589 lines21.6 KB

1import {
2 ProviderSetupError,
3 type ProviderAuthState,
4 type ProviderInstanceId,
5} from "@t3tools/contracts";
6import * as Cause from "effect/Cause";
7import * as Clock from "effect/Clock";
8import * as SecureRandom from "effect/crypto/SecureRandom";
9import * as DateTime from "effect/DateTime";
10import * as Deferred from "effect/Deferred";
11import * as Effect from "effect/Effect";
12import * as Exit from "effect/Exit";
13import * as Fiber from "effect/Fiber";
14import * as Option from "effect/Option";
15import * as Schema from "effect/Schema";
16import * as Scope from "effect/Scope";
17import * as Semaphore from "effect/Semaphore";
18import * as Stream from "effect/Stream";
19import * as SubscriptionRef from "effect/SubscriptionRef";
20import * as AcpErrors from "effect-acp/errors";
21​
22import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
23import {
24 parseAntigravityAuthorizationUrl,
25 type AntigravityAuthorizationUrl,
26} from "./antigravityAuthSupport.ts";
27import {
28 forwardAntigravityCallback,
29 validateAntigravityCallbackUrl,
30} from "./antigravityCallback.ts";
31import type { ProviderAuthController } from "./ProviderAuthService.ts";
32​
33const AUTH_TIMEOUT_MS = 300_000;
34// Once initialized, a healthy agent shows the Google link or finishes within seconds. Its bundled
35// Python has no IPv4 fallback race, so a host with broken IPv6 waits about two minutes per Google
36// request. The hint is timed from initialize, not spawn: the one-file runtime unpacks itself on
37// every launch, which can take about a minute on Windows before it answers at all.
38const NO_RESPONSE_HINT_MS = 30_000;
39const NO_RESPONSE_MESSAGE =
40 "Antigravity has not reached Google after 30 seconds. Check this machine's network connection. Broken IPv6 is a common cause.";
41const UNREACHABLE_MESSAGE =
42 "Antigravity could not reach Google. Check this machine's network connection, then start sign-in again.";
43const FORWARDING_FAILED_MESSAGE = "Could not deliver the sign-in response. Start sign-in again.";
44const isSetupError = Schema.is(ProviderSetupError);
45const isAcpRequestError = Schema.is(AcpErrors.AcpRequestError);
46​
47interface AuthSnapshot {
48 readonly ownerSessionId: string | null;
49 readonly state: ProviderAuthState;
51​
52interface AuthFlow {
53 readonly id: string;
54 readonly ownerSessionId: string;
55 readonly expiresAtMillis: number;
56 state: ProviderAuthState;
57 pending: AntigravityAuthorizationUrl | undefined;
58 callbackSent: boolean;
59 fiber: Fiber.Fiber<void> | undefined;
60 forwarding: Fiber.Fiber<void, ProviderSetupError> | undefined;
62​
63interface OwnedProcess {
64 readonly stop: Effect.Effect<void>;
65 startup: Fiber.Fiber<unknown, unknown> | undefined;
67​
68export interface AntigravityAuth {
69 readonly controller: ProviderAuthController;
70 readonly withProcess: <A, E, R>(
71 stop: Effect.Effect<void>,
72 task: Effect.Effect<A, E, R>,
73 ) => Effect.Effect<A, E | ProviderSetupError, R | Scope.Scope>;
75​
76export type AntigravityAuthRuntime = Pick<
77 AcpSessionRuntime.AcpSessionRuntime["Service"],
78 "initialize" | "start" | "request"
79>;
80​
81export interface AntigravityAuthOptions<
82 Runtime extends AntigravityAuthRuntime = AcpSessionRuntime.AcpSessionRuntime["Service"],
83> {
84 readonly instanceId: ProviderInstanceId;
85 readonly makeRuntime: (input: {
86 readonly onAuthorizationUrl?: (url: string) => Effect.Effect<void, AcpErrors.AcpError>;
87 }) => Effect.Effect<Runtime, AcpErrors.AcpError | ProviderSetupError, Scope.Scope>;
88 readonly onAuthenticated: (
89 result: AcpSessionRuntime.AcpSessionRuntimeStartResult,
90 runtime: Runtime,
91 ) => Effect.Effect<void>;
92 readonly onSignedOut: Effect.Effect<void>;
93 readonly forwardCallback?: (callback: URL) => Effect.Effect<void, ProviderSetupError>;
94 readonly usesBrowser?: boolean;
96​
97function visibleSnapshot(snapshot: AuthSnapshot, ownerSessionId: string): ProviderAuthState {
98 if (snapshot.ownerSessionId === null || snapshot.ownerSessionId === ownerSessionId) {
99 return snapshot.state;
100 }
101 const busy = ["starting", "waiting", "verifying"].includes(snapshot.state.phase);
102 return {
103 ...snapshot.state,
104 flowId: null,
105 authorizationUrl: null,
106 interaction: null,
107 expiresAt: null,
108 ...(busy ? { message: "Sign-in is in progress in another client." } : {}),
109 };
111​
112function safeAuthFailure(cause: Cause.Cause<unknown>, usesBrowser: boolean): string {
113 const error = Cause.findErrorOption(cause);
114 if (Option.isSome(error)) {
115 if (isSetupError(error.value)) {
116 return error.value.detail;
117 }
118 if (isAcpRequestError(error.value)) {
119 if (error.value.errorMessage.includes("SUBSCRIPTION_REQUIRED")) {
120 return "Google requires an eligible Antigravity subscription for this account.";
121 }
122 if (/access_denied|denied access|cancelled/i.test(error.value.errorMessage)) {
123 return "Google sign-in was not approved. Start sign-in again.";
124 }
125 if (error.value.method === "session/new" && error.value.code === -32603) {
126 return "Antigravity authenticated, but could not initialize a session or load models.";
127 }
128 if (!usesBrowser && error.value.code === -32602) {
129 return "Antigravity rejected the configured credentials. Check the provider settings.";
130 }
131 }
132 }
133 return usesBrowser
134 ? "Google sign-in failed. Start sign-in again."
135 : "Antigravity could not authenticate with the configured credentials.";
137​
138export const makeAntigravityAuth = Effect.fn("makeAntigravityAuth")(function* <
139 Runtime extends AntigravityAuthRuntime,
140>(
141 options: AntigravityAuthOptions<Runtime>,
142): Effect.fn.Return<AntigravityAuth, never, SecureRandom.SecureRandom | Scope.Scope> {
143 const random = yield* SecureRandom.SecureRandom;
144 const instanceScope = yield* Scope.Scope;
145 const usesBrowser = options.usesBrowser ?? true;
146 const lock = yield* Semaphore.make(1);
147 const closed = yield* Deferred.make<void>();
148 const emptyState: ProviderAuthState = {
149 instanceId: options.instanceId,
150 phase: "idle",
151 flowId: null,
152 authorizationUrl: null,
153 expiresAt: null,
154 message: null,
155 };
156 const snapshot = yield* SubscriptionRef.make<AuthSnapshot>({
157 ownerSessionId: null,
158 state: emptyState,
159 });
160 const processes = new Set<OwnedProcess>();
161 let activeFlow: AuthFlow | undefined;
162 let operation: "idle" | "auth" | "logout" | "cancel" | "closed" = "idle";
163​
164 const setupError = (name: string, detail: string) =>
165 new ProviderSetupError({ instanceId: options.instanceId, operation: name, detail });
166 const currentState = (ownerSessionId: string) =>
167 SubscriptionRef.get(snapshot).pipe(
168 Effect.map((value) => visibleSnapshot(value, ownerSessionId)),
169 );
170 const publishFlow = (flow: AuthFlow, state: ProviderAuthState) => {
171 flow.state = state;
172 return SubscriptionRef.set(snapshot, { ownerSessionId: flow.ownerSessionId, state });
173 };
174 const stopOwnedProcesses = Effect.suspend(() =>
175 Effect.forEach(
176 Array.from(processes),
177 (owned) =>
178 Effect.gen(function* () {
179 if (owned.startup) {
180 yield* Fiber.interrupt(owned.startup);
181 }
182 yield* owned.stop;
183 }),
184 { discard: true, concurrency: "unbounded" },
185 ),
186 );
187​
188 const withProcess: AntigravityAuth["withProcess"] = (stop, task) =>
189 Effect.uninterruptibleMask((restore) =>
190 Effect.gen(function* () {
191 const scope = yield* Scope.Scope;
192 const owned: OwnedProcess = { stop, startup: undefined };
193 const fiber = yield* lock.withPermits(1)(
194 Effect.gen(function* () {
195 if (operation !== "idle") {
196 return yield* setupError(
197 "startProcess",
198 "Antigravity sign-in or sign-out is in progress. Try again after it finishes.",
199 );
200 }
201 processes.add(owned);
202 yield* Scope.addFinalizer(
203 scope,
204 Effect.sync(() => {
205 processes.delete(owned);
206 }),
207 );
208 const child = yield* restore(task).pipe(Effect.forkIn(scope));
209 owned.startup = child;
210 return child;
211 }),
212 );
213 // Propagate interruption after the exit wait so concurrent stop waiters stay attached.
214 return yield* restore(Fiber.await(fiber)).pipe(
215 Effect.flatten,
216 Effect.ensuring(Fiber.interrupt(fiber)),
217 Effect.ensuring(
218 Effect.sync(() => {
219 owned.startup = undefined;
220 }),
221 ),
222 );
223 }),
224 );
225​
226 const finishFlow = (flow: AuthFlow, result: Exit.Exit<void, unknown>) =>
227 lock.withPermits(1)(
228 Effect.gen(function* () {
229 if (activeFlow !== flow) return;
230 activeFlow = undefined;
231 operation = "idle";
232 flow.pending = undefined;
233 yield* publishFlow(flow, {
234 ...flow.state,
235 phase: Exit.isSuccess(result) ? "succeeded" : "failed",
236 authorizationUrl: null,
237 expiresAt: null,
238 message: Exit.isSuccess(result)
239 ? usesBrowser
240 ? "Signed in with Google."
241 : "Connected to Antigravity."
242 : safeAuthFailure(result.cause, usesBrowser),
243 });
244 }),
245 );
246​
247 const receiveAuthorizationUrl = (flow: AuthFlow, url: string) =>
248 parseAntigravityAuthorizationUrl(url).pipe(
249 Effect.flatMap((authorization) =>
250 lock.withPermits(1)(
251 Effect.gen(function* () {
252 if (activeFlow !== flow || operation !== "auth") return;
253 if (flow.pending) {
254 if (flow.pending.authorizationUrl === authorization.authorizationUrl) return;
255 return yield* new AcpErrors.AcpTransportError({
256 detail: "Antigravity started more than one Google sign-in request.",
257 cause: undefined,
258 });
259 }
260 flow.pending = authorization;
261 yield* publishFlow(flow, {
262 ...flow.state,
263 phase: "waiting",
264 authorizationUrl: authorization.authorizationUrl,
265 message:
266 "Open the Google sign-in link. If you are remote, paste the redirect URL here.",
267 });
268 }),
269 ),
270 ),
271 );
272​
273 const runSignIn = Effect.fn("AntigravityAuth.runSignIn")(
274 function* (flow: AuthFlow, stopSessions: Effect.Effect<void, ProviderSetupError>) {
275 yield* stopSessions.pipe(Effect.ensuring(stopOwnedProcesses));
276 const runtime = yield* options.makeRuntime({
277 onAuthorizationUrl: (url) => receiveAuthorizationUrl(flow, url),
278 });
279 // `start` reuses this memoized handshake.
280 yield* runtime.initialize();
281 yield* Effect.sleep(NO_RESPONSE_HINT_MS).pipe(
282 Effect.andThen(
283 lock.withPermits(1)(
284 Effect.gen(function* () {
285 if (activeFlow !== flow || flow.state.phase !== "starting") return;
286 yield* publishFlow(flow, { ...flow.state, message: NO_RESPONSE_MESSAGE });
287 }),
288 ),
289 ),
290 Effect.forkScoped,
291 );
292 const started = yield* runtime.start();
293 yield* lock.withPermits(1)(
294 Effect.gen(function* () {
295 if (activeFlow !== flow) return;
296 flow.pending = undefined;
297 yield* publishFlow(flow, {
298 ...flow.state,
299 phase: "verifying",
300 authorizationUrl: null,
301 message: "Checking Antigravity access and models.",
302 });
303 }),
304 );
305 yield* options.onAuthenticated(started, runtime);
306 },
307 (effect, flow, _stopSessions) =>
308 effect.pipe(
309 Effect.scoped,
310 Effect.timeoutOrElse({
311 duration: AUTH_TIMEOUT_MS,
312 orElse: () =>
313 Effect.fail(
314 setupError(
315 "start",
316 flow.state.phase === "starting"
317 ? UNREACHABLE_MESSAGE
318 : "Google sign-in expired. Start sign-in again.",
319 ),
320 ),
321 }),
322 Effect.exit,
323 Effect.flatMap((result) => finishFlow(flow, result)),
324 ),
325 );
326​
327 const stopFlow = (flow: AuthFlow, phase: "cancelled" | "failed", message: string) =>
328 Effect.uninterruptible(
329 Effect.gen(function* () {
330 const detached = yield* lock.withPermits(1)(
331 Effect.gen(function* () {
332 if (activeFlow !== flow) return false;
333 activeFlow = undefined;
334 operation = "cancel";
335 flow.pending = undefined;
336 yield* publishFlow(flow, {
337 ...flow.state,
338 phase,
339 authorizationUrl: null,
340 expiresAt: null,
341 message,
342 });
343 return true;
344 }),
345 );
346 if (!detached) return;
347 if (flow.forwarding) yield* Fiber.interrupt(flow.forwarding);
348 if (flow.fiber) yield* Fiber.interrupt(flow.fiber);
349 yield* lock.withPermits(1)(
350 Effect.sync(() => {
351 if (operation === "cancel") operation = "idle";
352 }),
353 );
354 }),
355 );
356​
357 const requireFlow = Effect.fn("AntigravityAuth.requireFlow")(function* (
358 ownerSessionId: string,
359 flowId: string,
360 name: string,
361 ) {
362 const flow = activeFlow;
363 if (!flow || flow.id !== flowId || flow.ownerSessionId !== ownerSessionId) {
364 return yield* setupError(name, "This sign-in is no longer active in this client.");
365 }
366 const now = yield* Clock.currentTimeMillis;
367 if (now >= flow.expiresAtMillis) {
368 return yield* setupError(name, "Google sign-in expired. Start sign-in again.");
369 }
370 return flow;
371 });
372​
373 const controller: ProviderAuthController = {
374 start: (ownerSessionId, stopSessions = Effect.void) =>
375 lock.withPermits(1)(
376 Effect.uninterruptible(
377 Effect.gen(function* () {
378 if (activeFlow?.ownerSessionId === ownerSessionId && operation === "auth") {
379 return activeFlow.state;
380 }
381 if (operation !== "idle") {
382 return yield* setupError("start", "Antigravity setup is already in progress.");
383 }
384 const flowId = yield* random
385 .uuidV4()
386 .pipe(
387 Effect.mapError(() =>
388 setupError("start", "Could not start Google sign-in. Try again."),
389 ),
390 );
391 const expiresAtMillis = (yield* Clock.currentTimeMillis) + AUTH_TIMEOUT_MS;
392 const state: ProviderAuthState = {
393 ...emptyState,
394 phase: "starting",
395 flowId,
396 expiresAt: DateTime.formatIso(DateTime.makeUnsafe(expiresAtMillis)),
397 message: usesBrowser ? "Starting Google sign-in." : "Checking credentials.",
398 };
399 const flow: AuthFlow = {
400 id: flowId,
401 ownerSessionId,
402 expiresAtMillis,
403 state,
404 pending: undefined,
405 callbackSent: false,
406 fiber: undefined,
407 forwarding: undefined,
408 };
409 activeFlow = flow;
410 operation = "auth";
411 yield* publishFlow(flow, state);
412 flow.fiber = yield* runSignIn(flow, stopSessions).pipe(
413 Effect.interruptible,
414 Effect.forkIn(instanceScope),
415 );
416 return state;
417 }),
418 ),
419 ),
420 complete: Effect.fn("AntigravityAuth.complete")(function* (ownerSessionId, input) {
421 const pending = yield* lock.withPermits(1)(
422 Effect.gen(function* () {
423 const flow = yield* requireFlow(ownerSessionId, input.flowId, "complete");
424 if (!flow.pending || flow.callbackSent) {
425 return yield* setupError(
426 "complete",
427 flow.callbackSent
428 ? "The sign-in response was already sent. Wait for Google to finish."
429 : "Wait for the Google sign-in link before you send a redirect URL.",
430 );
431 }
432 const callback = yield* validateAntigravityCallbackUrl(
433 options.instanceId,
434 flow.pending,
435 input.callbackUrl,
436 );
437 flow.callbackSent = true;
438 yield* publishFlow(flow, {
439 ...flow.state,
440 phase: "verifying",
441 authorizationUrl: null,
442 message: "Waiting for Google to finish sign-in.",
443 });
444 const forwarding = yield* (
445 options.forwardCallback?.(callback) ??
446 forwardAntigravityCallback(options.instanceId, callback)
447 ).pipe(
448 // stopFlow interrupts this fiber, so it runs from a sibling fiber.
449 Effect.tapError(() =>
450 stopFlow(flow, "failed", FORWARDING_FAILED_MESSAGE).pipe(
451 Effect.forkIn(instanceScope),
452 ),
453 ),
454 Effect.interruptible,
455 Effect.forkIn(instanceScope),
456 );
457 flow.forwarding = forwarding;
458 return { flow, forwarding };
459 }),
460 );
461 const forwarded = yield* Fiber.await(pending.forwarding);
462 if (Exit.isFailure(forwarded)) {
463 return yield* setupError("complete", FORWARDING_FAILED_MESSAGE);
464 }
465 return pending.flow.state;
466 }),
467 cancel: Effect.fn("AntigravityAuth.cancel")(function* (ownerSessionId, flowId) {
468 const flow = yield* lock.withPermits(1)(requireFlow(ownerSessionId, flowId, "cancel"));
469 yield* stopFlow(flow, "cancelled", "Google sign-in was cancelled.");
470 return flow.state;
471 }),
472 logout: Effect.fn("AntigravityAuth.logout")(function* (stopSessions) {
473 const task = Effect.uninterruptibleMask((restore) =>
474 Effect.gen(function* () {
475 const flow = yield* lock.withPermits(1)(
476 Effect.gen(function* () {
477 if (operation !== "idle" && operation !== "auth") {
478 return yield* setupError("logout", "Antigravity setup is already stopping.");
479 }
480 operation = "logout";
481 const currentFlow = activeFlow;
482 activeFlow = undefined;
483 if (currentFlow) {
484 currentFlow.pending = undefined;
485 yield* publishFlow(currentFlow, {
486 ...currentFlow.state,
487 phase: "cancelled",
488 authorizationUrl: null,
489 expiresAt: null,
490 message: "Google sign-in was cancelled by sign-out.",
491 });
492 }
493 return currentFlow;
494 }),
495 );
496 const stopRemaining = Effect.gen(function* () {
497 if (flow?.forwarding) yield* Fiber.interrupt(flow.forwarding);
498 if (flow?.fiber) yield* Fiber.interrupt(flow.fiber);
499 yield* stopOwnedProcesses;
500 });
501 const result = yield* restore(
502 Effect.gen(function* () {
503 yield* stopSessions.pipe(Effect.ensuring(stopRemaining));
504 const runtime = yield* options.makeRuntime({});
505 const initialized = yield* runtime.initialize();
506 if (!initialized.agentCapabilities?.auth?.logout) {
507 return yield* setupError(
508 "logout",
509 "This Antigravity version does not support sign-out. Update the provider.",
510 );
511 }
512 yield* runtime.request("logout", {});
513 yield* options.onSignedOut;
514 }).pipe(
515 Effect.scoped,
516 Effect.timeoutOrElse({
517 duration: "90 seconds",
518 orElse: () => Effect.fail(setupError("logout", "Antigravity sign-out timed out.")),
519 }),
520 ),
521 ).pipe(Effect.exit);
522 yield* lock.withPermits(1)(
523 Effect.gen(function* () {
524 operation = "idle";
525 yield* SubscriptionRef.set(snapshot, {
526 ownerSessionId: null,
527 state: {
528 ...emptyState,
529 phase: Exit.isSuccess(result) ? "idle" : "failed",
530 message: Exit.isSuccess(result)
531 ? "Signed out of Google."
532 : "Antigravity sign-out failed. Try again.",
533 },
534 });
535 }),
536 );
537 if (Exit.isFailure(result)) {
538 const failure = Cause.findErrorOption(result.cause);
539 return yield* Option.isSome(failure) && isSetupError(failure.value)
540 ? failure.value
541 : setupError("logout", "Antigravity sign-out failed. Try again.");
542 }
543 return yield* currentState("");
544 }),
545 );
546 const worker = yield* task.pipe(Effect.forkIn(instanceScope));
547 return yield* Fiber.await(worker).pipe(Effect.flatten);
548 }),
549 subscribe: (ownerSessionId) =>
550 SubscriptionRef.changes(snapshot).pipe(
551 Stream.map((value) => {
552 const state = visibleSnapshot(value, ownerSessionId);
553 return {
554 ...state,
555 credentialOwner: "provider" as const,
556 interaction:
557 state.phase === "waiting" && state.authorizationUrl && state.flowId
558 ? {
559 type: "browser" as const,
560 id: state.flowId,
561 url: state.authorizationUrl,
562 requiresConsent: false,
563 acceptsCallback: true,
564 }
565 : null,
566 };
567 }),
568 Stream.interruptWhen(Deferred.await(closed)),
569 ),
570 isLogoutPrompt: (text, hasAttachments) => !hasAttachments && text.trim() === "/logout",
571 };
572​
573 yield* Effect.addFinalizer(() =>
574 Effect.gen(function* () {
575 operation = "closed";
576 const flow = activeFlow;
577 activeFlow = undefined;
578 if (flow) {
579 flow.pending = undefined;
580 if (flow.forwarding) yield* Fiber.interrupt(flow.forwarding);
581 if (flow.fiber) yield* Fiber.interrupt(flow.fiber);
582 }
583 yield* stopOwnedProcesses;
584 yield* Deferred.succeed(closed, undefined);
585 }),
586 );
587​
588 return { controller, withProcess };
589});