Mobile app (Android):
- Sign-in to any server, with authenticator codes. The server address and
token are kept in secure storage; a dropped connection never signs out.
- Workspaces, recent pages, spaces and a foldable page tree; search; the
inbox with mark-read.
- Pages open read-only in the shared editor from their saved content and
join the live document to edit (with the native toolbar). Page links in
the text open in the app (new "navigate" bridge message).
- Comments: threads, replies, resolve.
- "Save to Docwell" in the Android share sheet makes a page from shared
text, with web addresses as links.
- Offline reading: every answer the app reads is kept on the phone, and
used when the server can't be reached.
- Push through UnifiedPush (ntfy, NextPush, ...). The app uses the Android
connector directly; the umbrella package pulls in a native crypto build
for Linux that breaks `dart run` and tests.
Server:
- /me/devices registers a phone's UnifiedPush endpoint and Web Push keys
(new push_devices collection). Each notification is also pushed,
encrypted with RFC 8291 aes128gcm so the distributor can't read it; the
app drops messages that don't decrypt. Endpoints answering 404/410 are
forgotten. Endpoints follow the webhook address rules.
- /collab accepts the apps' own origins ("null" for the mobile editor page,
wails:// for the desktop app). Sign-in is a token in the first message,
not a cookie, so this opens no cross-site hijacking.
Tried on an Android 15 emulator: sign-in, browsing, reading, live editing,
sharing and offline reading. Not covered: push end to end (no distributor
on the emulator), iOS, and YouTube embeds, which refuse to play from the
app's local editor page (error 153).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
303 lines
11 KiB
Go
303 lines
11 KiB
Go
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
package httpapi
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"log/slog"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"docwell/server/internal/access"
|
|
"docwell/server/internal/apperr"
|
|
"docwell/server/internal/auth"
|
|
)
|
|
|
|
// AuthService is the part of auth.Service the HTTP layer uses.
|
|
type AuthService interface {
|
|
Methods(ctx context.Context) (auth.Methods, error)
|
|
Signup(ctx context.Context, in auth.SignupInput) (auth.Session, error)
|
|
Login(ctx context.Context, email, password, mfaID string) (auth.Session, error)
|
|
RequestOTP(ctx context.Context, email string) (string, error)
|
|
LoginWithOTP(ctx context.Context, otpID, code, mfaID string) (auth.Session, error)
|
|
Refresh(ctx context.Context, token string) (auth.Session, error)
|
|
Verify(ctx context.Context, token string) (auth.User, error)
|
|
RequestPasswordReset(ctx context.Context, email string) error
|
|
ConfirmPasswordReset(ctx context.Context, token, password string) error
|
|
RequestVerification(ctx context.Context, email string) error
|
|
ConfirmVerification(ctx context.Context, token string) error
|
|
UserByID(ctx context.Context, id string) (auth.User, error)
|
|
|
|
VerifyTOTP(ctx context.Context, challenge, code string) (auth.Session, error)
|
|
TOTPStatus(ctx context.Context, userID string) (auth.TOTPStatus, error)
|
|
StartTOTP(ctx context.Context, u auth.User, issuer string) (auth.TOTPSetup, error)
|
|
EnableTOTP(ctx context.Context, u auth.User, code string) ([]string, error)
|
|
DisableTOTP(ctx context.Context, u auth.User, code string) error
|
|
ResetTOTP(ctx context.Context, userID string) error
|
|
|
|
StartOAuth(ctx context.Context, provider, redirect string) (auth.OAuthStart, error)
|
|
FinishOAuth(ctx context.Context, state, code string) (auth.Session, error)
|
|
|
|
CreateAPIToken(ctx context.Context, u auth.User, name, scope string, expiresDays int) (auth.NewAPIToken, error)
|
|
ListAPITokens(ctx context.Context, userID string) ([]auth.APIToken, error)
|
|
AdminListAPITokens(ctx context.Context, c access.Caller) ([]auth.APIToken, error)
|
|
RevokeAPIToken(ctx context.Context, c access.Caller, id string, manage func(ownerID string) error) error
|
|
VerifyAPIToken(ctx context.Context, token string) (auth.User, string, error)
|
|
}
|
|
|
|
type ctxKey struct{}
|
|
|
|
// viaTokenKey marks requests authenticated with an API token.
|
|
type viaTokenKey struct{}
|
|
|
|
// CurrentUser returns the signed-in user set by requireUser.
|
|
func CurrentUser(ctx context.Context) (auth.User, bool) {
|
|
u, ok := ctx.Value(ctxKey{}).(auth.User)
|
|
return u, ok
|
|
}
|
|
|
|
type api struct {
|
|
audit AuditService
|
|
auth AuthService
|
|
dir DirectoryService
|
|
settings SettingsService
|
|
files *auth.FileTokens
|
|
instance InstanceService
|
|
collab CollabHub
|
|
previews LinkPreviewer
|
|
push PushService
|
|
log *slog.Logger
|
|
}
|
|
|
|
// requireUser lets in a signed-in user, or an API token acting as its owner
|
|
// ("read" tokens only for reads). Successful changes go to the audit log.
|
|
func (a *api) requireUser(next http.HandlerFunc) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
token := auth.BearerToken(r)
|
|
var u auth.User
|
|
var err error
|
|
ctx := r.Context()
|
|
if strings.HasPrefix(token, auth.TokenPrefix) {
|
|
var scope string
|
|
u, scope, err = a.auth.VerifyAPIToken(ctx, token)
|
|
if err == nil && scope != auth.ScopeWrite && r.Method != http.MethodGet && r.Method != http.MethodHead {
|
|
err = apperr.Forbidden("this API token can only read")
|
|
}
|
|
ctx = context.WithValue(ctx, viaTokenKey{}, true)
|
|
} else {
|
|
u, err = a.auth.Verify(ctx, token)
|
|
}
|
|
if err != nil {
|
|
a.writeError(w, err)
|
|
return
|
|
}
|
|
r = r.WithContext(context.WithValue(ctx, ctxKey{}, u))
|
|
if r.Method == http.MethodGet || r.Method == http.MethodHead || a.audit == nil || unaudited[r.Pattern] {
|
|
next(w, r)
|
|
return
|
|
}
|
|
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
|
|
next(rec, r)
|
|
if rec.status < 400 {
|
|
a.audit.Record(routeEntry(r, u, rec.status))
|
|
}
|
|
}
|
|
}
|
|
|
|
// requireSession is requireUser without API tokens: for managing tokens and
|
|
// two-step sign-in, which a leaked token must not be able to change.
|
|
func (a *api) requireSession(next http.HandlerFunc) http.HandlerFunc {
|
|
return a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
|
if via, _ := r.Context().Value(viaTokenKey{}).(bool); via {
|
|
a.writeError(w, apperr.Forbidden("sign in to do this; API tokens cannot"))
|
|
return
|
|
}
|
|
next(w, r)
|
|
})
|
|
}
|
|
|
|
func (a *api) requireManager(next http.HandlerFunc) http.HandlerFunc {
|
|
return a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
|
if u, _ := CurrentUser(r.Context()); !u.Caller().IsManager() {
|
|
a.writeError(w, apperr.Forbidden("admin role required"))
|
|
return
|
|
}
|
|
next(w, r)
|
|
})
|
|
}
|
|
|
|
func (a *api) routes(mux *routeMux) {
|
|
mux.HandleFunc("GET /api/v1/auth/methods", func(w http.ResponseWriter, r *http.Request) {
|
|
m, err := a.auth.Methods(r.Context())
|
|
a.respond(w, m, err)
|
|
})
|
|
mux.HandleFunc("POST /api/v1/auth/signup", func(w http.ResponseWriter, r *http.Request) {
|
|
var in auth.SignupInput
|
|
if !a.decode(w, r, &in) {
|
|
return
|
|
}
|
|
sess, err := a.auth.Signup(r.Context(), in)
|
|
a.auditAuth(r, "auth.signup", in.Email, sess, err)
|
|
a.respond(w, sess, err)
|
|
})
|
|
mux.HandleFunc("POST /api/v1/auth/login", func(w http.ResponseWriter, r *http.Request) {
|
|
var in struct{ Email, Password, MFAID string }
|
|
if !a.decode(w, r, &in) {
|
|
return
|
|
}
|
|
sess, err := a.auth.Login(r.Context(), in.Email, in.Password, in.MFAID)
|
|
a.auditAuth(r, "auth.login", in.Email, sess, err)
|
|
a.respond(w, sess, err)
|
|
})
|
|
mux.HandleFunc("POST /api/v1/auth/otp/request", func(w http.ResponseWriter, r *http.Request) {
|
|
var in struct{ Email string }
|
|
if !a.decode(w, r, &in) {
|
|
return
|
|
}
|
|
id, err := a.auth.RequestOTP(r.Context(), in.Email)
|
|
a.respond(w, map[string]string{"otpId": id}, err)
|
|
})
|
|
mux.HandleFunc("POST /api/v1/auth/otp/login", func(w http.ResponseWriter, r *http.Request) {
|
|
var in struct{ OTPID, Code, MFAID string }
|
|
if !a.decode(w, r, &in) {
|
|
return
|
|
}
|
|
sess, err := a.auth.LoginWithOTP(r.Context(), in.OTPID, in.Code, in.MFAID)
|
|
a.auditAuth(r, "auth.otp", sess.User.Email, sess, err)
|
|
a.respond(w, sess, err)
|
|
})
|
|
mux.HandleFunc("POST /api/v1/auth/refresh", func(w http.ResponseWriter, r *http.Request) {
|
|
sess, err := a.auth.Refresh(r.Context(), auth.BearerToken(r))
|
|
a.respond(w, sess, err)
|
|
})
|
|
mux.HandleFunc("GET /api/v1/auth/me", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
|
u, _ := CurrentUser(r.Context())
|
|
writeJSON(w, http.StatusOK, u)
|
|
}))
|
|
mux.HandleFunc("POST /api/v1/auth/password-reset/request", func(w http.ResponseWriter, r *http.Request) {
|
|
var in struct{ Email string }
|
|
if !a.decode(w, r, &in) {
|
|
return
|
|
}
|
|
a.respondNoContent(w, a.auth.RequestPasswordReset(r.Context(), in.Email))
|
|
})
|
|
mux.HandleFunc("POST /api/v1/auth/password-reset/confirm", func(w http.ResponseWriter, r *http.Request) {
|
|
var in struct{ Token, Password string }
|
|
if !a.decode(w, r, &in) {
|
|
return
|
|
}
|
|
a.respondNoContent(w, a.auth.ConfirmPasswordReset(r.Context(), in.Token, in.Password))
|
|
})
|
|
mux.HandleFunc("POST /api/v1/auth/verification/request", func(w http.ResponseWriter, r *http.Request) {
|
|
var in struct{ Email string }
|
|
if !a.decode(w, r, &in) {
|
|
return
|
|
}
|
|
a.respondNoContent(w, a.auth.RequestVerification(r.Context(), in.Email))
|
|
})
|
|
mux.HandleFunc("POST /api/v1/auth/verification/confirm", func(w http.ResponseWriter, r *http.Request) {
|
|
var in struct{ Token string }
|
|
if !a.decode(w, r, &in) {
|
|
return
|
|
}
|
|
a.respondNoContent(w, a.auth.ConfirmVerification(r.Context(), in.Token))
|
|
})
|
|
|
|
a.directoryRoutes(mux)
|
|
a.spaceRoutes(mux)
|
|
a.settingsRoutes(mux)
|
|
a.inviteRoutes(mux)
|
|
a.groupRoutes(mux)
|
|
a.favoriteRoutes(mux)
|
|
a.searchRoutes(mux)
|
|
a.transferRoutes(mux)
|
|
a.shareRoutes(mux)
|
|
a.permissionRoutes(mux)
|
|
a.linkRoutes(mux)
|
|
a.pushRoutes(mux)
|
|
a.securityRoutes(mux, a.dir)
|
|
a.webhookRoutes(mux)
|
|
a.commentRoutes(mux)
|
|
a.adminRoutes(mux)
|
|
}
|
|
|
|
func (a *api) decode(w http.ResponseWriter, r *http.Request, v any) bool {
|
|
return a.decodeMax(w, r, v, 1<<20)
|
|
}
|
|
|
|
// decodeMax is decode with a larger body limit, for page content.
|
|
func (a *api) decodeMax(w http.ResponseWriter, r *http.Request, v any, limit int64) bool {
|
|
r.Body = http.MaxBytesReader(w, r.Body, limit)
|
|
if err := json.NewDecoder(r.Body).Decode(v); err != nil {
|
|
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid_json"})
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
func (a *api) respond(w http.ResponseWriter, v any, err error) {
|
|
if err != nil {
|
|
a.writeError(w, err)
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, v)
|
|
}
|
|
|
|
func (a *api) respondNoContent(w http.ResponseWriter, err error) {
|
|
if err != nil {
|
|
a.writeError(w, err)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
// writeError maps domain errors to HTTP responses: {"error": "<code>", ...}.
|
|
func (a *api) writeError(w http.ResponseWriter, err error) {
|
|
if e, ok := apperr.As(err); ok {
|
|
status := map[apperr.Kind]int{
|
|
apperr.KindInvalid: http.StatusBadRequest,
|
|
apperr.KindForbidden: http.StatusForbidden,
|
|
apperr.KindNotFound: http.StatusNotFound,
|
|
apperr.KindConflict: http.StatusConflict,
|
|
}[e.Kind]
|
|
body := map[string]any{"error": e.Code, "message": e.Message}
|
|
if len(e.Fields) > 0 {
|
|
body["fields"] = e.Fields
|
|
}
|
|
writeJSON(w, status, body)
|
|
return
|
|
}
|
|
var mfa *auth.MFARequiredError
|
|
var totp *auth.TOTPRequiredError
|
|
var verr *auth.ValidationError
|
|
switch {
|
|
case errors.As(err, &mfa):
|
|
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "mfa_required", "mfaId": mfa.MFAID})
|
|
case errors.As(err, &totp):
|
|
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "totp_required", "challenge": totp.Challenge})
|
|
case errors.Is(err, auth.ErrInvalidCode):
|
|
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid_code"})
|
|
case errors.As(err, &verr):
|
|
writeJSON(w, http.StatusBadRequest, map[string]any{"error": "validation", "fields": verr.Fields})
|
|
case errors.Is(err, auth.ErrInvalidCredentials):
|
|
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "invalid_credentials"})
|
|
case errors.Is(err, auth.ErrUnauthorized):
|
|
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "unauthorized"})
|
|
case errors.Is(err, auth.ErrAccountDisabled):
|
|
writeJSON(w, http.StatusForbidden, map[string]string{"error": "account_disabled"})
|
|
case errors.Is(err, auth.ErrForbidden):
|
|
writeJSON(w, http.StatusForbidden, map[string]string{"error": "forbidden"})
|
|
case errors.Is(err, auth.ErrSignupDisabled):
|
|
writeJSON(w, http.StatusForbidden, map[string]string{"error": "signup_disabled"})
|
|
case errors.Is(err, auth.ErrDomainNotAllowed):
|
|
writeJSON(w, http.StatusForbidden, map[string]string{"error": "domain_not_allowed"})
|
|
case errors.Is(err, auth.ErrInvalidToken):
|
|
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid_token"})
|
|
default:
|
|
a.log.Error("request failed", "err", err)
|
|
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "internal"})
|
|
}
|
|
}
|