Add session abstraction, mobile bearer auth, and pluggable SSO
Refactor authentication into a provider-agnostic session layer and build
two new auth surfaces on top of it, without changing local password/TOTP
behavior. Every flow now issues sessions through
sessionService.createSession(user, authMethod).
Part 1 — Session abstraction (backward-compatible refactor):
- New server/src/auth/: token.js (JWT/cookie primitives), session.service.js
(create/validate/partial-TOTP/revoke), session.middleware.js
(attachSession/requireAuth/requireRole). utils/auth.js is now a thin
compat facade so existing imports are unchanged.
Part 2 — Mobile bearer auth (additive):
- /api/v1/auth/mobile/{login,refresh,logout}: short-lived access JWT +
long-lived refresh token, stored hashed and rotated on use, in a new
mobile_refresh_tokens table. Reuses web bot-scoring/backoff; single-request
TOTP. token.signToken gains a backward-compatible expiresIn option.
Part 3 — Pluggable SSO (Google, Discord, generic OIDC):
- OAuth2Provider base + built-in Google/Discord (fixed endpoints) + generic
OIDC, a registry with health/validation, PKCE+CSRF transaction state, and
discovery (GET /auth/providers), start/link/callback routes.
- Link-only policy: SSO signs in only to an already-linked account; external
identities are never auto-provisioned. Client secrets encrypted at rest
(AES-256-GCM, utils/secretBox.js). Admin CRUD (/admin/auth/providers) and
account linking (/admin/account/identities). New auth_providers +
user_identities tables.
Frontend:
- Login page renders provider buttons from /auth/providers (inline SVG icons,
graceful with zero providers). New Authentication admin view
(Local/Google/Discord/Custom). Account page linked-accounts section.
Tests: 83 passing (session, mobile, providers, registry, secretBox, ssoState,
ssoCallback) — all DB-free via fetch mocks + model stubs. README + .env.example
updated.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
59
server/src/auth/ssoState.js
Normal file
59
server/src/auth/ssoState.js
Normal file
@@ -0,0 +1,59 @@
|
||||
// ── SSO transaction state (CSRF + PKCE) ────────────────────────────────────
|
||||
//
|
||||
// An OAuth redirect flow spans two requests (start → callback) with a hop to the
|
||||
// IdP in between, so we must carry state across it safely:
|
||||
//
|
||||
// - CSRF: an attacker must not be able to forge a callback. We bind the flow to
|
||||
// the user's browser with a short-lived, signed, httpOnly cookie (sso_tx) and
|
||||
// put only an opaque `nonce` in the URL `state` param. The callback requires
|
||||
// state === cookie.nonce, so a callback not initiated by this browser fails.
|
||||
// - PKCE: the code_verifier is generated at start, kept ONLY in the httpOnly
|
||||
// cookie (never in the URL/logs), and sent to the token endpoint at callback.
|
||||
//
|
||||
// The cookie is a signed JWT (reusing the app's JWT signing) with a tight TTL, so
|
||||
// it cannot be tampered with and expires quickly if a flow is abandoned.
|
||||
|
||||
const crypto = require('crypto')
|
||||
const token = require('./token')
|
||||
|
||||
const TX_COOKIE = 'sso_tx'
|
||||
const TX_TTL = '10m' // a login round-trip is quick; abandon after 10 minutes
|
||||
|
||||
// base64url of random bytes — used for the nonce and the PKCE verifier.
|
||||
function randomUrlSafe(bytes = 32) {
|
||||
return crypto.randomBytes(bytes).toString('base64url')
|
||||
}
|
||||
|
||||
// PKCE S256 challenge for a given verifier.
|
||||
function codeChallengeFor(verifier) {
|
||||
return crypto.createHash('sha256').update(verifier).digest('base64url')
|
||||
}
|
||||
|
||||
// Create a transaction: returns { nonce, verifier, codeChallenge, txToken }.
|
||||
// `data` = { provider, mode ('login'|'link'), linkUserId?, returnTo? }.
|
||||
function createTx(data) {
|
||||
const nonce = randomUrlSafe(16)
|
||||
const verifier = randomUrlSafe(32)
|
||||
const codeChallenge = codeChallengeFor(verifier)
|
||||
const txToken = token.signToken(
|
||||
{ id: 'sso' }, // subject is irrelevant; this is a flow token, not a session
|
||||
{ nonce, verifier, ...data, kind: 'sso_tx' },
|
||||
{ expiresIn: TX_TTL },
|
||||
)
|
||||
return { nonce, verifier, codeChallenge, txToken }
|
||||
}
|
||||
|
||||
// Verify a tx cookie against the state param. Returns the tx payload
|
||||
// ({ nonce, verifier, provider, mode, ... }) or null if missing/expired/mismatched.
|
||||
function verifyTx(txToken, stateNonce) {
|
||||
if (!txToken || !stateNonce) return null
|
||||
const decoded = token.verifyToken(txToken)
|
||||
if (!decoded || decoded.kind !== 'sso_tx') return null
|
||||
// Constant-time compare so a mismatch can't be timed.
|
||||
const a = Buffer.from(String(decoded.nonce))
|
||||
const b = Buffer.from(String(stateNonce))
|
||||
if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) return null
|
||||
return decoded
|
||||
}
|
||||
|
||||
module.exports = { TX_COOKIE, TX_TTL, createTx, verifyTx, codeChallengeFor, randomUrlSafe }
|
||||
Reference in New Issue
Block a user