auth

package
v0.8.0-alpha Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: AGPL-3.0 Imports: 25 Imported by: 0

Documentation

Overview

Package auth provides users, password hashing and session tokens.

Index

Constants

View Source
const (
	KindAdult = "adult"
	KindKids  = "kids"
	KindGuest = "guest"
)

Kinds of accounts.

View Source
const (
	MinPassword = 8
	MinPIN      = 4
)

Shortest passwords for new ones (those set earlier keep working): a full account's password protects everything; a Kids or Guest profile's is a PIN to keep siblings apart.

View Source
const CookieName = "wms_token"
View Source
const MaxDisplayName = 60

MaxDisplayName is the longest profile name, in characters.

View Source
const PlainAwayTTL = 24 * time.Hour

PlainAwayTTL is the longest a session lasts once its token has crossed the internet unencrypted: whoever read it on the way can use it only this long.

View Source
const (

	// StreamTokenTTL is long enough for a long film with a pause in it. A
	// player that outlasts it gets 401 and opens the playlist again.
	StreamTokenTTL = 6 * time.Hour
)

Stream tokens keep a session's token out of HLS playlists. A player that had to put its token in a playlist's address can't send one with the segments either, so the playlist names them with a stream token: it opens that one stream, only for reading, for a few hours, and only while the session it came from lasts, so a playlist in a player's cache or a log is worth little.

Variables

View Source
var (
	AvatarNames   = []string{"star", "heart", "moon", "sun", "bolt", "diamond", "crown", "flower", "music", "planet", "paw", "tree", "rocket", "gamepad", "book"}
	AvatarColours = []string{"red", "orange", "yellow", "green", "teal", "blue", "purple", "pink"}
)

SetShowUsername chooses which name the corner of the screen shows. Avatars a profile can choose from, and the colours behind them. The apps draw them; the server only keeps the choice, so no picture is ever uploaded.

View Source
var (
	// ErrCodeNeeded: the password was right, and the account also wants a code.
	ErrCodeNeeded = errors.New("Enter the 6-digit code from your authenticator app.")
	// ErrCodeWrong: the code was wrong or has already been used.
	ErrCodeWrong = errors.New("That code isn't right, or it has already been used.")
)
View Source
var ErrInvalid = errors.New("invalid name or password")
View Source
var ErrNoAccount = errors.New("no account with that name")

ErrNoAccount: nobody signs in with that name.

Functions

func CheckSecret

func CheckSecret(hash, secret string) bool

CheckSecret reports whether secret is what hash was made from. An empty hash matches nothing, and takes as long to say so.

func CleanAvatar

func CleanAvatar(v string) (string, error)

CleanAvatar checks a choice of avatar: "name:colour", or "" for the initial.

func ClearTwoFactorByName

func ClearTwoFactorByName(ctx context.Context, d *db.DB, name string) error

ClearTwoFactorByName is the way back for an owner who lost both their phone and their recovery codes (`wittymediaserver reset-2fa`, on the server itself).

func CurrentCode

func CurrentCode(secret string) string

CurrentCode is the code an authenticator app would show right now.

func HashSecret

func HashSecret(secret string) (string, error)

