All files / src/routes admin-age-verification.js

86.91% Statements 206/237
79.23% Branches 103/130
100% Functions 17/17
93.42% Lines 199/213

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                                                                                                1x 1x           1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 33x 30x   1x     44x 44x 44x 44x 44x           44x       18x 18x 18x 4x   14x         14x         18x 18x 15x   3x         3x               18x 18x 17x   1x       1x         15x         1x 1x 1x 1x         2x 1x                                       1x 3x 3x 3x 3x 3x 3x 1x   2x 2x       1x   1x 1x                           1x 8x 8x 8x 8x                 8x 8x 8x 8x 8x 7x 7x 1x 1x   6x   6x             6x         6x     8x 7x 6x   6x 6x         6x         6x   6x                 1x 3x 3x 3x 3x 3x 3x 1x       2x 2x 2x 2x 2x 2x 2x 1x 1x   1x   1x               1x     2x 2x 1x   1x 1x         1x       1x   1x                 1x 15x 15x 15x 15x 15x 15x 15x 1x             14x 14x   2x   12x 1x         11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x       11x   11x 11x 11x 11x 11x 11x                       11x 11x 11x 7x 7x 7x 7x 4x   7x 7x 4x 4x           7x 7x 3x 3x 2x   2x   2x 2x   7x 1x 1x 1x   1x   1x 1x       11x                 11x                                   11x 3x 2x 2x       1x 1x         11x       11x 11x   11x     11x 11x 11x                               11x 11x 11x 11x 9x   2x 2x 2x                 11x 11x             11x               11x         11x                                     1x  
/**
 * Admin-side age-verification routes (PR 4b/14).
 *
 *   GET  /api/admin/age-verification/pending
 *     List all pending submissions (oldest first).
 *
 *   POST /api/admin/age-verification/:id/approve
 *     Body: { reason: string }
 *     Marks the submission approved. Flips `ageVerified=true` on the
 *     target user, records `ageVerifiedAt` + `ageVerificationMethod`.
 *     Best-effort: deletes R2 ID image and writes audit-log entry.
 *
 *   POST /api/admin/age-verification/:id/reject
 *     Body: { reason: string }
 *     Marks the submission rejected. User stays unverified. Image is
 *     still deleted (privacy: spec required image destruction on
 *     decision regardless of outcome). Writes audit entry.
 *
 *   POST /api/admin/age-verification/:id/modify-dob
 *     Body: { newDob: number (ms), reason: string }
 *     Updates `users/<uid>.dateOfBirth` to the new value. If the new
 *     DOB makes the user 18+, behaves like approve. If <18, the
 *     account is reverted to unverified — they age in. PMs lock-out
 *     is downstream (PR 11 migration). DOB plausibility (1900 ≤ dob
 *     ≤ now) is validated PRE-transaction; an implausible DOB cannot
 *     get past the user-doc mutation only to fail at the audit-log
 *     stage.
 *
 * Concurrency: each decision endpoint uses `db.runTransaction(...)`
 * to atomically read submission + user docs and write both updates.
 *
 * Partial-failure contract: the route returns success with explicit
 * `auditWritten` / `imageDeleted` flags when post-commit cleanup
 * partially fails. The Firestore decision is the source of truth;
 * a failed audit-log write or R2 deletion is logged for ops sweep
 * and surfaced to the admin UI via the response flags rather than
 * masked as a 500. Crash-window between the transaction commit and
 * the post-commit cleanup leaves the decision recorded with no
 * audit / a leaked image — see follow-up task for a reconciliation
 * job that detects gaps.
 *
 * Submission-doc lifecycle: after a decision commits, the
 * `r2Key` field is set to null in the same transaction so a future
 * reader (admin audit-trail tab) doesn't see a stale reference to a
 * deleted object. The original key is preserved in the audit-log
 * entry for compliance traceability.
 */
 
const express = require('express');
const router = express.Router();
// FCM push helper (PR 10) — sends a data-only push to the user's
// stored fcmTokens after each decision so the Android service renders
// a local notification when the app is backgrounded. Best-effort —
// failures surface via the partial-failure response shape, not a 500.
 
const { db, auth, FieldValue } = require('../utils/firebase');
const r2 = require('../utils/r2');
const audit = require('../utils/age-verification-audit');
const systemPm = require('../utils/age-verification-system-pm');
const fcmPush = require('../utils/age-verification-fcm');
const { mintClaimsMerging, effectiveCohort } = require('../utils/firebase-claims');
const { now } = require('../utils/helpers');
const log = require('../utils/log');
const { requireAdmin } = require('../middleware/auth');
 
// Phase 2H finding #2 dedup: scope admin guard by path prefix.
const _adminGuardWrapper = async (req, res, next) => {
  if (await requireAdmin(req, res)) return;
  next();
};
router.use('/admin/age-verification', _adminGuardWrapper);
 
function isAtLeast18FromDob(dateOfBirthMs) {
  Iif (typeof dateOfBirthMs !== 'number' || !Number.isFinite(dateOfBirthMs)) return false;
  const today = new Date();
  const dob = new Date(dateOfBirthMs);
  let age = today.getUTCFullYear() - dob.getUTCFullYear();
  Iif (
    today.getUTCMonth() < dob.getUTCMonth() ||
    (today.getUTCMonth() === dob.getUTCMonth() && today.getUTCDate() < dob.getUTCDate())
  ) {
    age -= 1;
  }
  return age >= 18;
}
 
async function deleteImageBestEffort(r2Key, submissionId) {
  Iif (!r2Key) return true;
  try {
    await r2.deleteObject(r2Key);
    return true;
  } catch (err) {
    log.error('admin-age-verification', 'R2 image deletion failed', {
      submissionId,
      r2Key,
      error: err?.message,
    });
    return false;
  }
}
 
async function writeAuditBestEffort(action, submissionId, payload) {
  try {
    await action(db, payload);
    return true;
  } catch (err) {
    log.error('admin-age-verification', 'Audit-log write failed', {
      submissionId,
      payload,
      error: err?.message,
    });
    return false;
  }
}
 
async function sendPmBestEffort(action, submissionId, args) {
  // Same partial-failure shape as audit / R2 — a failed PM doesn't
  // roll back the decision. Surfaced via the response so the admin
  // UI can flag "decision committed, user not notified".
  try {
    await action(...args);
    return true;
  } catch (err) {
    log.error('admin-age-verification', 'System PM send failed', {
      submissionId,
      error: err?.message,
    });
    return false;
  }
}
 
function requireNonBlankReason(reason) {
  return typeof reason === 'string' && reason.trim().length > 0;
}
 
// ─── GET /pending ───────────────────────────────────────────────────
 
router.get('/admin/age-verification/pending', async (req, res) => {
  Iif (await requireAdmin(req, res)) return;
  try {
    const snap = await db
      .collection('ageVerificationSubmissions')
      .where('status', '==', 'pending')
      .orderBy('submittedAt', 'asc')
      .get();
    const submissions = snap.docs.map((d) => ({ id: d.id, ...d.data() }));
    return res.json({ submissions });
  } catch (err) {
    log.error('admin-age-verification', 'list pending failed', { error: err?.message });
    return res
      .status(500)
      .json({ error: 'Failed to list pending submissions', errorId: 'AGE_VERIF_LIST' });
  }
});
 
// ─── GET /:id/image-url ─────────────────────────────────────────────
//
// Returns a short-lived signed URL the admin browser can use to view
// the submitted ID image directly from R2. Stored privately; no
// long-lived URLs leave the API surface. 5-minute expiry mirrors the
// upload PUT URL.
//
// Returns 404 if the submission's r2Key is null — that happens after
// a decision commits (key is wiped post-decision; the image is also
// deleted from R2 best-effort).
 
router.get('/admin/age-verification/:id/image-url', async (req, res) => {
  Iif (await requireAdmin(req, res)) return;
  const { id } = req.params;
  try {
    const subRef = db.doc(`ageVerificationSubmissions/${id}`);
    const snap = await subRef.get();
    if (!snap.exists) {
      return res.status(404).json({ error: 'Submission not found' });
    }
    const data = snap.data();
    if (!data.r2Key) {
      // Post-decision: image has been deleted (best-effort) and key
      // wiped from the doc. Admin can still read the audit log for
      // compliance traceability.
      return res.status(404).json({ error: 'Image already removed' });
    }
    const url = await r2.getSignedGetUrl(data.r2Key, 300);
    return res.json({ url, expiresInSec: 300 });
  } catch (err) {
    log.error('admin-age-verification', 'image-url failed', {
      submissionId: id,
      error: err?.message,
    });
    return res
      .status(500)
      .json({ error: 'Failed to issue image URL', errorId: 'AGE_VERIF_IMAGE_URL' });
  }
});
 
// ─── POST /:id/approve ──────────────────────────────────────────────
 
router.post('/admin/age-verification/:id/approve', async (req, res) => {
  Iif (await requireAdmin(req, res)) return;
  const { id } = req.params;
  const errorId = 'AGE_VERIF_APPROVE';
  try {
    // Approve does NOT require a reason. Original spec only asked for
    // an admin justification on outcomes the user needs explained
    // (Reject / DOB-modified). Approve is the "everything is fine"
    // path; the audit log records WHO approved + WHEN, sufficient for
    // the compliance trail. (Question 1 from 2026-05-04 spec
    // follow-up — revisit if regulators ever ask for it.)
 
    let submission;
    let approved = false;
    await db.runTransaction(async (tx) => {
      const subRef = db.doc(`ageVerificationSubmissions/${id}`);
      const subSnap = await tx.get(subRef);
      if (!subSnap.exists) return;
      const data = subSnap.data();
      if (data.status !== 'pending') {
        submission = { ...data, _conflict: true };
        return;
      }
      submission = { ...data, id };
 
      tx.update(subRef, {
        status: 'approved',
        decisionAt: now(),
        decidedBy: req.auth.uniqueId,
        // r2Key tombstoned — original preserved in audit-log entry.
        r2Key: null,
      });
      tx.update(db.doc(`users/${data.userId}`), {
        ageVerified: true,
        ageVerifiedAt: now(),
        ageVerificationMethod: data.idMethod,
      });
      approved = true;
    });
 
    if (!submission) return res.status(404).json({ error: 'Submission not found' });
    if (submission._conflict) return res.status(409).json({ error: 'Submission already decided' });
    Iif (!approved) return res.status(500).json({ error: 'Approval did not commit', errorId });
 
    const imageDeleted = await deleteImageBestEffort(submission.r2Key, id);
    const auditWritten = await writeAuditBestEffort(audit.logVerificationApproved, id, {
      adminUid: req.auth.uniqueId,
      targetUserId: submission.userId,
      method: submission.idMethod,
    });
    const userNotified = await sendPmBestEffort(systemPm.sendAgeVerificationApprovedPm, id, [
      submission.userId,
      submission.idMethod,
    ]);
    // FCM push (PR 10) — best-effort, separate failure flag.
    const pushNotified = await fcmPush.sendAgeVerificationApprovedPush(submission.userId);
 
    return res.json({ ok: true, imageDeleted, auditWritten, userNotified, pushNotified });
  } catch (err) {
    log.error('admin-age-verification', `${errorId} failed`, { id, error: err?.message });
    return res.status(500).json({ error: 'Failed to approve submission', errorId });
  }
});
 
// ─── POST /:id/reject ───────────────────────────────────────────────
 
router.post('/admin/age-verification/:id/reject', async (req, res) => {
  Iif (await requireAdmin(req, res)) return;
  const { id } = req.params;
  const errorId = 'AGE_VERIF_REJECT';
  try {
    const reason = (req.body?.reason || '').toString();
    if (!requireNonBlankReason(reason)) {
      return res.status(400).json({ error: 'reason is required' });
    }
 
    let submission;
    let rejected = false;
    await db.runTransaction(async (tx) => {
      const subRef = db.doc(`ageVerificationSubmissions/${id}`);
      const subSnap = await tx.get(subRef);
      Iif (!subSnap.exists) return;
      const data = subSnap.data();
      if (data.status !== 'pending') {
        submission = { ...data, _conflict: true };
        return;
      }
      submission = { ...data, id };
 
      tx.update(subRef, {
        status: 'rejected',
        decisionAt: now(),
        decidedBy: req.auth.uniqueId,
        decisionReason: reason,
        r2Key: null,
      });
      // User doc intentionally NOT touched — they stay unverified.
      rejected = true;
    });
 
    Iif (!submission) return res.status(404).json({ error: 'Submission not found' });
    if (submission._conflict) return res.status(409).json({ error: 'Submission already decided' });
    Iif (!rejected) return res.status(500).json({ error: 'Rejection did not commit', errorId });
 
    const imageDeleted = await deleteImageBestEffort(submission.r2Key, id);
    const auditWritten = await writeAuditBestEffort(audit.logVerificationRejected, id, {
      adminUid: req.auth.uniqueId,
      targetUserId: submission.userId,
      reason,
    });
    const userNotified = await sendPmBestEffort(systemPm.sendAgeVerificationRejectedPm, id, [
      submission.userId,
      reason,
    ]);
    const pushNotified = await fcmPush.sendAgeVerificationRejectedPush(submission.userId, reason);
 
    return res.json({ ok: true, imageDeleted, auditWritten, userNotified, pushNotified });
  } catch (err) {
    log.error('admin-age-verification', `${errorId} failed`, { id, error: err?.message });
    return res.status(500).json({ error: 'Failed to reject submission', errorId });
  }
});
 
// ─── POST /:id/modify-dob ───────────────────────────────────────────
 
