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

mozilla / blurts-server / #12021

pending completion
#12021

push

circleci

web-flow
Merge pull request #2788 from mozilla/MNTOR-1117

MNTOR-1117: Fix auth state issue

282 of 1205 branches covered (23.4%)

Branch coverage included in aggregate %.

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

959 of 3221 relevant lines covered (29.77%)

2.42 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 express from 'express'
6
import session from 'express-session'
7
import connectRedis from 'connect-redis'
8
import helmet from 'helmet'
9
import accepts from 'accepts'
10
import redis from 'redis'
11
import cookieParser from 'cookie-parser'
12

13
import AppConstants from './app-constants.js'
14
import { localStorage } from './utils/local-storage.js'
15
import { errorHandler } from './middleware/error.js'
16
import { doubleCsrfProtection } from './utils/csrf.js'
17
import { initFluentBundles, updateLocale } from './utils/fluent.js'
18
import { loadBreachesIntoApp } from './utils/hibp.js'
19
import { initEmail } from './utils/email.js'
20
import indexRouter from './routes/index.js'
21

22
const app = express()
×
23
const isDev = AppConstants.NODE_ENV === 'dev'
×
24

25
// Determine from where to serve client code/assets:
26
// Build script is triggered for `npm start` and assets are served from /dist.
27
// Build script is NOT run for `npm run dev`, assets are served from /src, and nodemon restarts server without build (faster dev).
28
const staticPath =
29
  process.env.npm_lifecycle_event === 'start' ? '../dist' : './client'
×
30

31
await initFluentBundles()
×
32

33
async function getRedisStore () {
34
  const RedisStoreConstructor = connectRedis(session)
×
35
  if (['', 'redis-mock'].includes(AppConstants.REDIS_URL)) {
×
36
    const redisMock = await import('redis-mock') // for devs without local redis
×
37
    return new RedisStoreConstructor({
×
38
      client: redisMock.default.createClient()
39
    })
40
  }
41
  return new RedisStoreConstructor({
×
42
    client: redis.createClient({ url: AppConstants.REDIS_URL })
43
  })
44
}
45

46
// middleware
47
app.use(
×
48
  helmet({
49
    crossOriginEmbedderPolicy: false
50
  })
51
)
52

53
const imgSrc = [
×
54
  "'self'"
55
]
56

57
if (AppConstants.FXA_ENABLED) {
×
58
  const fxaSrc = new URL(AppConstants.OAUTH_PROFILE_URI).origin
×
59
  imgSrc.push(fxaSrc)
×
60
}
61

62
// disable forced https to allow localhost on Safari
63
app.use(
×
64
  helmet.contentSecurityPolicy({
65
    directives: {
66
      imgSrc,
67
      upgradeInsecureRequests: isDev ? null : []
×
68
    }
69
  })
70
)
71

72
// fallback to default 'no-referrer' only when 'strict-origin-when-cross-origin' not available
73
app.use(
×
74
  helmet.referrerPolicy({
75
    policy: ['no-referrer', 'strict-origin-when-cross-origin']
76
  })
77
)
78

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

84
  localStorage.run(new Map(), () => {
×
85
    req.locale = updateLocale(accepts(req).languages())
×
86
    localStorage.getStore().set('locale', req.locale)
×
87
    next()
×
88
  })
89
})
90

91
// MNTOR-1009, 1117:
92
// Because of proxy settings, request / cookies are not persisted between calls
93
// Setting the trust proxy to high and securing the cookie allowed the cookie to persist
94
// If cookie.secure is set as true, for nodejs behind proxy, "trust proxy" needs to be set
95
app.set('trust proxy', 1)
×
96

97
// session
98
const SESSION_DURATION_HOURS = AppConstants.SESSION_DURATION_HOURS || 48
×
99
app.use(
×
100
  session({
101
    cookie: {
102
      maxAge: SESSION_DURATION_HOURS * 60 * 60 * 1000, // 48 hours
103
      rolling: true,
104
      sameSite: 'lax',
105
      secure: !isDev
106
    },
107
    resave: false,
108
    saveUninitialized: true,
109
    secret: AppConstants.COOKIE_SECRET,
110
    store: await getRedisStore()
111
  })
112
)
113

114
// Load breaches into namespaced cache
115
try {
×
116
  await loadBreachesIntoApp(app)
×
117
} catch (error) {
118
  console.error('Error loading breaches into app.locals', error)
×
119
}
120

121
app.use(express.static(staticPath))
×
122
app.use(express.json())
×
123
app.use(cookieParser(AppConstants.COOKIE_SECRET))
×
124
app.use(doubleCsrfProtection)
×
125

126
// routing
127
app.use('/', indexRouter)
×
128
app.use(errorHandler)
×
129

130
app.listen(AppConstants.PORT, async function () {
×
131
  console.info(`MONITOR V2: Server listening at ${this.address().port}`)
×
132
  console.info(`Static files served from ${staticPath}`)
×
133
  try {
×
134
    await initEmail()
×
135
    console.info('Email initialized')
×
136
  } catch (ex) {
137
    console.error('try-initialize-email-error', { ex })
×
138
  }
139
})
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