lastpass

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2022 License: MIT Imports: 28 Imported by: 6

README

Documentation Go Report Card Test

Go client for LastPass

Features

  • login with
    • user name and master password
    • two-factor authentication with out-of-band mechanism such as push notification to LastPass Authenticator or Duo Security
    • two-factor authentication with one-time password from LastPass Authenticator, Google Authenticator, Microsoft Authenticator, YubiKey, Duo Security, Sesame, etc.
    • trust: after first successful login with two-factor authentication, the second factor can be skipped
  • create account
  • read accounts
  • update account
  • delete account
  • create / read / update / delete account in shared folder
  • logout

Documentation

https://pkg.go.dev/github.com/ansd/lastpass-go

Installation

Install:

$ go get github.com/ansd/lastpass-go

Import:

import "github.com/ansd/lastpass-go"

Usage

Below, error handling is excluded for brevity.

See examples directory for more examples.

// authenticate with LastPass servers
client, _ := lastpass.NewClient(context.Background(), "user name", "master password")

// two-factor authentication with one-time password as second factor:
// client, _ := lastpass.NewClient(context.Background(), "user name", "master password", lastpass.WithOneTimePassword("123456"))

account := &lastpass.Account{
	Name:     "my site",
	Username: "my user",
	Password: "my pwd",
	URL:      "https://myURL",
	Group:    "my group",
	Notes:    "my notes",
}

// Add() account
client.Add(context.Background(), account)

// read all Accounts()
accounts, _ := client.Accounts(context.Background())

// Update() account
account.Password = "updated password"
client.Update(context.Background(), account)

// Delete() account
client.Delete(context.Background(), account)

// Logout()
client.Logout(context.Background())

Notes

This repository is a port of detunized/lastpass-ruby and a clone of mattn/lastpass-go.

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

This repository's ecb (Electronic Codebook) package contains code which is "Copyright 2013 The Go Authors. All rights reserved."

Documentation

Overview

Package lastpass implements a LastPass client.

Index

Examples

Constants

View Source
const (
	EndpointLogin       = "/login.php"
	EndpointTrust       = "/trust.php"
	EndpointLoginCheck  = "/login_check.php"
	EndpointGetAccts    = "/getaccts.php"
	EndpointShowWebsite = "/show_website.php"
	EndpointLogout      = "/logout.php"
)

LastPass API endpoints used by this client.

View Source
const (
	MaxLoginRetries = 7
)

MaxLoginRetries determines the maximum number of login retries if the login fails with cause "outofbandrequired". This increases the user's time to approve the out-of-band (2nd) factor (e.g. approving a push notification sent to their mobile phone).

Variables

This section is empty.

Functions

func NewContextWithLogger

func NewContextWithLogger(ctx context.Context, logger Logger) context.Context

NewContextWithLogger returns a new context with logging enabled.

Example

NewContextWithLogger logs only for a specific method (request scope). In the following example, it emits logs for only the NewClient method.

logger := log.New(os.Stderr, "lastpass: ", log.LstdFlags)

_, _ = lastpass.NewClient(
	lastpass.NewContextWithLogger(context.Background(), logger),
	"user name", "master password")
Output:

Types

type Account

type Account struct {
	ID       string
	Name     string
	Username string
	Password string
	URL      string
	Group    string
	// Shared folder name.
	// If non-empty, it must have prefix "Shared-".
	// Empty means this Account is not in a shared folder.
	Share string
	Notes string
	// Timestamp in seconds (set by LastPass servers).
	LastModifiedGMT string
	LastTouch       string
}

Account represents a LastPass item. An item can be a password, payment card, bank account, etc., or a custom item type.

type AccountNotFoundError

type AccountNotFoundError struct {
	// account ID that does not exist
	ID string
}

AccountNotFoundError indicates that no account with AccountNotFoundError.ID exists on LastPass.

func (*AccountNotFoundError) Error

func (e *AccountNotFoundError) Error() string

type AuthenticationError

type AuthenticationError struct {
	// contains filtered or unexported fields
}

AuthenticationError indicates that the Client is not logged in.

func (*AuthenticationError) Error

func (e *AuthenticationError) Error() string

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client represents a LastPass client. A Client can be logged in to a single account at a given time.

func NewClient

func NewClient(ctx context.Context, username, masterPassword string, opts ...ClientOption) (*Client, error)

NewClient authenticates with the LastPass servers.

