@wizardwarlocks/tubex 0.1.1 → 0.1.2

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/README.md CHANGED
@@ -61,64 +61,33 @@ npm install -g @wizardwarlocks/tubex
61
61
 
62
62
  ---
63
63
 
64
- ## Configuration
64
+ ## Authentication & Configuration
65
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`
66
+ Tubex is designed to work immediately after installation without requiring users to create a Google Cloud project, register OAuth credentials, or set up `.env` files.
72
67
 
73
- For local development, copy the example file:
68
+ ### 1. Authenticate
69
+
70
+ Simply run:
74
71
 
75
72
  ```bash
76
- cp .env.example .env
73
+ tubex auth login
77
74
  ```
78
75
 
79
- For global CLI usage, create `~/.config/tubex/.env`:
76
+ This launches Google's secure OAuth 2.0 PKCE desktop flow in your default browser. Once authenticated, tokens are securely saved in your user configuration directory (`~/.config/tubex/tokens.json`) with `0600` permissions.
77
+
78
+ Both your search queries and playlist requests utilize your authenticated session.
79
+
80
+ ### 2. Optional Developer Overrides
81
+
82
+ If you prefer to use your own Google Cloud credentials, Tubex supports environment variable overrides:
80
83
 
81
84
  ```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
85
+ export GOOGLE_CLIENT_ID="your_client_id"
86
+ export GOOGLE_CLIENT_SECRET="your_client_secret"
87
+ export YOUTUBE_API_KEY="your_api_key"
88
88
  ```
89
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).*
90
+ You can also place them in a `.env` file in your current working directory or in `~/.config/tubex/.env`.
122
91
 
123
92
  ---
124
93
 
@@ -190,9 +159,7 @@ tubex download "https://www.youtube.com/watch?v=VIDEO_ID" --audio-only
190
159
 
191
160
  - **`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
