All files / server/auth_integrations/auth oauthAuth.ts

0% Statements 0/234
0% Branches 0/180
0% Functions 0/31
0% Lines 0/228

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 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
import * as client from "openid-client";
import { Strategy, type VerifyFunction } from "openid-client/passport";
 
import passport from "passport";
import { Strategy as GitHubStrategy, type Profile as GitHubProfile } from "passport-github2";
import session from "express-session";
import cookieParser from "cookie-parser";
import type { Express, RequestHandler } from "express";
import memoize from "memoizee";
import connectPg from "connect-pg-simple";
import { authStorage } from "./storage";
import rateLimit from "express-rate-limit";
 
const sessionTtlMs = 7 * 24 * 60 * 60 * 1000; // 1 week
const sessionTtlSeconds = Math.floor(sessionTtlMs / 1000);
 
type OidcProvider = "google" | "apple" | "custom";
type OAuthProvider = OidcProvider | "github";
 
const legacyIssuerUrl = process.env.ISSUER_URL;
const legacyClientId = process.env.CLIENT_ID;
const legacyClientSecret = process.env.CLIENT_SECRET;
 
function resolveLegacyProvider(): OidcProvider | null {
  if (!legacyClientId) {
    return null;
  }
 
  if (legacyIssuerUrl === "https://accounts.google.com") {
    return "google";
  }
 
  if (legacyIssuerUrl === "https://appleid.apple.com") {
    return "apple";
  }
 
  if (legacyIssuerUrl) {
    return "custom";
  }
 
  return null;
}
 
function isOidcProvider(provider: OAuthProvider): provider is OidcProvider {
  return provider !== "github";
}
 
type OidcProviderConfig = {
  issuerUrl?: string;
  clientId?: string;
  clientSecret?: string;
  label: string;
  requiresSecret: boolean;
  scopes?: string;
  accessTypeOffline?: boolean;
};
 
function getOidcProviderConfig(provider: OidcProvider): OidcProviderConfig {
  const legacyProvider = resolveLegacyProvider();
 
  switch (provider) {
    case "google":
      return {
        issuerUrl: "https://accounts.google.com",
        clientId:
          process.env.GOOGLE_CLIENT_ID ||
          (legacyProvider === "google" ? legacyClientId : undefined),
        clientSecret:
          process.env.GOOGLE_CLIENT_SECRET ||
          (legacyProvider === "google" ? legacyClientSecret : undefined),
        label: "Google",
        requiresSecret: true,
        scopes: "openid email profile",
        accessTypeOffline: true,
      };
    case "apple":
      return {
        issuerUrl: "https://appleid.apple.com",
        clientId:
          process.env.APPLE_CLIENT_ID ||
          (legacyProvider === "apple" ? legacyClientId : undefined),
        clientSecret:
          process.env.APPLE_CLIENT_SECRET ||
          (legacyProvider === "apple" ? legacyClientSecret : undefined),
        label: "Apple",
        requiresSecret: true,
        scopes: "openid email name",
      };
    case "custom":
      return {
        issuerUrl: legacyProvider === "custom" ? legacyIssuerUrl : undefined,
        clientId: legacyProvider === "custom" ? legacyClientId : undefined,
        clientSecret: legacyProvider === "custom" ? legacyClientSecret : undefined,
        label: "Custom",
        requiresSecret: true,
        scopes: "openid email profile offline_access",
      };
  }
}
 
function isOidcProviderConfigured(provider: OidcProvider): boolean {
  const config = getOidcProviderConfig(provider);
  if (!config.clientId || !config.issuerUrl) {
    return false;
  }
 
  if (config.requiresSecret && !config.clientSecret) {
    return false;
  }
 
  return true;
}
 
export function getConfiguredProviders(): Set<OAuthProvider> {
  const providers = new Set<OAuthProvider>();
 
  (['google', 'apple', 'custom'] as OidcProvider[]).forEach((provider) => {
    if (isOidcProviderConfigured(provider)) {
      providers.add(provider);
    }
  });
 
  if (process.env.GITHUB_CLIENT_ID && process.env.GITHUB_CLIENT_SECRET) {
    providers.add("github");
  }
 
  return providers;
}
 
function resolveProvider(input?: unknown): OAuthProvider | null {
  const raw = Array.isArray(input)
    ? input[0]
    : typeof input === "string"
      ? input
      : null;
  const normalized = raw?.toLowerCase();
 
  if (normalized === "google" || normalized === "apple" || normalized === "custom" || normalized === "github") {
    return normalized;
  }
 
  const configured = getConfiguredProviders();
  const preferred = process.env.DEFAULT_AUTH_PROVIDER?.toLowerCase();
  if (preferred && configured.has(preferred as OAuthProvider)) {
    return preferred as OAuthProvider;
  }
 
  if (configured.has("google")) return "google";
  if (configured.has("apple")) return "apple";
  if (configured.has("github")) return "github";
  if (configured.has("custom")) return "custom";
 
  return null;
}
 
