Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
121 lines (109 loc) · 4.94 KB
/
Copy pathserver.js
File metadata and controls
121 lines (109 loc) · 4.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import 'dotenv/config'
import fastify from 'fastify'
import fastifyStatic from '@fastify/static'
import helmet from '@fastify/helmet'
import cookie from '@fastify/cookie'
import csrfProtection from '@fastify/csrf-protection'
import nunjucks from 'nunjucks'
import { randomBytes } from 'node:crypto'
import { resolve } from 'node:path'
import {
createGovUkAnalyticsConsent,
govukAnalyticsConsentTemplatePath
} from '../../dist/index.js'
import govukAnalyticsConsentFastifyPlugin from '../../dist/integrations/fastify.js'
import { exampleLanguage, languageCookieName, languageReturnUrl, languageView } from '../language.js'
// Standard Fastify setup: app, Nunjucks views, and GOV.UK static assets.
const app = fastify({ logger: true })
const port = Number(process.env.PORT ?? 3000)
const env = new nunjucks.Environment(new nunjucks.FileSystemLoader([
govukAnalyticsConsentTemplatePath(),
'node_modules/govuk-frontend/dist',
'examples/views'
]), { autoescape: true })
await app.register(fastifyStatic, {
root: resolve('node_modules/govuk-frontend/dist/govuk'),
prefix: '/govuk-frontend/'
})
// Consent integration: declare categories, tags, and the CSRF field for its forms.
const consent = createGovUkAnalyticsConsent({
serviceName: 'Example service',
cookiesPageUrl: '/cookies',
auditEnabled: true,
categories: ['default', 'personalization'],
tags: ['google-analytics'],
gtmAllowlist: ['auto'],
cookies: [
{ name: 'session_id', categoryId: 'essential', purposeKey: 'govukAnalyticsConsent.cookies.session.purpose', expiry: { value: 'session' } },
{ name: '_csrf', categoryId: 'essential', purposeKey: 'govukAnalyticsConsent.cookies.csrf.purpose', expiry: { value: 'session' } },
{ name: languageCookieName, categoryId: 'essential', purposeKey: 'govukAnalyticsConsent.cookies.language.purpose', expiry: { value: 1, unit: 'year' } },
{
name: 'example_preferences',
categoryId: 'personalization',
purpose: 'Remembers your display preferences',
expiry: { value: 1, unit: 'year' }
}
],
getLanguage: (request) => exampleLanguage(request.headers.cookie),
getCsrfFormFields: async (_request, reply) => ({ _csrf: await reply.generateCsrf() })
})
// Host security plugins share consent's CSP sources and protect its form route.
await app.register(helmet, {
enableCSPNonces: true,
contentSecurityPolicy: {
directives: consent.helmetCsp({
defaultSrc: ["'self'"],
scriptSrc: ["'self'"],
styleSrc: ["'self'"],
connectSrc: ["'self'"],
imgSrc: ["'self'"],
frameSrc: ["'self'"]
})
}
})
await app.register(cookie, { secret: process.env.COOKIE_SECRET ?? randomBytes(32).toString('hex') })
await app.register(csrfProtection, {
cookieOpts: { signed: true, path: '/', httpOnly: true, sameSite: 'lax', secure: process.env.NODE_ENV === 'production' }
})
// Validate after form parsing; GET pages must remain free to generate CSRF tokens.
app.addHook('preValidation', (request, reply, done) => {
if (request.method === 'POST' && request.url.split('?')[0] === '/govuk-analytics-consent/consent') {
app.csrfProtection(request, reply, done)
} else {
done()
}
})
// Consent installs its routes and request-scoped view context.
await app.register(govukAnalyticsConsentFastifyPlugin, consent)
// Ordinary service routes handle the language switch and render the example pages.
app.get('/language/:language', (request, reply) => {
const language = request.params.language
if (language !== 'en' && language !== 'cy') {
return reply.code(404).send()
}
const secure = request.protocol === 'https' ? '; Secure' : ''
reply.header('set-cookie', `${languageCookieName}=${language}; Path=/; Max-Age=31536000; SameSite=Lax${secure}`)
return reply.code(303).redirect(languageReturnUrl(request.query.returnUrl))
})
app.get('/', (request, reply) => {
// The host may inspect consent state to decide what its own page displays.
const consent = request.govukAnalyticsConsent
const personalizationMessage = consent.isCategoryAccepted('personalization')
? 'Personalisation cookies are enabled. This page can use your saved display preferences.'
: consent.hasChoice
? 'Personalisation cookies are disabled. This page is using the default display settings.'
: 'You have not chosen your cookie preferences yet. This page is using the default display settings.'
return reply.type('text/html').send(env.render('index.njk', {
cspNonce: reply.cspNonce.script,
govukAnalyticsConsent: request.govukAnalyticsConsentContext,
personalizationMessage,
...languageView(request.headers.cookie, request.raw.url)
}))
})
// The host owns /cookies; consent provides the fragment via the view context.
app.get('/cookies', (request, reply) => reply.type('text/html').send(env.render('cookies.njk', {
cspNonce: reply.cspNonce.script,
govukAnalyticsConsent: request.govukAnalyticsConsentContext,
...languageView(request.headers.cookie, request.raw.url)
})))
await app.listen({ port, host: 'localhost' })