accounts

package
v0.1.0-alpha.76 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: GPL-3.0 Imports: 22 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package accounts owns authenticated user identities and opaque browser sessions. It borrows MagicHandy's process-owned SQLite handle; it never owns a second database or closes the shared handle.

Index

Constants

View Source
const (
	// ControlRelationshipSelf is the authenticated account itself.
	ControlRelationshipSelf = "self"
	// ControlRelationshipLinked is an explicitly active directional link.
	ControlRelationshipLinked = "linked"
)
View Source
const (
	// InterfaceFull is the main application. An empty value is accepted only for
	// old in-process callers; persisted records always contain an explicit value.
	InterfaceFull = "full"
	// InterfaceRemote allows the dedicated remote and account self-service only.
	InterfaceRemote = "remote"
)
View Source
const (
	// MinPasswordCharacters is the minimum accepted Unicode password length.
	MinPasswordCharacters = 15
	// MaxPasswordBytes bounds password-hashing work and request memory.
	MaxPasswordBytes = 1024
)
View Source
const (
	// MaxProfileImageBytes bounds an accepted browser-normalized JPEG.
	MaxProfileImageBytes = 2 << 20
	// MaxProfileImageEdge is the largest decoded dimension accepted by the API.
	MaxProfileImageEdge = 1024
)
View Source
const (
	// RoleAdmin can manage accounts and use the shared application.
	RoleAdmin = "admin"
	// RoleOperator can use the shared application but cannot manage accounts.
	RoleOperator = "operator"

	// DefaultSessionLifetime is the absolute server-side session limit.
	DefaultSessionLifetime = 12 * time.Hour
	// DefaultSessionIdleLimit expires a login without deliberate user activity.
	DefaultSessionIdleLimit = 8 * time.Hour
	// MaxSessionsPerAccount bounds persistent sessions for one account.
	MaxSessionsPerAccount = 20
)
View Source
const MaxRecoveryCodes = 8

MaxRecoveryCodes is also enforced by the datastore's insertion trigger.

View Source
const MaxSessionNameRunes = 80

MaxSessionNameRunes bounds optional, informational device names.

Variables

View Source
var (
	// ErrProfileImageInvalid reports a payload that is not a bounded JPEG.
	ErrProfileImageInvalid = errors.New("profile image is not a supported JPEG")
	// ErrProfileImageNotFound reports an account with no stored image.
	ErrProfileImageNotFound = errors.New("profile image has not been set")
)
View Source
var (
	// ErrManagedSessionNotFound conceals whether an identifier belongs to another account.
	ErrManagedSessionNotFound = errors.New("session is no longer available")
	// ErrInvalidSessionName rejects oversized or non-displayable names.
	ErrInvalidSessionName = errors.New("session name must be at most 80 characters without control characters")
)
View Source
var (
	// ErrAlreadyInitialized prevents a second first-account bootstrap.
	ErrAlreadyInitialized = errors.New("user accounts are already initialized")
	// ErrInvalidCredentials deliberately covers every failed login reason.
	ErrInvalidCredentials = errors.New("invalid username or password")
	// ErrInvalidRole marks an unsupported account role.
	ErrInvalidRole = errors.New("invalid account role")
	// ErrInvalidSession deliberately covers missing, expired, and revoked tokens.
	ErrInvalidSession = errors.New("invalid or expired session")
	// ErrInvalidUsername marks a username syntax or length failure.
	ErrInvalidUsername = errors.New("invalid username")
	// ErrLastAdmin prevents loss of the final enabled administrator.
	ErrLastAdmin = errors.New("the last enabled administrator cannot be disabled")
	// ErrNotFound reports a requested account ID that does not exist.
	ErrNotFound = errors.New("user account not found")
	// ErrUsernameTaken reports a case-insensitive username collision.
	ErrUsernameTaken = errors.New("username is already in use")
)
View Source
var ErrAdministratorRequired = errors.New("administrator access required")

ErrAdministratorRequired rejects a live login without administrative authority.

View Source
var ErrControlIdentityNotAllowed = errors.New("control identity is not available to this account")

ErrControlIdentityNotAllowed rejects a target that is neither self nor an enabled account connected by an active backend-owned link.

View Source
var ErrControlPermissionRequired = errors.New("this account does not have permission to control motion")

ErrControlPermissionRequired reports an expired or revoked control grant.

View Source
var ErrInterfaceAccess = errors.New("this account can sign in only to the remote interface")

ErrInterfaceAccess rejects an incompatible account or login audience.

View Source
var ErrInvalidPassword = errors.New("invalid password")

