### SSH Config Usage Example Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/usage-patterns.md Example demonstrating the usage of safe configuration reading and computation. Assumes `configPath` and `hostname` are defined elsewhere. ```typescript // Usage const config = safeReadAndParseConfig(configPath) const result = safeCompute(config, hostname) ``` -------------------------------- ### Directive Parsing Example Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/api-reference/parse.md Illustrates how directives like HostName are parsed into parameter, separator, and value components. ```text HostName example.com ^param ^sep ^value HostName=example.com ^param^^sep ^value ProxyCommand ssh -W "%h:%p" firewall ^param ^sep ^value (can contain spaces and quotes) ``` -------------------------------- ### Valid Match Syntax Examples Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/errors.md Provides examples of correctly formatted Match directives in SSH configurations, showcasing different criteria and their values, including flag-only options. ```typescript SSHConfig.parse(` Match all ServerAliveInterval 60 Match final host *.prod.* IdentityFile ~/.ssh/prod_key Match host *.example.com user admin exec "test -f ~/.ssh/admin_key" # All criteria with values `) ``` -------------------------------- ### Example Usage of FindOptions Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/types.md Demonstrates how to use the FindOptions interface to search for a specific host in the SSH configuration. ```typescript config.find({ Host: 'example.com' }) ``` -------------------------------- ### Example Usage of MatchOptions Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/types.md Illustrates using MatchOptions to compute SSH configuration, including specifying a user. ```typescript config.compute({ Host: 'example.com', User: 'admin' }) ``` -------------------------------- ### SSH Host Pattern Matching Examples Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/api-reference/glob.md Provides examples of common SSH host patterns, including matching everything, specific hostnames, domain suffixes, and IP address ranges. Note that this uses glob matching, not regular expressions. ```typescript // Common SSH config Host patterns glob('*', 'anything.com') // true (matches everything) glob('localhost', 'localhost') // true glob('*.local', 'myhost.local') // true glob('192.168.*', '192.168.1.1') // true (glob, not regex) glob(['example.com', '*.dev.example.com'], 'staging.dev.example.com') // true ``` -------------------------------- ### Example Match Section Structure Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/types.md Demonstrates the structure of a Match section, showing how to specify criteria like host, user, and execution commands, along with nested configurations. ```typescript { type: LineType.DIRECTIVE, param: 'Match', value: [ /* complex structure */ ], criteria: { host: '*.prod.*', user: 'deploy', exec: 'test -f ~/.ssh/prod_authorized' }, config: SSHConfig [ /* nested directives */ ] } ``` -------------------------------- ### Complete SSHConfig Workflow Example Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/api-reference/ssh-config.md Demonstrates a full cycle of SSH configuration management: parsing an existing configuration string, finding and modifying a specific host section by adding a directive, appending a new host section, computing effective settings for a host, and finally stringifying the modified configuration. ```typescript import SSHConfig from 'ssh-config' // Parse existing config const config = SSHConfig.parse(` Host * ServerAliveInterval 60 Host prod.example.com HostName prod.example.com User deploy IdentityFile ~/.ssh/deploy_key `) // Find and modify const section = config.find({ Host: 'prod.example.com' }) if (section && section.config) { section.config.push({ type: SSHConfig.DIRECTIVE, param: 'Port', value: '2222', separator: ' ', before: '\n ', after: '' }) } // Add new section config.append({ Host: 'staging.example.com', HostName: 'staging.example.com', User: 'deploy', IdentityFile: '~/.ssh/staging_key' }) // Compute settings for a host const deploySettings = config.compute('prod.example.com') console.log(deploySettings.User) // 'deploy' console.log(deploySettings.ServerAliveInterval) // '60' console.log(deploySettings.IdentityFile) // ['~/.ssh/deploy_key'] // Output modified config console.log(SSHConfig.stringify(config)) ``` -------------------------------- ### Stringify Instance Method Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/api-reference/stringify.md You can also use the toString() method on an SSHConfig instance to get the string representation of the configuration. ```typescript import { SSHConfig } from 'ssh-config'; const config = new SSHConfig(); config.load(text); const output = config.toString(); console.log(output === text); // true ``` -------------------------------- ### Example Usage of ComputeOptions: Skip Match Exec Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/types.md Demonstrates using ComputeOptions to enhance security by skipping the evaluation of 'Match exec' criteria, which executes shell commands. ```typescript // Skip Match exec for security config.compute('example.com', { matchExec: false }) ``` -------------------------------- ### Example Usage of ComputeOptions: Ignore Case Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/types.md Shows how to use ComputeOptions to match OpenSSH behavior by normalizing directive names to lowercase. ```typescript // Match OpenSSH behavior with lowercase directives config.compute('example.com', { ignoreCase: true }) // => { hostname: '192.168.1.1', user: 'admin' } ``` -------------------------------- ### SSHConfig Glob Usage Example Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/api-reference/glob.md Demonstrates how the glob function is used internally by SSHConfig.parse() and config.compute() to match host patterns, including handling negated patterns. ```typescript const config = SSHConfig.parse(` Host *.example.com User admin Host *.dev.example.com !staging.dev.example.com IdentityFile ~/.ssh/dev_key `) // glob is used internally here: config.compute('prod.example.com') // matches '*.example.com' config.compute('staging.dev.example.com') // excluded by negation ``` -------------------------------- ### Reconstructing ProxyCommand Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/api-reference/stringify.md This example shows how the stringify function reconstructs a ProxyCommand with multiple values, including separators and quoting, from its internal representation. ```typescript // Internal structure with separators value: [ { val: 'ssh', separator: '' }, { val: '-W', separator: ' ' }, { val: '%h:%p', separator: ' ', quoted: true }, { val: 'firewall', separator: ' ' } ] // Output reconstructs with separators: ProxyCommand ssh -W "%h:%p" firewall ``` -------------------------------- ### Quoted Value Handling Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/api-reference/parse.md Shows examples of how quoted values are interpreted, including backslash escapes for quotes and backslashes. ```text IdentityFile "~/.ssh/My Key File.pem" // Spaces allowed in quoted section ProxyCommand ssh -W "%h:%p" firewall // Mixed quotes and unquoted ``` -------------------------------- ### Example of Missing Value for Match Criteria Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/errors.md Demonstrates a configuration that causes a 'Missing value for match criteria' error because the 'user' keyword in a Match directive is not followed by a value. ```typescript const config = SSHConfig.parse(` Match host *.example.com user # Missing value after 'user' keyword IdentityFile ~/.ssh/key `) ``` -------------------------------- ### Complex Real-World Glob Patterns Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/api-reference/glob.md Demonstrates advanced usage with complex patterns including exclusions for specific hosts or IP addresses, and patterns for jump hosts. These examples show how to combine wildcards and negations for precise matching. ```typescript // Host pattern with exclusions const hostPattern = '*.example.com,!internal-*.example.com' glob(hostPattern, 'web.example.com') // true glob(hostPattern, 'internal-dev.example.com') // false (negated) // Jump host patterns const jumpPattern = 'jump*,bastion*' glob(jumpPattern, 'jump-prod') // true glob(jumpPattern, 'gateway-prod') // false // Exclude localhost and special addresses const pattern = '*,!localhost,!127.0.0.1,![::1]' glob(pattern, 'remote.example.com') // true glob(pattern, 'localhost') // false (negated) ``` -------------------------------- ### Connect to SSH Host Using SSH Config Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/usage-patterns.md Parses an SSH config file and computes the necessary settings to connect to a specified host using a Node.js SSH client library. Ensure the ssh-config and node-ssh libraries are installed. ```typescript import SSHConfig from 'ssh-config' import { NodeSSH } from 'node-ssh' import fs from 'fs' async function connectViaConfig(configPath, hostName, username) { // Parse SSH config const config = SSHConfig.parse( fs.readFileSync(configPath, 'utf-8') ) // Compute settings for host const hostConfig = config.compute(hostName) // Connect using computed settings const ssh = new NodeSSH() await ssh.connect({ host: hostConfig.HostName, port: parseInt(hostConfig.Port) || 22, username: username || hostConfig.User, privateKeyPath: hostConfig.IdentityFile[0], readyTimeout: 5000 }) return ssh } // Usage const ssh = await connectViaConfig( `${process.env.HOME}/.ssh/config`, 'prod.example.com', 'deploy' ) ``` -------------------------------- ### Remove SSH Config Sections Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/usage-patterns.md Shows how to remove configuration sections by exact host match or by using a predicate function. It also includes an example of selectively keeping global directives while removing others. ```typescript // Remove specific host const removed = config.remove({ Host: 'old.example.com' }) if (removed) { console.log('Removed section for old.example.com') } // Remove using predicate config.remove(line => line.type === SSHConfig.DIRECTIVE && line.param === 'Host' && /deprecated|obsolete/.test(line.value) ) // Remove all but keep globals const kept = new SSHConfig() for (const line of config) { if (line.type === SSHConfig.DIRECTIVE && /^(Host|Match)$/i.test(line.param)) { continue // Skip Host/Match sections } kept.push(line) } ``` -------------------------------- ### Instance Methods Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/OVERVIEW.md Methods for interacting with an existing SSH configuration object, such as computing effective configurations, finding, removing, appending, or prepending sections. ```APIDOC ## Instance Methods ### `compute(host, options?)` #### Description Get the effective configuration for a given host, considering all directives and options. #### Parameters - **host** (string) - The hostname for which to compute the configuration. - **options** (ComputeOptions, optional) - Options to control the computation, such as ignoring case or evaluating `Match exec`. ### `find(opts|predicate)` #### Description Find a section within the configuration based on provided options or a predicate function. #### Parameters - **opts|predicate** (FindOptions | function) - Options or a predicate function to locate a specific section. ### `remove(opts|predicate)` #### Description Remove a section from the configuration based on provided options or a predicate function. #### Parameters - **opts|predicate** (FindOptions | function) - Options or a predicate function to identify the section to remove. ### `append(object)` #### Description Add directives to the end of the configuration. #### Parameters - **object** (object) - The directives to append. ### `prepend(object, boolean?)` #### Description Add directives to the beginning of the configuration. #### Parameters - **object** (object) - The directives to prepend. - **boolean** (boolean, optional) - An optional boolean flag. ### `toString()` #### Description Convert the current configuration object into its text representation. #### Returns - (string) - The SSH configuration text. ``` -------------------------------- ### Build New SSH Config Programmatically Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/api-reference/stringify.md Illustrates how to construct a new SSH configuration object from scratch. This involves using methods like `prepend` to add directives at the beginning (e.g., include statements) and `append` to add new host configurations. ```typescript const config = new SSHConfig() config.prepend({ Include: '~/.ssh/config.d/*' }, true) config.append({ Host: 'prod.example.com', HostName: 'prod.example.com', User: 'deploy' }) ``` ```typescript const text = config.toString() ``` -------------------------------- ### Build an SSH config programmatically Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/INDEX.md Shows how to construct an SSH configuration from scratch using the library's methods. ```APIDOC ## Build an SSH config programmatically ### Description Illustrates how to create a new SSH configuration object and populate it with host entries and their configurations programmatically. ### Method `new SSHConfig()`, `config.append()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const config = new SSHConfig() config.append({ Host: 'example.com', HostName: 'example.com' }) console.log(config.toString()) ``` ### Response #### Success Response (200) - **config** (SSHConfig) - The newly built SSH configuration object. #### Response Example ```json { "example": "Host example.com\n HostName example.com" } ``` ``` -------------------------------- ### Get effective SSH config for a host Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/INDEX.md Computes the effective SSH configuration for a given host, considering all directives and match rules. ```APIDOC ## Get effective SSH config for a host ### Description Computes the effective SSH configuration for a specified host, resolving all relevant directives and match criteria. ### Method `config.compute(host: string | object): object` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const result = config.compute('example.com') const result = config.compute({ Host: 'example.com', User: 'admin' }) ``` ### Response #### Success Response (200) - **effectiveConfig** (object) - An object containing the computed configuration for the host. #### Response Example ```json { "example": "{ HostName: '...', User: '...', ... }" } ``` ``` -------------------------------- ### Build New Configuration with Append Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/api-reference/stringify.md Demonstrates building a new SSH configuration from scratch using the `append` method, ensuring proper formatting is applied, and then stringifying the result. ```typescript const config = new SSHConfig() // Use append to build with proper formatting config.append({ Host: 'new.example.com', HostName: 'new.example.com', User: 'deploy', IdentityFile: ['~/.ssh/id_rsa', '~/.ssh/backup_key'] }) console.log(SSHConfig.stringify(config)) ``` -------------------------------- ### Get Host Settings Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/README.md Retrieve computed settings for a specific host from a parsed SSH configuration. The result includes properties like HostName, User, and IdentityFile. ```typescript const result = config.compute('example.com') // { HostName: '...', User: '...', IdentityFile: [...], ... } ``` -------------------------------- ### Initialize SSHConfig Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/configuration.md Creates an empty SSHConfig instance. No options are accepted by the constructor. ```typescript const config = new SSHConfig() // Empty config, equivalent to parsing an empty string ``` -------------------------------- ### Static Methods Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/OVERVIEW.md Provides methods for parsing SSH configuration text into a structured object and stringifying a configuration object back into text. ```APIDOC ## Static Methods ### `parse(text)` #### Description Parse SSH config text into a structured configuration object. #### Parameters - **text** (string) - The SSH configuration text to parse. ### `stringify(config)` #### Description Stringify a configuration object into SSH config text format. #### Parameters - **config** (object) - The configuration object to stringify. ``` -------------------------------- ### Compute SSH Config with User and Match Criteria Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/usage-patterns.md Illustrates computing SSH configurations with specific host and user criteria, demonstrating how 'Match' directives affect the computed configuration. ```typescript const config = SSHConfig.parse(` Host prod.* staging.* HostName proxy.example.com Match host prod.* user deploy IdentityFile ~/.ssh/deploy_prod_key Port 2222 Match host staging.* user dev IdentityFile ~/.ssh/dev_key `) // Compute with just host (uses current system user) config.compute('prod.example.com') // Compute with specific user (affects Match user criteria) config.compute({ Host: 'prod.example.com', User: 'deploy' }) // Compute for different user config.compute({ Host: 'staging.example.com', User: 'dev' }) ``` -------------------------------- ### Apply Configuration via Methods Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/configuration.md Configuration directives are applied after initialization using methods like append and prepend. ```typescript config.append({ Host: 'example.com', HostName: 'example.com' }) config.prepend({ IdentityFile: '~/.ssh/id_rsa' }, true) ``` -------------------------------- ### Compute Effective SSH Config for a Host Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/INDEX.md Use config.compute to get the effective configuration for a given host. You can provide a hostname string or an object with Host and User properties. ```typescript const result = config.compute('example.com') const result = config.compute({ Host: 'example.com', User: 'admin' }) ``` -------------------------------- ### Example of Unexpected Line Break in Quoted Value Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/errors.md Illustrates a scenario that triggers an 'Unexpected line break' error in the ssh-config parser due to a missing closing quote in a directive value. ```typescript const config = SSHConfig.parse(` Host example ProxyCommand ssh -W "%h:%p" firewall # Missing closing quote above causes error `) ``` -------------------------------- ### Compute SSH Configuration with Case-Insensitive Matching Source: https://github.com/cyjake/ssh-config/blob/master/Readme.md Demonstrates computing SSH configuration parameters while normalizing directive names to lowercase to match OpenSSH's case-insensitive behavior. ```javascript const config = SSHConfig.parse( ` Host example hOsTnaME 1.2.3.4 USER admin ` ) // Default - preserves original case config.compute('example') // => { hOsTnaME: '1.2.3.4', USER: 'admin' } // With ignoreCase - lowercase to match OpenSSH config.compute('example', { ignoreCase: true }) // => { hostname: '1.2.3.4', user: 'admin' } ``` -------------------------------- ### Import SSHConfig in Deno Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/OVERVIEW.md Import the SSHConfig library for use in Deno projects. ```typescript import SSHConfig from 'https://jsr.io/@cyjake/ssh-config/5.1.0/src/ssh-config.ts' ``` -------------------------------- ### SSHConfig Architecture Overview Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/OVERVIEW.md Diagram illustrating the main components and methods of the SSHConfig class and its interactions. ```text SSHConfig (extends Array) ├── parse(text) → SSHConfig │ └── Creates structured representation preserving all formatting ├── compute(host, options?) → Record │ ├── Matches Host patterns and Match criteria │ ├── Applies directives in order (first-match-wins) │ └── Returns flattened config for the host ├── find(opts) → Line | undefined │ └── Locates a section by Host name ├── remove(opts) → Line[] | undefined │ └── Removes a section and returns it ├── append(record) → SSHConfig │ └── Adds directives to end of config ├── prepend(record, boolean?) → SSHConfig │ └── Adds directives to beginning of config └── toString() / stringify() → string └── Reconstructs SSH config text ``` -------------------------------- ### CLI Tool for SSH Config Management Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/usage-patterns.md A command-line interface tool for managing SSH configurations. It supports listing all hosts, displaying computed host information, adding new hosts, and removing existing hosts from the SSH config file. Ensure the script is executable and Node.js is installed. ```typescript #!/usr/bin/env node import SSHConfig from 'ssh-config' import fs from 'fs' const command = process.argv[2] const arg = process.argv[3] const configPath = process.env.HOME + '/.ssh/config' const config = SSHConfig.parse(fs.readFileSync(configPath, 'utf-8')) switch (command) { case 'list': // List all hosts for (const line of config) { if (line.type === SSHConfig.DIRECTIVE && line.param === 'Host') { console.log(line.value) } } break case 'info': // Show computed config for host const info = config.compute(arg) console.log(JSON.stringify(info, null, 2)) break case 'add': // Add new host config.append({ Host: arg, HostName: arg, User: 'user' }) fs.writeFileSync(configPath, config.toString()) console.log(`Added host: ${arg}`) break case 'remove': // Remove host config.remove({ Host: arg }) fs.writeFileSync(configPath, config.toString()) console.log(`Removed host: ${arg}`) break default: console.log('Usage: ssh-config [arg]') console.log('Commands: list, info , add , remove ') } ``` -------------------------------- ### Typical Host Section Usage Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/types.md Illustrates the structure of a typical Host section in SSH configuration, including its type, parameters, value, and nested configuration. ```typescript // A Host section { type: LineType.DIRECTIVE, param: 'Host', value: 'example.com', config: SSHConfig [ { param: 'HostName', value: 'example.com', ... }, { param: 'User', value: 'admin', ... } ] } ``` -------------------------------- ### SSHConfig Constructor Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/api-reference/ssh-config.md Creates a new empty SSHConfig instance. Since SSHConfig extends Array, you can use all standard Array methods. ```APIDOC ## Constructor ```typescript constructor() ``` Creates a new empty SSHConfig instance. Since SSHConfig extends Array, you can use all standard Array methods. ``` -------------------------------- ### Configuration Options Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/OVERVIEW.md Details on the options interfaces used by various methods, including `ComputeOptions`, `FindOptions`, and `MatchOptions`. ```APIDOC ## Configuration Options ### `ComputeOptions` (for compute method) #### Description Options to control the behavior of the `compute` method. #### Fields - **ignoreCase** (boolean, optional) - Normalize directive names to lowercase. - **matchExec** (boolean, optional) - Evaluate `Match exec` directives. Defaults to `true`. ### `FindOptions` (for find/remove methods) #### Description Options used for finding or removing configuration sections. #### Fields - **Host** (string, optional) - Exact hostname to search for. ### `MatchOptions` (for compute with user) #### Description Options for matching criteria, particularly when specifying a user. #### Fields - **Host** (string, required) - The hostname to match. - **User** (string, optional) - The user to match. ``` -------------------------------- ### Handle errors safely Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/INDEX.md Demonstrates how to safely handle potential errors during SSH configuration parsing. ```APIDOC ## Handle errors safely ### Description Provides guidance on how to implement error handling when parsing SSH configuration files to gracefully manage potential issues. ### Method `try...catch` block around `SSHConfig.parse()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript try { const config = SSHConfig.parse(text) } catch (e) { if (e.message.includes('Unexpected line break')) { // Handle parse error } } ``` ### Response #### Success Response (200) - **config** (SSHConfig) - The parsed SSH configuration object if parsing is successful. #### Response Example ```json { "example": "SSHConfig object or error handling" } ``` ``` -------------------------------- ### Build SSH Configuration Programmatically Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/OVERVIEW.md Creates a new SSH configuration object and appends a host entry, then prints the resulting configuration string. ```typescript const config = new SSHConfig() config.append({ Host: 'example.com', HostName: '192.168.1.1' }) console.log(config.toString()) ``` -------------------------------- ### Build Dynamic SSH Proxy Commands Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/usage-patterns.md Dynamically constructs an SSH configuration string by parsing a base configuration, computing gateway and target host settings, and injecting a ProxyCommand directive. This is useful for setting up complex jump host scenarios. ```typescript function buildProxyConfig(baseConfig, targetHost) { const config = SSHConfig.parse(baseConfig) // Find gateway from config const gatewayConfig = config.compute('gateway.example.com') // Find target server const targetConfig = config.compute(targetHost) // Inject proxy command const section = config.find({ Host: targetHost }) if (section && 'config' in section) { section.config.push({ type: SSHConfig.DIRECTIVE, param: 'ProxyCommand', value: `ssh -q ${gatewayConfig.User}@${gatewayConfig.HostName} -W %h:%p`, separator: ' ', before: '\n ', after: '' }) } return config.toString() } ``` -------------------------------- ### Read, Compute, and Use SSH Config Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/usage-patterns.md Read an SSH config file, compute settings for a specific host, and then use those settings. Ensure the config file exists and is readable. ```typescript import SSHConfig from 'ssh-config' import fs from 'fs' // Read config from file const configText = fs.readFileSync( process.env.HOME + '/.ssh/config', 'utf-8' ) // Parse into structured form const config = SSHConfig.parse(configText) // Compute settings for a specific host const hostConfig = config.compute('prod.example.com') // Use the computed settings console.log(`Connecting to: ${hostConfig.HostName}`) console.log(`As user: ${hostConfig.User}`) console.log(`On port: ${hostConfig.Port || 22}`) console.log(`Identity files: ${hostConfig.IdentityFile.join(', ')}`) ``` -------------------------------- ### Stringify SSH Config (Preserving Formatting) Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/api-reference/stringify.md Shows how `stringify` (or `toString`) on an SSHConfig object preserves the original formatting, including comments and whitespace, even if the initial parsed configuration was compact. To apply new formatting, manual adjustments to `before` and `after` fields or using `append`/`prepend` are necessary. ```typescript // Even if original was compact, stringify reconstructs with saved formatting // To apply new formatting, manually set before/after fields or use append/prepend const config = SSHConfig.parse(minifiedConfig) config.stringify(config) // Preserves original compact format ``` -------------------------------- ### Basic Glob Pattern Matching Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/api-reference/glob.md Demonstrates basic wildcard matching with '*' and '?' characters. Ensure the pattern is a string and the target is a string. '*' matches any sequence of characters, while '?' matches any single character. ```typescript import glob from 'ssh-config' glob('*.example.com', 'host.example.com') // true glob('*.example.com', 'example.com') // false (doesn't have a prefix) glob('*.example.com', 'a.b.example.com') // true (matches everything) glob('host?.example.com', 'host1.example.com') // true glob('host?.example.com', 'host.example.com') // false (needs one char for ?) ``` -------------------------------- ### Integrate with an SSH client library Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/INDEX.md Explains how to use the computed SSH configuration with external SSH client libraries. ```APIDOC ## Integrate with an SSH client library ### Description Provides guidance on how to leverage the computed SSH configuration details (like HostName, User, etc.) when initializing or configuring external SSH client libraries. ### Method `config.compute(hostname)` followed by using the result with a client library. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const hostConfig = config.compute(hostname) // Use hostConfig.HostName, hostConfig.User, etc. with client ``` ### Response #### Success Response (200) - **hostConfig** (object) - The effective configuration for the specified hostname. #### Response Example ```json { "example": "{ HostName: '...', User: '...', ... }" } ``` ``` -------------------------------- ### MatchOptions Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/types.md Options for computing SSH config with both host and user. This interface specifies the host and optional user for matching SSH configuration entries. ```APIDOC ## MatchOptions Options for computing SSH config with both host and user. ### Fields - **Host** (string, Required) - The hostname to compute for - **User** (string, Optional) - The username (used for Match user criteria evaluation) ### Usage ```typescript config.compute({ Host: 'example.com', User: 'admin' }) ``` ``` -------------------------------- ### toString Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/api-reference/ssh-config.md Converts the current SSH configuration object into its textual representation. ```APIDOC ## toString ### Description Converts this SSH config to its textual representation, preserving formatting. ### Method Signature ```typescript tostring(): string ``` ### Returns `string` - SSH config text with formatting preserved. ### Example ```typescript const text = config.toString() const stringified = SSHConfig.stringify(config) // Equivalent ``` ``` -------------------------------- ### prepend Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/api-reference/ssh-config.md Prepends a new section or directives to the beginning of the SSH configuration. ```APIDOC ## prepend ### Description Prepends a new section or directives to the beginning of the SSH configuration. ### Method Signature ```typescript prepend(opts: Record, beforeFirstSection?: boolean): SSHConfig ``` ### Parameters - **opts** (Record) - Required - Object with directive names and values. - **beforeFirstSection** (boolean) - Optional - If true, inserts above the first section; otherwise, appends to existing global directives. Defaults to false. ### Returns `SSHConfig` - The modified config (chainable). ### Behavior - If `beforeFirstSection` is false and global directives exist, prepends after them. - If `beforeFirstSection` is true, inserts before the first Host/Match section. - Useful for adding global Include or IdentityFile directives at the file start. ### Example ```typescript // Prepend a directive to global scope config.prepend({ IdentityFile: '/path/to/default/key' }) // Prepend before the first section config.prepend({ Include: '~/.ssh/config.d/*' }, true) ``` ``` -------------------------------- ### SSHConfig Class Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/INDEX.md The main SSHConfig class, which extends Array. It provides methods for parsing, stringifying, computing, finding, removing, appending, and prepending configuration lines, as well as converting the configuration to a string. ```APIDOC ## Class: SSHConfig ### Description The main class for managing SSH configurations, extending `Array`. It offers a rich set of methods for manipulating SSH configuration data. ### Methods - **parse(text: string | Buffer): SSHConfig** - Parses SSH configuration text into an SSHConfig object. - **stringify(config: SSHConfig): string** - Converts an SSHConfig object back into a string representation. - **compute()** - Computes the configuration based on options. - **find(options: FindOptions): SSHConfig** - Finds configuration entries matching the provided options. - **remove(options: MatchOptions): SSHConfig** - Removes configuration entries matching the provided options. - **append(line: Line): SSHConfig** - Appends a line to the configuration. - **prepend(line: Line): SSHConfig** - Prepends a line to the configuration. - **toString(): string** - Converts the SSHConfig object to its string representation. ``` -------------------------------- ### Parse and Stringify SSH Configuration Source: https://github.com/cyjake/ssh-config/blob/master/Readme.md Demonstrates parsing an SSH configuration string into a structured array and then stringifying it back. Preserves original whitespaces and comments. ```javascript const SSHConfig = require('ssh-config') const config = SSHConfig.parse(` IdentityFile ~/.ssh/id_rsa Host tahoe HostName tahoe.com Host walden HostName waldenlake.org Host * User keanu ForwardAgent true `) expect(config).to.eql( [ { "param": "IdentityFile", "value": "~/.ssh/id_rsa" }, { "param": "Host", "value": "tahoe", "config": [ { "param": "HostName", "value": "tahoe.com" } ] }, { "param": "Host", "value": "walden", "config": [ { "param": "HostName", "value": "waldenlake.org" } ] }, { "param": "Host", "value": "*", "config": [ { "param": "User", "value": "keanu" }, { "param": "ForwardAgent", "value": "true" } ] } ] ) // Change the HostName in the Host walden section const section = config.find({ Host: 'walden' }) for (const line of section.config) { if (line.param === 'HostName') { line.value = 'waldenlake.org' break } } // The original whitespaces and comments are preserved. console.log(SSHConfig.stringify(config)) // console.log(config.toString()) ``` -------------------------------- ### Build SSH Config Programmatically Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/usage-patterns.md Create an SSH configuration from scratch without reading an existing file. This is useful for generating dynamic configurations. ```typescript import SSHConfig from 'ssh-config' const config = new SSHConfig() // Add global directives config.prepend({ IdentityFile: '~/.ssh/id_rsa', IdentityFile: '~/.ssh/id_ed25519', ServerAliveInterval: '60' }, true) // Add host sections config.append({ Host: 'prod.example.com', HostName: 'prod.example.com', User: 'deploy', Port: '2222', IdentityFile: '~/.ssh/prod_deploy' }) config.append({ Host: 'staging.example.com', HostName: 'staging.example.com', User: 'deploy', IdentityFile: '~/.ssh/staging_deploy' }) // Add catch-all config.append({ Host: '*', ServerAliveCountMax: '2', Compression: 'yes' }) // Output as text console.log(config.toString()) ``` -------------------------------- ### SSHConfig.stringify Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/api-reference/ssh-config.md Converts a structured SSHConfig object back into SSH configuration text format, preserving original formatting. ```APIDOC ### stringify ```typescript static stringify(config: SSHConfig): string ``` Convert structured SSHConfig back into SSH config text format, preserving original formatting (whitespace, comments, separators). | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | config | SSHConfig | Yes | — | Parsed config object to stringify | **Returns:** `string` — SSH config text with all formatting preserved **Example:** ```typescript const config = SSHConfig.parse(originalText) // Modify config... const text = SSHConfig.stringify(config) console.log(text) // Reconstructed config with original formatting ``` ``` -------------------------------- ### os.userInfo() Fallback Mechanism Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/errors.md In the event that 'os.userInfo()' throws a SystemError (e.g., user has no username or homedir), the system falls back to using environment variables like 'process.env.USER' or 'process.env.USERNAME'. ```typescript // In compute(), if os.userInfo() fails: const userInfo = os.userInfo() // Throws // Falls back to environment variable userInfo = { username: process.env.USER || '' } ``` -------------------------------- ### Import SSHConfig in Node.js Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/OVERVIEW.md Import the SSHConfig library using CommonJS or ES Module syntax. ```javascript const SSHConfig = require('ssh-config') // or import SSHConfig from 'ssh-config' ``` -------------------------------- ### Handle Match Directives with User Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/README.md Compute SSH configuration settings for a host, specifying the user to handle 'Match' directives correctly. This overload is useful when the user is known. ```typescript config.compute({ Host: 'example.com', User: 'deploy' }) ``` -------------------------------- ### Read, Modify, and Write SSH Config File Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/INDEX.md This pattern shows how to read an SSH config file using fs.readFileSync, modify the parsed configuration object, and then write the changes back to the file using fs.writeFileSync. ```typescript const config = SSHConfig.parse(fs.readFileSync(path, 'utf-8')) // ... modify config ... fs.writeFileSync(path, config.toString()) ``` -------------------------------- ### Prepend SSH Config Section Before Generic Options Source: https://github.com/cyjake/ssh-config/blob/master/Readme.md Prepends a new host configuration section to the beginning of the SSHConfig object, placing it before any existing generic options. Set the second argument to `true` to enable this behavior. ```javascript config.prepend({ Host: 'tahoe', HostName 'tahoe.com', }, true) ``` -------------------------------- ### Host Section Structure Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/api-reference/parse.md Demonstrates the transformation of a Host section in an SSH config file into a structured object. ```javascript Host example.com HostName example.com User admin Port 2222 ``` ```javascript { type: LineType.DIRECTIVE, param: 'Host', value: 'example.com', config: SSHConfig [ { param: 'HostName', value: 'example.com', ... }, { param: 'User', value: 'admin', ... }, { param: 'Port', value: '2222', ... } ] } ``` -------------------------------- ### SSHConfig Class Methods Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/README.md The SSHConfig class provides methods for managing SSH configuration files. It allows parsing, stringifying, computing, finding, removing, appending, and prepending configuration entries. ```APIDOC ## SSHConfig Class ### Description Provides an object-oriented interface for manipulating SSH configuration files. ### Methods - **parse(input: string, options?: ParseOptions): SSHConfig** Parses an SSH configuration string into an SSHConfig object. - **stringify(options?: StringifyOptions): string** Converts the SSHConfig object back into a formatted string. - **compute(options?: ComputeOptions): SSHConfig** Computes the final configuration based on inheritance and host matching. - **find(host: string, options?: FindOptions): Section | null** Finds the configuration section for a given host. - **remove(host: string, options?: RemoveOptions): boolean** Removes all configuration entries for a given host. - **append(config: string | SSHConfig, options?: AppendOptions): boolean** Appends new configuration entries from a string or another SSHConfig object. - **prepend(config: string | SSHConfig, options?: PrependOptions): boolean** Prepends new configuration entries from a string or another SSHConfig object. - **toString(): string** An alias for the `stringify` method. ``` -------------------------------- ### Find and Modify SSH Config Sections Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/usage-patterns.md Demonstrates how to find configuration sections by exact host match or using a predicate function. Modifications are made by pushing new directives to the found section's config. ```typescript const section = config.find({ Host: 'example.com' }) if (section && 'config' in section) { // Modify directives inside section.config.push({ type: SSHConfig.DIRECTIVE, param: 'AddKeysToAgent', value: 'yes', separator: ' ', before: '\n ', after: '' }) } // Find using predicate const proxySection = config.find(line => line.type === SSHConfig.DIRECTIVE && line.param === 'Host' && /proxy|gateway/.test(line.value) ) // Find and modify multiple for (const line of config) { if (line.type === SSHConfig.DIRECTIVE && line.param === 'Host' && /prod/.test(line.value)) { // Modify all production hosts } } ``` -------------------------------- ### Use append/prepend for Consistent Indentation Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/configuration.md The `append` and `prepend` methods automatically apply consistent indentation when adding new directives or host configurations, simplifying formatting management. ```typescript config.append({ Host: 'new.example.com', ... }) // Automatically applies consistent indentation ``` -------------------------------- ### Compute SSH Configuration with Match Options Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/configuration.md Computes SSH configuration based on host and optionally user criteria. If no user is specified, the current system user is used. Additional options like 'ignoreCase' and 'matchExec' can be provided. ```typescript export interface MatchOptions { Host: string; User?: string; } ``` ```typescript const config = SSHConfig.parse(` Match host *.prod.* user deploy IdentityFile ~/.ssh/deploy_key Host prod.example.com HostName prod.example.com `) ``` ```typescript // Just host (uses current system user) config.compute('prod.example.com') ``` ```typescript // Host and specific user config.compute({ Host: 'prod.example.com', User: 'deploy' }) ``` ```typescript // Combined with compute options config.compute( { Host: 'prod.example.com', User: 'deploy' }, { ignoreCase: true, matchExec: false } ) ``` -------------------------------- ### Add a New Host Section Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/INDEX.md Use config.append to add a new Host section to the configuration. Provide an object with the desired host parameters. ```typescript config.append({ Host: 'new.example.com', HostName: 'new.example.com', User: 'admin' }) ``` -------------------------------- ### Basic SSH Config Parsing Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/api-reference/parse.md Parses a simple SSH configuration string and logs specific parameters and values from the first host entry. ```typescript import { parse } from 'ssh-config' const config = parse(` Host example.com HostName 192.168.1.1 User admin `) console.log(config[0].param) // 'Host' console.log(config[0].value) // 'example.com' console.log(config[0].config[0].param) // 'HostName' ``` -------------------------------- ### Parse, Modify, and Stringify SSH Configuration Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/configuration.md Demonstrates parsing an SSH configuration string, adding directives with formatting options, querying host information with various options, and stringifying the modified configuration. ```typescript import SSHConfig from 'ssh-config' // Parse config (no options) const config = SSHConfig.parse(configText) // Add directives with formatting config.prepend( { IdentityFile: '~/.ssh/default_key' }, true // Insert before first section ) // Query with full options const result = config.compute( { Host: 'prod.example.com', User: 'deploy' }, { ignoreCase: true, // Normalize directive names matchExec: true // Evaluate Match exec (for trusted configs) } ) // Safely query untrusted config const untrustedResult = config.compute( 'example.com', { matchExec: false } // Skip shell execution ) // Stringify (no options) const output = SSHConfig.stringify(config) ``` -------------------------------- ### Compute SSH Configuration Parameters by Host Source: https://github.com/cyjake/ssh-config/blob/master/Readme.md Computes the effective SSH configuration parameters for a given host, including default values and handling of multiple IdentityFile entries. ```javascript expect(config.compute('walden')).to.eql({ IdentityFile: [ '~/.ssh/id_rsa' ], Host: 'walden', HostName: 'waldenlake.org', User: 'nil', ForwardAgent: 'true' }) ``` -------------------------------- ### Parse, Modify, and Stringify SSH Config Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/api-reference/stringify.md Demonstrates the common workflow of parsing an existing SSH configuration, finding and modifying a specific host's settings, and then stringifying the modified configuration back into text. Ensure the target section is found and has a 'config' property before attempting modifications. ```typescript const config = SSHConfig.parse(originalText) // Find and modify const section = config.find({ Host: 'example.com' }) if (section && section.config) { // Modify section... } ``` ```typescript // Output modified const newText = config.toString() // or SSHConfig.stringify(config) ``` -------------------------------- ### compute(opts: MatchOptions, computeOpts?: ComputeOptions): Record Source: https://github.com/cyjake/ssh-config/blob/master/_autodocs/api-reference/ssh-config.md Computes SSH configuration parameters by evaluating both host and user criteria, primarily for 'Match' directives. This overload allows for more granular configuration lookups when user context is important. ```APIDOC ## compute(opts: MatchOptions, computeOpts?: ComputeOptions): Record ### Description Query SSH config with both host and user for Match directive evaluation. ### Parameters #### Path Parameters - **opts** (MatchOptions) - Required - Object with Host (required) and User (optional) - **computeOpts** (ComputeOptions) - Optional - Optional computation options ### Returns `Record` - Same as overload 1 ### Example ```typescript const result = config.compute({ Host: 'prod.example.com', User: 'deploy' }) // Evaluates Match user and Match host criteria ``` ```