huaweicloud-devkit 2.0.1-next.1 → 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.
@@ -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
  );
@@ -9,6 +9,18 @@ import { stripExecutable } from './unwrap.ts';
9
9
  import { SECRET_ARGS_RE } from './vocabulary.ts';
10
10
  import type { RiskDecision } from '../risk-rule-engine.ts';
11
11
 
12
+ // The dry-run preflight vocabulary (see the carve-out comment in
13
+ // classifyHcloudArgs). The global `--dryrun` flag is KooCLI's own
14
+ // "print the request, do not execute" (hcloud --help, service-agnostic);
15
+ // the body param `--dry_run=true` is the service-side preflight, pinned to
16
+ // the `${service} ${operation}` pairs (lowercased) whose operation-level
17
+ // --help documents it. Verified against `hcloud <op> --help` on
18
+ // 2026-11-27 for both entries; a future operation joins the set only with
19
+ // the same --help evidence.
20
+ const DRYRUN_GLOBAL_TOKEN = '--dryrun';
21
+ const DRY_RUN_PREFLIGHT_OPERATIONS = new Set(['ecs createservers', 'ecs createpostpaidservers']);
22
+ const DRY_RUN_EXACT_TOKEN = '--dry_run=true';
23
+
12
24
  export function classifyHcloudArgs(args: unknown, options: ClassifyOptions = {}): RiskDecision {
13
25
  const policy = options.policy || DEFAULT_POLICY;
14
26
  const unwrappedTokens = stripExecutable(Array.isArray(args) ? args.map((arg) => String(arg)) : []);
@@ -122,6 +134,58 @@ export function classifyHcloudArgs(args: unknown, options: ClassifyOptions = {})
122
134
  };
123
135
  }
124
136
 
137
+ // The dry-run preflight carve-out (the argv tool faces only — never the
138
+ // text/hook faces, see the rawCommand guard): a command whose child
139
+ // provably creates nothing is not a write, so plans/runs need no
140
+ // confirmation. Two documented zero-side-effect channels:
141
+ // (a) the KooCLI GLOBAL flag `--dryrun` — "Print the request message
142
+ // after verification, without execution" (hcloud --help): no
143
+ // request ever leaves the CLI, for ANY service/operation.
144
+ // (b) the ECS body param `--dry_run=true` — the service-side preflight
145
+ // ("true: indicates that only the request is sent, but the ECS
146
+ // will not be created. Check items include mandatory parameters
147
+ // and request format", per `hcloud ECS CreateServers --help`),
148
+ // allowlisted to the operations whose --help documents it
149
+ // (ECS CreateServers / CreatePostPaidServers, verified 2026-11-27).
150
+ // Fences keep the carve-out narrower than the facts it rests on:
151
+ // - EXACT TOKENS — only `--dryrun` and `--dry_run=true`. Case
152
+ // variants, `=True`, `=1`, `--dry-run`, or a bare `--dry_run` keep
153
+ // the write verdict, so a misspelled preflight still asks the user
154
+ // (fail-closed).
155
+ // - The body-param arm refuses `--cli-jsonInput`: a JSON body could
156
+ // carry a conflicting dry_run value under a precedence the CLI owns
157
+ // and the classifier cannot see.
158
+ // - The rawCommand === undefined guard is the face boundary: every
159
+ // hook entry point (the .mjs PreToolUse twin, the opencode
160
+ // in-process gate, and every nested walk inside classifyTextCommand)
161
+ // classifies TEXT with rawCommand set, so raw Bash keeps its deny
162
+ // and the py twin's verdicts stay parity-true. The argv faces —
163
+ // plan/run tool calls — carry no rawCommand and take the carve-out.
164
+ // A compound argv (a value containing `;`/`&&`/…) fragments in the
165
+ // segment pass and lands here WITHOUT its preflight token in the
166
+ // fragment, so the severity merge denies fail-closed.
167
+ if (
168
+ options.rawCommand === undefined &&
169
+ (normalizedArgs.includes(DRYRUN_GLOBAL_TOKEN) ||
170
+ (DRY_RUN_PREFLIGHT_OPERATIONS.has(`${service.toLowerCase()} ${operation.toLowerCase()}`) &&
171
+ normalizedArgs.includes(DRY_RUN_EXACT_TOKEN) &&
172
+ !normalizedArgs.some((arg) => arg.startsWith('--cli-jsonInput'))))
173
+ ) {
174
+ return applyCommandRiskRules(
175
+ {
176
+ decision: 'allow',
177
+ risk: 'preflight',
178
+ reason:
179
+ 'Documented dry-run preflight: the CLI prints the request without executing, or the service validates it and creates nothing, so no confirmation is required.',
180
+ service,
181
+ operation,
182
+ args: normalizedArgs,
183
+ },
184
+ normalizedArgs,
185
+ options,
186
+ );
187
+ }
188
+
125
189
  const readOnly = hasReadPrefix(operation, policy);