ErrInvalidPassword marks a password-policy failure without exposing a hash.

View Source
var ErrInvalidRecoveryCode = errors.New("invalid username or recovery code")

ErrInvalidRecoveryCode intentionally does not distinguish unknown accounts, disabled accounts, invalid codes, and codes that have already been consumed.

View Source
var ErrInvalidSessionPolicy = errors.New("idle sign-out must be off or 30, 60, 120, 240 or 480 minutes")

ErrInvalidSessionPolicy rejects unsupported idle sign-out durations.

Functions

func HashPassword

func HashPassword(password string) (string, error)

HashPassword returns a self-describing Argon2id PHC string. The parameters are stored with each hash so they can be raised later without invalidating existing accounts.

func MatchesSessionKey

func MatchesSessionKey(token, key string) bool

MatchesSessionKey recognizes a token for an already-held server identity. It performs no authentication, expiry, revocation or permission check. The HTTP edge uses it only for scheduling; admission still resolves the session.

func ValidatePassword

func ValidatePassword(password string) error

ValidatePassword applies only safety bounds. MagicHandy deliberately avoids composition rules that encourage predictable substitutions; callers should use a long, unique passphrase.

func VerifyPassword

func VerifyPassword(password, encoded string) (bool, error)

VerifyPassword compares password to a bounded Argon2id PHC string. Database values are treated as untrusted: excessive cost values are rejected before they can consume attacker-controlled memory or CPU.

Types

type Account

type Account struct {
	ID               string `json:"id"`
	Username         string `json:"username"`
	Role             string `json:"role"`
	InterfaceAccess  string `json:"interface_access"`
	Disabled         bool   `json:"disabled"`
	HasProfileImage  bool   `json:"has_profile_image"`
	ProfileUpdatedAt string `json:"profile_updated_at,omitempty"`
	LastLoginAt      string `json:"last_login_at,omitempty"`
	CreatedAt        string `json:"created_at"`
	UpdatedAt        string `json:"updated_at"`
}

Account is the non-secret public view of a user identity.

func (Account) FullAccess

func (a Account) FullAccess() bool

FullAccess is independent of role: an operator may be remote-only, but an administrator may not. Unknown values fail closed.

type ControlGrant

type ControlGrant struct {
	ID        string    `json:"id"`
	AccountID string    `json:"account_id"`
	IssuedBy  string    `json:"issued_by"`
	CreatedAt time.Time `json:"created_at"`
	// A nil expiry is an explicitly issued permanent permission.
	ExpiresAt *time.Time `json:"expires_at"`
}

ControlGrant authorizes one account to operate this shared installation's existing motion/chat/media path. It grants no host-administration privileges and never follows the selected linked-account attribution profile.

type ControlIdentity

type ControlIdentity struct {
	Account      Account `json:"account"`
	Relationship string  `json:"relationship"`
	Label        string  `json:"label"`
	Selected     bool    `json:"selected"`
}

ControlIdentity is an account this login session may represent in the shell's control-context selector. It never changes authentication role or grants controller ownership.

type RecoveredAccount

type RecoveredAccount struct {
	AccountID   string   `json:"-"`
	SessionKeys []string `json:"-"`
}

RecoveredAccount supplies private session identities only to the HTTP edge for immediate lifetime retirement. Recovery never creates a login session.

type RecoveryCodes

type RecoveryCodes struct {
	RecoveryStatus
	Codes []string `json:"codes"`
}

RecoveryCodes is a one-time issuance result for the account owner. Existing codes cannot be retrieved; diagnostics and exports must use RecoveryStatus.

type RecoveryStatus

type RecoveryStatus struct {
	Remaining int    `json:"remaining"`
	Limit     int    `json:"limit"`
	CreatedAt string `json:"created_at,omitempty"`
}

RecoveryStatus is safe to inspect; it never contains codes or their digests.

type Session

type Session struct {
	ID string `json:"id"`
	// Key is a non-bearer database identity used only for server-side lifetime
	// checks. It must never be serialized or accepted as a login credential.
	Key              string        `json:"-"`
	Interface        string        `json:"interface"`
	Account          Account       `json:"account"`
	ControlAccountID string        `json:"control_account_id"`
	ExpiresAt        time.Time     `json:"expires_at"`
	ControlGrant     *ControlGrant `json:"control_grant,omitempty"`
}

Session is an authenticated account plus the server-enforced absolute expiration. The raw bearer token is returned only by NewSession.

func (Session) CanControl

func (s Session) CanControl(now time.Time) bool

CanControl reports authority at the supplied instant, including grant expiry.

func (Session) CanUseRemote

