@wizardwarlocks/tubex 0.0.0-stage → 0.1.1

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015-present 650 Industries, Inc. (aka Expo)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,201 @@
1
- # Temporary Holding Version
1
+ # Tubex
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Tubex is a minimal, terminal-based YouTube client and video downloader built with JavaScript (ES Modules). It allows you to search YouTube, browse your playlists, authenticate via Google OAuth 2.0, and download videos or extract audio using `yt-dlp`.
4
+
5
+ ---
6
+
7
+ ## Features
8
+
9
+ - 🔍 **YouTube Search**: Search for videos directly from your terminal with customizable result limits.
10
+ - 🔐 **Google OAuth 2.0 Authentication**: Connect your Google account via a secure loopback browser flow.
11
+ - 📂 **Playlist Management**: View your playlists and inspect video tracks with full pagination support.
12
+ - 📥 **Video Downloading**: Download videos safely using `yt-dlp` with live terminal progress.
13
+ - ⚙️ **Configurable Downloads**: Select video resolution (360p to 4K / best), choose container formats (`mp4`, `mkv`, `webm`), specify output directories, or extract audio-only (`mp3`).
14
+ - 🎨 **Clean Terminal Interface**: Minimal, non-intrusive terminal styling with clear error handling.
15
+
16
+ ---
17
+
18
+ ## Prerequisites
19
+
20
+ - **Node.js**: v20.0.0 or later
21
+ - **yt-dlp**: Required for downloading videos
22
+ - **FFmpeg**: Required for audio extraction (`--audio-only`) and stream merging
23
+
24
+ ### Installing External Tools
25
+
26
+ #### macOS (Homebrew)
27
+ ```bash
28
+ brew install yt-dlp ffmpeg
29
+ ```
30
+
31
+ #### Linux (Debian/Ubuntu)
32
+ ```bash
33
+ sudo apt update && sudo apt install yt-dlp ffmpeg
34
+ ```
35
+
36
+ #### Windows (winget / Chocolatey)
37
+ ```powershell
38
+ winget install yt-dlp Gyan.FFmpeg
39
+ # or via Chocolatey:
40
+ choco install yt-dlp ffmpeg
41
+ ```
42
+
43
+ ---
44
+
45
+ ## Installation
46
+
47
+ ### From Source
48
+
49
+ ```bash
50
+ git clone https://github.com/kartikktripathi/Tubex.git
51
+ cd Tubex
52
+ npm install
53
+ npm link
54
+ ```
55
+
56
+ ### Via npm (when published)
57
+
58
+ ```bash
59
+ npm install -g @wizardwarlocks/tubex
60
+ ```
61
+
62
+ ---
63
+
64
+ ## Configuration
65
+
66
+ Tubex resolves credentials in the following order of precedence:
67
+ 1. **Shell environment variables** (`export YOUTUBE_API_KEY=...`)
68
+ 2. **Current working directory `.env` file** (convenient for local project development)
69
+ 3. **User configuration `.env` file** (recommended for global installation):
70
+ - Linux / macOS: `~/.config/tubex/.env`
71
+ - Windows: `%APPDATA%\tubex\.env`
72
+
73
+ For local development, copy the example file:
74
+
75
+ ```bash
76
+ cp .env.example .env
77
+ ```
78
+
79
+ For global CLI usage, create `~/.config/tubex/.env`:
80
+
81
+ ```bash
82
+ mkdir -p ~/.config/tubex
83
+ cat << 'EOF' > ~/.config/tubex/.env
84
+ YOUTUBE_API_KEY=your_api_key_here
85
+ GOOGLE_CLIENT_ID=your_client_id_here
86
+ GOOGLE_CLIENT_SECRET=your_client_secret_here
87
+ EOF
88
+ ```
89
+
90
+ ### 1. YouTube Data API Key (Required for Search)
91
+
92
+ 1. Open the [Google Cloud Console](https://console.cloud.google.com/).
93
+ 2. Create a project and enable the **YouTube Data API v3**.
94
+ 3. Go to **APIs & Services > Credentials** and click **Create Credentials > API Key**.
95
+ 4. Add it to your `~/.config/tubex/.env` (or project `.env`):
96
+ ```env
97
+ YOUTUBE_API_KEY=your_api_key_here
98
+ ```
99
+ Or set it in your environment:
100
+ ```bash
101
+ export YOUTUBE_API_KEY="your_api_key_here"
102
+ ```
103
+
104
+ ### 2. Google OAuth 2.0 Credentials (Required for Playlists)
105
+
106
+ 1. In Google Cloud Console, enable **YouTube Data API v3**.
107
+ 2. Go to **APIs & Services > OAuth consent screen**, select User Type (e.g., External), and add your email as a test user.
108
+ 3. Under **Credentials**, click **Create Credentials > OAuth client ID**.
109
+ 4. Select Application type: **Desktop app**.
110
+ 5. Add the generated credentials to `~/.config/tubex/.env` (or project `.env`):
111
+ ```env
112
+ GOOGLE_CLIENT_ID=your_client_id_here
113
+ GOOGLE_CLIENT_SECRET=your_client_secret_here
114
+ ```
115
+ Or export them in your terminal:
116
+ ```bash
117
+ export GOOGLE_CLIENT_ID="your_client_id_here"
118
+ export GOOGLE_CLIENT_SECRET="your_client_secret_here"
119
+ ```
120
+
121
+ *(Note: OAuth tokens are saved securely to your user configuration directory `~/.config/tubex/tokens.json` with `0600` permissions and are never committed to Git).*
122
+
123
+ ---
124
+
125
+ ## Usage & Commands
126
+
127
+ ### 1. Searching Videos
128
+
129
+ Search YouTube videos with an optional limit (1–50, default: 10):
130
+
131
+ ```bash
132
+ # Default search (10 results)
133
+ tubex search "lofi hip hop"
134
+
135
+ # Custom limit
136
+ tubex search "javascript tutorial" --limit 20
137
+ ```
138
+
139
+ ### 2. Authentication
140
+
141
+ Connect your Google account to access your playlists:
142
+
143
+ ```bash
144
+ # Login (opens browser for Google OAuth)
145
+ tubex auth login
146
+
147
+ # Check current authentication status
148
+ tubex auth status
149
+
150
+ # Logout and remove stored tokens
151
+ tubex auth logout
152
+ ```
153
+
154
+ ### 3. Playlists
155
+
156
+ View your playlists and video listings:
157
+
158
+ ```bash
159
+ # List all your playlists
160
+ tubex playlists
161
+
162
+ # Inspect videos inside a specific playlist
163
+ tubex playlist <playlist-id>
164
+ ```
165
+
166
+ ### 4. Downloading Videos
167
+
168
+ Download YouTube videos using `yt-dlp`:
169
+
170
+ ```bash
171
+ # Basic download (default: best quality, saved to ./downloads)
172
+ tubex download "https://www.youtube.com/watch?v=VIDEO_ID"
173
+
174
+ # Specify video quality (360, 480, 720, 1080, 1440, 2160, best)
175
+ tubex download "https://www.youtube.com/watch?v=VIDEO_ID" --quality 1080
176
+
177
+ # Specify container format (mp4, mkv, webm)
178
+ tubex download "https://www.youtube.com/watch?v=VIDEO_ID" --format mp4
179
+
180
+ # Specify output directory
181
+ tubex download "https://www.youtube.com/watch?v=VIDEO_ID" --output ./my-videos
182
+
183
+ # Audio-only mode (extracts MP3)
184
+ tubex download "https://www.youtube.com/watch?v=VIDEO_ID" --audio-only
185
+ ```
186
+
187
+ ---
188
+
189
+ ## Troubleshooting
190
+
191
+ - **`yt-dlp is not installed or not found in your PATH`**: Ensure `yt-dlp` is installed and accessible from your terminal. Test with `yt-dlp --version`.
192
+ - **`ffmpeg is required for audio extraction`**: When using `--audio-only`, FFmpeg must be installed. Test with `ffmpeg -version`.
193
+ - **`YOUTUBE_API_KEY is not configured`**: Add your API key to `.env` or run `export YOUTUBE_API_KEY="your_key"`.
194
+ - **`Google OAuth credentials are not configured`**: Set `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` in `.env` before running `tubex auth login`.
195
+ - **`Authentication expired or revoked`**: Run `tubex auth login` to refresh your OAuth session.
196
+
197
+ ---
198
+
199
+ ## License
200
+
201
+ MIT License. See [LICENSE](LICENSE) for details.
package/bin/tubex.js ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { run } from "../src/cli.js";
4
+
5
+ run().catch((error) => {
6
+ console.error(`\x1b[31mError:\x1b[0m ${error.message || error}`);
7
+ process.exitCode = 1;
8
+ });
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@wizardwarlocks/tubex",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Terminal-based YouTube client and video downloader",
5
+ "main": "bin/tubex.js",
6
+ "bin": {
7
+ "tubex": "./bin/tubex.js"
8
+ },
9
+ "publishConfig": {
10
+ "access": "public"
11
+ },
12
+ "type": "module",
13
+ "engines": {
14
+ "node": ">=20.0.0"
15
+ },
16
+ "scripts": {
17
+ "start": "node ./bin/tubex.js",
18
+ "test": "node --test"
19
+ },
20
+ "files": [
21
+ "bin",
22
+ "src",
23
+ "README.md",
24
+ "LICENSE"
25
+ ],
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/kartikktripathi/Tubex.git"
29
+ },
30
+ "keywords": [
31
+ "youtube",
32
+ "cli",
33
+ "terminal",
34
+ "downloader",
35
+ "yt-dlp",
36
+ "oauth",
37
+ "playlists"
38
+ ],
39
+ "author": "Kartik Tripathi <kartiktripathi103@gmail.com>",
40
+ "license": "MIT",
41
+ "bugs": {
42
+ "url": "https://github.com/kartikktripathi/Tubex/issues"
43
+ },
44
+ "homepage": "https://github.com/kartikktripathi/Tubex#readme",
45
+ "dependencies": {
46
+ "commander": "^15.1.0",
47
+ "google-auth-library": "^11.3.4"
48
+ },
49
+ "devDependencies": {
50
+ "prettier": "^3.10.1"
51
+ }
52
+ }
package/src/auth.js ADDED
@@ -0,0 +1,382 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import http from "node:http";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { execFile } from "node:child_process";
7
+ import { OAuth2Client } from "google-auth-library";
8
+
9
+ const SCOPES = ["https://www.googleapis.com/auth/youtube.readonly"];
10
+
11
+ export function getConfigDir() {
12
+ if (process.platform === "win32") {
13
+ return process.env.APPDATA
14
+ ? path.join(process.env.APPDATA, "tubex")
15
+ : path.join(os.homedir(), ".tubex");
16
+ }
17
+
18
+ const configHome =
19
+ process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
20
+ return path.join(configHome, "tubex");
21
+ }
22
+
23
+ export function getTokenPath() {
24
+ return path.join(getConfigDir(), "tokens.json");
25
+ }
26
+
27
+ export async function saveTokens(tokens) {
28
+ const dir = getConfigDir();
29
+ await fs.mkdir(dir, { recursive: true, mode: 0o700 });
30
+
31
+ const tokenPath = getTokenPath();
32
+ await fs.writeFile(tokenPath, JSON.stringify(tokens, null, 2), {
33
+ mode: 0o600,
34
+ });
35
+
36
+ try {
37
+ await fs.chmod(tokenPath, 0o600);
38
+ } catch {
39
+ // Ignore permissions errors on platforms without POSIX chmod support
40
+ }
41
+ }
42
+
43
+ export async function loadTokens() {
44
+ try {
45
+ const data = await fs.readFile(getTokenPath(), "utf-8");
46
+ return JSON.parse(data);
47
+ } catch (error) {
48
+ if (error.code === "ENOENT") {
49
+ return null;
50
+ }
51
+ return null;
52
+ }
53
+ }
54
+
55
+ export async function clearTokens() {
56
+ try {
57
+ await fs.unlink(getTokenPath());
58
+ return true;
59
+ } catch (error) {
60
+ if (error.code === "ENOENT") {
61
+ return false;
62
+ }
63
+ throw error;
64
+ }
65
+ }
66
+
67
+ export async function getAuthStatus() {
68
+ const tokens = await loadTokens();
69
+ if (tokens && (tokens.access_token || tokens.refresh_token)) {
70
+ return {
71
+ authenticated: true,
72
+ account: "Connected Google account",
73
+ };
74
+ }
75
+
76
+ return {
77
+ authenticated: false,
78
+ };
79
+ }
80
+
81
+ export function loadEnvironment() {
82
+ if (typeof process.loadEnvFile !== "function") return;
83
+
84
+ // 1. Try loading from current working directory (local .env)
85
+ try {
86
+ process.loadEnvFile();
87
+ } catch (err) {
88
+ if (err.code !== "ENOENT") {
89
+ // Ignore missing .env
90
+ }
91
+ }
92
+
93
+ // 2. Try loading from user config directory (~/.config/tubex/.env)
94
+ try {
95
+ process.loadEnvFile(path.join(getConfigDir(), ".env"));
96
+ } catch (err) {
97
+ if (err.code !== "ENOENT") {
98
+ // Ignore missing .env
99
+ }
100
+ }
101
+ }
102
+
103
+ export function getOAuthCredentials() {
104
+ if (!process.env.GOOGLE_CLIENT_ID || !process.env.GOOGLE_CLIENT_SECRET) {
105
+ loadEnvironment();
106
+ }
107
+
108
+ const clientId = process.env.GOOGLE_CLIENT_ID?.trim();
109
+ const clientSecret = process.env.GOOGLE_CLIENT_SECRET?.trim();
110
+
111
+ return { clientId, clientSecret };
112
+ }
113
+
114
+ export async function getValidAccessToken() {
115
+ const tokens = await loadTokens();
116
+ if (!tokens || (!tokens.access_token && !tokens.refresh_token)) {
117
+ const error = new Error("You must be authenticated to perform this action.");
118
+ error.code = "NOT_AUTHENTICATED";
119
+ throw error;
120
+ }
121
+
122
+ // If token is present and not expired (with 60-second buffer), use it directly
123
+ if (
124
+ tokens.access_token &&
125
+ tokens.expiry_date &&
126
+ tokens.expiry_date > Date.now() + 60000
127
+ ) {
128
+ return tokens.access_token;
129
+ }
130
+
131
+ // If token is expired or expiring, refresh using refresh_token
132
+ if (tokens.refresh_token) {
133
+ const { clientId, clientSecret } = getOAuthCredentials();
134
+ if (!clientId || !clientSecret) {
135
+ if (tokens.access_token) {
136
+ return tokens.access_token;
137
+ }
138
+ const error = new Error(
139
+ "Google OAuth credentials are not configured. Unable to refresh token.",
140
+ );
141
+ error.code = "MISSING_OAUTH_CREDENTIALS";
142
+ throw error;
143
+ }
144
+
145
+ const oauth2Client = new OAuth2Client(clientId, clientSecret);
146
+ oauth2Client.setCredentials(tokens);
147
+
148
+ oauth2Client.on("tokens", async (newTokens) => {
149
+ const current = (await loadTokens()) || {};
150
+ await saveTokens({ ...current, ...newTokens });
151
+ });
152
+
153
+ try {
154
+ const res = await oauth2Client.getAccessToken();
155
+ const freshToken = res.token || oauth2Client.credentials.access_token;
156
+ if (!freshToken) {
157
+ throw new Error("Failed to refresh access token.");
158
+ }
159
+ return freshToken;
160
+ } catch (err) {
161
+ if (
162
+ err.message?.includes("invalid_grant") ||
163
+ err.message?.includes("revoked") ||
164
+ err.message?.includes("expired")
165
+ ) {
166
+ const error = new Error(
167
+ "Authentication has expired or been revoked. Please run 'tubex auth login' again.",
168
+ );
169
+ error.code = "AUTH_REVOKED";
170
+ throw error;
171
+ }
172
+ throw err;
173
+ }
174
+ }
175
+
176
+ const error = new Error(
177
+ "Authentication has expired. Please run 'tubex auth login' again.",
178
+ );
179
+ error.code = "AUTH_EXPIRED";
180
+ throw error;
181
+ }
182
+
183
+ export function openBrowser(url) {
184
+ if (process.platform === "darwin") {
185
+ execFile("open", [url], () => {});
186
+ } else if (process.platform === "win32") {
187
+ execFile("cmd", ["/c", "start", "", url], () => {});
188
+ } else {
189
+ execFile("xdg-open", [url], () => {});
190
+ }
191
+ }
192
+
193
+ function getSuccessHtml() {
194
+ return `<!DOCTYPE html>
195
+ <html>
196
+ <head>
197
+ <meta charset="utf-8">
198
+ <title>Tubex — Authentication Successful</title>
199
+ <style>
200
+ body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; background: #0f0f0f; color: #f1f1f1; }
201
+ .card { background: #212121; padding: 2rem 2.5rem; border-radius: 8px; text-align: center; max-width: 420px; box-shadow: 0 4px 12px rgba(0,0,0,0.5); }
202
+ h1 { margin-top: 0; color: #4ade80; font-size: 1.5rem; }
203
+ p { color: #aaa; line-height: 1.5; }
204
+ </style>
205
+ </head>
206
+ <body>
207
+ <div class="card">
208
+ <h1>Authentication Successful</h1>
209
+ <p>You have successfully authenticated with Google. You can now close this tab and return to the terminal.</p>
210
+ </div>
211
+ </body>
212
+ </html>`;
213
+ }
214
+
215
+ function getErrorHtml(message) {
216
+ return `<!DOCTYPE html>
217
+ <html>
218
+ <head>
219
+ <meta charset="utf-8">
220
+ <title>Tubex — Authentication Failed</title>
221
+ <style>
222
+ body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; background: #0f0f0f; color: #f1f1f1; }
223
+ .card { background: #212121; padding: 2rem 2.5rem; border-radius: 8px; text-align: center; max-width: 420px; box-shadow: 0 4px 12px rgba(0,0,0,0.5); }
224
+ h1 { margin-top: 0; color: #f87171; font-size: 1.5rem; }
225
+ p { color: #aaa; line-height: 1.5; }
226
+ </style>
227
+ </head>
228
+ <body>
229
+ <div class="card">
230
+ <h1>Authentication Failed</h1>
231
+ <p>${message}</p>
232
+ <p>Please return to the terminal to try again.</p>
233
+ </div>
234
+ </body>
235
+ </html>`;
236
+ }
237
+
238
+ export async function loginWithGoogle() {
239
+ const { clientId, clientSecret } = getOAuthCredentials();
240
+
241
+ if (!clientId || !clientSecret) {
242
+ const error = new Error("Google OAuth credentials are not configured.");
243
+ error.code = "MISSING_OAUTH_CREDENTIALS";
244
+ throw error;
245
+ }
246
+
247
+ return new Promise((resolve, reject) => {
248
+ let resolved = false;
249
+ let timer = null;
250
+ let oauth2Client = null;
251
+ let expectedState = null;
252
+
253
+ const cleanup = () => {
254
+ if (timer) clearTimeout(timer);
255
+ process.removeListener("SIGINT", handleSigInt);
256
+ try {
257
+ server.close();
258
+ } catch {}
259
+ };
260
+
261
+ const handleSigInt = () => {
262
+ cleanup();
263
+ process.exit(130);
264
+ };
265
+
266
+ process.once("SIGINT", handleSigInt);
267
+
268
+ const server = http.createServer(async (req, res) => {
269
+ try {
270
+ const reqUrl = new URL(req.url, `http://${req.headers.host}`);
271
+ if (reqUrl.pathname !== "/") {
272
+ res.writeHead(404);
273
+ res.end("Not found");
274
+ return;
275
+ }
276
+
277
+ const returnedState = reqUrl.searchParams.get("state");
278
+ const code = reqUrl.searchParams.get("code");
279
+ const oauthError = reqUrl.searchParams.get("error");
280
+
281
+ if (oauthError) {
282
+ res.writeHead(200, { "Content-Type": "text/html" });
283
+ res.end(
284
+ getErrorHtml(`Authentication was denied or cancelled (${oauthError}).`),
285
+ );
286
+ cleanup();
287
+ resolved = true;
288
+ const error = new Error(
289
+ `Authentication denied by user: ${oauthError}`,
290
+ );
291
+ error.code = "AUTH_DENIED";
292
+ reject(error);
293
+ return;
294
+ }
295
+
296
+ if (!returnedState || returnedState !== expectedState) {
297
+ res.writeHead(400, { "Content-Type": "text/html" });
298
+ res.end(getErrorHtml("Invalid state parameter. Possible CSRF detected."));
299
+ cleanup();
300
+ resolved = true;
301
+ const error = new Error(
302
+ "Authentication failed: State parameter mismatch.",
303
+ );
304
+ error.code = "STATE_MISMATCH";
305
+ reject(error);
306
+ return;
307
+ }
308
+
309
+ if (!code) {
310
+ res.writeHead(400, { "Content-Type": "text/html" });
311
+ res.end(getErrorHtml("Authorization code missing from callback."));
312
+ cleanup();
313
+ resolved = true;
314
+ const error = new Error(
315
+ "Authentication failed: No authorization code received.",
316
+ );
317
+ error.code = "MISSING_CODE";
318
+ reject(error);
319
+ return;
320
+ }
321
+
322
+ res.writeHead(200, { "Content-Type": "text/html" });
323
+ res.end(getSuccessHtml());
324
+
325
+ const { tokens } = await oauth2Client.getToken(code);
326
+ await saveTokens(tokens);
327
+
328
+ cleanup();
329
+ resolved = true;
330
+ resolve();
331
+ } catch (err) {
332
+ try {
333
+ res.writeHead(500, { "Content-Type": "text/html" });
334
+ res.end(getErrorHtml("Failed to exchange tokens."));
335
+ } catch {}
336
+ cleanup();
337
+ resolved = true;
338
+ reject(err);
339
+ }
340
+ });
341
+
342
+ server.listen(0, "127.0.0.1", () => {
343
+ const { port } = server.address();
344
+ const redirectUri = `http://127.0.0.1:${port}`;
345
+
346
+ oauth2Client = new OAuth2Client(clientId, clientSecret, redirectUri);
347
+ expectedState = crypto.randomBytes(32).toString("hex");
348
+
349
+ const authUrl = oauth2Client.generateAuthUrl({
350
+ access_type: "offline",
351
+ scope: SCOPES,
352
+ state: expectedState,
353
+ prompt: "consent",
354
+ });
355
+
356
+ console.log("Opening browser for Google authentication...\n");
357
+ console.log("If your browser does not open automatically, visit this URL:\n");
358
+ console.log(authUrl);
359
+ console.log("\nWaiting for authentication...");
360
+
361
+ openBrowser(authUrl);
362
+
363
+ timer = setTimeout(() => {
364
+ if (!resolved) {
365
+ cleanup();
366
+ const error = new Error(
367
+ "Authentication timed out (no response received within 2 minutes).",
368
+ );
369
+ error.code = "AUTH_TIMEOUT";
370
+ reject(error);
371
+ }
372
+ }, 120000);
373
+ });
374
+
375
+ server.on("error", (err) => {
376
+ cleanup();
377
+ reject(
378
+ new Error(`Failed to start local callback server: ${err.message}`),
379
+ );
380
+ });
381
+ });
382
+ }