@cloudhal/cloudflare 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -21,3 +21,38 @@ export default createAdminWorker({ skills });
21
21
  | `CLOUDHAL_SIGNUP` | `first-user` (default — only the first account, the owner, can sign up), `closed` or `open` |
22
22
 
23
23
  The site Worker itself is the project's Astro build (`@cloudhal/astro-renderer/cloudflare-entry`). Both are deployed, configured and tested by `@cloudhal/cli` (`cloudhal deploy`, `test/cloudflare*.test.ts` on workerd).
24
+
25
+ ## Playground Worker (RFC-0036)
26
+
27
+ `@cloudhal/cloudflare/playground` runs a public playground: every visitor gets a disposable Cloudhal in their own SQLite-backed Durable Object (`PlaygroundSite`), seeded on first use and deleted an hour after the last request (two hours at most), or at once on Reset.
28
+
29
+ ```ts
30
+ // worker.ts in the deploying repo (e.g. cloudhal-dev/try)
31
+ import "@cloudhal/cloudflare/workerd-prelude";
32
+ import { handle } from "@astrojs/cloudflare/handler";
33
+ import { serveMedia, withRequestStore } from "@cloudhal/astro-renderer/runtime";
34
+ import { createPlaygroundWorker } from "@cloudhal/cloudflare/playground";
35
+
36
+ const playground = createPlaygroundWorker({
37
+ deployUrl: "https://cloudhal.dev/docs/deploy",
38
+ seed: async (store) => ({ siteId: (await seedDemo(store)).id }),
39
+ render: (request, { store, siteId, env, ctx }) =>
40
+ withRequestStore(store, siteId, async () =>
41
+ (await serveMedia(request, { siteId })) ?? (handle(request, env as never, ctx) as Promise<Response>)),
42
+ demoMedia: { prefix: "demo/", keys: DEMO_KEYS },
43
+ });
44
+ export const PlaygroundSite = playground.PlaygroundSite;
45
+ export default playground.worker;
46
+ ```
47
+
48
+ | Binding / secret | Purpose |
49
+ |---|---|
50
+ | `PLAYGROUND` (Durable Object, `new_sqlite_classes: ["PlaygroundSite"]`) | one database per session, and the daily counter |
51
+ | `ASSETS` (`run_worker_first: true`) | landing page (`/landing/`), Studio at the root with SPA fallback, site assets, demo media |
52
+ | `PLAYGROUND_SECRET` (≥ 32 chars) | signs the `__Host-cloudhal_try` session cookie; without it only the landing page is served |
53
+ | `PLAYGROUND_ENABLED` | `"false"` is the kill switch |
54
+ | `PLAYGROUND_DAILY_SESSIONS` | new sessions per UTC day |
55
+ | `SESSION_LIMIT`, `WRITE_LIMIT` (rate limits) | new sessions per IP, writes per session |
56
+ | `TURNSTILE_SECRET`, `TURNSTILE_SITE_KEY` | asked for only after a session-rate-limit hit |
57
+
58
+ Routes: `POST /_playground/session` (cookie, then `303 /sites`), `POST /_playground/reset`, `/api/*` (guarded by `isBlockedInPlayground`), `/s/<session>/…` (the session's site, `private, no-store`, `noindex`), `/media/*`. Tested on workerd in `test/playground-workerd.test.ts`.
@@ -0,0 +1,79 @@
1
+ /** Options, limits and bindings of the playground Worker (RFC-0036 §1, §7). */
2
+ import type { SiteGraphStore } from "@cloudhal/core-ts";
3
+ /** A Workers Rate Limiting binding (`ratelimits` in wrangler config). */
4
+ export interface RateLimitBinding {
5
+ limit(options: {
6
+ key: string;
7
+ }): Promise<{
8
+ success: boolean;
9
+ }>;
10
+ }
11
+ export interface PlaygroundEnv {
12
+ /** The `PlaygroundSite` Durable Object class (`new_sqlite_classes`). */
13
+ PLAYGROUND: DurableObjectNamespace;
14
+ /** Static files: the landing page, Studio and the site's own assets, demo media. */
15
+ ASSETS: Fetcher;
16
+ /** Signs session cookies; at least 32 characters. Without it the Worker serves only the landing page. */
17
+ PLAYGROUND_SECRET?: string;
18
+ /** `"false"` is the kill switch: the landing page only; open sessions expire on their own. */
19
+ PLAYGROUND_ENABLED?: string;
20
+ /** New sessions per UTC day; past it the kill-switch page shows until midnight UTC. */
21
+ PLAYGROUND_DAILY_SESSIONS?: string;
22
+ /** New sessions per IP (key `CF-Connecting-IP`). */
23
+ SESSION_LIMIT?: RateLimitBinding;
24
+ /** Writes per session. */
25
+ WRITE_LIMIT?: RateLimitBinding;
26
+ /** Turnstile, asked for only after a session-rate-limit hit. */
27
+ TURNSTILE_SECRET?: string;
28
+ TURNSTILE_SITE_KEY?: string;
29
+ }
30
+ export interface PlaygroundLimits {
31
+ /** A session's data lives this long after its last request… */
32
+ idleMinutes: number;
33
+ /** …and never longer than this after it was created. */
34
+ maxMinutes: number;
35
+ /** `ctx.storage.sql.databaseSize` past which writes get 507. */
36
+ maxDatabaseBytes: number;
37
+ /** The session's own blobs (node bodies, bundle shards). */
38
+ maxBlobBytes: number;
39
+ /** One blob. */
40
+ maxObjectBytes: number;
41
+ /** Nodes a session may hold; creating past it gets 507. */
42
+ maxNodes: number;
43
+ /** The API's body limit (one entry or section). */
44
+ maxBodyBytes: number;
45
+ /** Any request body, checked in the Worker before forwarding. */
46
+ maxRequestBytes: number;
47
+ }
48
+ export declare const DEFAULT_PLAYGROUND_LIMITS: PlaygroundLimits;
49
+ /** What renders a session's site: the Astro handler, run inside `withRequestStore`. */
50
+ export type PlaygroundRender = (request: Request, scope: {
51
+ store: SiteGraphStore;
52
+ siteId: string;
53
+ env: unknown;
54
+ ctx: ExecutionContext;
55
+ }) => Promise<Response>;
56
+ export interface PlaygroundOptions {
57
+ /** Fills a new session's store (starter site plus the demo pack); returns the site shown. */
58
+ seed(store: SiteGraphStore): Promise<{
59
+ siteId: string;
60
+ }>;
61
+ /** Renders `/s/<session>/…` (the path without the prefix). Without it those paths are 404. */
62
+ render?: PlaygroundRender;
63
+ /** Where "Deploy to Cloudflare" leads. */
64
+ deployUrl: string;
65
+ /** The landing page among the static files. Default `/landing/`. */
66
+ landingPath?: string;
67
+ /** Demo media under this prefix of the static files, read-only beneath each session's blobs. */
68
+ demoMedia?: {
69
+ prefix: string;
70
+ keys?: readonly string[];
71
+ };
72
+ limits?: Partial<PlaygroundLimits>;
73
+ }
74
+ /** Header the Worker sets (and strips from clients) with the verified session ID. */
75
+ export declare const SESSION_HEADER = "x-cloudhal-playground-session";
76
+ export declare const RESET_PATH = "/_playground/reset";
77
+ export declare const SESSION_PATH = "/_playground/session";
78
+ /** Where a session's site renders: `/s/<session>/…`. */
79
+ export declare const SITE_PREFIX = "/s/";
@@ -0,0 +1,84 @@
1
+ /** Options, limits and bindings of the playground Worker (RFC-0036 §1, §7). */
2
+
3
+
4
+ /** A Workers Rate Limiting binding (`ratelimits` in wrangler config). */
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+
30
+  
31
+
32
+  
33
+
34
+
35
+
36
+
37
+
38
+
39
+
40
+
41
+
42
+
43
+
44
+
45
+
46
+
47
+
48
+ export const DEFAULT_PLAYGROUND_LIMITS = {
49
+ idleMinutes: 60,
50
+ maxMinutes: 120,
51
+ maxDatabaseBytes: 20 * 1024 * 1024,
52
+ maxBlobBytes: 8 * 1024 * 1024,
53
+ maxObjectBytes: 1024 * 1024,
54
+ maxNodes: 500,
55
+ maxBodyBytes: 200_000,
56
+ maxRequestBytes: 1024 * 1024,
57
+ };
58
+
59
+ /** What renders a session's site: the Astro handler, run inside `withRequestStore`. */
60
+
61
+
62
+
63
+
64
+
65
+
66
+
67
+
68
+  
69
+
70
+
71
+
72
+
73
+
74
+
75
+
76
+
77
+
78
+
79
+ /** Header the Worker sets (and strips from clients) with the verified session ID. */
80
+ export const SESSION_HEADER = "x-cloudhal-playground-session";
81
+ export const RESET_PATH = "/_playground/reset";
82
+ export const SESSION_PATH = "/_playground/session";
83
+ /** Where a session's site renders: `/s/<session>/…`. */
84
+ export const SITE_PREFIX = "/s/";
@@ -0,0 +1,7 @@
1
+ /**
2
+ * A playground session's rendered site (RFC-0036 §4): private to the session, never cached or
3
+ * tagged at the edge, `noindex`, and its links kept under `/s/<session>/`.
4
+ */
5
+ /** `/about/` → `/s/<id>/about/`; other origins, fragments and Worker paths stay as they are. */
6
+ export declare function prefixPath(href: string, prefix: string): string;
7
+ export declare function privateSiteResponse(response: Response, prefix: string): Response;
@@ -0,0 +1,42 @@
1
+ /**
2
+ * A playground session's rendered site (RFC-0036 §4): private to the session, never cached or
3
+ * tagged at the edge, `noindex`, and its links kept under `/s/<session>/`.
4
+ */
5
+
6
+ /** Paths the Worker serves itself (static files, media, the API), never under the session prefix. */
7
+ const UNPREFIXED = /^\/(?:media|_astro|_cloudhal|assets|api|_playground)(?:\/|$)/;
8
+
9
+ /** `/about/` → `/s/<id>/about/`; other origins, fragments and Worker paths stay as they are. */
10
+ export function prefixPath(href , prefix ) {
11
+ if (!href.startsWith("/") || href.startsWith("//") || UNPREFIXED.test(href)) return href;
12
+ if (href === prefix || href.startsWith(`${prefix}/`)) return href;
13
+ return `${prefix}${href}`;
14
+ }
15
+
16
+ export function privateSiteResponse(response , prefix ) {
17
+ const headers = new Headers(response.headers);
18
+ headers.set("cache-control", "private, no-store");
19
+ headers.set("cloudflare-cdn-cache-control", "no-store");
20
+ headers.set("x-robots-tag", "noindex");
21
+ headers.delete("cache-tag");
22
+ const location = headers.get("location");
23
+ if (location) headers.set("location", prefixPath(location, prefix));
24
+ const out = new Response(response.body, {
25
+ status: response.status,
26
+ statusText: response.statusText,
27
+ headers,
28
+ });
29
+ const html = headers.get("content-type")?.includes("text/html");
30
+ const Rewriter = (globalThis ).HTMLRewriter;
31
+ if (!html || !Rewriter) return out;
32
+ const rewrite = (attr ) => ({
33
+ element(el ) {
34
+ const v = el.getAttribute(attr);
35
+ if (v) el.setAttribute(attr, prefixPath(v, prefix));
36
+ },
37
+ });
38
+ return new Rewriter()
39
+ .on("a[href]", rewrite("href"))
40
+ .on("form[action]", rewrite("action"))
41
+ .transform(out);
42
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Playground sessions (RFC-0036 §6): a ULID in a host-only cookie. The ULID's timestamp is the
3
+ * creation time, so no server keeps a session table. The cookie carries an HMAC of the ULID: an
4
+ * unsigned one would let a client mint sessions at will and skip the per-IP and daily limits on
5
+ * session creation (amendment to RFC-0036 §6, ADR-0038).
6
+ */
7
+ export declare const SESSION_COOKIE = "__Host-cloudhal_try";
8
+ /** A new ULID: 48-bit milliseconds, then 80 random bits. */
9
+ export declare function newSessionId(now: number): string;
10
+ /** The creation time a session ID carries, or undefined when it is not a ULID. */
11
+ export declare function sessionTime(id: string): number | undefined;
12
+ /** The cookie value for a session: `<ulid>.<mac>`. */
13
+ export declare function signSession(id: string, secret: string): Promise<string>;
14
+ /** The session ID of a cookie value whose MAC holds, else undefined. */
15
+ export declare function verifySession(value: string, secret: string): Promise<string | undefined>;
16
+ /** The session cookie's value in a request, if any. */
17
+ export declare function readSessionCookie(request: Request): string | undefined;
18
+ /** `Set-Cookie` for a session (host-only, `__Host-`: Secure, Path=/, no Domain; ADR-0037). */
19
+ export declare function sessionCookie(value: string, maxAgeSeconds: number): string;
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Playground sessions (RFC-0036 §6): a ULID in a host-only cookie. The ULID's timestamp is the
3
+ * creation time, so no server keeps a session table. The cookie carries an HMAC of the ULID: an
4
+ * unsigned one would let a client mint sessions at will and skip the per-IP and daily limits on
5
+ * session creation (amendment to RFC-0036 §6, ADR-0038).
6
+ */
7
+
8
+ export const SESSION_COOKIE = "__Host-cloudhal_try";
9
+ const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
10
+ const ULID_RE = /^[0-9A-HJKMNP-TV-Z]{26}$/;
11
+ const enc = new TextEncoder();
12
+
13
+ /** A new ULID: 48-bit milliseconds, then 80 random bits. */
14
+ export function newSessionId(now ) {
15
+ let time = "";
16
+ let t = now;
17
+ for (let i = 0; i < 10; i++) {
18
+ time = CROCKFORD[t % 32] + time;
19
+ t = Math.floor(t / 32);
20
+ }
21
+ const random = crypto.getRandomValues(new Uint8Array(16));
22
+ let rest = "";
23
+ for (const b of random) rest += CROCKFORD[b % 32];
24
+ return time + rest;
25
+ }
26
+
27
+ /** The creation time a session ID carries, or undefined when it is not a ULID. */
28
+ export function sessionTime(id ) {
29
+ if (!ULID_RE.test(id)) return undefined;
30
+ let t = 0;
31
+ for (const ch of id.slice(0, 10)) t = t * 32 + CROCKFORD.indexOf(ch);
32
+ return t;
33
+ }
34
+
35
+ async function mac(id , secret ) {
36
+ const key = await crypto.subtle.importKey(
37
+ "raw",
38
+ enc.encode(secret),
39
+ { name: "HMAC", hash: "SHA-256" },
40
+ false,
41
+ ["sign"],
42
+ );
43
+ const sig = new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(id)));
44
+ let bin = "";
45
+ for (const b of sig.slice(0, 16)) bin += String.fromCharCode(b);
46
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
47
+ }
48
+
49
+ /** The cookie value for a session: `<ulid>.<mac>`. */
50
+ export async function signSession(id , secret ) {
51
+ return `${id}.${await mac(id, secret)}`;
52
+ }
53
+
54
+ /** The session ID of a cookie value whose MAC holds, else undefined. */
55
+ export async function verifySession(value , secret ) {
56
+ const [id, tag, extra] = value.split(".");
57
+ if (!id || !tag || extra !== undefined || sessionTime(id) === undefined) return undefined;
58
+ const want = await mac(id, secret);
59
+ if (want.length !== tag.length) return undefined;
60
+ let diff = 0;
61
+ for (let i = 0; i < want.length; i++) diff |= want.charCodeAt(i) ^ tag.charCodeAt(i);
62
+ return diff === 0 ? id : undefined;
63
+ }
64
+
65
+ /** The session cookie's value in a request, if any. */
66
+ export function readSessionCookie(request ) {
67
+ const header = request.headers.get("cookie") ?? "";
68
+ for (const part of header.split(";")) {
69
+ const [name, ...value] = part.trim().split("=");
70
+ if (name === SESSION_COOKIE) return value.join("=");
71
+ }
72
+ return undefined;
73
+ }
74
+
75
+ /** `Set-Cookie` for a session (host-only, `__Host-`: Secure, Path=/, no Domain; ADR-0037). */
76
+ export function sessionCookie(value , maxAgeSeconds ) {
77
+ return `${SESSION_COOKIE}=${value}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=${maxAgeSeconds}`;
78
+ }
@@ -0,0 +1,8 @@
1
+ import { type PlaygroundEnv, type PlaygroundOptions } from "./playground-options.js";
2
+ /** The `PlaygroundSite` Durable Object class, as the Worker module exports it. */
3
+ export type PlaygroundSiteClass = new (state: DurableObjectState, env: PlaygroundEnv) => {
4
+ fetch(request: Request): Promise<Response>;
5
+ alarm(): Promise<void>;
6
+ };
7
+ /** Builds the Durable Object class for `options` (exported by the Worker module as `PlaygroundSite`). */
8
+ export declare function playgroundSiteClass(options: PlaygroundOptions): PlaygroundSiteClass;
@@ -0,0 +1,216 @@
1
+ /**
2
+ * `PlaygroundSite` (RFC-0036 §1–§6): one SQLite-backed Durable Object per playground session. It
3
+ * holds the session's whole Cloudhal — store, API and renderer — over `DoSqliteDriver`, seeds it
4
+ * on first use, deletes everything at the TTL alarm or on Reset, and refuses requests past the
5
+ * session's 2-hour cap even if the alarm never ran. The Worker in front has already checked the
6
+ * cookie, the guard and the rate limits; this object trusts only its `SESSION_HEADER`.
7
+ */
8
+ import { createApi } from "@cloudhal/api";
9
+ import { SiteGraphStore } from "@cloudhal/core-ts";
10
+ import {
11
+
12
+ FetcherBlobStore,
13
+ LayeredBlobStore,
14
+ SqlBlobStore,
15
+ } from "@cloudhal/storage";
16
+ import { DoSqliteDriver } from "@cloudhal/storage/do-sqlite";
17
+ import {
18
+ DEFAULT_PLAYGROUND_LIMITS,
19
+
20
+
21
+
22
+ RESET_PATH,
23
+ SESSION_HEADER,
24
+ SITE_PREFIX,
25
+ } from "./playground-options.js";
26
+ import { privateSiteResponse } from "./playground-render.js";
27
+ import { sessionTime } from "./playground-session.js";
28
+
29
+ const MINUTE = 60_000;
30
+ const json = (status , body ) =>
31
+ new Response(JSON.stringify(body), {
32
+ status,
33
+ headers: { "content-type": "application/json", "cache-control": "no-store" },
34
+ });
35
+
36
+
37
+
38
+
39
+
40
+
41
+
42
+
43
+ /** The `PlaygroundSite` Durable Object class, as the Worker module exports it. */
44
+
45
+
46
+
47
+
48
+
49
+ /** Builds the Durable Object class for `options` (exported by the Worker module as `PlaygroundSite`). */
50
+ export function playgroundSiteClass(options ) {
51
+ const limits = { ...DEFAULT_PLAYGROUND_LIMITS, ...options.limits };
52
+
53
+ return class PlaygroundSite {
54
+ state ;
55
+ env ;
56
+ #session ;
57
+ #expiresAt = 0;
58
+
59
+ constructor(state , env ) {
60
+ this.state = state;
61
+ this.env = env;
62
+ }
63
+
64
+ async fetch(request ) {
65
+ const url = new URL(request.url);
66
+ if (url.pathname === "/_count") return this.#count();
67
+ const id = request.headers.get(SESSION_HEADER) ?? "";
68
+ const created = sessionTime(id);
69
+ if (created === undefined) return json(400, { error: "no_session" });
70
+ if (url.pathname === RESET_PATH) {
71
+ await this.#wipe();
72
+ return new Response(null, { status: 204 });
73
+ }
74
+ const now = Date.now();
75
+ if (now >= created + limits.maxMinutes * MINUTE) {
76
+ // No resurrection: past the cap, even when the alarm did not run.
77
+ await this.#wipe();
78
+ return json(410, { error: "playground_expired" });
79
+ }
80
+ const session = await this.#open();
81
+ this.#expiresAt = Math.min(
82
+ now + limits.idleMinutes * MINUTE,
83
+ created + limits.maxMinutes * MINUTE,
84
+ );
85
+ await this.state.storage.setAlarm(this.#expiresAt);
86
+ const full = await fullResponse(request, url, session, limits);
87
+ if (full) return full;
88
+ if (url.pathname.startsWith("/api/") || url.pathname === "/mcp")
89
+ return session.api.fetch(request);
90
+ if (url.pathname.startsWith(SITE_PREFIX) || url.pathname.startsWith("/media/"))
91
+ return renderSite(request, url, { session, options, state: this.state, env: this.env });
92
+ return json(404, { error: "not_found" });
93
+ }
94
+
95
+ async alarm() {
96
+ await this.#wipe();
97
+ }
98
+
99
+ /** The daily session counter (an object named `daily:<UTC date>`). */
100
+ async #count() {
101
+ const count = ((await this.state.storage.get ("count")) ?? 0) + 1;
102
+ await this.state.storage.put("count", count);
103
+ if (count === 1) {
104
+ const midnight = new Date();
105
+ midnight.setUTCHours(24, 0, 0, 0);
106
+ await this.state.storage.setAlarm(midnight.getTime() + MINUTE);
107
+ }
108
+ return json(200, { count });
109
+ }
110
+
111
+ async #wipe() {
112
+ this.#session = undefined;
113
+ await this.state.storage.deleteAll();
114
+ await this.state.storage.deleteAlarm();
115
+ }
116
+
117
+ /** The session's store, API and site; migrated and seeded on first use. */
118
+ async #open() {
119
+ if (this.#session) return this.#session;
120
+ await this.state.blockConcurrencyWhile(async () => {
121
+ if (this.#session) return;
122
+ const sql = new DoSqliteDriver(this.state.storage);
123
+ const own = new SqlBlobStore(sql, {
124
+ maxBytes: limits.maxBlobBytes,
125
+ maxObjectBytes: limits.maxObjectBytes,
126
+ });
127
+ const demo = options.demoMedia;
128
+ const blobs = demo
129
+ ? new LayeredBlobStore(
130
+ new FetcherBlobStore(
131
+ this.env.ASSETS,
132
+ demo.prefix,
133
+ demo.keys ? { keys: demo.keys } : {},
134
+ ),
135
+ own,
136
+ )
137
+ : own;
138
+ const store = new SiteGraphStore({ sql, blobs });
139
+ await store.init();
140
+ let siteId = await this.state.storage.get ("siteId");
141
+ if (!siteId) {
142
+ siteId = (await options.seed(store)).siteId;
143
+ await this.state.storage.put("siteId", siteId);
144
+ }
145
+ const api = createApi({
146
+ store,
147
+ defer: (task) => this.state.waitUntil(task.catch(() => {})),
148
+ playground: {
149
+ info: () => ({
150
+ expiresAt: new Date(this.#expiresAt).toISOString(),
151
+ resetUrl: RESET_PATH,
152
+ deployUrl: options.deployUrl,
153
+ }),
154
+ maxBodyBytes: limits.maxBodyBytes,
155
+ },
156
+ });
157
+ this.#session = { store, sql, siteId, api };
158
+ });
159
+ return this.#session ;
160
+ }
161
+ };
162
+ }
163
+
164
+ /** RFC-0036 §7: a full database or too many nodes refuse writes with 507. */
165
+ async function fullResponse(
166
+ request ,
167
+ url ,
168
+ session ,
169
+ limits ,
170
+ ) {
171
+ if (request.method === "GET" || request.method === "HEAD" || !url.pathname.startsWith("/api/"))
172
+ return undefined;
173
+ if (session.sql.databaseSize > limits.maxDatabaseBytes)
174
+ return json(507, {
175
+ error: "playground_full",
176
+ message: "This playground is full. Reset to start over.",
177
+ });
178
+ if (request.method === "POST") {
179
+ const row = await session.sql.get ("SELECT count(*) AS n FROM nodes");
180
+ if ((row?.n ?? 0) >= limits.maxNodes)
181
+ return json(507, {
182
+ error: "playground_full",
183
+ message: "This playground holds no more items.",
184
+ });
185
+ }
186
+ return undefined;
187
+ }
188
+
189
+ /** `/s/<session>/…` (and `/media/…`) through the deployment's renderer, kept private (§4). */
190
+ async function renderSite(
191
+ request ,
192
+ url ,
193
+ scope ,
194
+ ) {
195
+ const { session, options, state } = scope;
196
+ if (!options.render) return json(404, { error: "not_found" });
197
+ const sitePath = url.pathname.startsWith(SITE_PREFIX);
198
+ const prefix = sitePath ? url.pathname.split("/").slice(0, 3).join("/") : "";
199
+ const inner = new URL(url);
200
+ inner.pathname = url.pathname.slice(prefix.length) || "/";
201
+ const ctx = {
202
+ waitUntil: (p ) => state.waitUntil(p),
203
+ passThroughOnException: () => {},
204
+ props: {},
205
+ } ;
206
+ const response = await options.render(new Request(inner, request), {
207
+ store: session.store,
208
+ siteId: session.siteId,
209
+ env: scope.env,
210
+ ctx,
211
+ });
212
+ return privateSiteResponse(
213
+ response,
214
+ prefix || `${SITE_PREFIX}${request.headers.get(SESSION_HEADER)}`,
215
+ );
216
+ }
@@ -0,0 +1,13 @@
1
+ import { type PlaygroundEnv, type PlaygroundOptions } from "./playground-options.js";
2
+ import { type PlaygroundSiteClass } from "./playground-site.js";
3
+ export * from "./playground-options.js";
4
+ export { prefixPath } from "./playground-render.js";
5
+ export { newSessionId, sessionTime, signSession, verifySession } from "./playground-session.js";
6
+ export type { PlaygroundSiteClass } from "./playground-site.js";
7
+ export interface PlaygroundWorker {
8
+ worker: {
9
+ fetch(request: Request, env: PlaygroundEnv): Promise<Response>;
10
+ };
11
+ PlaygroundSite: PlaygroundSiteClass;
12
+ }
13
+ export declare function createPlaygroundWorker(options: PlaygroundOptions): PlaygroundWorker;
@@ -0,0 +1,187 @@
1
+ /**
2
+ * `@cloudhal/cloudflare/playground` (RFC-0036): the single Worker of a public playground. Every
3
+ * visitor gets a disposable Cloudhal in their own `PlaygroundSite` Durable Object; this Worker only
4
+ * serves static files (landing page, Studio, site assets), issues and checks the session cookie,
5
+ * applies `isBlockedInPlayground`, the rate limits, the daily cap and the kill switch, and forwards.
6
+ *
7
+ * ```ts
8
+ * const playground = createPlaygroundWorker({ seed, render, deployUrl });
9
+ * export const PlaygroundSite = playground.PlaygroundSite;
10
+ * export default playground.worker;
11
+ * ```
12
+ */
13
+ import { isBlockedInPlayground } from "@cloudhal/api";
14
+ import {
15
+ DEFAULT_PLAYGROUND_LIMITS,
16
+
17
+
18
+
19
+ RESET_PATH,
20
+ SESSION_HEADER,
21
+ SESSION_PATH,
22
+ SITE_PREFIX,
23
+ } from "./playground-options.js";
24
+ import {
25
+ newSessionId,
26
+ readSessionCookie,
27
+ sessionCookie,
28
+ sessionTime,
29
+ signSession,
30
+ verifySession,
31
+ } from "./playground-session.js";
32
+ import { playgroundSiteClass } from "./playground-site.js";
33
+
34
+ export * from "./playground-options.js";
35
+ export { prefixPath } from "./playground-render.js";
36
+ export { newSessionId, sessionTime, signSession, verifySession } from "./playground-session.js";
37
+
38
+
39
+ const MINUTE = 60_000;
40
+ const json = (status , body , headers = {}) =>
41
+ new Response(JSON.stringify(body), {
42
+ status,
43
+ headers: { "content-type": "application/json", "cache-control": "no-store", ...headers },
44
+ });
45
+
46
+ /** Paths that belong to a session's Durable Object. */
47
+ function isSessionPath(path ) {
48
+ return (
49
+ path.startsWith("/api/") ||
50
+ path === "/mcp" ||
51
+ path.startsWith("/mcp/") ||
52
+ path.startsWith(SITE_PREFIX) ||
53
+ path.startsWith("/media/") ||
54
+ path === RESET_PATH
55
+ );
56
+ }
57
+
58
+
59
+
60
+
61
+
62
+
63
+ export function createPlaygroundWorker(options ) {
64
+ const limits = { ...DEFAULT_PLAYGROUND_LIMITS, ...options.limits };
65
+ const landingPath = options.landingPath ?? "/landing/";
66
+
67
+ const landing = (request , env , status = 200) =>
68
+ env.ASSETS.fetch(
69
+ new Request(new URL(landingPath, request.url), { headers: request.headers }),
70
+ ).then((res) =>
71
+ status === 200 ? res : new Response(res.body, { status, headers: res.headers }),
72
+ );
73
+
74
+ /** The verified, unexpired session of a request. */
75
+ async function sessionOf(request , env ) {
76
+ const value = readSessionCookie(request);
77
+ if (!value || !env.PLAYGROUND_SECRET) return undefined;
78
+ const id = await verifySession(value, env.PLAYGROUND_SECRET);
79
+ const created = id ? sessionTime(id) : undefined;
80
+ if (!id || created === undefined) return undefined;
81
+ const now = Date.now();
82
+ if (created > now + MINUTE || now >= created + limits.maxMinutes * MINUTE) return undefined;
83
+ return id;
84
+ }
85
+
86
+ async function createSession(request , env ) {
87
+ const secret = env.PLAYGROUND_SECRET;
88
+ if (!secret || secret.length < 32) return landing(request, env, 503);
89
+ const ip = request.headers.get("cf-connecting-ip") ?? "unknown";
90
+ if (env.SESSION_LIMIT && !(await env.SESSION_LIMIT.limit({ key: ip })).success) {
91
+ if (!(await passedTurnstile(request, env, ip)))
92
+ return json(429, {
93
+ error: "rate_limited",
94
+ message: "Too many new sessions. Try again in a minute.",
95
+ ...(env.TURNSTILE_SITE_KEY ? { turnstile: env.TURNSTILE_SITE_KEY } : {}),
96
+ });
97
+ }
98
+ const cap = Number(env.PLAYGROUND_DAILY_SESSIONS ?? 0);
99
+ if (cap > 0) {
100
+ const day = new Date().toISOString().slice(0, 10);
101
+ const counter = env.PLAYGROUND.get(env.PLAYGROUND.idFromName(`daily:${day}`));
102
+ const { count } = (await (await counter.fetch("https://playground/_count")).json())
103
+
104
+ ;
105
+ if (count > cap) return landing(request, env, 503);
106
+ }
107
+ const id = newSessionId(Date.now());
108
+ const cookie = sessionCookie(await signSession(id, secret), limits.maxMinutes * 60);
109
+ return new Response(null, {
110
+ status: 303,
111
+ headers: { location: "/sites", "set-cookie": cookie },
112
+ });
113
+ }
114
+
115
+ async function forward(request , env , id , path ) {
116
+ if (path.startsWith(SITE_PREFIX) && path.split("/")[2] !== id)
117
+ return json(404, { error: "not_found" });
118
+ const block = isBlockedInPlayground(request.method, path);
119
+ if (block)
120
+ return json(403, {
121
+ error: "playground",
122
+ block,
123
+ message: "This is not available in the playground. It works in your own install.",
124
+ });
125
+ const length = Number(request.headers.get("content-length") ?? 0);
126
+ if (length > limits.maxRequestBytes) return json(413, { error: "payload_too_large" });
127
+ const write = request.method !== "GET" && request.method !== "HEAD";
128
+ if (write && env.WRITE_LIMIT && !(await env.WRITE_LIMIT.limit({ key: id })).success)
129
+ return json(429, { error: "rate_limited", message: "Slow down a little." });
130
+ const headers = new Headers(request.headers);
131
+ headers.set(SESSION_HEADER, id);
132
+ const stub = env.PLAYGROUND.get(env.PLAYGROUND.idFromName(id));
133
+ return stub.fetch(new Request(request, { headers }));
134
+ }
135
+
136
+ const worker = {
137
+ async fetch(request , env ) {
138
+ const url = new URL(request.url);
139
+ const path = url.pathname;
140
+ // Never trust a client's own session header.
141
+ if (request.headers.has(SESSION_HEADER)) {
142
+ const headers = new Headers(request.headers);
143
+ headers.delete(SESSION_HEADER);
144
+ request = new Request(request, { headers });
145
+ }
146
+ const enabled = env.PLAYGROUND_ENABLED !== "false" && Boolean(env.PLAYGROUND_SECRET);
147
+ if (path === SESSION_PATH && request.method === "POST")
148
+ return enabled ? createSession(request, env) : landing(request, env, 503);
149
+ if (isSessionPath(path)) {
150
+ if (!enabled) return json(503, { error: "playground_closed" });
151
+ const id = await sessionOf(request, env);
152
+ if (!id)
153
+ return path.startsWith("/api/") || path === "/mcp" || path === RESET_PATH
154
+ ? json(410, { error: "playground_expired", message: "This session has ended." })
155
+ : Response.redirect(new URL("/", url).href, 303);
156
+ if (path === RESET_PATH && request.method !== "POST") return json(405, { error: "method" });
157
+ return forward(request, env, id, path);
158
+ }
159
+ // Static files. "/" is the landing page unless the visitor has a session (then Studio).
160
+ if (path === "/" && (!enabled || !(await sessionOf(request, env))))
161
+ return landing(request, env);
162
+ return env.ASSETS.fetch(request);
163
+ },
164
+ };
165
+
166
+ return { worker, PlaygroundSite: playgroundSiteClass(options) };
167
+ }
168
+
169
+ /** After a rate-limit hit, a valid Turnstile token (form field or header) lets one session through. */
170
+ async function passedTurnstile(request , env , ip ) {
171
+ if (!env.TURNSTILE_SECRET) return false;
172
+ let token = request.headers.get("cf-turnstile-response");
173
+ if (!token && request.headers.get("content-type")?.includes("form")) {
174
+ const form = await request.clone().formData();
175
+ token = String(form.get("cf-turnstile-response") ?? "");
176
+ }
177
+ if (!token) return false;
178
+ const body = new FormData();
179
+ body.set("secret", env.TURNSTILE_SECRET);
180
+ body.set("response", token);
181
+ body.set("remoteip", ip);
182
+ const res = await fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify", {
183
+ method: "POST",
184
+ body,
185
+ });
186
+ return ((await res.json()) ).success === true;
187
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudhal/cloudflare",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "description": "Cloudhal on Cloudflare: the admin Worker (API, auth, MCP, Studio) over D1 + R2",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://cloudhal.dev",
@@ -37,6 +37,10 @@
37
37
  "./scheduler": {
38
38
  "types": "./dist/src/scheduler.d.ts",
39
39
  "default": "./dist/src/scheduler.js"
40
+ },
41
+ "./playground": {
42
+ "types": "./dist/src/playground.d.ts",
43
+ "default": "./dist/src/playground.js"
40
44
  }