func (s Session) CanUseRemote(now time.Time) bool

CanUseRemote checks the same time-bounded grant as local control without allowing a remote login to acquire controller ownership or call core APIs.

func (Session) RemoteDesktopAccount

func (s Session) RemoteDesktopAccount() string

RemoteDesktopAccount scopes a remote-only login to its granting administrator's desktop. A grant is never global access to other users.

type SessionClient

type SessionClient struct {
	Browser  string `json:"browser"`
	Platform string `json:"platform"`
}

SessionClient contains coarse hints, never a fingerprint, address or raw UA. These labels are informational and confer no authority.

type SessionInfo

type SessionInfo struct {
	ID            string        `json:"id"`
	Name          string        `json:"name"`
	Client        SessionClient `json:"client"`
	CreatedAt     string        `json:"created_at"`
	LastActiveAt  string        `json:"last_active_at"`
	ExpiresAt     time.Time     `json:"expires_at"`
	IdleExpiresAt *time.Time    `json:"idle_expires_at"`
	Current       bool          `json:"current"`
	Interface     string        `json:"interface"`
	Key           string        `json:"-"`
}

SessionInfo is the public management view. Key is private bookkeeping for server-side cancellation and must not enter a response or export.

type SessionPolicy

type SessionPolicy struct {
	IdleMinutes     int `json:"idle_minutes"`
	LifetimeMinutes int `json:"lifetime_minutes"`
}

SessionPolicy controls login inactivity, independently of controller liveness. Zero disables only idle expiry; absolute expiry and revocation still apply.

type Store

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

Store provides account operations over the process-owned datastore.

func New

func New(db *appstore.DB) (*Store, error)

New creates the account domain over an existing process-owned datastore.

func (*Store) Authenticate

func (s *Store) Authenticate(ctx context.Context, username, password string) (Account, error)

Authenticate performs the same Argon2id work for missing, disabled, and existing accounts and returns one generic credential error.

func (*Store) BootstrapAdmin

func (s *Store) BootstrapAdmin(ctx context.Context, username, password string) (Account, error)

BootstrapAdmin creates the first account. The emptiness check and insert use the shared serialized writer so simultaneous bootstrap requests cannot both succeed.

func (*Store) CanViewProfile

func (s *Store) CanViewProfile(ctx context.Context, viewer Account, targetAccountID string) (bool, error)

CanViewProfile reports whether viewer may fetch target's profile image.

func (*Store) ChangeOwnPassword

func (s *Store) ChangeOwnPassword(ctx context.Context, actorKey, currentPassword, newPassword string) ([]string, error)

ChangeOwnPassword binds password confirmation and the eventual mutation to the same still-live session and password. Return retired private keys only for immediate server-side cancellation; never serialize them to a browser.

func (*Store) CheckSession

func (s *Store) CheckSession(ctx context.Context, key string) (Session, error)

CheckSession validates a server-side session identity without renewing idle time. Background streams and control watchdogs are observations, not activity.

func (*Store) ControlGrant

func (s *Store) ControlGrant(ctx context.Context, accountID string) (*ControlGrant, error)

ControlGrant returns a permanent or unexpired permission, or nil for an observer.

func (*Store) ControlIdentities

func (s *Store) ControlIdentities(ctx context.Context, ownerID, selectedID string) ([]ControlIdentity, error)

ControlIdentities returns the backend-authorized choices for one signed-in account. The authenticated account is always first and labeled Self.

func (*Store) Create

func (s *Store) Create(ctx context.Context, username, password, role string) (Account, error)

Create adds an account for trusted internal callers. HTTP mutations must use CreateForSession so revocation is serialized with the write.

func (*Store) CreateForSession

func (s *Store) CreateForSession(ctx context.Context, actorKey, username, password, role string) (Account, error)

CreateForSession creates an account only while the acting administrator's login is still valid at the instant of the write.

func (*Store) CreateWithAccessForSession

func (s *Store) CreateWithAccessForSession(ctx context.Context, actorKey, username, password, role, access string) (Account, error)

CreateWithAccessForSession creates an explicitly scoped account under the same serialized administrator check used for ordinary account creation.

func (*Store) DeleteOwnProfileImage

func (s *Store) DeleteOwnProfileImage(ctx context.Context, key string) (Account, error)

DeleteOwnProfileImage applies the same admission contract as replacement.

func (*Store) DeleteProfileImage

func (s *Store) DeleteProfileImage(ctx context.Context, id string) (Account, error)

DeleteProfileImage returns the account to its generated monogram.

func (*Store) EnabledCount

func (s *Store) EnabledCount(ctx context.Context) (int, error)

