Documentation
¶
Index ¶
- Variables
- func FindOpExecutable() (string, error)
- func FormatCategories(categories []Category) string
- func ResolvePermissions(permission Permission) string
- func TestOpCli(opPath string) error
- func ValidateVault(vault Vault) error
- func ValidateVaultID(id string) error
- func VerifyOpExecutable(path string) error
- type Account
- type Category
- type Field
- type FieldPurpose
- type FieldType
- type Group
- func (group *Group) AddManager(user User) error
- func (group *Group) AddMember(user User) error
- func (group *Group) Delete() error
- func (group *Group) ListMembers() ([]User, error)
- func (group *Group) RemoveManager(user User) error
- func (group *Group) RemoveMember(user User) error
- func (group *Group) SetDescription(description string) error
- func (group *Group) SetName(name string) error
- type Item
- func (item *Item) AddField(field Field)
- func (item *Item) AddFieldToSection(section Section, field Field) error
- func (item *Item) AddNotes(notes string)
- func (item *Item) AddPassword(password string)
- func (item *Item) AddSection(section Section) error
- func (item *Item) AddTag(tag string)
- func (item *Item) AddURL(url ItemURL)
- func (item *Item) AddUserName(username string)
- func (item *Item) Delete() error
- func (item *Item) DeleteField(field Field) error
- func (item *Item) DeleteFieldFromSection(section Section, field Field) error
- func (item *Item) DeleteSection(section Section) error
- func (item *Item) DeleteTag(tag string) error
- func (item *Item) DeleteURLs(href string) error
- func (item *Item) GetFieldByID(fieldID string) (*Field, error)
- func (item *Item) GetFieldsByLabel(fieldLabel string) ([]*Field, error)
- func (item *Item) GetFieldsByPurpose(fieldPurpose FieldPurpose) ([]*Field, error)
- func (item *Item) MoveFieldToSection(field Field, section Section) error
- func (item *Item) NewField(label, value string, fieldType FieldType) Field
- func (item *Item) RenameSection(section Section, newLabel string) error
- func (item *Item) Save() error
- func (item *Item) SetAsFavorite(favorite bool)
- func (item *Item) ToJSON() ([]byte, error)
- func (item *Item) UpdateField(field Field) error
- type ItemTemplate
- type ItemURL
- type OpCLI
- func (cli *OpCLI) CreateGroup(name string, description string) (*Group, error)
- func (cli *OpCLI) CreateItem(item *Item, genPassword bool) (*Item, error)
- func (cli *OpCLI) CreateVault(name, description string, icon VaultIcon, adminAccess bool) (*Vault, error)
- func (cli *OpCLI) Execute(args ...string) ([]byte, error)
- func (cli *OpCLI) ExecuteOpCommand(args ...string) ([]byte, error)
- func (cli *OpCLI) GetAccountDetails() ([]Account, error)
- func (cli *OpCLI) GetAccountDetailsByAccountUUID(accountUUID string) (*Account, error)
- func (cli *OpCLI) GetAccountDetailsByEmail(email string) (*Account, error)
- func (cli *OpCLI) GetAccountDetailsByURL(url string) (*Account, error)
- func (cli *OpCLI) GetAccountDetailsByUUID(accountUUID string) (*Account, error)
- func (cli *OpCLI) GetGroupByID(id string) (*Group, error)
- func (cli *OpCLI) GetGroupByName(name string) (*Group, error)
- func (cli *OpCLI) GetGroups() ([]Group, error)
- func (cli *OpCLI) GetItemByID(itemID string) (*Item, error)
- func (cli *OpCLI) GetItemByName(itemName string) (*Item, error)
- func (cli *OpCLI) GetItemTemplateByName(templateName string) (*Item, error)
- func (cli *OpCLI) GetItemTemplates() (*[]ItemTemplate, error)
- func (cli *OpCLI) GetItems() (*[]Item, error)
- func (cli *OpCLI) GetItemsByCategory(categories []Category) (*[]Item, error)
- func (cli *OpCLI) GetItemsByVault(vault Vault) (*[]Item, error)
- func (cli *OpCLI) GetMe() (*User, error)
- func (cli *OpCLI) GetServiceAccountRateLimits() ([]ServiceAccountRateLimit, error)
- func (cli *OpCLI) GetUserByEmail(userEmail string) (*User, error)
- func (cli *OpCLI) GetUserByID(userID string) (*User, error)
- func (cli *OpCLI) GetUserByName(userName string) (*User, error)
- func (cli *OpCLI) GetVaultDetails() (*[]Vault, error)
- func (cli *OpCLI) GetVaultDetailsByID(vaultID string) (*Vault, error)
- func (cli *OpCLI) GetVaultDetailsByName(vaultName string) (*Vault, error)
- func (cli *OpCLI) ListUsers() ([]User, error)
- func (cli *OpCLI) ProvisionUser(name, email, language string) (*User, error)
- func (cli *OpCLI) SignIn(ctx context.Context, account *Account) error
- func (cli *OpCLI) SignInWithServiceAccount(accesstoken string) error
- func (cli *OpCLI) UpdateVaultIcon(vaultID string, icon VaultIcon) error
- type OpCliError
- type PasswordDetails
- type PasswordStrength
- type Permission
- type PermissionDependenciesMap
- type Section
- type ServiceAccountRateLimit
- type User
- type UserState
- type UserType
- type Vault
- func (vault *Vault) Delete() error
- func (vault *Vault) GrantGroupPermission(group Group, permission Permission) error
- func (vault *Vault) GrantUserPermission(user User, permission Permission) error
- func (vault *Vault) RevokeGroupPermission(group Group, permission Permission) error
- func (vault *Vault) RevokeUserPermission(user User, permission Permission) error
- func (vault *Vault) SetDescription(description string) error
- func (vault *Vault) SetIcon(icon VaultIcon) error
- func (vault *Vault) SetName(name string) error
- func (vault *Vault) SetTravelMode(travelModeOn bool) error
- type VaultIcon
Constants ¶
This section is empty.
Variables ¶
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.
var PermissionDependencies = PermissionDependenciesMap{ PermissionCreateItems: {PermissionCreateItems, PermissionViewItems}, PermissionViewAndCopyPasswords: {PermissionViewItems, PermissionViewAndCopyPasswords}, PermissionEditItems: {PermissionEditItems, PermissionViewAndCopyPasswords, PermissionViewItems}, PermissionArchiveItems: {PermissionArchiveItems, PermissionEditItems, PermissionViewAndCopyPasswords, PermissionViewItems}, PermissionDeleteItems: {PermissionDeleteItems, PermissionEditItems, PermissionViewAndCopyPasswords, PermissionViewItems}, PermissionViewItemHistory: {PermissionViewItemHistory, PermissionViewAndCopyPasswords, PermissionViewItems}, PermissionImportItems: {PermissionImportItems, PermissionCreateItems, PermissionViewItems}, PermissionExportItems: {PermissionExportItems, PermissionViewItemHistory, PermissionViewAndCopyPasswords, PermissionViewItems}, PermissionCopyAndShareItems: {PermissionCopyAndShareItems, PermissionViewItemHistory, PermissionViewAndCopyPasswords, PermissionViewItems}, PermissionPrintItems: {PermissionPrintItems, PermissionViewItemHistory, PermissionViewAndCopyPasswords, PermissionViewItems}, PermissionMoveItems: {PermissionViewItems, PermissionEditItems, PermissionArchiveItems, PermissionViewAndCopyPasswords, PermissionViewItemHistory, PermissionCopyAndShareItems}, }
Functions ¶
func FindOpExecutable ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
AddTag appends a new tag to the item's Tags slice.
Parameters: - tag: A string representing the tag to add.
func (*Item) AddURL ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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) 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 ¶
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) GetUserByName ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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" 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 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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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" )