The following authentication schemes are supported: single-factor authentication via master password, two-factor authentication via out-of-band mechanism (e.g. LastPass Authenticator Push Notification, Duo Security Push Notification), and two-factor authentication via one-time password (e.g. one-time verification code of LastPass Authenticator, Google Authenticator, Microsoft Authenticator, YubiKey, Transakt, Duo Security, or Sesame)

If authentication fails, an *AuthenticationError is returned.

Example (OneTimePasswordAuthentication)

Login with two-factor authentication: 1st factor is master passord, 2nd factor is one-time password (e.g. one-time verification code of LastPass Authenticator, Google Authenticator, Microsoft Authenticator, YubiKey, Transakt, Duo Security, or Sesame).

If an invalid user name, master password, or one-time password is supplied, NewClient returns an error of type *AuthenticationError.

_, _ = lastpass.NewClient(context.Background(), "user name", "master password",
	lastpass.WithOneTimePassword("123456"),
)
Output:

Example (OutOfBandAuthentication)

Login with two-factor authentication: 1st factor is master passord, 2nd factor is out-of-band mechanism (e.g. LastPass Authenticator Push Notification or Duo Security Push Notification).

Below code is the same as the login without two-factor authentication. Once the NewClient function got invoked, the user has around 90 seconds to accept the out-of-band mechanism (e.g. by selecting "Approve" in the LastPass Authenticator or Duo Security app.)

If the user does not accept the out-of-band mechanism within the 90 seconds, NewClient returns an error of type *AuthenticationError.

_, _ = lastpass.NewClient(context.Background(), "user name", "master password")
Output:

Example (PasswordBasedAuthentication)

Login with master password (without two-factor authentication).

If an invalid user name or master password is supplied, NewClient returns an error of type *AuthenticationError.

_, _ = lastpass.NewClient(context.Background(), "user name", "master password")
Output:

Example (Trust)

Login with two-factor authentication and trust:

The WithTrust option will cause subsequent logins to not require multifactor authentication. It will create a trust label with the format `<hostname> <operating system name> lastpass-go` which will show up in the LastPass Web Browser Extension under Account Settings => Trusted Devices.

// On first login, the 2nd factor must be provided.
_, _ = lastpass.NewClient(context.Background(), "user name", "master password",
	lastpass.WithOneTimePassword("123456"),
	lastpass.WithTrust(),
)
// Thereafter, within the next 30 days, the 2nd factor can be omitted.
// (If you want to disable the default limit of 30 days, in the LastPass Web Browser Extension select the checkbox
// Account Settings => General => Show Advanced Settings => Don't end trust period after 30 days.)
_, _ = lastpass.NewClient(context.Background(), "user name", "master password")
Output:

func NewClientFromSession added in v0.4.0

func NewClientFromSession(ctx context.Context, currentSession *Session, opts ...ClientOption) (*Client, error)

func (*Client) Accounts

func (c *Client) Accounts(ctx context.Context) ([]*Account, error)

Accounts lists all LastPass accounts.

If Client is not logged in, an *AuthenticationError is returned.

func (*Client) Add

func (c *Client) Add(ctx context.Context, account *Account) error

Add adds the account to LastPass. Since LastPass generates a new account ID, account.ID is ignored. When this method returns (without an error), account.ID is set to the newly generated account ID. If Client is not logged in, an *AuthenticationError is returned. To add an account to a shared folder, account.Share must be prefixed with "Shared-".

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, account *Account) error

Delete deletes the LastPass Account with the given account.ID. If account.ID does not exist in LastPass, an *AccountNotFoundError is returned. If Client is not logged in, an *AuthenticationError is returned. If Client is not logged in, an *AuthenticationError is returned.

All Account fields other than account.ID and account.Share are ignored.

func (*Client) FetchEncryptedAccounts added in v0.4.0

func (c *Client) FetchEncryptedAccounts(ctx context.Context) ([]byte, error)

FetchEncryptedAccounts fetches the user's encrypted accounts from LastPass. The returned []byte can be parsed using the ParseEncryptedAccounts method.

func (*Client) Logout

func (c *Client) Logout(ctx context.Context) error

Logout invalidates the session cookie.

func (*Client) ParseEncryptedAccounts added in v0.4.0

func (c *Client) ParseEncryptedAccounts(r io.Reader) ([]*Account, error)

ParseEncryptedAccounts parses encrypted accounts into a []*Account. The original encrypted accounts data can be obtained from LastPass using the FetchEncryptedAccounts method.

