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

AntigravityAuth.ts

560 lines20.3 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 = Effect.fn("AntigravityAuth.runSignIn")(
265 function* (flow: AuthFlow, stopSessions: Effect.Effect<void, ProviderSetupError>) {
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 },
285 (effect, flow, stopSessions) =>
286 effect.pipe(
287 Effect.scoped,
288 Effect.timeoutOrElse({
289 duration: AUTH_TIMEOUT_MS,
290 orElse: () =>
291 Effect.fail(setupError("start", "Google sign-in expired. Start sign-in again.")),
292 }),
293 Effect.exit,
294 Effect.flatMap((result) => finishFlow(flow, result)),
295 ),
296 );
297​
298 const stopFlow = (flow: AuthFlow, phase: "cancelled" | "failed", message: string) =>
299 Effect.uninterruptible(
300 Effect.gen(function* () {
301 const detached = yield* lock.withPermits(1)(
302 Effect.gen(function* () {
303 if (activeFlow !== flow) return false;
304 activeFlow = undefined;
305 operation = "cancel";
306 flow.pending = undefined;
307 yield* publishFlow(flow, {
308 ...flow.state,
309 phase,
310 authorizationUrl: null,
311 expiresAt: null,
312 message,
313 });
314 return true;
315 }),
316 );
317 if (!detached) return;
318 if (flow.forwarding) yield* Fiber.interrupt(flow.forwarding);
319 if (flow.fiber) yield* Fiber.interrupt(flow.fiber);
320 yield* lock.withPermits(1)(
321 Effect.sync(() => {
322 if (operation === "cancel") operation = "idle";
323 }),
324 );
325 }),
326 );
327​
328 const requireFlow = Effect.fn("AntigravityAuth.requireFlow")(function* (
329 ownerSessionId: string,
330 flowId: string,
331 name: string,
332 ) {
333 const flow = activeFlow;
334 if (!flow || flow.id !== flowId || flow.ownerSessionId !== ownerSessionId) {
335 return yield* setupError(name, "This sign-in is no longer active in this client.");
336 }
337 const now = yield* Clock.currentTimeMillis;
338 if (now >= flow.expiresAtMillis) {
339 return yield* setupError(name, "Google sign-in expired. Start sign-in again.");
340 }
341 return flow;
342 });
343​
344 const controller: ProviderAuthController = {
345 start: (ownerSessionId, stopSessions = Effect.void) =>
346 lock.withPermits(1)(
347 Effect.uninterruptible(
348 Effect.gen(function* () {
349 if (activeFlow?.ownerSessionId === ownerSessionId && operation === "auth") {
350 return activeFlow.state;
351 }
352 if (operation !== "idle") {
353 return yield* setupError("start", "Antigravity setup is already in progress.");
354 }
355 const flowId = yield* crypto
356 .randomUUIDv4()
357 .pipe(
358 Effect.mapError(() =>
359 setupError("start", "Could not start Google sign-in. Try again."),
360 ),
361 );
362 const expiresAtMillis = (yield* Clock.currentTimeMillis) + AUTH_TIMEOUT_MS;
363 const state: ProviderAuthState = {
364 ...emptyState,
365 phase: "starting",
366 flowId,
367 expiresAt: DateTime.formatIso(DateTime.makeUnsafe(expiresAtMillis)),
368 message: usesBrowser ? "Starting Google sign-in." : "Checking credentials.",
369 };
370 const flow: AuthFlow = {
371 id: flowId,
372 ownerSessionId,
373 expiresAtMillis,
374 state,
375 pending: undefined,
376 callbackSent: false,
377 fiber: undefined,
378 forwarding: undefined,
379 };
380 activeFlow = flow;
381 operation = "auth";
382 yield* publishFlow(flow, state);
383 flow.fiber = yield* runSignIn(flow, stopSessions).pipe(
384 Effect.interruptible,
385 Effect.forkIn(instanceScope),
386 );
387 return state;
388 }),
389 ),
390 ),
391 complete: Effect.fn("AntigravityAuth.complete")(function* (ownerSessionId, input) {
392 const pending = yield* lock.withPermits(1)(
393 Effect.gen(function* () {
394 const flow = yield* requireFlow(ownerSessionId, input.flowId, "complete");
395 if (!flow.pending || flow.callbackSent) {
396 return yield* setupError(
397 "complete",
398 flow.callbackSent
399 ? "The sign-in response was already sent. Wait for Google to finish."
400 : "Wait for the Google sign-in link before you send a redirect URL.",
401 );
402 }
403 const callback = yield* validateAntigravityCallbackUrl(
404 options.instanceId,
405 flow.pending,
406 input.callbackUrl,
407 );
408 flow.callbackSent = true;
409 yield* publishFlow(flow, {
410 ...flow.state,
411 phase: "verifying",
412 authorizationUrl: null,
413 message: "Waiting for Google to finish sign-in.",
414 });
415 const forwarding = yield* (
416 options.forwardCallback?.(callback) ??
417 forwardAntigravityCallback(options.instanceId, callback)
418 ).pipe(
419 // stopFlow interrupts this fiber, so it runs from a sibling fiber.
420 Effect.tapError(() =>
421 stopFlow(flow, "failed", FORWARDING_FAILED_MESSAGE).pipe(
422 Effect.forkIn(instanceScope),
423 ),
424 ),
425 Effect.interruptible,
426 Effect.forkIn(instanceScope),
427 );
428 flow.forwarding = forwarding;
429 return { flow, forwarding };
430 }),
431 );
432 const forwarded = yield* Fiber.await(pending.forwarding);
433 if (Exit.isFailure(forwarded)) {
434 return yield* setupError("complete", FORWARDING_FAILED_MESSAGE);
435 }
436 return pending.flow.state;
437 }),
438 cancel: Effect.fn("AntigravityAuth.cancel")(function* (ownerSessionId, flowId) {
439 const flow = yield* lock.withPermits(1)(requireFlow(ownerSessionId, flowId, "cancel"));
440 yield* stopFlow(flow, "cancelled", "Google sign-in was cancelled.");
441 return flow.state;
442 }),
443 logout: Effect.fn("AntigravityAuth.logout")(function* (stopSessions) {
444 const task = Effect.uninterruptibleMask((restore) =>
445 Effect.gen(function* () {
446 const flow = yield* lock.withPermits(1)(
447 Effect.gen(function* () {
448 if (operation !== "idle" && operation !== "auth") {
449 return yield* setupError("logout", "Antigravity setup is already stopping.");
450 }
451 operation = "logout";
452 const currentFlow = activeFlow;
453 activeFlow = undefined;
454 if (currentFlow) {
455 currentFlow.pending = undefined;
456 yield* publishFlow(currentFlow, {
457 ...currentFlow.state,
458 phase: "cancelled",
459 authorizationUrl: null,
460 expiresAt: null,
461 message: "Google sign-in was cancelled by sign-out.",
462 });
463 }
464 return currentFlow;
465 }),
466 );
467 const stopRemaining = Effect.gen(function* () {
468 if (flow?.forwarding) yield* Fiber.interrupt(flow.forwarding);
469 if (flow?.fiber) yield* Fiber.interrupt(flow.fiber);
470 yield* stopOwnedProcesses;
471 });
472 const result = yield* restore(
473 Effect.gen(function* () {
474 yield* stopSessions.pipe(Effect.ensuring(stopRemaining));
475 const runtime = yield* options.makeRuntime({});
476 const initialized = yield* runtime.initialize();
477 if (!initialized.agentCapabilities?.auth?.logout) {
478 return yield* setupError(
479 "logout",
480 "This Antigravity version does not support sign-out. Update the provider.",
481 );
482 }
483 yield* runtime.request("logout", {});
484 yield* options.onSignedOut;
485 }).pipe(
486 Effect.scoped,
487 Effect.timeoutOrElse({
488 duration: "90 seconds",
489 orElse: () => Effect.fail(setupError("logout", "Antigravity sign-out timed out.")),
490 }),
491 ),
492 ).pipe(Effect.exit);
493 yield* lock.withPermits(1)(
494 Effect.gen(function* () {
495 operation = "idle";
496 yield* SubscriptionRef.set(snapshot, {
497 ownerSessionId: null,
498 state: {
499 ...emptyState,
500 phase: Exit.isSuccess(result) ? "idle" : "failed",
501 message: Exit.isSuccess(result)
502 ? "Signed out of Google."
503 : "Antigravity sign-out failed. Try again.",
504 },
505 });
506 }),
507 );
508 if (Exit.isFailure(result)) {
509 const failure = Cause.findErrorOption(result.cause);
510 return yield* Option.isSome(failure) && isSetupError(failure.value)
511 ? failure.value
512 : setupError("logout", "Antigravity sign-out failed. Try again.");
513 }
514 return yield* currentState("");
515 }),
516 );
517 const worker = yield* task.pipe(Effect.forkIn(instanceScope));
518 return yield* Fiber.await(worker).pipe(Effect.flatMap((result) => result));
519 }),
520 subscribe: (ownerSessionId) =>
521 SubscriptionRef.changes(snapshot).pipe(
522 Stream.map((value) => {
523 const state = visibleSnapshot(value, ownerSessionId);
524 return {
525 ...state,
526 credentialOwner: "provider" as const,
527 interaction:
528 state.phase === "waiting" && state.authorizationUrl && state.flowId
529 ? {
530 type: "browser" as const,
531 id: state.flowId,
532 url: state.authorizationUrl,
533 requiresConsent: false,
534 acceptsCallback: true,
535 }
536 : null,
537 };
538 }),
539 Stream.interruptWhen(Deferred.await(closed)),
540 ),
541 isLogoutPrompt: (text, hasAttachments) => !hasAttachments && text.trim() === "/logout",
542 };
543​
544 yield* Effect.addFinalizer(() =>
545 Effect.gen(function* () {
546 operation = "closed";
547 const flow = activeFlow;
548 activeFlow = undefined;
549 if (flow) {
550 flow.pending = undefined;
551 if (flow.forwarding) yield* Fiber.interrupt(flow.forwarding);
552 if (flow.fiber) yield* Fiber.interrupt(flow.fiber);
553 }
554 yield* stopOwnedProcesses;
555 yield* Deferred.succeed(closed, undefined);
556 }),
557 );
558​
559 return { controller, withProcess };
560});