onepassword

package module
v0.0.0-...-aa09434 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 19, 2026 License: MIT Imports: 15 Imported by: 0

README

onepassword-cli-go

onepassword-cli-go is a Go library for interacting with the 1Password CLI. It provides a set of utilities to manage accounts, items, vaults, groups, and permissions programmatically, enabling seamless integration with 1Password in your Go applications.

Features

  • Account Management:

    • Retrieve account details by UUID, email, or URL.
    • Check session validity and expiration.
    • Sign in to accounts with passwordless or password-based authentication.
    • Sign in with service account accesstoken
  • Item Management:

    • Define and manage 1Password items, including fields, sections, and URLs.
    • Support for various item categories (e.g., Login, Password, Secure Note, Identity).
    • Add and delete sections within items, ensuring unique section IDs.
    • Add and delete fields within specific sections, maintaining consistent state.
    • Add and remove URLs associated with items.
    • Save and delete items programmatically.
    • Add tags to items for better organization.
  • Vault Management:

    • Represent and interact with 1Password vaults.
    • Retrieve vault details by ID or name.
    • Validate vault IDs and update vault icons.
    • Create, delete, and update vaults.
  • Group Management:

    • List, create, and delete groups.
    • Add and remove members or managers from groups.
    • Update group names and descriptions.
  • Permission Management:

    • Define and resolve granular permissions for items and vaults.
    • Manage dependencies between permissions.
  • CLI Integration:

    • Execute 1Password CLI commands with support for interactive and non-interactive modes.
    • Verify the integrity of the 1Password CLI executable.
    • Centralized command execution with automatic account flag inclusion.

Installation

To use this library, add it to your Go project:

go get github.com/sthayduk/onepassword-cli-go

Ensure you have the 1Password CLI (op) installed and available in your system's PATH.

Usage

Initialize the CLI
package main

import (
    "log"
    "github.com/sthayduk/onepassword-cli-go"
)

func main() {
    cli := onepassword.NewOpCLI()
    
    if err := onepassword.TestOpCli(cli.Path); err != nil {
        log.Fatalf("1Password CLI is not functional: %v", err)
    }
    
    if err := onepassword.VerifyOpExecutable(cli.Path); err != nil {
        log.Fatalf("CLI verification failed: %v", err)
    }

    log.Println("1Password CLI is ready to use.")
}
Account Management

Retrieve account details:

accounts, err := cli.GetAccountDetails()
if err != nil {
    log.Fatalf("Failed to retrieve accounts: %v", err)
}

for _, account := range accounts {
    log.Printf("Account: %s (%s)", account.Email, account.URL)
}

Sign in to an account:

ctx := context.Background()
account, err := cli.GetAccountDetailsByEmail("your-email@example.com")
if err != nil {
    log.Fatalf("Failed to get account details: %v", err)
}

if err := cli.SignIn(ctx, account); err != nil {
    log.Fatalf("Failed to sign in: %v", err)
}

log.Println("Signed in successfully!")
Item Management

Define and create an item:

item := onepassword.Item{
    Title:    "Example Login",
    Category: onepassword.CategoryLogin,
    Vault: onepassword.Vault{
        ID:   "vault-id", // Replace with a valid vault ID
        Name: "Personal",
    },
    Fields: []onepassword.Field{
        {
            Label:   "Username",
            Value:   "example_user",
            Type:    onepassword.FieldTypeString,
            Purpose: onepassword.FieldPurposeUsername,
        },
        {
            Label:   "Password",
            Value:   "example_password",
            Type:    onepassword.FieldTypeConcealed,
            Purpose: onepassword.FieldPurposePassword,
        },
    },
}

createdItem, err := cli.CreateItem(&item, false) // Set to true to generate a password
if err != nil {
    log.Fatalf("Failed to create item: %v", err)
}

log.Printf("Created item: %s (ID: %s)", createdItem.Title, createdItem.ID)
Add a Section to an Item
section := onepassword.Section{
    ID:    "section-id",
    Label: "Example Section",
}

err := item.AddSection(section)
if err != nil {
    log.Fatalf("Failed to add section: %v", err)
}

log.Println("Section added successfully!")
Delete a Section from an Item
err := item.DeleteSection(section)
if err != nil {
    log.Fatalf("Failed to delete section: %v", err)
}

log.Println("Section deleted successfully!")
Add and Remove URLs

Add a URL to an item:

newURL := onepassword.ItemURL{
    Href:    "https://example.com",
    Label:   "Example URL",
    Primary: true,
}
item.AddURL(newURL)

if err := item.Save(); err != nil {
    log.Fatalf("Failed to save item: %v", err)
}

log.Println("Added new URL to item.")

Remove a URL from an item:

err := item.DeleteURLs("https://example.com")
if err != nil {
    log.Fatalf("Failed to remove URL: %v", err)
}

if err := item.Save(); err != nil {
    log.Fatalf("Failed to save item after URL removal: %v", err)
}

log.Println("Removed URL from item.")
Persist item changes in 1Password
// Note: Ensure you call the .Save() method to persist the item to 1Password.
// Without calling .Save(), the item will only be updated locally and not written to 1Password.
if err := createdItem.Save(); err != nil {
    log.Fatalf("Failed to save item: %v", err)
}
Vault Management

Retrieve vault details:

vaults, err := cli.GetVaultDetails()
if err != nil {
    log.Fatalf("Failed to retrieve vaults: %v", err)
}

for _, vault := range *vaults {
    log.Printf("Vault: %s (%s)", vault.Name, vault.ID)
}

Retrieve a specific vault by ID:

vaultID := "your-vault-id"
vault, err := cli.GetVaultDetailsByID(vaultID)
if err != nil {
    log.Fatalf("Failed to retrieve vault details: %v", err)
}

log.Printf("Vault Name: %s, Items: %d", vault.Name, vault.Items)
Group Management

List all groups:

groups, err := cli.GetGroups()
if err != nil {
    log.Fatalf("Failed to list groups: %v", err)
}

for _, group := range groups {
    log.Printf("Group: %s (%s)", group.Name, group.ID)
}

Create a new group:

group, err := cli.CreateGroup("Example Group", "This is an example group.")
if err != nil {
    log.Fatalf("Failed to create group: %v", err)
}

log.Printf("Created group: %s (%s)", group.Name, group.ID)

Development

Project Structure
  • accounts.go: Handles account-related operations, including sign-in and session management.
  • client.go: Provides the core CLI integration and command execution logic.
  • items.go: Defines structures and utilities for managing 1Password items.
  • vaults.go: Contains functions for vault-related operations.
  • groups.go: Manages groups and their members.
  • permissions.go: Handles permission definitions and dependencies.
  • examples/: Contains example programs demonstrating library usage.
  • go.mod: Specifies module dependencies.
Dependencies
  • golang.org/x/term: Used for secure password input.
  • golang.org/x/sys: Provides system-level utilities (indirect dependency).
Testing

To test the library, ensure the op CLI is installed and functional. Use the provided methods to interact with your 1Password environment.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Contributing

