auth

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: Apache-2.0 Imports: 36 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 auth implements accounts and access control: argon2id passwords with no password rules beyond a length cap, the generated first admin, cookie sessions, invites, password-reset links, roles, login and API rate limiting, and the authentication middleware. It owns its SQL; HTTP handlers live in internal/httpapi.

Index

Constants

View Source
const (
	// AdminPasswordFile is the file in the data directory that holds the
	// first admin's generated password until that password changes.
	AdminPasswordFile = "admin-password.txt"
	// BootstrapAdminUsername is the username of the account BootstrapAdmin
	// creates.
	BootstrapAdminUsername = "admin"
)
View Source
const (
	// DevicePrefixLen is the length of the token prefix shown to identify a
	// device ("bub_" plus four secret characters).
	DevicePrefixLen = 8
	// MaxDevices caps the active device tokens of one user.
	MaxDevices = 25
	// DeviceLastUsedInterval throttles last_used_at writes.
	DeviceLastUsedInterval = time.Minute
)
View Source
const (
	DefaultInviteExpiry = 72 * time.Hour
	MaxInviteExpiry     = 90 * 24 * time.Hour
	MaxInviteUses       = 1000
)

Invite defaults and bounds.

View Source
const (
	ViaCookie = "cookie"
	// ViaBearer is an app token in the Authorization header.
	ViaBearer = "bearer"
)

How a request proved who it is.

View Source
const (
	LoginUserMaxFailures = 5
	LoginIPMaxFailures   = 20
	LoginWindow          = 15 * time.Minute
	APIRatePerSecond     = 20
	APIBurst             = 50

	// SignupIPMaxAttempts is how many sign-up attempts (register and
	// device-register) one IP address may make within SignupWindow.
	SignupIPMaxAttempts = 20
	SignupWindow        = time.Hour
)

Rate limits (plan: REST API, rate limits).

View Source
const (
	// CookieName carries the session token. The __Host- prefix makes
	// browsers require Secure, Path=/ and no Domain.
	CookieName = "__Host-bubbles_session"
	// AbsoluteLifetime is the longest a session lives, however active.
	AbsoluteLifetime = 90 * 24 * time.Hour
	// LastSeenInterval throttles last_seen_at / idle-expiry updates.
	LastSeenInterval = time.Minute

	// SessionWeb is a browser session; SessionHandoff a tray-to-browser one.
	SessionWeb     = "web"
	SessionHandoff = "handoff"
)

Session constants (Locked Decision 2).

View Source
const (
	KindHuman = "human"
	KindApp   = "app"
)

Kinds of user accounts.

View Source
const DefaultMaxConcurrentHashes = 4

DefaultMaxConcurrentHashes bounds simultaneous argon2 computations: each holds MemoryKiB of memory, so a login burst must queue, not allocate.

View Source
const (
	// HandoffTTL is how long a handoff code can be redeemed.
	HandoffTTL = 60 * time.Second
)
View Source
const MaxPasswordLen = 128

MaxPasswordLen is the longest accepted password, in characters (runes).

View Source
const MaxStatusTextChars = 100

MaxStatusTextChars is the longest status text (the users table CHECK).

View Source
const ResetTTL = 24 * time.Hour

ResetTTL is how long a password-reset link stays valid.

View Source
const ViaDevice = "device"

ViaDevice marks a principal that proved itself with a tray device token.

Variables

View Source
var (
	// ErrLastAdmin means the change would leave no active admin.
	ErrLastAdmin = errors.New("at least one active admin account must remain")
	// ErrSelfLockout means an admin tried to demote or deactivate themselves.
	ErrSelfLockout = errors.New("you cannot demote or deactivate your own account")
)

Errors of the admin user operations; the HTTP layer answers 409.

