Skip to content
← Back to writing

April 17, 2026

Eight.ly Professional had no auth. Now it does.

Settings > Dashboard Users showed three accounts. None of them were real. Here is what it took to replace the theater with a real auth layer.

Settings > Dashboard Users showed a clean table of three accounts: admin, john_doe, jane_smith. You could add users, delete them, reset passwords, toggle 2FA, assign roles, and none of it was real.

git show a94da539 --stat, the real PR #64 commit: the new pkg/api/auth package plus the frontend auth screens, 20 files changed, 2,061 insertions, 323 deletions.

The whole Users tab was theater

571 lines of React in UsersSettingsTab.tsx, wired to a service called apiWithFallback. When the backend was reachable the UI would call /users. When it was not, and it never was because the backend did not implement /users, the service silently fell back to a hardcoded MOCK_DATA.users array and fired a toast that said "(demo mode)." Here is the actual mock the whole tab was rendering:

// web/eightly-dashboard/src/services/apiWithFallback.ts
// Mock data for demo mode
const MOCK_DATA = {
  users: [
    { id: 1, username: 'admin', email: '[email protected]', role: 'admin', status: 'active', twofa: true },
    { id: 2, username: 'john_doe', email: '[email protected]', role: 'user', status: 'active', twofa: false },
    { id: 3, username: 'jane_smith', email: '[email protected]', role: 'viewer', status: 'inactive', twofa: false }
  ],

Click "Add User", the user appeared. Click "Delete", it vanished. Close the tab, open it again, and the three originals came back. The toasts were the only honest part of the whole screen.

Separately, /api/auth/user was a Go handler that returned this regardless of who asked:

// simple-server.go (before)
http.HandleFunc("/api/auth/user", func(w http.ResponseWriter, r *http.Request) {
    enableCORS(w, r)
    if r.Method == "OPTIONS" {
        w.WriteHeader(http.StatusOK)
        return
    }
    response := Response{
        Success: true,
        Data: map[string]interface{}{
            "id":       "admin",
            "username": "admin",
            "email":    "[email protected]",
            "role":     "administrator",
        },
        Message: "User information retrieved successfully",
    }
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(response)
})

No authentication, no session, no cookie check, no middleware. Hit Eight.ly Professional's web UI and you were admin. Script a curl, same thing. A guest who found the URL on your home network was admin too, because the role went to anyone who could reach the port.

The scope I was walking into

I wanted a login-gate in front of the dashboard, and at first it felt like a small job: the welcome screen was easy, but the gate turned out to be a lot more than that.

Eight.ly, the Docker product, already has real auth: a user store, sessions, middleware that wraps every protected route, role-based access. Professional had none of that. Adding it was a backend layer, a frontend layer, and a rewire of Settings > Users to hit real endpoints. I broke it into three phases. This was one to two days of work, even though it looked like an hour at a glance.

Phase 1: the backend layer

The auth as a sequence: login runs bcrypt (and a dummy bcrypt on a missing user, meant to keep the timing from leaking which usernames exist, with the cost-factor caveat the post gets to), signs a stateless HMAC cookie, and every gated request walks the middleware checks in order, failing safe at each one.

New package at pkg/api/auth/. types.go holds the User and PublicUser structs, store.go does the /etc/eightly/users.json CRUD with bcrypt cost 12, session.go handles HMAC-SHA256 signed cookies, middleware.go wraps the whole mux, and handlers.go has the endpoints.

The session layer is the part I cared most about getting right. It's a stateless signed cookie, no JWT and no server-side session table: base64 of the JSON payload, a dot, then a hex HMAC-SHA256 of that payload. The secret is 32 random bytes written once to /etc/eightly/auth-secret at 0600 and reused after that.

// pkg/api/auth/session.go
func loadOrCreateSecret(path string) ([]byte, error) {
    if data, err := os.ReadFile(path); err == nil {
        if decoded, err := hex.DecodeString(strings.TrimSpace(string(data))); err == nil && len(decoded) >= 32 {
            return decoded, nil
        }
    }
    if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
        return nil, err
    }
    secret := make([]byte, 32)
    if _, err := rand.Read(secret); err != nil {
        return nil, err
    }
    if err := os.WriteFile(path, []byte(hex.EncodeToString(secret)), 0600); err != nil {
        return nil, err
    }
    return secret, nil
}

func (m *SessionManager) sign(payload []byte) string {
    mac := hmac.New(sha256.New, m.secret)
    mac.Write(payload)
    return base64.RawURLEncoding.EncodeToString(payload) + "." + hex.EncodeToString(mac.Sum(nil))
}

Verification uses hmac.Equal, not ==, so the signature compare is constant-time, and the error returned is deliberately vague. It does not tell you whether the cookie was tampered with or just expired, because the difference is information an attacker would like to have. The cookie itself is HttpOnly and SameSite=Lax, and it gets the Secure flag whenever the request came in over HTTPS, including when r.TLS is nil but X-Forwarded-Proto is https, which is what happens behind a Cloudflare tunnel or Traefik.

The login path got the same paranoia. The whole point of bcrypt is that it is slow, which means a "user does not exist" answer comes back fast and a "wrong password" answer comes back slow, and that timing difference quietly tells an attacker which usernames are real. So the not-found branch runs a bcrypt compare against a dummy hash anyway, to keep the response time flat:

// pkg/api/auth/store.go
var dummyHash, _ = bcrypt.GenerateFromPassword([]byte("dummy"), bcrypt.MinCost)

