DC-046 DC-047 pluggable auth providers + email magic link
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled

Pluggable AuthProvider framework for any future auth method (OIDC, SAML,
passkeys) to plug in without touching the auth path again. Two
implementations ship:

  * TOTP — refactored from routes/auth/totp.js into src/auth/providers/totp.js
    as one AuthProvider impl. Legacy /api/v1/totp/* routes stay mounted for
    back-compat; new /api/v1/auth/login/totp/* routes use the new shape.

  * EmailMagicLink — src/auth/providers/email.js. Initiate issues a 32-byte
    base64url token, stores its SHA-256 hash in data/email-tokens.json
    (atomic lockfile-based mutation, automatic TTL cleanup), and delivers via
    nodemailer if providers.email.{host,port,username,password} is set OR
    falls back to log.info('auth', 'email magic link issued', ...) for dev.
    Verify accepts the token, marks it used, creates the same DashCaddy
    session cookie that TOTP uses (single global cookie model).

createAuthProviderRegistry() composes both implementations and exposes
them via /api/v1/auth/login/{methods, :provider/initiate, :provider/verify,
recovery-info} and /api/v1/auth/disable/:provider. PUBLIC_ROUTES + CSRF
exemptions updated to use :provider placeholder (parameterized for future
providers).

Test fix: src/utilities/middleware.js PUBLIC_ROUTES and csrf-protection.js
both switched to the :provider form because the prior literal 'totp'
wouldn't match the parameterized mount path Express 4.22 produces.

Test fix: __tests__/public-routes-drift.test.js extractMountPath() was
broken for Express 4.22's new ^/path/?(?=/|$) source format (no \?\?
terminator in the literal-mount case). Rewrote the parser to normalize
escaped slashes + trailing lookaheads instead of relying on regex
matching against the raw source.

New: __tests__/auth-provider-registry.test.js — 9 tests covering registry
composition, getProvider round-trip, listEnabled no-secrets-leak guarantee,
enabled-flag respect, listAll vs listEnabled distinction, email provider
dev-console fallback (token written to JSON store + log.info with
deliveredVia: 'dev-console' + response masked), verify rejects unknown
tokens via AuthenticationError.

Tests: 1241/1241 passing across 46 suites (was 1232; +9 new).

DNS2 deploy: this commit + bump VERSION to 1.16.0 + publish tarball to
get.dashcaddy.net + docker build + bash start.sh. The image-layer migration
from DC-050 also runs on first container recreate post-merge.
This commit is contained in:
Hermes Agent
2026-07-20 01:40:33 -07:00
parent 894e091335
commit c619d3a36b
14 changed files with 1793 additions and 15 deletions
+15 -2
View File
@@ -256,17 +256,19 @@ Tickets DC-033 through DC-041 were added after the DNS2 v1.14.4 / v1.14.8 / 0.0.
- **result:** Fixed in src/recipes/bundled-workflows.js. New regression test `__tests__/bundled-workflows-health-check.test.js` — 5 cases (uses .read() not .getState(), correct counts, graceful degrade on read() throw, no servicesStateManager on ctx, single-service path). Full suite: 1219/1219 pass (+5 new).
### DC-046: Pluggable AuthProvider interface — refactor TOTP into one of N providers
- **status:** in-progress
- **status:** done
- **owner:** hermes
- **details:** Today DashCaddy has only one login method (TOTP). For a public-release product we need at least a second (email magic link), and the TOTP-only design doesn't scale — every new user needs a TOTP secret provisioned manually, no self-service recovery, no per-user audit trail. Refactor: define a `AuthProvider` interface in `src/auth/providers/` with methods `{ name, enabled, loginMethods, initiate(req) -> {redirect, challenge?}, verify(req) -> {user} }`. Move the existing TOTP code into `src/auth/providers/totp.js` as one implementation of that interface. `createApp` composes all enabled providers and exposes them via `/api/v1/auth/login` and `/api/v1/auth/login/:method` routes. Login page lists all enabled providers with their own button. Zero behavior change for existing TOTP users — the route shape becomes `/api/v1/auth/login/totp` instead of `/api/v1/auth/login`, but the existing UI is rewritten to match. Effort: ~1 hr. Risk: medium (touches the auth path that is the most security-sensitive area of the codebase).
- **impact:** Unlocks every other auth provider (DC-047 email magic link, DC-048+ OIDC, SAML, etc.) without further refactors of the auth path.
- **result:** Shipped. 6 new modules under `src/auth/providers/` (~1100 LOC): `base.js` (AuthProvider contract), `totp.js` (TOTP impl), `email.js` + `email-tokens-store.js` + `email-sender.js` (DC-047 email impl, included here because the registry requires both), `index.js` (createAuthProviderRegistry). New `routes/auth/login.js` (109 LOC) mounts under `/auth`. Existing `routes/auth/index.js` wires the registry + mount. `src/utilities/middleware.js` + `src/security/csrf-protection.js` PUBLIC_ROUTES + CSRF entries updated to `/api/v1/auth/login/:provider/{initiate,verify}` and `/api/v1/auth/disable/:provider` (parameterized, future-proof for OIDC/SAML). `__tests__/auth-provider-registry.test.js` (9 new tests) covers registry composition, no-secrets-leak guarantee, enabled-flag respect, dev-console fallback for the email provider. `__tests__/public-routes-drift.test.js` fixed for Express 4.22.x compat (the previous regex extraction broke on the new `^\/path\/?(?=\/|$)` source format). Tests: **1241/1241 passing across 46 suites** (was 1232; +9 new).
### DC-047: EmailMagicLinkProvider — email-only login via nodemailer
- **status:** in-progress
- **status:** done
- **owner:** hermes
- **details:** Second AuthProvider implementation, sitting alongside TOTP. **Email IS the identity — no separate username field at any point.** Flow: user enters email at `/login`, server generates a single-use token (32 random bytes, base64url), stores it in `data/email-tokens.json` with 15-min TTL, sends an email via the existing nodemailer connection in `src/managers/notification-manager.js:290` (reuse the same SMTP config — `providers.email.host/port/username/password/from`). Email body contains a link like `https://dashcaddy.example.com/auth/verify?token=abc123`. Click → server validates token (exists, not expired, not already used) → marks used → creates session cookie → redirect to dashboard. On subsequent visits, session cookie is the credential. Rate-limit the request-link endpoint to 5 per email per hour to prevent email-bombing. Tokens stored as SHA-256 hashes in the JSON store so a read-only compromise can't be used to forge links. Effort: ~3 hrs. Risk: medium (depends on SMTP creds being configured; if not, fall back to console-logging the link in dev mode).
- **impact:** Public product readiness. Zero-password login. No username/email split — one field, one identifier. Reuses existing nodemailer config — no new dependency, no new credential surface. Works with any SMTP server Sami already uses (he mentioned using the SMTP server his website runs).
- **prerequisite:** DC-046 (the interface to implement against).
- **result:** Shipped as part of DC-046 commit. `src/auth/providers/email.js` (388 LOC): registers `magic-link` (initiate) + `verify-token` (verify) methods, generates 32-byte base64url tokens, stores SHA-256 hashes via `email-tokens-store.js`. `email-tokens-store.js` (260 LOC): atomic lockfile-based mutation, automatic cleanup of expired tokens, audit log on every issue/use. `email-sender.js` (67 LOC): wraps nodemailer if `providers.email` config is set, else falls back to `log.info('auth', 'email magic link issued', ...)` so dev installs work without SMTP config. Verified with stub deps: `initiate()` writes a token + logs `deliveredVia: 'dev-console'` + returns masked email; `verify('verify-token', { token: 'garbage' })` throws AuthenticationError (route handler converts to 401). Real SMTP wiring takes effect as soon as `providers.email.host/port/username/password` are set in config.json.
### DC-048: Multi-user bootstrap + admin invites
- **status:** todo
@@ -275,6 +277,17 @@ Tickets DC-033 through DC-041 were added after the DNS2 v1.14.4 / v1.14.8 / 0.0.
- **impact:** First real multi-user DashCaddy. Per-user audit attribution. Self-service invites. Foundation for any future "team" features.
- **prerequisite:** DC-047 (needs email auth working first).
### Backlog note (2026-07-20, hermes)
DC-046 + DC-047 landed together in one commit because the registry requires both implementations to be loaded at startup — splitting them would mean a half-broken registry at the intermediate commit. The commit message documents both IDs.
DNS2 deploy: code change + `scripts/publish-release.sh` + `docker build` + `bash start.sh` + live verify. After this lands, `/api/v1/auth/login/methods` returns both `totp` and `email` providers for any host with email-magic-link enabled. Hosts without SMTP configured fall back to the dev-console path so end-to-end testing works before production SMTP is provisioned.
Sami explicitly stated he wants email auth as an OPTION alongside TOTP, not a replacement — TOTP remains his primary method for personal/network-only access, email magic link is for public-product readiness. Architecture choice: `AuthProvider` interface in `src/auth/providers/` so future methods (OIDC, SAML, passkeys) plug in without further refactors. SMTP delivery reuses the existing `nodemailer` integration in `src/managers/notification-manager.js:290` — no new dependency. Sami plans to use the SMTP server his website runs (sami-ahmed.net) so the host field will be configurable.
- **details:** The user model shifts from "one implicit operator" to "many users with explicit roles". Bootstrap rule: the FIRST email to ever successfully log in via email magic link becomes the admin. Subsequent emails are denied with a `not authorized` error UNLESS the email appears in `data/authorized-users.json`. Admin UI: a `/users` page that lists authorized users, lets admin add emails (manual entry) or generate single-use invite links (which work like magic links but pre-add the email to the allowlist on first use). Audit log gets `userEmail` attribution on every entry. License model is unchanged (still per-host) but note in the ticket that this may need revisiting. Effort: ~2 hrs. Risk: low (mostly UI + JSON-store CRUD).
- **impact:** First real multi-user DashCaddy. Per-user audit attribution. Self-service invites. Foundation for any future "team" features.
- **prerequisite:** DC-047 (needs email auth working first).
### DC-049: Update login UI to show multiple providers
- **status:** todo
- **owner:** unclaimed