All files / src/middleware auth.js

96.03% Statements 194/202
93.91% Branches 139/148
100% Functions 24/24
97.29% Lines 180/185

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 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738              307x 307x 307x 307x       307x 307x     307x     307x             307x 307x                   307x   307x     1231x 2x 2x                                                                         475x 400x 5x 5x 4x 4x 2x 2x 2x                             457x 457x 80x         377x 377x   364x 364x 364x 363x 363x 363x 363x         364x     364x 364x                   467x   448x 448x 76x       372x 372x   356x 356x 356x 356x 356x 356x 356x 356x   356x     356x 356x                                           473x 473x   16x       16x 16x                       7x       7x       467x 467x 15x     452x     452x 452x 2x 2x                 450x 450x   438x 438x     438x     437x   437x 23x                         414x 301x                 298x 298x 38x 36x   38x         38x               260x 2x       373x 10x 10x     363x 363x   4x                               307x                                                                       394x 374x 261x         32x 32x 32x 127x                                                   484x 484x 484x 484x 2286x                               10x         10x               465x                                                                                 414x             411x                     25x 25x 2x     23x             23x 23x                         23x 23x   19x 19x     19x     19x               19x         19x 1x                   18x       18x 11x     8x 8x 2x 2x   2x         2x               6x         13x         13x 13x   3x                                                       564x 551x   13x 13x 13x 3x   10x 10x 9x 9x 9x 9x   1x 1x                                           621x 64x 64x         557x 557x 3x 3x   554x                 1860x             332x 332x   1528x     1528x                     331x 1x   330x           422x 1x 1x   421x 421x           503x 503x     307x                                          
/**
 * Firebase Auth middleware for Express.
 *
 * Verifies Firebase ID tokens and resolves Firebase UID → uniqueId
 * via the identity system. Sets req.auth = { uid, uniqueId, token }.
 */
 
const { auth, db } = require('../utils/firebase');
const { checkUserBans, clearBanCache } = require('../utils/bans');
const { syncBannedClaim } = require('../utils/banned-claim');
const log = require('../utils/log');
 
// ─── In-memory caches ────────────────────────────────────────────
 
const CACHE_TTL = 5 * 60 * 1000; // 5 minutes
const MAX_CACHE_SIZE = 500;
 
// uid → { uniqueId, expiresAt }
const uniqueIdCache = new Map();
 
// uniqueId → { isSuspended, expiresAt }
const suspensionCache = new Map();
 
// In-flight Promise dedup (Phase 2H finding #5). Without these, N concurrent
// first-touch requests for the same key issue N parallel Firestore reads —
// Spark-tier free quota is 50K reads/day; cold-start fires 5-10 parallel
// calls per user, so 1000 users × 10 = 10K reads in the warmup minute
// without dedup (vs ~1K with).
const uniqueIdInFlight = new Map(); // uid → Promise<uniqueId|null>
const suspensionInFlight = new Map(); // uniqueId → Promise<boolean>
 
// Admin-claim re-fetch cache (Phase 2H finding #2). The decoded ID token's
// `admin` claim is whatever Firebase wrote when the token was ISSUED —
// admin demotion via `setCustomUserClaims({admin:false})` doesn't
// invalidate an in-flight token, so a demoted admin keeps full powers for
// up to ~1h until natural token expiry. `requireAdmin` re-checks the live
// customClaims via `auth.getUser(uid)` with a short TTL, so the worst-case
// privilege-leak window is `ADMIN_CLAIM_TTL` (60s), not the full token
// lifetime.
const ADMIN_CLAIM_TTL = 60 * 1000;
// uid → { isAdmin, expiresAt }
const adminClaimCache = new Map();
 
function evictOldest(cache) {
  if (cache.size > MAX_CACHE_SIZE) {
    const firstKey = cache.keys().next().value;
    cache.delete(firstKey);
  }
}
 
