All files / src/routes subscriptions.js

96.45% Statements 136/141
91.2% Branches 83/91
100% Functions 9/9
96.06% Lines 122/127

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                        2x 2x 2x 2x 2x     2x                   2x     45x 6x 6x   39x         2x 7x 7x   6x 5x 2x                       3x   1x 1x           2x 14x 14x   13x 13x   13x     15x 9x 5x 5x 5x 1x         8x     12x 1x 1x 11x 2x   2x 1x 1x 1x           12x               12x 8x 8x     12x     11x 11x   1x 1x           2x 10x 10x   9x 9x     7x 7x 7x 1x     6x 6x       5x   1x 1x           2x 6x 6x   5x 5x 5x   4x 4x 4x   4x 1x     3x 3x 3x   3x 2x   1x 1x           2x 5x 5x   4x 4x   3x       2x   1x 1x           2x 3x 3x   2x       1x   1x 1x           2x 16x 16x 16x 7x       9x   9x 9x         9x 9x 4x     5x 5x         5x 1x       4x 4x 4x 1x 1x         1x     4x             2x  
/**
 * Subscription routes for roadmap/suggestion notifications.
 *
 * GET    /subscriptions/me            → get preferences
 * PUT    /subscriptions/me            → update preferences
 * POST   /subscriptions/me/watch      → add to watch list
 * DELETE /subscriptions/me/watch/:id  → remove from watch list
 * POST   /subscriptions/push-token    → register push token
 * DELETE /subscriptions/push-token    → revoke push token
 * POST   /subscriptions/unsubscribe   → one-click email unsubscribe (token-based, no auth)
 */
 
const crypto = require('node:crypto');
const router = require('express').Router();
const { db, FieldValue } = require('../utils/firebase');
const log = require('../utils/log');
const { now } = require('../utils/helpers');
 
// Default channel preferences (in-app only for most, +systemMessage for key events)
const DEFAULT_PREFS = {
  roadmapUpdate: { email: false, push: false, inApp: true, systemMessage: false },
  suggestionAccepted: { email: false, push: false, inApp: true, systemMessage: true },
  suggestionPlanned: { email: false, push: false, inApp: true, systemMessage: false },
  suggestionCompleted: { email: false, push: false, inApp: true, systemMessage: true },
  suggestionRejected: { email: false, push: false, inApp: true, systemMessage: true },
  suggestionMerged: { email: false, push: false, inApp: true, systemMessage: true },
  commentOnSuggestion: { email: false, push: false, inApp: true, systemMessage: false },
};
 
const { computeRoadmapOptedIn } = require('../utils/notification-prefs');
 
function requireAuth(req, res) {
  if (!req.auth || !req.auth.uniqueId) {
    res.status(401).json({ error: 'Authentication required' });
    return true;
  }
  return false;
}
 
// ─── GET /subscriptions/me ──────────────────────────────────────
 
