zoho-sites-dev-cli 1.0.0 → 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.
@@ -23,7 +23,7 @@ const PRODUCTION_ENVIRONMENTS = [
23
23
  authDomain: 'https://accounts.zoho.com',
24
24
  siteDomain: 'https://sites.zoho.com',
25
25
  siteBuilderDomainTemplate: 'https://sitebuilder-{siteId}.zoho.com',
26
- promptMode: 'none',
26
+ promptMode: 'none'
27
27
  },
28
28
  {
29
29
  id: 'indc',
@@ -31,9 +31,24 @@ const PRODUCTION_ENVIRONMENTS = [
31
31
  authDomain: 'https://accounts.zoho.in',
32
32
  siteDomain: 'https://sites.zoho.in', // PLACEHOLDER: confirm real IN DC site domain
33
33
  siteBuilderDomainTemplate: 'https://sitebuilder-{siteId}.zoho.in', // PLACEHOLDER
34
- promptMode: 'none',
34
+ promptMode: 'none'
35
35
  },
36
- // Add additional DCs (EU, AU, JP, CA, SA, …) here following the same shape.
36
+ {
37
+ id: 'eudc',
38
+ label: 'EU DC',
39
+ authDomain: 'https://accounts.zoho.eu',
40
+ siteDomain: 'https://sites.zoho.eu', // PLACEHOLDER: confirm real EU DC site domain
41
+ siteBuilderDomainTemplate: 'https://sitebuilder-{siteId}.zoho.eu', // PLACEHOLDER
42
+ promptMode: 'none'
43
+ },
44
+ {
45
+ id: 'audc',
46
+ label: 'AU DC',
47
+ authDomain: 'https://accounts.zoho.com.au',
48
+ siteDomain: 'https://sites.zoho.com.au', // PLACEHOLDER: confirm real AU DC site domain
49
+ siteBuilderDomainTemplate: 'https://sitebuilder-{siteId}.zoho.com.au', // PLACEHOLDER
50
+ promptMode: 'none'
51
+ }
37
52
  ];
38
53
 
39
54
  module.exports = { PRODUCTION_ENVIRONMENTS };
