All files / src/lib auth.ts

93.13% Statements 95/102
87.61% Branches 92/105
100% Functions 11/11
95.23% Lines 80/84

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 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420                  80x   80x                               80x                                   2x                                     80x         18x 18x 17x   17x             11x   6x 6x 6x                                 12x 12x 9x 9x 9x 9x 9x   1x                                     11x   11x 23x 19x 19x     11x 11x 11x   11x     80x         16x 4x           4x 4x 4x 4x 4x   12x 11x 11x       11x 11x 11x         11x 11x     11x 11x     11x 11x   11x   12x     14x 14x           14x 14x     14x                                           80x                             4x             80x                           80x                                                                                                                                                                                                                           118x 96x 96x 86x   76x 118x 76x             76x           76x   76x                       15x             498x 27x 23x 23x 15x 15x 9x 2x    
import { type NextAuthOptions, type User } from "next-auth";
import type { OAuthConfig } from "next-auth/providers/oauth";
import CredentialsProvider from "next-auth/providers/credentials";
import type { AssuranceLevel } from "@/lib/assurance";
import { getTransaction, updateTransaction } from "@/lib/eudi-store";
import { patientPseudonym } from "@/lib/patient-identity";
import { ownPatientId } from "@/lib/overview/patient";
 
const keycloakServerUrl =
  process.env.KEYCLOAK_ISSUER ?? "http://keycloak:8080/realms/edcv";
const keycloakPublicUrl =
  process.env.KEYCLOAK_PUBLIC_URL ?? "http://localhost:8080/realms/edcv";
 
/**
 * Custom Keycloak OIDC provider with split URLs (Docker-internal vs public).
 *
 * All server-side endpoints (token, userinfo, jwks) use the Docker-internal
 * hostname (keycloak:8080). Browser-facing endpoints (authorization, issuer)
 * use the public localhost URL.
 *
 * IMPORTANT: Do NOT set `wellKnown` — NextAuth v4 fetches the OIDC discovery
 * document and uses its endpoint URLs, which contain `localhost:8080`. From
 * inside the container, `localhost` resolves to the container itself (not the
 * Keycloak container), causing ECONNREFUSED during token exchange.
 *
 * See CLAUDE.md Gotchas #5 and #6.
 */
const keycloakProvider: OAuthConfig<Record<string, unknown>> = {
  id: "keycloak",
  name: "Keycloak",
  type: "oauth",
  issuer: keycloakPublicUrl,
  clientId: process.env.KEYCLOAK_CLIENT_ID || "health-dataspace-ui",
  clientSecret:
    process.env.KEYCLOAK_CLIENT_SECRET || "health-dataspace-ui-secret",
  authorization: {
    url: `${keycloakPublicUrl}/protocol/openid-connect/auth`,
    params: { scope: "openid profile email" },
  },
  token: `${keycloakServerUrl}/protocol/openid-connect/token`,
  userinfo: `${keycloakServerUrl}/protocol/openid-connect/userinfo`,
  jwks_endpoint: `${keycloakServerUrl}/protocol/openid-connect/certs`,
  idToken: true,
  checks: ["pkce", "state"],
  profile(profile) {
    return {
      id: profile.sub as string,
      name: (profile.name ?? profile.preferred_username) as string,
      email: profile.email as string,
      image: null,
    };
  },
};
 
/**
 * EUDI Wallet (OpenID4VP) sign-in provider.
 *
 * The browser only ever holds an opaque `sid`. The QR-login routes verify the
 * wallet presentation server-side (delegating cryptographic verification to the
 * verifier backend) and pin the resolved demo patient to that `sid` in
 * eudi-store. authorize() re-reads that pinned, server-verified result and
 * mints a PATIENT session. Single-use: the sid is consumed so a captured value
 * cannot be replayed. Requires session.strategy="jwt" (already set below).
 */
const eudiWalletProvider = CredentialsProvider({
  id: "eudi-wallet",
  name: "EUDI Wallet",
  credentials: { sid: { label: "sid", type: "text" } },
  async authorize(credentials) {
    const sid = credentials?.sid;
    if (!sid) return null;
    const tx = getTransaction(sid);
    // A link presentation (ADR-067) changes an account; it never signs in.
    if (
      !tx ||
      tx.status !== "completed" ||
      tx.purpose === "link" ||
      tx.consumed ||
      !tx.verifiedPatient
    ) {
      return null;
    }
    updateTransaction(sid, { consumed: true });
    const p = tx.verifiedPatient;
    return {
      id: `eudi:${p.username}`,
      name: p.displayName,
      roles: p.roles,
      preferredUsername: p.username,
      assurance: p.assurance,
    } as unknown as User;
  },
});
 
