@git.zone/cli 9.0.1 → 9.1.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.
@@ -4,6 +4,7 @@
4
4
  set -euo pipefail
5
5
 
6
6
  SHOW_HELP=0
7
+ DRY_RUN=0
7
8
  SPECIFIED_VERSION=""
8
9
  SPECIFIED_MAJOR=""
9
10
  INSTALL_DIR="{{installer.installDir}}"
@@ -15,6 +16,14 @@ REPO_URL="{{{repository.gitUrl}}}"
15
16
  SERVICE_RESTART_NAME="{{installer.service.restartName}}"
16
17
  PRIMARY_PRESERVE_PATH="{{installer.primaryPreservePath}}"
17
18
 
19
+ # Every transfer is an HTTPS release asset or the Gitea API: no other protocol, also not on a redirect,
20
+ # at most 10 redirects, and the same limits as the npm postinstall (30 s to connect or without data,
21
+ # 15 minutes per transfer).
22
+ CURL_OPTS=(--proto '=https' --proto-redir '=https' --max-redirs 10 --connect-timeout 30 --speed-limit 1 --speed-time 30 --max-time 900)
23
+
24
+ # A release tag is a SemVer 2.0 version with an optional v; nothing else goes into a download URL.
25
+ RELEASE_TAG_REGEX='^v?(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-(0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)(\.(0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*))*)?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$'
26
+
18
27
  SERVICE_NAMES=(
19
28
  {{#each installer.service.detectNames}}
20
29
  "{{this}}"
@@ -51,6 +60,10 @@ while [[ $# -gt 0 ]]; do
51
60
  shift 2
52
61
  ;;
53
62
  {{/if}}
63
+ --dry-run)
64
+ DRY_RUN=1
65
+ shift
66
+ ;;
54
67
  --install-dir)
55
68
  if [[ $# -lt 2 ]]; then
56
69
  echo "Error: --install-dir requires a value"
@@ -85,11 +98,12 @@ if [[ $SHOW_HELP -eq 1 ]]; then
85
98
  echo ""
86
99
  echo "Options:"
87
100
  echo " -h, --help Show this help message"
88
- echo " --version VERSION Install a specific tag/version (e.g. vX.Y.Z)"
101
+ echo " --version VERSION Install a specific release: vX.Y.Z or X.Y.Z (latest: the newest)"
89
102
  {{#if installer.supportsMajor}}
90
103
  echo " --major MAJOR Install latest release for a major version (e.g. 1)"
91
104
  {{/if}}
92
105
  echo " --install-dir DIR Installation directory (default: {{installer.installDir}})"
106
+ echo " --dry-run Resolve the version and check the release assets; change nothing"
93
107
  {{#if installer.source.enabled}}
94
108
  echo " --binary Install release binary (default)"
95
109
  echo " --source Clone the tag and build from source locally"
@@ -104,20 +118,46 @@ if [[ $SHOW_HELP -eq 1 ]]; then
104
118
  {{#if installer.source.enabled}}
105
119
  echo " curl -sSL {{{installer.publicInstallUrl}}} | sudo bash -s -- --source"
106
120
  {{/if}}
121
+ echo " curl -sSL {{{installer.publicInstallUrl}}} | bash -s -- --dry-run"
107
122
  exit 0
108
123
  fi
109
124
 
125
+ # Succeeds when the value matches the extended regular expression in the C locale. Bash compiles the
126
+ # expression with the current locale's collation, where a range such as [A-Za-z] can match accented letters;
127
+ # the local LC_ALL applies to this match only and leaves the caller's locale as it was.
128
+ matches_ascii_pattern() {
129
+ local LC_ALL=C
130
+ [[ "$1" =~ $2 ]]
131
+ }
132
+
133
+ # Prints the release tag of a version (with its v), or fails when it is not a SemVer 2.0 version.
134
+ normalize_release_tag() {
135
+ if ! matches_ascii_pattern "$1" "$RELEASE_TAG_REGEX"; then
136
+ printf 'Error: %s is not a {{displayName}} release tag: %q\n' "$2" "$1" >&2
137
+ echo "Expected a SemVer version such as v1.2.3, 1.2.3 or v1.2.3-beta.1" >&2
138
+ exit 1
139
+ fi
140
+ echo "v${1#v}"
141
+ }
142
+
143
+ # --version latest is the same as no --version: the newest release.
144
+ if [[ "$SPECIFIED_VERSION" == "latest" ]]; then
145
+ SPECIFIED_VERSION=""
146
+ elif [[ -n "$SPECIFIED_VERSION" ]]; then
147
+ SPECIFIED_VERSION=$(normalize_release_tag "$SPECIFIED_VERSION" "--version argument") || exit 1
148
+ fi
149
+
110
150
  if [[ -n "$SPECIFIED_VERSION" && -n "$SPECIFIED_MAJOR" ]]; then
111
151
  echo "Error: --version and --major are mutually exclusive"
112
152
  exit 1
113
153
  fi
114
154
 
115
- if [[ -n "$SPECIFIED_MAJOR" && ! "$SPECIFIED_MAJOR" =~ ^[0-9]+$ ]]; then
155
+ if [[ -n "$SPECIFIED_MAJOR" ]] && ! matches_ascii_pattern "$SPECIFIED_MAJOR" '^[0-9]+$'; then
116
156
  echo "Error: --major must be a numeric major version, for example: --major 1"
117
157
  exit 1
118
158
  fi
119
159
 
120
- if [[ "$EUID" -ne 0 ]]; then
160
+ if [[ $DRY_RUN -eq 0 && "$EUID" -ne 0 ]]; then
121
161
  echo "Please run as root (sudo bash install.sh or pipe to sudo bash)"
122
162
  exit 1
123
163
  fi
@@ -153,7 +193,7 @@ get_latest_version() {
153
193
  echo "Fetching latest release version from Gitea..." >&2
154
194
  local api_url="${GITEA_BASE_URL}/api/v1/repos/${GITEA_REPO}/releases/latest"
155
195
  local response
156
- if ! response=$(curl -fsSL "$api_url" 2>/dev/null); then
196
+ if ! response=$(curl "${CURL_OPTS[@]}" -fsSL "$api_url" 2>/dev/null); then
157
197
  echo "Error: Failed to fetch latest release information from Gitea API" >&2
158
198
  echo "URL: $api_url" >&2
159
199
  exit 1
@@ -165,7 +205,7 @@ get_latest_version() {
165
205
  echo "Error: Could not determine latest version from API response" >&2
166
206
  exit 1
167
207
  fi
168
- echo "$version"
208
+ normalize_release_tag "$version" "tag_name from the Gitea releases API"
169
209
  }
170
210
 
171
211
  {{#if installer.supportsMajor}}
@@ -174,7 +214,7 @@ get_latest_major_version() {
174
214
  echo "Fetching latest v${major}.x release version from Gitea..." >&2
175
215
  local api_url="${GITEA_BASE_URL}/api/v1/repos/${GITEA_REPO}/releases?limit=50"
176
216
  local response
177
- if ! response=$(curl -fsSL "$api_url" 2>/dev/null); then
217
+ if ! response=$(curl "${CURL_OPTS[@]}" -fsSL "$api_url" 2>/dev/null); then
178
218
  echo "Error: Failed to fetch release list from Gitea API" >&2
179
219
  echo "URL: $api_url" >&2
180
220
  exit 1
@@ -186,7 +226,7 @@ get_latest_major_version() {
186
226
  echo "Error: Could not determine latest v${major}.x version from API response" >&2
187
227
  exit 1
188
228
  fi
189
- echo "$version"
229
+ normalize_release_tag "$version" "tag_name from the Gitea releases API"
190
230
  }
191
231
 
192
232
  {{/if}}
@@ -240,6 +280,109 @@ detect_binary_name() {
240
280
  esac
241
281
  }
242
282
 
283
+ # Sets NOTICE_FILES to the third-party notice files the release ships for an executable.
284
+ select_notice_files() {
285
+ NOTICE_FILES=()
286
+ case "$1" in
287
+ {{#each binary.targets}}
288
+ "{{name}}")
289
+ {{#each noticeFiles}}
290
+ NOTICE_FILES+=("{{this}}")
291
+ {{/each}}
292
+ ;;
293
+ {{/each}}
294
+ esac
295
+ }
296
+
297
+ # The extra release assets installed beside the executable, as name:mode:repository path. The mode is the
298
+ # file's mode in the Git index when the installer was generated.
299
+ EXTRA_FILES=(
300
+ {{#each installer.extraFiles}}
301
+ "{{name}}:{{mode}}:{{path}}"
302
+ {{/each}}
303
+ )
304
+
305
+ # Sets RELEASE_ASSETS to every release file a binary install of the executable downloads.
306
+ select_release_assets() {
307
+ local extra
308
+ select_notice_files "$1"
309
+ RELEASE_ASSETS=("$1" ${NOTICE_FILES[@]+"${NOTICE_FILES[@]}"})
310
+ for extra in ${EXTRA_FILES[@]+"${EXTRA_FILES[@]}"}; do
311
+ RELEASE_ASSETS+=("${extra%%:*}")
312
+ done
313
+ }
314
+
315
+ # The download URL of a release asset of $VERSION.
316
+ release_asset_url() {
317
+ echo "${GITEA_BASE_URL}/${GITEA_REPO}/releases/download/${VERSION}/$1"
318
+ }
319
+
320
+ # Downloads SHA256SUMS.txt of the release into $TEMP_DIR, once.
321
+ fetch_release_sums() {
322
+ local sums_file="$TEMP_DIR/SHA256SUMS.txt"
323
+ if [[ -f "$sums_file" ]]; then
324
+ return 0
325
+ fi
326
+ echo "Downloading checksums: $(release_asset_url SHA256SUMS.txt)"
327
+ if ! curl "${CURL_OPTS[@]}" -fsSL "$(release_asset_url SHA256SUMS.txt)" -o "$sums_file"; then
328
+ rm -f "$sums_file"
329
+ return 1
330
+ fi
331
+ }
332
+
333
+ # Prints the SHA-256 that SHA256SUMS.txt of the release lists for an asset, or nothing.
334
+ listed_checksum() {
335
+ local sum
336
+ local entry
337
+ while read -r sum entry; do
338
+ if [[ "${entry#\*}" == "$1" ]]; then
339
+ echo "$sum"
340
+ return 0
341
+ fi
342
+ done < "$TEMP_DIR/SHA256SUMS.txt"
343
+ }
344
+
345
+ # --dry-run: checks that the release carries every file this installation would download, and changes nothing.
346
+ run_dry_run() {
347
+ local binary_name
348
+ local asset
349
+ local status
350
+ local failed=0
351
+ echo "Dry run: nothing is installed, stopped or changed."
352
+ if [[ "$INSTALL_MODE" == "source" ]]; then
353
+ echo "A source install clones $REPO_URL at $VERSION and builds it."
354
+ exit 0
355
+ fi
356
+ binary_name=$(detect_binary_name) || exit 1
357
+ select_release_assets "$binary_name"
358
+ if ! fetch_release_sums; then
359
+ echo "Error: could not download $(release_asset_url SHA256SUMS.txt)" >&2
360
+ exit 1
361
+ fi
362
+ for asset in ${RELEASE_ASSETS[@]+"${RELEASE_ASSETS[@]}"}; do
363
+ if [[ -z "$(listed_checksum "$asset")" ]]; then
364
+ echo "Error: SHA256SUMS.txt of $VERSION has no entry for $asset" >&2
365
+ failed=1
366
+ fi
367
+ done
368
+ echo "Release assets:"
369
+ for asset in ${RELEASE_ASSETS[@]+"${RELEASE_ASSETS[@]}"}; do
370
+ status=$(curl "${CURL_OPTS[@]}" -sSL -r 0-0 -o /dev/null -w '%{http_code}' "$(release_asset_url "$asset")" 2>/dev/null) || true
371
+ status="${status:-000}"
372
+ echo " $status $(release_asset_url "$asset")"
373
+ case "$status" in
374
+ 200|206) ;;
375
+ *) failed=1 ;;
376
+ esac
377
+ done
378
+ if [[ $failed -ne 0 ]]; then
379
+ echo "Error: dry run failed: $VERSION lacks files this installation needs" >&2
380
+ exit 1
381
+ fi
382
+ echo "Dry run passed: $VERSION carries every file this installation needs."
383
+ exit 0
384
+ }
385
+
243
386
  echo "================================================"
244
387
  echo " {{displayName}} Installation Script"
245
388
  echo "================================================"
@@ -253,11 +396,11 @@ if [[ -n "$SPECIFIED_VERSION" ]]; then
253
396
  echo "Installing specified version: $VERSION"
254
397
  {{#if installer.supportsMajor}}
255
398
  elif [[ -n "$SPECIFIED_MAJOR" ]]; then
256
- VERSION=$(get_latest_major_version "$SPECIFIED_MAJOR")
399
+ VERSION=$(get_latest_major_version "$SPECIFIED_MAJOR") || exit 1
257
400
  echo "Installing latest v${SPECIFIED_MAJOR}.x version: $VERSION"
258
401
  {{/if}}
259
402
  else
260
- VERSION=$(get_latest_version)
403
+ VERSION=$(get_latest_version) || exit 1
261
404
  echo "Installing latest version: $VERSION"
262
405
  fi
263
406
  echo "Install mode: $INSTALL_MODE"
@@ -277,6 +420,10 @@ cleanup_temp() {
277
420
  }
278
421
  trap cleanup_temp EXIT
279
422
 
423
+ if [[ $DRY_RUN -eq 1 ]]; then
424
+ run_dry_run
425
+ fi
426
+
280
427
  if command -v systemctl >/dev/null 2>&1; then
281
428
  SYSTEMD_AVAILABLE=1
282
429
  for service_name in ${SERVICE_NAMES[@]+"${SERVICE_NAMES[@]}"}; do
@@ -423,24 +570,14 @@ sha256_of() {
423
570
  verify_release_checksum() {
424
571
  local file="$1"
425
572
  local name="$2"
426
- local sums_url="${GITEA_BASE_URL}/${GITEA_REPO}/releases/download/${VERSION}/SHA256SUMS.txt"
427
- local sums_file="$TEMP_DIR/SHA256SUMS.txt"
428
- local expected=""
573
+ local expected
429
574
  local actual
430
- local sum
431
- local entry
432
575
 
433
- echo "Downloading checksums: $sums_url"
434
- if ! curl -fsSL "$sums_url" -o "$sums_file"; then
435
- echo "Error: could not download $sums_url; refusing to install an unverified binary" >&2
576
+ if ! fetch_release_sums; then
577
+ echo "Error: could not download $(release_asset_url SHA256SUMS.txt); refusing to install an unverified binary" >&2
436
578
  exit 1
437
579
  fi
438
- while read -r sum entry; do
439
- if [[ "${entry#\*}" == "$name" ]]; then
440
- expected="$sum"
441
- break
442
- fi
443
- done < "$sums_file"
580
+ expected=$(listed_checksum "$name")
444
581
  if [[ -z "$expected" ]]; then
445
582
  echo "Error: SHA256SUMS.txt of $VERSION has no entry for $name; refusing to install it" >&2
446
583
  exit 1
@@ -455,23 +592,72 @@ verify_release_checksum() {
455
592
  echo "Checksum verified: $name"
456
593
  }
457
594
 
595
+ # Copies the verified extra release assets into the installation directory, with their modes.
596
+ install_extra_files() {
597
+ local extra
598
+ local name
599
+ local rest
600
+ for extra in ${EXTRA_FILES[@]+"${EXTRA_FILES[@]}"}; do
601
+ name="${extra%%:*}"
602
+ rest="${extra#*:}"
603
+ install -m "${rest%%:*}" "$1/$name" "$INSTALL_DIR/$name" || return 1
604
+ done
605
+ }
606
+
607
+ # Copies the verified notice files into the installation directory.
608
+ install_notice_files() {
609
+ local notice_file
610
+ for notice_file in ${NOTICE_FILES[@]+"${NOTICE_FILES[@]}"}; do
611
+ install -m 0644 "$1/$notice_file" "$INSTALL_DIR/$notice_file" || return 1
612
+ done
613
+ }
614
+
458
615
  install_release_binary() {
459
616
  local binary_name
460
617
  local download_url
461
618
  local temp_file
462
619
 
463
620
  binary_name=$(detect_binary_name)
464
- download_url="${GITEA_BASE_URL}/${GITEA_REPO}/releases/download/${VERSION}/${binary_name}"
621
+ download_url=$(release_asset_url "$binary_name")
465
622
  temp_file="$TEMP_DIR/$binary_name"
466
623
 
467
624
  echo "Downloading {{displayName}} binary: $download_url"
468
- if ! curl -fSL "$download_url" -o "$temp_file"; then
625
+ if ! curl "${CURL_OPTS[@]}" -fSL "$download_url" -o "$temp_file"; then
469
626
  echo "Error: could not download $download_url; the current installation is untouched" >&2
470
627
  exit 1
471
628
  fi
472
629
  verify_release_checksum "$temp_file" "$binary_name"
473
630
  chmod 0755 "$temp_file"
474
631
 
632
+ # The third-party notices are installed with the executable, under their release asset names.
633
+ local notice_file
634
+ local notice_dir="$TEMP_DIR/notices"
635
+ select_notice_files "$binary_name"
636
+ mkdir -p "$notice_dir"
637
+ for notice_file in ${NOTICE_FILES[@]+"${NOTICE_FILES[@]}"}; do
638
+ echo "Downloading notices: $(release_asset_url "$notice_file")"
639
+ if ! curl "${CURL_OPTS[@]}" -fSL "$(release_asset_url "$notice_file")" -o "$notice_dir/$notice_file"; then
640
+ echo "Error: could not download the notice file $notice_file of $VERSION; the current installation is untouched" >&2
641
+ exit 1
642
+ fi
643
+ verify_release_checksum "$notice_dir/$notice_file" "$notice_file"
644
+ done
645
+
646
+ # The extra release assets installed beside the executable.
647
+ local extra
648
+ local extra_name
649
+ local extra_dir="$TEMP_DIR/extras"
650
+ mkdir -p "$extra_dir"
651
+ for extra in ${EXTRA_FILES[@]+"${EXTRA_FILES[@]}"}; do
652
+ extra_name="${extra%%:*}"
653
+ echo "Downloading: $(release_asset_url "$extra_name")"
654
+ if ! curl "${CURL_OPTS[@]}" -fSL "$(release_asset_url "$extra_name")" -o "$extra_dir/$extra_name"; then
655
+ echo "Error: could not download $extra_name of $VERSION; the current installation is untouched" >&2
656
+ exit 1
657
+ fi
658
+ verify_release_checksum "$extra_dir/$extra_name" "$extra_name"
659
+ done
660
+
475
661
  # The new binary must run before the current installation is touched.
476
662
  echo "Validating downloaded binary..."
477
663
  if ! "$temp_file" --version >/dev/null; then
@@ -485,6 +671,8 @@ install_release_binary() {
485
671
  echo "Installing binary to $INSTALL_DIR"
486
672
  mkdir -p "$INSTALL_DIR" \
487
673
  && install -m 0755 "$temp_file" "$INSTALL_DIR/{{binary.installFileName}}" \
674
+ && install_notice_files "$notice_dir" \
675
+ && install_extra_files "$extra_dir" \
488
676
  && mkdir -p "$BIN_DIR" \
489
677
  && ln -sf "$INSTALL_DIR/{{binary.installFileName}}" "$BIN_DIR/{{cliName}}" \
490
678
  || abort_update "could not install the binary to $INSTALL_DIR"
@@ -522,6 +710,29 @@ install_source_build() {
522
710
  fi
523
711
  chmod 0755 "$INSTALL_DIR/$executable_file" || abort_update "could not make $INSTALL_DIR/$executable_file executable"
524
712
  done
713
+ # The extra release assets sit beside the executable as in a binary install, with their committed modes.
714
+ local extra
715
+ local extra_name
716
+ local extra_rest
717
+ local extra_path
718
+ for extra in ${EXTRA_FILES[@]+"${EXTRA_FILES[@]}"}; do
719
+ extra_name="${extra%%:*}"
720
+ extra_rest="${extra#*:}"
721
+ extra_path="${extra_rest#*:}"
722
+ if [[ ! -f "$INSTALL_DIR/$extra_path" ]]; then
723
+ abort_update "the source build has no $extra_path, which installer.extraFiles installs as $extra_name"
724
+ fi
725
+ if [[ "$extra_path" != "$extra_name" ]]; then
726
+ if [[ -e "$INSTALL_DIR/$extra_name" || -L "$INSTALL_DIR/$extra_name" ]]; then
727
+ if [[ -L "$INSTALL_DIR/$extra_name" ]] || ! cmp -s "$INSTALL_DIR/$extra_path" "$INSTALL_DIR/$extra_name"; then
728
+ abort_update "the source build already has a different $extra_name; refusing to overwrite it with $extra_path"
729
+ fi
730
+ else
731
+ cp "$INSTALL_DIR/$extra_path" "$INSTALL_DIR/$extra_name" || abort_update "could not copy $extra_path to $INSTALL_DIR/$extra_name"
732
+ fi
733
+ fi
734
+ chmod "${extra_rest%%:*}" "$INSTALL_DIR/$extra_name" || abort_update "could not set the mode of $INSTALL_DIR/$extra_name"
735
+ done
525
736
  mkdir -p "$BIN_DIR" \
526
737
  && ln -sf "$INSTALL_DIR/{{installer.source.executable}}" "$BIN_DIR/{{cliName}}" \
527
738
  || abort_update "could not link $BIN_DIR/{{cliName}}"
@@ -2,10 +2,10 @@
2
2
  // Managed by @git.zone/cli from assets/templates/asset_binary_postinstall. Do not edit by hand.
3
3
 
4
4
  import { arch, constants, platform } from 'node:os';
5
- import { existsSync } from 'node:fs';
5
+ import { closeSync, constants as fsConstants, existsSync, openSync } from 'node:fs';
6
6
  import { dirname, join } from 'node:path';
7
7
  import { fileURLToPath } from 'node:url';
8
- import { spawnSync } from 'node:child_process';
8
+ import { spawn } from 'node:child_process';
9
9
 
10
10
  const __filename = fileURLToPath(import.meta.url);
11
11
  const __dirname = dirname(__filename);
@@ -29,18 +29,67 @@ if (!existsSync(binaryPath)) {
29
29
  process.exit(1);
30
30
  }
31
31
 
32
- const result = spawnSync(binaryPath, process.argv.slice(2), { stdio: 'inherit' });
33
- if (result.error) {
34
- console.error(result.error.message);
35
- process.exit(1);
36
- }
37
- if (result.signal) {
38
- // Die of the same signal, so callers see what ended the binary. Node ignores some signals
39
- // (SIGPIPE) and starts its inspector on SIGUSR1; those end with the shell convention 128 + n.
40
- if (result.signal !== 'SIGUSR1') {
41
- process.removeAllListeners(result.signal);
42
- process.kill(process.pid, result.signal);
32
+ // Without a controlling terminal (setsid, docker run without -t, a detached spawn) no Ctrl+C can reach the
33
+ // binary through a terminal, so SIGINT is forwarded like SIGTERM. Opening /dev/tty only names an existing
34
+ // controlling terminal and cannot acquire one; ENXIO means there is none. O_NONBLOCK keeps a serial line
35
+ // without carrier from holding the open.
36
+ const hasNoTerminal = () => {
37
+ let fd;
38
+ try {
39
+ fd = openSync('/dev/tty', fsConstants.O_RDONLY | fsConstants.O_NONBLOCK);
40
+ return false;
41
+ } catch (error) {
42
+ return error.code === 'ENXIO';
43
+ } finally {
44
+ if (fd !== undefined) closeSync(fd);
45
+ }
46
+ };
47
+ const forwardInterrupt = platform() !== 'win32' && hasNoTerminal();
48
+
49
+ const child = spawn(binaryPath, process.argv.slice(2), { stdio: 'inherit' });
50
+
51
+ // Pass termination requests on to the binary while it runs; the wrapper ends when the binary does.
52
+ // SIGTERM and SIGHUP usually reach the wrapper's pid alone (kill <pid>, kill -HUP $MAINPID), so they are forwarded.
53
+ // With a controlling terminal SIGINT is not: a terminal Ctrl+C goes to the whole foreground process group and
54
+ // reaches the binary directly, so forwarding would deliver it twice. The wrapper only ignores SIGINT until the
55
+ // binary ends, which also ignores a parent's child.kill('SIGINT') (Node names no sender): send SIGTERM, or spawn
56
+ // the wrapper detached. Windows has no POSIX signals: a console Ctrl+C reaches the binary directly, and
57
+ // child.kill() would terminate it outright, so the wrapper forwards nothing there.
58
+ // A signal sent to the whole process group (systemd's default KillMode=control-group, kill -TERM -<pgid>, and
59
+ // without a terminal also a group SIGINT such as tini -g or KillSignal=SIGINT) reaches the binary directly and
60
+ // once more through the wrapper: supervisors should run the native binary, or use KillMode=mixed with this wrapper.
61
+ const forwardedSignals = platform() === 'win32' ? [] : ['SIGTERM', 'SIGHUP', ...(forwardInterrupt ? ['SIGINT'] : [])];
62
+ const forwardSignal = (signal) => {
63
+ if (child.exitCode === null && child.signalCode === null) {
64
+ child.kill(signal);
43
65
  }
44
- process.exit(128 + (constants.signals[result.signal] ?? 0));
66
+ };
67
+ const ignoreSignal = () => {};
68
+ for (const signal of forwardedSignals) {
69
+ process.on(signal, forwardSignal);
70
+ }
71
+ if (platform() !== 'win32' && !forwardInterrupt) {
72
+ process.on('SIGINT', ignoreSignal);
45
73
  }
46
- process.exit(result.status ?? 1);
74
+
75
+ child.on('error', (error) => {
76
+ console.error(error.message);
77
+ process.exit(1);
78
+ });
79
+
80
+ child.on('exit', (code, signal) => {
81
+ for (const forwardedSignal of forwardedSignals) {
82
+ process.removeListener(forwardedSignal, forwardSignal);
83
+ }
84
+ process.removeListener('SIGINT', ignoreSignal);
85
+ if (signal) {
86
+ // Die of the same signal, so callers see what ended the binary. Node ignores some signals
87
+ // (SIGPIPE) and starts its inspector on SIGUSR1; those end with the shell convention 128 + n.
88
+ if (signal !== 'SIGUSR1') {
89
+ process.removeAllListeners(signal);
90
+ process.kill(process.pid, signal);
91
+ }
92
+ process.exit(128 + (constants.signals[signal] ?? 0));
93
+ }
94
+ process.exit(code ?? 1);
95
+ });
@@ -16,6 +16,8 @@ const REPO_BASE = '{{{repository.baseUrl}}}';
16
16
  const PACKAGE_ROOT = resolve(__dirname, '..');
17
17
  const VERSION = JSON.parse(readFileSync(join(PACKAGE_ROOT, 'package.json'), 'utf8')).version;
18
18
  const RELEASE_BASE = `${REPO_BASE}/releases/download/v${VERSION}`;
19
+ /** A SemVer 2.0 version; the release tag is it with a leading v. Nothing else goes into a download URL. */
20
+ const VERSION_PATTERN = /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-(0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)(\.(0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*))*)?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/;
19
21
  const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
20
22
  const MAX_REDIRECTS = 10;
21
23
  /** Connecting and every silence while transferring. */
@@ -28,6 +30,12 @@ const BINARY_MAP = new Map([
28
30
  ['{{nodeKey}}', '{{name}}'],
29
31
  {{/each}}
30
32
  ]);
33
+ /** The third-party notice files each executable's release ships; they are installed beside it. */
34
+ const NOTICE_FILES = new Map([
35
+ {{#each binary.targets}}
36
+ ['{{name}}', [{{#each noticeFiles}}{{#unless @first}}, {{/unless}}'{{this}}'{{/each}}]],
37
+ {{/each}}
38
+ ]);
31
39
 
32
40
  /**
33
41
  * npm, pnpm, Yarn and Bun place every installed package, local or global, inside a
@@ -116,9 +124,10 @@ function fetchHttps(url, consume) {
116
124
  });
117
125
  }
118
126
 
119
- /** The SHA-256 SHA256SUMS.txt of the release lists for `name`. */
120
- async function expectedDigest(name) {
121
- const sums = await fetchHttps(`${RELEASE_BASE}/SHA256SUMS.txt`, async (response) => {
127
+ let releaseSums;
128
+ /** The release's SHA256SUMS.txt, fetched once. */
129
+ function fetchReleaseSums() {
130
+ releaseSums ??= fetchHttps(`${RELEASE_BASE}/SHA256SUMS.txt`, async (response) => {
122
131
  let text = '';
123
132
  for await (const chunk of response) {
124
133
  text += chunk;
@@ -126,6 +135,12 @@ async function expectedDigest(name) {
126
135
  }
127
136
  return text;
128
137
  });
138
+ return releaseSums;
139
+ }
140
+
141
+ /** The SHA-256 SHA256SUMS.txt of the release lists for `name`. */
142
+ async function expectedDigest(name) {
143
+ const sums = await fetchReleaseSums();
129
144
  for (const line of sums.split(/\r?\n/)) {
130
145
  const match = /^([0-9a-fA-F]{64})\s+\*?(.+?)\s*$/.exec(line);
131
146
  if (match && match[2] === name) return match[1].toLowerCase();
@@ -133,25 +148,19 @@ async function expectedDigest(name) {
133
148
  throw new Error(`SHA256SUMS.txt of v${VERSION} has no entry for ${name}`);
134
149
  }
135
150
 
136
- /** Downloads `url` next to `destination`, verifies its SHA-256 and only then moves it into place. */
137
- async function downloadVerified(url, destination, digest) {
138
- const partial = `${destination}.download-${process.pid}`;
139
- try {
140
- const actual = await fetchHttps(url, (response) => new Promise((resolveDigest, rejectDigest) => {
141
- const hash = createHash('sha256');
142
- const file = createWriteStream(partial, { mode: 0o600 });
143
- response.on('data', (chunk) => hash.update(chunk));
144
- response.on('error', rejectDigest);
145
- file.on('error', rejectDigest);
146
- file.on('finish', () => resolveDigest(hash.digest('hex')));
147
- response.pipe(file);
148
- }));
149
- if (actual !== digest) {
150
- throw new Error(`checksum mismatch: SHA256SUMS.txt lists ${digest}, the download is ${actual}`);
151
- }
152
- renameSync(partial, destination);
153
- } finally {
154
- rmSync(partial, { force: true });
151
+ /** Downloads `url` to `partial` and fails unless its SHA-256 is `digest`. */
152
+ async function downloadVerified(url, partial, digest) {
153
+ const actual = await fetchHttps(url, (response) => new Promise((resolveDigest, rejectDigest) => {
154
+ const hash = createHash('sha256');
155
+ const file = createWriteStream(partial, { mode: 0o600 });
156
+ response.on('data', (chunk) => hash.update(chunk));
157
+ response.on('error', rejectDigest);
158
+ file.on('error', rejectDigest);
159
+ file.on('finish', () => resolveDigest(hash.digest('hex')));
160
+ response.pipe(file);
161
+ }));
162
+ if (actual !== digest) {
163
+ throw new Error(`checksum mismatch: SHA256SUMS.txt lists ${digest}, the download is ${actual}`);
155
164
  }
156
165
  }
157
166
 
@@ -161,6 +170,11 @@ async function main() {
161
170
  return;
162
171
  }
163
172
 
173
+ if (typeof VERSION !== 'string' || !VERSION_PATTERN.test(VERSION)) {
174
+ console.error(`Error: the version ${JSON.stringify(VERSION)} in package.json is not a SemVer version; refusing to build a release URL from it`);
175
+ process.exit(1);
176
+ }
177
+
164
178
  console.log('===========================================');
165
179
  console.log(' {{displayName}} - Binary Installation');
166
180
  console.log('===========================================');
@@ -179,23 +193,47 @@ async function main() {
179
193
  }
180
194
 
181
195
  const binaryPath = join(binariesDir, binaryInfo.binaryName);
182
- if (existsSync(binaryPath)) {
183
- console.log('Binary already exists, skipping download');
196
+ // The executable and its third-party notices travel together: a missing notice file is fetched
197
+ // even when the executable is already in place.
198
+ const releaseFiles = [binaryInfo.binaryName, ...(NOTICE_FILES.get(binaryInfo.binaryName) ?? [])];
199
+ const missingFiles = releaseFiles.filter((name) => !existsSync(join(binariesDir, name)));
200
+ if (missingFiles.length === 0) {
201
+ console.log('Binary and notices already exist, skipping download');
184
202
  } else {
185
- const releaseUrl = `${RELEASE_BASE}/${binaryInfo.binaryName}`;
203
+ if (!missingFiles.includes(binaryInfo.binaryName)) {
204
+ console.log('Binary already exists, downloading its missing notice files');
205
+ }
206
+ const partials = new Map(missingFiles.map((name) => [name, join(binariesDir, `${name}.download-${process.pid}`)]));
186
207
  let failedUrl = `${RELEASE_BASE}/SHA256SUMS.txt`;
187
208
  try {
188
- const digest = await expectedDigest(binaryInfo.binaryName);
189
- failedUrl = releaseUrl;
190
- console.log(`Downloading from: ${releaseUrl}`);
191
- await downloadVerified(releaseUrl, binaryPath, digest);
209
+ // Every file needs its checksum entry before anything downloads.
210
+ const digests = new Map();
211
+ for (const name of missingFiles) {
212
+ digests.set(name, await expectedDigest(name));
213
+ }
214
+ for (const name of missingFiles) {
215
+ const releaseUrl = `${RELEASE_BASE}/${name}`;
216
+ failedUrl = releaseUrl;
217
+ console.log(`Downloading from: ${releaseUrl}`);
218
+ await downloadVerified(releaseUrl, partials.get(name), digests.get(name));
219
+ console.log(`Checksum verified: ${name}`);
220
+ }
221
+ // Only a complete, verified set moves into place, the executable last.
222
+ for (const name of [...missingFiles].reverse()) {
223
+ if (name !== binaryInfo.binaryName) {
224
+ chmodSync(partials.get(name), 0o644);
225
+ }
226
+ renameSync(partials.get(name), join(binariesDir, name));
227
+ }
192
228
  } catch (error) {
229
+ for (const partial of partials.values()) {
230
+ rmSync(partial, { force: true });
231
+ }
193
232
  console.error(`Error: Failed to install the {{displayName}} ${VERSION} binary for ${binaryInfo.key}`);
194
233
  console.error(` URL: ${failedUrl}`);
195
234
  console.error(` Cause: ${error.message}`);
196
235
  process.exit(1);
197
236
  }
198
- console.log(`Checksum verified: ${binaryInfo.binaryName}`);
199
237
  }
200
238
 
201
239
  if (binaryInfo.platform !== 'win32') {