Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | 'use strict';
/**
* Module OIDC générique (flux Authorization Code + PKCE).
*
* Fournisseur par défaut : SSO « Les Communs » (Keycloak, login.lescommuns.org).
* - discovery OpenID (cache mémoire),
* - PKCE S256 (client public, pas de secret) ou client confidentiel (OIDC_CLIENT_SECRET),
* - `state` signé (JWT) portant state/nonce/code_verifier,
* - échange du code au token endpoint,
* - vérification de l'id_token via JWKS (RS256, iss, aud, exp, nonce).
*
* Aucune dépendance nouvelle : axios + crypto + jsonwebtoken (déjà présents).
* Ce module n'importe ni Express ni Mongoose → testable unitairement.
*/
const crypto = require('crypto');
const jwt = require('jsonwebtoken');
const axios = require('axios');
const STATE_TTL_SECONDS = 600;
const CACHE_TTL_MS = 60 * 60 * 1000;
class OidcError extends Error {
constructor(code, message) {
super(message || code);
this.name = 'OidcError';
this.code = code;
}
}
function getConfig() {
return {
issuer: (process.env.OIDC_ISSUER || '').replace(/\/+$/, ''),
clientId: process.env.OIDC_CLIENT_ID || '',
clientSecret: process.env.OIDC_CLIENT_SECRET || '',
redirectUri: process.env.OIDC_REDIRECT_URI || '',
scopes: (process.env.OIDC_SCOPES || 'openid profile email').split(/\s+/).filter(Boolean),
displayName: process.env.OIDC_DISPLAY_NAME || 'Les Communs',
secret: process.env.JWT_SECRET,
};
}
function isEnabled() {
const c = getConfig();
return Boolean(c.issuer && c.clientId);
}
function displayName() {
return getConfig().displayName;
}
// ---------------------------------------------------------------------------
// Caches discovery / JWKS (mémoire)
// ---------------------------------------------------------------------------
let _discovery = null;
let _discoveryAt = 0;
let _jwks = null;
let _jwksAt = 0;
function _resetCache() {
_discovery = null;
_discoveryAt = 0;
_jwks = null;
_jwksAt = 0;
}
async function getDiscovery() {
const c = getConfig();
if (_discovery && Date.now() - _discoveryAt < CACHE_TTL_MS) return _discovery;
const url = `${c.issuer}/.well-known/openid-configuration`;
let data;
try {
({ data } = await axios.get(url, { timeout: 10000 }));
} catch (e) {
throw new OidcError('discovery_failed', `Discovery OIDC injoignable (${e.message})`);
}
if (!data || !data.authorization_endpoint || !data.token_endpoint) {
throw new OidcError('discovery_failed', 'Discovery OIDC incomplète');
}
_discovery = data;
_discoveryAt = Date.now();
return _discovery;
}
async function getJwks(discovery) {
if (_jwks && Date.now() - _jwksAt < CACHE_TTL_MS) return _jwks;
if (!discovery.jwks_uri) throw new OidcError('discovery_failed', 'jwks_uri absent');
let data;
try {
({ data } = await axios.get(discovery.jwks_uri, { timeout: 10000 }));
} catch (e) {
throw new OidcError('discovery_failed', `JWKS injoignable (${e.message})`);
}
_jwks = data;
_jwksAt = Date.now();
return _jwks;
}
// ---------------------------------------------------------------------------
// PKCE / state
// ---------------------------------------------------------------------------
function createPkcePair() {
const verifier = crypto.randomBytes(32).toString('base64url');
const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
return { verifier, challenge };
}
function signState(payload, secret = getConfig().secret) {
return jwt.sign(payload, secret, { expiresIn: STATE_TTL_SECONDS });
}
function verifyState(token, secret = getConfig().secret) {
try {
return jwt.verify(token, secret);
} catch (e) {
throw new OidcError('invalid_state', 'state invalide ou expiré');
}
}
function parseCookies(header) {
const out = {};
String(header || '').split(';').forEach((part) => {
const i = part.indexOf('=');
if (i > -1) {
const k = part.slice(0, i).trim();
if (k) {
try {
out[k] = decodeURIComponent(part.slice(i + 1).trim());
} catch {
out[k] = part.slice(i + 1).trim();
}
}
}
});
return out;
}
// ---------------------------------------------------------------------------
// URL d'autorisation
// ---------------------------------------------------------------------------
function buildAuthorizationUrl(discovery, c, { state, nonce, codeChallenge }) {
const params = new URLSearchParams({
client_id: c.clientId,
redirect_uri: c.redirectUri,
response_type: 'code',
scope: c.scopes.join(' '),
state,
nonce,
code_challenge: codeChallenge,
code_challenge_method: 'S256',
});
const sep = discovery.authorization_endpoint.includes('?') ? '&' : '?';
return `${discovery.authorization_endpoint}${sep}${params.toString()}`;
}
async function start({ plan = null } = {}) {
const c = getConfig();
const discovery = await getDiscovery();
const state = crypto.randomBytes(16).toString('base64url');
const nonce = crypto.randomBytes(16).toString('base64url');
const { verifier, challenge } = createPkcePair();
const url = buildAuthorizationUrl(discovery, c, { state, nonce, codeChallenge: challenge });
const cookieValue = signState(
{ state, nonce, code_verifier: verifier, plan: plan || null },
c.secret
);
return { url, cookieValue };
}
// ---------------------------------------------------------------------------
// Vérification de l'id_token (JWKS)
// ---------------------------------------------------------------------------
function jwkToPem(jwk) {
const key = crypto.createPublicKey({ key: jwk, format: 'jwk' });
return key.export({ type: 'spki', format: 'pem' });
}
function verifyIdToken(idToken, { jwks, issuer, clientId, nonce }) {
if (!idToken) throw new OidcError('invalid_token', 'id_token manquant');
const decoded = jwt.decode(idToken, { complete: true });
if (!decoded || !decoded.header || !decoded.header.kid) {
throw new OidcError('invalid_token', 'id_token illisible');
}
const keys = (jwks && jwks.keys) || [];
const jwk = keys.find((k) => k.kid === decoded.header.kid);
if (!jwk) throw new OidcError('invalid_token', 'clé JWKS introuvable');
let claims;
try {
claims = jwt.verify(idToken, jwkToPem(jwk), {
algorithms: ['RS256', 'RS384', 'RS512'],
audience: clientId,
issuer,
});
} catch (e) {
throw new OidcError('invalid_token', `id_token invalide: ${e.message}`);
}
if (nonce && claims.nonce !== nonce) {
throw new OidcError('invalid_token', 'nonce invalide');
}
return claims;
}
// ---------------------------------------------------------------------------
// Échange du code + callback
// ---------------------------------------------------------------------------
async function finish({ code, state, cookieValue, error } = {}) {
const c = getConfig();
if (error) {
throw new OidcError(
error === 'access_denied' ? 'access_denied' : 'provider_error',
`Erreur fournisseur: ${error}`
);
}
if (!cookieValue) throw new OidcError('invalid_state', 'cookie oidc_state manquant');
const saved = verifyState(cookieValue, c.secret);
if (!state || state !== saved.state) throw new OidcError('invalid_state', 'state mismatch');
if (!code) throw new OidcError('provider_error', 'code manquant');
const discovery = await getDiscovery();
const body = new URLSearchParams({
grant_type: 'authorization_code',
code,
redirect_uri: c.redirectUri,
client_id: c.clientId,
code_verifier: saved.code_verifier,
});
if (c.clientSecret) body.set('client_secret', c.clientSecret);
let tokenData;
try {
const resp = await axios.post(discovery.token_endpoint, body.toString(), {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
timeout: 15000,
});
tokenData = resp.data;
} catch (e) {
const detail = e.response?.data?.error || e.message;
throw new OidcError('exchange_failed', `Échange du code échoué: ${detail}`);
}
const jwks = await getJwks(discovery);
const claims = verifyIdToken(tokenData.id_token, {
jwks,
issuer: discovery.issuer || c.issuer,
clientId: c.clientId,
nonce: saved.nonce,
});
return { claims, plan: saved.plan || null };
}
function normalizeClaims(claims, issuer) {
const issuerHost = (() => {
try {
return new URL(issuer).hostname;
} catch {
return 'sso';
}
})();
const preferred = claims.preferred_username || '';
const email = String(
claims.email || (preferred ? `${preferred}@${issuerHost}` : '')
).toLowerCase();
if (!email) throw new OidcError('no_email', 'Email absent du profil SSO');
return {
sub: claims.sub,
email,
name: claims.name || preferred || email.split('@')[0],
picture: claims.picture || null,
emailVerified: !!claims.email_verified,
};
}
module.exports = {
OidcError,
isEnabled,
displayName,
getConfig,
getDiscovery,
getJwks,
createPkcePair,
signState,
verifyState,
parseCookies,
buildAuthorizationUrl,
start,
finish,
verifyIdToken,
jwkToPem,
normalizeClaims,
_resetCache,
STATE_TTL_SECONDS,
};
|