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:
128
server/src/auth/providers/registry.js
Normal file
128
server/src/auth/providers/registry.js
Normal file
@@ -0,0 +1,128 @@
|
||||
// ── Provider registry ──────────────────────────────────────────────────────
|
||||
//
|
||||
// Turns stored auth_providers rows into live provider instances, and owns the
|
||||
// "which providers are usable" health logic. The authentication layer talks to
|
||||
// the registry, never to a specific provider class, so adding a provider is just
|
||||
// a new entry in KINDS.
|
||||
//
|
||||
// Built-ins (google, discord) always "exist" as defaults even before an admin
|
||||
// creates a row, so the admin UI can render their config form. A provider is only
|
||||
// shown to end users (login page) when it is enabled AND its config validates.
|
||||
|
||||
const GoogleProvider = require('./google.provider')
|
||||
const DiscordProvider = require('./discord.provider')
|
||||
const GenericOidcProvider = require('./genericOidc.provider')
|
||||
const authProviders = require('../../model/authProviders/authProviders.model')
|
||||
|
||||
// kind → provider class.
|
||||
const KINDS = {
|
||||
google: GoogleProvider,
|
||||
discord: DiscordProvider,
|
||||
oidc: GenericOidcProvider,
|
||||
oauth2: GenericOidcProvider,
|
||||
}
|
||||
|
||||
// Built-in providers and their fixed display metadata. Endpoints are in the
|
||||
// provider classes; only enabled/clientId/secret are admin-configurable.
|
||||
const BUILTINS = [
|
||||
{ id: 'google', kind: 'google', name: 'Google', priority: 1 },
|
||||
{ id: 'discord', kind: 'discord', name: 'Discord', priority: 2 },
|
||||
]
|
||||
|
||||
const BUILTIN_IDS = new Set(BUILTINS.map((b) => b.id))
|
||||
|
||||
function isBuiltin(id) {
|
||||
return BUILTIN_IDS.has(id)
|
||||
}
|
||||
|
||||
// Instantiate a provider from a config row (secret already decrypted by the
|
||||
// model as `client_secret`). Returns null for an unknown kind.
|
||||
function instantiate(row) {
|
||||
const Klass = KINDS[row.kind]
|
||||
if (!Klass) return null
|
||||
return new Klass({
|
||||
id: row.id,
|
||||
kind: row.kind,
|
||||
name: row.name,
|
||||
enabled: row.enabled,
|
||||
clientId: row.client_id,
|
||||
clientSecret: row.client_secret, // present only via getWithSecret
|
||||
authorizeUrl: row.authorize_url,
|
||||
tokenUrl: row.token_url,
|
||||
userinfoUrl: row.userinfo_url,
|
||||
scopes: row.scopes,
|
||||
priority: row.priority,
|
||||
})
|
||||
}
|
||||
|
||||
// Load a ready-to-use provider instance (secret decrypted) by id, or null.
|
||||
async function load(id) {
|
||||
const row = await authProviders.getWithSecret(id)
|
||||
if (!row) return null
|
||||
return instantiate(row)
|
||||
}
|
||||
|
||||
// Validate a config row's completeness. Built-ins need client_id + a secret;
|
||||
// custom (oidc/oauth2) also need the three endpoint URLs. Returns { valid, missing }.
|
||||
function validateConfig(row) {
|
||||
const missing = []
|
||||
if (!row.client_id) missing.push('client_id')
|
||||
// A stored secret shows up as client_secret_enc on plain rows, or client_secret
|
||||
// on decrypted rows — accept either as "has a secret".
|
||||
if (!row.client_secret_enc && !row.client_secret) missing.push('client_secret')
|
||||
if (row.kind === 'oidc' || row.kind === 'oauth2') {
|
||||
if (!row.authorize_url) missing.push('authorize_url')
|
||||
if (!row.token_url) missing.push('token_url')
|
||||
if (!row.userinfo_url) missing.push('userinfo_url')
|
||||
}
|
||||
return { valid: missing.length === 0, missing }
|
||||
}
|
||||
|
||||
// All configured rows merged with built-in defaults (so google/discord always
|
||||
// appear for the admin UI even with no row yet). Each entry carries health.
|
||||
async function listConfigured() {
|
||||
const rows = await authProviders.list()
|
||||
const byId = new Map(rows.map((r) => [r.id, r]))
|
||||
const out = []
|
||||
// Built-ins first, in their fixed order.
|
||||
for (const b of BUILTINS) {
|
||||
const row = byId.get(b.id) || {
|
||||
id: b.id, kind: b.kind, name: b.name, enabled: 0,
|
||||
client_id: null, client_secret_enc: null, priority: b.priority,
|
||||
}
|
||||
byId.delete(b.id)
|
||||
out.push({ ...row, builtin: true, health: validateConfig(row) })
|
||||
}
|
||||
// Then any custom providers.
|
||||
for (const row of byId.values()) {
|
||||
out.push({ ...row, builtin: false, health: validateConfig(row) })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Providers that should appear to end users: enabled AND valid. Shaped for the
|
||||
// public discovery endpoint and sorted by priority.
|
||||
async function listEnabledValid() {
|
||||
const configured = await listConfigured()
|
||||
return configured
|
||||
.filter((p) => p.enabled && validateConfig(p).valid)
|
||||
.sort((a, b) => (a.priority ?? 100) - (b.priority ?? 100))
|
||||
.map((p) => ({
|
||||
id: p.id,
|
||||
name: p.name,
|
||||
icon: p.kind, // 'google' | 'discord' | 'oidc' | 'oauth2'
|
||||
loginUrl: `/api/v1/auth/sso/${p.id}/start`,
|
||||
priority: p.priority ?? 100,
|
||||
}))
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
KINDS,
|
||||
BUILTINS,
|
||||
isBuiltin,
|
||||
instantiate,
|
||||
load,
|
||||
validateConfig,
|
||||
listConfigured,
|
||||
listEnabledValid,
|
||||
}
|
||||
Reference in New Issue
Block a user