@zero-transfer/ssh 0.4.2 → 0.4.7

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/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { EventEmitter } from 'node:events';
2
2
  import { SecureVersion, PeerCertificate } from 'node:tls';
3
3
  import { Readable } from 'node:stream';
4
- import { Buffer } from 'node:buffer';
4
+ import { Buffer as Buffer$1 } from 'node:buffer';
5
5
  import { Socket } from 'node:net';
6
6
  import { KeyObject } from 'node:crypto';
7
7
 
@@ -183,7 +183,7 @@ interface CapabilitySet {
183
183
  */
184
184
 
185
185
  /** Resolved secret value accepted by profile credential fields. */
186
- type SecretValue = string | Buffer;
186
+ type SecretValue = string | Buffer$1;
187
187
  /** Callback source used by applications to integrate vaults or credential brokers. */
188
188
  type SecretProvider = () => SecretValue | Promise<SecretValue>;
189
189
  /** Inline secret descriptor. Prefer env, path, or callback sources for real applications. */
@@ -215,7 +215,7 @@ interface ResolveSecretOptions {
215
215
  /** Environment source. Defaults to `process.env`. */
216
216
  env?: NodeJS.ProcessEnv;
217
217
  /** File reader. Defaults to `fs.promises.readFile`. */
218
- readFile?: (path: string) => Promise<Buffer> | Buffer;
218
+ readFile?: (path: string) => Promise<Buffer$1> | Buffer$1;
219
219
  }
220
220
  /**
221
221
  * Resolves a secret source into a string or Buffer without logging the value.
@@ -396,7 +396,7 @@ interface TlsProfile {
396
396
  * hex form with or without colons. When present, the TLS handshake additionally requires the
397
397
  * leaf certificate's SHA-256 fingerprint to match one of these values.
398
398
  *
399
- * Not required for normal CA-trusted endpoints public CAs and `ca` bundles already gate
399
+ * Not required for normal CA-trusted endpoints - public CAs and `ca` bundles already gate
400
400
  * trust via `rejectUnauthorized`. Pinning is **recommended for production** when you control
401
401
  * the server and want defence-in-depth against rogue certificates issued by trusted CAs.
402
402
  *
@@ -1724,7 +1724,7 @@ interface ConnectionPoolOptions {
1724
1724
  /**
1725
1725
  * Maximum number of *idle* sessions retained per pool key.
1726
1726
  *
1727
- * Active leases are not counted against this limit the cap only applies
1727
+ * Active leases are not counted against this limit - the cap only applies
1728
1728
  * to sessions waiting in the pool. When more than `maxIdlePerKey` sessions
1729
1729
  * become idle simultaneously, the oldest ones are disconnected. Defaults
1730
1730
  * to `4`.
@@ -3004,7 +3004,7 @@ interface DiffRemoteTreesOptions {
3004
3004
  * Compares two remote subtrees and produces an entry-level diff.
3005
3005
  *
3006
3006
  * Source and destination paths are walked independently; entries are then aligned by
3007
- * the relative path from each tree root. Directory equality is structural directories
3007
+ * the relative path from each tree root. Directory equality is structural - directories
3008
3008
  * are equal when their relative paths match and the entry types agree.
3009
3009
  *
3010
3010
  * @param source - Source-side remote file system.
@@ -3249,7 +3249,7 @@ interface CreateAtomicDeployPlanOptions {
3249
3249
  * 2. Atomically swap the `current` symlink/rename to point at the new release.
3250
3250
  * 3. Optionally prune old releases beyond `retain`.
3251
3251
  *
3252
- * No I/O is performed the host executes the plan steps. Pair with
3252
+ * No I/O is performed - the host executes the plan steps. Pair with
3253
3253
  * {@link createTransferPlan} or {@link createTransferJobsFromPlan} to execute.
3254
3254
  *
3255
3255
  * @param options - Inputs and policies that shape the deploy.
@@ -3469,6 +3469,12 @@ declare function joinRemotePath(...segments: string[]): string;
3469
3469
  */
3470
3470
  declare function basenameRemotePath(input: string): string;
3471
3471
 
3472
+ /**
3473
+ * Returns `true` when the file containing `import.meta.url` is the entry point
3474
+ * of the current Node.js process. Returns `false` outside Node.
3475
+ */
3476
+ declare function isMainModule(importMetaUrl: string): boolean;
3477
+
3472
3478
  /** Algorithm lists exchanged during SSH KEXINIT negotiation. */
3473
3479
  interface SshAlgorithmPreferences {
3474
3480
  compressionClientToServer: readonly string[];
@@ -3514,7 +3520,7 @@ interface SshIdentification {
3514
3520
 
3515
3521
  /** Parsed SSH_MSG_KEXINIT payload. */
3516
3522
  interface SshKexInitMessage extends SshAlgorithmPreferences {
3517
- cookie: Buffer;
3523
+ cookie: Buffer$1;
3518
3524
  firstKexPacketFollows: boolean;
3519
3525
  messageType: number;
3520
3526
  reserved: number;
@@ -3522,31 +3528,31 @@ interface SshKexInitMessage extends SshAlgorithmPreferences {
3522
3528
 
3523
3529
  /** Directional key material used after SSH NEWKEYS. */
3524
3530
  interface SshTransportDirectionKeys {
3525
- encryptionKey: Buffer;
3526
- iv: Buffer;
3527
- macKey: Buffer;
3531
+ encryptionKey: Buffer$1;
3532
+ iv: Buffer$1;
3533
+ macKey: Buffer$1;
3528
3534
  }
3529
3535
  /** Session key bundle derived from K, H, and session id. */
3530
3536
  interface SshDerivedSessionKeys {
3531
3537
  clientToServer: SshTransportDirectionKeys;
3532
- exchangeHash: Buffer;
3538
+ exchangeHash: Buffer$1;
3533
3539
  serverToClient: SshTransportDirectionKeys;
3534
- sessionId: Buffer;
3540
+ sessionId: Buffer$1;
3535
3541
  }
3536
3542
 
3537
3543
  /** Initial client-side handshake state before key exchange math starts. */
3538
3544
  interface SshTransportHandshakeResult {
3539
3545
  keyExchange: {
3540
3546
  algorithm: string;
3541
- clientKexInitPayload: Buffer;
3542
- clientPublicKey: Buffer;
3543
- exchangeHash: Buffer;
3544
- serverHostKey: Buffer;
3545
- serverKexInitPayload: Buffer;
3546
- serverPublicKey: Buffer;
3547
- serverSignature: Buffer;
3548
- sessionId: Buffer;
3549
- sharedSecret: Buffer;
3547
+ clientKexInitPayload: Buffer$1;
3548
+ clientPublicKey: Buffer$1;
3549
+ exchangeHash: Buffer$1;
3550
+ serverHostKey: Buffer$1;
3551
+ serverKexInitPayload: Buffer$1;
3552
+ serverPublicKey: Buffer$1;
3553
+ serverSignature: Buffer$1;
3554
+ sessionId: Buffer$1;
3555
+ sharedSecret: Buffer$1;
3550
3556
  transportKeys: {
3551
3557
  clientToServer: SshDerivedSessionKeys["clientToServer"];
3552
3558
  serverToClient: SshDerivedSessionKeys["serverToClient"];
@@ -3599,18 +3605,18 @@ declare class SshTransportHandshake {
3599
3605
  * to enforce known_hosts or pinned-fingerprint policies.
3600
3606
  */
3601
3607
  verifyHostKey?: (input: {
3602
- hostKeyBlob: Buffer;
3603
- hostKeySha256: Buffer;
3608
+ hostKeyBlob: Buffer$1;
3609
+ hostKeySha256: Buffer$1;
3604
3610
  algorithmName: string;
3605
3611
  }) => void | Promise<void>;
3606
3612
  });
3607
3613
  /** Creates the first outbound bytes (client identification line). */
3608
- createInitialClientBytes(): Buffer;
3614
+ createInitialClientBytes(): Buffer$1;
3609
3615
  /**
3610
3616
  * Feeds raw server bytes into the handshake state machine.
3611
3617
  */
3612
3618
  pushServerBytes(chunk: Uint8Array): {
3613
- outbound: Buffer[];
3619
+ outbound: Buffer$1[];
3614
3620
  result?: SshTransportHandshakeResult;
3615
3621
  };
3616
3622
  getServerBannerLines(): readonly string[];
@@ -3620,7 +3626,7 @@ declare class SshTransportHandshake {
3620
3626
  * Call this once after `pushServerBytes` returns a result to drain bytes that belong to the
3621
3627
  * post-NEWKEYS encrypted phase but arrived in the same TCP segment as NEWKEYS.
3622
3628
  */
3623
- takeRemainingBytes(): Buffer;
3629
+ takeRemainingBytes(): Buffer$1;
3624
3630
  private pushServerBytesWithPhase;
3625
3631
  }
3626
3632
 
@@ -3668,8 +3674,8 @@ interface SshTransportConnectionOptions {
3668
3674
  * exchange hash is verified. Throw to reject the server's identity.
3669
3675
  */
3670
3676
  verifyHostKey?: (input: {
3671
- hostKeyBlob: Buffer;
3672
- hostKeySha256: Buffer;
3677
+ hostKeyBlob: Buffer$1;
3678
+ hostKeySha256: Buffer$1;
3673
3679
  algorithmName: string;
3674
3680
  }) => void;
3675
3681
  }
@@ -3716,7 +3722,7 @@ declare class SshTransportConnection {
3716
3722
  * Sends an SSH payload over the encrypted transport.
3717
3723
  * The payload must start with the SSH message type byte.
3718
3724
  */
3719
- sendPayload(payload: Buffer | Uint8Array): void;
3725
+ sendPayload(payload: Buffer$1 | Uint8Array): void;
3720
3726
  /**
3721
3727
  * Async generator that yields inbound SSH payloads (post-NEWKEYS).
3722
3728
  *
@@ -3725,7 +3731,7 @@ declare class SshTransportConnection {
3725
3731
  * - SSH_MSG_DISCONNECT (1) from the server throws a `ConnectionError`.
3726
3732
  * - Socket error or close terminates the generator.
3727
3733
  */
3728
- receivePayloads(): AsyncGenerator<Buffer>;
3734
+ receivePayloads(): AsyncGenerator<Buffer$1>;
3729
3735
  /**
3730
3736
  * Sends SSH_MSG_DISCONNECT and ends the socket.
3731
3737
  * Safe to call multiple times; subsequent calls are no-ops.
@@ -3775,7 +3781,7 @@ interface SshKeyboardInteractiveCredential {
3775
3781
  type SshCredential = SshPasswordCredential | SshPublickeyCredential | SshKeyboardInteractiveCredential;
3776
3782
  interface SshAuthOptions {
3777
3783
  credential: SshCredential;
3778
- /** SSH session id (exchange hash) from key exchange required for publickey signing. */
3784
+ /** SSH session id (exchange hash) from key exchange - required for publickey signing. */
3779
3785
  sessionId: Uint8Array;
3780
3786
  /** Maximum number of USERAUTH_FAILURE retries before giving up. Defaults to 4. */
3781
3787
  maxAttempts?: number;
@@ -3892,7 +3898,7 @@ declare class SshSessionChannel {
3892
3898
  * Async generator that yields raw data buffers from the channel.
3893
3899
  * Returns (done) when the channel receives EOF or CLOSE.
3894
3900
  */
3895
- receiveData(): AsyncGenerator<Buffer, void, undefined>;
3901
+ receiveData(): AsyncGenerator<Buffer$1, void, undefined>;
3896
3902
  /**
3897
3903
  * Sends EOF and CLOSE. Should be called when the client is done sending.
3898
3904
  */
@@ -3901,7 +3907,7 @@ declare class SshSessionChannel {
3901
3907
  * Feed an inbound transport payload to this channel.
3902
3908
  * Called by the channel multiplexer (`SshConnectionManager`).
3903
3909
  */
3904
- dispatch(payload: Buffer): void;
3910
+ dispatch(payload: Buffer$1): void;
3905
3911
  dispatchError(error: Error): void;
3906
3912
  private consumeLocalWindow;
3907
3913
  private enqueueInbound;
@@ -3941,7 +3947,7 @@ declare class SshConnectionManager {
3941
3947
  * Channel setup happens sequentially before `start()` begins pumping, so we
3942
3948
  * pull directly from the transport iterator here.
3943
3949
  */
3944
- nextSetupPayload(): Promise<Buffer>;
3950
+ nextSetupPayload(): Promise<Buffer$1>;
3945
3951
  /**
3946
3952
  * Opens a session channel and starts the SFTP subsystem on it.
3947
3953
  * Must be called before `start()`.
@@ -3982,10 +3988,10 @@ declare class SshDataReader {
3982
3988
  hasMore(): boolean;
3983
3989
  readByte(): number;
3984
3990
  readBoolean(): boolean;
3985
- readBytes(length: number): Buffer;
3991
+ readBytes(length: number): Buffer$1;
3986
3992
  readUint32(): number;
3987
3993
  readUint64(): bigint;
3988
- readString(): Buffer;
3994
+ readString(): Buffer$1;
3989
3995
  readUtf8String(): string;
3990
3996
  readNameList(): string[];
3991
3997
  /**
@@ -3993,7 +3999,7 @@ declare class SshDataReader {
3993
3999
  * big-endian integer. Returns the raw magnitude bytes (non-negative integers
3994
4000
  * may have a leading 0x00 byte preserved by the caller as needed).
3995
4001
  */
3996
- readMpint(): Buffer;
4002
+ readMpint(): Buffer$1;
3997
4003
  assertFinished(): void;
3998
4004
  private ensureAvailable;
3999
4005
  }
@@ -4012,9 +4018,74 @@ declare class SshDataWriter {
4012
4018
  writeString(value: string | Uint8Array, encoding?: BufferEncoding): this;
4013
4019
  writeMpint(value: Uint8Array): this;
4014
4020
  writeNameList(values: readonly string[]): this;
4015
- toBuffer(): Buffer;
4021
+ toBuffer(): Buffer$1;
4016
4022
  private push;
4017
4023
  private assertByte;
4018
4024
  }
4019
4025
 
4020
- export { AbortError, type AtomicDeployActivateOperation, type AtomicDeployActivateStep, type AtomicDeployPlan, type AtomicDeployPruneStep, type AtomicDeployStrategy, type AuthenticationCapability, AuthenticationError, AuthorizationError, type BandwidthSleep, type BandwidthThrottle, type BandwidthThrottleOptions, type Base64EnvSecretSource, type BuiltInProviderId, CLASSIC_PROVIDER_IDS, type CapabilitySet, type ChecksumCapability, type ClassicProviderId, type ClientDiagnostics, type CompareRemoteManifestsOptions, ConfigurationError, type ConnectionDiagnosticTimings, type ConnectionDiagnosticsResult, ConnectionError, type ConnectionPoolOptions, type ConnectionProfile, type CopyBetweenOptions, type CreateAtomicDeployPlanOptions, type CreateRemoteBrowserOptions, type CreateRemoteManifestOptions, type CreateSyncPlanOptions, DEFAULT_SSH_ALGORITHM_PREFERENCES, type DiffRemoteTreesOptions, type DownloadFileOptions, type EnvSecretSource, type FileSecretSource, type FileZillaSite, type FriendlyTransferOptions, type FtpReplyErrorInput, type ImportFileZillaSitesResult, type ImportOpenSshConfigOptions, type ImportOpenSshConfigResult, type ImportWinScpSessionsResult, type KnownHostsEntry, type KnownHostsMarker, type ListOptions, type LocalProviderOptions, type LogLevel, type LogRecord, type LogRecordInput, type LoggerMethod, type MemoryProviderEntry, type MemoryProviderOptions, type MetadataCapability, type MkdirOptions, type NegotiatedSshAlgorithms, type OAuthAccessToken, type OAuthRefreshCallback, type OAuthTokenSecretSourceOptions, type OpenSshConfigEntry, ParseError, PathAlreadyExistsError, PathNotFoundError, PermissionDeniedError, type PooledTransferClient, type ProgressEventInput, ProtocolError, type AuthenticationCapability as ProviderAuthenticationCapability, type CapabilitySet as ProviderCapabilities, type ChecksumCapability as ProviderChecksumCapability, type ProviderFactory, type ProviderId, type MetadataCapability as ProviderMetadataCapability, ProviderRegistry, type ProviderSelection, type ProviderTransferEndpointRole, type ProviderTransferExecutorOptions, type ProviderTransferOperations, type ProviderTransferReadRequest, type ProviderTransferReadResult, type ProviderTransferRequest, type ProviderTransferSessionResolver, type ProviderTransferSessionResolverInput, type ProviderTransferWriteRequest, type ProviderTransferWriteResult, REDACTED, REMOTE_MANIFEST_FORMAT_VERSION, type RemoteBreadcrumb, type RemoteBrowser, type RemoteBrowserFilter, type RemoteBrowserSnapshot, type RemoteEntry, type RemoteEntrySortKey, type RemoteEntrySortOrder, type RemoteEntryType, type RemoteFileAdapter, type RemoteFileEndpoint, type RemoteFileSystem, type RemoteManifest, type RemoteManifestEntry, type RemotePermissions, type RemoteProtocol, type RemoteStat, type RemoteTreeDiff, type RemoteTreeDiffEntry, type RemoteTreeDiffReason, type RemoteTreeDiffStatus, type RemoteTreeDiffSummary, type RemoteTreeEntry, type RemoteTreeFilter, type RemoveOptions, type RenameOptions, type ResolveSecretOptions, type ResolvedConnectionProfile, type ResolvedOpenSshHost, type ResolvedSshProfile, type ResolvedTlsProfile, type RmdirOptions, type RunConnectionDiagnosticsOptions, type SecretProvider, type SecretSource, type SecretValue, type SpecializedErrorDetails, type SshAgentSource, type SshAlgorithmPreferences, type SshAlgorithms, SshAuthSession, SshConnectionManager, SshDataReader, SshDataWriter, SshDisconnectReason, type SshKeyboardInteractiveChallenge, type SshKeyboardInteractiveCredential, type SshKeyboardInteractiveHandler, type SshKeyboardInteractivePrompt, type SshKnownHostsSource, type SshPasswordCredential, type SshProfile, type SshPublickeyCredential, SshSessionChannel, type SshSocketFactory, type SshSocketFactoryContext, SshTransportConnection, type SshTransportConnectionOptions, SshTransportHandshake, type SshTransportHandshakeResult, type StatOptions, type SyncConflictPolicy, type SyncDeletePolicy, type SyncDirection, type SyncEndpointInput, TimeoutError, type TlsProfile, type TlsSecretSource, type TransferAttempt, type TransferAttemptError, type TransferBandwidthLimit, type TransferByteRange, TransferClient, type TransferClientOptions, type TransferDataChunk, type TransferDataSource, type TransferEndpoint, TransferEngine, type TransferEngineExecuteOptions, type TransferEngineOptions, TransferError, type TransferExecutionContext, type TransferExecutionResult, type TransferExecutor, type TransferJob, type TransferOperation, type TransferPlan, type TransferPlanAction, type TransferPlanInput, type TransferPlanStep, type TransferPlanSummary, type TransferProgressEvent, type TransferProvider, TransferQueue, type TransferQueueExecutorResolver, type TransferQueueItem, type TransferQueueItemStatus, type TransferQueueOptions, type TransferQueueRunOptions, type TransferQueueSummary, type TransferReceipt, type TransferResult, type TransferResultInput, type TransferRetryDecisionInput, type TransferRetryPolicy, type TransferSession, type TransferTimeoutPolicy, type TransferVerificationResult, UnsupportedFeatureError, type UploadFileOptions, type ValueSecretSource, VerificationError, type WalkRemoteTreeOptions, type WinScpSession, ZeroTransfer, type ZeroTransferCapabilities, ZeroTransferError, type ZeroTransferErrorDetails, type ZeroTransferLogger, type ZeroTransferOptions, assertSafeFtpArgument, basenameRemotePath, buildPublickeyCredential, buildRemoteBreadcrumbs, compareRemoteManifests, copyBetween, createAtomicDeployPlan, createBandwidthThrottle, createLocalProviderFactory, createMemoryProviderFactory, createOAuthTokenSecretSource, createPooledTransferClient, createProgressEvent, createProviderTransferExecutor, createRemoteBrowser, createRemoteManifest, createSyncPlan, createTransferClient, createTransferJobsFromPlan, createTransferPlan, createTransferResult, diffRemoteTrees, downloadFile, emitLog, errorFromFtpReply, filterRemoteEntries, importFileZillaSites, importOpenSshConfig, importWinScpSessions, isClassicProviderId, isSensitiveKey, joinRemotePath, matchKnownHosts, matchKnownHostsEntry, negotiateSshAlgorithms, noopLogger, normalizeRemotePath, parentRemotePath, parseKnownHosts, parseOpenSshConfig, parseRemoteManifest, redactCommand, redactConnectionProfile, redactObject, redactSecretSource, redactValue, resolveConnectionProfileSecrets, resolveOpenSshHost, resolveProviderId, resolveSecret, runConnectionDiagnostics, serializeRemoteManifest, sortRemoteEntries, summarizeClientDiagnostics, summarizeTransferPlan, throttleByteIterable, uploadFile, validateConnectionProfile, walkRemoteTree };
4026
+ /**
4027
+ * Options for {@link runSshCommand}.
4028
+ */
4029
+ interface RunSshCommandOptions {
4030
+ /** Hostname or IP of the SSH server. */
4031
+ host: string;
4032
+ /** TCP port. Defaults to `22`. */
4033
+ port?: number;
4034
+ /** Command to execute on the remote shell. */
4035
+ command: string;
4036
+ /**
4037
+ * Authentication credential. Use one of:
4038
+ *
4039
+ * - `{ type: "password", username, password }`
4040
+ * - `{ type: "publickey", username, algorithmName, publicKeyBlob, sign }`
4041
+ * (build one from a private-key file with `buildPublickeyCredential`)
4042
+ * - `{ type: "keyboard-interactive", username, respond }`
4043
+ */
4044
+ auth: SshCredential;
4045
+ /**
4046
+ * Forwarded to {@link SshTransportConnection}; covers host-key pinning,
4047
+ * algorithm overrides, and handshake timeout. The default
4048
+ * `handshakeTimeoutMs` is 10 seconds.
4049
+ */
4050
+ transport?: SshTransportConnectionOptions;
4051
+ /** TCP connect timeout in milliseconds. Defaults to 10 000. */
4052
+ connectTimeoutMs?: number;
4053
+ /** Maximum total bytes captured from stdout. Defaults to 16 MiB. */
4054
+ maxOutputBytes?: number;
4055
+ }
4056
+ /**
4057
+ * Result of {@link runSshCommand}. The full captured stdout is provided as
4058
+ * both a `Buffer` (for binary output) and as a UTF-8 decoded `string`.
4059
+ *
4060
+ * Note: stderr (CHANNEL_EXTENDED_DATA) and exit-status are not currently
4061
+ * surfaced - drop down to {@link SshConnectionManager}/{@link SshSessionChannel}
4062
+ * directly if you need them.
4063
+ */
4064
+ interface RunSshCommandResult {
4065
+ /** Captured stdout as raw bytes. */
4066
+ stdout: Buffer;
4067
+ /** Captured stdout decoded as UTF-8. */
4068
+ stdoutText: string;
4069
+ /** Bytes received before the channel closed. */
4070
+ bytesReceived: number;
4071
+ }
4072
+ /**
4073
+ * Connects, authenticates, runs `command` on a fresh exec channel, drains
4074
+ * stdout, and disconnects. The TCP socket, transport, auth session, and
4075
+ * channel are all owned by this helper and torn down before it returns.
4076
+ *
4077
+ * @example Run `uname -a` with a password credential
4078
+ * ```ts
4079
+ * import { runSshCommand } from "@zero-transfer/ssh";
4080
+ *
4081
+ * const { stdoutText } = await runSshCommand({
4082
+ * host: "ssh.example.com",
4083
+ * auth: { type: "password", username: "deploy", password: process.env.SSH_PASSWORD! },
4084
+ * command: "uname -a",
4085
+ * });
4086
+ * console.log(stdoutText);
4087
+ * ```
4088
+ */
4089
+ declare function runSshCommand(options: RunSshCommandOptions): Promise<RunSshCommandResult>;
4090
+
4091
+ export { AbortError, type AtomicDeployActivateOperation, type AtomicDeployActivateStep, type AtomicDeployPlan, type AtomicDeployPruneStep, type AtomicDeployStrategy, type AuthenticationCapability, AuthenticationError, AuthorizationError, type BandwidthSleep, type BandwidthThrottle, type BandwidthThrottleOptions, type Base64EnvSecretSource, type BuiltInProviderId, CLASSIC_PROVIDER_IDS, type CapabilitySet, type ChecksumCapability, type ClassicProviderId, type ClientDiagnostics, type CompareRemoteManifestsOptions, ConfigurationError, type ConnectionDiagnosticTimings, type ConnectionDiagnosticsResult, ConnectionError, type ConnectionPoolOptions, type ConnectionProfile, type CopyBetweenOptions, type CreateAtomicDeployPlanOptions, type CreateRemoteBrowserOptions, type CreateRemoteManifestOptions, type CreateSyncPlanOptions, DEFAULT_SSH_ALGORITHM_PREFERENCES, type DiffRemoteTreesOptions, type DownloadFileOptions, type EnvSecretSource, type FileSecretSource, type FileZillaSite, type FriendlyTransferOptions, type FtpReplyErrorInput, type ImportFileZillaSitesResult, type ImportOpenSshConfigOptions, type ImportOpenSshConfigResult, type ImportWinScpSessionsResult, type KnownHostsEntry, type KnownHostsMarker, type ListOptions, type LocalProviderOptions, type LogLevel, type LogRecord, type LogRecordInput, type LoggerMethod, type MemoryProviderEntry, type MemoryProviderOptions, type MetadataCapability, type MkdirOptions, type NegotiatedSshAlgorithms, type OAuthAccessToken, type OAuthRefreshCallback, type OAuthTokenSecretSourceOptions, type OpenSshConfigEntry, ParseError, PathAlreadyExistsError, PathNotFoundError, PermissionDeniedError, type PooledTransferClient, type ProgressEventInput, ProtocolError, type ProviderFactory, type ProviderId, ProviderRegistry, type ProviderSelection, type ProviderTransferEndpointRole, type ProviderTransferExecutorOptions, type ProviderTransferOperations, type ProviderTransferReadRequest, type ProviderTransferReadResult, type ProviderTransferRequest, type ProviderTransferSessionResolver, type ProviderTransferSessionResolverInput, type ProviderTransferWriteRequest, type ProviderTransferWriteResult, REDACTED, REMOTE_MANIFEST_FORMAT_VERSION, type RemoteBreadcrumb, type RemoteBrowser, type RemoteBrowserFilter, type RemoteBrowserSnapshot, type RemoteEntry, type RemoteEntrySortKey, type RemoteEntrySortOrder, type RemoteEntryType, type RemoteFileAdapter, type RemoteFileEndpoint, type RemoteFileSystem, type RemoteManifest, type RemoteManifestEntry, type RemotePermissions, type RemoteProtocol, type RemoteStat, type RemoteTreeDiff, type RemoteTreeDiffEntry, type RemoteTreeDiffReason, type RemoteTreeDiffStatus, type RemoteTreeDiffSummary, type RemoteTreeEntry, type RemoteTreeFilter, type RemoveOptions, type RenameOptions, type ResolveSecretOptions, type ResolvedConnectionProfile, type ResolvedOpenSshHost, type ResolvedSshProfile, type ResolvedTlsProfile, type RmdirOptions, type RunConnectionDiagnosticsOptions, type RunSshCommandOptions, type RunSshCommandResult, type SecretProvider, type SecretSource, type SecretValue, type SpecializedErrorDetails, type SshAgentSource, type SshAlgorithmPreferences, type SshAlgorithms, SshAuthSession, SshConnectionManager, SshDataReader, SshDataWriter, SshDisconnectReason, type SshKeyboardInteractiveChallenge, type SshKeyboardInteractiveCredential, type SshKeyboardInteractiveHandler, type SshKeyboardInteractivePrompt, type SshKnownHostsSource, type SshPasswordCredential, type SshProfile, type SshPublickeyCredential, SshSessionChannel, type SshSocketFactory, type SshSocketFactoryContext, SshTransportConnection, type SshTransportConnectionOptions, SshTransportHandshake, type SshTransportHandshakeResult, type StatOptions, type SyncConflictPolicy, type SyncDeletePolicy, type SyncDirection, type SyncEndpointInput, TimeoutError, type TlsProfile, type TlsSecretSource, type TransferAttempt, type TransferAttemptError, type TransferBandwidthLimit, type TransferByteRange, TransferClient, type TransferClientOptions, type TransferDataChunk, type TransferDataSource, type TransferEndpoint, TransferEngine, type TransferEngineExecuteOptions, type TransferEngineOptions, TransferError, type TransferExecutionContext, type TransferExecutionResult, type TransferExecutor, type TransferJob, type TransferOperation, type TransferPlan, type TransferPlanAction, type TransferPlanInput, type TransferPlanStep, type TransferPlanSummary, type TransferProgressEvent, type TransferProvider, TransferQueue, type TransferQueueExecutorResolver, type TransferQueueItem, type TransferQueueItemStatus, type TransferQueueOptions, type TransferQueueRunOptions, type TransferQueueSummary, type TransferReceipt, type TransferResult, type TransferResultInput, type TransferRetryDecisionInput, type TransferRetryPolicy, type TransferSession, type TransferTimeoutPolicy, type TransferVerificationResult, UnsupportedFeatureError, type UploadFileOptions, type ValueSecretSource, VerificationError, type WalkRemoteTreeOptions, type WinScpSession, ZeroTransfer, type ZeroTransferCapabilities, ZeroTransferError, type ZeroTransferErrorDetails, type ZeroTransferLogger, type ZeroTransferOptions, assertSafeFtpArgument, basenameRemotePath, buildPublickeyCredential, buildRemoteBreadcrumbs, compareRemoteManifests, copyBetween, createAtomicDeployPlan, createBandwidthThrottle, createLocalProviderFactory, createMemoryProviderFactory, createOAuthTokenSecretSource, createPooledTransferClient, createProgressEvent, createProviderTransferExecutor, createRemoteBrowser, createRemoteManifest, createSyncPlan, createTransferClient, createTransferJobsFromPlan, createTransferPlan, createTransferResult, diffRemoteTrees, downloadFile, emitLog, errorFromFtpReply, filterRemoteEntries, importFileZillaSites, importOpenSshConfig, importWinScpSessions, isClassicProviderId, isMainModule, isSensitiveKey, joinRemotePath, matchKnownHosts, matchKnownHostsEntry, negotiateSshAlgorithms, noopLogger, normalizeRemotePath, parentRemotePath, parseKnownHosts, parseOpenSshConfig, parseRemoteManifest, redactCommand, redactConnectionProfile, redactObject, redactSecretSource, redactValue, resolveConnectionProfileSecrets, resolveOpenSshHost, resolveProviderId, resolveSecret, runConnectionDiagnostics, runSshCommand, serializeRemoteManifest, sortRemoteEntries, summarizeClientDiagnostics, summarizeTransferPlan, throttleByteIterable, uploadFile, validateConnectionProfile, walkRemoteTree };
package/dist/index.mjs CHANGED
@@ -4785,6 +4785,19 @@ function isModifiedAtDifferent2(source, destination, toleranceMs) {
4785
4785
  return Math.abs(sourceTime - destinationTime) > toleranceMs;
4786
4786
  }
4787
4787
 
4788
+ // src/utils/mainModule.ts
4789
+ import { fileURLToPath } from "url";
4790
+ function isMainModule(importMetaUrl) {
4791
+ if (typeof process === "undefined" || !process.argv || process.argv.length < 2) {
4792
+ return false;
4793
+ }
4794
+ try {
4795
+ return process.argv[1] === fileURLToPath(importMetaUrl);
4796
+ } catch {
4797
+ return false;
4798
+ }
4799
+ }
4800
+
4788
4801
  // src/protocols/ssh/transport/SshTransportConnection.ts
4789
4802
  import { Buffer as Buffer16 } from "buffer";
4790
4803
 
@@ -6160,7 +6173,7 @@ var SshTransportPacketUnprotector = class {
6160
6173
  }
6161
6174
  /**
6162
6175
  * Feeds raw encrypted bytes from the socket and returns any fully decoded payloads.
6163
- * Maintains internal framing state across calls pass each `data` event chunk directly.
6176
+ * Maintains internal framing state across calls - pass each `data` event chunk directly.
6164
6177
  */
6165
6178
  pushBytes(chunk) {
6166
6179
  this.framePendingRaw = Buffer15.concat([this.framePendingRaw, chunk]);
@@ -6668,7 +6681,7 @@ var SshTransportConnection = class {
6668
6681
  assertConnected() {
6669
6682
  if (!this.connected) {
6670
6683
  throw new ProtocolError({
6671
- message: "SshTransportConnection is not yet connected \u2014 call connect() first",
6684
+ message: "SshTransportConnection is not yet connected - call connect() first",
6672
6685
  protocol: "sftp",
6673
6686
  retryable: false
6674
6687
  });
@@ -7624,6 +7637,84 @@ var SshConnectionManager = class {
7624
7637
  }
7625
7638
  }
7626
7639
  };
7640
+
7641
+ // src/protocols/ssh/runSshCommand.ts
7642
+ import { connect } from "net";
7643
+ var DEFAULT_PORT = 22;
7644
+ var DEFAULT_CONNECT_TIMEOUT_MS = 1e4;
7645
+ var DEFAULT_HANDSHAKE_TIMEOUT_MS = 1e4;
7646
+ var DEFAULT_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
7647
+ async function runSshCommand(options) {
7648
+ const {
7649
+ host,
7650
+ port = DEFAULT_PORT,
7651
+ command,
7652
+ auth,
7653
+ transport: transportOptions,
7654
+ connectTimeoutMs = DEFAULT_CONNECT_TIMEOUT_MS,
7655
+ maxOutputBytes = DEFAULT_MAX_OUTPUT_BYTES
7656
+ } = options;
7657
+ const socket = await openTcpSocket(host, port, connectTimeoutMs);
7658
+ const transport = new SshTransportConnection({
7659
+ handshakeTimeoutMs: DEFAULT_HANDSHAKE_TIMEOUT_MS,
7660
+ ...transportOptions
7661
+ });
7662
+ try {
7663
+ const handshake = await transport.connect(socket);
7664
+ const authSession = new SshAuthSession(transport);
7665
+ await authSession.authenticate({
7666
+ credential: auth,
7667
+ sessionId: handshake.keyExchange.sessionId
7668
+ });
7669
+ const conn = new SshConnectionManager(transport);
7670
+ const channel = await conn.openExecChannel(command);
7671
+ const pump = conn.start();
7672
+ pump.catch(() => {
7673
+ });
7674
+ const chunks = [];
7675
+ let bytesReceived = 0;
7676
+ try {
7677
+ for await (const chunk of channel.receiveData()) {
7678
+ bytesReceived += chunk.length;
7679
+ if (bytesReceived > maxOutputBytes) {
7680
+ throw new Error(
7681
+ `runSshCommand: stdout exceeded ${maxOutputBytes} bytes (set maxOutputBytes to allow more)`
7682
+ );
7683
+ }
7684
+ chunks.push(chunk);
7685
+ }
7686
+ } finally {
7687
+ channel.close();
7688
+ }
7689
+ const stdout = Buffer.concat(chunks);
7690
+ return {
7691
+ stdout,
7692
+ stdoutText: stdout.toString("utf8"),
7693
+ bytesReceived
7694
+ };
7695
+ } finally {
7696
+ transport.disconnect();
7697
+ }
7698
+ }
7699
+ function openTcpSocket(host, port, timeoutMs) {
7700
+ return new Promise((resolve, reject) => {
7701
+ const socket = connect({ host, port });
7702
+ const timer = setTimeout(() => {
7703
+ socket.destroy();
7704
+ reject(
7705
+ new Error(`runSshCommand: TCP connect to ${host}:${port} timed out after ${timeoutMs}ms`)
7706
+ );
7707
+ }, timeoutMs);
7708
+ socket.once("connect", () => {
7709
+ clearTimeout(timer);
7710
+ resolve(socket);
7711
+ });
7712
+ socket.once("error", (error) => {
7713
+ clearTimeout(timer);
7714
+ reject(error);
7715
+ });
7716
+ });
7717
+ }
7627
7718
  export {
7628
7719
  AbortError,
7629
7720
  AuthenticationError,
@@ -7687,6 +7778,7 @@ export {
7687
7778
  importOpenSshConfig,
7688
7779
  importWinScpSessions,
7689
7780
  isClassicProviderId,
7781
+ isMainModule,
7690
7782
  isSensitiveKey,
7691
7783
  joinRemotePath,
7692
7784
  matchKnownHosts,
@@ -7708,6 +7800,7 @@ export {
7708
7800
  resolveProviderId,
7709
7801
  resolveSecret,
7710
7802
  runConnectionDiagnostics,
7803
+ runSshCommand,
7711
7804
  serializeRemoteManifest,
7712
7805
  sortRemoteEntries,
7713
7806
  summarizeClientDiagnostics,