router.get('/subscriptions/me', async (req, res) => {
  try {
    if (requireAuth(req, res)) return;
 
    const doc = await db.doc(`subscriptions/${req.auth.uniqueId}`).get();
    if (!doc.exists) {
      return res.json({
        channelPreferences: DEFAULT_PREFS,
        scope: 'all',
        watchedFeatures: [],
        watchedSuggestions: [],
        language: 'en',
        pushToken: null,
        email: null,
        emailConsentAt: null,
      });
    }
 
    res.json(doc.data());
  } catch (err) {
    log.error('subscriptions', 'Failed to get preferences', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ─── PUT /subscriptions/me ──────────────────────────────────────
 
router.put('/subscriptions/me', async (req, res) => {
  try {
    if (requireAuth(req, res)) return;
 
    const { channelPreferences, emailConsent, email, scope } = req.body;
    const updates = { updatedAt: now() };
 
    if (channelPreferences) {
      // GDPR: if any channel enables email, require either emailConsent in this request
      // or existing emailConsentAt in the stored subscription doc
      const wantsEmail = Object.values(channelPreferences).some((ch) => ch && ch.email === true);
      if (wantsEmail && emailConsent !== true) {
        const existing = await db.doc(`subscriptions/${req.auth.uniqueId}`).get();
        const hasConsent = existing.exists && existing.data().emailConsentAt;
        if (!hasConsent) {
          return res
            .status(400)
            .json({ error: 'Email consent required (GDPR). Set emailConsent: true.' });
        }
      }
      updates.channelPreferences = channelPreferences;
    }
 
    if (emailConsent === true) {
      updates.emailConsentAt = now();
      Eif (email) updates.email = email;
    } else if (emailConsent === false) {
      updates.emailConsentAt = null;
      // Disable all email channels
      if (updates.channelPreferences) {
        for (const key of Object.keys(updates.channelPreferences)) {
          Eif (updates.channelPreferences[key]) {
            updates.channelPreferences[key].email = false;
          }
        }
      }
    }
 
    if (scope) updates.scope = scope;
 
    // Maintain the denormalised opt-in flag so roadmap-notify can use a
    // server-side filter instead of scanning the whole collection. We
    // recompute against the *full* prefs object (caller-supplied OR
    // existing-doc fallback) so a partial update like `{ inApp: true }`
    // doesn't silently flip the flag to false because the other channels
    // are absent from the request body.
    if (updates.channelPreferences) {
      const roadmapPrefs = updates.channelPreferences.roadmapUpdate;
      updates.roadmapUpdateOptedIn = computeRoadmapOptedIn(roadmapPrefs);
    }
 
    await db.doc(`subscriptions/${req.auth.uniqueId}`).set(updates, { merge: true });
 
    // Return current state
    const doc = await db.doc(`subscriptions/${req.auth.uniqueId}`).get();
    res.json(doc.exists ? doc.data() : { channelPreferences: DEFAULT_PREFS });
  } catch (err) {
    log.error('subscriptions', 'Failed to update preferences', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ─── POST /subscriptions/me/watch ───────────────────────────────
 
router.post('/subscriptions/me/watch', async (req, res) => {
  try {
    if (requireAuth(req, res)) return;
 
    const { type, id } = req.body;
    if (!type || !id) return res.status(400).json({ error: 'Type and ID required' });
 
    // Validate that the target exists
    const collection = type === 'feature' ? 'roadmapFeatures' : 'suggestions';
    const targetDoc = await db.doc(`${collection}/${id}`).get();
    if (!targetDoc.exists) {
      return res.status(404).json({ error: `${type} not found` });
    }
 
    const field = type === 'feature' ? 'watchedFeatures' : 'watchedSuggestions';
    await db
      .doc(`subscriptions/${req.auth.uniqueId}`)
      .set({ [field]: FieldValue.arrayUnion(id), updatedAt: now() }, { merge: true });
 
    res.json({ success: true });
  } catch (err) {
    log.error('subscriptions', 'Failed to add watch', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ─── DELETE /subscriptions/me/watch/:id ─────────────────────────
 
router.delete('/subscriptions/me/watch/:id', async (req, res) => {
  try {
    if (requireAuth(req, res)) return;
 
    const { id } = req.params;
    const doc = await db.doc(`subscriptions/${req.auth.uniqueId}`).get();
    if (!doc.exists) return res.status(404).json({ error: 'Not watching this item' });
 
    const data = doc.data();
    const inFeatures = (data.watchedFeatures || []).includes(id);
    const inSuggestions = (data.watchedSuggestions || []).includes(id);
 
    if (!inFeatures && !inSuggestions) {
      return res.status(404).json({ error: 'Not watching this item' });
    }
 
    const updates = { updatedAt: now() };
    if (inFeatures) updates.watchedFeatures = FieldValue.arrayRemove(id);
    if (inSuggestions) updates.watchedSuggestions = FieldValue.arrayRemove(id);
 
    await db.doc(`subscriptions/${req.auth.uniqueId}`).update(updates);
    res.json({ success: true });
  } catch (err) {
    log.error('subscriptions', 'Failed to remove watch', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ─── POST /subscriptions/push-token ─────────────────────────────
 
router.post('/subscriptions/push-token', async (req, res) => {
  try {
    if (requireAuth(req, res)) return;
 
    const { token } = req.body;
    if (!token) return res.status(400).json({ error: 'Token required' });
 
    await db
      .doc(`subscriptions/${req.auth.uniqueId}`)
      .set({ pushToken: token, updatedAt: now() }, { merge: true });
 
    res.json({ success: true });
  } catch (err) {
    log.error('subscriptions', 'Failed to register push token', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ─── DELETE /subscriptions/push-token ───────────────────────────
 
router.delete('/subscriptions/push-token', async (req, res) => {
  try {
    if (requireAuth(req, res)) return;
 
    await db
      .doc(`subscriptions/${req.auth.uniqueId}`)
      .set({ pushToken: null, updatedAt: now() }, { merge: true });
 
    res.json({ success: true });
  } catch (err) {
    log.error('subscriptions', 'Failed to remove push token', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ─── POST /subscriptions/unsubscribe (no auth — HMAC token-based) ────
 
router.post('/subscriptions/unsubscribe', async (req, res) => {
  try {
    const { token } = req.body;
    if (!token || typeof token !== 'string' || token.trim().length === 0) {
      return res.status(400).json({ error: 'Unsubscribe token required' });
    }
 
    // Token format: base64(uid:timestamp:hmac)
    const secret = process.env.UNSUBSCRIBE_SECRET || 'dev-unsubscribe-secret';
    let decoded;
    try {
      decoded = Buffer.from(token, 'base64').toString('utf-8');
    } catch {
      return res.status(400).json({ error: 'Invalid unsubscribe token' });
    }
 
    const parts = decoded.split(':');
    if (parts.length !== 3) {
      return res.status(400).json({ error: 'Invalid unsubscribe token format' });
    }
 
    const [uid, timestamp, providedHmac] = parts;
    const expectedHmac = crypto
      .createHmac('sha256', secret)
      .update(`${uid}:${timestamp}`)
      .digest('hex');
 
    if (providedHmac !== expectedHmac) {
      return res.status(403).json({ error: 'Invalid unsubscribe token' });
    }
 
    // Token is valid — disable email channel for this user
    const subRef = db.collection('subscriptions').doc(uid);
    const subSnap = await subRef.get();
    if (subSnap.exists) {
      const prefs = subSnap.data().preferences || {};
      for (const [event, channels] of Object.entries(prefs)) {
        if (channels && channels.email) {
          prefs[event] = { ...channels, email: false };
        }
      }
      await subRef.update({ preferences: prefs, gdprEmailConsent: false });
    }
 
    res.json({ success: true, message: 'Email notifications disabled' });
  } catch (err) {
    log.error('subscriptions', 'Unsubscribe failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
module.exports = router;