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
- Variables
- func HashPassword(password string) (string, error)
- func MatchesSessionKey(token, key string) bool
- func ValidatePassword(password string) error
- func VerifyPassword(password, encoded string) (bool, error)
- type Account
- type ControlGrant
- type ControlIdentity
- type RecoveredAccount
- type RecoveryCodes
- type RecoveryStatus
- type Session
- type SessionClient
- type SessionInfo
- type Store
- func (s *Store) Authenticate(ctx context.Context, username, password string) (Account, error)
- func (s *Store) BootstrapAdmin(ctx context.Context, username, password string) (Account, error)
- func (s *Store) CanViewProfile(ctx context.Context, viewer Account, targetAccountID string) (bool, error)
- func (s *Store) ChangeOwnPassword(ctx context.Context, actorKey, currentPassword, newPassword string) ([]string, error)
- func (s *Store) CheckSession(ctx context.Context, key string) (Session, error)
- func (s *Store) ControlGrant(ctx context.Context, accountID string) (*ControlGrant, error)
- func (s *Store) ControlIdentities(ctx context.Context, ownerID, selectedID string) ([]ControlIdentity, error)
- func (s *Store) Create(ctx context.Context, username, password, role string) (Account, error)
- func (s *Store) CreateForSession(ctx context.Context, actorKey, username, password, role string) (Account, error)
- func (s *Store) DeleteProfileImage(ctx context.Context, id string) (Account, error)
- func (s *Store) EnabledCount(ctx context.Context) (int, error)
- func (s *Store) GrantControl(ctx context.Context, administratorID, accountID string, lifetime time.Duration) (*ControlGrant, error)
- func (s *Store) GrantControlForSession(ctx context.Context, actorKey, accountID string, lifetime time.Duration) (*ControlGrant, error)
- func (s *Store) GrantPermanentControl(ctx context.Context, administratorID, accountID string) (*ControlGrant, error)
- func (s *Store) Initialized(ctx context.Context) (bool, error)
- func (s *Store) InspectSession(ctx context.Context, token string) (Session, error)
- func (s *Store) List(ctx context.Context) ([]Account, error)
- func (s *Store) ListOwnSessions(ctx context.Context, actorKey string) ([]SessionInfo, error)
- func (s *Store) LoginWithClient(ctx context.Context, username, password string, client SessionClient) (string, Session, error)
- func (s *Store) NewSession(ctx context.Context, accountID string) (string, Session, error)
- func (s *Store) NewSessionWithClient(ctx context.Context, accountID string, client SessionClient) (string, Session, error)
- func (s *Store) OpenProfileImage(ctx context.Context, id string) (*os.File, error)
- func (s *Store) ProfileImageDir() string
- func (s *Store) RecoverPassword(ctx context.Context, username, code, password string) (RecoveredAccount, error)
- func (s *Store) RecoveryStatus(ctx context.Context, actorKey string) (RecoveryStatus, error)
- func (s *Store) RemoveRecoveryCodes(ctx context.Context, actorKey, password string) error
- func (s *Store) RenameOwnSession(ctx context.Context, actorKey, id, name string) error
- func (s *Store) ReplaceRecoveryCodes(ctx context.Context, actorKey, password string) (RecoveryCodes, error)
- func (s *Store) ResetPasswordForSession(ctx context.Context, actorKey, accountID, password string) ([]string, error)
- func (s *Store) ResolveSession(ctx context.Context, token string) (Session, error)
- func (s *Store) RevokeControl(ctx context.Context, administratorID, accountID string) error
- func (s *Store) RevokeControlForSession(ctx context.Context, actorKey, accountID string) error
- func (s *Store) RevokeOtherSessions(ctx context.Context, actorKey string) ([]string, error)
- func (s *Store) RevokeOwnSession(ctx context.Context, actorKey, id string) (string, error)
- func (s *Store) RevokeSession(ctx context.Context, token string) error
- func (s *Store) SaveProfileImage(ctx context.Context, id string, data []byte) (Account, error)
- func (s *Store) SessionOwnerTx(ctx context.Context, tx *sql.Tx, key string) (string, error)
- func (s *Store) SetControlIdentity(ctx context.Context, token, targetAccountID string) error
- func (s *Store) SetDisabled(ctx context.Context, accountID string, disabled bool) error
- func (s *Store) SetDisabledForSession(ctx context.Context, actorKey, accountID string, disabled bool) ([]string, error)
- func (s *Store) SetPassword(ctx context.Context, accountID, password string) error
- func (s *Store) WithConfirmedAdministrator(ctx context.Context, actorKey, password string, write func(*sql.Tx) error) error
Constants ¶
const ( // ControlRelationshipSelf is the authenticated account itself. ControlRelationshipSelf = "self" // ControlRelationshipLinked is an explicitly active directional link. ControlRelationshipLinked = "linked" )
const ( // MinPasswordCharacters is the minimum accepted Unicode password length. MinPasswordCharacters = 8 // MaxPasswordBytes bounds password-hashing work and request memory. MaxPasswordBytes = 1024 )
const ( // MaxProfileImageBytes bounds an accepted browser-normalized JPEG. MaxProfileImageBytes = 2 << 20 // MaxProfileImageEdge is the largest decoded dimension accepted by the API. MaxProfileImageEdge = 1024 )
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 session not seen by the server. DefaultSessionIdleLimit = 30 * time.Minute // MaxSessionsPerAccount bounds persistent sessions for one account. MaxSessionsPerAccount = 20 )
const MaxRecoveryCodes = 8
MaxRecoveryCodes is also enforced by the datastore's insertion trigger.
const MaxSessionNameRunes = 80
MaxSessionNameRunes bounds optional, informational device names.
Variables ¶
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") )
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") )
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") )
var ErrAdministratorRequired = errors.New("administrator access required")
ErrAdministratorRequired rejects a live login without administrative authority.
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.
var ErrInvalidPassword = errors.New("invalid password")
ErrInvalidPassword marks a password-policy failure without exposing a hash.
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.
Functions ¶
func HashPassword ¶
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 ¶
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 ¶
ValidatePassword applies only safety bounds. MagicHandy deliberately avoids composition rules that encourage predictable substitutions; callers should use a long, unique passphrase.
func VerifyPassword ¶
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"`
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.
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 ¶
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:"-"`
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.
type SessionClient ¶
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"`
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 Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store provides account operations over the process-owned datastore.
func (*Store) Authenticate ¶
Authenticate performs the same Argon2id work for missing, disabled, and existing accounts and returns one generic credential error.
func (*Store) BootstrapAdmin ¶
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 ¶
CheckSession validates a server-side session identity without renewing idle time. Background streams and control watchdogs are observations, not activity.
func (*Store) ControlGrant ¶
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 ¶
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) DeleteProfileImage ¶
DeleteProfileImage returns the account to its generated monogram.
func (*Store) EnabledCount ¶
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 ¶
Initialized reports whether any account exists, including disabled rows.
func (*Store) InspectSession ¶
InspectSession authenticates passive polling without extending idle time.
func (*Store) List ¶
List returns public account metadata. Password hashes never leave this package, even to another backend package.
func (*Store) ListOwnSessions ¶
ListOwnSessions reads one bounded snapshot without extending any idle time.
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 ¶
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 ¶
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 ¶
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 ¶
RecoveryStatus returns the signed-in account's saved-code count, never codes.
func (*Store) RemoveRecoveryCodes ¶
RemoveRecoveryCodes disables offline recovery after fresh password proof.
func (*Store) RenameOwnSession ¶
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) 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 ¶
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 ¶
RevokeControl removes permission without ending the account's read access.
func (*Store) RevokeControlForSession ¶
RevokeControlForSession checks the actor's login in the revocation transaction.
func (*Store) RevokeOtherSessions ¶
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 ¶
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 ¶
RevokeSession invalidates one opaque bearer token. It is idempotent.
func (*Store) SaveProfileImage ¶
SaveProfileImage validates and atomically replaces one account image.
func (*Store) SessionOwnerTx ¶
SessionOwnerTx revalidates an account's session inside a domain write transaction using the shared datastore. It grants no host or control permission.
func (*Store) SetControlIdentity ¶
SetControlIdentity changes only this opaque login session's attribution context. It cannot change authentication role or controller ownership.
func (*Store) SetDisabled ¶
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) SetPassword ¶
SetPassword replaces a hash and transactionally invalidates every existing session for the account.
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.