func (s *Store) Authenticate(username, password string) (*User, error) {
    // ... find user by lowercased username ...
    if found == nil {
        // Still run bcrypt.Compare to keep response time constant.
        _ = bcrypt.CompareHashAndPassword(dummyHash, []byte(password))
        return nil, fmt.Errorf("invalid username or password")
    }
    if err := bcrypt.CompareHashAndPassword([]byte(s.users[*found].PasswordHash), []byte(password)); err != nil {
        return nil, fmt.Errorf("invalid username or password")
    }
    // ... record LastLoginAt, return user ...
}

There is a subtlety here I have to flag, because a careful reviewer will catch it before I do: that dummy hash is generated at bcrypt.MinCost, but real passwords are stored at cost 12. A MinCost compare is an order of magnitude cheaper than a cost-12 one, so the not-found branch still returns measurably faster, and the exact timing leak this code is supposed to close stays open. The dummy has to be generated at the same cost as the real hashes, or the whole exercise is theater. It is a one-line fix, and it is exactly the kind of thing that looks done when it isn't.

The middleware wraps the mux and gates everything under /api/* except a small whitelist for the routes you need before you have a session: the health probes, plus login, setup, status, and logout. Two details earned their place. Anything not under /api/ is public, because that is the React shell and it has to render to show you a login modal. And if zero users exist yet, the middleware falls through instead of 401ing, so a fresh install can actually reach /api/auth/setup instead of bricking itself.

// pkg/api/auth/middleware.go
func (s *Service) Middleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        if s.Disabled {
            next.ServeHTTP(w, r)
            return
        }
        if isPublic(r.URL.Path) {
            next.ServeHTTP(w, r)
            return
        }
        // No users yet -> let the setup flow through, don't brick the install.
        if s.Store.Count() == 0 {
            next.ServeHTTP(w, r)
            return
        }
        userID := s.Session.UserIDFromRequest(r)
        if userID == "" {
            writeJSONErr(w, http.StatusUnauthorized, "unauthorized")
            return
        }
        // ... resolve user, stash in context ...
    })
}

The old stub at /api/auth/user got deleted, replaced by /api/auth/me, which actually reads the cookie and returns the real logged-in user. The rollout valve is s.Disabled, wired to EIGHTLY_AUTH_DISABLED=1. That let me deploy the binary with auth bypassed, confirm it broke nothing, then flip it on.

Phase 2: the frontend

Ported AuthContext, LoginModal, and WelcomePage from Eight.ly, adjusted for Professional's dark theme and the cookie model. Eight.ly keeps a JWT in localStorage; Professional uses an HttpOnly session cookie the frontend never sees. The context has five states, and they decide which screen renders:

// web/eightly-dashboard/src/contexts/AuthContext.tsx
export type AuthStatus =
  | 'loading'
  | 'unconfigured'     // zero users exist — show SetupScreen
  | 'unauthenticated'  // users exist, no session cookie — show WelcomePage
  | 'authenticated'    // logged in
  | 'disabled';        // EIGHTLY_AUTH_DISABLED=1 — bypass UI entirely

On boot the context hits /api/auth/status first, so an unconfigured install lands on the setup screen without doing the 401 dance. SetupScreen is the one component Eight.ly does not have, because Eight.ly ships pre-configured with admin/admin. Professional starts empty. The screen collects a username, optional email, password and confirm, creates the admin, issues the cookie, and drops you on the dashboard.

Settings > Users got rewired. The apiWithFallback mock path is gone, replaced by an authFetch helper that sends credentials: 'same-origin', unwraps the {success, data} envelope, and throws on {success: false} instead of quietly serving fake users. User IDs went from auto-incrementing numbers to strings from the backend. The table now shows the real admin you just created.

Phase 3: the cleanup

Three things that only made sense once the auth layer existed.

License activation got admin-gated. POST /api/license/activate now checks the role on the request and 403s anyone who is not admin, so a guest account cannot bind a license key on someone else's NAS:

// pkg/api/license/handlers.go
writeJSON(w, 403, map[string]interface{}{
    "success": false,
    "error":   "admin access required to activate a license",
})

The SSE event stream got pulled out of the public whitelist. /api/events had been bypassing auth; now it needs a session like everything else, the way the container shell WebSocket already did.

The "Demo Mode" badge in the header got removed. That badge existed to warn you when the frontend was serving mock data because the backend was unreachable. With the mock fallback ripped out, the badge would be a lie, so it is gone along with the MOCK_DATA.currentUser fallback path that fed it.

There is also a must_change_password flag now. When an admin creates a user, it gets set, and the frontend renders a yellow banner at the top of every page until that user rotates their temporary password.

The smoke test

I verified the whole thing on pro-dev in enforcing mode. Setup created the admin and auto-issued the cookie, and /api/auth/status flipped to configured: true. Without a cookie, /api/apps returned 401; with the cookie, 200. /api/auth/me returned the real user, /api/users listed them, logout cleared the cookie, the wrong password was rejected, and the right one let me back in.

The events change checked out too: /api/events returned 401 without a cookie, where it had been 200 before. And a viewer-role account got 403 on /api/license/activate, while the admin passed the gate and only failed later on key format, which is exactly what should happen.

The part I did not do

The Users tab still has a 2FA toggle the backend does not implement, so the toggle does nothing. API keys for headless automation, which Eight.ly has and Professional does not, are not in this pass. Neither is password reset over email. All of it is on the backlog, and I said so rather than wiring up a switch that pretends to work, because pretending to work is the exact problem I just spent two days deleting.

The lesson I am taking from this one is that "pretty easy, right?" is almost never true on reflex. The welcome page was easy. The gate was real auth, and real auth is real infrastructure: two days, three phases. Calling it a one-hour job and then quietly burning a day and a half would have been worse than scoping it honestly up front.

The Users tab shows one real user now, backed by a bcrypt hash on disk, a signed cookie, and middleware that actually checks it.

mjashley.com · Eight.ly