View Source
var (
	// ErrInvalidCredentials is the one answer to every failed login.
	ErrInvalidCredentials = errors.New("invalid username or password")
	// ErrWrongPassword means the current password given to a password
	// change is incorrect.
	ErrWrongPassword = errors.New("current password is incorrect")
	// ErrUsernameTaken means the requested username exists.
	ErrUsernameTaken = errors.New("username is already taken")
	// ErrNameTaken means another active person already has that name.
	ErrNameTaken = errors.New("name is already taken")
	// ErrInviteInvalid means an invite code is unknown, expired, revoked or
	// used up.
	ErrInviteInvalid = errors.New("invite is invalid or has expired")
	// ErrResetInvalid means a password-reset code is unknown, expired or
	// already used.
	ErrResetInvalid = errors.New("password reset link is invalid or has expired")
	// ErrNotFound means the addressed user, session or invite does not exist.
	ErrNotFound = errors.New("not found")
	// ErrRegistrationClosed means open registration is switched off.
	ErrRegistrationClosed = errors.New("registration is closed")
)

Errors returned by Service. Handlers map them to the REST error model.

View Source
var DefaultParams = Params{Time: 3, MemoryKiB: 64 * 1024, Threads: 4, SaltLen: 16, KeyLen: 32}

DefaultParams are the production parameters (Locked Decision 2): t=3, m=64 MiB, p=4, 16-byte salt, 32-byte key.

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

ErrInvalidHash means a stored password hash is not a supported PHC string.

Functions

func ClearCookie

func ClearCookie() *http.Cookie

ClearCookie returns a cookie that deletes the session cookie.

func ErrorFrom

func ErrorFrom(ctx context.Context) error

ErrorFrom returns the infrastructure error (database failure) that kept an authenticator from deciding, or nil. Handlers answer 503/500 for it rather than treating the request as merely anonymous.

func GeneratePassword added in v0.2.0

func GeneratePassword() (string, error)

GeneratePassword returns a random password of 16 characters from passwordAlphabet, grouped 4-4-4-4 with dashes (19 characters in all).

func HashToken

func HashToken(token string) []byte

HashToken returns the SHA-256 of a token; only this hash is stored.

func IPKey

func IPKey(ip string) string

IPKey returns the key an IP limiter uses for a client address. IPv4 (and IPv4-mapped IPv6) addresses are keyed in full. An IPv6 address is keyed by its /64 prefix, since one host usually owns a whole /64 and could otherwise rotate addresses to dodge a per-address limit. Input that does not parse is keyed as given; an empty address has no key.

func Middleware

func Middleware(auths ...Authenticator) func(http.Handler) http.Handler

Middleware loads the principal into the request context: the first authenticator that recognizes the request wins. It never rejects a request; anonymous requests simply carry no principal (handlers decide whether that is acceptable, see UserFrom and ErrorFrom).

func NewCookie

func NewCookie(token string, expires, now time.Time) *http.Cookie

NewCookie returns the session cookie for token, living until expires. Attributes are fixed: Secure, HttpOnly, SameSite=Strict, Path=/ and no Domain (required by the __Host- prefix).

func NewToken

func NewToken() (string, error)

NewToken returns 256 random bits as lower-case base32 (52 characters). It is the format of session tokens, invite codes, reset codes and setup tokens.

func NormalizeUsername

func NormalizeUsername(s string) string

NormalizeUsername lower-cases and trims a username.

func PublicSessionID

func PublicSessionID(idHash []byte) string

PublicSessionID derives the id shown to users from a session hash (its first 16 bytes in hex). It identifies a session in the API without exposing the stored hash itself.

func RetryAfterSeconds

func RetryAfterSeconds(d time.Duration) int

RetryAfterSeconds rounds d up to whole seconds for a Retry-After header (at least 1).

func RevokeDevicesTx

func RevokeDevicesTx(tx *store.Tx, userID string) error

RevokeDevicesTx revokes every active device token of userID and closes their sockets. Password changes and resets call it next to RevokeSessionsTx.

func RevokeSessionsTx

func RevokeSessionsTx(tx *store.Tx, userID string, exceptHash []byte) error

RevokeSessionsTx deletes every session of userID except the one whose hash is exceptHash (empty keeps none), inside tx, and appends a session.revoked event. Services that deactivate users or change passwords call it in their own transaction.

