huaweicloud-devkit 2.0.1-next.2 → 2.0.1-next.3

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.
@@ -0,0 +1,363 @@
1
+ import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, writeSync } from 'node:fs';
2
+ import { spawnSync } from 'node:child_process';
3
+ import { randomInt } from 'node:crypto';
4
+ import { dirname, join, resolve } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ // ---------------------------------------------------------------------------
7
+ // Deterministic defaults (contest/ops alignment: fixed service names, fixed
8
+ // user, fixed port pair so graders and scripts can discover them). These
9
+ // mirror the v1 installer's values one-for-one so one grading script covers
10
+ // both release lines.
11
+ // ---------------------------------------------------------------------------
12
+ export const DEFAULT_SERVER_INSTALL_PATH = '/opt/kunpeng';
13
+ export const DEFAULT_BUSINESS_PORT = 8088;
14
+ export const DEFAULT_TOOL_PORT = 7088;
15
+ export const DEFAULT_SERVER_USER = 'devkit';
16
+ export const BUSINESS_SERVICE_NAME = 'huaweicloud-devkit.service';
17
+ export const TOOL_SERVICE_NAME = 'huaweicloud-devkit-tool.service';
18
+ export const NODE_VERSION = '22.19.0';
19
+ const NODE_MIRROR = 'https://mirrors.huaweicloud.com/nodejs';
20
+ // The running module may be an individually compiled dist file (setup-cli
21
+ // loads it as dist/server-install.js) or inlined inside the bundled server
22
+ // entry. Walking up to the nearest package.json *named like this package*
23
+ // is robust against both layouts; the v1 installer's fixed three-levels-up
24
+ // resolve shipped a one-level-off copy bug before it was patched, so the
25
+ // walk is also the validation.
26
+ function resolvePackageRoot(startDir) {
27
+ let current = startDir;
28
+ for (let depth = 0; depth < 8; depth++) {
29
+ const manifest = join(current, 'package.json');
30
+ if (existsSync(manifest)) {
31
+ let name;
32
+ try {
33
+ ({ name } = JSON.parse(readFileSync(manifest, 'utf8')));
34
+ }
35
+ catch {
36
+ throw new Error(`unreadable package manifest while locating the install root: ${manifest}`);
37
+ }
38
+ if (name === 'huaweicloud-devkit')
39
+ return current;
40
+ }
41
+ const parent = dirname(current);
42
+ if (parent === current)
43
+ break;
44
+ current = parent;
45
+ }
46
+ throw new Error(`could not locate the huaweicloud-devkit package root above ${startDir}`);
47
+ }
48
+ const MODULE_DIR = dirname(fileURLToPath(import.meta.url));
49
+ const PACKAGE_ROOT = resolvePackageRoot(MODULE_DIR);
50
+ export function parseServerInstallArgs(argv = []) {
51
+ const opts = {
52
+ installPath: DEFAULT_SERVER_INSTALL_PATH,
53
+ port: DEFAULT_BUSINESS_PORT,
54
+ toolPort: DEFAULT_TOOL_PORT,
55
+ user: DEFAULT_SERVER_USER,
56
+ rotatePassword: false,
57
+ removeUser: false,
58
+ };
59
+ for (let i = 0; i < argv.length; i++) {
60
+ const arg = argv[i];
61
+ if (arg === undefined)
62
+ break;
63
+ const value = () => {
64
+ const next = argv[i + 1];
65
+ if (!next || next.startsWith('--')) {
66
+ throw new Error(`Missing value for ${arg}`);
67
+ }
68
+ i += 1;
69
+ return next;
70
+ };
71
+ if (arg === '--install-path')
72
+ opts.installPath = value();
73
+ else if (arg === '--port')
74
+ opts.port = Number(value());
75
+ else if (arg === '--tool-port')
76
+ opts.toolPort = Number(value());
77
+ else if (arg === '--user')
78
+ opts.user = value();
79
+ else if (arg === '--rotate-password')
80
+ opts.rotatePassword = true;
81
+ else if (arg === '--remove-user')
82
+ opts.removeUser = true;
83
+ else
84
+ throw new Error(`Unknown option for install-server: ${arg}`);
85
+ }
86
+ if (!Number.isSafeInteger(opts.port) || opts.port < 1024 || opts.port > 65535) {
87
+ throw new Error(`Invalid --port: ${opts.port}`);
88
+ }
89
+ if (!Number.isSafeInteger(opts.toolPort) || opts.toolPort < 1024 || opts.toolPort > 65535) {
90
+ throw new Error(`Invalid --tool-port: ${opts.toolPort}`);
91
+ }
92
+ if (opts.port === opts.toolPort) {
93
+ throw new Error('--port and --tool-port must differ');
94
+ }
95
+ if (!/^[a-z_][a-z0-9_-]{0,31}$/.test(opts.user)) {
96
+ throw new Error(`Invalid --user: ${opts.user}`);
97
+ }
98
+ return opts;
99
+ }
100
+ // Deconfusable alphabet (no 0/O/1/I/l): the password is transcribed by
101
+ // humans from a headless server terminal exactly once, at install time.
102
+ // randomInt samples each character uniformly — a modulo of randomBytes
103
+ // would bias the first two alphabet entries (256 % 56 != 0).
104
+ export function randomPassword(length = 24) {
105
+ const alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789';
106
+ let out = '';
107
+ for (let i = 0; i < length; i++)
108
+ out += alphabet[randomInt(0, alphabet.length)];
109
+ return out;
110
+ }
111
+ export function renderSystemdUnit({ serviceName, description, nodePath, appEntry, port, user, authPasswordFile, unitDir = '/etc/systemd/system', }) {
112
+ const unit = [
113
+ '[Unit]',
114
+ `Description=${description}`,
115
+ 'After=network.target',
116
+ '',
117
+ '[Service]',
118
+ 'Type=simple',
119
+ `ExecStart=${nodePath} ${appEntry} --transport remote --port ${port} --host 0.0.0.0 --auth-password-file ${authPasswordFile}`,
120
+ 'Restart=on-failure',
121
+ 'RestartSec=3',
122
+ `User=${user}`,
123
+ '',
124
+ '[Install]',
125
+ 'WantedBy=multi-user.target',
126
+ '',
127
+ ].join('\n');
128
+ return {
129
+ unitDir: unitDir.endsWith('/') ? unitDir : `${unitDir}/`,
130
+ unitPath: `${unitDir}/${serviceName}`,
131
+ unit,
132
+ };
133
+ }
134
+ export function nodeArchiveUrl(version, arch = process.arch) {
135
+ const flat = arch === 'arm64' || arch === 'aarch64' ? 'arm64' : 'x64';
136
+ return `${NODE_MIRROR}/v${version}/node-v${version}-linux-${flat}.tar.xz`;
137
+ }
138
+ export function isSupportedPlatform(platform = process.platform) {
139
+ return platform === 'linux';
140
+ }
141
+ function run(cmd, args) {
142
+ const res = spawnSync(cmd, args, { encoding: 'utf8' });
143
+ const out = (res.stdout ?? '').trim();
144
+ const err = (res.stderr ?? '').trim();
145
+ return { code: res.status, out, err, ok: res.status === 0 };
146
+ }
147
+ function runOrDie(cmd, args, what) {
148
+ const res = run(cmd, args);
149
+ if (!res.ok) {
150
+ throw new Error(`${what} failed: ${cmd} ${args.join(' ')}\n${res.err || res.out}`);
151
+ }
152
+ return res;
153
+ }
154
+ function writeFileOwner(path, content, owner, mode = 0o644) {
155
+ mkdirSync(dirname(path), { recursive: true });
156
+ const fd = openSync(path, 'w', mode);
157
+ writeSync(fd, content);
158
+ closeSync(fd);
159
+ chmodSync(path, mode);
160
+ if (owner)
161
+ runOrDie('chown', [owner, path], `chown ${path}`);
162
+ }
163
+ // ---------------------------------------------------------------------------
164
+ // Steps
165
+ // ---------------------------------------------------------------------------
166
+ function ensureRoot() {
167
+ if (typeof process.getuid === 'function' && process.getuid() !== 0) {
168
+ throw new Error('install-server must run as root (needs user/group creation and systemd)');
169
+ }
170
+ }
171
+ function ensureLinux() {
172
+ if (!isSupportedPlatform()) {
173
+ throw new Error('install-server is Linux-only today (systemd required). Use `install` to configure coding agents.');
174
+ }
175
+ }
176
+ function ensureUser(user) {
177
+ const check = run('id', ['-u', user]);
178
+ if (check.ok)
179
+ return;
180
+ const nologin = ['/usr/sbin/nologin', '/sbin/nologin'].find((p) => existsSync(p)) || '/bin/false';
181
+ runOrDie('useradd', ['--system', '--no-create-home', '--shell', nologin, user], `create system user ${user}`);
182
+ }
183
+ function resolveSystemNode() {
184
+ const res = run('node', ['-v']);
185
+ if (res.ok) {
186
+ const major = Number.parseInt(res.out.replace(/^v/, ''), 10);
187
+ if (Number.isSafeInteger(major) && major >= 22) {
188
+ const where = run('bash', ['-c', 'command -v node']);
189
+ // An npx-shim node dies with the cache; the service must not pin it.
190
+ if (where.ok && where.out && !where.out.includes('_npx'))
191
+ return where.out.trim();
192
+ }
193
+ }
194
+ return null;
195
+ }
196
+ function provisionNode(installPath) {
197
+ const target = join(installPath, 'node');
198
+ const bin = join(target, 'bin', 'node');
199
+ if (existsSync(bin))
200
+ return bin;
201
+ const url = nodeArchiveUrl(NODE_VERSION);
202
+ mkdirSync(installPath, { recursive: true });
203
+ console.log(` downloading Node.js v${NODE_VERSION} from ${url}`);
204
+ runOrDie('curl', ['-sL', '--retry', '3', '-o', join(installPath, 'node.tar.xz'), url], 'download Node.js');
205
+ runOrDie('mkdir', ['-p', target], 'mkdir node dir');
206
+ runOrDie('tar', ['-xJf', join(installPath, 'node.tar.xz'), '-C', target, '--strip-components', '1'], 'extract Node.js');
207
+ rmSync(join(installPath, 'node.tar.xz'), { force: true });
208
+ return bin;
209
+ }
210
+ function installAppDir(installPath, user) {
211
+ const app = join(installPath, 'devkit', 'app');
212
+ rmSync(app, { recursive: true, force: true });
213
+ mkdirSync(app, { recursive: true });
214
+ // Copy the running package (bin/ + plugins/ + package.json + node_modules
215
+ // when present) so the service is self-contained. Direct argv, no shell:
216
+ // every path component stays a literal argument.
217
+ const res = run('cp', ['-a', `${PACKAGE_ROOT}/.`, `${app}/`]);
218
+ if (!res.ok) {
219
+ throw new Error(`copy package to ${app} failed: ${res.err || res.out}`);
220
+ }
221
+ rmSync(join(app, '.git'), { recursive: true, force: true });
222
+ runOrDie('chown', ['-R', `${user}:${user}`, join(installPath, 'devkit')], 'chown app dir');
223
+ chmodSync(app, 0o750);
224
+ return app;
225
+ }
226
+ function writePasswordFile(installPath, user, rotate) {
227
+ const pwFile = join(installPath, 'devkit', 'server', '.auth-password');
228
+ if (existsSync(pwFile) && !rotate) {
229
+ return pwFile;
230
+ }
231
+ const password = randomPassword(24);
232
+ writeFileOwner(pwFile, `${password}\n`, user, 0o600);
233
+ return pwFile;
234
+ }
235
+ function writeUnits(installPath, params) {
236
+ // The dist bundle, not the TypeScript sources: the remote transport ships
237
+ // only inside the bundled entry (the individual mcp-server-remote.js is
238
+ // removed from dist by the build), so this is the one runnable path — the
239
+ // same file the `huaweicloud-devkit-mcp` bin resolves to.
240
+ const entry = join(params.app, 'plugins', 'huaweicloud-core', 'dist', 'mcp-server.js');
241
+ const business = renderSystemdUnit({
242
+ serviceName: BUSINESS_SERVICE_NAME,
243
+ description: 'HuaweiCloud DevKit MCP server (business port)',
244
+ nodePath: params.nodePath,
245
+ appEntry: entry,
246
+ port: params.port,
247
+ user: params.user,
248
+ authPasswordFile: params.pwFile,
249
+ });
250
+ const tool = renderSystemdUnit({
251
+ serviceName: TOOL_SERVICE_NAME,
252
+ description: 'HuaweiCloud DevKit MCP server (tool port)',
253
+ nodePath: params.nodePath,
254
+ appEntry: entry,
255
+ port: params.toolPort,
256
+ user: params.user,
257
+ authPasswordFile: params.pwFile,
258
+ });
259
+ writeFileOwner(business.unitPath, business.unit, 'root', 0o644);
260
+ writeFileOwner(tool.unitPath, tool.unit, 'root', 0o644);
261
+ runOrDie('systemctl', ['daemon-reload'], 'systemd daemon-reload');
262
+ }
263
+ export function planServiceCommands() {
264
+ return [
265
+ {
266
+ cmd: 'systemctl',
267
+ args: ['enable', BUSINESS_SERVICE_NAME, TOOL_SERVICE_NAME],
268
+ label: 'enable services',
269
+ },
270
+ {
271
+ cmd: 'systemctl',
272
+ args: ['restart', BUSINESS_SERVICE_NAME, TOOL_SERVICE_NAME],
273
+ label: 'restart services',
274
+ },
275
+ ];
276
+ }
277
+ // One joint restart call removes the serial-restart failure window (the
278
+ // first restart succeeding and the second erroring, leaving one unit
279
+ // restarted and the other untouched). It is not a transaction: systemd
280
+ // enqueues the two units' jobs independently, so a mid-call failure can
281
+ // still land between them — but any failure aborts the install at
282
+ // runOrDie before "install complete" is ever printed.
283
+ function startServices() {
284
+ for (const { cmd, args, label } of planServiceCommands()) {
285
+ runOrDie(cmd, args, label);
286
+ }
287
+ }
288
+ function waitHealthy(port, timeoutMs = 15000) {
289
+ const deadline = Date.now() + timeoutMs;
290
+ while (Date.now() < deadline) {
291
+ const res = run('curl', ['-fsS', `http://127.0.0.1:${port}/health`]);
292
+ if (res.ok && res.out.includes('"ok"'))
293
+ return true;
294
+ const sleep = run('sleep', ['1']);
295
+ if (!sleep.ok)
296
+ break;
297
+ }
298
+ return false;
299
+ }
300
+ // The installer never mutates firewall state — punching network holes is a
301
+ // security decision the operator makes knowingly. When firewalld is active
302
+ // we print the exact commands so the step is copy-paste instead of research.
303
+ function printFirewallHint(port, toolPort) {
304
+ const state = run('firewall-cmd', ['--state']);
305
+ if (state.ok && state.out === 'running') {
306
+ console.log('\nFirewalld is active on this host; the installer did not change firewall rules.');
307
+ console.log('Open the service ports yourself if external access is intended:');
308
+ console.log(` firewall-cmd --permanent --add-port=${port}/tcp`);
309
+ console.log(` firewall-cmd --permanent --add-port=${toolPort}/tcp`);
310
+ console.log(' firewall-cmd --reload');
311
+ }
312
+ else {
313
+ console.log('\nNote: firewall rules were not changed. If external clients will connect, open the service ports per your distro (firewalld/ufw/iptables).');
314
+ }
315
+ }
316
+ // ---------------------------------------------------------------------------
317
+ // CLI entry points
318
+ // ---------------------------------------------------------------------------
319
+ export async function installServerCli(argv = []) {
320
+ ensureLinux();
321
+ ensureRoot();
322
+ const opts = parseServerInstallArgs(argv);
323
+ const installPath = resolve(opts.installPath);
324
+ console.log(`Installing HuaweiCloud DevKit server under ${installPath}`);
325
+ console.log(` business port: ${opts.port} tool port: ${opts.toolPort} service user: ${opts.user}`);
326
+ ensureUser(opts.user);
327
+ const nodePath = resolveSystemNode() || provisionNode(installPath);
328
+ const app = installAppDir(installPath, opts.user);
329
+ const pwFile = writePasswordFile(installPath, opts.user, opts.rotatePassword);
330
+ writeUnits(installPath, { nodePath, app, port: opts.port, toolPort: opts.toolPort, user: opts.user, pwFile });
331
+ startServices();
332
+ const okBusiness = waitHealthy(opts.port);
333
+ const okTool = waitHealthy(opts.toolPort);
334
+ if (!okBusiness || !okTool) {
335
+ const failed = !okBusiness ? BUSINESS_SERVICE_NAME : TOOL_SERVICE_NAME;
336
+ console.log(` warning: ${failed} did not report healthy yet; inspect with: journalctl -u ${failed} -n 50`);
337
+ }
338
+ console.log('\nServer install complete:');
339
+ console.log(` install path : ${installPath}/devkit/app`);
340
+ console.log(` service user : ${opts.user}`);
341
+ console.log(` business svc : ${BUSINESS_SERVICE_NAME} -> 0.0.0.0:${opts.port}`);
342
+ console.log(` tool svc : ${TOOL_SERVICE_NAME} -> 0.0.0.0:${opts.toolPort}`);
343
+ console.log(` auth password: ${pwFile} (0600; header: Authorization: Bearer <password> or x-devkit-password)`);
344
+ console.log(' health check : GET http://127.0.0.1:<port>/health');
345
+ printFirewallHint(opts.port, opts.toolPort);
346
+ }
347
+ export async function uninstallServerCli(argv = []) {
348
+ ensureLinux();
349
+ ensureRoot();
350
+ const opts = parseServerInstallArgs(argv);
351
+ run('systemctl', ['disable', '--now', BUSINESS_SERVICE_NAME]);
352
+ run('systemctl', ['disable', '--now', TOOL_SERVICE_NAME]);
353
+ for (const unit of [BUSINESS_SERVICE_NAME, TOOL_SERVICE_NAME]) {
354
+ rmSync(`/etc/systemd/system/${unit}`, { force: true });
355
+ }
356
+ run('systemctl', ['daemon-reload']);
357
+ rmSync(join(opts.installPath, 'devkit'), { recursive: true, force: true });
358
+ if (opts.removeUser) {
359
+ run('userdel', [opts.user]);
360
+ console.log(`removed service user: ${opts.user}`);
361
+ }
362
+ console.log('HuaweiCloud DevKit server uninstalled.');
363
+ }
@@ -15,6 +15,7 @@ import { removeKooCli, removeObsConfig } from "./sandbox/uninstall-cleanup.js";
15
15
  import { readReceipt, removeReceipt } from "./dep/receipts.js";
