Sign-in:
- Google, GitHub, Microsoft and any OpenID Connect provider, set up in the
admin panel (secrets are write-only). PocketBase talks to the provider,
and docwell-server keeps the state and PKCE verifier. Accounts a
provider creates follow the sign-up switch and the domain list; refused
ones are removed again.
- Two-step sign-in with an authenticator app (TOTP), set up under "Your
account", with ten single-use recovery codes. After any first factor
(password, email code, provider) the session is held behind a
five-minute challenge: five tries, each code works once. Turning it off
needs a code. Managers can reset it for someone who lost their phone.
Both the web app and the admin panel ask for the code.
Integrations:
- Personal API tokens ("dw_…") that act as their owner, read-only or
read-write, with optional expiry. Only a hash is stored, and the token is
shown once. Tokens cannot manage tokens or two-step sign-in. Admins see
and can revoke their organization's tokens.
- Workspace webhooks for page, comment and space events. Deliveries are
HMAC-SHA256 signed and retried (10 s, 1 min, 5 min), with a 30-day log
and a test button. Loopback and link-local addresses are refused
(DOCWELL_WEBHOOKS_ALLOW_LOCAL is for development).
Audit log: sign-ins (including failures and second steps, filed under the
account's organization) and every successful change request, by route and
path ids, never bodies. Superadmins see everything and org admins their
organization. It is searchable and exportable as CSV in the admin panel's
new Security page, and kept for DOCWELL_AUDIT_RETENTION_DAYS (365).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
525 lines
16 KiB
Go
525 lines
16 KiB
Go
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
// Package auth implements Docwell sign-in on top of PocketBase's "users" auth
|
|
// collection. PocketBase stores the credentials and issues the tokens;
|
|
// docwell-server forwards the calls and adds Docwell rules (signup policy,
|
|
// disabled accounts, instance admins).
|
|
package auth
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"docwell/server/internal/access"
|
|
"docwell/server/internal/store/pocketbase"
|
|
)
|
|
|
|
const usersPath = "/api/collections/users"
|
|
|
|
var (
|
|
ErrInvalidCredentials = errors.New("invalid credentials")
|
|
ErrUnauthorized = errors.New("unauthorized")
|
|
ErrForbidden = errors.New("forbidden")
|
|
ErrAccountDisabled = errors.New("account disabled")
|
|
ErrSignupDisabled = errors.New("signup disabled")
|
|
ErrDomainNotAllowed = errors.New("email domain not allowed")
|
|
ErrInvalidToken = errors.New("invalid or expired token")
|
|
)
|
|
|
|
// MFARequiredError means the first factor passed; the client must finish
|
|
// with a second method (e.g. OTP) and send MFAID along.
|
|
type MFARequiredError struct{ MFAID string }
|
|
|
|
func (e *MFARequiredError) Error() string { return "mfa required" }
|
|
|
|
// ValidationError lists invalid input fields with a message per field.
|
|
type ValidationError struct{ Fields map[string]string }
|
|
|
|
func (e *ValidationError) Error() string { return fmt.Sprintf("validation failed: %v", e.Fields) }
|
|
|
|
// User is the public view of a Docwell account.
|
|
type User struct {
|
|
ID string `json:"id"`
|
|
Email string `json:"email"`
|
|
Name string `json:"name"`
|
|
Avatar string `json:"avatar"`
|
|
Locale string `json:"locale"`
|
|
Theme string `json:"theme"`
|
|
Status string `json:"status"`
|
|
Verified bool `json:"verified"`
|
|
Created string `json:"created"`
|
|
// Role is the instance role: user, admin (of their organization) or superadmin.
|
|
Role string `json:"role"`
|
|
// Organization is the id of the user's organization ("" = none).
|
|
Organization string `json:"organization"`
|
|
OrganizationName string `json:"organizationName"`
|
|
// TOTP is whether the account signs in with an authenticator app too.
|
|
TOTP bool `json:"totp"`
|
|
}
|
|
|
|
// Caller returns the identity the access rules decide for.
|
|
func (u User) Caller() access.Caller {
|
|
return access.Caller{ID: u.ID, Role: u.Role, OrgID: u.Organization}
|
|
}
|
|
|
|
// UserRecord is the PocketBase JSON shape of a "users" record (with the
|
|
// organization optionally expanded).
|
|
type UserRecord struct {
|
|
ID string `json:"id"`
|
|
Email string `json:"email"`
|
|
Name string `json:"name"`
|
|
Avatar string `json:"avatar"`
|
|
Locale string `json:"locale"`
|
|
Theme string `json:"theme"`
|
|
Status string `json:"status"`
|
|
Verified bool `json:"verified"`
|
|
Created string `json:"created"`
|
|
Role string `json:"role"`
|
|
Organization string `json:"organization"`
|
|
TOTPEnabled bool `json:"totp_enabled"`
|
|
Expand struct {
|
|
Organization *struct {
|
|
Name string `json:"name"`
|
|
} `json:"organization"`
|
|
} `json:"expand"`
|
|
}
|
|
|
|
// User converts the record to the public view, filling defaults.
|
|
func (r UserRecord) User() User {
|
|
status := r.Status
|
|
if status == "" {
|
|
status = "active"
|
|
}
|
|
role, ok := access.NormalizeRole(r.Role)
|
|
if !ok {
|
|
role = access.RoleUser
|
|
}
|
|
u := User{
|
|
ID: r.ID, Email: r.Email, Name: r.Name, Avatar: r.Avatar, Locale: r.Locale, Theme: r.Theme,
|
|
Status: status, Verified: r.Verified, Created: r.Created, Role: role, Organization: r.Organization,
|
|
TOTP: r.TOTPEnabled,
|
|
}
|
|
if r.Expand.Organization != nil {
|
|
u.OrganizationName = r.Expand.Organization.Name
|
|
}
|
|
return u
|
|
}
|
|
|
|
// Session is a signed-in user and their PocketBase auth token.
|
|
type Session struct {
|
|
Token string `json:"token"`
|
|
User User `json:"user"`
|
|
}
|
|
|
|
type authResponse struct {
|
|
Token string `json:"token"`
|
|
Record UserRecord `json:"record"`
|
|
}
|
|
|
|
// Methods lists the sign-in methods enabled in PocketBase.
|
|
type Methods struct {
|
|
Password bool `json:"password"`
|
|
OTP bool `json:"otp"`
|
|
MFA bool `json:"mfa"`
|
|
OAuth2 []string `json:"oauth2"`
|
|
// Providers names the OAuth2 providers for sign-in buttons.
|
|
Providers []Provider `json:"providers"`
|
|
Signup bool `json:"signup"`
|
|
}
|
|
|
|
type Provider struct {
|
|
Name string `json:"name"`
|
|
DisplayName string `json:"displayName"`
|
|
}
|
|
|
|
type Options struct {
|
|
// SignupEnabled allows self-service signup. The first account can always
|
|
// sign up and becomes the instance admin.
|
|
SignupEnabled bool
|
|
// SignupDomains, if not empty, limits signup to these email domains.
|
|
SignupDomains []string
|
|
// Rules, when set, replaces SignupEnabled and SignupDomains with rules
|
|
// read on every signup (the admin panel can change them at runtime).
|
|
Rules func(ctx context.Context) (enabled bool, domains []string, err error)
|
|
// CacheTTL is how long a verified token is trusted without asking
|
|
// PocketBase again.
|
|
CacheTTL time.Duration
|
|
// OAuthRedirects are the addresses providers may send people back to
|
|
// (the web app's /oauth/callback, docwell://oauth/callback).
|
|
OAuthRedirects []string
|
|
}
|
|
|
|
type Service struct {
|
|
pb *pocketbase.Client
|
|
opts Options
|
|
now func() time.Time
|
|
|
|
mu sync.Mutex
|
|
cache map[[32]byte]cachedUser
|
|
|
|
totp *totpState
|
|
oauth *oauthState
|
|
}
|
|
|
|
type cachedUser struct {
|
|
user User
|
|
expires time.Time
|
|
// scope and tokenHash are set for API tokens.
|
|
scope string
|
|
tokenHash string
|
|
}
|
|
|
|
// Forget drops cached token checks for a user, so a role change, move or
|
|
// deletion takes effect on their next request instead of after CacheTTL.
|
|
func (s *Service) Forget(userID string) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
for k, c := range s.cache {
|
|
if c.user.ID == userID {
|
|
delete(s.cache, k)
|
|
}
|
|
}
|
|
}
|
|
|
|
func NewService(pb *pocketbase.Client, opts Options) *Service {
|
|
if opts.CacheTTL == 0 {
|
|
opts.CacheTTL = 30 * time.Second
|
|
}
|
|
return &Service{
|
|
pb: pb, opts: opts, now: time.Now, cache: map[[32]byte]cachedUser{},
|
|
totp: newTOTPState(), oauth: newOAuthState(),
|
|
}
|
|
}
|
|
|
|
// Login signs in with email and password. mfaID is set when finishing an
|
|
// MFA flow started by another method.
|
|
func (s *Service) Login(ctx context.Context, email, password, mfaID string) (Session, error) {
|
|
body := map[string]string{"identity": strings.TrimSpace(email), "password": password}
|
|
if mfaID != "" {
|
|
body["mfaId"] = mfaID
|
|
}
|
|
return s.authenticate(ctx, "/auth-with-password", body)
|
|
}
|
|
|
|
// RequestOTP emails a one-time code and returns the id to log in with.
|
|
func (s *Service) RequestOTP(ctx context.Context, email string) (string, error) {
|
|
var res struct {
|
|
OTPID string `json:"otpId"`
|
|
}
|
|
err := s.pb.DoAs(ctx, http.MethodPost, usersPath+"/request-otp", "", map[string]string{"email": strings.TrimSpace(email)}, &res)
|
|
return res.OTPID, mapError(err)
|
|
}
|
|
|
|
// LoginWithOTP signs in with a code sent by RequestOTP.
|
|
func (s *Service) LoginWithOTP(ctx context.Context, otpID, code, mfaID string) (Session, error) {
|
|
body := map[string]string{"otpId": otpID, "password": code}
|
|
if mfaID != "" {
|
|
body["mfaId"] = mfaID
|
|
}
|
|
return s.authenticate(ctx, "/auth-with-otp", body)
|
|
}
|
|
|
|
func (s *Service) authenticate(ctx context.Context, action string, body any) (Session, error) {
|
|
var res authResponse
|
|
err := s.pb.DoAs(ctx, http.MethodPost, usersPath+action, "", body, &res)
|
|
if err != nil {
|
|
var pbErr *pocketbase.Error
|
|
if errors.As(err, &pbErr) {
|
|
if pbErr.MFAID != "" {
|
|
return Session{}, &MFARequiredError{MFAID: pbErr.MFAID}
|
|
}
|
|
// PocketBase answers 400 "Failed to authenticate." for bad credentials.
|
|
if pbErr.Status == http.StatusBadRequest && len(pbErr.Data) == 0 {
|
|
return Session{}, ErrInvalidCredentials
|
|
}
|
|
// 403 means the credentials were right but the collection authRule
|
|
// (status != 'disabled') rejected the account.
|
|
if pbErr.Status == http.StatusForbidden {
|
|
return Session{}, ErrAccountDisabled
|
|
}
|
|
}
|
|
return Session{}, mapError(err)
|
|
}
|
|
return s.secondStep(ctx, Session{Token: res.Token, User: s.withOrganization(ctx, res.Token, res.Record.User())})
|
|
}
|
|
|
|
// withOrganization fills in the organization name. PocketBase applies the
|
|
// user's own access rules when expanding auth responses, and users cannot read
|
|
// the organizations collection, so the name comes from the token-check hook
|
|
// instead (which also warms the Verify cache).
|
|
func (s *Service) withOrganization(ctx context.Context, token string, u User) User {
|
|
if u.Organization == "" || u.OrganizationName != "" {
|
|
return u
|
|
}
|
|
if full, err := s.Verify(ctx, token); err == nil {
|
|
return full
|
|
}
|
|
return u
|
|
}
|
|
|
|
// SignupInput is a new account request.
|
|
type SignupInput struct {
|
|
Email string `json:"email"`
|
|
Password string `json:"password"`
|
|
Name string `json:"name"`
|
|
}
|
|
|
|
// Signup creates an account and signs it in. The first account on the
|
|
// instance becomes the superadmin.
|
|
func (s *Service) Signup(ctx context.Context, in SignupInput) (Session, error) {
|
|
in.Email = strings.TrimSpace(in.Email)
|
|
in.Name = strings.TrimSpace(in.Name)
|
|
|
|
fields := map[string]string{}
|
|
if in.Name == "" {
|
|
fields["name"] = "Name is required."
|
|
}
|
|
if len(in.Password) < 8 {
|
|
fields["password"] = "Password must be at least 8 characters."
|
|
}
|
|
if len(fields) > 0 {
|
|
return Session{}, &ValidationError{Fields: fields}
|
|
}
|
|
|
|
existing, err := pocketbase.List[UserRecord](ctx, s.pb, "users", pocketbase.ListOptions{PerPage: 1})
|
|
if err != nil {
|
|
return Session{}, err
|
|
}
|
|
first := existing.TotalItems == 0
|
|
// The first account runs the instance; everyone after starts as a plain
|
|
// user without an organization (they can create one or be invited).
|
|
role := access.RoleUser
|
|
if first {
|
|
role = access.RoleSuperadmin
|
|
}
|
|
|
|
if !first {
|
|
enabled, domains, err := s.signupRules(ctx)
|
|
if err != nil {
|
|
return Session{}, err
|
|
}
|
|
if !enabled {
|
|
return Session{}, ErrSignupDisabled
|
|
}
|
|
if !DomainAllowed(domains, in.Email) {
|
|
return Session{}, ErrDomainNotAllowed
|
|
}
|
|
}
|
|
|
|
_, err = pocketbase.Create[UserRecord](ctx, s.pb, "users", map[string]any{
|
|
"email": in.Email,
|
|
"password": in.Password,
|
|
"passwordConfirm": in.Password,
|
|
"name": in.Name,
|
|
"status": "active",
|
|
"role": role,
|
|
"emailVisibility": false,
|
|
})
|
|
if err != nil {
|
|
return Session{}, mapError(err)
|
|
}
|
|
|
|
// Best effort: without SMTP configured PocketBase cannot send it.
|
|
_ = s.RequestVerification(ctx, in.Email)
|
|
|
|
return s.Login(ctx, in.Email, in.Password, "")
|
|
}
|
|
|
|
func (s *Service) signupRules(ctx context.Context) (bool, []string, error) {
|
|
if s.opts.Rules != nil {
|
|
return s.opts.Rules(ctx)
|
|
}
|
|
return s.opts.SignupEnabled, s.opts.SignupDomains, nil
|
|
}
|
|
|
|
// DomainAllowed reports whether email's domain is on the allow-list; an empty
|
|
// list allows every domain.
|
|
func DomainAllowed(domains []string, email string) bool {
|
|
if len(domains) == 0 {
|
|
return true
|
|
}
|
|
at := strings.LastIndexByte(email, '@')
|
|
if at < 0 {
|
|
return false
|
|
}
|
|
domain := strings.ToLower(strings.TrimSpace(email[at+1:]))
|
|
for _, d := range domains {
|
|
if strings.EqualFold(d, domain) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// Refresh exchanges a valid token for a new one.
|
|
func (s *Service) Refresh(ctx context.Context, token string) (Session, error) {
|
|
var res authResponse
|
|
if err := s.pb.DoAs(ctx, http.MethodPost, usersPath+"/auth-refresh", token, nil, &res); err != nil {
|
|
return Session{}, tokenError(err)
|
|
}
|
|
u := res.Record.User()
|
|
if u.Status == "disabled" {
|
|
return Session{}, ErrAccountDisabled
|
|
}
|
|
return Session{Token: res.Token, User: s.withOrganization(ctx, res.Token, u)}, nil
|
|
}
|
|
|
|
// Verify returns the user that owns token. Results are cached for CacheTTL.
|
|
func (s *Service) Verify(ctx context.Context, token string) (User, error) {
|
|
if token == "" {
|
|
return User{}, ErrUnauthorized
|
|
}
|
|
key := sha256.Sum256([]byte(token))
|
|
now := s.now()
|
|
|
|
s.mu.Lock()
|
|
if c, ok := s.cache[key]; ok && now.Before(c.expires) {
|
|
s.mu.Unlock()
|
|
return c.user, nil
|
|
}
|
|
s.mu.Unlock()
|
|
|
|
var rec UserRecord
|
|
if err := s.pb.DoAs(ctx, http.MethodGet, "/api/docwell/auth/verify", token, nil, &rec); err != nil {
|
|
return User{}, tokenError(err)
|
|
}
|
|
u := rec.User()
|
|
if u.Status == "disabled" {
|
|
return User{}, ErrAccountDisabled
|
|
}
|
|
|
|
s.mu.Lock()
|
|
if len(s.cache) > 10000 {
|
|
for k, c := range s.cache {
|
|
if now.After(c.expires) {
|
|
delete(s.cache, k)
|
|
}
|
|
}
|
|
}
|
|
s.cache[key] = cachedUser{user: u, expires: now.Add(s.opts.CacheTTL)}
|
|
s.mu.Unlock()
|
|
return u, nil
|
|
}
|
|
|
|
// UserByID loads an active user by id (for file tokens, which carry only the id).
|
|
func (s *Service) UserByID(ctx context.Context, id string) (User, error) {
|
|
if id == "" || strings.ContainsAny(id, "/?#") {
|
|
return User{}, ErrUnauthorized
|
|
}
|
|
rec, err := pocketbase.GetExpand[UserRecord](ctx, s.pb, "users", id, "organization")
|
|
if err != nil {
|
|
return User{}, tokenError(err)
|
|
}
|
|
u := rec.User()
|
|
if u.Status == "disabled" {
|
|
return User{}, ErrAccountDisabled
|
|
}
|
|
return u, nil
|
|
}
|
|
|
|
// Methods reports which sign-in methods are enabled.
|
|
func (s *Service) Methods(ctx context.Context) (Methods, error) {
|
|
var res struct {
|
|
Password struct{ Enabled bool } `json:"password"`
|
|
OTP struct{ Enabled bool } `json:"otp"`
|
|
MFA struct{ Enabled bool } `json:"mfa"`
|
|
OAuth2 struct {
|
|
Enabled bool
|
|
Providers []struct {
|
|
Name string `json:"name"`
|
|
DisplayName string `json:"displayName"`
|
|
} `json:"providers"`
|
|
} `json:"oauth2"`
|
|
}
|
|
if err := s.pb.DoAs(ctx, http.MethodGet, usersPath+"/auth-methods", "", nil, &res); err != nil {
|
|
return Methods{}, mapError(err)
|
|
}
|
|
signup, _, err := s.signupRules(ctx)
|
|
if err != nil {
|
|
return Methods{}, err
|
|
}
|
|
m := Methods{
|
|
Password: res.Password.Enabled, OTP: res.OTP.Enabled, MFA: res.MFA.Enabled,
|
|
OAuth2: []string{}, Providers: []Provider{}, Signup: signup,
|
|
}
|
|
if res.OAuth2.Enabled {
|
|
for _, p := range res.OAuth2.Providers {
|
|
m.OAuth2 = append(m.OAuth2, p.Name)
|
|
m.Providers = append(m.Providers, Provider{Name: p.Name, DisplayName: p.DisplayName})
|
|
}
|
|
}
|
|
return m, nil
|
|
}
|
|
|
|
// RequestPasswordReset emails a reset link. It succeeds for unknown emails too.
|
|
func (s *Service) RequestPasswordReset(ctx context.Context, email string) error {
|
|
return mapError(s.pb.DoAs(ctx, http.MethodPost, usersPath+"/request-password-reset", "", map[string]string{"email": strings.TrimSpace(email)}, nil))
|
|
}
|
|
|
|
// ConfirmPasswordReset sets a new password using the emailed token.
|
|
func (s *Service) ConfirmPasswordReset(ctx context.Context, token, password string) error {
|
|
err := s.pb.DoAs(ctx, http.MethodPost, usersPath+"/confirm-password-reset", "",
|
|
map[string]string{"token": token, "password": password, "passwordConfirm": password}, nil)
|
|
return confirmError(err)
|
|
}
|
|
|
|
// RequestVerification emails an email-verification link.
|
|
func (s *Service) RequestVerification(ctx context.Context, email string) error {
|
|
return mapError(s.pb.DoAs(ctx, http.MethodPost, usersPath+"/request-verification", "", map[string]string{"email": strings.TrimSpace(email)}, nil))
|
|
}
|
|
|
|
// ConfirmVerification marks the email as verified using the emailed token.
|
|
func (s *Service) ConfirmVerification(ctx context.Context, token string) error {
|
|
err := s.pb.DoAs(ctx, http.MethodPost, usersPath+"/confirm-verification", "", map[string]string{"token": token}, nil)
|
|
return confirmError(err)
|
|
}
|
|
|
|
func tokenError(err error) error {
|
|
var pbErr *pocketbase.Error
|
|
if errors.As(err, &pbErr) && (pbErr.Status == http.StatusUnauthorized || pbErr.Status == http.StatusForbidden || pbErr.Status == http.StatusNotFound) {
|
|
return ErrUnauthorized
|
|
}
|
|
return err
|
|
}
|
|
|
|
func confirmError(err error) error {
|
|
var pbErr *pocketbase.Error
|
|
if errors.As(err, &pbErr) && pbErr.Status == http.StatusBadRequest {
|
|
if _, ok := pbErr.Data["token"]; ok {
|
|
return ErrInvalidToken
|
|
}
|
|
}
|
|
return mapError(err)
|
|
}
|
|
|
|
// mapError turns PocketBase validation errors into ValidationError.
|
|
func mapError(err error) error {
|
|
var pbErr *pocketbase.Error
|
|
if errors.As(err, &pbErr) && pbErr.Status == http.StatusBadRequest && len(pbErr.Data) > 0 {
|
|
fields := make(map[string]string, len(pbErr.Data))
|
|
for k, v := range pbErr.Data {
|
|
if k == "passwordConfirm" {
|
|
continue
|
|
}
|
|
fields[k] = v.Message
|
|
}
|
|
return &ValidationError{Fields: fields}
|
|
}
|
|
return err
|
|
}
|
|
|
|
// BearerToken extracts the token from an "Authorization: Bearer ..." header.
|
|
func BearerToken(r *http.Request) string {
|
|
h := r.Header.Get("Authorization")
|
|
if t, ok := strings.CutPrefix(h, "Bearer "); ok {
|
|
return strings.TrimSpace(t)
|
|
}
|
|
return ""
|
|
}
|