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

mozilla / blurts-server / 888b0fd0-c8ae-440d-8d0a-f67e71a46a26

pending completion
888b0fd0-c8ae-440d-8d0a-f67e71a46a26

push

circleci

GitHub
Merge pull request #2905 from mozilla/MNTOR-1316-lost-locale

282 of 1435 branches covered (19.65%)

Branch coverage included in aggregate %.

5 of 5 new or added lines in 2 files covered. (100.0%)

959 of 3916 relevant lines covered (24.49%)

4.07 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
    crossOriginResourcePolicy: { policy: 'cross-origin' },
77
    crossOriginEmbedderPolicy: false
78
  })
79
)
80

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

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

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

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

100
app.use((_req, res, _next) => {
×
101
  res.locals.nonce = crypto.randomBytes(16).toString('hex')
×
102
  helmet.contentSecurityPolicy({
×
103
    directives: {
104
      upgradeInsecureRequests: isDev ? null : [], // disable forced https to allow localhost on Safari
×
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
// For text/html or */* (if Accept has not been set), negotiate and store the requested language.
130
// This filter avoids running unecessary locale functions for every image/webp request, for example.
131
// Using AsyncLocalStorage avoids having to pass req context down through every function (e.g. for getMessage())
132
app.use((req, res, next) => {
×
133
  if (!['text/html', '*/*'].includes(accepts(req).types()[0])) return next()
×
134

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

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

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

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

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

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

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

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

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

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

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