Phase E of the AFFiNE parity plan (ADR-15): - internal/ai: OpenAI-compatible, Anthropic (official Go SDK) and Ollama drivers; BYOK profiles per workspace and for the instance, with keys encrypted by DOCWELL_SECRET_KEY, failover order, a test call and usage counters. - Embeddings: an indexer that follows PocketBase like the search index, chunks pages along their blocks and keeps vectors in a bbolt file in the data dir (no cgo); progress, ignored pages and extra files. - Chat sessions scoped to a page, space or workspace, streamed as server-sent events, with citations to pages and blocks, fork and history; retrieval only from pages the asker can read. - Writing actions (rewrite, fix, shorter, longer, summarise, translate, continue, custom) in the editor's selection toolbar. - POST /mcp: MCP over Streamable HTTP with personal API tokens; read tokens search and read pages, write tokens also create and update them. - Web app chat panel (Ctrl+J), workspace AI settings, an admin AI page, OpenAPI, generated clients, migration and translations. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
234 lines
8.5 KiB
Go
234 lines
8.5 KiB
Go
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
package httpapi
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"io"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"docwell/server/internal/access"
|
|
"docwell/server/internal/audit"
|
|
"docwell/server/internal/auth"
|
|
)
|
|
|
|
// AuditService records and reads the audit log.
|
|
type AuditService interface {
|
|
Record(e audit.Entry)
|
|
List(ctx context.Context, c access.Caller, q audit.Query) (audit.Page, error)
|
|
ExportCSV(ctx context.Context, c access.Caller, q audit.Query, w io.Writer) error
|
|
}
|
|
|
|
// UserManager is the part of directory.Service that checks a manager's
|
|
// rights over another user.
|
|
type UserManager interface {
|
|
CanManageUser(ctx context.Context, c access.Caller, id string) error
|
|
// AccountByEmail finds an account's id and organization (empty when
|
|
// there is none), to file sign-in attempts under the right organization.
|
|
AccountByEmail(ctx context.Context, email string) (id, org string)
|
|
}
|
|
|
|
// unaudited are changes too frequent or too slight for the audit log.
|
|
var unaudited = map[string]bool{
|
|
"POST /api/v1/pages/{id}/visit": true,
|
|
"POST /api/v1/notifications/read": true,
|
|
"POST /api/v1/files/token": true,
|
|
"PUT /api/v1/pages/{id}/favorite": true,
|
|
"POST /api/v1/comments/{id}/reactions": true,
|
|
// Questions and writing help change no page; their sessions are private.
|
|
"POST /api/v1/ai/sessions/{id}/messages": true,
|
|
"POST /api/v1/workspaces/{id}/ai/write": true,
|
|
"POST /api/v1/workspaces/{id}/ai/sessions": true,
|
|
"POST /api/v1/ai/sessions/{id}/fork": true,
|
|
"PATCH /api/v1/ai/sessions/{id}": true,
|
|
"DELETE /api/v1/ai/sessions/{id}": true,
|
|
}
|
|
|
|
// routeEntry describes a successful change request: the route (without the
|
|
// /api/v1 prefix), the ids in its path and who made it. Never the body.
|
|
func routeEntry(r *http.Request, u auth.User, status int) audit.Entry {
|
|
route := strings.Replace(r.Pattern, " /api/v1/", " /", 1)
|
|
e := audit.Entry{
|
|
Action: route, ActorID: u.ID, ActorEmail: u.Email, Org: u.Organization, Status: status,
|
|
IP: audit.ClientIP(r), UserAgent: r.UserAgent(),
|
|
}
|
|
if _, path, ok := strings.Cut(route, " /"); ok {
|
|
e.TargetType, _, _ = strings.Cut(path, "/")
|
|
}
|
|
e.TargetID = r.PathValue("id")
|
|
meta := map[string]any{}
|
|
for _, k := range []string{"userId", "groupId", "pageId", "fileId", "name", "key"} {
|
|
if v := r.PathValue(k); v != "" {
|
|
meta[k] = v
|
|
}
|
|
}
|
|
if via, _ := r.Context().Value(viaTokenKey{}).(bool); via {
|
|
meta["apiToken"] = true
|
|
}
|
|
if len(meta) > 0 {
|
|
e.Meta = meta
|
|
}
|
|
return e
|
|
}
|
|
|
|
// auditAuth records a sign-in step: success (with the user), a failure, or
|
|
// a second step being asked for.
|
|
func (a *api) auditAuth(r *http.Request, action, email string, sess auth.Session, err error) {
|
|
if a.audit == nil {
|
|
return
|
|
}
|
|
e := audit.Entry{Action: action, ActorEmail: email, IP: audit.ClientIP(r), UserAgent: r.UserAgent(), Status: http.StatusOK}
|
|
var totp *auth.TOTPRequiredError
|
|
switch {
|
|
case err == nil:
|
|
e.ActorID, e.ActorEmail, e.Org = sess.User.ID, sess.User.Email, sess.User.Organization
|
|
case errors.As(err, &totp):
|
|
e.Action += ".second_step"
|
|
e.Status = http.StatusUnauthorized
|
|
default:
|
|
e.Action += ".failed"
|
|
e.Status = http.StatusUnauthorized
|
|
e.Meta = map[string]any{"reason": err.Error()}
|
|
}
|
|
if e.ActorID == "" && email != "" && a.dir != nil {
|
|
e.ActorID, e.Org = a.dir.AccountByEmail(r.Context(), email)
|
|
}
|
|
a.audit.Record(e)
|
|
}
|
|
|
|
func (a *api) securityRoutes(mux *routeMux, users UserManager) {
|
|
// Second step of sign-in, and sign-in with a provider.
|
|
mux.HandleFunc("POST /api/v1/auth/totp/verify", func(w http.ResponseWriter, r *http.Request) {
|
|
var in struct{ Challenge, Code string }
|
|
if !a.decode(w, r, &in) {
|
|
return
|
|
}
|
|
sess, err := a.auth.VerifyTOTP(r.Context(), in.Challenge, in.Code)
|
|
a.auditAuth(r, "auth.totp", sess.User.Email, sess, err)
|
|
a.respond(w, sess, err)
|
|
})
|
|
mux.HandleFunc("POST /api/v1/auth/oauth2/start", func(w http.ResponseWriter, r *http.Request) {
|
|
var in struct{ Provider, Redirect string }
|
|
if !a.decode(w, r, &in) {
|
|
return
|
|
}
|
|
start, err := a.auth.StartOAuth(r.Context(), in.Provider, in.Redirect)
|
|
a.respond(w, start, err)
|
|
})
|
|
mux.HandleFunc("POST /api/v1/auth/oauth2/finish", func(w http.ResponseWriter, r *http.Request) {
|
|
var in struct{ State, Code string }
|
|
if !a.decode(w, r, &in) {
|
|
return
|
|
}
|
|
sess, err := a.auth.FinishOAuth(r.Context(), in.State, in.Code)
|
|
a.auditAuth(r, "auth.oauth2", sess.User.Email, sess, err)
|
|
a.respond(w, sess, err)
|
|
})
|
|
|
|
// The caller's own two-step sign-in and API tokens: sessions only.
|
|
mux.HandleFunc("GET /api/v1/me/totp", a.requireSession(func(w http.ResponseWriter, r *http.Request) {
|
|
u, _ := CurrentUser(r.Context())
|
|
st, err := a.auth.TOTPStatus(r.Context(), u.ID)
|
|
a.respond(w, st, err)
|
|
}))
|
|
mux.HandleFunc("POST /api/v1/me/totp/setup", a.requireSession(func(w http.ResponseWriter, r *http.Request) {
|
|
u, _ := CurrentUser(r.Context())
|
|
issuer := "Docwell"
|
|
if a.settings != nil {
|
|
if p, err := a.settings.Public(r.Context()); err == nil && p.AppName != "" {
|
|
issuer = p.AppName
|
|
}
|
|
}
|
|
setup, err := a.auth.StartTOTP(r.Context(), u, issuer)
|
|
a.respond(w, setup, err)
|
|
}))
|
|
mux.HandleFunc("POST /api/v1/me/totp/enable", a.requireSession(func(w http.ResponseWriter, r *http.Request) {
|
|
var in struct{ Code string }
|
|
if !a.decode(w, r, &in) {
|
|
return
|
|
}
|
|
u, _ := CurrentUser(r.Context())
|
|
codes, err := a.auth.EnableTOTP(r.Context(), u, in.Code)
|
|
a.respond(w, map[string][]string{"recoveryCodes": codes}, err)
|
|
}))
|
|
mux.HandleFunc("POST /api/v1/me/totp/disable", a.requireSession(func(w http.ResponseWriter, r *http.Request) {
|
|
var in struct{ Code string }
|
|
if !a.decode(w, r, &in) {
|
|
return
|
|
}
|
|
u, _ := CurrentUser(r.Context())
|
|
a.respondNoContent(w, a.auth.DisableTOTP(r.Context(), u, in.Code))
|
|
}))
|
|
mux.HandleFunc("GET /api/v1/me/tokens", a.requireSession(func(w http.ResponseWriter, r *http.Request) {
|
|
u, _ := CurrentUser(r.Context())
|
|
list, err := a.auth.ListAPITokens(r.Context(), u.ID)
|
|
a.respond(w, list, err)
|
|
}))
|
|
mux.HandleFunc("POST /api/v1/me/tokens", a.requireSession(func(w http.ResponseWriter, r *http.Request) {
|
|
var in struct {
|
|
Name string
|
|
Scope string
|
|
ExpiresDays int
|
|
}
|
|
if !a.decode(w, r, &in) {
|
|
return
|
|
}
|
|
u, _ := CurrentUser(r.Context())
|
|
t, err := a.auth.CreateAPIToken(r.Context(), u, in.Name, in.Scope, in.ExpiresDays)
|
|
a.respondStatus(w, http.StatusCreated, t, err)
|
|
}))
|
|
mux.HandleFunc("DELETE /api/v1/me/tokens/{id}", a.requireSession(func(w http.ResponseWriter, r *http.Request) {
|
|
u, _ := CurrentUser(r.Context())
|
|
a.respondNoContent(w, a.auth.RevokeAPIToken(r.Context(), u.Caller(), r.PathValue("id"), nil))
|
|
}))
|
|
|
|
// Admins: the audit log, everyone's tokens, and resetting two-step sign-in.
|
|
query := func(r *http.Request) audit.Query {
|
|
q := r.URL.Query()
|
|
page, _ := strconv.Atoi(q.Get("page"))
|
|
perPage, _ := strconv.Atoi(q.Get("perPage"))
|
|
return audit.Query{Search: q.Get("q"), Since: q.Get("since"), Until: q.Get("until"), Page: page, PerPage: perPage}
|
|
}
|
|
mux.HandleFunc("GET /api/v1/admin/audit", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
|
|
if a.audit == nil {
|
|
writeJSON(w, http.StatusOK, audit.Page{Items: []audit.View{}})
|
|
return
|
|
}
|
|
page, err := a.audit.List(r.Context(), caller(r), query(r))
|
|
a.respond(w, page, err)
|
|
}))
|
|
mux.HandleFunc("GET /api/v1/admin/audit/export", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
|
|
if a.audit == nil {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
|
|
w.Header().Set("Content-Disposition", `attachment; filename="docwell-audit-`+time.Now().UTC().Format("2006-01-02")+`.csv"`)
|
|
if err := a.audit.ExportCSV(r.Context(), caller(r), query(r), w); err != nil {
|
|
a.log.Error("audit export", "err", err)
|
|
}
|
|
}))
|
|
mux.HandleFunc("GET /api/v1/admin/tokens", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
|
|
list, err := a.auth.AdminListAPITokens(r.Context(), caller(r))
|
|
a.respond(w, list, err)
|
|
}))
|
|
mux.HandleFunc("DELETE /api/v1/admin/tokens/{id}", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
|
|
c := caller(r)
|
|
a.respondNoContent(w, a.auth.RevokeAPIToken(r.Context(), c, r.PathValue("id"), func(owner string) error {
|
|
return users.CanManageUser(r.Context(), c, owner)
|
|
}))
|
|
}))
|
|
mux.HandleFunc("DELETE /api/v1/users/{id}/totp", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
|
|
id := r.PathValue("id")
|
|
if err := users.CanManageUser(r.Context(), caller(r), id); err != nil {
|
|
a.writeError(w, err)
|
|
return
|
|
}
|
|
a.respondNoContent(w, a.auth.ResetTOTP(r.Context(), id))
|
|
}))
|
|
}
|