Contributions are welcome! Please open an issue or submit a pull request for any improvements or bug fixes.

Acknowledgments

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrMultipleAccounts = errors.New("multiple accounts found")

ErrMultipleAccounts is an error that indicates multiple accounts were found when only one was expected. This error can be used to signal ambiguity in account selection or retrieval operations.

Functions

func FindOpExecutable

func FindOpExecutable() (string, error)

FindOpExecutable searches for the "op" executable in the system's PATH. It iterates through each directory in the PATH environment variable and checks if the "op" executable exists and is not a directory. On Windows, it appends ".exe" to the executable name.

Returns: - The full path to the "op" executable if found. - An error if the executable is not found in any of the directories in PATH.

func FormatCategories

func FormatCategories(categories []Category) string

FormatCategories takes a slice of Category and returns a formatted string representation. If the slice contains only one category, it returns the string representation of that category. If the slice contains multiple categories, it concatenates their string representations with a comma (",") as the separator.

Parameters:

  • categories: A slice of Category values to format.

Returns:

A string representation of the categories, either as a single value or a comma-separated list.

func ResolvePermissions

func ResolvePermissions(permission Permission) string

ResolvePermissions generates a string of permissions for a given permission key in the PermissionDependenciesMap.

func TestOpCli

func TestOpCli(opPath string) error

TestOpCli verifies the availability of the 1Password CLI by executing the "--version" command using the provided path to the CLI executable. It returns an error if the command fails to execute or the CLI is not found.

Parameters:

  • opPath: The file path to the 1Password CLI executable.

Returns:

  • error: An error if the CLI is unavailable or the command execution fails, otherwise nil.

func ValidateVault

func ValidateVault(vault Vault) error

ValidateVault validates all fields of a Vault struct.

This method performs comprehensive validation of a Vault struct, including checks for ID format, name, content version, timestamps, item count, description length, and type.

Parameters: - vault: The Vault struct to validate.

Returns: - error: An error object if any validation fails, otherwise nil.

func ValidateVaultID

func ValidateVaultID(id string) error

ValidateVaultID validates the format of a vault ID.

This method checks if the provided vault ID is a 26-character alphanumeric string.

Parameters: - id: The vault ID to validate.

Returns: - error: An error object if the ID format is invalid, otherwise nil.

func VerifyOpExecutable

func VerifyOpExecutable(path string) error

VerifyOpExecutable verifies the authenticity of the 1Password CLI executable at the given path.

On all platforms, it first runs "op --version" and validates that the output matches a valid 1Password CLI semver pattern (e.g., "2.30.0").

Additional OS-specific checks:

  • On macOS, it uses the codesign command to verify the binary is signed by "Developer ID Application: AgileBits Inc."
  • On Windows, it uses PowerShell's Get-AuthenticodeSignature to verify the Authenticode signature and confirm the signer is AgileBits.
  • On Linux, no binary-level signature verification is available. The function relies on version output validation only and logs a warning.

Parameters:

  • path: The file path to the executable to be verified.

Returns:

  • An error if verification fails. Returns nil if verification succeeds.

Types

type Account

type Account struct {
	URL         string `json:"url"`
	Email       string `json:"email"`
	UserUUID    string `json:"user_uuid"`
	AccountUUID string `json:"account_uuid"`
	// contains filtered or unexported fields
}

Account represents a 1Password account with associated details. It includes the account's URL, the email address of the user, the unique identifier for the user (UserUUID), and the unique identifier for the account (AccountUUID).

func (*Account) IsSessionExpired

func (a *Account) IsSessionExpired() bool

IsSessionExpired checks if the session associated with the account has expired. It compares the time elapsed since the account's sign-in time with the session's expiration duration. Returns true if the session has expired, otherwise false.

func (*Account) IsSessionValid

func (a *Account) IsSessionValid() bool

IsSessionValid checks if the session associated with the account is valid. It returns true if the session is not expired, otherwise false.

func (*Account) SetSignInInfo

func (a *Account) SetSignInInfo(token string)

SetSignInInfo updates the account's sign-in information by setting the sign-in time, session token, and session expiration duration.

Parameters:

  • token: The session token to be associated with the account.

Notes:

  • Session tokens expire after 30 minutes of inactivity. This method sets the expiration duration to 29 minutes to provide a buffer.

type Category

type Category string

Category represents the type of item in 1Password

const (
	CategoryAPICredential   Category = "API Credential"
	CategoryBankAccount     Category = "Bank Account"
	CategoryCreditCard      Category = "Credit Card"
	CategoryDatabase        Category = "Database"
	CategoryDocument        Category = "Document"
	CategoryDriverLicense   Category = "Driver License"
	CategoryEmailAccount    Category = "Email Account"
	CategoryIdentity        Category = "Identity"
	CategoryLogin           Category = "Login"
	CategoryMembership      Category = "Membership"
	CategoryOutdoorLicense  Category = "Outdoor License"
	CategoryPassport        Category = "Passport"
	CategoryPassword        Category = "Password"
	CategoryRewardProgram   Category = "Reward Program"
	CategorySecureNote      Category = "Secure Note"
	CategoryServer          Category = "Server"
	CategorySocialSecurity  Category = "Social Security Number"
	CategorySoftwareLicense Category = "Software License"
	CategorySSHKey          Category = "SSH Key"
	CategoryWirelessRouter  Category = "Wireless Router"
)

type Field

type Field struct {
	ID              string           `json:"id,omitempty"`
	Label           string           `json:"label"`
	Value           string           `json:"value,omitempty"`
	Reference       string           `json:"reference,omitempty"`
	Type            FieldType        `json:"type"`
	Purpose         FieldPurpose     `json:"purpose,omitempty"`
	Section         *Section         `json:"section,omitempty"`
	PasswordDetails *PasswordDetails `json:"password_details,omitempty"`
	Entropy         float64          `json:"entropy,omitempty"`
}

Field represents a field in a 1Password item with its type, purpose, and value

type FieldPurpose

type FieldPurpose string

FieldPurpose represents the purpose of a field

const (
	FieldPurposeUsername  FieldPurpose = "username"  // A username.
	FieldPurposeNotes     FieldPurpose = "notes"     // A notes field.
	FieldPurposePassword  FieldPurpose = "password"  // A concealed password.
	FieldPurposeText      FieldPurpose = "text"      // A text string.
	FieldPurposeEmail     FieldPurpose = "email"     // An email address.
	FieldPurposeURL       FieldPurpose = "url"       // A web address to copy or open in your default web browser, not used for autofill behavior. Use the --url flag to set the website where 1Password suggests and fills a Login, Password, or API Credential item.
	FieldPurposeDate      FieldPurpose = "date"      // A date with the format YYYY-MM-DD.
	FieldPurposeMonthYear FieldPurpose = "monthyear" // A date with the format YYYYMM or YYYY/MM.
	FieldPurposePhone     FieldPurpose = "phone"     // A phone number.
	FieldPurposeOTP       FieldPurpose = "otp"       // A one-time password. Accepts an otpauth:// URI as the value.
	FieldPurposeFile      FieldPurpose = "file"      // A file attachment. Accepts the path to the file as the value. Can only be added with assignment statements.
)

