All files / src/routes users.js

91.39% Statements 510/558
85.36% Branches 315/369
100% Functions 38/38
92.91% Lines 472/508

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 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434                                        9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x           9x 9x   9x 9x 9x     9x             9x 9x   9x                               60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 22x   60x                                       26x 26x 24x 22x 20x                           30x 30x       28x 28x 26x 26x   28x                   28x 13x 13x                         96x 96x 1x 1x   95x 12x 12x   83x             9x 39x   39x   39x 37x 35x 1x                   34x 1x   33x 33x 2x                       31x 31x 31x 31x 31x 1x               31x 3x 3x     28x 28x 28x   28x   28x 28x     28x 3x 3x   2x       2x     1x         25x 25x 25x   25x     25x     25x                                                       25x                 25x                   25x 25x             24x   24x 24x   4x 1x   3x 2x       1x 1x               9x 19x 19x   19x 18x   17x 17x   17x 2x     15x 2x     13x                     13x 13x 13x 11x 11x 11x 2x 2x                 11x                           11x           11x   11x 11x                               9x 12x 12x 12x     1x 1x                               9x 34x 34x 34x 30x 1x       29x 1x         28x             10x 9x 9x 2x   7x     7x 1x   6x 6x       18x 18x           2x 2x               9x 41x 41x           41x 41x 6x   35x           35x 1x     34x 34x 34x       34x   34x                       9x                     9x             9x                       9x                     2x 18x     18x                 2x 20x   2x 12x     2x 4x     2x 4x     2x             9x 5x 5x   3x 3x   3x                                                       3x 3x 75x     3x 1x       2x 2x     2x       2x       2x   2x                           9x 19x 19x   18x 18x 17x 16x           16x 16x     16x         16x     16x 2x     14x   2x 2x       2x 4x       2x   2x         2x     12x           32x 12x 2x         10x     10x                   10x       10x   10x         10x                           9x 9x 9x   8x 8x 8x   8x 8x     8x         8x 8x     7x 1x       11x 6x 2x         4x     4x           4x 8x       4x   4x         4x                           9x 6x 6x   4x 4x 3x 1x         2x           2x 2x 2x 2x 2x 1x       1x   1x                             1x                           9x 5x 5x   4x 4x 4x 4x 1x     3x 3x 1x     2x   2x                 2x   2x                           9x 10x 10x 10x 10x 10x           9x 9x 2x   7x     1x     6x 6x             6x 6x   5x     3x     3x 3x     3x     3x 3x   3x                             9x 8x 8x 8x 8x 7x         6x 6x     6x 1x           5x   4x 4x     2x     3x 3x 3x     3x     3x 3x   3x                             9x 8x 8x 8x 8x 7x     6x 6x     6x 1x         5x   4x 4x     2x     3x 3x 3x     3x     3x 3x   3x                             9x 10x 10x 10x 10x   9x 1x   8x   7x               7x         7x 7x   6x 2x     4x 4x 4x   4x 1x 1x       1x     1x   3x 3x                   3x       3x     4x                         6x 6x 5x 5x 5x         6x 5x 5x                               9x 15x 15x   14x 14x     14x 13x 1x   12x     12x 1x       11x 1x                 10x 2x         2x     8x 1x   7x 7x 1x       6x 6x       6x 6x     6x           6x     6x 6x           6x     6x               6x 6x   1x 1x               9x 8x 8x   7x   7x 6x 1x   5x   5x 1x       4x 1x           3x 1x     2x             2x             2x 2x   1x 1x               9x 5x 5x   4x   4x 3x 1x   2x   2x 1x                 1x 1x   1x               1x 1x       9x  
/**
 * User routes — identity-based profile CRUD, sign-in, provider linking.
 *
 * POST   /api/users                          → Create new user (identity + uniqueId)
 * POST   /api/users/sign-in                  → Resolve identity, update firebaseUid
 * GET    /api/users/:uniqueId                → Get user profile
 * PATCH  /api/users/:uniqueId                → Update user profile fields
 * POST   /api/users/:uniqueId/link-provider  → Link additional provider
 * DELETE /api/users/:uniqueId/link-provider  → Soft-remove (unlink) provider
 * POST   /api/users/:uniqueId/appeal         → Submit suspension appeal
 * POST   /api/users/:uniqueId/lift-suspension→ Lift expired suspension
 * POST   /api/users/:uniqueId/follow         → Follow a user
 * POST   /api/users/:uniqueId/unfollow       → Unfollow a user
 * POST   /api/users/:uniqueId/remove-follower→ Remove a follower
 * POST   /api/users/:uniqueId/record-visit   → Record profile visit (stalker)
 * POST   /api/users/:uniqueId/delete         → Schedule account deletion (owner)
 * POST   /api/users/:uniqueId/cancel-delete  → Cancel scheduled deletion (owner)
 * GET    /api/users/:uniqueId/deletion-status → Check deletion status (owner)
 */
 
const router = require('express').Router();
const bcrypt = require('bcrypt');
const { db, auth, FieldValue } = require('../utils/firebase');
const { generateId, now } = require('../utils/helpers');
const { getDoc } = require('../utils/firestore-helpers');
const log = require('../utils/log');
const { clearSuspensionCache, updateUniqueIdCache } = require('../middleware/auth');
const { sendEmail } = require('../utils/email');
const { buildDeletionScheduledEmail } = require('../utils/email-templates');
const { sendFcmToTokens } = require('../utils/fcm');
const { viewerIsBlocked } = require('../utils/block-check');
const {
  mintClaimsMerging,
  deriveCohortFromUser,
  cohortFromClaim,
  effectiveCohort,
} = require('../utils/firebase-claims');
const { requireSameCohort } = require('../middleware/sameCohort');
 
const VALID_PROVIDERS = ['google', 'apple', 'email'];
const MIN_UNIQUE_ID = 10000000;
const MAX_IDENTIFIERS_PER_PROVIDER = 5;
 
// UK OSA #17 PR 5 — Discovery + search: shared limits and field hygiene.
const DISCOVERY_LIMIT = 50;
// 3-char minimum on Express defence-in-depth path: combined with the
// 30/min writeLimiter this raises brute-force prefix enumeration from
// ~22 min (bigram, 676 prefixes) to ~9.4 hr (trigram, 17,576 prefixes)
// at the rate cap. PR 5 security-review MEDIUM. Existing iOS client
// queries Firestore directly (gated by PR 3 rules), so the API-level
// min-char does not alter end-user typeahead UX.
const SEARCH_MIN_QUERY_CHARS = 3;
const SEARCH_MAX_QUERY_CHARS = 50;
// Highest BMP code point — canonical Firestore prefix-range upper bound.
const PREFIX_UPPER_SENTINEL = '\uf8ff';
 
/**
 * Strip fields that must never leave the server. Applied uniformly to
 * every user payload returned from this router so the discovery, search,
 * and profile-view endpoints share a single source of truth and cannot
 * drift apart.
 *
 * `cohort` and `cohortOverride` are stripped on top of the original
 * sensitive set: a caller's same-cohort gate already implies they know
 * their own bucket, and exposing `cohortOverride` would surface a
 * moderator-action side channel (PR 5 security-review MEDIUM).
 *
 * Mutates and returns the input for compactness inside `.map` chains.
 */
function stripSensitiveFields(user) {
  Iif (!user || typeof user !== 'object') return user;
  delete user.gcsScore;
  delete user.gcsLastDeductionAt;
  delete user.gcsDisplayScore;
  delete user.warningCount;
  delete user.warningIssuedAt;
  delete user.hasNewWarning;
  delete user.pinHash;
  delete user.fcmTokens;
  delete user.firebaseUid;
  delete user.email;
  delete user.dateOfBirth;
  delete user.deletionScheduledAt;
  delete user.deletionReason;
  delete user.deletionExecuteAt;
  delete user.cohort;
  delete user.cohortOverride;
  if (Array.isArray(user.providers)) {
    user.providers = user.providers.map(({ identifier: _identifier, ...rest }) => rest);
  }
  return user;
}
 
/**
 * List-helpers: shape the per-doc shared filtering used by both
 * `/users/discover` and the `/users/search` displayName branch. Returns
 * `null` when the doc should be dropped (self, cross-effective-cohort,
 * blocked-by-target). Otherwise returns the strip-sanitised doc.
 *
 * Defence layers in order:
 *   1. Self-exclude   — caller never appears in their own results.
 *   2. effectiveCohort gate — guards against `cohort` field drift vs
 *      `cohortOverride`. The Firestore `where('cohort', '==', x)`
 *      narrowed the candidate set; this is the correctness backstop
 *      against the cache-field semantics documented in firebase-claims.js.
 *   3. viewerIsBlocked — preserves the C7 block-list-integrity invariant
 *      that `GET /users/:uniqueId` enforces; the new list endpoints
 *      MUST NOT bypass it (PR 5 security-review HIGH).
 */
function shapeForViewer(callerUniqueId, callerCohort, data) {
  Iif (!data) return null;
  if (data.uniqueId === callerUniqueId) return null;
  if (effectiveCohort(data) !== callerCohort) return null;
  if (viewerIsBlocked(callerUniqueId, data)) return null;
  return stripSensitiveFields(data);
}
 
/**
 * Run a same-cohort list query and respond with the shaped + filtered
 * results. Single source of truth for both `/users/discover` and the
 * `/users/search` displayName branch — eliminates the result-aggregation
 * duplication those routes would otherwise share.
 *
 * `queryBuilder` receives the users collection ref and the caller's
 * resolved cohort, returns a Firestore query (without `.limit()` — the
 * helper applies `DISCOVERY_LIMIT` consistently).
 */
async function respondWithSameCohortUsers(req, res, queryBuilder) {
  const callerCohort = cohortFromClaim(req);
  const snap = await queryBuilder(db.collection('users'), callerCohort)
    .limit(DISCOVERY_LIMIT)
    .get();
 
  const users = [];
  for (const doc of snap.docs) {
    const shaped = shapeForViewer(req.auth.uniqueId, callerCohort, doc.data());
    if (shaped) users.push(shaped);
  }
  res.json({ users });
}
 
/**
 * Search disambiguator. A query is treated as a uniqueId lookup only
 * when it is a positive integer ≥ MIN_UNIQUE_ID. Anything else falls
 * through to the displayName-prefix branch — so e.g. "100" or "abc123"
 * never short-circuits the cohort-filtered name search.
 */
function looksLikeUniqueId(q) {
  if (!/^[1-9]\d*$/.test(q)) return false;
  const n = Number(q);
  return Number.isSafeInteger(n) && n >= MIN_UNIQUE_ID;
}
 
// ─── Helper: ownership check ────────────────────────────────────
 
function requireOwner(req, res) {
  // Audit L1 (Phase 2A): explicit NaN guard. Without this, a non-
  // numeric :uniqueId param produces NaN from Number(), and the
  // comparison `req.auth.uniqueId !== NaN` is always true (NaN
  // is unequal to everything including itself), so the route fails
  // closed (403) — safe but obscure. Returning a clearer 400 makes
  // a malformed-route-param the visible failure mode rather than
  // a misleading 'Cannot modify another user'.
  const paramId = Number(req.params.uniqueId);
  if (!Number.isInteger(paramId)) {
    res.status(400).json({ error: 'uniqueId must be a positive integer' });
    return true; // blocked
  }
  if (req.auth.uniqueId !== paramId) {
    res.status(403).json({ error: 'Cannot modify another user' });
    return true; // blocked
  }
  return false;
}
 
// ═══════════════════════════════════════════════════════════════════
// POST /api/users — Create new user with identity map
// ═══════════════════════════════════════════════════════════════════
 
router.post('/users', async (req, res) => {
  try {
    const { provider, identifier, displayName, email, profilePhotoUrl, dateOfBirth, language } =
      req.body || {};
 
    if (!provider) return res.status(400).json({ error: 'provider required' });
    if (!identifier) return res.status(400).json({ error: 'identifier required' });
    if (!VALID_PROVIDERS.includes(provider)) {
      return res
        .status(400)
        .json({ error: `Invalid provider. Must be one of: ${VALID_PROVIDERS.join(', ')}` });
    }
 
    // Server-side age validation. Floor bumped 13 → 16 on 2026-05-03 for
    // Apple App Store content-guideline compliance — see
    // `.project/plans/2026-05-03-age-verification.md`. The 16-17 cohort
    // signs up but cannot use 18+ gated features (private messages,
    // gacha) until they age in or complete ID verification.
    if (!dateOfBirth) {
      return res.status(400).json({ error: 'Date of birth is required' });
    }
    const dob = new Date(dateOfBirth);
    if (Number.isNaN(dob.getTime())) {
      return res.status(400).json({ error: 'Invalid date of birth format' });
    }
    // Calendar-year age computation. Pre-fix used (Date.now() - dob)
    // / year-in-ms which produces wrong values around leap years
    // (Feb 29 birthdays return 15.99... years for ~5 days after the
    // 16th birthday) AND can be off-by-one near year boundaries due
    // to UTC offset handling. Audit H1 (Phase 2A): regulatory issue
    // (COPPA, GDPR, Apple age gate require accurate age).
    //
    // Correct algorithm: yearDiff, then subtract 1 if today's
    // month/day is BEFORE the birth month/day (haven't had this
    // year's birthday yet).
    const today = new Date();
    let age = today.getUTCFullYear() - dob.getUTCFullYear();
    const monthDiff = today.getUTCMonth() - dob.getUTCMonth();
    const dayDiff = today.getUTCDate() - dob.getUTCDate();
    if (monthDiff < 0 || (monthDiff === 0 && dayDiff < 0)) {
      age -= 1;
    }
    // Minimum sign-up age bumped 13 → 16 on 2026-05-03 for Apple App
    // Store content-guideline compliance — see
    // `.project/plans/2026-05-03-age-verification.md`. The 16-17 cohort
    // can still create accounts but cannot use 18+ gated features
    // (private messages, gacha) until they age into them OR complete
    // ID-based age verification (handled in later PRs of this plan).
    if (age < 16) {
      log.warn('users', 'Age validation rejected', { dateOfBirth });
      return res.status(403).json({ error: 'Must be at least 16 years old' });
    }
 
    const identityDocId = `${provider}:${identifier}`;
    const counterRef = db.doc('counters/uniqueId');
    const identityRef = db.doc(`identityMap/${identityDocId}`);
 
    const newUniqueId = await db.runTransaction(async (t) => {
      // All reads first (Firestore transaction requirement)
      const counterSnap = await t.get(counterRef);
      const identitySnap = await t.get(identityRef);
 
      // Check identity not already claimed
      if (identitySnap.exists) {
        const identityData = identitySnap.data();
        if (identityData.unlinked) {
          // Deleted accounts: allow clean re-registration, block suspended
          Iif (identityData.deletedAccount && identityData.deletionStanding === 'clean') {
            // Clean deletion — allow re-registration with new uniqueId
            // The old identity map entry will be replaced below
          } else {
            throw Object.assign(new Error('Identity deactivated'), { code: 'DEACTIVATED' });
          }
        } else {
          throw Object.assign(new Error('Identity already linked'), { code: 'ALREADY_LINKED' });
        }
      }
 
      // Atomic counter increment
      let current = counterSnap.exists ? counterSnap.data().value || 0 : 0;
      if (current < MIN_UNIQUE_ID) current = MIN_UNIQUE_ID - 1;
      const next = current + 1;
 
      const timestamp = now();
 
      // Write counter
      t.set(counterRef, { value: next }, { merge: true });
 
      // Write user doc
      t.set(db.doc(`users/${next}`), {
        uniqueId: next,
        firebaseUid: req.auth.uid,
        displayName: displayName || null,
        email: email || null,
        profilePhotoUrl: profilePhotoUrl || null,
        dateOfBirth: dateOfBirth || null,
        providers: [{ type: provider, identifier, active: true, linkedAt: timestamp }],
        userType: 'MEMBER',
        blockedUserIds: [],
        followingIds: [],
        followerIds: [],
        fcmTokens: [],
        aliases: {},
        language: language || 'en',
        stalkerCount: 0,
        newStalkerCount: 0,
        // Age verification (Apple App Store 18+ enforcement on PMs +
        // gacha). New users start unverified; admin approves a manual
        // ID review to flip to verified. See age-verification PR plan.
        ageVerified: false,
        ageVerifiedAt: null,
        ageVerificationMethod: null,
        createdAt: timestamp,
        lastSeenAt: timestamp,
      });
 
      // Write identity map entry
      t.set(db.doc(`identityMap/${identityDocId}`), {
        uniqueId: next,
        provider,
        identifier,
        linkedAt: timestamp,
        unlinked: false,
        unlinkedAt: null,
      });
 
      return next;
    });
 
    // Set Firebase custom claims so Firestore security rules can use
    // callerUniqueId() AND the UK OSA #17 cohort gate. `age` was
    // computed above from the validated DOB — cohort follows the
    // same `>=18y` predicate as pmLocked. `skipFetch: true` because
    // signup creates a brand-new Firebase Auth record with no
    // existing claims; the getUser round-trip would be wasted work
    // on the signup critical path.
    const signupCohort = age >= 18 ? 'adult' : 'minor';
    await mintClaimsMerging(
      req.auth.uid,
      { uniqueId: newUniqueId, cohort: signupCohort },
      { skipFetch: true },
    );
 
    // Update uid → uniqueId cache so subsequent requests resolve instantly
    updateUniqueIdCache(req.auth.uid, newUniqueId);
 
    log.info('users', 'New user created', { uniqueId: newUniqueId, provider });
    res.json({ success: true, created: true, uniqueId: newUniqueId });
  } catch (err) {
    if (err.code === 'ALREADY_LINKED') {
      return res.status(409).json({ error: 'Identity already linked to an account' });
    }
    if (err.code === 'DEACTIVATED') {
      return res
        .status(409)
        .json({ error: 'This identity has been deactivated. Contact support for assistance.' });
    }
    log.error('users', 'POST /users failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ═══════════════════════════════════════════════════════════════════
// POST /api/users/sign-in — Identity resolution + firebaseUid update
// ═══════════════════════════════════════════════════════════════════
 
router.post('/users/sign-in', async (req, res) => {
  try {
    const { provider, identifier } = req.body || {};
 
    if (!provider) return res.status(400).json({ error: 'provider required' });
    if (!identifier) return res.status(400).json({ error: 'identifier required' });
 
    const identityDocId = `${provider}:${identifier}`;
    const identity = await getDoc(`identityMap/${identityDocId}`);
 
    if (!identity) {
      return res.json({ found: false });
    }
 
    if (identity.unlinked) {
      return res.json({ found: false, deactivated: true });
    }
 
    const uniqueId = identity.uniqueId;
 
    // Suspension check BEFORE updating firebaseUid + custom claims.
    // Audit M5 (Phase 2A): pre-fix signed in suspended users (updated
    // their UID and granted custom claims) before the auth-middleware
    // suspension check ran. The suspension cache had a 5-min TTL —
    // brief window where suspended users could perform writes.
    //
    // Now: read the user doc, check isSuspended, return found+suspended
    // WITHOUT mutating Firebase state. Client surfaces the suspension
    // to the user; no UID refresh, no custom claim grant.
    const userSnap = await db.doc(`users/${uniqueId}`).get();
    let userData = null;
    if (userSnap.exists) {
      userData = userSnap.data();
      const isSuspended = userData.isSuspended ?? userData.is_suspended ?? false;
      if (isSuspended) {
        log.warn('users', 'Sign-in attempt by suspended user', { uniqueId, provider });
        return res.json({
          found: true,
          suspended: true,
          uniqueId,
        });
      }
    }
 
    // Update firebaseUid to current project's UID + refresh lastSeenAt
    await db.doc(`users/${uniqueId}`).update({
      firebaseUid: req.auth.uid,
      lastSeenAt: now(),
    });
 
    // Mint custom claims (UK OSA #17 PR 2). Goes through the merge
    // helper because the user may already have other claims
    // (`admin: true` for moderators) we must preserve. Cohort is
    // resolved via `deriveCohortFromUser` (NOT `effectiveCohort`):
    // we re-derive from `dateOfBirth` rather than trusting the
    // cached `cohort` field. Defends against the narrow window
    // where admin DOB-modified the user but pm-lock-check hasn't
    // run yet — the cached field would lie. Override (allow-listed)
    // still wins; falls back to `'minor'` for legacy/missing DOB.
    await mintClaimsMerging(req.auth.uid, {
      uniqueId,
      cohort: deriveCohortFromUser(userData),
    });
 
    // Update caches
    updateUniqueIdCache(req.auth.uid, uniqueId);
 
    log.info('users', 'User signed in via identity', { uniqueId, provider });
    res.json({ found: true, uniqueId });
  } catch (err) {
    log.error('users', 'POST /users/sign-in failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ═══════════════════════════════════════════════════════════════════
// GET /api/users/discover — Same-cohort discovery feed
// ═══════════════════════════════════════════════════════════════════
// UK OSA #17 PR 5. Registered BEFORE `/users/:uniqueId` so the literal
// "discover" path segment doesn't get captured as a uniqueId param.
// Filters at the Firestore query level via the `(cohort, lastSeenAt)`
// composite index so cross-cohort users are never serialised at all,
// even before the response-layer sanitisation runs.
 
router.get('/users/discover', async (req, res) => {
  try {
    await respondWithSameCohortUsers(req, res, (col, cohort) =>
      col.where('cohort', '==', cohort).orderBy('lastSeenAt', 'desc'),
    );
  } catch (err) {
    log.error('users', 'GET /users/discover failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ═══════════════════════════════════════════════════════════════════
// GET /api/users/search?q=... — Same-cohort search
// ═══════════════════════════════════════════════════════════════════
// Two branches, auto-routed by query shape:
//   • numeric q ≥ MIN_UNIQUE_ID → exact uniqueId fetch + requireSameCohort.
//     Cross-cohort returns the existence-hiding 404 + segregationEvents
//     audit just like every other interaction endpoint (the PR 4
//     contract is preserved end-to-end here).
//   • everything else          → displayName prefix range gated by
//     `where('cohort','==',callerCohort)`. The cohort `where` clause
//     is the same Firestore-query-level enforcement as discovery.
 
router.get('/users/search', async (req, res) => {
  try {
    const q = typeof req.query.q === 'string' ? req.query.q.trim() : '';
    if (!q) return res.status(400).json({ error: 'q required' });
    if (q.length < SEARCH_MIN_QUERY_CHARS) {
      return res
        .status(400)
        .json({ error: `q must be at least ${SEARCH_MIN_QUERY_CHARS} characters` });
    }
    if (q.length > SEARCH_MAX_QUERY_CHARS) {
      return res
        .status(400)
        .json({ error: `q must be at most ${SEARCH_MAX_QUERY_CHARS} characters` });
    }
 
    if (looksLikeUniqueId(q)) {
      // Numeric branch: single-doc lookup + same-cohort gate.
      // `requireSameCohort` writes the existence-hiding 404 + audit on
      // miss too — so when `target` is null and `!isSelf`, the middleware
      // already sent the 404 and we returned above. The `if (!target)`
      // below is reachable only on the self-search-of-own-missing-id
      // path (caller asks for their own uniqueId, doc somehow absent).
      const target = await getDoc(`users/${q}`);
      const isSelf = String(req.auth.uniqueId) === q;
      if (!isSelf && (await requireSameCohort(req, res, q, () => target))) {
        return;
      }
      Iif (!target) return res.status(404).json({ error: 'Not found' });
      // Block-list integrity: blocked viewer must not retrieve target
      // profile (matches `GET /users/:uniqueId` semantics; self bypasses).
      if (!isSelf && viewerIsBlocked(req.auth.uniqueId, target)) {
        return res.status(403).json({ error: 'Cannot view content of users who have blocked you' });
      }
      stripSensitiveFields(target);
      return res.json({ users: [target] });
    }
 
    // displayName prefix branch.
    await respondWithSameCohortUsers(req, res, (col, cohort) =>
      col
        .where('cohort', '==', cohort)
        .where('displayName', '>=', q)
        .where('displayName', '<', q + PREFIX_UPPER_SENTINEL),
    );
  } catch (err) {
    log.error('users', 'GET /users/search failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ═══════════════════════════════════════════════════════════════════
// GET /api/users/:uniqueId — Get user profile
// ═══════════════════════════════════════════════════════════════════
 
router.get('/users/:uniqueId', async (req, res) => {
  try {
    const user = await getDoc(`users/${req.params.uniqueId}`);
 
    // UK OSA #17 PR 4 — cross-cohort profile views return 404 with
    // existence-hiding body (`{ error: 'Not found' }`), byte-identical
    // to the legitimate "missing target" 404. Self-view bypasses the
    // gate (caller's own profile is always visible).
    const isSelf = String(req.auth.uniqueId) === String(req.params.uniqueId);
    if (!isSelf && (await requireSameCohort(req, res, req.params.uniqueId, () => user))) {
      return;
    }
    Iif (!user) return res.status(404).json({ error: 'Not found' });
 
    // C7 (block-list integrity): the target user must not be visible
    // to a viewer they have blocked. Returns 403 — the client already
    // handles 403 from interaction endpoints (gift-send) the same way.
    // Allowed exception: the user looking at their own profile.
    if (!isSelf && viewerIsBlocked(req.auth.uniqueId, user)) {
      return res.status(403).json({ error: 'Cannot view content of users who have blocked you' });
    }
 
    user.blockedUserIds = user.blockedUserIds || [];
    user.followingIds = user.followingIds || [];
    user.followerIds = user.followerIds || [];
 
    // Strip admin-only / PII / deletion / cohort fields. Single source of
    // truth shared with /users/discover and /users/search.
    stripSensitiveFields(user);
 
    res.json(user);
  } catch (err) {
    log.error('users', 'GET /users/:uniqueId failed', {
      uniqueId: req.params.uniqueId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ─── Profile update validation ─────────────────────────────────
 
const PROFILE_STRING_FIELDS = [
  'displayName',
  'description',
  'nationality',
  'profilePhotoUrl',
  'coverPhotoUrl',
  'pmPrivacy',
  'currentRoomId',
  'lastRoomName',
  'language',
];
const PROFILE_MAX_LENGTHS = {
  displayName: 20,
  description: 200,
  nationality: 3,
  language: 10,
  lastRoomName: 50,
};
const PROFILE_BOOL_FIELDS = [
  'pmNotificationsEnabled',
  'pmSoundEnabled',
  'pmShowTimestamps',
  'pmShowDateSeparators',
  'pmNotificationPreview',
  'hideFollowing',
  'hideOnlineStatus',
  'hideAge',
  'selfDestructAlertEnabled',
  'dndEnabled',
];
const PROFILE_INT_FIELDS = [
  'dndStartHour',
  'dndStartMinute',
  'dndEndHour',
  'dndEndMinute',
  'minGiftAnimationValue',
  'acceptedLegalVersion',
];
 
/** Validate profile update field types and constraints. Returns error string or null. */
function validateProfileUpdates(updates) {
  for (const key of PROFILE_STRING_FIELDS) {
    Iif (key in updates && updates[key] !== null && typeof updates[key] !== 'string') {
      return `${key} must be a string`;
    }
    Iif (
      key in updates &&
      typeof updates[key] === 'string' &&
      PROFILE_MAX_LENGTHS[key] &&
      updates[key].length > PROFILE_MAX_LENGTHS[key]
    ) {
      return `${key} exceeds max length of ${PROFILE_MAX_LENGTHS[key]}`;
    }
  }
  for (const key of PROFILE_BOOL_FIELDS) {
    Iif (key in updates && typeof updates[key] !== 'boolean') return `${key} must be a boolean`;
  }
  for (const key of PROFILE_INT_FIELDS) {
    Iif (key in updates && (typeof updates[key] !== 'number' || !Number.isInteger(updates[key])))
      return `${key} must be an integer`;
  }
  for (const key of ['dndStartHour', 'dndEndHour']) {
    Iif (key in updates && (updates[key] < 0 || updates[key] > 23))
      return `${key} must be between 0 and 23`;
  }
  for (const key of ['dndStartMinute', 'dndEndMinute']) {
    Iif (key in updates && (updates[key] < 0 || updates[key] > 59))
      return `${key} must be between 0 and 59`;
  }
  return null;
}
 
// ═══════════════════════════════════════════════════════════════════
// PATCH /api/users/:uniqueId — Update user profile
// ═══════════════════════════════════════════════════════════════════
 
router.patch('/users/:uniqueId', async (req, res) => {
  try {
    if (requireOwner(req, res)) return;
 
    const body = req.body;
    Iif (!body) return res.status(400).json({ error: 'Invalid JSON body' });
 
    const allowedFields = [
      'displayName',
      'description',
      'nationality',
      'profilePhotoUrl',
      'coverPhotoUrl',
      'pmPrivacy',
      'pmNotificationsEnabled',
      'pmSoundEnabled',
      'pmShowTimestamps',
      'pmShowDateSeparators',
      'pmNotificationPreview',
      'hideFollowing',
      'hideOnlineStatus',
      'hideAge',
      'selfDestructAlertEnabled',
      'minGiftAnimationValue',
      'dndEnabled',
      'dndStartHour',
      'dndStartMinute',
      'dndEndHour',
      'dndEndMinute',
      'acceptedLegalVersion',
      'currentRoomId',
      'lastRoomName',
      'language',
    ];
 
    const updates = {};
    for (const key of allowedFields) {
      if (key in body) updates[key] = body[key];
    }
 
    if (Object.keys(updates).length === 0) {
      return res.status(400).json({ error: 'No valid fields to update' });
    }
 
    // Validate field value types and lengths
    const validationError = validateProfileUpdates(updates);
    Iif (validationError) return res.status(400).json({ error: validationError });
 
    // GDPR consent audit trail — store acceptance timestamp
    Iif (updates.acceptedLegalVersion !== undefined) {
      updates.legalAcceptedAt = Date.now();
    }
 
    log.info('users', 'Updating profile', {
      uniqueId: req.params.uniqueId,
      fields: Object.keys(updates),
    });
    await db.doc(`users/${req.params.uniqueId}`).update(updates);
 
    res.json({ success: true });
  } catch (err) {
    log.error('users', 'PATCH /users/:uniqueId failed', {
      uniqueId: req.params.uniqueId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ═══════════════════════════════════════════════════════════════════
// POST /api/users/:uniqueId/link-provider — Link additional provider
// ═══════════════════════════════════════════════════════════════════
 
router.post('/users/:uniqueId/link-provider', async (req, res) => {
  try {
    if (requireOwner(req, res)) return;
 
    const { provider, identifier } = req.body || {};
    if (!provider) return res.status(400).json({ error: 'provider required' });
    if (!identifier) return res.status(400).json({ error: 'identifier required' });
    Iif (!VALID_PROVIDERS.includes(provider)) {
      return res
        .status(400)
        .json({ error: `Invalid provider. Must be one of: ${VALID_PROVIDERS.join(', ')}` });
    }
 
    const uniqueId = Number(req.params.uniqueId);
    const identityDocId = `${provider}:${identifier}`;
 
    // Load user doc + identity map entry in parallel
    const [user, existingIdentity] = await Promise.all([
      getDoc(`users/${uniqueId}`),
      getDoc(`identityMap/${identityDocId}`),
    ]);
 
    Iif (!user) return res.status(404).json({ error: 'User not found' });
 
    // Check if identity is already claimed
    if (existingIdentity && existingIdentity.uniqueId !== uniqueId) {
      return res.status(409).json({ error: 'This identity is already linked to another account' });
    }
 
    if (existingIdentity && existingIdentity.unlinked) {
      // Re-linking own deactivated identity
      const timestamp = now();
      await db
        .doc(`identityMap/${identityDocId}`)
        .update({ unlinked: false, unlinkedAt: null, linkedAt: timestamp });
 
      const providers = (user.providers || []).map((p) =>
        p.type === provider && p.identifier === identifier
          ? { ...p, active: true, linkedAt: timestamp, unlinkedAt: undefined }
          : p,
      );
      await db.doc(`users/${uniqueId}`).update({ providers });
 
      log.info('users', 'Provider re-linked', {
        uniqueId,
        provider,
        identifier: identifier.includes('@') ? `***@${identifier.split('@')[1]}` : '***',
      });
      return res.json({ success: true, relinked: true });
    }
 
    Iif (existingIdentity) {
      // Already active — no-op
      return res.json({ success: true, alreadyLinked: true });
    }
 
    // Check provider count limit
    const existingOfType = (user.providers || []).filter((p) => p.type === provider && p.active);
    if (existingOfType.length >= MAX_IDENTIFIERS_PER_PROVIDER) {
      return res
        .status(409)
        .json({ error: 'Unable to link this account. Please contact support for assistance.' });
    }
 
    const timestamp = now();
 
    // Create identity map entry
    await db.doc(`identityMap/${identityDocId}`).set({
      uniqueId,
      provider,
      identifier,
      linkedAt: timestamp,
      unlinked: false,
      unlinkedAt: null,
    });
 
    // Update providers array
    const providers = [
      ...(user.providers || []),
      { type: provider, identifier, active: true, linkedAt: timestamp },
    ];
    await db.doc(`users/${uniqueId}`).update({ providers });
 
    log.info('users', 'Provider linked', {
      uniqueId,
      provider,
      identifier: identifier.includes('@') ? `***@${identifier.split('@')[1]}` : '***',
    });
    res.json({ success: true });
  } catch (err) {
    log.error('users', 'Link provider failed', {
      uniqueId: req.params.uniqueId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ═══════════════════════════════════════════════════════════════════
// DELETE /api/users/:uniqueId/link-provider — Soft-remove provider
// ═══════════════════════════════════════════════════════════════════
 
router.delete('/users/:uniqueId/link-provider', async (req, res) => {
  try {
    if (requireOwner(req, res)) return;
 
    const { provider, identifier } = req.body || {};
    Iif (!provider) return res.status(400).json({ error: 'provider required' });
    Iif (!identifier) return res.status(400).json({ error: 'identifier required' });
 
    const uniqueId = Number(req.params.uniqueId);
    const identityDocId = `${provider}:${identifier}`;
 
    // Load user doc + identity map entry
    const [user, identity] = await Promise.all([
      getDoc(`users/${uniqueId}`),
      getDoc(`identityMap/${identityDocId}`),
    ]);
 
    Iif (!user) return res.status(404).json({ error: 'User not found' });
    if (!identity) return res.status(404).json({ error: 'Identity not found' });
 
    // Verify identity belongs to this user
    if (identity.uniqueId !== uniqueId) {
      return res.status(403).json({ error: 'Identity does not belong to this user' });
    }
 
    // Check at least 2 active providers remain
    const activeProviders = (user.providers || []).filter((p) => p.active);
    if (activeProviders.length < 2) {
      return res.status(400).json({
        error: 'Cannot unlink your only active provider. At least one provider must remain linked.',
      });
    }
 
    const timestamp = now();
 
    // Soft-remove identity map entry
    await db.doc(`identityMap/${identityDocId}`).update({
      unlinked: true,
      unlinkedAt: timestamp,
    });
 
    // Update providers array — set active=false + unlinkedAt
    const providers = (user.providers || []).map((p) =>
      p.type === provider && p.identifier === identifier
        ? { ...p, active: false, unlinkedAt: timestamp }
        : p,
    );
    await db.doc(`users/${uniqueId}`).update({ providers });
 
    log.info('users', 'Provider unlinked', {
      uniqueId,
      provider,
      identifier: identifier.includes('@') ? `***@${identifier.split('@')[1]}` : '***',
    });
    res.json({ success: true });
  } catch (err) {
    log.error('users', 'Unlink provider failed', {
      uniqueId: req.params.uniqueId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ═══════════════════════════════════════════════════════════════════
// POST /api/users/:uniqueId/appeal — Suspension appeal
// ═══════════════════════════════════════════════════════════════════
 
router.post('/users/:uniqueId/appeal', async (req, res) => {
  try {
    if (requireOwner(req, res)) return;
 
    const body = req.body;
    if (!body?.appealText) return res.status(400).json({ error: 'appealText required' });
    if (typeof body.appealText !== 'string' || body.appealText.length > 500) {
      return res
        .status(400)
        .json({ error: 'appealText must be a string of at most 500 characters' });
    }
 
    const uniqueId = req.params.uniqueId;
 
    // Idempotency check: if a pending appeal already exists, reject
    // with 409. Without this, a user could spam the endpoint, creating
    // unbounded suspensionAppeals docs (Spark quota burn) and admin
    // noise. Audit H2 (Phase 2A).
    const userSnap = await db.doc(`users/${uniqueId}`).get();
    Eif (userSnap.exists) {
      const userData = userSnap.data();
      const currentStatus = userData.suspensionAppealStatus;
      if (currentStatus === 'pending') {
        return res.status(409).json({ error: 'Appeal already pending' });
      }
    }
 
    log.info('users', 'Suspension appeal submitted', { uniqueId });
 
    await Promise.all([
      db.doc(`suspensionAppeals/${generateId()}`).set(
        {
          uniqueId,
          appealText: body.appealText,
          status: 'pending',
          createdAt: now(),
        },
        { merge: true },
      ),
      db.doc(`users/${uniqueId}`).update({
        suspensionAppealStatus: 'pending',
      }),
    ]);
 
    res.json({ success: true });
  } catch (err) {
    log.error('users', 'Suspension appeal failed', {
      uniqueId: req.params.uniqueId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ═══════════════════════════════════════════════════════════════════
// POST /api/users/:uniqueId/lift-suspension — Lift expired suspension
// ═══════════════════════════════════════════════════════════════════
 
router.post('/users/:uniqueId/lift-suspension', async (req, res) => {
  try {
    if (requireOwner(req, res)) return;
 
    const uniqueId = req.params.uniqueId;
    const user = await getDoc(`users/${uniqueId}`);
    const isSuspended = user?.isSuspended ?? user?.is_suspended ?? false;
    if (!user || !isSuspended) {
      return res.status(400).json({ error: 'User is not suspended' });
    }
 
    const suspensionEndDate = user.suspensionEndDate ?? user.suspension_end_date ?? null;
    if (suspensionEndDate && suspensionEndDate > now()) {
      return res.status(400).json({ error: 'Suspension has not expired yet' });
    }
 
    log.info('users', 'Lifting expired suspension', { uniqueId });
 
    await db.doc(`users/${uniqueId}`).update({
      isSuspended: false,
      suspensionReason: null,
      suspensionEndDate: null,
      suspensionCanAppeal: true,
      suspensionAppealStatus: null,
      suspendedBy: null,
    });
 
    clearSuspensionCache(Number(uniqueId));
 
    res.json({ success: true });
  } catch (err) {
    log.error('users', 'Lift suspension failed', {
      uniqueId: req.params.uniqueId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ═══════════════════════════════════════════════════════════════════
// POST /api/users/:uniqueId/follow — Follow a user
// ═══════════════════════════════════════════════════════════════════
 
router.post('/users/:uniqueId/follow', async (req, res) => {
  try {
    const body = req.body;
    const rawTargetId = body?.targetUserId;
    Iif (!rawTargetId) return res.status(400).json({ error: 'targetUserId required' });
    if (requireOwner(req, res)) return;
 
    // Strict integer validation. Pre-fix used Number(targetId) which
    // turns 'evil../path' into NaN and stuffs NaN into followingIds via
    // arrayUnion(NaN). NaN poisoning corrupts every subsequent array
    // operation against the field. Audit H3 (Phase 2A).
    const targetId = Number.parseInt(String(rawTargetId), 10);
    if (!Number.isInteger(targetId) || targetId <= 0) {
      return res.status(400).json({ error: 'targetUserId must be a positive integer' });
    }
    if (String(targetId) !== String(rawTargetId).trim()) {
      // Reject inputs like '123abc' that parseInt would silently
      // truncate to 123 — strict round-trip equality.
      return res.status(400).json({ error: 'targetUserId must be a positive integer' });
    }
 
    const uniqueId = Number(req.params.uniqueId);
    Iif (uniqueId === targetId) {
      return res.status(400).json({ error: 'Cannot follow yourself' });
    }
 
    // Verify target user exists + UK OSA #17 PR 4 cross-cohort gate.
    // requireSameCohort returns 404 with `{ error: 'Not found' }` for
    // both missing-target AND cross-cohort cases (existence-hiding).
    const targetSnap = await db.doc(`users/${targetId}`).get();
    if (
      await requireSameCohort(req, res, targetId, () =>
        targetSnap.exists ? targetSnap.data() : null,
      )
    ) {
      return;
    }
 
    const batch = db.batch();
    batch.update(db.doc(`users/${uniqueId}`), {
      followingIds: FieldValue.arrayUnion(targetId),
    });
    batch.update(db.doc(`users/${targetId}`), {
      followerIds: FieldValue.arrayUnion(uniqueId),
    });
    await batch.commit();
    log.info('users', 'User followed', { uniqueId, targetUserId: targetId });
 
    res.json({ success: true });
  } catch (err) {
    log.error('users', 'Follow failed', {
      uniqueId: req.params.uniqueId,
      targetUserId: req.body?.targetUserId,
      error: err.message,
    });
    res.status(500).json({ error: 'Failed to follow user' });
  }
});
 
// ═══════════════════════════════════════════════════════════════════
// POST /api/users/:uniqueId/unfollow — Unfollow a user
// ═══════════════════════════════════════════════════════════════════
 
router.post('/users/:uniqueId/unfollow', async (req, res) => {
  try {
    const body = req.body;
    const rawTargetId = body?.targetUserId;
    if (!rawTargetId) return res.status(400).json({ error: 'targetUserId required' });
    if (requireOwner(req, res)) return;
 
    // Strict integer validation (mirrors follow handler — Phase 2A
    // audit H3). `Number.parseInt('123abc', 10) === 123` silently
    // truncates, then arrayRemove(123) poisons followingIds.
    const targetId = Number.parseInt(String(rawTargetId), 10);
    Iif (!Number.isInteger(targetId) || targetId <= 0) {
      return res.status(400).json({ error: 'targetUserId must be a positive integer' });
    }
    if (String(targetId) !== String(rawTargetId).trim()) {
      return res.status(400).json({ error: 'targetUserId must be a positive integer' });
    }
 
    // UK OSA #17 PR 4 — cross-cohort unfollow returns 404 (existence-hiding).
    // Even though PR 6 migration revokes cross-cohort follows server-side,
    // a stale client retry must not leak existence of the cross-cohort user.
    if (
      await requireSameCohort(req, res, targetId, async () => {
        const snap = await db.doc(`users/${Number(targetId)}`).get();
        return snap.exists ? snap.data() : null;
      })
    ) {
      return;
    }
 
    const uniqueId = req.params.uniqueId;
    const batch = db.batch();
    batch.update(db.doc(`users/${uniqueId}`), {
      followingIds: FieldValue.arrayRemove(Number(targetId)),
    });
    batch.update(db.doc(`users/${targetId}`), {
      followerIds: FieldValue.arrayRemove(Number(uniqueId)),
    });
    await batch.commit();
    log.info('users', 'User unfollowed', { uniqueId, targetUserId: targetId });
 
    res.json({ success: true });
  } catch (err) {
    log.error('users', 'Unfollow failed', {
      uniqueId: req.params.uniqueId,
      targetUserId: req.body?.targetUserId,
      error: err.message,
    });
    res.status(500).json({ error: 'Failed to unfollow user' });
  }
});
 
// ═══════════════════════════════════════════════════════════════════
// POST /api/users/:uniqueId/remove-follower — Remove a follower
// ═══════════════════════════════════════════════════════════════════
 
router.post('/users/:uniqueId/remove-follower', async (req, res) => {
  try {
    const body = req.body;
    const rawFollowerId = body?.followerUserId;
    if (!rawFollowerId) return res.status(400).json({ error: 'followerUserId required' });
    if (requireOwner(req, res)) return;
 
    // Strict integer validation — same NaN-poisoning defence as follow.
    const followerId = Number.parseInt(String(rawFollowerId), 10);
    Iif (!Number.isInteger(followerId) || followerId <= 0) {
      return res.status(400).json({ error: 'followerUserId must be a positive integer' });
    }
    if (String(followerId) !== String(rawFollowerId).trim()) {
      return res.status(400).json({ error: 'followerUserId must be a positive integer' });
    }
 
    // UK OSA #17 PR 4 — cross-cohort remove-follower returns 404
    // (existence-hiding); mirrors unfollow.
    if (
      await requireSameCohort(req, res, followerId, async () => {
        const snap = await db.doc(`users/${Number(followerId)}`).get();
        return snap.exists ? snap.data() : null;
      })
    ) {
      return;
    }
 
    const uniqueId = req.params.uniqueId;
    const batch = db.batch();
    batch.update(db.doc(`users/${uniqueId}`), {
      followerIds: FieldValue.arrayRemove(Number(followerId)),
    });
    batch.update(db.doc(`users/${followerId}`), {
      followingIds: FieldValue.arrayRemove(Number(uniqueId)),
    });
    await batch.commit();
    log.info('users', 'Follower removed', { uniqueId, followerUserId: followerId });
 
    res.json({ success: true });
  } catch (err) {
    log.error('users', 'Remove follower failed', {
      uniqueId: req.params.uniqueId,
      followerUserId: req.body?.followerUserId,
      error: err.message,
    });
    res.status(500).json({ error: 'Failed to remove follower' });
  }
});
 
// ═══════════════════════════════════════════════════════════════════
// POST /api/users/:uniqueId/record-visit — Record profile visit
// ═══════════════════════════════════════════════════════════════════
 
router.post('/users/:uniqueId/record-visit', async (req, res) => {
  try {
    const body = req.body;
    const visitorId = body?.visitorId;
    if (!visitorId) return res.status(400).json({ error: 'visitorId required' });
    // visitorId must match caller's uniqueId (string comparison since param is string)
    if (String(req.auth.uniqueId) !== String(visitorId)) {
      return res.status(403).json({ error: 'Forbidden' });
    }
    if (req.params.uniqueId === visitorId) return res.json({ success: true }); // don't stalk yourself
 
    const profileUniqueId = req.params.uniqueId;
 
    // C7: blocked viewers must not tick the stalker counter on the
    // target's profile (otherwise blocking is observably useless —
    // the blocker keeps getting "X new visitors" notifications driven
    // by a user they've already chosen to disengage from). Return 200
    // with success:true so the client treats the call as completed,
    // avoiding a retry loop or a UI signal that reveals block state.
    const targetUser = await getDoc(`users/${profileUniqueId}`);
 
    // UK OSA #17 PR 4 cross-cohort gate. Same guard-pattern as
    // requireOwner / requireAdmin: returns true when it has already
    // sent the response (404 existence-hiding), so caller returns.
    const blocked = await requireSameCohort(req, res, profileUniqueId, () => targetUser);
    if (blocked) return;
 
    if (viewerIsBlocked(visitorId, targetUser)) {
      return res.json({ success: true, recorded: false });
    }
 
    const stalkerPath = `users/${profileUniqueId}/stalkers/${visitorId}`;
    const existing = await getDoc(stalkerPath);
    const timestamp = now();
 
    if (existing) {
      const batch = db.batch();
      batch.update(db.doc(stalkerPath), {
        lastVisitedAt: timestamp,
        visitCount: (existing.visitCount || 1) + 1,
      });
      batch.update(db.doc(`users/${profileUniqueId}`), {
        newStalkerCount: FieldValue.increment(1),
      });
      await batch.commit();
    } else {
      const batch = db.batch();
      batch.set(
        db.doc(stalkerPath),
        {
          visitorId,
          lastVisitedAt: timestamp,
          firstVisitedAt: timestamp,
          visitCount: 1,
        },
        { merge: true },
      );
      batch.update(db.doc(`users/${profileUniqueId}`), {
        stalkerCount: FieldValue.increment(1),
        newStalkerCount: FieldValue.increment(1),
      });
      await batch.commit();
    }
 
    res.json({ success: true });
  } catch (err) {
    log.error('users', 'Record visit failed', {
      profileUniqueId: req.params.uniqueId,
      visitorId: req.body?.visitorId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
/** Send email and push notification for scheduled account deletion. */
async function sendDeletionNotifications(user, executeAt) {
  const deleteDate = new Date(executeAt).toISOString().split('T')[0];
  if (user.email) {
    try {
      const template = buildDeletionScheduledEmail(deleteDate);
      await sendEmail(user.email, template.subject, template.html);
    } catch (emailErr) {
      log.error('users', 'Failed to send deletion email', { error: emailErr.message });
    }
  }
  if (user.fcmTokens && user.fcmTokens.length > 0) {
    try {
      await sendFcmToTokens(user.fcmTokens, {
        notification: {
          title: 'Account Deletion Scheduled',
          body: `Your account will be deleted on ${deleteDate}. Sign in to cancel.`,
        },
      });
    } catch (fcmErr) {
      log.error('users', 'Failed to send deletion push', { error: fcmErr.message });
    }
  }
}
 
// ═══════════════════════════════════════════════════════════════════
// POST /api/users/:uniqueId/delete — Schedule account deletion
// ═══════════════════════════════════════════════════════════════════
 
router.post('/users/:uniqueId/delete', async (req, res) => {
  try {
    if (requireOwner(req, res)) return;
 
    const uniqueId = req.params.uniqueId;
    const { pin } = req.body || {};
 
    // Fetch user
    const userSnap = await db.doc(`users/${uniqueId}`).get();
    if (!userSnap.exists) {
      return res.status(404).json({ error: 'User not found' });
    }
    const user = userSnap.data();
 
    // Check if already scheduled
    if (user.deletionScheduledAt) {
      return res.status(409).json({ error: 'Deletion already scheduled' });
    }
 
    // Verify identity: PIN required
    if (!pin) {
      return res.status(400).json({ error: 'PIN verification required' });
    }
 
    // Length-validate PIN BEFORE bcrypt.compare. Without this, a
    // 1MB-string PIN (allowed by express.json limit) would block the
    // Node event loop for hundreds of ms — single-request DoS. Audit
    // H4 (Phase 2A). PINs are app-side 4-digit codes; allowing 4-16
    // chars covers any future format expansion (alphanumeric backup
    // codes, etc.) without exposing the bcrypt-DoS surface.
    if (typeof pin !== 'string' || pin.length < 4 || pin.length > 16) {
      log.warn('users', 'PIN length validation rejected', {
        uniqueId,
        pinType: typeof pin,
        pinLength: typeof pin === 'string' ? pin.length : null,
      });
      return res.status(400).json({ error: 'PIN must be a string of 4-16 characters' });
    }
 
    if (!user.pinHash) {
      return res.status(400).json({ error: 'No PIN set for this account' });
    }
    const isValid = await bcrypt.compare(pin, user.pinHash);
    if (!isValid) {
      return res.status(401).json({ error: 'Wrong PIN' });
    }
 
    // Get grace period from config
    const configSnap = await db.doc('config/app').get();
    const graceDays = configSnap.exists
      ? configSnap.data().accountDeletionGracePeriodDays || 30
      : 30;
 
    const timestamp = now();
    const executeAt = timestamp + graceDays * 86400000;
 
    // Set deletion fields + clear room
    const updates = {
      deletionScheduledAt: timestamp,
      deletionReason: 'self',
      deletionExecuteAt: executeAt,
      currentRoomId: null,
    };
    await db.doc(`users/${uniqueId}`).update(updates);
 
    // Revoke refresh tokens (sign out all devices)
    try {
      await auth.revokeRefreshTokens(user.firebaseUid);
    } catch (revokeErr) {
      log.error('users', 'Failed to revoke refresh tokens', { error: revokeErr.message });
    }
 
    // Send deletion notifications (best-effort)
    await sendDeletionNotifications(user, executeAt);
 
    // Audit log
    await db.doc(`adminAuditLog/${generateId()}`).set({
      action: 'ACCOUNT_DELETION_SCHEDULED',
      targetUserId: uniqueId,
      triggeredBy: 'self',
      reason: 'self',
      createdAt: timestamp,
    });
 
    log.info('users', 'Account deletion scheduled', { uniqueId, executeAt });
    res.json({ success: true, deleteAt: executeAt });
  } catch (err) {
    log.error('users', 'Failed to schedule account deletion', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ═══════════════════════════════════════════════════════════════════
// POST /api/users/:uniqueId/cancel-delete — Cancel scheduled deletion
// ═══════════════════════════════════════════════════════════════════
 
router.post('/users/:uniqueId/cancel-delete', async (req, res) => {
  try {
    if (requireOwner(req, res)) return;
 
    const uniqueId = req.params.uniqueId;
 
    const userSnap = await db.doc(`users/${uniqueId}`).get();
    if (!userSnap.exists) {
      return res.status(404).json({ error: 'User not found' });
    }
    const user = userSnap.data();
 
    if (!user.deletionScheduledAt) {
      return res.status(404).json({ error: 'No deletion scheduled' });
    }
 
    // Admin-initiated deletions cannot be cancelled by the user
    if (user.deletionReason === 'admin') {
      return res
        .status(403)
        .json({ error: 'Admin-initiated deletion cannot be cancelled by the user' });
    }
 
    // Check if deletion already executed
    if (user.deletionExecuteAt && user.deletionExecuteAt <= now()) {
      return res.status(410).json({ error: 'Deletion has already been executed' });
    }
 
    await db.doc(`users/${uniqueId}`).update({
      deletionScheduledAt: null,
      deletionReason: null,
      deletionExecuteAt: null,
    });
 
    // Audit log
    await db.doc(`adminAuditLog/${generateId()}`).set({
      action: 'ACCOUNT_DELETION_CANCELLED',
      targetUserId: uniqueId,
      triggeredBy: 'self',
      createdAt: now(),
    });
 
    log.info('users', 'Account deletion cancelled', { uniqueId });
    res.json({ success: true });
  } catch (err) {
    log.error('users', 'Failed to cancel account deletion', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ═══════════════════════════════════════════════════════════════════
// GET /api/users/:uniqueId/deletion-status — Check deletion status
// ═══════════════════════════════════════════════════════════════════
 
router.get('/users/:uniqueId/deletion-status', async (req, res) => {
  try {
    if (requireOwner(req, res)) return;
 
    const uniqueId = req.params.uniqueId;
 
    const userSnap = await db.doc(`users/${uniqueId}`).get();
    if (!userSnap.exists) {
      return res.status(404).json({ error: 'User not found' });
    }
    const user = userSnap.data();
 
    if (!user.deletionScheduledAt) {
      return res.json({
        scheduled: false,
        scheduledAt: null,
        executeAt: null,
        reason: null,
        daysRemaining: null,
      });
    }
 
    const msRemaining = user.deletionExecuteAt - now();
    const daysRemaining = Math.max(0, Math.ceil(msRemaining / 86400000));
 
    res.json({
      scheduled: true,
      scheduledAt: user.deletionScheduledAt,
      executeAt: user.deletionExecuteAt,
      reason: user.deletionReason,
      daysRemaining,
    });
  } catch (err) {
    log.error('users', 'Failed to get deletion status', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
module.exports = router;