@cloudhal/astro-renderer 0.0.0-stage → 0.1.0
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/LICENSE +202 -0
- package/README.md +36 -2
- package/dist/src/ambient-client.d.ts +17 -0
- package/dist/src/ambient-client.js +55 -0
- package/dist/src/analytics-client.d.ts +17 -0
- package/dist/src/analytics-client.js +96 -0
- package/dist/src/analytics-middleware.d.ts +6 -0
- package/dist/src/analytics-middleware.js +43 -0
- package/dist/src/analytics-node.d.ts +46 -0
- package/dist/src/analytics-node.js +134 -0
- package/dist/src/analytics.d.ts +117 -0
- package/dist/src/analytics.js +372 -0
- package/dist/src/archive.d.ts +106 -0
- package/dist/src/archive.js +207 -0
- package/dist/src/astro-env.d.ts +21 -0
- package/dist/src/block-html.d.ts +14 -0
- package/dist/src/block-html.js +103 -0
- package/dist/src/blocks.d.ts +24 -0
- package/dist/src/blocks.js +66 -0
- package/dist/src/cache-tags.d.ts +25 -0
- package/dist/src/cache-tags.js +59 -0
- package/dist/src/carousel-client.d.ts +28 -0
- package/dist/src/carousel-client.js +67 -0
- package/dist/src/chart.d.ts +34 -0
- package/dist/src/chart.js +182 -0
- package/dist/src/chrome-client.d.ts +27 -0
- package/dist/src/chrome-client.js +64 -0
- package/dist/src/cloudflare-entry.d.ts +87 -0
- package/dist/src/cloudflare-entry.js +548 -0
- package/dist/src/comments-client.d.ts +11 -0
- package/dist/src/comments-client.js +58 -0
- package/dist/src/comments-html.d.ts +42 -0
- package/dist/src/comments-html.js +303 -0
- package/dist/src/comments-middleware.d.ts +6 -0
- package/dist/src/comments-middleware.js +38 -0
- package/dist/src/comments-node.d.ts +42 -0
- package/dist/src/comments-node.js +112 -0
- package/dist/src/comments-view.d.ts +68 -0
- package/dist/src/comments-view.js +174 -0
- package/dist/src/comments.d.ts +66 -0
- package/dist/src/comments.js +258 -0
- package/dist/src/components/Block.astro +39 -0
- package/dist/src/components/Body.astro +43 -0
- package/dist/src/components/Comments.astro +19 -0
- package/dist/src/components/ContentList.astro +31 -0
- package/dist/src/components/EntryArticle.astro +31 -0
- package/dist/src/components/Hero.astro +36 -0
- package/dist/src/components/Image.astro +36 -0
- package/dist/src/components/RichText.astro +19 -0
- package/dist/src/components/Sections.astro +66 -0
- package/dist/src/components/SeoHead.astro +22 -0
- package/dist/src/components/Surface.astro +36 -0
- package/dist/src/components/SurfaceNode.astro +82 -0
- package/dist/src/components/index.d.ts +12 -0
- package/dist/src/components/index.js +12 -0
- package/dist/src/csp.d.ts +20 -0
- package/dist/src/csp.js +28 -0
- package/dist/src/embed-client.d.ts +38 -0
- package/dist/src/embed-client.js +98 -0
- package/dist/src/embed-middleware.d.ts +9 -0
- package/dist/src/embed-middleware.js +49 -0
- package/dist/src/feeds.d.ts +72 -0
- package/dist/src/feeds.js +246 -0
- package/dist/src/gates.d.ts +25 -0
- package/dist/src/gates.js +63 -0
- package/dist/src/index.d.ts +17 -0
- package/dist/src/index.js +17 -0
- package/dist/src/integration.d.ts +55 -0
- package/dist/src/integration.js +244 -0
- package/dist/src/kit.d.ts +48 -0
- package/dist/src/kit.js +83 -0
- package/dist/src/locale-feeds.d.ts +29 -0
- package/dist/src/locale-feeds.js +152 -0
- package/dist/src/locale-middleware.d.ts +5 -0
- package/dist/src/locale-middleware.js +26 -0
- package/dist/src/locales.d.ts +87 -0
- package/dist/src/locales.js +336 -0
- package/dist/src/markdown.d.ts +83 -0
- package/dist/src/markdown.js +533 -0
- package/dist/src/media-middleware.d.ts +5 -0
- package/dist/src/media-middleware.js +18 -0
- package/dist/src/media-route.d.ts +47 -0
- package/dist/src/media-route.js +238 -0
- package/dist/src/media.d.ts +109 -0
- package/dist/src/media.js +298 -0
- package/dist/src/motion-client.d.ts +39 -0
- package/dist/src/motion-client.js +115 -0
- package/dist/src/navigation.d.ts +127 -0
- package/dist/src/navigation.js +382 -0
- package/dist/src/not-found.d.ts +16 -0
- package/dist/src/not-found.js +41 -0
- package/dist/src/overlay-client.d.ts +20 -0
- package/dist/src/overlay-client.js +49 -0
- package/dist/src/prefs-client.d.ts +14 -0
- package/dist/src/prefs-client.js +18 -0
- package/dist/src/preview.d.ts +70 -0
- package/dist/src/preview.js +551 -0
- package/dist/src/resolver.d.ts +71 -0
- package/dist/src/resolver.js +206 -0
- package/dist/src/routing.d.ts +108 -0
- package/dist/src/routing.js +285 -0
- package/dist/src/runtime-workerd.d.ts +87 -0
- package/dist/src/runtime-workerd.js +275 -0
- package/dist/src/runtime.d.ts +59 -0
- package/dist/src/runtime.js +153 -0
- package/dist/src/safe-urls.d.ts +13 -0
- package/dist/src/safe-urls.js +35 -0
- package/dist/src/sanitize.d.ts +7 -0
- package/dist/src/sanitize.js +217 -0
- package/dist/src/search-client.d.ts +29 -0
- package/dist/src/search-client.js +92 -0
- package/dist/src/search-limit.d.ts +36 -0
- package/dist/src/search-limit.js +66 -0
- package/dist/src/search.d.ts +64 -0
- package/dist/src/search.js +155 -0
- package/dist/src/seo.d.ts +85 -0
- package/dist/src/seo.js +468 -0
- package/dist/src/site-dispatch.d.ts +37 -0
- package/dist/src/site-dispatch.js +86 -0
- package/dist/src/site-hosts.d.ts +35 -0
- package/dist/src/site-hosts.js +110 -0
- package/dist/src/source.d.ts +227 -0
- package/dist/src/source.js +794 -0
- package/dist/src/static-gates.d.ts +3 -0
- package/dist/src/static-gates.js +28 -0
- package/dist/src/static-headers.d.ts +30 -0
- package/dist/src/static-headers.js +140 -0
- package/dist/src/static-media.d.ts +4 -0
- package/dist/src/static-media.js +65 -0
- package/dist/src/static-redirects.d.ts +4 -0
- package/dist/src/static-redirects.js +40 -0
- package/dist/src/surface-client.d.ts +34 -0
- package/dist/src/surface-client.js +146 -0
- package/dist/src/surfaces/html.d.ts +35 -0
- package/dist/src/surfaces/html.js +184 -0
- package/dist/src/surfaces/markup.d.ts +57 -0
- package/dist/src/surfaces/markup.js +135 -0
- package/dist/src/surfaces/motion.d.ts +33 -0
- package/dist/src/surfaces/motion.js +132 -0
- package/dist/src/surfaces/primitives/carousel.d.ts +2 -0
- package/dist/src/surfaces/primitives/carousel.js +95 -0
- package/dist/src/surfaces/primitives/content.d.ts +13 -0
- package/dist/src/surfaces/primitives/content.js +159 -0
- package/dist/src/surfaces/primitives/data.d.ts +5 -0
- package/dist/src/surfaces/primitives/data.js +80 -0
- package/dist/src/surfaces/primitives/index.d.ts +54 -0
- package/dist/src/surfaces/primitives/index.js +106 -0
- package/dist/src/surfaces/primitives/inputs.d.ts +8 -0
- package/dist/src/surfaces/primitives/inputs.js +68 -0
- package/dist/src/surfaces/primitives/layout.d.ts +14 -0
- package/dist/src/surfaces/primitives/layout.js +61 -0
- package/dist/src/surfaces/primitives/motion.d.ts +9 -0
- package/dist/src/surfaces/primitives/motion.js +45 -0
- package/dist/src/surfaces/primitives/overlays.d.ts +6 -0
- package/dist/src/surfaces/primitives/overlays.js +79 -0
- package/dist/src/surfaces/tree.d.ts +107 -0
- package/dist/src/surfaces/tree.js +321 -0
- package/dist/src/surfaces.d.ts +14 -0
- package/dist/src/surfaces.js +33 -0
- package/dist/src/taxonomy.d.ts +86 -0
- package/dist/src/taxonomy.js +268 -0
- package/dist/src/theme-settings.d.ts +24 -0
- package/dist/src/theme-settings.js +111 -0
- package/package.json +219 -3
|
@@ -0,0 +1,548 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Worker entry for a Cloudhal site on Cloudflare (`"main"` in the site's wrangler config).
|
|
3
|
+
* Wraps the Astro handler with what a deployed Cloudhal site needs on top:
|
|
4
|
+
*
|
|
5
|
+
* - `POST /__cloudhal/purge` (Bearer `CLOUDHAL_PURGE_TOKEN`) purges this site's edge cache. The
|
|
6
|
+
* admin Worker calls it after publish/rollback. Purges are scoped to the Worker that cached the
|
|
7
|
+
* responses, which is why this lives here and not in the admin Worker (ADR-0012). A JSON body
|
|
8
|
+
* `{ "tags": [...] }` (at most 100, Cloudflare's limit per purge request) purges only those tags
|
|
9
|
+
* (`cloudhal-site-`, `-node-`, `-term-`, `-list-`, see `cache-tags.ts`) — what the admin Worker
|
|
10
|
+
* sends after working out what a publish changed; without one, everything is purged.
|
|
11
|
+
* - `GET /__cloudhal/features` (Bearer `CLOUDHAL_PURGE_TOKEN`) says what this Worker enforces, so
|
|
12
|
+
* the admin Worker never writes data an older site Worker would mishandle (RFC-0008 §7.7):
|
|
13
|
+
* `{ "gates": 1 }` — every public path checks pages' and entries' time gates per request and
|
|
14
|
+
* caps the edge cache at the next one. Until it answers so, writers refuse `availability`.
|
|
15
|
+
* - Redirects (RFC-0002) are answered by the routes themselves (real 301s, `no-store` here like
|
|
16
|
+
* every non-200), so a publish that adds or removes one needs no purge of its own.
|
|
17
|
+
* - Preview responses get every internal link rewritten to keep the signed token, so navigation
|
|
18
|
+
* stays in preview without a cookie (the edge cache does not vary on cookies). Media URLs in
|
|
19
|
+
* images, sources, video and audio keep it too, so draft media show (RFC-0004 §7.3).
|
|
20
|
+
* - `/media/<sha16>/<slug>.<ext>` (RFC-0004 §7.1) is answered here, before Astro: published media
|
|
21
|
+
* are immutable and tagged `cloudhal-media-<siteId>` / `cloudhal-asset-<id>` (not the site tag),
|
|
22
|
+
* so purging pages after a publish leaves them cached.
|
|
23
|
+
* - Site analytics (RFC-0006 §5): `POST /__cloudhal/e` takes page-view and vitals beacons (always
|
|
24
|
+
* `204`, never cached) and writes them to Workers Analytics Engine (`ANALYTICS`); published HTML
|
|
25
|
+
* pages get the `/_cloudhal/p.<hash>.js` tag while the site's setting is on (it sits in the cached
|
|
26
|
+
* HTML, so a settings change purges); responses the Worker renders become `render` events. All of
|
|
27
|
+
* it is off without `CLOUDHAL_ANALYTICS=on` and the binding (`analytics.ts`).
|
|
28
|
+
* - Reader comments (RFC-0007 §6, §15.2): `GET /__cloudhal/comments/challenge`,
|
|
29
|
+
* `POST /__cloudhal/comments` and `POST /__cloudhal/comments/report` are answered here, before
|
|
30
|
+
* Astro and never cached (`comments.ts`), with `CF-Connecting-IP` as the client address. Pages
|
|
31
|
+
* render the section themselves (`loadComments`, `<Comments />`) and set their own CSP when an
|
|
32
|
+
* open form uses Turnstile; `withSecurityHeaders` keeps it. All of it is off without a usable
|
|
33
|
+
* `CLOUDHAL_COMMENTS_KEY` (or when the build has no comments module).
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
import { cache } from "cloudflare:workers";
|
|
37
|
+
import config from "virtual:cloudhal/config";
|
|
38
|
+
import { handle } from "@astrojs/cloudflare/handler";
|
|
39
|
+
import { WaeWriter } from "@cloudhal/analytics/wae";
|
|
40
|
+
import {
|
|
41
|
+
analyticsBackend,
|
|
42
|
+
CACHE_TAG_PREFIX,
|
|
43
|
+
resetSource,
|
|
44
|
+
serveMedia,
|
|
45
|
+
withRequestSite,
|
|
46
|
+
} from "@cloudhal/astro-renderer/runtime";
|
|
47
|
+
import { SqlCommentStore } from "@cloudhal/comments/sql";
|
|
48
|
+
import { GATES_FEATURE_VERSION } from "@cloudhal/core-ts/availability";
|
|
49
|
+
import { D1Driver } from "@cloudhal/storage/d1";
|
|
50
|
+
import {
|
|
51
|
+
ANALYTICS_BEACON_PATH,
|
|
52
|
+
deploymentDefaults,
|
|
53
|
+
parseHosts,
|
|
54
|
+
SiteAnalytics,
|
|
55
|
+
} from "./analytics.js";
|
|
56
|
+
import { isCloudhalCacheTag } from "./cache-tags.js";
|
|
57
|
+
import { isCommentsPath, SiteComments } from "./comments.js";
|
|
58
|
+
import { SITE_CSP } from "./csp.js";
|
|
59
|
+
import { EMBED_HEADER, withEmbedFrames } from "./embed-client.js";
|
|
60
|
+
import { PREVIEW_PARAM } from "./resolver.js";
|
|
61
|
+
import { SearchLimiter, searchCost } from "./search-limit.js";
|
|
62
|
+
import { SiteDispatch, unknownHost, withNoindex } from "./site-dispatch.js";
|
|
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
|
+
* Writes made through an RPC-style binding (a test double, or a future binding that returns a
|
|
110
|
+
* promise) are kept alive with `waitUntil`; Workers Analytics Engine's `writeDataPoint` returns
|
|
111
|
+
* nothing, so this costs nothing in production.
|
|
112
|
+
*/
|
|
113
|
+
class PendingWrites {
|
|
114
|
+
#pending = new Set ();
|
|
115
|
+
dataset(binding ) {
|
|
116
|
+
return {
|
|
117
|
+
writeDataPoint: (point) => {
|
|
118
|
+
const result = (binding.writeDataPoint )(point);
|
|
119
|
+
if (result && typeof (result ).then === "function") {
|
|
120
|
+
const p = (result ).catch(() => {});
|
|
121
|
+
this.#pending.add(p);
|
|
122
|
+
p.finally(() => this.#pending.delete(p));
|
|
123
|
+
}
|
|
124
|
+
},
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
/** Settles when the writes made so far have. */
|
|
128
|
+
settled() {
|
|
129
|
+
return Promise.allSettled([...this.#pending]);
|
|
130
|
+
}
|
|
131
|
+
/** Keeps the invocation alive until the writes made so far have settled. */
|
|
132
|
+
flush(ctx ) {
|
|
133
|
+
if (this.#pending.size > 0) ctx.waitUntil(this.settled());
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const pendingWrites = new PendingWrites();
|
|
138
|
+
/** Per site the isolate has served (one on a single-site Worker). */
|
|
139
|
+
const analyticsBySite = new Map ();
|
|
140
|
+
const commentsBySite = new Map ();
|
|
141
|
+
let dispatch ;
|
|
142
|
+
|
|
143
|
+
/** One per isolate: which site a request is for (RFC-0034 §4). */
|
|
144
|
+
function siteDispatch(env , siteIdFromBuild ) {
|
|
145
|
+
dispatch ??= new SiteDispatch({
|
|
146
|
+
siteId: env.CLOUDHAL_SITE_ID ?? (env.CLOUDHAL_SITE_IDS ? undefined : siteIdFromBuild),
|
|
147
|
+
siteIds: env.CLOUDHAL_SITE_IDS,
|
|
148
|
+
sql: () => new D1Driver(env.DB ),
|
|
149
|
+
});
|
|
150
|
+
return dispatch;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** The hosts a site answers on: `CLOUDHAL_SITE_HOSTS`, plus its `site_hosts` rows when multi-site. */
|
|
154
|
+
async function siteHosts(env , siteId ) {
|
|
155
|
+
return [...parseHosts(env.CLOUDHAL_SITE_HOSTS), ...((await dispatch?.hosts(siteId)) ?? [])];
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** One per site and isolate: keys, limits, today's count, replay cache, settings and pointer. */
|
|
159
|
+
async function siteComments(env , siteId ) {
|
|
160
|
+
const known = commentsBySite.get(siteId);
|
|
161
|
+
if (known) return known;
|
|
162
|
+
const { sql, site, snapshot } = analyticsBackend(siteId);
|
|
163
|
+
let store ;
|
|
164
|
+
const comments = new SiteComments({
|
|
165
|
+
siteId,
|
|
166
|
+
secret: env.CLOUDHAL_COMMENTS_KEY,
|
|
167
|
+
// the integration built the module only when `comments.available` is not false
|
|
168
|
+
available: Boolean(config.commentsScript),
|
|
169
|
+
store: async () => {
|
|
170
|
+
store ??= new SqlCommentStore(sql());
|
|
171
|
+
return store;
|
|
172
|
+
},
|
|
173
|
+
site,
|
|
174
|
+
snapshot,
|
|
175
|
+
hosts: await siteHosts(env, siteId),
|
|
176
|
+
acceptRequestHost: (host) => host.endsWith(".workers.dev"),
|
|
177
|
+
rateLimit: env.COMMENTS_RL,
|
|
178
|
+
onError: (m, e) => console.error(m, e),
|
|
179
|
+
});
|
|
180
|
+
commentsBySite.set(siteId, comments);
|
|
181
|
+
return comments;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** One per site and isolate: settings, pointer, rate limits and the render sampler. */
|
|
185
|
+
async function siteAnalytics(env , siteId ) {
|
|
186
|
+
const known = analyticsBySite.get(siteId);
|
|
187
|
+
if (known) return known;
|
|
188
|
+
const { sql, site, snapshot } = analyticsBackend(siteId);
|
|
189
|
+
const analytics = new SiteAnalytics({
|
|
190
|
+
siteId,
|
|
191
|
+
defaults: deploymentDefaults(env.CLOUDHAL_ANALYTICS, env.CLOUDHAL_ANALYTICS_DEFAULTS),
|
|
192
|
+
writer: env.ANALYTICS
|
|
193
|
+
? new WaeWriter(pendingWrites.dataset(env.ANALYTICS), {
|
|
194
|
+
onError: (m, e) => console.error(m, e),
|
|
195
|
+
})
|
|
196
|
+
: undefined,
|
|
197
|
+
sql,
|
|
198
|
+
site,
|
|
199
|
+
snapshot,
|
|
200
|
+
script: config.analyticsScript,
|
|
201
|
+
hosts: await siteHosts(env, siteId),
|
|
202
|
+
acceptRequestHost: (host) => host.endsWith(".workers.dev"),
|
|
203
|
+
rateLimit:
|
|
204
|
+
env.ANALYTICS_RL && env.CLOUDHAL_PURGE_TOKEN
|
|
205
|
+
? { binding: env.ANALYTICS_RL, secret: env.CLOUDHAL_PURGE_TOKEN }
|
|
206
|
+
: undefined,
|
|
207
|
+
onError: (m, e) => console.error(m, e),
|
|
208
|
+
});
|
|
209
|
+
analyticsBySite.set(siteId, analytics);
|
|
210
|
+
return analytics;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Appends the analytics tag to `<head>` of a published HTML page (§5.1). */
|
|
214
|
+
async function withAnalyticsTag(response , a ) {
|
|
215
|
+
if (
|
|
216
|
+
response.status !== 200 ||
|
|
217
|
+
response.headers.get("x-cloudhal-mode") !== "published" ||
|
|
218
|
+
!(response.headers.get("content-type") ?? "").includes("text/html")
|
|
219
|
+
)
|
|
220
|
+
return response;
|
|
221
|
+
const tag = await a.tag();
|
|
222
|
+
if (!tag) return response;
|
|
223
|
+
return new HTMLRewriter()
|
|
224
|
+
.on("head", {
|
|
225
|
+
element(el) {
|
|
226
|
+
el.append(tag, { html: true });
|
|
227
|
+
},
|
|
228
|
+
})
|
|
229
|
+
.transform(response);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function timingSafeEqual(a , b ) {
|
|
233
|
+
const ea = new TextEncoder().encode(a);
|
|
234
|
+
const eb = new TextEncoder().encode(b);
|
|
235
|
+
if (ea.length !== eb.length) return false;
|
|
236
|
+
let diff = 0;
|
|
237
|
+
for (let i = 0; i < ea.length; i++) diff |= (ea[i] ) ^ (eb[i] );
|
|
238
|
+
return diff === 0;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** True when the request carries the shared purge token (the admin Worker over `SITE`). */
|
|
242
|
+
function fromAdmin(request , env ) {
|
|
243
|
+
const expected = env.CLOUDHAL_PURGE_TOKEN;
|
|
244
|
+
const given = request.headers.get("authorization")?.replace(/^Bearer\s+/i, "") ?? "";
|
|
245
|
+
return !!expected && timingSafeEqual(given, expected);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* What this site Worker enforces (RFC-0008 §7.6–§7.7): the admin Worker asks before it lets anyone
|
|
250
|
+
* write time gates. Authenticated like the purge (it is not a public endpoint), never cached.
|
|
251
|
+
*/
|
|
252
|
+
function features(request , env ) {
|
|
253
|
+
const headers = { "cache-control": "no-store", "cloudflare-cdn-cache-control": "no-store" };
|
|
254
|
+
if (request.method !== "GET" && request.method !== "HEAD")
|
|
255
|
+
return new Response("method not allowed", {
|
|
256
|
+
status: 405,
|
|
257
|
+
headers: { ...headers, allow: "GET" },
|
|
258
|
+
});
|
|
259
|
+
if (!fromAdmin(request, env))
|
|
260
|
+
return Response.json({ error: "unauthorized" }, { status: 401, headers });
|
|
261
|
+
return Response.json({ gates: GATES_FEATURE_VERSION }, { headers });
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* The purge's optional JSON body: `tags` (1–100 Cloudhal cache tags) and, on a multi-site Worker,
|
|
266
|
+
* the `siteId` whose publish it is (RFC-0034 §4). A 400 for anything else.
|
|
267
|
+
*/
|
|
268
|
+
async function purgeBody(
|
|
269
|
+
request ,
|
|
270
|
+
served ,
|
|
271
|
+
) {
|
|
272
|
+
if (!(request.headers.get("content-type") ?? "").includes("application/json")) return {};
|
|
273
|
+
const body = (await request.json().catch(() => undefined))
|
|
274
|
+
|
|
275
|
+
;
|
|
276
|
+
const out = {};
|
|
277
|
+
if (body?.siteId !== undefined) {
|
|
278
|
+
if (typeof body.siteId !== "string" || !served.includes(body.siteId))
|
|
279
|
+
return Response.json({ error: "siteId is not served by this Worker" }, { status: 400 });
|
|
280
|
+
out.siteId = body.siteId;
|
|
281
|
+
}
|
|
282
|
+
if (body?.tags !== undefined) {
|
|
283
|
+
if (
|
|
284
|
+
!Array.isArray(body.tags) ||
|
|
285
|
+
body.tags.length === 0 ||
|
|
286
|
+
body.tags.length > 100 ||
|
|
287
|
+
!body.tags.every((t) => typeof t === "string" && isCloudhalCacheTag(t))
|
|
288
|
+
)
|
|
289
|
+
return Response.json(
|
|
290
|
+
{
|
|
291
|
+
error:
|
|
292
|
+
"tags must be 1–100 cloudhal-site-/node-/term-/list-/media-/asset-/comments- cache tags",
|
|
293
|
+
},
|
|
294
|
+
{ status: 400 },
|
|
295
|
+
);
|
|
296
|
+
out.tags = body.tags ;
|
|
297
|
+
}
|
|
298
|
+
return out;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
async function purge(
|
|
302
|
+
request ,
|
|
303
|
+
env ,
|
|
304
|
+
siteIdFromBuild ,
|
|
305
|
+
) {
|
|
306
|
+
if (request.method !== "POST") return new Response("method not allowed", { status: 405 });
|
|
307
|
+
const expected = env.CLOUDHAL_PURGE_TOKEN;
|
|
308
|
+
const given = request.headers.get("authorization")?.replace(/^Bearer\s+/i, "") ?? "";
|
|
309
|
+
if (!expected || !timingSafeEqual(given, expected))
|
|
310
|
+
return Response.json({ error: "unauthorized" }, { status: 401 });
|
|
311
|
+
const d = siteDispatch(env, siteIdFromBuild);
|
|
312
|
+
const siteId = d.siteIds[0];
|
|
313
|
+
const tag = `${CACHE_TAG_PREFIX}${siteId}`;
|
|
314
|
+
// `cache.purge` exists on Cloudflare; local workerd has no edge cache to purge.
|
|
315
|
+
const purger = (
|
|
316
|
+
cache
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
)?.purge;
|
|
322
|
+
// Optional body `{ "tags": [...] }`: purge only those Cloudhal tags (RFC-0002 §7). 100 per
|
|
323
|
+
// request is Cloudflare's limit for tag purges on the Free tier, which Workers Cache always uses
|
|
324
|
+
// (https://developers.cloudflare.com/cache/how-to/purge-cache/#hostname-tag-prefix-url-and-purge-everything-limits,
|
|
325
|
+
// https://developers.cloudflare.com/workers/cache/purge/); the admin Worker batches to it.
|
|
326
|
+
// Without a body everything is purged (first publish, or when the diff is unavailable).
|
|
327
|
+
const body = await purgeBody(request, d.siteIds);
|
|
328
|
+
if (body instanceof Response) return body;
|
|
329
|
+
const only = body.siteId;
|
|
330
|
+
let tags = body.tags;
|
|
331
|
+
// Re-read what the purged sites' publish or settings change touched (RFC-0006 §9.2, RFC-0007
|
|
332
|
+
// §8.3): pointers, settings, and on a multi-site Worker the hostnames.
|
|
333
|
+
d.reset();
|
|
334
|
+
for (const id of only ? [only] : d.siteIds) {
|
|
335
|
+
resetSource(id);
|
|
336
|
+
analyticsBySite.get(id)?.reset();
|
|
337
|
+
commentsBySite.get(id)?.reset();
|
|
338
|
+
}
|
|
339
|
+
if (!tags && d.multi)
|
|
340
|
+
tags = (only ? [only] : [...d.siteIds]).map((id) => `${CACHE_TAG_PREFIX}${id}`).slice(0, 100);
|
|
341
|
+
if (!purger)
|
|
342
|
+
return Response.json({
|
|
343
|
+
purged: false,
|
|
344
|
+
tag,
|
|
345
|
+
...(tags ? { tags } : {}),
|
|
346
|
+
reason: "no edge cache in this runtime",
|
|
347
|
+
});
|
|
348
|
+
// A single-site Worker cached only its site, so purging everything also drops entries Cloudflare
|
|
349
|
+
// cached on its own (a 404 for a page published since). A multi-site Worker purges tags only:
|
|
350
|
+
// one site's publish never empties another's cache (RFC-0034 invariant 4).
|
|
351
|
+
const result = await purger.call(cache, tags ? { tags } : { purgeEverything: true });
|
|
352
|
+
return Response.json(
|
|
353
|
+
{ purged: result.success, tag, ...(tags ? { tags } : {}), errors: result.errors ?? [] },
|
|
354
|
+
{ status: result.success ? 200 : 502 },
|
|
355
|
+
);
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** A site-relative URL with the preview token added; anything else unchanged. */
|
|
359
|
+
function withToken(value , token ) {
|
|
360
|
+
if (!value.startsWith("/") || value.startsWith("//")) return value;
|
|
361
|
+
const url = new URL(value, "https://x");
|
|
362
|
+
url.searchParams.set(PREVIEW_PARAM, token);
|
|
363
|
+
return `${url.pathname}${url.search}${url.hash}`;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
function keepPreviewInLinks(response , token ) {
|
|
367
|
+
const rewrite = (attr ) => ({
|
|
368
|
+
element(el ) {
|
|
369
|
+
const value = el.getAttribute(attr);
|
|
370
|
+
if (value) el.setAttribute(attr, withToken(value, token));
|
|
371
|
+
},
|
|
372
|
+
});
|
|
373
|
+
// `srcset`: "<url> <descriptor>, …" — each candidate URL keeps the token.
|
|
374
|
+
const rewriteSrcset = {
|
|
375
|
+
element(el ) {
|
|
376
|
+
const value = el.getAttribute("srcset");
|
|
377
|
+
if (!value) return;
|
|
378
|
+
el.setAttribute(
|
|
379
|
+
"srcset",
|
|
380
|
+
value
|
|
381
|
+
.split(",")
|
|
382
|
+
.map((c) => {
|
|
383
|
+
const [u, ...rest] = c.trim().split(/\s+/);
|
|
384
|
+
return [withToken(u ?? "", token), ...rest].join(" ");
|
|
385
|
+
})
|
|
386
|
+
.join(", "),
|
|
387
|
+
);
|
|
388
|
+
},
|
|
389
|
+
};
|
|
390
|
+
return new HTMLRewriter()
|
|
391
|
+
.on("a[href]", rewrite("href"))
|
|
392
|
+
.on("form[action]", rewrite("action"))
|
|
393
|
+
.on("img[src]", rewrite("src"))
|
|
394
|
+
.on("img[srcset]", rewriteSrcset)
|
|
395
|
+
.on("source[srcset]", rewriteSrcset)
|
|
396
|
+
.on("source[src]", rewrite("src"))
|
|
397
|
+
.on("video[src]", rewrite("src"))
|
|
398
|
+
.on("video[poster]", rewrite("poster"))
|
|
399
|
+
.on("audio[src]", rewrite("src"))
|
|
400
|
+
.transform(response);
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* Only a 200 page may sit in the edge cache (tagged, until the next publish). Anything else — a
|
|
405
|
+
* 404 for a page that does not exist *yet*, a 503 before the first publish — must not be cached,
|
|
406
|
+
* or it would outlive the publish that fixes it.
|
|
407
|
+
*/
|
|
408
|
+
function cacheOnlySuccess(response ) {
|
|
409
|
+
if (response.status === 200 || response.status === 304) return response;
|
|
410
|
+
const headers = new Headers(response.headers);
|
|
411
|
+
headers.set("cloudflare-cdn-cache-control", "no-store");
|
|
412
|
+
headers.set("cache-control", "no-store");
|
|
413
|
+
return new Response(response.body, {
|
|
414
|
+
status: response.status,
|
|
415
|
+
statusText: response.statusText,
|
|
416
|
+
headers,
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function withSecurityHeaders(response ) {
|
|
421
|
+
if (!(response.headers.get("content-type") ?? "").includes("text/html")) return response;
|
|
422
|
+
const headers = new Headers(response.headers);
|
|
423
|
+
if (!headers.has("content-security-policy")) headers.set("content-security-policy", SITE_CSP);
|
|
424
|
+
// A page with a video player asked for its frames (RFC-0015 §4): this page only.
|
|
425
|
+
if (headers.has(EMBED_HEADER)) {
|
|
426
|
+
headers.set(
|
|
427
|
+
"content-security-policy",
|
|
428
|
+
withEmbedFrames(headers.get("content-security-policy") ?? SITE_CSP),
|
|
429
|
+
);
|
|
430
|
+
headers.delete(EMBED_HEADER);
|
|
431
|
+
}
|
|
432
|
+
headers.set("x-content-type-options", "nosniff");
|
|
433
|
+
headers.set("referrer-policy", "strict-origin-when-cross-origin");
|
|
434
|
+
return new Response(response.body, {
|
|
435
|
+
status: response.status,
|
|
436
|
+
statusText: response.statusText,
|
|
437
|
+
headers,
|
|
438
|
+
});
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/** Everything after the operator endpoints, for one site (or none: a Worker not yet pointed at one). */
|
|
442
|
+
async function serveSite(
|
|
443
|
+
call ,
|
|
444
|
+
siteId ,
|
|
445
|
+
searchLimiter ,
|
|
446
|
+
) {
|
|
447
|
+
const { request, env, ctx } = call;
|
|
448
|
+
const url = new URL(request.url);
|
|
449
|
+
const a = siteId ? await siteAnalytics(env, siteId) : undefined;
|
|
450
|
+
// Analytics beacons (RFC-0006 §5.2): 204 for every outcome, never cached (POST).
|
|
451
|
+
if (url.pathname === ANALYTICS_BEACON_PATH) {
|
|
452
|
+
if (!a)
|
|
453
|
+
return new Response(null, {
|
|
454
|
+
status: request.method === "POST" ? 204 : 405,
|
|
455
|
+
headers: { "cache-control": "no-store" },
|
|
456
|
+
});
|
|
457
|
+
// On Cloudflare the edge sets CF-Connecting-IP (a client's own value is overwritten), so
|
|
458
|
+
// it is the trusted address here; the beacon handler never reads headers for it.
|
|
459
|
+
const clientIp = request.headers.get("cf-connecting-ip")?.trim();
|
|
460
|
+
const answer = await a.beacon(request, clientIp ? { clientIp } : {});
|
|
461
|
+
pendingWrites.flush(ctx);
|
|
462
|
+
return answer;
|
|
463
|
+
}
|
|
464
|
+
// Reader comments (RFC-0007 §6.1): before Astro, never cached; `404` while comments are off.
|
|
465
|
+
if (isCommentsPath(url.pathname)) {
|
|
466
|
+
if (!siteId)
|
|
467
|
+
return Response.json(
|
|
468
|
+
{ error: "not_found" },
|
|
469
|
+
{ status: 404, headers: { "cache-control": "no-store" } },
|
|
470
|
+
);
|
|
471
|
+
// CF-Connecting-IP is set by Cloudflare's edge (a client's own value is overwritten).
|
|
472
|
+
return (await (
|
|
473
|
+
await siteComments(env, siteId)
|
|
474
|
+
).handle(request, {
|
|
475
|
+
clientAddress: request.headers.get("cf-connecting-ip") ?? undefined,
|
|
476
|
+
})) ;
|
|
477
|
+
}
|
|
478
|
+
// Site search (RFC-0019 §3, RFC-0029 §5): per-client limit before anything renders; the
|
|
479
|
+
// modal's endpoint answers in JSON.
|
|
480
|
+
const cost = searchCost(url.pathname);
|
|
481
|
+
if (cost !== undefined) {
|
|
482
|
+
const wait = searchLimiter.take(request.headers.get("cf-connecting-ip") ?? undefined, cost);
|
|
483
|
+
if (wait > 0) {
|
|
484
|
+
const json = url.pathname.endsWith(".json");
|
|
485
|
+
return new Response(
|
|
486
|
+
json
|
|
487
|
+
? JSON.stringify({ error: "rate_limited" })
|
|
488
|
+
: "Too many searches; try again in a minute.",
|
|
489
|
+
{
|
|
490
|
+
status: 429,
|
|
491
|
+
headers: {
|
|
492
|
+
"retry-after": String(wait),
|
|
493
|
+
"cache-control": "no-store",
|
|
494
|
+
"content-type": json ? "application/json; charset=utf-8" : "text/plain; charset=utf-8",
|
|
495
|
+
},
|
|
496
|
+
},
|
|
497
|
+
);
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
const started = Date.now();
|
|
501
|
+
const media = siteId ? await serveMedia(request, { siteId }) : undefined;
|
|
502
|
+
const rendered =
|
|
503
|
+
media ??
|
|
504
|
+
withSecurityHeaders(
|
|
505
|
+
cacheOnlySuccess((await handle(request, env , ctx)) ),
|
|
506
|
+
);
|
|
507
|
+
// Server-side render events (§5.4), off the response path: published HTML 200s (cache
|
|
508
|
+
// misses), redirects, 404, 410, 451 and 5xx; never previews or HEAD.
|
|
509
|
+
if (a?.available) {
|
|
510
|
+
const renderMs = Date.now() - started;
|
|
511
|
+
ctx.waitUntil(a.render(request, rendered, renderMs).then(() => pendingWrites.settled()));
|
|
512
|
+
}
|
|
513
|
+
if (media) return media;
|
|
514
|
+
const response = a?.available ? await withAnalyticsTag(rendered, a) : rendered;
|
|
515
|
+
const token = response.headers.get("x-cloudhal-preview-token");
|
|
516
|
+
if (response.headers.get("x-cloudhal-mode") !== "preview" || !token) return response;
|
|
517
|
+
const headers = new Headers(response.headers);
|
|
518
|
+
headers.delete("x-cloudhal-preview-token");
|
|
519
|
+
const stripped = new Response(response.body, {
|
|
520
|
+
status: response.status,
|
|
521
|
+
statusText: response.statusText,
|
|
522
|
+
headers,
|
|
523
|
+
});
|
|
524
|
+
return (headers.get("content-type") ?? "").includes("text/html")
|
|
525
|
+
? keepPreviewInLinks(stripped, token)
|
|
526
|
+
: stripped;
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
export function createSiteWorker(options = {}) {
|
|
530
|
+
const searchLimiter = new SearchLimiter();
|
|
531
|
+
return {
|
|
532
|
+
async fetch(request , env , ctx ) {
|
|
533
|
+
const url = new URL(request.url);
|
|
534
|
+
if (url.pathname === "/__cloudhal/purge") return purge(request, env, options.siteId);
|
|
535
|
+
if (url.pathname === "/__cloudhal/features") return features(request, env);
|
|
536
|
+
// RFC-0034 §4: the hostname picks the site on a multi-site Worker; everything the request
|
|
537
|
+
// runs (Astro's render included) then sees that site.
|
|
538
|
+
const choice = await siteDispatch(env, options.siteId).choose(request);
|
|
539
|
+
if (choice.kind === "unknown") return unknownHost();
|
|
540
|
+
const siteId = choice.siteId;
|
|
541
|
+
const run = () => serveSite({ request, env, ctx }, siteId, searchLimiter);
|
|
542
|
+
const response = siteId ? await withRequestSite(siteId, run) : await run();
|
|
543
|
+
return choice.noindex ? withNoindex(response) : response;
|
|
544
|
+
},
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
export default createSiteWorker();
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type AnalyticsClientFile } from "./analytics-client.js";
|
|
2
|
+
export interface CommentsClient {
|
|
3
|
+
/** The module the comments section loads (`/_cloudhal/c.<hash>.js`). */
|
|
4
|
+
readonly module: AnalyticsClientFile;
|
|
5
|
+
/** The dedicated worker that solves challenges (`/_cloudhal/cw.<hash>.js`). */
|
|
6
|
+
readonly solver: AnalyticsClientFile;
|
|
7
|
+
}
|
|
8
|
+
/** Writes both files under `dir` (a URL or path of the site's static-assets directory). */
|
|
9
|
+
export declare function writeCommentsClient(client: CommentsClient, dir: URL | string): Promise<void>;
|
|
10
|
+
/** Builds both files once per process (they depend only on the package sources). */
|
|
11
|
+
export declare function buildCommentsClient(): Promise<CommentsClient>;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Builds the comments module and its proof-of-work worker (RFC-0007 §7.3, §8.2) from
|
|
3
|
+
* `@cloudhal/comments/client` with Vite, at integration time: the worker first, so its hashed URL
|
|
4
|
+
* can be baked into the module. Both are minified ES modules named by the first 8 hex characters of
|
|
5
|
+
* their SHA-256 (`/_cloudhal/c.<hash>.js`, `/_cloudhal/cw.<hash>.js`), so the static-assets layer
|
|
6
|
+
* can serve them as immutable. Node only (build time).
|
|
7
|
+
*/
|
|
8
|
+
import { createHash } from "node:crypto";
|
|
9
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
import { fileURLToPath } from "node:url";
|
|
12
|
+
import { CLIENT_DIR, COMMENTS_CLIENT_SOURCES, SOLVER_URL_DEFINE } from "@cloudhal/comments/client";
|
|
13
|
+
import { bundle } from "./analytics-client.js";
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
function hashed(prefix , code ) {
|
|
23
|
+
const hash = createHash("sha256").update(code).digest("hex").slice(0, 8);
|
|
24
|
+
return { path: `${CLIENT_DIR}${prefix}.${hash}.js`, code };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Writes both files under `dir` (a URL or path of the site's static-assets directory). */
|
|
28
|
+
export async function writeCommentsClient(
|
|
29
|
+
client ,
|
|
30
|
+
dir ,
|
|
31
|
+
) {
|
|
32
|
+
const root = typeof dir === "string" ? dir : fileURLToPath(dir.href);
|
|
33
|
+
for (const file of [client.module, client.solver]) {
|
|
34
|
+
const target = path.join(root, file.path);
|
|
35
|
+
await mkdir(path.dirname(target), { recursive: true });
|
|
36
|
+
await writeFile(target, file.code);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
let built ;
|
|
41
|
+
|
|
42
|
+
/** Builds both files once per process (they depend only on the package sources). */
|
|
43
|
+
export function buildCommentsClient() {
|
|
44
|
+
built ??= (async () => {
|
|
45
|
+
const solver = hashed("cw", await bundle(COMMENTS_CLIENT_SOURCES.solver));
|
|
46
|
+
const module = hashed(
|
|
47
|
+
"c",
|
|
48
|
+
await bundle(COMMENTS_CLIENT_SOURCES.module, {
|
|
49
|
+
[SOLVER_URL_DEFINE]: JSON.stringify(solver.path),
|
|
50
|
+
}),
|
|
51
|
+
);
|
|
52
|
+
return { module, solver };
|
|
53
|
+
})();
|
|
54
|
+
built.catch(() => {
|
|
55
|
+
built = undefined;
|
|
56
|
+
});
|
|
57
|
+
return built;
|
|
58
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { CommentsView } from "./comments-view.js";
|
|
2
|
+
export interface CommentStrings {
|
|
3
|
+
readonly heading: (count: number) => string;
|
|
4
|
+
readonly preview: string;
|
|
5
|
+
readonly closed: string;
|
|
6
|
+
readonly removed: string;
|
|
7
|
+
readonly anonymous: string;
|
|
8
|
+
readonly author: string;
|
|
9
|
+
readonly team: string;
|
|
10
|
+
readonly inReplyTo: (name: string) => string;
|
|
11
|
+
readonly reply: string;
|
|
12
|
+
readonly cancelReply: string;
|
|
13
|
+
readonly replyingTo: string;
|
|
14
|
+
readonly report: string;
|
|
15
|
+
readonly reportReason: string;
|
|
16
|
+
readonly reasons: Readonly<Record<"spam" | "abuse" | "personal-data" | "illegal-content" | "other", string>>;
|
|
17
|
+
readonly reportDetails: string;
|
|
18
|
+
readonly reportEmail: string;
|
|
19
|
+
readonly sendReport: string;
|
|
20
|
+
readonly more: string;
|
|
21
|
+
readonly pages: string;
|
|
22
|
+
readonly formTitle: string;
|
|
23
|
+
readonly name: string;
|
|
24
|
+
readonly nameHint: string;
|
|
25
|
+
readonly email: string;
|
|
26
|
+
readonly emailHint: string;
|
|
27
|
+
readonly comment: string;
|
|
28
|
+
readonly website: string;
|
|
29
|
+
readonly moderation: string;
|
|
30
|
+
readonly scriptRequired: string;
|
|
31
|
+
readonly submit: string;
|
|
32
|
+
readonly sending: string;
|
|
33
|
+
readonly awaiting: string;
|
|
34
|
+
readonly notes: Readonly<Record<"pending" | "invalid" | "closed" | "script-required" | "slow-down" | "try-again" | "paused" | "reported", string>>;
|
|
35
|
+
}
|
|
36
|
+
/** The section's words for a locale (English for languages without a translation). */
|
|
37
|
+
export declare function commentStrings(locale: string): CommentStrings;
|
|
38
|
+
/**
|
|
39
|
+
* The section's HTML for a view, or `""` when nothing is shown (hidden and off threads, or no
|
|
40
|
+
* view). Previews get a placeholder and never show comments.
|
|
41
|
+
*/
|
|
42
|
+
export declare function commentsHtml(view: CommentsView | undefined, strings?: CommentStrings): string;
|