/**
 * Decodes a JWT payload without verifying the signature.
 * Safe here because the token comes directly from the Keycloak token endpoint
 * over TLS during the NextAuth server-side callback — we only read claims,
 * never trust them for authorisation beyond what Keycloak already validated.
 */
function decodeJwtPayload(jwt: string): Record<string, unknown> | null {
  const parts = jwt.split(".");
  if (parts.length < 2) return null;
  try {
    const base64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
    const padded = base64 + "=".repeat((4 - (base64.length % 4)) % 4);
    const json = Buffer.from(padded, "base64").toString("utf8");
    return JSON.parse(json) as Record<string, unknown>;
  } catch {
    return null;
  }
}
 
/**
 * Extracts realm roles from all Keycloak-provided sources.
 *
 * Keycloak may expose `realm_access.roles` in any of: userinfo (profile),
 * id_token, or access_token. Which one depends on the realm's client-scope
 * mapper flags ("Add to userinfo" / "Add to id token" / "Add to access token"),
 * which differ by Keycloak version and can be lost on realm reimport.
 *
 * To be robust across configurations, merge roles from every source that
 * carries them.
 */
function extractRealmRoles(
  profile: Record<string, unknown> | undefined,
  account: { access_token?: string; id_token?: string } | null,
): string[] {
  const collected = new Set<string>();
 
  const addFrom = (src: Record<string, unknown> | null | undefined) => {
    if (!src) return;
    const realmAccess = src.realm_access as { roles?: string[] } | undefined;
    for (const r of realmAccess?.roles ?? []) collected.add(r);
  };
 
  addFrom(profile);
  Eif (account?.access_token) addFrom(decodeJwtPayload(account.access_token));
  if (account?.id_token) addFrom(decodeJwtPayload(account.id_token));
 
  return [...collected];
}
 
export const authOptions: NextAuthOptions = {
  providers: [keycloakProvider, eudiWalletProvider],
  callbacks: {
    async jwt({ token, account, profile, user }) {
      // EUDI Wallet (Credentials) path — `user` is set only on initial sign-in.
      if (user && (user as { roles?: string[] }).roles) {
        const u = user as {
          id?: string;
          roles?: string[];
          preferredUsername?: string;
          assurance?: AssuranceLevel;
        };
        token.roles = u.roles ?? ["PATIENT"];
        token.preferredUsername = u.preferredUsername ?? "";
        token.assurance = u.assurance ?? "low";
        Eif (u.id) token.sub = u.id;
        return token;
      }
      if (account && profile) {
        token.accessToken = account.access_token;
        token.refreshToken = account.refresh_token;
        // Persist the id_token so the client can pass it as `id_token_hint`
        // to Keycloak's end-session endpoint on sign-out. Without it Keycloak
        // shows a logout-confirmation prompt instead of logging out directly.
        token.idToken = account.id_token;
        const keycloakProfile = profile as Record<string, unknown>;
        const roles = extractRealmRoles(keycloakProfile, account);
        // Store the Keycloak login name (preferred_username) for derivation.
        // user.name is the display name (e.g. "Maria Schmidt") which may not
        // match the username-based derivation patterns.
        const preferredUsername =
          (keycloakProfile.preferred_username as string) ?? "";
        token.preferredUsername = preferredUsername;
        // Augment roles with derived participant type so Navigation/UserMenu
        // always have the correct roles regardless of Keycloak configuration.
        const derived = deriveParticipantType(roles, preferredUsername);
        Iif (derived && !roles.includes(derived)) {
          roles.push(derived);
        }
        token.roles = roles;
        token.sub = profile.sub;
        // A password at Keycloak identifies nobody beyond level low (#708).
        token.assurance = "low";
      }
      return token;
    },
    async session({ session, token }) {
      const roles = (token.roles as string[]) ?? [];
      const preferredUsername = (token.preferredUsername as string) ?? "";
      // A patient session carries no name (#475, 2026-10-07): the record's
      // pseudonym stands in for it, in the menu and wherever the session's
      // name is shown. A Keycloak profile or a wallet's PID may hold a real
      // person's name; it stays in the token and never reaches a screen.
      const patientOnly =
        roles.includes("PATIENT") && !roles.includes("EDC_ADMIN");
      const name = patientOnly
        ? patientPseudonym(ownPatientId(preferredUsername) ?? preferredUsername)
        : session.user?.name;
      return {
        ...session,
        accessToken: token.accessToken as string,
        idToken: token.idToken as string,
        roles,
        assurance: token.assurance ?? "low",
        user: {
          ...session.user,
          name,
          id: token.sub as string,
          // Expose preferred_username so tab-session can use it for derivation
          preferredUsername,
        },
      };
    },
  },
  pages: { signIn: "/auth/signin" },
  session: { strategy: "jwt", maxAge: 8 * 60 * 60 },
  debug: process.env.NEXTAUTH_DEBUG === "true",
  events: {},
};
 
