@defra/lis-hubs-infra-access 0.44.0 → 0.45.0-lreg-907.alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -125,6 +125,7 @@ await server.register(
125
125
  buildAuthorizationUrl,
126
126
  completeAuthorizationCodeGrant,
127
127
  buildLogoutUrl,
128
+ getLogoutOrigins, // from createOidcClient, like buildLogoutUrl
128
129
  loginRoutes,
129
130
  notAuthorisedPath: '/auth/access-denied', // optional, defaults to '/auth/not-authorised'
130
131
  authorize: async (user, request) => true // optional
@@ -132,8 +133,8 @@ await server.register(
132
133
  )
133
134
  ```
134
135
 
135
- Registers the login, `/sso`, `/auth/logout` and
136
- `/signout` routes (all `auth: false`) and the not-authorised route (`auth: try`), plus the `lis-hub-session`
136
+ Registers the login and `/sso` routes, `POST /signout`, `GET /signout` and
137
+ `GET /auth/logout` (all `auth: false`) and the not-authorised route (`auth: try`), plus the `lis-hub-session`
137
138
  scheme as the default strategy, backed by the yar hub session. A signed-out
138
139
  user on a required route is redirected to the first login route with
139
140
  `?returnUrl=<path+search>`; a `try` route continues unauthenticated.
@@ -149,6 +150,41 @@ returns it (or `null`), and the hub's proxy injects it on proxied spoke
149
150
  requests in the `x-lis-jwt-assertion` header (`JWT_ASSERTION_HEADER` from `@defra/lis-hubs-infra-core`).
150
151
  Signing out resets the session, which drops the JWT with it.
151
152
 
153
+ The header Sign out (and the not-authorised page's) is a link to `GET /signout`,
154
+ which never signs out: for a session with a CSRF token (only a signed-in one has
155
+ one) it renders the `auth/sign-out` view from `@defra/lis-infra-ui-services`,
156
+ asking the user to confirm with a `Sign out` button posting the token, or
157
+ `Cancel`; anyone else is redirected to `/`. The old `GET /auth/logout` redirects
158
+ to `/signout`.
159
+
160
+ `POST /signout` builds the identity provider's end-session URL, resets the
161
+ session (even if building the URL fails, when the error propagates) and
162
+ redirects there. The hub must register `csrfPlugin` from
163
+ `@defra/lis-infra-ui-services/csrf` with `{ tokenSource: 'session' }`, which
164
+ requires the post to be same-origin and to carry the session's token in its
165
+ `_csrf` field. The plugin is declared as a dependency, so a hub that has not
166
+ registered it fails to start. A post that fails either check (an expired session
167
+ has no token left, or the request is forged) signs nothing out and redirects to
168
+ `/`, through the plugin's route `failAction`, rather than answering 403.
169
+
170
+ Browsers hold every redirect after a form post to the posting page's CSP
171
+ `form-action`, which is `'self'` on every hub page. So the confirmation page
172
+ alone allows the origins the sign-out passes through: `getLogoutOrigins(request)`
173
+ gives the end-session endpoint's origin, the issuer's (an identity provider
174
+ on a custom domain redirects to its issuer host to finish) and the post-logout
175
+ redirect URI's (from the configured hub origin, which may not be the one the
176
+ user is on), from the same
177
+ discovery metadata and provider as `buildLogoutUrl`. After the hub's Blankie
178
+ plugin (`blankie`) has set the header, an `onPreResponse` hook appends them to
179
+ the `form-action` directive of that response, leaving the rest of the policy
180
+ as it is. Blankie's own route options cannot do it: they replace the whole
181
+ policy and are fixed at route registration. If discovery fails, the
182
+ confirmation page still renders, with `form-action` left as `'self'`, and the
183
+ error is logged; the sign-out post then still resets the session.
184
+
185
+ A successful sign-in at `/sso` clears the session's CSRF token, so a new one is
186
+ issued.
187
+
152
188
  A hub-level refusal keeps authentication and authorisation apart: the user
153
189
  stays signed in to the hub but is not authorised to use it. `resolveAuthSession`
154
190
  refuses a login (e.g. a user not on an allow-list) by returning
@@ -160,7 +196,7 @@ redirected to `notAuthorisedPath`. A refused
160
196
  login is stored as a session flagged `refused`, and every later authenticated
161
197
  request, including the login route, is sent to `notAuthorisedPath` without
162
198
  re-running the hub's checks, until the user signs out through the normal
163
- `/signout` flow. The identity provider is not involved in the refusal, so no
199
+ `POST /signout` flow. The identity provider is not involved in the refusal, so no
164
200
  post-logout redirect URI is needed for it. `notAuthorisedPath` must be a hub
165
201
  path starting with `/`, and the old `accessDeniedPath` option is rejected.
166
202
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@defra/lis-hubs-infra-access",
3
- "version": "0.44.0",
3
+ "version": "0.45.0-lreg-907.alpha.2",
4
4
  "description": "Shared hub access and capability resolution for the livestock platform.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -3,12 +3,18 @@ import { logger } from '@defra/lis-hubs-infra-core'
3
3
  import { HUBS } from '@defra/lis-hubs-infra-registry'
4
4
 
5
5
  import {
6
- clearHubAuthSession,
6
+ clearCsrfToken,
7
7
  clearHubJwt,
8
8
  getHubAuthSession,
9
9
  setHubAuthSession,
10
10
  setHubJwt
11
11
  } from './session.js'
12
+ import {
13
+ CSRF_PLUGIN_NAME,
14
+ SIGN_OUT_PATH,
15
+ allowSignOutFormAction,
16
+ createSignOutRoutes
17
+ } from './sign-out.js'
12
18
  import { getReturnUrlFromRequest, issueHubJwt } from './tokens/index.js'
13
19
  import { getAuthorizedSpecies } from '../authorization/modules/species.js'
14
20
  import { hydrateAuthorization } from '../authorization/permissions/hydrate.js'
@@ -181,6 +187,10 @@ function createCallbackController({
181
187
  }
182
188
 
183
189
  const { user, authSession, accessToken, returnUrl } = grant
190
+
191
+ // A new sign-in gets a new CSRF token, whatever the session held.
192
+ clearCsrfToken(request)
193
+
184
194
  const authorization = await resolveAuthSession({
185
195
  user,
186
196
  authSession,
@@ -218,27 +228,6 @@ function createCallbackController({
218
228
  }
219
229
  }
220
230
 
221
- function createLogoutController({ buildLogoutUrl }) {
222
- return {
223
- options: {
224
- auth: false
225
- },
226
- async handler(request, h) {
227
- // Build the logout URL while the session is still alive (it reads the
228
- // id token for id_token_hint), but invalidate the session in `finally`
229
- // so a failure building the URL cannot leave the session replayable.
230
- // Resetting the session also drops the hub JWT it holds.
231
- try {
232
- const logoutUrl = await buildLogoutUrl(request)
233
-
234
- return h.redirect(logoutUrl)
235
- } finally {
236
- clearHubAuthSession(request)
237
- }
238
- }
239
- }
240
- }
241
-
242
231
  function createNotAuthorisedRoute({ path, loginPath }) {
243
232
  return {
244
233
  method: 'GET',
@@ -250,7 +239,7 @@ function createNotAuthorisedRoute({ path, loginPath }) {
250
239
  // The view comes from @defra/lis-infra-ui-services, which every hub
251
240
  // registers. A signed-in visitor is offered Sign out, anyone else Sign in.
252
241
  const action = request.auth.isAuthenticated
253
- ? { signOutHref: '/signout' }
242
+ ? { signOutHref: SIGN_OUT_PATH }
254
243
  : { signInHref: loginPath }
255
244
 
256
245
  return h
@@ -264,9 +253,11 @@ function createNotAuthorisedRoute({ path, loginPath }) {
264
253
  }
265
254
 
266
255
  /**
267
- * Builds the login, `/sso`, `/auth/logout` and
268
- * `/signout` routes (all `auth: false`), plus the shared not-authorised route
269
- * when the hub uses the default not-authorised path.
256
+ * Builds the login and `/sso` routes, `POST /signout`, its `GET /signout`
257
+ * confirmation and `GET /auth/logout`, which redirects to it (all
258
+ * `auth: false`), plus the
259
+ * shared not-authorised route when the hub uses the default not-authorised
260
+ * path.
270
261
  *
271
262
  * @param {object} options - `createHubAuth` options, minus `pluginName` and `authorize`.
272
263
  * @param {Function} options.refuseAccess - Shared hub-level refusal response.
@@ -280,6 +271,7 @@ function createHubAuthRegistration(options) {
280
271
  buildAuthorizationUrl,
281
272
  completeAuthorizationCodeGrant,
282
273
  buildLogoutUrl,
274
+ getLogoutOrigins,
283
275
  loginRoutes,
284
276
  notAuthorisedPath,
285
277
  registerNotAuthorisedRoute,
@@ -295,7 +287,6 @@ function createHubAuthRegistration(options) {
295
287
  isAuthorized,
296
288
  loginPath
297
289
  })
298
- const logoutController = createLogoutController({ buildLogoutUrl })
299
290
  const routes = [
300
291
  ...loginRoutes.map(({ path, providerId }) => ({
301
292
  method: 'GET',
@@ -314,23 +305,7 @@ function createHubAuthRegistration(options) {
314
305
  path: '/sso',
315
306
  ...callbackController
316
307
  },
317
- {
318
- method: 'GET',
319
- path: '/auth/logout',
320
- ...logoutController
321
- },
322
- {
323
- // The shared nunjucks layout's header nav links here (see
324
- // createNunjucksContextBuilder's logoutUrl default).
325
- method: 'GET',
326
- path: '/signout',
327
- options: {
328
- auth: false
329
- },
330
- handler(_request, h) {
331
- return h.redirect('/auth/logout')
332
- }
333
- },
308
+ ...createSignOutRoutes({ buildLogoutUrl, getLogoutOrigins }),
334
309
  ...(registerNotAuthorisedRoute
335
310
  ? [createNotAuthorisedRoute({ path: notAuthorisedPath, loginPath })]
336
311
  : [])
@@ -375,8 +350,10 @@ function createHubSessionScheme({ loginPath, caller }) {
375
350
  /**
376
351
  * Creates a Hapi plugin for hub authentication built on a Hapi auth scheme.
377
352
  *
378
- * Registers the login, `/sso`, `/auth/logout` and
379
- * `/signout` routes (all `auth: false`), the shared not-authorised route
353
+ * Registers the login and `/sso` routes, `POST /signout`, which signs the user
354
+ * out, `GET /signout`, which asks a signed-in user to confirm and sends anyone
355
+ * else home, and `GET /auth/logout`, which redirects to it (all
356
+ * `auth: false`), the shared not-authorised route
380
357
  * (`auth: { mode: 'try' }`, unless the hub sets its own `notAuthorisedPath`), and the
381
358
  * `lis-hub-session` scheme and
382
359
  * strategy, made the server's default. Signed-out requests to `required`
@@ -390,6 +367,11 @@ function createHubSessionScheme({ loginPath, caller }) {
390
367
  * `getHubJwt`), so the browser only carries the session cookie; the hub's
391
368
  * proxy sends it to spokes in the `x-lis-jwt-assertion` header.
392
369
  *
370
+ * `POST /signout` relies on the hub registering `csrfPlugin` from
371
+ * `@defra/lis-infra-ui-services/csrf` with `{ tokenSource: 'session' }`,
372
+ * declared as a plugin dependency, so the server fails to start without it. A
373
+ * successful sign-in clears the session's CSRF token, so a new one is issued.
374
+ *
393
375
  * @param {object} options - Plugin configuration options.
394
376
  * @param {string} [options.pluginName='auth'] - Name of the plugin.
395
377
  * @param {string} options.hubId - Registry id of this hub: 'front-office' or 'back-office'.
@@ -398,6 +380,7 @@ function createHubSessionScheme({ loginPath, caller }) {
398
380
  * @param {Function} options.buildAuthorizationUrl - Function to build OIDC authorization URL.
399
381
  * @param {Function} options.completeAuthorizationCodeGrant - Function to complete OIDC authorization code flow.
400
382
  * @param {Function} options.buildLogoutUrl - Function to build logout URL.
383
+ * @param {Function} options.getLogoutOrigins - The OIDC client's, giving the origins a sign-out redirects through, which the sign-out page's CSP form-action allows.
401
384
  * @param {Array<{path: string, providerId: string|Function}>} options.loginRoutes - Login route configurations; the first is where signed-out users are sent.
402
385
  * @param {string} [options.notAuthorisedPath='/auth/not-authorised'] - Where a user lands after a hub-level refusal (`resolveAuthSession` returning `{ denied: true }`, or `authorize` returning `false`). They stay signed in to the hub, with no spoke JWT, and every other authenticated request is redirected here until they sign out. The default path is registered by this plugin with `auth: try` and renders the `error/not-authorised` view with a 403, offering Sign out to a signed-in visitor and Sign in (to the first login route) to anyone else. A hub that sets its own path registers that route itself and should do the same.
403
386
  * @param {(user: object, request: object) => boolean | Promise<boolean>} [options.authorize] - Optional hub-wide rule for authenticated requests; `false` redirects the user to `notAuthorisedPath` without signing them out.
@@ -420,6 +403,12 @@ export function createHubAuth({
420
403
  )
421
404
  }
422
405
 
406
+ if (typeof options.getLogoutOrigins !== 'function') {
407
+ throw new TypeError(
408
+ "createHubAuth() requires getLogoutOrigins, the OIDC client's, for the sign-out page's CSP"
409
+ )
410
+ }
411
+
423
412
  if (
424
413
  notAuthorisedPath !== undefined &&
425
414
  !(
@@ -460,7 +449,12 @@ export function createHubAuth({
460
449
  server.auth.strategy(HUB_AUTH_STRATEGY, HUB_AUTH_STRATEGY)
461
450
  server.auth.default(HUB_AUTH_STRATEGY)
462
451
 
452
+ // POST /signout is protected only by the CSRF plugin, so a hub that
453
+ // has not registered it fails at start rather than exposing it.
454
+ server.dependency(CSRF_PLUGIN_NAME)
455
+
463
456
  register(server)
457
+ allowSignOutFormAction(server)
464
458
 
465
459
  server.ext('onPostAuth', async (request, h) => {
466
460
  if (!request.auth.isAuthenticated || request.path === landingPath) {
@@ -326,6 +326,17 @@ function createAuthorizationCodeCompleter({
326
326
  }
327
327
  }
328
328
 
329
+ /**
330
+ * @param {() => string} getHubOrigin
331
+ * @param {string} [returnPath]
332
+ * @returns {string} the URI the identity provider returns to after sign-out
333
+ */
334
+ function resolvePostLogoutRedirectUri(getHubOrigin, returnPath) {
335
+ return returnPath
336
+ ? new URL(returnPath, getHubOrigin()).toString()
337
+ : getHubOrigin()
338
+ }
339
+
329
340
  function createLogoutUrlBuilder({
330
341
  getPrimaryProviderId,
331
342
  getOidcMetadata,
@@ -344,9 +355,10 @@ function createLogoutUrlBuilder({
344
355
  ) {
345
356
  const providerId = authSession?.authProvider ?? getPrimaryProviderId?.()
346
357
  const metadata = await getOidcMetadata(providerId)
347
- const postLogoutRedirectUri = returnPath
348
- ? new URL(returnPath, getHubOrigin()).toString()
349
- : getHubOrigin()
358
+ const postLogoutRedirectUri = resolvePostLogoutRedirectUri(
359
+ getHubOrigin,
360
+ returnPath
361
+ )
350
362
 
351
363
  // A provider without an end-session endpoint cannot be signed out of, so
352
364
  // the user goes straight to where it would have returned them.
@@ -369,6 +381,79 @@ function createLogoutUrlBuilder({
369
381
  }
370
382
  }
371
383
 
384
+ /**
385
+ * @param {unknown} value
386
+ * @returns {string | undefined} the http(s) origin of the URL, or undefined when it is not one
387
+ */
388
+ function toWebOrigin(value) {
389
+ if (typeof value !== 'string') {
390
+ return undefined
391
+ }
392
+
393
+ try {
394
+ const url = new URL(value)
395
+
396
+ return ['https:', 'http:'].includes(url.protocol) ? url.origin : undefined
397
+ } catch {
398
+ return undefined
399
+ }
400
+ }
401
+
402
+ function createLogoutOriginsResolver({
403
+ getPrimaryProviderId,
404
+ getOidcMetadata,
405
+ getHubOrigin
406
+ }) {
407
+ /**
408
+ * The origins a sign-out passes through before it returns to the hub, for
409
+ * the confirmation page's CSP form-action: browsers hold every redirect
410
+ * after a form post to it. They are the end-session endpoint's origin and
411
+ * the issuer's, as an identity provider on a custom domain (Defra CI's
412
+ * your-account.defra.gov.uk) redirects to its issuer host (b2clogin.com)
413
+ * to finish, and the post-logout redirect URI's, which comes from the
414
+ * configured hub origin and may not be the origin the user is browsing on.
415
+ * Uses the same provider, metadata and redirect URI as buildLogoutUrl.
416
+ * @param {object} request - The Hapi request.
417
+ * @param {object} [options]
418
+ * @param {object} [options.authSession] - Session to sign out instead of the stored hub session.
419
+ * @param {string} [options.returnPath] - As for buildLogoutUrl.
420
+ * @returns {Promise<string[]>} The origins; only the post-logout one when the provider has no end-session endpoint, as sign-out then redirects straight there.
421
+ * @throws {TypeError} when the end-session endpoint or post-logout redirect URI is not an http(s) URL
422
+ */
423
+ return async function getLogoutOrigins(
424
+ request,
425
+ { authSession = getHubAuthSession(request), returnPath } = {}
426
+ ) {
427
+ const providerId = authSession?.authProvider ?? getPrimaryProviderId?.()
428
+ const metadata = await getOidcMetadata(providerId)
429
+ const postLogoutOrigin = toWebOrigin(
430
+ resolvePostLogoutRedirectUri(getHubOrigin, returnPath)
431
+ )
432
+
433
+ if (!postLogoutOrigin) {
434
+ throw new TypeError('Post-logout redirect URI is not an http(s) URL')
435
+ }
436
+
437
+ if (!metadata.end_session_endpoint) {
438
+ return [postLogoutOrigin]
439
+ }
440
+
441
+ const endSessionOrigin = toWebOrigin(metadata.end_session_endpoint)
442
+
443
+ if (!endSessionOrigin) {
444
+ throw new TypeError('OIDC end_session_endpoint is not an http(s) URL')
445
+ }
446
+
447
+ const issuerOrigin = toWebOrigin(metadata.issuer)
448
+
449
+ return [
450
+ ...new Set(
451
+ [endSessionOrigin, issuerOrigin, postLogoutOrigin].filter(Boolean)
452
+ )
453
+ ]
454
+ }
455
+ }
456
+
372
457
  /**
373
458
  * Creates the OIDC operations used by the hub authentication plugin.
374
459
  * @param {object} options OIDC client dependencies.
@@ -400,6 +485,11 @@ export function createOidcClient(options) {
400
485
  getOidcMetadata,
401
486
  getHubOrigin
402
487
  }),
488
+ getLogoutOrigins: createLogoutOriginsResolver({
489
+ getPrimaryProviderId,
490
+ getOidcMetadata,
491
+ getHubOrigin
492
+ }),
403
493
  completeAuthorizationCodeGrant: createAuthorizationCodeCompleter({
404
494
  getPrimaryProviderId,
405
495
  resolveProviderConfig,
@@ -3,6 +3,9 @@ import crypto from 'node:crypto'
3
3
  const authFlowKey = 'hub-auth-flow'
4
4
  const authSessionKey = 'hub-auth-session'
5
5
  const hubJwtKey = 'hub-jwt'
6
+ // Must match CSRF_SESSION_KEY in @defra/lis-infra-ui-services/csrf, which
7
+ // depends on this package, so this one cannot import it.
8
+ const csrfTokenKey = 'lis-csrf-token'
6
9
  const keyLength = 32
7
10
 
8
11
  /**
@@ -104,3 +107,12 @@ export function clearHubJwt(request) {
104
107
  export function clearHubAuthSession(request) {
105
108
  request?.yar?.reset?.()
106
109
  }
110
+
111
+ /**
112
+ * Drops the session's CSRF token, so the CSRF plugin issues a new one on the
113
+ * next signed-in request and a token from before sign-in is never reused.
114
+ * @param {object} request - The Hapi request object with yar session support.
115
+ */
116
+ export function clearCsrfToken(request) {
117
+ request?.yar?.clear?.(csrfTokenKey)
118
+ }
@@ -0,0 +1,203 @@
1
+ import { logger } from '@defra/lis-hubs-infra-core'
2
+
3
+ import { clearHubAuthSession } from './session.js'
4
+
5
+ // The CSRF plugin's name, which keys its route options and request.plugins.
6
+ // Must match CSRF_PLUGIN_NAME in @defra/lis-infra-ui-services/csrf, which
7
+ // depends on this package, so this one cannot import it.
8
+ export const CSRF_PLUGIN_NAME = 'lis-csrf'
9
+
10
+ // The hubs set their CSP with Blankie (registered under this name), which
11
+ // cannot widen one directive for one route: its route options replace the
12
+ // whole policy, and are fixed when the route is registered.
13
+ const CSP_PLUGIN_NAME = 'blankie'
14
+ const CSP_HEADER = 'content-security-policy'
15
+ // Keys the sign-out origins on the confirmation page's response.
16
+ const RESPONSE_PLUGIN_KEY = 'lis-hub-auth-sign-out'
17
+
18
+ // The shared layout's header Sign out links here, as does the not-authorised
19
+ // page (see createNunjucksContextBuilder's logoutUrl default).
20
+ export const SIGN_OUT_PATH = '/signout'
21
+ // The sign-out path before the confirmation page, which old links may still
22
+ // point at.
23
+ const LEGACY_SIGN_OUT_PATH = '/auth/logout'
24
+
25
+ /**
26
+ * Sign out is a POST, so another site cannot sign a user out with a link or
27
+ * an image. It is `auth: false`, so the hub-wide refusal check does not send
28
+ * a refused user away from it, and the CSRF plugin's default checks (origin
29
+ * and token, the token read from the session) apply.
30
+ * @param {object} options
31
+ * @param {Function} options.buildLogoutUrl - Builds the identity provider's end-session URL.
32
+ * @returns {object} the route's options and handler
33
+ */
34
+ function createLogoutController({ buildLogoutUrl }) {
35
+ return {
36
+ options: {
37
+ auth: false,
38
+ plugins: {
39
+ // A failed check is a session that has already ended (no token left)
40
+ // or a forged request: either way nothing is signed out, and the
41
+ // user lands on the home page rather than a 403.
42
+ [CSRF_PLUGIN_NAME]: { failAction: (_request, h) => h.redirect('/') }
43
+ }
44
+ },
45
+ async handler(request, h) {
46
+ // Build the logout URL while the session is still alive (it reads the
47
+ // id token for id_token_hint), but invalidate the session in `finally`
48
+ // so a failure building the URL cannot leave the session replayable.
49
+ // Resetting the session also drops the hub JWT and CSRF token it holds.
50
+ try {
51
+ const logoutUrl = await buildLogoutUrl(request)
52
+
53
+ return h.redirect(logoutUrl)
54
+ } finally {
55
+ clearHubAuthSession(request)
56
+ }
57
+ }
58
+ }
59
+ }
60
+
61
+ /**
62
+ * A GET never signs out, as any site could send one. A signed-in user (the
63
+ * plugin issues a token only to a signed-in session, and signing out resets
64
+ * the session) is asked to confirm with the POST form; anyone else goes home.
65
+ * The page's CSP form-action also allows the origins the sign-out redirects
66
+ * through, as browsers hold each redirect after the form post to it.
67
+ * @param {object} options
68
+ * @param {(request: object) => Promise<string[]>} options.getLogoutOrigins - The origins the sign-out passes through.
69
+ * @returns {object} the hapi route
70
+ */
71
+ function createSignOutConfirmationRoute({ getLogoutOrigins }) {
72
+ return {
73
+ method: 'GET',
74
+ path: SIGN_OUT_PATH,
75
+ options: {
76
+ auth: false
77
+ },
78
+ async handler(request, h) {
79
+ if (!request.plugins[CSRF_PLUGIN_NAME]?.token) {
80
+ return h.redirect('/')
81
+ }
82
+
83
+ const logoutOrigins = await getLogoutOriginsOrNone(
84
+ getLogoutOrigins,
85
+ request
86
+ )
87
+ // The view comes from @defra/lis-infra-ui-services, which every hub
88
+ // registers, and reads csrfToken from the view context.
89
+ const response = h.view('auth/sign-out', {
90
+ pageTitle: 'Are you sure you want to sign out?',
91
+ signOutHref: SIGN_OUT_PATH
92
+ })
93
+ response.plugins[RESPONSE_PLUGIN_KEY] = { logoutOrigins }
94
+
95
+ return response
96
+ }
97
+ }
98
+ }
99
+
100
+ /**
101
+ * The page still renders when discovery fails, with form-action left as
102
+ * 'self'. The sign-out post then resets the session as usual; only the
103
+ * browser's redirect to the identity provider may be refused.
104
+ * @param {(request: object) => Promise<string[]>} getLogoutOrigins
105
+ * @param {object} request
106
+ * @returns {Promise<string[]>}
107
+ */
108
+ async function getLogoutOriginsOrNone(getLogoutOrigins, request) {
109
+ try {
110
+ return await getLogoutOrigins(request)
111
+ } catch (error) {
112
+ logger.error(
113
+ error,
114
+ 'Sign-out origins unavailable, so the sign-out page CSP is not widened'
115
+ )
116
+
117
+ return []
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Appends sources to a policy's form-action directive, leaving every other
123
+ * directive as it is. A policy without form-action does not restrict form
124
+ * posts (it does not fall back to default-src), so it is left alone.
125
+ * @param {string} policy
126
+ * @param {string[]} sources
127
+ * @returns {string}
128
+ */
129
+ export function addFormActionSources(policy, sources) {
130
+ return policy
131
+ .split(';')
132
+ .map((directive) =>
133
+ directive.trim().split(/\s+/)[0].toLowerCase() === 'form-action'
134
+ ? [directive.trimEnd(), ...sources].join(' ')
135
+ : directive
136
+ )
137
+ .join(';')
138
+ }
139
+
140
+ /**
141
+ * Widens form-action on the confirmation page only, once the hub's CSP
142
+ * plugin has set the header.
143
+ * @param {object} server - The hapi server (or plugin realm) to extend.
144
+ */
145
+ export function allowSignOutFormAction(server) {
146
+ server.ext(
147
+ 'onPreResponse',
148
+ (request, h) => {
149
+ const { response } = request
150
+ const logoutOrigins =
151
+ response?.plugins?.[RESPONSE_PLUGIN_KEY]?.logoutOrigins
152
+
153
+ if (response.isBoom || !logoutOrigins?.length) {
154
+ return h.continue
155
+ }
156
+
157
+ // response.header() stores names lowercased, but Blankie 5 assigns
158
+ // `Content-Security-Policy` into response.headers directly, so the
159
+ // name is looked up in any case and the value replaced under that same
160
+ // name: response.header() would add a second, lowercased entry.
161
+ const headerName = Object.keys(response.headers).find(
162
+ (name) => name.toLowerCase() === CSP_HEADER
163
+ )
164
+ const policy = headerName && response.headers[headerName]
165
+
166
+ if (typeof policy !== 'string') {
167
+ return h.continue
168
+ }
169
+
170
+ response.headers[headerName] = addFormActionSources(policy, logoutOrigins)
171
+
172
+ return h.continue
173
+ },
174
+ { after: [CSP_PLUGIN_NAME] }
175
+ )
176
+ }
177
+
178
+ /**
179
+ * @param {object} options
180
+ * @param {Function} options.buildLogoutUrl - Builds the identity provider's end-session URL.
181
+ * @param {(request: object) => Promise<string[]>} options.getLogoutOrigins - The origins the sign-out passes through.
182
+ * @returns {object[]} `POST /signout`, its `GET` confirmation, and `GET /auth/logout`, which redirects to it
183
+ */
184
+ export function createSignOutRoutes({ buildLogoutUrl, getLogoutOrigins }) {
185
+ return [
186
+ {
187
+ method: 'POST',
188
+ path: SIGN_OUT_PATH,
189
+ ...createLogoutController({ buildLogoutUrl })
190
+ },
191
+ createSignOutConfirmationRoute({ getLogoutOrigins }),
192
+ {
193
+ method: 'GET',
194
+ path: LEGACY_SIGN_OUT_PATH,
195
+ options: {
196
+ auth: false
197
+ },
198
+ handler(_request, h) {
199
+ return h.redirect(SIGN_OUT_PATH)
200
+ }
201
+ }
202
+ ]
203
+ }