type FieldType

type FieldType string

FieldType represents the type of a field

const (
	FieldTypeString    FieldType = "STRING"     // A text string.
	FieldTypeConcealed FieldType = "CONCEALED"  // A concealed password.
	FieldTypeEmail     FieldType = "EMAIL"      // An email address.
	FieldTypeURL       FieldType = "URL"        // A web address to copy or open in your default web browser, not used for autofill behavior. Use the --url flag to set the website where 1Password suggests and fills a Login, Password, or API Credential item.
	FieldTypeDate      FieldType = "DATE"       // A date with the format YYYY-MM-DD.
	FieldTypeMonthYear FieldType = "MONTH_YEAR" // A date with the format YYYYMM or YYYY/MM.
	FieldTypePhone     FieldType = "PHONE"      // A phone number.
	FieldTypeOTP       FieldType = "OTP"        // A one-time password. Accepts an otpauth:// URI as the value.
	FieldTypeFile      FieldType = "N/A"        // A file attachment. Accepts the path to the file as the value. Can only be added with assignment statements.
)

type Group

type Group struct {
	ID          string       `json:"id"`
	Name        string       `json:"name"`
	Description string       `json:"description,omitempty"`
	State       string       `json:"state"`
	CreatedAt   time.Time    `json:"created_at"`
	UpdatedAt   time.Time    `json:"updated_at"`
	Permissions []Permission `json:"permissions,omitempty"`
	Type        string       `json:"type"`
	// contains filtered or unexported fields
}

func (*Group) AddManager

func (group *Group) AddManager(user User) error

AddManager adds a user to the group with the role of "manager". It executes the "group user grant" command with the user's ID and the group's ID.

Parameters:

  • user (User): The user to add as a manager to the group.

Returns:

  • (error): An error if the operation fails.

func (*Group) AddMember

func (group *Group) AddMember(user User) error

AddMember adds a user to the group with the default role of "member". It executes the "group user grant" command with the user's ID and the group's ID.

Parameters:

  • user (User): The user to add to the group.

Returns:

  • (error): An error if the operation fails.

func (*Group) Delete

func (group *Group) Delete() error

Delete removes the group from the 1Password CLI. It executes the "group delete" command using the group's ID.

Returns:

  • (error): An error if the operation fails.

func (*Group) ListMembers

func (group *Group) ListMembers() ([]User, error)

ListMembers retrieves a list of all users who are members of the group. It executes the "group user list" command and parses the output into a slice of User objects.

Returns:

  • ([]User): A slice of User objects.
  • (error): An error if the operation fails.

func (*Group) RemoveManager

func (group *Group) RemoveManager(user User) error

RemoveManager removes a user from the group who has the role of "manager". It executes the "group user revoke" command with the user's ID and the group's ID.

Parameters:

  • user (User): The user to remove as a manager from the group.

Returns:

  • (error): An error if the operation fails.

func (*Group) RemoveMember

func (group *Group) RemoveMember(user User) error

RemoveMember removes a user from the group. It executes the "group user revoke" command with the user's ID and the group's ID.

Parameters:

  • user (User): The user to remove from the group.

Returns:

  • (error): An error if the operation fails.

func (*Group) SetDescription

func (group *Group) SetDescription(description string) error

SetDescription updates the description of the group. It executes the "group edit" command with the new description.

Parameters:

  • description (string): The new description for the group.

Returns:

  • (error): An error if the operation fails.

func (*Group) SetName

func (group *Group) SetName(name string) error

SetName updates the name of the group. It executes the "group edit" command with the new name.

Parameters:

  • name (string): The new name for the group.

Returns:

  • (error): An error if the operation fails.

type Item

type Item struct {
	ID             string    `json:"id"`
	Title          string    `json:"title"`
	LastEditedBy   string    `json:"last_edited_by"`
	AdditionalInfo string    `json:"additional_information"`
	Vault          Vault     `json:"vault"`
	Category       Category  `json:"category"`
	Favorite       bool      `json:"favorite"`
	Version        int       `json:"version"`
	CreatedAt      time.Time `json:"created_at"`
	UpdatedAt      time.Time `json:"updated_at"`
	Tags           []string  `json:"tags,omitempty"`
	URLs           []ItemURL `json:"urls,omitempty"`
	Sections       []Section `json:"sections,omitempty"`
	Fields         []Field   `json:"fields,omitempty"`
	// contains filtered or unexported fields
}

Item represents a 1Password item

func (*Item) AddField

func (item *Item) AddField(field Field)

AddField appends a new field to the item's Fields slice.

Parameters: - field: The Field struct to be added to the item.

func (*Item) AddFieldToSection

func (item *Item) AddFieldToSection(section Section, field Field) error

AddFieldToSection adds a new field to a specific section in the item.

Parameters: - section: The Section struct where the field will be added. - field: The Field struct to be added to the section.

Returns: - error: An error object if the section is not found in the item.

This method associates the field with the specified section and appends it to the item's Fields slice.

func (*Item) AddNotes

func (item *Item) AddNotes(notes string)

AddNotes adds or updates a notes field in the item.

Parameters: - notes: A string representing the notes to add or update.

This method checks if a notes field already exists in the item. If it does, it updates the value of the existing field. Otherwise, it creates a new notes field and appends it to the item's Fields slice.

func (*Item) AddPassword

func (item *Item) AddPassword(password string)

AddPassword adds or updates a password field in the item.

Parameters: - password: A string representing the password to add or update.

This method checks if a password field already exists in the item. If it does, it updates the value of the existing field. Otherwise, it creates a new password field and appends it to the item's Fields slice.

func (*Item) AddSection

func (item *Item) AddSection(section Section) error

AddSection adds a new section to the item.

Parameters: - section: The Section struct to be added to the item.

Returns: - error: An error object if the section ID is not unique.

This method appends the provided section to the item's Sections slice.

func (*Item) AddTag

func (item *Item) AddTag(tag string)

AddTag appends a new tag to the item's Tags slice.

Parameters: - tag: A string representing the tag to add.

func (*Item) AddURL

func (item *Item) AddURL(url ItemURL)

AddURL adds a new ItemURL to the item.

Parameters: - url: The ItemURL struct to be added to the item.

This method appends the provided URL to the item's URLs slice. If the URL is marked as primary, it ensures no other URL is marked as primary.

func (*Item) AddUserName

func (item *Item) AddUserName(username string)

AddUserName adds or updates a username field in the item.

Parameters: - username: A string representing the username to add or update.

This method checks if a username field already exists in the item. If it does, it updates the value of the existing field. Otherwise, it creates a new username field and appends it to the item's Fields slice.

func (*Item) Delete

func (item *Item) Delete() error

Delete deletes the item from the 1Password CLI.

Returns: - error: An error object if the operation fails.

This method uses the DeleteItem method of the OpCLI instance to delete the item. It ensures that the cli field and item ID are properly set before attempting to delete.

func (*Item) DeleteField

func (item *Item) DeleteField(field Field) error

