password

package
v0.0.0-...-14162ad Latest Latest
Warning

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

Go to latest
Published: May 4, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package password provides secure password management functionality leveraging the existing keychain and security infrastructure.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GeneratePassword

func GeneratePassword(opts GenerateOptions) ([]byte, error)

GeneratePassword creates a cryptographically random password with the given options. The returned slice holds plaintext secret material; the caller is responsible for zeroing it (e.g. secure.SecureZeroBytes) once done.

Types

type ConflictStrategy

type ConflictStrategy string

ConflictStrategy controls how import handles duplicate entries.

const (
	ConflictSkip      ConflictStrategy = "skip"
	ConflictOverwrite ConflictStrategy = "overwrite"
)

type EncryptedEnvelope

type EncryptedEnvelope struct {
	Algorithm  string                `json:"algorithm"`
	Salt       string                `json:"salt"`       // base64
	Ciphertext string                `json:"ciphertext"` // base64
	Params     encryptedExportParams `json:"params"`
	Version    int                   `json:"version"`
}

EncryptedEnvelope is the on-disk format for a password-encrypted export. salt + params are public (needed to re-derive the key); ciphertext is the AES-256-GCM output of the JSON-serialized entries.

type Entry

type Entry struct {
	CreatedAt   time.Time         `json:"created_at"`
	UpdatedAt   time.Time         `json:"updated_at"`
	Metadata    map[string]string `json:"metadata,omitempty"`
	ID          string            `json:"id"`
	Service     string            `json:"service"`
	Username    string            `json:"username,omitempty"`
	Type        EntryType         `json:"type"`
	Description string            `json:"description,omitempty"`
}

Entry represents a password manager entry

type EntryType

type EntryType string

EntryType represents the type of password entry

const (
	// EntryTypePassword represents a stored password entry.
	EntryTypePassword EntryType = "password"
	// EntryTypeAPIKey represents an API key entry.
	EntryTypeAPIKey EntryType = "api_key"
	// EntryTypeTOTP represents a TOTP secret entry.
	EntryTypeTOTP EntryType = "totp"
	// EntryTypeNote represents a secure note entry.
	EntryTypeNote EntryType = "secure_note"
)

type ExportEntry

type ExportEntry struct {
	CreatedAt time.Time `json:"created_at,omitzero"`
	UpdatedAt time.Time `json:"updated_at,omitzero"`
	Service   string    `json:"service"`
	Username  string    `json:"username,omitempty"`
	Type      EntryType `json:"type"`
	Secret    string    `json:"secret"`
}

ExportEntry is an entry with its decrypted secret, used for export/import. Timestamps are preserved through round-trip when the underlying store implements keychain.TimestampedStore (the SQLite backend does).

type ExportFormat

type ExportFormat string

ExportFormat specifies the output format for export.

const (
	FormatJSON ExportFormat = "json"
	FormatCSV  ExportFormat = "csv"
)

type ExportOptions

type ExportOptions struct {
	Format    ExportFormat
	EntryType EntryType // empty means all types
}

ExportOptions controls what gets exported and how.

type GenerateOptions

type GenerateOptions struct {
	Length    int  // Password length (default 24)
	Uppercase bool // Include uppercase letters (default true)
	Lowercase bool // Include lowercase letters (default true)
	Digits    bool // Include digits (default true)
	Symbols   bool // Include symbols (default true)
}

GenerateOptions controls password generation.

func DefaultGenerateOptions

func DefaultGenerateOptions() GenerateOptions

DefaultGenerateOptions returns sensible defaults for password generation.

type ImportOptions

type ImportOptions struct {
	Format     ExportFormat
	OnConflict ConflictStrategy
}

ImportOptions controls how entries are imported.

type ImportResult

type ImportResult struct {
	Errors   []string
	Imported int
	Skipped  int
}

ImportResult reports what happened during import.

type ListFilter

type ListFilter struct {
	EntryType EntryType // empty means all types
	Service   string    // empty means all services
	SortBy    SortField // empty defaults to SortByService
	Limit     int       // 0 means no limit
	Offset    int
}

ListFilter controls which entries are returned and in what order.

type Manager

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

Manager provides secure password management operations

func NewManager

func NewManager(keychainProvider keychain.Provider, user string) *Manager

NewManager creates a new password manager instance

func (*Manager) DeleteEntry

func (m *Manager) DeleteEntry(service, username string, entryType EntryType) error

DeleteEntry removes a password entry and its metadata

func (*Manager) EntryExists

func (m *Manager) EntryExists(service, username string, entryType EntryType) (bool, error)