// ─── Synthetic-token bypass (NODE_ENV=local ONLY) ──────────────────
//
// The manual-qa-runner synthesises sessions for personas it can't sign
// in via the Firebase Auth emulator (ephemeral personas: P-01 Adam,
// P-03 Mia — and also as a shortcut for provisioned personas to avoid
// the emulator round-trip on every scenario). The synthetic idToken
// has shape `synthetic:<name>:<uniqueId>` and is sent as the Bearer
// token on subsequent API calls.
//
// In production this token shape would fail `auth.verifyIdToken` and
// return 401 — which is the correct behaviour because no real user
// could forge such a token.
//
// In NODE_ENV=local, the entire stack runs against the Firebase
// emulator (which accepts unsigned tokens anyway) and the only callers
// are the test harness + developers running the local seed. Accepting
// synthetic tokens HERE lets the manual-qa-runner exercise cohort-gate
// and other auth-gated routes end-to-end without requiring every
// persona to have a real Firebase Auth user record.
//
// SECURITY:
//   - HARD GATE: NODE_ENV must literally equal 'local'. Any other
//     value (production, staging, undefined, '') refuses synthetic
//     tokens and falls through to real verification.
//   - The function returns null whenever the gate fails or the token
//     can't be parsed, so the caller falls through to the standard
//     verifyIdToken path.
//   - No suspension check is bypassed: synthetic tokens skip the
//     suspension lookup because in local-emulator state the
//     suspensions collection is the seed, and the test scenarios
//     either don't seed suspensions or seed them on purpose (in which
//     case the cohort gate, not auth, is what the scenario asserts).
function decodeSyntheticToken(idToken) {
  if (process.env.NODE_ENV !== 'local') return null;
  if (typeof idToken !== 'string' || !idToken.startsWith('synthetic:')) return null;
  const parts = idToken.split(':');
  if (parts.length !== 3) return null;
  const [, name, uniqueIdStr] = parts;
  if (!name || !/^\d+$/.test(uniqueIdStr)) return null;
  const uniqueId = parseInt(uniqueIdStr, 10);
  Iif (!Number.isFinite(uniqueId) || uniqueId <= 0) return null;
  return {
    uid: `synthetic-${name}-${uniqueId}`,
    uniqueId,
    token: { uid: `synthetic-${name}-${uniqueId}`, uniqueId, synthetic: true, name },
  };
}
 
// ─── UniqueId resolution ─────────────────────────────────────────
 
/**
 * Resolves a Firebase UID to the user's stable uniqueId by querying
 * the users collection for a doc where firebaseUid matches.
 * Returns null if no user doc is found (new user or cross-project).
 */
async function resolveUniqueId(uid) {
  const cached = uniqueIdCache.get(uid);
  if (cached && Date.now() < cached.expiresAt) {
    return cached.uniqueId;
  }
 
  // Inflight dedup: if another caller is already resolving this uid, await
  // their Promise instead of issuing a parallel Firestore query.
  const existing = uniqueIdInFlight.get(uid);
  if (existing) return existing;
 
  const promise = (async () => {
    try {
      const snap = await db.collection('users').where('firebaseUid', '==', uid).limit(1).get();
      const uniqueId = snap.empty ? null : (snap.docs[0].data().uniqueId ?? null);
      uniqueIdCache.set(uid, { uniqueId, expiresAt: Date.now() + CACHE_TTL });
      evictOldest(uniqueIdCache);
      return uniqueId;
    } finally {
      // Always release the inflight slot — including on Firestore errors —
      // so a transient outage doesn't pin a stuck Promise that subsequent
      // callers keep awaiting forever.
      uniqueIdInFlight.delete(uid);
    }
  })();
  uniqueIdInFlight.set(uid, promise);
  return promise;
}
 
// ─── Suspension check ────────────────────────────────────────────
 
/**
 * Checks if a user is suspended by reading their user doc.
 * Uses uniqueId-based doc path: users/{uniqueId}.
 */
async function checkSuspension(uniqueId) {
  if (uniqueId === null || uniqueId === undefined) return false;
 
  const cached = suspensionCache.get(uniqueId);
  if (cached && Date.now() < cached.expiresAt) {
    return cached.isSuspended;
  }
 
  // Inflight dedup — see resolveUniqueId for rationale.
  const existing = suspensionInFlight.get(uniqueId);
  if (existing) return existing;
 
  const promise = (async () => {
    try {
      const snap = await db.doc(`users/${uniqueId}`).get();
      const user = snap.exists ? snap.data() : null;
      const isSuspended = !!(user?.isSuspended || user?.is_suspended);
      suspensionCache.set(uniqueId, { isSuspended, expiresAt: Date.now() + CACHE_TTL });
      evictOldest(suspensionCache);
      return isSuspended;
    } finally {
      suspensionInFlight.delete(uniqueId);
    }
  })();
  suspensionInFlight.set(uniqueId, promise);
  return promise;
}
 
