All files / src/cron accountDeletion.js

82.18% Statements 143/174
80.95% Branches 34/42
57.14% Functions 16/28
82.82% Lines 135/163

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                    1x 1x 1x 1x 1x 1x 1x 1x   1x 1x               87x 7x 7x 7x   7x           16x 15x 15x 15x               16x             16x 80x 80x 80x                 7x         7x           7x                                                     16x 16x       16x 7x 7x 7x                                                   16x 16x       16x 7x     7x           1x           16x 16x       16x 7x       15x       15x 6x         1x           16x 16x 16x 6x     1x           16x 16x 16x 46x 46x 45x 45x 45x 15x 15x       1x           16x 16x       16x   1x     16x 15x 15x 15x 15x 15x           16x 16x       16x 6x           1x                 16x 16x 16x 80x 80x   16x               16x 16x       16x 6x               1x           16x 16x       16x   1x           16x 16x                     16x 16x 16x   16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x     16x         16x                                       16x             9x     9x             9x 2x   2x 2x 1x   1x             9x 9x 9x   9x 2x 2x   2x               2x 1x 1x         1x                     1x 1x 1x  
/**
 * 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 { 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 all its subcollections. */
async function deleteOneOnOneConversation(convId) {
  const [messages, userSettings, mutes] = await Promise.all([
    queryDocs(db.collection(`conversations/${convId}/messages`)),
    queryDocs(db.collection(`conversations/${convId}/userSettings`)),
    queryDocs(db.collection(`conversations/${convId}/mutes`)),
  ]);
  const allDocs = [
    ...messages.map((m) => `conversations/${convId}/messages/${m.id}`),
    ...userSettings.map((s) => `conversations/${convId}/userSettings/${s.id}`),
    ...mutes.map((m) => `conversations/${convId}/mutes/${m.id}`),
    `conversations/${convId}`,
  ];
  await batchDeletePaths(allDocs);
}
 
/** 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 */
async function cleanupConversations(uniqueId) {
  try {
    const convSnap = await db
      .collection('conversations')
      .where('participantIds', 'array-contains', Number(uniqueId))
      .get();
    for (const convDoc of convSnap.docs) {
      const participantCount = (convDoc.data().participantIds || []).length;
      if (participantCount <= 2) {
        await deleteOneOnOneConversation(convDoc.id);
      } else E{
        await removeUserFromGroupConversation(convDoc.id, uniqueId);
      }
    }
  } catch (err) {
    log.error('cron', 'Failed to cleanup conversations', { uniqueId, error: err.message });
  }
}
 
/** 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) {
      Iif (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 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();
      Iif (otpSnap.exists) await db.doc(`otpCodes/${user.email.toLowerCase()}`).delete();
      const metricsSnap = await db.doc(`emailMetrics/${user.email.toLowerCase()}`).get();
      Iif (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 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',
      '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();
 
  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();
      if (!freshSnap.exists || !freshSnap.data().deletionExecuteAt) {
        continue;
      }
      await hardDeleteAccount(freshSnap);
    } catch (err) {
      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,
        });
      }
    }
  }
}
 
module.exports = accountDeletion;
module.exports.hardDeleteAccount = hardDeleteAccount;
module.exports._hardDeleteAccount = hardDeleteAccount;