export const Roles = {
  EDC_ADMIN: "EDC_ADMIN",
  EDC_USER_PARTICIPANT: "EDC_USER_PARTICIPANT",
  HDAB_AUTHORITY: "HDAB_AUTHORITY",
  // Participant sub-types — set as Keycloak roles alongside EDC_USER_PARTICIPANT.
  // Falls back to username pattern detection for the demo stack.
  DATA_HOLDER: "DATA_HOLDER",
  DATA_USER: "DATA_USER",
  TRUST_CENTER_OPERATOR: "TRUST_CENTER_OPERATOR",
  // EHDS Chapter II / GDPR Art. 15-22 — patient primary-use access
  PATIENT: "PATIENT",
} as const;
export type Role = (typeof Roles)[keyof typeof Roles];
 
export function hasRole(roles: string[] | undefined, role: Role): boolean {
  return roles?.includes(role) ?? false;
}
 
/**
 * Friendly display labels for each role code.
 * Shown in UserMenu and the sign-in persona cards.
 */
export const ROLE_LABELS: Record<string, string> = {
  EDC_ADMIN: "Dataspace Admin",
  EDC_USER_PARTICIPANT: "Participant",
  HDAB_AUTHORITY: "HDAB Authority",
  DATA_HOLDER: "Data Holder",
  DATA_USER: "Researcher",
  TRUST_CENTER_OPERATOR: "Trust Center",
  PATIENT: "Patient / Citizen",
};
 
/**
 * Demo participant cards shown on the sign-in page.
 * Each entry matches a Keycloak user in the local EDCV realm.
 */