DeleteField removes a field from the item by its ID.

Parameters: - field: The Field struct to be removed from the item.

Returns: - error: An error object if the field with the specified ID is not found.

func (*Item) DeleteFieldFromSection

func (item *Item) DeleteFieldFromSection(section Section, field Field) error

DeleteFieldFromSection removes a field from a specific section in the item.

Parameters: - section: The Section struct from which the field will be removed. - field: The Field struct to be removed from the section.

Returns: - error: An error object if the field is not found in the section.

This method ensures that the field is properly disassociated from the section and removed from the item's Fields slice.

func (*Item) DeleteSection

func (item *Item) DeleteSection(section Section) error

DeleteSection removes a section from the item by its ID.

Parameters: - section: The Section struct to be removed from the item.

This method ensures that all fields associated with the section are removed before deleting the section itself to maintain a consistent state.

func (*Item) DeleteTag

func (item *Item) DeleteTag(tag string) error

DeleteTag removes a tag from the item by its name.

Parameters: - tag: A string representing the name of the tag to remove.

Returns: - error: An error object if the tag with the specified name is not found.

func (*Item) DeleteURLs

func (item *Item) DeleteURLs(href string) error

DeleteURLs removes all ItemURLs from the item that match the given Href.

Parameters: - href: A string representing the Href of the URLs to remove.

Returns: - error: An error object if no URLs with the given Href are found or if the last URL cannot be deleted.

Note: The 1Password CLI has a known issue where the last URL cannot be deleted. This method will return an error if attempting to delete the last remaining URL.

func (*Item) GetFieldByID

func (item *Item) GetFieldByID(fieldID string) (*Field, error)

GetFieldByID retrieves a field by its ID.

Parameters: - fieldID: A string representing the unique identifier of the field.

Returns: - *Field: A pointer to the Field struct if found. - error: An error object if the field is not found.

func (*Item) GetFieldsByLabel

func (item *Item) GetFieldsByLabel(fieldLabel string) ([]*Field, error)

GetFieldsByLabel retrieves fields by their label.

Parameters: - fieldLabel: A string representing the label of the fields to retrieve.

Returns: - []*Field: A slice of pointers to Field structs matching the label. - error: An error object if no fields with the given label are found.

func (*Item) GetFieldsByPurpose

func (item *Item) GetFieldsByPurpose(fieldPurpose FieldPurpose) ([]*Field, error)

GetFieldsByPurpose retrieves fields by their purpose.

Parameters: - fieldPurpose: A FieldPurpose value representing the purpose of the fields to retrieve.

Returns: - []*Field: A slice of pointers to Field structs matching the purpose. - error: An error object if no fields with the given purpose are found.

func (*Item) MoveFieldToSection

func (item *Item) MoveFieldToSection(field Field, section Section) error

MoveFieldToSection moves a field to a specific section in the item.

Parameters: - field: The Field struct to be moved. - section: The Section struct where the field will be moved.

Returns: - error: An error object if the section is not found in the item.

This method associates the field with the specified section and updates its Section reference. If the section is not found, it returns an error.

func (*Item) NewField

func (item *Item) NewField(label, value string, fieldType FieldType) Field

NewField creates a new Field instance with the specified label, value, and type.

Parameters: - label: A string representing the label of the field. - value: A string representing the value of the field. - fieldType: A FieldType value representing the type of the field.

Returns: - Field: A new Field struct initialized with the provided parameters.

func (*Item) RenameSection

func (item *Item) RenameSection(section Section, newLabel string) error

RenameSection updates the label of a specified section within an item. It searches for a section in the item's Sections slice that matches the provided section's ID and Label. If a match is found, the section's label is updated to the newLabel, and the function returns nil. If no matching section is found, an error is returned.

Parameters:

section - The Section object to be renamed, identified by its ID and Label.
newLabel - The new label to assign to the section.

Returns:

error - Returns nil if the section is successfully renamed, or an error
        if the section is not found in the item.

func (*Item) Save

func (item *Item) Save() error

Save saves the current state of the item to the 1Password CLI.

Returns: - error: An error object if the operation fails.

This method uses the UpdateItemWithStruct method of the OpCLI instance to save the item. It ensures that the cli field and item ID are properly set before attempting to save.

func (*Item) SetAsFavorite

func (item *Item) SetAsFavorite(favorite bool)

SetFavorite sets the favorite status of the item. It updates the Favorite field of the Item struct to the specified boolean value.

Parameters:

  • favorite: A boolean value indicating whether the item should be marked as a favorite.

func (*Item) ToJSON

func (item *Item) ToJSON() ([]byte, error)

ToJSON converts the Item struct into a JSON-encoded byte slice. It returns the JSON representation of the item or an error if the marshaling process fails.

func (*Item) UpdateField

func (item *Item) UpdateField(field Field) error

UpdateField updates an existing field in the Item's Fields slice with the provided field. It searches for a field with a matching ID and replaces it with the new field. If no fields are present in the Item, or if a field with the specified ID is not found, an error is returned.

Parameters:

  • field: The Field object containing the updated data.

Returns:

  • error: An error if no fields are present or if the specified field ID is not found.

type ItemTemplate

type ItemTemplate struct {
	UUID string `json:"uuid"`
	Name string `json:"name"`
}

ItemTemplate represents a 1Password item template

type ItemURL

type ItemURL struct {
	Href    string `json:"href"`
	Label   string `json:"label"`
	Primary bool   `json:"primary"`
}

ItemURL represents a URL associated with an item

type OpCLI

type OpCLI struct {
	Path string

	Account *Account
	// contains filtered or unexported fields
}

OpCLI represents the 1Password CLI executor

func NewOpCLI

func NewOpCLI() *OpCLI

NewOpCLI initializes a new instance of the OpCLI struct. It locates the 1Password CLI executable and sets up an empty item cache.

Returns: - A pointer to an OpCLI instance.

func (*OpCLI) CreateGroup

func (cli *OpCLI) CreateGroup(name string, description string) (*Group, error)

CreateGroup creates a new group with the specified name and description. It executes the "group create" command and parses the output into a Group object.

Parameters:

  • name (string): The name of the group to create.
  • description (string): The description of the group.

Returns:

  • (*Group): A pointer to the newly created Group object.
  • (error): An error if the operation fails.

func (*OpCLI) CreateItem

func (cli *OpCLI) CreateItem(item *Item, genPassword bool) (*Item, error)

CreateItem creates a new item in the 1Password vault using the "op item create" command. It accepts an Item object and a boolean flag indicating whether to generate a password.

Parameters:

  • item: A pointer to the Item struct representing the item to be created. The ID field of the item must be empty for new items.
  • genPassword: A boolean flag indicating whether to generate a password for the item.

Returns:

  • A pointer to the created Item struct populated with the details of the newly created item.
  • An error if the operation fails, such as when the item ID is not empty, account information is missing, JSON serialization fails, the "op item create" command fails, or the output cannot be unmarshaled.

Notes:

  • The function requires the OpCLI instance to have valid account information (Account.UserUUID).
  • The "op" CLI tool must be installed and accessible via the path specified in the OpCLI.Path field.