func ValidatePassword

func ValidatePassword(pw string) error

ValidatePassword enforces the password policy: not empty and at most 128 characters.

func WithPrincipal

func WithPrincipal(ctx context.Context, p *Principal) context.Context

WithPrincipal returns ctx carrying p.

Types

type AcceptInviteInput

type AcceptInviteInput struct {
	Code string
	// Name is the person's display name; when set, the handle is derived
	// from it and Username / DisplayName are ignored.
	Name        string
	Username    string
	Password    string
	DisplayName string
	UserAgent   string
	IP          string
}

AcceptInviteInput is the input of AcceptInvite.

type AdminCreateUserInput added in v0.2.0

type AdminCreateUserInput struct {
	Name     string
	Password string
	// Role defaults to member.
	Role Role
}

AdminCreateUserInput is the input of AdminCreateUser.

type AdminUserPatch

type AdminUserPatch struct {
	Role        *Role
	Deactivated *bool
}

AdminUserPatch is a partial change of a human account by an admin.

type Authenticator

type Authenticator interface {
	Authenticate(r *http.Request) (*Principal, error)
}

Authenticator resolves the credentials of a request. It returns (nil, nil) when the request carries none of its credentials or they are not valid, and a non-nil error only for infrastructure failures.

The app token authenticator (internal/apps) returns a Principal with Via == ViaBearer and is passed to Middleware next to CookieAuthenticator.

type BucketLimiter

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

BucketLimiter is a token bucket per key: rate tokens per second up to burst. It is in memory and safe for concurrent use.

func NewAPILimiter

func NewAPILimiter(now func() time.Time) *BucketLimiter

NewAPILimiter returns the per-session API limit: 20 requests per second, burst 50.

func NewBucketLimiter

func NewBucketLimiter(now func() time.Time, ratePerSecond float64, burst int) *BucketLimiter

NewBucketLimiter returns a limiter that refills ratePerSecond tokens per second per key, up to burst. now is the clock (nil means time.Now).

func (*BucketLimiter) Allow

func (b *BucketLimiter) Allow(key string) (bool, time.Duration)

Allow takes one token from key's bucket. When none is left it returns false and the time until one is available.

type ChangePasswordInput

type ChangePasswordInput struct {
	UserID  string
	Current string
	New     string
	// KeepSession is the hash of the caller's own session, which survives.
	KeepSession []byte
	IP          string
}

ChangePasswordInput is the input of ChangePassword.

type CreateInviteInput

type CreateInviteInput struct {
	Role Role
	Note string
	// ExpiresIn defaults to DefaultInviteExpiry.
	ExpiresIn time.Duration
	// MaxUses defaults to 1.
	MaxUses int
}

CreateInviteInput is the input of CreateInvite.

type Device

type Device struct {
	ID         string
	Name       string
	Prefix     string
	Scopes     []string
	CreatedAt  int64
	LastUsedAt int64 // unix ms; 0 = never
}

Device is a registered tray device.

type DeviceGrant

type DeviceGrant struct {
	ID     string
	Name   string
	Scopes []string
}

DeviceGrant is the authority of the device token behind a ViaDevice principal. It is deliberately not a TokenGrant: a device acts as its user (a human), limited by the route allowlist, not by an app's channel list.

type DeviceLoginInput

type DeviceLoginInput struct {
	Username   string
	Password   string
	DeviceName string
	UserAgent  string
	IP         string
}

DeviceLoginInput is the input of DeviceLogin.

type DeviceLoginResult

type DeviceLoginResult struct {
	Token       string
	DeviceID    string
	HandoffCode string
	User        *User
}

DeviceLoginResult is what DeviceLogin hands back; Token is shown once.

type DeviceRegisterInput added in v0.2.0

type DeviceRegisterInput struct {
	Name       string
	Password   string
	DeviceName string
	UserAgent  string
	IP         string
}

DeviceRegisterInput is the input of DeviceRegister.

type FailureLimiter

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

FailureLimiter blocks a key after max failures within a sliding window. It is in memory and safe for concurrent use.

