@saptools/cf-debugger 0.3.0 → 0.3.1

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
@@ -117,7 +117,11 @@ When region, org, or space is omitted, the current `cf target` supplies it.
117
117
  > restarting the named app is acceptable. `CF_DEBUGGER_ALLOW_RESTART=0` keeps
118
118
  > the guard enabled for a production shell and also vetoes a programmatic
119
119
  > `allowSshEnableRestart: true`. The environment value `1` can opt in the CLI,
120
- > but never grants permission to a programmatic caller by itself.
120
+ > but never grants permission to a programmatic caller by itself. CF CLI v7+
121
+ > used to reach this path as `SSH_PERMISSION_DENIED`, so an existing opt-in
122
+ > (flag, environment value, or programmatic option) could never restart an app
123
+ > with those CLIs; it now can, when `cf ssh-enabled` names the app itself as the
124
+ > layer that disables SSH.
121
125
 
122
126
  `--api-endpoint` accepts arbitrary hostnames but requires an absolute `https:`
123
127
  URL with no userinfo, query, fragment, or non-root path. Invalid values are
@@ -127,16 +131,39 @@ endpoint.
127
131
 
128
132
  Even with permission, a restart occurs only when all of these are true:
129
133
 
130
- 1. the one-shot SSH error specifically says SSH support is disabled;
131
- 2. `cf ssh-enabled <app>` proves app-level SSH is disabled;
134
+ 1. the one-shot SSH attempt fails with the generic "not authorized" error that
135
+ CF CLI v6.40+ and v7+ print for an app whose own SSH flag is off, or with an
136
+ older "SSH support is disabled" diagnostic;
137
+ 2. `cf ssh-enabled <app>` names the app itself as the layer that disables SSH
138
+ (CF CLI v7+ prints that reason line);
132
139
  3. this invocation runs `cf enable-ssh <app>`;
133
- 4. a second probe proves app-level SSH is now enabled.
140
+ 4. a second probe proves SSH is now enabled.
134
141
 
135
- An unknown probe result, an already-enabled app, a permission error, or a
136
- space-level SSH policy never causes a restart. Before an allowed restart,
137
- stderr names the app and org/space. With an explicit `--node-pid`, automatic
138
- restart is always rejected because the container replacement invalidates that
139
- PID.
142
+ The CLI prints the same "not authorized" error for an app whose SSH flag is
143
+ off as for a user without the Space Developer role, so after any such failure
144
+ cf-debugger first runs the read-only `cf ssh-enabled <app>` probe, and only
145
+ then checks the restart permission:
146
+
147
+ | Probe result | Outcome |
148
+ | --- | --- |
149
+ | SSH enabled | `SSH_PERMISSION_DENIED`: check the role and the space policy, or restart an app whose SSH was enabled after it started |
150
+ | State unknown (probe failed) | `SSH_PERMISSION_DENIED` (or `SSH_STATE_UNKNOWN` after the older diagnostic), with the probe error |
151
+ | Disabled by a space or platform policy | `SSH_POLICY_DISABLED`; the app is never changed |
152
+ | Disabled, but no layer named (for example CF CLI v6) | `SSH_STATE_UNKNOWN`; the app is never changed |
153
+ | Disabled for the app itself | `SSH_NOT_ENABLED` with the opt-in hint, or the guarded enable and restart |
154
+
155
+ Copy-paste commands in these messages start with
156
+ `cf login -a <api> -o <org> -s <space> &&` for the session's API endpoint,
157
+ because cf-debugger uses its own `CF_HOME` and your shell may be logged in to
158
+ another landscape (`cf api` alone would log the CLI out, so one `cf login`
159
+ selects the API, org, and space before the command runs). Only Space Developers and admins may change an app's SSH feature
160
+ (Space Supporters may restart apps but not enable SSH), so a user without SSH
161
+ access is stopped at `cf enable-ssh` before any restart. If the confirming
162
+ probe fails after `cf enable-ssh`, startup fails with `SSH_STATE_UNKNOWN`
163
+ without a restart, and the app's SSH flag may already be on. Before an allowed
164
+ restart, stderr names the app and org/space. With an explicit `--node-pid`,
165
+ automatic restart is always rejected because the container replacement
166
+ invalidates that PID.
140
167
 
141
168
  Read-only CF commands have a 60-second per-attempt cap and retry transient
142
169
  transport errors with bounded exponential delays while the single overall
@@ -232,7 +259,8 @@ with `UNKNOWN_REGION`.
232
259
 
233
260
  1. Resolve and validate the endpoint, deadline, target, and credentials.
234
261
  2. Prune only provably stale state and register a unique session/port.
235
- 3. Run `cf api`, environment-only `cf auth`, `cf target`, and an app existence check.
262
+ 3. Run `cf api`, environment-only `cf auth`, `cf target`, and a GUID-only app
263
+ existence check (`cf app <app> --guid`).
236
264
  4. Probe the selected instance through one-shot `cf ssh`.
237
265
  5. If an inspector already owns the remote port and is Node, reuse that PID.
238
266
  6. Otherwise:
@@ -259,9 +287,13 @@ results. GNU `find -lname` is capability-probed and is normally fast; the
259
287
  portable fallback walks descriptors with `readlink` and can take roughly
260
288
  10–12 seconds in a descriptor-heavy non-GNU container.
261
289
 