func (*OpCLI) CreateVault

func (cli *OpCLI) CreateVault(name, description string, icon VaultIcon, adminAccess bool) (*Vault, error)

CreateVault creates a new vault in 1Password.

This method executes the "vault create" command using the 1Password CLI to create a new vault with the specified parameters.

Parameters: - name: The name of the new vault. - description: A brief description of the vault's purpose or contents. - icon: The icon to associate with the vault. Must be a valid VaultIcon. - adminAccess: A boolean indicating whether admins are allowed to manage the vault.

Returns: - *Vault: A pointer to a Vault struct containing the details of the newly created vault. - error: An error object if the operation fails.

func (*OpCLI) Execute

func (cli *OpCLI) Execute(args ...string) ([]byte, error)

Execute runs a 1Password CLI command with the specified arguments. It handles both interactive and non-interactive commands, as well as special handling for the "signin" command.

For non-interactive commands, the output is captured and returned as a byte slice. If an error occurs during execution, an OpCliError is returned containing the error and any stderr output.

For the "signin" command, the function reads the user's password securely and pipes it into the command.

For other interactive commands, the function connects the command's standard input, output, and error streams to the current process.

Args:

args: A variadic list of strings representing the command arguments.

Returns:

[]byte: The output of the command for non-interactive commands.
error: An error if the command fails or if there is an issue with execution.

func (*OpCLI) ExecuteOpCommand

func (cli *OpCLI) ExecuteOpCommand(args ...string) ([]byte, error)

ExecuteOpCommand executes a 1Password CLI command with the provided arguments. It ensures that account information is available and appends default arguments (such as the account ID) to the command before execution.

Parameters:

args - A variadic list of strings representing the command-line arguments
       to pass to the 1Password CLI.

Returns:

[]byte - The output of the executed command.
error  - An error if the command execution fails or if account information
         is missing.

Errors:

  • Returns an error if the account information is missing (Account or UserUUID is empty).
  • Returns an error if the command execution fails, wrapping the underlying error.

Example:

output, err := cli.ExecuteOpCommand("list", "items")
if err != nil {
    log.Fatalf("Command failed: %v", err)
}
fmt.Println(string(output))

func (*OpCLI) GetAccountDetails

func (cli *OpCLI) GetAccountDetails() ([]Account, error)

GetAccountDetails retrieves the details of all 1Password accounts configured in the CLI. It executes the "op account list" command, parses the result, and returns a slice of Account objects.

Returns:

  • ([]Account): A slice of Account objects representing the 1Password accounts.
  • (error): An error if the command execution or JSON parsing fails, or if no accounts are found.

Errors:

  • Returns an error if the "op account list" command fails to execute.
  • Returns an error if the JSON output cannot be parsed into Account objects.
  • Returns an error if no accounts are found.

func (*OpCLI) GetAccountDetailsByAccountUUID

func (cli *OpCLI) GetAccountDetailsByAccountUUID(accountUUID string) (*Account, error)

GetAccountDetailsByAccountUUID retrieves the details of a 1Password account by its unique account UUID.

This method fetches all available account details using the GetAccountDetails method and searches for the account that matches the provided UUID. If a match is found, it returns the account details. If no match is found, an error is returned.

Parameters:

  • accountUUID: A string representing the unique identifier of the account.

Returns:

  • *Account: A pointer to the Account struct containing the account details, if found.
  • error: An error if the account with the specified UUID is not found or if there is an issue retrieving the account details.

func (*OpCLI) GetAccountDetailsByEmail

func (cli *OpCLI) GetAccountDetailsByEmail(email string) (*Account, error)

GetAccountDetailsByEmail retrieves the details of a 1Password account associated with the specified email address.

This method fetches all available account details using the GetAccountDetails method and searches for an account that matches the provided email.

Parameters:

  • email: The email address of the account to retrieve.

Returns:

  • A pointer to the Account struct if an account with the specified email is found.
  • An error if no account with the specified email is found or if there is an issue retrieving account details.

func (*OpCLI) GetAccountDetailsByURL

func (cli *OpCLI) GetAccountDetailsByURL(url string) (*Account, error)

GetAccountDetailsByURL retrieves the details of a 1Password account that matches the specified URL. It searches through all available accounts and returns the account details if a match is found.

Parameters:

  • url: The URL of the 1Password account to retrieve.

Returns:

  • *Account: A pointer to the matching Account object if found.
  • error: An error if no account is found, multiple accounts match the URL, or if there is an issue retrieving account details.

Errors:

  • Returns an error if no account matches the specified URL.
  • Returns an error if multiple accounts match the specified URL.
  • Returns an error if there is an issue retrieving the account details.

func (*OpCLI) GetAccountDetailsByUUID

func (cli *OpCLI) GetAccountDetailsByUUID(accountUUID string) (*Account, error)

GetAccountDetailsByUUID retrieves the details of a 1Password account by its UUID. It searches through the list of accounts obtained from the GetAccountDetails method. If an account with the specified UUID is found, it returns the account details. Otherwise, it returns an error indicating that the account was not found.

Parameters:

  • accountUUID: The UUID of the account to retrieve.

Returns:

  • *Account: A pointer to the Account struct containing the account details.
  • error: An error if the account is not found or if there is an issue retrieving the account details.

func (*OpCLI) GetGroupByID

func (cli *OpCLI) GetGroupByID(id string) (*Group, error)

GetGroupByID retrieves a group by its ID. It internally calls getGroup with the group ID.

Parameters:

  • id (string): The ID of the group to retrieve.

Returns:

  • (*Group): A pointer to the Group object.
  • (error): An error if the operation fails.

func (*OpCLI) GetGroupByName

func (cli *OpCLI) GetGroupByName(name string) (*Group, error)

GetGroupByName retrieves a group by its name. It internally calls getGroup with the group name.

Parameters:

  • name (string): The name of the group to retrieve.

Returns:

  • (*Group): A pointer to the Group object.
  • (error): An error if the operation fails.

func (*OpCLI) GetGroups

func (cli *OpCLI) GetGroups() ([]Group, error)

ListGroups retrieves a list of all groups available in the 1Password CLI. It executes the "group list" command and parses the output into a slice of Group objects.

Returns:

  • ([]Group): A slice of Group objects.
  • (error): An error if the operation fails.

func (*OpCLI) GetItemByID

func (cli *OpCLI) GetItemByID(itemID string) (*Item, error)

GetItemByID retrieves an item by its ID.

Parameters: - itemID: A string representing the unique identifier of the item.

Returns: - *Item: A pointer to the Item struct containing the item's details. - error: An error object if the operation fails.

func (*OpCLI) GetItemByName

func (cli *OpCLI) GetItemByName(itemName string) (*Item, error)

GetItemByName retrieves an item by its name.

Parameters: - itemName: A string representing the name of the item.

Returns: - *Item: A pointer to the Item struct containing the item's details. - error: An error object if the operation fails.

func (*OpCLI) GetItemTemplateByName

func (cli *OpCLI) GetItemTemplateByName(templateName string) (*Item, error)

GetItemTemplateByName retrieves an item template by its name.

Parameters: - templateName: A string representing the name of the template.

Returns: - *Item: A pointer to the Item struct containing the template's details. - error: An error object if the operation fails.

This method executes the "item template get" command using the CLI and parses the JSON output into an Item struct. It also populates the cli field for the item.

func (*OpCLI) GetItemTemplates

func (cli *OpCLI) GetItemTemplates() (*[]ItemTemplate, error)

GetItemTemplates retrieves a list of all item templates using the 1Password CLI.

Returns: - *[]ItemTemplate: A pointer to a slice of ItemTemplate structs containing details of each template. - error: An error object if the operation fails.

This method executes the "item template list" command using the CLI and parses the JSON output into a slice of ItemTemplate structs.

func (*OpCLI) GetItems

func (cli *OpCLI) GetItems() (*[]Item, error)

GetItems retrieves a list of all items using the 1Password CLI.

Returns: - *[]Item: A pointer to a slice of Item structs containing details of each item. - error: An error object if the operation fails.

This method executes the "item list" command using the CLI and parses the JSON output into a slice of Item structs. It also populates the cli field for each item.

func (*OpCLI) GetItemsByCategory

func (cli *OpCLI) GetItemsByCategory(categories []Category) (*[]Item, error)

GetItemsByCategory retrieves a list of items filtered by the specified categories. It executes the "op" CLI command to fetch the items, unmarshals the JSON output into a slice of Item structs, and associates each item with the OpCLI instance.

Parameters:

  • categories: A slice of Category values to filter the items by.

Returns:

  • A pointer to a slice of Item structs containing the filtered items.
  • An error if the command execution or JSON unmarshaling fails.

func (*OpCLI) GetItemsByVault

func (cli *OpCLI) GetItemsByVault(vault Vault) (*[]Item, error)

GetItemsByVault retrieves a list of items from a specified vault using the 1Password CLI. It executes the "item list" command with the provided vault ID and parses the output into a slice of Item objects. Each item in the returned list is associated with the OpCLI instance.

Parameters:

  • vault: A Vault object representing the vault from which to retrieve items.

Returns:

  • A pointer to a slice of Item objects retrieved from the specified vault.
  • An error if the command execution or JSON unmarshalling fails.

func (*OpCLI) GetMe

func (cli *OpCLI) GetMe() (*User, error)

func (*OpCLI) GetServiceAccountRateLimits

func (cli *OpCLI) GetServiceAccountRateLimits() ([]ServiceAccountRateLimit, error)

GetServiceAccountRateLimits retrieves the current rate limit information for the authenticated service account.

This method checks if the OpCLI instance is authenticated as a service account. If not, it returns an error. It then executes the "service-account rate-limit" command using the 1Password CLI and parses the resulting JSON output into a ServiceAccountRateLimit struct. If any step fails (authentication check, command execution, or JSON unmarshalling), an appropriate error is returned.

Returns:

  • []ServiceAccountRateLimit: Slice containing the current rate limit details for the service account.
  • error: Non-nil if the operation fails due to authentication, command execution, or parsing errors.

Example usage:

rateLimits, err := cli.GetServiceAccountRateLimits()
if err != nil {
    log.Fatalf("Failed to get rate limit: %v", err)
}
fmt.Printf("Remaining requests: %d\n", rateLimits[0].Remaining)

func (*OpCLI) GetUserByEmail

func (cli *OpCLI) GetUserByEmail(userEmail string) (*User, error)

GetUserByEmail retrieves a user by their email address. It validates the email format before attempting to fetch the user.

Parameters:

  • userEmail: The email address of the user to retrieve.

Returns:

  • A pointer to the User object if found.
  • An error if the email format is invalid or if the user cannot be retrieved.

func (*OpCLI) GetUserByID

func (cli *OpCLI) GetUserByID(userID string) (*User, error)

func (*OpCLI) GetUserByName

func (cli *OpCLI) GetUserByName(userName string) (*User, error)

GetUserByName retrieves a user by their name. It uses the "op user get" command to fetch the user details.

Parameters: - userName: The name of the user to retrieve.

Returns: - A pointer to the User object if found. - An error if the user is not found or the command fails.

func (*OpCLI) GetVaultDetails

func (cli *OpCLI) GetVaultDetails() (*[]Vault, error)

GetVaultDetails retrieves a list of all vaults using the 1Password CLI.

This method executes the "vault list" command using the 1Password CLI to fetch details of all vaults. It unmarshals the JSON output into a slice of Vault structs and sets the CLI reference for each vault.

Returns: - *[]Vault: A pointer to a slice of Vault structs containing details of each vault. - error: An error object if the operation fails.

func (*OpCLI) GetVaultDetailsByID

func (cli *OpCLI) GetVaultDetailsByID(vaultID string) (*Vault, error)

GetVaultDetailsByID retrieves the details of a vault by its ID.

This method validates the vault ID format and then calls getVaultDetails to fetch the vault details.

Parameters: - vaultID: The unique identifier of the vault.

Returns: - *Vault: A pointer to a Vault struct containing the vault's details. - error: An error object if the operation fails.

func (*OpCLI) GetVaultDetailsByName

func (cli *OpCLI) GetVaultDetailsByName(vaultName string) (*Vault, error)

GetVaultDetailsByName retrieves the details of a vault by its name.

This method is a wrapper around getVaultDetails, allowing retrieval of vault details using the vault's name.

Parameters: - vaultName: The name of the vault.

Returns: - *Vault: A pointer to a Vault struct containing the vault's details. - error: An error object if the operation fails.

func (*OpCLI) ListUsers

func (cli *OpCLI) ListUsers() ([]User, error)

ListUsers retrieves a list of all users in the 1Password system. It executes the "op user list" command using the OpCLI instance.

Returns: - A slice of User objects representing the users in the system. - An error if the command execution or JSON unmarshalling fails.

func (*OpCLI) ProvisionUser

func (cli *OpCLI) ProvisionUser(name, email, language string) (*User, error)

ProvisionUser creates a new user in the 1Password system. It uses the "op user provision" command to create the user.

Parameters: - name: The name of the user to create. - email: The email address of the user. - language: The preferred language of the user (default is "en").

Returns: - A pointer to the newly created User object. - An error if the command fails or the email format is invalid.

func (*OpCLI) SignIn

func (cli *OpCLI) SignIn(ctx context.Context, account *Account) error

SignIn attempts to sign in to a 1Password account using the provided account details. It first tries a passwordless sign-in method. If that fails and the error indicates that password authentication is required, it prompts the user for a password and retries the sign-in process.

Upon successful sign-in, the session token is stored in an environment variable and the account's sign-in information is updated.

Parameters:

  • ctx: The context for managing the command execution lifecycle.
  • account: A pointer to the Account struct containing the account details.

Returns:

  • An error if the sign-in process fails, or nil if the sign-in is successful.

func (*OpCLI) SignInWithServiceAccount

func (cli *OpCLI) SignInWithServiceAccount(accesstoken string) error

