@cloudhal/cloudflare 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,23 @@
1
- # Temporary Holding Version
1
+ # @cloudhal/cloudflare
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The Cloudhal **admin Worker** (ADR-0012): Studio (static assets), the HTTP API, Better Auth on D1, the MCP endpoint and the push/pull endpoints on one origin, over the deployment's D1 database and R2 bucket. After every publish/rollback it purges the **site Worker**'s edge cache through the `SITE` service binding.
4
+
5
+ ```ts
6
+ // worker.ts — generated by `cloudhal deploy`
7
+ import "@cloudhal/cloudflare/workerd-prelude"; // must stay first (zod init order, see the module)
8
+ import { createAdminWorker } from "@cloudhal/cloudflare/admin";
9
+ import skills from "./skills.ts";
10
+ export default createAdminWorker({ skills });
11
+ ```
12
+
13
+ | Binding / secret | Purpose |
14
+ |---|---|
15
+ | `DB` (D1), `BLOBS` (R2) | the site graph, snapshots, auth, audit |
16
+ | `ASSETS` | built Studio (`not_found_handling: single-page-application`, `run_worker_first` for `/api/*`, `/mcp`, `/.well-known/*`) |
17
+ | `SITE` (service) | the site Worker, for cache purges |
18
+ | `BETTER_AUTH_SECRET`, `MCP_STATE_KEY` | sessions; signed approval state |
19
+ | `CLOUDHAL_PREVIEW_SECRET`, `CLOUDHAL_PURGE_TOKEN` | shared with the site Worker |
20
+ | `CLOUDHAL_DEPLOY_TOKEN` | `cloudhal push` / `pull` |
21
+ | `CLOUDHAL_SIGNUP` | `first-user` (default — only the first account, the owner, can sign up), `closed` or `open` |
22
+
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).
@@ -0,0 +1,148 @@
1
+ /**
2
+ * The Cloudhal admin Worker (ADR-0012): one origin for the Studio SPA (static assets), the HTTP
3
+ * API, Better Auth and the MCP endpoint — all over the deployment's D1 database and R2 bucket.
4
+ *
5
+ * After every publish/rollback it purges the site Worker's edge cache through the `SITE` service
6
+ * binding (cache purges are scoped to the Worker that cached the responses): only the tags of what
7
+ * changed between the previously live snapshot and the new one (`purge.ts`), everything when that
8
+ * cannot be worked out.
9
+ *
10
+ * Site analytics (RFC-0006 §7.5, §8): with `CLOUDHAL_ANALYTICS_DATASET` set the deployment records to
11
+ * Workers Analytics Engine; Studio and MCP read it through the `ANALYTICS_SQL` binding (no API
12
+ * token), and the hourly `scheduled` handler rolls finished days into D1 and deletes old salts. A
13
+ * missing binding means the "can't read yet" state (`reader: "none"`), never a crash.
14
+ *
15
+ * Reader comments (RFC-0007 step 5, `comments.ts`): with `CLOUDHAL_COMMENTS_KEY` (the site Worker's
16
+ * secret) the API and MCP serve comments; moderation queues comment cache tags, which the flusher
17
+ * sends through `SITE` within the purge budget publishes share (every purge request is logged in
18
+ * `cache_purge_log`): takedowns 2 s after the write, normal tags 20 s later, and on any later
19
+ * admin request whose queue is due; the hourly job applies retention, purges threads that closed by
20
+ * time and deletes old salts.
21
+ *
22
+ * Schedules (RFC-0008 §8, `scheduler.ts`): one tick a minute runs due releases, automation
23
+ * occurrences and the hourly jobs behind `system_jobs` watermarks — from the `* * * * *` cron
24
+ * trigger (`scheduled`), or, with `CLOUDHAL_SCHEDULER=alarm`, from the `SchedulerClock` Durable
25
+ * Object this module exports; admin requests are the backstop when the heartbeat is stale.
26
+ *
27
+ * Email (RFC-0011, `mail.ts`): with the `EMAIL` send binding and `CLOUDHAL_MAIL_FROM` the API mails
28
+ * invites and reset links through Cloudflare Email Service, after the response where it must not
29
+ * show (`defer` → `waitUntil`).
30
+ *
31
+ * In-editor AI (RFC-0016): with the `AI` binding (`ai` in cloudhal.json) the API reaches Workers AI
32
+ * without a secret; each site's owner turns it on, picks the model and sets the daily cap in Studio.
33
+ *
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).
36
+ */
37
+ import { type SkillSource } from "@cloudhal/agent-runtime";
38
+ import { type AnalyticsDefaults } from "@cloudhal/analytics";
39
+ import { AnalyticsService } from "@cloudhal/analytics/service";
40
+ import { type AiBinding } from "@cloudhal/api";
41
+ import { type AiSearchEnv } from "@cloudhal/core-ts";
42
+ import { type BlockType, type PropsSchema } from "@cloudhal/core-ts/blocks";
43
+ import { type SqlDriver } from "@cloudhal/storage";
44
+ import { type BrowserBinding } from "./browser-render.js";
45
+ import { type BuildRoomsEnv } from "./build-rooms.js";
46
+ import { type CommentsEnv } from "./comments.js";
47
+ import { type MailEnv } from "./mail.js";
48
+ import { type SchedulerEnv } from "./scheduler.js";
49
+ export interface AdminEnv extends CommentsEnv, SchedulerEnv, MailEnv, BuildRoomsEnv, AiSearchEnv {
50
+ DB: D1Database;
51
+ BLOBS: R2Bucket;
52
+ /** Workers AI (RFC-0016), bound when cloudhal.json has an `ai` key. */
53
+ AI?: AiBinding;
54
+ ASSETS?: Fetcher;
55
+ SITE?: Fetcher;
56
+ /** RFC-0034 §4: `{siteId: binding}` for sites served by attached site Workers. */
57
+ CLOUDHAL_SITE_ROUTES?: string;
58
+ BETTER_AUTH_SECRET: string;
59
+ MCP_STATE_KEY: string;
60
+ CLOUDHAL_PREVIEW_SECRET?: string;
61
+ CLOUDHAL_PURGE_TOKEN?: string;
62
+ CLOUDHAL_DEPLOY_TOKEN?: string;
63
+ /** One-time token the first account must present (see `cloudhal deploy` output). */
64
+ CLOUDHAL_SETUP_TOKEN?: string;
65
+ /** `first-user` (default: only the owner can sign up), `closed` or `open`. */
66
+ CLOUDHAL_SIGNUP?: string;
67
+ /** Reads Workers Analytics Engine (RFC-0006 §7.3); absent: analytics recorded but not readable. */
68
+ ANALYTICS_SQL?: AnalyticsSQLBinding;
69
+ /** `<deployment>_events`; set by `cloudhal deploy` when `analytics.enabled` (absent: no analytics). */
70
+ CLOUDHAL_ANALYTICS_DATASET?: string;
71
+ /** Uncached live analytics queries per UTC day (default 8000, §7.7). */
72
+ CLOUDHAL_ANALYTICS_BUDGET?: string;
73
+ /** Deployment defaults for sites without a settings row (compact JSON from cloudhal.json). */
74
+ CLOUDHAL_ANALYTICS_DEFAULTS?: string;
75
+ /** Cloudflare Browser Rendering for `render_page` (RFC-0021 §4); absent: `render_unavailable`. */
76
+ BROWSER?: BrowserBinding;
77
+ /** `off` keeps `render_page` unavailable even with a `BROWSER` binding. */
78
+ CLOUDHAL_RENDER?: string;
79
+ }
80
+ /** Default daily budget of uncached live queries: 80 % of WAE Free's 10,000 (§7.7, A2). */
81
+ export declare const DEFAULT_ANALYTICS_BUDGET = 8000;
82
+ /**
83
+ * `CLOUDHAL_ANALYTICS_DEFAULTS` as the Site Worker reads it (`deploymentDefaults` in the renderer):
84
+ * cloudhal.json's `analytics` block, in which `enabled` defaults to `true`.
85
+ */
86
+ export declare function analyticsDefaults(json: string | undefined): AnalyticsDefaults;
87
+ /**
88
+ * The deployment's analytics (RFC-0006 §8) from its bindings and vars. Plain construction, no I/O,
89
+ * so it is built per request or scheduled run (ADR-0012: nothing but plain values is cached).
90
+ */
91
+ export declare function adminAnalytics(env: AdminEnv, sql: SqlDriver, options?: {
92
+ now?: () => Date;
93
+ log?: (line: string) => void;
94
+ }): AnalyticsService;
95
+ export interface AdminWorkerOptions {
96
+ /** Skills exposed over MCP (bundled at deploy time). */
97
+ skills?: SkillSource[];
98
+ /** The theme's block types (`src/blocks.ts`, RFC-0015 §6), bundled at deploy time. */
99
+ blockTypes?: readonly BlockType[];
100
+ /** The theme's design settings (`src/settings.ts`, RFC-0017 §1), bundled at deploy time. */
101
+ themeSettings?: PropsSchema;
102
+ /** The theme's DESIGN.md (RFC-0021 §1), bundled at deploy time. */
103
+ themeDesign?: string;
104
+ log?: (line: string) => void;
105
+ }
106
+ /**
107
+ * What `apps/studio/public/_headers` sets on Studio's static files, also on the shell this Worker
108
+ * serves for client routes: Studio is the most privileged origin of a deployment (sessions,
109
+ * approvals, members), so it is never framed, loads no plugins and keeps its `<base>`.
110
+ */
111
+ export declare const STUDIO_SECURITY_HEADERS: Readonly<Record<string, string>>;
112
+ export declare function createAdminWorker(options?: AdminWorkerOptions): {
113
+ fetch(request: Request, env: AdminEnv, ctx: ExecutionContext): Promise<Response>;
114
+ /**
115
+ * The minute tick (RFC-0008 §8.2, cron `* * * * *`): due releases, automation occurrences, and
116
+ * the hourly jobs behind their watermarks — the analytics rollup (RFC-0006 §7.5) and the
117
+ * comments job (RFC-0007 §8.5) at :17, unchanged and with their log lines. Bounded work per
118
+ * invocation (`TickBudget`); a missed minute is caught up by the next tick.
119
+ */
120
+ scheduled(controller: ScheduledController, env: AdminEnv, ctx: ExecutionContext): Promise<void>;
121
+ };
122
+ /**
123
+ * Build rooms (RFC-0020 §6): one Durable Object per page carrying Studio's Build view events
124
+ * between isolates (`BUILD_ROOMS`, SQLite-backed, hibernatable WebSockets). The generated admin
125
+ * entry re-exports it.
126
+ */
127
+ export declare const BuildRoom: {
128
+ new (state: DurableObjectState, _env: unknown): {
129
+ readonly state: DurableObjectState;
130
+ fetch(request: Request): Promise<Response>;
131
+ webSocketMessage(): void;
132
+ webSocketClose(ws: WebSocket, code: number): void;
133
+ };
134
+ };
135
+ /**
136
+ * The scheduler's Durable Object clock (RFC-0008 §8.3), declared by every deploy
137
+ * (`SCHEDULER_CLOCK`, SQLite-backed) and woken only with `CLOUDHAL_SCHEDULER=alarm`. The generated
138
+ * admin entry re-exports it.
139
+ */
140
+ export declare const SchedulerClock: {
141
+ new (state: DurableObjectState, env: SchedulerEnv): {
142
+ readonly state: DurableObjectState;
143
+ readonly env: SchedulerEnv;
144
+ fetch(request: Request): Promise<Response>;
145
+ poke(at: number): Promise<number>;
146
+ alarm(): Promise<void>;
147
+ };
148
+ };