41
45
  },
42
46
  "files": [
@@ -44,18 +48,19 @@
44
48
  "README.md"
45
49
  ],
46
50
  "dependencies": {
47
- "@cloudhal/agent-runtime": "0.2.0",
48
- "@cloudhal/analytics": "0.2.0",
49
- "@cloudhal/api": "0.2.0",
50
- "@cloudhal/comments": "0.2.0",
51
- "@cloudhal/core-ts": "0.2.0",
52
- "@cloudhal/mcp-server": "0.2.0",
53
- "@cloudhal/schedules": "0.2.0",
54
- "@cloudhal/storage": "0.2.0",
51
+ "@cloudhal/agent-runtime": "0.3.1",
52
+ "@cloudhal/analytics": "0.3.1",
53
+ "@cloudhal/api": "0.3.1",
54
+ "@cloudhal/comments": "0.3.1",
55
+ "@cloudhal/core-ts": "0.3.1",
56
+ "@cloudhal/mcp-server": "0.3.1",
57
+ "@cloudhal/schedules": "0.3.1",
58
+ "@cloudhal/storage": "0.3.1",
55
59
  "zod": "^4.6.5"
56
60
  },
57
61
  "devDependencies": {
58
62
  "@cloudflare/workers-types": "^5.20261007.1",
63
+ "@cloudhal/astro-renderer": "0.3.1",
59
64
  "@types/node": "^26.6.5",
60
65
  "typescript": "7.0.2",
61
66
  "vitest": "5.0.3",