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

mozilla / blurts-server / f9ba8642-7b25-40df-89a8-4929ed132b32

pending completion
f9ba8642-7b25-40df-89a8-4929ed132b32

push

circleci

Vincent
Prevent search engines from indexing non-prod envs

282 of 1529 branches covered (18.44%)

Branch coverage included in aggregate %.

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

959 of 4153 relevant lines covered (23.09%)

3.84 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
]
92

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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