// ─── Middleware ───────────────────────────────────────────────────
 
/**
 * Express middleware: verifies Firebase ID token, resolves uniqueId,
 * checks suspension. Sets req.auth = { uid, uniqueId, token }.
 */
/**
 * Verify the caller's credential, or answer 401 `token_rejected` and return
 * null. Both middlewares share this so they cannot drift apart -- they
 * previously held byte-identical blocks, which is exactly how one of them gets
 * a fix the other does not (SHY-0308).
 *
 * Returns the decoded token, or null when it has ALREADY answered the request.
 * Callers must `return` on null; they must not fall through.
 *
 * @param {boolean} checkRevoked - strict routes pass true, so a revoked session
 *   is refused here as the rejected credential it is.
 */
async function verifyCredentialOrReject(res, idToken, checkRevoked) {
  try {
    return await auth.verifyIdToken(idToken, checkRevoked);
  } catch (err) {
    log.error('auth', 'Authentication failed: token rejected', {
      error: err.message,
      firebaseCode: err.code,
    });
    res.status(401).json({ error: 'Authentication failed', code: 'token_rejected' });
    return null;
  }
}
 
/**
 * Refuse a request whose credential was ACCEPTED but whose standing could not
 * be established -- identity resolution, the suspension check, or the ban
 * lookup failing. Refusing is correct (a control that fails open is not a
 * control); the caller's credential was simply never the problem, and saying
 * so is the difference this story exists for.
 */
function rejectStandingUnavailable(req, res, err) {
  log.error('auth', 'Authentication failed: standing lookup failed', {
    error: err.message,
    path: req.path,
  });
  return res.status(401).json({ error: 'Authentication failed', code: 'standing_unavailable' });
}
 
async function authMiddleware(req, res, next) {
  const authHeader = req.headers.authorization;
  if (!authHeader?.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'Missing or invalid Authorization header' });
  }
 
  const idToken = authHeader.slice(7);
 
  // Synthetic-token bypass (NODE_ENV=local only — see helper for rationale).
  const synth = decodeSyntheticToken(idToken);
  if (synth) {
    req.auth = synth;
    return next();
  }
 
  // SHY-0308: the credential check is deliberately OUTSIDE the block below.
  // A rejected token and a standing lookup that could not complete are
  // different failures that happened to share one catch, one status and one
  // string -- so a refusal could not be attributed to either. It cost a dig
  // through a Playwright trace to learn that a suite failure reading
  // "Expected 403, Received 401" had never reached the ban gate at all.
  const decoded = await verifyCredentialOrReject(res, idToken, false);
  if (!decoded) return undefined; // verifyCredentialOrReject already answered.
 
  try {
    const uid = decoded.uid;
 
    // Resolve Firebase UID → stable uniqueId
    const uniqueId = await resolveUniqueId(uid);
 
    // Check suspension (only if user exists)
    const isSuspended = await checkSuspension(uniqueId);
 
    if (isSuspended && !isSuspensionExemptPath(req)) {
      return res.status(403).json({ error: 'Account suspended' });
    }
 
    // Per-request ban gate (SHY-0149): device + network bans, matched on
    // the REAL edge IP. Runs on every auth-gated request so the web,
    // direct-API, modified-client, and mid-session bypasses are all closed.
    //
    // The exemption is tested BEFORE the lookup, never after. An exempt path
    // is reachable by a banned user by definition, so its verdict is already
    // known — and a lookup FAILURE (fail-closed, rejects into the catch → 401)
    // must not confiscate the appeal / GDPR-export / ban-screen rights a ban
    // itself spares. Ordering this the other way locked those paths out of a
    // permanently-truncating account for good (reviewer C-NEW-1).
    if (!isBanExemptPath(req)) {
      const ban = await checkUserBans(uniqueId, req.ip);
      // SHY-0150 lazy claim sync: the fresh verdict and the decoded token
      // meet exactly here — when they disagree, reconcile the `banned`
      // custom claim so the Firestore rules gate tracks standings no route
      // ever mutated (lazy expiry, binding flips, UNLINKED network bans
      // caught by the live IP). Mint rides the verdict; clear goes through
      // the full recompute inside syncBannedClaim (never the IP-scoped
      // verdict). syncBannedClaim never throws — a sync failure must not
      // turn this request into the outer catch's 401.
      const tokenBanned = decoded.banned === true;
      if (ban.isBanned) {
        if (!tokenBanned) {
          await syncBannedClaim(uniqueId, { uid, verdictBanned: true, dedupe: true });
        }
        log.warn('auth', 'Request denied: banned', {
          path: req.path,
          uniqueId,
          banType: ban.banType,
        });
        return res.status(403).json({
          error: 'Account banned',
          code: 'banned',
          banType: ban.banType,
          reason: ban.reason,
          expiresAt: ban.expiresAt,
        });
      }
      if (tokenBanned) {
        await syncBannedClaim(uniqueId, { uid, dedupe: true });
      }
    }
 
    if (!hasResolvedIdentity(uniqueId) && !allowsMissingIdentity(req)) {
      req.__authUid = uid;
      return rejectMissingIdentity(req, res);
    }
 
    req.auth = { uid, uniqueId, token: decoded };
    next();
  } catch (err) {
    return rejectStandingUnavailable(req, res, err);
  }
}
 