func NewFailureLimiter

func NewFailureLimiter(now func() time.Time, max int, window time.Duration) *FailureLimiter

NewFailureLimiter returns a limiter that blocks a key after max failures within window. now is the clock (nil means time.Now).

func (*FailureLimiter) Blocked

func (l *FailureLimiter) Blocked(key string) (time.Duration, bool)

Blocked reports whether key has used up its failures and, if so, how long until the oldest failure leaves the window.

func (*FailureLimiter) Fail

func (l *FailureLimiter) Fail(key string)

Fail records one failure for key.

func (*FailureLimiter) Reset

func (l *FailureLimiter) Reset(key string)

Reset forgets the failures of key.

type Hasher

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

Hasher computes and verifies argon2id hashes in PHC string format.

func NewHasher

func NewHasher(p Params, maxConcurrent int) *Hasher

NewHasher returns a Hasher that creates hashes with p. At most maxConcurrent computations run at once (0 means DefaultMaxConcurrentHashes).

func (*Hasher) Hash

func (h *Hasher) Hash(ctx context.Context, password string) (string, error)

Hash returns the PHC string of password with a fresh random salt: $argon2id$v=19$m=65536,t=3,p=4$<salt>$<key>

func (*Hasher) NeedsRehash

func (h *Hasher) NeedsRehash(encoded string) bool

NeedsRehash reports whether encoded was made with different parameters than this Hasher creates (or cannot be parsed).

func (*Hasher) Verify

func (h *Hasher) Verify(ctx context.Context, password, encoded string) (bool, error)

Verify reports whether password matches encoded, comparing in constant time with the parameters stored in encoded.

type Invite

type Invite struct {
	ID        string
	CreatedBy string
	Role      Role
	Note      string
	ExpiresAt int64 // unix ms
	MaxUses   int
	UseCount  int
	RevokedAt *int64
	CreatedAt int64
}

Invite is one row of the invites table; the code itself is never stored.

type InviteStatus

type InviteStatus struct {
	Valid bool
	Role  Role
}

InviteStatus describes what an invite code currently allows.

type LoginAttempt

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

LoginAttempt is an attempt reserved by LoginLimiter.Begin before its password is checked. The reservation counts as a failure from the start. Succeed settles it as a success, Abort undoes it, and leaving it alone keeps the failure.

func (*LoginAttempt) Abort

func (a *LoginAttempt) Abort()

Abort settles the attempt as if it never happened: both slots are refunded. Use it when no credential check ran (cancelled request, lookup error) or when the credentials were right but the request was refused for another reason. It does nothing after Succeed or Abort.

func (*LoginAttempt) Succeed

func (a *LoginAttempt) Succeed()

Succeed settles the attempt as a success: the key's failures are cleared and the IP slot is refunded. It does nothing after Succeed or Abort.

type LoginInput

type LoginInput struct {
	Username  string
	Password  string
	UserAgent string
	IP        string
	// ReplaceToken is the session token the browser presented, if any. It
	// is revoked in the same transaction (rotation on login).
	ReplaceToken string
}

LoginInput is the input of Login.

type LoginLimiter

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

LoginLimiter combines the per-username and per-IP failure limits.

func NewLoginLimiter

func NewLoginLimiter(now func() time.Time) *LoginLimiter

NewLoginLimiter returns the production limits: 5 failures per username and 20 per IP address within 15 minutes.

func (*LoginLimiter) Begin

func (l *LoginLimiter) Begin(key, ip string) (*LoginAttempt, time.Duration, bool)

Begin reserves one attempt for key (a normalized username, or another per-account key) from ip, before any password is checked. The limit check and the reservation happen under one lock, so concurrent attempts cannot all pass the check before one of them is recorded. When either key is at its limit Begin reserves nothing and returns the wait.

func (*LoginLimiter) Check

func (l *LoginLimiter) Check(username, ip string) (time.Duration, bool)

Check reports whether a login attempt for username from ip is blocked and how long the caller must wait. It reserves nothing: code that verifies a password must use Begin, or a burst of concurrent attempts can all pass.

