sap-adt-cli 1.5.3 → 1.6.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 CHANGED
@@ -11,8 +11,12 @@ instead.
11
11
 
12
12
  Linux x86_64 and Windows x86_64 runtimes are provided. Windows support
13
13
  starts with package 1.5.3 and also requires `tar.exe` (included in current
14
- Windows 10/11). macOS has no self-contained runtime yet; use the Python
15
- package there. Upgrading an older Windows launcher requires reinstalling
14
+ Windows 10/11). From 1.6.0, experimental macOS 15+ runtimes cover Intel
15
+ (`darwin-x86_64`) and Apple Silicon (`darwin-aarch64`). Native CI builds and
16
+ isolated npm installations gate publication; personal Macs, older macOS,
17
+ Keychain, Gatekeeper/quarantine, signing/notarization and live SAP on macOS
18
+ remain unverified. The Python package is an alternative.
19
+ Upgrading an older launcher requires reinstalling
16
20
  the npm package before running `sap-adt install` again.
17
21
 
18
22
  ## Install the runtime (once)
@@ -40,9 +44,28 @@ artifact over HTTPS, verifies its SHA-256 (from the manifest bundled with
40
44
  the package — never from the download endpoint), extracts safely and swaps
41
45
  it in atomically, then self-tests with the absolute install path.
42
46
 
43
- On a proxied network, set `HTTPS_PROXY` (and `NO_PROXY` for hosts that go
44
- direct) before running `install`; the wizard tunnels through an `http://`
45
- proxy, reports download progress, and aborts on a timeout instead of hanging.
47
+ From 1.6.0, the installer selects an explicit proxy environment
48
+ variable first, then npm's persistent proxy settings, then Windows current-user
49
+ manual proxy settings. It respects `NO_PROXY` and Windows manual bypass rules.
50
+ It prints the selected route without credentials, bounds connection setup
51
+ to 30 seconds, and aborts stalled downloads after 60 seconds of inactivity.
52
+ System settings are never modified. PAC/WPAD scripts, SOCKS and integrated
53
+ NTLM/Kerberos proxy authentication are not evaluated or enabled automatically.
54
+
55
+ For older installers or Linux/macOS desktop-only proxies, set `HTTPS_PROXY`
56
+ (and `NO_PROXY` for hosts that go direct) before `install`.
57
+ An `http://` CONNECT proxy is required; interception
58
+ proxies need their CA configured with `NODE_EXTRA_CA_CERTS`, not disabled TLS.
59
+
60
+ The installer retains the previous runtime until the new self-test
61
+ succeeds, restores it on failure and reports a retained backup if recovery
62
+ is blocked. Extraction/self-test are limited to 120/60 seconds, configurable
63
+ through `SAP_ADT_INSTALL_EXTRACT_TIMEOUT_MS` /
64
+ `SAP_ADT_INSTALL_SELFTEST_TIMEOUT_MS`. Failures include actionable network,
65
+ CA, permission, disk and OS-runtime hints; unsupported platforms get Python
66
+ venv instructions. The update launcher passes discovered Windows
67
+ manual proxies to npm's registry/package steps too, without changing user
68
+ configuration. Bootstrap `npm install` remains npm's own operation.
46
69
 
47
70
  ## Use
48
71
 
@@ -57,7 +80,25 @@ With npx, prefix each command: `npx "sap-adt-cli@^1.5.0" <command>`.
57
80
 
58
81
  Configuration and credentials live in `~/.sap-adt-cli/` and the OS keystore —
59
82
  never inside this package. Upgrading the npm package requires re-running
60
- `install` (the runtime slot lives next to the launcher).
83
+ `install` (the runtime slot lives next to the launcher). From 1.6.0,
84
+ `sap-adt update` handles both steps for a confirmed global npm installation.
85
+
86
+ ## Explicit updates (1.6.0+)
87
+
88
+ ```bash
89
+ sap-adt update --check
90
+ sap-adt update # preview + confirmation, current major only
91
+ sap-adt update --yes # explicit approval for automation
92
+ ```
93
+
94
+ The launcher first stages and verifies the new runtime, then updates this
95
+ global package and verifies the final version. It replaces files only after
96
+ the frozen runtime has exited. Staging failures keep the existing install;
97
+ the npm commit itself is not a full transaction, and later errors provide
98
+ repair instructions. Local/workspace installs and npx get guidance instead
99
+ of being silently rewritten. No SAP config or credentials are needed.
100
+ `--major` explicitly allows a new major, outside the default skill range.
101
+ Older versions need one manual package upgrade to obtain this command.
61
102
 
62
103
  ## Security model notes
63
104
 
@@ -66,7 +107,8 @@ never inside this package. Upgrading the npm package requires re-running
66
107
  for a fresh `[y/N]` confirmation per operation.
67
108
  - The installer refuses digest mismatches, unsupported platforms, non-HTTPS
68
109
  or unlisted redirect hosts, and archives with path traversal or symlinks.
69
- - A normal `sap-adt` invocation never downloads or upgrades anything.
110
+ - Normal SAP commands never download or upgrade anything; only explicit
111
+ `install` and confirmed `update` requests do.
70
112
 
71
113
  Package versions track the CLI version exactly; installing version X always
72
114
  installs runtime X (no `latest` surprises).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sap-adt-cli",
3
- "version": "1.5.3",
3
+ "version": "1.6.0",
4
4
  "description": "Installer and launcher for the self-contained sap-adt CLI (SAP ADT REST API). No Python required; Node.js >=18 needed for this npm channel only.",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -1,12 +1,34 @@