/**
 * Routes that legitimately run before a `uniqueId` exists (SHY-0426).
 *
 * Everything else is refused when the account cannot be identified. This is
 * the whole allowlist, kept short deliberately so it can be read and argued
 * with — the alternative was a guard in each of 30 route files, which is 30
 * chances to miss one and 30 more for every route added afterwards.
 *
 * Matched on METHOD and EXACT path: `GET /users` is a listing and has no
 * business running without an identity, and `/users/50000010/appeal` must not
 * inherit `/users`'s exemption by prefix.
 */
const PRE_IDENTITY_ROUTES = [
  // Creates the account. There is no identity yet, by definition.
  //
  // NOT `standingExempt`: creating an account is an ACTION, not a verdict.
  // With no identity to resolve, the standing gates match this caller by
  // device and IP — which is exactly how a banned person is stopped from
  // opening a fresh account on the banned handset. Exempting it would
  // legalise ban evasion at the one route that performs it (SHY-0461).
  { method: 'POST', path: '/users', standingExempt: false },
  // May be what creates the document for a Firebase account that authenticated
  // first. It is also the FIRST call the app makes, and it already answers
  // `{ found, suspended }` without mutating — see `POST /users/sign-in`.
  { method: 'POST', path: '/users/sign-in', standingExempt: true },
  // Device binding, which runs in the SIGN-IN flow before any account exists —
  // it is how the app learns whether this handset is already locked to
  // somebody.
  { method: 'POST', path: '/devices/lock-check', standingExempt: true },
  // How the app LEARNS it is banned. Gating it would replace the ban screen
  // with a generic error while enforcing nothing; it is a verdict channel, not
  // an abuse-capable action.
  { method: 'POST', path: '/device-info', standingExempt: true },
  { method: 'GET', path: '/device-info', standingExempt: true },
];
 
/**
 * Is this a real account identifier, or the absence of one?
 *
 * PRESENCE, deliberately — not `Number.isInteger`. The defect is that `null`
 * collapses every unidentified caller into one "account" because
 * `null === null`. That is what this refuses. Insisting on an integer would
 * ALSO change an unrelated contract: the codebase is inconsistent about
 * whether a uniqueId is a number or a string (the seeded personas use numbers,
 * several suites use strings), so a type gate here would lock out real callers
 * for a reason nobody asked about.
 */
function hasResolvedIdentity(uniqueId) {
  if (uniqueId === null || uniqueId === undefined) return false;
  if (typeof uniqueId === 'string') return uniqueId.trim() !== '';
  return typeof uniqueId === 'number' ? Number.isFinite(uniqueId) : Boolean(uniqueId);
}
 
