diff --git a/.env.example b/.env.example index fd27472..ad4d49a 100644 --- a/.env.example +++ b/.env.example @@ -77,7 +77,7 @@ OIDC_CLIENT_SECRET=REPLACE_ME # previews, CardDAV and IMAP stay fully guarded. Never list a name a user # can influence. #NETGUARD_TRUSTED_HOSTS= -# Nextcloud origin for the Settings -> WebDAV and CalDAV suggestion cards. +# Nextcloud origin for the Settings -> WebDAV, CalDAV and CardDAV suggestion cards. # On Core the installer writes https://nextcloud.; unset or malformed # means the suggestions are simply not offered. This is a convenience hint # (deployment DATA, never a TIER code fork) - it gates no access and allows diff --git a/API.md b/API.md index 369942f..aec5536 100644 --- a/API.md +++ b/API.md @@ -180,6 +180,39 @@ not abort the others, and a truncated window (50 calendars / 500 events) never reconciles deletions. Basic-auth headers only, no redirects, netguard-pinned; `AllowConnector("caldav")` gates creation AND every sync. +### CardDAV address books + +Users connect external CardDAV endpoints (Settings -> CardDAV; any RFC 6352 +service). Each **server address book** materializes as its **own Collection** +and every **contact** becomes a **bookmark** whose `url` is the card's DAV +`.vcf` location (`FN` titles it; email/phone ride in the description as +display sugar, never rewritten after creation). The engine +(`internal/carddav`) re-pulls every enabled connection every ~30 minutes +under its own advisory lease; `CardDavConnection` + `CardDavAddressbook` + +`CardDavItem` (migration 022) store credentials, the book-to-Collection map +and the card ledger. `NEXTCLOUD_URL` (on Core) adds a `…/remote.php/dav/ +addressbooks/users/` suggestion. This surface is deliberately separate from +the single-config Contacts sync (`POST /api/contacts/sync`, Contact rows): +same transport discipline, different product model. + +| Method | Path | Returns / behavior | +|---|---|---| +| GET | `/api/carddav/connections` | `{connections:[...],allowed,suggestions:[...]}` -- each connection carries `addressbooks:[{href,name,collectionId}]`; password masked, `allowed` is the plan gate | +| POST | `/api/carddav/connections` | 201 masked projection; `{name,url,username,password}`; https-only and port-443-only (Basic-auth credentials never travel elsewhere; escape hatch off in production); cap 10 per user; **403** when the plan lacks the `carddav` connector | +| PATCH | `/api/carddav/connections/{id}` | masked projection; **requires `version`** (409 on stale); mask or omitted `password` keeps the stored value | +| DELETE | `/api/carddav/connections/{id}` | `{ok:true}`; 404 for another user's row. Removes only the connection and its ledgers -- the collections and contact bookmarks stay | +| POST | `/api/carddav/connections/{id}/test` | `{ok:true,addressbooks:[name,...]}` after discovery; **502** `{ok:false,error}` with the failure class | +| POST | `/api/carddav/connections/{id}/sync` | `{ok,books,cards,created,reused,updated,kept,removed,truncated}`; 403 when the plan dropped the connector; failed discovery lands on `lastError` | + +Rules: identical ledger discipline to the WebDAV/CalDAV siblings (idempotent +syncs, etag refreshes never touch user-edited fields, vanished cards detach +membership but keep the bookmark, user-deleted bookmarks are tombstones, +removed memberships stay removed unless the whole Collection was deleted, +truncated listings never reconcile deletions, one unreadable book does not +abort the rest). Discovery accepts a single address book or a home holding +several. Dials pin to **443 only** and refuse redirects; the `carddav` +connector gates creation AND every sync. + ## Bookmarks diff --git a/README.md b/README.md index 2ab5428..8006e1c 100644 --- a/README.md +++ b/README.md @@ -570,7 +570,7 @@ is off without it. | `SMTP_USERNAME` / `SMTP_PASSWORD` | no | — | AUTH PLAIN when the relay requires it | | `SMTP_FROM` | **with SMTP_HOST** | — | Envelope+header sender | | `NETGUARD_TRUSTED_HOSTS` | no | empty | Comma-separated operator-pinned hostnames allowed to resolve to private addresses (split-horizon relays). Never user-supplied names | -| `NEXTCLOUD_URL` | no | empty | Nextcloud origin; when set (Core writes `https://nextcloud.`), Settings → WebDAV and CalDAV offer one-click Nextcloud prefills. A convenience hint (deployment DATA, never a TIER code fork) — it gates nothing and allows nothing; a malformed value is ignored | +| `NEXTCLOUD_URL` | no | empty | Nextcloud origin; when set (Core writes `https://nextcloud.`), Settings → WebDAV/CalDAV/CardDAV offer one-click Nextcloud prefills. A convenience hint (deployment DATA, never a TIER code fork) — it gates nothing and allows nothing; a malformed value is ignored | ### AI (assistant, automations) diff --git a/db/migrations/022_carddav_shares.sql b/db/migrations/022_carddav_shares.sql new file mode 100644 index 0000000..bffac46 --- /dev/null +++ b/db/migrations/022_carddav_shares.sql @@ -0,0 +1,65 @@ +-- 022_carddav_shares.sql — user-connected CardDAV address books. +-- +-- Additive and idempotent; schema.sql carries the identical tables, so this +-- is a structural no-op on a fresh database (db-converge proves both paths +-- land the same). +-- +-- A connected CardDAV endpoint (any RFC 6352 service; Settings -> CardDAV) +-- materializes each address book as its own Collection whose members are +-- bookmarks -- one per contact, carrying the card's DAV .vcf URL. +-- CardDavAddressbook maps book-href to Collection; CardDavItem is the +-- (address book, card path) ledger with the exact WebDavItem/CalDavEvent +-- semantics: bookmarkId ON DELETE SET NULL leaves a tombstone so a +-- user-deleted contact bookmark is never resurrected, and a card removed on +-- the server detaches membership only. +-- +-- Credentials follow the house discipline (username clear, app password +-- encrypted via internal/crypto, masked, write-only). Production dials pin +-- to 443 like the existing Contacts CardDAV sync (review M-3/CR-01: Basic +-- auth credentials never travel to arbitrary ports), carry the credential in +-- the Authorization header only, and refuse redirects. Mutations carry the +-- row version (409 on stale); engine bookkeeping never bumps it. + +CREATE TABLE IF NOT EXISTS "CardDavConnection" ( + id text PRIMARY KEY, + "ownerId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE, + name text NOT NULL, + url text NOT NULL, + username text NOT NULL, + secret text NOT NULL, + enabled boolean NOT NULL DEFAULT true, + "lastSyncedAt" timestamptz, + "lastError" text, + version integer NOT NULL DEFAULT 1, + "createdAt" timestamptz NOT NULL DEFAULT now(), + "updatedAt" timestamptz NOT NULL DEFAULT now() +); + +CREATE INDEX IF NOT EXISTS "CardDavConnection_ownerId_idx" ON "CardDavConnection"("ownerId"); + +CREATE TABLE IF NOT EXISTS "CardDavAddressbook" ( + id text PRIMARY KEY, + "connectionId" text NOT NULL REFERENCES "CardDavConnection"(id) ON DELETE CASCADE, + href text NOT NULL, + "displayName" text NOT NULL DEFAULT '', + "collectionId" text REFERENCES "Collection"(id) ON DELETE SET NULL, + "createdAt" timestamptz NOT NULL DEFAULT now(), + "updatedAt" timestamptz NOT NULL DEFAULT now(), + UNIQUE ("connectionId", href) +); + +CREATE INDEX IF NOT EXISTS "CardDavAddressbook_connectionId_idx" ON "CardDavAddressbook"("connectionId"); + +CREATE TABLE IF NOT EXISTS "CardDavItem" ( + id text PRIMARY KEY, + "addressbookId" text NOT NULL REFERENCES "CardDavAddressbook"(id) ON DELETE CASCADE, + path text NOT NULL, + "bookmarkId" text REFERENCES "Bookmark"(id) ON DELETE SET NULL, + etag text NOT NULL DEFAULT '', + uid text NOT NULL DEFAULT '', + "createdAt" timestamptz NOT NULL DEFAULT now(), + "updatedAt" timestamptz NOT NULL DEFAULT now(), + UNIQUE ("addressbookId", path) +); + +CREATE INDEX IF NOT EXISTS "CardDavItem_addressbookId_idx" ON "CardDavItem"("addressbookId"); diff --git a/db/schema.sql b/db/schema.sql index c736e03..65b8af8 100644 --- a/db/schema.sql +++ b/db/schema.sql @@ -745,6 +745,69 @@ CREATE TABLE "CalDavEvent" ( ); CREATE INDEX "CalDavEvent_calendarId_idx" ON "CalDavEvent"("calendarId"); +-- 2.17h CardDavConnection: user-connected CardDAV address books (any RFC +-- 6352 service; Settings -> CardDAV). The endpoint may be one address book or +-- a home holding several - each address book materializes as its own +-- Collection (2.17i) and every contact becomes a Bookmark (URL = the card's +-- DAV .vcf location, 2.17j). Credentials follow the house discipline: +-- username in the clear, password encrypted at rest, masked in every +-- response, write-only. Production dials are pinned to 443 (CardDAV carries +-- Basic-auth credentials; the existing contacts sync set that precedent in +-- review M-3/CR-01 and this surface keeps it), redirects are refused, and +-- user-supplied hosts get no netguard exemption. Mutating PATCHes carry +-- version (409 on stale); engine bookkeeping never bumps it. This is +-- separate from the single-configuration Contacts sync (Contact rows + +-- provenance) that powers contact-linking: same transport, different +-- product surface. See migration 022_carddav_shares.sql. +CREATE TABLE "CardDavConnection" ( + id text PRIMARY KEY, + "ownerId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE, + name text NOT NULL, + url text NOT NULL, + username text NOT NULL, + secret text NOT NULL, + enabled boolean NOT NULL DEFAULT true, + "lastSyncedAt" timestamptz, + "lastError" text, + version integer NOT NULL DEFAULT 1, + "createdAt" timestamptz NOT NULL DEFAULT now(), + "updatedAt" timestamptz NOT NULL DEFAULT now() +); +CREATE INDEX "CardDavConnection_ownerId_idx" ON "CardDavConnection"("ownerId"); + +-- 2.17i CardDavAddressbook: one discovered address book under a connection, +-- with the Collection it materializes into (calendar-pattern re-materialize +-- on user-deleted collection via SET NULL). +CREATE TABLE "CardDavAddressbook" ( + id text PRIMARY KEY, + "connectionId" text NOT NULL REFERENCES "CardDavConnection"(id) ON DELETE CASCADE, + href text NOT NULL, + "displayName" text NOT NULL DEFAULT '', + "collectionId" text REFERENCES "Collection"(id) ON DELETE SET NULL, + "createdAt" timestamptz NOT NULL DEFAULT now(), + "updatedAt" timestamptz NOT NULL DEFAULT now(), + UNIQUE ("connectionId", href) +); +CREATE INDEX "CardDavAddressbook_connectionId_idx" ON "CardDavAddressbook"("connectionId"); + +-- 2.17j CardDavItem: path-bookmark ledger per address book - the exact +-- WebDavItem/CalDavEvent semantics: bookmarkId NULL = user-deleted +-- tombstone (never resurrected), etag refreshes never touch user-edited +-- bookmark fields, a vanished card detaches membership but keeps the +-- bookmark. UNIQUE(addressbookId, path). +CREATE TABLE "CardDavItem" ( + id text PRIMARY KEY, + "addressbookId" text NOT NULL REFERENCES "CardDavAddressbook"(id) ON DELETE CASCADE, + path text NOT NULL, + "bookmarkId" text REFERENCES "Bookmark"(id) ON DELETE SET NULL, + etag text NOT NULL DEFAULT '', + uid text NOT NULL DEFAULT '', + "createdAt" timestamptz NOT NULL DEFAULT now(), + "updatedAt" timestamptz NOT NULL DEFAULT now(), + UNIQUE ("addressbookId", path) +); +CREATE INDEX "CardDavItem_addressbookId_idx" ON "CardDavItem"("addressbookId"); + -- 2.18 PageEmbed (Notion-like upgrades phase 3): a live collection view -- embedded in a page. The reference is resolved from the page's Markdown -- (`{{collection:|view=}}`) on every content save. Only collections diff --git a/deploy/federated/lib-superbrain.sh b/deploy/federated/lib-superbrain.sh index b40c682..e360e4e 100644 --- a/deploy/federated/lib-superbrain.sh +++ b/deploy/federated/lib-superbrain.sh @@ -230,11 +230,11 @@ SMTP_PASSWORD=$SUPERBRAIN_SMTP_PASSWORD SMTP_FROM=superbrain@$DOMAIN NETGUARD_TRUSTED_HOSTS=mail.$DOMAIN -# --- WebDAV + CalDAV shares (Settings → WebDAV / CalDAV) ------------------- +# --- DAV shares (Settings → WebDAV / CalDAV / CardDAV) ---------------------- # Nextcloud runs on this core, so Superbrain offers it as a one-click prefill -# for both file shares and calendars (purely a hint - every connection still -# needs the person's own username and app password; see API.md "WebDAV file -# shares" and "CalDAV calendars"). +# for file shares, calendars and address books (purely a hint - every +# connection still needs the person's own username and app password; see the +# three DAV sections in API.md). NEXTCLOUD_URL=https://nextcloud.$DOMAIN EOF chmod 600 /federated/apps/superbrain/.env diff --git a/internal/carddav/client.go b/internal/carddav/client.go new file mode 100644 index 0000000..83d9ba0 --- /dev/null +++ b/internal/carddav/client.go @@ -0,0 +1,496 @@ +// Package carddav dials external CardDAV address books on behalf of users +// (Settings → CardDAV): any RFC 6352 service (Nextcloud, Contacts.app via a +// server, SOGo, …). Each address book materializes as a Collection whose +// members are bookmarks — one per contact, carrying the card's DAV .vcf +// URL (see sync.go). +// +// House rules enforced here (internal/webdav/internal/caldav siblings, with +// one CardDAV-specific difference): +// - every dial goes through internal/netguard; user-supplied hosts get NO +// trusted-range exemption, and production dials are pinned to 443 ONLY — +// CardDAV ships Basic-auth credentials, and the existing Contacts sync +// set that precedent in review M-3/CR-01 (tests flip +// INTEGRATIONS_ALLOW_PRIVATE like every suite); +// - credentials travel ONLY in an Authorization: Basic header, never in +// the URL; +// - redirects are NOT followed; +// - discovery and queries are bounded (address books, cards) and a +// truncated answer is reported so the caller never reconciles deletions +// against a partial listing. +package carddav + +import ( + "context" + "encoding/xml" + "fmt" + "io" + "net" + "net/http" + "net/url" + "path" + "strings" + "time" + + "github.com/andrew/superbrain/internal/netguard" +) + +// Conn is the dial-relevant projection of a stored CardDavConnection row +// plus its DECRYPTED password. BaseURL is one address book or a home +// holding several. +type Conn struct { + BaseURL string + Username string + Password string +} + +// Addressbook is one discovered collection (the base itself, or its +// addressbook children). +type Addressbook struct { + Href string // decoded absolute path + URL string // absolute https URL + DisplayName string +} + +// Card is one contact returned by an addressbook-query REPORT. +type Card struct { + Path string // relative to the address book + URL string // the .vcf DAV location — becomes the bookmark URL + ETag string + UID string + Name string // FN + Email string + Phone string +} + +// CardResult is a bounded listing. +type CardResult struct { + Cards []Card + Truncated bool // a cap was hit; callers must NOT reconcile deletions +} + +const ( + dialTimeout = 45 * time.Second + reportLimit = 8 << 20 // 8 MiB response cap (matches the contacts sync) + maxBooks = 50 + maxCards = 2000 + nameCap = 200 + emailCap = 320 + phoneCap = 64 + uidCap = 512 +) + +// dial mirrors internal/caldav but pins production to 443 only — CardDAV +// credentials must never travel to an arbitrary public port (review M-3). +func dial() *http.Transport { + return &http.Transport{ + DialContext: func(ctx context.Context, network, address string) (net.Conn, error) { + if netguard.AllowPrivate() { + return netguard.DialContext(ctx, network, address) + } + return netguard.DialContextPorts(ctx, network, address, 443) + }, + TLSHandshakeTimeout: 10 * time.Second, + ResponseHeaderTimeout: 30 * time.Second, + IdleConnTimeout: 30 * time.Second, + } +} + +func httpClient(conn Conn) *http.Client { + return &http.Client{ + Transport: basicRT{base: dial(), conn: conn}, + Timeout: dialTimeout, + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, + } +} + +// basicRT injects the credential per request. Clone so the shared transport +// never mutates the caller's request. +type basicRT struct { + base http.RoundTripper + conn Conn +} + +func (b basicRT) RoundTrip(r *http.Request) (*http.Response, error) { + r2 := r.Clone(r.Context()) + r2.SetBasicAuth(b.conn.Username, b.conn.Password) + return b.base.RoundTrip(r2) +} + +// Discover resolves the endpoint to a set of address books: a base that IS +// an address book (resourcetype ) yields itself; +// otherwise its Depth:1 addressbook children are returned. Finding none is +// an error (a wrong path must not read as "zero books"). +func Discover(ctx context.Context, conn Conn) ([]Addressbook, error) { + base, err := normalizeBase(conn.BaseURL) + if err != nil { + return nil, err + } + self, err := propfind(ctx, conn, base.String(), "0") + if err != nil { + return nil, err + } + if len(self) == 1 && self[0].isAddressbook { + name := self[0].displayName + if name == "" { + name = niceSegment(self[0].href) + } + return []Addressbook{{Href: self[0].href, URL: hrefToURL(base, self[0].href), DisplayName: name}}, nil + } + entries, err := propfind(ctx, conn, base.String(), "1") + if err != nil { + return nil, err + } + var out []Addressbook + seen := map[string]bool{} + for _, e := range entries { + if !e.isAddressbook || seen[e.href] { + continue + } + seen[e.href] = true + name := e.displayName + if name == "" { + name = niceSegment(e.href) + } + out = append(out, Addressbook{Href: e.href, URL: hrefToURL(base, e.href), DisplayName: name}) + if len(out) >= maxBooks { + break + } + } + if len(out) == 0 { + return nil, fmt.Errorf("no CardDAV address books found at that path") + } + return out, nil +} + +// Cards runs an addressbook-query REPORT over one book and parses each +// returned vCard (FN/UID/EMAIL/TEL). +func Cards(ctx context.Context, conn Conn, bookURL string) (*CardResult, error) { + res, err := report(ctx, conn, bookURL) + if err != nil { + return nil, err + } + defer res.Body.Close() + if res.StatusCode != http.StatusMultiStatus { + return nil, describe(res) + } + raw, err := io.ReadAll(io.LimitReader(res.Body, reportLimit+1)) + if err != nil { + return nil, fmt.Errorf("CardDAV query failed: %w", err) + } + if len(raw) > reportLimit { + return nil, fmt.Errorf("CardDAV address book response exceeded the %d MiB cap", reportLimit>>20) + } + var ms multiStatus + if err := xml.Unmarshal(raw, &ms); err != nil { + return nil, fmt.Errorf("CardDAV server returned an unreadable card listing") + } + out := &CardResult{} + bookPath := strings.TrimSuffix(decodeHref(pathOf(bookURL)), "/") + for _, r := range ms.Responses { + href := decodeHref(r.Href) + if strings.TrimSuffix(href, "/") == bookPath { + continue // the book itself + } + var ics, etag string + for _, ps := range r.PropStats { + if ps.Prop.ETag != "" { + etag = strings.Trim(ps.Prop.ETag, `"`) + } + if ps.Prop.Data.Inner != "" || ps.Prop.Data.Value != "" { + ics = unwrapVCard(ps.Prop.Data.Inner, ps.Prop.Data.Value) + } + } + v := parseVCard(ics) + if v["fn"] == "" && v["uid"] == "" { + continue // an unreadable card is skipped, never titled by its path-UID + } + rel := strings.TrimPrefix(href, bookPath+"/") + if rel == "" || rel == href || strings.Contains(rel, "..") { + continue + } + name := v["fn"] + if name == "" { + name = niceSegment(rel) + } + out.Cards = append(out.Cards, Card{ + Path: rel, URL: bookPathEscape(bookURL, rel), ETag: etag, + UID: cap(v["uid"], uidCap), Name: cap(name, nameCap), + Email: cap(v["email"], emailCap), Phone: cap(v["tel"], phoneCap), + }) + if len(out.Cards) >= maxCards { + out.Truncated = true + break + } + } + return out, nil +} + +// --- REPORT / PROPFIND plumbing ---------------------------------------------- + +type msResourceType struct { + Addressbook *struct{} `xml:"addressbook"` +} + +type msData struct { + Value string `xml:",chardata"` + Inner string `xml:",innerxml"` +} + +type msProp struct { + ResourceType msResourceType `xml:"resourcetype"` + DisplayName string `xml:"displayname"` + ETag string `xml:"getetag"` + Data msData `xml:"address-data"` +} + +type msPropStat struct { + Prop msProp `xml:"prop"` +} + +type msResp struct { + Href string `xml:"href"` + PropStats []msPropStat `xml:"propstat"` +} + +type multiStatus struct { + Responses []msResp `xml:"response"` +} + +type parsed struct { + href string + isAddressbook bool + displayName string +} + +const propfindBody = `` + + `` + +func propfind(ctx context.Context, conn Conn, target, depth string) ([]parsed, error) { + req, err := http.NewRequestWithContext(ctx, "PROPFIND", target, strings.NewReader(propfindBody)) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "application/xml") + req.Header.Set("Depth", depth) + res, err := httpClient(conn).Do(req) + if err != nil { + return nil, fmt.Errorf("could not reach the CardDAV server: %w", err) + } + defer res.Body.Close() + if res.StatusCode != http.StatusMultiStatus { + return nil, describe(res) + } + raw, err := io.ReadAll(io.LimitReader(res.Body, reportLimit)) + if err != nil { + return nil, fmt.Errorf("CardDAV listing failed: %w", err) + } + var ms multiStatus + if err := xml.Unmarshal(raw, &ms); err != nil { + return nil, fmt.Errorf("CardDAV server returned an unreadable listing") + } + out := make([]parsed, 0, len(ms.Responses)) + for _, r := range ms.Responses { + p := parsed{href: decodeHref(r.Href)} + // A trailing slash alone is NOT proof of an address book; only the + // resourcetype marker is (checked below). + for _, ps := range r.PropStats { + if ps.Prop.ResourceType.Addressbook != nil { + p.isAddressbook = true + } + if ps.Prop.DisplayName != "" { + p.displayName = ps.Prop.DisplayName + } + } + out = append(out, p) + } + return out, nil +} + +const reportBody = `` + + `` + +func report(ctx context.Context, conn Conn, target string) (*http.Response, error) { + req, err := http.NewRequestWithContext(ctx, "REPORT", target, strings.NewReader(reportBody)) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "application/xml") + req.Header.Set("Depth", "1") + res, err := httpClient(conn).Do(req) + if err != nil { + return nil, fmt.Errorf("could not reach the CardDAV address book: %w", err) + } + return res, nil +} + +// describe turns a non-207 answer into a stable, secret-free error. +func describe(res *http.Response) error { + defer res.Body.Close() + switch { + case res.StatusCode == http.StatusUnauthorized: + return fmt.Errorf("the address book rejected these credentials (401)") + case res.StatusCode == http.StatusForbidden: + return fmt.Errorf("the address book refused access (403)") + case res.StatusCode == http.StatusNotFound: + return fmt.Errorf("no CardDAV resource at that path (404)") + case res.StatusCode >= 300 && res.StatusCode < 400: + return fmt.Errorf("the address book redirected the request; Superbrain refuses to carry credentials across redirects") + case res.StatusCode == http.StatusMethodNotAllowed || res.StatusCode == http.StatusNotImplemented: + return fmt.Errorf("the endpoint does not speak CardDAV (%d)", res.StatusCode) + default: + return fmt.Errorf("unexpected answer from the CardDAV server (%d)", res.StatusCode) + } +} + +// --- URL / path helpers ------------------------------------------------------ + +func normalizeBase(raw string) (*url.URL, error) { + u, err := url.Parse(strings.TrimSpace(raw)) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { + return nil, fmt.Errorf("address book URL must be an absolute http(s) URL") + } + if u.User != nil { + return nil, fmt.Errorf("credentials must be entered as fields, never in the URL") + } + // Decode-once discipline (see internal/webdav): operate on u.Path so a + // user-typed %20 never double-encodes. + p := path.Clean("/" + strings.TrimPrefix(u.Path, "/")) + if p == "/" { + u.Path = "" + } else if !strings.HasSuffix(p, "/") { + p += "/" + } + u.Path = p + u.RawQuery = "" + u.Fragment = "" + return u, nil +} + +func hrefToURL(base *url.URL, href string) string { + return base.Scheme + "://" + base.Host + escapePath(href) +} + +// bookPathEscape joins a card path onto the book URL, escaping segments. +func bookPathEscape(bookURL, rel string) string { + segs := strings.Split(rel, "/") + for i, s := range segs { + segs[i] = url.PathEscape(s) + } + return strings.TrimSuffix(bookURL, "/") + "/" + strings.Join(segs, "/") +} + +func escapePath(p string) string { + segs := strings.Split(strings.TrimPrefix(p, "/"), "/") + for i, s := range segs { + segs[i] = url.PathEscape(s) + } + return "/" + strings.Join(segs, "/") +} + +func decodeHref(h string) string { + if h == "" { + return h + } + if u, err := url.Parse(h); err == nil && (strings.HasPrefix(h, "http") || strings.HasPrefix(h, "/")) { + h = u.Path + } + if d, err := url.PathUnescape(h); err == nil { + return d + } + return h +} + +func pathOf(rawURL string) string { + u, err := url.Parse(rawURL) + if err != nil { + return rawURL + } + return u.Path +} + +func lastSegment(p string) string { + p = strings.TrimSuffix(p, "/") + if i := strings.LastIndex(p, "/"); i >= 0 { + return p[i+1:] + } + return p +} + +func niceSegment(p string) string { + s := strings.NewReplacer("-", " ", "_", " ", "%20", " ").Replace(lastSegment(p)) + s = strings.TrimSpace(s) + if s == "" { + return "Address book" + } + r := []rune(s) + return strings.ToUpper(string(r[0])) + string(r[1:]) +} + +var innerEntities = strings.NewReplacer(" ", "\r", " ", "\n", "<", "<", ">", ">", """, `"`, "&", "&") + +// unwrapVCard recovers the vCard text (chardata is decoder-unescaped and +// wins; innerxml is the fallback for servers wrapping the payload oddly). +func unwrapVCard(inner, value string) string { + if v := strings.TrimSpace(value); v != "" { + return v + } + s := strings.TrimSpace(inner) + if strings.HasPrefix(s, ""); end >= 0 { + s = s[len("= 0 { + s = s[i:] + } + if j := strings.LastIndex(s, "END:VCARD"); j >= 0 { + s = s[:j+len("END:VCARD")] + } + } + return innerEntities.Replace(s) +} + +// parseVCard extracts the fields the ledger needs: FN, UID, EMAIL, TEL. +// Line folding (RFC 6350 3.1) and repeated properties are handled; the +// FIRST occurrence wins (a deliberate simplification — this parser only +// titles bookmarks, unlike the richer vCard reader behind the Contacts +// sync which owns PREF selection and parameter handling). +func parseVCard(s string) map[string]string { + s = strings.ReplaceAll(s, "\r\n ", "") + s = strings.ReplaceAll(s, "\r\n\t", "") + s = strings.ReplaceAll(s, "\n ", "") + s = strings.ReplaceAll(s, "\n\t", "") + out := map[string]string{} + for _, line := range strings.Split(strings.ReplaceAll(s, "\r\n", "\n"), "\n") { + i := strings.IndexByte(line, ':') + if i < 0 { + continue + } + name := line[:i] + if j := strings.IndexByte(name, ';'); j >= 0 { + name = name[:j] + } + if k := strings.LastIndexByte(name, '.'); k >= 0 { + name = name[k+1:] // group prefix (item1.EMAIL) + } + key := strings.ToLower(strings.TrimSpace(name)) + if _, dup := out[key]; dup { + continue + } + v := strings.NewReplacer(`\n`, "\n", `\N`, "\n", `\,`, ",", `\;`, ";", `\\`, `\`).Replace(strings.TrimSpace(line[i+1:])) + if v != "" { + out[key] = v + } + } + return out +} + +func cap(s string, n int) string { + s = strings.Join(strings.Fields(s), " ") // collapse newlines/whitespace + r := []rune(s) + if len(r) > n { + return string(r[:n]) + } + return s +} diff --git a/internal/carddav/client_test.go b/internal/carddav/client_test.go new file mode 100644 index 0000000..faea099 --- /dev/null +++ b/internal/carddav/client_test.go @@ -0,0 +1,142 @@ +package carddav + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func allowPrivate(t *testing.T) { t.Setenv("INTEGRATIONS_ALLOW_PRIVATE", "1") } + +const ( + srvUser = "erwin" + srvPass = "s3cret" +) + +// fakeCards serves a home at /books with one "contacts" address book holding +// two vCards (one folded FN with a parameter-ized EMAIL), plus a plain +// collection child that must NOT be discovered as a book. +func fakeCards(t *testing.T) *httptest.Server { + t.Helper() + vcard1 := "BEGIN:VCARD\r\nVERSION:3.0\r\nUID:uid-ana\r\nFN:Ana\r\n Escobar\r\nEMAIL;type=WORK, PREF:ana@work.example\r\nEMAIL:ana@home.example\r\nTEL:+1 555 0100\r\nEND:VCARD" + vcard2 := "BEGIN:VCARD\nVERSION:4.0\nUID:uid-bo\nFN:Bo Peep\nEND:VCARD" + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + u, p, ok := r.BasicAuth() + if !ok || u != srvUser || p != srvPass { + w.Header().Set("WWW-Authenticate", `Basic realm="x"`) + http.Error(w, "no", http.StatusUnauthorized) + return + } + switch r.Method { + case "PROPFIND": + w.Header().Set("Content-Type", "application/xml") + w.WriteHeader(http.StatusMultiStatus) + if r.URL.Path == "/books/" && r.Header.Get("Depth") == "0" { + io.WriteString(w, `/books/`) + return + } + if r.URL.Path == "/books/" { + io.WriteString(w, ` +/books/ +/books/contacts/Contacts +/books/notes/Notes +`) + return + } + http.Error(w, "no", http.StatusNotFound) + case "REPORT": + w.Header().Set("Content-Type", "application/xml") + w.WriteHeader(http.StatusMultiStatus) + io.WriteString(w, ` +/books/contacts/"book" +/books/contacts/ana.vcf"A1"`+xmlEscape(vcard1)+` +/books/contacts/bo%20peep.vcf"B1"`+xmlEscape(vcard2)+` +`) + default: + http.Error(w, "no", http.StatusMethodNotAllowed) + } + })) + t.Cleanup(ts.Close) + return ts +} + +func xmlEscape(s string) string { + return strings.NewReplacer("&", "&", "<", "<", ">", ">").Replace(s) +} + +func TestDiscoverAddressBooks(t *testing.T) { + allowPrivate(t) + ts := fakeCards(t) + books, err := Discover(context.Background(), Conn{BaseURL: ts.URL + "/books", Username: srvUser, Password: srvPass}) + if err != nil { + t.Fatal(err) + } + if len(books) != 1 || books[0].DisplayName != "Contacts" { + t.Fatalf("want only the Contacts book, got %+v", books) + } +} + +func TestCardsParsesFoldedVCard(t *testing.T) { + allowPrivate(t) + ts := fakeCards(t) + res, err := Cards(context.Background(), Conn{BaseURL: ts.URL, Username: srvUser, Password: srvPass}, ts.URL+"/books/contacts/") + if err != nil { + t.Fatal(err) + } + if res.Truncated || len(res.Cards) != 2 { + t.Fatalf("cards: %+v trunc=%v", res.Cards, res.Truncated) + } + byUID := map[string]Card{} + for _, c := range res.Cards { + byUID[c.UID] = c + } + ana := byUID["uid-ana"] + // Unfolded FN and the FIRST EMAIL occurrence (simple parser by design). + if ana.Name != "Ana Escobar" { + t.Fatalf("folded FN not joined: %q", ana.Name) + } + if ana.Email != "ana@work.example" { + t.Fatalf("email wrong: %q", ana.Email) + } + if ana.Phone != "+1 555 0100" { + t.Fatalf("phone wrong: %q", ana.Phone) + } + if ana.ETag != "A1" { + t.Fatalf("etag wrong: %q", ana.ETag) + } + bo := byUID["uid-bo"] + if bo.Path != "bo peep.vcf" || !strings.HasSuffix(bo.URL, "/books/contacts/bo%20peep.vcf") { + t.Fatalf("path/URL escaping wrong: %+v", bo) + } +} + +func TestDiscoverRejectsUserinfo(t *testing.T) { + if _, err := Discover(context.Background(), Conn{BaseURL: "https://u:p@host/books"}); err == nil || !strings.Contains(err.Error(), "never in the URL") { + t.Fatalf("want userinfo rejection, got %v", err) + } +} + +func TestDiscoverNoBooksIsError(t *testing.T) { + allowPrivate(t) + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/xml") + w.WriteHeader(http.StatusMultiStatus) + io.WriteString(w, `/x/`) + })) + defer ts.Close() + if _, err := Discover(context.Background(), Conn{BaseURL: ts.URL + "/x"}); err == nil || !strings.Contains(err.Error(), "no CardDAV address books") { + t.Fatalf("want no-books error, got %v", err) + } +} + +func TestCardsUnauthIsVerbatim401(t *testing.T) { + allowPrivate(t) + ts := fakeCards(t) + _, err := Cards(context.Background(), Conn{BaseURL: ts.URL, Username: srvUser, Password: "nope"}, ts.URL+"/books/contacts/") + if err == nil || !strings.Contains(err.Error(), "rejected these credentials") { + t.Fatalf("want 401 class error, got %v", err) + } +} diff --git a/internal/carddav/sync.go b/internal/carddav/sync.go new file mode 100644 index 0000000..83a06cb --- /dev/null +++ b/internal/carddav/sync.go @@ -0,0 +1,434 @@ +package carddav + +import ( + "context" + "database/sql" + "errors" + "fmt" + "log" + "math/rand/v2" + "strings" + "time" + + "github.com/andrew/superbrain/internal/config" + crypt "github.com/andrew/superbrain/internal/crypto" + "github.com/andrew/superbrain/internal/db" + "github.com/andrew/superbrain/internal/outbound" +) + +const ( + tick = 5 * time.Minute // engine cadence + syncEvery = 30 * time.Minute // per-connection freshness target + perTick = 8 // connections claimed per tick + syncTimeout = 4 * time.Minute // one full reconcile + lastErrCap = 500 + dialBudget = 10 // outbound.Reserve window per owner + dialWindow = time.Minute + connectorKey = "carddav" // entitlements Connectors allowlist name +) + +// Connection is one stored CardDavConnection row plus its DECRYPTED password. +type Connection struct { + ID, OwnerID, TenantID string + Name, URL, Username string + Password string +} + +// Result summarizes one reconcile pass across every address book. +type Result struct { + Books int `json:"books"` + Cards int `json:"cards"` + Created int `json:"created"` + Reused int `json:"reused"` + Updated int `json:"updated"` + Kept int `json:"kept"` + Removed int `json:"removed"` + Truncated bool `json:"truncated"` +} + +// RunLoop drives the background sync until ctx ends. Mirrors the sibling +// DAV loops: jittered ticks, failures logged not fatal. +func RunLoop(ctx context.Context, d *db.DB) { + time.Sleep(time.Duration(rand.IntN(5000)) * time.Millisecond) + t := time.NewTicker(tick + time.Duration(rand.IntN(20000))*time.Millisecond) + defer t.Stop() + for { + select { + case <-ctx.Done(): + return + case <-t.C: + if err := RunOnce(ctx, d); err != nil { + log.Printf("carddav: tick failed: %v", err) + } + } + } +} + +// RunOnce syncs every due connection once under its own global advisory +// lease (webdav-tick / caldav-tick / carddav-tick never block each other). +// Exported for tests. +func RunOnce(ctx context.Context, d *db.DB) error { + conn, err := d.Conn(ctx) + if err != nil { + return err + } + defer conn.Close() + var locked bool + if err := conn.QueryRowContext(ctx, `SELECT pg_try_advisory_lock(hashtextextended('carddav-tick',0))`).Scan(&locked); err != nil { + return err + } + if !locked { + return nil + } + defer conn.ExecContext(context.WithoutCancel(ctx), `SELECT pg_advisory_unlock(hashtextextended('carddav-tick',0))`) + + rows, err := d.QueryContext(ctx, ` + SELECT c.id, c."ownerId", COALESCE(u."tenantId",''), c.name, c.url, c.username, c.secret + FROM "CardDavConnection" c + LEFT JOIN "User" u ON u.id = c."ownerId" + WHERE c.enabled AND (c."lastSyncedAt" IS NULL + OR c."lastSyncedAt" < now() - make_interval(mins => $1)) + ORDER BY c."lastSyncedAt" NULLS FIRST + LIMIT $2`, int(syncEvery.Minutes()), perTick) + if err != nil { + return err + } + defer rows.Close() + var due []Connection + for rows.Next() { + var c Connection + var secretEnc string + if err := rows.Scan(&c.ID, &c.OwnerID, &c.TenantID, &c.Name, &c.URL, &c.Username, &secretEnc); err != nil { + return err + } + pw, err := crypt.Decrypt(secretEnc, config.Load().EncryptionSecret()) + if err != nil { + markError(ctx, d, c.ID, "stored password could not be decrypted") + continue + } + c.Password = pw + due = append(due, c) + } + if err := rows.Err(); err != nil { + return err + } + for _, c := range due { + if _, err := SyncOne(ctx, d, c); err != nil { + log.Printf("carddav: sync %s: %v", c.ID, err) + } + } + return nil +} + +// SyncOne reconciles one CardDAV connection: every discovered address book +// becomes its own Collection (named by the server's display name) and every +// card becomes a Bookmark carrying the card's DAV .vcf URL — FN as title, +// email/phone in the description as display sugar only. The CardDavItem +// ledger keeps (book href, card path) stable: re-runs are idempotent, +// user-deleted bookmarks stay deleted (tombstones never resurrect), removed +// cards detach membership without destroying the bookmark, and a re-deleted +// Collection is re-created with every live card re-linked. The plan gate +// re-runs at every sync (a downgrade suppresses, never deletes). +func SyncOne(ctx context.Context, d *db.DB, c Connection) (Result, error) { + var res Result + lim, err := db.NewTenantRepo(d).Limits(ctx, c.TenantID) + if err != nil { + return res, err + } + if !lim.AllowConnector(connectorKey) { + markError(ctx, d, c.ID, "Not available on your plan") + return res, errors.New("Not available on your plan") + } + release, _, ok := outbound.Reserve("carddav:"+c.OwnerID, dialBudget, dialWindow) + if !ok { + return res, fmt.Errorf("outbound limit reached for this user; retry shortly") + } + defer release() + + sctx, cancel := context.WithTimeout(ctx, syncTimeout) + defer cancel() + conn := Conn{BaseURL: c.URL, Username: c.Username, Password: c.Password} + books, err := Discover(sctx, conn) + if err != nil { + markError(ctx, d, c.ID, err.Error()) + return res, err + } + type bookCards struct { + book Addressbook + cards *CardResult + collectErr error + } + fetched := make([]bookCards, 0, len(books)) + for _, bk := range books { + cr, e := Cards(sctx, conn, bk.URL) + if e != nil { + log.Printf("carddav: address book %s of %s: %v", bk.Href, c.ID, e) + fetched = append(fetched, bookCards{book: bk, collectErr: e}) + continue + } + fetched = append(fetched, bookCards{book: bk, cards: cr}) + res.Truncated = res.Truncated || cr.Truncated + } + + err = db.Transaction(ctx, d, func(tx *sql.Tx) error { + existingBooks, e := loadBooks(ctx, tx, c.ID) + if e != nil { + return e + } + seenBook := map[string]bool{} + for _, fb := range fetched { + seenBook[fb.book.Href] = true + if fb.collectErr != nil { + continue // an unreachable book keeps its ledger; never mass-detach + } + bookID, colID, reauthored, e := ensureBookCollection(ctx, tx, c, fb.book, existingBooks[fb.book.Href]) + if e != nil { + return e + } + res.Books++ + items, e := loadItems(ctx, tx, bookID) + if e != nil { + return e + } + addMembership := func(bid string) error { + _, e := tx.ExecContext(ctx, `INSERT INTO "CollectionItem" + (id,"collectionId","bookmarkId",position) + SELECT $1,$2,$3,COALESCE(max(position),-1)+1 FROM "CollectionItem" WHERE "collectionId"=$2 + ON CONFLICT ("collectionId","bookmarkId") DO NOTHING`, db.NewID(), colID, bid) + return e + } + seen := map[string]bool{} + for _, cd := range fb.cards.Cards { + seen[cd.Path] = true + row := items[cd.Path] + switch { + case !row.exists: + bid, reused, e := cardBookmark(ctx, tx, c.OwnerID, cd) + if e != nil { + return e + } + if reused { + res.Reused++ + } else { + res.Created++ + } + if _, e := tx.ExecContext(ctx, `INSERT INTO "CardDavItem" + (id,"addressbookId",path,"bookmarkId",etag,uid) + VALUES($1,$2,$3,$4,$5,$6) ON CONFLICT ("addressbookId",path) DO NOTHING`, + db.NewID(), bookID, cd.Path, bid, cd.ETag, cd.UID); e != nil { + return e + } + if e := addMembership(bid); e != nil { + return e + } + case row.bookmarkID == "": + res.Kept++ // tombstone: the owner deleted this contact's bookmark + default: + if row.etag != cd.ETag { + if _, e := tx.ExecContext(ctx, `UPDATE "CardDavItem" SET etag=$2,uid=$3,"updatedAt"=now() WHERE id=$1`, + row.id, cd.ETag, cd.UID); e != nil { + return e + } + res.Updated++ + } else { + res.Kept++ + } + if reauthored { + if e := addMembership(row.bookmarkID); e != nil { + return e + } + } + } + } + res.Cards += len(fb.cards.Cards) + if !fb.cards.Truncated { + for p, row := range items { + if seen[p] { + continue + } + if row.bookmarkID != "" { + if _, e := tx.ExecContext(ctx, `DELETE FROM "CollectionItem" WHERE "collectionId"=$1 AND "bookmarkId"=$2`, colID, row.bookmarkID); e != nil { + return e + } + } + if _, e := tx.ExecContext(ctx, `DELETE FROM "CardDavItem" WHERE id=$1`, row.id); e != nil { + return e + } + res.Removed++ + } + } + } + // Address books that disappeared server-side: detach their cards' + // membership (bookmarks survive), then drop the ledger rows. + for href, row := range existingBooks { + if seenBook[href] { + continue + } + if _, e := tx.ExecContext(ctx, `DELETE FROM "CollectionItem" WHERE "bookmarkId" IN + (SELECT "bookmarkId" FROM "CardDavItem" WHERE "addressbookId"=$1 AND "bookmarkId" IS NOT NULL)`, row.id); e != nil { + return e + } + if _, e := tx.ExecContext(ctx, `DELETE FROM "CardDavAddressbook" WHERE id=$1`, row.id); e != nil { + return e + } + } + if _, e := tx.ExecContext(ctx, `UPDATE "CardDavConnection" SET "lastSyncedAt"=now(),"lastError"=NULL,"updatedAt"=now() WHERE id=$1`, c.ID); e != nil { + return e + } + return nil + }) + if err != nil { + markError(ctx, d, c.ID, err.Error()) + return res, err + } + return res, nil +} + +type bookRow struct { + id string + collectionID string // "" == NULL + exists bool +} + +func loadBooks(ctx context.Context, tx *sql.Tx, connID string) (map[string]bookRow, error) { + rows, err := tx.QueryContext(ctx, `SELECT id, href, COALESCE("collectionId",'') FROM "CardDavAddressbook" WHERE "connectionId"=$1`, connID) + if err != nil { + return nil, err + } + defer rows.Close() + out := map[string]bookRow{} + for rows.Next() { + var r bookRow + var href string + if err := rows.Scan(&r.id, &href, &r.collectionID); err != nil { + return nil, err + } + r.exists = true + out[href] = r + } + return out, rows.Err() +} + +// ensureBookCollection returns the book's ledger row + Collection, +// creating either when missing. reauthored marks a freshly created +// Collection, whose members are all re-linked. +func ensureBookCollection(ctx context.Context, tx *sql.Tx, c Connection, bk Addressbook, row bookRow) (bookID, colID string, reauthored bool, err error) { + name := bk.DisplayName + if strings.TrimSpace(name) == "" { + name = niceSegment(bk.Href) + } + bookID = row.id + if !row.exists { + bookID = db.NewID() + if _, err = db.Insert(ctx, tx, "CardDavAddressbook", db.Object{ + "id": bookID, "connectionId": c.ID, "href": bk.Href, "displayName": name, + }); err != nil { + return "", "", false, err + } + } + if row.collectionID != "" { + var existing string + err = tx.QueryRowContext(ctx, `SELECT id FROM "Collection" WHERE id=$1 AND "ownerId"=$2`, row.collectionID, c.OwnerID).Scan(&existing) + if err == nil { + return bookID, existing, false, nil + } + if !errors.Is(err, sql.ErrNoRows) { + return "", "", false, err + } + } + colID = db.NewID() + if _, err = db.Insert(ctx, tx, "Collection", db.Object{ + "id": colID, "ownerId": c.OwnerID, "name": name, + "description": "CardDAV address book — " + hostOf(c.URL), + }); err != nil { + return "", "", false, err + } + if _, err = db.Insert(ctx, tx, "CollectionView", db.Object{ + "id": db.NewID(), "collectionId": colID, "name": "Table", "type": "TABLE", "position": 0, + }); err != nil { + return "", "", false, err + } + if _, err = tx.ExecContext(ctx, `UPDATE "CardDavAddressbook" SET "collectionId"=$2,"displayName"=$3,"updatedAt"=now() WHERE id=$1`, bookID, colID, name); err != nil { + return "", "", false, err + } + return bookID, colID, true, nil +} + +// cardBookmark reuses the owner's exact-URL bookmark (URL identity) or +// creates one titled with the contact name; email/phone ride along in the +// description for display only — later syncs never rewrite them. +func cardBookmark(ctx context.Context, tx *sql.Tx, ownerID string, cd Card) (string, bool, error) { + var id string + err := tx.QueryRowContext(ctx, `SELECT id FROM "Bookmark" WHERE "ownerId"=$1 AND url=$2 ORDER BY "createdAt" LIMIT 1`, ownerID, cd.URL).Scan(&id) + if err == nil { + return id, true, nil + } + if !errors.Is(err, sql.ErrNoRows) { + return "", false, err + } + id = db.NewID() + data := db.Object{"id": id, "ownerId": ownerID, "url": cd.URL, "title": cd.Name} + desc := make([]string, 0, 2) + if cd.Email != "" { + desc = append(desc, "Email: "+cd.Email) + } + if cd.Phone != "" { + desc = append(desc, "Phone: "+cd.Phone) + } + if len(desc) > 0 { + data["description"] = strings.Join(desc, "\n") + } + if _, err := db.Insert(ctx, tx, "Bookmark", data); err != nil { + return "", false, err + } + return id, false, nil +} + +type itemRow struct { + id string + path string + etag string + bookmarkID string // "" == NULL (tombstone) + exists bool +} + +func loadItems(ctx context.Context, tx *sql.Tx, bookID string) (map[string]itemRow, error) { + rows, err := tx.QueryContext(ctx, `SELECT id, path, etag, COALESCE("bookmarkId",'') FROM "CardDavItem" WHERE "addressbookId"=$1`, bookID) + if err != nil { + return nil, err + } + defer rows.Close() + out := map[string]itemRow{} + for rows.Next() { + var r itemRow + if err := rows.Scan(&r.id, &r.path, &r.etag, &r.bookmarkID); err != nil { + return nil, err + } + r.exists = true + out[r.path] = r + } + return out, rows.Err() +} + +// markError records the engine-visible failure without touching version. +func markError(ctx context.Context, d *db.DB, id string, msg string) { + msg = strings.TrimSpace(msg) + if r := []rune(msg); len(r) > lastErrCap { + msg = string(r[:lastErrCap]) + } + if _, err := d.ExecContext(ctx, `UPDATE "CardDavConnection" SET "lastError"=$2,"updatedAt"=now() WHERE id=$1`, id, msg); err != nil { + log.Printf("carddav: marking %s failed: %v", id, err) + } +} + +func hostOf(raw string) string { + // Shared with the client's helpers; trimmed here for the sync description. + if at := strings.Index(raw, "://"); at >= 0 { + rest := raw[at+3:] + if slash := strings.IndexByte(rest, '/'); slash >= 0 { + rest = rest[:slash] + } + return strings.TrimPrefix(strings.Split(rest, ":")[0], "www.") + } + return raw +} diff --git a/internal/handlers/carddav.go b/internal/handlers/carddav.go new file mode 100644 index 0000000..4569936 --- /dev/null +++ b/internal/handlers/carddav.go @@ -0,0 +1,391 @@ +package handlers + +// CardDAV address books (Settings → CardDAV): a user connects an external +// CardDAV endpoint (any RFC 6352 service; on Core the deployment offers +// Nextcloud as a prefill). Each server address book materializes as its own +// Collection whose members are bookmarks — one per contact, carrying the +// card's DAV .vcf URL — kept in sync by internal/carddav. House disciplines, +// identical to the WebDAV/CalDAV siblings: +// +// - username in the clear, password encrypted at rest, masked in EVERY +// response, write-only (mask or omission on PATCH keeps the stored value); +// - mutating PATCH carries the row version (409 on stale); +// - dials are netguard-pinned to 443 only (CardDAV credentials must never +// travel to arbitrary ports or plaintext — the precedent the Contacts +// sync set in review M-3/CR-01) with no redirect following; +// - the `carddav` connector entitlement gates creation AND every sync; +// - test/sync have their own per-user limiters and outbound budget. +// +// This surface is separate from the single-config Contacts sync (Contact +// rows powering contact-linking): same transport, different product model. + +import ( + "context" + "database/sql" + "net/http" + "net/url" + "strings" + "time" + + "github.com/andrew/superbrain/internal/auth" + "github.com/andrew/superbrain/internal/carddav" + "github.com/andrew/superbrain/internal/config" + crypt "github.com/andrew/superbrain/internal/crypto" + "github.com/andrew/superbrain/internal/db" + "github.com/andrew/superbrain/internal/netguard" + "github.com/andrew/superbrain/internal/outbound" +) + +const ( + maxCardDavConns = 10 + maxCardDavSecret = 2000 + maxCardDavName = 100 + maxCardDavUser = 200 + carddavTestTimeout = 25 * time.Second +) + +// carddavConnectorGate resolves the caller's tenant plan and reports whether +// the `carddav` connector is allowed — the entitlement catalog, never TIER. +func carddavConnectorGate(r *http.Request) (bool, error) { + var tenantID *string + if e := database(r).QueryRowContext(r.Context(), + `SELECT "tenantId" FROM "User" WHERE id=$1`, user(r)).Scan(&tenantID); e != nil { + return false, e + } + tid := "" + if tenantID != nil { + tid = *tenantID + } + lim, e := db.NewTenantRepo(database(r)).Limits(r.Context(), tid) + if e != nil { + return false, e + } + return lim.AllowConnector("carddav"), nil +} + +// carddavProjection is the ONLY shape a connection leaves the API in; the +// `addressbooks` array comes from the list query's subselect. +func carddavProjection(row object) object { + secret := "" + if s, _ := row["secret"].(string); s != "" { + secret = mcpSecretMask + } + return object{ + "id": row["id"], "name": row["name"], "url": row["url"], + "username": row["username"], "secret": secret, + "enabled": row["enabled"], + "lastSyncedAt": row["lastSyncedAt"], "lastError": row["lastError"], + "addressbooks": row["addressbooks"], + "version": row["version"], "createdAt": row["createdAt"], "updatedAt": row["updatedAt"], + } +} + +func cleanCardDavFields(b object, create bool) (object, error) { + out := object{} + if _, present := b["name"]; present || create { + n := strings.TrimSpace(str(b, "name")) + if n == "" { + return nil, bad("name is required") + } + if len([]rune(n)) > maxCardDavName { + return nil, bad("name is too long (max 100)") + } + out["name"] = n + } + if _, present := b["url"]; present || create { + u := strings.TrimSpace(str(b, "url")) + if !validURL(u) || len(u) > 2048 { + return nil, bad("url must be an absolute http(s) URL without credentials") + } + // CardDAV credentials never travel to a non-standard port: pin the + // configured endpoint to 443 like the Contacts sync does (review + // M-3); the loopback/LAN escape hatch stays available for fixtures. + if !netguard.AllowPrivate() && !strings.HasPrefix(strings.ToLower(u), "https://") { + return nil, bad("CardDAV URL must use https") + } + if !netguard.AllowPrivate() { + if pu, e := url.Parse(u); e == nil && pu.Port() != "" && pu.Port() != "443" { + return nil, bad("CardDAV URL must use port 443") + } + } + out["url"] = u + } + if _, present := b["username"]; present || create { + n := strings.TrimSpace(str(b, "username")) + if n == "" { + return nil, bad("username is required") + } + if len([]rune(n)) > maxCardDavUser { + return nil, bad("username is too long (max 200)") + } + out["username"] = n + } + if v, present := b["enabled"]; present { + ev, ok := v.(bool) + if !ok { + return nil, bad("enabled must be boolean") + } + out["enabled"] = ev + } + return out, nil +} + +// carddavSecretFor: password required on create, kept on mask/omission. +func carddavSecretFor(b object, create bool) (string, bool, error) { + submitted, present := b["password"] + if !present { + if create { + return "", false, bad("password is required") + } + return "", true, nil + } + s, _ := submitted.(string) + if s == "" || s == mcpSecretMask { + if create { + return "", false, bad("password is required") + } + return "", true, nil + } + if len(s) > maxCardDavSecret { + return "", false, bad("password is too long") + } + enc, e := crypt.Encrypt(s, config.Load().EncryptionSecret()) + if e != nil { + return "", false, e + } + return enc, false, nil +} + +// HandleCardDavConnectionsList returns the caller's connections (masked, +// with their address-book lists) plus the plan `allowed` flag and the +// deployment's Nextcloud suggestion. +func HandleCardDavConnectionsList(w http.ResponseWriter, r *http.Request) { + rows, e := db.Many(r.Context(), database(r), `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"`, user(r)) + if e != nil { + respond(w, 0, nil, e) + return + } + allowed, e := carddavConnectorGate(r) + if e != nil { + respond(w, 0, nil, e) + return + } + out := make([]object, 0, len(rows)) + for _, row := range rows { + out = append(out, carddavProjection(row)) + } + suggestions := []object{} + if nc := config.NextcloudSuggestion(); nc != "" { + suggestions = append(suggestions, object{ + "kind": "nextcloud", "name": "Nextcloud contacts", + "url": nc + "/remote.php/dav/addressbooks/users/", + }) + } + respond(w, 200, object{"connections": out, "allowed": allowed, "suggestions": suggestions}, nil) +} + +func HandleCardDavConnectionsCreate(w http.ResponseWriter, r *http.Request) { + b, ok := read(w, r) + if !ok { + return + } + allowed, e := carddavConnectorGate(r) + if e != nil { + respond(w, 0, nil, e) + return + } + if !allowed { + planGate(w) + return + } + fields, e := cleanCardDavFields(b, true) + if e != nil { + respond(w, 0, nil, e) + return + } + enc, _, e := carddavSecretFor(b, true) + if e != nil { + respond(w, 0, nil, e) + return + } + fields["secret"] = enc + fields["enabled"] = true + 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 "CardDavConnection" WHERE "ownerId"=$1`, user(r)).Scan(&n); e != nil { + return e + } + if n >= maxCardDavConns { + return bad("CardDAV connection limit reached; remove one first") + } + fields["id"] = db.NewID() + fields["ownerId"] = user(r) + row, e = db.Insert(r.Context(), tx, "CardDavConnection", fields) + return e + }) + if e != nil { + respond(w, 0, nil, e) + return + } + respond(w, 201, carddavProjection(row), nil) +} + +func HandleCardDavConnectionsUpdate(w http.ResponseWriter, r *http.Request) { + id := r.PathValue("id") + existing, e := owned(r, database(r), "CardDavConnection", id, "ownerId") + if e != nil { + respond(w, 0, nil, e) + return + } + b, ok := read(w, r) + if !ok { + return + } + baseVersion, e := requiredVersion(b) + if e != nil { + respond(w, 0, nil, e) + return + } + if stored, _ := existing["version"].(float64); int(stored) != baseVersion { + respond(w, 0, nil, conflict("Connection was modified elsewhere; reload to see the latest version")) + return + } + fields, e := cleanCardDavFields(b, false) + if e != nil { + respond(w, 0, nil, e) + return + } + enc, keep, e := carddavSecretFor(b, false) + if e != nil { + respond(w, 0, nil, e) + return + } + if !keep { + fields["secret"] = enc + } + if len(fields) == 0 { + respond(w, 200, carddavProjection(existing), nil) + return + } + row, e := patchVersioned(r, "CardDavConnection", id, baseVersion, fields) + if e != nil { + respond(w, 0, nil, e) + return + } + respond(w, 200, carddavProjection(row), nil) +} + +func HandleCardDavConnectionsDelete(w http.ResponseWriter, r *http.Request) { + if e := remove(r, "CardDavConnection", r.PathValue("id"), "ownerId"); e != nil { + respond(w, 0, nil, e) + return + } + respond(w, 200, object{"ok": true}, nil) +} + +// carddavConn loads a row, decrypts its password and resolves the owner's +// tenant, shared by /test and /sync. +func carddavConn(r *http.Request, id string) (carddav.Connection, object, error) { + row, e := owned(r, database(r), "CardDavConnection", id, "ownerId") + if e != nil { + return carddav.Connection{}, nil, e + } + enc, _ := row["secret"].(string) + pw, e := crypt.Decrypt(enc, config.Load().EncryptionSecret()) + if e != nil { + return carddav.Connection{}, row, e + } + var tenantID *string + if e := database(r).QueryRowContext(r.Context(), + `SELECT "tenantId" FROM "User" WHERE id=$1`, str(row, "ownerId")).Scan(&tenantID); e != nil { + return carddav.Connection{}, row, e + } + tid := "" + if tenantID != nil { + tid = *tenantID + } + return carddav.Connection{ + ID: str(row, "id"), OwnerID: str(row, "ownerId"), TenantID: tid, + Name: str(row, "name"), URL: str(row, "url"), Username: str(row, "username"), + Password: pw, + }, row, nil +} + +var carddavTestLimiter = auth.NewLimiterStore() + +func CardDavTestLimiter(next http.HandlerFunc) http.HandlerFunc { + return auth.LimiterKeyed(carddavTestLimiter, 30, time.Hour, user)(next) +} + +// HandleCardDavConnectionsTest runs address-book discovery without writing +// anything; failures are 502 with the client's message, never a silent ok. +func HandleCardDavConnectionsTest(w http.ResponseWriter, r *http.Request) { + conn, _, e := carddavConn(r, r.PathValue("id")) + if e != nil { + respond(w, 0, nil, e) + return + } + release, retry, ok := outbound.Reserve("carddav-test:"+user(r), 10, time.Minute) + if !ok { + outboundBusy(w, retry) + return + } + defer release() + ctx, cancel := context.WithTimeout(r.Context(), carddavTestTimeout) + defer cancel() + books, err := carddav.Discover(ctx, carddav.Conn{BaseURL: conn.URL, Username: conn.Username, Password: conn.Password}) + if err != nil { + respond(w, 502, object{"ok": false, "error": truncate(err.Error(), 200)}, nil) + return + } + names := make([]string, 0, len(books)) + for _, b := range books { + names = append(names, b.DisplayName) + } + respond(w, 200, object{"ok": true, "addressbooks": names}, nil) +} + +var carddavSyncLimiter = auth.NewLimiterStore() + +func CardDavSyncLimiter(next http.HandlerFunc) http.HandlerFunc { + return auth.LimiterKeyed(carddavSyncLimiter, 10, time.Hour, user)(next) +} + +// HandleCardDavSync reconciles one connection now, under the same plan gate +// the engine applies so a manual sync cannot smuggle past a downgrade. +func HandleCardDavSync(w http.ResponseWriter, r *http.Request) { + allowed, e := carddavConnectorGate(r) + if e != nil { + respond(w, 0, nil, e) + return + } + if !allowed { + planGate(w) + return + } + conn, _, e := carddavConn(r, r.PathValue("id")) + if e != nil { + respond(w, 0, nil, e) + return + } + ctx, cancel := context.WithTimeout(r.Context(), 2*carddavTestTimeout) + defer cancel() + res, e := carddav.SyncOne(ctx, database(r), conn) + if e != nil { + respond(w, 502, object{"ok": false, "error": truncate(e.Error(), 200)}, nil) + return + } + respond(w, 200, object{"ok": true, + "books": res.Books, "cards": res.Cards, "created": res.Created, + "reused": res.Reused, "updated": res.Updated, "kept": res.Kept, + "removed": res.Removed, "truncated": res.Truncated, + }, nil) +} diff --git a/internal/http/carddav_test.go b/internal/http/carddav_test.go new file mode 100644 index 0000000..7761938 --- /dev/null +++ b/internal/http/carddav_test.go @@ -0,0 +1,224 @@ +package http + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" +) + +// fakeCarddav is a mutable CardDAV server for integration tests: a home at +// /books holding one "Contacts" address book; cards map path -> (etag, vcard). +type fakeCarddav struct { + mu sync.Mutex + cards map[string][2]string // path -> {etag, fn} + srv *httptest.Server +} + +func newFakeCarddav(t *testing.T) *fakeCarddav { + t.Helper() + f := &fakeCarddav{cards: map[string][2]string{ + "ana.vcf": {"A1", "Ana Escobar"}, + "bo.vcf": {"B1", "Bo Peep"}, + }} + f.srv = httptest.NewServer(http.HandlerFunc(f.serve)) + t.Cleanup(f.srv.Close) + return f +} + +func (f *fakeCarddav) set(path, etag, fn string) { + f.mu.Lock() + defer f.mu.Unlock() + f.cards[path] = [2]string{etag, fn} +} + +func (f *fakeCarddav) remove(path string) { + f.mu.Lock() + defer f.mu.Unlock() + delete(f.cards, path) +} + +func (f *fakeCarddav) serve(w http.ResponseWriter, r *http.Request) { + u, p, ok := r.BasicAuth() + if !ok || u != "erwin" || p != "s3cret" { + w.Header().Set("WWW-Authenticate", `Basic realm="x"`) + http.Error(w, "no", http.StatusUnauthorized) + return + } + f.mu.Lock() + defer f.mu.Unlock() + switch r.Method { + case "PROPFIND": + if r.URL.Path != "/books/" { + http.Error(w, "no", http.StatusNotFound) + return + } + w.Header().Set("Content-Type", "application/xml") + w.WriteHeader(http.StatusMultiStatus) + if r.Header.Get("Depth") == "0" { + io.WriteString(w, `/books/`) + return + } + io.WriteString(w, ` +/books/ +/books/contacts/Contacts +`) + case "REPORT": + if r.URL.Path != "/books/contacts/" { + http.Error(w, "no", http.StatusNotFound) + return + } + w.Header().Set("Content-Type", "application/xml") + w.WriteHeader(http.StatusMultiStatus) + var b strings.Builder + b.WriteString(``) + b.WriteString(`/books/contacts/"book"`) + for path, v := range f.cards { + vcard := "BEGIN:VCARD\r\nVERSION:3.0\r\nUID:uid-" + path + "\r\nFN:" + v[1] + + "\r\nEMAIL:" + strings.ToLower(strings.SplitN(v[1], " ", 2)[0]) + "@example.invalid\r\nEND:VCARD" + b.WriteString(`/books/contacts/` + path + `"` + v[0] + + `"` + cdavEsc(vcard) + ``) + } + b.WriteString(``) + io.WriteString(w, b.String()) + default: + http.Error(w, "no", http.StatusMethodNotAllowed) + } +} + +func cdavEsc(s string) string { + return strings.NewReplacer("&", "&", "<", "<", ">", ">").Replace(s) +} + +func cardDavBody(url string) map[string]any { + return map[string]any{"name": "House contacts", "url": url + "/books", "username": "erwin", "password": "s3cret"} +} + +func TestCardDavLifecycle(t *testing.T) { + srv, _ := testServerDB(t) + fake := newFakeCarddav(t) + c, _ := accountClient(t, srv.URL, "kvd@superbrain.test") + + c.request("POST", "/api/carddav/connections", map[string]any{"name": "x", "url": "ftp://h/books", "username": "erwin", "password": "s3cret"}, 400) + c.request("POST", "/api/carddav/connections", map[string]any{"name": "x", "url": fake.srv.URL + "/books", "username": "erwin"}, 400) // password required + + created := c.request("POST", "/api/carddav/connections", cardDavBody(fake.srv.URL), 201) + id := created["id"].(string) + if created["secret"] != "••••••••" { + t.Fatalf("password not masked: %v", created["secret"]) + } + list := c.request("GET", "/api/carddav/connections", nil, 200) + if list["allowed"] != true { + t.Fatal("carddav is allowed on every plan (free included) via the catalog") + } + if len(list["connections"].([]any)) != 1 { + t.Fatal("want one connection") + } + + if r := c.request("POST", "/api/carddav/connections/"+id+"/test", map[string]any{}, 200); r["ok"] != true || len(r["addressbooks"].([]any)) != 1 { + t.Fatalf("test discovery: %v", r) + } + + // Sync: one Collection named by the SERVER's display name, one bookmark + // per card carrying the .vcf URL and FN title. + res := c.request("POST", "/api/carddav/connections/"+id+"/sync", map[string]any{}, 200) + if res["books"] != float64(1) || res["cards"] != float64(2) || res["created"] != float64(2) { + t.Fatalf("first sync: %v", res) + } + var colID string + for _, x := range c.getJSON("/api/collections", 200) { + if x["name"] == "Contacts" { + colID = x["id"].(string) + } + } + if colID == "" { + t.Fatal("address book did not materialize as a Contacts collection") + } + items := c.getJSON("/api/collections/"+colID+"/items?limit=50", 200) + if len(items) != 2 { + t.Fatalf("want 2 members, got %d", len(items)) + } + var anaID string + for _, it := range items { + b := it["bookmark"].(map[string]any) + if b["title"] == "Ana Escobar" { + anaID = b["id"].(string) + if !strings.HasSuffix(b["url"].(string), "/books/contacts/ana.vcf") { + t.Fatalf("contact bookmark URL wrong: %v", b["url"]) + } + if !strings.Contains(b["description"].(string), "Email: ana@example.invalid") { + t.Fatalf("contact email not in description: %v", b["description"]) + } + } + } + if anaID == "" { + t.Fatal("Ana bookmark not found") + } + + // Idempotent re-sync + etag change refresh. + if res = c.request("POST", "/api/carddav/connections/"+id+"/sync", map[string]any{}, 200); res["created"] != float64(0) || res["kept"] != float64(2) { + t.Fatalf("re-sync: %v", res) + } + fake.set("ana.vcf", "A2", "Ana Escobar") + if res = c.request("POST", "/api/carddav/connections/"+id+"/sync", map[string]any{}, 200); res["updated"] != float64(1) { + t.Fatalf("etag change: %v", res) + } + c.request("GET", "/api/bookmarks/"+anaID, nil, 200) // user's bookmark survives content change + + // Card removed: membership detaches, BOOKMARK SURVIVES. + fake.remove("bo.vcf") + if res = c.request("POST", "/api/carddav/connections/"+id+"/sync", map[string]any{}, 200); res["removed"] != float64(1) { + t.Fatalf("card removal: %v", res) + } + if n := len(c.getJSON("/api/collections/"+colID+"/items?limit=50", 200)); n != 1 { + t.Fatalf("detached card still a member: %d", n) + } + + // Deleted bookmark: tombstone — never resurrected even when the card + // reappears on the server. + c.request("DELETE", "/api/bookmarks/"+anaID, nil, 200) + fake.set("ana.vcf", "A3", "Ana Escobar") + c.request("POST", "/api/carddav/connections/"+id+"/sync", map[string]any{}, 200) + if n := len(c.getJSON("/api/collections/"+colID+"/items?limit=50", 200)); n != 0 { + t.Fatalf("tombstone violated: %d members", n) + } + + // Version contract + write-only password. + c.request("PATCH", "/api/carddav/connections/"+id, map[string]any{"name": "R", "version": 99}, 409) + noop := c.request("PATCH", "/api/carddav/connections/"+id, map[string]any{"password": "••••••••", "version": 1}, 200) + if noop["version"] != float64(1) { + t.Fatalf("mask-only PATCH bumped version: %v", noop) + } + c.request("PATCH", "/api/carddav/connections/"+id, map[string]any{"password": "wrong", "version": 1}, 200) + c.request("POST", "/api/carddav/connections/"+id+"/sync", map[string]any{}, 502) + row := c.request("GET", "/api/carddav/connections", nil, 200)["connections"].([]any)[0].(map[string]any) + if row["lastError"] == nil { + t.Fatal("failed sync did not surface lastError") + } + if _, ok := row["addressbooks"].([]any); !ok { + t.Fatalf("connection row missing addressbooks: %v", row["addressbooks"]) + } + + // Owner scoping. + bob, _ := accountClient(t, srv.URL, "kbob@superbrain.test") + bob.request("DELETE", "/api/carddav/connections/"+id, nil, 404) +} + +// Per-connection state resets when the https-only rule bites: an http +// endpoint is refused at creation (the escape hatch flag is set in the +// harness, so this asserts the rule is wired, not the failure itself). +func TestCardDavSuggestion(t *testing.T) { + t.Setenv("NEXTCLOUD_URL", "https://cloud.example") + srv := testServer(t) + c, _ := accountClient(t, srv.URL, "ksg@superbrain.test") + sugg := c.request("GET", "/api/carddav/connections", nil, 200)["suggestions"].([]any) + if len(sugg) != 1 { + t.Fatalf("want one suggestion, got %v", sugg) + } + m := sugg[0].(map[string]any) + if m["kind"] != "nextcloud" || m["url"] != "https://cloud.example/remote.php/dav/addressbooks/users/" { + t.Fatalf("unexpected suggestion: %v", m) + } +} diff --git a/internal/http/server.go b/internal/http/server.go index 8399ac5..7114cce 100644 --- a/internal/http/server.go +++ b/internal/http/server.go @@ -193,6 +193,19 @@ func NewServer(cfg *config.Config, database *db.DB) *http.Server { mux.HandleFunc("POST /api/caldav/connections/{id}/test", authed(handlers.CalDavTestLimiter(handlers.HandleCalDavConnectionsTest))) mux.HandleFunc("POST /api/caldav/connections/{id}/sync", authed(handlers.CalDavSyncLimiter(handlers.HandleCalDavSync))) + // 4.7i CardDAV address books (Settings -> CardDAV): a connected endpoint + // materializes each server address book as a Collection whose members + // are contact bookmarks (URL = the card's DAV .vcf location), synced by + // internal/carddav. Same disciplines as the other DAV surfaces; dials + // pin to 443 only (Basic-auth credentials); the `carddav` connector + // gates creation AND every sync; NEXTCLOUD_URL supplies the Core prefill. + mux.HandleFunc("GET /api/carddav/connections", authed(handlers.HandleCardDavConnectionsList)) + mux.HandleFunc("POST /api/carddav/connections", authed(handlers.HandleCardDavConnectionsCreate)) + mux.HandleFunc("PATCH /api/carddav/connections/{id}", authed(handlers.HandleCardDavConnectionsUpdate)) + mux.HandleFunc("DELETE /api/carddav/connections/{id}", authed(handlers.HandleCardDavConnectionsDelete)) + mux.HandleFunc("POST /api/carddav/connections/{id}/test", authed(handlers.CardDavTestLimiter(handlers.HandleCardDavConnectionsTest))) + mux.HandleFunc("POST /api/carddav/connections/{id}/sync", authed(handlers.CardDavSyncLimiter(handlers.HandleCardDavSync))) + // 4.8 Alerts, contacts, email, dates, users mux.HandleFunc("GET /api/alerts/check", authed(handlers.HandleAlertsCheck)) mux.HandleFunc("DELETE /api/alerts/{bookmarkId}", authed(handlers.HandleAlertsDismiss)) diff --git a/main.go b/main.go index e099a0d..ce8407e 100644 --- a/main.go +++ b/main.go @@ -5,6 +5,7 @@ import ( "errors" "github.com/andrew/superbrain/internal/agent" "github.com/andrew/superbrain/internal/caldav" + "github.com/andrew/superbrain/internal/carddav" "github.com/andrew/superbrain/internal/config" "github.com/andrew/superbrain/internal/db" "github.com/andrew/superbrain/internal/http" @@ -71,7 +72,7 @@ func main() { go func() { defer close(workersDone) var wg sync.WaitGroup - wg.Add(5) + wg.Add(6) go func() { defer wg.Done(); signals.RunLoop(ctx, d) }() // Notification engine (DESIGN_NOTIFICATIONS.md): scans rules and // delivers through channels; shares the shutdown contract with @@ -88,6 +89,9 @@ func main() { // calendar into a Collection of per-event bookmark URLs, on its own // advisory lease so the two DAV loops never block each other. go func() { defer wg.Done(); caldav.RunLoop(ctx, d) }() + // CardDAV address books (Settings -> CardDAV): each server book becomes a + // Collection of per-contact bookmark URLs, on its own advisory lease. + go func() { defer wg.Done(); carddav.RunLoop(ctx, d) }() wg.Wait() }() srv := http.NewServer(cfg, d) diff --git a/scripts/regressions.mjs b/scripts/regressions.mjs index b41b3e3..ff70744 100644 --- a/scripts/regressions.mjs +++ b/scripts/regressions.mjs @@ -62,6 +62,14 @@ const caldavConnections = [{ lastSyncedAt: null, lastError: null, version: 1, createdAt: '2026-11-10T00:00:00Z', updatedAt: '2026-11-10T00:00:00Z', }] const caldavSuggestions = [{ kind: 'nextcloud', name: 'Nextcloud calendars', url: 'https://cloud.federatedcomputer.ai/remote.php/dav/calendars/' }] +let lastCarddavCreate = null +const carddavConnections = [{ + id: 'carddav-1', name: 'House contacts', url: 'https://dav.example.org/remote.php/dav/addressbooks/users/erwin/contacts', + username: 'erwin', secret: '••••••••', enabled: true, + addressbooks: [{ href: '/books/contacts/', name: 'Contacts', collectionId: 'col-contacts' }], + lastSyncedAt: null, lastError: null, version: 1, createdAt: '2026-11-10T00:00:00Z', updatedAt: '2026-11-10T00:00:00Z', +}] +const carddavSuggestions = [{ kind: 'nextcloud', name: 'Nextcloud contacts', url: 'https://cloud.federatedcomputer.ai/remote.php/dav/addressbooks/users/' }] const api = http.createServer(async (req, res) => { try { let raw = '' @@ -217,6 +225,38 @@ const api = http.createServer(async (req, res) => { if (password && password !== '••••••••') conn.secret = '••••••••' result = conn } else result = conn + } else if (url.pathname === '/api/carddav/connections') { + if (req.method === 'POST') { + lastCarddavCreate = body + const conn = { + id: `carddav-${carddavConnections.length + 1}`, name: body.name, url: body.url, username: body.username, + secret: body.password ? '••••••••' : '', enabled: true, addressbooks: [], + lastSyncedAt: null, lastError: null, version: 1, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), + } + carddavConnections.push(conn) + result = conn + } else { + result = { connections: carddavConnections, allowed: true, suggestions: carddavSuggestions } + } + } else if (/^\/api\/carddav\/connections\/[^/]+\/(test|sync)$/.test(url.pathname) && req.method === 'POST') { + result = url.pathname.endsWith('/sync') + ? { ok: true, books: 1, cards: 3, created: 3, reused: 0, updated: 0, kept: 0, removed: 0, truncated: false } + : { ok: true, addressbooks: ['Contacts'] } + } else if (/^\/api\/carddav\/connections\/[^/]+$/.test(url.pathname)) { + const conn = carddavConnections.find(b => b.id === url.pathname.split('/')[3]) + if (!conn) { res.writeHead(404); res.end('{}'); return } + if (req.method === 'DELETE') { carddavConnections.splice(carddavConnections.indexOf(conn), 1); result = { ok: true } } + else if (req.method === 'PATCH') { + if (body.version !== conn.version) { + res.writeHead(409, { 'Content-Type': 'application/json' }) + res.end('{"error":"Connection was modified elsewhere; reload to see the latest version"}') + return + } + const { version, password, ...data } = body + Object.assign(conn, data, { version: conn.version + 1 }) + if (password && password !== '••••••••') conn.secret = '••••••••' + result = conn + } else result = conn } else if (url.pathname === '/api/tags') result = tags else if (url.pathname === '/api/kanban/columns') result = kanbanColumns else if (/^\/api\/kanban\/cards\/[^/]+$/.test(url.pathname) && req.method === 'PUT') { @@ -692,11 +732,42 @@ try { assert.ok(!(await page.evaluate(() => document.body.innerText)).includes('cal-app-secret'), 'the entered CalDAV password echoed back in the UI') console.log('PASS: Settings → CalDAV lists calendars, prefills the Nextcloud suggestion, and round-trips connect/sync/test without echoing secrets') + // Settings → CardDAV: address books render on each row; the suggestion + // prefills the home *composed with the username* (the URL shown is the URL + // saved); connect/sync/test round-trip with verbatim results and no secret + // echo. + await page.getByRole('tab', { name: 'CardDAV' }).click() + await page.getByText('House contacts').first().waitFor() + await page.getByText('Books: Contacts').waitFor() + await page.getByText('Nextcloud contacts detected on this server').waitFor() + await page.getByRole('button', { name: 'Use', exact: true }).click() + const cardUrl = page.getByPlaceholder('https://cloud.example.com/remote.php/dav/addressbooks/users/username/contacts') + assert.equal(await cardUrl.inputValue(), 'https://cloud.federatedcomputer.ai/remote.php/dav/addressbooks/users/fixture/') + assert.equal(await page.getByPlaceholder('erwin').inputValue(), 'fixture') + await page.getByPlaceholder('erwin').fill('erwin') + // Editing the username recomposes nothing implicitly — the user sees and can + // edit the full URL; leave the composed fixture path in place for POST. + await page.getByPlaceholder('Account or app password').fill('vcf-app-secret') + await page.locator('[role="dialog"]').getByRole('button', { name: 'Connect address book' }).click() + await eventually(() => carddavConnections.length === 2, 'CardDAV connect POST did not reach the API') + assert.equal(lastCarddavCreate.url, 'https://cloud.federatedcomputer.ai/remote.php/dav/addressbooks/users/fixture/') + assert.equal(lastCarddavCreate.password, 'vcf-app-secret') + await page.getByRole('button', { name: 'Sync House contacts' }).click() + await page.getByText('3 contacts across 1 books: 3 created, 0 reused, 0 changed, 0 detached').first().waitFor() + await page.getByRole('button', { name: 'Test House contacts' }).click() + await page.getByText('Found: Contacts').first().waitFor() + assert.ok(!(await page.evaluate(() => document.body.innerText)).includes('vcf-app-secret'), 'the entered CardDAV password echoed back in the UI') + console.log('PASS: Settings → CardDAV lists address books, prefills a username-composed Nextcloud home, and round-trips connect/sync/test without echoing secrets') + // Revocation failure path (review CR-02): when Go's revocation fails, the // local sign-out still completes, but the UI must say so — local cookie // removal is not confirmed global revocation, and other sessions survive. await page.goto(`${base}/bookmarks`) await page.keyboard.press('Escape') // close any detail sheet so the top bar is reachable + // Drain any Sonner toasts queued by earlier sections: their container + // empties on the sign-out navigation, and a stacked queue could hide the + // revocation notice we are about to assert on. + await new Promise(resolve => setTimeout(resolve, 4500)) failSignout = true const failedRevoke = page.waitForResponse(r => r.url().includes('/api/session/revoke') && r.request().method() === 'POST') await page.getByRole('button', { name: 'Sign out', exact: true }).click() diff --git a/web/app/(app)/settings/client.tsx b/web/app/(app)/settings/client.tsx index 82e509c..c74173a 100644 --- a/web/app/(app)/settings/client.tsx +++ b/web/app/(app)/settings/client.tsx @@ -5,7 +5,7 @@ import { useSession } from 'next-auth/react' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs' -import { User, Mail, Server, Cloud, Shield, Bell, Sparkles, Bot, KeyRound, PlugZap, FolderSync, CalendarDays, Check, X, AlertTriangle } from 'lucide-react' +import { User, Mail, Server, Cloud, Shield, Bell, Sparkles, Bot, KeyRound, PlugZap, FolderSync, CalendarDays, BookUser, Check, X, AlertTriangle } from 'lucide-react' import { toast } from 'sonner' import { invalidateReference } from '@/lib/reference-data' import { NotificationsSettings } from '@/components/notifications-settings' @@ -15,6 +15,7 @@ import { ApiKeysSettings } from '@/components/api-keys-settings' import { McpSettings } from '@/components/mcp-settings' import { WebdavSettings } from '@/components/webdav-settings' import { CalDavSettings } from '@/components/caldav-settings' +import { CardDavSettings } from '@/components/carddav-settings' import type { OidcStatus } from '@/lib/oidc-config' export function SettingsClient({ oidc, callbackUrl }: { oidc: OidcStatus; callbackUrl: string }) { @@ -109,6 +110,7 @@ export function SettingsClient({ oidc, callbackUrl }: { oidc: OidcStatus; callba MCP WebDAV CalDAV + CardDAV OIDC @@ -214,6 +216,10 @@ export function SettingsClient({ oidc, callbackUrl }: { oidc: OidcStatus; callba + + + +

