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