auth

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 31 Imported by: ? 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 signs people in with passkeys and keeps their browser sessions: setup links, invites, step-up and the passkey list. It is Family Hub's internal/auth (Family Hub docs/PLAN.md §2 "Login", §5.9 "Auth", card T1.2, the fixes of T2.F2) on plain net/http, log/slog and the gatekeeper's store.

Passkeys

WebAuthn runs through github.com/go-webauthn/webauthn. The relying party ID and the only origin come from core.Site, its display name from core.Brand.Product. Every ceremony asks for a discoverable credential and user verification (Face ID, Touch ID) and no attestation. The WebAuthn user handle is the person id. A begin answers {"options": …}, the options JSON the browser takes (PublicKeyCredentialCreationOptionsJSON or PublicKeyCredentialRequestOptionsJSON); a finish sends {"credential": …}, the browser's answer unchanged, and the server finds the pending ceremony again by the challenge inside it. A ceremony lives in memory for 5 minutes and is finished at most once, by the endpoint of its own kind and, for step-up and a new passkey, by the session that began it. A signature counter that goes backwards is refused.

Sessions

A sign-in or a registration creates a core.Session and sets the cookie Brand.SessionCookie (Family Hub: __Host-fh_session; Path=/; Secure; HttpOnly; SameSite=Strict) to 32 random bytes; only their sha256 is stored. A session ends 12 hours after its last request or 7 days after sign-in; LastSeenAt is written at most once a minute, and an hourly sweep deletes dead sessions. Signing in counts as step-up; a step-up assertion is fresh for 5 minutes. Deleting a passkey and POST /api/me/sessions/revoke ("sign out on other devices", step-up) end every session of the person in one transaction and give the current browser a new session and cookie with the old one's sign-in time, absolute end and step-up.

Access terms

A person who is not core.Person.Active (disabled, or past core.Person.AccessUntil, a guest's term) is out: Viewer refuses their session and deletes it, and a sign-in with their passkey is refused with 403 access_ended (CodeAccessEnded) "your access has ended" (a disabled person's fails like a passkey that did not verify). A member invite may carry a term and the application's permissions (IssueInviteWithAccess); registering with it copies both to the new person in the transaction that uses the invite, and an invite whose term has ended reads as a dead link.

What applications and the other packages use

auth.New(auth.Options{…})            *Auth: core.Sessions and core.RouteRegistrar; Start and Stop run the sweeps
a.RegisterRoutes(mux)                the routes below, on Go 1.22 patterns
a.RequireViewer, a.RequireStepUp     core.Sessions: 401 no_session, 403 step_up_required; RequireViewer also
                                     applies the CSRF checks to mutating methods (403 forbidden)
