• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mozilla / blurts-server / #12642

pending completion
#12642

push

circleci

web-flow
Merge pull request #2881 from mozilla/MNTOR-1285/fix-heroku-redis-crash

fix heroku/redis 4 crashes

282 of 1416 branches covered (19.92%)

Branch coverage included in aggregate %.

4 of 4 new or added lines in 1 file covered. (100.0%)

959 of 3914 relevant lines covered (24.5%)

2.04 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/src/app.js
1
/* This Source Code Form is subject to the terms of the Mozilla Public
2
 * License, v. 2.0. If a copy of the MPL was not distributed with this
3
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4

5
import crypto from 'node:crypto'
6

7
import express from 'express'
8
import session from 'express-session'
9
import helmet from 'helmet'
10
import accepts from 'accepts'
11
import { createClient } from 'redis'
12
import RedisStore from 'connect-redis'
13
import cookieParser from 'cookie-parser'
14
import rateLimit from 'express-rate-limit'
15
import Sentry from '@sentry/node'
16
import '@sentry/tracing'
17

18
import AppConstants from './app-constants.js'
19
import { localStorage } from './utils/local-storage.js'
20
import { errorHandler } from './middleware/error.js'
21
import { doubleCsrfProtection } from './utils/csrf.js'
22
import { initFluentBundles, updateLocale, getMessageWithLocale, getMessage } from './utils/fluent.js'
23
import { loadBreachesIntoApp } from './utils/hibp.js'
24
import { RateLimitError } from './utils/error.js'
25
import { initEmail } from './utils/email.js'
26
import indexRouter from './routes/index.js'
27

28
const app = express()
×
29
const isDev = AppConstants.NODE_ENV === 'dev'
×
30

31
// init sentry
32
Sentry.init({
×
33
  dsn: AppConstants.SENTRY_DSN,
34
  environment: AppConstants.NODE_ENV,
35
  debug: isDev,
36
  beforeSend (event, hint) {
37
    if (!hint.originalException.locales || hint.originalException.locales[0] === 'en') return event // return if no localization or localization is in english
×
38

39
    // try to force an english translation for the error message if localized
40
    if (hint.originalException.fluentID) {
×
41
      event.exception.values[0].value = getMessageWithLocale(hint.originalException.fluentID, 'en') || getMessage(hint.originalException.fluentID)
×
42
    }
43

44
    return event
×
45
  }
46
})
47

48
// Determine from where to serve client code/assets:
49
// Build script is triggered for `npm start` and assets are served from /dist.
50
// Build script is NOT run for `npm run dev`, assets are served from /src, and nodemon restarts server without build (faster dev).
51
const staticPath =
52
  process.env.npm_lifecycle_event === 'start' ? '../dist' : './client'
×
53

54
await initFluentBundles()
×
55

56
async function getRedisStore () {
57
  if (['', 'redis-mock'].includes(AppConstants.REDIS_URL)) {
×
58
    // allow mock redis for setups without local redis server
59
    const { redisMockClient } = await import('./utils/redis-mock.js')
×
60
    return new RedisStore({ client: redisMockClient })
×
61
  }
62

63
  const redisClient = createClient({ url: AppConstants.REDIS_URL })
×
64
  // the following event handlers are currently required for Heroku server stability: https://github.com/Shopify/shopify-app-js/issues/129
65
  redisClient.on('error', err => console.error('Redis client error', err))
×
66
  redisClient.on('connect', () => console.log('Redis client is connecting'))
×
67
  redisClient.on('reconnecting', () => console.log('Redis client is reconnecting'))
×
68
  redisClient.on('ready', () => console.log('Redis client is ready'))
×
69
  await redisClient.connect().catch(console.error)
×
70
  return new RedisStore({ client: redisClient })
×
71
}
72

73
// middleware
74
app.use(
×
75
  helmet({
76
    crossOriginEmbedderPolicy: false
77
  })
78
)
79

80
app.use(
×
81
  Sentry.Handlers.requestHandler({
82
    request: ['headers', 'method', 'url'], // omit cookies, data, query_string
83
    user: ['id'] // omit username, email
84
  })
85
)
86

87
const imgSrc = [
×
88
  "'self'"
89
]
90

91
if (AppConstants.FXA_ENABLED) {
×
92
  const fxaSrc = new URL(AppConstants.OAUTH_PROFILE_URI).origin
×
93
  imgSrc.push(fxaSrc)
×
94
}
95

96
// Support GA4 per https://developers.google.com/tag-platform/tag-manager/web/csp
97
imgSrc.push('www.googletagmanager.com')
×
98

99
// disable forced https to allow localhost on Safari
100
app.use((_req, res, _next) => {
×
101
  res.locals.nonce = crypto.randomBytes(16).toString('hex')
×
102
  helmet.contentSecurityPolicy({
×
103
    directives: {
104
      upgradeInsecureRequests: isDev ? null : [],
×
105
      scriptSrc: [
106
        "'self'",
107
        // Support GA4 per https://developers.google.com/tag-platform/tag-manager/web/csp
108
        `'nonce-${res.locals.nonce}'`
109
      ],
110
      imgSrc,
111
      connectSrc: [
112
        "'self'",
113
        // Support GA4 per https://developers.google.com/tag-platform/tag-manager/web/csp
114
        'https://*.google-analytics.com',
115
        'https://*.analytics.google.com',
116
        'https://*.googletagmanager.com'
117
      ]
118
    }
119
  })(_req, res, _next)
120
})
121

122
// fallback to default 'no-referrer' only when 'strict-origin-when-cross-origin' not available
123
app.use(
×
124
  helmet.referrerPolicy({
125
    policy: ['no-referrer', 'strict-origin-when-cross-origin']
126
  })
127
)
128

129
// When a text/html request is received, negotiate and store the requested language
130
// Using asyncLocalStorage avoids having to pass req context down through every function (e.g. getMessage())
131
app.use((req, res, next) => {
×
132
  if (!req.headers.accept?.startsWith('text/html')) return next()
×
133

134
  localStorage.run(new Map(), () => {
×
135
    req.locale = updateLocale(accepts(req).languages())
×
136
    localStorage.getStore().set('locale', req.locale)
×
137
    next()
×
138
  })
139
})
140

141
// MNTOR-1009, 1117:
142
// Because of proxy settings, request / cookies are not persisted between calls
143
// Setting the trust proxy to high and securing the cookie allowed the cookie to persist
144
// If cookie.secure is set as true, for nodejs behind proxy, "trust proxy" needs to be set
145
app.set('trust proxy', 1)
×
146

147
// session
148
const SESSION_DURATION_HOURS = AppConstants.SESSION_DURATION_HOURS || 48
×
149
app.use(
×
150
  session({
151
    cookie: {
152
      maxAge: SESSION_DURATION_HOURS * 60 * 60 * 1000, // 48 hours
153
      rolling: true,
154
      sameSite: 'lax',
155
      secure: !isDev
156
    },
157
    resave: false,
158
    saveUninitialized: true,
159
    secret: AppConstants.COOKIE_SECRET,
160
    store: await getRedisStore()
161
  })
162
)
163

164
// Load breaches into namespaced cache
165
try {
×
166
  await loadBreachesIntoApp(app)
×
167
} catch (error) {
168
  console.error('Error loading breaches into app.locals', error)
×
169
}
170

171
app.use(express.static(staticPath))
×
172
app.use(express.json())
×
173
app.use(cookieParser(AppConstants.COOKIE_SECRET))
×
174
app.use(doubleCsrfProtection)
×
175

176
const apiLimiter = rateLimit({
×
177
  windowMs: 15 * 60 * 1000, // 15 minutes
178
  max: 100, // Limit each IP to 100 requests per `window` (here, per 15 minutes)
179
  standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
180
  legacyHeaders: false // Disable the `X-RateLimit-*` headers
181
})
182

183
app.use('/api', apiLimiter)
×
184

185
// routing
186
app.use('/', indexRouter)
×
187

188
// sentry error handler
189
app.use(Sentry.Handlers.errorHandler({
×
190
  shouldHandleError (error) {
191
    if (error instanceof RateLimitError) return true
×
192
  }
193
}))
194

195
// app error handler
196
app.use(errorHandler)
×
197

198
app.listen(AppConstants.PORT, async function () {
×
199
  console.info(`MONITOR V2: Server listening at ${this.address().port}`)
×
200
  console.info(`Static files served from ${staticPath}`)
×
201
  try {
×
202
    await initEmail()
×
203
    console.info('Email initialized')
×
204
  } catch (ex) {
205
    console.error('try-initialize-email-error', { ex })
×
206
  }
207
})
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc