CardDAV address books: each server book a Collection, each contact a URL bookmark

Settings -> CardDAV connects an external CardDAV endpoint (any RFC 6352
service; on Core the deployment's NEXTCLOUD_URL adds a Nextcloud-contacts
one-click prefill, composed visibly with the username so the URL shown is
the URL saved). Each server address book materializes as its own Collection
and every contact becomes a Bookmark carrying the card's DAV .vcf URL — FN
as title, email/phone in the description as display sugar set once.

internal/carddav mirrors the WebDAV/CalDAV siblings:
- client.go — discovery accepts a single book or a home (resourcetype
  <card:addressbook/>), addressbook-query REPORT bounded at 50 books /
  2000 cards, netguard-pinned, Basic auth in the header only, redirects
  refused, folded-vCard parser;
- sync.go — RunLoop/RunOnce under a dedicated carddav-tick advisory lease;
  full ledger discipline: idempotent re-runs, etag refreshes never touch
  user-edited bookmark fields, vanished cards detach membership but keep
  the bookmark, user-deleted bookmarks are tombstones that never
  resurrect, a re-deleted Collection is re-created and re-linked, a
  truncated listing never reconciles deletions, one unreadable book does
  not abort the rest.

CardDAV dials pin to 443 only and require https — CardDAV ships
Basic-auth credentials, and the Contacts sync's review rulings (M-3/CR-01)
stand; the INTEGRATIONS_ALLOW_PRIVATE escape hatch keeps loopback fakes
working. This surface is deliberately separate from the single-config
Contacts sync (Contact rows powering contact-linking): same transport,
different product model, stated in API.md and the UI copy.

Three tables (CardDavConnection/CardDavAddressbook/CardDavItem) via
migration 022 + schema.sql. Handlers expose /api/carddav/connections CRUD
+ /test + /sync with the house credential (encrypted, masked, write-only),
version (409 on stale) and AllowConnector("carddav") plan gate on creation
AND every sync; cap 10; wired as the sixth background loop.

Settings -> CardDAV tab (web/components/carddav-settings.tsx): masked
write-only password, version on PATCH, per-row address-book list,
verbatim test/sync results, Core suggestion prefill, allowed flag drives
the plan notice.

Verification: full Go integration suite green incl. TestCardDavLifecycle
(materialize/URL+title checks, idempotency, etag refresh, detach-but-
survive, tombstone, version contract, 502+lastError, owner scoping) and
TestCardDavSuggestion; carddav unit tests on httptest fakes;
make db-converge passes; browser regressions all 19 PASS incl. the new
CardDAV walkthrough (and a deterministic Sonner-toast drain before the
sign-out assertion, which the added toasts had made racy); web lint/SSR-
lint/build clean. API.md contract section, AGENTS invariant, env docs and
the Core installer wording updated for the three-way DAV prefill.
This commit is contained in:
Andrew S Erwin
2026-11-16 03:47:51 -06:00
parent 47ade10e4a
commit 4f919033d1
16 changed files with 2250 additions and 8 deletions
+71
View File
@@ -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()