SignInWithServiceAccount authenticates the OpCLI instance using a 1Password service account access token.

This method sets the provided access token as the current authentication token for the CLI instance, marks the instance as authenticated via a service account, and sets the "OP_SERVICE_ACCOUNT_TOKEN" environment variable for downstream processes. It then retrieves the current user's details using the GetMe method and updates the OpCLI's Account field with the user's UUID and email.

Parameters:

  • accesstoken: A string representing the 1Password service account access token.

Returns:

  • error: Returns an error if retrieving the user details fails; otherwise, returns nil.

Side Effects:

  • Modifies the OpCLI instance's accesstoken and isServiceAccount fields.
  • Sets the "OP_SERVICE_ACCOUNT_TOKEN" environment variable.
  • Updates the OpCLI's Account field with the authenticated user's details.

Example usage:

err := cli.SignInWithServiceAccount("your-access-token")
if err != nil {
    log.Fatalf("Failed to sign in: %v", err)
}

func (*OpCLI) UpdateVaultIcon

func (cli *OpCLI) UpdateVaultIcon(vaultID string, icon VaultIcon) error

UpdateVaultIcon updates the icon of a specified vault.

This method validates the vault ID and icon name, then executes the "vault edit" command using the 1Password CLI to update the icon of the specified vault.

Parameters: - vaultID: The unique identifier of the vault. - icon: The new icon to set for the vault. Must be a valid VaultIcon.

Returns: - error: An error object if the operation fails.

type OpCliError

type OpCliError struct {
	StderrOutput string
	Err          error
}

OpCliError represents an error from the 1Password CLI operations

func (*OpCliError) Error

func (e *OpCliError) Error() string

Error returns the string representation of the CLI error

type PasswordDetails

type PasswordDetails struct {
	Strength  PasswordStrength `json:"strength"`
	History   []string         `json:"history,omitempty"`
	Entropy   float64          `json:"entropy,omitempty"`
	Generated bool             `json:"generated,omitempty"`
}

PasswordDetails contains password-specific information

type PasswordStrength

type PasswordStrength string

PasswordStrength represents password strength levels

const (
	StrengthFantastic PasswordStrength = "FANTASTIC"
	StrengthTerrible  PasswordStrength = "TERRIBLE"
)

type Permission

type Permission string

Permission represents a specific permission in 1Password.

const (
	// Granular permissions
	PermissionViewItems            Permission = "view_items"
	PermissionCreateItems          Permission = "create_items"
	PermissionEditItems            Permission = "edit_items"
	PermissionArchiveItems         Permission = "archive_items"
	PermissionDeleteItems          Permission = "delete_items"
	PermissionViewAndCopyPasswords Permission = "view_and_copy_passwords"
	PermissionViewItemHistory      Permission = "view_item_history"
	PermissionImportItems          Permission = "import_items"
	PermissionExportItems          Permission = "export_items"
	PermissionCopyAndShareItems    Permission = "copy_and_share_items"
	PermissionPrintItems           Permission = "print_items"
	PermissionManageVault          Permission = "manage_vault"

	// Broader permissions
	PermissionAllowViewing  Permission = "allow_viewing"
	PermissionAllowEditing  Permission = "allow_editing"
	PermissionAllowManaging Permission = "allow_managing"

	// Derived permissions
	PermissionMoveItems Permission = "move_items"
)

type PermissionDependenciesMap

type PermissionDependenciesMap map[Permission][]Permission

PermissionDependencies maps each permission to its required broader permissions.

type Section

type Section struct {
	ID    string `json:"id"`
	Label string `json:"label"`
}

Section represents a section in an item

type ServiceAccountRateLimit

type ServiceAccountRateLimit struct {
	Type      string `json:"type"`
	Action    string `json:"action"`
	Limit     int    `json:"limit"`
	Used      int    `json:"used"`
	Remaining int    `json:"remaining"`
	Reset     int64  `json:"reset"` // Time in seconds until the rate limit resets
}

ServiceAccountRateLimit represents the rate limit information for a service account action. It includes the type of rate limit, the action being limited, the maximum allowed requests (Limit), the number of requests used (Used), the number of requests remaining (Remaining), and the time when the rate limit resets (Reset, as a Unix timestamp).

type User

type User struct {
	ID         string    `json:"id"`
	Name       string    `json:"name"`
	Email      string    `json:"email"`
	Type       UserType  `json:"type"`
	State      UserState `json:"state"`
	CreatedAt  time.Time `json:"created_at"`
	UpdatedAt  time.Time `json:"updated_at"`
	LastAuthAt time.Time `json:"last_auth_at"`
	// contains filtered or unexported fields
}

User represents a user in the 1Password system.

func (*User) Confirm

func (user *User) Confirm() (*User, error)

Confirm confirms a user by their ID using the 1Password CLI. It executes the "user confirm" command with the user's ID and parses the resulting output into an updated User object.

Returns:

  • A pointer to the updated User object if the confirmation is successful.
  • An error if the command execution or JSON unmarshalling fails.

func (*User) Delete

func (user *User) Delete() error

Delete removes a user from the 1Password system. It uses the "op user delete" command to delete the user by their ID.

Returns: - An error if the command fails.

func (*User) Reactivate

func (user *User) Reactivate() error

Reactivate reactivates a deactivated user in the system.

This method sends a command to the 1Password CLI to reactivate the user associated with the current User instance. The reactivation is performed using the user's unique ID.

Returns:

  • nil if the reactivation is successful.
  • An error if the reactivation command fails or encounters an issue.

Usage:

err := user.Reactivate()
if err != nil {
    log.Fatalf("Failed to reactivate user: %v", err)
}

Note:

Ensure that the 1Password CLI is properly configured and authenticated
before calling this method, as it relies on the CLI to execute the command.

func (*User) SetName

func (user *User) SetName(name string) error

SetName updates the name of the user by executing a command with the user's ID. It uses the 1Password CLI to perform the operation.

Parameters:

  • name: The new name to set for the user.

Returns:

  • error: An error if the command execution fails, otherwise nil.

func (*User) SetTravelMode

func (user *User) SetTravelMode(enabled bool) error

SetTravelMode enables or disables travel mode for a user. It uses the "op user edit" command to update the travel mode setting.

Parameters: - enabled: A boolean indicating whether to enable or disable travel mode.

Returns: - An error if the command fails.

func (*User) Suspend

func (user *User) Suspend() (*User, error)

Suspend suspends the current user by executing the appropriate CLI command. It sends a request to suspend the user identified by their ID and returns the updated user object if successful.

Returns:

  • A pointer to the updated User object with the suspension applied.
  • An error if the suspension process fails or if the response cannot be unmarshaled.

type UserState

type UserState string

UserState represents the state of a user.

const (
	UserStateActive            UserState = "ACTIVE"
	UserStateTransferStarted   UserState = "TRANSFER_STARTED"
	UserStateSuspended         UserState = "SUSPENDED"
	UserStateTransferSuspended UserState = "TRANSFER_SUSPENDED"
)

type UserType

type UserType string

UserType represents the type of a user.