func (*LoginLimiter) Fail

func (l *LoginLimiter) Fail(username, ip string)

Fail records a failed attempt against username and ip. Prefer Begin when a password is being checked: Fail does not stop a burst of attempts that are already in flight.

func (*LoginLimiter) Succeed

func (l *LoginLimiter) Succeed(username string)

Succeed clears the failures of username (the IP count is kept).

type Options

type Options struct {
	// DB is the store; required.
	DB *store.DB
	// Settings supplies session_idle_days, open_registration and
	// instance_name; required.
	Settings *settings.Store
	// DataDir holds admin-password.txt; BootstrapAdmin skips the file when
	// it is empty.
	DataDir string
	// Now is the clock; nil means time.Now. It should be the clock the store
	// uses, so session expiry and created_at agree.
	Now func() time.Time
	// Logger receives non-fatal errors; nil discards them.
	Logger *slog.Logger
	// Params are the argon2id parameters for new hashes; the zero value
	// means DefaultParams. Tests inject cheap ones.
	Params Params
	// MaxConcurrentHashes bounds simultaneous argon2 computations; 0 means
	// DefaultMaxConcurrentHashes.
	MaxConcurrentHashes int
	// OnBootstrap runs inside the bootstrap transaction after the first admin
	// exists; the chat service uses it to create #general. An error aborts
	// the bootstrap.
	OnBootstrap func(ctx context.Context, tx *store.Tx, adminID string) error
	// OnUserCreated runs inside the transaction that creates a human account:
	// the bootstrap admin (after OnBootstrap), an invite redemption and a registration.
	// An error aborts that transaction. nil means no-op.
	OnUserCreated func(ctx context.Context, tx *store.Tx, userID string) error
	// LoginLimiter and APILimiter replace the default rate limiters.
	LoginLimiter *LoginLimiter
	APILimiter   *BucketLimiter
	// RegisterLimiter replaces the per-IP limit on sign-up attempts (register
	// and device-register); nil means 20 attempts per IP per hour.
	RegisterLimiter *FailureLimiter
	// AdminPassword fixes the password BootstrapAdmin sets instead of a
	// generated one. Tests and the e2e build use it; empty means generate.
	AdminPassword string
}

Options configure a Service.

type Params

type Params struct {
	Time      uint32 // passes
	MemoryKiB uint32
	Threads   uint8
	SaltLen   int
	KeyLen    uint32
}

Params are argon2id parameters.

type PolicyError

type PolicyError struct{ Reason string }

PolicyError is returned by ValidatePassword; Reason is safe to show.

func (*PolicyError) Error

func (e *PolicyError) Error() string

type Principal

type Principal struct {
	User *User
	// Session is the cookie session; nil for bearer-token principals.
	Session *Session
	// Via is ViaCookie or ViaBearer.
	Via string
	// Token is what an app token grants; nil for cookie principals.
	Token *TokenGrant
	// Device is what a tray device token grants; nil unless Via is ViaDevice.
	Device *DeviceGrant
}

Principal is an authenticated request identity.

func PrincipalFrom

func PrincipalFrom(ctx context.Context) *Principal

PrincipalFrom returns the request's principal, or nil when anonymous.

type ProfileInput

type ProfileInput struct {
	DisplayName *string
	StatusText  *string
	// SetAvatar makes AvatarFileID apply; a nil AvatarFileID then removes
	// the avatar.
	SetAvatar    bool
	AvatarFileID *string
	// Prefs replaces the whole preferences object; nil leaves it alone.
	Prefs json.RawMessage
}

ProfileInput is a partial update of the caller's own profile: nil / false fields are left alone.

type RateLimitedError

type RateLimitedError struct{ RetryAfter time.Duration }

RateLimitedError carries the wait before the caller may retry.

func (*RateLimitedError) Error

func (e *RateLimitedError) Error() string

type RegisterInput

type RegisterInput struct {
	// Name is the person's display name; the handle is derived from it.
	Name      string
	Password  string
	UserAgent string
	IP        string
}