const getOidcConfig = memoize(
  async (provider: OidcProvider) => {
    const providerConfig = getOidcProviderConfig(provider);
 
    if (!providerConfig.clientId) {
      return null;
    }
 
    if (!providerConfig.issuerUrl) {
      console.error(`❌ ISSUER_URL not set for ${providerConfig.label} OAuth.`);
      return null;
    }
 
    if (providerConfig.requiresSecret && !providerConfig.clientSecret) {
      console.error(`❌ CLIENT_SECRET not set for ${providerConfig.label} OAuth.`);
      return null;
    }
 
    try {
      console.log(`🔐 Using ${providerConfig.label} OAuth`);
      return await client.discovery(
        new URL(providerConfig.issuerUrl),
        providerConfig.clientId,
        providerConfig.clientSecret
      );
    } catch (error) {
      console.error(`❌ Failed to discover OIDC configuration from ${providerConfig.issuerUrl}:`, error);
      return null;
    }
  },
  {
    maxAge: 3600 * 1000,
    normalizer: (args) => args[0],
  }
);
 
export function getSession(): RequestHandler {
  const pgStore = connectPg(session);
  const sessionStore = new pgStore({
    conString: process.env.DATABASE_URL,
    createTableIfMissing: true,
    ttl: sessionTtlMs,
    tableName: "sessions",
  });
  // Determine if we should use secure cookies
  // Only use secure cookies in production AND when not on localhost
  const isProduction = process.env.NODE_ENV === "production";
  const isLocalhost = process.env.HOST === "localhost" || process.env.HOST === "127.0.0.1";
  const useSecureCookies = isProduction && !isLocalhost;
 
  const sessionMiddleware = session({
    secret: process.env.SESSION_SECRET!,
    store: sessionStore,
    resave: false,
    saveUninitialized: false,
    cookie: {
      httpOnly: true,
      secure: useSecureCookies,
      sameSite: "lax",
      maxAge: sessionTtlMs,
    },
  });
 
  return sessionMiddleware;
}
 
type UserClaims = {
  sub?: string;
  email?: string;
  name?: string;
  given_name?: string;
  family_name?: string;
  first_name?: string;
  last_name?: string;
  picture?: string;
  profile_image_url?: string;
  exp?: number;
  [key: string]: unknown;
};
 
function updateUserSession(
  user: any,
  claims: UserClaims,
  accessToken?: string,
  refreshToken?: string,
  provider?: OAuthProvider
) {
  user.claims = claims;
  user.access_token = accessToken;
  user.refresh_token = refreshToken;
  user.expires_at = claims?.exp ?? Math.floor(Date.now() / 1000) + sessionTtlSeconds;
  user.auth_provider = provider;
}
 
function splitName(name?: string): { firstName?: string; lastName?: string } {
  if (!name) {
    return {};
  }
 
  const parts = name.trim().split(/\s+/);
  if (parts.length === 1) {
    return { firstName: parts[0] };
  }
 
  return {
    firstName: parts[0],
    lastName: parts.slice(1).join(" "),
  };
}
 
function extractUserFromClaims(claims: UserClaims) {
  const nameParts = splitName(claims.name);
 
  return {
    id: claims.sub!,
    email: claims.email,
    firstName: claims.first_name || claims.given_name || nameParts.firstName,
    lastName: claims.last_name || claims.family_name || nameParts.lastName,
    profileImageUrl: claims.profile_image_url || claims.picture,
  };
}
 
async function upsertUser(claims: UserClaims) {
  if (!claims.sub) {
    return;
  }
 
  await authStorage.upsertUser(extractUserFromClaims(claims));
}
 
function buildGithubClaims(profile: GitHubProfile): UserClaims {
  const primaryEmail = profile.emails?.[0]?.value;
  const displayName = profile.displayName || profile.username || "";
  const nameParts = splitName(displayName);
 
  return {
    sub: `github:${profile.id}`,
    email: primaryEmail,
    name: displayName,
    given_name: nameParts.firstName,
    family_name: nameParts.lastName,
    picture: profile.photos?.[0]?.value,
  };
}
 
