@caelo-cms/shared 0.11.21 → 0.12.1
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/dist/ai-tools.d.ts +4 -0
- package/dist/ai-tools.d.ts.map +1 -1
- package/dist/ai-tools.js +6 -0
- package/dist/ai-tools.js.map +1 -1
- package/dist/bug-intake.d.ts +15 -0
- package/dist/bug-intake.d.ts.map +1 -1
- package/dist/bug-intake.js +14 -0
- package/dist/bug-intake.js.map +1 -1
- package/dist/change-journal.d.ts.map +1 -1
- package/dist/change-journal.js +1 -0
- package/dist/change-journal.js.map +1 -1
- package/dist/context.d.ts +26 -0
- package/dist/context.d.ts.map +1 -1
- package/dist/context.js +2 -1
- package/dist/context.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/link-refs.d.ts +18 -2
- package/dist/link-refs.d.ts.map +1 -1
- package/dist/link-refs.js +24 -6
- package/dist/link-refs.js.map +1 -1
- package/dist/lists/address.d.ts +6 -0
- package/dist/lists/address.d.ts.map +1 -1
- package/dist/lists/address.js +9 -1
- package/dist/lists/address.js.map +1 -1
- package/dist/lists/resolve-values.d.ts +11 -0
- package/dist/lists/resolve-values.d.ts.map +1 -1
- package/dist/lists/resolve-values.js +19 -0
- package/dist/lists/resolve-values.js.map +1 -1
- package/dist/lists/resolve.d.ts +5 -0
- package/dist/lists/resolve.d.ts.map +1 -1
- package/dist/lists/resolve.js +7 -0
- package/dist/lists/resolve.js.map +1 -1
- package/dist/owner-setup-token.d.ts +28 -0
- package/dist/owner-setup-token.d.ts.map +1 -0
- package/dist/owner-setup-token.js +41 -0
- package/dist/owner-setup-token.js.map +1 -0
- package/dist/redirect-emit-front-door.d.ts.map +1 -1
- package/dist/redirect-emit-front-door.js +4 -0
- package/dist/redirect-emit-front-door.js.map +1 -1
- package/dist/redirect-emit-gcp.d.ts +8 -0
- package/dist/redirect-emit-gcp.d.ts.map +1 -1
- package/dist/redirect-emit-gcp.js +4 -1
- package/dist/redirect-emit-gcp.js.map +1 -1
- package/dist/redirect-plan.d.ts +2 -2
- package/dist/redirect-plan.d.ts.map +1 -1
- package/dist/redirect-plan.js +13 -4
- package/dist/redirect-plan.js.map +1 -1
- package/dist/redirect-target.d.ts +57 -7
- package/dist/redirect-target.d.ts.map +1 -1
- package/dist/redirect-target.js +130 -8
- package/dist/redirect-target.js.map +1 -1
- package/dist/seo.d.ts +21 -0
- package/dist/seo.d.ts.map +1 -1
- package/dist/seo.js +21 -0
- package/dist/seo.js.map +1 -1
- package/dist/site-security-headers.d.ts +323 -0
- package/dist/site-security-headers.d.ts.map +1 -0
- package/dist/site-security-headers.js +424 -0
- package/dist/site-security-headers.js.map +1 -0
- package/dist/staged-site.d.ts +11 -0
- package/dist/staged-site.d.ts.map +1 -1
- package/dist/staged-site.js +26 -0
- package/dist/staged-site.js.map +1 -1
- package/dist/template-engine.d.ts +7 -0
- package/dist/template-engine.d.ts.map +1 -1
- package/dist/template-engine.js +38 -1
- package/dist/template-engine.js.map +1 -1
- package/dist/template-sections.d.ts +23 -1
- package/dist/template-sections.d.ts.map +1 -1
- package/dist/template-sections.js +124 -17
- package/dist/template-sections.js.map +1 -1
- package/dist/version.d.ts +2 -2
- package/dist/version.d.ts.map +1 -1
- package/dist/version.js +1 -1
- package/dist/version.js.map +1 -1
- package/package.json +1 -1
- package/src/ai-tools.ts +7 -0
- package/src/bug-intake.ts +16 -0
- package/src/change-journal.ts +1 -0
- package/src/context.ts +28 -0
- package/src/index.ts +2 -0
- package/src/link-refs.test.ts +38 -4
- package/src/link-refs.ts +39 -6
- package/src/lists/address.ts +16 -1
- package/src/lists/lists.test.ts +2 -0
- package/src/lists/resolve-values.ts +19 -0
- package/src/lists/resolve.test.ts +8 -0
- package/src/lists/resolve.ts +8 -0
- package/src/owner-setup-token.ts +49 -0
- package/src/redirect-emit-front-door.ts +6 -0
- package/src/redirect-emit-gcp.ts +12 -1
- package/src/redirect-emit.test.ts +44 -0
- package/src/redirect-plan.test.ts +57 -0
- package/src/redirect-plan.ts +12 -5
- package/src/redirect-target.test.ts +110 -4
- package/src/redirect-target.ts +142 -8
- package/src/seo.test.ts +24 -0
- package/src/seo.ts +25 -0
- package/src/site-security-headers.test.ts +263 -0
- package/src/site-security-headers.ts +509 -0
- package/src/staged-site.ts +30 -0
- package/src/template-engine-link-field.test.ts +148 -0
- package/src/template-engine-lists.test.ts +1 -1
- package/src/template-engine.ts +41 -1
- package/src/template-sections.ts +136 -20
- package/src/version.ts +1 -1
|
@@ -0,0 +1,509 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MPL-2.0
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Issue #1454 — the response headers of a site's pages, the one definition
|
|
5
|
+
* every host serves them from (docs/dev/site-security-headers.md).
|
|
6
|
+
*
|
|
7
|
+
* The Owner's {@link SiteSecurityPolicy} (`site_settings.security_headers`)
|
|
8
|
+
* and what a build really ships ({@link SiteCspFacts}, scanned from its
|
|
9
|
+
* pages) make one {@link SiteHeaderSet}. The generator writes it into the
|
|
10
|
+
* build as {@link SECURITY_HEADERS_BUILD_FILE}, so a build and its headers
|
|
11
|
+
* travel together: a CSP derived from one build can never sit on the files
|
|
12
|
+
* of another, which is what would take a site's scripts down. That makes
|
|
13
|
+
* the setting a RENDERED one (CLAUDE.md §2): it goes live with a human
|
|
14
|
+
* Publish live, and a rollback restores the headers of the build it restores.
|
|
15
|
+
*
|
|
16
|
+
* Two levels, so that a rollout cannot break a live site:
|
|
17
|
+
*
|
|
18
|
+
* - Always enforced, on every install: Referrer-Policy, Permissions-Policy,
|
|
19
|
+
* clickjacking protection and the part of the CSP that blocks no script
|
|
20
|
+
* (`frame-ancestors`, `base-uri`, `object-src`).
|
|
21
|
+
* - The full CSP: `Content-Security-Policy-Report-Only` until the Owner
|
|
22
|
+
* switches `cspMode` to `enforce`. Report-only breaks nothing; the Stage's
|
|
23
|
+
* Lighthouse run reports each violation with its next step, and the
|
|
24
|
+
* `security-headers` quality check names what could not be derived. That
|
|
25
|
+
* is all the evidence there is: {@link ENFORCE_EVIDENCE_NOTE}.
|
|
26
|
+
*
|
|
27
|
+
* `script-src` carries no `'unsafe-inline'`: it is `'self'`, the origins the
|
|
28
|
+
* build references and the hashes of the few inline scripts left, because
|
|
29
|
+
* the composer's per-page script is a content-hashed file on a deployed page
|
|
30
|
+
* (static-generator page-scripts-pass.ts). A hash per page would not fit a
|
|
31
|
+
* header on a 50,000-page site. `style-src` does keep `'unsafe-inline'`:
|
|
32
|
+
* `style` attributes cannot be hashed, shadow-DOM `<style>` of plugin
|
|
33
|
+
* components is written at runtime, and each page's inline `<style>` varies
|
|
34
|
+
* with its modules. A linked stylesheet instead would block first paint, and
|
|
35
|
+
* CSS cannot run script.
|
|
36
|
+
*/
|
|
37
|
+
|
|
38
|
+
import { z } from "zod";
|
|
39
|
+
import { NOSNIFF } from "./static-security-headers.js";
|
|
40
|
+
|
|
41
|
+
/** The build file holding the {@link SiteHeaderSet}; served, and read by every publisher. */
|
|
42
|
+
export const SECURITY_HEADERS_BUILD_FILE = "_security-headers.json";
|
|
43
|
+
|
|
44
|
+
/** The source lists an Owner or a build can add to, by what the browser loads. */
|
|
45
|
+
export const CSP_SOURCE_KINDS = [
|
|
46
|
+
"script",
|
|
47
|
+
"style",
|
|
48
|
+
"img",
|
|
49
|
+
"font",
|
|
50
|
+
"connect",
|
|
51
|
+
"frame",
|
|
52
|
+
"media",
|
|
53
|
+
"form",
|
|
54
|
+
] as const;
|
|
55
|
+
export type CspSourceKind = (typeof CSP_SOURCE_KINDS)[number];
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The most bytes of header names and values one page may carry. Hard limit
|
|
59
|
+
* on `gcp`: 8 KB of custom headers per backend, nosniff included. Firebase
|
|
60
|
+
* documents none, so the same figure is the safe one there; browsers and
|
|
61
|
+
* proxies start refusing around 8 KB too.
|
|
62
|
+
*/
|
|
63
|
+
export const SITE_HEADERS_MAX_BYTES = 6 * 1024;
|
|
64
|
+
|
|
65
|
+
/** Features every page denies. Autoplay, fullscreen and the like stay open: video embeds use them. */
|
|
66
|
+
export const DENIED_BROWSER_FEATURES = [
|
|
67
|
+
"bluetooth",
|
|
68
|
+
"camera",
|
|
69
|
+
"geolocation",
|
|
70
|
+
"hid",
|
|
71
|
+
"microphone",
|
|
72
|
+
"midi",
|
|
73
|
+
"payment",
|
|
74
|
+
"serial",
|
|
75
|
+
"usb",
|
|
76
|
+
] as const;
|
|
77
|
+
|
|
78
|
+
/** The `Referrer-Policy` values an Owner may pick (no `unsafe-url`: it leaks full URLs). */
|
|
79
|
+
export const REFERRER_POLICIES = [
|
|
80
|
+
"strict-origin-when-cross-origin",
|
|
81
|
+
"strict-origin",
|
|
82
|
+
"same-origin",
|
|
83
|
+
"no-referrer",
|
|
84
|
+
] as const;
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* What enforcing rests on, said wherever the switch is made. There is no
|
|
88
|
+
* report endpoint, so nothing from a visitor's browser reaches anyone.
|
|
89
|
+
*/
|
|
90
|
+
export const ENFORCE_EVIDENCE_NOTE =
|
|
91
|
+
"Enforcing rests on what the Stage's quality check saw. It opens a few pages and gives no consent, so a violation on any other page, or after a visitor consents, reaches nobody and is blocked for visitors.";
|
|
92
|
+
|
|
93
|
+
/** Why a build shipped no page headers, for a Publish live or rollback of one. */
|
|
94
|
+
export const NO_BUILD_HEADERS_NOTE =
|
|
95
|
+
"No security headers shipped: this build was staged before Caelo sent them, so the site serves it without them. A new Stage and Publish live fixes it.";
|
|
96
|
+
|
|
97
|
+
const ORIGIN_RE =
|
|
98
|
+
/^(https|wss):\/\/(\*\.)?[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+(:\d{1,5})?$/;
|
|
99
|
+
|
|
100
|
+
/** One origin in a source list: scheme and host, lower case, no path. */
|
|
101
|
+
export const cspOriginSchema = z
|
|
102
|
+
.string()
|
|
103
|
+
.max(253)
|
|
104
|
+
.regex(
|
|
105
|
+
ORIGIN_RE,
|
|
106
|
+
"an origin like https://cdn.example.com or https://*.example.com: https or wss, no path, no keyword such as 'unsafe-inline', 'unsafe-eval', * or data:",
|
|
107
|
+
);
|
|
108
|
+
|
|
109
|
+
const originList = (max: number) =>
|
|
110
|
+
z
|
|
111
|
+
.array(cspOriginSchema)
|
|
112
|
+
.max(max)
|
|
113
|
+
.refine((list) => new Set(list).size === list.length, { message: "each origin only once" });
|
|
114
|
+
|
|
115
|
+
/** Extra origins per kind; a kind left out has none. */
|
|
116
|
+
export const cspExtraSourcesSchema = z
|
|
117
|
+
.object({
|
|
118
|
+
script: originList(50).optional(),
|
|
119
|
+
style: originList(50).optional(),
|
|
120
|
+
img: originList(50).optional(),
|
|
121
|
+
font: originList(50).optional(),
|
|
122
|
+
connect: originList(50).optional(),
|
|
123
|
+
frame: originList(50).optional(),
|
|
124
|
+
media: originList(50).optional(),
|
|
125
|
+
form: originList(50).optional(),
|
|
126
|
+
})
|
|
127
|
+
.strict();
|
|
128
|
+
|
|
129
|
+
/** The Owner's policy, as `site_settings.security_headers` stores it. */
|
|
130
|
+
export const siteSecurityPolicySchema = z
|
|
131
|
+
.object({
|
|
132
|
+
/** `report_only` breaks nothing; `enforce` makes browsers block what the policy leaves out. */
|
|
133
|
+
cspMode: z.enum(["report_only", "enforce"]),
|
|
134
|
+
/** Origins that may frame the site, beside itself. */
|
|
135
|
+
frameAncestors: originList(20),
|
|
136
|
+
referrerPolicy: z.enum(REFERRER_POLICIES),
|
|
137
|
+
/** Features this site's own pages use (`feature=(self)` instead of denied). */
|
|
138
|
+
allowedFeatures: z.array(z.enum(DENIED_BROWSER_FEATURES)).max(DENIED_BROWSER_FEATURES.length),
|
|
139
|
+
/** Where the host does not send HSTS itself. Browsers remember it: hard to take back. */
|
|
140
|
+
hsts: z
|
|
141
|
+
.object({
|
|
142
|
+
maxAgeSeconds: z.number().int().min(0).max(63_072_000),
|
|
143
|
+
includeSubdomains: z.boolean(),
|
|
144
|
+
preload: z.boolean(),
|
|
145
|
+
})
|
|
146
|
+
.strict(),
|
|
147
|
+
/** Origins the build cannot see: what a tag or module script loads at runtime. */
|
|
148
|
+
extraSources: cspExtraSourcesSchema,
|
|
149
|
+
})
|
|
150
|
+
.strict();
|
|
151
|
+
export type SiteSecurityPolicy = z.infer<typeof siteSecurityPolicySchema>;
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* The stored default of every install (migration 0639): the full CSP is
|
|
155
|
+
* report-only, so an update cannot take a site's scripts down.
|
|
156
|
+
*/
|
|
157
|
+
export const DEFAULT_SITE_SECURITY_POLICY: SiteSecurityPolicy = {
|
|
158
|
+
cspMode: "report_only",
|
|
159
|
+
frameAncestors: [],
|
|
160
|
+
referrerPolicy: "strict-origin-when-cross-origin",
|
|
161
|
+
allowedFeatures: [],
|
|
162
|
+
hsts: { maxAgeSeconds: 31_536_000, includeSubdomains: false, preload: false },
|
|
163
|
+
extraSources: {},
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* What a plugin's client code reaches, returned as the reserved
|
|
168
|
+
* `csp-sources.json` of `buildAssets`: the build cannot see what a runtime
|
|
169
|
+
* injects after consent.
|
|
170
|
+
*/
|
|
171
|
+
export const pluginCspSourcesSchema = z
|
|
172
|
+
.object({
|
|
173
|
+
origins: z
|
|
174
|
+
.object({
|
|
175
|
+
script: z.array(cspOriginSchema).max(100).optional(),
|
|
176
|
+
style: z.array(cspOriginSchema).max(100).optional(),
|
|
177
|
+
img: z.array(cspOriginSchema).max(100).optional(),
|
|
178
|
+
font: z.array(cspOriginSchema).max(100).optional(),
|
|
179
|
+
connect: z.array(cspOriginSchema).max(100).optional(),
|
|
180
|
+
frame: z.array(cspOriginSchema).max(100).optional(),
|
|
181
|
+
media: z.array(cspOriginSchema).max(100).optional(),
|
|
182
|
+
form: z.array(cspOriginSchema).max(100).optional(),
|
|
183
|
+
})
|
|
184
|
+
.strict()
|
|
185
|
+
.optional(),
|
|
186
|
+
/** Exact text of inline scripts its runtime injects; the build hashes them. */
|
|
187
|
+
inlineScripts: z.array(z.string().max(60_000)).max(200).optional(),
|
|
188
|
+
})
|
|
189
|
+
.strict();
|
|
190
|
+
export type PluginCspSources = z.infer<typeof pluginCspSourcesSchema>;
|
|
191
|
+
|
|
192
|
+
/** Markup no CSP without `'unsafe-inline'` lets run. */
|
|
193
|
+
export const cspBlockerSchema = z.object({
|
|
194
|
+
kind: z.enum(["inline-handler", "javascript-url", "data-script", "foreign-base"]),
|
|
195
|
+
/** What was found: `onclick`, the `<base>` target, … */
|
|
196
|
+
detail: z.string().max(200),
|
|
197
|
+
/** Pages it is on, a sample. */
|
|
198
|
+
pages: z.array(z.string().max(1024)).max(5),
|
|
199
|
+
/** On how many pages it is. */
|
|
200
|
+
pageCount: z.number().int().nonnegative(),
|
|
201
|
+
});
|
|
202
|
+
export type CspBlocker = z.infer<typeof cspBlockerSchema>;
|
|
203
|
+
|
|
204
|
+
/** What one build ships, as far as the policy depends on it. */
|
|
205
|
+
export const siteCspFactsSchema = z.object({
|
|
206
|
+
/** Third-party origins per kind, sorted. The site itself is `'self'`. */
|
|
207
|
+
origins: z.partialRecord(z.enum(CSP_SOURCE_KINDS), z.array(z.string())),
|
|
208
|
+
/** Inline scripts, as CSP sources (`'sha256-…'`), sorted. */
|
|
209
|
+
inlineScriptHashes: z.array(z.string()),
|
|
210
|
+
/** `object-src` sources of `<object>` and `<embed>`, sorted. */
|
|
211
|
+
objectOrigins: z.array(z.string()),
|
|
212
|
+
/**
|
|
213
|
+
* Inline scripts holding the build's own origin. The staging gateway
|
|
214
|
+
* rewrites that origin in the body, which changes their hash, so it hashes
|
|
215
|
+
* them again for its host (staging/site.ts).
|
|
216
|
+
*/
|
|
217
|
+
originBoundScripts: z.array(z.string()),
|
|
218
|
+
blockers: z.array(cspBlockerSchema),
|
|
219
|
+
/** What each plugin contributed, shown to the Owner beside the policy. */
|
|
220
|
+
plugins: z.array(
|
|
221
|
+
z.object({
|
|
222
|
+
slug: z.string(),
|
|
223
|
+
origins: z.array(z.string()),
|
|
224
|
+
inlineScripts: z.number().int().nonnegative(),
|
|
225
|
+
}),
|
|
226
|
+
),
|
|
227
|
+
});
|
|
228
|
+
export type SiteCspFacts = z.infer<typeof siteCspFactsSchema>;
|
|
229
|
+
|
|
230
|
+
/** Facts of a build that ships nothing third-party (a policy's preview before the first Stage). */
|
|
231
|
+
export const EMPTY_CSP_FACTS: SiteCspFacts = {
|
|
232
|
+
origins: {},
|
|
233
|
+
inlineScriptHashes: [],
|
|
234
|
+
objectOrigins: [],
|
|
235
|
+
originBoundScripts: [],
|
|
236
|
+
blockers: [],
|
|
237
|
+
plugins: [],
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
/** The headers of one build ({@link SECURITY_HEADERS_BUILD_FILE}). */
|
|
241
|
+
export const siteHeaderSetSchema = z.object({
|
|
242
|
+
version: z.literal(1),
|
|
243
|
+
policy: siteSecurityPolicySchema,
|
|
244
|
+
facts: siteCspFactsSchema,
|
|
245
|
+
/** On every document, on every host. */
|
|
246
|
+
headers: z.record(z.string(), z.string()),
|
|
247
|
+
/** `Strict-Transport-Security`, for hosts that do not send their own; null at max-age 0. */
|
|
248
|
+
hsts: z.string().nullable(),
|
|
249
|
+
/** True when the CSP did not fit and a report-only build left parts of it out. */
|
|
250
|
+
cspCut: z.boolean(),
|
|
251
|
+
});
|
|
252
|
+
export type SiteHeaderSet = z.infer<typeof siteHeaderSetSchema>;
|
|
253
|
+
|
|
254
|
+
function uniqueSorted(values: Iterable<string>): string[] {
|
|
255
|
+
return [...new Set(values)].sort();
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function directive(name: string, sources: readonly string[]): string {
|
|
259
|
+
return `${name} ${sources.join(" ")}`;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function frameAncestors(policy: SiteSecurityPolicy): string {
|
|
263
|
+
return directive("frame-ancestors", ["'self'", ...policy.frameAncestors]);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function objectSrc(facts: SiteCspFacts): string {
|
|
267
|
+
return directive("object-src", facts.objectOrigins.length > 0 ? facts.objectOrigins : ["'none'"]);
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** The directives enforced in every mode: none of them can stop a script or a style. */
|
|
271
|
+
function baselineCsp(policy: SiteSecurityPolicy, facts: SiteCspFacts): string[] {
|
|
272
|
+
return [frameAncestors(policy), "base-uri 'self'", objectSrc(facts)];
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* The full policy.
|
|
277
|
+
*
|
|
278
|
+
* @param hashes - the inline-script sources it allows.
|
|
279
|
+
*/
|
|
280
|
+
function fullCsp(
|
|
281
|
+
policy: SiteSecurityPolicy,
|
|
282
|
+
facts: SiteCspFacts,
|
|
283
|
+
hashes: readonly string[],
|
|
284
|
+
): string {
|
|
285
|
+
const of = (kind: (typeof CSP_SOURCE_KINDS)[number]) =>
|
|
286
|
+
uniqueSorted([...(facts.origins[kind] ?? []), ...(policy.extraSources[kind] ?? [])]);
|
|
287
|
+
return [
|
|
288
|
+
"default-src 'self'",
|
|
289
|
+
directive("script-src", ["'self'", ...hashes, ...of("script")]),
|
|
290
|
+
// 'unsafe-inline': see the file comment.
|
|
291
|
+
directive("style-src", ["'self'", "'unsafe-inline'", ...of("style")]),
|
|
292
|
+
// data: — inline SVG backgrounds and icons; blob: — what a module draws on a canvas.
|
|
293
|
+
directive("img-src", ["'self'", "data:", "blob:", ...of("img")]),
|
|
294
|
+
directive("font-src", ["'self'", "data:", ...of("font")]),
|
|
295
|
+
directive("connect-src", ["'self'", ...of("connect")]),
|
|
296
|
+
directive("media-src", ["'self'", "blob:", ...of("media")]),
|
|
297
|
+
directive("frame-src", ["'self'", ...of("frame")]),
|
|
298
|
+
directive("form-action", ["'self'", ...of("form")]),
|
|
299
|
+
...baselineCsp(policy, facts),
|
|
300
|
+
].join("; ");
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function permissionsPolicy(policy: SiteSecurityPolicy): string {
|
|
304
|
+
const allowed = new Set<string>(policy.allowedFeatures);
|
|
305
|
+
return DENIED_BROWSER_FEATURES.map((f) => `${f}=${allowed.has(f) ? "(self)" : "()"}`).join(", ");
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function hstsValue(policy: SiteSecurityPolicy): string | null {
|
|
309
|
+
const { maxAgeSeconds, includeSubdomains, preload } = policy.hsts;
|
|
310
|
+
if (maxAgeSeconds === 0) return null;
|
|
311
|
+
return [
|
|
312
|
+
`max-age=${maxAgeSeconds}`,
|
|
313
|
+
...(includeSubdomains ? ["includeSubDomains"] : []),
|
|
314
|
+
...(preload ? ["preload"] : []),
|
|
315
|
+
].join("; ");
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
function headerBytes(headers: Readonly<Record<string, string>>): number {
|
|
319
|
+
const encoder = new TextEncoder();
|
|
320
|
+
return Object.entries(headers).reduce(
|
|
321
|
+
(sum, [name, value]) => sum + name.length + encoder.encode(value).length,
|
|
322
|
+
0,
|
|
323
|
+
);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** The policy does not fit a response header (see {@link SITE_HEADERS_MAX_BYTES}). */
|
|
327
|
+
export class SiteHeadersTooLargeError extends Error {
|
|
328
|
+
constructor(bytes: number, hashes: number) {
|
|
329
|
+
super(
|
|
330
|
+
`The site's security headers take ${bytes} bytes, over the ${SITE_HEADERS_MAX_BYTES} that fit a response, with ${hashes} inline script hashes in the CSP. Move inline <script> elements of modules into the module's js, or remove origins from the policy's extraSources, then Stage again. To Stage meanwhile, propose cspMode report_only.`,
|
|
331
|
+
);
|
|
332
|
+
this.name = "SiteHeadersTooLargeError";
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* The headers of one build.
|
|
338
|
+
*
|
|
339
|
+
* In report-only mode a policy that does not fit loses its inline hashes, and
|
|
340
|
+
* then the report-only header (`cspCut`): the page keeps working, the quality
|
|
341
|
+
* check says so and `enforce` stays closed. In enforce mode the same policy
|
|
342
|
+
* would block scripts, so the build stops instead.
|
|
343
|
+
*
|
|
344
|
+
* @throws {@link SiteHeadersTooLargeError} when an enforced policy does not fit.
|
|
345
|
+
*/
|
|
346
|
+
export function composeSiteHeaders(policy: SiteSecurityPolicy, facts: SiteCspFacts): SiteHeaderSet {
|
|
347
|
+
const base: Record<string, string> = {
|
|
348
|
+
"Referrer-Policy": policy.referrerPolicy,
|
|
349
|
+
"Permissions-Policy": permissionsPolicy(policy),
|
|
350
|
+
// X-Frame-Options has no list; with extra ancestors only the CSP can say it.
|
|
351
|
+
...(policy.frameAncestors.length === 0 ? { "X-Frame-Options": "SAMEORIGIN" } : {}),
|
|
352
|
+
};
|
|
353
|
+
const hsts = hstsValue(policy);
|
|
354
|
+
const compose = (hashes: readonly string[]): Record<string, string> =>
|
|
355
|
+
policy.cspMode === "enforce"
|
|
356
|
+
? { ...base, "Content-Security-Policy": fullCsp(policy, facts, hashes) }
|
|
357
|
+
: {
|
|
358
|
+
...base,
|
|
359
|
+
"Content-Security-Policy": baselineCsp(policy, facts).join("; "),
|
|
360
|
+
"Content-Security-Policy-Report-Only": fullCsp(policy, facts, hashes),
|
|
361
|
+
};
|
|
362
|
+
const size = (headers: Readonly<Record<string, string>>) =>
|
|
363
|
+
headerBytes(headers) + (hsts === null ? 0 : hsts.length + "Strict-Transport-Security".length);
|
|
364
|
+
const set = { version: 1 as const, policy, facts, hsts };
|
|
365
|
+
const headers = compose(facts.inlineScriptHashes);
|
|
366
|
+
if (size(headers) <= SITE_HEADERS_MAX_BYTES) return { ...set, headers, cspCut: false };
|
|
367
|
+
if (policy.cspMode === "enforce") {
|
|
368
|
+
throw new SiteHeadersTooLargeError(size(headers), facts.inlineScriptHashes.length);
|
|
369
|
+
}
|
|
370
|
+
const reduced = compose([]);
|
|
371
|
+
if (size(reduced) <= SITE_HEADERS_MAX_BYTES) return { ...set, headers: reduced, cspCut: true };
|
|
372
|
+
const { "Content-Security-Policy-Report-Only": _cut, ...baseline } = reduced;
|
|
373
|
+
return { ...set, headers: baseline, cspCut: true };
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** Parse {@link SECURITY_HEADERS_BUILD_FILE}. */
|
|
377
|
+
export function parseSiteHeaderSet(text: string): SiteHeaderSet {
|
|
378
|
+
return siteHeaderSetSchema.parse(JSON.parse(text));
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* What would break in `enforce` that the build can already see: blockers in
|
|
383
|
+
* the markup, or hashes that did not fit. Empty when it is safe to offer.
|
|
384
|
+
*/
|
|
385
|
+
export function enforceBlockers(set: SiteHeaderSet): string[] {
|
|
386
|
+
const out = set.facts.blockers.map(
|
|
387
|
+
(b) => `${b.kind} ${b.detail} on ${b.pageCount} page(s), e.g. ${b.pages[0] ?? "?"}`,
|
|
388
|
+
);
|
|
389
|
+
if (set.cspCut) out.push("the full CSP does not fit a response header");
|
|
390
|
+
return out;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// ─── hosts ─────────────────────────────────────────────────────────────
|
|
394
|
+
|
|
395
|
+
/** How one host serves the headers, or why it cannot. */
|
|
396
|
+
export interface SiteHeaderHost {
|
|
397
|
+
/** False where no publisher exists: a Stage refuses there. */
|
|
398
|
+
readonly served: boolean;
|
|
399
|
+
/** The host sends HSTS itself, so the policy's `hsts` is not used. */
|
|
400
|
+
readonly hostSendsHsts: boolean;
|
|
401
|
+
readonly note: string;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/** Per `CAELO_PROVIDER`. */
|
|
405
|
+
export const SITE_HEADER_HOSTS: Readonly<Record<string, SiteHeaderHost>> = {
|
|
406
|
+
"gcp-firebase": {
|
|
407
|
+
served: true,
|
|
408
|
+
hostSendsHsts: true,
|
|
409
|
+
note: "In the Hosting version: they go live with the release of the build.",
|
|
410
|
+
},
|
|
411
|
+
gcp: {
|
|
412
|
+
served: true,
|
|
413
|
+
hostSendsHsts: false,
|
|
414
|
+
note: "Custom headers of the static backend bucket, set by Publish live and rollback.",
|
|
415
|
+
},
|
|
416
|
+
"self-hosted": {
|
|
417
|
+
served: true,
|
|
418
|
+
hostSendsHsts: false,
|
|
419
|
+
note: "Caddy, from the _redirects.caddy snippet of the build it serves.",
|
|
420
|
+
},
|
|
421
|
+
aws: {
|
|
422
|
+
served: false,
|
|
423
|
+
hostSendsHsts: false,
|
|
424
|
+
note: "No static publisher exists on AWS yet (#749), so nothing is published here.",
|
|
425
|
+
},
|
|
426
|
+
azure: {
|
|
427
|
+
served: false,
|
|
428
|
+
hostSendsHsts: false,
|
|
429
|
+
note: "No static publisher exists on Azure yet (#750), so nothing is published here.",
|
|
430
|
+
},
|
|
431
|
+
};
|
|
432
|
+
|
|
433
|
+
const FIRST_SEGMENT = "(?:[^_a/][^/]*|a(?:[^p/][^/]*)?|ap(?:[^i/][^/]*)?|api[^/]+)";
|
|
434
|
+
const FIRST_SEGMENT_NO_DOT = "(?:[^_a/.][^/.]*|a(?:[^p/.][^/.]*)?|ap(?:[^i/.][^/.]*)?|api[^/.]+)";
|
|
435
|
+
|
|
436
|
+
/**
|
|
437
|
+
* RE2-and-ECMAScript regex for a path that serves a page: `/`, `/about`,
|
|
438
|
+
* `/about/`, `/a/b`, `/about.html`; never `/api`, `/api/…`, `/_…` or a file
|
|
439
|
+
* with another extension. Disjoint from `SVG_PATH_PATTERN`, because Firebase
|
|
440
|
+
* does not document which entry wins when two set the same header. A
|
|
441
|
+
* document is all a CSP acts on, so other files need no entry.
|
|
442
|
+
*/
|
|
443
|
+
export const SITE_DOCUMENT_PATH_PATTERN = `^/(?:${FIRST_SEGMENT}/(?:.*/|.*\\.html|(?:.*/)?[^/.]+)?|${FIRST_SEGMENT_NO_DOT}|[^_/][^/]*\\.html)?$`;
|
|
444
|
+
|
|
445
|
+
function withHsts(set: SiteHeaderSet): Record<string, string> {
|
|
446
|
+
return set.hsts === null
|
|
447
|
+
? set.headers
|
|
448
|
+
: { ...set.headers, "Strict-Transport-Security": set.hsts };
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/** Caddyfile lines serving `set` on the documents of a public vhost. */
|
|
452
|
+
export function emitCaddySiteHeaders(set: SiteHeaderSet): string {
|
|
453
|
+
const lines = ["@caelo_documents {", "\tnot path /api/* /_*", "\tnot path *.svg", "}"];
|
|
454
|
+
for (const [name, value] of Object.entries(withHsts(set))) {
|
|
455
|
+
// A quote or backslash would end the quoted string and a brace would be
|
|
456
|
+
// read as a Caddy placeholder; the composer never produces one, so one
|
|
457
|
+
// here is a broken build file, not something to escape.
|
|
458
|
+
if (!/^[A-Za-z0-9-]+$/.test(name) || !/^[ -~]*$/.test(value) || /["\\{}]/.test(value)) {
|
|
459
|
+
throw new Error(
|
|
460
|
+
`The build's ${name} header holds a character a Caddyfile cannot carry (quote, backslash, brace or control character). Stage again; if it repeats, the build's ${SECURITY_HEADERS_BUILD_FILE} is corrupt.`,
|
|
461
|
+
);
|
|
462
|
+
}
|
|
463
|
+
lines.push(`header @caelo_documents ${name} "${value}"`);
|
|
464
|
+
}
|
|
465
|
+
return `${lines.join("\n")}\n`;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/**
|
|
469
|
+
* The static backend bucket's `customResponseHeaders` on `gcp`, in the
|
|
470
|
+
* `Name: value` form of the Compute API. One list per bucket, so it covers
|
|
471
|
+
* every file; harmless, a CSP only acts on documents and an SVG is served
|
|
472
|
+
* as a download there (`gcsObjectMetadata`). Nosniff stays first: it is the
|
|
473
|
+
* entry the provisioning stack owns.
|
|
474
|
+
*
|
|
475
|
+
* @param set - null for a build from before the headers: its files must not
|
|
476
|
+
* keep the previous build's CSP, which names other inline scripts.
|
|
477
|
+
*/
|
|
478
|
+
export function gcpBackendBucketHeaders(set: SiteHeaderSet | null): string[] {
|
|
479
|
+
return [
|
|
480
|
+
`X-Content-Type-Options: ${NOSNIFF}`,
|
|
481
|
+
...(set === null ? [] : Object.entries(withHsts(set))).map(
|
|
482
|
+
([name, value]) => `${name}: ${value}`,
|
|
483
|
+
),
|
|
484
|
+
];
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/** The staged manifest's fields for a build's headers. */
|
|
488
|
+
export function stagedHeaderFields(set: SiteHeaderSet): {
|
|
489
|
+
securityHeaders: Record<string, string>;
|
|
490
|
+
originBoundScripts: string[];
|
|
491
|
+
} {
|
|
492
|
+
return { securityHeaders: set.headers, originBoundScripts: set.facts.originBoundScripts };
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
/** `headers` with more inline-script sources in whichever CSP has a `script-src`. */
|
|
496
|
+
export function withScriptHashes(
|
|
497
|
+
headers: Readonly<Record<string, string>>,
|
|
498
|
+
hashes: readonly string[],
|
|
499
|
+
): Record<string, string> {
|
|
500
|
+
if (hashes.length === 0) return { ...headers };
|
|
501
|
+
const out = { ...headers };
|
|
502
|
+
for (const name of ["Content-Security-Policy", "Content-Security-Policy-Report-Only"]) {
|
|
503
|
+
const value = out[name];
|
|
504
|
+
if (value?.includes("script-src 'self'")) {
|
|
505
|
+
out[name] = value.replace("script-src 'self'", `script-src 'self' ${hashes.join(" ")}`);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
return out;
|
|
509
|
+
}
|
package/src/staged-site.ts
CHANGED
|
@@ -100,6 +100,13 @@ export const stagedManifestSchema = z.object({
|
|
|
100
100
|
.refine((files) => Object.keys(files).every(isSafeStagedPath), {
|
|
101
101
|
message: "every path must be a plain build-relative path",
|
|
102
102
|
}),
|
|
103
|
+
/**
|
|
104
|
+
* #1454 — the headers of the build's pages (`SiteHeaderSet.headers`).
|
|
105
|
+
* Absent on a build staged before they existed.
|
|
106
|
+
*/
|
|
107
|
+
securityHeaders: z.record(z.string(), z.string()).optional(),
|
|
108
|
+
/** #1454 — `SiteCspFacts.originBoundScripts`: this gateway hashes them for its host. */
|
|
109
|
+
originBoundScripts: z.array(z.string()).optional(),
|
|
103
110
|
});
|
|
104
111
|
|
|
105
112
|
export type StagedManifest = z.infer<typeof stagedManifestSchema>;
|
|
@@ -129,6 +136,11 @@ export function stagedKeysFor(requestPath: string): string[] | null {
|
|
|
129
136
|
return [key, `${key}/index.html`];
|
|
130
137
|
}
|
|
131
138
|
|
|
139
|
+
/** True for an HTML document's Content-Type (#1454: the page headers go on these). */
|
|
140
|
+
export function isHtmlContentType(contentType: string): boolean {
|
|
141
|
+
return contentType.trimStart().toLowerCase().startsWith("text/html");
|
|
142
|
+
}
|
|
143
|
+
|
|
132
144
|
function extensionOf(key: string): string {
|
|
133
145
|
const name = key.slice(key.lastIndexOf("/") + 1);
|
|
134
146
|
const dot = name.lastIndexOf(".");
|
|
@@ -248,6 +260,24 @@ function escapeRegExp(literal: string): string {
|
|
|
248
260
|
return literal.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
249
261
|
}
|
|
250
262
|
|
|
263
|
+
/**
|
|
264
|
+
* `text` as {@link originRewriteStream} would serve it.
|
|
265
|
+
*
|
|
266
|
+
* @example
|
|
267
|
+
* rewriteOrigins('fetch("https://example.com/x")', originRewritePairs("https://example.com", "https://staging.example.com"))
|
|
268
|
+
*/
|
|
269
|
+
export function rewriteOrigins(
|
|
270
|
+
text: string,
|
|
271
|
+
pairs: readonly (readonly [string, string])[],
|
|
272
|
+
): string {
|
|
273
|
+
let out = text;
|
|
274
|
+
for (const [from, to] of pairs) {
|
|
275
|
+
if (from.length === 0) continue;
|
|
276
|
+
out = out.replace(new RegExp(`${escapeRegExp(from)}${AFTER_ORIGIN}`, "g"), to);
|
|
277
|
+
}
|
|
278
|
+
return out;
|
|
279
|
+
}
|
|
280
|
+
|
|
251
281
|
/**
|
|
252
282
|
* A stream transform that replaces every occurrence of each `from` origin
|
|
253
283
|
* with its `to`, also across chunk boundaries. An origin only matches as a
|