zoho-sites-dev-cli 0.0.0-stage → 1.0.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.
Files changed (53) hide show
  1. package/README.md +396 -2
  2. package/bin/zoho-sites-dev-cli.js +108 -0
  3. package/config/default.json +26 -0
  4. package/index.js +6 -0
  5. package/package.json +55 -4
  6. package/src/commands/auth.js +125 -0
  7. package/src/commands/create.js +175 -0
  8. package/src/commands/deploy.js +409 -0
  9. package/src/commands/generate-zip.js +49 -0
  10. package/src/commands/index.js +23 -0
  11. package/src/commands/init-tailwind.js +57 -0
  12. package/src/commands/init.js +449 -0
  13. package/src/commands/install.js +90 -0
  14. package/src/commands/login.js +253 -0
  15. package/src/commands/pull.js +41 -0
  16. package/src/commands/serve.js +163 -0
  17. package/src/compilers/css-compiler.js +230 -0
  18. package/src/compilers/css-ignore-loader.js +33 -0
  19. package/src/compilers/plugins/index.js +12 -0
  20. package/src/compilers/plugins/root-selector-transform-plugin.js +79 -0
  21. package/src/compilers/tailwind-compiler.js +102 -0
  22. package/src/compilers/webpack-compiler.js +512 -0
  23. package/src/compilers/webpack-config.js +103 -0
  24. package/src/config/constants.js +164 -0
  25. package/src/config/environments/audiences.js +19 -0
  26. package/src/config/environments/index.js +78 -0
  27. package/src/config/environments/internal.js +72 -0
  28. package/src/config/environments/production.js +54 -0
  29. package/src/locales/en.json +216 -0
  30. package/src/services/devServer.js +583 -0
  31. package/src/services/oauthService.js +796 -0
  32. package/src/templates/component/fields.json +6 -0
  33. package/src/templates/component/index.js +11 -0
  34. package/src/templates/component/llm.md +9 -0
  35. package/src/templates/component/meta.json +9 -0
  36. package/src/templates/component/styles.css +3 -0
  37. package/src/templates/oauth/complete.html +41 -0
  38. package/src/templates/oauth/error.html +69 -0
  39. package/src/templates/oauth/invalid-request.html +58 -0
  40. package/src/templates/oauth/loading.html +80 -0
  41. package/src/templates/oauth/not-found.html +33 -0
  42. package/src/templates/oauth/success.html +70 -0
  43. package/src/templates/oauth/timeout.html +56 -0
  44. package/src/templates/oauth/token-error.html +57 -0
  45. package/src/utils/cliName.js +35 -0
  46. package/src/utils/configUtil.js +67 -0
  47. package/src/utils/httpUtil.js +351 -0
  48. package/src/utils/i18n.js +222 -0
  49. package/src/utils/loadingUtil.js +190 -0
  50. package/src/utils/secureConfig.js +75 -0
  51. package/src/utils/secureStorage.js +230 -0
  52. package/src/utils/templateLoader.js +89 -0
  53. package/src/utils/urlUtil.js +372 -0
