1Password Connect SDK for JavaScript and TypeScript

repository·main·Indexed 41 days ago

https://github.com/1password/connect-sdk-js

A JavaScript and TypeScript SDK (version 1.4.2) for interacting with a self-hosted 1Password Connect server. It enables Node.js applications and automations to securely access and manage 1Password secrets and items via the Connect API, featuring a fluent ItemBuilder for programmatic item creation and support for custom HTTP clients via the IRequestClient interface.

Tokens
9.5K
Snippets
37
Records
45
Agent score
51%

What's inside 1Password Connect SDK JS

  1. Overview of 1Password Connect SDK JS

    main
    The 1Password Connect SDK JS is a library designed for Node.js applications, tools, and automations. It provides access to the 1Password Connect API hosted on your own infrastructure, enabling your applications to leverage 1Password Secrets Automation to access and manage items in 1Password vaults.
  2. Implement a custom HTTPClient

    main

    You can customize how the library sends requests by providing a custom class that implements the IRequestClient interface. This is useful for handling proxy network access, adding custom logging, or using a specific Node.js HTTP library.

    The interface requires a defaultTimeout and a request method.

    import { ClientRequestOptions } from "./client";
    
    interface IRequestClient {
        defaultTimeout: number;
    
        request(
            method: HTTPMethod,
            url: string,
            opts: ClientRequestOptions,
        ): Promise<Response>;
    }
  3. Prerequisites for running the JavaScript Connect SDK example

    main

    To run the provided example, you must have the following components ready:

    1. Docker: Installed and running on your machine.
    2. 1Password Connect Server: A server deployed on your infrastructure.
    3. Connect Token: A token with read/write permissions for at least one vault accessible by the Connect instance.
  4. Build and run the JavaScript Connect SDK example via Docker

    main

    The example is packaged as a Docker image. You can build the image and then run it by passing your 1Password Connect configuration via environment variables.

    Build the image

    docker build -t js-connect-sdk-example .

    Run the container

    Pass the following environment variables to the docker run command:

    • OP_CONNECT_TOKEN: Your 1Password Connect token.
    • OP_VAULT: The ID of the vault you want to use.
    • OP_CONNECT_HOST: The host address of your Connect instance.
    • SECRET_STRING: A random string that the example will use to create an item.

    Note for local development: If your Connect instance is running locally on your host machine, set OP_CONNECT_HOST to http://host.docker.internal:8080.

    docker build -t js-connect-sdk-example .
    
    docker run \
    --env OP_CONNECT_TOKEN=<YOUR_CONNECT_TOKEN> \
    --env OP_VAULT=<YOUR_VAULT_ID> \
    --env OP_CONNECT_HOST=<YOUR_CONNECT_HOST> \\
    --env SECRET_STRING=<ANY_RANDOM_STRING> \
    -it js-connect-sdk-example
  5. Install the 1Password Connect SDK JS

    main

    You can install the @1password/connect SDK using npm or Yarn to allow your JavaScript or TypeScript applications to access 1Password items via a self-hosted 1Password Connect server.

    npm install @1password/connect
    yarn add @1password/connect
  6. Create a Connect API Client

    main

    Initialize a new connection to the 1Password Connect server using the OnePasswordConnect function. You must provide the serverURL and an authentication token. You can also enable keepAlive to use HTTP pooling for better performance.

    import { OnePasswordConnect } from "@1password/connect";
    
    // Create new connector with HTTP Pooling
    const op = OnePasswordConnect({
        serverURL: "http://localhost:8080",
        token: "my-token",
        keepAlive: true,
    });
  7. Manage item sections and fields within them

    main

    Sections allow you to group related fields within a 1Password item.

    • Explicit Creation: Use addSection(sectionName: string) to create an empty section.
    • Implicit Creation: When calling addField(opts), providing a sectionName will automatically create that section if it does not already exist.
    • Normalization: Section names are normalized using slugify (converted to lowercase and stripped of special characters) to ensure consistent lookups. Section IDs are unique only within the scope of a single item.
  8. Initialize the 1Password Connect client

    main

    To interact with 1Password Connect, use the newConnectClient factory function or instantiate the OPConnect class directly. You must provide a configuration object containing the serverURL of your 1Password Connect instance and a valid token for your Service Account.

    Configuration Options (OPConfig)

    • serverURL (required): The URL of your 1Password Connect server.
    • token (required): The Service Account token.
    • httpClient (optional): A custom implementation of IRequestClient if you need to override default HTTP behavior.
    • keepAlive (optional): Boolean to enable/disable keep-alive.
    • timeout (optional): Request timeout in milliseconds.
    import { newConnectClient } from '@1password/connect';
    
    const client = newConnectClient({
        serverURL: 'https://your-connect-server.com',
        token: 'your-service-account-token'
    });
  9. Manage Vaults

    main

    Use the client instance to list all available vaults or retrieve specific vaults by their ID or title.

    • listVaults(): Returns a list of all vaults.
    • getVault(idOrTitle): Retrieves a vault using either its ID or its title.
    • getVaultById(vaultId): Retrieves a vault specifically by its unique ID.
    • getVaultByTitle(vaultTitle): Retrieves a vault specifically by its title.
    // Get a list of all vaults
    const vaults = await op.listVaults();
    
    // Get a specific vault
    const vault1 = await op.getVault("vaultId _or_ vaultTitle");
    const vault2 = await op.getVaultById("vaultId");
    const vault3 = await op.getVaultByTitle("Vault Title");
  10. Manage Items

    main

    The SDK provides an ItemBuilder to construct new items and several methods to perform CRUD operations on items within a specific vault.

    Creating Items

    Use ItemBuilder to define the category and fields (including label, value, and sectionName), then call createItem(vaultId, newItem).

    Retrieving Items

    • getItem(vaultId, idOrTitle): Get an item by ID or title.
    • getItemById(itemId): Get an item by its unique ID.
    • getItemByTitle(vaultId, itemTitle): Get an item by its title within a vault.

    Updating and Deleting Items

    • To update, modify the properties on the returned item object and pass it to updateItem(vaultId, item).
    • To delete, pass the vaultId and the item's id to deleteItem(vaultId, itemId).
    import { ItemBuilder } from "@1password/connect";
    
    const vaultId = "vaultId";
    
    // Create an item
    const newItem = new ItemBuilder()
        .setCategory("LOGIN")
        .addField({
            label: "Example",
            value: "MySecret",
            sectionName: "Demo Section",
        })
        .build();
    
    const createdItem = await op.createItem(vaultId, newItem);
    
    // Get an item
    const item = await op.getItem(vaultId, "itemId _or_ itemTitle");
    const itemById = await op.getItemById("itemId");
    const itemByName = await op.getItemByTitle(vaultId, "Item Title");
    
    // Update an item
    item.title = "New Item Title";
    const updatedItem = await op.updateItem(vaultId, item);
    
    // Delete an item
    await op.deleteItem(vaultId, updatedItem.id);
  11. Configure HTTPClient with ClientConfig

    main

    When instantiating an HTTPClient, you can pass a ClientConfig object to customize the underlying axios instance:

    • keepAlive (boolean, optional): If set to true, enables HTTP/HTTPS keep-alive agents to reuse connections.
    • timeout (number, optional): The request timeout in milliseconds. Defaults to 15000 (15 seconds).
    const config: ClientConfig = {
      keepAlive: true,
      timeout: 5000
    };
    
    const client = new HTTPClient(config);