/** Fails CLOSED: an unrecognised request shape is not a way through. */
function allowsMissingIdentity(req) {
  const method = req?.method;
  const path = req?.path;
  if (typeof method !== 'string' || typeof path !== 'string') return false;
  return PRE_IDENTITY_ROUTES.some((r) => r.method === method && r.path === path);
}
 
/**
 * A route whose job is to TELL the caller what its standing is must not be
 * gated on that standing (SHY-0461).
 *
 * The gate was circular. `POST /users/sign-in` is the FIRST call the app
 * makes, and both standing gates refused it — so a suspended person could
 * not resolve their identity, therefore never reached the user document they
 * are in fact allowed to read, never reached the ban check, and was shown
 * "cannot connect" with no reason and no appeal. A banned person hit the same
 * wall, which put the ban screen out of reach on a cold sign-in too. Verified
 * on the OnePlus; J11 pins it.
 *
 * Read off `PRE_IDENTITY_ROUTES` rather than a second hand-written list, so
 * the two cannot drift and adding a pre-identity route forces one explicit
 * decision — `standingExempt` — instead of silently inheriting either answer.
 *
 * Being pre-identity is NOT sufficient on its own: `POST /users` is in that
 * table and is deliberately `standingExempt: false`, because it acts rather
 * than reports and exempting it would legalise ban evasion.
 *
 * Matched on METHOD and EXACT path, exactly as `allowsMissingIdentity` is.
 */
function isStandingVerdictChannel(req) {
  const method = req?.method;
  const path = req?.path;
  Iif (typeof method !== 'string' || typeof path !== 'string') return false;
  return PRE_IDENTITY_ROUTES.some(
    (r) => r.standingExempt && r.method === method && r.path === path,
  );
}
 
/**
 * Refuse a caller whose account could not be identified.
 *
 * A distinct code, not a generic 401: the credential was fine, and the client
 * needs to tell "sign in again" from "your account is in a state we cannot
 * resolve" — the second is a bug report, not a retry.
 *
 * Shared by both middlewares rather than written twice; byte-identical blocks
 * in this file are exactly how one of them gets a fix the other does not
 * (SHY-0308).
 */
function rejectMissingIdentity(req, res) {
  log.warn('auth', 'Refused a caller with no resolved identity', {
    uid: req.auth?.uid || req.__authUid,
    method: req.method,
    path: req.path,
  });
  res.status(403).json({ error: 'Your account could not be identified', code: 'no_identity' });
}
 
/**
 * Paths a SUSPENDED user may still reach: the appeal flow plus the
 * account-deletion / GDPR-export rights that suspension must not remove.
 */
function isSuspensionExemptPath(req) {
  return (
    // The standing-verdict channels. Without these a suspended person cannot
    // discover that they are suspended, which is the whole of SHY-0461.
    isStandingVerdictChannel(req) ||
    /^\/users\/[^/]+\/appeal$/.test(req.path) ||
    /^\/users\/[^/]+\/lift-suspension$/.test(req.path) ||
    /^\/users\/[^/]+\/delete$/.test(req.path) ||
    /^\/users\/[^/]+\/cancel-delete$/.test(req.path) ||
    /^\/users\/[^/]+\/deletion-status$/.test(req.path) ||
    /^\/users\/[^/]+\/data-export/.test(req.path) ||
    (req.method === 'POST' && req.path === '/appeals') ||
    // Portal self-service. portal.js mounts `authMiddlewareStrict` per-route,
    // and that middleware carves these two out — but EVERY /api request runs
    // through THIS middleware first (index.js mounts it globally), so without
    // the same carve-out here the strict exemption was unreachable: a
    // suspended user could not view their own portal profile or even sign
    // out. Pre-existing for suspension; the ban gate would have inherited it
    // (reviewer R3-C2).
    req.path === '/portal/me' ||
    req.path === '/portal/sign-out'
  );
}
 
