-
Notifications
You must be signed in to change notification settings - Fork 372
/
Copy pathindex.ts
273 lines (239 loc) · 7.85 KB
/
index.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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
import type { IncomingMessage, ServerResponse } from "http";
type ContentSecurityPolicyDirectiveValueFunction = (
req: IncomingMessage,
res: ServerResponse,
) => string;
type ContentSecurityPolicyDirectiveValue =
| string
| ContentSecurityPolicyDirectiveValueFunction;
export interface ContentSecurityPolicyOptions {
useDefaults?: boolean;
directives?: Record<
string,
| null
| Iterable<ContentSecurityPolicyDirectiveValue>
| typeof dangerouslyDisableDefaultSrc
>;
reportOnly?: boolean;
}
type NormalizedDirectives = Map<
string,
Iterable<ContentSecurityPolicyDirectiveValue>
>;
interface ContentSecurityPolicy {
(
options?: Readonly<ContentSecurityPolicyOptions>,
): (
req: IncomingMessage,
res: ServerResponse,
next: (err?: Error) => void,
) => void;
getDefaultDirectives: typeof getDefaultDirectives;
dangerouslyDisableDefaultSrc: typeof dangerouslyDisableDefaultSrc;
}
const dangerouslyDisableDefaultSrc = Symbol("dangerouslyDisableDefaultSrc");
const SHOULD_BE_QUOTED: ReadonlySet<string> = new Set([
"none",
"self",
"strict-dynamic",
"report-sample",
"inline-speculation-rules",
"unsafe-inline",
"unsafe-eval",
"unsafe-hashes",
"wasm-unsafe-eval",
]);
const getDefaultDirectives = (): Record<
string,
Iterable<ContentSecurityPolicyDirectiveValue>
> => ({
"default-src": ["'self'"],
"base-uri": ["'self'"],
"font-src": ["'self'", "https:", "data:"],
"form-action": ["'self'"],
"frame-ancestors": ["'self'"],
"img-src": ["'self'", "data:"],
"object-src": ["'none'"],
"script-src": ["'self'"],
"script-src-attr": ["'none'"],
"style-src": ["'self'", "https:", "'unsafe-inline'"],
"upgrade-insecure-requests": [],
});
const dashify = (str: string): string =>
str.replace(/[A-Z]/g, (capitalLetter) => "-" + capitalLetter.toLowerCase());
const isDirectiveValueInvalid = (directiveValue: string): boolean =>
/;|,/.test(directiveValue);
const isDirectiveValueEntryInvalid = (directiveValueEntry: string): boolean =>
SHOULD_BE_QUOTED.has(directiveValueEntry) ||
directiveValueEntry.startsWith("nonce-") ||
directiveValueEntry.startsWith("sha256-") ||
directiveValueEntry.startsWith("sha384-") ||
directiveValueEntry.startsWith("sha512-");
const invalidDirectiveValueError = (directiveName: string): Error =>
new Error(
`Content-Security-Policy received an invalid directive value for ${JSON.stringify(
directiveName,
)}`,
);
function normalizeDirectives(
options: Readonly<ContentSecurityPolicyOptions>,
): NormalizedDirectives {
const defaultDirectives = getDefaultDirectives();
const { useDefaults = true, directives: rawDirectives = defaultDirectives } =
options;
const result: NormalizedDirectives = new Map();
const directiveNamesSeen = new Set<string>();
const directivesExplicitlyDisabled = new Set<string>();
for (const rawDirectiveName in rawDirectives) {
if (!Object.hasOwn(rawDirectives, rawDirectiveName)) {
continue;
}
if (
rawDirectiveName.length === 0 ||
/[^a-zA-Z0-9-]/.test(rawDirectiveName)
) {
throw new Error(
`Content-Security-Policy received an invalid directive name ${JSON.stringify(
rawDirectiveName,
)}`,
);
}
const directiveName = dashify(rawDirectiveName);
if (directiveNamesSeen.has(directiveName)) {
throw new Error(
`Content-Security-Policy received a duplicate directive ${JSON.stringify(
directiveName,
)}`,
);
}
directiveNamesSeen.add(directiveName);
const rawDirectiveValue = rawDirectives[rawDirectiveName];
let directiveValue: Iterable<ContentSecurityPolicyDirectiveValue>;
if (rawDirectiveValue === null) {
if (directiveName === "default-src") {
throw new Error(
"Content-Security-Policy needs a default-src but it was set to `null`. If you really want to disable it, set it to `contentSecurityPolicy.dangerouslyDisableDefaultSrc`.",
);
}
directivesExplicitlyDisabled.add(directiveName);
continue;
} else if (typeof rawDirectiveValue === "string") {
directiveValue = [rawDirectiveValue];
} else if (!rawDirectiveValue) {
throw new Error(
`Content-Security-Policy received an invalid directive value for ${JSON.stringify(
directiveName,
)}`,
);
} else if (rawDirectiveValue === dangerouslyDisableDefaultSrc) {
if (directiveName === "default-src") {
directivesExplicitlyDisabled.add("default-src");
continue;
} else {
throw new Error(
`Content-Security-Policy: tried to disable ${JSON.stringify(
directiveName,
)} as if it were default-src; simply omit the key`,
);
}
} else {
directiveValue = rawDirectiveValue;
}
for (const element of directiveValue) {
if (
typeof element === "string" &&
(isDirectiveValueInvalid(element) ||
isDirectiveValueEntryInvalid(element))
) {
throw invalidDirectiveValueError(directiveName);
}
}
result.set(directiveName, directiveValue);
}
if (useDefaults) {
Object.entries(defaultDirectives).forEach(
([defaultDirectiveName, defaultDirectiveValue]) => {
if (
!result.has(defaultDirectiveName) &&
!directivesExplicitlyDisabled.has(defaultDirectiveName)
) {
result.set(defaultDirectiveName, defaultDirectiveValue);
}
},
);
}
if (!result.size) {
throw new Error(
"Content-Security-Policy has no directives. Either set some or disable the header",
);
}
if (
!result.has("default-src") &&
!directivesExplicitlyDisabled.has("default-src")
) {
throw new Error(
"Content-Security-Policy needs a default-src but none was provided. If you really want to disable it, set it to `contentSecurityPolicy.dangerouslyDisableDefaultSrc`.",
);
}
return result;
}
function getHeaderValue(
req: IncomingMessage,
res: ServerResponse,
normalizedDirectives: Readonly<NormalizedDirectives>,
): string | Error {
const result: string[] = [];
for (const [directiveName, rawDirectiveValue] of normalizedDirectives) {
let directiveValue = "";
for (const element of rawDirectiveValue) {
if (typeof element === "function") {
const newElement = element(req, res);
if (isDirectiveValueEntryInvalid(newElement)) {
return invalidDirectiveValueError(directiveName);
}
directiveValue += " " + newElement;
} else {
directiveValue += " " + element;
}
}
if (!directiveValue) {
result.push(directiveName);
} else if (isDirectiveValueInvalid(directiveValue)) {
return invalidDirectiveValueError(directiveName);
} else {
result.push(`${directiveName}${directiveValue}`);
}
}
return result.join(";");
}
const contentSecurityPolicy: ContentSecurityPolicy =
function contentSecurityPolicy(
options: Readonly<ContentSecurityPolicyOptions> = {},
): (
req: IncomingMessage,
res: ServerResponse,
next: (err?: Error) => void,
) => void {
const headerName = options.reportOnly
? "Content-Security-Policy-Report-Only"
: "Content-Security-Policy";
const normalizedDirectives = normalizeDirectives(options);
return function contentSecurityPolicyMiddleware(
req: IncomingMessage,
res: ServerResponse,
next: (error?: Error) => void,
) {
const result = getHeaderValue(req, res, normalizedDirectives);
if (result instanceof Error) {
next(result);
} else {
res.setHeader(headerName, result);
next();
}
};
};
contentSecurityPolicy.getDefaultDirectives = getDefaultDirectives;
contentSecurityPolicy.dangerouslyDisableDefaultSrc =
dangerouslyDisableDefaultSrc;
export default contentSecurityPolicy;
export { getDefaultDirectives, dangerouslyDisableDefaultSrc };