tuxevil-rotator 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/CHANGELOG.md +773 -0
  2. package/LICENSE +21 -0
  3. package/README.md +341 -0
  4. package/bin/pi-antigravity-rotator.js +27 -0
  5. package/bin/tuxevil-rotator.js +5 -0
  6. package/package.json +63 -0
  7. package/src/account-store.ts +542 -0
  8. package/src/admin-auth.ts +126 -0
  9. package/src/body-limit.ts +52 -0
  10. package/src/cli.ts +293 -0
  11. package/src/compat/cache.ts +38 -0
  12. package/src/compat/model-specs.ts +82 -0
  13. package/src/compat/schema-sanitizer.ts +284 -0
  14. package/src/compat.ts +2357 -0
  15. package/src/compression/index.ts +92 -0
  16. package/src/compression/lite.ts +210 -0
  17. package/src/compression/preservation.ts +183 -0
  18. package/src/compression/rtk/command-detector.ts +170 -0
  19. package/src/compression/rtk/deduplicator.ts +39 -0
  20. package/src/compression/rtk/filter-loader.ts +84 -0
  21. package/src/compression/rtk/filter-types.ts +25 -0
  22. package/src/compression/rtk/filters/aws.json +34 -0
  23. package/src/compression/rtk/filters/biome.json +35 -0
  24. package/src/compression/rtk/filters/build-eslint.json +37 -0
  25. package/src/compression/rtk/filters/build-typescript.json +33 -0
  26. package/src/compression/rtk/filters/build-vite.json +41 -0
  27. package/src/compression/rtk/filters/build-webpack.json +34 -0
  28. package/src/compression/rtk/filters/bundle-install.json +35 -0
  29. package/src/compression/rtk/filters/composer.json +81 -0
  30. package/src/compression/rtk/filters/curl.json +34 -0
  31. package/src/compression/rtk/filters/df.json +34 -0
  32. package/src/compression/rtk/filters/docker-build.json +78 -0
  33. package/src/compression/rtk/filters/docker-logs.json +42 -0
  34. package/src/compression/rtk/filters/docker-ps.json +33 -0
  35. package/src/compression/rtk/filters/dotnet.json +47 -0
  36. package/src/compression/rtk/filters/du.json +33 -0
  37. package/src/compression/rtk/filters/error-stacktrace.json +41 -0
  38. package/src/compression/rtk/filters/gcloud.json +34 -0
  39. package/src/compression/rtk/filters/generic-output.json +32 -0
  40. package/src/compression/rtk/filters/gh.json +98 -0
  41. package/src/compression/rtk/filters/git-branch.json +45 -0
  42. package/src/compression/rtk/filters/git-diff.json +33 -0
  43. package/src/compression/rtk/filters/git-log.json +33 -0
  44. package/src/compression/rtk/filters/git-status.json +40 -0
  45. package/src/compression/rtk/filters/golangci-lint.json +34 -0
  46. package/src/compression/rtk/filters/gradle.json +47 -0
  47. package/src/compression/rtk/filters/json-output.json +40 -0
  48. package/src/compression/rtk/filters/kubectl.json +99 -0
  49. package/src/compression/rtk/filters/make.json +38 -0
  50. package/src/compression/rtk/filters/mypy.json +34 -0
  51. package/src/compression/rtk/filters/npm-audit.json +43 -0
  52. package/src/compression/rtk/filters/npm-install.json +41 -0
  53. package/src/compression/rtk/filters/nx.json +34 -0
  54. package/src/compression/rtk/filters/pip.json +41 -0
  55. package/src/compression/rtk/filters/playwright.json +42 -0
  56. package/src/compression/rtk/filters/poetry-install.json +35 -0
  57. package/src/compression/rtk/filters/prettier.json +40 -0
  58. package/src/compression/rtk/filters/ps.json +34 -0
  59. package/src/compression/rtk/filters/rsync.json +33 -0
  60. package/src/compression/rtk/filters/rubocop.json +34 -0
  61. package/src/compression/rtk/filters/ruff.json +40 -0
  62. package/src/compression/rtk/filters/shell-find.json +33 -0
  63. package/src/compression/rtk/filters/shell-grep.json +37 -0
  64. package/src/compression/rtk/filters/shell-ls.json +33 -0
  65. package/src/compression/rtk/filters/ssh.json +43 -0
  66. package/src/compression/rtk/filters/systemctl-status.json +43 -0
  67. package/src/compression/rtk/filters/terraform-plan.json +34 -0
  68. package/src/compression/rtk/filters/test-cargo.json +42 -0
  69. package/src/compression/rtk/filters/test-go.json +41 -0
  70. package/src/compression/rtk/filters/test-jest.json +43 -0
  71. package/src/compression/rtk/filters/test-pytest.json +41 -0
  72. package/src/compression/rtk/filters/test-vitest.json +43 -0
  73. package/src/compression/rtk/filters/tofu-plan.json +34 -0
  74. package/src/compression/rtk/filters/turbo.json +34 -0
  75. package/src/compression/rtk/filters/uv-sync.json +35 -0
  76. package/src/compression/rtk/filters/wget.json +34 -0
  77. package/src/compression/rtk/index.ts +103 -0
  78. package/src/compression/rtk/line-filter.ts +124 -0
  79. package/src/compression/rtk/smart-truncate.ts +71 -0
  80. package/src/config-defaults.ts +93 -0
  81. package/src/config-normalize.ts +48 -0
  82. package/src/config-storage.ts +21 -0
  83. package/src/dashboard.ts +1169 -0
  84. package/src/db-store.ts +188 -0
  85. package/src/doctor.ts +115 -0
  86. package/src/env.ts +15 -0
  87. package/src/exposure.ts +17 -0
  88. package/src/fetch-with-retry.ts +93 -0
  89. package/src/idempotency.ts +137 -0
  90. package/src/index.ts +267 -0
  91. package/src/key-auth.ts +159 -0
  92. package/src/key-migrations.ts +84 -0
  93. package/src/logger.ts +92 -0
  94. package/src/login.ts +48 -0
  95. package/src/notification-poller.ts +155 -0
  96. package/src/onboarding.ts +754 -0
  97. package/src/paths.ts +153 -0
  98. package/src/providers/adapter.ts +131 -0
  99. package/src/providers/credential-helpers.ts +72 -0
  100. package/src/providers/google-antigravity/code-assist.ts +161 -0
  101. package/src/providers/google-antigravity/credentials.ts +24 -0
  102. package/src/providers/google-antigravity/forward.ts +424 -0
  103. package/src/providers/google-antigravity/index.ts +168 -0
  104. package/src/providers/google-antigravity/login.ts +285 -0
  105. package/src/providers/google-antigravity/oauth.ts +314 -0
  106. package/src/providers/google-antigravity/quota.ts +152 -0
  107. package/src/providers/google-antigravity/translators.ts +1663 -0
  108. package/src/providers/ollama/api-key-validation.ts +59 -0
  109. package/src/providers/ollama/credentials.ts +28 -0
  110. package/src/providers/ollama/forward.ts +306 -0
  111. package/src/providers/ollama/index.ts +85 -0
  112. package/src/providers/ollama/login.ts +55 -0
  113. package/src/providers/ollama/prediction.ts +188 -0
  114. package/src/providers/ollama/quota-poll-store.ts +160 -0
  115. package/src/providers/ollama/quota.ts +189 -0
  116. package/src/providers/ollama/translators.ts +256 -0
  117. package/src/providers/ollama/usage-windows.ts +48 -0
  118. package/src/providers/proxy-dispatcher.ts +269 -0
  119. package/src/providers/registry.ts +70 -0
  120. package/src/proxy.ts +2446 -0
  121. package/src/rate-limit-parser.ts +126 -0
  122. package/src/response-headers.ts +98 -0
  123. package/src/responses-store.ts +159 -0
  124. package/src/rotator.ts +3614 -0
  125. package/src/settings-repository.ts +327 -0
  126. package/src/spend-logger.ts +696 -0
  127. package/src/static/dashboard-keys.js +384 -0
  128. package/src/static/dashboard-logs.js +797 -0
  129. package/src/static/dashboard.css +2740 -0
  130. package/src/static/dashboard.js +3177 -0
  131. package/src/storage.ts +105 -0
  132. package/src/systemd-env.ts +214 -0
  133. package/src/telemetry.ts +384 -0
  134. package/src/token-encryption.ts +199 -0
  135. package/src/types.ts +897 -0
  136. package/src/validators.ts +218 -0
  137. package/src/version-check.ts +225 -0
  138. package/src/virtual-keys.ts +312 -0
  139. package/tools/telemetry-receiver/README.md +147 -0
  140. package/tools/telemetry-receiver/package.json +13 -0
  141. package/tools/telemetry-receiver/receiver.js +2334 -0
  142. package/tuxevil-rotator_logo.png +0 -0