RegisterInput is the input of Register.

type Role

type Role string

Role is a user's permission level.

const (
	RoleAdmin  Role = "admin"
	RoleMember Role = "member"
	RoleGuest  Role = "guest"
)

Roles, from most to least privileged.

func ParseRole

func ParseRole(s string) (Role, error)

ParseRole converts s to a Role.

func (Role) AtLeast

func (r Role) AtLeast(min Role) bool

AtLeast reports whether r grants at least the rights of min.

func (Role) IsAdmin

func (r Role) IsAdmin() bool

IsAdmin reports whether r is the admin role.

func (Role) Valid

func (r Role) Valid() bool

Valid reports whether r is one of the three roles.

type Service

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

Service is the auth domain service.

func New

func New(o Options) (*Service, error)

New returns a Service.

func (*Service) APILimiter

func (s *Service) APILimiter() *BucketLimiter

APILimiter returns the per-session API rate limiter (20 req/s, burst 50).

func (*Service) AcceptInvite

func (s *Service) AcceptInvite(ctx context.Context, in AcceptInviteInput) (*SessionResult, error)

AcceptInvite redeems one use of an invite: it creates the account with the invite's role and starts a session, in one transaction. A bad code is ErrInviteInvalid; a taken username is ErrUsernameTaken (and consumes no use).

func (*Service) AdminCreateUser added in v0.2.0

func (s *Service) AdminCreateUser(ctx context.Context, actor audit.Actor, in AdminCreateUserInput) (*User, error)

AdminCreateUser creates a human account for an admin ("Add person"). It is not gated by the sign-up window or the sign-up rate limit. A taken name is ErrNameTaken.

func (*Service) AdminUpdateUser

func (s *Service) AdminUpdateUser(ctx context.Context, actor audit.Actor, id string, p AdminUserPatch) (*User, error)

AdminUpdateUser changes the role and/or the deactivated state of a human account. Deactivation ends every session, device token and app token of the user in the same transaction and appends user.updated {deactivated:true}, which makes the realtime layer close the user's sockets. A role change appends user.updated too. Nothing changes if the patch is a no-op.

func (*Service) Authenticate

func (s *Service) Authenticate(ctx context.Context, token string) (*Principal, error)

Authenticate resolves a session token to its session and user. Unknown, expired and deactivated-user sessions return ErrNotFound. A valid session has last_seen_at and the idle expiry moved forward at most once per LastSeenInterval.

func (*Service) BootstrapAdmin added in v0.2.0

func (s *Service) BootstrapAdmin(ctx context.Context) (string, error)

BootstrapAdmin creates the first account on an empty database: user "admin" (display name "Admin", role admin) with a generated password. In one transaction it runs the OnBootstrap and OnUserCreated hooks and writes the setup.complete audit row (console actor); afterwards it writes the password to <data>/admin-password.txt (0600) and returns it. With any user present it does nothing and returns "".

func (*Service) ChangePassword

func (s *Service) ChangePassword(ctx context.Context, in ChangePasswordInput) error

ChangePassword replaces a user's password after verifying the current one and revokes every other session of the user (and any pending reset link). A wrong current password is ErrWrongPassword and counts as a failed login for rate limiting; a weak new password is a *ValidationError.

func (*Service) CookieAuthenticator

func (s *Service) CookieAuthenticator() Authenticator

CookieAuthenticator returns the Authenticator for the session cookie. A request carrying an Authorization header is left to the bearer authenticators: its cookie, if any, is ignored.

func (*Service) CountUsers

func (s *Service) CountUsers(ctx context.Context) (int, error)

CountUsers returns the number of accounts.

func (*Service) CreateInvite

func (s *Service) CreateInvite(ctx context.Context, actor audit.Actor, in CreateInviteInput) (*Invite, string, error)

CreateInvite stores a new invite and returns it with its one-time code, which cannot be recovered afterwards.

func (*Service) CreateReset

func (s *Service) CreateReset(ctx context.Context, actor audit.Actor, userID string) (string, time.Time, error)

