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