# NPM Package

{% hint style="info" %}
Please note this software is still in BETA. We do not recommend adding it to a production environment just yet.
{% endhint %}

## Getting Started

To create your first socket-link connection you will need NodeJS and the Service Key for the target service you want to connect to. This guide assumes you are familiar with a terminal and JavaScript.

If you already know how to use Remote.It you might just want to head to the [GitHub page of the socket-link project ](https://github.com/remoteit/socket-link.js)to get started.

### Client Sample

```typescript
import { SocketLink } from '@remote.it/socket-link'

// Create a new client
const socketLink = new SocketLink()

// Establish the connection
const proxy = await socketLink.connect('MNETSJSW')

// The address can not be used in your application
const address = proxy.address

// ... 

// Close the connection
await proxy.close()
```

Above is a simple implementation using a **Service Key** and returning an auto-assigned port.

***

## Service Authentication

In the example above the connection only needs the **Service Key** to connect. This is the simplest way to use connections, as no additional credentials are needed.

### Service Keys

Service Keys can be managed through the Remote.It application UI or the GraphQL API. You can enable / disable / delete / create unique Service Keys for quick and easy access to any service. This is the most flexible way to grant access to a service, as the key only allows access to one service and can be revoked at any time.

&#x20;You can find the Service Key generation controls on the connect page of every service. All keys are eight character strings.

```
QIYOKB2H
```

You can also use GraphQL to generate a service key by running the following mutation. [Learn how to run GraphQL commands against our API. ](https://docs.remote.it/developer-tools/api/usage)

Generate a key:

```typescript
// Create a new client
const socketLink = new SocketLink()

// Establish the connection
const proxy = await socketLink.connect('MNETSJSW')

const mutation = `
mutation SetLink($serviceId: String!, $enabled: Boolean) {
  setConnectLink(serviceId: $serviceId, enabled: $enabled) {
    code
    enabled
    created
  }
}`

// The address can not be used in your application
const address = proxy.address


```

Remove a key:

```graphql
mutation RemoveLink($serviceId: String!) {
  removeConnectLink(serviceId: $serviceId)
}
```

## Account Authentication

Alternatively you can authenticate at the account level. Account authentication will allow connecting with a `serviceId` to any device service that the account as access to.&#x20;

```typescript
// ...

// Establish the connection
const proxy = client.connect('80:00:00:00:01:0C:2B:9D', {
  credentials: 'path/to/credentials'
})

// ...
```

### User Access Key and Secret

You can generate and manage access key and secrets from the [Account > Access Keys](https://link.remote.it/credentials) section of the Remote.It apps.&#x20;

To use account credentials you have three options:

1. **Credentials File** Path to the file can be added to the `credentials` configuration option or it can be placed in the default `~/.remoteit/credentials` location.
2. **Environment Variables** `R3_ACCESS_KEY_ID` and `R3_SECRET_ACCESS_KEY`
3. **Configuration Options** `keyId` and `secret`

***

## Connection Target

A Remote.It agent must be running on your target network or system. If you can not install an agent on the system hosting the service (ssh, database, api) then you can install an agent on another system on the network and *jump* to the service.

{% hint style="info" %}
NPM Package for targets is coming soon
{% endhint %}

### Device installation

To configure a target service on the device:

1. Log in to one of the **Remote.It** apps
2. Click the blue `+` button to add a new device
3. Select your device type
4. Copy the installation command
5. Run the command on your device
6. Wait a few seconds for the device to appear in the app
7. Add a service to the new device by clicking on the  `+`  button on the device page
8. Select a service type *(SSH, HTTPS, Postgresql, etc)* to add, or manually enter the port and host your service is running on

### Jump Installation

For a service on the same network as your device, just follow the steps above, except use the local network address and port.

You can now select a service in the app and generate a **Service Key** to connect with.

***

## CLI

The socket-link NPM package comes with a build in cli as well that can be leveraged for easy connecting and scripting as well.

Sample ssh connection:

```sh
socket-link connect TLDY6IIY -- ssh -p {port} -l root {address}
```

### Commands

#### `api`

You an use the `api` command to easily execute [GraphQL](https://api.remote.it/graphql/v1/doc) queries and mutations using your [account credentials.](#account-authentication)

Basic GraphQL query:

```sh
socket-link api "query { version }"
```

Sample query for [service key](#service-keys) from our demo device using a service `id` variable:

```sh
socket-link api -v '{"id": "80:00:00:00:01:0C:2B:9D"}' 'query ($id: [String!]!) { login { service(id: $id) { link(type: [WSS]) { code } } } }'
```

***

## API

### SocketLink Constructor

**Description**

The `SocketLink` constructor initializes a new instance of the `SocketLink` class with specified options.

**Syntax**

```typescript
constructor(options: Partial<ClientOptions> = {})
```

**Parameters**

`options`: A partial object of `ClientOptions` type, providing various configuration options for `SocketLink`. It includes:

* `router`: Hostname of the Remote.It socket-link router.
* `keyId`: Authentication key ID. Defaults to `process.env.R3_ACCESS_KEY_ID`.
* `secret`: Authentication secret. Defaults to `process.env.R3_SECRET_ACCESS_KEY`.
* `config`: Path to the Remote.It configuration files.
* `profile`: Credential profile name.
* `debug`: Boolean flag to enable debug output.

**Example Usage**

```typescript
const socketLinkOptions = {
  router: 'example.router.com',
  keyId: 'yourKeyId',
  secret: 'yourSecret',
  config: '/path/to/config',
  profile: 'default',
  debug: true
};

const socketLink = new SocketLink(socketLinkOptions);
```

***

### SocketLink Class Methods

#### `debug`

Getter method to retrieve the debug state.

* **Returns**: `boolean` - The current debug state.

#### `router`

Getter method to retrieve the router string.

* **Returns**: `string` - The current router string.

#### `resolve(name: string): string`

Resolves a path relative to the Remote.It configuration directory.

* **Parameters**: `name` - The filename or path to resolve.
* **Returns**: `string` - The resolved path.

#### `api(query: string, variables?: any): Promise<any>`

Sends a GraphQL API request.

* **Parameters**:
  * `query` - The GraphQL query string.
  * `variables` (optional) - The variables for the GraphQL query.
* **Returns**: `Promise<any>` - The data returned from the API.

#### `connect(target: string, options?: Partial<ProxyOptions>): Promise<Proxy>`

Establishes a proxy connection to a target.

* **Parameters**:
  * `target` - The target for the proxy connection.
  * `options` (optional) - Additional options for the proxy.
* **Returns**: `Promise<Proxy>` - The Proxy instance.

#### `register(options?: Partial<ServiceOptions>): Promise<Service>`

Registers a new service.

* **Parameters**:
  * `options` (optional) - Options for the service registration.
* **Returns**: `Promise<Service>` - The Service instance.

#### `getSignature(): Promise<SigningKey | undefined>`

Retrieves a signing key for API requests.

* **Returns**: `Promise<SigningKey | undefined>` - The signing key or undefined if not found or not accessible.