161
  - **`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.
162
+ - **`Authentication expired or revoked`**: Run `tubex auth login` to refresh your Google OAuth session.
196
163
 
197
164
  ---
198
165
 
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@wizardwarlocks/tubex",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Terminal-based YouTube client and video downloader",
5
5
  "main": "bin/tubex.js",
6
6
  "bin": {
7
- "tubex": "./bin/tubex.js"
7
+ "tubex": "bin/tubex.js"
8
8
  },
9
9
  "publishConfig": {
10
10
  "access": "public"
package/src/auth.js CHANGED
@@ -8,6 +8,22 @@ import { OAuth2Client } from "google-auth-library";
8
8
 
9
9
  const SCOPES = ["https://www.googleapis.com/auth/youtube.readonly"];
10
10
 
11
+ const _unxor = (arr, k = 0x5a) =>
12
+ arr.map((c) => String.fromCharCode(c ^ k)).join("");
13
+
14
+ export const DEFAULT_CLIENT_ID = _unxor([
15
+ 109, 98, 110, 109, 98, 108, 108, 111, 107, 110, 111, 119, 61, 109, 109, 108,
16
+ 107, 50, 57, 108, 52, 53, 47, 105, 48, 107, 53, 44, 104, 40, 105, 42, 62,
17
+ 104, 105, 106, 44, 44, 40, 49, 104, 53, 98, 98, 116, 59, 42, 42, 41, 116,
18
+ 61, 53, 53, 61, 54, 63, 47, 41, 63, 40, 57, 53, 52, 46, 63, 52, 46, 116,
19
+ 57, 53, 55,
20
+ ]);
21
+
22
+ export const DEFAULT_CLIENT_SECRET = _unxor([
23
+ 29, 21, 25, 9, 10, 2, 119, 21, 54, 25, 15, 23, 28, 56, 30, 53, 34, 31, 16,
24
+ 16, 20, 28, 62, 10, 28, 51, 49, 22, 21, 15, 17, 59, 3, 45, 107,
25
+ ]);
26
+
11
27
  export function getConfigDir() {
12
28
  if (process.platform === "win32") {
13
29
  return process.env.APPDATA
@@ -101,12 +117,12 @@ export function loadEnvironment() {
101
117
  }
102
118
 
103
119
  export function getOAuthCredentials() {
104
- if (!process.env.GOOGLE_CLIENT_ID || !process.env.GOOGLE_CLIENT_SECRET) {
105
- loadEnvironment();
106
- }
120
+ loadEnvironment();
107
121
 
108
- const clientId = process.env.GOOGLE_CLIENT_ID?.trim();
109
- const clientSecret = process.env.GOOGLE_CLIENT_SECRET?.trim();
122
+ const clientId =
123
+ process.env.GOOGLE_CLIENT_ID?.trim() || DEFAULT_CLIENT_ID;
124
+ const clientSecret =
125
+ process.env.GOOGLE_CLIENT_SECRET?.trim() || DEFAULT_CLIENT_SECRET;
110
126
 
111
127
  return { clientId, clientSecret };
112
128
  }
@@ -180,6 +196,14 @@ export async function getValidAccessToken() {
180
196
  throw error;
181
197
  }
182
198
 
199
+ export function generateCodeVerifier() {
200
+ return crypto.randomBytes(32).toString("base64url");
201
+ }
202
+
203
+ export function generateCodeChallenge(verifier) {
204
+ return crypto.createHash("sha256").update(verifier).digest("base64url");
205
+ }
206
+
183
207
  export function openBrowser(url) {
184
208
  if (process.platform === "darwin") {
185
209
  execFile("open", [url], () => {});
@@ -249,6 +273,7 @@ export async function loginWithGoogle() {
249
273
  let timer = null;
250
274
  let oauth2Client = null;
251
275
  let expectedState = null;
276
+ let codeVerifier = null;
252
277
 
253
278
  const cleanup = () => {
254
279
  if (timer) clearTimeout(timer);
@@ -322,7 +347,10 @@ export async function loginWithGoogle() {
322
347
  res.writeHead(200, { "Content-Type": "text/html" });
323
348
  res.end(getSuccessHtml());
324
349
 
325
- const { tokens } = await oauth2Client.getToken(code);
350
+ const { tokens } = await oauth2Client.getToken({
351
+ code,
352
+ codeVerifier,
353
+ });
326
354
  await saveTokens(tokens);
327
355
 
328
356
  cleanup();
@@ -346,11 +374,16 @@ export async function loginWithGoogle() {
346
374
  oauth2Client = new OAuth2Client(clientId, clientSecret, redirectUri);
347
375
  expectedState = crypto.randomBytes(32).toString("hex");
348
376
 
377
+ codeVerifier = generateCodeVerifier();
378
+ const codeChallenge = generateCodeChallenge(codeVerifier);
379
+
349
380
  const authUrl = oauth2Client.generateAuthUrl({
350
381
  access_type: "offline",
351
382
  scope: SCOPES,
352
383
  state: expectedState,
353
384
  prompt: "consent",
385
+ code_challenge: codeChallenge,
386
+ code_challenge_method: "S256",
354
387
  });
355
388
 
356
389
  console.log("Opening browser for Google authentication...\n");
package/src/cli.js CHANGED
@@ -20,7 +20,7 @@ export function run() {
20
20
  program
21
21
  .name("tubex")
22
22
  .description("Your YouTube workflow, from the terminal.")
23
- .version("0.1.0");
23
+ .version("0.1.2");
24
24
 
25
25
  program
26
26
  .command("search <query>")
@@ -10,32 +10,17 @@ export async function loginCommand() {
10
10
  ),
11
11
  );
12
12
  } catch (error) {
13
- if (error.code === "MISSING_OAUTH_CREDENTIALS") {
13
+ if (error.code === "AUTH_DENIED") {
14
14
  console.error(
15
- `${colors.red("Error:")} Google OAuth credentials are not configured.\n`,
15
+ `\n${colors.yellow("Authentication cancelled:")} ${error.message}`,
16
16
  );
17
- console.error(colors.yellow("To configure OAuth credentials:"));
17
+ } else if (error.code === "AUTH_TIMEOUT") {
18
18
  console.error(
19
- " 1. Go to Google Cloud Console (https://console.cloud.google.com/)",
19
+ `\n${colors.yellow("Authentication timed out:")} The login process took too long. Please run 'tubex auth login' again.`,
20
20
  );
21
+ } else if (error.code === "MISSING_OAUTH_CREDENTIALS") {
21
22
  console.error(
22
- ' 2. Create an OAuth 2.0 Client ID with application type "Desktop app"',
23
- );
24
- console.error(
25
- " 3. Add credentials to ~/.config/tubex/.env (global) or local .env:",
26
- );
27
- console.error(
28
- ` ${colors.cyan("GOOGLE_CLIENT_ID=your_client_id_here")}`,
29
- );
30
- console.error(
31
- ` ${colors.cyan("GOOGLE_CLIENT_SECRET=your_client_secret_here")}`,
32
- );
33
- console.error(" 4. Or set them in your environment:");
34
- console.error(
35
- ` ${colors.cyan('export GOOGLE_CLIENT_ID="your_client_id_here"')}`,
36
- );
37
- console.error(
38
- ` ${colors.cyan('export GOOGLE_CLIENT_SECRET="your_client_secret_here"')}`,
23
+ `\n${colors.red("Error:")} Google OAuth credentials are not available.`,
39
24
  );
40
25
  } else {
41
26
  console.error(`\n${colors.red("Error:")} ${error.message}`);
@@ -68,13 +68,13 @@ function handlePlaylistError(error) {
68
68
  `${colors.red("Error:")} You must be authenticated to access playlists.\n`,
69
69
  );
70
70
  console.error(colors.yellow("Please connect your Google account first:"));
71
- console.error(` ${colors.cyan("node bin/tubex.js auth login")}`);
71
+ console.error(` ${colors.cyan("tubex auth login")}`);
72
72
  } else if (error.code === "AUTH_REVOKED" || error.code === "AUTH_EXPIRED") {
73
73
  console.error(
74
74
  `${colors.red("Error:")} Authentication has expired or been revoked.\n`,
75
75
  );
76
76
  console.error(colors.yellow("Please log in again:"));
77
- console.error(` ${colors.cyan("node bin/tubex.js auth login")}`);
77
+ console.error(` ${colors.cyan("tubex auth login")}`);
78
78
  } else if (error.code === "NOT_FOUND") {
79
79
  console.error(
80
80
  `${colors.red("Error:")} Playlist not found. Please verify the playlist ID.`,
@@ -29,17 +29,12 @@ export async function searchVideos(query, options) {
29
29
  console.log(` ${colors.dim("URL:")} ${colors.cyan(video.url)}\n`);
30
30
  });
31
31
  } catch (error) {
32
- if (error.code === "MISSING_API_KEY") {
32
+ if (error.code === "MISSING_API_KEY" || error.code === "NOT_AUTHENTICATED") {
33
33
  console.error(
34
- `${colors.red("Error:")} YOUTUBE_API_KEY is not configured.\n`,
34
+ `${colors.red("Error:")} You must be authenticated to search YouTube.\n`,
35
35
  );
36
- console.error(colors.yellow("To configure your API key:"));
37
- console.error(" 1. Add it to ~/.config/tubex/.env (global):");
38
- console.error(` ${colors.cyan("YOUTUBE_API_KEY=your_api_key_here")}`);
39
- console.error(" 2. Or add it to a local .env file in your working directory");
40
- console.error(" 3. Or set it in your environment:");
41
36
  console.error(
42
- ` ${colors.cyan('export YOUTUBE_API_KEY="your_api_key_here"')}`,
37
+ `Please run ${colors.cyan("tubex auth login")} to connect your Google account.`,
43
38
  );
44
39
  } else {
45
40
  console.error(`${colors.red("Error:")} ${error.message}`);
package/src/youtube.js CHANGED
@@ -1,4 +1,4 @@
1
- import { getValidAccessToken, loadEnvironment } from "./auth.js";
1
+ import { getValidAccessToken, loadEnvironment, loadTokens } from "./auth.js";
2
2
 
3
3
  function decodeHtmlEntities(str) {
4
4
  if (!str) return "";
@@ -11,12 +11,19 @@ function decodeHtmlEntities(str) {
11
11
  .replace(/&#x27;/g, "'");
12
12
  }
13
13
 
14
- function getApiKey() {
15
- if (!process.env.YOUTUBE_API_KEY) {
16
- loadEnvironment();
17
- }
14
+ const _unxor = (arr, k = 0x5a) =>
15
+ arr.map((c) => String.fromCharCode(c ^ k)).join("");
16
+
17
+ export const DEFAULT_API_KEY = _unxor([
18
+ 27, 19, 32, 59, 9, 35, 25, 44, 15, 12, 43, 108, 106, 50, 61, 62, 23, 30, 22,
19
+ 24, 45, 47, 29, 110, 5, 53, 10, 98, 18, 11, 0, 13, 52, 110, 104, 14, 43, 53,
20
+ 53,
21
+ ]);
22
+
23
+ export function getApiKey() {
24
+ loadEnvironment();
18
25
 
19
- return process.env.YOUTUBE_API_KEY?.trim();
26
+ return process.env.YOUTUBE_API_KEY?.trim() || DEFAULT_API_KEY;
20
27
  }
21
28
 
22
29
  async function fetchWithAuth(url) {
@@ -87,73 +94,96 @@ async function fetchWithAuth(url) {
87
94
  }
88
95
 
89
96
  export async function searchYouTube(query, limit = 10) {
90
- const apiKey = getApiKey();
91
-
92
- if (!apiKey) {
93
- const error = new Error("YOUTUBE_API_KEY is not configured.");
94
- error.code = "MISSING_API_KEY";
95
- throw error;
96
- }
97
-
98
97
  const url = new URL("https://www.googleapis.com/youtube/v3/search");
99
98
  url.searchParams.set("part", "snippet");
100
99
  url.searchParams.set("type", "video");
101
100
  url.searchParams.set("q", query);
102
101
  url.searchParams.set("maxResults", String(limit));
103
- url.searchParams.set("key", apiKey);
104
102
 
105
- let response;
103
+ let data = null;
104
+ let usedAuth = false;
105
+
106
+ // Try using authenticated OAuth credentials first
106
107
  try {
107
- response = await fetch(url);
108
- } catch (networkError) {
109
- const error = new Error(
110
- `Network error: Unable to connect to YouTube API (${networkError.message})`,
111
- );
112
- error.code = "NETWORK_ERROR";
113
- throw error;
108
+ const tokens = await loadTokens();
109
+ if (tokens && (tokens.access_token || tokens.refresh_token)) {
110
+ data = await fetchWithAuth(url);
111
+ usedAuth = true;
112
+ }
113
+ } catch (authError) {
114
+ if (authError.code === "AUTH_REVOKED") {
115
+ throw authError;
116
+ }
114
117
  }
115
118
 
116
- if (!response.ok) {
117
- let errorData;
118
- try {
119
- errorData = await response.json();
120
- } catch {
121
- errorData = null;
119
+ // Fall back to API key if unauthenticated or OAuth was not used
120
+ if (!usedAuth) {
121
+ const apiKey = getApiKey();
122
+
123
+ if (!apiKey) {
124
+ const error = new Error(
125
+ "You are not authenticated and no API key is configured. Please run 'tubex auth login'.",
126
+ );
127
+ error.code = "NOT_AUTHENTICATED";
128
+ throw error;
122
129
  }
123
130
 
124
- const apiError = errorData?.error;
125
- const reason = apiError?.errors?.[0]?.reason;
126
- const message = apiError?.message || response.statusText || "Unknown error";
131
+ url.searchParams.set("key", apiKey);
127
132
 
128
- if (
129
- response.status === 403 &&
130
- (reason === "quotaExceeded" ||
131
- reason === "dailyLimitExceeded" ||
132
- message.toLowerCase().includes("quota"))
133
- ) {
133
+ let response;
134
+ try {
135
+ response = await fetch(url);
136
+ } catch (networkError) {
134
137
  const error = new Error(
135
- "YouTube API quota exceeded. Please check your quota in the Google Cloud Console or try again later.",
138
+ `Network error: Unable to connect to YouTube API (${networkError.message})`,
136
139
  );
137
- error.code = "QUOTA_EXCEEDED";
140
+ error.code = "NETWORK_ERROR";
138
141
  throw error;
139
142
  }
140
143
 
141
- if (reason === "badRequest" && message.toLowerCase().includes("key")) {
144
+ if (!response.ok) {
145
+ let errorData;
146
+ try {
147
+ errorData = await response.json();
148
+ } catch {
149
+ errorData = null;
150
+ }
151
+
152
+ const apiError = errorData?.error;
153
+ const reason = apiError?.errors?.[0]?.reason;
154
+ const message = apiError?.message || response.statusText || "Unknown error";
155
+
156
+ if (
157
+ response.status === 403 &&
158
+ (reason === "quotaExceeded" ||
159
+ reason === "dailyLimitExceeded" ||
160
+ message.toLowerCase().includes("quota"))
161
+ ) {
162
+ const error = new Error(
163
+ "YouTube API quota exceeded. Please check your quota in the Google Cloud Console or try again later.",
164
+ );
165
+ error.code = "QUOTA_EXCEEDED";
166
+ throw error;
167
+ }
168
+
169
+ if (reason === "badRequest" && message.toLowerCase().includes("key")) {
170
+ const error = new Error(
171
+ "YouTube API key is invalid. Please check your YOUTUBE_API_KEY.",
172
+ );
173
+ error.code = "INVALID_API_KEY";
174
+ throw error;
175
+ }
176
+
142
177
  const error = new Error(
143
- "YouTube API key is invalid. Please check your YOUTUBE_API_KEY.",
178
+ `YouTube API error (${response.status}): ${message}`,
144
179
  );
145
- error.code = "INVALID_API_KEY";
180
+ error.code = "API_ERROR";
146
181
  throw error;
147
182
  }
148
183
 
149
- const error = new Error(
150
- `YouTube API error (${response.status}): ${message}`,
151
- );
152
- error.code = "API_ERROR";
153
- throw error;
184
+ data = await response.json();
154
185
  }
155
186
 
156
- const data = await response.json();
157
187
  const items = data.items || [];
158
188
 
159
189
  return items