EnabledCount returns the number of accounts allowed to authenticate.

func (*Store) GrantControl

func (s *Store) GrantControl(ctx context.Context, administratorID, accountID string, lifetime time.Duration) (*ControlGrant, error)

GrantControl replaces an account's previous permission with a fresh identity. The issuing administrator is checked inside the same write transaction.

func (*Store) GrantControlForSession

func (s *Store) GrantControlForSession(ctx context.Context, actorKey, accountID string, lifetime time.Duration) (*ControlGrant, error)

GrantControlForSession issues permission under a live administrator login. A zero lifetime explicitly requests permanent permission.

func (*Store) GrantPermanentControl

func (s *Store) GrantPermanentControl(ctx context.Context, administratorID, accountID string) (*ControlGrant, error)

GrantPermanentControl explicitly issues control until revoked or replaced. Login expiry, account disabling and controller leases still apply.

func (*Store) Initialized

func (s *Store) Initialized(ctx context.Context) (bool, error)

Initialized reports whether any account exists, including disabled rows.

func (*Store) InspectSession

func (s *Store) InspectSession(ctx context.Context, token string) (Session, error)

InspectSession authenticates passive polling without extending idle time.

func (*Store) List

func (s *Store) List(ctx context.Context) ([]Account, error)

List returns public account metadata. Password hashes never leave this package, even to another backend package.

func (*Store) ListOwnSessions

func (s *Store) ListOwnSessions(ctx context.Context, actorKey string) ([]SessionInfo, error)

ListOwnSessions reads one bounded snapshot without extending any idle time.

func (*Store) LoginForInterface

func (s *Store) LoginForInterface(ctx context.Context, username, password string, client SessionClient, audience string) (string, Session, error)

LoginForInterface binds a new opaque login to one listener in the same transaction that revalidates the account and password proof.

func (*Store) LoginWithClient

func (s *Store) LoginWithClient(ctx context.Context, username, password string, client SessionClient) (string, Session, error)

LoginWithClient verifies the password outside the writer, then revalidates it and creates the session in the same transaction. HTTP password login must use this method, not separate Authenticate and NewSession calls.

func (*Store) NewSession

func (s *Store) NewSession(ctx context.Context, accountID string) (string, Session, error)

NewSession creates a high-entropy bearer token while storing only its SHA-256 digest. A database disclosure therefore does not reveal live tokens.

func (*Store) NewSessionWithClient

func (s *Store) NewSessionWithClient(ctx context.Context, accountID string, client SessionClient) (string, Session, error)

NewSessionWithClient records only a coarse, untrusted browser/platform hint. The independent management ID is never accepted as a bearer credential.

func (*Store) OpenProfileImage

func (s *Store) OpenProfileImage(ctx context.Context, id string) (*os.File, error)

OpenProfileImage opens a stable image file while holding the read lock only for lookup/open. The returned descriptor remains valid after the lock exits.

func (*Store) ProfileImageDir

func (s *Store) ProfileImageDir() string

ProfileImageDir is app-owned and removed with the rest of MagicHandy data.

func (*Store) RecoverPassword

func (s *Store) RecoverPassword(ctx context.Context, username, code, password string) (RecoveredAccount, error)

RecoverPassword redeems a saved code, changes the password and revokes every login and every remaining recovery code in one transaction. Concurrent uses, replacement, disabling and password changes are rechecked before committing.

func (*Store) RecoveryStatus

func (s *Store) RecoveryStatus(ctx context.Context, actorKey string) (RecoveryStatus, error)

RecoveryStatus returns the signed-in account's saved-code count, never codes.

func (*Store) RemoveRecoveryCodes

func (s *Store) RemoveRecoveryCodes(ctx context.Context, actorKey, password string) error

RemoveRecoveryCodes disables offline recovery after fresh password proof.

func (*Store) RenameOwnSession

func (s *Store) RenameOwnSession(ctx context.Context, actorKey, id, name string) error

RenameOwnSession updates a display name after checking ownership and current login validity in the writer transaction. Empty names restore the client hint.

func (*Store) ReplaceRecoveryCodes

func (s *Store) ReplaceRecoveryCodes(ctx context.Context, actorKey, password string) (RecoveryCodes, error)

ReplaceRecoveryCodes requires both a current login and the current password. The proof/session are rechecked in the write transaction before replacing all older codes. A lost response can be recovered by generating a new set.

func (*Store) RequireControlSessionTx

func (s *Store) RequireControlSessionTx(ctx context.Context, tx *sql.Tx, key string) error

