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