Die Upstream-Route prüft nur, ob newUsername der eigenen Sitzung gehört, nicht den alten Namen. Der Fork-Router beantwortet die Route jetzt vorher: - OIDC-Sitzung: 403 A01 (unverändert) - ohne Anmeldung: 403 - naturalcrit, HB_NATURALCRIT_RENAME=off (Standard): 403 A02 - naturalcrit, HB_NATURALCRIT_RENAME=signed: nur mit Nachweis oldSession (nc_session-Token des alten Namens, HS256 mit SECRET), sonst 403 A03 Mit signed startet die App außerhalb lokaler Umgebungen nicht, solange SECRET der Standardwert ist. server/app.js bleibt unverändert. ADR 0001: neuer Abschnitt 7, Konfiguration, Tests, Folgen, F14. Closes #21 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
124 lines
5.3 KiB
JavaScript
124 lines
5.3 KiB
JavaScript
import express from 'express';
|
|
import cookieParser from 'cookie-parser';
|
|
import { readAuthConfig, hasProvider, clientConfig } from './config.js';
|
|
import { createOidcClient, OidcCallbackError } from './oidc.js';
|
|
import { issueSession, readSession, clearSession, setTx, takeTx, safeRedirect } from './session.js';
|
|
import { mapAccount } from './accountMapping.js';
|
|
import { renameGuard } from './rename.js';
|
|
|
|
export { readAuthConfig, clientConfig };
|
|
|
|
const esc = (s)=>String(s).replace(/[&<>"']/g, (c)=>({ '&': '&', '<': '<', '>': '>', '"': '"', '\'': ''' }[c]));
|
|
|
|
const page = (title, body)=>`<!DOCTYPE html><html lang="de"><head><meta charset="utf-8"><title>${esc(title)}</title>`
|
|
+ `<meta name="viewport" content="width=device-width,initial-scale=1">`
|
|
+ `<style>body{font-family:sans-serif;max-width:32rem;margin:4rem auto;padding:0 1rem}a.btn{display:block;margin:.75rem 0;padding:.75rem 1rem;background:#0a7f6f;color:#fff;text-decoration:none;border-radius:4px;text-align:center}</style>`
|
|
+ `</head><body><h1>${esc(title)}</h1>${body}</body></html>`;
|
|
|
|
const errorPage = (res, status, message, retryUrl = '/auth/oidc/login')=>{
|
|
res.status(status).type('html').send(page('Anmeldung fehlgeschlagen',
|
|
`<p>${esc(message)}</p><p><a href="${esc(retryUrl)}">Erneut anmelden</a></p>`));
|
|
};
|
|
|
|
// Account-Middleware: läuft direkt nach der Upstream-Middleware und setzt req.account neu (ADR 0001 §3)
|
|
export const accountMiddleware = (config)=>(req, res, next)=>{
|
|
const session = hasProvider(config, 'oidc') ? readSession(req, config) : null;
|
|
if(session) {
|
|
req.account = { username: session.username, uid: session.uid, provider: 'oidc' };
|
|
} else if(hasProvider(config, 'naturalcrit')) {
|
|
if(req.account) req.account = { ...req.account, provider: 'naturalcrit' };
|
|
} else {
|
|
req.account = undefined;
|
|
}
|
|
next();
|
|
};
|
|
|
|
/**
|
|
* @param {object} config Ergebnis von readAuthConfig()
|
|
* @param {{ getUsers: ()=>object, brewAuthorExists: (name:string)=>Promise<boolean>, oidcClient?: object }} deps
|
|
*/
|
|
export const createAuthRouter = (config, deps = {})=>{
|
|
const router = express.Router();
|
|
const oidcEnabled = hasProvider(config, 'oidc');
|
|
const naturalcritEnabled = hasProvider(config, 'naturalcrit');
|
|
const parseCookies = cookieParser();
|
|
router.use((req, res, next)=>req.cookies ? next() : parseCookies(req, res, next));
|
|
|
|
// Upstream-Route absichern, bevor sie greift: OIDC gesperrt (A01), naturalcrit nur mit Nachweis (ADR 0001 §7)
|
|
router.put('/api/user/rename', renameGuard(config));
|
|
|
|
if(!naturalcritEnabled) {
|
|
router.post('/local/login', (req, res)=>res.status(404).json({ error: 'Not found' }));
|
|
}
|
|
|
|
router.get('/auth/logout', async (req, res)=>{
|
|
const wasOidc = req.account?.provider === 'oidc';
|
|
clearSession(res, config);
|
|
if(wasOidc && oidcEnabled) {
|
|
try {
|
|
const url = await (deps.oidcClient ?? (deps.oidcClient = createOidcClient(config))).buildEndSessionUrl();
|
|
if(url) return res.redirect(url);
|
|
} catch (err) {
|
|
console.warn('OIDC end_session nicht möglich:', err?.message);
|
|
}
|
|
}
|
|
res.redirect('/');
|
|
});
|
|
|
|
if(!oidcEnabled) {
|
|
// Abgeschaltete Methode: Endpunkte gesperrt
|
|
router.all('/auth/oidc/*splat', (req, res)=>res.status(404).json({ error: 'OIDC-Login ist deaktiviert.' }));
|
|
router.get('/auth/login', (req, res)=>res.status(404).json({ error: 'Not found' }));
|
|
return router;
|
|
}
|
|
|
|
const oidc = deps.oidcClient ?? (deps.oidcClient = createOidcClient(config));
|
|
|
|
// Auswahlseite, wenn beide Provider aktiv sind
|
|
router.get('/auth/login', (req, res)=>{
|
|
const redirect = safeRedirect(req.query.redirect);
|
|
if(!naturalcritEnabled) return res.redirect(`/auth/oidc/login?redirect=${encodeURIComponent(redirect)}`);
|
|
const ncUrl = `https://www.naturalcrit.com/login?redirect=${encodeURIComponent(`${config.publicUrl}${redirect}`)}`;
|
|
res.type('html').send(page('Anmelden',
|
|
`<a class="btn" href="/auth/oidc/login?redirect=${encodeURIComponent(redirect)}">${esc(config.oidc.label)}</a>`
|
|
+ `<a class="btn" href="${esc(ncUrl)}">NaturalCrit-Konto (Benutzername/Passwort, Google)</a>`));
|
|
});
|
|
|
|
router.get('/auth/oidc/login', async (req, res)=>{
|
|
try {
|
|
const { url, tx } = await oidc.buildLogin(req.query.redirect);
|
|
setTx(res, config, tx);
|
|
res.redirect(url);
|
|
} catch (err) {
|
|
console.error('OIDC login:', err);
|
|
if(err instanceof OidcCallbackError) return errorPage(res, err.status, err.message);
|
|
errorPage(res, 500, 'Anmeldung nicht möglich.');
|
|
}
|
|
});
|
|
|
|
router.get('/auth/oidc/callback', async (req, res)=>{
|
|
const tx = takeTx(req, res, config);
|
|
if(!tx) return errorPage(res, 400, 'Die Anmeldung ist abgelaufen oder wurde nicht von dieser Seite gestartet.');
|
|
if(req.query.state !== tx.state) return errorPage(res, 400, 'Ungültiger Anmeldezustand (state).');
|
|
|
|
try {
|
|
const identity = await oidc.handleCallback(tx, `${config.publicUrl}${req.originalUrl}`);
|
|
const users = deps.getUsers();
|
|
const user = await mapAccount(identity, {
|
|
users,
|
|
brewAuthorExists : deps.brewAuthorExists,
|
|
usernameClaim : config.oidc.usernameClaim,
|
|
linkByEmail : config.oidc.linkByEmail
|
|
});
|
|
issueSession(res, config, user, identity);
|
|
res.redirect(safeRedirect(tx.redirect));
|
|
} catch (err) {
|
|
console.error('OIDC callback:', err?.cause ?? err);
|
|
if(err instanceof OidcCallbackError) return errorPage(res, err.status, err.message);
|
|
errorPage(res, 500, 'Die Anmeldung ist fehlgeschlagen.');
|
|
}
|
|
});
|
|
|
|
return router;
|
|
};
|