All files / src/cron accountDeletion.js

87% Statements 221/254
84.44% Branches 76/90
100% Functions 26/26
86.44% Lines 204/236

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                    10x 10x 10x 10x 10x 10x 10x 10x 10x   10x 10x               221x 6x 6x 8x   6x           47x 27x 27x 27x               47x             47x 235x 235x 235x                 13x         1x     1x       1x   2x 1x   2x 1x   1x 2x                       47x       47x 47x 14x 14x 13x 10x 27x     1x     44x         1x       1x 1x 1x     1x         44x 44x       44x 2x 1x   1x                       44x 44x       44x 10x       44x       44x 10x                     44x 44x 44x 1x                 44x 44x 44x 132x 132x 132x 132x 132x 44x 44x                                                             44x 44x   44x 44x       44x 1x 1x 1x 1x         1x 1x           1x                 44x 44x 44x 44x 44x 3x 3x 2x 2x 2x 2x 1x   2x 2x           44x               44x 44x       44x 44x 44x 1x 1x 1x           1x 1x           44x               44x 44x               44x         44x       44x 44x 44x 44x 4x 4x 3x 3x 3x 3x           44x                     44x 44x       44x         44x 27x 27x 27x 27x 27x           44x 44x       44x 1x                             44x 44x 44x 220x 220x   44x               44x 44x       44x 2x                           44x 44x       44x               44x 44x   37x                 47x 47x 47x   47x 47x 47x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x     44x         44x                                                 44x             15x     15x             15x 15x 21x   21x 21x     21x   3x 3x         15x 15x 15x   15x 2x 2x   2x               2x 1x 1x         1x                   15x     3x       10x 10x 10x  
/**
 * Account deletion cron job.
 *
 * Runs daily at 03:00 UTC:
 * 1. Processes pending deletions past their execute date (hard delete)
 * 2. Schedules inactive accounts for deletion (if enabled)
 *
 * Limited to 10 accounts per run for Firestore quota awareness.
 */
 
const { db, auth, FieldValue } = require('../utils/firebase');
const { generateId, now } = require('../utils/helpers');
const { queryDocs } = require('../utils/firestore-helpers');
const { deleteTree } = require('../utils/delete-tree');
const { sendEmail } = require('../utils/email');
const { buildDeletionCompleteEmail } = require('../utils/email-templates');
const r2 = require('../utils/r2');
const log = require('../utils/log');
const crypto = require('node:crypto');
 
const AUDIT_HASH_SECRET = process.env.AUDIT_HASH_SECRET;
Iif (!AUDIT_HASH_SECRET && process.env.NODE_ENV === 'production') {
  log.error('cron', 'AUDIT_HASH_SECRET not set — audit log hashes will be insecure');
}
 
/**
 * Delete docs in batches of 500.
 */
async function batchDeletePaths(paths) {
  for (let i = 0; i < paths.length; i += 500) {
    const batch = db.batch();
    for (const path of paths.slice(i, i + 500)) {
      batch.delete(db.doc(path));
    }
    await batch.commit();
  }
}
 
/** Step 1: Send final email */
async function sendDeletionEmail(user, uniqueId) {
  if (!user.email) return;
  try {
    const template = buildDeletionCompleteEmail();
    await sendEmail(user.email, template.subject, template.html);
  } catch (err) {
    log.error('cron', 'Failed to send deletion complete email', { uniqueId, error: err.message });
  }
}
 
/** Step 2: Delete R2 storage */
async function deleteUserR2Storage(uniqueId) {
  const prefixes = [
    `profiles/${uniqueId}/`,
    `covers/${uniqueId}/`,
    `messages/${uniqueId}/`,
    `groups/${uniqueId}/`,
    `evidence/${uniqueId}/`,
  ];
  for (const prefix of prefixes) {
    try {
      const keys = await r2.listObjects(prefix);
      if (keys.length > 0) await r2.deleteObjects(keys);
    } catch (err) {
      log.error('cron', 'Failed to delete R2 prefix', { prefix, error: err.message });
    }
  }
}
 
/** Delete a 1-on-1 conversation and everything under it (SHY-0631). */
async function deleteOneOnOneConversation(convId) {
  return deleteTree(db, db.doc(`conversations/${convId}`));
}
 