a.Viewer(r)                          the signed-in person, or core.ErrNoSession
a.SameOrigin                         the CSRF checks alone, for routes without a session
a.IssueInvite(ctx, kind, acc, name, by), a.IssueInviteIn(ctx, st, …)
                                     owner and member invites: {ID, URL with #t=, ExpiresAt}, 24 hours
a.IssueInviteWithAccess(ctx, kind, acc, name, by, until, perms)
                                     a member invite with a term and permissions for the person
a.IssueSetupLink(ctx)                the setup-link command for a caller in the process (a first-run page)
a.IssueSetupLinkTTL(ctx, ttl)        the same with a shorter life (≤ 15 minutes)
a.SuperadminCanSignIn(ctx)           whether an enabled superadmin has a passkey of this site (no setup link then)
a.ClearSessionCookie(w)              drops the cookie (after the application ended the session itself)
a.AdminCommands()                    setup-link and reset-access; Options.Admin registers them on a socket
Options.OnAccessReset                the application hears of every reset-access (an alert for its owner)
auth.NormalizeName(v)                the name rule (1–40 characters, no controls, quotes, backslashes, backticks)

Tokens are 32 random bytes, stored as sha256, carried in the URL fragment: <public URL>/setup#t=… (15 minutes) and <public URL>/join#t=… (24 hours). Each works once; a new setup link revokes the older ones. The setup-link admin command makes one only while no enabled superadmin has a passkey: with no superadmin, registering creates the first account (named by account_name) and its owner with the superadmin flag; after reset-access, which wipes the superadmin's passkeys and sessions, revokes their OAuth grants, runs the application's ResetSteps (Family Hub: deletes their legacy keys) and revokes the open invites they made, it adds a new passkey to the same superadmin. IssueSetupLink makes the same link under the same rule for a caller inside the process, IssueSetupLinkTTL a shorter one, and SuperadminCanSignIn answers that rule's question.

An owner invite to an account without an owner makes its owner, who may rename the account (account_name); one to an account that has an owner makes a co-owner (core.RoleOwner, not superadmin), who joins it as it is named. Who may invite whom is package people's rule.

Limits and checks

Every mutating call needs Brand.CSRFHeader: 1 (Family Hub: X-Family-Hub), and an Origin and a Sec-Fetch-Site, when the browser sends them, of the public URL and same-origin. Rate limits have separate buckets per class: auth/token and registration per client address (20 a minute); sign-in per client address, counting begins (30) and failed finishes (10); step-up and a new passkey per session the same way. No bucket is shared by all clients (T2.R H2). The client address is core.ClientIP; IPv6 counts per /64.

Audit and logs

Audit actions: auth.register, auth.join, auth.login, auth.login.fail (a system entry), auth.stepup, auth.stepup.fail, auth.logout, auth.sessions.revoke, auth.passkey.add, auth.passkey.rename, auth.passkey.delete, admin.setup-link and admin.reset-access. auth.login.fail is coalesced: at most one entry per address group (an IPv4 address or an IPv6 /64, which is also its IP) a minute, with detail count = the failures since the group's previous entry. admin.setup-link and admin.reset-access name the admin socket's peer (detail peer_pid and peer_exe, when the socket knew them, and peer_chain, who started it, when known; review GK-5); an in-process setup link has detail via=in-process. Tokens, cookies, links, challenges and credentials never reach a log or an audit entry; a failed ceremony logs only the name of the check that failed.

The hourly sweep also purges what has expired from a store that cannot expire rows by itself (store.Purger, e.g. sqlitestore; review GK-3). Texts that name the application use core.Brand.AppWord ("hub" by default, review GK-18).

Routes

POST   /api/auth/token              public: what a setup link or invite is
POST   /api/auth/register/begin     public: a passkey for a setup link or invite
POST   /api/auth/register/finish    public: creates the person (and the first account) and signs in
POST   /api/auth/login/begin        public
POST   /api/auth/login/finish       public: signs in
POST   /api/auth/stepup/begin       session
POST   /api/auth/stepup/finish      session
POST   /api/auth/logout             204, with or without a session
GET    /api/me                      session
GET    /api/me/passkeys             session
POST   /api/me/passkeys/begin       session + step-up
POST   /api/me/passkeys/finish      session + step-up
PATCH  /api/me/passkeys/{id}        session
DELETE /api/me/passkeys/{id}        session + step-up; never the last passkey; ends the other sessions
POST   /api/me/sessions/revoke      session + step-up: sign out on other devices; 204 with a new cookie

Index

Constants

View Source
const (
	// IdleTimeout ends a session that made no request for this long.
	IdleTimeout = 12 * time.Hour
	// AbsoluteTimeout ends every session this long after sign-in.
	AbsoluteTimeout = 7 * 24 * time.Hour
	// StepUpWindow is how long a passkey assertion (sign-in included) counts as fresh for dangerous actions.
	StepUpWindow = 5 * time.Minute
	// CeremonyTTL is how long a begun passkey ceremony can be finished.
	CeremonyTTL = 5 * time.Minute
	// SetupLinkTTL is the life of a setup link.
	SetupLinkTTL = 15 * time.Minute
	// InviteTTL is the life of an owner or member invite.
	InviteTTL = 24 * time.Hour
)

Lifetimes (Family Hub's docs/PLAN.md §2 "Login", card T1.2).

View Source
const CodeAccessEnded = "access_ended"

CodeAccessEnded is the error code of a sign-in whose passkey verified but whose person's term has ended (core.Person.AccessUntil), answered 403: the UI tells them to ask the owner to extend it. It is its own code, not forbidden, which a CSRF refusal answers too.

View Source
const MaxNameLen = 40

MaxNameLen is the longest name of a person, an account or a passkey, in characters.

Variables

View Source
var ErrInvalidName = errors.New("invalid name")

ErrInvalidName is wrapped by NormalizeName's errors.

Functions

func NormalizeName

func NormalizeName(v string) (string, error)

NormalizeName trims a display name (a person, an account, a passkey) and checks it: 1 to 40 characters, no control characters, no line or paragraph separators, no bidirectional controls, and no double quotes, backslashes or backticks. Names reach the identity claims modules get and the assistants' answers, where a line break or a quote could pass for an instruction of its own. T1.4 uses the same rule for its names.

Types

type AccessReset added in v0.2.0

type AccessReset struct {
	At     time.Time
	People []core.PersonID
	Peer   adminsock.Peer
}

AccessReset is what Options.OnAccessReset learns after reset-access: when, whose access was wiped (the superadmins; empty on an application nobody has set up), and the socket peer that asked (adminsock.Peer: its pid, executable and ancestors, when known).

type Auth

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

Auth is the passkey, session and invite service. It is safe for concurrent use.

func New

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

New checks the options and returns an Auth. The Site must pass core.Site.Validate: PublicURL an origin (scheme, host, optional port, nothing else) and a known client address mode. With Options.Admin set, it registers auth's admin commands there.

func (*Auth) AdminCommands

func (a *Auth) AdminCommands() []adminsock.Command

AdminCommands are auth's admin commands; New adds them to Options.Admin when it is set.

setup-link    a one-time link that registers the superadmin's passkey: with no superadmin yet it creates the
              first account and its superadmin owner; after reset-access it adds a passkey to the superadmin.
              Refused while an enabled superadmin has a passkey.
reset-access  wipes every passkey and session of the superadmin, revokes their OAuth grants, runs the
              application's ResetSteps (Family Hub: deletes their legacy keys) and revokes the invites they made,
              revokes the older setup links and prints a new one; then Options.OnAccessReset hears of it.

The links are printed to the operator's terminal only, never logged. Both commands audit the socket's peer (its pid and executable, and who started it: adminsock.Peer) when the socket knew it.

func (*Auth) ClearSessionCookie

func (a *Auth) ClearSessionCookie(w http.ResponseWriter)

ClearSessionCookie tells the browser to drop the session cookie, with the attributes it was set with. Logout sends it; so does an application that ended the session another way (Family Hub: deleting the whole account).

func (*Auth) IssueInvite

func (a *Auth) IssueInvite(ctx context.Context, kind core.InviteKind, account core.AccountID, name string,
	by core.PersonID) (IssuedInvite, error)

IssueInvite makes an invite: core.InviteOwner (the owner of an account the superadmin made, or a co-owner of an account that has its owner already) or core.InviteMember (a member of an account, made by its owner). It lives 24 hours and is used once; registering with it creates the person in the account, named name unless they type another. by is the person who asked. Who may ask for which kind is the caller's rule (package people). Errors wrap ErrInvalidName for a bad name and core.ErrNotFound for an unknown account. Called with a context inside store.Store.Tx, it joins that transaction.

func (*Auth) IssueInviteIn

func (a *Auth) IssueInviteIn(ctx context.Context, st store.Store, kind core.InviteKind, account core.AccountID,
	name string, by core.PersonID) (IssuedInvite, error)

IssueInviteIn is IssueInvite on st, e.g. the store whose transaction (carried in ctx) also creates the account.

func (*Auth) IssueInviteWithAccess added in v0.2.0

func (a *Auth) IssueInviteWithAccess(ctx context.Context, kind core.InviteKind, account core.AccountID, name string,
	by core.PersonID, until *time.Time, perms []string) (IssuedInvite, error)

IssueInviteWithAccess is IssueInvite for an invite that gives the person who redeems it a term (until; nil is no end) and the application's permission ids (perms; nil or empty is the application's default), the core.Person.AccessUntil and Permissions that registering copies to the new member in the same transaction. Only a member invite takes them: an owner has everything, with no end. A term that has already ended is refused. auth stores the ids as given; checking them against the application's catalog, and the term's bounds, is the caller's (package people, whose AccessInviter this is the core of).

func (a *Auth) IssueSetupLink(ctx context.Context) (url string, expires time.Time, err error)

IssueSetupLink is the setup-link admin command for a caller inside the application process (Homie's first-run page on the home box): the same rule (only while no enabled superadmin has a usable passkey of this site; refused with an error wrapping core.ErrConflict otherwise), the same 15-minute link, and the older links revoked. It is audited as admin.setup-link with detail via=in-process. The URL carries the token in its fragment: show it to the person at the box only, never log or store it.

func (*Auth) IssueSetupLinkTTL added in v0.2.0

func (a *Auth) IssueSetupLinkTTL(ctx context.Context, ttl time.Duration) (url string, expires time.Time, err error)

IssueSetupLinkTTL is IssueSetupLink with a shorter life for the link (Homie's first-run page: 3 minutes). A ttl that is not positive, or longer than SetupLinkTTL, means SetupLinkTTL. The stored link, expires and the audit's expires_at all carry the real end.

func (*Auth) RegisterRoutes

func (a *Auth) RegisterRoutes(mux *http.ServeMux)

RegisterRoutes adds the routes of Family Hub's §5.9 "Auth":

POST   /api/auth/token              public: what a setup link or invite is
POST   /api/auth/register/begin     public: a passkey for a setup link or invite
POST   /api/auth/register/finish    public: creates the person (and the first account) and signs in
POST   /api/auth/login/begin        public
POST   /api/auth/login/finish       public: signs in
POST   /api/auth/stepup/begin       session
POST   /api/auth/stepup/finish      session
POST   /api/auth/logout             204, with or without a session
GET    /api/me                      session
GET    /api/me/passkeys             session
POST   /api/me/passkeys/begin       session + step-up
POST   /api/me/passkeys/finish      session + step-up
PATCH  /api/me/passkeys/{id}        session
DELETE /api/me/passkeys/{id}        session + step-up; never the last passkey; ends the other sessions
POST   /api/me/sessions/revoke      session + step-up: sign out on other devices; 204 with a new cookie

func (*Auth) RequireStepUp

func (a *Auth) RequireStepUp(next http.Handler) http.Handler

RequireStepUp is middleware after RequireViewer: 403 step_up_required unless the session's last passkey assertion (sign-in included) is less than 5 minutes old. Nothing of the request happens then; the SPA steps up and retries.

func (*Auth) RequireViewer

func (a *Auth) RequireViewer(next http.Handler) http.Handler

RequireViewer is middleware: 401 no_session without a valid session; otherwise it stores the Viewer in the request context (core.ViewerFrom) and calls next. For a mutating method it first applies the CSRF checks (403 forbidden), so every session-protected write of every package gets them.

func (*Auth) SameOrigin

func (a *Auth) SameOrigin(next http.Handler) http.Handler

SameOrigin is middleware with the checks of a mutating request: the header Brand.CSRFHeader: 1, an Origin (when the browser sends one) equal to the public URL, and a Sec-Fetch-Site (when sent) of same-origin; otherwise 403 forbidden. GET, HEAD and OPTIONS pass. RequireViewer applies it already.

func (*Auth) Start

func (a *Auth) Start(context.Context) error

Start sweeps expired sessions now and then every hour, and writes the counted failed sign-ins every minute, until Stop.

func (*Auth) Stop

func (a *Auth) Stop(ctx context.Context) error

Stop ends the sweeps and writes the failed sign-ins still counted.

func (*Auth) SuperadminCanSignIn added in v0.2.0

func (a *Auth) SuperadminCanSignIn(ctx context.Context) (bool, error)

SuperadminCanSignIn reports whether an enabled superadmin has a usable passkey of this site: a stored passkey whose credential was registered for this Auth's RP ID. It is the rule IssueSetupLink and the setup-link command refuse a link by (they also refuse while every superadmin is disabled); an application asks it to know whether its first-run page must still offer a setup link, without reading auth's stored passkeys itself. Errors are store failures.

func (*Auth) Viewer

func (a *Auth) Viewer(r *http.Request) (core.Viewer, error)

Viewer returns the signed-in person of r, or core.ErrNoSession; other errors are store failures. It owns the expiry rules: a session past its absolute end or idle for 12 hours, or whose person is gone or not active (core.Person.Active: disabled, or past the end of their term), or whose account is gone, is deleted. LastSeenAt is written at most once a minute.

type IssuedInvite

type IssuedInvite struct {
	ID        string
	URL       string
	ExpiresAt time.Time
}

IssuedInvite is a new one-time link. URL carries the token in its fragment (#t=…), so neither a proxy's log nor a Referer ever holds it: show the URL once to whoever asked, never log or store it.

type Options

type Options struct {
	// Site is where the application is served: the public URL is the only WebAuthn origin and the base of the setup
	// and invite links; an empty RPID is the host of PublicURL.
	Site core.Site
	// Brand names the session cookie (SessionCookie, "__Host-…"), the CSRF header (CSRFHeader) and the relying party
	// a browser shows next to the domain (Product). TxnCookie is not auth's.
	Brand core.Brand
	// Store keeps people, passkeys, sessions, invites and the audit.
	Store store.Store
	// Logger gets auth's lines; nil discards.
	Logger *slog.Logger
	// Clock is the time; nil is the system clock.
	Clock core.Clock
	// Admin, when set, gets auth's admin commands (setup-link and reset-access, see AdminCommands).
	Admin *adminsock.Registry
	// AdminCLI is how the operator runs an admin command, named in messages, e.g. "hub admin"; "" is "admin".
	AdminCLI string
	// ResetSteps are the application's parts of reset-access (Family Hub: deleting the superadmin's legacy keys).
	ResetSteps []ResetStep
	// OnAccessReset, when set, is called after reset-access succeeded, so the application can raise an "access was
	// reset" alert where its owner looks (review GK-5: on a desktop any program of the same user reaches the socket).
	// It runs on the command's goroutine with a context that is not cancelled; keep it short.
	OnAccessReset func(ctx context.Context, r AccessReset)
}

Options is what New needs.

type ResetStep

type ResetStep struct {
	Key    string // e.g. "legacy_keys"
	Phrase string // e.g. "legacy keys"
	Run    func(ctx context.Context, p core.Person, now time.Time) (int, error)
}

ResetStep is an application's part of reset-access: it ends what one superadmin's identity left behind in the application's own data (Family Hub: the superadmin's legacy Site keys). Run is called for every superadmin inside reset-access's transaction (ctx carries it), after their passkeys, sessions and OAuth grants and before their open invites; it returns how many things it ended, and an error rolls the whole reset back. Its count goes into the audit detail under Key and into the printed summary as "<n> <Phrase>".

Jump to

Keyboard shortcuts

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