-
Notifications
You must be signed in to change notification settings - Fork 0
/
setup-headers.ts
234 lines (201 loc) · 7.27 KB
/
setup-headers.ts
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import debug from 'debug';
import { Request, Response, NextFunction } from 'express';
const log = debug('reporting-api:headers');
interface ReportingHeadersConfig {
/**
* The reporting group name to use. Set to avoid collision with existing Reporting API usage.
*
* If `enableDefaultReporters` is set, this group name will always be set to `default`
* @default "reporter"
*/
reportingGroup?: string;
/**
* Add a `default` reporter group to receive Deprecation, Crash and Intervention reports
*/
enableDefaultReporters?: boolean;
/**
* Enable `NEL` (Network Error Logging)
*
* Uses Reporting API v0 `Report-To` header as the Reporting API v1 doesn't support
* Network Error Logging. See https://developer.chrome.com/blog/reporting-api-migration#network_error_logging
*/
enableNetworkErrorLogging?:
| boolean
| {
success_fraction?: number;
failure_fraction?: number;
include_subdomains?: boolean;
};
/**
* Report version
*/
version?: string | number;
}
/**
* Headers that support the Reporting API v1
*/
const headers = [
'Content-Security-Policy',
'Content-Security-Policy-Report-Only',
'Permissions-Policy',
'Permissions-Policy-Report-Only',
'Cross-Origin-Opener-Policy',
'Cross-Origin-Opener-Policy-Report-Only',
'Cross-Origin-Embedder-Policy',
'Cross-Origin-Embedder-Policy-Report-Only',
] as const;
type Header = (typeof headers)[number];
/**
* Adds reporting to all existing headers and sets the `Reporting-Endpoints` header
*
* Headers that support the Reporting API `report-to` directive:
*
* - Content-Security-Policy
* - Content-Security-Policy-Report-Only
* - Permissions-Policy
* - Permissions-Policy-Report-Only
* - Cross-Origin-Opener-Policy
* - Cross-Origin-Opener-Policy-Report-Only
* - Cross-Origin-Embedder-Policy
* - Cross-Origin-Embedder-Policy-Report-Only
*
* @param reportingUrl The pathname or full URL for the reporting endpoint
*/
export function setupReportingHeaders(
reportingUrl: string,
config: ReportingHeadersConfig = {}
) {
// If a version is set then include it in the endpoint
if (config.version) {
reportingUrl = addSearchParams(reportingUrl, {
version: String(config.version),
});
}
return (req: Request, res: Response, next?: NextFunction) => {
let setHeader = false;
if (res.getHeader('Reporting-Endpoints')) {
log('Reporting-Endpoints already set, will not set up reporting');
if (next) {
next();
}
return;
}
// The 'default' reporting group always receives Deprecation, Crash and Intervention reports.
// If we do not want to collect those, always use 'reporter' as group name.
const reportTo = config.enableDefaultReporters
? 'default'
: config.reportingGroup || 'reporter';
for (const headerKey of headers) {
const headers = res.getHeader(headerKey);
if (!headers) {
continue;
}
const values = Array.isArray(headers) ? headers : [headers];
for (let i = 0; i < values.length; i++) {
const value = values[i];
if (typeof value !== 'string') {
continue;
}
const newHeader = addReporterToHeader(
headerKey,
value,
reportTo,
reportingUrl
);
if (newHeader) {
values[i] = newHeader;
setHeader = true;
}
}
res.setHeader(headerKey, values as any);
}
// Only set Reporting-Endpoints if any existing header was modified with reporting
if (setHeader) {
res.append('Reporting-Endpoints', `${reportTo}="${reportingUrl}"`);
}
if (config.enableNetworkErrorLogging) {
// Reporting API v1 does not support Network Error Logging
// so we rely on the Reporting API v0 `Report-To` header
// https://developer.chrome.com/blog/reporting-api-migration#network_error_logging
res.append(
'Report-To',
JSON.stringify({
group: reportTo,
max_age: 60 * 60 * 24, // seconds?
endpoints: [{ url: reportingUrl }],
})
);
const nel: any = {
report_to: reportTo,
max_age: 60 * 60 * 24, // 1 day
};
if (typeof config.enableNetworkErrorLogging === 'object') {
nel.failure_fraction =
config.enableNetworkErrorLogging.failure_fraction;
nel.success_fraction =
config.enableNetworkErrorLogging.success_fraction;
nel.include_subdomains =
config.enableNetworkErrorLogging.include_subdomains;
}
res.setHeader('NEL', JSON.stringify(nel));
}
if (next) {
next();
}
return;
};
}
/**
* Adds a reporter to a header
*/
function addReporterToHeader(
header: Header,
value: string,
reportingGroup: string,
reportingUri: string
): string | null {
if (
typeof value !== 'string' ||
value.includes('report-to') ||
value.includes('report-uri ')
) {
log(`Header "%s: %s" already contains reporter`, header, value);
return null;
}
switch (header) {
case 'Content-Security-Policy':
case 'Content-Security-Policy-Report-Only':
// report-uri is deprecated in CSP 3 and ignored if the browser supports report-to, but Firefox does not and will use report-uri
const reportUri = addSearchParams(reportingUri, {
// Older versions of firefox doesn't include the disposition so we track it manually
disposition:
header === 'Content-Security-Policy' ? 'enforce' : 'report',
});
value += `;report-uri ${reportUri}`;
// CSP does not have a `=` between report-to and the group name
value += `;report-to ${reportingGroup}`;
break;
case 'Permissions-Policy':
case 'Permissions-Policy-Report-Only':
// https://github.com/w3c/webappsec-permissions-policy/blob/main/reporting.md
value += `;report-to=${reportingGroup}`;
break;
case 'Cross-Origin-Embedder-Policy':
case 'Cross-Origin-Embedder-Policy-Report-Only':
case 'Cross-Origin-Opener-Policy':
case 'Cross-Origin-Opener-Policy-Report-Only':
// All other headers than CSP needs the `=` and needs to be encapsulated with ""
value += `;report-to="${reportingGroup}"`;
break;
default:
log(`Unknown header ${header}`);
return null;
}
return value;
}
function addSearchParams(url: string, params: Record<string, string>) {
const sep = url.includes('?') ? '&' : '?';
const usp = new URLSearchParams(params);
usp.sort();
return `${url}${sep}${usp.toString()}`;
}