/** Remove user from a group conversation. */
async function removeUserFromGroupConversation(convId, uniqueId) {
  await db.doc(`conversations/${convId}`).update({
    participantIds: FieldValue.arrayRemove(Number(uniqueId)),
  });
  const [userSettings, mutes] = await Promise.all([
    queryDocs(db.collection(`conversations/${convId}/userSettings`)),
    queryDocs(db.collection(`conversations/${convId}/mutes`)),
  ]);
  const toDelete = [
    ...userSettings
      .filter((s) => s.userId === String(uniqueId))
      .map((s) => `conversations/${convId}/userSettings/${s.id}`),
    ...mutes
      .filter((m) => m.id === String(uniqueId))
      .map((m) => `conversations/${convId}/mutes/${m.id}`),
  ];
  for (const path of toDelete) {
    await db.doc(path).delete();
  }
}
 
/**
 * Step 3: Cleanup conversations.
 *
 * Errors are not caught here (SHY-0631): they leave hardDeleteAccount before
 * step 8 deletes the user document, so the account stays due and the next
 * run deletes what is left.
 */
async function cleanupConversations(uniqueId) {
  const convSnap = await db
    .collection('conversations')
    .where('participantIds', 'array-contains', Number(uniqueId))
    .get();
  const deleted = {};
  for (const convDoc of convSnap.docs) {
    const participantCount = (convDoc.data().participantIds || []).length;
    if (participantCount <= 2) {
      const counts = await deleteOneOnOneConversation(convDoc.id);
      for (const [collection, n] of Object.entries(counts)) {
        deleted[collection] = (deleted[collection] || 0) + n;
      }
    } else {
      await removeUserFromGroupConversation(convDoc.id, uniqueId);
    }
  }
  log.info('cron', 'Conversation documents deleted', { uniqueId, deleted });
}
 
/** Delete a room and all its subcollections. */
async function deleteOwnedRoom(roomDocId) {
  const [messages, seatRequests] = await Promise.all([
    queryDocs(db.collection(`rooms/${roomDocId}/messages`)),
    queryDocs(db.collection(`rooms/${roomDocId}/seatRequests`)),
  ]);
  const allDocs = [
    ...messages.map((m) => `rooms/${roomDocId}/messages/${m.id}`),
    ...seatRequests.map((s) => `rooms/${roomDocId}/seatRequests/${s.id}`),
    `rooms/${roomDocId}`,
  ];
  await batchDeletePaths(allDocs);
}
 
/** Step 4: Cleanup rooms */
async function cleanupRooms(uniqueId) {
  try {
    const roomSnap = await db
      .collection('rooms')
      .where('participantIds', 'array-contains', Number(uniqueId))
      .get();
    for (const roomDoc of roomSnap.docs) {
      if (String(roomDoc.data().ownerId) === uniqueId) {
        await deleteOwnedRoom(roomDoc.id);
      } else {
        await db.doc(`rooms/${roomDoc.id}`).update({
          participantIds: FieldValue.arrayRemove(Number(uniqueId)),
        });
      }
    }
  } catch (err) {
    log.error('cron', 'Failed to cleanup rooms', { uniqueId, error: err.message });
  }
}
 
/** Step 5: Remove from follower/following arrays */
async function cleanupFollowerFollowing(uniqueId) {
  try {
    const followerSnap = await db
      .collection('users')
      .where('followerIds', 'array-contains', Number(uniqueId))
      .get();
    for (const doc of followerSnap.docs) {
      await db.doc(`users/${doc.id}`).update({
        followerIds: FieldValue.arrayRemove(Number(uniqueId)),
      });
    }
    const followingSnap = await db
      .collection('users')
      .where('followingIds', 'array-contains', Number(uniqueId))
      .get();
    for (const doc of followingSnap.docs) {
      await db.doc(`users/${doc.id}`).update({
        followingIds: FieldValue.arrayRemove(Number(uniqueId)),
      });
    }
  } catch (err) {
    log.error('cron', 'Failed to cleanup follower/following', { uniqueId, error: err.message });
  }
}
 
/** Step 5b: Gift rankings cleanup */
async function cleanupGiftRankings(uniqueId) {
  try {
    const rankSnap = await db.collection('giftRankings').where('userId', '==', uniqueId).get();
    for (const doc of rankSnap.docs) {
      await db.doc(`giftRankings/${doc.id}`).delete();
    }
  } catch (err) {
    log.error('cron', 'Failed to cleanup gift rankings', { uniqueId, error: err.message });
  }
}
 
/** Step 6: Reports & appeals */
async function cleanupReportsAndAppeals(uniqueId) {
  try {
    const collections = ['reports', 'reportsArchive', 'suspensionAppeals'];
    for (const col of collections) {
      const snap1 = await db.collection(col).where('reportedUserId', '==', uniqueId).get();
      for (const doc of snap1.docs) await db.doc(`${col}/${doc.id}`).delete();
      const snap2 = await db.collection(col).where('reporterId', '==', uniqueId).get();
      for (const doc of snap2.docs) await db.doc(`${col}/${doc.id}`).delete();
      if (col === 'suspensionAppeals') {
        const snap3 = await db.collection(col).where('userId', '==', uniqueId).get();
        for (const doc of snap3.docs) await db.doc(`${col}/${doc.id}`).delete();
      }
    }
  } catch (err) {
    log.error('cron', 'Failed to cleanup reports/appeals', { uniqueId, error: err.message });
  }
}
 