/**
 * Paths a BANNED user may still reach: everything a suspended user may
 * (appeals + GDPR rights survive a ban), PLUS the two ban-delivery /
 * device-binding channels — /device-info is how the app LEARNS it is
 * banned (the ban screen), and /devices/lock-check runs pre-ban-screen in
 * the sign-in flow. Gating those would replace the ban screen with a
 * generic error while enforcing nothing (both are telemetry/verdict
 * endpoints, not abuse-capable actions).
 *
 * ONE deliberate subtraction: `/portal/me`. A SUSPENDED user reaches it and
 * portal.js answers with an explicit `isSuspended` payload — but portal.js
 * has no ban branch at all, so exempting a BANNED user would hand them a
 * normal-looking dashboard with no hint they are banned. The gate's own 403
 * (`code: 'banned'` + reason + expiresAt) IS the ban notice, and it is the
 * same shape every other client already renders. Signing out, by contrast,
 * must always work — a ban is not a reason to trap someone in a session.
 */
function isBanExemptPath(req) {
  if (req.path === '/portal/me') return false;
  // `/device-info` and `/devices/lock-check` used to be named again here.
  // They are standing-verdict channels, so `isSuspensionExemptPath` now
  // derives them from `PRE_IDENTITY_ROUTES` and this list would have been a
  // second place for the same fact to be stated — and eventually disagreed
  // with. The derived form is also method-exact, where the old string compare
  // matched any verb on those paths.
  return isSuspensionExemptPath(req);
}
 
/**
 * Strict auth middleware: verifies Firebase ID token with checkRevoked,
 * resolves uniqueId, checks suspension. For portal and admin routes
 * where token revocation must be enforced.
 *
 * Suspension exemption paths: /portal/me, /portal/sign-out, /users/{id}/appeal
 */
async function authMiddlewareStrict(req, res, next) {
  const authHeader = req.headers.authorization;
  if (!authHeader?.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'Missing or invalid Authorization header' });
  }
 
  const idToken = authHeader.slice(7);
 
  // Synthetic-token bypass (NODE_ENV=local only). The strict variant
  // normally adds revocation-checking via verifyIdToken(token, true) —
  // there's nothing to revoke on a synthetic token, so the bypass is
  // semantically equivalent here. Both middlewares behave identically
  // for synthetic tokens; only the live-token branches differ.
  const synth = decodeSyntheticToken(idToken);
  Iif (synth) {
    req.auth = synth;
    return next();
  }
 
  // SHY-0308: the credential check is deliberately OUTSIDE the block below.
  // A rejected token and a standing lookup that could not complete are
  // different failures that happened to share one catch, one status and one
  // string -- so a refusal could not be attributed to either. It cost a dig
  // through a Playwright trace to learn that a suite failure reading
  // "Expected 403, Received 401" had never reached the ban gate at all.
  // `true` = check revocation, so `auth/id-token-revoked` lands here too: a
  // revoked session IS a rejected credential.
  const decoded = await verifyCredentialOrReject(res, idToken, true);
  if (!decoded) return undefined; // verifyCredentialOrReject already answered.
 
  try {
    const uid = decoded.uid;
 
    // Resolve Firebase UID → stable uniqueId
    const uniqueId = await resolveUniqueId(uid);
 
    // Check suspension (only if user exists)
    const isSuspended = await checkSuspension(uniqueId);
 
    const isStrictSuspensionExempt =
      // Same rule as the outer gate. No standing-verdict channel is mounted
      // under STRICT today (it guards /portal/* and admin), so this term
      // changes nothing now — it is here because the two gates diverging is
      // the failure this file has already been bitten by (reviewer R5-C1),
      // and one rule stated once cannot diverge from itself.
      isStandingVerdictChannel(req) ||
      req.path === '/portal/me' ||
      req.path === '/portal/sign-out' ||
      /^\/users\/[^/]+\/appeal$/.test(req.path);
 
    if (isSuspended && !isStrictSuspensionExempt) {
      return res.status(403).json({ error: 'Account suspended' });
    }
 
    // A BAN exempts strictly less than a suspension does. `/portal/me` is
    // reachable while suspended (portal.js answers with an `isSuspended`
    // payload) but NOT while banned — portal.js has no ban branch, so a banned
    // caller would receive a normal-looking dashboard. This is the same
    // subtraction `isBanExemptPath` makes for the outer gate. The two lists
    // must agree: today the outer gate reaches every /portal/* request first
    // and masks a divergence here (reviewer R5-C1).
    const isStrictBanExempt = isStrictSuspensionExempt && req.path !== '/portal/me';
 
    // Per-request ban gate (SHY-0149). Exemption is checked BEFORE the lookup
    // so a fail-closed rejection cannot strip those rights (reviewer C-NEW-1).
    if (!isStrictBanExempt) {
      const ban = await checkUserBans(uniqueId, req.ip);
      // SHY-0150 lazy claim sync — same reconciliation as authMiddleware
      // (see the comment there); the two gates must not diverge.
      const tokenBanned = decoded.banned === true;
      if (ban.isBanned) {
        Eif (!tokenBanned) {
          await syncBannedClaim(uniqueId, { uid, verdictBanned: true, dedupe: true });
        }
        log.warn('auth', 'Request denied: banned (strict)', {
          path: req.path,
          uniqueId,
          banType: ban.banType,
        });
        return res.status(403).json({
          error: 'Account banned',
          code: 'banned',
          banType: ban.banType,
          reason: ban.reason,
          expiresAt: ban.expiresAt,
        });
      }
      Iif (tokenBanned) {
        await syncBannedClaim(uniqueId, { uid, dedupe: true });
      }
    }
 
    Iif (!hasResolvedIdentity(uniqueId) && !allowsMissingIdentity(req)) {
      req.__authUid = uid;
      return rejectMissingIdentity(req, res);
    }
 
    req.auth = { uid, uniqueId, token: decoded };
    next();
  } catch (err) {
    return rejectStandingUnavailable(req, res, err);
  }
}
 