@@ -0,0 +1,796 @@
1
+ const express = require("express");
2
+ const cors = require("cors");
3
+ const open = require("open");
4
+ const axios = require("axios");
5
+ const crypto = require("crypto");
6
+ const SecureConfig = require("../utils/secureConfig.js");
7
+ const SecureStorage = require("../utils/secureStorage.js");
8
+ const { templateLoader } = require("../utils/templateLoader.js");
9
+ const { i18n } = require("../utils/i18n.js");
10
+ const { UrlUtil } = require("../utils/urlUtil.js");
11
+ const {
12
+ getOAuthClient,
13
+ DEFAULT_PORT,
14
+ DEFAULT_SCOPE,
15
+ ACCESS_TYPE,
16
+ PROMPT,
17
+ AUTH_TIMEOUT,
18
+ SERVER_CLEANUP_DELAY,
19
+ TOKEN_EXPIRY_BUFFER,
20
+ } = require("../config/constants.js");
21
+
22
+ // --- OAuth State Management ---
23
+
24
+ let oauthState = {
25
+ app: null,
26
+ server: null,
27
+ port: DEFAULT_PORT,
28
+ redirectUri: `http://localhost:${DEFAULT_PORT}/oauth/callback`,
29
+ secureConfig: new SecureConfig(),
30
+ secureStorage: new SecureStorage(),
31
+ environmentId: null,
32
+ clientId: null,
33
+ codeVerifier: null,
34
+ expectedState: null,
35
+ scope: DEFAULT_SCOPE,
36
+ accessType: ACCESS_TYPE,
37
+ prompt: PROMPT,
38
+ authPromise: null,
39
+ authResolve: null,
40
+ authReject: null,
41
+ oauthStatus: null,
42
+ oauthMessage: null,
43
+ currentAuthCode: null,
44
+ };
45
+
46
+ /**
47
+ * Bind OAuth client credentials for the selected login environment.
48
+ * Must be called before authorize / token exchange for that environment.
49
+ * @param {string} environmentId - e.g. 'csez' | 'localzoho' | 'usdc'
50
+ */
51
+ function setClientForEnvironment(environmentId) {
52
+ const { clientId } = getOAuthClient(environmentId);
53
+ oauthState.environmentId = environmentId;
54
+ oauthState.clientId = clientId;
55
+ }
56
+
57
+ /**
58
+ * Generate PKCE code_verifier and S256 code_challenge (RFC 7636).
59
+ * @returns {{ codeVerifier: string, codeChallenge: string }}
60
+ */
61
+ function generatePkcePair() {
62
+ const codeVerifier = crypto.randomBytes(32).toString("base64url");
63
+ const codeChallenge = crypto
64
+ .createHash("sha256")
65
+ .update(codeVerifier)
66
+ .digest("base64url");
67
+ return { codeVerifier, codeChallenge };
68
+ }
69
+
70
+ /**
71
+ * Constant-time comparison of OAuth state parameter.
72
+ * @param {string} received
73
+ * @param {string} expected
74
+ * @returns {boolean}
75
+ */
76
+ function isOAuthStateValid(received, expected) {
77
+ if (typeof received !== "string" || typeof expected !== "string") {
78
+ return false;
79
+ }
80
+ if (received.length !== expected.length) {
81
+ return false;
82
+ }
83
+ try {
84
+ return crypto.timingSafeEqual(
85
+ Buffer.from(received, "utf8"),
86
+ Buffer.from(expected, "utf8")
87
+ );
88
+ } catch (_) {
89
+ return false;
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Resolve client id for token refresh from stored auth environment.
95
+ * @param {Object} authData
96
+ * @returns {{ clientId: string }}
97
+ */
98
+ function resolveClientCredentials(authData) {
99
+ if (authData?.environment) {
100
+ return getOAuthClient(authData.environment);
101
+ }
102
+ if (authData?.client_id) {
103
+ return { clientId: authData.client_id };
104
+ }
105
+ if (oauthState.clientId) {
106
+ return { clientId: oauthState.clientId };
107
+ }
108
+ throw new Error(
109
+ 'Cannot resolve OAuth client credentials: no environment on stored auth data.'
110
+ );
111
+ }
112
+
113
+ // --- Utility Functions ---
114
+
115
+ /**
116
+ * Get authorization header with valid token (refreshes if needed)
117
+ */
118
+ async function getAuthorizationHeader() {
119
+ try {
120
+ const authData = await getValidAuthData();
121
+ if (authData && authData.access_token) {
122
+ return {
123
+ Authorization: `Zoho-oauthtoken ${authData.access_token}`,
124
+ };
125
+ }
126
+ return null;
127
+ } catch (error) {
128
+ i18n.warning("commands.login.couldNotRetrieveAuthenticationToken", {
129
+ error: error.message,
130
+ });
131
+ return null;
132
+ }
133
+ }
134
+
135
+ /**
136
+ * Check if user is authenticated with valid token
137
+ */
138
+ async function isAuthenticated() {
139
+ const authData = await getValidAuthData();
140
+ return !!(authData && authData.access_token);
141
+ }
142
+
143
+ /**
144
+ * Get valid authentication data, refreshing token if expired
145
+ */
146
+ async function getValidAuthData() {
147
+ try {
148
+ const authData = await oauthState.secureStorage.getAuthData();
149
+ if (!authData || !authData.access_token) {
150
+ return null;
151
+ }
152
+
153
+ // Check if token is expired
154
+ if (authData.expires_at) {
155
+ const expiresAt = new Date(authData.expires_at);
156
+ const now = new Date();
157
+ const timeUntilExpiry = expiresAt - now;
158
+
159
+ if (timeUntilExpiry < TOKEN_EXPIRY_BUFFER) {
160
+ const refreshedData = await refreshAccessToken(authData);
161
+
162
+ if (refreshedData) {
163
+ return refreshedData;
164
+ } else {
165
+ i18n.warning("commands.login.failedToRefreshTokenUsingExistingToken");
166
+ return authData;
167
+ }
168
+ }
169
+ }
170
+
171
+ return authData;
172
+ } catch (error) {
173
+ i18n.error("commands.login.errorGettingValidAuthData", {
174
+ error: error.message,
175
+ });
176
+ return null;
177
+ }
178
+ }
179
+
180
+ /**
181
+ * Refresh access token using refresh token
182
+ */
183
+ async function refreshAccessToken(authData) {
184
+ if (!authData.refresh_token) {
185
+ i18n.warning("commands.login.noRefreshTokenAvailable");
186
+ return null;
187
+ }
188
+
189
+ try {
190
+ // Resolve token URL: use stored auth domain (works for both DEV and static envs)
191
+ const tokenUrl = await UrlUtil.getAuthUrl("OAUTH.TOKEN");
192
+ if (!tokenUrl) {
193
+ throw new Error("Could not build token URL for current environment");
194
+ }
195
+
196
+ const { clientId } = resolveClientCredentials(authData);
197
+
198
+ // Configure axios for local development
199
+ const axiosConfig = {
200
+ method: "POST",
201
+ url: tokenUrl,
202
+ headers: {
203
+ "Content-Type": "application/x-www-form-urlencoded",
204
+ },
205
+ data: new URLSearchParams({
206
+ grant_type: "refresh_token",
207
+ refresh_token: authData.refresh_token,
208
+ client_id: clientId,
209
+ }).toString(),
210
+ timeout: 30000, // 30 seconds
211
+ };
212
+
213
+ // Make refresh token request
214
+ const response = await axios(axiosConfig);
215
+
216
+ if (response.data.access_token) {
217
+ // Calculate new expiry time
218
+ const expiresIn = response.data.expires_in || 3600; // Default 1 hour
219
+ const newExpiresAt = new Date(
220
+ Date.now() + expiresIn * 1000
221
+ ).toISOString();
222
+
223
+ // Update stored auth data
224
+ const updatedAuthData = {
225
+ ...authData,
226
+ access_token: response.data.access_token,
227
+ expires_at: newExpiresAt,
228
+ };
229
+
230
+ // If we got a new refresh token, update that too
231
+ if (response.data.refresh_token) {
232
+ updatedAuthData.refresh_token = response.data.refresh_token;
233
+ }
234
+
235
+ // Store updated data
236
+ await oauthState.secureStorage.storeAuthData(updatedAuthData);
237
+
238
+ i18n.success("commands.login.accessTokenRefreshedSuccessfully");
239
+ return updatedAuthData;
240
+ } else {
241
+ throw new Error("No access token in refresh response");
242
+ }
243
+ } catch (error) {
244
+ // Don't log sensitive error details in production
245
+ const errorMessage =
246
+ error.response?.data?.error || error.message || "Unknown error";
247
+ i18n.error("commands.login.failedToRefreshAccessToken", {
248
+ error: errorMessage,
249
+ });
250
+
251
+ // If refresh fails with 401, the refresh token is invalid
252
+ if (error.response?.status === 401) {
253
+ i18n.error("commands.login.refreshTokenInvalid");
254
+ // Clear invalid token data
255
+ await oauthState.secureStorage.clearAuthData();
256
+ }
257
+
258
+ return null;
259
+ }
260
+ }
261
+
262
+ /**
263
+ * Build OAuth authorize URL with PKCE (S256) and CSRF state.
264
+ * @param {string} authDomain - The full auth base URL (e.g. https://accounts.zoho.com)
265
+ */
266
+ async function buildAuthUrl(authDomain) {
267
+ if (!oauthState.clientId) {
268
+ throw new Error(
269
+ 'OAuth client is not set. Call setClientForEnvironment(environmentId) before login.'
270
+ );
271
+ }
272
+
273
+ const { codeVerifier, codeChallenge } = generatePkcePair();
274
+ const state = crypto.randomBytes(16).toString("hex");
275
+ oauthState.codeVerifier = codeVerifier;
276
+ oauthState.expectedState = state;
277
+
278
+ const params = {
279
+ response_type: "code",
280
+ client_id: oauthState.clientId,
281
+ scope: oauthState.scope,
282
+ redirect_uri: oauthState.redirectUri,
283
+ access_type: oauthState.accessType,
284
+ prompt: oauthState.prompt,
285
+ state,
286
+ code_challenge: codeChallenge,
287
+ code_challenge_method: "S256",
288
+ };
289
+
290
+ const endpoint = UrlUtil.getApiEndpoint("OAUTH.AUTHORIZE");
291
+ const queryString = new URLSearchParams(params).toString();
292
+ return `${authDomain}/${endpoint}?${queryString}`;
293
+ }
294
+
295
+ /**
296
+ * Exchange authorization code for tokens.
297
+ * @param {string} authCode
298
+ * @param {string} authDomain - The full auth base URL (e.g. https://accounts.zoho.com)
299
+ */
300
+ async function exchangeCodeForTokens(authCode, authDomain) {
301
+ try {
302
+ if (!oauthState.clientId || !oauthState.codeVerifier) {
303
+ throw new Error(
304
+ 'OAuth client or PKCE verifier is not set. Call setClientForEnvironment(environmentId) before login.'
305
+ );
306
+ }
307
+
308
+ const tokenEndpoint = UrlUtil.getApiEndpoint("OAUTH.TOKEN");
309
+ const tokenUrl = `${authDomain}/${tokenEndpoint}`;
310
+
311
+ const requestData = new URLSearchParams({
312
+ client_id: oauthState.clientId,
313
+ grant_type: "authorization_code",
314
+ code: authCode,
315
+ redirect_uri: oauthState.redirectUri,
316
+ code_verifier: oauthState.codeVerifier,
317
+ });
318
+
319
+ const response = await axios.post(tokenUrl, requestData, {
320
+ headers: {
321
+ Accept: "application/json",
322
+ "Content-Type": "application/x-www-form-urlencoded",
323
+ },
324
+ });
325
+
326
+ if (response.data.access_token) {
327
+ return response.data;
328
+ } else {
329
+ throw new Error("No access token received");
330
+ }
331
+ } catch (error) {
332
+ if (error.response) {
333
+ if (error.response.status === 400) {
334
+ const errorData = error.response.data;
335
+
336
+ if (errorData.error === "invalid_client") {
337
+ i18n.error("commands.login.invalidClient");
338
+ } else if (errorData.error === "invalid_grant") {
339
+ i18n.error("commands.login.invalidGrant");
340
+ } else if (errorData.error === "invalid_request") {
341
+ i18n.error("commands.login.invalidRequest");
342
+ } else if (errorData.error === "unauthorized_client") {
343
+ i18n.error("commands.login.clientNotAuthorized");
344
+ }
345
+ }
346
+ } else if (error.code === "ENOTFOUND" || error.code === "ECONNREFUSED") {
347
+ i18n.error("commands.login.networkConnectionError");
348
+ }
349
+
350
+ throw error;
351
+ }
352
+ }
353
+
354
+ /**
355
+ * Get user profile information.
356
+ * @param {string} accessToken
357
+ * @param {string} authDomain - The full auth base URL (e.g. https://accounts.zoho.com)
358
+ */
359
+ async function getUserProfile(accessToken, authDomain) {
360
+ const profileEndpoint = UrlUtil.getApiEndpoint("OAUTH.PROFILE");
361
+ const profileUrl = `${authDomain}/${profileEndpoint}`;
362
+
363
+ const response = await axios.get(profileUrl, {
364
+ headers: {
365
+ Authorization: `Zoho-oauthtoken ${accessToken}`,
366
+ },
367
+ });
368
+
369
+ if (response.data) {
370
+ return response.data;
371
+ }
372
+
373
+ throw new Error("No user profile data received");
374
+ }
375
+
376
+ /**
377
+ * Set OAuth status for polling
378
+ */
379
+ function setOAuthStatus(status, message) {
380
+ oauthState.oauthStatus = status;
381
+ oauthState.oauthMessage = message;
382
+ }
383
+
384
+ // --- Route Handlers ---
385
+
386
+ /**
387
+ * OAuth callback handler
388
+ */
389
+ async function handleOAuthCallback(req, res) {
390
+ const { code, error, error_description, state } = req.query;
391
+
392
+ if (error) {
393
+ i18n.error("commands.login.oauthError", { error: error });
394
+ if (error_description) {
395
+ i18n.error("commands.login.oauthErrorDescription", {
396
+ error_description: error_description,
397
+ });
398
+ }
399
+
400
+ // Send error response using template
401
+ const errorMessage = error_description || error;
402
+ const errorHtml = templateLoader.renderTemplate("oauth/error.html", {
403
+ ERROR_MESSAGE: errorMessage,
404
+ });
405
+ res.send(errorHtml);
406
+
407
+ if (oauthState.authReject) {
408
+ oauthState.authReject(
409
+ new Error(`OAuth Error: ${error} - ${error_description}`)
410
+ );
411
+ }
412
+ return;
413
+ }
414
+
415
+ if (code) {
416
+ if (!isOAuthStateValid(state, oauthState.expectedState)) {
417
+ const stateErrorMessage = "Invalid or missing OAuth state parameter";
418
+ i18n.error("commands.login.oauthError", { error: stateErrorMessage });
419
+ const errorHtml = templateLoader.renderTemplate("oauth/error.html", {
420
+ ERROR_MESSAGE: stateErrorMessage,
421
+ });
422
+ res.send(errorHtml);
423
+ if (oauthState.authReject) {
424
+ oauthState.authReject(new Error(`OAuth Error: ${stateErrorMessage}`));
425
+ }
426
+ return;
427
+ }
428
+
429
+ // Show loading page using template
430
+ const loadingHtml = templateLoader.renderTemplate("oauth/loading.html");
431
+ res.send(loadingHtml);
432
+
433
+ // Store the auth code and trigger token validation
434
+ oauthState.currentAuthCode = code;
435
+ if (oauthState.authResolve) {
436
+ oauthState.authResolve(code);
437
+ }
438
+ } else {
439
+ const invalidRequestHtml = templateLoader.renderTemplate(
440
+ "oauth/invalid-request.html"
441
+ );
442
+ res.send(invalidRequestHtml);
443
+
444
+ if (oauthState.authReject) {
445
+ oauthState.authReject(new Error("No authorization code received"));
446
+ }
447
+ }
448
+ }
449
+
450
+ /**
451
+ * OAuth status handler
452
+ */
453
+ function handleOAuthStatus(req, res) {
454
+ res.json({
455
+ status: oauthState.oauthStatus || "processing",
456
+ message: oauthState.oauthMessage || "Processing authentication...",
457
+ });
458
+ }
459
+
460
+ /**
461
+ * OAuth success page handler
462
+ */
463
+ function handleOAuthSuccess(req, res) {
464
+ const successHtml = templateLoader.renderTemplate("oauth/success.html");
465
+ res.send(successHtml);
466
+ }
467
+
468
+ /**
469
+ * OAuth error page handler
470
+ */
471
+ function handleOAuthError(req, res) {
472
+ const message =
473
+ req.query.message || "An error occurred during authentication";
474
+ const errorHtml = templateLoader.renderTemplate("oauth/token-error.html", {
475
+ ERROR_MESSAGE: decodeURIComponent(message),
476
+ });
477
+ res.send(errorHtml);
478
+ }
479
+
480
+ /**
481
+ * OAuth timeout page handler
482
+ */
483
+ function handleOAuthTimeout(req, res) {
484
+ const timeoutHtml = templateLoader.renderTemplate("oauth/timeout.html");
485
+ res.send(timeoutHtml);
486
+ }
487
+
488
+ /**
489
+ * OAuth complete page handler
490
+ */
491
+ function handleOAuthComplete(req, res) {
492
+ const completeHtml = templateLoader.renderTemplate("oauth/complete.html");
493
+ res.send(completeHtml);
494
+ }
495
+
496
+ /**
497
+ * Health check handler
498
+ */
499
+ function handleHealthCheck(req, res) {
500
+ res.json({ status: "OK", service: "ZS CLI OAuth Server" });
501
+ }
502
+
503
+ /**
504
+ * 404 handler
505
+ */
506
+ function handleNotFound(req, res) {
507
+ const notFoundHtml = templateLoader.renderTemplate("oauth/not-found.html");
508
+ res.status(404).send(notFoundHtml);
509
+ }
510
+
511
+ // --- Route Configuration ---
512
+
513
+ /**
514
+ * Route map - all URLs listed explicitly
515
+ */
516
+ const oauthRoutes = {
517
+ "GET /oauth/callback": handleOAuthCallback,
518
+ "GET /oauth/status": handleOAuthStatus,
519
+ "GET /oauth/success": handleOAuthSuccess,
520
+ "GET /oauth/error": handleOAuthError,
521
+ "GET /oauth/timeout": handleOAuthTimeout,
522
+ "GET /oauth/complete": handleOAuthComplete,
523
+ "GET /health": handleHealthCheck,
524
+ "GET *": handleNotFound,
525
+ };
526
+
527
+ // --- App Creation ---
528
+
529
+ /**
530
+ * Create Express server with all routes
531
+ */
532
+ function createOAuthApp() {
533
+ const app = express();
534
+
535
+ // Security middleware
536
+ app.use((req, res, next) => {
537
+ res.setHeader("X-Content-Type-Options", "nosniff");
538
+ res.setHeader("X-Frame-Options", "DENY");
539
+ res.setHeader("X-XSS-Protection", "1; mode=block");
540
+ next();
541
+ });
542
+
543
+ // Middleware
544
+ app.use(cors());
545
+ app.use(express.json());
546
+ app.use(express.urlencoded({ extended: true }));
547
+
548
+ // Register all routes from the route map
549
+ for (const [route, handler] of Object.entries(oauthRoutes)) {
550
+ const [method, path] = route.split(" ");
551
+ if (path === "*") {
552
+ app.use(handler); // 404 handler
553
+ } else {
554
+ app[method.toLowerCase()](path, handler);
555
+ }
556
+ }
557
+
558
+ return app;
559
+ }
560
+
561
+ // --- Server Management ---
562
+
563
+ /**
564
+ * Start the OAuth server
565
+ */
566
+ async function startOAuthServer() {
567
+ return new Promise((resolve, reject) => {
568
+ try {
569
+ oauthState.app = createOAuthApp();
570
+
571
+ oauthState.server = oauthState.app.listen(
572
+ oauthState.port,
573
+ "localhost",
574
+ () => {
575
+ resolve();
576
+ }
577
+ );
578
+
579
+ oauthState.server.on("error", (err) => {
580
+ if (err.code === "EADDRINUSE") {
581
+ i18n.warning("commands.login.portBusy", {
582
+ port: oauthState.port,
583
+ newPort: oauthState.port + 1,
584
+ });
585
+ oauthState.port++;
586
+ oauthState.redirectUri = `http://localhost:${oauthState.port}/oauth/callback`;
587
+ startOAuthServer().then(resolve).catch(reject);
588
+ } else {
589
+ reject(err);
590
+ }
591
+ });
592
+ } catch (error) {
593
+ reject(error);
594
+ }
595
+ });
596
+ }
597
+
598
+ /**
599
+ * Stop the OAuth server
600
+ */
601
+ function stopOAuthServer() {
602
+ return new Promise((resolve) => {
603
+ if (oauthState.server) {
604
+ oauthState.server.close(() => {
605
+ oauthState.server = null;
606
+ resolve();
607
+ });
608
+ } else {
609
+ resolve();
610
+ }
611
+ });
612
+ }
613
+
614
+ // --- OAuth Flow Functions ---
615
+
616
+ /**
617
+ * Initiate OAuth flow.
618
+ * @param {string} authDomain - The full auth base URL (e.g. https://accounts.zoho.com)
619
+ */
620
+ async function authenticate(authDomain) {
621
+ try {
622
+ // Initialize OAuth status
623
+ oauthState.oauthStatus = "processing";
624
+ oauthState.oauthMessage = "Starting authentication...";
625
+
626
+ // Start the OAuth server
627
+ await startOAuthServer();
628
+
629
+ // Build the OAuth URL
630
+ const authUrl = await buildAuthUrl(authDomain);
631
+
632
+ i18n.info("commands.login.openingBrowserForAuthentication");
633
+
634
+ // Create a promise that will be resolved when we get the callback
635
+ oauthState.authPromise = new Promise((resolve, reject) => {
636
+ oauthState.authResolve = resolve;
637
+ oauthState.authReject = reject;
638
+ });
639
+
640
+ // Open the browser
641
+ await open(authUrl);
642
+
643
+ i18n.info("commands.login.waitingForAuthenticationInBrowser");
644
+
645
+ // Wait for the callback with a timeout
646
+ const timeoutPromise = new Promise((_, reject) => {
647
+ setTimeout(() => {
648
+ reject(new Error("Authentication timeout (5 minutes)"));
649
+ }, AUTH_TIMEOUT);
650
+ });
651
+
652
+ const authCode = await Promise.race([
653
+ oauthState.authPromise,
654
+ timeoutPromise,
655
+ ]);
656
+
657
+ return authCode;
658
+ } catch (error) {
659
+ setOAuthStatus("error", error.message);
660
+ throw error;
661
+ }
662
+ }
663
+
664
+ /**
665
+ * Complete OAuth flow with token validation.
666
+ * @param {string} authDomain - The full auth base URL (e.g. https://accounts.zoho.com)
667
+ */
668
+ async function completeAuthentication(authDomain) {
669
+ try {
670
+ // Get the authorization code
671
+ const authCode = await authenticate(authDomain);
672
+
673
+ // Set status to processing token exchange
674
+ setOAuthStatus("processing", "Exchanging authorization code for tokens...");
675
+
676
+ // Exchange authorization code for tokens
677
+ const tokenData = await exchangeCodeForTokens(authCode, authDomain);
678
+
679
+ // Set status to processing user profile
680
+ setOAuthStatus("processing", "Fetching user profile...");
681
+
682
+ // Get user profile
683
+ const userProfile = await getUserProfile(tokenData.access_token, authDomain);
684
+
685
+ // Set success status
686
+ setOAuthStatus("success", "Authentication completed successfully!");
687
+
688
+ // Return both token data and user profile
689
+ return { tokenData, userProfile };
690
+ } catch (error) {
691
+ setOAuthStatus("error", error.message);
692
+ throw error;
693
+ } finally {
694
+ // Clean up auth promise variables
695
+ oauthState.authPromise = null;
696
+ oauthState.authResolve = null;
697
+ oauthState.authReject = null;
698
+ oauthState.codeVerifier = null;
699
+ oauthState.expectedState = null;
700
+
701
+ // Stop the server after a delay so the browser can show the final status
702
+ setTimeout(async () => {
703
+ await stopOAuthServer();
704
+ oauthState.oauthStatus = null;
705
+ oauthState.oauthMessage = null;
706
+ }, SERVER_CLEANUP_DELAY);
707
+ }
708
+ }
709
+
710
+ // --- Legacy Class Interface (for backward compatibility) ---
711
+
712
+ /**
713
+ * OAuth Service Class (Legacy Interface)
714
+ * @deprecated Use individual functions instead
715
+ */
716
+ class OAuthService {
717
+ constructor() {
718
+ // Preload templates for better performance
719
+ templateLoader.preloadTemplates();
720
+ }
721
+
722
+ get clientId() {
723
+ return oauthState.clientId;
724
+ }
725
+
726
+ get scope() {
727
+ return oauthState.scope;
728
+ }
729
+
730
+ setClientForEnvironment(environmentId) {
731
+ return setClientForEnvironment(environmentId);
732
+ }
733
+
734
+ getAuthorizationHeader() {
735
+ return getAuthorizationHeader();
736
+ }
737
+
738
+ isAuthenticated() {
739
+ return isAuthenticated();
740
+ }
741
+
742
+ getValidAuthData() {
743
+ return getValidAuthData();
744
+ }
745
+
746
+ refreshAccessToken(authData) {
747
+ return refreshAccessToken(authData);
748
+ }
749
+
750
+ buildAuthUrl(environmentUrl) {
751
+ return buildAuthUrl(environmentUrl);
752
+ }
753
+
754
+ authenticate(environmentUrl) {
755
+ return authenticate(environmentUrl);
756
+ }
757
+
758
+ completeAuthentication(environmentUrl) {
759
+ return completeAuthentication(environmentUrl);
760
+ }
761
+
762
+ exchangeCodeForTokens(authCode, environmentUrl) {
763
+ return exchangeCodeForTokens(authCode, environmentUrl);
764
+ }
765
+
766
+ getUserProfile(accessToken, environmentUrl) {
767
+ return getUserProfile(accessToken, environmentUrl);
768
+ }
769
+
770
+ setOAuthStatus(status, message) {
771
+ return setOAuthStatus(status, message);
772
+ }
773
+
774
+ startServer() {
775
+ return startOAuthServer();
776
+ }
777
+
778
+ stopServer() {
779
+ return stopOAuthServer();
780
+ }
781
+
782
+ initializeServer() {
783
+ oauthState.app = createOAuthApp();
784
+ }
785
+ }
786
+
787
+ module.exports = OAuthService;
788
+ module.exports.setClientForEnvironment = setClientForEnvironment;
789
+ module.exports.getOAuthClient = getOAuthClient;
790
+ module.exports.generatePkcePair = generatePkcePair;
791
+ module.exports.isOAuthStateValid = isOAuthStateValid;
792
+ module.exports.buildAuthUrl = buildAuthUrl;
793
+ module.exports.exchangeCodeForTokens = exchangeCodeForTokens;
794
+ module.exports.refreshAccessToken = refreshAccessToken;
795
+ module.exports.handleOAuthCallback = handleOAuthCallback;
796
+ module.exports.oauthState = oauthState;