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:
36
server/src/model/authProviders/authProviders.db.js
Normal file
36
server/src/model/authProviders/authProviders.db.js
Normal file
@@ -0,0 +1,36 @@
|
||||
const { query } = require('../../utils/db')
|
||||
|
||||
const COLS =
|
||||
'id, kind, name, enabled, client_id, client_secret_enc, authorize_url, token_url, userinfo_url, scopes, priority, created_at, updated_at'
|
||||
|
||||
async function list() {
|
||||
return query(`SELECT ${COLS} FROM auth_providers ORDER BY priority ASC, id ASC`)
|
||||
}
|
||||
|
||||
async function get(id) {
|
||||
const rows = await query(`SELECT ${COLS} FROM auth_providers WHERE id = ? LIMIT 1`, [id])
|
||||
return rows[0] || null
|
||||
}
|
||||
|
||||
// Upsert a provider row. `fields` are column values already prepared by the model
|
||||
// (secret pre-encrypted). Only the provided columns are written/updated.
|
||||
async function upsert(id, fields) {
|
||||
const cols = Object.keys(fields)
|
||||
const vals = cols.map((c) => fields[c])
|
||||
const insertCols = ['id', ...cols].map((c) => `\`${c}\``).join(', ')
|
||||
const placeholders = ['?', ...cols.map(() => '?')].join(', ')
|
||||
const updates = cols.map((c) => `\`${c}\` = VALUES(\`${c}\`)`).join(', ')
|
||||
await query(
|
||||
`INSERT INTO auth_providers (${insertCols}) VALUES (${placeholders})
|
||||
ON DUPLICATE KEY UPDATE ${updates}`,
|
||||
[id, ...vals],
|
||||
)
|
||||
return get(id)
|
||||
}
|
||||
|
||||
async function remove(id) {
|
||||
const res = await query('DELETE FROM auth_providers WHERE id = ?', [id])
|
||||
return Number(res.affectedRows || 0)
|
||||
}
|
||||
|
||||
module.exports = { list, get, upsert, remove }
|
||||
50
server/src/model/authProviders/authProviders.model.js
Normal file
50
server/src/model/authProviders/authProviders.model.js
Normal file
@@ -0,0 +1,50 @@
|
||||
// Auth-provider config store. Thin logic layer over authProviders.db, mirroring
|
||||
// the users model split. Owns encryption of the client secret at the boundary so
|
||||
// the DB layer only ever sees ciphertext and callers only ever see the decrypted
|
||||
// secret when they explicitly ask (getWithSecret) — the plain list/get paths
|
||||
// never surface it.
|
||||
|
||||
const db = require('./authProviders.db')
|
||||
const secretBox = require('../../utils/secretBox')
|
||||
|
||||
// All configured provider rows (secret column left as ciphertext; callers that
|
||||
// need the secret use getWithSecret).
|
||||
async function list() {
|
||||
return db.list()
|
||||
}
|
||||
|
||||
async function get(id) {
|
||||
return db.get(id)
|
||||
}
|
||||
|
||||
// Provider row with the client secret decrypted (server-side only — used by the
|
||||
// registry at token-exchange time). Returns null if the provider does not exist.
|
||||
async function getWithSecret(id) {
|
||||
const row = await db.get(id)
|
||||
if (!row) return null
|
||||
return { ...row, client_secret: row.client_secret_enc ? secretBox.decrypt(row.client_secret_enc) : null }
|
||||
}
|
||||
|
||||
// Create/update a provider. `secret` (raw) is encrypted here; pass secret ===
|
||||
// undefined to leave an existing secret untouched, or '' to keep it unchanged as
|
||||
// well (blank means "no change" from the admin UI). Returns the stored row.
|
||||
async function save(id, { kind, name, enabled, clientId, secret, authorizeUrl, tokenUrl, userinfoUrl, scopes, priority }) {
|
||||
const fields = {}
|
||||
if (kind !== undefined) fields.kind = kind
|
||||
if (name !== undefined) fields.name = name
|
||||
if (enabled !== undefined) fields.enabled = enabled ? 1 : 0
|
||||
if (clientId !== undefined) fields.client_id = clientId
|
||||
if (secret) fields.client_secret_enc = secretBox.encrypt(secret) // only when a new secret is given
|
||||
if (authorizeUrl !== undefined) fields.authorize_url = authorizeUrl
|
||||
if (tokenUrl !== undefined) fields.token_url = tokenUrl
|
||||
if (userinfoUrl !== undefined) fields.userinfo_url = userinfoUrl
|
||||
if (scopes !== undefined) fields.scopes = scopes
|
||||
if (priority !== undefined) fields.priority = priority
|
||||
return db.upsert(id, fields)
|
||||
}
|
||||
|
||||
async function remove(id) {
|
||||
return db.remove(id)
|
||||
}
|
||||
|
||||
module.exports = { list, get, getWithSecret, save, remove }
|
||||
62
server/src/model/mobileSessions/mobileSessions.db.js
Normal file
62
server/src/model/mobileSessions/mobileSessions.db.js
Normal file
@@ -0,0 +1,62 @@
|
||||
const { query } = require('../../utils/db')
|
||||
|
||||
// SQL for the mobile_refresh_tokens table. Tokens are stored only as sha256
|
||||
// hashes (token_hash); the raw refresh token never touches the database.
|
||||
|
||||
// Insert a new refresh-token row. expiresAt is a JS Date (or ms epoch).
|
||||
async function insert({ userId, tokenHash, deviceHash = null, userAgent = null, expiresAt }) {
|
||||
const res = await query(
|
||||
`INSERT INTO mobile_refresh_tokens (user_id, token_hash, device_hash, user_agent, expires_at)
|
||||
VALUES (?, ?, ?, ?, ?)`,
|
||||
[userId, tokenHash, deviceHash, userAgent, new Date(expiresAt)],
|
||||
)
|
||||
return res.insertId
|
||||
}
|
||||
|
||||
// Look up a token by hash only if it is still usable: not revoked and not past
|
||||
// its expiry. Returns the row (incl. user_id) or null.
|
||||
async function findValidByHash(tokenHash) {
|
||||
const rows = await query(
|
||||
`SELECT * FROM mobile_refresh_tokens
|
||||
WHERE token_hash = ? AND revoked_at IS NULL AND expires_at > NOW()
|
||||
LIMIT 1`,
|
||||
[tokenHash],
|
||||
)
|
||||
return rows[0] || null
|
||||
}
|
||||
|
||||
// Mark a single token revoked (idempotent — only affects a not-yet-revoked row).
|
||||
// Returns the number of rows changed.
|
||||
async function revokeByHash(tokenHash) {
|
||||
const res = await query(
|
||||
'UPDATE mobile_refresh_tokens SET revoked_at = NOW() WHERE token_hash = ? AND revoked_at IS NULL',
|
||||
[tokenHash],
|
||||
)
|
||||
return Number(res.affectedRows || 0)
|
||||
}
|
||||
|
||||
// Revoke every active token for a user (logout-everywhere). Returns rows changed.
|
||||
async function revokeAllForUser(userId) {
|
||||
const res = await query(
|
||||
'UPDATE mobile_refresh_tokens SET revoked_at = NOW() WHERE user_id = ? AND revoked_at IS NULL',
|
||||
[userId],
|
||||
)
|
||||
return Number(res.affectedRows || 0)
|
||||
}
|
||||
|
||||
// Housekeeping: delete rows that are long dead (expired or revoked). Keeps the
|
||||
// table from growing without bound. Returns rows removed.
|
||||
async function pruneExpired() {
|
||||
const res = await query(
|
||||
'DELETE FROM mobile_refresh_tokens WHERE expires_at < NOW() OR revoked_at IS NOT NULL',
|
||||
)
|
||||
return Number(res.affectedRows || 0)
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
insert,
|
||||
findValidByHash,
|
||||
revokeByHash,
|
||||
revokeAllForUser,
|
||||
pruneExpired,
|
||||
}
|
||||
40
server/src/model/mobileSessions/mobileSessions.model.js
Normal file
40
server/src/model/mobileSessions/mobileSessions.model.js
Normal file
@@ -0,0 +1,40 @@
|
||||
// Mobile refresh-token store. Thin logic layer over mobileSessions.db — mirrors
|
||||
// the users model split (.db = SQL, .model = the API the rest of the app calls).
|
||||
// The refresh token itself is opaque and lives client-side; only its hash is
|
||||
// persisted (hashing is done by the session service so caller + store agree).
|
||||
|
||||
const db = require('./mobileSessions.db')
|
||||
|
||||
// Persist a newly issued refresh token (by hash). Returns the row id.
|
||||
async function store({ userId, tokenHash, deviceHash, userAgent, expiresAt }) {
|
||||
return db.insert({ userId, tokenHash, deviceHash, userAgent, expiresAt })
|
||||
}
|
||||
|
||||
// Return the stored row for a still-valid (unrevoked, unexpired) token, else null.
|
||||
async function findValidByHash(tokenHash) {
|
||||
return db.findValidByHash(tokenHash)
|
||||
}
|
||||
|
||||
// Revoke one refresh token (logout / rotation). Returns rows changed (0 if it was
|
||||
// already gone/revoked — callers treat this idempotently).
|
||||
async function revokeByHash(tokenHash) {
|
||||
return db.revokeByHash(tokenHash)
|
||||
}
|
||||
|
||||
// Revoke all of a user's refresh tokens (logout everywhere).
|
||||
async function revokeAllForUser(userId) {
|
||||
return db.revokeAllForUser(userId)
|
||||
}
|
||||
|
||||
// Drop expired/revoked rows.
|
||||
async function pruneExpired() {
|
||||
return db.pruneExpired()
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
store,
|
||||
findValidByHash,
|
||||
revokeByHash,
|
||||
revokeAllForUser,
|
||||
pruneExpired,
|
||||
}
|
||||
38
server/src/model/userIdentities/userIdentities.db.js
Normal file
38
server/src/model/userIdentities/userIdentities.db.js
Normal file
@@ -0,0 +1,38 @@
|
||||
const { query } = require('../../utils/db')
|
||||
|
||||
// Find the identity row for an external (provider, subject) pair. This is the
|
||||
// link-only login lookup: no row → no account → login refused.
|
||||
async function findByProviderSubject(provider, subject) {
|
||||
const rows = await query(
|
||||
'SELECT * FROM user_identities WHERE provider = ? AND subject = ? LIMIT 1',
|
||||
[provider, subject],
|
||||
)
|
||||
return rows[0] || null
|
||||
}
|
||||
|
||||
// All identities linked to a given internal user (for the Account page).
|
||||
async function listForUser(userId) {
|
||||
return query(
|
||||
'SELECT id, provider, subject, email, created_at FROM user_identities WHERE user_id = ? ORDER BY provider',
|
||||
[userId],
|
||||
)
|
||||
}
|
||||
|
||||
async function insert({ userId, provider, subject, email = null }) {
|
||||
const res = await query(
|
||||
'INSERT INTO user_identities (user_id, provider, subject, email) VALUES (?, ?, ?, ?)',
|
||||
[userId, provider, subject, email],
|
||||
)
|
||||
return res.insertId
|
||||
}
|
||||
|
||||
// Remove a user's link to a provider. Returns rows deleted.
|
||||
async function deleteForUserProvider(userId, provider) {
|
||||
const res = await query(
|
||||
'DELETE FROM user_identities WHERE user_id = ? AND provider = ?',
|
||||
[userId, provider],
|
||||
)
|
||||
return Number(res.affectedRows || 0)
|
||||
}
|
||||
|
||||
module.exports = { findByProviderSubject, listForUser, insert, deleteForUserProvider }
|
||||
27
server/src/model/userIdentities/userIdentities.model.js
Normal file
27
server/src/model/userIdentities/userIdentities.model.js
Normal file
@@ -0,0 +1,27 @@
|
||||
// Account-linking store: maps external SSO identities to internal users. Thin
|
||||
// logic layer over userIdentities.db (mirrors the users model split).
|
||||
|
||||
const db = require('./userIdentities.db')
|
||||
|
||||
// The link-only login lookup. Returns the identity row (with user_id) or null.
|
||||
async function findByProviderSubject(provider, subject) {
|
||||
return db.findByProviderSubject(provider, subject)
|
||||
}
|
||||
|
||||
// Identities linked to a user (Account page).
|
||||
async function listForUser(userId) {
|
||||
return db.listForUser(userId)
|
||||
}
|
||||
|
||||
// Link an external identity to an internal user. Returns the new row id. The
|
||||
// (provider, subject) UNIQUE constraint enforces one-identity-one-user at the DB.
|
||||
async function link({ userId, provider, subject, email }) {
|
||||
return db.insert({ userId, provider, subject, email })
|
||||
}
|
||||
|
||||
// Unlink a provider from a user. Returns rows removed (0 if nothing was linked).
|
||||
async function unlink(userId, provider) {
|
||||
return db.deleteForUserProvider(userId, provider)
|
||||
}
|
||||
|
||||
module.exports = { findByProviderSubject, listForUser, link, unlink }
|
||||
Reference in New Issue
Block a user