1
1
  {
2
- "cli_version": "1.5.3",
2
+ "cli_version": "1.6.0",
3
3
  "release_state": "published",
4
4
  "artifacts": {
5
+ "darwin-aarch64": {
6
+ "url": "https://github.com/shrek-abaper/sap-engineering-skill/releases/download/sap-adt-v1.6.0/sap-adt-1.6.0-darwin-aarch64.tar.gz",
7
+ "sha256": "945438100a560a89a33ae44c5b6571bdfd0d3bcd7accc817a4fec794edce6f03",
8
+ "format": "tar.gz",
9
+ "size_bytes": 24963794,
10
+ "allowed_redirect_hosts": [
11
+ "github.com",
12
+ "release-assets.githubusercontent.com",
13
+ "objects.githubusercontent.com"
14
+ ]
15
+ },
16
+ "darwin-x86_64": {
17
+ "url": "https://github.com/shrek-abaper/sap-engineering-skill/releases/download/sap-adt-v1.6.0/sap-adt-1.6.0-darwin-x86_64.tar.gz",
18
+ "sha256": "16fdbe688c0dd35696171769eba1161ccfa43383d5da3dc2d8f7613c655bab59",
19
+ "format": "tar.gz",
20
+ "size_bytes": 24065117,
21
+ "allowed_redirect_hosts": [
22
+ "github.com",
23
+ "release-assets.githubusercontent.com",
24
+ "objects.githubusercontent.com"
25
+ ]
26
+ },
5
27
  "linux-x86_64": {
6
- "url": "https://github.com/shrek-abaper/sap-engineering-skill/releases/download/sap-adt-v1.5.3/sap-adt-1.5.3-linux-x86_64.tar.gz",
7
- "sha256": "19d13fc0512265b2612bb8b01d3a45592e6eecfbdeb108ba4ddb1679cf27476d",
28
+ "url": "https://github.com/shrek-abaper/sap-engineering-skill/releases/download/sap-adt-v1.6.0/sap-adt-1.6.0-linux-x86_64.tar.gz",
29
+ "sha256": "ab1dd95e294834929a36b8bb9fde0afd48cf9d4204db56cb937bc0cf15e200f0",
8
30
  "format": "tar.gz",
9
- "size_bytes": 16557337,
31
+ "size_bytes": 16590088,
10
32
  "allowed_redirect_hosts": [
11
33
  "github.com",
12
34
  "release-assets.githubusercontent.com",
@@ -14,10 +36,10 @@
14
36
  ]
15
37
  },
16
38
  "windows-x86_64": {
17
- "url": "https://github.com/shrek-abaper/sap-engineering-skill/releases/download/sap-adt-v1.5.3/sap-adt-1.5.3-windows-x86_64.zip",
18
- "sha256": "5989c1d65a4c202e925c48ad825b8350caf4440b9aca6706df31eb3c6984b152",
39
+ "url": "https://github.com/shrek-abaper/sap-engineering-skill/releases/download/sap-adt-v1.6.0/sap-adt-1.6.0-windows-x86_64.zip",
40
+ "sha256": "5dee03b7dadfe0e8ecb233c76bd751433a07fdfe071df53111d1a9aea830a87a",
19
41
  "format": "zip",
20
- "size_bytes": 15569808,
42
+ "size_bytes": 15604192,
21
43
  "allowed_redirect_hosts": [
22
44
  "github.com",
23
45
  "release-assets.githubusercontent.com",
@@ -13,8 +13,8 @@
13
13
  * explicitly allow-listed redirect host in the manifest
14
14
  * - extraction rejects absolute paths, ".." traversal, and symlinks
15
15
  * - no curl|sh, no shell:true, no string-concatenated commands
16
- * - the only network egress is the artifact download, through the proxy
17
- * named by HTTPS_PROXY/HTTP_PROXY when the environment sets one
16
+ * - the only network egress is the artifact download, through the selected
17
+ * environment, npm or Windows manual proxy (PAC scripts are never run)
18
18
  *
19
19
  * Test seam: file:// artifact URLs are accepted ONLY when the environment
20
20
  * variable SAP_ADT_INSTALL_ALLOW_FILE=1 is set (local packaging tests).
@@ -33,15 +33,28 @@ const tls = require("node:tls");
33
33
  const { Transform } = require("node:stream");
34
34
  const { pipeline } = require("node:stream/promises");
35
35
  const { fileURLToPath } = require("node:url");
36
+ const { findNpm, childEnv, installationHint, safeMessage } = require("./npm.js");
36
37
 
37
38
  const PKG_DIR = path.resolve(__dirname, "..");
38
39
  const MAX_REDIRECTS = 3;
39
40
  // Node's core https client ignores HTTPS_PROXY before v24, so a blocked
40
- // direct route hung this wizard forever. Both timers are inactivity-based:
41
- // a slow but progressing download is never aborted.
41
+ // direct route hung this wizard forever. Connection setup has a hard deadline;
42
+ // after connecting, an idle timeout permits slow but progressing downloads.
42
43
  const CONNECT_TIMEOUT_MS = intEnv("SAP_ADT_INSTALL_CONNECT_TIMEOUT_MS", 30_000);
43
- const IDLE_TIMEOUT_MS = 60_000;
44
+ const IDLE_TIMEOUT_MS = intEnv("SAP_ADT_INSTALL_IDLE_TIMEOUT_MS", 60_000);
45
+ const EXTRACT_TIMEOUT_MS = intEnv("SAP_ADT_INSTALL_EXTRACT_TIMEOUT_MS", 120_000);
46
+ const SELFTEST_TIMEOUT_MS = intEnv("SAP_ADT_INSTALL_SELFTEST_TIMEOUT_MS", 60_000);
44
47
  const PROGRESS_INTERVAL_MS = 5_000;
48
+ const PROXY_NAMES = [
49
+ "https_proxy", "HTTPS_PROXY", "npm_config_https_proxy", "npm_config_proxy",
50
+ "http_proxy", "HTTP_PROXY", "all_proxy", "ALL_PROXY",
51
+ ];
52
+ const NO_PROXY_NAMES = ["no_proxy", "NO_PROXY", "npm_config_noproxy"];
53
+ const WINDOWS_PROXY_SCRIPT = `
54
+ [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)
55
+ $p = Get-ItemProperty -LiteralPath 'HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings' -ErrorAction SilentlyContinue
56
+ @{enabled=($p.ProxyEnable -eq 1);server=[string]$p.ProxyServer;bypass=[string]$p.ProxyOverride;automatic=([bool]$p.AutoConfigURL -or [bool]$p.AutoDetect)} | ConvertTo-Json -Compress
57
+ `;
45
58
 
46
59
  function intEnv(name, fallback) {
47
60
  const raw = process.env[name];
@@ -51,7 +64,8 @@ function intEnv(name, fallback) {
51
64
  }
52
65
 
53
66
  function fail(message, code = 1) {
54
- process.stderr.write(`[sap-adt install] ERROR: ${message}\n`);
67
+ process.stderr.write(`[sap-adt install] ERROR: ${safeMessage(message)}\n` +
68
+ `Hint: ${message?.hint || installationHint(message)}\n`);
55
69
  process.exit(code);
56
70
  }
57
71
 
@@ -105,21 +119,94 @@ function firstEnv(env, names) {
105
119
  return "";
106
120
  }
107
121
 
122
+ function resolveProxySettings(env = process.env, platform = process.platform, run = spawnSync) {
123
+ if (firstEnv(env, PROXY_NAMES)) return { env, source: "environment" };
124
+ const resolved = { ...env };
125
+ const options = { env: childEnv(env), encoding: "utf8", timeout: 10_000, windowsHide: true };
126
+ const npm = findNpm(env);
127
+ if (npm) {
128
+ // Read only proxy keys, never npm's full config (which can contain tokens).
129
+ const result = run(process.execPath, [npm, "config", "get", "https-proxy", "proxy", "noproxy"], options);
130
+ if (result.error || result.status !== 0) {
131
+ throw new Error("Cannot read npm proxy settings within 10 seconds; set HTTPS_PROXY explicitly.");
132
+ }
133
+ const config = {};
134
+ for (const line of result.stdout.split(/\r?\n/)) {
135
+ const match = /^(https-proxy|proxy|noproxy)=(.*)$/.exec(line);
136
+ if (match) config[match[1]] = ["null", "undefined"].includes(match[2].trim()) ? "" : match[2].trim();
137
+ }
138
+ if (!firstEnv(resolved, NO_PROXY_NAMES) && config.noproxy) resolved.no_proxy = config.noproxy;
139
+ const proxy = config["https-proxy"] || config.proxy;
140
+ if (proxy) {
141
+ resolved.https_proxy = proxy;
142
+ return { env: resolved, source: "npm configuration" };
143
+ }
144
+ }
145
+ if (platform === "win32") {
146
+ const powershell = path.join(env.SystemRoot || "C:\\Windows", "System32",
147
+ "WindowsPowerShell", "v1.0", "powershell.exe");
148
+ const result = run(powershell,
149
+ ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_PROXY_SCRIPT], options);
150
+ if (result.error || result.status !== 0) {
151
+ throw new Error("Cannot read Windows proxy settings within 10 seconds; set HTTPS_PROXY explicitly.");
152
+ }
153
+ let settings;
154
+ try {
155
+ settings = JSON.parse(result.stdout.replace(/^\uFEFF/, "").trim());
156
+ if (!settings || typeof settings !== "object") throw new Error("missing settings");
157
+ } catch {
158
+ throw new Error("Cannot parse Windows proxy settings; set HTTPS_PROXY explicitly.");
159
+ }
160
+ if (settings.automatic) {
161
+ throw new Error("Windows PAC/WPAD automatic proxy settings are not evaluated. " +
162
+ "Set HTTPS_PROXY=http://host:port explicitly; no PAC script was downloaded or executed.");
163
+ }
164
+ if (settings.enabled && settings.server) {
165
+ const server = String(settings.server).trim();
166
+ const parts = server.split(";").map((part) => part.trim()).filter(Boolean);
167
+ const proxy = parts.some((part) => part.includes("="))
168
+ ? parts.find((part) => /^https\s*=/i.test(part))?.replace(/^https\s*=\s*/i, "")
169
+ : server;
170
+ if (!proxy) {
171
+ throw new Error("Windows has no manual HTTPS proxy endpoint; set HTTPS_PROXY to an HTTP CONNECT proxy.");
172
+ }
173
+ resolved.https_proxy = proxy;
174
+ if (!firstEnv(resolved, NO_PROXY_NAMES) && settings.bypass) {
175
+ resolved.no_proxy = String(settings.bypass).replace(/;/g, ",");
176
+ }
177
+ return { env: resolved, source: "Windows user proxy settings" };
178
+ }
179
+ }
180
+ return { env: resolved, source: "direct (no proxy configured)" };
181
+ }
182
+
183
+ function npmEnvironment(env = process.env, platform = process.platform, run = spawnSync) {
184
+ const network = resolveProxySettings(env, platform, run);
185
+ const resolved = childEnv(network.env);
186
+ if (network.source === "Windows user proxy settings") {
187
+ const raw = firstEnv(network.env, PROXY_NAMES);
188
+ const proxy = raw.includes("://") ? raw : `http://${raw}`;
189
+ resolved.npm_config_https_proxy = proxy;
190
+ resolved.npm_config_proxy = proxy;
191
+ resolved.npm_config_noproxy = firstEnv(network.env, NO_PROXY_NAMES);
192
+ }
193
+ return resolved;
194
+ }
195
+
108
196
  /* Proxy for a target URL, or null when the request should go direct.
109
197
  * Honors the usual spellings plus npm's own config variables; `env` is
110
198
  * injectable so the tests never depend on the machine's network. */
111
199
  function proxyForUrl(targetUrl, env = process.env) {
112
- const raw = firstEnv(env, [
113
- "https_proxy", "HTTPS_PROXY", "npm_config_https_proxy", "npm_config_proxy",
114
- "http_proxy", "HTTP_PROXY",
115
- ]);
200
+ const target = new URL(targetUrl);
201
+ if (bypassesProxy(target.hostname, target.port || "443", firstEnv(env, NO_PROXY_NAMES))) return null;
202
+ const raw = firstEnv(env, PROXY_NAMES);
116
203
  if (!raw) return null;
117
204
 
118
205
  let proxy;
119
206
  try {
120
207
  proxy = new URL(raw.includes("://") ? raw : `http://${raw}`);
121
208
  } catch {
122
- throw new Error(`HTTPS_PROXY is not a valid URL (got "${raw.replace(/:[^:@/]*@/, ":***@")}")`);
209
+ throw new Error("Proxy is not a valid URL; set HTTPS_PROXY=http://host:port and URL-encode credentials.");
123
210
  }
124
211
  // Only plain HTTP CONNECT proxies: TLS-to-the-proxy would need TLS-in-TLS,
125
212
  // and refusing loudly beats a half-working tunnel.
@@ -127,9 +214,7 @@ function proxyForUrl(targetUrl, env = process.env) {
127
214
  throw new Error(`unsupported proxy scheme "${proxy.protocol}" in HTTPS_PROXY (only http:// proxies are supported)`);
128
215
  }
129
216
 
130
- const target = new URL(targetUrl);
131
- const noProxy = firstEnv(env, ["no_proxy", "NO_PROXY", "npm_config_noproxy"]);
132
- return bypassesProxy(target.hostname, target.port || "443", noProxy) ? null : proxy;
217
+ return proxy;
133
218
  }
134
219
 
135
220
  function bypassesProxy(hostname, port, noProxy) {
@@ -139,6 +224,7 @@ function bypassesProxy(hostname, port, noProxy) {
139
224
  entry = entry.trim().toLowerCase();
140
225
  if (!entry) continue;
141
226
  if (entry === "*") return true;
227
+ if (entry === "<local>" && !net.isIP(host) && !host.includes(".")) return true;
142
228
  // "host:port" (never "::1" — the host part must be colon-free)
143
229
  const withPort = /^([^:]+):(\d+)$/.exec(entry);
144
230
  if (withPort) {
@@ -171,8 +257,9 @@ function fmtBytes(n) {
171
257
 
172
258
  /* HTTPS through an HTTP(S) proxy: CONNECT tunnel, then TLS to the target so
173
259
  * the certificate is still verified against the real host name. */
174
- function openTunnel(proxy, host, port) {
260
+ function openTunnel(proxy, host, port, signal) {
175
261
  return new Promise((resolve, reject) => {
262
+ host = host.replace(/^\[|\]$/g, "");
176
263
  const target = net.isIP(host) === 6 ? `[${host}]` : host;
177
264
  const headers = { Host: `${target}:${port}` };
178
265
  if (proxy.username) {
@@ -182,15 +269,21 @@ function openTunnel(proxy, host, port) {
182
269
  `Basic ${Buffer.from(`${user}:${pass}`).toString("base64")}`;
183
270
  }
184
271
  const req = http.request({
185
- host: proxy.hostname,
272
+ host: proxy.hostname.replace(/^\[|\]$/g, ""),
186
273
  port: proxy.port || 80,
187
274
  method: "CONNECT",
188
275
  path: `${target}:${port}`,
189
276
  headers,
190
277
  agent: false,
191
278
  timeout: CONNECT_TIMEOUT_MS,
279
+ signal,
192
280
  });
193
- req.on("connect", (res, socket) => {
281
+ const deadline = setTimeout(() => req.destroy(new Error(
282
+ `proxy CONNECT to ${proxy.host} timed out after ${CONNECT_TIMEOUT_MS} ms — ` +
283
+ "check HTTPS_PROXY/NO_PROXY and that the proxy allows CONNECT")), CONNECT_TIMEOUT_MS);
284
+ req.on("connect", (res, socket, head) => {
285
+ clearTimeout(deadline);
286
+ req.setTimeout(0);
194
287
  if (res.statusCode === 407) {
195
288
  socket.destroy();
196
289
  return reject(new Error(
@@ -202,24 +295,39 @@ function openTunnel(proxy, host, port) {
202
295
  return reject(new Error(
203
296
  `proxy CONNECT ${proxy.host} -> ${target}:${port} failed: HTTP ${res.statusCode}`));
204
297
  }
298
+ if (head.length) socket.unshift(head);
205
299
  const secure = tls.connect({
206
300
  socket,
301
+ host,
207
302
  servername: net.isIP(host) ? undefined : host,
208
303
  });
209
- secure.setTimeout(CONNECT_TIMEOUT_MS, () => secure.destroy(new Error(
210
- `TLS handshake with ${target} through the proxy timed out after ${CONNECT_TIMEOUT_MS} ms`)));
304
+ const abort = () => secure.destroy(new Error("Proxy TLS connection cancelled."));
305
+ signal.addEventListener("abort", abort, { once: true });
306
+ if (signal.aborted) abort();
307
+ const handshake = setTimeout(() => secure.destroy(new Error(
308
+ `TLS handshake with ${target} through the proxy timed out after ${CONNECT_TIMEOUT_MS} ms`)),
309
+ CONNECT_TIMEOUT_MS);
310
+ const cleanup = () => {
311
+ clearTimeout(handshake);
312
+ signal.removeEventListener("abort", abort);
313
+ };
211
314
  secure.once("secureConnect", () => {
212
- secure.setTimeout(0);
315
+ cleanup();
213
316
  resolve(secure);
214
317
  });
215
- secure.once("error", (e) => reject(new Error(
216
- `TLS handshake with ${target} through the proxy failed: ${e.message} ` +
217
- "(a TLS-intercepting proxy needs NODE_EXTRA_CA_CERTS pointing at its CA)")));
318
+ secure.once("error", (e) => {
319
+ cleanup();
320
+ reject(new Error(`TLS handshake with ${target} through the proxy failed: ${e.message} ` +
321
+ "(a TLS-intercepting proxy needs NODE_EXTRA_CA_CERTS pointing at its CA)"));
322
+ });
218
323
  });
219
324
  req.on("timeout", () => req.destroy(new Error(
220
325
  `proxy CONNECT to ${proxy.host} timed out after ${CONNECT_TIMEOUT_MS} ms — ` +
221
326
  "check HTTPS_PROXY/NO_PROXY and that the proxy allows CONNECT")));
222
- req.on("error", reject);
327
+ req.on("error", (error) => {
328
+ clearTimeout(deadline);
329
+ reject(error);
330
+ });
223
331
  req.end();
224
332
  });
225
333
  }
@@ -228,16 +336,22 @@ class TunnelAgent extends https.Agent {
228
336
  constructor(proxy) {
229
337
  super({ keepAlive: false, maxSockets: 1 });
230
338
  this.proxy = proxy;
339
+ this.controller = new AbortController();
231
340
  }
232
341
 
233
342
  // Node's Agent contract: a 2-argument createConnection is the async form.
234
343
  createConnection(options, cb) {
235
344
  const host = options.servername || options.host;
236
- openTunnel(this.proxy, host, options.port || 443).then(
345
+ openTunnel(this.proxy, host, options.port || 443, this.controller.signal).then(
237
346
  (socket) => cb(null, socket),
238
347
  cb,
239
348
  );
240
349
  }
350
+
351
+ destroy() {
352
+ this.controller.abort();
353
+ super.destroy();
354
+ }
241
355
  }
242
356
 
243
357
  function timeoutHint(target, proxy) {
@@ -245,10 +359,10 @@ function timeoutHint(target, proxy) {
245
359
  const advice = proxy
246
360
  ? "check HTTPS_PROXY or add this host to NO_PROXY"
247
361
  : "if this network requires a proxy, set HTTPS_PROXY=http://host:port";
248
- return `timed out after ${IDLE_TIMEOUT_MS} ms connecting to ${target}${via} — ${advice}`;
362
+ return `timed out after ${IDLE_TIMEOUT_MS} ms waiting for data from ${target}${via} — ${advice}`;
249
363
  }
250
364
 
251
- function download(url, allowedHosts, dest, redirectsLeft) {
365
+ function download(url, allowedHosts, dest, redirectsLeft, network) {
252
366
  return new Promise((resolve, reject) => {
253
367
  const parsed = new URL(url);
254
368
  if (parsed.protocol === "file:") {
@@ -265,34 +379,46 @@ function download(url, allowedHosts, dest, redirectsLeft) {
265
379
  if (!allowedHosts.includes(parsed.host)) {
266
380
  return reject(new Error(`artifact host not allow-listed: ${parsed.host}`));
267
381
  }
268
- const proxy = proxyForUrl(url);
269
- const options = { timeout: IDLE_TIMEOUT_MS };
382
+ const proxy = proxyForUrl(url, network.env);
383
+ const agent = proxy ? new TunnelAgent(proxy) : new https.Agent({ keepAlive: false });
384
+ const options = { timeout: IDLE_TIMEOUT_MS, agent };
270
385
  if (proxy) {
271
- info(`using proxy ${proxy.host} for ${parsed.host}`);
272
- options.agent = new TunnelAgent(proxy);
386
+ info(`using proxy ${proxy.host} for ${parsed.host} (${network.source})`);
387
+ } else {
388
+ info(`direct connection to ${parsed.host}${firstEnv(network.env, NO_PROXY_NAMES) ? " (proxy bypass/no proxy)" : ""}`);
273
389
  }
274
-
390
+ let deadline;
391
+ const cleanup = () => {
392
+ clearTimeout(deadline);
393
+ agent.destroy();
394
+ };
395
+ const failDownload = (error) => {
396
+ cleanup();
397
+ reject(error);
398
+ };
275
399
  const req = https.get(url, options, (res) => {
400
+ clearTimeout(deadline);
276
401
  if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
277
402
  res.resume();
278
- if (redirectsLeft <= 0) return reject(new Error("too many redirects"));
403
+ if (redirectsLeft <= 0) return failDownload(new Error("too many redirects"));
279
404
  let next;
280
405
  try {
281
406
  next = new URL(res.headers.location, url);
282
407
  } catch {
283
- return reject(new Error("invalid redirect location"));
408
+ return failDownload(new Error("invalid redirect location"));
284
409
  }
285
410
  if (next.protocol !== "https:") {
286
- return reject(new Error(`refusing redirect to non-HTTPS: ${next}`));
411
+ return failDownload(new Error(`refusing redirect to non-HTTPS: ${next}`));
287
412
  }
288
413
  if (!allowedHosts.includes(next.host)) {
289
- return reject(new Error(`refusing redirect to non-allow-listed host: ${next.host}`));
414
+ return failDownload(new Error(`refusing redirect to non-allow-listed host: ${next.host}`));
290
415
  }
291
- return resolve(download(next.toString(), allowedHosts, dest, redirectsLeft - 1));
416
+ cleanup();
417
+ return resolve(download(next.toString(), allowedHosts, dest, redirectsLeft - 1, network));
292
418
  }
293
419
  if (res.statusCode !== 200) {
294
420
  res.resume();
295
- return reject(new Error(`download failed: HTTP ${res.statusCode}`));
421
+ return failDownload(new Error(`download failed: HTTP ${res.statusCode}`));
296
422
  }
297
423
  const total = Number(res.headers["content-length"]) || 0;
298
424
  info(`downloading ${total ? fmtBytes(total) : "artifact"}${proxy ? ` via ${proxy.host}` : ""}`);
@@ -315,10 +441,21 @@ function download(url, allowedHosts, dest, redirectsLeft) {
315
441
  callback();
316
442
  },
317
443
  });
318
- pipeline(res, counter, fs.createWriteStream(dest)).then(resolve, reject);
444
+ pipeline(res, counter, fs.createWriteStream(dest)).then(() => {
445
+ cleanup();
446
+ resolve();
447
+ }, failDownload);
448
+ });
449
+ deadline = setTimeout(() => req.destroy(new Error(
450
+ `connection to ${parsed.host} timed out after ${CONNECT_TIMEOUT_MS} ms` +
451
+ `${proxy ? " through the selected proxy; check HTTPS_PROXY/NO_PROXY" : "; configure HTTPS_PROXY if a proxy is required"}`)),
452
+ CONNECT_TIMEOUT_MS);
453
+ req.on("socket", (socket) => {
454
+ if (proxy) clearTimeout(deadline); // TunnelAgent hands back an established TLS socket.
455
+ else socket.once("secureConnect", () => clearTimeout(deadline));
319
456
  });
320
457
  req.on("timeout", () => req.destroy(new Error(timeoutHint(parsed.host, proxy))));
321
- req.on("error", reject);
458
+ req.on("error", failDownload);
322
459
  });
323
460
  }
324
461
 
@@ -334,14 +471,23 @@ function sha256File(file) {
334
471
 
335
472
  /* Extract with tar (bsdtar on Windows handles .zip too) via an argument
336
473
  * array — never a shell. Then walk entries rejecting traversal/symlinks. */
337
- function extract(archive, format, destDir) {
474
+ function extract(archive, format, destDir, run = spawnSync) {
338
475
  fs.mkdirSync(destDir, { recursive: true });
339
476
  const args = format === "zip"
340
477
  ? ["-xf", archive, "-C", destDir]
341
478
  : ["-xzf", archive, "-C", destDir];
342
- const result = spawnSync("tar", args, { encoding: "utf8" });
343
- if (result.error) throw new Error(`tar unavailable: ${result.error.message}`);
344
- if (result.status !== 0) throw new Error(`tar failed: ${result.stderr.trim()}`);
479
+ const result = run("tar", args, {
480
+ encoding: "utf8", timeout: EXTRACT_TIMEOUT_MS, killSignal: "SIGKILL", windowsHide: true,
481
+ });
482
+ if (result.error?.code === "ETIMEDOUT") {
483
+ throw new Error(`Archive extraction timed out after ${EXTRACT_TIMEOUT_MS} ms.`);
484
+ }
485
+ if (result.error) throw new Error(`tar unavailable: ${safeMessage(result.error)}`);
486
+ if (result.status !== 0) {
487
+ const error = new Error(`Archive extraction failed (exit ${result.status}).`);
488
+ error.hint = installationHint(result.stderr || "extract");
489
+ throw error;
490
+ }
345
491
 
346
492
  for (const entry of fs.readdirSync(destDir, { recursive: true })) {
347
493
  const full = path.join(destDir, entry);
@@ -356,11 +502,24 @@ function extract(archive, format, destDir) {
356
502
  }
357
503
  }
358
504
 
505
+ function renameRuntime(from, to) {
506
+ for (let attempt = 0; ; attempt++) {
507
+ try {
508
+ return fs.renameSync(from, to);
509
+ } catch (error) {
510
+ // Windows scanners can retain short-lived handles after a child exits.
511
+ if (process.platform !== "win32" || attempt >= 20 ||
512
+ !["EACCES", "EPERM", "EBUSY"].includes(error.code)) throw error;
513
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100);
514
+ }
515
+ }
516
+ }
517
+
359
518
  /* Rename, or copy when staging and target sit on different filesystems
360
519
  * (os.tmpdir() is tmpfs on many Linux/WSL setups → EXDEV). */
361
520
  function moveTree(staging, target) {
362
521
  try {
363
- fs.renameSync(staging, target);
522
+ renameRuntime(staging, target);
364
523
  } catch (e) {
365
524
  if (e.code !== "EXDEV") throw e;
366
525
  fs.cpSync(staging, target, { recursive: true });
@@ -370,21 +529,62 @@ function moveTree(staging, target) {
370
529
 
371
530
  /* Swap runtime atomically-ish: stage -> rename old aside -> rename new in ->
372
531
  * on any failure, restore the old one and leave it working. */
373
- function installTree(staging, runtimeDir) {
374
- const backup = `${runtimeDir}.old-${process.pid}`;
532
+ function installTree(staging, runtimeDir, validate = () => {}) {
533
+ const backup = `${runtimeDir}.old-${process.pid}-${crypto.randomBytes(6).toString("hex")}`;
375
534
  let movedOld = false;
535
+ let replacing = false;
376
536
  try {
377
537
  if (fs.existsSync(runtimeDir)) {
378
- fs.renameSync(runtimeDir, backup);
538
+ renameRuntime(runtimeDir, backup);
379
539
  movedOld = true;
380
540
  }
541
+ replacing = true;
381
542
  moveTree(staging, runtimeDir);
382
- if (movedOld) fs.rmSync(backup, { recursive: true, force: true });
543
+ validate(runtimeDir);
383
544
  } catch (e) {
384
- fs.rmSync(runtimeDir, { recursive: true, force: true });
385
- if (movedOld) fs.renameSync(backup, runtimeDir);
545
+ try {
546
+ if (replacing) fs.rmSync(runtimeDir, { recursive: true, force: true });
547
+ if (movedOld) renameRuntime(backup, runtimeDir);
548
+ } catch {
549
+ e.message += movedOld
550
+ ? ` Rollback incomplete; previous runtime backup is at ${backup}. Restore it before retrying.`
551
+ : ` Cleanup incomplete at ${runtimeDir}; inspect it before retrying.`;
552
+ e.hint = movedOld
553
+ ? `Keep ${backup}. Close file handles and restore it to ${runtimeDir} before retrying.`
554
+ : `Close file handles and inspect the incomplete runtime at ${runtimeDir} before retrying.`;
555
+ e.needsInspection = true;
556
+ throw e;
557
+ }
558
+ e.message += movedOld ? " Previous runtime restored."
559
+ : replacing ? " Failed candidate removed; no runtime was installed."
560
+ : " Existing installation was not replaced.";
386
561
  throw e;
387
562
  }
563
+ if (movedOld) {
564
+ try {
565
+ fs.rmSync(backup, { recursive: true, force: true });
566
+ } catch {
567
+ process.stderr.write(`[sap-adt install] WARNING: verified runtime installed, but backup cleanup ` +
568
+ `failed at ${backup}. Close file handles and remove that backup after verification.\n`);
569
+ }
570
+ }
571
+ }
572
+
573
+ function verifyRuntime(bin, run = spawnSync) {
574
+ const result = run(bin, ["--version"], {
575
+ encoding: "utf8", timeout: SELFTEST_TIMEOUT_MS, killSignal: "SIGKILL", windowsHide: true,
576
+ });
577
+ if (result.error || result.status !== 0) {
578
+ const error = new Error(result.error?.code === "ETIMEDOUT"
579
+ ? `Runtime self-test timed out after ${SELFTEST_TIMEOUT_MS} ms.`
580
+ : `Runtime self-test failed (exit ${result.status ?? result.error?.code ?? "unknown"}).`);
581
+ error.hint = installationHint({
582
+ code: result.error?.code,
583
+ message: `self-test ${result.stderr || ""}`,
584
+ });
585
+ throw error;
586
+ }
587
+ return result.stdout.trim();
388
588
  }
389
589
 
390
590
  async function main() {
@@ -401,11 +601,13 @@ async function main() {
401
601
  try {
402
602
  const archive = path.join(tmp, `artifact.${entry.format === "zip" ? "zip" : "tar.gz"}`);
403
603
  const allowedHosts = [new URL(entry.url).host, ...(entry.allowed_redirect_hosts || [])];
404
- await download(entry.url, allowedHosts, archive, MAX_REDIRECTS);
604
+ const network = new URL(entry.url).protocol === "https:"
605
+ ? resolveProxySettings() : { env: process.env, source: "environment" };
606
+ await download(entry.url, allowedHosts, archive, MAX_REDIRECTS, network);
405
607
 
406
608
  const actual = await sha256File(archive);
407
609
  if (actual.toLowerCase() !== entry.sha256.toLowerCase()) {
408
- fail(`sha256 mismatch: expected ${entry.sha256}, got ${actual}. Nothing was installed.`, 1);
610
+ throw new Error(`sha256 mismatch: expected ${entry.sha256}, got ${actual}. Nothing was installed.`);
409
611
  }
410
612
  info("sha256 verified");
411
613
 
@@ -417,28 +619,30 @@ async function main() {
417
619
  ? path.join(staging, "sap-adt")
418
620
  : staging;
419
621
  if (!fs.existsSync(path.join(treeRoot, exeName))) {
420
- fail(`archive has no ${exeName} at its root`, 1);
622
+ throw new Error(`archive has no ${exeName} at its root`);
421
623
  }
422
624
 
423
625
  const runtimeDir = path.join(PKG_DIR, "runtime", key, "sap-adt");
424
626
  fs.mkdirSync(path.dirname(runtimeDir), { recursive: true });
425
- installTree(treeRoot, runtimeDir);
426
-
427
- const bin = path.join(runtimeDir, exeName);
428
- const selftest = spawnSync(bin, ["--version"], { encoding: "utf8" });
429
- if (selftest.status !== 0) {
430
- fail(`self-test failed (${bin} --version exited ${selftest.status}). Restored previous runtime if any.`, 1);
431
- }
432
- info(`installed ${selftest.stdout.trim() || bin}`);
627
+ let version;
628
+ installTree(treeRoot, runtimeDir, (installed) => {
629
+ version = verifyRuntime(path.join(installed, exeName));
630
+ });
631
+ info(`installed ${version || path.join(runtimeDir, exeName)}`);
433
632
  info("next: sap-adt configure (interactive; password goes to the OS keystore)");
434
633
  } finally {
435
- fs.rmSync(tmp, { recursive: true, force: true });
634
+ try {
635
+ fs.rmSync(tmp, { recursive: true, force: true });
636
+ } catch {
637
+ process.stderr.write(`[sap-adt install] WARNING: temporary files remain at ${tmp}; ` +
638
+ "close file handles and clean up that directory.\n");
639
+ }
436
640
  }
437
641
  }
438
642
 
439
643
  if (require.main === module) {
440
- main().catch((e) => fail(e.message));
644
+ main().catch((e) => fail(e, e.needsInspection ? 3 : 1));
441
645
  }
442
646
 
443
- // Pure helpers only; the wizard itself stays a script.
444
- module.exports = { moveTree, proxyForUrl };
647
+ // Helpers only; the wizard itself stays a script.
648
+ module.exports = { moveTree, installTree, extract, verifyRuntime, proxyForUrl, resolveProxySettings, npmEnvironment };
package/scripts/npm.js ADDED
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+
3
+ const fs = require("node:fs");
4
+ const path = require("node:path");
5
+
6
+ function findNpm(env = process.env) {
7
+ const candidates = [
8
+ env.npm_execpath,
9
+ path.join(path.dirname(process.execPath), "node_modules", "npm", "bin", "npm-cli.js"),
10
+ path.resolve(path.dirname(process.execPath), "..", "lib", "node_modules", "npm", "bin", "npm-cli.js"),
11
+ ...(env.PATH || env.Path || "").split(path.delimiter).flatMap((dir) => [
12
+ path.join(dir, "npm"),
13
+ path.join(dir, "node_modules", "npm", "bin", "npm-cli.js"),
14
+ ]),
15
+ ];
16
+ for (const candidate of candidates) {
17
+ if (!candidate) continue;
18
+ try {
19
+ const real = fs.realpathSync(candidate);
20
+ if (path.basename(real) === "npm-cli.js" && fs.statSync(real).isFile()) return real;
21
+ } catch { /* Continue with the next conventional npm location. */ }
22
+ }
23
+ return "";
24
+ }
25
+
26
+ function childEnv(env = process.env) {
27
+ return Object.fromEntries(Object.entries(env).filter(([key]) =>
28
+ !key.toUpperCase().startsWith("SAP_")));
29
+ }
30
+
31
+ function pythonFallback(platform = process.platform) {
32
+ const python = platform === "win32" ? "py -3" : "python3";
33
+ const venv = platform === "win32" ? ".venv-sap-adt\\Scripts\\python.exe" : ".venv-sap-adt/bin/python";
34
+ return "Use Python >=3.10 in a separate virtual environment instead:\n" +
35
+ `${python} -m venv .venv-sap-adt\n${venv} -m pip install "sap-adt-cli>=1.5.0,<2"`;
36
+ }
37
+
38
+ function safeMessage(value) {
39
+ return String(value?.message || value).replace(
40
+ /(\b[a-z][a-z0-9+.-]*:\/\/)[^\s/]*@/gi, "$1<redacted>@");
41
+ }
42
+
43
+ function installationHint(error, platform = process.platform) {
44
+ const text = `${error?.code || ""} ${error?.message || error}`.toLowerCase();
45
+ if (/407|proxy authentication/.test(text)) {
46
+ return "The proxy requires authentication. Set HTTPS_PROXY with URL-encoded credentials " +
47
+ "or configure npm's https-proxy; do not use SAP credentials.";
48
+ }
49
+ if (/certificate|self.signed|unable.to.verify|cert_has_expired/.test(text)) {
50
+ return "Configure the trusted corporate CA with NODE_EXTRA_CA_CERTS, then restart this command. " +
51
+ "Do not disable TLS verification.";
52
+ }
53
+ if (/enospc|edquot|no space|disk full/.test(text)) {
54
+ return "Free space on both the temporary-file drive and the installation drive, then retry.";
55
+ }
56
+ if (/eacces|eperm|ebusy|access.denied|permission|being used|winerror (5|32)/.test(text)) {
57
+ return "Close running sap-adt processes and check installation-folder permissions, " +
58
+ "antivirus quarantine and file locks. Do not automatically elevate privileges. " +
59
+ pythonFallback(platform);
60
+ }
61
+ if (/self-test|exec format|enoexec|glibc|vcruntime|dll|win32 application/.test(text)) {
62
+ return (platform === "win32"
63
+ ? "Check Windows architecture, missing DLLs and antivirus quarantine; close other sap-adt processes. "
64
+ : platform === "linux"
65
+ ? "Check CPU architecture and glibc compatibility; this runtime is not an Alpine/musl build. "
66
+ : "Check that a native runtime was published for this macOS architecture. ") +
67
+ pythonFallback(platform);
68
+ }
69
+ if (/extract|tar unavailable/.test(text)) {
70
+ return "Check tar on PATH, free disk space and archive access. Windows requires tar.exe. " +
71
+ "For a genuinely slow extraction, increase SAP_ADT_INSTALL_EXTRACT_TIMEOUT_MS after investigation.";
72
+ }
73
+ if (/unsupported platform|not published/.test(text)) return pythonFallback(platform);
74
+ if (/sha256|unsafe|traversal|symlink/.test(text)) {
75
+ return "Retry the matching official release; do not bypass checksums or archive safety checks.";
76
+ }
77
+ if (/enoent|not found/.test(text)) {
78
+ return "Check that Node.js >=18, npm and tar are available on PATH. " + pythonFallback(platform);
79
+ }
80
+ if (/401|403/.test(text)) {
81
+ return "Check npm registry authentication and corporate firewall rules; do not use SAP credentials.";
82
+ }
83
+ if (/404/.test(text)) {
84
+ return "Check that this package version has a published release asset for your platform. " +
85
+ pythonFallback(platform);
86
+ }
87
+ if (/timeout|timed out|etimedout|enotfound|eai_again|econn|proxy|network|429|50[234]/.test(text)) {
88
+ return "Check DNS/firewall access to the npm registry and GitHub release CDN. " +
89
+ "Set HTTPS_PROXY or npm's https-proxy if required, and check NO_PROXY bypass rules.";
90
+ }
91
+ return "Inspect this installation before retrying. Check network, free disk space and folder permissions; " +
92
+ "SAP configuration is unchanged.";
93
+ }
94
+
95
+ module.exports = { findNpm, childEnv, pythonFallback, safeMessage, installationHint };
package/scripts/run.js CHANGED
@@ -3,7 +3,8 @@
3
3
  *
4
4
  * Dispatches to the installed self-contained runtime. The runtime must have
5
5
  * been fetched once by `<bin> install` — a normal invocation NEVER downloads
6
- * or upgrades anything. Node.js is required only for this launcher path;
6
+ * or upgrades anything (except the explicitly requested update command).
7
+ * Node.js is required only for this launcher path;
7
8
  * the runtime itself is a native, Python-free executable.
8
9
  *
9
10
  * `sap-adt install` is our custom install wizard, not an npx/npm feature.
@@ -13,6 +14,7 @@
13
14
  const { spawnSync } = require("node:child_process");
14
15
  const fs = require("node:fs");
15
16
  const path = require("node:path");
17
+ const { pythonFallback, safeMessage, installationHint } = require("./npm.js");
16
18
 
17
19
  const PKG_DIR = path.resolve(__dirname, "..");
18
20
 
@@ -45,6 +47,13 @@ function main(argv) {
45
47
 
46
48
  const bin = runtimeBin();
47
49
  if (!fs.existsSync(bin)) {
50
+ try {
51
+ const manifest = JSON.parse(fs.readFileSync(path.join(PKG_DIR, "runtime-manifest.json"), "utf8"));
52
+ if (manifest.artifacts && !manifest.artifacts[platformKey()]) {
53
+ fail(`No native runtime is published for ${platformKey()} in this package.\n` +
54
+ pythonFallback(), 2);
55
+ }
56
+ } catch { /* The install wizard diagnoses a missing or invalid manifest. */ }
48
57
  fail(
49
58
  `sap-adt runtime is not installed for ${platformKey()}.\n` +
50
59
  `Run the install wizard once: npx sap-adt-cli install\n` +
@@ -53,10 +62,26 @@ function main(argv) {
53
62
  );
54
63
  }
55
64
 
65
+ const { isUpdate, runUpdate } = require("./update.js");
66
+ if (isUpdate(argv)) {
67
+ try {
68
+ process.exit(runUpdate(PKG_DIR, bin, argv));
69
+ } catch (error) {
70
+ process.stderr.write(JSON.stringify({
71
+ ok: false, format_version: 1, command: "update",
72
+ error: { code: error.needsInspection ? "CONFIRM_REQUIRED" : "SERVER_ERROR",
73
+ message: safeMessage(error), http_status: null,
74
+ hint: installationHint(error) },
75
+ }) + "\n");
76
+ process.exit(error.needsInspection ? 3 : 1);
77
+ }
78
+ }
79
+
56
80
  // Argument array, no shell: exit code and both streams pass through.
57
81
  const result = spawnSync(bin, argv, { stdio: "inherit" });
58
82
  if (result.error) {
59
- fail(`Failed to launch runtime at ${bin}: ${result.error.message}`, 2);
83
+ fail(`Failed to launch runtime at ${bin}: ${safeMessage(result.error)}\n` +
84
+ installationHint({ code: result.error.code, message: "runtime self-test startup" }), 2);
60
85
  }
61
86
  process.exit(result.status === null ? 1 : result.status);
62
87
  }
@@ -0,0 +1,124 @@
1
+ "use strict";
2
+
3
+ const fs = require("node:fs");
4
+ const os = require("node:os");
5
+ const path = require("node:path");
6
+ const { spawnSync } = require("node:child_process");
7
+ const { installTree, npmEnvironment } = require("./install.js");
8
+ const { findNpm, childEnv, installationHint } = require("./npm.js");
9
+
10
+ function isUpdate(argv) {
11
+ for (let i = 0; i < argv.length; i++) {
12
+ if (["--help", "--version"].includes(argv[i])) return false;
13
+ if (["--profile", "--keystore", "--format", "-f"].includes(argv[i])) {
14
+ i++;
15
+ } else if (argv[i] === "--") {
16
+ return argv[i + 1] === "update";
17
+ } else if (!argv[i].startsWith("-")) {
18
+ return argv[i] === "update" && !argv.slice(i + 1).includes("--help");
19
+ }
20
+ }
21
+ return false;
22
+ }
23
+
24
+ function checked(run, command, args, options) {
25
+ const result = run(command, args, options);
26
+ if (result.error || result.status !== 0) {
27
+ throw new Error(`Update step failed (${result.status ?? result.error?.code ?? "could not start"}). ` +
28
+ installationHint(result.error || result.stderr || "Inspect npm permissions/connectivity"));
29
+ }
30
+ return result;
31
+ }
32
+
33
+ function applyUpdate(root, npm, plan, run = spawnSync, environment = process.env) {
34
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8"));
35
+ if (!plan || plan.root !== root || pkg.version !== plan.current ||
36
+ !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(plan.target)) {
37
+ throw new Error("Invalid update plan; nothing was changed.");
38
+ }
39
+ const env = childEnv(environment);
40
+ // Stage outside the installed package: npm replaces that directory, and
41
+ // Windows cannot replace a still-running frozen runtime.
42
+ const staging = fs.mkdtempSync(path.join(os.tmpdir(), "sap-adt-update-"));
43
+ let committing = false;
44
+ try {
45
+ const options = { env, stdio: ["inherit", 2, "pipe"], encoding: "utf8",
46
+ maxBuffer: 1024 * 1024, timeout: 600_000, killSignal: "SIGKILL", windowsHide: true };
47
+ checked(run, process.execPath, [npm, "install", "--prefix", staging,
48
+ "--global=false",
49
+ "--ignore-scripts", "--no-audit", "--no-fund", "--no-package-lock",
50
+ "--save-exact", `sap-adt-cli@${plan.target}`], options);
51
+ const stagedPackage = path.join(staging, "node_modules", "sap-adt-cli");
52
+ const stagedMetadata = JSON.parse(fs.readFileSync(path.join(stagedPackage, "package.json"), "utf8"));
53
+ if (stagedMetadata.name !== "sap-adt-cli" || stagedMetadata.version !== plan.target) {
54
+ throw new Error("Staged npm package version mismatch; the installed package was not changed.");
55
+ }
56
+ checked(run, process.execPath, [path.join(stagedPackage, "scripts", "install.js")], options);
57
+ const stagedVersion = checked(run, process.execPath,
58
+ [path.join(stagedPackage, "scripts", "run.js"), "--version"],
59
+ { env, encoding: "utf8", timeout: 60_000 }).stdout.trim();
60
+ if (stagedVersion !== `sap-adt, version ${plan.target}`) {
61
+ throw new Error("Staged runtime version mismatch; the installed package was not changed.");
62
+ }
63
+ // Check scope again immediately before the first change to the live install.
64
+ const globalRoot = checked(run, process.execPath, [npm, "root", "--global"],
65
+ { env, encoding: "utf8", timeout: 60_000 }).stdout.trim();
66
+ let canonicalGlobalRoot;
67
+ try {
68
+ canonicalGlobalRoot = fs.realpathSync(globalRoot);
69
+ } catch {
70
+ throw new Error("npm global root could not be verified; no update was committed.");
71
+ }
72
+ // Resolve prefix aliases, but do not authorize a symlinked package.
73
+ if (path.join(canonicalGlobalRoot, "sap-adt-cli") !== fs.realpathSync(root)) {
74
+ throw new Error("npm global root changed; the installed package was not changed.");
75
+ }
76
+ const live = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8"));
77
+ if (live.name !== "sap-adt-cli" || live.version !== plan.current) {
78
+ throw new Error("The installed npm package changed during staging; no update was committed.");
79
+ }
80
+ committing = true;
81
+ checked(run, process.execPath, [npm, "install", "--global", "--ignore-scripts",
82
+ "--no-audit", "--no-fund", `sap-adt-cli@${plan.target}`], options);
83
+ const updated = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8"));
84
+ if (updated.name !== "sap-adt-cli" || updated.version !== plan.target) {
85
+ throw new Error("npm did not update the expected package directory.");
86
+ }
87
+ installTree(path.join(stagedPackage, "runtime"), path.join(root, "runtime"));
88
+ const actual = checked(run, process.execPath, [path.join(root, "scripts", "run.js"), "--version"],
89
+ { env, encoding: "utf8", timeout: 60_000 }).stdout.trim();
90
+ if (actual !== `sap-adt, version ${plan.target}`) throw new Error("Final runtime version mismatch.");
91
+ process.stdout.write(`Updated and verified sap-adt ${plan.target}.\n`);
92
+ } catch (error) {
93
+ if (committing) {
94
+ error.needsInspection = true;
95
+ error.message += " The npm package may already have changed; repair with npm install -g " +
96
+ `"sap-adt-cli@${plan.target}" followed by sap-adt install. No full npm rollback is guaranteed.`;
97
+ }
98
+ throw error;
99
+ } finally {
100
+ fs.rmSync(staging, { recursive: true, force: true });
101
+ }
102
+ }
103
+
104
+ function runUpdate(root, bin, argv) {
105
+ const npm = findNpm();
106
+ if (!npm) throw new Error("npm-cli.js not found; repair the Node.js/npm installation.");
107
+ const env = npmEnvironment();
108
+ const result = spawnSync(bin, argv, {
109
+ stdio: ["inherit", "pipe", "inherit"], encoding: "utf8", maxBuffer: 1024 * 1024,
110
+ timeout: 120_000, killSignal: "SIGKILL", windowsHide: true,
111
+ env: { ...env, _SAP_ADT_UPDATE_LAUNCHER: "1",
112
+ _SAP_ADT_NPM_ROOT: root, _SAP_ADT_NPM_NODE: process.execPath, _SAP_ADT_NPM_CLI: npm },
113
+ });
114
+ if (result.error) throw new Error("Could not complete the runtime update check. " +
115
+ installationHint(result.error));
116
+ if (result.status !== 0) return result.status ?? 1;
117
+ const response = JSON.parse(result.stdout);
118
+ if (!Object.hasOwn(response, "update_plan")) throw new Error("Missing runtime update plan.");
119
+ if (response.message) process.stdout.write(`${response.message}\n`);
120
+ if (response.update_plan) applyUpdate(root, npm, response.update_plan, spawnSync, env);
121
+ return 0;
122
+ }
123
+
124
+ module.exports = { findNpm, isUpdate, childEnv, applyUpdate, runUpdate };