RequireControlSessionTx checks login and control permission in the same transaction as a domain write, including time spent waiting for the writer.

func (*Store) ResetPasswordForSession

func (s *Store) ResetPasswordForSession(ctx context.Context, actorKey, accountID, password string) ([]string, error)

ResetPasswordForSession rechecks the administrator's own login inside the mutation, so a queued reset cannot survive that administrator's recovery.

func (*Store) ResolveSession

func (s *Store) ResolveSession(ctx context.Context, token string) (Session, error)

ResolveSession authenticates a token and advances its idle timestamp at most once per minute, avoiding a SQLite write for every UI polling request.

func (*Store) RevokeControl

func (s *Store) RevokeControl(ctx context.Context, administratorID, accountID string) error

RevokeControl removes permission without ending the account's read access.

func (*Store) RevokeControlForSession

func (s *Store) RevokeControlForSession(ctx context.Context, actorKey, accountID string) error

RevokeControlForSession checks the actor's login in the revocation transaction.

func (*Store) RevokeOtherSessions

func (s *Store) RevokeOtherSessions(ctx context.Context, actorKey string) ([]string, error)

RevokeOtherSessions preserves the caller and ends the account's other logins. The private returned keys are solely for immediate server-side cancellation.

func (*Store) RevokeOwnSession

func (s *Store) RevokeOwnSession(ctx context.Context, actorKey, id string) (string, error)

RevokeOwnSession returns a private key for immediate runtime invalidation. Another account's management ID, including one presented by an administrator, cannot address this caller's self-service session collection.

func (*Store) RevokeSession

func (s *Store) RevokeSession(ctx context.Context, token string) error

RevokeSession invalidates one opaque bearer token. It is idempotent.

func (*Store) SaveOwnProfileImage

func (s *Store) SaveOwnProfileImage(ctx context.Context, key string, data []byte) (Account, error)

SaveOwnProfileImage keeps HTTP writes bound to a live session through the final metadata transaction. A revoked upload rolls back its staged image.

func (*Store) SaveProfileImage

func (s *Store) SaveProfileImage(ctx context.Context, id string, data []byte) (Account, error)

SaveProfileImage validates and atomically replaces one account image.

func (*Store) SessionOwnerTx

func (s *Store) SessionOwnerTx(ctx context.Context, tx *sql.Tx, key string) (string, error)

SessionOwnerTx revalidates an account's session inside a domain write transaction using the shared datastore. It grants no host or control permission.

func (*Store) SessionPolicy

func (s *Store) SessionPolicy(ctx context.Context) (SessionPolicy, error)

SessionPolicy reads persisted policy without renewing the caller's login.

func (*Store) SetControlIdentity

func (s *Store) SetControlIdentity(ctx context.Context, token, targetAccountID string) error

SetControlIdentity changes only this opaque login session's attribution context. It cannot change authentication role or controller ownership.

func (*Store) SetDisabled

func (s *Store) SetDisabled(ctx context.Context, accountID string, disabled bool) error

SetDisabled changes login eligibility for trusted internal callers. HTTP mutations must use SetDisabledForSession. At least one enabled administrator is always retained.

func (*Store) SetDisabledForSession

func (s *Store) SetDisabledForSession(ctx context.Context, actorKey, accountID string, disabled bool) ([]string, error)

SetDisabledForSession serializes administrator authority with the mutation. Returned private session keys are for immediate cancellation, never JSON.

func (*Store) SetInterfaceAccessForSession

func (s *Store) SetInterfaceAccessForSession(ctx context.Context, actorKey, accountID, access string) ([]string, error)

SetInterfaceAccessForSession invalidates all logins and grants when access changes, so an already admitted operation cannot outlive a downgrade.

func (*Store) SetPassword

func (s *Store) SetPassword(ctx context.Context, accountID, password string) error

SetPassword replaces a hash and transactionally invalidates every existing session for the account.

func (*Store) SetSessionPolicy

func (s *Store) SetSessionPolicy(ctx context.Context, actorKey string, minutes int) ([]string, error)

SetSessionPolicy rechecks administrator authority and changes all still-valid logins atomically. Returned private keys let the HTTP owner cancel any work whose login expired. The policy is read with session rows, not cached.

func (*Store) WithConfirmedAdministrator

func (s *Store) WithConfirmedAdministrator(ctx context.Context, actorKey, password string, write func(*sql.Tx) error) error

WithConfirmedAdministrator binds a host configuration write to a still-live administrator login and the exact password confirmed before acquiring the writer. The callback must use this transaction, never start another one or perform external side effects. Password material stays in the accounts domain.

Jump to

Keyboard shortcuts

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