CreateReset creates a one-time password-reset link for userID and returns its code and expiry. Earlier unused links of that user stop working. The code cannot be recovered afterwards.

func (*Service) DeviceAuthenticator

func (s *Service) DeviceAuthenticator() Authenticator

DeviceAuthenticator returns the Authenticator for tray device tokens ("Authorization: Bearer bub_..."). Tokens it does not know fall through to the next authenticator (app tokens share the prefix).

func (*Service) DeviceLogin

func (s *Service) DeviceLogin(ctx context.Context, in DeviceLoginInput) (*DeviceLoginResult, error)

DeviceLogin verifies the credentials exactly like Login (same rate limiter reservation, lockout and audit of failures) and registers a tray device: it returns a new device token and a one-time handoff code.

func (*Service) DeviceRegister added in v0.2.0

func (s *Service) DeviceRegister(ctx context.Context, in DeviceRegisterInput) (*DeviceLoginResult, error)

DeviceRegister creates a member account like Register (same window, same per-IP limit, unique name) and registers a tray device for it in the same transaction: it returns the new device token and a one-time handoff code.

func (*Service) HashPassword

func (s *Service) HashPassword(ctx context.Context, password string) (string, error)

HashPassword hashes a password that already passed ValidatePassword.

func (*Service) IssueHandoff

func (s *Service) IssueHandoff(p *Principal) (string, error)

IssueHandoff returns a new one-time code for the device behind p.

func (*Service) ListDevices

func (s *Service) ListDevices(ctx context.Context, userID string) ([]Device, error)

ListDevices returns the active device tokens of userID, newest first.

func (*Service) ListInvites

func (s *Service) ListInvites(ctx context.Context) ([]Invite, error)

ListInvites returns every invite, newest first.

func (*Service) ListSessions

func (s *Service) ListSessions(ctx context.Context, userID string) ([]Session, error)

ListSessions returns userID's live sessions, most recently used first.

func (*Service) ListUsers

func (s *Service) ListUsers(ctx context.Context) ([]User, error)

ListUsers returns every account ordered by creation.

func (*Service) Login

func (s *Service) Login(ctx context.Context, in LoginInput) (*SessionResult, error)

Login verifies the credentials and starts a new session. Every failure returns ErrInvalidCredentials, whatever the cause (unknown user, wrong password, deactivated, app account), after the same amount of hashing. Failures are rate limited per username and per IP; a blocked caller gets *RateLimitedError without any password check.

func (*Service) Logout

func (s *Service) Logout(ctx context.Context, token, ip string) error

Logout revokes the session for token. An unknown token is not an error.

func (*Service) LookupInvite

func (s *Service) LookupInvite(ctx context.Context, code string) (InviteStatus, error)

LookupInvite reports whether code is a usable invite (known, not revoked, not expired, not used up) and the role it grants.

func (*Service) Now added in v0.2.0

func (s *Service) Now() time.Time

Now returns the service clock; sign-up deadlines are judged against it.

func (*Service) PurgeExpired

func (s *Service) PurgeExpired(ctx context.Context) (int64, error)

PurgeExpired deletes expired sessions and password-reset rows that expired more than a week ago, and returns how many sessions were removed.

func (*Service) RedeemHandoff

func (s *Service) RedeemHandoff(ctx context.Context, code, userAgent, ip, replaceToken string) (*SessionResult, error)

RedeemHandoff consumes a handoff code and starts a web session for the user it was issued to (same cookie attributes and rotation as Login). Unknown, expired, already used codes, and codes whose device was revoked in the meantime, are ErrNotFound.

func (*Service) Register

func (s *Service) Register(ctx context.Context, in RegisterInput) (*SessionResult, error)

Register creates a member account while sign-up is open (switched on and inside its window; ErrRegistrationClosed otherwise) and starts a session. Every attempt counts against the per-IP limit.

func (*Service) ResetPassword

func (s *Service) ResetPassword(ctx context.Context, code, newPassword, ip string) error

ResetPassword sets a new password using a reset code. The code is single use. All of the user's sessions end and the user must sign in again. An unusable code is ErrResetInvalid; a weak password is a *ValidationError and leaves the code usable.