@@ -1,15 +1,15 @@
1
1
  {
2
2
  "cli": {
3
- "description": "ZS CLI tool for component management and authentication",
3
+ "description": "Zoho Sites CLI tool for component management and authentication",
4
4
  "invalidCommand": "Invalid command: {command} \nSee --help for a list of available commands."
5
5
  },
6
6
  "commands": {
7
7
  "login": {
8
- "description": "Login to ZS platform",
8
+ "description": "Login to Zoho Sites platform",
9
9
  "alreadyLoggedIn": "Already logged in as {name} ({email})",
10
10
  "environment": "Environment: {environment}",
11
11
  "logoutSuccess": "Logged out successfully",
12
- "welcome": "Welcome to Zoho Sites Login\n",
12
+ "welcome": "Welcome to Zoho Sites login\n",
13
13
  "selectedEnvironment": "\nSelected environment: {environment}",
14
14
  "startingAuth": "\nšŸ” Starting OAuth authentication...",
15
15
  "loginSuccess": "\nšŸŽ‰ Login successful!",
@@ -32,7 +32,7 @@
32
32
  "requestSuccessful": "āœ… Request successful (status: {status})",
33
33
  "requestFailed": "āŒ Request failed: {error}",
34
34
  "fetchingComponents": "šŸ“¦ Fetching components...",
35
- "authenticationFailed": "šŸ” Authentication required. Please run `zs login` to authenticate.",
35
+ "authenticationFailed": "šŸ” Authentication required. Please run `{cli} login` to authenticate.",
36
36
  "accessForbidden": "🚫 Access forbidden. You may not have permission to access this resource.",
37
37
  "resourceNotFound": "ā“ The requested resource was not found.",
38
38
  "rateLimitExceeded": "āš ļø Too many requests. Please wait and try again.",
@@ -61,7 +61,7 @@
61
61
  },
62
62
  "auth": {
63
63
  "notLoggedIn": "Not logged in",
64
- "loginToAuthenticate": "Use `zs login` to authenticate",
64
+ "loginToAuthenticate": "Use `{cli} login` to authenticate",
65
65
  "logoutSuccess": "Logged out successfully. Goodbye, {name}!",
66
66
  "logoutFailed": "Failed to logout: {error}",
67
67
  "authenticationDataNotFound": "Authentication data not found",
@@ -71,11 +71,11 @@
71
71
  "environment": "Environment: {environment}",
72
72
  "organization": "Organization: {organization}",
73
73
  "apiDomain": "API Domain: {apiDomain}",
74
- "tokenType": "Token Type: {tokenType}",
74
+ "userId": "User ID: {userId}",
75
75
  "permissions": "Permissions: {permissions}",
76
- "tokenExpiresIn": "Token expires in: {hours}h {minutes}m",
76
+ "lastLogin": "Last login: {lastLogin}",
77
77
  "tokenExpired": "Token has expired",
78
- "loginToReauthenticate": "Use `zs login` to reauthenticate",
78
+ "loginToReauthenticate": "Use `{cli} login` to reauthenticate",
79
79
  "failedToGetUserInfo": "Failed to get user info: {error}",
80
80
  "authenticationStatus": "Authentication Status:",
81
81
  "authenticated": "āœ“ Authenticated",
@@ -85,9 +85,9 @@
85
85
  "failedToCheckStatus": "Failed to check authentication status: {error}"
86
86
  },
87
87
  "init": {
88
- "description": "Initialize a new ZS project",
89
- "initCommand": "šŸš€ ZS Init Command",
90
- "initializingNewProject": "Initializing new ZS project...",
88
+ "description": "Initialize a new Zoho sites project",
89
+ "initCommand": "šŸš€ Zoho sites init command",
90
+ "initializingNewProject": "Initializing new Zoho sites project...",
91
91
  "creatingFolder": "Creating project folder: {app}",
92
92
  "structureCreated": "āœ“ Project structure created successfully!",
93
93
  "fetchingAccount": "šŸ” Fetching account details...",
@@ -105,36 +105,36 @@
105
105
  "selectAppMessage": "Select an app for your project:",
106
106
  "choiceLabel": "{name} (namespace: {namespace})",
107
107
  "projectInitializationCompleted": "šŸŽ‰ Project initialization completed successfully!",
108
- "alreadyInProject": "Cannot run 'zs init' inside an existing ZS project directory ('.zs' found).",
108
+ "alreadyInProject": "Cannot run '{cli} init' inside an existing Zoho sites project directory ('.zs' found).",
109
109
  "errorDuringInitialization": "āŒ Error during initialization: {error}"
110
110
  },
111
111
  "initTailwind": {
112
- "description": "Add Tailwind CSS config to the current ZS project",
113
- "notInProject": "Not in a ZS project directory. Run 'zs init' first.",
112
+ "description": "Add Tailwind CSS config to the current Zoho sites project",
113
+ "notInProject": "Not in a Zoho sites project directory. Run '{cli} init' first.",
114
114
  "alreadyExists": "tailwind.config.js already exists. Skipping.",
115
115
  "created": "āœ“ tailwind.config.js created. Tailwind will be built at compile time.",
116
116
  "error": "Failed to init Tailwind: {error}"
117
117
  },
118
118
  "pull": {
119
119
  "description": "Pull components from remote repository",
120
- "title": "ZS Pull Command",
120
+ "title": "Zoho sites pull command",
121
121
  "notAuthenticated": "āŒ Authentication required",
122
- "pleaseLogin": "Please run 'zs login' to authenticate first",
122
+ "pleaseLogin": "Please run '{cli} login' to authenticate first",
123
123
  "fetchingComponents": "šŸ“” Fetching components list...",
124
124
  "fetchSuccess": "āœ… Components fetched successfully!",
125
125
  "fetchError": "āŒ Failed to fetch components: {error}",
126
- "authenticationRequired": "šŸ” Authentication expired - please run 'zs login' to reauthenticate",
126
+ "authenticationRequired": "šŸ” Authentication expired - please run '{cli} login' to reauthenticate",
127
127
  "permissionDenied": "🚫 Permission denied - you may not have access to components",
128
128
  "connectionError": "🌐 Connection failed - please check your network and server configuration"
129
129
  },
130
130
  "create": {
131
131
  "description": "Create a new component with the specified name",
132
- "title": "šŸš€ ZS Create Command",
132
+ "title": "šŸš€ Zoho sites create command",
133
133
  "creating": "šŸ“¦ Creating component: {componentName}",
134
- "componentNameRequired": "āŒ Component name is required. Usage: zs create <component-name>",
134
+ "componentNameRequired": "āŒ Component name is required. Usage: {cli} create <component-name>",
135
135
  "invalidComponentName": "āŒ Invalid component name: {componentName}. Component name should start with a letter and contain only letters, numbers, hyphens, and underscores (3-50 characters).",
136
- "noConfigFound": "āŒ No ZS project configuration found in current directory.",
137
- "configHint": "šŸ’” Please navigate to a ZS project directory or initialize a new project with 'zs init'.\n Expected config files: .zs, .zs.json, zs.config.js, zs.config.json, or package.json with ZS dependencies.",
136
+ "noConfigFound": "āŒ No Zoho sites project configuration found in current directory.",
137
+ "configHint": "šŸ’” Please navigate to a Zoho sites project directory or initialize a new project with '{cli} init'.\n Expected config files: .zs, .zs.json, zs.config.js, zs.config.json, or package.json with Zoho sites dependencies.",
138
138
  "directoryExists": "āŒ Component '{componentName}' already exists. Please choose a different name or remove the existing component.",
139
139
  "directoryCreated": "āœ… Created component directory: {componentName}",
140
140
  "fileCreated": "āœ… Created file: {filename}",
@@ -146,8 +146,8 @@
146
146
  },
147
147
  "install": {
148
148
  "description": "Create package.json if missing and run npm install for given packages",
149
- "title": "šŸ“¦ ZS Install",
150
- "packageRequired": "āŒ At least one package is required. Usage: zs install <pkg> [pkg2 pkg3...]",
149
+ "title": "šŸ“¦ Zoho sites install command",
150
+ "packageRequired": "āŒ At least one package is required. Usage: {cli} install <pkg> [pkg2 pkg3...]",
151
151
  "packageJsonCreated": "āœ… Created package.json",
152
152
  "packageJsonExists": "ā„¹ļø package.json already exists",
153
153
  "runningNpmInstall": "šŸ“„ Installing packages: {packages}",
@@ -156,7 +156,7 @@
156
156
  },
157
157
  "serve": {
158
158
  "description": "Start development server for components",
159
- "notInProject": "Not in a ZS project directory. Run 'zs init' first.",
159
+ "notInProject": "Not in a Zoho sites project directory. Run '{cli} init' first.",
160
160
  "error": "Development server error: {error}",
161
161
  "startingServer": "Starting development server for: {siteName}",
162
162
  "serverRunning": "Development server running on https://localhost:{port}",
@@ -188,7 +188,7 @@
188
188
  "description": "Deploy components to server",
189
189
  "starting": "šŸš€ Starting deployment...",
190
190
  "notAuthenticated": "āŒ Not authenticated",
191
- "pleaseLogin": "Please run 'zs login' first",
191
+ "pleaseLogin": "Please run '{cli} login' first",
192
192
  "usingEnvironment": "šŸŒ Using environment: {environment}",
193
193
  "deployingToEnvironment": "šŸš€ Deploying to environment: {environment} (siteId: {siteId})",
194
194
  "tempDirCreated": "āœ… Created temporary directory",
@@ -206,7 +206,7 @@
206
206
  "cleanupComplete": "šŸ—‘ļø Cleanup complete",
207
207
  "cleanupFailed": "āš ļø Failed to clean up: {error}",
208
208
  "error": "āŒ Deployment error: {error}",
209
- "authenticationRequired": "šŸ” Authentication required. Please run 'zs login'",
209
+ "authenticationRequired": "šŸ” Authentication required. Please run '{cli} login'",
210
210
  "permissionDenied": "🚫 Permission denied. Check your access rights."
211
211
  }
212
212
  },
@@ -8,6 +8,59 @@ const WebpackCompiler = require("../compilers/webpack-compiler.js");
8
8
 
9
9
  const { getNamespace } = require("../utils/configUtil.js");
10
10
 
11
+ /**
12
+ * Check whether targetPath is equal to or nested inside rootPath using path components.
13
+ */
14
+ function isPathWithinRoot(rootPath, targetPath) {
15
+ const relative = path.relative(rootPath, targetPath);
16
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
17
+ }
18
+
19
+ /**
20
+ * Resolve a relative request path within rootDir and verify containment both
21
+ * lexically and after resolving filesystem symlinks.
22
+ * @returns {{ status: "ok", filePath: string } | { status: "forbidden" } | { status: "missing" }}
23
+ */
24
+ function resolveContainedPath(rootDir, relPath) {
25
+ if (!rootDir) {
26
+ return { status: "missing" };
27
+ }
28
+
29
+ const resolvedRoot = path.resolve(rootDir);
30
+ const resolvedTarget = path.resolve(resolvedRoot, relPath || "");
31
+ if (!isPathWithinRoot(resolvedRoot, resolvedTarget)) {
32
+ return { status: "forbidden" };
33
+ }
34
+
35
+ if (!fs.existsSync(resolvedRoot)) {
36
+ return { status: "missing" };
37
+ }
38
+
39
+ let realRoot;
40
+ try {
41
+ realRoot = fs.realpathSync(resolvedRoot);
42
+ } catch (_) {
43
+ return { status: "missing" };
44
+ }
45
+
46
+ if (!fs.existsSync(resolvedTarget)) {
47
+ return { status: "missing" };
48
+ }
49
+
50
+ let realTarget;
51
+ try {
52
+ realTarget = fs.realpathSync(resolvedTarget);
53
+ } catch (_) {
54
+ return { status: "missing" };
55
+ }
56
+
57
+ if (!isPathWithinRoot(realRoot, realTarget)) {
58
+ return { status: "forbidden" };
59
+ }
60
+
61
+ return { status: "ok", filePath: realTarget };
62
+ }
63
+
11
64
  /**
12
65
  * Create filesystem-backed dev server serving component assets:
13
66
  * /:namespace/__widgets/dist/index.js
@@ -79,7 +132,24 @@ function createWebpackDevServerConfig(portOverride) {
79
132
  // HTTP server that serves assets from the current build's real dist directory
80
133
  const server = http.createServer((req, res) => {
81
134
  try {
82
- const urlPath = decodeURIComponent(req.url || "/");
135
+ const rawUrlPath = (req.url || "/").split("?")[0];
136
+ let urlPath;
137
+ try {
138
+ urlPath = decodeURIComponent(rawUrlPath);
139
+ } catch (_) {
140
+ res.setHeader("Access-Control-Allow-Origin", "*");
141
+ res.statusCode = 400;
142
+ res.end("Bad Request");
143
+ return;
144
+ }
145
+
146
+ if (urlPath.includes("\0")) {
147
+ res.setHeader("Access-Control-Allow-Origin", "*");
148
+ res.statusCode = 400;
149
+ res.end("Bad Request");
150
+ return;
151
+ }
152
+
83
153
  const expectedPrefix = `/${namespace}/__widgets/dist`;
84
154
  const distDir = getDistDir();
85
155
 
@@ -158,8 +228,8 @@ function createWebpackDevServerConfig(portOverride) {
158
228
  return;
159
229
  }
160
230
 
161
- // Validate URL path starts with expected prefix
162
- if (!urlPath.startsWith(expectedPrefix)) {
231
+ // Validate URL path starts with expected prefix on a path boundary
232
+ if (urlPath !== expectedPrefix && !urlPath.startsWith(`${expectedPrefix}/`)) {
163
233
  // Set CORS headers for 404 responses too
164
234
  res.setHeader("Access-Control-Allow-Origin", "*");
165
235
  res.setHeader(
@@ -186,19 +256,16 @@ function createWebpackDevServerConfig(portOverride) {
186
256
  if (isAssetsRequest) {
187
257
  const relAssetPath = rel.replace(/^assets\/?/, "");
188
258
  const assetsRoot = path.join(baseDir, "assets");
189
- const requestedAbs = path.join(assetsRoot, relAssetPath);
259
+ const resolvedAsset = resolveContainedPath(assetsRoot, relAssetPath);
190
260
 
191
- // Prevent path traversal
192
- const resolved = path.resolve(requestedAbs);
193
- const resolvedRoot = path.resolve(assetsRoot);
194
- if (!resolved.startsWith(resolvedRoot)) {
261
+ if (resolvedAsset.status === "forbidden") {
195
262
  res.setHeader("Access-Control-Allow-Origin", "*");
196
263
  res.statusCode = 400;
197
264
  res.end("Bad Request");
198
265
  return;
199
266
  }
200
267
 
201
- if (!fs.existsSync(resolved) || fs.statSync(resolved).isDirectory()) {
268
+ if (resolvedAsset.status !== "ok" || fs.statSync(resolvedAsset.filePath).isDirectory()) {
202
269
  res.setHeader("Access-Control-Allow-Origin", "*");
203
270
  res.statusCode = 404;
204
271
  res.end("Not Found");
@@ -224,22 +291,35 @@ function createWebpackDevServerConfig(portOverride) {
224
291
  return;
225
292
  }
226
293
 
227
- const ext = path.extname(resolved).toLowerCase();
294
+ const ext = path.extname(resolvedAsset.filePath).toLowerCase();
228
295
  const ctype = CONTENT_TYPES[ext] || "application/octet-stream";
229
296
  res.setHeader("Content-Type", ctype);
230
- res.end(fs.readFileSync(resolved));
297
+ res.end(fs.readFileSync(resolvedAsset.filePath));
231
298
  return;
232
299
  }
233
300
 
234
- let distPath = distDir ? path.join(distDir, rel || "") : null;
301
+ let resolvedDist = resolveContainedPath(distDir, rel || "");
235
302
 
236
- // If path is a directory, serve index.js by default
237
- if (distPath && fs.existsSync(distPath) && fs.statSync(distPath).isDirectory()) {
238
- distPath = path.join(distPath, "index.js");
303
+ if (resolvedDist.status === "forbidden") {
304
+ res.setHeader("Access-Control-Allow-Origin", "*");
305
+ res.statusCode = 400;
306
+ res.end("Bad Request");
307
+ return;
239
308
  }
240
309
 
241
- // Check if file exists
242
- if (!distPath || !fs.existsSync(distPath)) {
310
+ // If path is a directory, serve index.js by default (re-validating containment)
311
+ if (resolvedDist.status === "ok" && fs.statSync(resolvedDist.filePath).isDirectory()) {
312
+ resolvedDist = resolveContainedPath(distDir, path.join(rel || "", "index.js"));
313
+ if (resolvedDist.status === "forbidden") {
314
+ res.setHeader("Access-Control-Allow-Origin", "*");
315
+ res.statusCode = 400;
316
+ res.end("Bad Request");
317
+ return;
318
+ }
319
+ }
320
+
321
+ // Check if file exists and is not a directory
322
+ if (resolvedDist.status !== "ok" || fs.statSync(resolvedDist.filePath).isDirectory()) {
243
323
  // Set CORS headers for 404 responses too
244
324
  res.setHeader("Access-Control-Allow-Origin", "*");
245
325
  res.setHeader(
@@ -253,10 +333,12 @@ function createWebpackDevServerConfig(portOverride) {
253
333
  res.setHeader("Access-Control-Allow-Credentials", "true");
254
334
 
255
335
  res.statusCode = 404;
256
- res.end(`Not Found: ${distPath}\n\nRequested: ${urlPath}\nExpected prefix: ${expectedPrefix}`);
336
+ res.end("Not Found");
257
337
  return;
258
338
  }
259
339
 
340
+ const distPath = resolvedDist.filePath;
341
+
260
342
  // Set CORS headers
261
343
  res.setHeader("Access-Control-Allow-Origin", "*");
262
344
  res.setHeader(
@@ -300,8 +382,16 @@ function createWebpackDevServerConfig(portOverride) {
300
382
  }
301
383
  });
302
384
 
303
- const listenPort = Number(portOverride) || SERVER_CONFIG.HTTP_PORT || 8083;
304
- server.listen(listenPort, () => {
385
+ const parsedPort =
386
+ portOverride !== undefined && portOverride !== null && portOverride !== ""
387
+ ? Number(portOverride)
388
+ : NaN;
389
+ const listenPort =
390
+ Number.isInteger(parsedPort) && parsedPort >= 0
391
+ ? parsedPort
392
+ : SERVER_CONFIG.HTTP_PORT || 8083;
393
+ const listenHost = SERVER_CONFIG.HTTP_HOST || "127.0.0.1";
394
+ server.listen(listenPort, listenHost, () => {
305
395
  i18n.info("commands.serve.serverRunning", { port: listenPort, namespace });
306
396
  });
307
397
 
@@ -486,4 +576,8 @@ function createWebpackDevServerConfig(portOverride) {
486
576
  };
487
577
  }
488
578
 
489
- module.exports = { createWebpackDevServerConfig };
579
+ module.exports = {
580
+ createWebpackDevServerConfig,
581
+ isPathWithinRoot,
582
+ resolveContainedPath
583
+ };
@@ -9,8 +9,7 @@ const { templateLoader } = require("../utils/templateLoader.js");
9
9
  const { i18n } = require("../utils/i18n.js");
10
10
  const { UrlUtil } = require("../utils/urlUtil.js");
11
11
  const {
12
- CLIENT_ID,
13
- CLIENT_SECRET,
12
+ getOAuthClient,
14
13
  DEFAULT_PORT,
15
14
  DEFAULT_SCOPE,
16
15
  ACCESS_TYPE,
@@ -29,8 +28,10 @@ let oauthState = {
29
28
  redirectUri: `http://localhost:${DEFAULT_PORT}/oauth/callback`,
30
29
  secureConfig: new SecureConfig(),
31
30
  secureStorage: new SecureStorage(),
32
- clientId: CLIENT_ID,
33
- clientSecret: CLIENT_SECRET,
31
+ environmentId: null,
32
+ clientId: null,
33
+ codeVerifier: null,
34
+ expectedState: null,
34
35
  scope: DEFAULT_SCOPE,
35
36
  accessType: ACCESS_TYPE,
36
37
  prompt: PROMPT,
@@ -42,6 +43,73 @@ let oauthState = {
42
43
  currentAuthCode: null,
43
44
  };
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
+
45
113
  // --- Utility Functions ---
46
114
 
47
115
  /**
@@ -125,6 +193,8 @@ async function refreshAccessToken(authData) {
125
193
  throw new Error("Could not build token URL for current environment");
126
194
  }
127
195
 
196
+ const { clientId } = resolveClientCredentials(authData);
197
+
128
198
  // Configure axios for local development
129
199
  const axiosConfig = {
130
200
  method: "POST",
@@ -135,8 +205,7 @@ async function refreshAccessToken(authData) {
135
205
  data: new URLSearchParams({
136
206
  grant_type: "refresh_token",
137
207
  refresh_token: authData.refresh_token,
138
- client_id: CLIENT_ID,
139
- client_secret: CLIENT_SECRET,
208
+ client_id: clientId,
140
209
  }).toString(),
141
210
  timeout: 30000, // 30 seconds
142
211
  };
@@ -191,18 +260,31 @@ async function refreshAccessToken(authData) {
191
260
  }
192
261
 
193
262
  /**
194
- * Build OAuth URL without PKCE.
263
+ * Build OAuth authorize URL with PKCE (S256) and CSRF state.
195
264
  * @param {string} authDomain - The full auth base URL (e.g. https://accounts.zoho.com)
196
265
  */
197
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
+
198
278
  const params = {
199
279
  response_type: "code",
200
- client_id: CLIENT_ID,
280
+ client_id: oauthState.clientId,
201
281
  scope: oauthState.scope,
202
282
  redirect_uri: oauthState.redirectUri,
203
283
  access_type: oauthState.accessType,
204
284
  prompt: oauthState.prompt,
205
- state: crypto.randomBytes(16).toString("hex"), // CSRF protection
285
+ state,
286
+ code_challenge: codeChallenge,
287
+ code_challenge_method: "S256",
206
288
  };
207
289
 
208
290
  const endpoint = UrlUtil.getApiEndpoint("OAUTH.AUTHORIZE");
@@ -217,15 +299,21 @@ async function buildAuthUrl(authDomain) {
217
299
  */
218
300
  async function exchangeCodeForTokens(authCode, authDomain) {
219
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
+
220
308
  const tokenEndpoint = UrlUtil.getApiEndpoint("OAUTH.TOKEN");
221
309
  const tokenUrl = `${authDomain}/${tokenEndpoint}`;
222
310
 
223
311
  const requestData = new URLSearchParams({
224
- client_id: CLIENT_ID,
225
- client_secret: CLIENT_SECRET,
312
+ client_id: oauthState.clientId,
226
313
  grant_type: "authorization_code",
227
314
  code: authCode,
228
315
  redirect_uri: oauthState.redirectUri,
316
+ code_verifier: oauthState.codeVerifier,
229
317
  });
230
318
 
231
319
  const response = await axios.post(tokenUrl, requestData, {
@@ -325,6 +413,19 @@ async function handleOAuthCallback(req, res) {
325
413
  }
326
414
 
327
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
+
328
429
  // Show loading page using template
329
430
  const loadingHtml = templateLoader.renderTemplate("oauth/loading.html");
330
431
  res.send(loadingHtml);
@@ -594,6 +695,8 @@ async function completeAuthentication(authDomain) {
594
695
  oauthState.authPromise = null;
595
696
  oauthState.authResolve = null;
596
697
  oauthState.authReject = null;
698
+ oauthState.codeVerifier = null;
699
+ oauthState.expectedState = null;
597
700
 
598
701
  // Stop the server after a delay so the browser can show the final status
599
702
  setTimeout(async () => {
@@ -616,6 +719,18 @@ class OAuthService {
616
719
  templateLoader.preloadTemplates();
617
720
  }
618
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
+
619
734
  getAuthorizationHeader() {
620
735
  return getAuthorizationHeader();
621
736
  }
@@ -670,3 +785,12 @@ class OAuthService {
670
785
  }
671
786
 
672
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;
@@ -1,5 +1,5 @@
1
1
  {
2
- "title": "translated(ui.common.{{componentName}})",
2
+ "title": "componentName",
3
3
  "type": "{{namespacedComponentName}}",
4
4
  "componentName": "{{namespacedComponentName}}",
5
5
  "floater_config": {
@@ -0,0 +1,35 @@
1
+ const path = require('path');
2
+
3
+ /**
4
+ * Resolve the CLI binary name the user actually invoked.
5
+ *
6
+ * Supports the three shipping names:
7
+ * - zs (local sdk / source checkout)
8
+ * - zoho-sites-cli (public NPM build)
9
+ * - zoho-sites-dev-cli (internal build)
10
+ *
11
+ * Derived from process.argv[1] (the script path Node executed), so error
12
+ * messages and generated scripts match whatever command the user typed.
13
+ *
14
+ * @param {string} [argv1=process.argv[1]] - override for tests
15
+ * @returns {string}
16
+ */
17
+ function getCliName(argv1 = process.argv[1]) {
18
+ if (!argv1 || typeof argv1 !== 'string') {
19
+ return 'zs';
20
+ }
21
+
22
+ const base = path.basename(argv1).replace(/\.js$/i, '');
23
+ if (!base || base === 'node' || base === 'nodejs') {
24
+ return 'zs';
25
+ }
26
+
27
+ // Known bins and any future zoho-sites-* rename stay as-is.
28
+ if (base === 'zs' || base.startsWith('zoho-sites')) {
29
+ return base;
30
+ }
31
+
32
+ return 'zs';
33
+ }
34
+
35
+ module.exports = { getCliName };