// ─── Helpers ─────────────────────────────────────────────────────
 
/**
 * Re-check the live `admin` custom claim for a uid by querying Firebase
 * Auth (`auth.getUser`). Decoded ID tokens carry whatever claims existed
 * when the token was ISSUED, so a demoted admin's still-valid token shows
 * `admin: true` until natural expiry. This helper consults the live
 * customClaims, with a 60s TTL cache to keep the lookup cheap on hot
 * admin paths. (Phase 2H finding #2)
 *
 * Cached value is the boolean `customClaims.admin` from Firebase. Returns
 * `false` on lookup failure — fail closed, an admin route should never
 * grant privileges based on a Firestore-side outage.
 */
async function isLiveAdmin(uid) {
  // Skip the live check under Jest UNLESS AUTH_FORCE_LIVE_ADMIN_CHECK is set.
  // Most admin tests assert behaviour OTHER than the live re-check and would
  // otherwise need to seed live customClaims for every admin caller; skipping
  // (return true) lets them pass on the token claim alone. Production has no
  // JEST_WORKER_ID, so the live check ALWAYS fires there. Tests that DO exercise
  // the live path set AUTH_FORCE_LIVE_ADMIN_CHECK and establish the live claim
  // for REAL via auth.setCustomUserClaims against the Auth emulator — no mock of
  // auth.getUser is involved (EPIC-0003 real-only; see livekit-cohort.test.js
  // "admin cohort-bypass re-verifies the LIVE admin claim").
  if (process.env.JEST_WORKER_ID && !process.env.AUTH_FORCE_LIVE_ADMIN_CHECK) {
    return true;
  }
  Iif (!uid) return false;
  const cached = adminClaimCache.get(uid);
  if (cached && Date.now() < cached.expiresAt) {
    return cached.isAdmin;
  }
  try {
    const userRecord = await auth.getUser(uid);
    const isAdmin = userRecord?.customClaims?.admin === true;
    adminClaimCache.set(uid, { isAdmin, expiresAt: Date.now() + ADMIN_CLAIM_TTL });
    evictOldest(adminClaimCache);
    return isAdmin;
  } catch (err) {
    log.error('auth', 'Admin-claim re-fetch failed', { uid, error: err.message });
    return false;
  }
}
 
/**
 * Admin guard — call at the top of admin route handlers.
 *
 * Returns true if blocked (response already sent), false if admin.
 *
 * Two-layer check:
 *   1. Fast: `req.auth.token.admin` (decoded ID token claim).
 *   2. Live: `auth.getUser(uid).customClaims.admin` via 60s TTL cache.
 *
 * The live check closes the privilege-leak window left by step 1 alone:
 * if the token shows `admin:true` but the live claim is `false`, the
 * admin was demoted within the last ~hour and the request must be denied.
 *
 * Async — every caller does `if (await requireAdmin(req, res)) return;`.
 */
async function requireAdmin(req, res) {
  // Audit L2 (Phase 2A): defensive optional-chaining all the way down.
  // Fail closed on undefined req.auth/token rather than crashing.
  if (!req.auth?.token?.admin) {
    res.status(403).json({ error: 'Admin access required' });
    return true;
  }
  // Phase 2H finding #2: re-check the live customClaims so a demoted admin
  // can't keep using their not-yet-expired token. Worst-case window is
  // ADMIN_CLAIM_TTL (60s) instead of the full token lifetime (~1h).
  const liveAdmin = await isLiveAdmin(req.auth.uid);
  if (!liveAdmin) {
    res.status(403).json({ error: 'Admin access required' });
    return true;
  }
  return false;
}
 
function clearSuspensionCache(uniqueId) {
  // Guard on `=== undefined` (a genuine no-arg call), NOT truthiness: unlike the
  // string uids the sibling helpers take, uniqueId can arrive as Number(badId) →
  // NaN (e.g. identity-graph.js), and `if (NaN)` truthiness would wrongly wipe
  // the whole cache. A passed 0/NaN/null falls to the targeted delete (a safe
  // no-op) instead.
  if (uniqueId === undefined) {
    // No id → clear everything (mirrors clearUniqueIdCache/clearAdminClaimCache),
    // so the no-arg clearAuthCaches() test-isolation helper actually empties it.
    // suspensionInFlight is cleared for mirror-consistency; the no-arg path runs
    // between requests (test isolation) so there is no in-flight entry to drop —
    // the production ban/unban-during-traffic case goes through the targeted
    // branch below.
    suspensionCache.clear();
    suspensionInFlight.clear();
  } else {
    suspensionCache.delete(uniqueId);
    // Also drop any inflight Promise so the NEXT caller refetches from
    // Firestore (the inflight Promise was about to resolve to the OLD value).
    suspensionInFlight.delete(uniqueId);
  }
}
 
/**
 * Drop the cached admin claim for a uid. Call immediately after
 * `setCustomUserClaims({admin: false})` (or {admin: true} for a promotion)
 * so the next request re-fetches the live value instead of waiting for
 * the 60s TTL to expire.
 */
function clearAdminClaimCache(uid) {
  if (uid) {
    adminClaimCache.delete(uid);
  } else {
    adminClaimCache.clear();
  }
}
 
/** Clear uniqueId cache entry — call after firebaseUid is updated. */
function clearUniqueIdCache(uid) {
  if (uid) {
    uniqueIdCache.delete(uid);
    uniqueIdInFlight.delete(uid);
  } else {
    uniqueIdCache.clear();
    uniqueIdInFlight.clear();
  }
}
 
/** Update uniqueId cache — call after sign-in resolves a new mapping. */
function updateUniqueIdCache(uid, uniqueId) {
  uniqueIdCache.set(uid, { uniqueId, expiresAt: Date.now() + CACHE_TTL });
  evictOldest(uniqueIdCache);
}
 
module.exports = {
  authMiddleware,
  allowsMissingIdentity,
  hasResolvedIdentity,
  PRE_IDENTITY_ROUTES,
  authMiddlewareStrict,
  requireAdmin,
  isLiveAdmin,
  // Exported for the SSE fan-out (SHY-0169): a stream is ONE request, so the
  // middleware's suspension check runs once and then never again for the life
  // of a long connection. The fan-out re-checks per delivery.
  checkSuspension,
  clearSuspensionCache,
  clearUniqueIdCache,
  clearAdminClaimCache,
  // Re-exported from utils/bans so middleware consumers (tests, admin
  // routes already importing from here) have one import surface.
  clearBanCache,
  updateUniqueIdCache,
  resolveUniqueId,
};