package handlers // Unified Nextcloud connect (Settings → Nextcloud): ONE credential entry // connects the three DAV siblings at once — files (WebDAV), calendars // (CalDAV) and contacts (CardDAV) — against the same Nextcloud account. // This is an orchestration surface, not a fourth connector: it composes the // per-user DAV roots server-side, reuses each sibling's plan gate, field // validation, caps and credential verification, and stores one ordinary // connection row per protocol. The per-protocol tabs keep managing their // rows; the separate Contacts sync (Contact rows powering contact-linking) // is deliberately untouched. // // House disciplines carried over: // - the password is encrypted per row, never returned, never logged; // - each connector's entitlement gate applies independently — a plan that // only includes carddav connects contacts and reports the other two as // gated (partial success is a first-class result, never all-or-nothing); // - credentials are VERIFIED before anything is stored: parallel // netguard-pinned probes (the server's WriteTimeout is 60s; three // sequential 25s probes would not fit), each sharing its protocol's // /test outbound budget. A wrong password stores nothing; // - a repeat call with the same origin+username is idempotent: an existing // row with the composed URL is reported as "exists", never duplicated; // - materialization stays on the existing /sync surfaces (the UI fires // them right after connect), so limiters, budgets and timeouts remain // the siblings' own. import ( "context" "database/sql" "errors" "net/http" "net/url" "strings" "sync" "time" "gitea.federated.computer/Federated_Computer/superbrain/internal/auth" "gitea.federated.computer/Federated_Computer/superbrain/internal/caldav" "gitea.federated.computer/Federated_Computer/superbrain/internal/carddav" "gitea.federated.computer/Federated_Computer/superbrain/internal/config" crypt "gitea.federated.computer/Federated_Computer/superbrain/internal/crypto" "gitea.federated.computer/Federated_Computer/superbrain/internal/db" "gitea.federated.computer/Federated_Computer/superbrain/internal/outbound" "gitea.federated.computer/Federated_Computer/superbrain/internal/webdav" ) const nextcloudVerifyTimeout = 25 * time.Second // nextcloudConnector binds one result key to its sibling surface. Everything // protocol-specific (gate, validation incl. CardDAV's https/443 pin, caps, // projection, verification) is the sibling's own code — this file only // composes URLs and orchestrates. type nextcloudConnector struct { key string // result key: files | calendars | contacts label string // cap-error wording, matches the sibling create table string maxConns int name string // connection (and WebDAV collection) name root string // path between the origin and the username budget string // outbound.Reserve prefix, shared with the sibling /test listSQL string gate func(*http.Request) (bool, error) clean func(object, bool) (object, error) project func(object) object verify func(ctx context.Context, baseURL, username, password string) error } var nextcloudConnectors = []nextcloudConnector{ { key: "files", label: "WebDAV", table: "WebDavConnection", maxConns: maxWebdavConns, name: "Nextcloud files", root: "/remote.php/dav/files/", budget: "webdav-test:", listSQL: `SELECT to_jsonb(t) FROM "WebDavConnection" t WHERE "ownerId"=$1 ORDER BY "createdAt"`, gate: webdavConnectorGate, clean: cleanWebdavFields, project: webdavProjection, verify: func(ctx context.Context, baseURL, username, password string) error { return webdav.Check(ctx, webdav.Conn{BaseURL: baseURL, Username: username, Password: password}) }, }, { key: "calendars", label: "CalDAV", table: "CalDavConnection", maxConns: maxCalDavConns, name: "Nextcloud calendars", root: "/remote.php/dav/calendars/", budget: "caldav-test:", listSQL: `SELECT to_jsonb(t)||jsonb_build_object( 'calendars',COALESCE((SELECT jsonb_agg(jsonb_build_object('href',c.href,'name',c."displayName",'collectionId',c."collectionId") ORDER BY c."displayName") FROM "CalDavCalendar" c WHERE c."connectionId"=t.id),'[]'::jsonb)) FROM "CalDavConnection" t WHERE "ownerId"=$1 ORDER BY "createdAt"`, gate: caldavConnectorGate, clean: cleanCalDavFields, project: caldavProjection, verify: func(ctx context.Context, baseURL, username, password string) error { _, err := caldav.Discover(ctx, caldav.Conn{BaseURL: baseURL, Username: username, Password: password}) return err }, }, { key: "contacts", label: "CardDAV", table: "CardDavConnection", maxConns: maxCardDavConns, name: "Nextcloud contacts", root: "/remote.php/dav/addressbooks/users/", budget: "carddav-test:", listSQL: `SELECT to_jsonb(t)||jsonb_build_object( 'addressbooks',COALESCE((SELECT jsonb_agg(jsonb_build_object('href',a.href,'name',a."displayName",'collectionId',a."collectionId") ORDER BY a."displayName") FROM "CardDavAddressbook" a WHERE a."connectionId"=t.id),'[]'::jsonb)) FROM "CardDavConnection" t WHERE "ownerId"=$1 ORDER BY "createdAt"`, gate: carddavConnectorGate, clean: cleanCardDavFields, project: carddavProjection, verify: func(ctx context.Context, baseURL, username, password string) error { _, err := carddav.Discover(ctx, carddav.Conn{BaseURL: baseURL, Username: username, Password: password}) return err }, }, } // nextcloudOrigin normalizes the submitted server URL to the Nextcloud base // (scheme://host[/subdirectory]). A pasted DAV endpoint is accepted too: the // path is cut at /remote.php/ so subdirectory installs keep their prefix. func nextcloudOrigin(raw string) (string, error) { s := strings.TrimSpace(raw) if !validURL(s) || len(s) > 2048 { return "", bad("url must be an absolute http(s) URL without credentials") } u, e := url.Parse(s) if e != nil { return "", bad("url must be an absolute http(s) URL without credentials") } u.RawQuery, u.Fragment = "", "" if i := strings.Index(u.Path, "/remote.php/"); i >= 0 { u.Path = u.Path[:i] } u.Path = strings.TrimRight(u.Path, "/") return strings.TrimRight(u.String(), "/"), nil } // nextcloudErrMsg surfaces validation/cap messages verbatim (clientError) // and never leaks internal DB errors into a per-connector result. func nextcloudErrMsg(e error) string { var ce clientError if errors.As(e, &ce) { return ce.message } return "Could not save the connection" } // HandleNextcloudStatus gives the unified tab everything in one fetch: the // deployment's Nextcloud origin hint (NEXTCLOUD_URL, empty when unset) and, // per connector, the plan `allowed` flag plus the caller's existing // connections (masked, same projections as the sibling lists). func HandleNextcloudStatus(w http.ResponseWriter, r *http.Request) { out := object{"origin": config.NextcloudSuggestion()} for _, nc := range nextcloudConnectors { allowed, e := nc.gate(r) if e != nil { respond(w, 0, nil, e) return } rows, e := db.Many(r.Context(), database(r), nc.listSQL, user(r)) if e != nil { respond(w, 0, nil, e) return } conns := make([]object, 0, len(rows)) for _, row := range rows { conns = append(conns, nc.project(row)) } out[nc.key] = object{"allowed": allowed, "connections": conns} } respond(w, 200, out, nil) } var nextcloudConnectLimiter = auth.NewLimiterStore() // NextcloudConnectLimiter bounds unified connects per user (each opens up to // three outbound verification sessions). func NextcloudConnectLimiter(next http.HandlerFunc) http.HandlerFunc { return auth.LimiterKeyed(nextcloudConnectLimiter, 10, time.Hour, user)(next) } // HandleNextcloudConnect verifies one credential against all three DAV // roots and stores one connection per protocol that passes. Per-connector // outcomes are data in a 200 response — "created", "exists", "gated" or // "error" (message verbatim) — so a partial plan or a single unreachable // service never sinks the whole connect. Only malformed input is a 400. func HandleNextcloudConnect(w http.ResponseWriter, r *http.Request) { b, ok := read(w, r) if !ok { return } origin, e := nextcloudOrigin(str(b, "url")) if e != nil { respond(w, 0, nil, e) return } username := strings.TrimSpace(str(b, "username")) if username == "" { respond(w, 0, nil, bad("username is required")) return } if len([]rune(username)) > maxWebdavUser { respond(w, 0, nil, bad("username is too long (max 200)")) return } password := str(b, "password") if password == "" || password == mcpSecretMask { respond(w, 0, nil, bad("password is required")) return } if len(password) > maxWebdavSecret { respond(w, 0, nil, bad("password is too long")) return } results := map[string]object{} type pending struct { nc nextcloudConnector fields object url string } var todo []pending for _, nc := range nextcloudConnectors { u := origin + nc.root + url.PathEscape(username) + "/" allowed, e := nc.gate(r) if e != nil { respond(w, 0, nil, e) return } if !allowed { results[nc.key] = object{"status": "gated", "url": u, "error": "Not available on your plan"} continue } // The sibling's own validation — including CardDAV's https/443 pin, // which an http origin fails for contacts alone. fields, e := nc.clean(object{"name": nc.name, "url": u, "username": username}, true) if e != nil { results[nc.key] = object{"status": "error", "url": u, "error": nextcloudErrMsg(e)} continue } // Idempotent: the composed URL already connected stays as it is. var id, name string e = database(r).QueryRowContext(r.Context(), `SELECT id, name FROM `+db.Quote(nc.table)+` WHERE "ownerId"=$1 AND url=$2`, user(r), u).Scan(&id, &name) if e == nil { results[nc.key] = object{"status": "exists", "id": id, "name": name, "url": u} continue } if !errors.Is(e, sql.ErrNoRows) { respond(w, 0, nil, e) return } todo = append(todo, pending{nc: nc, fields: fields, url: u}) } // Verify in parallel: each probe is netguard-pinned by its protocol and // draws from the same outbound budget as that protocol's /test. var mu sync.Mutex var wg sync.WaitGroup verified := map[string]bool{} for _, p := range todo { wg.Add(1) go func(p pending) { defer wg.Done() release, _, ok := outbound.Reserve(p.nc.budget+user(r), 10, time.Minute) if !ok { mu.Lock() results[p.nc.key] = object{"status": "error", "url": p.url, "error": "Too much outbound work right now; try again shortly"} mu.Unlock() return } defer release() ctx, cancel := context.WithTimeout(r.Context(), nextcloudVerifyTimeout) defer cancel() err := p.nc.verify(ctx, p.url, username, password) mu.Lock() defer mu.Unlock() if err != nil { results[p.nc.key] = object{"status": "error", "url": p.url, "error": truncate(err.Error(), 200)} return } verified[p.nc.key] = true }(p) } wg.Wait() // Store what verified — ordinary creates, per-protocol caps apply. for _, p := range todo { if !verified[p.nc.key] { continue } enc, e := crypt.Encrypt(password, config.Load().EncryptionSecret()) if e != nil { results[p.nc.key] = object{"status": "error", "url": p.url, "error": nextcloudErrMsg(e)} continue } p.fields["secret"] = enc p.fields["enabled"] = true row, e := nextcloudInsertConn(r, p.nc, p.fields) if e != nil { results[p.nc.key] = object{"status": "error", "url": p.url, "error": nextcloudErrMsg(e)} continue } results[p.nc.key] = object{"status": "created", "id": str(row, "id"), "name": str(row, "name"), "url": p.url} } respond(w, 200, object{"results": results}, nil) } // nextcloudInsertConn mirrors the sibling create transaction (user lock, // per-owner cap, insert) without duplicating it three times. func nextcloudInsertConn(r *http.Request, nc nextcloudConnector, fields object) (object, error) { var row object e := db.Transaction(r.Context(), database(r), func(tx *sql.Tx) error { if e := lockUser(r, tx); e != nil { return e } var n int if e := tx.QueryRowContext(r.Context(), `SELECT count(*) FROM `+db.Quote(nc.table)+` WHERE "ownerId"=$1`, user(r)).Scan(&n); e != nil { return e } if n >= nc.maxConns { return bad(nc.label + " connection limit reached; remove one first") } fields["id"] = db.NewID() fields["ownerId"] = user(r) var e error row, e = db.Insert(r.Context(), tx, nc.table, fields) return e }) return row, e }