router.post('/admin/age-verification/:id/modify-dob', async (req, res) => {
  Iif (await requireAdmin(req, res)) return;
  const { id } = req.params;
  const errorId = 'AGE_VERIF_MODIFY_DOB';
  try {
    const newDob = req.body?.newDob;
    const reason = (req.body?.reason || '').toString();
    if (typeof newDob !== 'number' || !Number.isFinite(newDob)) {
      return res.status(400).json({ error: 'newDob is required (ms epoch)' });
    }
    // Plausibility: 1900 <= newDob <= now. Throws if out of range.
    // Validated up-front so an implausible DOB never reaches the user
    // doc — without this, the transaction would commit the bogus
    // value, then the audit-log helper's bounds check would throw and
    // the route would 500 with the mutation already persisted.
    try {
      audit.requirePlausibleDob(newDob, 'newDob');
    } catch (err) {
      return res.status(400).json({ error: err.message });
    }
    if (!requireNonBlankReason(reason)) {
      return res.status(400).json({ error: 'reason is required' });
    }
 
    let submission;
    let oldDob;
    let committed = false;
    let targetUserData = null;
    let targetFirebaseUid = null;
    let newCohort = 'minor';
    let clearedEdgeCount = 0;
    await db.runTransaction(async (tx) => {
      const subRef = db.doc(`ageVerificationSubmissions/${id}`);
      const subSnap = await tx.get(subRef);
      Iif (!subSnap.exists) return;
      const data = subSnap.data();
      Iif (data.status !== 'pending') {
        submission = { ...data, _conflict: true };
        return;
      }
      submission = { ...data, id };
 
      const userRef = db.doc(`users/${data.userId}`);
      const userSnap = await tx.get(userRef);
      const userData = userSnap.exists ? userSnap.data() : null;
      oldDob = userData?.dateOfBirth ?? null;
      const verifiedNow = isAtLeast18FromDob(newDob);
      newCohort = verifiedNow ? 'adult' : 'minor';
 
      // UK OSA #17 PR 6 — runtime equivalent of migrate-segregation-
      // relationships.js. When a cohort flips (admin DOB modification can
      // take a user adult→minor or minor→adult), the user's existing
      // follow edges that are now cross-cohort MUST be cleared in the
      // same transaction as the cohort write. The one-shot migration
      // script only handles legacy data; without this runtime hook the
      // flip leaves cross-cohort edges live, which fails j19's OSA
      // invariant probe and would violate the same compliance contract
      // in prod. We batch all counterparty reads BEFORE any writes —
      // Firestore transactions forbid reads after writes.
      const oldCohort = userData?.cohort ?? null;
      const counterpartyEdges = [];
      if (oldCohort && oldCohort !== newCohort && userData) {
        const followingIds = Array.isArray(userData.followingIds) ? userData.followingIds : [];
        const followerIds = Array.isArray(userData.followerIds) ? userData.followerIds : [];
        const uniqueCounterparties = [...new Set([...followingIds, ...followerIds])];
        const counterpartySnaps = await Promise.all(
          uniqueCounterparties.map((counterpartyId) => tx.get(db.doc(`users/${counterpartyId}`))),
        );
        const cohortByCounterparty = new Map();
        counterpartySnaps.forEach((snap, idx) => {
          Eif (snap.exists) {
            cohortByCounterparty.set(uniqueCounterparties[idx], snap.data()?.cohort ?? null);
          }
        });
        // Exempt SHYTALK_OFFICIAL accounts: the migration script preserves
        // Officia's cross-cohort edges intentionally so system PMs can reach
        // users of any cohort. Apply the same exemption at runtime.
        const userIsOfficial = userData.userType === 'SHYTALK_OFFICIAL' || userData.isOfficial;
        for (const targetId of followingIds) {
          const c = cohortByCounterparty.get(targetId);
          if (!c || c === newCohort) continue;
          const targetSnap = counterpartySnaps[uniqueCounterparties.indexOf(targetId)];
          const targetIsOfficial =
            targetSnap?.exists &&
            (targetSnap.data()?.userType === 'SHYTALK_OFFICIAL' || targetSnap.data()?.isOfficial);
          Iif (userIsOfficial || targetIsOfficial) continue;
          counterpartyEdges.push({ direction: 'following', counterpartyId: targetId });
        }
        for (const sourceId of followerIds) {
          const c = cohortByCounterparty.get(sourceId);
          Iif (!c || c === newCohort) continue;
          const sourceSnap = counterpartySnaps[uniqueCounterparties.indexOf(sourceId)];
          const sourceIsOfficial =
            sourceSnap?.exists &&
            (sourceSnap.data()?.userType === 'SHYTALK_OFFICIAL' || sourceSnap.data()?.isOfficial);
          Iif (userIsOfficial || sourceIsOfficial) continue;
          counterpartyEdges.push({ direction: 'follower', counterpartyId: sourceId });
        }
      }
 
      tx.update(subRef, {
        status: 'dob_modified',
        decisionAt: now(),
        decidedBy: req.auth.uniqueId,
        decisionReason: reason,
        oldDob,
        newDob,
        r2Key: null,
      });
      tx.update(userRef, {
        dateOfBirth: newDob,
        ageVerified: verifiedNow,
        ageVerifiedAt: verifiedNow ? now() : null,
        ageVerificationMethod: verifiedNow ? data.idMethod : null,
        // PR 11 PM-lock side effect. New DOB <18 → lock the user out
        // of PMs (their list hides + counterparties see disabled
        // input). New DOB ≥18 → unlock. Same transaction so the
        // ageVerified flip and the lock state can never diverge.
        pmLocked: !verifiedNow,
        // UK OSA #17 PR 2: cohort follows the same predicate.
        // Same transaction so cohort + pmLocked can never diverge.
        cohort: newCohort,
      });
      // Cross-cohort edge cleanup writes — mirror the migration script's
      // both-sides arrayRemove pattern so neither side retains a dangling
      // reference (a one-sided clean leaves a phantom follower count on
      // the surviving side, which a cohort-segregation audit would flag).
      for (const edge of counterpartyEdges) {
        if (edge.direction === 'following') {
          tx.update(userRef, { followingIds: FieldValue.arrayRemove(edge.counterpartyId) });
          tx.update(db.doc(`users/${edge.counterpartyId}`), {
            followerIds: FieldValue.arrayRemove(userData.uniqueId),
          });
        } else {
          tx.update(userRef, { followerIds: FieldValue.arrayRemove(edge.counterpartyId) });
          tx.update(db.doc(`users/${edge.counterpartyId}`), {
            followingIds: FieldValue.arrayRemove(userData.uniqueId),
          });
        }
      }
      clearedEdgeCount = counterpartyEdges.length;
      // Capture for the post-commit claim mint. Effective-cohort
      // computation must see the NEW cohort but the EXISTING
      // override (admin cohortOverride survives a DOB change).
      targetUserData = userData ? { ...userData, cohort: newCohort } : { cohort: newCohort };
      targetFirebaseUid =
        userData && typeof userData.firebaseUid === 'string' ? userData.firebaseUid : null;
      committed = true;
    });
 
    Iif (!submission) return res.status(404).json({ error: 'Submission not found' });
    Iif (submission._conflict) return res.status(409).json({ error: 'Submission already decided' });
    Iif (!committed)
      return res.status(500).json({ error: 'DOB modification did not commit', errorId });
 
    // UK OSA #17 PR 2: claim mint after Firestore commits. No
    // forceTokenRefresh round-trip — the target user is not the
    // caller; the next sign-in's pm-lock-check round-trip catches
    // up. Partial-failure flag surfaced for admin UI alerting.
    //
    // Security defense (review MEDIUM #3): when the mint fails the
    // target user's JWT is stale relative to the new Firestore
    // cohort. For the DOB→minor case this means a now-minor user
    // can read adult-cohort data via the stale claim until ~1h of
    // auto-refresh closes the window. We revoke refresh tokens on
    // mint failure so the next ID-token request from the client
    // must re-authenticate — and re-authentication runs through
    // the sign-in mint, closing the gap immediately.
    let claimMinted = false;
    Eif (typeof targetFirebaseUid === 'string') {
      try {
        await mintClaimsMerging(targetFirebaseUid, { cohort: effectiveCohort(targetUserData) });
        claimMinted = true;
      } catch (_mintErr) {
        claimMinted = false;
        try {
          await auth.revokeRefreshTokens(targetFirebaseUid);
        } catch (_revokeErr) {
          // Best-effort defence in depth — if revoke also fails,
          // we've already surfaced claimMinted:false and the
          // ~1h JWT TTL is the worst-case staleness window.
        }
      }
    }
 
    const imageDeleted = await deleteImageBestEffort(submission.r2Key, id);
    const auditWritten = await writeAuditBestEffort(audit.logVerificationDobModified, id, {
      adminUid: req.auth.uniqueId,
      targetUserId: submission.userId,
      oldDob,
      newDob,
      reason,
    });
    const userNotified = await sendPmBestEffort(systemPm.sendAgeVerificationDobModifiedPm, id, [
      submission.userId,
      {
        ageVerified: isAtLeast18FromDob(newDob),
        method: submission.idMethod,
        reason,
      },
    ]);
    const pushNotified = await fcmPush.sendAgeVerificationDobModifiedPush(
      submission.userId,
      isAtLeast18FromDob(newDob),
    );
 
    return res.json({
      ok: true,
      ageVerified: isAtLeast18FromDob(newDob),
      imageDeleted,
      auditWritten,
      userNotified,
      pushNotified,
      claimMinted,
      // OSA #17 PR 6 runtime cleanup count — surfaced so the admin UI
      // can show the audit trail (e.g., "downgraded Hayato to minor;
      // cleared 2 cross-cohort follow edges").
      crossCohortEdgesCleared: clearedEdgeCount,
    });
  } catch (err) {
    log.error('admin-age-verification', `${errorId} failed`, { id, error: err?.message });
    return res.status(500).json({ error: 'Failed to modify DOB', errorId });
  }
});
 
module.exports = router;