@runeditrun/rer 0.2.14 → 0.2.16
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/cli/demo-host.mjs +4 -4
- package/global/CHANGELOG.md +18 -0
- package/modules/demo-host/README.md +19 -2
- package/modules/demo-host/container.mjs +25 -6
- package/modules/demo-host/pages.mjs +17 -15
- package/modules/demo-host/plan.mjs +13 -8
- package/modules/demo-host/start-script.mjs +71 -0
- package/modules/demo-host/worker.mjs +13 -8
- package/package.json +1 -1
package/cli/demo-host.mjs
CHANGED
|
@@ -4,7 +4,7 @@ import { dirname, join } from 'node:path';
|
|
|
4
4
|
import { contained } from './project.mjs';
|
|
5
5
|
import { invalid, missing, refuse, RerError } from './errors.mjs';
|
|
6
6
|
import { imageFolder } from './container.mjs';
|
|
7
|
-
import { DEMO_FILES, demoPlan } from '../modules/demo-host/plan.mjs';
|
|
7
|
+
import { DEMO_FILES, INSTANCE_TYPES, demoPlan } from '../modules/demo-host/plan.mjs';
|
|
8
8
|
|
|
9
9
|
// `rer deploy --demo [--dry-run]`: the seed's hosted demo at demo.<domain>
|
|
10
10
|
// (modules/demo-host), from deploy-demo.json. It writes .rer/demo-host/: the
|
|
@@ -19,7 +19,7 @@ export async function demoHostCommand(project, options, store, signal, out, oper
|
|
|
19
19
|
if (!(app.platforms ?? ['workers']).includes('container')) throw refuse('A hosted demo runs the seed\'s container image: declare "container" in deploy.json platforms first.');
|
|
20
20
|
let plan;
|
|
21
21
|
try { plan = demoPlan({ project: app.project, environment: options.environment ?? 'production', compatibilityDate: app.compatibilityDate, originVar: app.originVar, declaration, turnstileSiteKey: process.env.TURNSTILE_SITE_KEY?.trim() }); }
|
|
22
|
-
catch (error) { throw invalid(`The demo deploy declaration is invalid (${error.message}). deploy-demo.json holds {"version": 1, "domain": "<run site apex>", "name": "<product name>"}, optionally "maxInstances" and plain "settings".`); }
|
|
22
|
+
catch (error) { throw invalid(`The demo deploy declaration is invalid (${error.message}). deploy-demo.json holds {"version": 1, "domain": "<run site apex>", "name": "<product name>"}, optionally "maxInstances", "instanceType" (${INSTANCE_TYPES.join(', ')}; default basic) and plain "settings".`); }
|
|
23
23
|
if (options.remove) return removeDemo(plan, store);
|
|
24
24
|
if (process.env.RER_DEMO_OPERATOR_TOKEN && (process.env.RER_DEMO_OPERATOR_TOKEN.length < 32 || process.env.RER_DEMO_OPERATOR_TOKEN.length > 512)) throw invalid('RER_DEMO_OPERATOR_TOKEN must contain 32 to 512 characters.');
|
|
25
25
|
const folder = join(project.root, '.rer', 'demo-host');
|
|
@@ -29,9 +29,9 @@ export async function demoHostCommand(project, options, store, signal, out, oper
|
|
|
29
29
|
await imageFolder(project, operation, { ...app, secrets: [...(app.secrets ?? []), { binding: 'RER_DEMO_OPERATOR_TOKEN' }, { binding: 'TURNSTILE_SECRET_KEY' }] }, { output: join(folder, 'image'), engine: 'workerd' });
|
|
30
30
|
for (const file of DEMO_FILES) await cp(new URL(`../modules/demo-host/${file}`, import.meta.url), join(folder, file));
|
|
31
31
|
await writeFile(join(folder, 'wrangler.json'), JSON.stringify(plan.wrangler, null, 2) + '\n');
|
|
32
|
-
const summary = { worker: plan.worker, origin: plan.origin, hostname: plan.hostname, folder: '.rer/demo-host', maxInstances: plan.maxInstances, settings: plan.settings, instanceType:
|
|
32
|
+
const summary = { worker: plan.worker, origin: plan.origin, hostname: plan.hostname, folder: '.rer/demo-host', maxInstances: plan.maxInstances, settings: plan.settings, instanceType: plan.instanceType, startsPerIpPerMinute: 3, minutes: 60, idleMinutes: 15, enableInternet: false };
|
|
33
33
|
const human = [`Demo plan: Worker ${summary.worker} on ${summary.hostname} (custom domain; workers.dev off), written to ${summary.folder}`,
|
|
34
|
-
` one container per visitor (
|
|
34
|
+
` one container per visitor (${summary.instanceType}, at most ${summary.maxInstances} at once, no internet, RER_DEMO=1), 3 starts per IP per minute behind Turnstile`,
|
|
35
35
|
` each demo ends after 60 minutes or 15 idle minutes; its container is destroyed and its state deleted`];
|
|
36
36
|
if (options.dryRun) {
|
|
37
37
|
if (options.json) out.event('demo', summary); else for (const line of human) out.human(line);
|
package/global/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.16
|
|
4
|
+
|
|
5
|
+
- A hosted demo's container stays up until the visitor's 15 idle minutes or the demo's hour, however long the visitor goes without a request. Before, the platform stopped it about three minutes after the last request, the next request got a Cloudflare 500, and its place stayed held. A container that is gone anyway (stopped by the platform, or failing once stopped) now ends its demo, frees its place at once and answers the ended page (410, with "Start a new demo").
|
|
6
|
+
- `deploy-demo.json` takes an optional `instanceType`, one of Cloudflare Containers' predefined types (`lite`, `basic`, `standard-1` to `standard-4`); `basic` unless set, so existing demos are unchanged. `rer deploy --demo --dry-run` prints the planned type and refuses any other value. DEMO.md notes what a larger type costs.
|
|
7
|
+
|
|
8
|
+
### Upgrade notes
|
|
9
|
+
|
|
10
|
+
- Update the exact rer package pin and redeploy hosted demos (`rer deploy --demo`, or run-demo) to receive the keepalive. Demos already running end as before. Set `instanceType` (for example `standard-1`) only where a faster start is worth the cost.
|
|
11
|
+
|
|
12
|
+
## 0.2.15
|
|
13
|
+
|
|
14
|
+
- Demo pages show a slim strip pinned to the top, collapsed by default. Captured mail and blocked-send details open in a popover without moving the page.
|
|
15
|
+
- Hosted demo starts show the human-check wait, a working indicator and progress steps. Failed or slow starts explain what happened and offer a new check with Try again; status updates use live regions.
|
|
16
|
+
|
|
17
|
+
### Upgrade notes
|
|
18
|
+
|
|
19
|
+
- Update the exact rer package pin and redeploy hosted demos to receive the start-page changes. Refresh the demo runtime in an existing seed when that seed vendors it.
|
|
20
|
+
|
|
3
21
|
## 0.2.14
|
|
4
22
|
|
|
5
23
|
- Workerd container and hosted demo builds admit native `cloudflare:workers` imports, Durable Object definitions, `WebSocketPair`, `crypto.subtle.timingSafeEqual` and `ctx.passThroughOnException`. Node-engine restrictions are unchanged.
|
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
The front Worker `rer deploy --demo` deploys at `demo.<domain>` for a seed
|
|
4
4
|
that adopted demo mode (`withDemo`, export/DEMO.md). `plan.mjs` turns `deploy-demo.json`
|
|
5
|
-
|
|
5
|
+
(optionally `instanceType`, one of Cloudflare's predefined Container instance
|
|
6
|
+
types, `basic` unless set) into the Worker's Wrangler configuration; the CLI (`cli/demo-host.mjs`) writes
|
|
6
7
|
it with these files and the seed's container image folder (workerd engine) to
|
|
7
8
|
`.rer/demo-host/` and runs `wrangler deploy` there.
|
|
8
9
|
|
|
@@ -21,8 +22,22 @@ it with these files and the seed's container image folder (workerd engine) to
|
|
|
21
22
|
(`claim.mjs`) to `/auth/owner-claim`. Its alarm ends the demo at its hour or
|
|
22
23
|
after 15 idle minutes: `destroy()`, `deleteAll()` and the place released. A
|
|
23
24
|
container that stops by itself ends its demo too.
|
|
25
|
+
The platform stops a container about two minutes after its Durable Object's
|
|
26
|
+
last event, when it evicts the object (and the object's exit watcher with
|
|
27
|
+
it). So the alarm stays in flight until the demo's next check, at most three
|
|
28
|
+
minutes, and arms the next at once, as the Containers class keeps its own
|
|
29
|
+
object alive. A request or alarm that finds the container gone ends the demo
|
|
30
|
+
and answers the ended page (410), never a 5xx.
|
|
24
31
|
- `capacity.mjs`: `DemoCapacity` admits at most `max_instances` live demos.
|
|
25
32
|
- `pages.mjs`: the start and ended pages (12ui designs), strict CSP.
|
|
33
|
+
`start-script.mjs` is the start page's script: once Turnstile passes it
|
|
34
|
+
posts the form with `Accept: application/json` (the Worker then answers
|
|
35
|
+
`{ location }` with the cookies, or `{ notice }` with the refusal's status)
|
|
36
|
+
and shows each step: the check, the private copy starting, the sign-in. A
|
|
37
|
+
refusal, a network failure or a start past 25 seconds is shown with Try
|
|
38
|
+
again, which runs a new check; progress is announced through a
|
|
39
|
+
`role="status"` region and failures through `role="alert"`. Without
|
|
40
|
+
JavaScript the form posts as before and gets the 303 or the page.
|
|
26
41
|
- `remove.mjs`: `rer deploy --demo --remove --yes`. The deploy passes the
|
|
27
42
|
demo's record (`plan.record`) to `wrangler deploy --message`; removal takes
|
|
28
43
|
the Worker for the demo's only while it serves that version, the Custom
|
|
@@ -35,7 +50,9 @@ it with these files and the seed's container image folder (workerd engine) to
|
|
|
35
50
|
|
|
36
51
|
`node --test modules/demo-host/tests/*.test.mjs` runs the Worker in workerd
|
|
37
52
|
with its real Durable Objects and rate limit; Turnstile and the container
|
|
38
|
-
platform are the only fakes.
|
|
53
|
+
platform are the only fakes. `start-page.test.mjs` drives the start page in
|
|
54
|
+
Chromium (default-seed's Playwright) through waiting, failure, Try again,
|
|
55
|
+
working and the signed-in landing. The end-to-end proof (`wrangler dev` with Docker)
|
|
39
56
|
is in DEMO.md.
|
|
40
57
|
|
|
41
58
|
Startup probes keep the existing 120-second budget, with a separate five-second
|
|
@@ -9,6 +9,11 @@ import { endedPage, clearCookie } from './pages.mjs';
|
|
|
9
9
|
// engine's egress worker refuse every send. The front signs the owner in
|
|
10
10
|
// through the existing signed owner claim. The demo ends at its hour or after
|
|
11
11
|
// 15 idle minutes: the alarm destroys the container and deletes everything.
|
|
12
|
+
// The platform stops a container about two minutes after its Durable Object's
|
|
13
|
+
// last event, when the object is evicted, and the exit watcher goes with it.
|
|
14
|
+
// So the alarm stays in flight until the demo's next check and then arms the
|
|
15
|
+
// next at once, as the Containers class keeps its object alive; a container
|
|
16
|
+
// that is gone anyway answers the ended page and frees its place.
|
|
12
17
|
const PORT = 8080, IDLE = 15 * 60_000, OWNER = 'owner@demo.invalid';
|
|
13
18
|
// The container's port speaks plain HTTP; the app takes its public origin from RER_INGRESS_ORIGIN.
|
|
14
19
|
const inside = url => `http://container${url.pathname}${url.search}`;
|
|
@@ -40,6 +45,7 @@ export class DemoContainer extends DurableObject {
|
|
|
40
45
|
startTimeout = 120_000;
|
|
41
46
|
probeTimeout = 5000;
|
|
42
47
|
cleanupRetry = 30_000;
|
|
48
|
+
hold = 3 * 60_000;
|
|
43
49
|
get container() { return this.ctx.container; }
|
|
44
50
|
port() { return this.container.getTcpPort(PORT); }
|
|
45
51
|
|
|
@@ -49,13 +55,13 @@ export class DemoContainer extends DurableObject {
|
|
|
49
55
|
const deadline = this.started + this.startTimeout;
|
|
50
56
|
const id = this.ctx.id.toString(), keys = await claimKeys(), now = Date.now();
|
|
51
57
|
await this.ctx.storage.put({ ends, seen: now, correlation, started: this.started });
|
|
52
|
-
await this.ctx.storage.setAlarm(Math.min(ends, now + this.idle));
|
|
53
58
|
report(correlation, this.started, 'start');
|
|
54
59
|
this.container.start({ enableInternet: false, env: { ...settings, RER_DEMO: '1', [originVar]: origin, RER_INGRESS_ORIGIN: origin,
|
|
55
60
|
SESSION_SECRET: random(), SETUP_TOKEN: random(), OWNER_EMAIL: OWNER, RER_OWNER_CLAIM_ISSUER: origin, RER_OWNER_CLAIM_INSTALLATION_ID: id,
|
|
56
61
|
RER_OWNER_CLAIM_PUBLIC_KEYS: JSON.stringify(keys.publicKeys), RER_DEMO_EXPIRES: endsLocal } });
|
|
57
62
|
// A container that stops by itself ends the demo too.
|
|
58
63
|
this.watch();
|
|
64
|
+
await this.ctx.storage.setAlarm(Date.now());
|
|
59
65
|
await this.healthy(deadline);
|
|
60
66
|
const token = await signClaim(keys, { origin, installationId: id, email: OWNER, now: Date.now() });
|
|
61
67
|
const claimed = await boundedFetch(this.port(), 'http://container/auth/owner-claim', { method: 'POST', redirect: 'manual',
|
|
@@ -94,17 +100,30 @@ export class DemoContainer extends DurableObject {
|
|
|
94
100
|
/** Every request carrying this demo's cookie: proxied while the demo lives, else the ended page. */
|
|
95
101
|
async fetch(request) {
|
|
96
102
|
const state = await this.ctx.storage.get(['ends', 'seen']), now = Date.now();
|
|
97
|
-
if (!(state.get('ends') > now)) return
|
|
103
|
+
if (!(state.get('ends') > now)) return this.ended();
|
|
104
|
+
if (!this.container.running) return this.gone();
|
|
98
105
|
if (now - state.get('seen') > 60_000) await this.ctx.storage.put('seen', now);
|
|
99
|
-
return this.port().fetch(new Request(inside(new URL(request.url)), request));
|
|
106
|
+
try { return await this.port().fetch(new Request(inside(new URL(request.url)), request)); }
|
|
107
|
+
catch (error) { if (this.container.running && !this.stopped) throw error; return this.gone(); }
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
ended() { return endedPage(this.env, { status: 410, headers: { 'set-cookie': clearCookie(this.env) } }); }
|
|
111
|
+
|
|
112
|
+
/** A container the platform stopped while nothing watched it: end the demo (the alarm retries a failed cleanup). */
|
|
113
|
+
async gone() {
|
|
114
|
+
this.record('exit', { outcome: 'gone' });
|
|
115
|
+
try { await this.end(); } catch (cause) { report(this.correlation, this.started, 'cleanup', { error: category(cause) }); }
|
|
116
|
+
return this.ended();
|
|
100
117
|
}
|
|
101
118
|
|
|
102
119
|
async alarm() {
|
|
103
120
|
const state = await this.ctx.storage.get(['ends', 'seen']), now = Date.now();
|
|
104
121
|
if (await this.ctx.storage.get('stopping')) return this.end();
|
|
105
122
|
if (!state.get('ends')) return;
|
|
106
|
-
|
|
107
|
-
|
|
123
|
+
const due = Math.min(state.get('ends'), state.get('seen') + this.idle);
|
|
124
|
+
if (now >= due || !this.container.running) return this.end();
|
|
125
|
+
await new Promise(resolve => { this.wake = resolve; setTimeout(resolve, Math.min(due - now, this.hold)); });
|
|
126
|
+
if (!this.stopped) await this.ctx.storage.setAlarm(Date.now());
|
|
108
127
|
}
|
|
109
128
|
|
|
110
129
|
/** Destroy the container and delete this demo's state and place; safe to repeat. */
|
|
@@ -115,7 +134,7 @@ export class DemoContainer extends DurableObject {
|
|
|
115
134
|
}
|
|
116
135
|
|
|
117
136
|
async cleanup() {
|
|
118
|
-
this.stopped = true;
|
|
137
|
+
this.stopped = true; this.wake?.();
|
|
119
138
|
// Keep the alarm and capacity reservation if destruction fails; retry cleanup.
|
|
120
139
|
await this.ctx.storage.put('stopping', true);
|
|
121
140
|
await this.ctx.storage.setAlarm(Date.now() + this.cleanupRetry);
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
// The demo host's two pages, from their 12ui designs: the start page (the
|
|
2
|
-
// Turnstile managed widget
|
|
2
|
+
// Turnstile managed widget starts the demo by itself, start-script.mjs) and the ended page.
|
|
3
3
|
// Both are one card in the family's quiet sign-in style.
|
|
4
|
+
import { START_SCRIPT } from './start-script.mjs';
|
|
5
|
+
|
|
4
6
|
const escape = value => String(value).replace(/[&<>"']/g, character => `&#${character.charCodeAt(0)};`);
|
|
5
7
|
|
|
6
8
|
const STYLE = `*{box-sizing:border-box}body{margin:0;background:#f2f5f7;color:#192333;font-family:system-ui,-apple-system,'Segoe UI',Arial,sans-serif;-webkit-font-smoothing:antialiased}
|
|
@@ -9,25 +11,23 @@ main{width:666px;margin:clamp(32px,18vh,184px) auto 48px}.card{padding:40px 42px
|
|
|
9
11
|
h1{font-size:42px;line-height:50px;letter-spacing:-1.3px;margin:0 0 14px;font-weight:700}.intro{font-size:20px;line-height:28px;color:#41516a;margin:0}
|
|
10
12
|
ul{padding:0;margin:23px 0 35px;list-style:none;color:#31415a;font-size:18px;line-height:33px}li{position:relative;padding-left:33px}li:before{content:'';position:absolute;left:7px;top:14px;width:7px;height:7px;background:#2b7864;border-radius:50%}
|
|
11
13
|
.notice{margin:0 0 16px;padding:12px 16px;border-radius:8px;background:#fdf6ec;color:#6b3d0f;font-size:16px;line-height:22px}
|
|
12
|
-
.cf-turnstile{min-height:65px}.button{display:
|
|
13
|
-
.button:disabled{
|
|
14
|
+
.cf-turnstile{min-height:65px}.button{display:flex;align-items:center;justify-content:center;gap:12px;width:100%;margin-top:28px;min-height:58px;border:1px solid #86a49f;border-radius:11px;background:linear-gradient(110deg,#225b51,#1e5148 60%,#20584d);color:#fff;font:inherit;font-size:20px;font-weight:700;line-height:26px;padding:15px;text-align:center;text-decoration:none;cursor:pointer}
|
|
15
|
+
.button:disabled{cursor:progress}[data-state=waiting] .button{background:#edf3f1;border-color:#78968f;color:#1b4d44;font-weight:600;cursor:default}
|
|
16
|
+
.spinner{display:none;flex:none;width:20px;height:20px;border:3px solid rgba(255,255,255,.35);border-top-color:#fff;border-radius:50%;animation:spin .8s linear infinite}[data-state=working] .spinner,[data-state=signing] .spinner{display:block}@keyframes spin{to{transform:rotate(360deg)}}
|
|
17
|
+
ol.steps{display:none;list-style:none;margin:22px auto 0;padding:0;width:max-content;max-width:100%;font-size:16px;line-height:22px;color:#50617e}[data-state=working] .steps,[data-state=signing] .steps,[data-state=slow] .steps{display:grid;gap:10px}[data-state=failed] .note{display:none}
|
|
18
|
+
.steps li{padding-left:30px;margin:0}.steps li:before{left:0;top:2px;width:18px;height:18px;box-sizing:border-box;background:none;border:2px solid #7f8da1}.steps [data-at=done]{color:#31415a}.steps [data-at=done]:before{content:'✓';border:0;background:#2b7864;color:#fff;font-size:12px;line-height:18px;font-weight:700;text-align:center}.steps [data-at=now]{color:#192333;font-weight:600}.steps [data-at=now]:before{border-color:#c9dcd7;border-top-color:#20574d;animation:spin .8s linear infinite}
|
|
19
|
+
.visually-hidden{position:absolute;width:1px;height:1px;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
|
|
20
|
+
@media(prefers-reduced-motion:reduce){.spinner,.steps [data-at=now]:before{animation:none}.steps [data-at=now]:before{border-color:#20574d}}.button:focus-visible,a:focus-visible{outline:3px solid #388c77;outline-offset:4px}
|
|
14
21
|
.note{font-size:15px;line-height:21px;color:#50617e;text-align:center;margin:21px 0 0}.secondary{text-align:center;margin:22px 0 0;font-size:18px;line-height:24px;font-weight:600}.secondary a{color:#1b554e;text-underline-offset:3px}
|
|
15
22
|
.back{text-align:center;margin:32px 0 0;font-size:15px;line-height:22px}.back a{color:#1b554e;text-underline-offset:3px}
|
|
16
23
|
.ended main{width:min(560px,calc(100% - 32px));margin-top:clamp(32px,26vh,262px)}.ended .card{padding:28px 36px 42px}.ended .brand{font-size:16px;margin-bottom:26px}.ended h1{font-size:36px;line-height:44px;margin-bottom:22px}.ended .intro{margin-bottom:36px}.ended .button{margin-top:0;font-size:18px}
|
|
17
24
|
@media(min-width:600px) and (max-width:1023px){main{width:calc(100% - 64px);max-width:666px;margin:100px auto 48px}.card{padding:36px}h1{font-size:38px;line-height:46px}.intro{font-size:18px;line-height:27px}}
|
|
18
|
-
@media(max-width:599px){main,.ended main{width:calc(100% - 32px);margin:32px auto}.ended .card{padding:26px 22px}.ended h1{font-size:29px;line-height:36px}.ended .intro{font-size:17px;line-height:25px;margin-bottom:28px}.card{padding:26px 22px;border-radius:16px}.brand{font-size:16px}h1{font-size:34px;line-height:41px;letter-spacing:-.8px}.intro{font-size:17px;line-height:25px}ul{font-size:16px;line-height:25px;margin:22px 0 26px}li{padding-left:22px;margin-bottom:9px}li:before{left:2px;top:9px}.button{font-size:18px;margin-top:22px}.note{font-size:13px;line-height:20px}.back{margin-top:24px;font-size:14px}}`;
|
|
19
|
-
|
|
20
|
-
// Starts the demo once Turnstile has passed: the widget put its token in the form.
|
|
21
|
-
// After a refused start the page waits for the visitor's own click instead.
|
|
22
|
-
const SCRIPT = `function rerDemoBusy(){document.querySelector('#start button').disabled=true;document.getElementById('status').textContent='Starting your demo…'}
|
|
23
|
-
function rerDemoStart(){rerDemoBusy();document.getElementById('start').submit()}
|
|
24
|
-
function rerDemoReady(){document.querySelector('#start button').disabled=false}
|
|
25
|
-
addEventListener('DOMContentLoaded',()=>document.getElementById('start').addEventListener('submit',rerDemoBusy))`;
|
|
25
|
+
@media(max-width:599px){main,.ended main{width:calc(100% - 32px);margin:32px auto}.ended .card{padding:26px 22px}.ended h1{font-size:29px;line-height:36px}.ended .intro{font-size:17px;line-height:25px;margin-bottom:28px}.card{padding:26px 22px;border-radius:16px}.brand{font-size:16px}h1{font-size:34px;line-height:41px;letter-spacing:-.8px}.intro{font-size:17px;line-height:25px}ul{font-size:16px;line-height:25px;margin:22px 0 26px}li{padding-left:22px;margin-bottom:9px}li:before{left:2px;top:9px}.button{font-size:18px;margin-top:22px}.note{font-size:13px;line-height:20px}.steps{font-size:15px}.back{margin-top:24px;font-size:14px}}`;
|
|
26
26
|
|
|
27
27
|
function html(env, { page, title, body, status = 200, headers = {}, turnstile = false }) {
|
|
28
28
|
const nonce = crypto.randomUUID().replaceAll('-', ''), site = new URL(env.DEMO_SITE);
|
|
29
|
-
const policy = `default-src 'none'; style-src 'nonce-${nonce}'; img-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'${turnstile ? `; script-src 'nonce-${nonce}' https://challenges.cloudflare.com; frame-src https://challenges.cloudflare.com; connect-src https://challenges.cloudflare.com` : ''}`;
|
|
30
|
-
return new Response(`<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex"><title>${escape(title)}</title><style nonce="${nonce}">${STYLE}</style>${turnstile ? `<script nonce="${nonce}">${
|
|
29
|
+
const policy = `default-src 'none'; style-src 'nonce-${nonce}'; img-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'${turnstile ? `; script-src 'nonce-${nonce}' https://challenges.cloudflare.com; frame-src https://challenges.cloudflare.com; connect-src 'self' https://challenges.cloudflare.com` : ''}`;
|
|
30
|
+
return new Response(`<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex"><title>${escape(title)}</title><style nonce="${nonce}">${STYLE}</style>${turnstile ? `<noscript><style nonce="${nonce}">#note{display:none}</style></noscript><script nonce="${nonce}">${START_SCRIPT}</script><script nonce="${nonce}" src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>` : ''}</head>
|
|
31
31
|
<body class="${page}"><main><section class="card" aria-labelledby="title"><div class="mark" aria-hidden="true"></div><p class="brand">${escape(env.DEMO_NAME)}</p>${body}</section><nav class="back" aria-label="Return"><a href="${escape(site.origin)}/">Back to ${escape(site.host)}</a></nav></main></body></html>`,
|
|
32
32
|
{ status, headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'content-security-policy': policy, 'referrer-policy': 'strict-origin', 'x-content-type-options': 'nosniff', ...headers } });
|
|
33
33
|
}
|
|
@@ -38,8 +38,10 @@ export function startPage(env, { status = 200, notice, headers = {} } = {}) {
|
|
|
38
38
|
return html(env, { page: 'start', title: `Try ${env.DEMO_NAME}`, status, headers, turnstile: true, body: `<h1 id="title">Try ${name}</h1>
|
|
39
39
|
<p class="intro">Your own copy of ${name}, signed in as its owner, with sample data.</p>
|
|
40
40
|
<ul><li>Nothing is sent: mail stays in an outbox.</li><li>It ends after an hour, or 15 idle minutes.</li><li>Then it is deleted. Nobody else can see it.</li></ul>
|
|
41
|
-
|
|
42
|
-
<button class="button" type="submit"
|
|
41
|
+
<p class="notice" id="notice" role="alert"${notice ? '' : ' hidden'}>${notice ? escape(notice) : ''}</p><form id="start" method="post" action="/__demo/start" data-auto="${notice ? '0' : '1'}"><div class="cf-turnstile" data-sitekey="${escape(env.TURNSTILE_SITE_KEY)}" data-size="flexible" data-callback="rerDemoVerified" data-before-interactive-callback="rerDemoInteractive" data-after-interactive-callback="rerDemoChecking" data-expired-callback="rerDemoExpired" data-error-callback="rerDemoCheckFailed"></div>
|
|
42
|
+
<button class="button" type="submit"><span class="spinner" aria-hidden="true"></span><span class="label">Start the demo</span></button>
|
|
43
|
+
<ol class="steps" aria-hidden="true"><li data-at="done">Checking you're human</li><li data-at="now">Starting a private copy</li><li data-at="next">Signing you in</li></ol>
|
|
44
|
+
<p class="note" id="note">Complete the human check to start your demo.</p><noscript><p class="note">The human check needs JavaScript. Turn it on to start the demo.</p></noscript><p class="visually-hidden" id="status" role="status"></p></form>` });
|
|
43
45
|
}
|
|
44
46
|
|
|
45
47
|
/** A demo whose hour or idle time is up: its container and data are gone. */
|
|
@@ -9,31 +9,36 @@ import { siteDeclaration } from '../deploy-kit/site.mjs';
|
|
|
9
9
|
* running the seed's own image (`rer build --platform container`, workerd
|
|
10
10
|
* engine), deployed by `wrangler deploy` with the image beside it. */
|
|
11
11
|
|
|
12
|
-
export const DEMO_FILES = ['worker.mjs', 'container.mjs', 'capacity.mjs', 'claim.mjs', 'pages.mjs', 'diagnostics.mjs', 'operator.mjs'];
|
|
12
|
+
export const DEMO_FILES = ['worker.mjs', 'container.mjs', 'capacity.mjs', 'claim.mjs', 'pages.mjs', 'start-script.mjs', 'diagnostics.mjs', 'operator.mjs'];
|
|
13
13
|
const FRONT_SET = /^(?:RER_.*|SESSION_SECRET|SETUP_TOKEN|OWNER_EMAIL)$/;
|
|
14
14
|
const SECRET = /SECRET|TOKEN|PASSWORD|_KEY$/;
|
|
15
|
+
// Cloudflare Containers' predefined instance types, smallest first (developers.cloudflare.com/containers/platform-details/limits).
|
|
16
|
+
export const INSTANCE_TYPES = ['lite', 'basic', 'standard-1', 'standard-2', 'standard-3', 'standard-4'];
|
|
15
17
|
|
|
16
18
|
/**
|
|
17
19
|
* deploy-demo.json: `{ "version": 1, "domain": "run-lamp.com", "name": "Lamp" }`, plus optionally
|
|
18
|
-
* `maxInstances` (concurrent demos, default 10)
|
|
19
|
-
* (such as MAIL_PROVIDER: "development").
|
|
20
|
+
* `maxInstances` (concurrent demos, default 10), `instanceType` (one of INSTANCE_TYPES, default
|
|
21
|
+
* "basic") and `settings`, the seed's plain demo settings (such as MAIL_PROVIDER: "development").
|
|
22
|
+
* Settings never carry secrets or what the front sets.
|
|
20
23
|
*/
|
|
21
24
|
export function demoDeclaration(value, originVar) {
|
|
22
|
-
assert(value && typeof value === 'object' && !Array.isArray(value) && value.version === 1 && Object.keys(value).every(key => ['version', 'domain', 'name', 'maxInstances', 'settings'].includes(key)), 'invalid-demo-declaration');
|
|
25
|
+
assert(value && typeof value === 'object' && !Array.isArray(value) && value.version === 1 && Object.keys(value).every(key => ['version', 'domain', 'name', 'maxInstances', 'instanceType', 'settings'].includes(key)), 'invalid-demo-declaration');
|
|
23
26
|
siteDeclaration({ version: 1, domain: value.domain });
|
|
24
27
|
assert(typeof value.name === 'string' && value.name.trim() === value.name && value.name.length > 0 && value.name.length <= 60 && !/[\p{Cc}\p{Cf}]/u.test(value.name), 'invalid-demo-name');
|
|
25
28
|
const maxInstances = value.maxInstances ?? 10;
|
|
26
29
|
assert(Number.isSafeInteger(maxInstances) && maxInstances >= 1 && maxInstances <= 100, 'invalid-demo-max-instances');
|
|
30
|
+
const instanceType = value.instanceType ?? 'basic';
|
|
31
|
+
assert(INSTANCE_TYPES.includes(instanceType), 'invalid-demo-instance-type');
|
|
27
32
|
const settings = value.settings ?? {};
|
|
28
33
|
assert(settings && typeof settings === 'object' && !Array.isArray(settings) && Object.entries(settings).every(([name, setting]) =>
|
|
29
34
|
/^[A-Z][A-Z0-9_]{0,63}$/.test(name) && !FRONT_SET.test(name) && !SECRET.test(name) && name !== originVar && typeof setting === 'string' && setting.length <= 1024), 'invalid-demo-settings');
|
|
30
|
-
return { domain: value.domain, name: value.name, maxInstances, settings };
|
|
35
|
+
return { domain: value.domain, name: value.name, maxInstances, instanceType, settings };
|
|
31
36
|
}
|
|
32
37
|
|
|
33
38
|
/** The demo Worker's name and its Wrangler configuration; no provider request. */
|
|
34
39
|
export function demoPlan({ project, environment, compatibilityDate, originVar, declaration, turnstileSiteKey }) {
|
|
35
40
|
assert(/^\d{4}-\d{2}-\d{2}$/.test(compatibilityDate ?? '') && /^[A-Z][A-Z0-9_]{0,63}$/.test(originVar ?? ''), 'invalid-plan');
|
|
36
|
-
const { domain, name, maxInstances, settings } = demoDeclaration(declaration, originVar);
|
|
41
|
+
const { domain, name, maxInstances, instanceType, settings } = demoDeclaration(declaration, originVar);
|
|
37
42
|
const worker = `${ownerWorkerName(project, environment)}--demo`, hostname = `demo.${domain}`, container = worker.replace(/-+/g, '-');
|
|
38
43
|
assert(resourceName(worker), 'owner-name-too-long');
|
|
39
44
|
// Rate limit namespaces are account-wide integers: one per demo Worker.
|
|
@@ -46,10 +51,10 @@ export function demoPlan({ project, environment, compatibilityDate, originVar, d
|
|
|
46
51
|
...(turnstileSiteKey ? { TURNSTILE_SITE_KEY: turnstileSiteKey } : {}) },
|
|
47
52
|
durable_objects: { bindings: [{ name: 'DEMO', class_name: 'DemoContainer' }, { name: 'CAPACITY', class_name: 'DemoCapacity' }] },
|
|
48
53
|
migrations: [{ tag: 'v1', new_sqlite_classes: ['DemoContainer', 'DemoCapacity'] }],
|
|
49
|
-
containers: [{ name: container, class_name: 'DemoContainer', image: './image/Dockerfile', max_instances: maxInstances, instance_type:
|
|
54
|
+
containers: [{ name: container, class_name: 'DemoContainer', image: './image/Dockerfile', max_instances: maxInstances, instance_type: instanceType }],
|
|
50
55
|
ratelimits: [{ name: 'STARTS', namespace_id: namespace, simple: { limit: 3, period: 60 } }],
|
|
51
56
|
};
|
|
52
|
-
return { worker, hostname, container, record: demoRecord({ worker, hostname, container }), origin: `https://${hostname}`, maxInstances, settings: Object.keys(settings), wrangler };
|
|
57
|
+
return { worker, hostname, container, record: demoRecord({ worker, hostname, container }), origin: `https://${hostname}`, maxInstances, instanceType, settings: Object.keys(settings), wrangler };
|
|
53
58
|
}
|
|
54
59
|
|
|
55
60
|
/** The demo's record of what `rer deploy --demo` creates, kept on the provider so a
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// The start page's script. Once Turnstile passes it starts the demo with fetch
|
|
2
|
+
// (Accept: application/json), so the visitor sees each step: the check, their
|
|
3
|
+
// private copy starting, and the sign-in. A refusal, a network failure or a start
|
|
4
|
+
// past 25 seconds is said plainly with a Try again that runs a new check. On a
|
|
5
|
+
// refusal page the server rendered (data-auto="0") the visitor presses Start
|
|
6
|
+
// instead. Turnstile renewing its token later never starts a demo by itself.
|
|
7
|
+
// Without JavaScript the form posts as a plain form.
|
|
8
|
+
export const START_SCRIPT = `(()=>{
|
|
9
|
+
const SLOW=25000,LONG=12000;
|
|
10
|
+
let page,attempt,timers=[];
|
|
11
|
+
const el=()=>page??=(form=>({form,button:form.querySelector('.button'),label:form.querySelector('.label'),steps:[...form.querySelectorAll('.steps li')],note:document.getElementById('note'),live:document.getElementById('status'),notice:document.getElementById('notice'),auto:form.dataset.auto==='1'}))(document.getElementById('start'));
|
|
12
|
+
function show(state,{label,note,live,step,notice}){
|
|
13
|
+
const p=el();
|
|
14
|
+
p.form.dataset.state=state;
|
|
15
|
+
p.button.disabled=!['ready','slow','failed'].includes(state);
|
|
16
|
+
p.label.textContent=label;
|
|
17
|
+
if(note!==undefined)p.note.textContent=note;
|
|
18
|
+
if(live!==undefined)p.live.textContent=live;
|
|
19
|
+
if(step!==undefined)p.steps.forEach((item,index)=>item.dataset.at=index<step?'done':index===step?'now':'next');
|
|
20
|
+
if(notice!==undefined){p.notice.textContent=notice;p.notice.hidden=!notice}
|
|
21
|
+
}
|
|
22
|
+
function waiting(){
|
|
23
|
+
const auto=el().auto;
|
|
24
|
+
show('waiting',{label:'Waiting for the human check…',note:auto?'Your demo will open automatically when ready.':'Once the check passes, press Start the demo.'});
|
|
25
|
+
}
|
|
26
|
+
function stop(){timers.forEach(clearTimeout);timers=[]}
|
|
27
|
+
async function go(){
|
|
28
|
+
const p=el(),controller=attempt=new AbortController();
|
|
29
|
+
show('working',{label:'Starting your demo…',note:'Your demo will open automatically when ready.',live:'Check passed. Starting a private copy.',step:1,notice:''});
|
|
30
|
+
timers.push(setTimeout(()=>p.note.textContent='Taking a little longer than usual. Still starting…',LONG));
|
|
31
|
+
timers.push(setTimeout(()=>show('slow',{label:'Try again',note:'Still starting. It will open by itself if it finishes.',notice:'This is taking longer than it should. Keep waiting, or try again.'}),SLOW));
|
|
32
|
+
try{
|
|
33
|
+
const response=await fetch(p.form.action,{method:'POST',body:new URLSearchParams(new FormData(p.form)),headers:{accept:'application/json'},signal:controller.signal});
|
|
34
|
+
const result=await response.json().catch(()=>({}));
|
|
35
|
+
if(attempt!==controller)return;
|
|
36
|
+
stop();
|
|
37
|
+
if(response.ok&&typeof result.location==='string'){
|
|
38
|
+
show('signing',{label:'Starting your demo…',note:'Opening your demo…',live:'Your copy is running. Signing you in…',step:2,notice:''});
|
|
39
|
+
location.assign(result.location);
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
show('failed',{label:'Try again',note:'',live:'',notice:result.notice||'The demo did not start. Try again.'});
|
|
43
|
+
}catch{
|
|
44
|
+
if(attempt!==controller)return;
|
|
45
|
+
stop();
|
|
46
|
+
show('failed',{label:'Try again',note:'',live:'',notice:'The demo could not be reached. Check your connection, then try again.'});
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
function again(){
|
|
50
|
+
attempt?.abort();attempt=null;stop();
|
|
51
|
+
el().auto=true;
|
|
52
|
+
show('waiting',{label:'Waiting for the human check…',note:'Running the check again. The demo starts by itself once it passes.',live:'Running the human check again.',notice:''});
|
|
53
|
+
turnstile.reset(el().form.querySelector('.cf-turnstile'));
|
|
54
|
+
}
|
|
55
|
+
// Turnstile's callbacks; once a start is under way only a new check (Try again) changes the page.
|
|
56
|
+
const checking=()=>['waiting','ready'].includes(el().form.dataset.state);
|
|
57
|
+
window.rerDemoVerified=()=>checking()&&(el().auto?go():show('ready',{label:'Start the demo',note:'Check passed. Press Start the demo.',live:'Check passed. Press Start the demo.'}));
|
|
58
|
+
window.rerDemoInteractive=()=>checking()&&show('waiting',{label:'Waiting for the human check…',note:'Tick the box above to show you are human.',live:'Tick the box above to show you are human.'});
|
|
59
|
+
window.rerDemoChecking=()=>checking()&&waiting();
|
|
60
|
+
window.rerDemoExpired=()=>checking()&&waiting();
|
|
61
|
+
window.rerDemoCheckFailed=()=>checking()&&show('failed',{label:'Try again',note:'',live:'',notice:'The human check did not load. Try again.'});
|
|
62
|
+
addEventListener('DOMContentLoaded',()=>{
|
|
63
|
+
if(!el().form.dataset.state)waiting();
|
|
64
|
+
el().form.addEventListener('submit',event=>{
|
|
65
|
+
event.preventDefault();
|
|
66
|
+
const state=el().form.dataset.state;
|
|
67
|
+
if(state==='ready')go();
|
|
68
|
+
else if(state==='slow'||state==='failed')again();
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
})()`;
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
// A seed's hosted demo at demo.<domain>, generated by `rer deploy --demo`.
|
|
2
|
-
// GET / shows the start page (a Turnstile managed widget that
|
|
2
|
+
// GET / shows the start page (a Turnstile managed widget that starts the demo by itself).
|
|
3
3
|
// POST /__demo/start checks the visitor's IP rate limit, Turnstile and capacity,
|
|
4
4
|
// then starts a container of their own, signs its owner in and sets the
|
|
5
|
-
// rer_demo cookie.
|
|
5
|
+
// rer_demo cookie. The page's script asks for JSON (Accept: application/json) to
|
|
6
|
+
// show its progress and failures; a plain form post gets the 303 or the page. Every request with that cookie goes to the visitor's
|
|
6
7
|
// container; nothing else on this host is reachable.
|
|
7
8
|
import { operatorPage } from './operator.mjs';
|
|
8
9
|
import { bounded, category, report } from './diagnostics.mjs';
|
|
@@ -39,20 +40,24 @@ async function human(env, token, ip) {
|
|
|
39
40
|
}
|
|
40
41
|
|
|
41
42
|
async function start(request, env) {
|
|
42
|
-
|
|
43
|
+
const json = request.headers.get('accept') === 'application/json';
|
|
44
|
+
const refuse = (status, notice, headers = {}) => json ? Response.json({ notice }, { status, headers: { 'cache-control': 'no-store', ...headers } }) : startPage(env, { status, notice, headers });
|
|
45
|
+
if (request.headers.get('origin') !== env.DEMO_ORIGIN) return refuse(403, 'Start the demo from this page.');
|
|
43
46
|
const ip = request.headers.get('cf-connecting-ip') ?? '';
|
|
44
|
-
if (!(await env.STARTS.limit({ key: ip })).success) return
|
|
47
|
+
if (!(await env.STARTS.limit({ key: ip })).success) return refuse(429, 'Too many demos started from your network. Try again in a minute.');
|
|
45
48
|
const form = await request.formData();
|
|
46
|
-
if (!await human(env, form.get('cf-turnstile-response'), ip)) return
|
|
49
|
+
if (!await human(env, form.get('cf-turnstile-response'), ip)) return refuse(403, 'The check did not pass. Try again.');
|
|
47
50
|
const id = env.DEMO.newUniqueId(), ends = Date.now() + HOUR;
|
|
48
51
|
if (!await env.CAPACITY.get(env.CAPACITY.idFromName('capacity')).acquire(id.toString(), ends, Number(env.DEMO_MAX_INSTANCES))) {
|
|
49
|
-
return
|
|
52
|
+
return refuse(503, 'Every demo is in use right now. Try again in a few minutes.');
|
|
50
53
|
}
|
|
51
54
|
const demo = env.DEMO.get(id), correlation = crypto.randomUUID(), started = Date.now();
|
|
52
55
|
try {
|
|
53
56
|
const signedIn = await bounded(demo.start({ correlation, origin: env.DEMO_ORIGIN, originVar: env.DEMO_ORIGIN_VAR, ends, endsLocal: localTime(ends, request.cf?.timezone), settings: JSON.parse(env.DEMO_SETTINGS) }), 121_000);
|
|
54
|
-
const headers = new Headers({
|
|
57
|
+
const headers = new Headers({ 'cache-control': 'no-store', 'x-rer-demo-correlation': correlation });
|
|
55
58
|
for (const cookie of [...signedIn.cookies, demoCookie(env, id.toString())]) headers.append('set-cookie', cookie);
|
|
59
|
+
if (json) return Response.json({ location: signedIn.location }, { headers });
|
|
60
|
+
headers.set('location', signedIn.location);
|
|
56
61
|
return new Response(null, { status: 303, headers });
|
|
57
62
|
} catch (error) {
|
|
58
63
|
const failure = ['health-deadline', 'container-stopped'].includes(error.message) ? error.message : category(error);
|
|
@@ -62,7 +67,7 @@ async function start(request, env) {
|
|
|
62
67
|
await bounded(env.CAPACITY.get(env.CAPACITY.idFromName('diagnostics')).record(correlation, diagnostic), 3000);
|
|
63
68
|
} catch (capture) { report(correlation, started, 'diagnostic', { error: category(capture) }); }
|
|
64
69
|
try { await bounded(demo.end(), 6000); } catch (cleanup) { report(correlation, started, 'cleanup', { error: category(cleanup) }); }
|
|
65
|
-
return
|
|
70
|
+
return refuse(502, 'The demo did not start. Try again.', { 'x-rer-demo-correlation': correlation });
|
|
66
71
|
}
|
|
67
72
|
}
|
|
68
73
|
|