export async function setupAuth(app: Express) {
  // trust proxy is configured in index.ts — no need to set it again here
  app.use(cookieParser());
  app.use(getSession());
 
  // Note: CSRF protection via csrf-csrf was removed because it requires
  // client-side integration to fetch and send CSRF tokens. The session
  // cookies use SameSite=lax which provides protection against most CSRF
  // attacks. Full CSRF protection can be added later if needed.
 
  app.use(passport.initialize());
  app.use(passport.session());
 
  const configuredProviders = getConfiguredProviders();
 
  // Skip OAuth setup if credentials are not configured
  if (configuredProviders.size === 0) {
    console.log("â„šī¸  Running in development mode without OAuth authentication");
    return;
  }
 
  console.log("✅ OAuth authentication enabled");
 
  const createVerifyOidc = (provider: OidcProvider): VerifyFunction =>
    async (
      tokens: client.TokenEndpointResponse & client.TokenEndpointResponseHelpers,
      verified: passport.AuthenticateCallback
    ) => {
      const user = {};
      const claims = tokens.claims() as UserClaims;
      updateUserSession(user, claims, tokens.access_token, tokens.refresh_token, provider);
      await upsertUser(claims);
      verified(null, user);
    };
 
  const verifyGithub = async (
    accessToken: string,
    _refreshToken: string,
    profile: GitHubProfile,
    done: passport.AuthenticateCallback
  ) => {
    const user = {};
    const claims = buildGithubClaims(profile);
    updateUserSession(user, claims, accessToken, undefined, "github");
    await upsertUser(claims);
    done(null, user);
  };
 
  // Keep track of registered strategies
  const registeredStrategies = new Set<string>();
 
  const getCallbackURL = (req: any, provider: OAuthProvider) => {
    // Use HOST env var for Docker/reverse-proxy deployments where req.hostname
    // returns the container-internal hostname instead of the public domain.
    // For local Docker (HOST=localhost, port mapped e.g. 5002:5000), we need
    // req.get("host") which includes the correct external port.
    const envHost = process.env.HOST;
    const reqHost = req.get("host") || req.hostname;
 
    let host: string;
    if (envHost && envHost !== "localhost" && envHost !== "127.0.0.1") {
      // Production: use the configured domain (no port needed, reverse proxy handles it)
      host = envHost;
    } else {
      // Local dev or local Docker: use req host which includes the correct port
      host = reqHost;
    }
 
    const isLocalhost = host === "localhost" || host.startsWith("localhost:") || host.startsWith("127.0.0.1");
    const protocol = isLocalhost ? "http" : "https";
    const baseUrl = `${protocol}://${host}`;
 
    if (provider === "github") {
      return `${baseUrl}/api/callback/github`;
    }
 
    return `${baseUrl}/api/callback?provider=${provider}`;
  };
 
  const ensureOidcStrategy = async (req: any, provider: OidcProvider) => {
    const config = await getOidcConfig(provider);
    if (!config) {
      return null;
    }
 
    const callbackURL = getCallbackURL(req, provider);
    const strategyName = `oidc:${provider}:${callbackURL}`;
    const providerConfig = getOidcProviderConfig(provider);
 
    if (!registeredStrategies.has(strategyName)) {
      console.log(`🔐 Registering OIDC strategy for ${provider}`);
      console.log(`   Callback URL: ${callbackURL}`);
      console.log(`   Client ID: ${providerConfig.clientId?.substring(0, 20)}...`);
 
      const strategy = new Strategy(
        {
          name: strategyName,
          config,
          callbackURL,
        },
        createVerifyOidc(provider)
      );
      passport.use(strategy);
      registeredStrategies.add(strategyName);
      console.log(`✓ Strategy registered: ${strategyName}`);
    }
 
    return strategyName;
  };
 
  const ensureGithubStrategy = (req: any) => {
    const callbackURL = getCallbackURL(req, "github");
    const strategyName = `github:${callbackURL}`;
    if (!registeredStrategies.has(strategyName)) {
      const strategy = new GitHubStrategy(
        {
          clientID: process.env.GITHUB_CLIENT_ID!,
          clientSecret: process.env.GITHUB_CLIENT_SECRET!,
          callbackURL,
        },
        verifyGithub
      );
      passport.use(strategyName, strategy);
      registeredStrategies.add(strategyName);
      console.log(`✓ Strategy registered: ${strategyName}`);
    }
 
    return strategyName;
  };
 
  passport.serializeUser((user: Express.User, cb) => cb(null, user));
  passport.deserializeUser((user: Express.User, cb) => cb(null, user));
 
  // Rate limiter for authentication routes to prevent brute force attacks
  // Only enabled in production to allow easier testing in development
  const authLimiter = process.env.NODE_ENV === "production"
    ? rateLimit({
        windowMs: 15 * 60 * 1000, // 15 minutes
        max: 100, // 100 attempts per 15 minutes
        standardHeaders: true,
        legacyHeaders: false,
        message: "Too many authentication attempts, please try again later.",
      })
    : ((_req: any, _res: any, next: any) => next()); // No-op in development
 
  app.get("/api/login", authLimiter, async (req, res, next) => {
    const provider = resolveProvider(req.query.provider);
    if (!provider) {
      return res.status(400).json({ message: "No OAuth providers configured." });
    }
 
    if (provider === "github") {
      const strategyName = ensureGithubStrategy(req);
      return passport.authenticate(strategyName, {
        scope: ["read:user", "user:email"],
      })(req, res, next);
    }
 
    const strategyName = await ensureOidcStrategy(req, provider);
    if (!strategyName) {
      return res.status(400).json({ message: `${provider} OAuth is not configured.` });
    }
 
    const providerConfig = getOidcProviderConfig(provider);
    const authOptions: any = {
      prompt: "login consent",
      scope: (providerConfig.scopes || "openid email profile").split(" "),
    };
    if (providerConfig.accessTypeOffline) {
      authOptions.access_type = "offline";
    }
 
    return passport.authenticate(strategyName, authOptions)(req, res, next);
  });
 
  app.get("/api/callback/github", authLimiter, (req, res, next) => {
    const strategyName = ensureGithubStrategy(req);
    return passport.authenticate(strategyName, {
      successReturnToOrRedirect: "/",
      failureRedirect: "/api/login?provider=github",
    })(req, res, next);
  });
 
  app.get("/api/callback", authLimiter, async (req, res, next) => {
    const provider = resolveProvider(req.query.provider);
    if (!provider) {
      return res.redirect("/api/login");
    }
 
    if (provider === "github") {
      return res.redirect("/api/callback/github");
    }
 
    const strategyName = await ensureOidcStrategy(req, provider);
    if (!strategyName) {
      return res.redirect("/api/login");
    }
 
    return passport.authenticate(strategyName, {
      successReturnToOrRedirect: "/",
      failureRedirect: `/api/login?provider=${provider}`,
    })(req, res, next);
  });
 
  app.get("/api/logout", authLimiter, async (req, res) => {
    const provider = resolveProvider(req.query.provider);
    req.logout(async () => {
      if (!provider || provider === "github") {
        return res.redirect("/");
      }
 
      const config = await getOidcConfig(provider);
      if (!config) {
        return res.redirect("/");
      }
 
      const providerConfig = getOidcProviderConfig(provider);
      const clientId = providerConfig.clientId;
      if (!clientId) {
        return res.redirect("/");
      }
 
      try {
        const envHost = process.env.HOST;
        const reqHost = req.get("host") || req.hostname;
        const host = envHost && envHost !== "localhost" && envHost !== "127.0.0.1" ? envHost : reqHost;
        const isLocal = host === "localhost" || host.startsWith("localhost:") || host.startsWith("127.0.0.1");
        const proto = isLocal ? "http" : "https";
 
        return res.redirect(
          client.buildEndSessionUrl(config, {
            client_id: clientId,
            post_logout_redirect_uri: `${proto}://${host}`,
          }).href
        );
      } catch (error) {
        return res.redirect("/");
      }
    });
  });
}
 