262
- `--remote-port` does not choose the port opened by `SIGUSR1`; Node always uses
263
- its default inspector port for that signal. A non-default value is therefore
264
- for an app already started with matching `--inspect=<port>`.
290
+ `--remote-port` does not choose the port opened by `SIGUSR1`. Node opens the
291
+ port from the app's own `--inspect-port` option (default `9229`, also settable
292
+ through `NODE_OPTIONS`), so a non-default value is for an app started with a
293
+ matching `--inspect=<port>` or `--inspect-port=<port>`. When the requested
294
+ port never opens but the selected process now listens on `9229`,
295
+ `INSPECTOR_NOT_READY` says so. That inspector stays open until the instance
296
+ restarts, and a start without `--remote-port` reuses it.
265
297
 
266
298
  ### Status sequence
267
299
 
@@ -355,7 +387,8 @@ domain code; it is never converted into success.
355
387
  | `CF_MUTATION_TIMEOUT` | A deployment mutation timed out, was not retried, and may still be completing remotely |
356
388
  | `STARTUP_TIMEOUT`, `ABORTED` | Overall deadline expired, or caller/stop intent cancelled startup |
357
389
  | `APP_NOT_FOUND` | The targeted app does not exist in the selected org/space |
358
- | `SSH_NOT_ENABLED`, `SSH_PERMISSION_DENIED`, `SSH_STATE_UNKNOWN` | Restart refused/not useful, permission denied, or SSH state ambiguous |
390
+ | `SSH_NOT_ENABLED`, `SSH_PERMISSION_DENIED`, `SSH_STATE_UNKNOWN` | SSH is off for the app itself, enablement failed, or a restart would not help; `cf ssh-enabled` reports SSH as enabled (or cannot verify it) yet access is denied; or the probe could not prove which layer disables SSH, or could not confirm SSH after `cf enable-ssh` ran (the app's SSH flag may then be on; no restart was attempted) |
391
+ | `SSH_POLICY_DISABLED` | A space or platform policy disables SSH; cf-debugger never changes policy or the app, even with restart permission |
359
392
  | `NODE_PID_RESTART_UNSAFE` | Explicit PID cannot survive an app restart |
360
393
  | `NODE_PROCESS_NOT_FOUND`, `NODE_PROCESS_AMBIGUOUS`, `NODE_PID_INVALID` | Remote Node selection failed closed |
361
394
  | `USR1_SIGNAL_FAILED`, `INSPECTOR_NOT_READY`, `INSPECTOR_OWNER_MISMATCH`, `INSPECTOR_OUTPUT_TOO_LARGE` | Remote signal/ownership protocol failed |
@@ -418,8 +451,31 @@ Not by default. Inspector activation sends `SIGUSR1` to the verified Node
418
451
  process, but app-level SSH enablement and `cf restart` require explicit
419
452
  `--allow-ssh-enable-restart` permission. Even with permission, restart occurs
420
453
  only after this run changes app SSH from proven disabled to proven enabled; an
421
- already-enabled, unknown, permission-denied, or space-policy result never
422
- restarts the app.
454
+ already-enabled, unknown, permission-denied, or space/platform-policy result,
455
+ or a probe that does not name the app as the disabling layer, never restarts
456
+ the app. If `cf enable-ssh` ran but its effect could not be confirmed, startup
457
+ stops before the restart and says that the app's SSH flag may now be on.
458
+
459
+ The inspector that `SIGUSR1` opens listens on the container's loopback
460
+ interface and stays open after `stop`, which closes only the local tunnel. It
461
+ closes when that app instance restarts, and a later `start` reuses it without
462
+ another signal. Readiness checks only read `/json/list`; cf-debugger never
463
+ attaches a debugger session itself.
464
+
465
+ ### How can I confirm what happened inside the app container?
466
+
467
+ Node writes its inspector events to the app's stderr, so they appear in the
468
+ app log stream:
469
+
470
+ | Log line | Meaning |
471
+ | --- | --- |
472
+ | `Debugger listening on ws://127.0.0.1:9229/<id>` | `SIGUSR1` opened the inspector |
473
+ | `Debugger attached.` | A debugger client connected through the tunnel |
474
+ | `Debugger ending on ws://127.0.0.1:9229/<id>` | The last client disconnected; the inspector keeps listening |
475
+
476
+ A busy app can push these lines out of `cf logs <app> --recent` within
477
+ seconds, so search a historical log backend (for example SAP Cloud Logging)
478
+ when you need them later.
423
479
 
424
480
  ### Is session state always removed when the CLI exits?
425
481
 
@@ -204,13 +204,14 @@ function redactSensitiveText(text, values) {
204
204
  function normalizeSensitiveValues(values) {
205
205
  return [...new Set(values.filter((value) => value.length > 0))].sort((left, right) => right.length - left.length);
206
206
  }
207
+ function startupDeadlineLabel(startupTimeoutMs) {
208
+ return startupTimeoutMs === void 0 ? "configured" : `${(startupTimeoutMs / 1e3).toString()}s`;
209
+ }
207
210
  function abortError(context) {
208
211
  if (context.deadlineAt !== void 0 && Date.now() >= context.deadlineAt) {
209
- const timeoutMs = context.startupTimeoutMs;
210
- const duration = timeoutMs === void 0 ? "configured" : `${(timeoutMs / 1e3).toString()}s`;
211
212
  return new CfDebuggerError(
212
213
  "STARTUP_TIMEOUT",
213
- `Debugger startup exceeded its ${duration} deadline during ${context.phase ?? "a CF command"}.`
214
+ `Debugger startup exceeded its ${startupDeadlineLabel(context.startupTimeoutMs)} deadline during ${context.phase ?? "a CF command"}.`
214
215
  );
215
216
  }
216
217
  return new CfDebuggerError("ABORTED", "Operation aborted by caller");
@@ -443,11 +444,9 @@ function mutationTimeoutError(args, redactionValues) {
443
444
  }
444
445
  function timeoutError(context, args, redactionValues) {
445
446
  if (context.deadlineAt !== void 0) {
446
- const timeoutMs = context.startupTimeoutMs;
447
- const duration = timeoutMs === void 0 ? "configured" : `${(timeoutMs / 1e3).toString()}s`;
448
447
  return new CfDebuggerError(
449
448
  "STARTUP_TIMEOUT",
450
- `Debugger startup could not complete within its ${duration} deadline during ${context.phase ?? "a CF command"}.`
449
+ `Debugger startup could not complete within its ${startupDeadlineLabel(context.startupTimeoutMs)} deadline during ${context.phase ?? "a CF command"}.`
451
450
  );
452
451
  }
453
452
  return new CfDebuggerError(
@@ -593,7 +592,7 @@ async function cfTarget(org, space, context) {
593
592
  async function cfAppExists(appName, context) {
594
593
  try {
595
594
  await runCf({
596
- args: ["app", appName],
595
+ args: ["app", appName, "--guid"],
597
596
  retryPolicy: "retry-transient"
598
597
  }, context);
599
598
  return true;
@@ -606,23 +605,36 @@ async function cfAppExists(appName, context) {
606
605
  throw err;
607
606
  }
608
607
  }
608
+ function sshDisabledScope(lines) {
609
+ if (lines.includes("ssh is disabled globally")) {
610
+ return "global";
611
+ }
612
+ if (lines.some((line) => line.startsWith("ssh is disabled for space"))) {
613
+ return "space";
614
+ }
615
+ return lines.includes("ssh is disabled for app") ? "app" : void 0;
616
+ }
617
+ function parseSshEnabledOutput(stdout) {
618
+ const lines = stdout.split(/\r?\n/).map((line) => line.trim().toLowerCase()).filter((line) => line.length > 0);
619
+ if (lines.some((line) => line.startsWith("ssh support is enabled"))) {
620
+ return { state: "enabled" };
621
+ }
622
+ if (!lines.some((line) => line.startsWith("ssh support is disabled"))) {
623
+ return { state: "unknown" };
624
+ }
625
+ const disabledScope = sshDisabledScope(lines);
626
+ return disabledScope === void 0 ? { state: "disabled" } : { state: "disabled", disabledScope };
627
+ }
609
628
  async function cfSshEnabled(appName, context) {
610
629
  try {
611
630
  const stdout = await runCf({
612
631
  args: ["ssh-enabled", appName],
613
632
  retryPolicy: "retry-transient"
614
633
  }, context);
615
- const normalized = stdout.toLowerCase();
616
- if (normalized.includes("ssh support is enabled")) {
617
- return "enabled";
618
- }
619
- if (normalized.includes("ssh support is disabled")) {
620
- return "disabled";
621
- }
622
- return "unknown";
634
+ return parseSshEnabledOutput(stdout);
623
635
  } catch (err) {
624
636
  rethrowControlFlowError(err);
625
- return "unknown";
637
+ return { state: "unknown", detail: err instanceof Error ? err.message : String(err) };
626
638
  }
627
639
  }
628
640
  async function cfEnableSsh(appName, context) {
@@ -768,11 +780,13 @@ function resolveNodeTarget(input) {
768
780
  validateNodePid(input.nodePid);
769
781
  return input.nodePid === void 0 ? { process: processName, instance } : { process: processName, instance, nodePid: input.nodePid };
770
782
  }
783
+ function procPortHex(port) {
784
+ return port.toString(16).toUpperCase().padStart(4, "0");
785
+ }
771
786
  function buildNodeInspectorCommand(nodePid, remotePort = DEFAULT_NODE_INSPECTOR_PORT) {
772
787
  validateNodePid(nodePid);
773
788
  validateRemotePort(remotePort);
774
- const remotePortHex = remotePort.toString(16).toUpperCase().padStart(4, "0");
775
- return NODE_INSPECTOR_SCRIPT.replace("__REQUESTED_NODE_PID__", nodePid?.toString() ?? "").replaceAll("__INSPECTOR_PORT_HEX__", remotePortHex);
789
+ return NODE_INSPECTOR_SCRIPT.replace("__REQUESTED_NODE_PID__", nodePid?.toString() ?? "").replaceAll("__INSPECTOR_PORT_HEX__", procPortHex(remotePort)).replaceAll("__DEFAULT_INSPECTOR_PORT_HEX__", procPortHex(DEFAULT_NODE_INSPECTOR_PORT));
776
790
  }
777
791
  function parseNodeInspectorMarkers(stdout, remotePort = DEFAULT_NODE_INSPECTOR_PORT) {
778
792
  validateRemotePort(remotePort);
@@ -829,11 +843,18 @@ function throwForRuntimeFailure(markers, remotePort) {
829
843
  throw new CfDebuggerError("USR1_SIGNAL_FAILED", `Failed to signal remote Node PID ${safePidText(signalFailed)}.`);
830
844
  }
831
845
  if (markers.has("saptools-inspector-not-ready")) {
832
- throw new CfDebuggerError(
833
- "INSPECTOR_NOT_READY",
834
- `Remote Node inspector did not become ready on port ${remotePort.toString()}.`
835
- );
846
+ throw new CfDebuggerError("INSPECTOR_NOT_READY", inspectorNotReadyMessage(markers, remotePort));
847
+ }
848
+ }
849
+ function inspectorNotReadyMessage(markers, remotePort) {
850
+ const port = remotePort.toString();
851
+ const message = `Remote Node inspector did not become ready on port ${port}.`;
852
+ const selectedPid = readMarkerPid(markers, "saptools-inspector-not-ready");
853
+ const defaultPortOwner = readMarkerPid(markers, "saptools-inspector-default-port-owner");
854
+ if (remotePort === DEFAULT_NODE_INSPECTOR_PORT || selectedPid === void 0 || defaultPortOwner !== selectedPid) {
855
+ return message;
836
856
  }
857
+ return `${message} Node PID ${selectedPid.toString()} is listening on the default inspector port ${DEFAULT_NODE_INSPECTOR_PORT.toString()} instead, and that inspector stays open until the instance restarts. Re-run without --remote-port, or start the app with --inspect-port=${port}.`;
837
858
  }
838
859
  function readMarkerPid(markers, name) {
839
860
  const raw = markers.get(name);
@@ -849,6 +870,7 @@ function safePidText(raw) {
849
870
  var NODE_INSPECTOR_SCRIPT = [
850
871
  "requested_node_pid=__REQUESTED_NODE_PID__",
851
872
  "inspector_port_hex=__INSPECTOR_PORT_HEX__",
873
+ "default_inspector_port_hex=__DEFAULT_INSPECTOR_PORT_HEX__",
852
874
  "is_node_pid() {",
853
875
  ' candidate_pid="$1"',
854
876
  ' candidate_exe="$(readlink "/proc/$candidate_pid/exe" 2>/dev/null || true)"',
@@ -922,6 +944,14 @@ var NODE_INSPECTOR_SCRIPT = [
922
944
  ` app_port_hex="$(printf '%04X' "$PORT" 2>/dev/null || true)"`,
923
945
  ' find_listener_pid "$app_port_hex"',
924
946
  "}",
947
+ "report_default_inspector_owner() {",
948
+ ' [ "$inspector_port_hex" != "$default_inspector_port_hex" ] || return 0',
949
+ ' default_inode="$(find_listener_inode "$default_inspector_port_hex")"',
950
+ ' [ -n "$default_inode" ] || return 0',
951
+ ' if pid_owns_inode "$selected_pid" "$default_inode"; then',
952
+ ' echo "saptools-inspector-default-port-owner=$selected_pid"',
953
+ " fi",
954
+ "}",
925
955
  "find_supports_lname=false",
926
956
  "if find /proc/self/fd -lname __saptools_no_match__ -print -quit >/dev/null 2>&1; then",
927
957
  " find_supports_lname=true",
@@ -978,6 +1008,7 @@ var NODE_INSPECTOR_SCRIPT = [
978
1008
  // CF Linux stacks accept fractional sleep; retain a one-second POSIX fallback.
979
1009
  " sleep 0.25 2>/dev/null || sleep 1",
980
1010
  "done",
1011
+ "report_default_inspector_owner",
981
1012
  'echo "saptools-inspector-not-ready=$selected_pid"'
982
1013
  ].join("\n");
983
1014
 
@@ -1077,7 +1108,7 @@ function sshAbortError(context) {
1077
1108
  if (context.deadlineAt !== void 0 && Date.now() >= context.deadlineAt) {
1078
1109
  return new CfDebuggerError(
1079
1110
  "STARTUP_TIMEOUT",
1080
- `Debugger startup exceeded its configured deadline during ${context.phase ?? "remote signalling"}.`
1111
+ `Debugger startup exceeded its ${startupDeadlineLabel(context.startupTimeoutMs)} deadline during ${context.phase ?? "remote signalling"}.`
1081
1112
  );
1082
1113
  }
1083
1114
  return new CfDebuggerError("ABORTED", "Operation aborted by caller");
@@ -3131,7 +3162,6 @@ async function registerNewSession(input) {
3131
3162
  }
3132
3163
  function withoutMessage(session) {
3133
3164
  const { message, ...clone } = session;
3134
- void message;
3135
3165
  return clone;
3136
3166
  }
3137
3167
  function startupMutationBlocked(session) {
@@ -3175,7 +3205,6 @@ async function updateSessionPid(sessionId, pid, access2) {
3175
3205
  return target;
3176
3206
  }
3177
3207
  const { tunnelProcessIdentity: previousIdentity, ...base } = target;
3178
- void previousIdentity;
3179
3208
  const next = {
3180
3209
  ...base,
3181
3210
  pid,
@@ -3762,7 +3791,7 @@ function throwIfStartupAborted(signal, expiresAt, timeoutMs, phase) {
3762
3791
 
3763
3792
  // src/debug-session/start.ts
3764
3793
  import { chmod as chmod4, mkdir as mkdir4 } from "fs/promises";
3765
- import nodeProcess7 from "process";
3794
+ import nodeProcess8 from "process";
3766
3795
 
3767
3796
  // src/debug-session/orphans.ts
3768
3797
  import { readdir as readdir2, stat as stat2, unlink as unlink4 } from "fs/promises";
@@ -3856,6 +3885,18 @@ function createStartupCancellation(sessionId, callerSignal) {
3856
3885
  };
3857
3886
  }
3858
3887
 
3888
+ // src/debug-session/startup-remote.ts
3889
+ import nodeProcess7 from "process";
3890
+
3891
+ // src/shell-quote.ts
3892
+ var SHELL_SAFE_WORD = /^[A-Za-z0-9_@%+:,./][A-Za-z0-9_@%+=:,./-]*$/;
3893
+ function shellQuoteForCommand(value) {
3894
+ return `'${value.replaceAll("'", `'"'"'`)}'`;
3895
+ }
3896
+ function shellWord(value) {
3897
+ return SHELL_SAFE_WORD.test(value) ? value : shellQuoteForCommand(value);
3898
+ }
3899
+
3859
3900
  // src/debug-session/startup-remote.ts
3860
3901
  function signalFailureDetail(result) {
3861
3902
  if (result.timedOutAfterMs !== void 0) {
@@ -3906,65 +3947,108 @@ async function executeRemoteSignal(inputs) {
3906
3947
  }
3907
3948
  );
3908
3949
  }
3909
- function restartRefusal(options, stderr) {
3910
- return new CfDebuggerError(
3911
- "SSH_NOT_ENABLED",
3912
- `SSH is disabled for ${options.app}. Re-run with --allow-ssh-enable-restart, or run \`cf enable-ssh ${options.app} && cf restart ${options.app}\` manually.`,
3913
- stderr
3914
- );
3950
+ function inTarget(inputs, command) {
3951
+ const { org, space } = inputs.options;
3952
+ return `\`cf login -a ${shellWord(inputs.apiEndpoint)} -o ${shellWord(org)} -s ${shellWord(space)} && ${command}\``;
3953
+ }
3954
+ function enableAndRestartCommand(inputs) {
3955
+ const app = shellWord(inputs.options.app);
3956
+ return inTarget(inputs, `cf enable-ssh ${app} && cf restart ${app}`);
3957
+ }
3958
+ function restartAdvice(inputs) {
3959
+ const manual = enableAndRestartCommand(inputs);
3960
+ if (nodeProcess7.env["CF_DEBUGGER_ALLOW_RESTART"] === "0") {
3961
+ return `CF_DEBUGGER_ALLOW_RESTART=0 forbids automatic enablement; run ${manual} yourself.`;
3962
+ }
3963
+ if (inputs.target.nodePid !== void 0) {
3964
+ return `cf-debugger never restarts an app while targeting an explicit Node PID; run ${manual} yourself, then select the new Node PID.`;
3965
+ }
3966
+ return `Re-run with --allow-ssh-enable-restart (enabling SSH needs the Space Developer role), or run ${manual} yourself.`;
3915
3967
  }
3916
3968
  function ensureRestartSafe(inputs, stderr) {
3917
3969
  if (inputs.options.allowSshEnableRestart !== true) {
3918
- throw restartRefusal(inputs.options, stderr);
3970
+ throw new CfDebuggerError(
3971
+ "SSH_NOT_ENABLED",
3972
+ `SSH is disabled for ${inputs.options.app}. ${restartAdvice(inputs)}`,
3973
+ stderr
3974
+ );
3919
3975
  }
3920
3976
  if (inputs.target.nodePid !== void 0) {
3921
3977
  throw new CfDebuggerError(
3922
3978
  "NODE_PID_RESTART_UNSAFE",
3923
- `Cannot restart ${inputs.options.app} while targeting Node PID ${inputs.target.nodePid.toString()}; restart manually and select its new PID.`,
3979
+ `Cannot restart ${inputs.options.app} while targeting Node PID ${inputs.target.nodePid.toString()}; run ${enableAndRestartCommand(inputs)} yourself, then select the new Node PID.`,
3924
3980
  stderr
3925
3981
  );
3926
3982
  }
3927
3983
  }
3928
- async function enableAppSsh(inputs, stderr) {
3929
- ensureRestartSafe(inputs, stderr);
3930
- const state = await cfSshEnabled(
3931
- inputs.options.app,
3932
- { ...inputs.context, phase: "checking app SSH state" }
3933
- );
3934
- if (state === "enabled") {
3984
+ async function probeSshEnablement(inputs, phase) {
3985
+ return await cfSshEnabled(inputs.options.app, { ...inputs.context, phase });
3986
+ }
3987
+ function probeDetail(enablement) {
3988
+ return enablement.detail === void 0 ? "" : ` (${enablement.detail})`;
3989
+ }
3990
+ function rejectSshPolicy(inputs, enablement, stderr) {
3991
+ const { app, space } = inputs.options;
3992
+ if (enablement.disabledScope === "space") {
3935
3993
  throw new CfDebuggerError(
3936
- "SSH_NOT_ENABLED",
3937
- `SSH is already enabled for ${inputs.options.app}, so restarting it is not a remedy. Check space-level SSH policy and your Developer role.`,
3994
+ "SSH_POLICY_DISABLED",
3995
+ `SSH is disabled for space ${space}, so enabling SSH for ${app} or restarting it cannot help; no deployment change was made. A space or org manager can allow it with ${inTarget(inputs, `cf allow-space-ssh ${shellWord(space)}`)}.`,
3938
3996
  stderr
3939
3997
  );
3940
3998
  }
3941
- if (state === "unknown") {
3999
+ if (enablement.disabledScope === "global") {
3942
4000
  throw new CfDebuggerError(
3943
- "SSH_STATE_UNKNOWN",
3944
- `Could not verify whether SSH is enabled for ${inputs.options.app}; no deployment change was made.`,
4001
+ "SSH_POLICY_DISABLED",
4002
+ `SSH is disabled for the whole Cloud Foundry platform, so enabling SSH for ${app} or restarting it cannot help; no deployment change was made.`,
3945
4003
  stderr
3946
4004
  );
3947
4005
  }
3948
- inputs.emit("ssh-enabling", "Enabling app-level SSH");
3949
- await inputs.transition("ssh-enabling", "Enabling app-level SSH");
3950
- await cfEnableSsh(
3951
- inputs.options.app,
3952
- { ...inputs.context, phase: "enabling app SSH" }
4006
+ }
4007
+ function requireAppLevelDisable(inputs, enablement, stderr) {
4008
+ rejectSshPolicy(inputs, enablement, stderr);
4009
+ if (enablement.disabledScope === "app") {
4010
+ return;
4011
+ }
4012
+ const { app, space } = inputs.options;
4013
+ throw new CfDebuggerError(
4014
+ "SSH_STATE_UNKNOWN",
4015
+ `cf ssh-enabled reported SSH as disabled for ${app} without naming whether the app, its space, or the platform disables it, so no deployment change was made. Check the space with ${inTarget(inputs, `cf space-ssh-allowed ${shellWord(space)}`)}; if it allows SSH, run \`cf enable-ssh ${shellWord(app)} && cf restart ${shellWord(app)}\` in that target yourself.`,
4016
+ stderr
3953
4017
  );
3954
- const confirmed = await cfSshEnabled(
3955
- inputs.options.app,
3956
- { ...inputs.context, phase: "confirming app SSH state" }
4018
+ }
4019
+ function sshPermissionDenied(inputs, enablement, stderr) {
4020
+ const { app, org, space } = inputs.options;
4021
+ const detail = enablement.state === "enabled" ? `\`cf ssh-enabled\` reports SSH as enabled, so check that your user has the Space Developer role in ${org}/${space} and that the space allows SSH (\`cf space-ssh-allowed ${shellWord(space)}\`; older CLIs report only the app flag), or restart the app if SSH was enabled after it last started.` : `Its SSH state could not be verified with \`cf ssh-enabled\`${probeDetail(enablement)}; check your Space Developer role and the app, space, and platform SSH settings.`;
4022
+ return new CfDebuggerError(
4023
+ "SSH_PERMISSION_DENIED",
4024
+ `CF SSH permission was denied for ${app}. ${detail}`,
4025
+ stderr
3957
4026
  );
3958
- if (confirmed !== "enabled") {
4027
+ }
4028
+ function sshProbeContradiction(inputs, enablement, stderr) {
4029
+ const { app } = inputs.options;
4030
+ return enablement.state === "enabled" ? new CfDebuggerError(
4031
+ "SSH_NOT_ENABLED",
4032
+ `SSH is already enabled for ${app}, so restarting it is not a remedy. Check the space SSH policy and your Space Developer role.`,
4033
+ stderr
4034
+ ) : new CfDebuggerError(
4035
+ "SSH_STATE_UNKNOWN",
4036
+ `Could not verify whether SSH is enabled for ${app}${probeDetail(enablement)}; no deployment change was made.`,
4037
+ stderr
4038
+ );
4039
+ }
4040
+ async function enableAndRestart(inputs) {
4041
+ const { app, org, space } = inputs.options;
4042
+ inputs.emit("ssh-enabling", "Enabling app-level SSH");
4043
+ await inputs.transition("ssh-enabling", "Enabling app-level SSH");
4044
+ await cfEnableSsh(app, { ...inputs.context, phase: "enabling app SSH" });
4045
+ const confirmed = await probeSshEnablement(inputs, "confirming app SSH state");
4046
+ if (confirmed.state !== "enabled") {
3959
4047
  throw new CfDebuggerError(
3960
4048
  "SSH_STATE_UNKNOWN",
3961
- `App-level SSH enablement for ${inputs.options.app} could not be confirmed; no restart was attempted.`
4049
+ `cf enable-ssh ran for ${app}, but cf ssh-enabled did not confirm SSH as enabled${probeDetail(confirmed)}, so no restart was attempted; the app's SSH flag may now be on.`
3962
4050
  );
3963
4051
  }
3964
- }
3965
- async function enableAndRestart(inputs, stderr) {
3966
- await enableAppSsh(inputs, stderr);
3967
- const { app, org, space } = inputs.options;
3968
4052
  inputs.warn(
3969
4053
  `Restarting app ${app} in ${org}/${space} so newly enabled SSH becomes active.`
3970
4054
  );
@@ -3972,6 +4056,15 @@ async function enableAndRestart(inputs, stderr) {
3972
4056
  await inputs.transition("ssh-restarting", "Restarting app so SSH becomes active");
3973
4057
  await cfRestartApp(app, { ...inputs.context, phase: "restarting the app" });
3974
4058
  }
4059
+ async function recoverUnavailableSsh(inputs, stderr, authorizationError) {
4060
+ const enablement = await probeSshEnablement(inputs, "checking app SSH state");
4061
+ if (enablement.state !== "disabled") {
4062
+ throw authorizationError ? sshPermissionDenied(inputs, enablement, stderr) : sshProbeContradiction(inputs, enablement, stderr);
4063
+ }
4064
+ requireAppLevelDisable(inputs, enablement, stderr);
4065
+ ensureRestartSafe(inputs, stderr);
4066
+ await enableAndRestart(inputs);
4067
+ }
3975
4068
  async function retrySignal(inputs) {
3976
4069
  inputs.emit("signaling");
3977
4070
  await inputs.transition("signaling");
@@ -3999,17 +4092,11 @@ async function signalRemoteNode(inputs) {
3999
4092
  if (result.exitCode === 0) {
4000
4093
  return parseSignalResult(inputs.options.app, remotePort, result);
4001
4094
  }
4002
- if (isSshPermissionError(result.stderr)) {
4003
- throw new CfDebuggerError(
4004
- "SSH_PERMISSION_DENIED",
4005
- `CF SSH permission was denied for ${inputs.options.app}. Check your space role and SSH policy.`,
4006
- result.stderr
4007
- );
4008
- }
4009
- if (!isSshDisabledError(result.stderr)) {
4095
+ const authorizationError = isSshPermissionError(result.stderr);
4096
+ if (!authorizationError && !isSshDisabledError(result.stderr)) {
4010
4097
  return parseSignalResult(inputs.options.app, remotePort, result);
4011
4098
  }
4012
- await enableAndRestart(inputs, result.stderr);
4099
+ await recoverUnavailableSsh(inputs, result.stderr, authorizationError);
4013
4100
  return await retrySignal(inputs);
4014
4101
  }
4015
4102
 
@@ -4106,6 +4193,9 @@ function createReadyWindow(timeoutMs) {
4106
4193
  ownerTimeoutMs
4107
4194
  };
4108
4195
  }
4196
+ function bindBudgetLabel(timeoutMs) {
4197
+ return timeoutMs < 1e3 ? `${timeoutMs.toString()}ms` : `${Math.round(timeoutMs / 1e3).toString()}s`;
4198
+ }
4109
4199
  function remainingWindowMs(window) {
4110
4200
  return Math.max(0, window.deadlineAt - Date.now());
4111
4201
  }
@@ -4163,7 +4253,7 @@ async function waitForLocalTunnel(inputs, child, timeoutMs) {
4163
4253
  }
4164
4254
  throw new CfDebuggerError(
4165
4255
  "TUNNEL_NOT_READY",
4166
- `SSH tunnel on local port ${inputs.session.localPort.toString()} did not bind within ${Math.round(timeoutMs / 1e3).toString()}s.`,
4256
+ `SSH tunnel on local port ${inputs.session.localPort.toString()} did not bind within ${bindBudgetLabel(timeoutMs)}.`,
4167
4257
  diagnosticsStderr(child)
4168
4258
  );
4169
4259
  }
@@ -4303,8 +4393,8 @@ function validateStartTarget(options) {
4303
4393
  };
4304
4394
  }
4305
4395
  function requireCredentials(options) {
4306
- const email = options.email ?? nodeProcess7.env["SAP_EMAIL"];
4307
- const password = options.password ?? nodeProcess7.env["SAP_PASSWORD"];
4396
+ const email = options.email ?? nodeProcess8.env["SAP_EMAIL"];
4397
+ const password = options.password ?? nodeProcess8.env["SAP_PASSWORD"];
4308
4398
  if (email === void 0 || email.length === 0) {
4309
4399
  throw new CfDebuggerError(
4310
4400
  "MISSING_CREDENTIALS",
@@ -4463,6 +4553,7 @@ async function establishDebuggerSession(inputs) {
4463
4553
  options: inputs.options,
4464
4554
  target: inputs.target,
4465
4555
  context: inputs.context,
4556
+ apiEndpoint: inputs.session.apiEndpoint,
4466
4557
  transition: inputs.transition,
4467
4558
  emit: inputs.emit,
4468
4559
  warn: writeWarning
@@ -4490,11 +4581,11 @@ async function establishDebuggerSession(inputs) {
4490
4581
  return readySession;
4491
4582
  }
4492
4583
  function writeWarning(message) {
4493
- nodeProcess7.stderr.write(`[cf-debugger] warning: ${message}
4584
+ nodeProcess8.stderr.write(`[cf-debugger] warning: ${message}
4494
4585
  `);
4495
4586
  }
4496
4587
  function writeTunnelOutput(stream, text) {
4497
- nodeProcess7.stderr.write(`[cf-debugger tunnel ${stream}] ${text}
4588
+ nodeProcess8.stderr.write(`[cf-debugger tunnel ${stream}] ${text}
4498
4589
  `);
4499
4590
  }
4500
4591
  function retryMessage(status) {
@@ -4540,7 +4631,7 @@ function resolveStartupPlan(options) {
4540
4631
  const validatedOptions = validateStartTarget(options);
4541
4632
  const restartAllowed = applyRestartEnvironmentVeto(
4542
4633
  validatedOptions.allowSshEnableRestart,
4543
- nodeProcess7.env["CF_DEBUGGER_ALLOW_RESTART"]
4634
+ nodeProcess8.env["CF_DEBUGGER_ALLOW_RESTART"]
4544
4635
  );
4545
4636
  const effectiveOptions = restartAllowed === validatedOptions.allowSshEnableRestart ? validatedOptions : { ...validatedOptions, allowSshEnableRestart: restartAllowed };
4546
4637
  const target = resolveNodeTarget(effectiveOptions);
@@ -4657,7 +4748,7 @@ import {
4657
4748
  } from "fs/promises";
4658
4749
  import { hostname as hostname4 } from "os";
4659
4750
  import { join as join5 } from "path";
4660
- import nodeProcess10 from "process";
4751
+ import nodeProcess11 from "process";
4661
4752
 
4662
4753
  // src/debug-session/doctor-homes.ts
4663
4754
  import { readdir as readdir3 } from "fs/promises";
@@ -4704,7 +4795,7 @@ async function discoverOrphanHomes(sessions) {
4704
4795
  import { lstat as lstat2, readFile as readFile6, readdir as readdir4 } from "fs/promises";
4705
4796
  import { hostname as hostname2 } from "os";
4706
4797
  import { join as join4 } from "path";
4707
- import nodeProcess8 from "process";
4798
+ import nodeProcess9 from "process";
4708
4799
  var LEGACY_STATE_FILENAME = "cf-debugger-state.json";
4709
4800
  var LEGACY_LOCK_FILENAME = "cf-debugger-state.lock";
4710
4801
  var LEGACY_HOMES_DIRNAME = "cf-debugger-homes";
@@ -4731,7 +4822,7 @@ function optionalInteger2(value, key, maximum = Number.MAX_SAFE_INTEGER) {
4731
4822
  }
4732
4823
  function inspectLegacyPid(pid) {
4733
4824
  try {
4734
- nodeProcess8.kill(pid, 0);
4825
+ nodeProcess9.kill(pid, 0);
4735
4826
  return {
4736
4827
  liveness: "alive",
4737
4828
  reason: "PID exists, but v1 state cannot prove process identity or tunnel ownership"
@@ -4828,9 +4919,6 @@ async function inspectLegacyHomes(path) {
4828
4919
  };
4829
4920
  }
4830
4921
  }
4831
- function shellQuoteForCommand(value) {
4832
- return `'${value.replaceAll("'", `'"'"'`)}'`;
4833
- }
4834
4922
  async function findLegacyArtifacts() {
4835
4923
  const statePath = join4(saptoolsDir(), LEGACY_STATE_FILENAME);
4836
4924
  const lockPath = join4(saptoolsDir(), LEGACY_LOCK_FILENAME);
@@ -4863,10 +4951,10 @@ async function findLegacyArtifacts() {
4863
4951
 
4864
4952
  // src/debug-session/doctor-session-health.ts
4865
4953
  import { hostname as hostname3 } from "os";
4866
- import nodeProcess9 from "process";
4954
+ import nodeProcess10 from "process";
4867
4955
  function missingIdentityCaveat(session) {
4868
4956
  const identity = session.status === "ready" ? session.tunnelProcessIdentity : session.controllerProcessIdentity;
4869
- return (nodeProcess9.platform === "linux" || nodeProcess9.platform === "darwin") && identity === void 0 ? "process identity token is absent, so PID-only compatibility is in use; an older cf-debugger sharing this state file may have stripped the additive field" : void 0;
4957
+ return (nodeProcess10.platform === "linux" || nodeProcess10.platform === "darwin") && identity === void 0 ? "process identity token is absent, so PID-only compatibility is in use; an older cf-debugger sharing this state file may have stripped the additive field" : void 0;
4870
4958
  }
4871
4959
  async function inspectDoctorSessions(sessions) {
4872
4960
  const local = sessions.filter((session) => session.hostname === hostname3());
@@ -5117,7 +5205,7 @@ function parseLockOwner2(raw) {
5117
5205
  }
5118
5206
  function isPidAlive2(pid) {
5119
5207
  try {
5120
- nodeProcess10.kill(pid, 0);
5208
+ nodeProcess11.kill(pid, 0);
5121
5209
  return true;
5122
5210
  } catch (error) {
5123
5211
  return errorCode9(error) !== "ESRCH";
@@ -5318,7 +5406,7 @@ async function runDoctor(options = {}) {
5318
5406
 
5319
5407
  // src/debug-session/sessions.ts
5320
5408
  import { hostname as getHostname4 } from "os";
5321
- import nodeProcess11 from "process";
5409
+ import nodeProcess12 from "process";
5322
5410
  function findMatchingSession(sessions, options) {
5323
5411
  if (options.sessionId !== void 0) {
5324
5412
  return sessions.find((session) => session.sessionId === options.sessionId);
@@ -5361,8 +5449,8 @@ async function ownsRecordedTunnel(target) {
5361
5449
  }
5362
5450
  async function terminateVerifiedTunnel(target, recordExpectedStop) {
5363
5451
  const tunnelPid = target.tunnelPid;
5364
- if (tunnelPid === void 0 || tunnelPid === nodeProcess11.pid) {
5365
- return tunnelPid === nodeProcess11.pid ? "still-alive" : "terminated";
5452
+ if (tunnelPid === void 0 || tunnelPid === nodeProcess12.pid) {
5453
+ return tunnelPid === nodeProcess12.pid ? "still-alive" : "terminated";
5366
5454
  }
5367
5455
  let stopIntentRecorded = false;
5368
5456
  try {
@@ -5617,4 +5705,4 @@ export {
5617
5705
  listSessions,
5618
5706
  getSession
5619
5707
  };
5620
- //# sourceMappingURL=chunk-QBB4N2WN.js.map
5708
+ //# sourceMappingURL=chunk-4UAIE7V6.js.map