const (
	UserTypeMember         UserType = "MEMBER"
	UserTypeServiceAccount UserType = "SERVICE_ACCOUNT"
)

type Vault

type Vault struct {
	ID               string `json:"id"`
	Name             string `json:"name"`
	ContentVersion   int    `json:"content_version"`
	CreatedAt        string `json:"created_at"`
	UpdatedAt        string `json:"updated_at"`
	Items            int    `json:"items"`
	Description      string `json:"description"`
	AttributeVersion int    `json:"attribute_version"`
	Type             string `json:"type"`
	// contains filtered or unexported fields
}

Vault represents a 1Password vault.

Fields: - ID: A unique 26-character alphanumeric identifier for the vault. - Name: The name of the vault. - ContentVersion: The version of the vault's content, incremented with changes. - CreatedAt: The timestamp when the vault was created, in ISO 8601 format. - UpdatedAt: The timestamp when the vault was last updated, in ISO 8601 format. - Items: The number of items stored in the vault. - Description: A brief description of the vault's purpose or contents. - AttributeVersion: The version of the vault's attributes. - Type: The type of the vault, e.g., USER_CREATED or SYSTEM_GENERATED.

func (*Vault) Delete

func (vault *Vault) Delete() error

Delete deletes the current vault.

This method executes the "vault delete" command using the 1Password CLI to delete the current vault.

Returns: - error: An error object if the operation fails.

func (*Vault) GrantGroupPermission

func (vault *Vault) GrantGroupPermission(group Group, permission Permission) error

GrantGroupPermission grants a specific permission to a group for the current vault.

This method validates the group and resolves the permission string, then executes the "vault group grant" command using the 1Password CLI to grant the specified permission to the group.

Parameters: - group: The Group struct representing the group to grant permission to. - permission: The Permission struct representing the permission to grant.

Returns: - error: An error object if the operation fails.

func (*Vault) GrantUserPermission

func (vault *Vault) GrantUserPermission(user User, permission Permission) error

GrantUserPermission grants a specific permission to a user for the current vault.

This method validates the user and resolves the permission string, then executes the "vault user grant" command using the 1Password CLI to grant the specified permission to the user.

Parameters: - user: The User struct representing the user to grant permission to. - permission: The Permission struct representing the permission to grant.

Returns: - error: An error object if the operation fails.

func (*Vault) RevokeGroupPermission

func (vault *Vault) RevokeGroupPermission(group Group, permission Permission) error

RevokeGroupPermission revokes a specific permission from a group for the current vault.

This method validates the group and resolves the permission string, then executes the "vault group revoke" command using the 1Password CLI to revoke the specified permission from the group.

Parameters: - group: The Group struct representing the group to revoke permission from. - permission: The Permission struct representing the permission to revoke.

Returns: - error: An error object if the operation fails.

func (*Vault) RevokeUserPermission

func (vault *Vault) RevokeUserPermission(user User, permission Permission) error

RevokeUserPermission revokes a specific permission from a user for the current vault.

This method validates the user and resolves the permission string, then executes the "vault user revoke" command using the 1Password CLI to revoke the specified permission from the user.

Parameters: - user: The User struct representing the user to revoke permission from. - permission: The Permission struct representing the permission to revoke.

Returns: - error: An error object if the operation fails.

func (*Vault) SetDescription

func (vault *Vault) SetDescription(description string) error

SetDescription updates the description of the current vault.

This method executes the "vault edit" command using the 1Password CLI to update the vault's description.

Parameters: - description: The new description to set for the vault.

Returns: - error: An error object if the operation fails.

func (*Vault) SetIcon

func (vault *Vault) SetIcon(icon VaultIcon) error

SetIcon updates the icon of the current vault.

This method validates the new icon and executes the "vault edit" command using the 1Password CLI to update the vault's icon.

Parameters: - icon: The new icon to set for the vault. Must be a valid VaultIcon.

Returns: - error: An error object if the operation fails.

func (*Vault) SetName

func (vault *Vault) SetName(name string) error

SetName updates the name of the current vault.

This method validates the new name and executes the "vault edit" command using the 1Password CLI to update the vault's name.

Parameters: - name: The new name to set for the vault.

Returns: - error: An error object if the operation fails.

func (*Vault) SetTravelMode

func (vault *Vault) SetTravelMode(travelModeOn bool) error

SetTravelMode sets the Travel Mode status for the current vault.

This method executes the "vault edit" command using the 1Password CLI to update the Travel Mode status of the vault.

Parameters: - travelModeOn: A boolean value indicating whether to turn Travel Mode on (true) or off (false).

Returns: - error: An error object if the operation fails.

type VaultIcon

type VaultIcon string

VaultIcon represents the valid icon names for a vault.

const (
	IconAirplane         VaultIcon = "airplane"
	IconApplication      VaultIcon = "application"
	IconArtSupplies      VaultIcon = "art-supplies"
	IconBankersBox       VaultIcon = "bankers-box"
	IconBrownBriefcase   VaultIcon = "brown-briefcase"
	IconBrownGate        VaultIcon = "brown-gate"
	IconBuildings        VaultIcon = "buildings"
	IconCabin            VaultIcon = "cabin"
	IconCastle           VaultIcon = "castle"
	IconCircleOfDots     VaultIcon = "circle-of-dots"
	IconCoffee           VaultIcon = "coffee"
	IconColorWheel       VaultIcon = "color-wheel"
	IconCurtainedWindow  VaultIcon = "curtained-window"
	IconDocument         VaultIcon = "document"
	IconDoughnut         VaultIcon = "doughnut"
	IconFence            VaultIcon = "fence"
	IconGalaxy           VaultIcon = "galaxy"
	IconGears            VaultIcon = "gears"
	IconGlobe            VaultIcon = "globe"
	IconGreenBackpack    VaultIcon = "green-backpack"
	IconGreenGem         VaultIcon = "green-gem"
	IconHandshake        VaultIcon = "handshake"
	IconHeartWithMonitor VaultIcon = "heart-with-monitor"
	IconHouse            VaultIcon = "house"
	IconIDCard           VaultIcon = "id-card"
	IconJet              VaultIcon = "jet"
	IconLargeShip        VaultIcon = "large-ship"
	IconLuggage          VaultIcon = "luggage"
	IconPlant            VaultIcon = "plant"
	IconPorthole         VaultIcon = "porthole"
	IconPuzzle           VaultIcon = "puzzle"
	IconRainbow          VaultIcon = "rainbow"
	IconRecord           VaultIcon = "record"
	IconRoundDoor        VaultIcon = "round-door"
	IconSandals          VaultIcon = "sandals"
	IconScales           VaultIcon = "scales"
	IconScrewdriver      VaultIcon = "screwdriver"
	IconShop             VaultIcon = "shop"
	IconTallWindow       VaultIcon = "tall-window"
	IconTreasureChest    VaultIcon = "treasure-chest"
	IconVaultDoor        VaultIcon = "vault-door"
	IconVehicle          VaultIcon = "vehicle"
	IconWallet           VaultIcon = "wallet"
	IconWrench           VaultIcon = "wrench"
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL