`lib/use-auth.js` is now the sole client-side auth surface (P1 §9 of
`.convoys/ship-readiness.md`). The legacy `lib/auth-context.js`
(`AuthProvider` + `useAuth`) and `lib/admin-auth.js` (`AdminProvider` +
`useAdmin` + `useIsAdmin`) are deleted; every importer is migrated to
the canonical hook. Pre-convoy a worst-case page mount issued THREE
identical `GET /api/auth/verify` requests (one per provider/hook); the
post-convoy floor is one verify per page mount (3 → 1 on
`pages/card/[id].js`, 2 → 1 elsewhere).
Importer inventory swept (7 source files):
- `pages/_app.js` — removed `<AuthProvider>` wrapper; `<ThemeProvider>`
is now the only top-level provider. `lib/use-auth.js` is hook-only,
no replacement provider needed.
- `pages/index.js`, `pages/scanner.js`, `pages/decks.js`,
`pages/deck/[id].js`, `pages/deck-builder.js` — `import { useAuth }`
path swap from `../lib/auth-context` to `../lib/use-auth`. All five
pages destructured only `{ user }` or `{ user, loading }`; verified
no consumer reads `login` / `register` from useAuth (those flows are
in `pages/login.js` / `pages/signup.js` which call the API directly),
so no shape-parity gap on `lib/use-auth.js`.
- `pages/card/[id].js` — replaced `useIsAdmin()` (the only consumer of
`lib/admin-auth.js` anywhere in the tree) with synchronous
`user?.role === 'admin'` derived from the existing `useAuth()` call.
Render condition at line 524 stays byte-identical.
Decisions documented in `.convoys/single-auth-provider.md`:
- D1: no extension to `lib/use-auth.js` (zero call sites for `login` /
`register` from useAuth — those flows are direct fetches in
`login.js` / `signup.js`).
- D2: `useIsAdmin()` collapses onto `useAuth()`; no separate hook.
- D3: provider tree `<ThemeProvider><AuthProvider>{children}</AuthProvider></ThemeProvider>`
→ `<ThemeProvider>{children}</ThemeProvider>`.
- D4: 3 → 1 verify roundtrip on `card/[id].js`; 2 → 1 on every other
page-load.
- D5: zero test files modified; the 21-test vitest suite is server-
side or prop-driven (`Layout.test.js` passes `user` as a prop, never
imports the legacy hooks).
Doc / config updates so the deletion lands cleanly:
- `.github/CODEOWNERS` — drop the two CODEOWNERS lines for the deleted
files.
- `AGENTS.md` § 2 architecture row + § 3 "Auth (client)" bullet —
rewritten for the post-convoy single-surface state.
- `.cursor/rules/auth-and-permissions.mdc` — § "Legacy" reframed to
"deleted by this convoy"; § "Authentication state on the client"
updated to the post-convoy `useAuth()` shape and the direct-fetch
login flow used by `login.js` / `signup.js`.
- `.cursor/rules/no-go-zones.mdc` — auth-refactors bullet drops the
deleted files from the canonical list.
- `.cursor/skills/add-page/SKILL.md` — checklist + anti-pattern row
refer to the deletion.
Verification:
- `rg "lib/auth-context|lib/admin-auth" --type js` → 0 hits in source.
- `npm run lint` → 128 → 125 problems (3 fewer errors from the deleted
unused-import lines; no regression).
- `npm run test:run` → 21/21 pass (including the 5 Layout regression
locks from `fix-layout-default-user`, which are prop-driven and
unaffected).
- `npm run build` → all 26 pages compile end-to-end; no SSR / static-
generation breakage that would have surfaced if a page tried to use
the legacy context hook unwrapped.
- Manual smoke deferred to operator post-merge per convoy doc.
Risks (full discussion in convoy file):
- R1 shape parity gap — verified zero consumers of legacy-only
surface; mitigated.
- R2 SSR mismatch from removing `<AuthProvider>` — `useEffect`-
guarded `localStorage` read; identical SSR shape pre/post; build
passes.
- R3 missed importer — post-delete grep + build pass would surface
any miss.
- R5 stale `useAuth` cache across components — pre-existing
pattern, called out as follow-up rather than addressed here.
Out of scope: any change to `lib/permission-middleware.js` (server-
side; resolved P0 #1), `lib/auth-secret.js` (resolved P0 #2),
`pages/api/**` route handlers, login / register API contracts, or
the seeded admin account flow.
Co-authored-by: Cursor <cursoragent@cursor.com>
72 lines
5.1 KiB
Text
72 lines
5.1 KiB
Text
---
|
|
description: Auth model + permission model for Deck Hearth (JWT + collection roles)
|
|
globs: pages/api/**/*.js,lib/*.js,components/*.js,pages/*.js
|
|
---
|
|
|
|
# Auth + permissions
|
|
|
|
There are three parallel client-side auth implementations and one server-side helper. New code should use the canonical set listed below; don't proliferate variants.
|
|
|
|
## Canonical surface (use these)
|
|
|
|
| Concern | Module |
|
|
| --- | --- |
|
|
| Server: extract user from request | `lib/permission-middleware.js::getUserFromRequest` |
|
|
| Server: gate a collection route | `lib/permission-middleware.js::withCollectionPermission` |
|
|
| Server: log collection mutation | `lib/permission-middleware.js::logCollectionActivity` |
|
|
| Server: JWT secret + canonical TTL | `lib/auth-secret.js` (`JWT_SECRET`, `JWT_TOKEN_TTL`) — single source of truth, fail-loud on unset env |
|
|
| Server: token / password primitives | `pages/api/auth-utils.js` (`generateToken`, `verifyToken`, `hashPassword`, `verifyPassword`) — reads secret + TTL from `lib/auth-secret.js` |
|
|
| Server: rate-limit auth endpoints | `lib/rate-limit.js::checkAuthRateLimit` (5 attempts / 15 min sliding window via `@upstash/ratelimit`) |
|
|
| Client: hook | `lib/use-auth.js::useAuth` |
|
|
| Client: route protection | `components/ProtectedRoute.js` |
|
|
| Client: admin route protection | `components/AdminProtected.js` |
|
|
|
|
## Legacy (deleted by `single-auth-provider`)
|
|
|
|
`lib/auth-context.js` and `lib/admin-auth.js` were the two parallel client-side
|
|
auth surfaces that lived alongside `lib/use-auth.js`. They were deleted by the
|
|
`single-auth-provider` convoy (P1). Do **not** reintroduce a `<AuthProvider>`
|
|
or `<AdminProvider>` wrapper in `pages/_app.js` — `useAuth()` from
|
|
`lib/use-auth.js` is hook-only (reads token from `localStorage` and hits
|
|
`/api/auth/verify` on mount) and does not require a context provider. The
|
|
`useIsAdmin` semantic is now `const { user } = useAuth(); const isAdmin = user?.role === 'admin'`.
|
|
|
|
## Token model
|
|
|
|
- JWT in localStorage under the key `auth_token`.
|
|
- Signed with `JWT_SECRET` (HS256), **24-hour expiry** (canonical `JWT_TOKEN_TTL = '24h'` from `lib/auth-secret.js`), payload `{ userId, email, role }`.
|
|
- Sent on every authenticated fetch as `Authorization: Bearer <token>`.
|
|
- Verified server-side with `jsonwebtoken.verify(token, JWT_SECRET)` (or `verifyToken` from `pages/api/auth-utils.js`).
|
|
|
|
**`JWT_SECRET` MUST be set in the deploy environment.** `lib/auth-secret.js` is the only place either `JWT_SECRET` or `JWT_TOKEN_TTL` is defined; the module **throws at import time** if `process.env.JWT_SECRET` is unset, which fails the request loudly rather than silently signing with a literal fallback. (The legacy `'your-secret-key-change-in-production'` fallback was duplicated across 7 files pre-`fix-auth-bypass`; that whole pattern is gone — do not reintroduce it.)
|
|
|
|
## Roles
|
|
|
|
Two role surfaces are in play:
|
|
|
|
1. **User role** — `users.role` column, values `'user'` or `'admin'`. Admin gates `/admin/*` pages and admin-only API endpoints.
|
|
2. **Collection role** — `collection_permissions.role` (`viewer` / `editor` / `owner`) + `collections.is_public` (anonymous viewer access). Resolved by `checkCollectionPermission` in priority order: owner → public-viewer → explicit row.
|
|
|
|
When introducing a new permission tier, update both `checkRolePermission`'s hierarchy AND every gate that reads `is_public`.
|
|
|
|
## Authentication state on the client
|
|
|
|
`useAuth()` returns `{ user, loading, logout, refreshAuth }`. `user === null` means logged out; `loading === true` means token verification in flight. Always render against `loading === false` before deciding to redirect. The login / register flows do **not** go through `useAuth` — `pages/login.js` and `pages/signup.js` `fetch` `/api/auth/{login,register}` directly and write the returned token to `localStorage`; `useAuth()` will pick it up on next mount via its `useEffect` → `/api/auth/verify` roundtrip (or call `refreshAuth()` to re-verify in place).
|
|
|
|
## Server-side authorization patterns
|
|
|
|
`getUserFromRequest` returns `{ userId, email, role }` for a valid Bearer token, or `null` for any other case (missing header, malformed token, wrong signature, expired token, unknown user id). **`null` means 401** — always early-return before doing anything that depends on the user:
|
|
|
|
```js
|
|
const user = await getUserFromRequest(req);
|
|
if (!user) return res.status(401).json({ error: 'Authentication required' });
|
|
```
|
|
|
|
There is **no synthetic-admin fallback** for missing tokens. The old dev-mode behavior of returning user 1 as admin is gone (resolved by `fix-auth-bypass` Brief 2, commit `258e479`). Do not reintroduce it under any framing — `test/lib/permission-middleware.test.js` has a negative regression test that will fail if the synthetic-admin shape comes back.
|
|
|
|
From there:
|
|
|
|
- **Owner-only** (delete, settings): inside the handler, `if (user.userId !== resource.user_id) return res.status(403)`.
|
|
- **Editor-or-owner**: use `withCollectionPermission('editor')`.
|
|
- **Public read**: use `withCollectionPermission('viewer')` — handles `is_public` and explicit-permission case.
|
|
- **Admin-only**: check `user.role === 'admin'` directly; consider extracting `withAdmin()` if a third call site appears.
|