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

AntigravityAuth.ts

542 lines20.1 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 { 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;
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 /** 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>;
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;
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 };
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 (error.value.method === "session/new" && error.value.code === -32603) {
118 return "Antigravity authenticated, but could not initialize a session or load models.";
119 }
120 if (!usesBrowser && error.value.code === -32602) {
121 return "Antigravity rejected the configured credentials. Check the provider settings.";
122 }
123 }
124 }
125 return usesBrowser
126 ? "Google sign-in failed. Start sign-in again."
127 : "Antigravity could not authenticate with the configured credentials.";
129​
130/** Owns one instance's explicit sign-in and all process admission around sign-out. */
131export const makeAntigravityAuth = Effect.fn("makeAntigravityAuth")(function* <
132 Runtime extends AntigravityAuthRuntime,
133>(
134 options: AntigravityAuthOptions<Runtime>,
135): Effect.fn.Return<AntigravityAuth, never, Crypto.Crypto | Scope.Scope> {
136 const crypto = yield* Crypto.Crypto;
137 const instanceScope = yield* Scope.Scope;
138 const usesBrowser = options.usesBrowser ?? true;
139 const lock = yield* Semaphore.make(1);
140 const closed = yield* Deferred.make<void>();
141 const emptyState: ProviderAuthState = {
142 instanceId: options.instanceId,
143 phase: "idle",
144 flowId: null,
145 authorizationUrl: null,
146 expiresAt: null,
147 message: null,
148 };
149 const snapshot = yield* SubscriptionRef.make<AuthSnapshot>({
150 ownerSessionId: null,
151 state: emptyState,
152 });
153 const processes = new Set<OwnedProcess>();
154 let activeFlow: AuthFlow | undefined;
155 let operation: "idle" | "auth" | "logout" | "cancel" | "closed" = "idle";
156​
157 const setupError = (name: string, detail: string) =>
158 new ProviderSetupError({ instanceId: options.instanceId, operation: name, detail });
159 const currentState = (ownerSessionId: string) =>
160 SubscriptionRef.get(snapshot).pipe(
161 Effect.map((value) => visibleSnapshot(value, ownerSessionId)),
162 );
163 const publishFlow = (flow: AuthFlow, state: ProviderAuthState) => {
164 flow.state = state;
165 return SubscriptionRef.set(snapshot, { ownerSessionId: flow.ownerSessionId, state });
166 };
167 const stopOwnedProcesses = Effect.suspend(() =>
168 Effect.forEach(
169 Array.from(processes),
170 (owned) =>
171 Effect.gen(function* () {
172 if (owned.startup) {
173 yield* Fiber.interrupt(owned.startup);
174 }
175 yield* owned.stop;
176 }),
177 { discard: true, concurrency: "unbounded" },
178 ),
179 );
180​
181 const withProcess: AntigravityAuth["withProcess"] = (stop, task) =>
182 Effect.uninterruptibleMask((restore) =>
183 Effect.gen(function* () {
184 const scope = yield* Scope.Scope;
185 const owned: OwnedProcess = { stop, startup: undefined };
186 const fiber = yield* lock.withPermits(1)(
187 Effect.gen(function* () {
188 if (operation !== "idle") {
189 return yield* setupError(
190 "startProcess",
191 "Antigravity sign-in or sign-out is in progress. Try again after it finishes.",
192 );
193 }
194 processes.add(owned);
195 yield* Scope.addFinalizer(
196 scope,
197 Effect.sync(() => {
198 processes.delete(owned);
199 }),
200 );
201 const child = yield* restore(task).pipe(Effect.forkIn(scope));
202 owned.startup = child;
203 return child;
204 }),
205 );
206 // Propagate interruption after the exit wait so concurrent stop waiters stay attached.
207 return yield* restore(Fiber.await(fiber)).pipe(
208 Effect.flatMap((result) => result),
209 Effect.ensuring(Fiber.interrupt(fiber)),
210 Effect.ensuring(
211 Effect.sync(() => {
212 owned.startup = undefined;
213 }),
214 ),
215 );
216 }),
217 );
218​
219 const finishFlow = (flow: AuthFlow, result: Exit.Exit<void, unknown>) =>
220 lock.withPermits(1)(
221 Effect.gen(function* () {
222 if (activeFlow !== flow) return;
223 activeFlow = undefined;
224 operation = "idle";
225 flow.pending = undefined;
226 yield* publishFlow(flow, {
227 ...flow.state,
228 phase: Exit.isSuccess(result) ? "succeeded" : "failed",
229 authorizationUrl: null,
230 expiresAt: null,
231 message: Exit.isSuccess(result)
232 ? usesBrowser
233 ? "Signed in with Google."
234 : "Connected to Antigravity."
235 : safeAuthFailure(result.cause, usesBrowser),
236 });
237 }),
238 );
239​
240 const receiveAuthorizationUrl = (flow: AuthFlow, url: string) =>
241 parseAntigravityAuthorizationUrl(url).pipe(
242 Effect.flatMap((authorization) =>
243 lock.withPermits(1)(
244 Effect.gen(function* () {
245 if (activeFlow !== flow || operation !== "auth") return;
246 if (flow.pending) {
247 if (flow.pending.authorizationUrl === authorization.authorizationUrl) return;
248 return yield* new AcpErrors.AcpTransportError({
249 detail: "Antigravity started more than one Google sign-in request.",
250 cause: undefined,
251 });
252 }
253 flow.pending = authorization;
254 yield* publishFlow(flow, {
255 ...flow.state,
256 phase: "waiting",
257 authorizationUrl: authorization.authorizationUrl,
258 message:
259 "Open the Google sign-in link. If you are remote, paste the redirect URL here.",
260 });
261 }),
262 ),
263 ),
264 );
265​
266 const runSignIn = (flow: AuthFlow, stopSessions: Effect.Effect<void, ProviderSetupError>) =>
267 Effect.gen(function* () {
268 yield* stopSessions.pipe(Effect.ensuring(stopOwnedProcesses));
269 const runtime = yield* options.makeRuntime({
270 onAuthorizationUrl: (url) => receiveAuthorizationUrl(flow, url),
271 });
272 const started = yield* runtime.start();
273 yield* lock.withPermits(1)(
274 Effect.gen(function* () {
275 if (activeFlow !== flow) return;
276 flow.pending = undefined;
277 yield* publishFlow(flow, {
278 ...flow.state,
279 phase: "verifying",
280 authorizationUrl: null,
281 message: "Checking Antigravity access and models.",
282 });
283 }),
284 );
285 yield* options.onAuthenticated(started, runtime);
286 }).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 const stopFlow = (flow: AuthFlow, phase: "cancelled" | "failed", message: string) =>
298 Effect.uninterruptible(
299 Effect.gen(function* () {
300 const detached = yield* lock.withPermits(1)(
301 Effect.gen(function* () {
302 if (activeFlow !== flow) return false;
303 activeFlow = undefined;
304 operation = "cancel";
305 flow.pending = undefined;
306 yield* publishFlow(flow, {
307 ...flow.state,
308 phase,
309 authorizationUrl: null,
310 expiresAt: null,
311 message,
312 });
313 return true;
314 }),
315 );
316 if (!detached) return;
317 if (flow.forwarding) yield* Fiber.interrupt(flow.forwarding);
318 if (flow.fiber) yield* Fiber.interrupt(flow.fiber);
319 yield* lock.withPermits(1)(
320 Effect.sync(() => {
321 if (operation === "cancel") operation = "idle";
322 }),
323 );
324 }),
325 );
326​
327 const requireFlow = (ownerSessionId: string, flowId: string, name: string) =>
328 Effect.gen(function* () {
329 const flow = activeFlow;
330 if (!flow || flow.id !== flowId || flow.ownerSessionId !== ownerSessionId) {
331 return yield* setupError(name, "This sign-in is no longer active in this client.");
332 }
333 const now = yield* Clock.currentTimeMillis;
334 if (now >= flow.expiresAtMillis) {
335 return yield* setupError(name, "Google sign-in expired. Start sign-in again.");
336 }
337 return flow;
338 });
339​
340 const controller: ProviderAuthController = {
341 start: (ownerSessionId, stopSessions = Effect.void) =>
342 lock.withPermits(1)(
343 Effect.uninterruptible(
344 Effect.gen(function* () {
345 if (activeFlow?.ownerSessionId === ownerSessionId && operation === "auth") {
346 return activeFlow.state;
347 }
348 if (operation !== "idle") {
349 return yield* setupError("start", "Antigravity setup is already in progress.");
350 }
351 const flowId = yield* crypto.randomUUIDv4.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 // The instance owns delivery and its failure handling. The RPC that
410 // sent the callback may disconnect before Google answers, and the
411 // flow must still settle instead of sitting at "verifying" until
412 // the deadline.
413 const forwarding = yield* (
414 options.forwardCallback?.(callback) ??
415 forwardAntigravityCallback(options.instanceId, callback)
416 ).pipe(
417 // stopFlow interrupts this fiber, so it runs from a sibling fiber.
418 Effect.tapError(() =>
419 stopFlow(flow, "failed", FORWARDING_FAILED_MESSAGE).pipe(
420 Effect.forkIn(instanceScope),
421 ),
422 ),
423 Effect.interruptible,
424 Effect.forkIn(instanceScope),
425 );
426 flow.forwarding = forwarding;
427 return { flow, forwarding };
428 }),
429 );
430 const forwarded = yield* Fiber.await(pending.forwarding);
431 if (Exit.isFailure(forwarded)) {
432 return yield* setupError("complete", FORWARDING_FAILED_MESSAGE);
433 }
434 return pending.flow.state;
435 }),
436 cancel: Effect.fn("AntigravityAuth.cancel")(function* (ownerSessionId, flowId) {
437 const flow = yield* lock.withPermits(1)(requireFlow(ownerSessionId, flowId, "cancel"));
438 yield* stopFlow(flow, "cancelled", "Google sign-in was cancelled.");
439 return flow.state;
440 }),
441 logout: Effect.fn("AntigravityAuth.logout")(function* (stopSessions) {
442 const task = Effect.uninterruptibleMask((restore) =>
443 Effect.gen(function* () {
444 const flow = yield* lock.withPermits(1)(
445 Effect.gen(function* () {
446 if (operation !== "idle" && operation !== "auth") {
447 return yield* setupError("logout", "Antigravity setup is already stopping.");
448 }
449 operation = "logout";
450 const currentFlow = activeFlow;
451 activeFlow = undefined;
452 if (currentFlow) {
453 currentFlow.pending = undefined;
454 yield* publishFlow(currentFlow, {
455 ...currentFlow.state,
456 phase: "cancelled",
457 authorizationUrl: null,
458 expiresAt: null,
459 message: "Google sign-in was cancelled by sign-out.",
460 });
461 }
462 return currentFlow;
463 }),
464 );
465 const stopRemaining = Effect.gen(function* () {
466 if (flow?.forwarding) yield* Fiber.interrupt(flow.forwarding);
467 if (flow?.fiber) yield* Fiber.interrupt(flow.fiber);
468 yield* stopOwnedProcesses;
469 });
470 const result = yield* restore(
471 Effect.gen(function* () {
472 yield* stopSessions.pipe(Effect.ensuring(stopRemaining));
473 const runtime = yield* options.makeRuntime({});
474 const initialized = yield* runtime.initialize();
475 if (!initialized.agentCapabilities?.auth?.logout) {
476 return yield* setupError(
477 "logout",
478 "This Antigravity version does not support sign-out. Update the provider.",
479 );
480 }
481 yield* runtime.request("logout", {});
482 yield* options.onSignedOut;
483 }).pipe(
484 Effect.scoped,
485 Effect.timeoutOrElse({
486 duration: "90 seconds",
487 orElse: () => Effect.fail(setupError("logout", "Antigravity sign-out timed out.")),
488 }),
489 ),
490 ).pipe(Effect.exit);
491 yield* lock.withPermits(1)(
492 Effect.gen(function* () {
493 operation = "idle";
494 yield* SubscriptionRef.set(snapshot, {
495 ownerSessionId: null,
496 state: {
497 ...emptyState,
498 phase: Exit.isSuccess(result) ? "idle" : "failed",
499 message: Exit.isSuccess(result)
500 ? "Signed out of Google."
501 : "Antigravity sign-out failed. Try again.",
502 },
503 });
504 }),
505 );
506 if (Exit.isFailure(result)) {
507 const failure = Cause.findErrorOption(result.cause);
508 return yield* Option.isSome(failure) && isSetupError(failure.value)
509 ? failure.value
510 : setupError("logout", "Antigravity sign-out failed. Try again.");
511 }
512 return yield* currentState("");
513 }),
514 );
515 const worker = yield* task.pipe(Effect.forkIn(instanceScope));
516 return yield* Fiber.await(worker).pipe(Effect.flatMap((result) => result));
517 }),
518 subscribe: (ownerSessionId) =>
519 SubscriptionRef.changes(snapshot).pipe(
520 Stream.map((value) => visibleSnapshot(value, ownerSessionId)),
521 Stream.interruptWhen(Deferred.await(closed)),
522 ),
523 isLogoutPrompt: (text, hasAttachments) => !hasAttachments && text.trim() === "/logout",
524 };
525​
526 yield* Effect.addFinalizer(() =>
527 Effect.gen(function* () {
528 operation = "closed";
529 const flow = activeFlow;
530 activeFlow = undefined;
531 if (flow) {
532 flow.pending = undefined;
533 if (flow.forwarding) yield* Fiber.interrupt(flow.forwarding);
534 if (flow.fiber) yield* Fiber.interrupt(flow.fiber);
535 }
536 yield* stopOwnedProcesses;
537 yield* Deferred.succeed(closed, undefined);
538 }),
539 );
540​
541 return { controller, withProcess };
542});