@@ -0,0 +1,285 @@
1
+ // Google Antigravity interactive login flow (OAuth2 + PKCE).
2
+ // 1. Opens OAuth URL -> user pastes redirect URL
3
+ // 2. Exchanges the code, resolves the user email + Cloud Code project
4
+ // Returns a ready-to-persist AccountConfig.
5
+
6
+ import { createInterface } from "node:readline";
7
+ import { createServer, type Server } from "node:http";
8
+ import { spawn } from "node:child_process";
9
+ import {
10
+ buildAuthUrl,
11
+ discoverProject,
12
+ exchangeAuthorizationCode,
13
+ generatePkce,
14
+ generateState,
15
+ getUserEmail,
16
+ getOAuthClientConfig,
17
+ } from "./oauth.js";
18
+ import type { AccountConfig } from "../../types.js";
19
+
20
+ function parseRedirectUrl(input: string): { code?: string; state?: string } {
21
+ const value = input.trim();
22
+ if (!value) return {};
23
+ try {
24
+ const url = new URL(value);
25
+ return {
26
+ code: url.searchParams.get("code") ?? undefined,
27
+ state: url.searchParams.get("state") ?? undefined,
28
+ };
29
+ } catch {
30
+ return {};
31
+ }
32
+ }
33
+
34
+ function askQuestion(prompt: string): Promise<string> {
35
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
36
+ return new Promise((resolve) => {
37
+ rl.question(prompt, (answer) => {
38
+ rl.close();
39
+ resolve(answer.trim());
40
+ });
41
+ });
42
+ }
43
+
44
+ const LOCAL_CALLBACK_TIMEOUT_MS = 5 * 60 * 1000;
45
+
46
+ export interface LocalOAuthCallbackOptions {
47
+ redirectUri?: string;
48
+ timeoutMs?: number;
49
+ port?: number;
50
+ onListening?: (port: number) => void;
51
+ }
52
+
53
+ export type LocalOAuthCallbackResult =
54
+ | { code: string; state: string }
55
+ | { error: string; errorDescription?: string };
56
+
57
+ export class OAuthCallbackUnavailableError extends Error {}
58
+ export class OAuthCallbackTimeoutError extends Error {}
59
+
60
+ function escapeHtml(value: unknown): string {
61
+ return String(value)
62
+ .replace(/&/g, "&amp;")
63
+ .replace(/</g, "&lt;")
64
+ .replace(/>/g, "&gt;")
65
+ .replace(/"/g, "&quot;")
66
+ .replace(/'/g, "&#39;");
67
+ }
68
+
69
+ function callbackPage(title: string, message: string, closeWindow = false): string {
70
+ const closeScript = closeWindow
71
+ ? "<script>window.close();</script>"
72
+ : "";
73
+ return `<!doctype html><html><head><meta charset="utf-8"><title>${escapeHtml(title)}</title></head><body><h1>${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p>${closeScript}</body></html>`;
74
+ }
75
+
76
+ function isLoopbackRedirectUri(redirectUri: string): boolean {
77
+ try {
78
+ const url = new URL(redirectUri);
79
+ return (
80
+ url.protocol === "http:" &&
81
+ ["localhost", "127.0.0.1", "[::1]", "::1"].includes(url.hostname) &&
82
+ url.pathname === "/oauth-callback"
83
+ );
84
+ } catch {
85
+ return false;
86
+ }
87
+ }
88
+
89
+ function closeServer(server: Server): Promise<void> {
90
+ if (!server.listening) return Promise.resolve();
91
+ return new Promise((resolve) => {
92
+ server.close(() => resolve());
93
+ });
94
+ }
95
+
96
+ /**
97
+ * Listen only on loopback for the CLI OAuth redirect. The server is always
98
+ * closed by the finally block, including callback errors and timeout.
99
+ */
100
+ export async function waitForLocalOAuthCallback(
101
+ expectedState: string,
102
+ options: LocalOAuthCallbackOptions = {},
103
+ ): Promise<LocalOAuthCallbackResult> {
104
+ const redirectUri = options.redirectUri ?? getOAuthClientConfig().redirectUri;
105
+ if (!isLoopbackRedirectUri(redirectUri)) {
106
+ throw new OAuthCallbackUnavailableError(
107
+ "The configured OAuth redirect is not a loopback callback.",
108
+ );
109
+ }
110
+
111
+ const redirect = new URL(redirectUri);
112
+ const host = redirect.hostname === "::1" || redirect.hostname === "[::1]"
113
+ ? "::1"
114
+ : "127.0.0.1";
115
+ const urlHost = host === "::1" ? `[${host}]` : host;
116
+ const port = options.port ?? Number(redirect.port || 51121);
117
+ const server = createServer((req, res) => {
118
+ const requestUrl = new URL(req.url || "/", `http://${urlHost}:${port}`);
119
+ if (req.method !== "GET" || requestUrl.pathname !== redirect.pathname) {
120
+ res.writeHead(404, { "Content-Type": "text/html; charset=utf-8" });
121
+ res.end(callbackPage("Not Found", "This callback endpoint is not available."));
122
+ return;
123
+ }
124
+
125
+ const callbackState = requestUrl.searchParams.get("state");
126
+ if (callbackState !== expectedState) {
127
+ res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
128
+ res.end(callbackPage("Callback Rejected", "The OAuth state did not match this login session."));
129
+ return;
130
+ }
131
+
132
+ const error = requestUrl.searchParams.get("error");
133
+ const errorDescription = requestUrl.searchParams.get("error_description") ?? undefined;
134
+ if (error) {
135
+ res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
136
+ res.end(callbackPage("Sign-In Cancelled", errorDescription || error, true));
137
+ finish({ error, ...(errorDescription ? { errorDescription } : {}) });
138
+ return;
139
+ }
140
+
141
+ const code = requestUrl.searchParams.get("code");
142
+ if (!code) {
143
+ res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
144
+ res.end(callbackPage("Missing Code", "Google did not return an authorization code."));
145
+ return;
146
+ }
147
+
148
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
149
+ res.end(callbackPage("Sign-In Complete", "You can close this window and return to the terminal.", true));
150
+ finish({ code, state: callbackState });
151
+ });
152
+
153
+ let finish: (result: LocalOAuthCallbackResult) => void = () => undefined;
154
+ const result = new Promise<LocalOAuthCallbackResult>((resolve) => {
155
+ finish = resolve;
156
+ });
157
+
158
+ try {
159
+ await new Promise<void>((resolve, reject) => {
160
+ const onError = (err: Error): void => reject(err);
161
+ server.once("error", onError);
162
+ server.listen(port, host, () => {
163
+ server.off("error", onError);
164
+ const address = server.address();
165
+ const listeningPort = typeof address === "object" && address ? address.port : port;
166
+ options.onListening?.(listeningPort);
167
+ resolve();
168
+ });
169
+ });
170
+ } catch {
171
+ await closeServer(server);
172
+ throw new OAuthCallbackUnavailableError(
173
+ "Could not start the local OAuth callback. Check whether port 51121 is already in use.",
174
+ );
175
+ }
176
+
177
+ try {
178
+ const timeoutMs = options.timeoutMs ?? LOCAL_CALLBACK_TIMEOUT_MS;
179
+ return await Promise.race([
180
+ result,
181
+ new Promise<LocalOAuthCallbackResult>((_, reject) => {
182
+ const timeout = setTimeout(() => {
183
+ reject(new OAuthCallbackTimeoutError("The local OAuth callback timed out."));
184
+ }, timeoutMs);
185
+ timeout.unref?.();
186
+ }),
187
+ ]);
188
+ } finally {
189
+ await closeServer(server);
190
+ }
191
+ }
192
+
193
+ function shouldOpenBrowser(): boolean {
194
+ return ["1", "true", "yes"].includes(
195
+ (process.env.TUXEVIL_OPEN_BROWSER ?? "").trim().toLowerCase(),
196
+ );
197
+ }
198
+
199
+ /** Open a URL without a shell; the auth URL contains no access/refresh token. */
200
+ export function openOAuthBrowser(url: string): boolean {
201
+ const browser = process.env.BROWSER?.trim();
202
+ const command = browser ||
203
+ (process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd.exe" : "xdg-open");
204
+ const args = browser
205
+ ? [url]
206
+ : process.platform === "win32"
207
+ ? ["/c", "start", "", url]
208
+ : [url];
209
+ try {
210
+ const child = spawn(command, args, { detached: true, stdio: "ignore", shell: false });
211
+ child.unref();
212
+ return true;
213
+ } catch {
214
+ return false;
215
+ }
216
+ }
217
+
218
+ export async function runLogin(): Promise<AccountConfig> {
219
+ console.log("=== Tuxevil Rotator - Add Google Antigravity Account ===");
220
+ console.log();
221
+
222
+ const { verifier, challenge } = generatePkce();
223
+ const state = generateState();
224
+ const authUrl = buildAuthUrl(state, challenge);
225
+
226
+ console.log("1. Open this URL in your browser:");
227
+ console.log();
228
+ console.log(authUrl);
229
+ console.log();
230
+ console.log("2. Complete the Google sign-in.");
231
+ console.log("3. Return to this terminal after Google redirects to the configured callback.");
232
+ console.log();
233
+
234
+ const redirectUri = getOAuthClientConfig().redirectUri;
235
+ let parsed: { code?: string; state?: string };
236
+ if (isLoopbackRedirectUri(redirectUri)) {
237
+ if (shouldOpenBrowser() && openOAuthBrowser(authUrl)) {
238
+ console.log("Opened the OAuth page in your browser.");
239
+ }
240
+ try {
241
+ const callback = await waitForLocalOAuthCallback(state, { redirectUri });
242
+ if ("error" in callback) {
243
+ throw new Error(callback.errorDescription || callback.error);
244
+ }
245
+ parsed = callback;
246
+ } catch (err) {
247
+ if (!(err instanceof OAuthCallbackUnavailableError)) throw err;
248
+ console.log(err.message);
249
+ const redirectUrl = await askQuestion("Paste the redirect URL: ");
250
+ parsed = parseRedirectUrl(redirectUrl);
251
+ }
252
+ } else {
253
+ const redirectUrl = await askQuestion("Paste the redirect URL: ");
254
+ if (!redirectUrl) throw new Error("No URL provided.");
255
+ parsed = parseRedirectUrl(redirectUrl);
256
+ }
257
+
258
+ if (!parsed.code) {
259
+ throw new Error("Could not extract authorization code from the URL.");
260
+ }
261
+
262
+ if (parsed.state !== state) {
263
+ throw new Error("State mismatch - the URL does not match this login session.");
264
+ }
265
+
266
+ console.log();
267
+ console.log("Exchanging code for tokens...");
268
+ const tokenData = await exchangeAuthorizationCode(parsed.code, verifier);
269
+
270
+ console.log("Getting user info...");
271
+ const email = await getUserEmail(tokenData.accessToken);
272
+
273
+ console.log("Discovering project...");
274
+ const project = await discoverProject(tokenData.accessToken);
275
+
276
+ const label = email ? email.split("@")[0] : "Account";
277
+ return {
278
+ provider: "google-antigravity",
279
+ email: email || "unknown@gmail.com",
280
+ refreshToken: tokenData.refreshToken,
281
+ projectId: project.projectId,
282
+ projectSource: project.source,
283
+ label,
284
+ };
285
+ }
@@ -0,0 +1,314 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { ANTIGRAVITY_VERSION, CLIENT_ID, CLIENT_SECRET, REQUEST_USER_AGENT, TOKEN_URL } from "../../types.js";
3
+ import { fetchWithRetry } from "../../fetch-with-retry.js";
4
+
5
+ export const DEFAULT_REDIRECT_URI = "http://localhost:51121/oauth-callback";
6
+ export const SCOPES = [
7
+ "https://www.googleapis.com/auth/cloud-platform",
8
+ "https://www.googleapis.com/auth/userinfo.email",
9
+ "https://www.googleapis.com/auth/userinfo.profile",
10
+ "https://www.googleapis.com/auth/cclog",
11
+ "https://www.googleapis.com/auth/experimentsandconfigs",
12
+ ];
13
+ export const AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth";
14
+
15
+ export interface OAuthClientConfig {
16
+ clientId: string;
17
+ clientSecret: string;
18
+ redirectUri: string;
19
+ }
20
+
21
+ export interface TokenExchangeResult {
22
+ accessToken: string;
23
+ refreshToken: string;
24
+ expiresIn: number;
25
+ }
26
+
27
+ export function getOAuthClientConfig(
28
+ env: NodeJS.ProcessEnv = process.env,
29
+ ): OAuthClientConfig {
30
+ const clientId = env.ANTIGRAVITY_CLIENT_ID?.trim() || CLIENT_ID;
31
+ const clientSecret = env.ANTIGRAVITY_CLIENT_SECRET?.trim() || CLIENT_SECRET;
32
+ const redirectUri = env.ANTIGRAVITY_REDIRECT_URI?.trim() || DEFAULT_REDIRECT_URI;
33
+ try {
34
+ const redirectUrl = new URL(redirectUri);
35
+ if (redirectUrl.protocol !== "http:" && redirectUrl.protocol !== "https:") {
36
+ throw new Error("unsupported protocol");
37
+ }
38
+ } catch {
39
+ throw new Error("Invalid OAuth redirect URI: use an absolute http:// or https:// URL.");
40
+ }
41
+
42
+ return {
43
+ clientId,
44
+ clientSecret,
45
+ redirectUri,
46
+ };
47
+ }
48
+
49
+ let warnedAboutFallback = false;
50
+
51
+ /**
52
+ * Check whether the rotator is using the legacy compatibility OAuth client.
53
+ * Operator-provided credentials always take precedence. The fallback remains
54
+ * available so existing installations do not break during upgrades.
55
+ *
56
+ * The warning is printed at most once per process to avoid log spam.
57
+ */
58
+ export function warnIfUsingFallbackOAuthCreds(env: NodeJS.ProcessEnv = process.env): boolean {
59
+ const usingFallbackId = !env.ANTIGRAVITY_CLIENT_ID?.trim();
60
+ const usingFallbackSecret = !env.ANTIGRAVITY_CLIENT_SECRET?.trim();
61
+ if (!usingFallbackId && !usingFallbackSecret) return false;
62
+ if (warnedAboutFallback) return true;
63
+ warnedAboutFallback = true;
64
+ const missing: string[] = [];
65
+ if (usingFallbackId) missing.push("ANTIGRAVITY_CLIENT_ID");
66
+ if (usingFallbackSecret) missing.push("ANTIGRAVITY_CLIENT_SECRET");
67
+ console.warn(
68
+ "Using the bundled legacy OAuth client credentials " +
69
+ `(missing env: ${missing.join(" and ")}). Set ${missing.join(" and ")} to your own registered OAuth client when convenient.`,
70
+ );
71
+ return true;
72
+ }
73
+
74
+ export function isHostedOAuthConfigured(): boolean {
75
+ try {
76
+ const { redirectUri } = getOAuthClientConfig();
77
+ const url = new URL(redirectUri);
78
+ return url.hostname !== "localhost" && url.hostname !== "127.0.0.1";
79
+ } catch {
80
+ return false;
81
+ }
82
+ }
83
+
84
+ export function generatePkce(): { verifier: string; challenge: string } {
85
+ const verifier = randomBytes(32).toString("base64url");
86
+ const challenge = createHash("sha256").update(verifier).digest("base64url");
87
+ return { verifier, challenge };
88
+ }
89
+
90
+ export function generateState(): string {
91
+ return randomBytes(24).toString("base64url");
92
+ }
93
+
94
+ export function buildAuthUrl(state: string, challenge: string): string {
95
+ const oauth = getOAuthClientConfig();
96
+ const authParams = new URLSearchParams({
97
+ client_id: oauth.clientId,
98
+ response_type: "code",
99
+ redirect_uri: oauth.redirectUri,
100
+ scope: SCOPES.join(" "),
101
+ code_challenge: challenge,
102
+ code_challenge_method: "S256",
103
+ state,
104
+ access_type: "offline",
105
+ prompt: "consent",
106
+ });
107
+
108
+ return `${AUTH_URL}?${authParams.toString()}`;
109
+ }
110
+
111
+ export async function exchangeAuthorizationCode(code: string, verifier: string): Promise<TokenExchangeResult> {
112
+ const oauth = getOAuthClientConfig();
113
+ const tokenResponse = await fetchWithRetry(TOKEN_URL, {
114
+ method: "POST",
115
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
116
+ body: new URLSearchParams({
117
+ client_id: oauth.clientId,
118
+ client_secret: oauth.clientSecret,
119
+ code,
120
+ grant_type: "authorization_code",
121
+ redirect_uri: oauth.redirectUri,
122
+ code_verifier: verifier,
123
+ }),
124
+ });
125
+
126
+ if (!tokenResponse.ok) {
127
+ const error = await tokenResponse.text();
128
+ throw new Error(`Token exchange failed: ${error}`);
129
+ }
130
+
131
+ const tokenData = (await tokenResponse.json()) as {
132
+ access_token: string;
133
+ refresh_token?: string;
134
+ expires_in: number;
135
+ };
136
+
137
+ if (!tokenData.refresh_token) {
138
+ throw new Error("No refresh token received. Try again.");
139
+ }
140
+
141
+ return {
142
+ accessToken: tokenData.access_token,
143
+ refreshToken: tokenData.refresh_token,
144
+ expiresIn: tokenData.expires_in,
145
+ };
146
+ }
147
+
148
+ export interface ProjectDiscoveryResult {
149
+ projectId: string;
150
+ source: "google";
151
+ endpoint: string;
152
+ }
153
+
154
+ // Discovery order mirrors what third-party Antigravity proxies observe:
155
+ // production endpoints first, sandbox last.
156
+ const LOAD_CODE_ASSIST_ENDPOINTS = [
157
+ "https://daily-cloudcode-pa.googleapis.com",
158
+ "https://cloudcode-pa.googleapis.com",
159
+ "https://daily-cloudcode-pa.sandbox.googleapis.com",
160
+ ] as const;
161
+
162
+ const ONBOARD_USER_ENDPOINT =
163
+ "https://daily-cloudcode-pa.googleapis.com/v1internal:onboardUser";
164
+
165
+ const ONBOARD_MAX_POLLS = 5;
166
+ const ONBOARD_POLL_INTERVAL_MS = 2_000;
167
+
168
+ function sleep(ms: number): Promise<void> {
169
+ return new Promise((resolve) => setTimeout(resolve, ms));
170
+ }
171
+
172
+ function extractProjectId(data: Record<string, unknown> | null): string | null {
173
+ if (!data || typeof data !== "object") return null;
174
+ for (const key of ["cloudaicompanionProject", "projectId", "project"]) {
175
+ const value = data[key];
176
+ if (typeof value === "string" && value.trim()) return value.trim();
177
+ if (
178
+ value &&
179
+ typeof value === "object" &&
180
+ typeof (value as { id?: unknown }).id === "string" &&
181
+ ((value as { id: string }).id as string).trim()
182
+ ) {
183
+ return ((value as { id: string }).id as string).trim();
184
+ }
185
+ }
186
+ return null;
187
+ }
188
+
189
+ // Mirrors the reference clients: the default tier is the allowedTiers entry
190
+ // marked isDefault, then currentTier.id, then "free-tier".
191
+ function extractDefaultTierId(data: Record<string, unknown> | null): string {
192
+ if (!data || typeof data !== "object") return "free-tier";
193
+ const allowedTiers = Array.isArray(data.allowedTiers) ? data.allowedTiers : [];
194
+ for (const rawTier of allowedTiers) {
195
+ const tier = rawTier && typeof rawTier === "object" ? (rawTier as Record<string, unknown>) : null;
196
+ if (tier && tier.isDefault === true && typeof tier.id === "string" && tier.id.trim()) {
197
+ return tier.id.trim();
198
+ }
199
+ }
200
+ const currentTier =
201
+ data.currentTier && typeof data.currentTier === "object"
202
+ ? (data.currentTier as Record<string, unknown>)
203
+ : null;
204
+ if (currentTier && typeof currentTier.id === "string" && currentTier.id.trim()) {
205
+ return currentTier.id.trim();
206
+ }
207
+ return "free-tier";
208
+ }
209
+
210
+ /**
211
+ * Provision a Cloud Code companion project for an account that has none yet.
212
+ * New accounts normally only get one bound after first use in the Antigravity
213
+ * IDE; calling the same `onboardUser` endpoint the IDE uses lets login
214
+ * complete without requiring a manual IDE activation step.
215
+ */
216
+ async function onboardUser(accessToken: string, tierId: string): Promise<string | null> {
217
+ const headers: Record<string, string> = {
218
+ Authorization: `Bearer ${accessToken}`,
219
+ "Content-Type": "application/json",
220
+ "User-Agent": `${REQUEST_USER_AGENT} google-api-nodejs-client/10.3.0`,
221
+ "X-Goog-Api-Client": "gl-node/22.21.1",
222
+ };
223
+
224
+ const body = JSON.stringify({
225
+ tier_id: tierId,
226
+ metadata: {
227
+ ide_type: "ANTIGRAVITY",
228
+ ide_version: ANTIGRAVITY_VERSION,
229
+ ide_name: "antigravity",
230
+ },
231
+ });
232
+
233
+ for (let attempt = 0; attempt < ONBOARD_MAX_POLLS; attempt++) {
234
+ if (attempt > 0) await sleep(ONBOARD_POLL_INTERVAL_MS);
235
+ try {
236
+ const response = await fetchWithRetry(ONBOARD_USER_ENDPOINT, {
237
+ method: "POST",
238
+ headers,
239
+ body,
240
+ });
241
+ if (!response.ok) return null;
242
+ const data = (await response.json()) as Record<string, unknown> | null;
243
+ if (data && data.done === true) {
244
+ const inner =
245
+ data.response && typeof data.response === "object"
246
+ ? (data.response as Record<string, unknown>)
247
+ : data;
248
+ return extractProjectId(inner);
249
+ }
250
+ // done:false — provisioning still running; poll again.
251
+ } catch {
252
+ return null;
253
+ }
254
+ }
255
+ return null;
256
+ }
257
+
258
+ export async function discoverProject(accessToken: string): Promise<ProjectDiscoveryResult> {
259
+ const headers: Record<string, string> = {
260
+ Authorization: `Bearer ${accessToken}`,
261
+ "Content-Type": "application/json",
262
+ "User-Agent": REQUEST_USER_AGENT,
263
+ };
264
+
265
+ let lastLoadData: Record<string, unknown> | null = null;
266
+
267
+ for (const endpoint of LOAD_CODE_ASSIST_ENDPOINTS) {
268
+ try {
269
+ const response = await fetchWithRetry(`${endpoint}/v1internal:loadCodeAssist`, {
270
+ method: "POST",
271
+ headers,
272
+ body: JSON.stringify({
273
+ metadata: { ideType: "ANTIGRAVITY" },
274
+ }),
275
+ });
276
+
277
+ if (response.ok) {
278
+ const data = (await response.json().catch(() => null)) as Record<string, unknown> | null;
279
+ lastLoadData = data;
280
+ const projectId = extractProjectId(data);
281
+ if (projectId) {
282
+ return { projectId, source: "google", endpoint };
283
+ }
284
+ }
285
+ } catch {
286
+ // Try next endpoint
287
+ }
288
+ }
289
+
290
+ // No project bound yet — provision one the same way the IDE does.
291
+ if (lastLoadData) {
292
+ const onboarded = await onboardUser(accessToken, extractDefaultTierId(lastLoadData));
293
+ if (onboarded) {
294
+ return { projectId: onboarded, source: "google", endpoint: ONBOARD_USER_ENDPOINT };
295
+ }
296
+ }
297
+
298
+ throw new Error("Could not discover Cloud Code companion project ID from Google. If this account is new, open it in Antigravity IDE and send one message first, then retry login. Login failed instead of falling back to a shared projectId.");
299
+ }
300
+
301
+ export async function getUserEmail(accessToken: string): Promise<string | undefined> {
302
+ try {
303
+ const response = await fetchWithRetry("https://www.googleapis.com/oauth2/v1/userinfo?alt=json", {
304
+ headers: { Authorization: `Bearer ${accessToken}` },
305
+ });
306
+ if (response.ok) {
307
+ const data = (await response.json()) as { email?: string };
308
+ return data.email;
309
+ }
310
+ } catch {
311
+ // Ignore
312
+ }
313
+ return undefined;
314
+ }