16
16
  import { runSecretCommand } from "./lib/secret-vault/cli.js";
17
17
  import { createProcessApproveIo, runApproveCommand, runPinCommand } from "./approvals-cli.js";
18
+ import { installServerCli, uninstallServerCli } from "./server-install.js";
18
19
  import { readConsentEvents } from "./approval-ledger.js";
19
20
  import { custodyReport } from "./lib/secret-vault/custody.js";
20
21
  import { vaultList } from "./lib/secret-vault/store.js";
@@ -1323,6 +1324,12 @@ async function main() {
1323
1324
  case 'install-hcloud':
1324
1325
  await cmdInstallHcloud();
1325
1326
  break;
1327
+ case 'install-server':
1328
+ await installServerCli(process.argv.slice(3));
1329
+ break;
1330
+ case 'uninstall-server':
1331
+ await uninstallServerCli(process.argv.slice(3));
1332
+ break;
1326
1333
  case 'dep':
1327
1334
  await cmdDep();
1328
1335
  break;
@@ -1364,6 +1371,8 @@ async function main() {
1364
1371
  console.log(' status Show installation status');
1365
1372
  console.log(' doctor Self-check: hcloud, MCP, skills, auth');
1366
1373
  console.log(' install-hcloud Show KooCLI install commands for your OS');
1374
+ console.log(' install-server Server mode: systemd services + dedicated user + auth password (Linux root)');
1375
+ console.log(' uninstall-server Remove server-mode services and files');
1367
1376
  console.log(' dep Dependency tooling: status | install <id> | uninstall <id>');
1368
1377
  console.log(' packs Post-install pack surface: status | enable <ids> | disable <ids> | all');
1369
1378
  console.log(' auth Manage unified auth: init | sync | status | reconcile');
@@ -1380,6 +1389,13 @@ async function main() {
1380
1389
  console.log(' --clean-obs (with: uninstall --target all) also remove OBS config');
1381
1390
  console.log(' --clean-gateway (with: uninstall --target all) also remove the devkit-installed open-mcp-gateway');
1382
1391
  console.log(' --clean-global (with: uninstall --target all) also remove KooCLI + OBS config + open-mcp-gateway');
1392
+ console.log('\ninstall-server options:');
1393
+ console.log(' --install-path <dir> Base install path (default /opt/kunpeng)');
1394
+ console.log(' --port <n> Business port (default 8088)');
1395
+ console.log(' --tool-port <n> Tool port (default 7088)');
1396
+ console.log(' --user <name> Dedicated service user (default devkit)');
1397
+ console.log(' --rotate-password Regenerate the server auth password');
1398
+ console.log(' --remove-user (with: uninstall-server) also delete the service user');
1383
1399
  console.log('\nExamples:');
1384
1400
  console.log(' npx huaweicloud-devkit install');
1385
1401
  console.log(' npx huaweicloud-devkit install --target codex');
@@ -2,7 +2,7 @@
2
2
  "name": "huaweicloud-devkit",
3
3
  "id": "huaweicloud-devkit",
4
4
  "displayName": "HuaweiCloud DevKit",
5
- "version": "2.0.1-next.2",
5
+ "version": "2.0.1-next.3",
6
6
  "family": "bundle-plugin",
7
7
  "bundleFormat": "codex",
8
8
  "description": "Guide coding agents to use Huawei Cloud safely �?KooCLI, APIs, SDKs, 40 MCP tools, skills, and safety guardrails.",
@@ -1,4 +1,12 @@
1
- import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
1
+ import {
2
+ createServer,
3
+ type IncomingHttpHeaders,
4
+ type IncomingMessage,
5
+ type Server,
6
+ type ServerResponse,
7
+ } from 'node:http';
8
+ import { timingSafeEqual } from 'node:crypto';
9
+ import { readFileSync } from 'node:fs';
2
10
  import { format } from 'node:util';
3
11
  import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
4
12
  import type { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';
@@ -12,6 +20,7 @@ export const DEFAULT_HOST = '127.0.0.1';
12
20
  interface RemoteServerOptions {
13
21
  port?: number;
14
22
  host?: string;
23
+ authPasswordFile?: string;
15
24
  }
16
25
 
17
26
  interface StartedRemoteServer {
@@ -20,15 +29,46 @@ interface StartedRemoteServer {
20
29
  close: () => Promise<void>;
21
30
  }
22
31
 
32
+ // Constant-time comparison over the raw bytes: length is checked once
33
+ // (an early exit on length only reveals whether the length matches —
34
+ // the generated password is fixed-length, so nothing usable leaks), and
35
+ // equal-length comparison runs in constant time. Plain `===` would leak
36
+ // how many leading characters a guess got right.
37
+ function constantTimeEquals(actual: string, expected: string): boolean {
38
+ const actualBytes = Buffer.from(actual, 'utf8');
39
+ const expectedBytes = Buffer.from(expected, 'utf8');
40
+ return actualBytes.length === expectedBytes.length && timingSafeEqual(actualBytes, expectedBytes);
41
+ }
42
+
43
+ // Pure helper: does an HTTP request carry the expected password? Accepted
44
+ // either as `Authorization: Bearer <password>` or as a direct
45
+ // `x-devkit-password` header. An empty expected password means auth is off
46
+ // and every request passes. Exported for tests.
47
+ export function verifyAuthPassword(headers: IncomingHttpHeaders, expected: string): boolean {
48
+ if (!expected) return true;
49
+ const auth = String(headers.authorization ?? '').trim();
50
+ const bearer = auth.startsWith('Bearer ') ? auth.slice(7).trim() : '';
51
+ if (bearer && constantTimeEquals(bearer, expected)) return true;
52
+ const direct = String(headers['x-devkit-password'] ?? '').trim();
53
+ return direct.length > 0 && constantTimeEquals(direct, expected);
54
+ }
55
+
23
56
  export async function startRemoteServer({
24
57
  port = DEFAULT_PORT,
25
58
  host = DEFAULT_HOST,
59
+ authPasswordFile,
26
60
  }: RemoteServerOptions = {}): Promise<StartedRemoteServer> {
61
+ // Fail closed: an unreadable or missing password file aborts startup —
62
+ // a misconfigured auth flag must never degrade to open access.
63
+ let authPassword = '';
64
+ if (authPasswordFile) {
65
+ authPassword = readFileSync(authPasswordFile, 'utf8').trim();
66
+ }
27
67
  // node:http wants a void-returning listener; the async request handling
28
68
  // lives in handleRemoteRequest and every failure path inside it answers
29
69
  // the response (400/202/500) rather than rejecting.
30
70
  const server = createServer((req, res) => {
31
- void handleRemoteRequest(req, res);
71
+ void handleRemoteRequest(req, res, authPassword);
32
72
  });
33
73
 
34
74
  await new Promise<void>((resolvePromise, rejectPromise) => {
@@ -49,12 +89,12 @@ export async function startRemoteServer({
49
89
  };
50
90
  }
51
91
 
52
- async function handleRemoteRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
92
+ async function handleRemoteRequest(req: IncomingMessage, res: ServerResponse, authPassword: string): Promise<void> {
53
93
  res.setHeader('Access-Control-Allow-Origin', '*');
54
94
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
55
95
  res.setHeader(
56
96
  'Access-Control-Allow-Headers',
57
- 'Content-Type, MCP-Protocol-Version, Mcp-Session-Id, Accept, Authorization',
97
+ 'Content-Type, MCP-Protocol-Version, Mcp-Session-Id, Accept, Authorization, X-DevKit-Password',
58
98
  );
59
99
  res.setHeader('Access-Control-Expose-Headers', 'MCP-Protocol-Version, Mcp-Session-Id');
60
100
 
@@ -64,9 +104,32 @@ async function handleRemoteRequest(req: IncomingMessage, res: ServerResponse): P
64
104
  return;
65
105
  }
66
106
 
107
+ // Liveness stays unauthenticated by contract: load balancers and systemd
108
+ // watchdogs must observe health without knowing the password. Query
109
+ // strings are stripped so probes like /health?probe=1 keep working.
110
+ if (req.method === 'GET' && (req.url ?? '').split('?')[0] === '/health') {
111
+ res.writeHead(200, { 'Content-Type': 'application/json' });
112
+ res.end(JSON.stringify({ ok: true }));
113
+ return;
114
+ }
115
+
116
+ // The auth gate runs before the shell method filter, so an unauthorized
117
+ // request is told 401 even for non-POST methods (mirrors the v1 server
118
+ // face); everything except /health needs the password when one is set.
119
+ if (authPassword && !verifyAuthPassword(req.headers, authPassword)) {
120
+ res.writeHead(401, {
121
+ 'Content-Type': 'application/json',
122
+ 'WWW-Authenticate': 'Bearer realm="huaweicloud-devkit-mcp"',
123
+ });
124
+ res.end(
125
+ JSON.stringify({ error: 'Unauthorized', hint: 'send Authorization: Bearer <password> or x-devkit-password' }),
126
+ );
127
+ return;
128
+ }
129
+
67
130
  // The shell keeps the method filter: GET stays 405 (legacy contract; the
68
131
  // SDK transport would turn it into a 406/200 SSE stream) and only POST
69
- // reaches the transport.
132
+ // reaches the transport. /health above is the one GET carve-out.
70
133
  if (req.method !== 'POST') {
71
134
  res.writeHead(405, { Allow: 'POST, OPTIONS' });
72
135
  res.end();
@@ -16,6 +16,9 @@ const portIdx = process.argv.indexOf('--port');
16
16
  const remotePort = portIdx > -1 ? Number(process.argv[portIdx + 1]) : DEFAULT_PORT;
17
17
  const hostIdx = process.argv.indexOf('--host');
18
18
  const remoteHost = hostIdx > -1 && process.argv[hostIdx + 1] ? process.argv[hostIdx + 1] : DEFAULT_HOST;
19
+ const authFileIdx = process.argv.indexOf('--auth-password-file');
20
+ const authFileArg = authFileIdx > -1 ? process.argv[authFileIdx + 1] : undefined;
21
+ const authPasswordFile = authFileArg ? resolve(authFileArg) : undefined;
19
22
 
20
23
  const projectDirIdx = process.argv.indexOf('--codearts-project-dir');
21
24
  if (projectDirIdx > -1 && process.argv[projectDirIdx + 1]) {
@@ -75,7 +78,7 @@ if (transport === 'remote') {
75
78
  );
76
79
  }
77
80
  const { startRemoteServer } = await import('./mcp-server-remote.ts');
78
- startRemoteServer({ port: remotePort, host: remoteHost }).catch((error: unknown) => {
81
+ startRemoteServer({ port: remotePort, host: remoteHost, authPasswordFile }).catch((error: unknown) => {
79
82
  process.stderr.write(
80
83
  `Failed to start MCP remote server: ${error instanceof Error ? error.message : String(error)}\n`,
81
84
  );