feat(frontend): server-side Zitadel OIDC auth (part 2)

Add Authorization Code + PKCE login/logout against Zitadel, handled entirely
server-side with an httpOnly signed session cookie:
- $lib/server/auth: openid-client discovery (config cached), jose-signed
  session encode/decode, cookie/name constants
- routes: /login (builds the authorize URL with PKCE/state/nonce, ?mode=register
  -> prompt=create), /auth/callback (code exchange + session cookie),
  /logout (clears session + Zitadel end_session)
- hooks.server populates locals.user/accessToken from the session
- +layout.server exposes the user; Navbar shows the signed-in user + Salir,
  or Iniciar sesión / Registrarse
- switch to adapter-node; env-driven config (.env gitignored, .env.example
  committed) with issuer http://host.docker.internal:8080

Verified: svelte-check + build clean; dev smoke test shows the landing in the
logged-out state and /login issuing a 302 to Zitadel's authorize endpoint with
PKCE/state/nonce (discovery reachable). Real client id/secret still needed to
complete the token exchange.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-05 22:58:47 +02:00
co-authored by Claude Opus 4.8
parent 6bb31ad7c5
commit 0163da096e
14 changed files with 979 additions and 119 deletions
+5
View File
@@ -0,0 +1,5 @@
import type { LayoutServerLoad } from './$types';
export const load: LayoutServerLoad = ({ locals }) => ({
user: locals.user
});
+2 -2
View File
@@ -4,13 +4,13 @@
import Navbar from '$lib/components/Navbar.svelte';
import Footer from '$lib/components/Footer.svelte';
let { children } = $props();
let { children, data } = $props();
</script>
<svelte:head><link rel="icon" href={favicon} /></svelte:head>
<div class="flex min-h-screen flex-col bg-neutral-950 text-neutral-100 antialiased">
<Navbar />
<Navbar user={data.user} />
<main class="flex-1">{@render children()}</main>
<Footer />
</div>
@@ -0,0 +1,69 @@
import { redirect, error } from '@sveltejs/kit';
import * as client from 'openid-client';
import type { RequestHandler } from './$types';
import {
getOidcConfig,
encodeSession,
type Session,
SESSION_COOKIE,
STATE_COOKIE,
VERIFIER_COOKIE,
NONCE_COOKIE,
RETURN_COOKIE
} from '$lib/server/auth';
export const GET: RequestHandler = async ({ url, cookies }) => {
const codeVerifier = cookies.get(VERIFIER_COOKIE);
const state = cookies.get(STATE_COOKIE);
const nonce = cookies.get(NONCE_COOKIE);
const returnTo = cookies.get(RETURN_COOKIE) ?? '/explore';
if (!codeVerifier || !state) {
error(400, 'Estado de autenticación inválido. Vuelve a iniciar sesión.');
}
const config = await getOidcConfig();
let tokens;
try {
tokens = await client.authorizationCodeGrant(config, url, {
pkceCodeVerifier: codeVerifier,
expectedState: state,
expectedNonce: nonce,
idTokenExpected: true
});
} catch (exception) {
console.error('Token exchange failed', exception);
error(401, 'La autenticación ha fallado.');
}
const claims = tokens.claims();
if (!claims) {
error(401, 'El proveedor no devolvió el token de identidad.');
}
const session: Session = {
sub: String(claims.sub),
name: claims.name as string | undefined,
email: claims.email as string | undefined,
picture: claims.picture as string | undefined,
accessToken: tokens.access_token,
refreshToken: tokens.refresh_token,
idToken: tokens.id_token,
expiresAt: Math.floor(Date.now() / 1000) + (tokens.expires_in ?? 3600)
};
cookies.set(SESSION_COOKIE, await encodeSession(session), {
httpOnly: true,
sameSite: 'lax',
secure: url.protocol === 'https:',
path: '/',
maxAge: 60 * 60 * 24 * 7
});
for (const name of [STATE_COOKIE, VERIFIER_COOKIE, NONCE_COOKIE, RETURN_COOKIE]) {
cookies.delete(name, { path: '/' });
}
redirect(302, returnTo);
};
+50
View File
@@ -0,0 +1,50 @@
import { redirect } from '@sveltejs/kit';
import * as client from 'openid-client';
import type { RequestHandler } from './$types';
import {
getOidcConfig,
authConfig,
OIDC_SCOPE,
STATE_COOKIE,
VERIFIER_COOKIE,
NONCE_COOKIE,
RETURN_COOKIE
} from '$lib/server/auth';
export const GET: RequestHandler = async ({ url, cookies }) => {
const config = await getOidcConfig();
const codeVerifier = client.randomPKCECodeVerifier();
const codeChallenge = await client.calculatePKCECodeChallenge(codeVerifier);
const state = client.randomState();
const nonce = client.randomNonce();
const register = url.searchParams.get('mode') === 'register';
const returnTo = url.searchParams.get('returnTo') ?? '/explore';
const parameters: Record<string, string> = {
redirect_uri: authConfig.redirectUri,
scope: OIDC_SCOPE,
code_challenge: codeChallenge,
code_challenge_method: 'S256',
state,
nonce
};
if (register) parameters.prompt = 'create';
const authorizationUrl = client.buildAuthorizationUrl(config, parameters);
const cookieOptions = {
httpOnly: true,
sameSite: 'lax' as const,
secure: url.protocol === 'https:',
path: '/',
maxAge: 600
};
cookies.set(VERIFIER_COOKIE, codeVerifier, cookieOptions);
cookies.set(STATE_COOKIE, state, cookieOptions);
cookies.set(NONCE_COOKIE, nonce, cookieOptions);
cookies.set(RETURN_COOKIE, returnTo, cookieOptions);
redirect(302, authorizationUrl.href);
};
+20
View File
@@ -0,0 +1,20 @@
import { redirect } from '@sveltejs/kit';
import * as client from 'openid-client';
import type { RequestHandler } from './$types';
import { getOidcConfig, authConfig, decodeSession, SESSION_COOKIE } from '$lib/server/auth';
const handleLogout: RequestHandler = async ({ cookies }) => {
const session = await decodeSession(cookies.get(SESSION_COOKIE));
cookies.delete(SESSION_COOKIE, { path: '/' });
const config = await getOidcConfig();
const endSessionUrl = client.buildEndSessionUrl(config, {
post_logout_redirect_uri: authConfig.postLogoutUri,
...(session?.idToken ? { id_token_hint: session.idToken } : {})
});
redirect(302, endSessionUrl.href);
};
export const GET = handleLogout;
export const POST = handleLogout;