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

mozilla / blurts-server / #12934

pending completion
#12934

push

circleci

web-flow
Merge pull request #2917 from mozilla/MNTOR-1343-breach-page-styling

List breaches

282 of 1595 branches covered (17.68%)

Branch coverage included in aggregate %.

96 of 96 new or added lines in 10 files covered. (100.0%)

959 of 4309 relevant lines covered (22.26%)

1.85 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
import { noSearchEngineIndex } from './middleware/noSearchEngineIndex.js'
28

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

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

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

45
    return event
×
46
  }
47
})
48

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

55
await initFluentBundles()
×
56

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

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

74
// middleware
75
app.use(
×
76
  helmet({
77
    crossOriginResourcePolicy: { policy: 'cross-origin' },
78
    crossOriginEmbedderPolicy: false
79
  })
80
)
81

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

89
const imgSrc = [
×
90
  "'self'",
91
  'https://monitor.cdn.mozilla.net'
92
]
93

94
if (AppConstants.FXA_ENABLED) {
×
95
  const fxaSrc = new URL(AppConstants.OAUTH_PROFILE_URI).origin
×
96
  imgSrc.push(fxaSrc)
×
97
}
98

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

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

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

131
// For text/html or */* (if Accept has not been set), negotiate and store the requested language.
132
// This filter avoids running unecessary locale functions for every image/webp request, for example.
133
// Using AsyncLocalStorage avoids having to pass req context down through every function (e.g. for getMessage())
134
app.use((req, res, next) => {
×
135
  if (!['text/html', '*/*'].includes(accepts(req).types()[0])) return next()
×
136

137
  req.locale = updateLocale(accepts(req).languages())
×
138
  localStorage.run(new Map(), () => {
×
139
    localStorage.getStore().set('locale', req.locale)
×
140
    next() // call next() inside this function to pass asyncLocalStorage context to other middleware.
×
141
  })
142
})
143

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

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

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

174
app.use(noSearchEngineIndex)
×
175
app.use(express.static(staticPath))
×
176
app.use(express.json())
×
177
app.use(cookieParser(AppConstants.COOKIE_SECRET))
×
178
app.use(doubleCsrfProtection)
×
179

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

187
app.use('/api', apiLimiter)
×
188

189
// routing
190
app.use('/', indexRouter)
×
191

192
// sentry error handler
193
app.use(Sentry.Handlers.errorHandler({
×
194
  shouldHandleError (error) {
195
    if (error instanceof RateLimitError) return true
×
196
  }
197
}))
198

199
// app error handler
200
app.use(errorHandler)
×
201

202
app.listen(AppConstants.PORT, async function () {
×
203
  console.info(`MONITOR V2: Server listening at ${this.address().port}`)
×
204
  console.info(`Static files served from ${staticPath}`)
×
205
  try {
×
206
    await initEmail()
×
207
    console.info('Email initialized')
×
208
  } catch (ex) {
209
    console.error('try-initialize-email-error', { ex })
×
210
  }
211
})
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