126
190
  const executionOps =
127
191
  /(^|\.)(Invoke|SyncInvoke|AsyncInvoke|Send|Trigger|Execute|Start|Reboot|Restart|Stop|Publish|Deploy)/i;
@@ -0,0 +1,442 @@
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
+ // ---------------------------------------------------------------------------
8
+ // Deterministic defaults (contest/ops alignment: fixed service names, fixed
9
+ // user, fixed port pair so graders and scripts can discover them). These
10
+ // mirror the v1 installer's values one-for-one so one grading script covers
11
+ // both release lines.
12
+ // ---------------------------------------------------------------------------
13
+
14
+ export const DEFAULT_SERVER_INSTALL_PATH = '/opt/kunpeng';
15
+ export const DEFAULT_BUSINESS_PORT = 8088;
16
+ export const DEFAULT_TOOL_PORT = 7088;
17
+ export const DEFAULT_SERVER_USER = 'devkit';
18
+ export const BUSINESS_SERVICE_NAME = 'huaweicloud-devkit.service';
19
+ export const TOOL_SERVICE_NAME = 'huaweicloud-devkit-tool.service';
20
+ export const NODE_VERSION = '22.19.0';
21
+ const NODE_MIRROR = 'https://mirrors.huaweicloud.com/nodejs';
22
+
23
+ // The running module may be an individually compiled dist file (setup-cli
24
+ // loads it as dist/server-install.js) or inlined inside the bundled server
25
+ // entry. Walking up to the nearest package.json *named like this package*
26
+ // is robust against both layouts; the v1 installer's fixed three-levels-up
27
+ // resolve shipped a one-level-off copy bug before it was patched, so the
28
+ // walk is also the validation.
29
+ function resolvePackageRoot(startDir: string): string {
30
+ let current = startDir;
31
+ for (let depth = 0; depth < 8; depth++) {
32
+ const manifest = join(current, 'package.json');
33
+ if (existsSync(manifest)) {
34
+ let name: unknown;
35
+ try {
36
+ ({ name } = JSON.parse(readFileSync(manifest, 'utf8')) as { name?: unknown });
37
+ } catch {
38
+ throw new Error(`unreadable package manifest while locating the install root: ${manifest}`);
39
+ }
40
+ if (name === 'huaweicloud-devkit') return current;
41
+ }
42
+ const parent = dirname(current);
43
+ if (parent === current) break;
44
+ current = parent;
45
+ }
46
+ throw new Error(`could not locate the huaweicloud-devkit package root above ${startDir}`);
47
+ }
48
+
49
+ const MODULE_DIR = dirname(fileURLToPath(import.meta.url));
50
+ const PACKAGE_ROOT = resolvePackageRoot(MODULE_DIR);
51
+
52
+ // ---------------------------------------------------------------------------
53
+ // Pure helpers (unit-testable on any OS)
54
+ // ---------------------------------------------------------------------------
55
+
56
+ export interface ServerInstallOptions {
57
+ installPath: string;
58
+ port: number;
59
+ toolPort: number;
60
+ user: string;
61
+ rotatePassword: boolean;
62
+ removeUser: boolean;
63
+ }
64
+
65
+ export function parseServerInstallArgs(argv: readonly string[] = []): ServerInstallOptions {
66
+ const opts: ServerInstallOptions = {
67
+ installPath: DEFAULT_SERVER_INSTALL_PATH,
68
+ port: DEFAULT_BUSINESS_PORT,
69
+ toolPort: DEFAULT_TOOL_PORT,
70
+ user: DEFAULT_SERVER_USER,
71
+ rotatePassword: false,
72
+ removeUser: false,
73
+ };
74
+ for (let i = 0; i < argv.length; i++) {
75
+ const arg = argv[i];
76
+ if (arg === undefined) break;
77
+ const value = (): string => {
78
+ const next = argv[i + 1];
79
+ if (!next || next.startsWith('--')) {
80
+ throw new Error(`Missing value for ${arg}`);
81
+ }
82
+ i += 1;
83
+ return next;
84
+ };
85
+ if (arg === '--install-path') opts.installPath = value();
86
+ else if (arg === '--port') opts.port = Number(value());
87
+ else if (arg === '--tool-port') opts.toolPort = Number(value());
88
+ else if (arg === '--user') opts.user = value();
89
+ else if (arg === '--rotate-password') opts.rotatePassword = true;
90
+ else if (arg === '--remove-user') opts.removeUser = true;
91
+ else throw new Error(`Unknown option for install-server: ${arg}`);
92
+ }
93
+ if (!Number.isSafeInteger(opts.port) || opts.port < 1024 || opts.port > 65535) {
94
+ throw new Error(`Invalid --port: ${opts.port}`);
95
+ }
96
+ if (!Number.isSafeInteger(opts.toolPort) || opts.toolPort < 1024 || opts.toolPort > 65535) {
97
+ throw new Error(`Invalid --tool-port: ${opts.toolPort}`);
98
+ }
99
+ if (opts.port === opts.toolPort) {
100
+ throw new Error('--port and --tool-port must differ');
101
+ }
102
+ if (!/^[a-z_][a-z0-9_-]{0,31}$/.test(opts.user)) {
103
+ throw new Error(`Invalid --user: ${opts.user}`);
104
+ }
105
+ return opts;
106
+ }
107
+
108
+ // Deconfusable alphabet (no 0/O/1/I/l): the password is transcribed by
109
+ // humans from a headless server terminal exactly once, at install time.
110
+ // randomInt samples each character uniformly — a modulo of randomBytes
111
+ // would bias the first two alphabet entries (256 % 56 != 0).
112
+ export function randomPassword(length = 24): string {
113
+ const alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789';
114
+ let out = '';
115
+ for (let i = 0; i < length; i++) out += alphabet[randomInt(0, alphabet.length)];
116
+ return out;
117
+ }
118
+
119
+ export interface SystemdUnitRender {
120
+ unitDir: string;
121
+ unitPath: string;
122
+ unit: string;
123
+ }
124
+
125
+ export function renderSystemdUnit({
126
+ serviceName,
127
+ description,
128
+ nodePath,
129
+ appEntry,
130
+ port,
131
+ user,
132
+ authPasswordFile,
133
+ unitDir = '/etc/systemd/system',
134
+ }: {
135
+ serviceName: string;
136
+ description: string;
137
+ nodePath: string;
138
+ appEntry: string;
139
+ port: number;
140
+ user: string;
141
+ authPasswordFile: string;
142
+ unitDir?: string;
143
+ }): SystemdUnitRender {
144
+ const unit = [
145
+ '[Unit]',
146
+ `Description=${description}`,
147
+ 'After=network.target',
148
+ '',
149
+ '[Service]',
150
+ 'Type=simple',
151
+ `ExecStart=${nodePath} ${appEntry} --transport remote --port ${port} --host 0.0.0.0 --auth-password-file ${authPasswordFile}`,
152
+ 'Restart=on-failure',
153
+ 'RestartSec=3',
154
+ `User=${user}`,
155
+ '',
156
+ '[Install]',
157
+ 'WantedBy=multi-user.target',
158
+ '',
159
+ ].join('\n');
160
+ return {
161
+ unitDir: unitDir.endsWith('/') ? unitDir : `${unitDir}/`,
162
+ unitPath: `${unitDir}/${serviceName}`,
163
+ unit,
164
+ };
165
+ }
166
+
167
+ export function nodeArchiveUrl(version: string, arch: string = process.arch): string {
168
+ const flat = arch === 'arm64' || arch === 'aarch64' ? 'arm64' : 'x64';
169
+ return `${NODE_MIRROR}/v${version}/node-v${version}-linux-${flat}.tar.xz`;
170
+ }
171
+
172
+ export function isSupportedPlatform(platform: string = process.platform): boolean {
173
+ return platform === 'linux';
174
+ }
175
+
176
+ // ---------------------------------------------------------------------------
177
+ // Shell helpers
178
+ // ---------------------------------------------------------------------------
179
+
180
+ interface ShellResult {
181
+ code: number | null;
182
+ out: string;
183
+ err: string;
184
+ ok: boolean;
185
+ }
186
+
187
+ function run(cmd: string, args: string[]): ShellResult {
188
+ const res = spawnSync(cmd, args, { encoding: 'utf8' });
189
+ const out = (res.stdout ?? '').trim();
190
+ const err = (res.stderr ?? '').trim();
191
+ return { code: res.status, out, err, ok: res.status === 0 };
192
+ }
193
+
194
+ function runOrDie(cmd: string, args: string[], what: string): ShellResult {
195
+ const res = run(cmd, args);
196
+ if (!res.ok) {
197
+ throw new Error(`${what} failed: ${cmd} ${args.join(' ')}\n${res.err || res.out}`);
198
+ }
199
+ return res;
200
+ }
201
+
202
+ function writeFileOwner(path: string, content: string, owner: string | null, mode = 0o644): void {
203
+ mkdirSync(dirname(path), { recursive: true });
204
+ const fd = openSync(path, 'w', mode);
205
+ writeSync(fd, content);
206
+ closeSync(fd);
207
+ chmodSync(path, mode);
208
+ if (owner) runOrDie('chown', [owner, path], `chown ${path}`);
209
+ }
210
+
211
+ // ---------------------------------------------------------------------------
212
+ // Steps
213
+ // ---------------------------------------------------------------------------
214
+
215
+ function ensureRoot(): void {
216
+ if (typeof process.getuid === 'function' && process.getuid() !== 0) {
217
+ throw new Error('install-server must run as root (needs user/group creation and systemd)');
218
+ }
219
+ }
220
+
221
+ function ensureLinux(): void {
222
+ if (!isSupportedPlatform()) {
223
+ throw new Error('install-server is Linux-only today (systemd required). Use `install` to configure coding agents.');
224
+ }
225
+ }
226
+
227
+ function ensureUser(user: string): void {
228
+ const check = run('id', ['-u', user]);
229
+ if (check.ok) return;
230
+ const nologin = ['/usr/sbin/nologin', '/sbin/nologin'].find((p) => existsSync(p)) || '/bin/false';
231
+ runOrDie('useradd', ['--system', '--no-create-home', '--shell', nologin, user], `create system user ${user}`);
232
+ }
233
+
234
+ function resolveSystemNode(): string | null {
235
+ const res = run('node', ['-v']);
236
+ if (res.ok) {
237
+ const major = Number.parseInt(res.out.replace(/^v/, ''), 10);
238
+ if (Number.isSafeInteger(major) && major >= 22) {
239
+ const where = run('bash', ['-c', 'command -v node']);
240
+ // An npx-shim node dies with the cache; the service must not pin it.
241
+ if (where.ok && where.out && !where.out.includes('_npx')) return where.out.trim();
242
+ }
243
+ }
244
+ return null;
245
+ }
246
+
247
+ function provisionNode(installPath: string): string {
248
+ const target = join(installPath, 'node');
249
+ const bin = join(target, 'bin', 'node');
250
+ if (existsSync(bin)) return bin;
251
+ const url = nodeArchiveUrl(NODE_VERSION);
252
+ mkdirSync(installPath, { recursive: true });
253
+ console.log(` downloading Node.js v${NODE_VERSION} from ${url}`);
254
+ runOrDie('curl', ['-sL', '--retry', '3', '-o', join(installPath, 'node.tar.xz'), url], 'download Node.js');
255
+ runOrDie('mkdir', ['-p', target], 'mkdir node dir');
256
+ runOrDie(
257
+ 'tar',
258
+ ['-xJf', join(installPath, 'node.tar.xz'), '-C', target, '--strip-components', '1'],
259
+ 'extract Node.js',
260
+ );
261
+ rmSync(join(installPath, 'node.tar.xz'), { force: true });
262
+ return bin;
263
+ }
264
+
265
+ function installAppDir(installPath: string, user: string): string {
266
+ const app = join(installPath, 'devkit', 'app');
267
+ rmSync(app, { recursive: true, force: true });
268
+ mkdirSync(app, { recursive: true });
269
+ // Copy the running package (bin/ + plugins/ + package.json + node_modules
270
+ // when present) so the service is self-contained. Direct argv, no shell:
271
+ // every path component stays a literal argument.
272
+ const res = run('cp', ['-a', `${PACKAGE_ROOT}/.`, `${app}/`]);
273
+ if (!res.ok) {
274
+ throw new Error(`copy package to ${app} failed: ${res.err || res.out}`);
275
+ }
276
+ rmSync(join(app, '.git'), { recursive: true, force: true });
277
+ runOrDie('chown', ['-R', `${user}:${user}`, join(installPath, 'devkit')], 'chown app dir');
278
+ chmodSync(app, 0o750);
279
+ return app;
280
+ }
281
+
282
+ function writePasswordFile(installPath: string, user: string, rotate: boolean): string {
283
+ const pwFile = join(installPath, 'devkit', 'server', '.auth-password');
284
+ if (existsSync(pwFile) && !rotate) {
285
+ return pwFile;
286
+ }
287
+ const password = randomPassword(24);
288
+ writeFileOwner(pwFile, `${password}\n`, user, 0o600);
289
+ return pwFile;
290
+ }
291
+
292
+ function writeUnits(
293
+ installPath: string,
294
+ params: { nodePath: string; app: string; port: number; toolPort: number; user: string; pwFile: string },
295
+ ): void {
296
+ // The dist bundle, not the TypeScript sources: the remote transport ships
297
+ // only inside the bundled entry (the individual mcp-server-remote.js is
298
+ // removed from dist by the build), so this is the one runnable path — the
299
+ // same file the `huaweicloud-devkit-mcp` bin resolves to.
300
+ const entry = join(params.app, 'plugins', 'huaweicloud-core', 'dist', 'mcp-server.js');
301
+ const business = renderSystemdUnit({
302
+ serviceName: BUSINESS_SERVICE_NAME,
303
+ description: 'HuaweiCloud DevKit MCP server (business port)',
304
+ nodePath: params.nodePath,
305
+ appEntry: entry,
306
+ port: params.port,
307
+ user: params.user,
308
+ authPasswordFile: params.pwFile,
309
+ });
310
+ const tool = renderSystemdUnit({
311
+ serviceName: TOOL_SERVICE_NAME,
312
+ description: 'HuaweiCloud DevKit MCP server (tool port)',
313
+ nodePath: params.nodePath,
314
+ appEntry: entry,
315
+ port: params.toolPort,
316
+ user: params.user,
317
+ authPasswordFile: params.pwFile,
318
+ });
319
+ writeFileOwner(business.unitPath, business.unit, 'root', 0o644);
320
+ writeFileOwner(tool.unitPath, tool.unit, 'root', 0o644);
321
+ runOrDie('systemctl', ['daemon-reload'], 'systemd daemon-reload');
322
+ }
323
+
324
+ // Pure command plan so the service lifecycle stays unit-testable:
325
+ // `enable` marks the units for boot without starting them; a single
326
+ // joint `restart` then starts fresh installs AND picks up rewritten files
327
+ // (e.g. a rotated auth password) on re-runs in one systemd call.
328
+ export interface ServiceCommand {
329
+ cmd: string;
330
+ args: string[];
331
+ label: string;
332
+ }
333
+
334
+ export function planServiceCommands(): ServiceCommand[] {
335
+ return [
336
+ {
337
+ cmd: 'systemctl',
338
+ args: ['enable', BUSINESS_SERVICE_NAME, TOOL_SERVICE_NAME],
339
+ label: 'enable services',
340
+ },
341
+ {
342
+ cmd: 'systemctl',
343
+ args: ['restart', BUSINESS_SERVICE_NAME, TOOL_SERVICE_NAME],
344
+ label: 'restart services',
345
+ },
346
+ ];
347
+ }
348
+
349
+ // One joint restart call removes the serial-restart failure window (the
350
+ // first restart succeeding and the second erroring, leaving one unit
351
+ // restarted and the other untouched). It is not a transaction: systemd
352
+ // enqueues the two units' jobs independently, so a mid-call failure can
353
+ // still land between them — but any failure aborts the install at
354
+ // runOrDie before "install complete" is ever printed.
355
+ function startServices(): void {
356
+ for (const { cmd, args, label } of planServiceCommands()) {
357
+ runOrDie(cmd, args, label);
358
+ }
359
+ }
360
+
361
+ function waitHealthy(port: number, timeoutMs = 15000): boolean {
362
+ const deadline = Date.now() + timeoutMs;
363
+ while (Date.now() < deadline) {
364
+ const res = run('curl', ['-fsS', `http://127.0.0.1:${port}/health`]);
365
+ if (res.ok && res.out.includes('"ok"')) return true;
366
+ const sleep = run('sleep', ['1']);
367
+ if (!sleep.ok) break;
368
+ }
369
+ return false;
370
+ }
371
+
372
+ // The installer never mutates firewall state — punching network holes is a
373
+ // security decision the operator makes knowingly. When firewalld is active
374
+ // we print the exact commands so the step is copy-paste instead of research.
375
+ function printFirewallHint(port: number, toolPort: number): void {
376
+ const state = run('firewall-cmd', ['--state']);
377
+ if (state.ok && state.out === 'running') {
378
+ console.log('\nFirewalld is active on this host; the installer did not change firewall rules.');
379
+ console.log('Open the service ports yourself if external access is intended:');
380
+ console.log(` firewall-cmd --permanent --add-port=${port}/tcp`);
381
+ console.log(` firewall-cmd --permanent --add-port=${toolPort}/tcp`);
382
+ console.log(' firewall-cmd --reload');
383
+ } else {
384
+ console.log(
385
+ '\nNote: firewall rules were not changed. If external clients will connect, open the service ports per your distro (firewalld/ufw/iptables).',
386
+ );
387
+ }
388
+ }
389
+
390
+ // ---------------------------------------------------------------------------
391
+ // CLI entry points
392
+ // ---------------------------------------------------------------------------
393
+
394
+ export async function installServerCli(argv: readonly string[] = []): Promise<void> {
395
+ ensureLinux();
396
+ ensureRoot();
397
+ const opts = parseServerInstallArgs(argv);
398
+ const installPath = resolve(opts.installPath);
399
+ console.log(`Installing HuaweiCloud DevKit server under ${installPath}`);
400
+ console.log(` business port: ${opts.port} tool port: ${opts.toolPort} service user: ${opts.user}`);
401
+
402
+ ensureUser(opts.user);
403
+ const nodePath = resolveSystemNode() || provisionNode(installPath);
404
+ const app = installAppDir(installPath, opts.user);
405
+ const pwFile = writePasswordFile(installPath, opts.user, opts.rotatePassword);
406
+ writeUnits(installPath, { nodePath, app, port: opts.port, toolPort: opts.toolPort, user: opts.user, pwFile });
407
+ startServices();
408
+
409
+ const okBusiness = waitHealthy(opts.port);
410
+ const okTool = waitHealthy(opts.toolPort);
411
+ if (!okBusiness || !okTool) {
412
+ const failed = !okBusiness ? BUSINESS_SERVICE_NAME : TOOL_SERVICE_NAME;
413
+ console.log(` warning: ${failed} did not report healthy yet; inspect with: journalctl -u ${failed} -n 50`);
414
+ }
415
+
416
+ console.log('\nServer install complete:');
417
+ console.log(` install path : ${installPath}/devkit/app`);
418
+ console.log(` service user : ${opts.user}`);
419
+ console.log(` business svc : ${BUSINESS_SERVICE_NAME} -> 0.0.0.0:${opts.port}`);
420
+ console.log(` tool svc : ${TOOL_SERVICE_NAME} -> 0.0.0.0:${opts.toolPort}`);
421
+ console.log(` auth password: ${pwFile} (0600; header: Authorization: Bearer <password> or x-devkit-password)`);
422
+ console.log(' health check : GET http://127.0.0.1:<port>/health');
423
+ printFirewallHint(opts.port, opts.toolPort);
424
+ }
425
+
426
+ export async function uninstallServerCli(argv: readonly string[] = []): Promise<void> {
427
+ ensureLinux();
428
+ ensureRoot();
429
+ const opts = parseServerInstallArgs(argv);
430
+ run('systemctl', ['disable', '--now', BUSINESS_SERVICE_NAME]);
431
+ run('systemctl', ['disable', '--now', TOOL_SERVICE_NAME]);
432
+ for (const unit of [BUSINESS_SERVICE_NAME, TOOL_SERVICE_NAME]) {
433
+ rmSync(`/etc/systemd/system/${unit}`, { force: true });
434
+ }
435
+ run('systemctl', ['daemon-reload']);
436
+ rmSync(join(opts.installPath, 'devkit'), { recursive: true, force: true });
437
+ if (opts.removeUser) {
438
+ run('userdel', [opts.user]);
439
+ console.log(`removed service user: ${opts.user}`);
440
+ }
441
+ console.log('HuaweiCloud DevKit server uninstalled.');
442
+ }