sap-adt-cli 1.5.2 → 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
@@ -9,6 +9,16 @@ if Node.js is not an option, use the desktop installer / portable archive
9
9
  from the [repository releases](https://github.com/shrek-abaper/sap-engineering-skill)
10
10
  instead.
11
11
 
12
+ Linux x86_64 and Windows x86_64 runtimes are provided. Windows support
13
+ starts with package 1.5.3 and also requires `tar.exe` (included in current
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
20
+ the npm package before running `sap-adt install` again.
21
+
12
22
  ## Install the runtime (once)
13
23
 
14
24
  The package is named `sap-adt-cli`; its bin is **`sap-adt`**.
@@ -34,9 +44,28 @@ artifact over HTTPS, verifies its SHA-256 (from the manifest bundled with
34
44
  the package — never from the download endpoint), extracts safely and swaps
35
45
  it in atomically, then self-tests with the absolute install path.
36
46
 
37
- On a proxied network, set `HTTPS_PROXY` (and `NO_PROXY` for hosts that go
38
- direct) before running `install`; the wizard tunnels through an `http://`
39
- 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.
40
69
 
41
70
  ## Use
42
71
 
@@ -51,7 +80,25 @@ With npx, prefix each command: `npx "sap-adt-cli@^1.5.0" <command>`.
51
80
 
52
81
  Configuration and credentials live in `~/.sap-adt-cli/` and the OS keystore —
53
82
  never inside this package. Upgrading the npm package requires re-running
54
- `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.
55
102
 
56
103
  ## Security model notes
57
104
 
@@ -60,7 +107,8 @@ never inside this package. Upgrading the npm package requires re-running
60
107
  for a fresh `[y/N]` confirmation per operation.
61
108
  - The installer refuses digest mismatches, unsupported platforms, non-HTTPS
62
109
  or unlisted redirect hosts, and archives with path traversal or symlinks.
63
- - 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.
64
112
 
65
113
  Package versions track the CLI version exactly; installing version X always
66
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.2",
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,45 @@
1
1
  {
2
- "cli_version": "1.5.2",
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.2/sap-adt-1.5.2-linux-x86_64.tar.gz",
7
- "sha256": "c1da5705f4e2b6efdacf15dec50b48e1b1c667acafc8432bc87f916cc84ce680",
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": 16556438,
31
+ "size_bytes": 16590088,
32
+ "allowed_redirect_hosts": [
33
+ "github.com",
34
+ "release-assets.githubusercontent.com",
35
+ "objects.githubusercontent.com"
36
+ ]
37
+ },
38
+ "windows-x86_64": {
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",
41
+ "format": "zip",
42
+ "size_bytes": 15604192,
10
43
  "allowed_redirect_hosts": [
11
44
  "github.com",
12
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).
@@ -32,15 +32,29 @@ const path = require("node:path");
32
32
  const tls = require("node:tls");
33
33
  const { Transform } = require("node:stream");
34
34
  const { pipeline } = require("node:stream/promises");
35
+ const { fileURLToPath } = require("node:url");
36
+ const { findNpm, childEnv, installationHint, safeMessage } = require("./npm.js");
35
37
 
36
38
  const PKG_DIR = path.resolve(__dirname, "..");
37
39
  const MAX_REDIRECTS = 3;
38
40
  // Node's core https client ignores HTTPS_PROXY before v24, so a blocked
39
- // direct route hung this wizard forever. Both timers are inactivity-based:
40
- // 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.
41
43
  const CONNECT_TIMEOUT_MS = intEnv("SAP_ADT_INSTALL_CONNECT_TIMEOUT_MS", 30_000);
42
- 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);
43
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
+ `;
44
58
 
45
59
  function intEnv(name, fallback) {
46
60
  const raw = process.env[name];
@@ -50,7 +64,8 @@ function intEnv(name, fallback) {
50
64
  }
51
65
 
52
66
  function fail(message, code = 1) {
53
- 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`);
54
69
  process.exit(code);
55
70
  }
56
71
 
@@ -104,21 +119,94 @@ function firstEnv(env, names) {
104
119
  return "";
105
120
  }
106
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
+
107
196
  /* Proxy for a target URL, or null when the request should go direct.
108
197
  * Honors the usual spellings plus npm's own config variables; `env` is
109
198
  * injectable so the tests never depend on the machine's network. */
110
199
  function proxyForUrl(targetUrl, env = process.env) {
111
- const raw = firstEnv(env, [
112
- "https_proxy", "HTTPS_PROXY", "npm_config_https_proxy", "npm_config_proxy",
113
- "http_proxy", "HTTP_PROXY",
114
- ]);
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);
115
203
  if (!raw) return null;
116
204
 
117
205
  let proxy;
118
206
  try {
119
207
  proxy = new URL(raw.includes("://") ? raw : `http://${raw}`);
120
208
  } catch {
121
- 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.");
122
210
  }
123
211
  // Only plain HTTP CONNECT proxies: TLS-to-the-proxy would need TLS-in-TLS,
124
212
  // and refusing loudly beats a half-working tunnel.
@@ -126,9 +214,7 @@ function proxyForUrl(targetUrl, env = process.env) {
126
214
  throw new Error(`unsupported proxy scheme "${proxy.protocol}" in HTTPS_PROXY (only http:// proxies are supported)`);
127
215
  }
128
216
 
129
- const target = new URL(targetUrl);
130
- const noProxy = firstEnv(env, ["no_proxy", "NO_PROXY", "npm_config_noproxy"]);
131
- return bypassesProxy(target.hostname, target.port || "443", noProxy) ? null : proxy;
217
+ return proxy;
132
218
  }
133
219
 
134
220
  function bypassesProxy(hostname, port, noProxy) {
@@ -138,6 +224,7 @@ function bypassesProxy(hostname, port, noProxy) {
138
224
  entry = entry.trim().toLowerCase();
139
225
  if (!entry) continue;
140
226
  if (entry === "*") return true;
227
+ if (entry === "<local>" && !net.isIP(host) && !host.includes(".")) return true;
141
228
  // "host:port" (never "::1" — the host part must be colon-free)
142
229
  const withPort = /^([^:]+):(\d+)$/.exec(entry);
143
230
  if (withPort) {
@@ -170,8 +257,9 @@ function fmtBytes(n) {
170
257
 
171
258
  /* HTTPS through an HTTP(S) proxy: CONNECT tunnel, then TLS to the target so
172
259
  * the certificate is still verified against the real host name. */
173
- function openTunnel(proxy, host, port) {
260
+ function openTunnel(proxy, host, port, signal) {
174
261
  return new Promise((resolve, reject) => {
262
+ host = host.replace(/^\[|\]$/g, "");
175
263
  const target = net.isIP(host) === 6 ? `[${host}]` : host;
176
264
  const headers = { Host: `${target}:${port}` };
177
265
  if (proxy.username) {
@@ -181,15 +269,21 @@ function openTunnel(proxy, host, port) {
181
269
  `Basic ${Buffer.from(`${user}:${pass}`).toString("base64")}`;
182
270
  }
183
271
  const req = http.request({
184
- host: proxy.hostname,
272
+ host: proxy.hostname.replace(/^\[|\]$/g, ""),
185
273
  port: proxy.port || 80,
186
274
  method: "CONNECT",
187
275
  path: `${target}:${port}`,
188
276
  headers,
189
277
  agent: false,
190
278
  timeout: CONNECT_TIMEOUT_MS,
279
+ signal,
191
280
  });
192
- 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);
193
287
  if (res.statusCode === 407) {
194
288
  socket.destroy();
195
289
  return reject(new Error(
@@ -201,24 +295,39 @@ function openTunnel(proxy, host, port) {
201
295
  return reject(new Error(
202
296
  `proxy CONNECT ${proxy.host} -> ${target}:${port} failed: HTTP ${res.statusCode}`));
203
297
  }
298
+ if (head.length) socket.unshift(head);
204
299
  const secure = tls.connect({
205
300
  socket,
301
+ host,
206
302
  servername: net.isIP(host) ? undefined : host,
207
303
  });
208
- secure.setTimeout(CONNECT_TIMEOUT_MS, () => secure.destroy(new Error(
209
- `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
+ };
210
314
  secure.once("secureConnect", () => {
211
- secure.setTimeout(0);
315
+ cleanup();
212
316
  resolve(secure);
213
317
  });
214
- secure.once("error", (e) => reject(new Error(
215
- `TLS handshake with ${target} through the proxy failed: ${e.message} ` +
216
- "(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
+ });
217
323
  });
218
324
  req.on("timeout", () => req.destroy(new Error(
219
325
  `proxy CONNECT to ${proxy.host} timed out after ${CONNECT_TIMEOUT_MS} ms — ` +
220
326
  "check HTTPS_PROXY/NO_PROXY and that the proxy allows CONNECT")));
221
- req.on("error", reject);
327
+ req.on("error", (error) => {
328
+ clearTimeout(deadline);
329
+ reject(error);
330
+ });
222
331
  req.end();
223
332
  });
224
333
  }
@@ -227,16 +336,22 @@ class TunnelAgent extends https.Agent {
227
336
  constructor(proxy) {
228
337
  super({ keepAlive: false, maxSockets: 1 });
229
338
  this.proxy = proxy;
339
+ this.controller = new AbortController();
230
340
  }
231
341
 
232
342
  // Node's Agent contract: a 2-argument createConnection is the async form.
233
343
  createConnection(options, cb) {
234
344
  const host = options.servername || options.host;
235
- openTunnel(this.proxy, host, options.port || 443).then(
345
+ openTunnel(this.proxy, host, options.port || 443, this.controller.signal).then(
236
346
  (socket) => cb(null, socket),
237
347
  cb,
238
348
  );
239
349
  }
350
+
351
+ destroy() {
352
+ this.controller.abort();
353
+ super.destroy();
354
+ }
240
355
  }
241
356
 
242
357
  function timeoutHint(target, proxy) {
@@ -244,10 +359,10 @@ function timeoutHint(target, proxy) {
244
359
  const advice = proxy
245
360
  ? "check HTTPS_PROXY or add this host to NO_PROXY"
246
361
  : "if this network requires a proxy, set HTTPS_PROXY=http://host:port";
247
- 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}`;
248
363
  }
249
364
 
250
- function download(url, allowedHosts, dest, redirectsLeft) {
365
+ function download(url, allowedHosts, dest, redirectsLeft, network) {
251
366
  return new Promise((resolve, reject) => {
252
367
  const parsed = new URL(url);
253
368
  if (parsed.protocol === "file:") {
@@ -255,7 +370,7 @@ function download(url, allowedHosts, dest, redirectsLeft) {
255
370
  return reject(new Error(
256
371
  "file:// artifacts are refused (test-only; set SAP_ADT_INSTALL_ALLOW_FILE=1 to allow)"));
257
372
  }
258
- return fs.promises.copyFile(decodeURIComponent(parsed.pathname), dest)
373
+ return fs.promises.copyFile(fileURLToPath(parsed), dest)
259
374
  .then(resolve, reject);
260
375
  }
261
376
  if (parsed.protocol !== "https:") {
@@ -264,34 +379,46 @@ function download(url, allowedHosts, dest, redirectsLeft) {
264
379
  if (!allowedHosts.includes(parsed.host)) {
265
380
  return reject(new Error(`artifact host not allow-listed: ${parsed.host}`));
266
381
  }
267
- const proxy = proxyForUrl(url);
268
- 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 };
269
385
  if (proxy) {
270
- info(`using proxy ${proxy.host} for ${parsed.host}`);
271
- 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)" : ""}`);
272
389
  }
273
-
390
+ let deadline;
391
+ const cleanup = () => {
392
+ clearTimeout(deadline);
393
+ agent.destroy();
394
+ };
395
+ const failDownload = (error) => {
396
+ cleanup();
397
+ reject(error);
398
+ };
274
399
  const req = https.get(url, options, (res) => {
400
+ clearTimeout(deadline);
275
401
  if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
276
402
  res.resume();
277
- if (redirectsLeft <= 0) return reject(new Error("too many redirects"));
403
+ if (redirectsLeft <= 0) return failDownload(new Error("too many redirects"));
278
404
  let next;
279
405
  try {
280
406
  next = new URL(res.headers.location, url);
281
407
  } catch {
282
- return reject(new Error("invalid redirect location"));
408
+ return failDownload(new Error("invalid redirect location"));
283
409
  }
284
410
  if (next.protocol !== "https:") {
285
- return reject(new Error(`refusing redirect to non-HTTPS: ${next}`));
411
+ return failDownload(new Error(`refusing redirect to non-HTTPS: ${next}`));
286
412
  }
287
413
  if (!allowedHosts.includes(next.host)) {
288
- 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}`));
289
415
  }
290
- return resolve(download(next.toString(), allowedHosts, dest, redirectsLeft - 1));
416
+ cleanup();
417
+ return resolve(download(next.toString(), allowedHosts, dest, redirectsLeft - 1, network));
291
418
  }
292
419
  if (res.statusCode !== 200) {
293
420
  res.resume();
294
- return reject(new Error(`download failed: HTTP ${res.statusCode}`));
421
+ return failDownload(new Error(`download failed: HTTP ${res.statusCode}`));
295
422
  }
296
423
  const total = Number(res.headers["content-length"]) || 0;
297
424
  info(`downloading ${total ? fmtBytes(total) : "artifact"}${proxy ? ` via ${proxy.host}` : ""}`);
@@ -314,10 +441,21 @@ function download(url, allowedHosts, dest, redirectsLeft) {
314
441
  callback();
315
442
  },
316
443
  });
317
- 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));
318
456
  });
319
457
  req.on("timeout", () => req.destroy(new Error(timeoutHint(parsed.host, proxy))));
320
- req.on("error", reject);
458
+ req.on("error", failDownload);
321
459
  });
322
460
  }
323
461
 
@@ -333,14 +471,23 @@ function sha256File(file) {
333
471
 
334
472
  /* Extract with tar (bsdtar on Windows handles .zip too) via an argument
335
473
  * array — never a shell. Then walk entries rejecting traversal/symlinks. */
336
- function extract(archive, format, destDir) {
474
+ function extract(archive, format, destDir, run = spawnSync) {
337
475
  fs.mkdirSync(destDir, { recursive: true });
338
476
  const args = format === "zip"
339
477
  ? ["-xf", archive, "-C", destDir]
340
478
  : ["-xzf", archive, "-C", destDir];
341
- const result = spawnSync("tar", args, { encoding: "utf8" });
342
- if (result.error) throw new Error(`tar unavailable: ${result.error.message}`);
343
- 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
+ }
344
491
 
345
492
  for (const entry of fs.readdirSync(destDir, { recursive: true })) {
346
493
  const full = path.join(destDir, entry);
@@ -355,11 +502,24 @@ function extract(archive, format, destDir) {
355
502
  }
356
503
  }
357
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
+
358
518
  /* Rename, or copy when staging and target sit on different filesystems
359
519
  * (os.tmpdir() is tmpfs on many Linux/WSL setups → EXDEV). */
360
520
  function moveTree(staging, target) {
361
521
  try {
362
- fs.renameSync(staging, target);
522
+ renameRuntime(staging, target);
363
523
  } catch (e) {
364
524
  if (e.code !== "EXDEV") throw e;
365
525
  fs.cpSync(staging, target, { recursive: true });
@@ -369,21 +529,62 @@ function moveTree(staging, target) {
369
529
 
370
530
  /* Swap runtime atomically-ish: stage -> rename old aside -> rename new in ->
371
531
  * on any failure, restore the old one and leave it working. */
372
- function installTree(staging, runtimeDir) {
373
- const backup = `${runtimeDir}.old-${process.pid}`;
532
+ function installTree(staging, runtimeDir, validate = () => {}) {
533
+ const backup = `${runtimeDir}.old-${process.pid}-${crypto.randomBytes(6).toString("hex")}`;
374
534
  let movedOld = false;
535
+ let replacing = false;
375
536
  try {
376
537
  if (fs.existsSync(runtimeDir)) {
377
- fs.renameSync(runtimeDir, backup);
538
+ renameRuntime(runtimeDir, backup);
378
539
  movedOld = true;
379
540
  }
541
+ replacing = true;
380
542
  moveTree(staging, runtimeDir);
381
- if (movedOld) fs.rmSync(backup, { recursive: true, force: true });
543
+ validate(runtimeDir);
382
544
  } catch (e) {
383
- fs.rmSync(runtimeDir, { recursive: true, force: true });
384
- 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.";
385
561
  throw e;
386
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();
387
588
  }
388
589
 
389
590
  async function main() {
@@ -400,11 +601,13 @@ async function main() {
400
601
  try {
401
602
  const archive = path.join(tmp, `artifact.${entry.format === "zip" ? "zip" : "tar.gz"}`);
402
603
  const allowedHosts = [new URL(entry.url).host, ...(entry.allowed_redirect_hosts || [])];
403
- 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);
404
607
 
405
608
  const actual = await sha256File(archive);
406
609
  if (actual.toLowerCase() !== entry.sha256.toLowerCase()) {
407
- 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.`);
408
611
  }
409
612
  info("sha256 verified");
410
613
 
@@ -416,28 +619,30 @@ async function main() {
416
619
  ? path.join(staging, "sap-adt")
417
620
  : staging;
418
621
  if (!fs.existsSync(path.join(treeRoot, exeName))) {
419
- fail(`archive has no ${exeName} at its root`, 1);
622
+ throw new Error(`archive has no ${exeName} at its root`);
420
623
  }
421
624
 
422
625
  const runtimeDir = path.join(PKG_DIR, "runtime", key, "sap-adt");
423
626
  fs.mkdirSync(path.dirname(runtimeDir), { recursive: true });
424
- installTree(treeRoot, runtimeDir);
425
-
426
- const bin = path.join(runtimeDir, exeName);
427
- const selftest = spawnSync(bin, ["--version"], { encoding: "utf8" });
428
- if (selftest.status !== 0) {
429
- fail(`self-test failed (${bin} --version exited ${selftest.status}). Restored previous runtime if any.`, 1);
430
- }
431
- 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)}`);
432
632
  info("next: sap-adt configure (interactive; password goes to the OS keystore)");
433
633
  } finally {
434
- 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
+ }
435
640
  }
436
641
  }
437
642
 
438
643
  if (require.main === module) {
439
- main().catch((e) => fail(e.message));
644
+ main().catch((e) => fail(e, e.needsInspection ? 3 : 1));
440
645
  }
441
646
 
442
- // Pure helpers only; the wizard itself stays a script.
443
- 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 };