EntryExists reports whether an entry is stored at (service, username, entryType) without reading or decrypting the secret. Use this for existence probes (e.g. overwrite prompts, migration conflict checks) instead of GetPassword + zero — cheaper, never touches plaintext, and returns a clean tri-state (exists / absent / backend error).

func (*Manager) Export

func (m *Manager) Export(w io.Writer, opts ExportOptions) (int, error)

Export decrypts entries and streams them to w, one at a time, so only one plaintext record is live in memory at a time. Returns the number of entries successfully written; a partial count + error is possible if a decrypt or write fails mid-stream (prior entries remain in the writer).

func (*Manager) ExportEncrypted

func (m *Manager) ExportEncrypted(w io.Writer, opts ExportOptions, password []byte) (int, error)

ExportEncrypted writes a password-encrypted export to w. The password is used to derive a key via Argon2id; the derived key encrypts the JSON payload with AES-256-GCM. The output is portable — anyone with the password can decrypt it, regardless of key source.

func (*Manager) GenerateTOTPCode

func (m *Manager) GenerateTOTPCode(service, username string) (string, error)

GenerateTOTPCode generates a TOTP code for a stored secret, using any stored non-standard parameters (algorithm, digits, period).

func (*Manager) GetPassword

func (m *Manager) GetPassword(service, username string, entryType EntryType) ([]byte, error)

GetPassword retrieves a password securely

func (*Manager) GetPasswordString

func (m *Manager) GetPasswordString(service, username string, entryType EntryType) (string, error)

GetPasswordString retrieves a password as a string (less secure)

func (*Manager) GetPasswordsByService

func (m *Manager) GetPasswordsByService(service string) ([]Entry, error)

GetPasswordsByService returns password entries (EntryTypePassword only) for a given service name. Use ListEntriesFiltered directly if the caller needs other types.

func (*Manager) GetTOTPParams

func (m *Manager) GetTOTPParams(service, username string) totp.Params

GetTOTPParams retrieves stored TOTP parameters for an entry.

func (*Manager) Import

func (m *Manager) Import(r io.Reader, opts ImportOptions) (ImportResult, error)

Import reads entries from the given reader and stores them.

func (*Manager) ImportEncrypted

func (m *Manager) ImportEncrypted(r io.Reader, opts ImportOptions, password []byte) (ImportResult, error)

ImportEncrypted reads a password-encrypted export from r and imports it.

func (*Manager) ListEntries

func (m *Manager) ListEntries() ([]Entry, error)

ListEntries returns all password entries

func (*Manager) ListEntriesFiltered

func (m *Manager) ListEntriesFiltered(filter ListFilter) ([]Entry, error)

ListEntriesFiltered returns entries matching the given filter.

func (*Manager) SearchEntries

func (m *Manager) SearchEntries(query string) ([]Entry, error)

SearchEntries returns entries where the query matches service, username, or description. If the underlying store supports FTS (implements Searcher), it is used for ranked results. Otherwise, falls back to in-memory case-insensitive substring matching.

func (*Manager) StorePassword

func (m *Manager) StorePassword(service, username string, password []byte, entryType EntryType, opts ...StoreOption) error

StorePassword securely stores a password entry.

func (*Manager) StorePasswordString

func (m *Manager) StorePasswordString(service, username, password string, entryType EntryType, opts ...StoreOption) error

StorePasswordString is a convenience method for string passwords

func (*Manager) StoreTOTPSecret

func (m *Manager) StoreTOTPSecret(service, username, secret string) error

StoreTOTPSecret stores a TOTP secret with validation.

func (*Manager) StoreTOTPSecretWithParams

func (m *Manager) StoreTOTPSecretWithParams(service, username, secret string, params totp.Params) error

StoreTOTPSecretWithParams stores a TOTP secret with validation and optional non-standard parameters (algorithm, digits, period, issuer).

type Searcher

type Searcher interface {
	SearchEntries(query string) ([]keychain.KeychainEntry, error)
}

Searcher is an optional interface that credential stores can implement to provide full-text search. The SQLite store implements this via FTS5.

type SortField

type SortField string

SortField controls the sort order of listed entries.

const (
	SortByService   SortField = "service"
	SortByCreatedAt SortField = "created_at"
	SortByUpdatedAt SortField = "updated_at"
)

type StoreOption

type StoreOption func(*storeOptions)

StoreOption configures optional behavior of StorePassword / StorePasswordString.

func WithTimestamps

func WithTimestamps(createdAt, updatedAt time.Time) StoreOption

WithTimestamps preserves the given create/update timestamps on backends that implement keychain.TimestampedStore (the SQLite store does; the macOS keychain backend does not — there the option is silently ignored and the current time is used). A zero-valued time.Time on either argument is treated as "unset" and falls back to the current time for that field.

Jump to

Keyboard shortcuts

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