@tokenoftrust/storefront-runner 2.0.16 → 2.0.18
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/apps/storefront/env.d.ts +18 -0
- package/apps/storefront/migrations-apps/0012_test_destinations.sql +29 -0
- package/apps/storefront/src/components/blog/ReactionBar.astro +1 -1
- package/apps/storefront/src/components/islands/CheckoutComplianceGate.tsx +365 -49
- package/apps/storefront/src/components/islands/checkoutVerificationFlow.ts +251 -0
- package/apps/storefront/src/config/compliance/rulesets.ts +18 -7
- package/apps/storefront/src/config/devTenantSeed.ts +24 -1
- package/apps/storefront/src/config/evidenceTenantRoster.ts +25 -0
- package/apps/storefront/src/config/publicationSpaceConfig.ts +25 -0
- package/apps/storefront/src/config/resolver.ts +5 -0
- package/apps/storefront/src/config/tenantAnalyticsFiles.ts +43 -0
- package/apps/storefront/src/config/tenants.ts +11 -0
- package/apps/storefront/src/layouts/Layout.astro +5 -1
- package/apps/storefront/src/lib/activity/killSwitch.ts +1 -1
- package/apps/storefront/src/lib/admin/consentSettingsClient.ts +113 -0
- package/apps/storefront/src/lib/apps/consentConfigRead.ts +24 -0
- package/apps/storefront/src/lib/apps/gtmMigrationDraft.ts +103 -0
- package/apps/storefront/src/lib/apps/routeParams.ts +45 -0
- package/apps/storefront/src/lib/auth/loginGate.ts +25 -0
- package/apps/storefront/src/lib/checkoutCommerce.ts +1 -1
- package/apps/storefront/src/lib/compliance/enforcement.ts +25 -3
- package/apps/storefront/src/lib/d1/schema-apps.ts +44 -0
- package/apps/storefront/src/lib/env.ts +13 -111
- package/apps/storefront/src/lib/fixtures/regulated-commerce-truth/index.ts +540 -0
- package/apps/storefront/src/lib/fixtures/ws3-readonly-clone-preflight/index.ts +495 -0
- package/apps/storefront/src/lib/integration/tenantAnalyticsDeclarations.ts +198 -0
- package/apps/storefront/src/lib/monitoring/manifest.ts +1 -1
- package/apps/storefront/src/lib/rawMarketingHtml.ts +9 -1
- package/apps/storefront/src/lib/runtimeEnv.ts +124 -0
- package/apps/storefront/src/lib/verification/totVerificationClient.ts +485 -0
- package/apps/storefront/src/middleware/candidatePin.ts +35 -0
- package/apps/storefront/src/middleware/controlPlane.ts +270 -0
- package/apps/storefront/src/middleware/index.ts +100 -796
- package/apps/storefront/src/middleware/publicRender.ts +43 -0
- package/apps/storefront/src/middleware/renderChain.ts +685 -0
- package/apps/storefront/src/middleware/routeBranch.ts +160 -0
- package/apps/storefront/src/middleware/staticBundle.ts +109 -0
- package/apps/storefront/src/pages/[...slug].astro +1 -0
- package/apps/storefront/src/pages/api/compliance/preflight.ts +179 -2
- package/apps/storefront/src/pages/index.astro +1 -0
- package/apps/storefront/vitest.config.ts +5 -0
- package/package.json +1 -1
- package/packages/public-runtime/package.json +1 -0
- package/packages/public-runtime/schemas/managed-analytics/v1/deliver-test-event-request.schema.json +122 -0
- package/packages/public-runtime/schemas/managed-analytics/v1/get-test-destination-delivery-request.schema.json +79 -0
- package/packages/public-runtime/schemas/managed-analytics/v1/register-test-destination-request.schema.json +93 -0
- package/packages/public-runtime/schemas/managed-analytics/v1/test-destination-delivery.schema.json +106 -0
- package/packages/public-runtime/schemas/managed-analytics/v1/test-destination.schema.json +77 -0
- package/packages/public-runtime/schemas/publication-space/v1/manifest.schema.json +195 -0
- package/packages/public-runtime/schemas/publication-space/v1/normalized-mount.schema.json +80 -0
- package/packages/public-runtime/schemas/publication-space/v1/ref.schema.json +20 -0
- package/packages/public-runtime/schemas/publication-version/v1/pointer.schema.json +28 -0
- package/packages/public-runtime/schemas/publication-version/v1/transition-request.schema.json +44 -0
- package/packages/public-runtime/schemas/publication-version/v1/transition.schema.json +47 -0
- package/packages/public-runtime/schemas/publication-version/v1/version.schema.json +58 -0
- package/packages/public-runtime/src/activity/catalog.ts +1 -1
- package/packages/public-runtime/src/candidate-index.ts +6 -0
- package/packages/public-runtime/src/customization-reconcile.ts +8 -0
- package/packages/public-runtime/src/html-cache-policy.ts +57 -0
- package/packages/public-runtime/src/index.ts +7 -0
- package/packages/public-runtime/src/integration/consent-broker.ts +115 -0
- package/packages/public-runtime/src/integration/interim-bridge.ts +111 -27
- package/packages/public-runtime/src/integration/managed-analytics-api-v1.schemas.ts +65 -0
- package/packages/public-runtime/src/integration/managed-analytics-api-v1.ts +81 -0
- package/packages/public-runtime/src/integration/render-phases.ts +8 -3
- package/packages/public-runtime/src/publication-artifact.ts +203 -0
- package/packages/public-runtime/src/publication-space.ts +853 -0
- package/packages/public-runtime/src/publication-version.ts +587 -0
- package/packages/public-runtime/src/route-tier.ts +257 -0
- package/packages/public-runtime/src/static-bundle.ts +18 -5
- package/packages/public-runtime/src/tenant-assets.ts +85 -17
- package/packages/public-runtime/src/tenant.ts +70 -0
- package/packages/public-runtime/tests/conformance/fake-destination.ts +402 -0
- package/packages/public-runtime/tests/fixtures/publication-spaces/internal.json +32 -0
- package/packages/public-runtime/tests/fixtures/publication-spaces/mounted-public.json +38 -0
- package/packages/public-runtime/tests/fixtures/publication-spaces/normalized-mounts.json +39 -0
- package/packages/public-runtime/tests/fixtures/publication-spaces/ref.json +5 -0
- package/packages/public-runtime/tests/fixtures/publication-spaces/root-public.json +31 -0
- package/packages/public-runtime/tests/fixtures/publication-versions/articles-v1.json +20 -0
- package/packages/public-runtime/tests/fixtures/publication-versions/articles-v2.json +20 -0
- package/packages/public-runtime/tests/fixtures/publication-versions/internal-v1.json +20 -0
- package/packages/public-runtime/tests/fixtures/publication-versions/live-pointer.json +11 -0
- package/packages/public-runtime/tests/fixtures/publication-versions/live-transition-request.json +14 -0
- package/packages/public-runtime/tests/fixtures/publication-versions/live-transition.json +17 -0
- package/packages/public-runtime/tests/fixtures/publication-versions/root-v1.json +20 -0
- package/packages/public-runtime/tests/fixtures/publication-versions/root-v2.json +20 -0
- package/scripts/dev/ai-edit.mjs +16 -3
- package/scripts/dev/port-check.mjs +18 -3
- package/scripts/dev/publish.mjs +26 -3
- package/scripts/tenant/validate.mjs +14 -1
|
@@ -0,0 +1,685 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The render chain both serving branches share: static-bundle serving, the
|
|
3
|
+
* integration plane, the edge page cache, theme/content/capability resolution,
|
|
4
|
+
* the render itself, and the response headers stamped over it.
|
|
5
|
+
*
|
|
6
|
+
* Everything that needs D1 arrives as an already-resolved INPUT. That is what
|
|
7
|
+
* keeps the public branch free of a request-time D1 read: `publicRender` passes
|
|
8
|
+
* the empty/absent forms, `controlPlane` passes what it read. This module
|
|
9
|
+
* imports no D1 reader of its own.
|
|
10
|
+
*/
|
|
11
|
+
import type { APIContext, MiddlewareNext } from "astro";
|
|
12
|
+
import { referenceTheme } from "@/themes/reference";
|
|
13
|
+
import { mergeTheme, themeToCssVars } from "@/themes/schema";
|
|
14
|
+
import { createToTClient } from "@/lib/tot/ToTClient";
|
|
15
|
+
import { readEnv } from "@/lib/runtimeEnv";
|
|
16
|
+
import { tryServeStaticBundle } from "./staticBundle.js";
|
|
17
|
+
import { resolveCandidateContentPin } from "./candidatePin.js";
|
|
18
|
+
import { createContentProvider, DevDraftContentProvider } from "@/lib/storyblok/provider";
|
|
19
|
+
import { DEV_DRAFT_COOKIE, devDraftKey, verifyDevDraftToken } from "@/lib/dev/devDraft";
|
|
20
|
+
import {
|
|
21
|
+
isCacheablePath,
|
|
22
|
+
pageCacheKey,
|
|
23
|
+
readCacheVersion,
|
|
24
|
+
getCachedPage,
|
|
25
|
+
putCachedPage,
|
|
26
|
+
} from "@/lib/edgeCache";
|
|
27
|
+
import { STATIC_SCRIPT_HASHES, STATIC_STYLE_HASHES } from "@/lib/cspStaticHashes";
|
|
28
|
+
import { applySecurityHeaders } from "@/lib/securityHeaders";
|
|
29
|
+
import { maybeInjectPreviewReload } from "@/lib/previewReload";
|
|
30
|
+
import {
|
|
31
|
+
resolveCustomizationEnv,
|
|
32
|
+
buildCsp,
|
|
33
|
+
STOREFRONT_CSP_ALLOWLIST,
|
|
34
|
+
checkoutCspAdditions,
|
|
35
|
+
appWidgetCspAdditions,
|
|
36
|
+
embedCspAdditions,
|
|
37
|
+
foldIntegrationCsp,
|
|
38
|
+
embedsArtifactPath,
|
|
39
|
+
resolveEffectiveEmbeds,
|
|
40
|
+
CSP_REPORT_GROUP,
|
|
41
|
+
CSP_REPORT_PATH,
|
|
42
|
+
readPublishedArtifact,
|
|
43
|
+
themeArtifactPath,
|
|
44
|
+
resolveTenantFeatures,
|
|
45
|
+
resolveCapabilities,
|
|
46
|
+
capabilitiesArtifactPath,
|
|
47
|
+
resolveServableChannelVersion,
|
|
48
|
+
channelFromEnv,
|
|
49
|
+
resolveEnvironmentOnlyPlan,
|
|
50
|
+
resolveInterimBridgePlan,
|
|
51
|
+
compileIntegrationCspFromPlan,
|
|
52
|
+
collectDeclaredCspProfiles,
|
|
53
|
+
INTEGRATION_NONCE_PLACEHOLDER,
|
|
54
|
+
defaultConsentSnapshot,
|
|
55
|
+
parseConsentSnapshot,
|
|
56
|
+
CONSENT_SNAPSHOT_INPUT_HEADER,
|
|
57
|
+
CONSENT_SNAPSHOT_SIG_HEADER,
|
|
58
|
+
CONSENT_SNAPSHOT_HMAC_SECRET_BINDING,
|
|
59
|
+
MATERIALIZE_MODE_BINDING,
|
|
60
|
+
verifyConsentSnapshotSig,
|
|
61
|
+
} from "@tot/public-runtime";
|
|
62
|
+
import type {
|
|
63
|
+
CapabilityConfig,
|
|
64
|
+
ConsentSnapshot,
|
|
65
|
+
DeepPartial,
|
|
66
|
+
IntegrationDeclarationInput,
|
|
67
|
+
TenantConfig,
|
|
68
|
+
ThemeTokens,
|
|
69
|
+
BrowserEnvironment,
|
|
70
|
+
} from "@tot/public-runtime";
|
|
71
|
+
import {
|
|
72
|
+
formatHtmlCacheControl,
|
|
73
|
+
HTML_CACHE_POLICY_CAPTURE_HEADER,
|
|
74
|
+
HTML_CACHE_POLICY_CAPTURE_PROBE,
|
|
75
|
+
} from "@tot/public-runtime";
|
|
76
|
+
import { loadTenantIntegrationDeclarations } from "@/lib/integration/tenantDeclarations";
|
|
77
|
+
import { resolveTenantCommerce } from "@/lib/checkoutCommerce";
|
|
78
|
+
import { requestBrowserEnvironment, deriveSiteSurface, cspHeaderName } from "@/lib/integration/browserEnvironment";
|
|
79
|
+
import { freshNonce, stampResponseNonce } from "@/lib/integration/nonceStamp";
|
|
80
|
+
import { recordActivity } from "@/lib/activity/recordActivity";
|
|
81
|
+
|
|
82
|
+
export interface RenderChainInput {
|
|
83
|
+
context: APIContext;
|
|
84
|
+
next: MiddlewareNext;
|
|
85
|
+
host: string;
|
|
86
|
+
url: URL;
|
|
87
|
+
tenant: TenantConfig;
|
|
88
|
+
basePath: string;
|
|
89
|
+
/** Tenant-relative path (selection prefix stripped). */
|
|
90
|
+
renderPath: string;
|
|
91
|
+
/** Workers Cache API default cache; undefined under `astro dev`. */
|
|
92
|
+
cache: Cache | undefined;
|
|
93
|
+
kv: KVNamespace | undefined;
|
|
94
|
+
/**
|
|
95
|
+
* Managed-install declarations, read from D1 by the caller. Empty on the public
|
|
96
|
+
* branch: a managed install is admin-installed state, and ADR 0013 puts that
|
|
97
|
+
* behind a publish-time bake, never a per-request read on the public path.
|
|
98
|
+
*/
|
|
99
|
+
managedIntegrationDeclarations: readonly IntegrationDeclarationInput[];
|
|
100
|
+
/**
|
|
101
|
+
* Reads the tenant's saved consent revision (D1). `null` on the public branch,
|
|
102
|
+
* which falls back to the fail-closed essential-only default — the posture the
|
|
103
|
+
* baked-snapshot path already documents for the public/materialize render.
|
|
104
|
+
*/
|
|
105
|
+
readTenantConsentSnapshot: (() => Promise<ConsentSnapshot | null>) | null;
|
|
106
|
+
/**
|
|
107
|
+
* Resolves the D1 catalog read replica. `null` on the public branch. Called at
|
|
108
|
+
* the point the catalog is actually built — after the static bundle and the
|
|
109
|
+
* edge cache have each had their chance to answer — so a request served from R2
|
|
110
|
+
* or a warm cache entry costs no D1 read. Typed off `createToTClient`'s own
|
|
111
|
+
* parameter rather than the D1 module, so this file names no D1 type at all.
|
|
112
|
+
*/
|
|
113
|
+
readCatalogD1: (() => Promise<Parameters<typeof createToTClient>[1]>) | null;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export async function runRenderChain(input: RenderChainInput): Promise<Response> {
|
|
117
|
+
const { context, next, host, url, tenant, basePath, renderPath, cache, kv } = input;
|
|
118
|
+
const { request, locals } = context;
|
|
119
|
+
|
|
120
|
+
// Preview/test detection (also reused for the customization env below). A
|
|
121
|
+
// production read is one with no preview host, query token, or preview cookie.
|
|
122
|
+
const isPreviewHost = host.toLowerCase().startsWith("preview.");
|
|
123
|
+
const queryToken = url.searchParams.get("__preview");
|
|
124
|
+
const cookieToken = context.cookies.get("tot_preview")?.value ?? null;
|
|
125
|
+
|
|
126
|
+
// Candidate-render CONTENT PIN (`__tot_candidate_pin`): a signed, tenant- and
|
|
127
|
+
// expiry-bound token minted ONLY by the control-plane candidate/revision
|
|
128
|
+
// renderers (`src/lib/preview/pinnedRouteRender.ts`, never client-forgeable)
|
|
129
|
+
// that pins THIS one render's content resolution to an exact immutable
|
|
130
|
+
// `versionId`, bypassing the shared `{live,test}` channel entirely. It rides
|
|
131
|
+
// an in-process `context.rewrite()` from those renderers so a real Astro
|
|
132
|
+
// route (blog, editorial pages, …) — not just the raw `home.html`/
|
|
133
|
+
// `pages-html/*` documents they serve directly — renders pinned to the
|
|
134
|
+
// candidate under review (fb-1788536381607). Verified against this tenant so a
|
|
135
|
+
// pin can only ever name its own version; a mismatched/expired/absent token
|
|
136
|
+
// falls through to the normal channel-resolved read below, same fail-closed
|
|
137
|
+
// posture as the `__preview` token.
|
|
138
|
+
const candidatePin = await resolveCandidateContentPin(url, tenant.tenant_id);
|
|
139
|
+
// Per-developer AI-edit draft: the signed
|
|
140
|
+
// tot_dev_draft cookie's mere PRESENCE opts the request out of the shared page
|
|
141
|
+
// cache below (a draft view must never be cached publicly); it's verified —
|
|
142
|
+
// signature, expiry, tenant binding — before the overlay is applied further down.
|
|
143
|
+
const draftCookie = context.cookies.get(DEV_DRAFT_COOKIE)?.value ?? null;
|
|
144
|
+
|
|
145
|
+
const managedIntegrationDeclarations = input.managedIntegrationDeclarations;
|
|
146
|
+
|
|
147
|
+
// Digest-addressed static-bundle serving. Deliberately BEFORE the edge page
|
|
148
|
+
// cache / catalog / theme / customization machinery below: none of that applies
|
|
149
|
+
// to bundle bytes served verbatim, and once eligible that path must fully own
|
|
150
|
+
// the response rather than degrade into the normal render.
|
|
151
|
+
const bundled = await tryServeStaticBundle({
|
|
152
|
+
request,
|
|
153
|
+
url,
|
|
154
|
+
tenant,
|
|
155
|
+
basePath,
|
|
156
|
+
cache,
|
|
157
|
+
kv,
|
|
158
|
+
isPreviewHost,
|
|
159
|
+
hasPreviewToken: !!queryToken || !!cookieToken,
|
|
160
|
+
hasCandidatePin: !!candidatePin,
|
|
161
|
+
hasDraftCookie: !!draftCookie,
|
|
162
|
+
hasManagedInstalls: managedIntegrationDeclarations.length > 0,
|
|
163
|
+
});
|
|
164
|
+
if (bundled) return bundled;
|
|
165
|
+
|
|
166
|
+
// ---- Tenant-local integration materialization (ext-kernel-09) --------------
|
|
167
|
+
// Resolve a tenant's OWN declared, exact-version integrations into the effective
|
|
168
|
+
// plan the render engine serves, THROUGH the interim marketing bridge (which
|
|
169
|
+
// refuses a regulated tenant and fail-closes an invalid declaration set). Done
|
|
170
|
+
// HERE, before the edge-cache read, so a declared tenant's `planRevision` folds
|
|
171
|
+
// into the page-cache key below (a rollback/uninstall resolves a new revision →
|
|
172
|
+
// the old warm entry is unreachable → a clean re-render without the removed
|
|
173
|
+
// origins, never a TTL wait) AND its reviewed CSP origins reach the strict header.
|
|
174
|
+
//
|
|
175
|
+
// An UNDECLARED tenant does NONE of this: `loadTenantIntegrationDeclarations`
|
|
176
|
+
// returns the empty set, so `integrationCsp` stays undefined (the page-cache key
|
|
177
|
+
// is byte-identical to the non-integration form) and the environment-only plan is
|
|
178
|
+
// resolved below exactly as before — zero cost.
|
|
179
|
+
let resolvedBrowserEnvironment: BrowserEnvironment | null = null;
|
|
180
|
+
const integrationDeclarations = [
|
|
181
|
+
...loadTenantIntegrationDeclarations(tenant),
|
|
182
|
+
...managedIntegrationDeclarations,
|
|
183
|
+
];
|
|
184
|
+
if (integrationDeclarations.length > 0) {
|
|
185
|
+
const declPreviewSecret = (await readEnv("CUSTOMIZATION_PREVIEW_SECRET")) ?? null;
|
|
186
|
+
const declEnv = await resolveCustomizationEnv({
|
|
187
|
+
isPreviewHost,
|
|
188
|
+
tenantId: tenant.tenant_id,
|
|
189
|
+
token: queryToken ?? cookieToken,
|
|
190
|
+
secret: declPreviewSecret,
|
|
191
|
+
nowSeconds: Math.floor(Date.now() / 1000),
|
|
192
|
+
pathname: url.pathname,
|
|
193
|
+
});
|
|
194
|
+
const declFeatures = resolveTenantFeatures(tenant);
|
|
195
|
+
resolvedBrowserEnvironment = requestBrowserEnvironment({
|
|
196
|
+
host,
|
|
197
|
+
isPreviewHost,
|
|
198
|
+
customizationEnv: declEnv.env,
|
|
199
|
+
canonicalHost: tenant.canonicalDomain || host,
|
|
200
|
+
siteSurface: deriveSiteSurface({ catalog: declFeatures.catalog, pathname: renderPath }),
|
|
201
|
+
});
|
|
202
|
+
const bridge = resolveInterimBridgePlan({
|
|
203
|
+
tenantPublicId: tenant.tenant_id,
|
|
204
|
+
tenant,
|
|
205
|
+
environment: resolvedBrowserEnvironment,
|
|
206
|
+
declarations: integrationDeclarations,
|
|
207
|
+
});
|
|
208
|
+
if (bridge.ok) {
|
|
209
|
+
// A resolved plan serves; its compiled CSP additions + `planRevision` reach the
|
|
210
|
+
// cache key and the header. A refusal (regulated) or an invalid set leaves the
|
|
211
|
+
// plan unset here → the environment-only fallback below fills it (nothing loads).
|
|
212
|
+
locals.integrationPlan = bridge.plan;
|
|
213
|
+
const compiled = compileIntegrationCspFromPlan(
|
|
214
|
+
bridge.plan,
|
|
215
|
+
collectDeclaredCspProfiles(integrationDeclarations),
|
|
216
|
+
);
|
|
217
|
+
if (compiled.ok) locals.integrationCsp = compiled.value;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// ---- Consent snapshot: the tenant's ACTUAL initial consent state, not a
|
|
222
|
+
// hardcoded default. Both document mounts (Layout.astro, rawHtmlResponse) inline
|
|
223
|
+
// THIS value; an unresolved tenant stays on the fail-closed essential-only default.
|
|
224
|
+
locals.consentSnapshot = defaultConsentSnapshot();
|
|
225
|
+
// BAKED-SNAPSHOT INPUT (ADR 0013), honored ONLY on the materialize render, ONLY
|
|
226
|
+
// under a valid tenant-bound signature. The go-live bake pipeline resolves the
|
|
227
|
+
// tenant's REAL snapshot from D1 ONCE on the Worker, signs it, and provides
|
|
228
|
+
// {snapshot, sig} to the materialize render via these materialize-only request
|
|
229
|
+
// headers — so the static bundle inlines the real snapshot with NO consent D1
|
|
230
|
+
// read on the public/materialize path. TWO gates make the header un-forgeable:
|
|
231
|
+
// 1. MATERIALIZE-MODE binding: honored only when `TOT_MATERIALIZE_MODE` is set — a
|
|
232
|
+
// binding the materializer's wrangler dev injects and the DEPLOYED Worker never
|
|
233
|
+
// has. So a client cannot forge consent on the live Worker (which serves
|
|
234
|
+
// preview/admin/gated + the public static bundle), and no cacheable response ever
|
|
235
|
+
// varies on the header (it is never read there, so it cannot enter a cache key).
|
|
236
|
+
// 2. HMAC signature over a length-prefixed framing of (tenant_id, snapshot),
|
|
237
|
+
// verified constant-time against the go-live secret and THIS tenant's id — so a
|
|
238
|
+
// caller who forges the dispatch payload (no secret) or replays another tenant's
|
|
239
|
+
// signed snapshot is rejected.
|
|
240
|
+
// Either gate failing ⇒ fall through to the caller-supplied reader (control plane
|
|
241
|
+
// only), never a caller-supplied snapshot.
|
|
242
|
+
let bakedConsent: ReturnType<typeof parseConsentSnapshot> = null;
|
|
243
|
+
if ((await readEnv(MATERIALIZE_MODE_BINDING)) === "1") {
|
|
244
|
+
const consentInputHeader = request.headers.get(CONSENT_SNAPSHOT_INPUT_HEADER);
|
|
245
|
+
const consentSig = request.headers.get(CONSENT_SNAPSHOT_SIG_HEADER);
|
|
246
|
+
const hmacSecret = await readEnv(CONSENT_SNAPSHOT_HMAC_SECRET_BINDING);
|
|
247
|
+
if (
|
|
248
|
+
consentInputHeader &&
|
|
249
|
+
hmacSecret &&
|
|
250
|
+
(await verifyConsentSnapshotSig(hmacSecret, tenant.tenant_id, consentInputHeader, consentSig))
|
|
251
|
+
) {
|
|
252
|
+
bakedConsent = parseConsentSnapshot(consentInputHeader);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
if (bakedConsent) {
|
|
256
|
+
locals.consentSnapshot = bakedConsent;
|
|
257
|
+
} else if (input.readTenantConsentSnapshot) {
|
|
258
|
+
const saved = await input.readTenantConsentSnapshot();
|
|
259
|
+
if (saved) locals.consentSnapshot = saved;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// ---- Edge page cache: short-circuit production browse reads on a hit,
|
|
263
|
+
// BEFORE building the client / theme / rendering. Misses store the final
|
|
264
|
+
// response at the end of this middleware.
|
|
265
|
+
//
|
|
266
|
+
// NEVER in dev (`astro dev`): the workerd dev runtime persists the Workers Cache
|
|
267
|
+
// API in .wrangler/state, so a cached page would be served stale across edits AND
|
|
268
|
+
// restarts — silently defeating hot-reload (edits look "lost"). Dev must always
|
|
269
|
+
// re-render. import.meta.env.DEV statically drops this guard from the prod build.
|
|
270
|
+
const pageCacheEligible =
|
|
271
|
+
!import.meta.env.DEV &&
|
|
272
|
+
request.method.toUpperCase() === "GET" &&
|
|
273
|
+
!isPreviewHost &&
|
|
274
|
+
!queryToken &&
|
|
275
|
+
!cookieToken &&
|
|
276
|
+
!candidatePin &&
|
|
277
|
+
!draftCookie &&
|
|
278
|
+
isCacheablePath(url.pathname, url.searchParams);
|
|
279
|
+
let pageKey: Request | null = null;
|
|
280
|
+
if (pageCacheEligible && cache && kv) {
|
|
281
|
+
const version = await readCacheVersion(kv, tenant.tenant_id);
|
|
282
|
+
// Fold the resolved integration plan revision into the key so a warm entry is
|
|
283
|
+
// version-scoped: a rollback/uninstall resolves a new revision → old entry
|
|
284
|
+
// unreachable → clean re-render without the removed origins (never a TTL wait).
|
|
285
|
+
// Undefined until the integration plane is resolved for this tenant — the key
|
|
286
|
+
// is then byte-identical to the non-integration form. The store below reuses
|
|
287
|
+
// this same `pageKey`, so read and write stay consistent.
|
|
288
|
+
pageKey = pageCacheKey(
|
|
289
|
+
tenant.tenant_id,
|
|
290
|
+
url.pathname,
|
|
291
|
+
url.search,
|
|
292
|
+
version,
|
|
293
|
+
locals.integrationCsp?.planRevision,
|
|
294
|
+
);
|
|
295
|
+
const hit = await getCachedPage(cache, pageKey);
|
|
296
|
+
// The cached artifact is nonce-free (carries the placeholder). Stamp a fresh
|
|
297
|
+
// per-response nonce into its body + CSP header so a warm hit is served with a
|
|
298
|
+
// brand-new nonce, never the one an earlier response rendered with.
|
|
299
|
+
if (hit) return await stampResponseNonce(hit, freshNonce());
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// Catalog source selection (docs/architecture/product-catalog.md).
|
|
303
|
+
// A store's product source graduates over its life: JSON fixtures (dev default) ->
|
|
304
|
+
// D1 edge replica (staging) -> hosted ToT catalog (go-live). The read backend is
|
|
305
|
+
// chosen by the CALLER: the control plane resolves the D1 edge replica when
|
|
306
|
+
// USE_D1_CATALOG=1; the public branch never does, so `createToTClient` falls back
|
|
307
|
+
// to the bundled JSON fixture snapshot. The hosted catalog graduates the SAME
|
|
308
|
+
// canonical records into the D1 read model (emitCatalogSql), so JSON/D1/hosted
|
|
309
|
+
// render identically — pinned by lib/tot/sourceSelection.test.ts.
|
|
310
|
+
const tot = await createToTClient(tenant, await input.readCatalogD1?.());
|
|
311
|
+
|
|
312
|
+
const proto = url.protocol === "http:" ? "http" : "https";
|
|
313
|
+
// Canonical base uses the tenant's canonical domain in prod; for local dev we
|
|
314
|
+
// keep the actual host (plus any /<domain> base path) so links resolve.
|
|
315
|
+
const isLocal = host.startsWith("localhost") || host.startsWith("127.0.0.1");
|
|
316
|
+
const canonicalBase = isLocal
|
|
317
|
+
? `${proto}://${host}${basePath}`
|
|
318
|
+
: `https://${tenant.canonicalDomain}`;
|
|
319
|
+
|
|
320
|
+
// Live vs test customization. Production hosts always serve "live" and
|
|
321
|
+
// ignore any token; a "preview." host is auth-gated by a signed, tenant-bound,
|
|
322
|
+
// short-TTL preview token (?__preview= on first hit, then the tot_preview
|
|
323
|
+
// cookie). Test is never indexable (X-Robots-Tag below).
|
|
324
|
+
const previewToken = queryToken ?? cookieToken;
|
|
325
|
+
const previewSecret = (await readEnv("CUSTOMIZATION_PREVIEW_SECRET")) ?? null;
|
|
326
|
+
const nowSeconds = Math.floor(Date.now() / 1000);
|
|
327
|
+
const customization = await resolveCustomizationEnv({
|
|
328
|
+
isPreviewHost,
|
|
329
|
+
tenantId: tenant.tenant_id,
|
|
330
|
+
token: previewToken,
|
|
331
|
+
secret: previewSecret,
|
|
332
|
+
nowSeconds,
|
|
333
|
+
pathname: url.pathname,
|
|
334
|
+
});
|
|
335
|
+
if (customization.reject) {
|
|
336
|
+
return new Response(customization.reject.message, {
|
|
337
|
+
status: customization.reject.status,
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
// Persist a query-supplied token as a cookie so later navigations stay in test.
|
|
341
|
+
if (customization.env === "test" && queryToken) {
|
|
342
|
+
context.cookies.set("tot_preview", queryToken, {
|
|
343
|
+
httpOnly: true,
|
|
344
|
+
secure: true,
|
|
345
|
+
sameSite: "lax",
|
|
346
|
+
path: "/",
|
|
347
|
+
maxAge: 3600,
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// Apply a published theme override for the resolved environment (store->app).
|
|
352
|
+
// The live domain serves `live`; a gated preview serves `test`. When nothing
|
|
353
|
+
// is published the build-time tenant theme is used unchanged.
|
|
354
|
+
//
|
|
355
|
+
// Resolution is versioned-aware inside readPublishedArtifact: env maps to a
|
|
356
|
+
// publish channel (live->live, test->preview); if the tenant has a channel
|
|
357
|
+
// pointer, the artifact is resolved through the immutable site version
|
|
358
|
+
// (channel -> versionId -> manifest -> content). Tenants with no channel
|
|
359
|
+
// pointer fall back to the legacy per-path selection — no behavior change.
|
|
360
|
+
const kvGet = kv ? (key: string) => kv.get(key) : async () => null;
|
|
361
|
+
|
|
362
|
+
// Self-heal a DANGLING channel pointer: the pointer for this env's channel may
|
|
363
|
+
// name a version that was never built (or whose manifest was evicted).
|
|
364
|
+
// `readVersionedArtifact` already serves last-built content instead of emptying
|
|
365
|
+
// the surface; here we do the once-per-request detection to ENQUEUE a rebuild of
|
|
366
|
+
// the dangling version. Fail-open: a KV hiccup never blocks the render (the reads
|
|
367
|
+
// below still run).
|
|
368
|
+
if (kv) {
|
|
369
|
+
const channel = channelFromEnv(customization.env);
|
|
370
|
+
await resolveServableChannelVersion(kvGet, tenant.tenant_id, channel, ({ versionId }) => {
|
|
371
|
+
recordActivity({
|
|
372
|
+
action: "preview.build.requested",
|
|
373
|
+
actor: { kind: "system", id: "storefront" },
|
|
374
|
+
source: "server",
|
|
375
|
+
outcome: { status: "succeeded" },
|
|
376
|
+
scope: { tenantId: tenant.tenant_id },
|
|
377
|
+
payload: { args: { changeId: versionId } },
|
|
378
|
+
});
|
|
379
|
+
}).catch(() => {
|
|
380
|
+
/* fail-open: self-heal detection never breaks the request */
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
// Verify the developer-draft cookie (signature + expiry + tenant binding) — the
|
|
385
|
+
// overlay below only engages for the developer who minted the draft, on THIS
|
|
386
|
+
// tenant. Same secret + trust model as the preview token; invalid/expired/foreign
|
|
387
|
+
// tokens degrade silently to the base chain (never an error page).
|
|
388
|
+
const draftClaims =
|
|
389
|
+
draftCookie && previewSecret && kv
|
|
390
|
+
? await verifyDevDraftToken(previewSecret, draftCookie, nowSeconds)
|
|
391
|
+
: null;
|
|
392
|
+
const draft =
|
|
393
|
+
draftClaims && draftClaims.tenantId === tenant.tenant_id ? draftClaims : null;
|
|
394
|
+
|
|
395
|
+
let theme = mergeTheme(referenceTheme, tenant.theme_tokens);
|
|
396
|
+
const publishedTheme = await readPublishedArtifact(
|
|
397
|
+
kvGet,
|
|
398
|
+
tenant.tenant_id,
|
|
399
|
+
customization.env,
|
|
400
|
+
themeArtifactPath(tenant.tenant_id),
|
|
401
|
+
);
|
|
402
|
+
if (publishedTheme) {
|
|
403
|
+
try {
|
|
404
|
+
theme = mergeTheme(theme, JSON.parse(publishedTheme) as DeepPartial<ThemeTokens>);
|
|
405
|
+
} catch {
|
|
406
|
+
/* malformed published artifact — keep the build-time theme */
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
// Developer-draft theme overlay (on top of published) — only for the draft owner.
|
|
410
|
+
if (draft) {
|
|
411
|
+
const draftTheme = await kvGet(devDraftKey(tenant.tenant_id, draft.draftId, "theme.json"));
|
|
412
|
+
if (draftTheme) {
|
|
413
|
+
try {
|
|
414
|
+
theme = mergeTheme(theme, JSON.parse(draftTheme) as DeepPartial<ThemeTokens>);
|
|
415
|
+
} catch {
|
|
416
|
+
/* malformed draft artifact — keep the resolved theme */
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// Per-environment capabilities (Track A/B). Config-as-code: the build-time
|
|
422
|
+
// TenantConfig default is overridden by the published capabilities artifact for
|
|
423
|
+
// THIS environment — materialized from the tenant repo's .tot/config.json per
|
|
424
|
+
// commit (localhost=working tree, preview=PR head, live=promoted). So a
|
|
425
|
+
// capability change is PR-gated and separable per environment.
|
|
426
|
+
let publishedCaps: Partial<CapabilityConfig> | null = null;
|
|
427
|
+
const publishedCapsRaw = await readPublishedArtifact(
|
|
428
|
+
kvGet,
|
|
429
|
+
tenant.tenant_id,
|
|
430
|
+
customization.env,
|
|
431
|
+
capabilitiesArtifactPath(tenant.tenant_id),
|
|
432
|
+
);
|
|
433
|
+
if (publishedCapsRaw) {
|
|
434
|
+
try {
|
|
435
|
+
publishedCaps = JSON.parse(publishedCapsRaw) as Partial<CapabilityConfig>;
|
|
436
|
+
} catch {
|
|
437
|
+
/* malformed published artifact — keep the build-time default */
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
const capabilities = resolveCapabilities(tenant, publishedCaps);
|
|
441
|
+
|
|
442
|
+
// Embed opt-in (self-serve, config-as-code on the same spine as capabilities):
|
|
443
|
+
// the build-time TenantConfig.embeds default is overlaid with the tenant's
|
|
444
|
+
// published embeds.json for THIS env, then filtered to the vetted catalog. A
|
|
445
|
+
// tenant enables a catalogued embed by committing embeds.json — no platform
|
|
446
|
+
// change — but can never introduce a non-catalog origin.
|
|
447
|
+
let publishedEmbeds: string[] | null = null;
|
|
448
|
+
const publishedEmbedsRaw = await readPublishedArtifact(
|
|
449
|
+
kvGet,
|
|
450
|
+
tenant.tenant_id,
|
|
451
|
+
customization.env,
|
|
452
|
+
embedsArtifactPath(tenant.tenant_id),
|
|
453
|
+
);
|
|
454
|
+
if (publishedEmbedsRaw) {
|
|
455
|
+
try {
|
|
456
|
+
const parsed = JSON.parse(publishedEmbedsRaw);
|
|
457
|
+
if (Array.isArray(parsed)) publishedEmbeds = parsed.filter((s) => typeof s === "string");
|
|
458
|
+
} catch {
|
|
459
|
+
/* malformed published artifact — keep the build-time default */
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
const effectiveEmbeds = resolveEffectiveEmbeds(tenant.embeds, publishedEmbeds);
|
|
463
|
+
|
|
464
|
+
// Nonce placeholder: the platform's inline tags AND the CSP header are rendered
|
|
465
|
+
// with this sentinel, never a live nonce (ADR 0018). A fresh per-response nonce
|
|
466
|
+
// is stamped in at serve time (stampResponseNonce below), so the cached artifact
|
|
467
|
+
// is nonce-free and every response — cold render or warm cache hit — gets a fresh
|
|
468
|
+
// matching nonce/CSP pair.
|
|
469
|
+
const cspNonce = INTEGRATION_NONCE_PLACEHOLDER;
|
|
470
|
+
|
|
471
|
+
locals.tenant = tenant;
|
|
472
|
+
// Effective capability flags for this tenant (commerce defaults unless the
|
|
473
|
+
// tenant declares siteType:"marketing" / explicit features). Pages and chrome
|
|
474
|
+
// read these instead of hard-coding tenant identity checks.
|
|
475
|
+
locals.features = resolveTenantFeatures(tenant);
|
|
476
|
+
locals.capabilities = capabilities;
|
|
477
|
+
// Cart/checkout facts (Track A) — only when the tenant has a catalog
|
|
478
|
+
// AND the cartCheckout capability is enabled for THIS environment. Drives the
|
|
479
|
+
// loader + signed add-to-cart, and the CSP additions below.
|
|
480
|
+
const commerce =
|
|
481
|
+
locals.features.catalog && capabilities.cartCheckout.enabled
|
|
482
|
+
? await resolveTenantCommerce(tenant)
|
|
483
|
+
: null;
|
|
484
|
+
locals.commerce = commerce ?? undefined;
|
|
485
|
+
locals.tot = tot;
|
|
486
|
+
// A verified candidate content pin takes priority over the channel-resolved
|
|
487
|
+
// read — a pinned candidate/revision render must never fall through to the
|
|
488
|
+
// shared `{live,test}` content (see `pinnedRouteRender.ts`).
|
|
489
|
+
locals.content = candidatePin
|
|
490
|
+
? createContentProvider(tenant, undefined, { get: kvGet, versionId: candidatePin.versionId })
|
|
491
|
+
: createContentProvider(tenant, {
|
|
492
|
+
get: kvGet,
|
|
493
|
+
env: customization.env,
|
|
494
|
+
});
|
|
495
|
+
// Developer-draft content overlay — serves the AI-edited artifacts to the draft
|
|
496
|
+
// owner only; every other viewer keeps the published/base chain above.
|
|
497
|
+
if (draft) {
|
|
498
|
+
locals.content = new DevDraftContentProvider(
|
|
499
|
+
locals.content,
|
|
500
|
+
tenant.tenant_id,
|
|
501
|
+
draft.draftId,
|
|
502
|
+
kvGet,
|
|
503
|
+
);
|
|
504
|
+
}
|
|
505
|
+
locals.themeStyle = themeToCssVars(theme);
|
|
506
|
+
locals.canonicalBase = canonicalBase;
|
|
507
|
+
locals.customizationEnv = customization.env;
|
|
508
|
+
locals.cspNonce = cspNonce;
|
|
509
|
+
// Seeded here, filled in by whichever page/layout renders a widget slot
|
|
510
|
+
// (renderSlot.ts) as the page renders inside next() below — read back out
|
|
511
|
+
// after next() resolves so the CSP frame-src reflects exactly what rendered.
|
|
512
|
+
locals.activeWidgetPlacements = [];
|
|
513
|
+
// Prefix that path-routed pages live under ("" for host-routed). Pages stay
|
|
514
|
+
// tenant-agnostic; the Layout uses this to keep root-absolute links inside
|
|
515
|
+
// the tenant prefix on the client. A candidate content pin overrides this to
|
|
516
|
+
// the PINNING render's own prefix (`/preview/rev/<sha>` or
|
|
517
|
+
// `/preview/render/<tenant>/<changeId>`) so a pinned page's OWN generated
|
|
518
|
+
// links stay inside that candidate instead of escaping to the live host.
|
|
519
|
+
locals.basePath = candidatePin ? candidatePin.basePath : basePath;
|
|
520
|
+
// Renderer-owned four-stage browser environment (ADR 0014 E1 / 0017), computed
|
|
521
|
+
// ONCE here from authoritative request state and serialized before app code by
|
|
522
|
+
// both document mounts (Layout.astro + rawHtmlResponse). The candidate render
|
|
523
|
+
// paths build their own `candidate`-stage object instead of this one.
|
|
524
|
+
// Reuse the environment resolved for a declared tenant's integration plane above
|
|
525
|
+
// (identical inputs → identical object) so the plan's environment and this object
|
|
526
|
+
// never diverge; an undeclared tenant computes it here for the first time.
|
|
527
|
+
locals.browserEnvironment =
|
|
528
|
+
resolvedBrowserEnvironment ??
|
|
529
|
+
requestBrowserEnvironment({
|
|
530
|
+
host,
|
|
531
|
+
isPreviewHost,
|
|
532
|
+
customizationEnv: customization.env,
|
|
533
|
+
canonicalHost: tenant.canonicalDomain || host,
|
|
534
|
+
siteSurface: deriveSiteSurface({ catalog: locals.features.catalog, pathname: renderPath }),
|
|
535
|
+
});
|
|
536
|
+
// Resolved effective plan (ext-kernel-03) for this request — the fixed-phase
|
|
537
|
+
// render engine (ext-kernel-04) consumes it in BOTH document mounts (Layout.astro
|
|
538
|
+
// + rawHtmlResponse). A declared tenant's plan is already resolved above (through
|
|
539
|
+
// the interim bridge); an undeclared tenant — or one the bridge refused / failed
|
|
540
|
+
// closed — resolves the environment-only plan here, so a page with no serving
|
|
541
|
+
// integration emits no vendor runtime/markup.
|
|
542
|
+
locals.integrationPlan =
|
|
543
|
+
locals.integrationPlan ??
|
|
544
|
+
resolveEnvironmentOnlyPlan(locals.browserEnvironment, tenant.tenant_id);
|
|
545
|
+
|
|
546
|
+
// When a /<domain>/ prefix selected the tenant, rewrite to the stripped route
|
|
547
|
+
// so the existing file-based routes match. next(path) rewrites WITHOUT
|
|
548
|
+
// re-running middleware, so the locals set above are preserved.
|
|
549
|
+
let response = basePath
|
|
550
|
+
? await next(`${renderPath}${url.search}`)
|
|
551
|
+
: await next();
|
|
552
|
+
|
|
553
|
+
// On-publish auto-refresh: inject the live-reload client into SHARED preview
|
|
554
|
+
// (`test`) HTML pages ONLY — never `live` (keeps live clean + edge-cacheable).
|
|
555
|
+
// It polls /__preview/version and reloads when this tenant's cache-version
|
|
556
|
+
// bumps on publish/reconcile. Injection happens before the CSP header is set so
|
|
557
|
+
// the script's per-request nonce (cspNonce) matches the enforced policy.
|
|
558
|
+
response = await maybeInjectPreviewReload(response, {
|
|
559
|
+
env: customization.env,
|
|
560
|
+
tenantId: tenant.tenant_id,
|
|
561
|
+
basePath,
|
|
562
|
+
nonce: cspNonce,
|
|
563
|
+
});
|
|
564
|
+
|
|
565
|
+
// Baseline security headers on every response — set before the page-cache
|
|
566
|
+
// store below so cached copies carry them too.
|
|
567
|
+
applySecurityHeaders(response.headers);
|
|
568
|
+
|
|
569
|
+
// Preview (test) output must never be indexed.
|
|
570
|
+
if (customization.noindex) {
|
|
571
|
+
response.headers.set("X-Robots-Tag", "noindex, nofollow");
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
// Strict CSP — now ENFORCED in every environment (Epic S2). The report-only
|
|
575
|
+
// rollout is complete: platform output is CSP-clean — inline styles are
|
|
576
|
+
// externalized (`inlineStylesheets: "never"`), Astro's static inline scripts +
|
|
577
|
+
// island style are hash-pinned (cspStaticHashes), our dynamic inline tags carry
|
|
578
|
+
// the per-request nonce, and the last inline event handler (SortSelect's
|
|
579
|
+
// `onchange`) is now a bundled 'self' script. Reporting endpoints stay attached
|
|
580
|
+
// (report-to/report-uri work in enforce mode), so we keep telemetry as tenant
|
|
581
|
+
// client JS arrives — those per-version tenant hashes extend `scriptSrc` per
|
|
582
|
+
// request (the mechanism below already supports it).
|
|
583
|
+
//
|
|
584
|
+
// DEV EXCEPTION: `astro dev` serves CSS/HMR as UN-nonced inline <style>/<script>
|
|
585
|
+
// (Vite injects them); the strict nonce policy blocks those, leaving the dev
|
|
586
|
+
// site unstyled. The BUILD is CSP-clean (styles are externalized via
|
|
587
|
+
// `inlineStylesheets:"never"`), so we enforce there and only REPORT in dev —
|
|
588
|
+
// violations are still surfaced, but styling/HMR work locally.
|
|
589
|
+
const cspHeader = cspHeaderName(import.meta.env.DEV);
|
|
590
|
+
response.headers.set(
|
|
591
|
+
"Reporting-Endpoints",
|
|
592
|
+
`${CSP_REPORT_GROUP}="${CSP_REPORT_PATH}"`,
|
|
593
|
+
);
|
|
594
|
+
// Checkout origins (loader CDN + the store's cart/checkout host) added to the
|
|
595
|
+
// strict policy only when this tenant has a store — so add-to-cart, the
|
|
596
|
+
// sidecart iframe/XHR, and the cross-origin form POST all pass.
|
|
597
|
+
const checkoutCsp = commerce ? checkoutCspAdditions(commerce.origin) : null;
|
|
598
|
+
// Private-app widget origins — read back AFTER next() so this reflects
|
|
599
|
+
// exactly the placements that rendered on THIS page, never a wildcard.
|
|
600
|
+
const widgetCsp = appWidgetCspAdditions(locals.activeWidgetPlacements ?? []);
|
|
601
|
+
// Third-party marketing embeds (e.g. a Pipedrive form) the tenant opted into
|
|
602
|
+
// via .tot/config.json `embeds:`. Only scan the HTML body when the tenant
|
|
603
|
+
// declared at least one embed — zero cost for everyone else — and add each
|
|
604
|
+
// provider's origins ONLY if its marker is actually on THIS page.
|
|
605
|
+
// Prefer an opt-in the render handler resolved for a tenant the URL router
|
|
606
|
+
// couldn't (the candidate renderer sets locals.embedOptIn — see candidateRender);
|
|
607
|
+
// otherwise use the router-resolved tenant's effective embeds.
|
|
608
|
+
const embedsForScan = locals.embedOptIn ?? effectiveEmbeds;
|
|
609
|
+
let embedCsp = { scriptSrc: [] as string[], connectSrc: [] as string[], frameSrc: [] as string[] };
|
|
610
|
+
if (
|
|
611
|
+
embedsForScan.length > 0 &&
|
|
612
|
+
(response.headers.get("content-type") ?? "").includes("text/html")
|
|
613
|
+
) {
|
|
614
|
+
embedCsp = embedCspAdditions(embedsForScan, await response.clone().text());
|
|
615
|
+
}
|
|
616
|
+
const cspOptions = {
|
|
617
|
+
nonce: cspNonce,
|
|
618
|
+
...STOREFRONT_CSP_ALLOWLIST,
|
|
619
|
+
// Pin Astro's static inline hydration scripts + island style by hash
|
|
620
|
+
// (they're identical every request); my dynamic inline tags use the nonce.
|
|
621
|
+
scriptSrc: [
|
|
622
|
+
...STOREFRONT_CSP_ALLOWLIST.scriptSrc,
|
|
623
|
+
...STATIC_SCRIPT_HASHES,
|
|
624
|
+
...(checkoutCsp?.scriptSrc ?? []),
|
|
625
|
+
...embedCsp.scriptSrc,
|
|
626
|
+
],
|
|
627
|
+
styleSrc: [
|
|
628
|
+
...STOREFRONT_CSP_ALLOWLIST.styleSrc,
|
|
629
|
+
...STATIC_STYLE_HASHES,
|
|
630
|
+
...(checkoutCsp?.styleSrc ?? []),
|
|
631
|
+
],
|
|
632
|
+
fontSrc: [...STOREFRONT_CSP_ALLOWLIST.fontSrc, ...(checkoutCsp?.fontSrc ?? [])],
|
|
633
|
+
connectSrc: [
|
|
634
|
+
...STOREFRONT_CSP_ALLOWLIST.connectSrc,
|
|
635
|
+
...(checkoutCsp?.connectSrc ?? []),
|
|
636
|
+
...embedCsp.connectSrc,
|
|
637
|
+
],
|
|
638
|
+
imgSrc: [...STOREFRONT_CSP_ALLOWLIST.imgSrc, ...(checkoutCsp?.imgSrc ?? [])],
|
|
639
|
+
frameSrc: [
|
|
640
|
+
...(checkoutCsp?.frameSrc ?? []),
|
|
641
|
+
...widgetCsp.frameSrc,
|
|
642
|
+
...embedCsp.frameSrc,
|
|
643
|
+
],
|
|
644
|
+
formAction: checkoutCsp?.formAction ?? [],
|
|
645
|
+
reportGroup: CSP_REPORT_GROUP,
|
|
646
|
+
reportUri: CSP_REPORT_PATH,
|
|
647
|
+
};
|
|
648
|
+
// Version-scoped integration plane: APPEND the resolved plan's compiled origins
|
|
649
|
+
// (curated adapter profiles + advanced exact origins) to the six contributable
|
|
650
|
+
// directives only — never the base. Absent (no integration) this is a no-op, so
|
|
651
|
+
// the header is byte-identical to a non-integration tenant's.
|
|
652
|
+
response.headers.set(
|
|
653
|
+
cspHeader,
|
|
654
|
+
buildCsp(foldIntegrationCsp(cspOptions, locals.integrationCsp?.additions ?? {})),
|
|
655
|
+
);
|
|
656
|
+
|
|
657
|
+
// Store the fully-rendered, CSP-stamped response for the next reader. Only
|
|
658
|
+
// production (no preview token reached here) cacheable GETs have a pageKey;
|
|
659
|
+
// putCachedPage additionally skips non-200, non-HTML, and cookie-bearing
|
|
660
|
+
// responses. Also expose Cache-Control to any fronting CDN.
|
|
661
|
+
if (pageKey && cache && customization.env === "live") {
|
|
662
|
+
response.headers.set(
|
|
663
|
+
"Cache-Control",
|
|
664
|
+
"public, s-maxage=300, stale-while-revalidate=86400",
|
|
665
|
+
);
|
|
666
|
+
// Store the nonce-free artifact (the placeholder is still in the body + CSP
|
|
667
|
+
// header) BEFORE stamping — so the cache never holds a live/reusable nonce.
|
|
668
|
+
await putCachedPage(cache, pageKey, response);
|
|
669
|
+
}
|
|
670
|
+
// MATERIALIZE-ONLY capture (ADR 0013): expose the tenant's resolved route-document
|
|
671
|
+
// Cache-Control so the publish/materialize plane can bake it into the bundle
|
|
672
|
+
// manifest (the same capture pattern as CSP). Gated on the materialize probe
|
|
673
|
+
// request header, so it NEVER reaches a public client — the LIVE served header
|
|
674
|
+
// comes from the manifest via `static-bundle`, not from this signal.
|
|
675
|
+
if (request.headers.get(HTML_CACHE_POLICY_CAPTURE_PROBE)) {
|
|
676
|
+
response.headers.set(
|
|
677
|
+
HTML_CACHE_POLICY_CAPTURE_HEADER,
|
|
678
|
+
formatHtmlCacheControl(locals.tenant?.serving?.htmlCachePolicy),
|
|
679
|
+
);
|
|
680
|
+
}
|
|
681
|
+
// Stamp a fresh per-response nonce into this cold response's body + CSP header
|
|
682
|
+
// (the warm-hit path above stamps its own). Both paths therefore serve a fresh,
|
|
683
|
+
// matching nonce/CSP pair, and no nonce is reused across responses (ADR 0018).
|
|
684
|
+
return await stampResponseNonce(response, freshNonce());
|
|
685
|
+
}
|