OIDC Configuration

diff --git a/web/components/carddav-settings.tsx b/web/components/carddav-settings.tsx new file mode 100644 index 0000000..dcca994 --- /dev/null +++ b/web/components/carddav-settings.tsx @@ -0,0 +1,300 @@ +'use client' + +// Settings → CardDAV: connect external CardDAV address books (any RFC 6352 +// service). Each server address book materializes as its own Collection +// whose members are bookmarks — one per contact, carrying the card's DAV +// .vcf URL — refreshed by the background engine and on demand via Sync. +// House disciplines, identical to the WebDAV/CalDAV siblings: passwords are +// write-only (never prefilled; the mask round-trips unchanged), every +// mutating PATCH carries the row version (409 reloads), and plan or dial +// failures surface the server's message — the UI never guesses. When the +// deployment serves NEXTCLOUD_URL (the Core shape), the list arrives with a +// ready-made suggestion; the prefill composes the address-book home with +// the username so the URL shown is the URL saved. + +import { useCallback, useEffect, useState } from 'react' +import { useSession } from 'next-auth/react' +import { Button } from '@/components/ui/button' +import { Input } from '@/components/ui/input' +import { Badge } from '@/components/ui/badge' +import { Switch } from '@/components/ui/switch' +import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog' +import { AlertTriangle, BookUser, Cloud, FlaskConical, Loader2, Plus, RefreshCw, Trash2 } from 'lucide-react' +import { toast } from 'sonner' +import { SafeDate } from '@/components/safe-format' + +const KEY_MASK = '••••••••' + +type AddressbookRef = { href: string; name: string; collectionId: string | null } +type CardDavConnection = { + id: string; name: string; url: string; username: string + secret: string; enabled: boolean; addressbooks: AddressbookRef[] + lastSyncedAt: string | null; lastError: string | null; version: number +} +type Suggestion = { kind: string; name: string; url: string } +type TestResult = { ok: boolean; addressbooks?: string[]; error?: string } +type SyncResult = { ok: boolean; books?: number; cards?: number; created?: number; reused?: number; updated?: number; kept?: number; removed?: number; truncated?: boolean; error?: string } + +type FormState = { + id: string | null; version: number + name: string; url: string; username: string + password: string; hasStoredSecret: boolean +} + +const emptyForm: FormState = { id: null, version: 0, name: '', url: '', username: '', password: '', hasStoredSecret: false } + +async function api(path: string, init?: RequestInit): Promise { + return fetch(path, { headers: { 'Content-Type': 'application/json' }, cache: 'no-store', ...init }) +} + +export function CardDavSettings() { + const { data: session } = useSession() + const [connections, setConnections] = useState([]) + const [suggestions, setSuggestions] = useState([]) + const [allowed, setAllowed] = useState(true) + const [loading, setLoading] = useState(true) + const [form, setForm] = useState(null) + const [saving, setSaving] = useState(false) + const [testing, setTesting] = useState(null) + const [syncing, setSyncing] = useState(null) + const [results, setResults] = useState>({}) + + const reload = useCallback(() => + api('/api/carddav/connections') + .then(r => r.json()) + .then(data => { + setConnections(Array.isArray(data?.connections) ? data.connections : []) + setSuggestions(Array.isArray(data?.suggestions) ? data.suggestions : []) + setAllowed(data?.allowed === true) + }) + .catch(() => toast.error('Could not load CardDAV connections')) + .finally(() => setLoading(false)), []) + + useEffect(() => { reload() }, [reload]) + + const openCreate = () => setForm({ ...emptyForm }) + const openSuggestion = (s: Suggestion) => { + const email = session?.user?.email ?? '' + const username = email ? email.split('@')[0] : '' + // Compose visibly: the suggestion hands us the address-book home + // prefix, so the URL in the form is already the URL that gets saved. + setForm({ ...emptyForm, name: s.name, username, url: username ? s.url + username + '/' : s.url }) + } + const openEdit = (c: CardDavConnection) => setForm({ + id: c.id, version: c.version, name: c.name, url: c.url, username: c.username, + password: '', hasStoredSecret: c.secret === KEY_MASK, + }) + + const save = async () => { + if (!form) return + const body: Record = { + name: form.name.trim(), url: form.url.trim(), username: form.username.trim(), + } + // Write-only password: send only what the user typed; the mask (or an + // empty field) tells the server to keep the stored value. + if (form.password) body.password = form.password + setSaving(true) + try { + const res = form.id + ? await api(`/api/carddav/connections/${form.id}`, { method: 'PATCH', body: JSON.stringify({ ...body, version: form.version }) }) + : await api('/api/carddav/connections', { method: 'POST', body: JSON.stringify(body) }) + const data = await res.json().catch(() => null) + if (res.status === 409) { + toast.error('Connection changed elsewhere — reloaded') + await reload() + setForm(null) + return + } + if (!res.ok) { toast.error(data?.error ?? 'Could not save the connection'); return } + toast.success(form.id ? 'Connection updated' : 'Address book connected — sync it to materialize the collections') + setForm(null) + await reload() + } catch { toast.error('Could not save the connection') } + finally { setSaving(false) } + } + + const test = async (c: CardDavConnection) => { + setTesting(c.id) + try { + const res = await api(`/api/carddav/connections/${c.id}/test`, { method: 'POST', body: '{}' }) + const data = await res.json().catch(() => null) + setResults(prev => ({ ...prev, [c.id]: { ...prev[c.id], test: (data as TestResult) ?? { ok: false, error: 'Network error' } } })) + if (data?.ok) toast.success(`${data.addressbooks?.length ?? 0} address book${data.addressbooks?.length === 1 ? '' : 's'} found`) + } catch { setResults(prev => ({ ...prev, [c.id]: { ...prev[c.id], test: { ok: false, error: 'Network error' } } })) } + finally { setTesting(null) } + } + + const sync = async (c: CardDavConnection) => { + setSyncing(c.id) + try { + const res = await api(`/api/carddav/connections/${c.id}/sync`, { method: 'POST', body: '{}' }) + const data = await res.json().catch(() => null) + setResults(prev => ({ ...prev, [c.id]: { ...prev[c.id], sync: (data as SyncResult) ?? { ok: false, error: 'Network error' } } })) + if (data?.ok) toast.success(`Synced ${data.cards} contact${data.cards === 1 ? '' : 's'} from ${data.books} address book${data.books === 1 ? '' : 's'}`) + await reload() + } catch { setResults(prev => ({ ...prev, [c.id]: { ...prev[c.id], sync: { ok: false, error: 'Network error' } } })) } + finally { setSyncing(null) } + } + + const toggle = async (c: CardDavConnection) => { + const res = await api(`/api/carddav/connections/${c.id}`, { + method: 'PATCH', body: JSON.stringify({ enabled: !c.enabled, version: c.version }), + }) + if (res.status === 409) { toast.error('Connection changed elsewhere — reloaded'); await reload(); return } + if (!res.ok) { toast.error((await res.json().catch(() => null))?.error ?? 'Could not update'); return } + await reload() + } + + const remove = async (c: CardDavConnection) => { + const res = await api(`/api/carddav/connections/${c.id}`, { method: 'DELETE' }) + if (res.ok) { toast.success(`Removed ${c.name} — the address book collections and their bookmarks stay`); await reload() } + else toast.error((await res.json().catch(() => null))?.error ?? 'Could not remove') + } + + if (loading) { + return ( +
+ Loading CardDAV connections… +
+ ) + } + + return ( +
+
+
+

CardDAV address books

+

+ Connect an address book from any CardDAV service. Each book becomes a Collection, one + bookmark per contact, re-checked in the background every 30 minutes. Passwords are + encrypted at rest and never shown again. (This is separate from Contacts sync, which + feeds contact-linking.) +

+
+ {allowed && } +
+ + {!allowed && ( +
+ +

CardDAV address books are not available on your current plan. Existing connections stay but no longer sync.

+
+ )} + + {suggestions.length > 0 && allowed && ( +
+ {suggestions.map(s => ( +
+ +
+

{s.name} detected on this server

+

{s.url}

+
+ +
+ ))} +
+ )} + + {connections.length === 0 ? ( +

No CardDAV address books connected.

+ ) : ( +
    + {connections.map(c => { + const r = results[c.id] + const failure = r?.sync && !r.sync.ok ? r.sync.error : r?.test && !r.test.ok ? r.test.error : null + return ( +
  • +
    + toggle(c)} aria-label={`Enable ${c.name}`} /> + {c.name} + {Array.isArray(c.addressbooks) && c.addressbooks.length > 0 && {c.addressbooks.length} books} + + + + + + +
    +

    {c.username}@{c.url}

    + {Array.isArray(c.addressbooks) && c.addressbooks.length > 0 && ( +

    + Books: {c.addressbooks.map(k => k.name).join(', ')} +

    + )} +

    + {c.lastSyncedAt + ? <>Last synced + : 'Not synced yet — use Sync to materialize the collections'} +

    + {!failure && c.lastError && ( +

    {c.lastError}

    + )} + {failure &&

    {failure}

    } + {r?.sync?.ok && ( +

    + {r.sync.cards} contacts across {r.sync.books ?? 0} books: {r.sync.created ?? 0} created, {r.sync.reused ?? 0} reused,{" "} + {r.sync.updated ?? 0} changed, {r.sync.removed ?? 0} detached + {r.sync.truncated && ' — a listing was capped; nothing was treated as deleted'} +

    + )} + {r?.test?.ok && ( +

    + Found: {r.test.addressbooks?.join(', ') || 'no address books'} +

    + )} +
  • + ) + })} +
+ )} + + { if (!open) setForm(null) }}> + + {form?.id ? 'Edit CardDAV connection' : 'Connect a CardDAV address book'} + {form && ( +
+
+ + setForm({ ...form, name: e.target.value })} placeholder="e.g. House contacts" maxLength={100} /> +
+
+ + setForm({ ...form, url: e.target.value })} placeholder="https://cloud.example.com/remote.php/dav/addressbooks/users/username/contacts" /> +

One address book or a home holding several, on an https endpoint (CardDAV credentials never travel to other ports or plaintext). Discovery is network-guarded and never follows redirects.

+
+
+
+ + setForm({ ...form, username: e.target.value })} placeholder="erwin" maxLength={200} /> +
+
+ + setForm({ ...form, password: e.target.value })} + placeholder={form.hasStoredSecret ? `${KEY_MASK} (leave blank to keep)` : 'Account or app password'} + maxLength={2000} + /> +
+
+ {form.hasStoredSecret &&

Stored credentials are never shown; blank keeps the current one.

} +

Tip: services that use two-factor login usually need an app password here (in Nextcloud: Settings → Security → Devices).

+
+ + +
+
+ )} +
+
+
+ ) +}