### Execute SDK Examples Source: https://github.com/1password/onepassword-sdk-js/blob/main/examples/README.md Run the provided example code using either ESM or CommonJS module formats. ```bash npm run esm-example ``` ```bash npm run commonjs-example ``` -------------------------------- ### DesktopAuth Authentication Example Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/configuration.md Example of creating a client using the DesktopAuth class for authentication. Requires the 1Password desktop app to be installed and running. ```typescript import sdk from "@1password/sdk"; const client = await sdk.createClient({ auth: new sdk.DesktopAuth("My Personal Account"), integrationName: "My Tool", integrationVersion: "v1.0.0", }); ``` -------------------------------- ### Example: Using DesktopAuth for Client Initialization Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-reference/client.md Illustrates how to create a DesktopAuth instance and use it to initialize the 1Password SDK client. ```typescript import sdk from "@1password/sdk"; const auth = new sdk.DesktopAuth("My Personal Account"); const client = await sdk.createClient({ auth: auth, integrationName: "My Tool", integrationVersion: "v2.1.0", }); ``` -------------------------------- ### Example: Client Creation Error Handling Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-reference/client.md Shows how to handle potential errors during client creation, such as DesktopSessionExpiredError or RateLimitExceededError. ```typescript try { const client = await sdk.createClient({ auth: process.env.OP_SERVICE_ACCOUNT_TOKEN, integrationName: "My App", integrationVersion: "v1.0.0", }); } catch (error) { if (error instanceof sdk.DesktopSessionExpiredError) { console.error("Desktop session expired, please unlock 1Password"); } else if (error instanceof sdk.RateLimitExceededError) { console.error("Rate limit exceeded, please retry later"); } else { console.error("Failed to create client:", error); } } ``` -------------------------------- ### Install 1Password SDK with NPM Source: https://github.com/1password/onepassword-sdk-js/blob/main/README.md Install the 1Password JavaScript SDK using NPM. This is the first step to integrating with 1Password in your project. ```bash npm install @1password/sdk ``` -------------------------------- ### Install 1Password SDK with Yarn Source: https://github.com/1password/onepassword-sdk-js/blob/main/README.md Install the 1Password JavaScript SDK using Yarn. This is another common package manager for installing the SDK. ```bash yarn add @1password/sdk ``` -------------------------------- ### Install 1Password SDK with PNPM Source: https://github.com/1password/onepassword-sdk-js/blob/main/README.md Install the 1Password JavaScript SDK using PNPM. This is an alternative package manager for installing the SDK. ```bash pnpm add @1password/sdk ``` -------------------------------- ### Example: Accessing Client Sub-APIs Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-reference/client.md Demonstrates how to use the client instance to access and interact with sub-APIs for secrets, items, vaults, and groups. ```typescript const client = await sdk.createClient(config); // Secrets operations const secret = await client.secrets.resolve("op://vault/item/field"); // Items operations const item = await client.items.get(vaultId, itemId); const items = await client.items.list(vaultId); // Vaults operations const vaults = await client.vaults.list(); const vault = await client.vaults.get(vaultId, { accessors: false }); // Groups operations const group = await client.groups.get(groupId, { vaultPermissions: true }); ``` -------------------------------- ### Example: Create Client with Desktop App Auth Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-reference/client.md Demonstrates creating a 1Password SDK client using desktop application authentication. Requires a DesktopAuth instance with the account name. ```typescript import sdk from "@1password/sdk"; const client = await sdk.createClient({ auth: new sdk.DesktopAuth("My 1Password Account"), integrationName: "My Integration", integrationVersion: "v1.0.0", }); const item = await client.items.get(vaultId, itemId); ``` -------------------------------- ### Minimal Service Account Configuration Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/configuration.md Demonstrates the basic setup for creating an SDK client using a service account token. Ensure the OP_SERVICE_ACCOUNT_TOKEN environment variable is set. ```typescript import sdk from "@1password/sdk"; const client = await sdk.createClient({ auth: process.env.OP_SERVICE_ACCOUNT_TOKEN, integrationName: "MyApp", integrationVersion: "v1.0.0", }); ``` -------------------------------- ### Example: Create Client with Service Account Auth Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-reference/client.md Demonstrates creating a 1Password SDK client using a service account token. Ensure the token is available in the environment variables. ```typescript import sdk from "@1password/sdk"; const client = await sdk.createClient({ auth: process.env.OP_SERVICE_ACCOUNT_TOKEN, integrationName: "My Integration", integrationVersion: "v1.0.0", }); const vaults = await client.vaults.list(); ``` -------------------------------- ### Secret Reference Format Examples Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/REFERENCE.md Examples demonstrating the 1Password secret reference URI format, including references by name and ID, and specifying attributes like TOTP or SSH format. ```typescript "op://personal/github/password" ``` ```typescript "op://vault-id/item-id/TOTP_field?attribute=totp" ``` ```typescript "op://vault/ssh-key/private_key?ssh-format=openssh" ``` -------------------------------- ### Using .env file for Service Account Token Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/configuration.md Example of configuring the OP_SERVICE_ACCOUNT_TOKEN using a .env file with the dotenv library for local development. ```bash # .env OP_SERVICE_ACCOUNT_TOKEN=your_token_here ``` ```typescript import dotenv from "dotenv"; dotenv.config(); const client = await sdk.createClient({ auth: process.env.OP_SERVICE_ACCOUNT_TOKEN, integrationName: "My App", integrationVersion: "v1.0.0", }); ``` -------------------------------- ### Secret Reference Examples Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/INDEX.md Illustrates the format for referencing secrets within the 1Password system, including examples using vault and item names or IDs. ```plaintext op://vault-name/item-name/field-name ``` ```plaintext op://personal/github/password ``` ```plaintext op://vault-id/item-id/TOTP_field?attribute=totp ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/1password/onepassword-sdk-js/blob/main/examples/README.md Set the required service account token and vault UUID environment variables before running the SDK examples. ```bash export OP_SERVICE_ACCOUNT_TOKEN="" ``` ```bash export OP_VAULT_ID="" ``` -------------------------------- ### Full Service Account Configuration with Error Handling Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/configuration.md Provides a robust example of initializing an SDK client with a service account token, including essential error handling for missing tokens and rate limit exceptions. ```typescript import sdk from "@1password/sdk"; const token = process.env.OP_SERVICE_ACCOUNT_TOKEN; if (!token) { throw new Error("Missing OP_SERVICE_ACCOUNT_TOKEN environment variable"); } try { const client = await sdk.createClient({ auth: token, integrationName: "MyApp", integrationVersion: "v1.2.3", }); console.log("Client initialized successfully"); } catch (error) { if (error instanceof sdk.RateLimitExceededError) { console.error("Rate limited, please retry later"); } else { console.error("Failed to initialize client:", error); } } ``` -------------------------------- ### Complete Vault Workflow Example Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-reference/vaults.md Demonstrates the full lifecycle of a vault using the 1Password SDK. This includes creating, listing, retrieving, updating, managing permissions, and deleting a vault. Ensure the SDK is imported and a client is initialized before running. ```typescript import sdk from "@1password/sdk"; const client = await sdk.createClient(config); // 1. Create a vault const vault = await client.vaults.create({ title: "Team Vault", description: "Shared team credentials", }); console.log(`Created vault: ${vault.id}`); // 2. List all vaults const vaults = await client.vaults.list(); console.log(`Total vaults: ${vaults.length}`); // 3. Get vault overview const overview = await client.vaults.getOverview(vault.id); console.log(`Vault title: ${overview.title}`); console.log(`Active items: ${overview.activeItemCount}`); // 4. Update vault const updated = await client.vaults.update(vault.id, { title: "Team Credentials Vault", description: "Updated description", }); console.log(`Updated: ${updated.title}`); // 5. Grant group permissions await client.vaults.grantGroupPermissions(vault.id, [ { groupId: "admins", permissions: sdk.MANAGE_VAULT | sdk.READ_ITEMS | sdk.CREATE_ITEMS, }, { groupId: "developers", permissions: sdk.READ_ITEMS | sdk.REVEAL_ITEM_PASSWORD, }, ]); // 6. Update permissions await client.vaults.updateGroupPermissions([ { vaultId: vault.id, groupId: "developers", permissions: sdk.READ_ITEMS | sdk.CREATE_ITEMS, }, ]); // 7. Revoke permissions await client.vaults.revokeGroupPermissions(vault.id, "developers"); // 8. Delete vault await client.vaults.delete(vault.id); console.log("Vault deleted"); ``` -------------------------------- ### get() Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-reference/vaults.md Fetches detailed vault information, optionally including accessor details for access control. ```APIDOC ## get() ### Description Gets detailed vault information including access details. ### Method GET ### Endpoint /vaults/{vaultId} ### Parameters #### Path Parameters - **vaultId** (string) - Yes - ID of the vault #### Query Parameters - **vaultParams.accessors** (boolean) - No - Include vault accessor information ### Response #### Success Response (200) - **Vault** - Full vault details with optional access information ### Throws - Generic `Error` - If vault not found or access denied ### Example - Get Vault with Access Info ```typescript const vault = await client.vaults.get(vaultId, { accessors: true }); console.log(`Vault: ${vault.title}`); console.log(`Type: ${vault.vaultType}`); if (vault.access) { for (const access of vault.access) { console.log(`Access: ${access.accessorType} ${access.accessorUuid}`); } } ``` ### Example - Get Vault Without Access Info ```typescript const vault = await client.vaults.get(vaultId, { accessors: false }); console.log(`Title: ${vault.title}`); console.log(`Description: ${vault.description}`); ``` ``` -------------------------------- ### Complete Group Workflow Example Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-reference/groups.md Demonstrates fetching group details, including vault permissions, and identifying specific group types like administrators and team members. Ensure the SDK is configured with appropriate credentials. ```typescript import sdk from "@1password/sdk"; const client = await sdk.createClient(config); // Get a group by ID const group = await client.groups.get(groupId, { vaultPermissions: false }); console.log(`Group Name: ${group.title}`); console.log(`Type: ${group.groupType}`); console.log(`State: ${group.state}`); // Get group with vault access details const groupWithAccess = await client.groups.get(groupId, { vaultPermissions: true }); if (groupWithAccess.vaultAccess) { console.log("\nVault Access:"); for (const access of groupWithAccess.vaultAccess) { console.log(`- Vault: ${access.vaultUuid}`); console.log(` Permissions: ${access.permissions}`); console.log(` Accessor Type: ${access.accessorType}`); } } // Example: Get admin group const admins = await client.groups.get("admin-group-id", { vaultPermissions: true }); if (admins.groupType === sdk.GroupType.Administrators) { console.log("This is the admin group"); } // Example: Get team members group const teamMembers = await client.groups.get("team-group-id", { vaultPermissions: true }); if (teamMembers.groupType === sdk.GroupType.TeamMembers) { console.log(`Team has ${teamMembers.vaultAccess?.length || 0} vaults`); } ``` -------------------------------- ### get() Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-reference/items.md Retrieves a single item by vault and item ID. ```APIDOC ## GET /items/{itemId} ### Description Retrieves a single item by vault and item ID. ### Method GET ### Endpoint /items/{itemId} ### Parameters #### Path Parameters - **itemId** (string) - Yes - ID of the item to retrieve #### Query Parameters - **vaultId** (string) - Yes - ID of the vault containing the item ### Response #### Success Response (200) - **Item** - The retrieved item with all fields populated. ### Throws - Generic `Error` - If the item is not found or permission issues occur. ``` -------------------------------- ### Complete File Workflow Example Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-reference/items-files.md This snippet shows the full lifecycle of managing file attachments for a 1Password item, including creation, reading, attaching, and deletion. Ensure you have the necessary configuration and vault ID set up before running. ```typescript import fs from "fs"; import sdk from "@1password/sdk"; const client = await sdk.createClient(config); // 1. Create an item with a file attachment let item = await client.items.create({ title: "Item with File", category: sdk.ItemCategory.Login, vaultId: vaultId, files: [ { name: "attachment.txt", content: new Uint8Array(fs.readFileSync("attachment.txt")), sectionId: "section-1", fieldId: "file-field-1", }, ], }); console.log(`Created item with file: ${item.files.length} file(s)`); // 2. Read the attached file const fileContent = await client.items.files.read( item.vaultId, item.id, item.files[0].attributes ); console.log(`File size: ${fileContent.length} bytes`); // 3. Attach another file item = await client.items.files.attach(item, { name: "new-file.txt", content: new Uint8Array(fs.readFileSync("new-file.txt")), sectionId: "section-1", fieldId: "file-field-2", }); console.log(`Total files: ${item.files.length}`); // 4. Delete the first file item = await client.items.files.delete( item, item.files[0].sectionId, item.files[0].fieldId ); console.log(`Deleted file, remaining: ${item.files.length}`); ``` -------------------------------- ### Accessing 1Password API Resources Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-index.md Examples demonstrating how to use the client to access various 1Password API endpoints for secrets, items, item sharing, item files, vaults, and groups. ```typescript // Secrets await client.secrets.resolve("op://vault/item/field"); // Items await client.items.create({ ... }); await client.items.get(vaultId, itemId); await client.items.put(item); // Item Sharing await client.items.shares.getAccountPolicy(vaultId, itemId); // Item Files await client.items.files.attach(item, fileParams); await client.items.files.read(vaultId, itemId, fileAttributes); // Vaults await client.vaults.create({ ... }); await client.vaults.list(); // Groups await client.groups.get(groupId, { vaultPermissions: true }); ``` -------------------------------- ### get() Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-reference/items.md Retrieves a single item by its vault and item ID. It returns the full item details with all fields decrypted. ```APIDOC ## get() ### Description Retrieves a single item by its vault and item ID. It returns the full item details with all fields decrypted. ### Method `get(vaultId: string, itemId: string): Promise` ### Parameters #### Path Parameters - **vaultId** (string) - Yes - ID of the vault - **itemId** (string) - Yes - ID of the item ### Return Type `Promise` - Full item details with all fields decrypted ### Throws - Generic `Error` - If item not found or access denied ### Example ```typescript const item = await client.items.get("vault-id", "item-id"); console.log(item.title); console.log(item.fields); console.log(item.notes); ``` ``` -------------------------------- ### Export Service Account Token Environment Variable Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/configuration.md Example of exporting the service account token as an environment variable. This token is used for authentication. ```bash export OP_SERVICE_ACCOUNT_TOKEN="" ``` -------------------------------- ### Basic Error Handling with Try-Catch Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/errors.md Implement a basic try-catch block to handle potential errors during SDK operations. This example shows how to catch specific SDK error types like DesktopSessionExpiredError and RateLimitExceededError. ```typescript try { const client = await sdk.createClient(config); const item = await client.items.get(vaultId, itemId); } catch (error) { if (error instanceof sdk.DesktopSessionExpiredError) { console.error("Desktop session expired"); } else if (error instanceof sdk.RateLimitExceededError) { console.error("Rate limited"); } else { console.error("Unexpected error:", error); } } ``` -------------------------------- ### Complete Sharing Workflow Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-reference/items-shares.md Demonstrates the full process of creating a share link for specific recipients. This includes getting the item, retrieving the account sharing policy, validating the provided recipients, and finally creating the share link with a one-day expiration and multiple uses allowed. ```typescript import sdk from "@1password/sdk"; const client = await sdk.createClient(config); // 1. Get the item to share const item = await client.items.get(vaultId, itemId); // 2. Retrieve the account sharing policy const policy = await client.items.shares.getAccountPolicy(vaultId, itemId); // 3. Validate the recipients const validRecipients = await client.items.shares.validateRecipients( policy, ["alice@example.com", "bob@example.com"] ); // 4. Create the share link const shareLink = await client.items.shares.create( item, policy, { recipients: validRecipients, expireAfter: sdk.ItemShareDuration.OneDay, oneTimeOnly: false, } ); console.log(`Share link created: ${shareLink}`); ``` -------------------------------- ### List All Vaults Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-reference/vaults.md Retrieve a list of all vaults accessible by the authenticated user or service account. This example iterates through the vaults and logs their ID, title, active item count, and type. ```typescript const vaults = await client.vaults.list(); for (const vault of vaults) { console.log(`${vault.id}: ${vault.title}`); console.log(` Active items: ${vault.activeItemCount}`); console.log(` Type: ${vault.vaultType}`); } ``` -------------------------------- ### Client Creation Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/REFERENCE.md Demonstrates how to create a client instance using either a service account token or the desktop application for authentication. ```APIDOC ## Client Creation ### Description This section details the methods for creating a client instance to interact with the 1Password API. Two primary authentication methods are supported: using a service account token or leveraging the desktop application. ### Method `sdk.createClient(options)` ### Parameters #### Request Body - **options** (object) - Required - Configuration options for the client. - **auth** (string | DesktopAuth) - Required - Authentication credential. Can be a service account token (string) or a `DesktopAuth` instance. - **integrationName** (string) - Required - The name of the integrating application. - **integrationVersion** (string) - Required - The version of the integrating application. #### `DesktopAuth` Object - **accountName** (string) - Required - The name of the 1Password account to authenticate with. ### Request Example (Service Account) ```typescript const client = await sdk.createClient({ auth: process.env.OP_SERVICE_ACCOUNT_TOKEN, integrationName: "My App", integrationVersion: "v1.0.0", }); ``` ### Request Example (Desktop App) ```typescript const client = await sdk.createClient({ auth: new sdk.DesktopAuth("My Account Name"), integrationName: "My App", integrationVersion: "v1.0.0", }); ``` ### Response - **client** (Client) - A client instance that can be used to make API calls. ``` -------------------------------- ### Groups API - Get Group Details Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-index.md Retrieves details for a specific group using its identifier and optional parameters. ```APIDOC ## GET client.groups.get ### Description Get group details by group identifier. ### Method GET ### Endpoint `/groups/{group}` ### Parameters #### Path Parameters - **group** (string) - Required - The identifier of the group. #### Query Parameters - **params** (GroupGetParams) - Optional - Parameters for fetching group details. ### Response #### Success Response (200) - **Group** - Details of the group. ``` -------------------------------- ### Get Vault Details Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-index.md Retrieves the full details of a specific 1Password vault. This method is part of the Vaults API. ```typescript `get(vault: string, params: VaultGetParams): Promise` ``` -------------------------------- ### Publish SDK Release Source: https://github.com/1password/onepassword-sdk-js/blob/main/client/release/README.md Execute these commands to publish the release. Ensure GITHUB_TOKEN and NPM_TOKEN are set before running. ```bash npm run release ``` ```bash npm run release-no-core ``` ```bash npm run release-stable ``` ```bash npm run release-no-core-stable ``` -------------------------------- ### Get Vault Overview Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-index.md Retrieves a summary overview of a specific 1Password vault. This method is part of the Vaults API. ```typescript `getOverview(vault: string): Promise` ``` -------------------------------- ### Prepare SDK Release Source: https://github.com/1password/onepassword-sdk-js/blob/main/client/release/README.md Run these commands at the root of the repository to prepare a release, depending on whether the SDK core has been updated. ```bash npm run prep-release ``` ```bash npm run prep-release-no-core ``` -------------------------------- ### Batch Get Items Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-index.md Retrieves multiple 1Password items by their identifiers from a specified vault. This method is part of the Items API. ```typescript `getAll(vault: string, items: string[]): Promise` ``` -------------------------------- ### Client Initialization Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/INDEX.md Details on how to create and initialize a client for interacting with the 1Password API, including authentication methods like service account tokens and DesktopAuth. ```APIDOC ## Client Module (`./api-reference/client.md`) ### Description This module provides the `createClient()` function and details about the Client class, enabling interaction with the 1Password API. It covers client initialization patterns and configuration passing, including support for DesktopAuth. ### Functions #### `createClient(config)` - **Description**: Initializes and returns a new 1Password client instance. - **Parameters**: - `config` (ClientConfiguration) - Required - Configuration object for the client. ### Classes #### Client - **Description**: Represents the main client for interacting with the 1Password API. - **Properties**: - (Details about client properties and methods would be listed here) ### Authentication - **DesktopAuth**: Class for handling authentication via the 1Password desktop application. - **Service Account Token**: Authentication using an OP_SERVICE_ACCOUNT_TOKEN environment variable or configuration object. ### Configuration Refer to `configuration.md` for detailed `ClientConfiguration` interface and examples. ``` -------------------------------- ### Get a Specific Item Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/REFERENCE.md Fetch a single item from a vault using its ID. This allows for detailed inspection or modification of an item. ```typescript // Get item const item = await client.items.get(vaultId, itemId); ``` -------------------------------- ### Create Client with Desktop Application Authentication Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/overview.md Instantiate the SDK client using the DesktopAuth class for authentication when running within a desktop environment. Specify your account name. ```typescript const client = await createClient({ auth: new DesktopAuth("My Account Name"), integrationName: "My App", integrationVersion: "v1.0.0" }); ``` -------------------------------- ### Create Client with Service Account Token Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/overview.md Use this method to create an SDK client by passing a service account token. Ensure the OP_SERVICE_ACCOUNT_TOKEN environment variable is set. ```typescript const client = await createClient({ auth: process.env.OP_SERVICE_ACCOUNT_TOKEN, integrationName: "My App", integrationVersion: "v1.0.0" }); ``` -------------------------------- ### Get Item Sharing Policy Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-index.md Retrieves the sharing policy for a specific item within a vault. This is part of the Items Shares API. ```typescript `getAccountPolicy(vault: string, item: string): Promise` ``` -------------------------------- ### Desktop Application Configuration Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/configuration.md Shows how to configure the SDK client for use in a desktop application by leveraging `DesktopAuth`. This method is suitable for local tools and applications running on a user's machine. ```typescript import sdk from "@1password/sdk"; const client = await sdk.createClient({ auth: new sdk.DesktopAuth("My Account Name"), integrationName: "LocalTool", integrationVersion: "v1.0.0", }); // Now use the client to access 1Password const vaults = await client.vaults.list(); ``` -------------------------------- ### createClient Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-index.md Main function to create an authenticated SDK client. Requires a configuration object including authentication details and integration information. ```APIDOC ## Client API **`createClient(config: ClientConfiguration): Promise`** Main function to create authenticated SDK client. See [Client API](./api-reference/client.md). ```typescript const client = await sdk.createClient({ auth: process.env.OP_SERVICE_ACCOUNT_TOKEN, integrationName: "My App", integrationVersion: "v1.0.0", }); ``` ``` -------------------------------- ### Get Single Item Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-index.md Retrieves a single 1Password item from a specified vault using its unique identifier. This method is part of the Items API. ```typescript `get(vault: string, item: string): Promise` ``` -------------------------------- ### Get Item Sharing Policy Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/REFERENCE.md Retrieves the account policy for sharing a specific item within a vault. This policy defines the rules and options for sharing. ```typescript // Get policy const policy = await client.items.shares.getAccountPolicy(vaultId, itemId); ``` -------------------------------- ### Get Group Without Vault Access Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-reference/groups.md Retrieves a group's basic information without including vault access details. Ensure the `groupId` is valid. ```typescript const group = await client.groups.get(groupId, { vaultPermissions: false }); console.log(`Group: ${group.title}`); console.log(`Type: ${group.groupType}`); console.log(`State: ${group.state}`); ``` -------------------------------- ### Environment-Specific Configuration Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/configuration.md Illustrates dynamic client configuration based on the environment (e.g., development vs. production). It uses `dotenv` for loading environment variables and conditionally sets authentication methods. ```typescript import sdk from "@1password/sdk"; import dotenv from "dotenv"; dotenv.config(); const isDevelopment = process.env.NODE_ENV === "development"; const client = await sdk.createClient({ auth: isDevelopment ? new sdk.DesktopAuth(process.env.OP_ACCOUNT_NAME || "Default") : process.env.OP_SERVICE_ACCOUNT_TOKEN, integrationName: "MyApp", integrationVersion: process.env.npm_package_version || "unknown", }); ``` -------------------------------- ### Get Detailed Vault Information with Accessors Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-reference/vaults.md Retrieve full vault details, including accessor information, by specifying `accessors: true`. This is useful for understanding who or what has access to the vault. ```typescript const vault = await client.vaults.get(vaultId, { accessors: true }); console.log(`Vault: ${vault.title}`); console.log(`Type: ${vault.vaultType}`); if (vault.access) { for (const access of vault.access) { console.log(`Access: ${access.accessorType} ${access.accessorUuid}`); } } ``` -------------------------------- ### Document Creation and Replacement Workflow Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-reference/items-files.md Demonstrates a workflow for creating a document item and then later replacing its content. ```typescript // Create document item const docItem = await client.items.create({ title: "My Document", category: sdk.ItemCategory.Document, vaultId: vaultId, document: { name: "initial.txt", content: new Uint8Array(fs.readFileSync("initial.txt")), }, }); // Later, replace with new version const updated = await client.items.files.replaceDocument( docItem, { name: "updated.txt", content: new Uint8Array(fs.readFileSync("updated.txt")), } ); ``` -------------------------------- ### Attach, Read, and Delete Files Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/REFERENCE.md Demonstrates how to attach a new file to an item, read an existing file's content, and delete a file from an item using the 1Password SDK. ```typescript // Attach file const updated = await client.items.files.attach(item, { name: "document.pdf", content: new Uint8Array(fs.readFileSync("document.pdf")), sectionId: "section-id", fieldId: "file-field", }); // Read file const content = await client.items.files.read( item.vaultId, item.id, item.files[0].attributes ); // Delete file const changed = await client.items.files.delete( item, item.files[0].sectionId, item.files[0].fieldId ); ``` -------------------------------- ### createClient() Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-reference/client.md Creates an authenticated 1Password SDK client. This function is the primary way to initialize the SDK for use. ```APIDOC ## createClient() ### Description Creates an authenticated 1Password SDK client. This function is the primary way to initialize the SDK for use. ### Method `async` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Parameters - **config** (ClientConfiguration) - Required - Configuration object for client initialization - **config.auth** (string | DesktopAuth) - Required - Authentication method: service account token string or DesktopAuth instance - **config.integrationName** (string) - Required - Name of your application/integration - **config.integrationVersion** (string) - Required - Version of your application (e.g., "v1.0.0") ### Request Example - Service Account Auth ```typescript import sdk from "@1password/sdk"; const client = await sdk.createClient({ auth: process.env.OP_SERVICE_ACCOUNT_TOKEN, integrationName: "My Integration", integrationVersion: "v1.0.0", }); const vaults = await client.vaults.list(); ``` ### Request Example - Desktop App Auth ```typescript import sdk from "@1password/sdk"; const client = await sdk.createClient({ auth: new sdk.DesktopAuth("My 1Password Account"), integrationName: "My Integration", integrationVersion: "v1.0.0", }); const item = await client.items.get(vaultId, itemId); ``` ### Response #### Success Response `Promise` - Authenticated client instance with secrets, items, vaults, and groups properties #### Response Example ```typescript // client instance { secrets: SecretsApi, items: ItemsApi, vaults: VaultsApi, groups: GroupsApi } ``` ### Throws - `DesktopSessionExpiredError` - Desktop app session expired (auth method only) - `RateLimitExceededError` - Rate limit exceeded - Generic `Error` - For invalid configuration or network issues ### Example - Error Handling ```typescript try { const client = await sdk.createClient({ auth: process.env.OP_SERVICE_ACCOUNT_TOKEN, integrationName: "My App", integrationVersion: "v1.0.0", }); } catch (error) { if (error instanceof sdk.DesktopSessionExpiredError) { console.error("Desktop session expired, please unlock 1Password"); } else if (error instanceof sdk.RateLimitExceededError) { console.error("Rate limit exceeded, please retry later"); } else { console.error("Failed to create client:", error); } } ``` ``` -------------------------------- ### Get Multiple Items Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-reference/items.md Retrieves multiple items from a vault using their IDs. This is useful for batch operations. The response contains individual results for each item, indicating success or failure. ```typescript const response = await client.items.getAll(vaultId, [ "item-id-1", "item-id-2", "item-id-3", ]); for (const result of response.individualResponses) { if (result.content) { console.log(`Retrieved: ${result.content.title}`); } else if (result.error) { console.error(`Failed: ${result.error.message}`); } } ``` -------------------------------- ### Configuration Reference Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/INDEX.md Details on client configuration options, including authentication methods and environment variables. ```APIDOC ## Configuration Reference (`./configuration.md`) ### Description Details the `ClientConfiguration` interface and various methods for configuring the 1Password JavaScript SDK, including authentication and environment-specific settings. ### ClientConfiguration Interface - **Description**: The primary interface for configuring the SDK client. ### Authentication Methods - **Service Account Token**: Configuration using an environment variable `OP_SERVICE_ACCOUNT_TOKEN` or directly within the configuration object. - **DesktopAuth Class**: Usage and integration of the `DesktopAuth` class for authentication via the 1Password desktop application. ### Environment Variables - **OP_SERVICE_ACCOUNT_TOKEN**: Used for authenticating with a service account token. ### Configuration Examples - Provides examples for setting up the client in different environments (e.g., Node.js, browser). ### Other Settings - **OS Detection**: Automatic detection of the operating system. - **Architecture Support**: Information on supported system architectures. - **Message Size Limits**: Details on any message size limitations. ``` -------------------------------- ### Get a Single Item Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-reference/items.md Retrieves a specific item from a vault by its ID. Ensure you have the correct vault and item IDs. This method returns the full item details with all fields decrypted. ```typescript const item = await client.items.get("vault-id", "item-id"); console.log(item.title); console.log(item.fields); console.log(item.notes); ``` -------------------------------- ### Get Account Policy for Item Sharing Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-reference/items-shares.md Retrieves the account's item sharing policy for a specific item. Use this to understand the sharing constraints before creating a share link. ```typescript const policy = await client.items.shares.getAccountPolicy(vaultId, itemId); console.log(`Max expiry: ${policy.maxExpiry}`); console.log(`Allowed types: ${policy.allowedTypes}`); console.log(`Max views: ${policy.maxViews}`); ``` -------------------------------- ### create() Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-reference/vaults.md Creates a new user-defined vault with specified parameters such as title, description, and admin access settings. ```APIDOC ## create() ### Description Creates a new user-defined vault. ### Method POST ### Endpoint /vaults ### Parameters #### Request Body - **params** (VaultCreateParams) - Yes - Vault creation parameters - **params.title** (string) - Yes - Vault name/title - **params.description** (string) - No - Vault description - **params.allowAdminsAccess** (boolean) - No - Whether admins have default access ### Response #### Success Response (200) - **Vault** - Created vault with full details ### Throws - Generic `Error` - If creation fails or title is invalid ### Example ```typescript const vault = await client.vaults.create({ title: "Team Vault", description: "Shared secrets for the team", allowAdminsAccess: true, }); console.log(`Created vault: ${vault.id} - ${vault.title}`); ``` ``` -------------------------------- ### createAll() Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-reference/items.md Creates multiple items in a single vault in batch. Returns a response indicating the success or failure of each item creation. ```APIDOC ## POST /items/batch ### Description Creates multiple items in a single vault in batch. Returns a response indicating the success or failure of each item creation. ### Method POST ### Endpoint /items/batch ### Parameters #### Query Parameters - **vaultId** (string) - Yes - ID of vault containing all items #### Request Body - **params** (ItemCreateParams[]) - Yes - Array of item creation parameters ### Response #### Success Response (200) - **ItemsUpdateAllResponse** - Response with individual results: - **individualResponses** (Response[]) - Array of individual responses, each containing either `content` (created item) or `error`. ### Example ```json { "vaultId": "vault-id", "params": [ { "title": "Item 1", "category": "Login", "vaultId": "vault-id", "fields": [] }, { "title": "Item 2", "category": "SecureNote", "vaultId": "vault-id", "notes": "Important notes" } ] } ``` ### Response Example ```json { "individualResponses": [ { "content": { "id": "item-id-1", "title": "Item 1", "category": "Login", "vaultId": "vault-id", "fields": [], "createdAt": "2023-01-01T12:00:00Z", "updatedAt": "2023-01-01T12:00:00Z" } }, { "error": { "code": "INVALID_ITEM", "message": "Item 2 is invalid." } } ] } ``` ``` -------------------------------- ### Main Entry Point Exports Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-index.md The main module exports all public APIs for direct use. This includes the client creation function, default integration constants, and re-exports of core types and functionalities. ```APIDOC ## Main Entry Point **`@1password/sdk`** (`client/src/sdk.ts`) The main module exports all public APIs: ```typescript // Default export export default client module // Named exports export const createClient(config: ClientConfiguration): Promise; export const DEFAULT_INTEGRATION_NAME: string; export const DEFAULT_INTEGRATION_VERSION: string; export { Secrets }; export { DesktopAuth }; export * from "./client.js"; export * from "./errors.js"; export * from "./types.js"; ``` ``` -------------------------------- ### Update an Item's Field Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-reference/items.md Updates a specific field within an existing item. The item object must include its current version number. This example shows how to modify a 'password' field. ```typescript const item = await client.items.get(vaultId, itemId); // Modify fields const updatedItem = { ...item, fields: item.fields.map((f) => { if (f.title === "password") { return { ...f, value: "new-password" }; } return f; }), }; const result = await client.items.put(updatedItem); console.log(`Updated item version: ${result.version}`); ``` -------------------------------- ### Get Group With Vault Access Details Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-reference/groups.md Retrieves a group's information along with its vault access details. This requires setting `vaultPermissions` to true. The `group.vaultAccess` array will be populated if access is granted. ```typescript const group = await client.groups.get(groupId, { vaultPermissions: true }); console.log(`Group: ${group.title}`); if (group.vaultAccess) { for (const access of group.vaultAccess) { console.log(`Vault: ${access.vaultUuid}`); console.log(`Permissions: ${access.permissions}`); } } ``` -------------------------------- ### Error Handling Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-index.md Demonstrates how to handle specific SDK errors using try-catch blocks. ```APIDOC ## Error Handling ### Description Demonstrates how to handle specific SDK errors using try-catch blocks. ### Example ```typescript try { // ... API call } catch (error) { if (error instanceof sdk.DesktopSessionExpiredError) { // Handle DesktopSessionExpiredError } else if (error instanceof sdk.RateLimitExceededError) { // Handle RateLimitExceededError } else { // Handle generic errors } } ``` ``` -------------------------------- ### Create 1Password SDK Client Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-reference/client.md Creates an authenticated 1Password SDK client. Requires configuration including authentication method, integration name, and version. ```typescript export const createClient = async ( config: ClientConfiguration, ): Promise ``` -------------------------------- ### Get Vault Information Without Accessors Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-reference/vaults.md Retrieve detailed vault information, excluding accessor details, by specifying `accessors: false`. This is useful when you only need the vault's core properties like title and description. ```typescript const vault = await client.vaults.get(vaultId, { accessors: false }); console.log(`Title: ${vault.title}`); console.log(`Description: ${vault.description}`); ``` -------------------------------- ### Import SDK Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-index.md Import the main SDK module to access its functionalities. ```typescript import sdk from "@1password/sdk"; ``` -------------------------------- ### Create Login Item Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-reference/items.md Creates a new Login item with username, password, and associated website. Includes tags for categorization. ```typescript const item = await client.items.create({ title: "My Website Login", category: sdk.ItemCategory.Login, vaultId: "vault-id", fields: [ { id: "username", title: "username", fieldType: sdk.ItemFieldType.Text, value: "john@example.com", }, { id: "password", title: "password", fieldType: sdk.ItemFieldType.Concealed, value: "my-secret-password", }, ], websites: [ { url: "https://example.com", label: "website", autofillBehavior: sdk.AutofillBehavior.AnywhereOnWebsite, }, ], tags: ["work", "important"], }); console.log(`Created item: ${item.id}`); ``` -------------------------------- ### Get Vault Overview by ID Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-reference/vaults.md Quickly retrieve a vault's overview using its ID. This is efficient for looking up metadata like title, creation date, and active item count without fetching full details. ```typescript const vaultOverview = await client.vaults.getOverview("vault-id"); console.log(`Vault: ${vaultOverview.title}`); console.log(`Created: ${vaultOverview.createdAt}`); console.log(`Items: ${vaultOverview.activeItemCount}`); ``` -------------------------------- ### Create Client and Resolve Secret with Service Account Source: https://github.com/1password/onepassword-sdk-js/blob/main/README.md Use the 1Password SDK to create an authenticated client using a service account token and resolve a secret using its reference URI. ```javascript const sdk = require("@1password/sdk"); async function main() { // Creates an authenticated client. const client = await sdk.createClient({ auth: process.env.OP_SERVICE_ACCOUNT_TOKEN, // Set the following to your own integration name and version. integrationName: "My 1Password Integration", integrationVersion: "v1.0.0", }); // Fetches a secret. const secret = await client.secrets.resolve("op://vault/item/field"); } main() ``` -------------------------------- ### create() Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-reference/items.md Creates a new item in a vault. Supports various item categories like Login, SecureNote, CreditCard, and Document, with options for fields, sections, notes, tags, websites, and file attachments. ```APIDOC ## POST /items ### Description Creates a new item in a vault. Supports various item categories like Login, SecureNote, CreditCard, and Document, with options for fields, sections, notes, tags, websites, and file attachments. ### Method POST ### Endpoint /items ### Parameters #### Request Body - **params** (ItemCreateParams) - Yes - Item creation parameters - **params.category** (ItemCategory) - Yes - Item type (Login, SecureNote, CreditCard, Document, etc.) - **params.vaultId** (string) - Yes - ID of the vault where item will be created - **params.title** (string) - Yes - Item title - **params.fields** (ItemField[]) - No - Array of item fields - **params.sections** (ItemSection[]) - No - Array of sections to group fields - **params.notes** (string) - No - Item notes/description - **params.tags** (string[]) - No - Tags for categorization - **params.websites** (Website[]) - No - Associated websites (for Login/Password items) - **params.files** (FileCreateParams[]) - No - File fields to attach - **params.document** (DocumentCreateParams) - No - Document file (for Document items only) ### Response #### Success Response (200) - **Item** - Created item with all fields populated including ID ### Throws - Generic `Error` - On validation errors or permission issues ### Request Example ```json { "title": "My Website Login", "category": "Login", "vaultId": "vault-id", "fields": [ { "id": "username", "title": "username", "fieldType": "Text", "value": "john@example.com" }, { "id": "password", "title": "password", "fieldType": "Concealed", "value": "my-secret-password" } ], "websites": [ { "url": "https://example.com", "label": "website", "autofillBehavior": "AnywhereOnWebsite" } ], "tags": ["work", "important"] } ``` ### Response Example ```json { "id": "item-id", "title": "My Website Login", "category": "Login", "vaultId": "vault-id", "fields": [ { "id": "username", "title": "username", "fieldType": "Text", "value": "john@example.com" }, { "id": "password", "title": "password", "fieldType": "Concealed", "value": "my-secret-password" } ], "websites": [ { "url": "https://example.com", "label": "website", "autofillBehavior": "AnywhereOnWebsite" } ], "tags": ["work", "important"], "createdAt": "2023-01-01T12:00:00Z", "updatedAt": "2023-01-01T12:00:00Z" } ``` ``` -------------------------------- ### Service Account Token Authentication Usage Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/configuration.md Demonstrates using the OP_SERVICE_ACCOUNT_TOKEN environment variable to authenticate the SDK client. ```typescript const client = await sdk.createClient({ auth: process.env.OP_SERVICE_ACCOUNT_TOKEN, integrationName: "My App", integrationVersion: "v1.0.0", }); ``` -------------------------------- ### Batch Item Creation Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/REFERENCE.md Demonstrates how to create multiple items in a vault concurrently and iterate through the responses to check for errors or confirm creation. ```typescript // Batch create const responses = await client.items.createAll(vaultId, items); for (const response of responses.individualResponses) { if (response.error) { console.error(`Failed: ${response.error}`); } else { console.log(`Created: ${response.content.id}`); } } ``` -------------------------------- ### DesktopAuth Source: https://github.com/1password/onepassword-sdk-js/blob/main/_autodocs/api-reference/client.md Specifies desktop application authentication for the SDK client. ```APIDOC ## DesktopAuth ### Description Specifies desktop application authentication for the SDK client. ### Constructor `public constructor(accountName: string)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Parameters - **accountName** (string) - Required - Your 1Password account name as shown in the desktop app sidebar, or your account UUID ### Example ```typescript import sdk from "@1password/sdk"; const auth = new sdk.DesktopAuth("My Personal Account"); const client = await sdk.createClient({ auth: auth, integrationName: "My Tool", integrationVersion: "v2.1.0", }); ``` ```