Scaffold Docwell monorepo with PocketBase authentication

Phase 0 foundation for Docwell, an open-source knowledge base:

- Database: PocketBase v0.40.6 with initial schema migrations; users is
  the built-in auth collection, plus a hook for token checks and
  env-driven app URL/SMTP settings
- Server: Go API (health, version, auth endpoints forwarded to
  PocketBase, admin user list) with an embedded Vue admin panel
- Web-App: Go static server and Vue/Tailwind app with Tiptap editor,
  sign-in, sign-up, password reset and email verification (EN/PL)
- Desktop-App: Wails v3 host reusing the web app
- Phone-App: Flutter app with sign-in
- Shared packages (editor, ui, api-client), OpenAPI spec, Docker
  compose (separate services and all-in-one), GitHub Actions CI
- Docs: feature inventory and architecture/build plan

Licensed under AGPL-3.0-or-later.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tajniak81andClaude Opus 5.5 committed 2026-10-30 22:18:25 +01:00
commit 4903bb12dd
264 files changed
+21422

No files matched your search

+199
View File
@@ -0,0 +1,199 @@
package httpapi
import (
"context"
"encoding/json"
"errors"
"log/slog"
"net/http"
"strconv"
"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
ListUsers(ctx context.Context, in auth.ListUsersInput) (auth.UserList, error)
}
type ctxKey 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 {
auth AuthService
log *slog.Logger
}
func (a *api) requireUser(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
u, err := a.auth.Verify(r.Context(), auth.BearerToken(r))
if err != nil {
a.writeError(w, err)
return
}
next(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, u)))
}
}
func (a *api) requireAdmin(next http.HandlerFunc) http.HandlerFunc {
return a.requireUser(func(w http.ResponseWriter, r *http.Request) {
if u, _ := CurrentUser(r.Context()); !u.IsAdmin {
a.writeError(w, auth.ErrForbidden)
return
}
next(w, r)
})
}
func (a *api) routes(mux *http.ServeMux) {
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.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.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.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))
})
mux.HandleFunc("GET /api/v1/admin/users", a.requireAdmin(func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
page, _ := strconv.Atoi(q.Get("page"))
perPage, _ := strconv.Atoi(q.Get("perPage"))
list, err := a.auth.ListUsers(r.Context(), auth.ListUsersInput{Page: page, PerPage: min(max(perPage, 0), 200), Search: q.Get("q")})
a.respond(w, list, err)
}))
}
func (a *api) decode(w http.ResponseWriter, r *http.Request, v any) bool {
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
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) {
var mfa *auth.MFARequiredError
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, &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"})
}
}
+128
View File
@@ -0,0 +1,128 @@
package httpapi
import (
"context"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"docwell/server/internal/auth"
)
// fakeAuth implements the AuthService calls these tests reach; the embedded
// nil interface panics on anything else.
type fakeAuth struct {
AuthService
}
var (
alice = auth.User{ID: "u1", Email: "alice@docwell.test", Name: "Alice", Status: "active"}
admin = auth.User{ID: "u2", Email: "root@docwell.test", Name: "Root", Status: "active", IsAdmin: true}
)
func (fakeAuth) Verify(_ context.Context, token string) (auth.User, error) {
switch token {
case "alice":
return alice, nil
case "admin":
return admin, nil
case "disabled":
return auth.User{}, auth.ErrAccountDisabled
}
return auth.User{}, auth.ErrUnauthorized
}
func (fakeAuth) Login(_ context.Context, email, password, mfaID string) (auth.Session, error) {
switch {
case email == "mfa@docwell.test" && mfaID == "":
return auth.Session{}, &auth.MFARequiredError{MFAID: "m1"}
case email == alice.Email && password == "password123":
return auth.Session{Token: "alice", User: alice}, nil
}
return auth.Session{}, auth.ErrInvalidCredentials
}
func (fakeAuth) Signup(_ context.Context, in auth.SignupInput) (auth.Session, error) {
return auth.Session{}, &auth.ValidationError{Fields: map[string]string{"password": "too short"}}
}
func (fakeAuth) ListUsers(context.Context, auth.ListUsersInput) (auth.UserList, error) {
return auth.UserList{Items: []auth.User{alice, admin}, TotalItems: 2}, nil
}
func authRouter() http.Handler {
return NewRouter(Deps{
Version: "test",
DB: fakeDB{},
Auth: fakeAuth{},
Log: slog.New(slog.NewTextHandler(io.Discard, nil)),
})
}
func send(h http.Handler, method, path, token, body string) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, path, strings.NewReader(body))
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
func TestLoginResponses(t *testing.T) {
h := authRouter()
cases := []struct {
body string
wantStatus int
wantBody string
}{
{`{"email":"alice@docwell.test","password":"password123"}`, 200, `"token":"alice"`},
{`{"email":"alice@docwell.test","password":"nope"}`, 401, `"invalid_credentials"`},
{`{"email":"mfa@docwell.test","password":"x"}`, 401, `"mfaId":"m1"`},
{`not json`, 400, `"invalid_json"`},
}
for _, c := range cases {
rec := send(h, "POST", "/api/v1/auth/login", "", c.body)
if rec.Code != c.wantStatus || !strings.Contains(rec.Body.String(), c.wantBody) {
t.Errorf("login %s = %d %s", c.body, rec.Code, rec.Body)
}
}
}
func TestSignupValidationError(t *testing.T) {
rec := send(authRouter(), "POST", "/api/v1/auth/signup", "", `{"email":"a@b.c","password":"x","name":"A"}`)
if rec.Code != 400 || !strings.Contains(rec.Body.String(), `"fields":{"password":"too short"}`) {
t.Errorf("signup = %d %s", rec.Code, rec.Body)
}
}
func TestMeRequiresValidToken(t *testing.T) {
h := authRouter()
if rec := send(h, "GET", "/api/v1/auth/me", "", ""); rec.Code != 401 {
t.Errorf("no token = %d", rec.Code)
}
if rec := send(h, "GET", "/api/v1/auth/me", "disabled", ""); rec.Code != 403 {
t.Errorf("disabled = %d", rec.Code)
}
rec := send(h, "GET", "/api/v1/auth/me", "alice", "")
if rec.Code != 200 || !strings.Contains(rec.Body.String(), `"email":"alice@docwell.test"`) {
t.Errorf("me = %d %s", rec.Code, rec.Body)
}
}
func TestAdminUsersRequiresAdmin(t *testing.T) {
h := authRouter()
if rec := send(h, "GET", "/api/v1/admin/users", "", ""); rec.Code != 401 {
t.Errorf("anonymous = %d", rec.Code)
}
if rec := send(h, "GET", "/api/v1/admin/users", "alice", ""); rec.Code != 403 {
t.Errorf("non-admin = %d", rec.Code)
}
rec := send(h, "GET", "/api/v1/admin/users?perPage=5000", "admin", "")
if rec.Code != 200 || !strings.Contains(rec.Body.String(), `"totalItems":2`) {
t.Errorf("admin = %d %s", rec.Code, rec.Body)
}
}
+102
View File
@@ -0,0 +1,102 @@
// Package httpapi wires the public HTTP surface of docwell-server.
package httpapi
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"slices"
"time"
)
// Pinger reports whether a dependency is reachable.
type Pinger interface {
Health(ctx context.Context) error
}
type Deps struct {
Version string
CORSOrigins []string
DB Pinger
Auth AuthService
Admin http.Handler
Log *slog.Logger
}
func NewRouter(d Deps) http.Handler {
mux := http.NewServeMux()
(&api{auth: d.Auth, log: d.Log}).routes(mux)
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
})
mux.HandleFunc("GET /readyz", func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
defer cancel()
if err := d.DB.Health(ctx); err != nil {
d.Log.Warn("readiness check failed", "err", err)
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"status": "unavailable", "db": err.Error()})
return
}
writeJSON(w, http.StatusOK, map[string]string{"status": "ok", "db": "ok"})
})
mux.HandleFunc("GET /api/v1/version", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"name": "docwell-server", "version": d.Version})
})
mux.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "not_found"})
})
if d.Admin != nil {
mux.Handle("GET /admin/", d.Admin)
mux.Handle("GET /admin", http.RedirectHandler("/admin/", http.StatusMovedPermanently))
}
return logRequests(d.Log, cors(d.CORSOrigins, mux))
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
func cors(origins []string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if origin != "" && slices.Contains(origins, origin) {
h := w.Header()
h.Set("Access-Control-Allow-Origin", origin)
h.Set("Access-Control-Allow-Credentials", "true")
h.Add("Vary", "Origin")
if r.Method == http.MethodOptions {
h.Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
h.Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
h.Set("Access-Control-Max-Age", "600")
w.WriteHeader(http.StatusNoContent)
return
}
}
next.ServeHTTP(w, r)
})
}
type statusRecorder struct {
http.ResponseWriter
status int
}
func (s *statusRecorder) WriteHeader(code int) {
s.status = code
s.ResponseWriter.WriteHeader(code)
}
func logRequests(log *slog.Logger, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(rec, r)
log.Info("http", "method", r.Method, "path", r.URL.Path, "status", rec.status, "dur", time.Since(start))
})
}
+72
View File
@@ -0,0 +1,72 @@
package httpapi
import (
"context"
"errors"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
type fakeDB struct{ err error }
func (f fakeDB) Health(context.Context) error { return f.err }
func newTestRouter(db Pinger) http.Handler {
return NewRouter(Deps{
Version: "test",
CORSOrigins: []string{"https://app.docwell.test"},
DB: db,
Log: slog.New(slog.NewTextHandler(io.Discard, nil)),
})
}
func do(h http.Handler, method, path string, header map[string]string) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, path, nil)
for k, v := range header {
req.Header.Set(k, v)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
func TestHealthAndVersion(t *testing.T) {
h := newTestRouter(fakeDB{})
if rec := do(h, "GET", "/healthz", nil); rec.Code != http.StatusOK {
t.Errorf("/healthz = %d", rec.Code)
}
rec := do(h, "GET", "/api/v1/version", nil)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"version":"test"`) {
t.Errorf("/api/v1/version = %d %s", rec.Code, rec.Body)
}
if rec := do(h, "GET", "/api/v1/nope", nil); rec.Code != http.StatusNotFound {
t.Errorf("unknown api route = %d", rec.Code)
}
}
func TestReadiness(t *testing.T) {
if rec := do(newTestRouter(fakeDB{}), "GET", "/readyz", nil); rec.Code != http.StatusOK {
t.Errorf("ready = %d", rec.Code)
}
if rec := do(newTestRouter(fakeDB{err: errors.New("down")}), "GET", "/readyz", nil); rec.Code != http.StatusServiceUnavailable {
t.Errorf("db down = %d", rec.Code)
}
}
func TestCORS(t *testing.T) {
h := newTestRouter(fakeDB{})
rec := do(h, "OPTIONS", "/api/v1/version", map[string]string{"Origin": "https://app.docwell.test"})
if rec.Code != http.StatusNoContent || rec.Header().Get("Access-Control-Allow-Origin") != "https://app.docwell.test" {
t.Errorf("preflight = %d %v", rec.Code, rec.Header())
}
rec = do(h, "GET", "/api/v1/version", map[string]string{"Origin": "https://evil.test"})
if rec.Header().Get("Access-Control-Allow-Origin") != "" {
t.Error("unknown origin must not be allowed")
}
}