export const DEMO_PERSONAS = [
  {
    username: "edcadmin",
    displayName: "edcadmin",
    organisation: "Dataspace Operator",
    roles: ["EDC_ADMIN"],
    personaId: "edc-admin",
    description: "Full operator access: all participants, contracts, admin",
    color: "text-(--role-admin-text)",
    badge:
      "bg-(--role-admin-bg) text-(--role-admin-text) border-(--role-admin-border)",
  },
  {
    username: "clinicuser",
    displayName: "clinicuser",
    organisation: "AlphaKlinik Berlin",
    roles: ["EDC_USER_PARTICIPANT", "DATA_HOLDER"],
    personaId: "hospital",
    description: "Publishes FHIR datasets, manages contracts with researchers",
    color: "text-(--role-holder-text)",
    badge:
      "bg-(--role-holder-bg) text-(--role-holder-text) border-(--role-holder-border)",
  },
  {
    username: "researcher",
    displayName: "researcher",
    organisation: "PharmaCo Research AG",
    roles: ["EDC_USER_PARTICIPANT", "DATA_USER"],
    personaId: "researcher",
    description: "Discovers datasets, negotiates access, runs OMOP analytics",
    color: "text-(--role-user-text)",
    badge:
      "bg-(--role-user-bg) text-(--role-user-text) border-(--role-user-border)",
  },
  {
    username: "regulator",
    displayName: "regulator",
    organisation: "MedReg DE",
    roles: ["HDAB_AUTHORITY"],
    personaId: "hdab",
    description: "Reviews access applications, governs Trust Centers",
    color: "text-(--role-hdab-text)",
    badge:
      "bg-(--role-hdab-bg) text-(--role-hdab-text) border-(--role-hdab-border)",
  },
  {
    // A second access body, so the coordination between access bodies of EHDS
    // Art. 67(3) (one application, forwarded to the others) has two sides to it.
    // Shares personaId "hdab" with MedReg DE: same role, same navigation, and
    // the demo switches between them to show the cross-border permit.
    username: "regulator-es",
    displayName: "regulator-es",
    organisation: "MedReg ES",
    roles: ["HDAB_AUTHORITY"],
    personaId: "hdab",
    description: "Spanish access body, cross-border permits (EHDS Art. 67(3))",
    color: "text-(--role-hdab-text)",
    badge:
      "bg-(--role-hdab-bg) text-(--role-hdab-text) border-(--role-hdab-border)",
  },
  {
    username: "lmcuser",
    displayName: "lmcuser",
    organisation: "Limburg Medical Centre",
    roles: ["EDC_USER_PARTICIPANT", "DATA_HOLDER"],
    personaId: "hospital",
    description: "NL data holder, publishes cross-border datasets",
    color: "text-(--role-holder-text)",
    badge:
      "bg-(--role-holder-bg) text-(--role-holder-text) border-(--role-holder-border)",
  },
  // EHDS Chapter II / GDPR Art. 15-22 — patient primary-use access
  {
    username: "patient1",
    // The static demo shows a patient their record's pseudonym, never a name
    // (#475): the label the fixtures carry, patientPseudonym("P1") under the
    // development key.
    displayName: "Patient 7f915eed",
    organisation: "AlphaKlinik Berlin (patient)",
    roles: ["PATIENT"],
    personaId: "patient",
    description:
      "EHDS Art. 3: access own EHR, donate to research, see insights",
    color: "text-(--role-patient-text)",
    badge:
      "bg-(--role-patient-bg) text-(--role-patient-text) border-(--role-patient-border)",
  },
  {
    username: "patient2",
    displayName: "Patient 2ed9f177",
    organisation: "Limburg Medical Centre (patient)",
    roles: ["PATIENT"],
    personaId: "patient",
    description:
      "Cross-border NL patient, data portability (Art. 7) via MyHealth@EU (Art. 23)",
    color: "text-(--role-patient-text)",
    badge:
      "bg-(--role-patient-bg) text-(--role-patient-text) border-(--role-patient-border)",
  },
] as const;
 
/**
 * Derives the participant sub-type from roles and username.
 * Checks explicit Keycloak roles first, then falls back to username patterns
 * for the local demo stack.
 */
export function deriveParticipantType(
  roles: string[],
  username?: string | null,
): "DATA_HOLDER" | "DATA_USER" | "TRUST_CENTER_OPERATOR" | "PATIENT" | null {
  if (roles.includes("PATIENT")) return "PATIENT";
  Iif (roles.includes("TRUST_CENTER_OPERATOR")) return "TRUST_CENTER_OPERATOR";
  if (roles.includes("DATA_HOLDER")) return "DATA_HOLDER";
  if (roles.includes("DATA_USER")) return "DATA_USER";
  // Demo fallback by username pattern
  const u = (username ?? "").toLowerCase();
  Iif (u.startsWith("patient")) return "PATIENT";
  Iif (
    u.includes("clinic") ||
    u.includes("klinik") ||
    u.includes("lmc") ||
    u.includes("hospital")
  )
    return "DATA_HOLDER";
  Iif (
    u.includes("researcher") ||
    u.includes("pharmaco") ||
    u.includes("research")
  )
    return "DATA_USER";
  Iif (u.includes("rki") || u.includes("rivm") || u.includes("trust"))
    return "TRUST_CENTER_OPERATOR";
  return null;
}
 
/**
 * Derives the graph persona ID for a user.
 * Used to auto-redirect to the correct graph view after login.
 */
/**
 * Where a login lands (issue #271): the persona overview, for every
 * persona. The graph explorer is retired from the navigation.
 */
export function landingFor(_personaId: string): string {
  return "/overview";
}
 
export function derivePersonaId(
  roles: string[],
  username?: string | null,
): string {
  if (roles.includes("EDC_ADMIN")) return "edc-admin";
  if (roles.includes("HDAB_AUTHORITY")) return "hdab";
  const type = deriveParticipantType(roles, username);
  if (type === "PATIENT") return "patient";
  Iif (type === "TRUST_CENTER_OPERATOR") return "trust-center";
  if (type === "DATA_HOLDER") return "hospital";
  if (type === "DATA_USER") return "researcher";
  return "default";
}