func (*Service) RevokeAllSessions

func (s *Service) RevokeAllSessions(ctx context.Context, actor audit.Actor, userID string) error

RevokeAllSessions ends every session and device token of the human user userID (their open sockets close) and audits it.

func (*Service) RevokeDevice

func (s *Service) RevokeDevice(ctx context.Context, actor audit.Actor, userID, deviceID string) error

RevokeDevice revokes one of userID's devices and closes its sockets. Another user's device is ErrNotFound; revoking twice is a no-op.

func (*Service) RevokeInvite

func (s *Service) RevokeInvite(ctx context.Context, actor audit.Actor, id string) error

RevokeInvite makes an invite unusable. Revoking twice keeps the first revocation time; an unknown id is ErrNotFound.

func (*Service) RevokeSession

func (s *Service) RevokeSession(ctx context.Context, actor audit.Actor, userID, publicID string) error

RevokeSession ends one of userID's sessions by its public id; another user's session is ErrNotFound.

func (*Service) Settings

func (s *Service) Settings() *settings.Store

Settings returns the settings store the service reads.

func (*Service) UpdateProfile

func (s *Service) UpdateProfile(ctx context.Context, userID string, in ProfileInput) (*User, error)

UpdateProfile changes the display name, status text, avatar and preferences of userID and returns the updated account. The avatar must be an image file the user uploaded. Rejected input is a *ValidationError. When something changed it appends a user.updated event in the same transaction.

func (*Service) UserByID

func (s *Service) UserByID(ctx context.Context, id string) (*User, error)

UserByID returns the user, or ErrNotFound.

func (*Service) UserByUsername

func (s *Service) UserByUsername(ctx context.Context, username string) (*User, error)

UserByUsername returns the user (case-insensitive), or ErrNotFound.

func (*Service) VerifyPassword

func (s *Service) VerifyPassword(ctx context.Context, userID, password string) error

VerifyPassword re-checks the password of an active account before a destructive action (reset). A wrong password, an unknown or deactivated account and an account without a password are all ErrWrongPassword; each costs one full argon2id comparison.

type Session

type Session struct {
	// ID is PublicSessionID(IDHash).
	ID            string
	IDHash        []byte
	UserID        string
	Kind          string
	CreatedAt     int64 // unix ms
	LastSeenAt    int64
	IdleExpiresAt int64
	AbsExpiresAt  int64
	UserAgent     string
	IP            string
}

Session is one row of the sessions table.

func (*Session) ExpiresAt

func (s *Session) ExpiresAt() time.Time

ExpiresAt is the absolute expiry as a time.

type SessionResult

type SessionResult struct {
	// Token is the cookie value; it is never stored.
	Token   string
	User    *User
	Session Session
}

SessionResult is returned by every call that starts a session.

type TokenGrant

type TokenGrant struct {
	// ID is the token id (not the secret).
	ID    string
	AppID string
	// Scopes are the scopes the token carries.
	Scopes []string
	// ChannelIDs is the token's channel allowlist; nil means every channel
	// the app's bot is a member of.
	ChannelIDs []string
	// ExpiresAt is the token's expiry in unix ms; 0 means it never expires.
	ExpiresAt int64
}

TokenGrant is the authority of the app token behind a ViaBearer principal.

type User

type User struct {
	ID            string
	Username      string
	DisplayName   string
	Kind          string
	Role          Role
	AvatarFileID  *string
	StatusText    string
	Prefs         json.RawMessage
	MustChangePW  bool
	CreatedAt     int64 // unix ms
	DeactivatedAt *int64
}

User is an account row without its password hash.

func UserFrom

func UserFrom(ctx context.Context) *User

UserFrom returns the authenticated user of the request, or nil.

func (*User) Active

func (u *User) Active() bool

Active reports whether the account may sign in.

type ValidationError

type ValidationError struct{ Fields map[string]string }

ValidationError lists the request fields that were rejected and why.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Jump to

Keyboard shortcuts

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