func (*Client) Session added in v0.4.0

func (c *Client) Session() (*Session, error)

func (*Client) Update

func (c *Client) Update(ctx context.Context, account *Account) error

Update updates the account with the given account.ID. If account.ID does not exist in LastPass, an *AccountNotFoundError is returned. If Client is not logged in, an *AuthenticationError is returned.

Updating an account within a shared folder is supported unless field account.Share itself is modified: To move an account to / from a shared folder, use Delete() and Add() functions instead.

type ClientOption

type ClientOption func(c *Client)

ClientOption is the type of constructor options for NewClient(...).

func WithBaseURL

func WithBaseURL(baseURL string) ClientOption

WithBaseURL overwrites the Client's default base URL https://lastpass.com/. This function is used for unit testing.

func WithConfigDir added in v0.2.0

func WithConfigDir(path string) ClientOption

WithConfigDir sets the path of this library's cofiguration directory to persist user specific configuration. If this option is not specified, the configuration directory defaults to <default-config-root-directory>/lastpass-go where <default-config-root-directory> is the path returned by method UserConfigDir, see https://golang.org/pkg/os/#UserConfigDir. The only user specific configuration currently supported by this library is a file called `trusted_id`.

func WithHTTPClient added in v0.4.0

func WithHTTPClient(httpClient HTTPClient) ClientOption

WithHTTPClient optionally specifies a custom HTTPClient to use.

A new instance of a http.Client is used if this option is not specified.

func WithLogger

func WithLogger(logger Logger) ClientOption

WithLogger enables logging.

Example

WithLogger enables logging for all methods on lastpass.Client.

logger := log.New(os.Stderr, "lastpass: ", log.LstdFlags)

_, _ = lastpass.NewClient(context.Background(), "user name", "master password",
	lastpass.WithLogger(logger))
Output:

func WithOneTimePassword

func WithOneTimePassword(oneTimePassword string) ClientOption

WithOneTimePassword enables two-factor authentication with a one-time password as the second factor. For an example how to use this function see https://godoc.org/github.com/ansd/lastpass-go#example-NewClient--OneTimePasswordAuthentication.

func WithTrust added in v0.2.0

func WithTrust() ClientOption

WithTrust will cause subsequent logins to not require multifactor authentication. It behaves like the `lpass login --trust` option of the LastPass CLI. If not already present, it will create a file `trusted_id` with a random trust ID in the configuration directory set by WithConfigDir. It will create a trust label with the format `<hostname> <operating system name> lastpass-go` which will show up in the LastPass Web Browser Extension under Account Settings => Trusted Devices.

type HTTPClient added in v0.4.0

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPClient abstracts a Go http.Client with the Do method.

type Logger

type Logger interface {
	Printf(format string, v ...interface{})
}

Logger is the interface which wraps the Printf method.

type Session added in v0.4.0

type Session struct {
	// PasswdIterations controls how many times the user's password
	// is hashed using PBKDF2 before being sent to LastPass.
	PasswdIterations int

	// Token is the session token returned by LastPass during the login process.
	Token string

	// EncryptionKey is derived by hashing the user's master password using PBKDF2.
	EncryptionKey []byte

	// OptPrivateKey is the user's private key for decrypting sharing
	// keys. Sharing keys are used for shared folders.
	//
	// The first time the user logs into LastPass using any official LastPass client
	// (e.g. browser extension) a key pair gets created.
	// The public key is uploaded unencrypted to LastPass so that
	// other users can encrypt data for the user (e.g. sharing keys).
	// The private key gets encrypted locally (within the client) with the user's encryption key
	// and also uploaded to LastPass.
	//
	// This is nil if the user has not generated a sharing key. See
	// https://support.lastpass.com/help/why-am-i-seeing-an-error-no-private-key-cannot-decrypt-pending-shares-message-lp010147
	OptPrivateKey *rsa.PrivateKey
}

Directories

Path Synopsis
examples
create_read_update_delete
Example showing how to create, read, update, delete accounts.
Example showing how to create, read, update, delete accounts.
logging
Example showing how to log HTTP requests
Example showing how to log HTTP requests
trust
Example showing the trust feature which allows to skip multifactor authentication in subsequent logins.
Example showing the trust feature which allows to skip multifactor authentication in subsequent logins.
test

Jump to

Keyboard shortcuts

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