HashSecret scrambles a short secret that isn't an account's password (the parents' PIN) the way passwords are, so the database never holds it.

func IsStreamToken

func IsStreamToken(tok string) bool

IsStreamToken tells stream tokens from session tokens.

func MinimumPasswordFor

func MinimumPasswordFor(kind string) int

MinimumPasswordFor is the shortest password an account of this kind may be given.

func QuickHashesForTests

func QuickHashesForTests()

QuickHashesForTests makes password hashes cheap, for test programs that make hundreds of accounts: at the real cost, hashing is most of internal/server's test time. It refuses to run outside a test program, where it would weaken every password set after it.

func SessionID

func SessionID(token string) string

SessionID is the public name of a token.

func StreamToken

func StreamToken(session, scope string, ttl time.Duration) (string, time.Time)

StreamToken makes a token from a session's token for one scope.

func TemporaryPassword

func TemporaryPassword() (string, error)

TemporaryPassword makes a random password of 20 characters, about 115 bits.

func TokenFrom

func TokenFrom(r *http.Request) string

TokenFrom returns the token a request names most explicitly: the Authorization header, X-WMS-Token, the ?token= of a media address, then the cookie.

func Tokens

func Tokens(r *http.Request) []string

Tokens lists every token a request carries, most explicit first. Browsers share cookies between servers on one machine (ports don't separate them), so a request can carry another server's, or an expired, cookie beside its own valid token.

func WeakPassword

func WeakPassword(name, password string) bool

WeakPassword says whether a password would fall quickly to guessing over the internet. It is deliberately simple: short, a common one, based on the account's name, all digits, or nearly the same character over and over.

Types

type RecoverableAccount

type RecoverableAccount struct {
	Name      string
	Kind      string
	IsAdmin   bool
	TwoFactor bool
}

RecoverableAccount is one account as the command line lists it.

func RecoverPassword

func RecoverPassword(ctx context.Context, d *db.DB, name, password string) (*RecoverableAccount, error)

RecoverPassword gives an account a new password and signs it out everywhere, in one step: someone who got hold of the old password or a device loses it here too. Two-factor sign-in stays as it was, which ClearTwoFactorByName is for.

func RecoverableAccounts

func RecoverableAccounts(ctx context.Context, d *db.DB) ([]RecoverableAccount, error)

RecoverableAccounts lists every account, administrators first.

type Service

type Service struct {
	DB *db.DB

	// OnEnd, when set, is told of every sign-in that is ended on purpose: signing
	// out, switching profile, "sign out everywhere", a new password, an account
	// deleted. The server uses it to end what that sign-in had open (streams that
	// would otherwise only notice at their next look). It is called after the
	// sign-in is gone from the database, without any lock held, and must not block.
	// A sign-in that merely runs out of time is not announced: whatever it has
	// open notices by itself.
	OnEnd func(SessionEnd)
	// contains filtered or unexported fields
}

func (*Service) AdminsWithoutTwoFactor

func (s *Service) AdminsWithoutTwoFactor(ctx context.Context) int

AdminsWithoutTwoFactor names administrators who only have a password.

func (*Service) CheckCode

func (s *Service) CheckCode(ctx context.Context, id int64, code string) bool

CheckCode reports whether code is valid for the account: a code from the authenticator app (each usable once), or an unused recovery code (used up by this call).

func (*Service) CheckPassword

func (s *Service) CheckPassword(ctx context.Context, id int64, password string) bool

CheckPassword reports whether password is the account's current one.

func (*Service) CheckTwoFactor

func (s *Service) CheckTwoFactor(ctx context.Context, u *User, code string) bool

CheckTwoFactor is the second step of a sensitive change: true when the account has none, or code is right.

func (*Service) ClearPassword

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

ClearPassword lets a Kids or Guest profile sign in without one.

func (*Service) ConfirmTwoFactor

func (s *Service) ConfirmTwoFactor(ctx context.Context, id int64, code string) ([]string, error)

ConfirmTwoFactor turns two-factor sign-in on after seeing one working code, and returns the recovery codes (shown once, stored only as hashes).

func (*Service) CreateProfile

func (s *Service) CreateProfile(ctx context.Context, name, password, kind string, admin bool, restrictions string) (*User, error)

CreateProfile adds an account of a kind. Kids and Guest profiles may have no password; adults always need one.

func (*Service) CreateUser

func (s *Service) CreateUser(ctx context.Context, name, password string, admin bool) (*User, error)

func (*Service) DeleteUser

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

func (*Service) DisableTwoFactor

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

DisableTwoFactor turns it off and forgets the secret and recovery codes.

func (*Service) EndPlainAway

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

EndPlainAway signs out every session MarkPlainAway marked, and says how many.

func (*Service) EndSession

func (s *Service) EndSession(ctx context.Context, userID int64, id string) (bool, error)

EndSession signs one device out. userID limits it to that account's sessions (0 = any account's, for the administrator). It reports whether there was such a session.

func (*Service) EndSessions

func (s *Service) EndSessions(ctx context.Context, id int64, keep string) error

EndSessions signs the account out everywhere except the session keep (after a password change, so a stolen session stops working).

func (*Service) HashStoredTokens

func (s *Service) HashStoredTokens(ctx context.Context) error

HashStoredTokens converts sessions saved before tokens were hashed, so those sign-ins keep working. It runs at start-up.

func (*Service) IssueSession

func (s *Service) IssueSession(ctx context.Context, userID int64, device string) (string, *User, error)

IssueSession signs an account in on a device that proved itself some other way than a password (TV pairing, approved by someone already signed in).

func (*Service) Login

func (s *Service) Login(ctx context.Context, name, password, device string, allowNoPassword bool) (string, *User, error)

Login verifies credentials and issues a token. allowNoPassword permits password-free Kids/Guest profiles (the server only allows it on the home network); adults always need their password.

func (*Service) LoginCode

func (s *Service) LoginCode(ctx context.Context, name, password, code, device string, allowNoPassword bool) (string, *User, error)

LoginCode is Login with the code of an account that has two-factor sign-in. Whether an account has it is only revealed after the right password.

func (*Service) Logout

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

Logout revokes a token.

func (*Service) MarkPlainAway

func (s *Service) MarkPlainAway(ctx context.Context, token string) bool

MarkPlainAway notes that a session's token was just sent or used without encryption from away from home, and cuts its life to PlainAwayTTL. It says whether the session wasn't marked before, so the first time can be logged.

func (*Service) NoAccounts

func (s *Service) NoAccounts(ctx context.Context) bool

NoAccounts is what first-run rules depend on, so it's true only when the database answered and has none. A failed read says false: a request hung up on halfway, or a damaged table, must never make a server that's set up look like a new one.

func (*Service) PlainAwaySessions

func (s *Service) PlainAwaySessions(ctx context.Context) int

PlainAwaySessions counts the sessions MarkPlainAway marked that haven't ended.

func (*Service) RecoveryLeft

func (s *Service) RecoveryLeft(ctx context.Context, id int64) int

RecoveryLeft says how many recovery codes an account has left.

func (*Service) Resolve

func (s *Service) Resolve(ctx context.Context, token string) (*User, error)

Resolve returns the user for a token.

func (*Service) ResolveStream

func (s *Service) ResolveStream(ctx context.Context, tok string, r *http.Request) (*User, error)

ResolveStream returns the user for a stream token on this request.

func (*Service) Sessions

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

Sessions lists sessions that have not expired, most recently used first: one account's, or everyone's when userID is 0. current is the token of the caller, whose session is marked.

func (*Service) SetAvatar

func (s *Service) SetAvatar(ctx context.Context, id int64, avatar string) error

SetAvatar saves a profile's picture.

func (*Service) SetDisplayName

func (s *Service) SetDisplayName(ctx context.Context, id int64, name string) error

SetDisplayName sets the profile name ("" goes back to the username).

func (*Service) SetPassword

func (s *Service) SetPassword(ctx context.Context, id int64, password string) error

func (*Service) SetRestrictions

func (s *Service) SetRestrictions(ctx context.Context, id int64, restrictions string) error

SetRestrictions stores an account's limits (JSON, "" = none).

func (*Service) SetShowUsername

func (s *Service) SetShowUsername(ctx context.Context, id int64, on bool) error

func (*Service) SetUI

func (s *Service) SetUI(ctx context.Context, id int64, ui string) error

SetUI stores an account's interface choices.

func (*Service) SetUsername

func (s *Service) SetUsername(ctx context.Context, id int64, name string) error

SetUsername changes the name an account signs in with.

func (*Service) StartTwoFactor

func (s *Service) StartTwoFactor(ctx context.Context, id int64, issuer string) (*TwoFactorSetup, error)

StartTwoFactor creates a new secret for an account. It takes effect only once ConfirmTwoFactor has seen a code made from it.

func (*Service) Touch

func (s *Service) Touch(ctx context.Context, token, ip, where, via string, streaming bool)

Touch records that a session was just used.

func (*Service) UI

func (s *Service) UI(ctx context.Context, id int64) string

UI returns an account's interface choices (JSON, "" = defaults).

func (*Service) User

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

func (*Service) Users

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

func (*Service) WeakAccounts

func (s *Service) WeakAccounts(ctx context.Context) ([]WeakAccount, error)

WeakAccounts lists adult accounts with a weak or unchecked password, and Kids and Guest profiles signing in with a short PIN: it keeps siblings apart, but it faces the internet just the same once remote access is on.

type Session

type Session struct {
	ID        string `json:"id"`
	UserID    int64  `json:"userId"`
	UserName  string `json:"userName"`
	Device    string `json:"device"`
	CreatedAt int64  `json:"createdAt"`
	ExpiresAt int64  `json:"expiresAt"`
	LastSeen  int64  `json:"lastSeen"`
	IP        string `json:"ip"`
	Where     string `json:"where"` // machine | home | vpn | internet
	Via       string `json:"via"`   // http | https | proxy
	Streaming bool   `json:"streaming"`
	Current   bool   `json:"current"`
	// PlainAway: its token has crossed the internet unencrypted, so anyone on
	// the way may have it. See MarkPlainAway.
	PlainAway bool `json:"plainAway"`
}

Session is one signed-in device.

type SessionEnd

type SessionEnd struct {
	Session string
	UserID  int64
	Keep    string
}

SessionEnd names the sign-ins that have just ended: one, by its public id (Session), or every one of an account (UserID) except Keep.

type TwoFactorSetup

type TwoFactorSetup struct {
	Secret string `json:"secret"`
	URI    string `json:"uri"`
}

TwoFactorSetup is what an authenticator app needs: the secret to type in, and the address a QR code holds.

type User

type User struct {
	ID int64 `json:"id"`
	// Name is the username: unique, and what signing in uses.
	Name string `json:"name"`
	// DisplayName is the profile name, which anyone may choose and anyone may
	// share ("" = use the username). ShowUsername: the corner of the screen shows
	// the username instead of this.
	DisplayName  string `json:"displayName"`
	ShowUsername bool   `json:"showUsername"`
	IsAdmin      bool   `json:"isAdmin"`
	CreatedAt    int64  `json:"createdAt"`
	// Kind is "adult", "kids" or "guest". Kids and Guest profiles may have
	// no password; they then sign in with a tap on the home network.
	Kind        string `json:"kind"`
	HasPassword bool   `json:"hasPassword"`
	// Restrictions is the account's library.Access as JSON ("" = none).
	Restrictions string `json:"-"`
	// TwoFactor: signing in also needs a code from an authenticator app.
	TwoFactor bool `json:"twoFactor"`
	// HomeOnly: the session this came from was made with no password, and only counts at home.
	HomeOnly bool `json:"-"`
	// Avatar is the picture the profile chose, as "name:colour" ("" = its initial).
	Avatar string `json:"avatar"`
}

type WeakAccount

type WeakAccount struct {
	Name    string `json:"name"`
	IsAdmin bool   `json:"isAdmin"`
	Unknown bool   `json:"unknown"`
}

WeakAccount is an account whose password should be changed, or (Unknown) whose password has not been checked yet because nobody signed in with it since this check was added.

Jump to

Keyboard shortcuts

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