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

AntigravityAuth.ts

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