/**
 * Step 6b: Suggestions-content cleanup (GDPR right-to-erasure cascade).
 *
 * The original hardDeleteAccount sequence omitted the suggestions footprint
 * entirely, leaving deleted users still identifiable across the corpus via
 * submitterUid / voterId / authorUid. This step closes that gap:
 *
 *   1. Anonymise own suggestions (preserve community value, redact identity)
 *   2. Delete own votes via collectionGroup + decrement parent voteCount
 *   3. Anonymise own comments via collectionGroup (preserve thread structure)
 *   4. Delete subscription preferences doc
 *   5. Delete inbox notifications
 *
 * Each sub-step is independently try/wrapped so a single failure does not
 * abort the wider cron. Defensive parent-id check on collectionGroup hits
 * future-proofs against unrelated `votes` / `comments` subcollections.
 *
 * Uses an anonymous sentinel of `submitterUid: 0` (no real user has uniqueId
 * 0 — the floor is ≥1, with Officia=1) plus an explicit `submitterDeleted`
 * flag so read-side code can distinguish anonymisation from a legitimate
 * never-existed user.
 */
async function cleanupSuggestionsContent(uniqueId) {
  const numericUid = Number(uniqueId);
  const ANON = { uid: 0, deletedAt: now() };
 
  try {
    const sugSnap = await db
      .collection('suggestions')
      .where('submitterUid', '==', numericUid)
      .get();
    if (sugSnap.docs && sugSnap.docs.length > 0) {
      let batch = db.batch();
      let count = 0;
      for (const doc of sugSnap.docs) {
        batch.update(doc.ref, {
          submitterUid: ANON.uid,
          submitterDeleted: true,
          submitterDeletedAt: ANON.deletedAt,
        });
        count++;
        Iif (count === 500) {
          await batch.commit();
          batch = db.batch();
          count = 0;
        }
      }
      Eif (count > 0) await batch.commit();
    }
  } catch (err) {
    log.error('cron', 'Failed to anonymise own suggestions', {
      uniqueId,
      error: err.message,
    });
  }
 
  try {
    const votesSnap = await db.collectionGroup('votes').where('voterId', '==', numericUid).get();
    let batch = db.batch();
    let count = 0;
    for (const voteDoc of votesSnap.docs || []) {
      const suggestionRef = voteDoc.ref.parent?.parent;
      if (!suggestionRef || suggestionRef.parent?.id !== 'suggestions') continue;
      const vote = voteDoc.data().vote;
      const delta = vote === 'up' ? -1 : vote === 'down' ? 1 : 0;
      batch.delete(voteDoc.ref);
      if (delta !== 0) {
        batch.update(suggestionRef, { voteCount: FieldValue.increment(delta) });
      }
      count++;
      Iif (count >= 250) {
        await batch.commit();
        batch = db.batch();
        count = 0;
      }
    }
    if (count > 0) await batch.commit();
  } catch (err) {
    log.error('cron', 'Failed to delete suggestion votes', {
      uniqueId,
      error: err.message,
    });
  }
 
  try {
    const commentsSnap = await db
      .collectionGroup('comments')
      .where('authorUid', '==', numericUid)
      .get();
    let batch = db.batch();
    let count = 0;
    for (const commentDoc of commentsSnap.docs || []) {
      const suggestionRef = commentDoc.ref.parent?.parent;
      Iif (!suggestionRef || suggestionRef.parent?.id !== 'suggestions') continue;
      batch.update(commentDoc.ref, {
        authorUid: ANON.uid,
        authorDeleted: true,
        authorDeletedAt: ANON.deletedAt,
        text: '[Comment from deleted user]',
      });
      count++;
      Iif (count === 500) {
        await batch.commit();
        batch = db.batch();
        count = 0;
      }
    }
    if (count > 0) await batch.commit();
  } catch (err) {
    log.error('cron', 'Failed to anonymise suggestion comments', {
      uniqueId,
      error: err.message,
    });
  }
 
  try {
    await db.doc(`subscriptions/${uniqueId}`).delete();
  } catch (err) {
    log.error('cron', 'Failed to delete subscription preferences', {
      uniqueId,
      error: err.message,
    });
  }
 
  try {
    // Notifications today set both `uid` and `recipientUid` to the same value
    // on every write path. Querying both fields and deduplicating by ref makes
    // erasure forward-safe: if a future path writes only `recipientUid`, that
    // record still gets deleted instead of silently surviving the cascade.
    const [byUid, byRecipient] = await Promise.all([
      db.collection('notifications').where('uid', '==', numericUid).get(),
      db.collection('notifications').where('recipientUid', '==', numericUid).get(),
    ]);
    const seen = new Set();
    let batch = db.batch();
    let count = 0;
    for (const notifDoc of [...(byUid.docs || []), ...(byRecipient.docs || [])]) {
      const path = notifDoc.ref.path;
      if (seen.has(path)) continue;
      seen.add(path);
      batch.delete(notifDoc.ref);
      count++;
      Iif (count === 500) {
        await batch.commit();
        batch = db.batch();
        count = 0;
      }
    }
    if (count > 0) await batch.commit();
  } catch (err) {
    log.error('cron', 'Failed to delete notification inbox', {
      uniqueId,
      error: err.message,
    });
  }
}
 
