Modul server/fork/auth (Config, Session-Cookie, OIDC-Flow, Kontozuordnung), Einhängen in server/app.js, Client-Helfer für Login/Logout, PUT /api/user/rename für OIDC-Sessions gesperrt (A01). Tests gegen Mock-IdP. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
83 lines
3.6 KiB
JavaScript
83 lines
3.6 KiB
JavaScript
// In-Process-Mock-IdP (oidc-provider von panva) für die Auth-Tests. Nur Test-Hilfe.
|
|
import http from 'http';
|
|
import Provider from 'oidc-provider';
|
|
|
|
export const CLIENT = { client_id: 'hb-test', client_secret: 'hb-test-secret' };
|
|
|
|
export const startIdp = async ({ accounts, redirectUri })=>{
|
|
let handler = (req, res)=>{ res.statusCode = 503; res.end(); };
|
|
const server = http.createServer((req, res)=>handler(req, res));
|
|
await new Promise((r)=>server.listen(0, '127.0.0.1', r));
|
|
const issuer = `http://127.0.0.1:${server.address().port}`;
|
|
const provider = new Provider(issuer, {
|
|
clients : [{
|
|
...CLIENT,
|
|
redirect_uris : [redirectUri],
|
|
post_logout_redirect_uris : [`${new URL(redirectUri).origin}/`],
|
|
grant_types : ['authorization_code'],
|
|
response_types : ['code'],
|
|
token_endpoint_auth_method : 'client_secret_basic'
|
|
}],
|
|
pkce : { required: ()=>true },
|
|
scopes : ['openid', 'profile', 'email'],
|
|
claims : { openid: ['sub'], profile: ['name', 'preferred_username'], email: ['email', 'email_verified'] },
|
|
findAccount : async (ctx, id)=>accounts[id] && {
|
|
accountId : id,
|
|
claims : async ()=>({ sub: id, ...accounts[id] })
|
|
},
|
|
features : { devInteractions: { enabled: true }, rpInitiatedLogout: { enabled: true, logoutSource: async (ctx, form)=>{ ctx.body = `<html><body>${form}<script>document.forms[0].submit()</script></body></html>`; } } },
|
|
cookies : { keys: ['test-key'] },
|
|
ttl : { AuthorizationCode: 60, IdToken: 60, AccessToken: 60, Session: 60, Interaction: 60, Grant: 60 }
|
|
});
|
|
provider.proxy = true;
|
|
handler = provider.callback();
|
|
return { issuer, provider, close: ()=>new Promise((r)=>{ server.closeAllConnections?.(); server.close(r); }) };
|
|
};
|
|
|
|
// Fährt den Login-Flow wie ein Browser (Cookie-Jar) bis zum Redirect auf die App und gibt die Callback-URL zurück
|
|
export const loginAtIdp = async (authUrl, { login })=>{
|
|
const jar = {};
|
|
const setCookies = (res)=>{
|
|
for (const c of res.headers.getSetCookie()) {
|
|
const [kv] = c.split(';');
|
|
const i = kv.indexOf('=');
|
|
jar[kv.slice(0, i)] = kv.slice(i + 1);
|
|
}
|
|
};
|
|
const cookieHeader = ()=>Object.entries(jar).map(([k, v])=>`${k}=${v}`).join('; ');
|
|
const step = async (url, init = {})=>{
|
|
const res = await fetch(url, { redirect: 'manual', ...init, headers: { cookie: cookieHeader(), ...(init.headers || {}) } });
|
|
setCookies(res);
|
|
return res;
|
|
};
|
|
const origin = new URL(authUrl).origin;
|
|
let res = await step(authUrl);
|
|
let guard = 0;
|
|
while (guard++ < 15) {
|
|
const loc = res.headers.get('location');
|
|
if(!loc) throw new Error(`IdP-Flow ohne Redirect bei ${res.url}: ${res.status} ${(await res.text()).slice(0, 400)}`);
|
|
const next = new URL(loc, origin);
|
|
if(next.origin !== origin) return { callbackUrl: next.href };
|
|
if(/^\/interaction\/[^/]+$/.test(next.pathname)) {
|
|
const page = await (await step(next.href)).text();
|
|
const form = /<form[^>]*action="([^"]+)"[\s\S]*?<\/form>/.exec(page);
|
|
if(!form) throw new Error(`Interaktion ohne Formular: ${page.slice(0, 300)}`);
|
|
const body = new URLSearchParams();
|
|
for (const m of form[0].matchAll(/<input[^>]*>/g)) {
|
|
const name = /name="([^"]+)"/.exec(m[0])?.[1];
|
|
const value = /value="([^"]*)"/.exec(m[0])?.[1] ?? '';
|
|
if(name) body.set(name, value);
|
|
}
|
|
if(body.has('login')) { body.set('login', login); body.set('password', 'x'); }
|
|
res = await step(new URL(form[1], origin).href, {
|
|
method : 'POST',
|
|
headers : { 'content-type': 'application/x-www-form-urlencoded' },
|
|
body
|
|
});
|
|
continue;
|
|
}
|
|
res = await step(next.href);
|
|
}
|
|
throw new Error('Zu viele Redirects im IdP-Flow');
|
|
};
|