1Password Connect SDK for JavaScript and TypeScript
repository·main·Indexed 41 days ago
https://github.com/1password/connect-sdk-jsA 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.
What's inside 1Password Connect SDK JS
- 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.
Implement a custom HTTPClient
mainYou can customize how the library sends requests by providing a custom class that implements the
IRequestClientinterface. This is useful for handling proxy network access, adding custom logging, or using a specific Node.js HTTP library.The interface requires a
defaultTimeoutand arequestmethod.import { ClientRequestOptions } from "./client"; interface IRequestClient { defaultTimeout: number; request( method: HTTPMethod, url: string, opts: ClientRequestOptions, ): Promise<Response>; }Prerequisites for running the JavaScript Connect SDK example
mainTo run the provided example, you must have the following components ready:
- Docker: Installed and running on your machine.
- 1Password Connect Server: A server deployed on your infrastructure.
- Connect Token: A token with read/write permissions for at least one vault accessible by the Connect instance.
Build and run the JavaScript Connect SDK example via Docker
mainThe 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 runcommand: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_HOSTtohttp://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-exampleInstall the 1Password Connect SDK JS
mainYou can install the
@1password/connectSDK 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/connectyarn add @1password/connectCreate a Connect API Client
mainInitialize a new connection to the 1Password Connect server using the
OnePasswordConnectfunction. You must provide theserverURLand an authenticationtoken. You can also enablekeepAliveto 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, });Manage item sections and fields within them
mainSections 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 asectionNamewill 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.
- Explicit Creation: Use
Initialize the 1Password Connect client
mainTo interact with 1Password Connect, use the
newConnectClientfactory function or instantiate theOPConnectclass directly. You must provide a configuration object containing theserverURLof your 1Password Connect instance and a validtokenfor 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 ofIRequestClientif 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' });Enable debug logging
mainThe client uses the
debuglibrary for runtime information. All logs are under theopconnectnamespace. To enable logging, set theDEBUGenvironment variable toopconnect:*.DEBUG=opconnect:*Manage Vaults
mainUse 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");Manage Items
mainThe SDK provides an
ItemBuilderto construct new items and several methods to perform CRUD operations on items within a specific vault.Creating Items
Use
ItemBuilderto define the category and fields (includinglabel,value, andsectionName), then callcreateItem(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
vaultIdand the item'sidtodeleteItem(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);Configure HTTPClient with ClientConfig
mainWhen instantiating an
HTTPClient, you can pass aClientConfigobject to customize the underlying axios instance:keepAlive(boolean, optional): If set totrue, enables HTTP/HTTPS keep-alive agents to reuse connections.timeout(number, optional): The request timeout in milliseconds. Defaults to15000(15 seconds).
const config: ClientConfig = { keepAlive: true, timeout: 5000 }; const client = new HTTPClient(config);