/** Step 7: Auth-related cleanup */
async function cleanupAuthData(user, uniqueId) {
  try {
    const bioSnap = await db
      .collection('biometricKeys')
      .where('uniqueId', '==', Number(uniqueId))
      .get();
    for (const doc of bioSnap.docs) await db.doc(`biometricKeys/${doc.id}`).delete();
  } catch (err) {
    log.error('cron', 'Failed to cleanup biometric keys', { uniqueId, error: err.message });
  }
 
  if (user.email) {
    try {
      const otpSnap = await db.doc(`otpCodes/${user.email.toLowerCase()}`).get();
      if (otpSnap.exists) await db.doc(`otpCodes/${user.email.toLowerCase()}`).delete();
      const metricsSnap = await db.doc(`emailMetrics/${user.email.toLowerCase()}`).get();
      if (metricsSnap.exists) await db.doc(`emailMetrics/${user.email.toLowerCase()}`).delete();
    } catch (err) {
      log.error('cron', 'Failed to cleanup OTP/email data', { uniqueId, error: err.message });
    }
  }
 
  try {
    const receiptSnap = await db
      .collection('purchaseReceipts')
      .where('userId', '==', uniqueId)
      .get();
    for (const doc of receiptSnap.docs) {
      await db.doc(`purchaseReceipts/${doc.id}`).update({
        markedForDeletion: true,
        deletionScheduledAt: now() + 180 * 86400000,
      });
    }
  } catch (err) {
    log.error('cron', 'Failed to mark purchase receipts for deletion', {
      uniqueId,
      error: err.message,
    });
  }
}
 
/** Step 8: User doc + subcollections */
async function deleteUserDocAndSubcollections(uniqueId) {
  try {
    const subcollections = ['backpack', 'giftWall', 'transactions', 'warnings', 'stalkers'];
    for (const sub of subcollections) {
      const subDocs = await queryDocs(db.collection(`users/${uniqueId}/${sub}`));
      await batchDeletePaths(subDocs.map((doc) => `users/${uniqueId}/${sub}/${doc.id}`));
    }
    await db.doc(`users/${uniqueId}`).delete();
  } catch (err) {
    log.error('cron', 'Failed to delete user doc', { uniqueId, error: err.message });
  }
}
 
/** Step 9: Identity map soft-delete */
async function softDeleteIdentityMap(user, uniqueId) {
  try {
    const identitySnap = await db
      .collection('identityMap')
      .where('uniqueId', '==', Number(uniqueId))
      .get();
    for (const doc of identitySnap.docs) {
      await db.doc(`identityMap/${doc.id}`).update({
        unlinked: true,
        unlinkedAt: now(),
        deletedAccount: true,
        deletionStanding: user.isSuspended ? 'suspended' : 'clean',
      });
    }
  } catch (err) {
    log.error('cron', 'Failed to soft-delete identity map', { uniqueId, error: err.message });
  }
}
 
/** Step 10: Device bindings */
async function deleteDeviceBindings(uniqueId) {
  try {
    const bindingSnap = await db
      .collection('deviceBindings')
      .where('uniqueId', '==', Number(uniqueId))
      .get();
    for (const doc of bindingSnap.docs) await db.doc(`deviceBindings/${doc.id}`).delete();
  } catch (err) {
    log.error('cron', 'Failed to delete device bindings', { uniqueId, error: err.message });
  }
}
 
