|
| 1 | +import { canonicalPublicRoute, MAX_PUBLISHED_PAGE_BYTES, MAX_PUBLISHED_REVISION_BYTES, PUBLISHED_PAGE_SCHEMA, validateCompletePublishedRevision } from "./published-reader.js" |
| 2 | +import { parseSiteContexts, previewDomain, resolvePreviewSiteContextFromRequest, resolveSiteContextFromRequest, siteStorageKeys, type SiteContext } from "./site-context.js" |
| 3 | +import { isCanonicalWpContentPath, validateWpContentManifestFiles } from "./wp-content-persistence.js" |
| 4 | +import { validateUploadManifestFiles } from "./upload-persistence.js" |
| 5 | +import { servePublicWordPressStaticAsset } from "./wordpress-static-reader.js" |
| 6 | + |
| 7 | +export interface PublicReaderEnv { |
| 8 | + WORDPRESS_STATE_BUCKET: R2Bucket |
| 9 | + WORDPRESS_SITE_CONTEXTS?: string |
| 10 | + WORDPRESS_PREVIEW_DOMAIN?: string |
| 11 | + WORDPRESS_PREVIEW_HOST_SECRET?: string |
| 12 | +} |
| 13 | + |
| 14 | +interface PageSnapshot { |
| 15 | + schema: typeof PUBLISHED_PAGE_SCHEMA |
| 16 | + canonicalRevision: string |
| 17 | + route: string |
| 18 | + status: number |
| 19 | + statusText: string |
| 20 | + headers: Array<[string, string]> |
| 21 | + body: string |
| 22 | +} |
| 23 | + |
| 24 | +interface PublicationAsset { |
| 25 | + path: string |
| 26 | + objectKey: string |
| 27 | + sha256: string |
| 28 | + size: number |
| 29 | +} |
| 30 | + |
| 31 | +/** |
| 32 | + * This is intentionally a complete request boundary: it has no mutation |
| 33 | + * fallback, so an absent or incomplete publication cannot boot WordPress. |
| 34 | + */ |
| 35 | +export function createCloudflarePublicReader<Env extends PublicReaderEnv>() { |
| 36 | + return { |
| 37 | + async fetch(request: Request, env: Env): Promise<Response> { |
| 38 | + let site: SiteContext |
| 39 | + try { |
| 40 | + const contexts = parseSiteContexts(env.WORDPRESS_SITE_CONTEXTS) |
| 41 | + try { |
| 42 | + site = resolveSiteContextFromRequest(request, contexts) |
| 43 | + } catch (error) { |
| 44 | + if (!(error instanceof Error) || error.message !== "Unknown site hostname.") throw error |
| 45 | + site = await resolvePreviewSiteContextFromRequest(request, previewDomain(env.WORDPRESS_PREVIEW_DOMAIN, env.WORDPRESS_PREVIEW_HOST_SECRET)) |
| 46 | + } |
| 47 | + } catch (error) { |
| 48 | + if (error instanceof Error && error.message === "Unknown site hostname.") return response("Unknown site hostname.", 421) |
| 49 | + return response("Public publication configuration is invalid.", 503) |
| 50 | + } |
| 51 | + return servePublicPublication(request, env.WORDPRESS_STATE_BUCKET, site) |
| 52 | + }, |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +export async function servePublicPublication(request: Request, bucket: R2Bucket, site: SiteContext): Promise<Response> { |
| 57 | + if (request.method !== "GET" && request.method !== "HEAD") return response("Public publication accepts GET and HEAD only.", 405) |
| 58 | + if (request.headers.has("authorization") || request.headers.has("cookie") || new URL(request.url).searchParams.has("phase")) return response("Dynamic WordPress requests are unavailable from the public reader.", 404) |
| 59 | + const staticAsset = await servePublicWordPressStaticAsset(request, bucket) |
| 60 | + if (staticAsset) return staticAsset |
| 61 | + const route = canonicalPublicRoute(request) |
| 62 | + let publication |
| 63 | + try { |
| 64 | + const current = await bucket.get(siteStorageKeys(site).publishedCurrent) |
| 65 | + if (!current) return response("Public publication is not ready.", 503) |
| 66 | + if (current.size > MAX_PUBLISHED_REVISION_BYTES) return response("Public publication is incomplete.", 503) |
| 67 | + publication = validateCompletePublishedRevision(JSON.parse(await current.text()), site) |
| 68 | + } catch { |
| 69 | + return response("Public publication is incomplete.", 503) |
| 70 | + } |
| 71 | + const asset = await servePublishedAsset(request, bucket, site, publication) |
| 72 | + if (asset) return asset |
| 73 | + const entry = publication.routes.find((candidate) => candidate.route === route) |
| 74 | + if (!entry) return response("Published route not found.", 404) |
| 75 | + |
| 76 | + const cache = typeof caches === "undefined" ? undefined : (caches as CacheStorage & { default?: Cache }).default |
| 77 | + const cacheKey = new Request(`https://wp-codebox-publication.invalid/${site.id}/${publication.revision}${route}`, { method: "GET" }) |
| 78 | + const cached = cache ? await cache.match(cacheKey) : null |
| 79 | + if (cached) return publicationResponse(cached, request.method === "HEAD", publication.revision, "edge") |
| 80 | + try { |
| 81 | + const object = await bucket.get(entry.objectKey) |
| 82 | + if (!object || object.size > MAX_PUBLISHED_PAGE_BYTES) return response("Public publication is incomplete.", 503) |
| 83 | + const snapshot = JSON.parse(await object.text()) as PageSnapshot |
| 84 | + if (!isPageSnapshot(snapshot, entry.canonicalRevision, route)) return response("Public publication is incomplete.", 503) |
| 85 | + const published = publicationResponse(new Response(snapshot.body, { status: snapshot.status, statusText: snapshot.statusText, headers: snapshot.headers }), request.method === "HEAD", publication.revision, "r2") |
| 86 | + if (cache && request.method === "GET") await cache.put(cacheKey, published.clone()).catch(() => undefined) |
| 87 | + return published |
| 88 | + } catch { |
| 89 | + return response("Public publication is incomplete.", 503) |
| 90 | + } |
| 91 | +} |
| 92 | + |
| 93 | +async function servePublishedAsset(request: Request, bucket: R2Bucket, site: SiteContext, publication: ReturnType<typeof validateCompletePublishedRevision>): Promise<Response | null> { |
| 94 | + const pathname = new URL(request.url).pathname |
| 95 | + const uploads = pathname.startsWith("/wp-content/uploads/") ? pathname.slice("/wp-content/uploads/".length) : null |
| 96 | + const wpContent = pathname.startsWith("/wp-content/") ? pathname.slice("/wp-content/".length) : null |
| 97 | + if (uploads === null && wpContent === null) return null |
| 98 | + let path: string |
| 99 | + try { |
| 100 | + path = decodeURIComponent(uploads ?? wpContent!) |
| 101 | + } catch { |
| 102 | + return response("Published asset path is invalid.", 400) |
| 103 | + } |
| 104 | + if ((uploads === null && !isCanonicalWpContentPath(path)) || (uploads !== null && !isCanonicalRelativePath(path))) return response("Published asset path is invalid.", 400) |
| 105 | + try { |
| 106 | + const manifestKey = `${siteStorageKeys(site).markdownRevisionPrefix}/${publication.canonicalRevision}.json` |
| 107 | + const manifestObject = await bucket.get(manifestKey) |
| 108 | + if (!manifestObject) return response("Public publication is incomplete.", 503) |
| 109 | + const manifest = await manifestObject.json<{ revision?: unknown; uploads?: PublicationAsset[]; wpContent?: PublicationAsset[] }>() |
| 110 | + if (manifest.revision !== publication.canonicalRevision) return response("Public publication is incomplete.", 503) |
| 111 | + const files = uploads === null ? manifest.wpContent ?? [] : manifest.uploads ?? [] |
| 112 | + if (uploads === null) validateWpContentManifestFiles(files, site) |
| 113 | + else validateUploadManifestFiles(files, site) |
| 114 | + const file = files.find((candidate) => candidate.path === path) |
| 115 | + if (!file) return response("Published asset not found.", 404) |
| 116 | + const cache = typeof caches === "undefined" ? undefined : (caches as CacheStorage & { default?: Cache }).default |
| 117 | + const cacheKey = new Request(`https://wp-codebox-publication.invalid/${site.id}/${publication.revision}/${file.sha256}/${pathname}`, { method: "GET" }) |
| 118 | + const cached = cache ? await cache.match(cacheKey) : null |
| 119 | + if (cached) return assetResponse(cached, request.method === "HEAD", publication.revision, "edge") |
| 120 | + const object = await bucket.get(file.objectKey) |
| 121 | + if (!object || object.size !== file.size) return response("Public publication is incomplete.", 503) |
| 122 | + const body = request.method === "HEAD" ? null : new Uint8Array(await object.arrayBuffer()) |
| 123 | + if (body && await sha256Hex(body) !== file.sha256) return response("Public publication is incomplete.", 503) |
| 124 | + const published = assetResponse(new Response(body ? Uint8Array.from(body).buffer : null, { headers: { "content-length": String(file.size), "content-type": object.httpMetadata?.contentType ?? "application/octet-stream", etag: `\"${file.sha256}\"` } }), request.method === "HEAD", publication.revision, "r2") |
| 125 | + if (cache && request.method === "GET") await cache.put(cacheKey, published.clone()).catch(() => undefined) |
| 126 | + return published |
| 127 | + } catch { |
| 128 | + return response("Public publication is incomplete.", 503) |
| 129 | + } |
| 130 | +} |
| 131 | + |
| 132 | +function isPageSnapshot(snapshot: PageSnapshot, canonicalRevision: string, route: string): boolean { |
| 133 | + return snapshot.schema === PUBLISHED_PAGE_SCHEMA && snapshot.canonicalRevision === canonicalRevision && snapshot.route === route |
| 134 | + && Number.isInteger(snapshot.status) && snapshot.status >= 100 && snapshot.status <= 599 && typeof snapshot.statusText === "string" |
| 135 | + && Array.isArray(snapshot.headers) && snapshot.headers.every((header) => Array.isArray(header) && header.length === 2 && header.every((value) => typeof value === "string")) |
| 136 | + && typeof snapshot.body === "string" |
| 137 | +} |
| 138 | + |
| 139 | +function publicationResponse(response: Response, head: boolean, revision: string, source: "edge" | "r2"): Response { |
| 140 | + const headers = new Headers(response.headers) |
| 141 | + // The Worker cache key includes this immutable publication revision and site generation. |
| 142 | + headers.set("cache-control", "public, max-age=60, s-maxage=60") |
| 143 | + headers.set("x-wp-codebox-publication-revision", revision) |
| 144 | + headers.set("x-wp-codebox-publication-cache", source) |
| 145 | + return new Response(head ? null : response.body, { status: response.status, statusText: response.statusText, headers }) |
| 146 | +} |
| 147 | + |
| 148 | +function response(message: string, status: number): Response { |
| 149 | + return new Response(message, { status, headers: { "cache-control": "no-store", "x-wp-codebox-public-reader": "bounded" } }) |
| 150 | +} |
| 151 | + |
| 152 | +function isCanonicalRelativePath(path: string): boolean { |
| 153 | + return path.length > 0 && path.length <= 2_048 && !path.startsWith("/") && !path.includes("\\") && path.split("/").every((part) => part !== "" && part !== "." && part !== "..") |
| 154 | +} |
| 155 | + |
| 156 | +async function sha256Hex(bytes: Uint8Array): Promise<string> { |
| 157 | + const digest = await crypto.subtle.digest("SHA-256", bytes as Uint8Array<ArrayBuffer>) |
| 158 | + return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("") |
| 159 | +} |
| 160 | + |
| 161 | +function assetResponse(response: Response, head: boolean, revision: string, source: "edge" | "r2"): Response { |
| 162 | + const headers = new Headers(response.headers) |
| 163 | + headers.set("cache-control", "public, max-age=60, s-maxage=60") |
| 164 | + headers.set("x-wp-codebox-publication-revision", revision) |
| 165 | + headers.set("x-wp-codebox-publication-asset", source) |
| 166 | + return new Response(head ? null : response.body, { status: response.status, headers }) |
| 167 | +} |
0 commit comments