All files / src/routes data-export.js

96.93% Statements 95/98
91.3% Branches 42/46
87.5% Functions 7/8
96.87% Lines 93/96

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                1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x     1x         17x 17x 2x 2x   15x       8x 8x       5x 5x             1x 11x 11x   10x   10x 9x 1x   8x     8x 2x 2x 1x       7x     7x           7x 7x 7x 6x     6x               3x 3x   3x       3x   3x             3x 3x 3x       3x               3x   4x       4x             7x   1x     1x               1x 6x 6x   5x   5x 4x 1x   3x   3x 3x             1x     1x               1x 7x 7x 7x   7x 1x       6x 6x 1x       5x 5x       1x       4x 4x 1x   3x   3x 1x       2x 1x 1x       1x   1x     1x       1x  
/**
 * Data export routes — GDPR Article 20 data portability.
 *
 * POST /api/users/:uniqueId/data-export          → Request export (owner, rate-limited)
 * GET  /api/users/:uniqueId/data-export/status    → Poll export status (owner)
 * GET  /api/users/:uniqueId/data-export/download  → Download ZIP (HMAC token)
 */
 
const node_crypto = require('node:crypto');
const router = require('express').Router();
const { db } = require('../utils/firebase');
const { generateId, now } = require('../utils/helpers');
const log = require('../utils/log');
const buildDataExport = require('../utils/data-export-builder');
const r2 = require('../utils/r2');
const { sendEmail } = require('../utils/email');
const { buildDataExportReadyEmail } = require('../utils/email-templates');
 
const RATE_LIMIT_MS = 24 * 60 * 60 * 1000; // 24 hours
const EXPORT_EXPIRY_MS = 48 * 60 * 60 * 1000; // 48 hours
Iif (!process.env.EXPORT_DOWNLOAD_SECRET && process.env.NODE_ENV === 'production') {
  throw new Error('EXPORT_DOWNLOAD_SECRET is required in production');
}
const EXPORT_DOWNLOAD_SECRET = process.env.EXPORT_DOWNLOAD_SECRET || 'dev-export-secret';
 
// ─── Helper: ownership check ────────────────────────────────────
 
function requireOwner(req, res) {
  const paramId = Number(req.params.uniqueId);
  if (req.auth.uniqueId !== paramId) {
    res.status(403).json({ error: "Cannot access another user's data" });
    return true;
  }
  return false;
}
 
function generateDownloadToken(uniqueId, expiresAt) {
  const data = `${uniqueId}:${expiresAt}`;
  return node_crypto.createHmac('sha256', EXPORT_DOWNLOAD_SECRET).update(data).digest('hex');
}
 
function verifyDownloadToken(uniqueId, expiresAt, token) {
  const expected = generateDownloadToken(uniqueId, expiresAt);
  return node_crypto.timingSafeEqual(Buffer.from(token, 'hex'), Buffer.from(expected, 'hex'));
}
 
// ═══════════════════════════════════════════════════════════════
// POST /api/users/:uniqueId/data-export — Request export
// ═══════════════════════════════════════════════════════════════
 