/** Step 11: Firebase Auth user */
async function deleteFirebaseAuthUser(firebaseUid, uniqueId) {
  try {
    await auth.deleteUser(firebaseUid);
  } catch (err) {
    log.error('cron', 'Failed to delete Firebase Auth user', { uniqueId, error: err.message });
  }
}
 
/**
 * Hard-delete all data for a single user account.
 * Follows the 12-step sequence from the design spec.
 */
async function hardDeleteAccount(userDoc) {
  const user = userDoc.data();
  const uniqueId = userDoc.id;
  const firebaseUid = user.firebaseUid;
 
  await sendDeletionEmail(user, uniqueId);
  await deleteUserR2Storage(uniqueId);
  await cleanupConversations(uniqueId);
  await cleanupRooms(uniqueId);
  await cleanupFollowerFollowing(uniqueId);
  await cleanupGiftRankings(uniqueId);
  await cleanupReportsAndAppeals(uniqueId);
  await cleanupSuggestionsContent(uniqueId);
  await cleanupAuthData(user, uniqueId);
  await deleteUserDocAndSubcollections(uniqueId);
  await softDeleteIdentityMap(user, uniqueId);
  await deleteDeviceBindings(uniqueId);
  await deleteFirebaseAuthUser(firebaseUid, uniqueId);
 
  // Step 12: Audit log (zero PII)
  const hashedUniqueId = crypto
    .createHmac('sha256', AUDIT_HASH_SECRET || 'dev-audit-secret')
    .update(String(uniqueId))
    .digest('hex');
 
  await db.doc(`adminAuditLog/${generateId()}`).set({
    action: 'account_deleted',
    timestamp: now(),
    hashedUniqueId,
    reason: user.deletionReason || 'unknown',
    triggeredBy: 'system',
    dataDeleted: [
      'user',
      'conversations',
      'rooms',
      'r2',
      'reports',
      'appeals',
      'suggestions',
      'votes',
      'comments',
      'subscriptions',
      'notifications',
      'auth',
      'identity',
      'deviceBindings',
    ],
    standing: user.isSuspended ? 'suspended' : 'clean',
  });
 
  log.info('cron', 'Account hard-deleted', { uniqueId });
}
 
/**
 * Main cron function: process pending deletions + schedule inactive accounts.
 */
async function accountDeletion() {
  const timestamp = now();
 
  // 1. Process pending deletions past their execute date
  const pendingSnap = await db
    .collection('users')
    .where('deletionExecuteAt', '>', 0)
    .where('deletionExecuteAt', '<=', timestamp)
    .limit(10)
    .get();
 
  let failed = 0;
  for (const doc of pendingSnap.docs) {
    try {
      // Re-read fresh doc to check if cancelled during processing
      const freshSnap = await db.doc(`users/${doc.id}`).get();
      Iif (!freshSnap.exists || !freshSnap.data().deletionExecuteAt) {
        continue;
      }
      await hardDeleteAccount(freshSnap);
    } catch (err) {
      failed += 1;
      log.error('cron', 'Account deletion failed', { uniqueId: doc.id, error: err.message });
    }
  }
 
  // 2. Schedule inactive accounts (if enabled)
  const configSnap = await db.doc('config/app').get();
  const config = configSnap.exists ? configSnap.data() : {};
  const thresholdMonths = config.inactiveAccountDeleteMonths || 0;
 
  if (thresholdMonths > 0) {
    const cutoff = timestamp - thresholdMonths * 30 * 86400000;
    const graceDays = config.accountDeletionGracePeriodDays || 30;
 
    const inactiveSnap = await db
      .collection('users')
      .where('lastActiveAt', '<', cutoff)
      .where('deletionScheduledAt', '==', null)
      .where('isSuspended', '==', false)
      .limit(10)
      .get();
 
    for (const doc of inactiveSnap.docs) {
      try {
        await db.doc(`users/${doc.id}`).update({
          deletionScheduledAt: timestamp,
          deletionReason: 'inactivity',
          deletionExecuteAt: timestamp + graceDays * 86400000,
        });
        log.info('cron', 'Inactive account scheduled for deletion', { uniqueId: doc.id });
      } catch (err) {
        log.error('cron', 'Failed to schedule inactive account', {
          uniqueId: doc.id,
          error: err.message,
        });
      }
    }
  }
 
  if (failed > 0) {
    // SHY-0631: a failed account keeps deletionExecuteAt, so the next run
    // tries it again; the sweep answers 500 so the nightly run is red.
    throw new Error(`${failed} account deletion(s) failed; each stays due for the next run`);
  }
}
 
module.exports = accountDeletion;
module.exports.hardDeleteAccount = hardDeleteAccount;
module.exports._hardDeleteAccount = hardDeleteAccount;