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
- Variables
- func ClearCookie() *http.Cookie
- func ErrorFrom(ctx context.Context) error
- func GeneratePassword() (string, error)
- func HashToken(token string) []byte
- func IPKey(ip string) string
- func Middleware(auths ...Authenticator) func(http.Handler) http.Handler
- func NewCookie(token string, expires, now time.Time) *http.Cookie
- func NewToken() (string, error)
- func NormalizeUsername(s string) string
- func PublicSessionID(idHash []byte) string
- func RetryAfterSeconds(d time.Duration) int
- func RevokeDevicesTx(tx *store.Tx, userID string) error
- func RevokeSessionsTx(tx *store.Tx, userID string, exceptHash []byte) error
- func ValidatePassword(pw string) error
- func WithPrincipal(ctx context.Context, p *Principal) context.Context
- type AcceptInviteInput
- type AdminCreateUserInput
- type AdminUserPatch
- type Authenticator
- type BucketLimiter
- type ChangePasswordInput
- type CreateInviteInput
- type Device
- type DeviceGrant
- type DeviceLoginInput
- type DeviceLoginResult
- type DeviceRegisterInput
- type FailureLimiter
- type Hasher
- type Invite
- type InviteStatus
- type LoginAttempt
- type LoginInput
- type LoginLimiter
- type Options
- type Params
- type PolicyError
- type Principal
- type ProfileInput
- type RateLimitedError
- type RegisterInput
- type Role
- type Service
- func (s *Service) APILimiter() *BucketLimiter
- func (s *Service) AcceptInvite(ctx context.Context, in AcceptInviteInput) (*SessionResult, error)
- func (s *Service) AdminCreateUser(ctx context.Context, actor audit.Actor, in AdminCreateUserInput) (*User, error)
- func (s *Service) AdminUpdateUser(ctx context.Context, actor audit.Actor, id string, p AdminUserPatch) (*User, error)
- func (s *Service) Authenticate(ctx context.Context, token string) (*Principal, error)
- func (s *Service) BootstrapAdmin(ctx context.Context) (string, error)
- func (s *Service) ChangePassword(ctx context.Context, in ChangePasswordInput) error
- func (s *Service) CookieAuthenticator() Authenticator
- func (s *Service) CountUsers(ctx context.Context) (int, error)
- func (s *Service) CreateInvite(ctx context.Context, actor audit.Actor, in CreateInviteInput) (*Invite, string, error)
- func (s *Service) CreateReset(ctx context.Context, actor audit.Actor, userID string) (string, time.Time, error)
- func (s *Service) DeviceAuthenticator() Authenticator
- func (s *Service) DeviceLogin(ctx context.Context, in DeviceLoginInput) (*DeviceLoginResult, error)
- func (s *Service) DeviceRegister(ctx context.Context, in DeviceRegisterInput) (*DeviceLoginResult, error)
- func (s *Service) HashPassword(ctx context.Context, password string) (string, error)
- func (s *Service) IssueHandoff(p *Principal) (string, error)
- func (s *Service) ListDevices(ctx context.Context, userID string) ([]Device, error)
- func (s *Service) ListInvites(ctx context.Context) ([]Invite, error)
- func (s *Service) ListSessions(ctx context.Context, userID string) ([]Session, error)
- func (s *Service) ListUsers(ctx context.Context) ([]User, error)
- func (s *Service) Login(ctx context.Context, in LoginInput) (*SessionResult, error)
- func (s *Service) Logout(ctx context.Context, token, ip string) error
- func (s *Service) LookupInvite(ctx context.Context, code string) (InviteStatus, error)
- func (s *Service) Now() time.Time
- func (s *Service) PurgeExpired(ctx context.Context) (int64, error)
- func (s *Service) RedeemHandoff(ctx context.Context, code, userAgent, ip, replaceToken string) (*SessionResult, error)
- func (s *Service) Register(ctx context.Context, in RegisterInput) (*SessionResult, error)
- func (s *Service) ResetPassword(ctx context.Context, code, newPassword, ip string) error
- func (s *Service) RevokeAllSessions(ctx context.Context, actor audit.Actor, userID string) error
- func (s *Service) RevokeDevice(ctx context.Context, actor audit.Actor, userID, deviceID string) error
- func (s *Service) RevokeInvite(ctx context.Context, actor audit.Actor, id string) error
- func (s *Service) RevokeSession(ctx context.Context, actor audit.Actor, userID, publicID string) error
- func (s *Service) Settings() *settings.Store
- func (s *Service) UpdateProfile(ctx context.Context, userID string, in ProfileInput) (*User, error)
- func (s *Service) UserByID(ctx context.Context, id string) (*User, error)
- func (s *Service) UserByUsername(ctx context.Context, username string) (*User, error)
- func (s *Service) VerifyPassword(ctx context.Context, userID, password string) error
- type Session
- type SessionResult
- type TokenGrant
- type User
- type ValidationError
Constants ¶
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" )
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 )
const ( DefaultInviteExpiry = 72 * time.Hour MaxInviteExpiry = 90 * 24 * time.Hour MaxInviteUses = 1000 )
Invite defaults and bounds.
const ( ViaCookie = "cookie" // ViaBearer is an app token in the Authorization header. ViaBearer = "bearer" )
How a request proved who it is.
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).
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).
const ( KindHuman = "human" KindApp = "app" )
Kinds of user accounts.
const DefaultMaxConcurrentHashes = 4
DefaultMaxConcurrentHashes bounds simultaneous argon2 computations: each holds MemoryKiB of memory, so a login burst must queue, not allocate.
const ( // HandoffTTL is how long a handoff code can be redeemed. HandoffTTL = 60 * time.Second )
const MaxPasswordLen = 128
MaxPasswordLen is the longest accepted password, in characters (runes).
const MaxStatusTextChars = 100
MaxStatusTextChars is the longest status text (the users table CHECK).
const ResetTTL = 24 * time.Hour
ResetTTL is how long a password-reset link stays valid.
const ViaDevice = "device"
ViaDevice marks a principal that proved itself with a tray device token.
Variables ¶
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.
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.
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.
var ErrInvalidHash = errors.New("invalid password hash")
ErrInvalidHash means a stored password hash is not a supported PHC string.
Functions ¶
func ClearCookie ¶
ClearCookie returns a cookie that deletes the session cookie.
func ErrorFrom ¶
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
GeneratePassword returns a random password of 16 characters from passwordAlphabet, grouped 4-4-4-4 with dashes (19 characters in all).
func IPKey ¶
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 ¶
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 ¶
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 ¶
NormalizeUsername lower-cases and trims a username.
func PublicSessionID ¶
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 ¶
RetryAfterSeconds rounds d up to whole seconds for a Retry-After header (at least 1).
func RevokeDevicesTx ¶
RevokeDevicesTx revokes every active device token of userID and closes their sockets. Password changes and resets call it next to RevokeSessionsTx.
func RevokeSessionsTx ¶
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 ¶
ValidatePassword enforces the password policy: not empty and at most 128 characters.
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 ¶
AdminUserPatch is a partial change of a human account by an admin.
type Authenticator ¶
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).
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 ¶
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 ¶
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 ¶
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 ¶
NewHasher returns a Hasher that creates hashes with p. At most maxConcurrent computations run at once (0 means DefaultMaxConcurrentHashes).
func (*Hasher) Hash ¶
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 ¶
NeedsRehash reports whether encoded was made with different parameters than this Hasher creates (or cannot be parsed).
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 ¶
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 ¶
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 ¶
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.
Roles, from most to least privileged.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service is the auth domain 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 ¶
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
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 ¶
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 ¶
HashPassword hashes a password that already passed ValidatePassword.
func (*Service) IssueHandoff ¶
IssueHandoff returns a new one-time code for the device behind p.
func (*Service) ListDevices ¶
ListDevices returns the active device tokens of userID, newest first.
func (*Service) ListInvites ¶
ListInvites returns every invite, newest first.
func (*Service) ListSessions ¶
ListSessions returns userID's live sessions, most recently used first.
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) LookupInvite ¶
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
Now returns the service clock; sign-up deadlines are judged against it.
func (*Service) PurgeExpired ¶
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 ¶
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 ¶
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 ¶
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) UpdateProfile ¶
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) UserByUsername ¶
UserByUsername returns the user (case-insensitive), or ErrNotFound.
func (*Service) VerifyPassword ¶
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.
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.
type ValidationError ¶
ValidationError lists the request fields that were rejected and why.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string