router.post('/users/:uniqueId/data-export', 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();
 
    // Rate limit: 24 hours
    if (user.lastDataExportRequestedAt) {
      const elapsed = now() - user.lastDataExportRequestedAt;
      if (elapsed < RATE_LIMIT_MS) {
        return res.status(429).json({ error: 'Please wait 24 hours between export requests' });
      }
    }
 
    const timestamp = now();
 
    // Update user doc
    await db.doc(`users/${uniqueId}`).update({
      lastDataExportRequestedAt: timestamp,
      dataExportStatus: 'pending',
    });
 
    // Fire-and-forget async export
    (async () => {
      try {
        const result = await buildDataExport(uniqueId);
        const r2Key = `exports/${uniqueId}/${generateId()}.zip`;
 
        // Upload to R2 with private cache headers
        await r2.putObject(
          r2Key,
          result.buffer,
          'application/zip',
          { expiresAt: String(timestamp + EXPORT_EXPIRY_MS) },
          { cacheControl: 'private, no-cache, no-store' },
        );
 
        const expiresAt = timestamp + EXPORT_EXPIRY_MS;
        const downloadToken = generateDownloadToken(uniqueId, expiresAt);
        const apiBase =
          process.env.API_BASE_URL ||
          (process.env.NODE_ENV === 'production'
            ? 'https://api.shytalk.shyden.co.uk'
            : 'https://dev-api.shytalk.shyden.co.uk');
        const downloadUrl = `${apiBase}/api/users/${uniqueId}/data-export/download?token=${downloadToken}&expiresAt=${expiresAt}`;
 
        await db.doc(`users/${uniqueId}`).update({
          dataExportStatus: 'ready',
          dataExportR2Key: r2Key,
          dataExportExpiresAt: expiresAt,
        });
 
        // Send email with download link
        Eif (user.email) {
          try {
            const template = buildDataExportReadyEmail(
              downloadUrl,
              new Date(expiresAt).toISOString(),
            );
            await sendEmail(user.email, template.subject, template.html);
          } catch (emailErr) {
            log.error('data-export', 'Failed to send export email', {
              error: emailErr.message,
            });
          }
        }
 
        log.info('data-export', 'Export ready', { uniqueId, r2Key });
      } catch (err) {
        log.error('data-export', 'Export build failed', {
          uniqueId,
          error: err.message,
        });
        await db
          .doc(`users/${uniqueId}`)
          .update({ dataExportStatus: 'failed' })
          .catch(() => {});
      }
    })();
 
    res.status(202).json({ requestedAt: timestamp });
  } catch (err) {
    log.error('data-export', 'Failed to request export', {
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ═══════════════════════════════════════════════════════════════
// GET /api/users/:uniqueId/data-export/status — Poll status
// ═══════════════════════════════════════════════════════════════
 
router.get('/users/:uniqueId/data-export/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();
 
    const status = user.dataExportStatus || 'none';
    res.json({
      status,
      requestedAt: user.lastDataExportRequestedAt || null,
      readyAt: status === 'ready' ? user.lastDataExportRequestedAt : null,
      expiresAt: user.dataExportExpiresAt || null,
    });
  } catch (err) {
    log.error('data-export', 'Failed to get export status', {
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ═══════════════════════════════════════════════════════════════
// GET /api/users/:uniqueId/data-export/download — Download ZIP
// ═══════════════════════════════════════════════════════════════
 
router.get('/users/:uniqueId/data-export/download', async (req, res) => {
  try {
    const { token, expiresAt } = req.query;
    const uniqueId = req.params.uniqueId;
 
    if (!token || !expiresAt) {
      return res.status(401).json({ error: 'Missing token or expiresAt' });
    }
 
    // Check expiry
    const expiry = Number(expiresAt);
    if (expiry <= Date.now()) {
      return res.status(410).json({ error: 'Download link has expired' });
    }
 
    // Verify HMAC
    try {
      Iif (!verifyDownloadToken(uniqueId, expiresAt, token)) {
        return res.status(401).json({ error: 'Invalid token' });
      }
    } catch {
      return res.status(401).json({ error: 'Invalid token' });
    }
 
    // Get R2 key from user doc
    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.dataExportR2Key) {
      return res.status(404).json({ error: 'No export available' });
    }
 
    // Stream from R2
    const r2Obj = await r2.getObject(user.dataExportR2Key);
    res.setHeader('Content-Type', 'application/zip');
    res.setHeader(
      'Content-Disposition',
      `attachment; filename="shytalk-data-export-${uniqueId}.zip"`,
    );
    r2Obj.Body.pipe(res);
  } catch (err) {
    log.error('data-export', 'Failed to download export', {
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
module.exports = router;