@cloudhal/cloudflare 0.10.1 → 0.12.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/README.md +2 -0
- package/dist/src/admin-worker.d.ts +16 -2
- package/dist/src/admin-worker.js +43 -25
- package/dist/src/agent-uploads.d.ts +15 -0
- package/dist/src/agent-uploads.js +28 -0
- package/dist/src/browser-cdp.d.ts +35 -0
- package/dist/src/browser-cdp.js +98 -0
- package/dist/src/features.d.ts +9 -8
- package/dist/src/features.js +25 -19
- package/dist/src/metrics.d.ts +67 -0
- package/dist/src/metrics.js +301 -0
- package/dist/src/playground-session.d.ts +8 -0
- package/dist/src/playground-session.js +14 -0
- package/dist/src/playground-site.js +18 -3
- package/dist/src/playground.js +23 -2
- package/package.json +13 -13
package/README.md
CHANGED
|
@@ -18,6 +18,8 @@ export default createAdminWorker({ skills });
|
|
|
18
18
|
| `BETTER_AUTH_SECRET`, `MCP_STATE_KEY` | sessions; signed approval state |
|
|
19
19
|
| `CLOUDHAL_PREVIEW_SECRET`, `CLOUDHAL_PURGE_TOKEN` | shared with the site Worker |
|
|
20
20
|
| `CLOUDHAL_DEPLOY_TOKEN` | `cloudhal push` / `pull` |
|
|
21
|
+
| `CLOUDHAL_UPLOAD_SECRET` | signs upload tickets and agents' upload links (RFC-0048; the preview secret without it) |
|
|
22
|
+
| `CLOUDHAL_AGENT_UPLOADS`, `CLOUDHAL_AGENT_UPLOAD_BYTES` | `off` turns agents' upload links off; their cap per file in bytes |
|
|
21
23
|
| `CLOUDHAL_SIGNUP` | `first-user` (default — only the first account, the owner, can sign up), `closed` or `open` |
|
|
22
24
|
|
|
23
25
|
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).
|
|
@@ -32,7 +32,9 @@
|
|
|
32
32
|
* without a secret; each site's owner turns it on, picks the model and sets the daily cap in Studio.
|
|
33
33
|
*
|
|
34
34
|
* Secrets: BETTER_AUTH_SECRET, MCP_STATE_KEY, CLOUDHAL_PREVIEW_SECRET, CLOUDHAL_PURGE_TOKEN,
|
|
35
|
-
* CLOUDHAL_DEPLOY_TOKEN, CLOUDHAL_COMMENTS_KEY (all ≥ 32 chars; `cloudhal deploy` generates them)
|
|
35
|
+
* CLOUDHAL_DEPLOY_TOKEN, CLOUDHAL_COMMENTS_KEY (all ≥ 32 chars; `cloudhal deploy` generates them),
|
|
36
|
+
* and the optional CLOUDHAL_UPLOAD_SECRET (RFC-0048 §2.2: signs upload tickets and agents' upload
|
|
37
|
+
* links ahead of the preview secret, so it rotates on its own).
|
|
36
38
|
*/
|
|
37
39
|
import { type SkillSource } from "@cloudhal/agent-runtime";
|
|
38
40
|
import { type AnalyticsDefaults } from "@cloudhal/analytics";
|
|
@@ -41,7 +43,8 @@ import { type AiBinding } from "@cloudhal/api";
|
|
|
41
43
|
import { type AiSearchEnv } from "@cloudhal/core-ts";
|
|
42
44
|
import { type BlockType, type PropsSchema } from "@cloudhal/core-ts/blocks";
|
|
43
45
|
import { type SqlDriver } from "@cloudhal/storage";
|
|
44
|
-
import { type
|
|
46
|
+
import { type DevtoolsBinding } from "./browser-cdp.js";
|
|
47
|
+
import type { BrowserBinding } from "./browser-render.js";
|
|
45
48
|
import { type BuildRoomsEnv } from "./build-rooms.js";
|
|
46
49
|
import { type CommentsEnv } from "./comments.js";
|
|
47
50
|
import { type MailEnv } from "./mail.js";
|
|
@@ -58,6 +61,11 @@ export interface AdminEnv extends CommentsEnv, SchedulerEnv, MailEnv, BuildRooms
|
|
|
58
61
|
BETTER_AUTH_SECRET: string;
|
|
59
62
|
MCP_STATE_KEY: string;
|
|
60
63
|
CLOUDHAL_PREVIEW_SECRET?: string;
|
|
64
|
+
/** RFC-0048 §2.2: the upload signing key (≥ 32 chars); the preview secret otherwise. */
|
|
65
|
+
CLOUDHAL_UPLOAD_SECRET?: string;
|
|
66
|
+
/** RFC-0048: `off` turns agents' upload links off; a cap per file in bytes. */
|
|
67
|
+
CLOUDHAL_AGENT_UPLOADS?: string;
|
|
68
|
+
CLOUDHAL_AGENT_UPLOAD_BYTES?: string;
|
|
61
69
|
CLOUDHAL_PURGE_TOKEN?: string;
|
|
62
70
|
CLOUDHAL_DEPLOY_TOKEN?: string;
|
|
63
71
|
/** One-time token the first account must present (see `cloudhal deploy` output). */
|
|
@@ -74,6 +82,12 @@ export interface AdminEnv extends CommentsEnv, SchedulerEnv, MailEnv, BuildRooms
|
|
|
74
82
|
CLOUDHAL_ANALYTICS_DEFAULTS?: string;
|
|
75
83
|
/** Cloudflare Browser Rendering for `render_page` (RFC-0021 §4); absent: `render_unavailable`. */
|
|
76
84
|
BROWSER?: BrowserBinding;
|
|
85
|
+
/** A Chrome over its DevTools port (the self-host sidecar, RFC-0047 §6), when there is no `BROWSER`. */
|
|
86
|
+
BROWSER_CDP?: DevtoolsBinding;
|
|
87
|
+
/** Where that Chrome reaches the site: `render_page` opens the signed preview link there. */
|
|
88
|
+
CLOUDHAL_RENDER_ORIGIN?: string;
|
|
89
|
+
/** Turns `GET /api/metrics` on for whoever holds it (self-host, #293); absent: 404. */
|
|
90
|
+
CLOUDHAL_METRICS_TOKEN?: string;
|
|
77
91
|
/** `off` keeps `render_page` unavailable even with a `BROWSER` binding. */
|
|
78
92
|
CLOUDHAL_RENDER?: string;
|
|
79
93
|
/** `off` turns the OAuth authorization server for remote MCP clients off (RFC-0044 §10). */
|
package/dist/src/admin-worker.js
CHANGED
|
@@ -32,7 +32,9 @@
|
|
|
32
32
|
* without a secret; each site's owner turns it on, picks the model and sets the daily cap in Studio.
|
|
33
33
|
*
|
|
34
34
|
* Secrets: BETTER_AUTH_SECRET, MCP_STATE_KEY, CLOUDHAL_PREVIEW_SECRET, CLOUDHAL_PURGE_TOKEN,
|
|
35
|
-
* CLOUDHAL_DEPLOY_TOKEN, CLOUDHAL_COMMENTS_KEY (all ≥ 32 chars; `cloudhal deploy` generates them)
|
|
35
|
+
* CLOUDHAL_DEPLOY_TOKEN, CLOUDHAL_COMMENTS_KEY (all ≥ 32 chars; `cloudhal deploy` generates them),
|
|
36
|
+
* and the optional CLOUDHAL_UPLOAD_SECRET (RFC-0048 §2.2: signs upload tickets and agents' upload
|
|
37
|
+
* links ahead of the preview secret, so it rotates on its own).
|
|
36
38
|
*/
|
|
37
39
|
|
|
38
40
|
import {
|
|
@@ -61,13 +63,16 @@ import { createBlockRegistry, } from "@cloudhal
|
|
|
61
63
|
import { workersTransport } from "@cloudhal/core-ts/media";
|
|
62
64
|
import { SqlScheduleStore } from "@cloudhal/schedules/sql";
|
|
63
65
|
import { migrate, migrations, } from "@cloudhal/storage";
|
|
64
|
-
|
|
66
|
+
|
|
65
67
|
import { R2BlobStore } from "@cloudhal/storage/r2";
|
|
66
|
-
import {
|
|
68
|
+
import { agentUploadMedia } from "./agent-uploads.js";
|
|
69
|
+
import { adminRender, } from "./browser-cdp.js";
|
|
70
|
+
|
|
67
71
|
import { buildRoomClass, createDurableBuildHub } from "./build-rooms.js";
|
|
68
72
|
import { adminComments, commentsOn, flushCommentPurges } from "./comments.js";
|
|
69
73
|
import { featureRoute, siteSupport } from "./features.js";
|
|
70
74
|
import { adminMail, } from "./mail.js";
|
|
75
|
+
import { adminSql, instrumentAdmin, watchedBucket } from "./metrics.js";
|
|
71
76
|
import { purgeSiteCache } from "./purge.js";
|
|
72
77
|
import {
|
|
73
78
|
|
|
@@ -94,6 +99,11 @@ import { routedSite } from "./site-routes.js";
|
|
|
94
99
|
|
|
95
100
|
|
|
96
101
|
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
|
|
97
107
|
|
|
98
108
|
|
|
99
109
|
|
|
@@ -110,6 +120,12 @@ import { routedSite } from "./site-routes.js";
|
|
|
110
120
|
|
|
111
121
|
|
|
112
122
|
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
|
|
113
129
|
|
|
114
130
|
|
|
115
131
|
|
|
@@ -310,6 +326,17 @@ function withStudioHeaders(res ) {
|
|
|
310
326
|
|
|
311
327
|
const WORKER_PATHS = /^\/(api\/|mcp(\/|$)|\.well-known\/)/;
|
|
312
328
|
|
|
329
|
+
/**
|
|
330
|
+
* RFC-0048's upload secret, and the secret #383's signed preview media URLs derive their key from:
|
|
331
|
+
* the preview secret when there is one, else the auth secret (every deployment has it).
|
|
332
|
+
*/
|
|
333
|
+
function signingSecrets(env ) {
|
|
334
|
+
return {
|
|
335
|
+
uploadSecret: env.CLOUDHAL_UPLOAD_SECRET,
|
|
336
|
+
previewMedia: { secret: env.CLOUDHAL_PREVIEW_SECRET || env.BETTER_AUTH_SECRET },
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
|
|
313
340
|
function required(env , key ) {
|
|
314
341
|
const value = env[key];
|
|
315
342
|
if (typeof value !== "string" || value.length < 32)
|
|
@@ -347,16 +374,12 @@ export function createAdminWorker(options = {}) {
|
|
|
347
374
|
const confirmed = { gates: {}, fields: {} };
|
|
348
375
|
const ensureMigrated = async (sql ) => {
|
|
349
376
|
if (migrated) return;
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
} catch {
|
|
353
|
-
// A concurrent request or isolate applied them first; a second pass sees them as done.
|
|
354
|
-
await migrate(sql, migrations);
|
|
355
|
-
}
|
|
377
|
+
// Safe against concurrent requests, isolates and instances: `migrate` skips what a peer applied.
|
|
378
|
+
await migrate(sql, migrations);
|
|
356
379
|
migrated = true;
|
|
357
380
|
};
|
|
358
381
|
|
|
359
|
-
return {
|
|
382
|
+
return instrumentAdmin({
|
|
360
383
|
async fetch(request , env , ctx ) {
|
|
361
384
|
const url = new URL(request.url);
|
|
362
385
|
// The assets layer answers existing files before the Worker runs, so a request for a file
|
|
@@ -376,8 +399,8 @@ export function createAdminWorker(options = {}) {
|
|
|
376
399
|
);
|
|
377
400
|
}
|
|
378
401
|
|
|
379
|
-
const sql =
|
|
380
|
-
const blobs = new R2BlobStore(env.BLOBS);
|
|
402
|
+
const sql = adminSql(env);
|
|
403
|
+
const blobs = new R2BlobStore(watchedBucket(env.BLOBS));
|
|
381
404
|
await ensureMigrated(sql);
|
|
382
405
|
|
|
383
406
|
// A takedown (RFC-0004 §4.6) purges the asset's media URLs at once, not at the next publish.
|
|
@@ -507,15 +530,14 @@ export function createAdminWorker(options = {}) {
|
|
|
507
530
|
oauth: auth.oauth && { issuer: auth.oauth.issuer, resource: auth.oauth.resource },
|
|
508
531
|
// fetch_asset_url never reaches this Worker's own host (Studio, API, purge); each site's
|
|
509
532
|
// domains are refused too. Workers cannot pin DNS: see `workersTransport` (RFC-0004 §5.7).
|
|
510
|
-
media: { blockedHosts: [url.hostname] },
|
|
511
|
-
// RFC-0021 §4: render_page opens the preview link in Browser Rendering.
|
|
512
|
-
...(env
|
|
513
|
-
? { render: { renderer: browserRenderingRenderer(env.BROWSER) } }
|
|
514
|
-
: {}),
|
|
533
|
+
media: { blockedHosts: [url.hostname], ...agentUploadMedia(env) },
|
|
534
|
+
// RFC-0021 §4: render_page opens the preview link in Browser Rendering or a sidecar.
|
|
535
|
+
...adminRender(env),
|
|
515
536
|
},
|
|
516
537
|
...(env.CLOUDHAL_PREVIEW_SECRET
|
|
517
538
|
? { preview: { secret: env.CLOUDHAL_PREVIEW_SECRET } }
|
|
518
539
|
: {}),
|
|
540
|
+
...signingSecrets(env),
|
|
519
541
|
...(env.CLOUDHAL_DEPLOY_TOKEN
|
|
520
542
|
? { admin: { deployToken: env.CLOUDHAL_DEPLOY_TOKEN, storage: { sql, blobs } } }
|
|
521
543
|
: {}),
|
|
@@ -559,7 +581,7 @@ export function createAdminWorker(options = {}) {
|
|
|
559
581
|
env ,
|
|
560
582
|
ctx ,
|
|
561
583
|
) {
|
|
562
|
-
const sql =
|
|
584
|
+
const sql = adminSql(env);
|
|
563
585
|
await ensureMigrated(sql);
|
|
564
586
|
const tick = (now ) =>
|
|
565
587
|
runAdminTick(env, {
|
|
@@ -583,7 +605,7 @@ export function createAdminWorker(options = {}) {
|
|
|
583
605
|
log(`schedules tick (cron) failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
584
606
|
}
|
|
585
607
|
},
|
|
586
|
-
};
|
|
608
|
+
});
|
|
587
609
|
}
|
|
588
610
|
|
|
589
611
|
/**
|
|
@@ -603,13 +625,9 @@ let clockMigrated = false;
|
|
|
603
625
|
*/
|
|
604
626
|
export const SchedulerClock = schedulerClockClass(async (env, o) => {
|
|
605
627
|
const e = env ;
|
|
606
|
-
const sql =
|
|
628
|
+
const sql = adminSql(e);
|
|
607
629
|
if (!clockMigrated) {
|
|
608
|
-
|
|
609
|
-
await migrate(sql, migrations);
|
|
610
|
-
} catch {
|
|
611
|
-
await migrate(sql, migrations);
|
|
612
|
-
}
|
|
630
|
+
await migrate(sql, migrations);
|
|
613
631
|
clockMigrated = true;
|
|
614
632
|
}
|
|
615
633
|
const log = (line ) => console.log(line);
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* RFC-0048: the admin Worker's settings for agents' upload links, from its vars (written by
|
|
3
|
+
* `cloudhal deploy` from `cloudhal.json` `media`, or set by a self-host operator):
|
|
4
|
+
* `CLOUDHAL_AGENT_UPLOADS=off` turns them off, `CLOUDHAL_AGENT_UPLOAD_BYTES` caps a file (1 byte to
|
|
5
|
+
* 100 MB; default 25 MB). Anything else is ignored.
|
|
6
|
+
*/
|
|
7
|
+
export interface AgentUploadsEnv {
|
|
8
|
+
CLOUDHAL_AGENT_UPLOADS?: string;
|
|
9
|
+
CLOUDHAL_AGENT_UPLOAD_BYTES?: string;
|
|
10
|
+
}
|
|
11
|
+
/** The MCP media options they set (`MediaToolOptions.agentUploads`, `agentUploadBytes`). */
|
|
12
|
+
export declare function agentUploadMedia(env: AgentUploadsEnv): {
|
|
13
|
+
agentUploads?: false;
|
|
14
|
+
agentUploadBytes?: number;
|
|
15
|
+
};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* RFC-0048: the admin Worker's settings for agents' upload links, from its vars (written by
|
|
3
|
+
* `cloudhal deploy` from `cloudhal.json` `media`, or set by a self-host operator):
|
|
4
|
+
* `CLOUDHAL_AGENT_UPLOADS=off` turns them off, `CLOUDHAL_AGENT_UPLOAD_BYTES` caps a file (1 byte to
|
|
5
|
+
* 100 MB; default 25 MB). Anything else is ignored.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
const MAX_BYTES = 100 * 1024 * 1024;
|
|
13
|
+
|
|
14
|
+
/** The MCP media options they set (`MediaToolOptions.agentUploads`, `agentUploadBytes`). */
|
|
15
|
+
export function agentUploadMedia(env )
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
{
|
|
19
|
+
const bytes = Number(env.CLOUDHAL_AGENT_UPLOAD_BYTES);
|
|
20
|
+
return {
|
|
21
|
+
...(env.CLOUDHAL_AGENT_UPLOADS?.trim().toLowerCase() === "off"
|
|
22
|
+
? { agentUploads: false }
|
|
23
|
+
: {}),
|
|
24
|
+
...(Number.isInteger(bytes) && bytes >= 1 && bytes <= MAX_BYTES
|
|
25
|
+
? { agentUploadBytes: bytes }
|
|
26
|
+
: {}),
|
|
27
|
+
};
|
|
28
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `render_page` with a Chrome of one's own (RFC-0047 §6, #292): the self-host image's Chrome
|
|
3
|
+
* sidecar, reached through the admin Worker's `BROWSER_CDP` service binding (an `ExternalServer`
|
|
4
|
+
* to its DevTools port). Each session opens one DevTools socket to the running browser and one
|
|
5
|
+
* browser context in it (`cdpSession`), and closes both; the browser itself is shared and never
|
|
6
|
+
* closed. Chrome answers its DevTools HTTP only for `Host: localhost` or an address, so every
|
|
7
|
+
* request names `localhost`; the binding delivers it to the sidecar whatever the URL says.
|
|
8
|
+
*/
|
|
9
|
+
import { type CdpSocket, type PageRenderer } from "@cloudhal/mcp-server/render";
|
|
10
|
+
import type { RenderDeps } from "@cloudhal/mcp-server/tools";
|
|
11
|
+
import { type BrowserBinding } from "./browser-render.js";
|
|
12
|
+
/** A service binding to the browser's DevTools HTTP port. */
|
|
13
|
+
export interface DevtoolsBinding {
|
|
14
|
+
fetch(input: string, init?: RequestInit): Promise<Response>;
|
|
15
|
+
}
|
|
16
|
+
/** The path of the browser's own DevTools socket, from `/json/version`. */
|
|
17
|
+
export declare function browserSocketPath(version: unknown): string;
|
|
18
|
+
/** A Workers WebSocket as a `CdpSocket` (DevTools sends text frames). */
|
|
19
|
+
export declare function devtoolsSocket(ws: WebSocket): CdpSocket;
|
|
20
|
+
export declare function devtoolsRenderer(binding: DevtoolsBinding): PageRenderer;
|
|
21
|
+
/** The bindings `render_page` can use (RFC-0021 §4; RFC-0047 §6). */
|
|
22
|
+
export interface RenderEnv {
|
|
23
|
+
/** Cloudflare Browser Rendering. */
|
|
24
|
+
BROWSER?: BrowserBinding;
|
|
25
|
+
/** A Chrome of one's own over its DevTools port (the self-host sidecar). */
|
|
26
|
+
BROWSER_CDP?: DevtoolsBinding;
|
|
27
|
+
/** Where that Chrome reaches the site (`http://cloudhal:8788`). */
|
|
28
|
+
CLOUDHAL_RENDER_ORIGIN?: string;
|
|
29
|
+
/** `off` keeps `render_page` unavailable whatever the bindings. */
|
|
30
|
+
CLOUDHAL_RENDER?: string;
|
|
31
|
+
}
|
|
32
|
+
/** `render_page`'s deps for the admin Worker: Browser Rendering first, else the sidecar. */
|
|
33
|
+
export declare function adminRender(env: RenderEnv): {
|
|
34
|
+
render?: RenderDeps;
|
|
35
|
+
};
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `render_page` with a Chrome of one's own (RFC-0047 §6, #292): the self-host image's Chrome
|
|
3
|
+
* sidecar, reached through the admin Worker's `BROWSER_CDP` service binding (an `ExternalServer`
|
|
4
|
+
* to its DevTools port). Each session opens one DevTools socket to the running browser and one
|
|
5
|
+
* browser context in it (`cdpSession`), and closes both; the browser itself is shared and never
|
|
6
|
+
* closed. Chrome answers its DevTools HTTP only for `Host: localhost` or an address, so every
|
|
7
|
+
* request names `localhost`; the binding delivers it to the sidecar whatever the URL says.
|
|
8
|
+
*/
|
|
9
|
+
import {
|
|
10
|
+
|
|
11
|
+
cdpSession,
|
|
12
|
+
|
|
13
|
+
RenderError,
|
|
14
|
+
} from "@cloudhal/mcp-server/render";
|
|
15
|
+
|
|
16
|
+
import { browserRenderingRenderer } from "./browser-render.js";
|
|
17
|
+
|
|
18
|
+
/** A service binding to the browser's DevTools HTTP port. */
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
const HOST = "http://localhost";
|
|
24
|
+
|
|
25
|
+
/** The path of the browser's own DevTools socket, from `/json/version`. */
|
|
26
|
+
export function browserSocketPath(version ) {
|
|
27
|
+
const url = (version )?.webSocketDebuggerUrl;
|
|
28
|
+
if (typeof url !== "string") throw new RenderError("the browser named no DevTools socket");
|
|
29
|
+
const path = new URL(url).pathname;
|
|
30
|
+
if (!path.startsWith("/devtools/browser/"))
|
|
31
|
+
throw new RenderError("the browser's DevTools socket is not a browser target");
|
|
32
|
+
return path;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** A Workers WebSocket as a `CdpSocket` (DevTools sends text frames). */
|
|
36
|
+
export function devtoolsSocket(ws ) {
|
|
37
|
+
return {
|
|
38
|
+
send: (m) => ws.send(m),
|
|
39
|
+
onMessage: (l) =>
|
|
40
|
+
ws.addEventListener("message", (e) => {
|
|
41
|
+
if (typeof e.data === "string") l(e.data);
|
|
42
|
+
}),
|
|
43
|
+
onClose: (l) => ws.addEventListener("close", () => l()),
|
|
44
|
+
close: () => {
|
|
45
|
+
try {
|
|
46
|
+
ws.close();
|
|
47
|
+
} catch {
|
|
48
|
+
// already closed
|
|
49
|
+
}
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function devtoolsRenderer(binding ) {
|
|
55
|
+
return {
|
|
56
|
+
async session() {
|
|
57
|
+
const version = await binding
|
|
58
|
+
.fetch(`${HOST}/json/version`, { signal: AbortSignal.timeout(10_000) })
|
|
59
|
+
.catch((e ) => {
|
|
60
|
+
throw new RenderError(`could not reach the browser: ${e.message}`);
|
|
61
|
+
});
|
|
62
|
+
if (version.status !== 200)
|
|
63
|
+
throw new RenderError(`the browser answered ${version.status} for /json/version`);
|
|
64
|
+
const path = browserSocketPath(await version.json());
|
|
65
|
+
const upgraded = await binding.fetch(`${HOST}${path}`, { headers: { Upgrade: "websocket" } });
|
|
66
|
+
const ws = (upgraded ).webSocket;
|
|
67
|
+
if (!ws) throw new RenderError(`the browser did not open a socket (${upgraded.status})`);
|
|
68
|
+
(ws ).accept();
|
|
69
|
+
return cdpSession(devtoolsSocket(ws));
|
|
70
|
+
},
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** The bindings `render_page` can use (RFC-0021 §4; RFC-0047 §6). */
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
/** `render_page`'s deps for the admin Worker: Browser Rendering first, else the sidecar. */
|
|
87
|
+
export function adminRender(env ) {
|
|
88
|
+
if (env.CLOUDHAL_RENDER === "off") return {};
|
|
89
|
+
if (env.BROWSER) return { render: { renderer: browserRenderingRenderer(env.BROWSER) } };
|
|
90
|
+
if (env.BROWSER_CDP)
|
|
91
|
+
return {
|
|
92
|
+
render: {
|
|
93
|
+
renderer: devtoolsRenderer(env.BROWSER_CDP),
|
|
94
|
+
...(env.CLOUDHAL_RENDER_ORIGIN ? { origin: env.CLOUDHAL_RENDER_ORIGIN } : {}),
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
return {};
|
|
98
|
+
}
|
package/dist/src/features.d.ts
CHANGED
|
@@ -30,16 +30,17 @@ export declare function siteGateSupport(options: {
|
|
|
30
30
|
}): GateSupport;
|
|
31
31
|
/**
|
|
32
32
|
* RFC-0045 §1: the store's reference and repeater capability for one admin Worker isolate, the
|
|
33
|
-
* twin of `siteGateSupport`: yes
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
33
|
+
* twin of `siteGateSupport`: yes for `version` (default `REFERENCE_TYPES_VERSION`, the two types;
|
|
34
|
+
* `REFERENCE_LISTINGS_VERSION` for listings and structured data by reference, rollout step 8) once
|
|
35
|
+
* the site Worker answers `{ "fields": n }` with n at least that. The highest answer is kept as a
|
|
36
|
+
* plain value; a refusal or an error is asked again, so deploying the site Worker is enough.
|
|
37
37
|
*/
|
|
38
38
|
export declare function siteFieldTypeSupport(options: {
|
|
39
39
|
readonly fetch: SiteFetch | undefined;
|
|
40
40
|
readonly token: string | undefined;
|
|
41
|
-
|
|
42
|
-
readonly
|
|
41
|
+
/** The `fields` version confirmed so far (0: none). */
|
|
42
|
+
readonly confirmed: () => number;
|
|
43
|
+
readonly remember: (version: number) => void;
|
|
43
44
|
readonly log?: (line: string) => void;
|
|
44
45
|
}): FieldTypeSupport;
|
|
45
46
|
/**
|
|
@@ -50,8 +51,8 @@ export declare function siteFieldTypeSupport(options: {
|
|
|
50
51
|
export interface SiteConfirmations {
|
|
51
52
|
/** The gates version each site Worker reported; absent: none yet. */
|
|
52
53
|
gates: Record<string, number>;
|
|
53
|
-
/** The site
|
|
54
|
-
fields: Record<string,
|
|
54
|
+
/** The `fields` version each site Worker reported, from 2 (RFC-0045); absent: none yet. */
|
|
55
|
+
fields: Record<string, number>;
|
|
55
56
|
}
|
|
56
57
|
/** The site Worker serving one site: its binding's name and a fetch to it. */
|
|
57
58
|
export interface SiteWorkerRoute {
|
package/dist/src/features.js
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* `expiry` until it answers `{ "gates": 2 }` (derived gates, RFC-0042 §3.6).
|
|
7
7
|
*/
|
|
8
8
|
import { AVAILABILITY_GATES_VERSION, } from "@cloudhal/core-ts/availability";
|
|
9
|
-
import {
|
|
9
|
+
import { REFERENCE_TYPES_VERSION } from "@cloudhal/core-ts/fields";
|
|
10
10
|
|
|
11
11
|
import { siteWorkerFor } from "./site-routes.js";
|
|
12
12
|
|
|
@@ -78,29 +78,35 @@ export function siteGateSupport(options
|
|
|
78
78
|
|
|
79
79
|
/**
|
|
80
80
|
* RFC-0045 §1: the store's reference and repeater capability for one admin Worker isolate, the
|
|
81
|
-
* twin of `siteGateSupport`: yes
|
|
82
|
-
*
|
|
83
|
-
*
|
|
84
|
-
*
|
|
81
|
+
* twin of `siteGateSupport`: yes for `version` (default `REFERENCE_TYPES_VERSION`, the two types;
|
|
82
|
+
* `REFERENCE_LISTINGS_VERSION` for listings and structured data by reference, rollout step 8) once
|
|
83
|
+
* the site Worker answers `{ "fields": n }` with n at least that. The highest answer is kept as a
|
|
84
|
+
* plain value; a refusal or an error is asked again, so deploying the site Worker is enough.
|
|
85
85
|
*/
|
|
86
86
|
export function siteFieldTypeSupport(options
|
|
87
87
|
|
|
88
88
|
|
|
89
|
-
|
|
90
|
-
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
|
|
91
92
|
|
|
92
93
|
) {
|
|
93
94
|
return {
|
|
94
|
-
supported: async () => {
|
|
95
|
-
if (options.confirmed()) return true;
|
|
95
|
+
supported: async (_siteId, version = REFERENCE_TYPES_VERSION) => {
|
|
96
|
+
if (options.confirmed() >= version) return true;
|
|
96
97
|
if (!options.fetch || !options.token) return false;
|
|
97
98
|
try {
|
|
98
99
|
const fields = (await siteFeatures(options.fetch, options.token))?.fields ?? 0;
|
|
99
|
-
if (fields
|
|
100
|
-
options.
|
|
100
|
+
if (fields > options.confirmed() && fields >= REFERENCE_TYPES_VERSION)
|
|
101
|
+
options.remember(fields);
|
|
102
|
+
if (fields < version) {
|
|
103
|
+
options.log?.(
|
|
104
|
+
version > REFERENCE_TYPES_VERSION
|
|
105
|
+
? "site Worker does not read listings or structured data by reference yet"
|
|
106
|
+
: "site Worker does not read reference and repeater fields yet",
|
|
107
|
+
);
|
|
101
108
|
return false;
|
|
102
109
|
}
|
|
103
|
-
options.remember();
|
|
104
110
|
return true;
|
|
105
111
|
} catch (e) {
|
|
106
112
|
options.log?.(`features check failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
@@ -118,8 +124,8 @@ export function siteFieldTypeSupport(options
|
|
|
118
124
|
|
|
119
125
|
|
|
120
126
|
|
|
121
|
-
|
|
122
|
-
|
|
127
|
+
|
|
128
|
+
|
|
123
129
|
|
|
124
130
|
|
|
125
131
|
/** The site Worker serving one site: its binding's name and a fetch to it. */
|
|
@@ -159,15 +165,15 @@ export function siteSupport(options
|
|
|
159
165
|
},
|
|
160
166
|
},
|
|
161
167
|
fieldTypes: {
|
|
162
|
-
supported: (siteId) => {
|
|
168
|
+
supported: (siteId, version) => {
|
|
163
169
|
const { r, base } = common(siteId);
|
|
164
170
|
return siteFieldTypeSupport({
|
|
165
171
|
...base,
|
|
166
|
-
confirmed: () => (r ? confirmed.fields[r.key]
|
|
167
|
-
remember: () => {
|
|
168
|
-
if (r) confirmed.fields[r.key] =
|
|
172
|
+
confirmed: () => (r ? (confirmed.fields[r.key] ?? 0) : 0),
|
|
173
|
+
remember: (v) => {
|
|
174
|
+
if (r) confirmed.fields[r.key] = v;
|
|
169
175
|
},
|
|
170
|
-
}).supported(siteId);
|
|
176
|
+
}).supported(siteId, version);
|
|
171
177
|
},
|
|
172
178
|
},
|
|
173
179
|
};
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `GET /api/metrics` (#293; RFC-0047 §7, amended 2026-11-29): one instance's metrics in the
|
|
3
|
+
* Prometheus text format (0.0.4), for a scraper that reaches each instance directly. Off unless
|
|
4
|
+
* `CLOUDHAL_METRICS_TOKEN` is set; then only `Authorization: Bearer <that token>` reads it (any
|
|
5
|
+
* other caller gets 401, and 404 while it is off). The token grants nothing else.
|
|
6
|
+
*
|
|
7
|
+
* - **Counters live in the isolate.** workerd runs one isolate per Worker per instance, so they
|
|
8
|
+
* are that instance's, from `cloudhal_process_start_time_seconds` on; a restart resets them,
|
|
9
|
+
* which Prometheus' `rate()` handles. On Cloudflare, with many isolates, they mean little, and
|
|
10
|
+
* traces and Workers Analytics are the tools there.
|
|
11
|
+
* - **Gauges are read when scraped:** the scheduler's last tick (D1), and the site Worker's own
|
|
12
|
+
* counters through `SITE` (`/__cloudhal/metrics`, Bearer `CLOUDHAL_PURGE_TOKEN`).
|
|
13
|
+
* - **Bounded labels only:** Worker, area of the path, status class, outcome, store. No paths,
|
|
14
|
+
* site ids, users or agents.
|
|
15
|
+
*/
|
|
16
|
+
import { Histogram, RequestMetrics, type RequestMetricsJson } from "@cloudhal/core-ts";
|
|
17
|
+
import { D1Driver } from "@cloudhal/storage/d1";
|
|
18
|
+
export declare const METRICS_PATH = "/api/metrics";
|
|
19
|
+
export declare const SITE_METRICS_URL = "https://site.internal/__cloudhal/metrics";
|
|
20
|
+
/** The site Worker's counters, as `/__cloudhal/metrics` answers them. */
|
|
21
|
+
export type SiteMetrics = RequestMetricsJson;
|
|
22
|
+
/** Which part of Studio's origin a path belongs to: a small, fixed set of labels. */
|
|
23
|
+
export declare function area(pathname: string): string;
|
|
24
|
+
/** This isolate's admin metrics. */
|
|
25
|
+
export declare class AdminMetrics {
|
|
26
|
+
#private;
|
|
27
|
+
readonly requests: RequestMetrics;
|
|
28
|
+
readonly publishes: Histogram;
|
|
29
|
+
readonly startedAt: number;
|
|
30
|
+
storeError(store: "d1" | "r2"): void;
|
|
31
|
+
/** The exposition, with what was read at scrape time. */
|
|
32
|
+
text(read: {
|
|
33
|
+
scheduler?: {
|
|
34
|
+
secondsSinceTick?: number;
|
|
35
|
+
lagSeconds?: number;
|
|
36
|
+
healthy: boolean;
|
|
37
|
+
};
|
|
38
|
+
site?: SiteMetrics;
|
|
39
|
+
}): string;
|
|
40
|
+
}
|
|
41
|
+
/** One per isolate. */
|
|
42
|
+
export declare const ADMIN_METRICS: AdminMetrics;
|
|
43
|
+
/** Equal tokens, compared without an early exit. */
|
|
44
|
+
export declare function sameToken(given: string, expected: string): boolean;
|
|
45
|
+
export interface MetricsEnv {
|
|
46
|
+
CLOUDHAL_METRICS_TOKEN?: string;
|
|
47
|
+
CLOUDHAL_PURGE_TOKEN?: string;
|
|
48
|
+
CLOUDHAL_SCHEDULER?: string;
|
|
49
|
+
DB: D1Database;
|
|
50
|
+
SITE?: {
|
|
51
|
+
fetch(input: string, init?: RequestInit): Promise<Response>;
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
/** The `/api/metrics` answer. */
|
|
55
|
+
export declare function metricsResponse(request: Request, env: MetricsEnv, metrics?: AdminMetrics): Promise<Response>;
|
|
56
|
+
type AnyFetch = (request: Request, env: never, ctx: ExecutionContext) => Promise<Response>;
|
|
57
|
+
/** The admin Worker with `/api/metrics` and its counters around every request. */
|
|
58
|
+
export declare function instrumentAdmin<W extends {
|
|
59
|
+
fetch: AnyFetch;
|
|
60
|
+
}>(worker: W, metrics?: AdminMetrics): W;
|
|
61
|
+
/** An R2 bucket whose failed operations count as store errors. */
|
|
62
|
+
export declare function watchedBucket(bucket: R2Bucket, metrics?: AdminMetrics): R2Bucket;
|
|
63
|
+
/** The admin Worker's database, its failures counted. */
|
|
64
|
+
export declare function adminSql(env: {
|
|
65
|
+
DB: D1Database;
|
|
66
|
+
}, metrics?: AdminMetrics): D1Driver;
|
|
67
|
+
export {};
|
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `GET /api/metrics` (#293; RFC-0047 §7, amended 2026-11-29): one instance's metrics in the
|
|
3
|
+
* Prometheus text format (0.0.4), for a scraper that reaches each instance directly. Off unless
|
|
4
|
+
* `CLOUDHAL_METRICS_TOKEN` is set; then only `Authorization: Bearer <that token>` reads it (any
|
|
5
|
+
* other caller gets 401, and 404 while it is off). The token grants nothing else.
|
|
6
|
+
*
|
|
7
|
+
* - **Counters live in the isolate.** workerd runs one isolate per Worker per instance, so they
|
|
8
|
+
* are that instance's, from `cloudhal_process_start_time_seconds` on; a restart resets them,
|
|
9
|
+
* which Prometheus' `rate()` handles. On Cloudflare, with many isolates, they mean little, and
|
|
10
|
+
* traces and Workers Analytics are the tools there.
|
|
11
|
+
* - **Gauges are read when scraped:** the scheduler's last tick (D1), and the site Worker's own
|
|
12
|
+
* counters through `SITE` (`/__cloudhal/metrics`, Bearer `CLOUDHAL_PURGE_TOKEN`).
|
|
13
|
+
* - **Bounded labels only:** Worker, area of the path, status class, outcome, store. No paths,
|
|
14
|
+
* site ids, users or agents.
|
|
15
|
+
*/
|
|
16
|
+
import {
|
|
17
|
+
METRIC_BUCKETS as BUCKETS,
|
|
18
|
+
Histogram,
|
|
19
|
+
RequestMetrics,
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
} from "@cloudhal/core-ts";
|
|
23
|
+
import { schedulerHealthReport } from "@cloudhal/core-ts/releases";
|
|
24
|
+
import { D1Driver } from "@cloudhal/storage/d1";
|
|
25
|
+
|
|
26
|
+
export const METRICS_PATH = "/api/metrics";
|
|
27
|
+
export const SITE_METRICS_URL = "https://site.internal/__cloudhal/metrics";
|
|
28
|
+
/** A Prometheus text line's number. */
|
|
29
|
+
const num = (n ) => (Number.isFinite(n) ? String(Math.round(n * 1e6) / 1e6) : "NaN");
|
|
30
|
+
|
|
31
|
+
function histogramLines(name , all ) {
|
|
32
|
+
const out = [];
|
|
33
|
+
for (const [labels, s] of Object.entries(all)) {
|
|
34
|
+
const pre = labels ? `${labels},` : "";
|
|
35
|
+
BUCKETS.forEach((le, i) => {
|
|
36
|
+
out.push(`${name}_bucket{${pre}le="${le}"} ${s.buckets[i]}`);
|
|
37
|
+
});
|
|
38
|
+
out.push(`${name}_bucket{${pre}le="+Inf"} ${s.count}`);
|
|
39
|
+
out.push(`${name}_sum${labels ? `{${labels}}` : ""} ${num(s.sum)}`);
|
|
40
|
+
out.push(`${name}_count${labels ? `{${labels}}` : ""} ${s.count}`);
|
|
41
|
+
}
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const family = (name , type , help , lines ) =>
|
|
46
|
+
[`# HELP ${name} ${help}`, `# TYPE ${name} ${type}`, ...lines].join("\n");
|
|
47
|
+
|
|
48
|
+
/** The site Worker's counters, as `/__cloudhal/metrics` answers them. */
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
/** Which part of Studio's origin a path belongs to: a small, fixed set of labels. */
|
|
52
|
+
export function area(pathname ) {
|
|
53
|
+
if (pathname === "/mcp" || pathname.startsWith("/mcp/")) return "mcp";
|
|
54
|
+
if (pathname.startsWith("/api/auth/")) return "auth";
|
|
55
|
+
if (pathname.startsWith("/api/admin/")) return "admin";
|
|
56
|
+
if (pathname.startsWith("/api/")) return "api";
|
|
57
|
+
if (pathname.startsWith("/.well-known/")) return "oauth";
|
|
58
|
+
return "studio";
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** This isolate's admin metrics. */
|
|
62
|
+
export class AdminMetrics {
|
|
63
|
+
requests = new RequestMetrics();
|
|
64
|
+
publishes = new Histogram();
|
|
65
|
+
#storeErrors = new Map ();
|
|
66
|
+
startedAt = Date.now();
|
|
67
|
+
|
|
68
|
+
storeError(store ) {
|
|
69
|
+
this.#storeErrors.set(store, (this.#storeErrors.get(store) ?? 0) + 1);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The exposition, with what was read at scrape time. */
|
|
73
|
+
text(read
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
) {
|
|
77
|
+
const reqs = this.requests.toJSON();
|
|
78
|
+
const counts = Object.entries(reqs.requests).map(([l, n]) =>
|
|
79
|
+
`{worker="admin",${l}}`.concat(` ${n}`),
|
|
80
|
+
);
|
|
81
|
+
const durations = {};
|
|
82
|
+
for (const [l, s] of Object.entries(reqs.durations)) durations[`worker="admin",${l}`] = s;
|
|
83
|
+
for (const [l, n] of Object.entries(read.site?.requests ?? {}))
|
|
84
|
+
counts.push(`{worker="site",${l}} ${n}`);
|
|
85
|
+
for (const [l, s] of Object.entries(read.site?.durations ?? {}))
|
|
86
|
+
durations[l ? `worker="site",${l}` : `worker="site"`] = s;
|
|
87
|
+
const errors = ["d1", "r2"].map((s) => `{store="${s}"} ${this.#storeErrors.get(s) ?? 0}`);
|
|
88
|
+
const out = [
|
|
89
|
+
family(
|
|
90
|
+
"cloudhal_http_requests_total",
|
|
91
|
+
"counter",
|
|
92
|
+
"Requests this instance's admin and site Workers answered, by area and status class.",
|
|
93
|
+
counts.map((c) => `cloudhal_http_requests_total${c}`),
|
|
94
|
+
),
|
|
95
|
+
family(
|
|
96
|
+
"cloudhal_http_request_duration_seconds",
|
|
97
|
+
"histogram",
|
|
98
|
+
"Time to answer a request.",
|
|
99
|
+
histogramLines("cloudhal_http_request_duration_seconds", durations),
|
|
100
|
+
),
|
|
101
|
+
family(
|
|
102
|
+
"cloudhal_publish_duration_seconds",
|
|
103
|
+
"histogram",
|
|
104
|
+
"Time of a publish asked for over the API or MCP, by how and outcome.",
|
|
105
|
+
histogramLines("cloudhal_publish_duration_seconds", this.publishes.toJSON()),
|
|
106
|
+
),
|
|
107
|
+
family(
|
|
108
|
+
"cloudhal_store_errors_total",
|
|
109
|
+
"counter",
|
|
110
|
+
"Database statements and media operations that failed (after any retries).",
|
|
111
|
+
errors.map((e) => `cloudhal_store_errors_total${e}`),
|
|
112
|
+
),
|
|
113
|
+
];
|
|
114
|
+
if (read.scheduler) {
|
|
115
|
+
const s = read.scheduler;
|
|
116
|
+
out.push(
|
|
117
|
+
family("cloudhal_scheduler_healthy", "gauge", "1 while the scheduler ticks on time.", [
|
|
118
|
+
`cloudhal_scheduler_healthy ${s.healthy ? 1 : 0}`,
|
|
119
|
+
]),
|
|
120
|
+
);
|
|
121
|
+
if (s.lagSeconds !== undefined)
|
|
122
|
+
out.push(
|
|
123
|
+
family(
|
|
124
|
+
"cloudhal_scheduler_lag_seconds",
|
|
125
|
+
"gauge",
|
|
126
|
+
"How late the oldest due release or automation run was at the last tick.",
|
|
127
|
+
[`cloudhal_scheduler_lag_seconds ${num(s.lagSeconds)}`],
|
|
128
|
+
),
|
|
129
|
+
);
|
|
130
|
+
if (s.secondsSinceTick !== undefined)
|
|
131
|
+
out.push(
|
|
132
|
+
family(
|
|
133
|
+
"cloudhal_scheduler_seconds_since_tick",
|
|
134
|
+
"gauge",
|
|
135
|
+
"Seconds since the scheduler's last tick (it ticks every minute).",
|
|
136
|
+
[`cloudhal_scheduler_seconds_since_tick ${num(s.secondsSinceTick)}`],
|
|
137
|
+
),
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
out.push(
|
|
141
|
+
family(
|
|
142
|
+
"cloudhal_process_start_time_seconds",
|
|
143
|
+
"gauge",
|
|
144
|
+
"When this isolate's counters started.",
|
|
145
|
+
[`cloudhal_process_start_time_seconds ${num(this.startedAt / 1000)}`],
|
|
146
|
+
),
|
|
147
|
+
);
|
|
148
|
+
return `${out.join("\n")}\n`;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** One per isolate. */
|
|
153
|
+
export const ADMIN_METRICS = new AdminMetrics();
|
|
154
|
+
|
|
155
|
+
/** Equal tokens, compared without an early exit. */
|
|
156
|
+
export function sameToken(given , expected ) {
|
|
157
|
+
const a = new TextEncoder().encode(given);
|
|
158
|
+
const b = new TextEncoder().encode(expected);
|
|
159
|
+
let diff = a.length ^ b.length;
|
|
160
|
+
for (let i = 0; i < b.length; i++) diff |= (a[i] ?? 0) ^ (b[i] );
|
|
161
|
+
return diff === 0;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
const plain = (status , text , extra = {}) =>
|
|
173
|
+
new Response(text, {
|
|
174
|
+
status,
|
|
175
|
+
headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store", ...extra },
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
async function readNow(env , metrics ) {
|
|
179
|
+
const sql = new D1Driver(env.DB, { onError: () => metrics.storeError("d1") });
|
|
180
|
+
const mode = env.CLOUDHAL_SCHEDULER === "cron" ? "cron" : "alarm";
|
|
181
|
+
const scheduler = await schedulerHealthReport(sql, { now: new Date(), mode })
|
|
182
|
+
.then((h) => ({
|
|
183
|
+
healthy: h.healthy,
|
|
184
|
+
...(h.lagSeconds !== undefined ? { lagSeconds: h.lagSeconds } : {}),
|
|
185
|
+
...(h.lastTickAt
|
|
186
|
+
? { secondsSinceTick: Math.max(0, (Date.now() - Date.parse(h.lastTickAt)) / 1000) }
|
|
187
|
+
: {}),
|
|
188
|
+
}))
|
|
189
|
+
.catch(() => undefined);
|
|
190
|
+
let site ;
|
|
191
|
+
if (env.SITE && env.CLOUDHAL_PURGE_TOKEN) {
|
|
192
|
+
const res = await env.SITE.fetch(SITE_METRICS_URL, {
|
|
193
|
+
headers: { authorization: `Bearer ${env.CLOUDHAL_PURGE_TOKEN}` },
|
|
194
|
+
}).catch(() => undefined);
|
|
195
|
+
if (res?.ok) site = (await res.json().catch(() => undefined)) ;
|
|
196
|
+
}
|
|
197
|
+
return { ...(scheduler ? { scheduler } : {}), ...(site ? { site } : {}) };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** The `/api/metrics` answer. */
|
|
201
|
+
export async function metricsResponse(
|
|
202
|
+
request ,
|
|
203
|
+
env ,
|
|
204
|
+
metrics = ADMIN_METRICS,
|
|
205
|
+
) {
|
|
206
|
+
const token = env.CLOUDHAL_METRICS_TOKEN;
|
|
207
|
+
if (!token) return plain(404, "not found");
|
|
208
|
+
const auth = request.headers.get("authorization") ?? "";
|
|
209
|
+
if (!auth.startsWith("Bearer ") || !sameToken(auth.slice(7), token))
|
|
210
|
+
return plain(401, "unauthorized", { "www-authenticate": 'Bearer realm="metrics"' });
|
|
211
|
+
if (request.method !== "GET") return plain(405, "method not allowed", { allow: "GET" });
|
|
212
|
+
return plain(200, metrics.text(await readNow(env, metrics)), {
|
|
213
|
+
"content-type": "text/plain; version=0.0.4; charset=utf-8",
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** `api` for a publish in Studio's API, `mcp` for the `publish` tool; undefined otherwise. */
|
|
218
|
+
async function publishVia(request , url ) {
|
|
219
|
+
if (request.method !== "POST") return undefined;
|
|
220
|
+
const parts = url.pathname.split("/");
|
|
221
|
+
if (
|
|
222
|
+
parts.length === 7 &&
|
|
223
|
+
parts[2] === "sites" &&
|
|
224
|
+
parts[4] === "releases" &&
|
|
225
|
+
parts[6] === "publish-now"
|
|
226
|
+
)
|
|
227
|
+
return "api";
|
|
228
|
+
const snapshots = parts.length === 5 && parts[2] === "sites" && parts[4] === "snapshots";
|
|
229
|
+
if (!snapshots && url.pathname !== "/mcp") return undefined;
|
|
230
|
+
const body = (await request
|
|
231
|
+
.clone()
|
|
232
|
+
.json()
|
|
233
|
+
.catch(() => undefined))
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
;
|
|
238
|
+
if (snapshots) return body?.publish === true ? "api" : undefined;
|
|
239
|
+
return body?.method === "tools/call" && body.params?.name === "publish" ? "mcp" : undefined;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
/** The admin Worker with `/api/metrics` and its counters around every request. */
|
|
245
|
+
export function instrumentAdmin (
|
|
246
|
+
worker ,
|
|
247
|
+
metrics = ADMIN_METRICS,
|
|
248
|
+
) {
|
|
249
|
+
const fetch = async (
|
|
250
|
+
request ,
|
|
251
|
+
env ,
|
|
252
|
+
ctx ,
|
|
253
|
+
) => {
|
|
254
|
+
const url = new URL(request.url);
|
|
255
|
+
if (url.pathname === METRICS_PATH) return metricsResponse(request, env, metrics);
|
|
256
|
+
const started = Date.now();
|
|
257
|
+
const via = await publishVia(request, url);
|
|
258
|
+
const done = (status ) => {
|
|
259
|
+
const seconds = (Date.now() - started) / 1000;
|
|
260
|
+
metrics.requests.record(`area="${area(url.pathname)}"`, status, seconds);
|
|
261
|
+
if (via)
|
|
262
|
+
metrics.publishes.observe(
|
|
263
|
+
`via="${via}",outcome="${status < 400 ? "ok" : "failed"}"`,
|
|
264
|
+
seconds,
|
|
265
|
+
);
|
|
266
|
+
};
|
|
267
|
+
try {
|
|
268
|
+
const res = await worker.fetch(request, env , ctx);
|
|
269
|
+
done(res.status);
|
|
270
|
+
return res;
|
|
271
|
+
} catch (error) {
|
|
272
|
+
done(500);
|
|
273
|
+
throw error;
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
return { ...worker, fetch } ;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** An R2 bucket whose failed operations count as store errors. */
|
|
280
|
+
export function watchedBucket(bucket , metrics = ADMIN_METRICS) {
|
|
281
|
+
return new Proxy(bucket, {
|
|
282
|
+
get(target, prop) {
|
|
283
|
+
const value = Reflect.get(target, prop);
|
|
284
|
+
if (typeof value !== "function") return value;
|
|
285
|
+
return (...args ) => {
|
|
286
|
+
const out = (value ).apply(target, args);
|
|
287
|
+
return out instanceof Promise
|
|
288
|
+
? out.catch((e ) => {
|
|
289
|
+
metrics.storeError("r2");
|
|
290
|
+
throw e;
|
|
291
|
+
})
|
|
292
|
+
: out;
|
|
293
|
+
};
|
|
294
|
+
},
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** The admin Worker's database, its failures counted. */
|
|
299
|
+
export function adminSql(env , metrics = ADMIN_METRICS) {
|
|
300
|
+
return new D1Driver(env.DB, { onError: () => metrics.storeError("d1") });
|
|
301
|
+
}
|
|
@@ -13,6 +13,14 @@ export declare function sessionTime(id: string): number | undefined;
|
|
|
13
13
|
export declare function signSession(id: string, secret: string): Promise<string>;
|
|
14
14
|
/** The session ID of a cookie value whose MAC holds, else undefined. */
|
|
15
15
|
export declare function verifySession(value: string, secret: string): Promise<string | undefined>;
|
|
16
|
+
/**
|
|
17
|
+
* #383: what a session's signed preview media URLs carry (`ps=<ulid>.<mac>`), so the Worker can
|
|
18
|
+
* route them to the session without its cookie: a sandboxed preview sends none. Its own MAC key
|
|
19
|
+
* (the secret with a purpose suffix), so it never passes as the cookie, and the Worker accepts it
|
|
20
|
+
* on `preview-media` GETs only.
|
|
21
|
+
*/
|
|
22
|
+
export declare function signPreviewSession(id: string, secret: string): Promise<string>;
|
|
23
|
+
export declare function verifyPreviewSession(value: string, secret: string): Promise<string | undefined>;
|
|
16
24
|
/** The session cookie's value in a request, if any. */
|
|
17
25
|
export declare function readSessionCookie(request: Request): string | undefined;
|
|
18
26
|
/** `Set-Cookie` for a session (host-only, `__Host-`: Secure, Path=/, no Domain; ADR-0037). */
|
|
@@ -62,6 +62,20 @@ export async function verifySession(value , secret )
|
|
|
62
62
|
return diff === 0 ? id : undefined;
|
|
63
63
|
}
|
|
64
64
|
|
|
65
|
+
/**
|
|
66
|
+
* #383: what a session's signed preview media URLs carry (`ps=<ulid>.<mac>`), so the Worker can
|
|
67
|
+
* route them to the session without its cookie: a sandboxed preview sends none. Its own MAC key
|
|
68
|
+
* (the secret with a purpose suffix), so it never passes as the cookie, and the Worker accepts it
|
|
69
|
+
* on `preview-media` GETs only.
|
|
70
|
+
*/
|
|
71
|
+
export function signPreviewSession(id , secret ) {
|
|
72
|
+
return signSession(id, `${secret}\npreview-media`);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function verifyPreviewSession(value , secret ) {
|
|
76
|
+
return verifySession(value, `${secret}\npreview-media`);
|
|
77
|
+
}
|
|
78
|
+
|
|
65
79
|
/** The session cookie's value in a request, if any. */
|
|
66
80
|
export function readSessionCookie(request ) {
|
|
67
81
|
const header = request.headers.get("cookie") ?? "";
|
|
@@ -25,7 +25,7 @@ import {
|
|
|
25
25
|
SITE_PREFIX,
|
|
26
26
|
} from "./playground-options.js";
|
|
27
27
|
import { privateSiteResponse } from "./playground-render.js";
|
|
28
|
-
import { sessionTime } from "./playground-session.js";
|
|
28
|
+
import { sessionTime, signPreviewSession } from "./playground-session.js";
|
|
29
29
|
|
|
30
30
|
const MINUTE = 60_000;
|
|
31
31
|
const json = (status , body ) =>
|
|
@@ -78,7 +78,7 @@ export function playgroundSiteClass(options )
|
|
|
78
78
|
await this.#wipe();
|
|
79
79
|
return json(410, { error: "playground_expired" });
|
|
80
80
|
}
|
|
81
|
-
const session = await this.#open();
|
|
81
|
+
const session = await this.#open(id);
|
|
82
82
|
this.#expiresAt = Math.min(
|
|
83
83
|
now + limits.idleMinutes * MINUTE,
|
|
84
84
|
created + limits.maxMinutes * MINUTE,
|
|
@@ -116,7 +116,7 @@ export function playgroundSiteClass(options )
|
|
|
116
116
|
}
|
|
117
117
|
|
|
118
118
|
/** The session's store, API and site; migrated and seeded on first use. */
|
|
119
|
-
async #open() {
|
|
119
|
+
async #open(id ) {
|
|
120
120
|
if (this.#session) return this.#session;
|
|
121
121
|
await this.state.blockConcurrencyWhile(async () => {
|
|
122
122
|
if (this.#session) return;
|
|
@@ -147,6 +147,7 @@ export function playgroundSiteClass(options )
|
|
|
147
147
|
}
|
|
148
148
|
const api = createApi({
|
|
149
149
|
store,
|
|
150
|
+
...(await previewMediaOf(id, this.env.PLAYGROUND_SECRET)),
|
|
150
151
|
defer: (task) => this.state.waitUntil(task.catch(() => {})),
|
|
151
152
|
playground: {
|
|
152
153
|
info: () => ({
|
|
@@ -164,6 +165,20 @@ export function playgroundSiteClass(options )
|
|
|
164
165
|
};
|
|
165
166
|
}
|
|
166
167
|
|
|
168
|
+
/**
|
|
169
|
+
* #383: a session's signed preview media URLs. The key comes from the playground secret and the
|
|
170
|
+
* session, so it outlives an evicted object; `ps` lets the Worker route a URL without the cookie.
|
|
171
|
+
*/
|
|
172
|
+
async function previewMediaOf(id , secret ) {
|
|
173
|
+
if (!secret) return {};
|
|
174
|
+
return {
|
|
175
|
+
previewMedia: {
|
|
176
|
+
secret: `${secret}\npreview-media\n${id}`,
|
|
177
|
+
query: `ps=${await signPreviewSession(id, secret)}`,
|
|
178
|
+
},
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
167
182
|
/** RFC-0036 §7: a full database or too many nodes refuse writes with 507. */
|
|
168
183
|
async function fullResponse(
|
|
169
184
|
request ,
|
package/dist/src/playground.js
CHANGED
|
@@ -27,6 +27,7 @@ import {
|
|
|
27
27
|
sessionCookie,
|
|
28
28
|
sessionTime,
|
|
29
29
|
signSession,
|
|
30
|
+
verifyPreviewSession,
|
|
30
31
|
verifySession,
|
|
31
32
|
} from "./playground-session.js";
|
|
32
33
|
import { playgroundSiteClass } from "./playground-site.js";
|
|
@@ -43,6 +44,9 @@ const json = (status , body , headers = {
|
|
|
43
44
|
headers: { "content-type": "application/json", "cache-control": "no-store", ...headers },
|
|
44
45
|
});
|
|
45
46
|
|
|
47
|
+
/** #383: a preview's signed media URL (`/api/sites/<site>/preview-media/…`). */
|
|
48
|
+
const PREVIEW_MEDIA_PATH = /^\/api\/sites\/[^/]{1,64}\/preview-media\//;
|
|
49
|
+
|
|
46
50
|
/** Paths that belong to a session's Durable Object. */
|
|
47
51
|
function isSessionPath(path ) {
|
|
48
52
|
return (
|
|
@@ -75,7 +79,24 @@ export function createPlaygroundWorker(options )
|
|
|
75
79
|
async function sessionOf(request , env ) {
|
|
76
80
|
const value = readSessionCookie(request);
|
|
77
81
|
if (!value || !env.PLAYGROUND_SECRET) return undefined;
|
|
78
|
-
|
|
82
|
+
return unexpired(await verifySession(value, env.PLAYGROUND_SECRET));
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** #383: a preview media GET's session, from its `ps` token (sandboxed previews send no cookie). */
|
|
86
|
+
async function previewMediaSessionOf(request , env , url ) {
|
|
87
|
+
if (request.method !== "GET" && request.method !== "HEAD") return undefined;
|
|
88
|
+
if (url.pathname.length > 512 || !PREVIEW_MEDIA_PATH.test(url.pathname)) return undefined;
|
|
89
|
+
const value = url.searchParams.get("ps");
|
|
90
|
+
if (!value || value.length > 128 || !env.PLAYGROUND_SECRET) return undefined;
|
|
91
|
+
return unexpired(await verifyPreviewSession(value, env.PLAYGROUND_SECRET));
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** The cookie's session, else (#383) a preview media URL's. */
|
|
95
|
+
async function requestSession(request , env , url ) {
|
|
96
|
+
return (await sessionOf(request, env)) ?? (await previewMediaSessionOf(request, env, url));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function unexpired(id ) {
|
|
79
100
|
const created = id ? sessionTime(id) : undefined;
|
|
80
101
|
if (!id || created === undefined) return undefined;
|
|
81
102
|
const now = Date.now();
|
|
@@ -148,7 +169,7 @@ export function createPlaygroundWorker(options )
|
|
|
148
169
|
return enabled ? createSession(request, env) : landing(request, env, 503);
|
|
149
170
|
if (isSessionPath(path)) {
|
|
150
171
|
if (!enabled) return json(503, { error: "playground_closed" });
|
|
151
|
-
const id = await
|
|
172
|
+
const id = await requestSession(request, env, url);
|
|
152
173
|
if (!id)
|
|
153
174
|
return path.startsWith("/api/") || path === "/mcp" || path === RESET_PATH
|
|
154
175
|
? json(410, { error: "playground_expired", message: "This session has ended." })
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cloudhal/cloudflare",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.0",
|
|
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",
|
|
@@ -48,23 +48,23 @@
|
|
|
48
48
|
"README.md"
|
|
49
49
|
],
|
|
50
50
|
"dependencies": {
|
|
51
|
-
"@cloudhal/agent-runtime": "0.
|
|
52
|
-
"@cloudhal/analytics": "0.
|
|
53
|
-
"@cloudhal/api": "0.
|
|
54
|
-
"@cloudhal/comments": "0.
|
|
55
|
-
"@cloudhal/core-ts": "0.
|
|
56
|
-
"@cloudhal/mcp-server": "0.
|
|
57
|
-
"@cloudhal/schedules": "0.
|
|
58
|
-
"@cloudhal/storage": "0.
|
|
51
|
+
"@cloudhal/agent-runtime": "0.12.0",
|
|
52
|
+
"@cloudhal/analytics": "0.12.0",
|
|
53
|
+
"@cloudhal/api": "0.12.0",
|
|
54
|
+
"@cloudhal/comments": "0.12.0",
|
|
55
|
+
"@cloudhal/core-ts": "0.12.0",
|
|
56
|
+
"@cloudhal/mcp-server": "0.12.0",
|
|
57
|
+
"@cloudhal/schedules": "0.12.0",
|
|
58
|
+
"@cloudhal/storage": "0.12.0",
|
|
59
59
|
"zod": "^4.6.7"
|
|
60
60
|
},
|
|
61
61
|
"devDependencies": {
|
|
62
62
|
"@cloudflare/workers-types": "^5.20261007.1",
|
|
63
|
-
"@cloudhal/astro-renderer": "0.
|
|
64
|
-
"@types/node": "^26.6.
|
|
63
|
+
"@cloudhal/astro-renderer": "0.12.0",
|
|
64
|
+
"@types/node": "^26.6.11",
|
|
65
65
|
"typescript": "7.0.2",
|
|
66
|
-
"vitest": "5.1.
|
|
67
|
-
"wrangler": "4.
|
|
66
|
+
"vitest": "5.1.2",
|
|
67
|
+
"wrangler": "4.169.0"
|
|
68
68
|
},
|
|
69
69
|
"engines": {
|
|
70
70
|
"node": ">=24"
|