// SPDX-License-Identifier: AGPL-3.0-or-later package auth import ( "context" "errors" "net/http" "net/url" "strings" "sync" "time" "docwell/server/internal/access" "docwell/server/internal/store/pocketbase" ) // ---- Sign-in with Google, GitHub, Microsoft or any OpenID Connect provider - // // PocketBase talks to the provider; docwell-server keeps the flow's state and // PKCE verifier (so the client never handles them), and applies Docwell's // rules to accounts the provider creates: the sign-up switch and domain list // (or the account is removed again), plain user role, and the second step. const oauthTTL = 10 * time.Minute type oauthFlow struct { provider string codeVerifier string redirect string expires time.Time } type oauthState struct { mu sync.Mutex flows map[string]oauthFlow } func newOAuthState() *oauthState { return &oauthState{flows: map[string]oauthFlow{}} } // OAuthStart is where to send the browser to sign in with a provider. type OAuthStart struct { URL string `json:"url"` State string `json:"state"` } type pbAuthMethods struct { OAuth2 struct { Enabled bool `json:"enabled"` Providers []struct { Name string `json:"name"` DisplayName string `json:"displayName"` State string `json:"state"` AuthURL string `json:"authURL"` CodeVerifier string `json:"codeVerifier"` } `json:"providers"` } `json:"oauth2"` } // redirectAllowed reports whether redirect is one of the configured callback // addresses (the web app's /oauth/callback, the desktop app's link). func (s *Service) redirectAllowed(redirect string) bool { for _, r := range s.opts.OAuthRedirects { if redirect == r { return true } } return false } // StartOAuth begins signing in with provider; the provider sends the browser // back to redirect with a code and the state. func (s *Service) StartOAuth(ctx context.Context, provider, redirect string) (OAuthStart, error) { if !s.redirectAllowed(redirect) { return OAuthStart{}, &ValidationError{Fields: map[string]string{"redirect": "This return address is not allowed."}} } var m pbAuthMethods if err := s.pb.DoAs(ctx, http.MethodGet, usersPath+"/auth-methods", "", nil, &m); err != nil { return OAuthStart{}, mapError(err) } for _, p := range m.OAuth2.Providers { if !m.OAuth2.Enabled || p.Name != provider { continue } now := s.now() s.oauth.mu.Lock() for k, f := range s.oauth.flows { if now.After(f.expires) { delete(s.oauth.flows, k) } } s.oauth.flows[p.State] = oauthFlow{provider: p.Name, codeVerifier: p.CodeVerifier, redirect: redirect, expires: now.Add(oauthTTL)} s.oauth.mu.Unlock() // PocketBase's authURL ends with "redirect_uri=" for the caller to fill. return OAuthStart{URL: p.AuthURL + url.QueryEscape(redirect), State: p.State}, nil } return OAuthStart{}, &ValidationError{Fields: map[string]string{"provider": "That sign-in method is not turned on."}} } // FinishOAuth completes a provider sign-in with the code from the callback. func (s *Service) FinishOAuth(ctx context.Context, state, code string) (Session, error) { s.oauth.mu.Lock() flow, ok := s.oauth.flows[state] delete(s.oauth.flows, state) s.oauth.mu.Unlock() if !ok || s.now().After(flow.expires) || strings.TrimSpace(code) == "" { return Session{}, ErrInvalidToken } var res struct { authResponse Meta struct { IsNew bool `json:"isNew"` } `json:"meta"` } err := s.pb.DoAs(ctx, http.MethodPost, usersPath+"/auth-with-oauth2", "", map[string]any{ "provider": flow.provider, "code": code, "codeVerifier": flow.codeVerifier, "redirectURL": flow.redirect, // Fields for an account the provider creates; role and status are ours to set. "createData": map[string]any{"status": "active", "role": access.RoleUser, "emailVisibility": false}, }, &res) if err != nil { return Session{}, s.authError(err) } if res.Meta.IsNew { if err := s.admitNewAccount(ctx, res.Record); err != nil { return Session{}, err } if res.Record, err = pocketbase.Get[UserRecord](ctx, s.pb, "users", res.Record.ID); err != nil { return Session{}, err } } u := res.Record.User() if u.Status == "disabled" { return Session{}, ErrAccountDisabled } return s.secondStep(ctx, Session{Token: res.Token, User: s.withOrganization(ctx, res.Token, u)}) } // admitNewAccount applies the sign-up rules to an account a provider just // created: the first account on the instance becomes the superadmin; later // ones need sign-up on and an allowed domain, or they are removed again. func (s *Service) admitNewAccount(ctx context.Context, rec UserRecord) error { all, err := pocketbase.List[UserRecord](ctx, s.pb, "users", pocketbase.ListOptions{PerPage: 1}) if err != nil { return err } if all.TotalItems <= 1 { _, err := pocketbase.Update[UserRecord](ctx, s.pb, "users", rec.ID, map[string]any{"role": access.RoleSuperadmin}) return err } enabled, domains, err := s.signupRules(ctx) if err != nil { return err } var refuse error switch { case !enabled: refuse = ErrSignupDisabled case !DomainAllowed(domains, rec.Email): refuse = ErrDomainNotAllowed } if refuse != nil { _ = s.pb.Delete(ctx, "users", rec.ID) return refuse } // The provider vouched for the address. _, err = pocketbase.Update[UserRecord](ctx, s.pb, "users", rec.ID, map[string]any{"verified": true}) return err } // authError maps PocketBase's sign-in failures like authenticate does. func (s *Service) authError(err error) error { var pbErr *pocketbase.Error if errors.As(err, &pbErr) { if pbErr.Status == http.StatusBadRequest && len(pbErr.Data) == 0 { return ErrInvalidCredentials } if pbErr.Status == http.StatusForbidden { return ErrAccountDisabled } } return mapError(err) }