export const isAuthenticated: RequestHandler = async (req, res, next) => {
  // If OAuth is not configured, provide a mock user for development mode
  if (getConfiguredProviders().size === 0) {
    // Create a mock user object for development
    req.user = {
      claims: {
        sub: process.env.DEV_USER_ID || "dev-user",
        email: process.env.DEV_USER_EMAIL || "dev@localhost",
        name: "Development User",
        given_name: "Development",
        family_name: "User",
      },
      access_token: "dev-token",
      expires_at: Math.floor(Date.now() / 1000) + sessionTtlSeconds,
      auth_provider: "development",
    } as any;
    return next();
  }
 
  const user = req.user as any;
 
  if (!req.isAuthenticated() || !user.expires_at) {
    return res.status(401).json({ message: "Unauthorized" });
  }
 
  const now = Math.floor(Date.now() / 1000);
  if (now <= user.expires_at) {
    return next();
  }
 
  const provider = user.auth_provider as OAuthProvider | undefined;
  if (!provider || !isOidcProvider(provider)) {
    res.status(401).json({ message: "Unauthorized" });
    return;
  }
 
  const refreshToken = user.refresh_token;
  if (!refreshToken) {
    res.status(401).json({ message: "Unauthorized" });
    return;
  }
 
  try {
    const config = await getOidcConfig(provider);
    if (!config) {
      return next();
    }
    const tokenResponse = await client.refreshTokenGrant(config, refreshToken);
    updateUserSession(user, tokenResponse.claims() as UserClaims, tokenResponse.access_token, tokenResponse.refresh_token, provider);
    return next();
  } catch (error) {
    res.status(401).json({ message: "Unauthorized" });
    return;
  }
};