@runeditrun/rer 0.2.13 → 0.2.15

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.
@@ -1,5 +1,23 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.15
4
+
5
+ - 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.
6
+ - 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.
7
+
8
+ ### Upgrade notes
9
+
10
+ - 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.
11
+
12
+ ## 0.2.14
13
+
14
+ - 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.
15
+ - Container packaging requires configured Durable Objects to be local and exported by the built Worker. External namespace bindings and missing exports fail before packaging. Raw sockets and the existing container isolation restrictions remain refused.
16
+
17
+ ### Upgrade notes
18
+
19
+ - Update rer and rebuild the demo image to receive the workerd admission fix. Durable Object namespaces still need local Wrangler bindings and exported classes. Allowing `WebSocketPair` does not add WebSocket upgrade handling to the container HTTP host.
20
+
3
21
  ## 0.2.13
4
22
 
5
23
  - `rer deploy --remove` accepts empty owned R2 object listings without pagination metadata, fixing the 0.2.9 regression. Populated or malformed listings still require complete pagination proof before deletion.
@@ -12,11 +12,37 @@ at the intended memory limit. A retained-public-snapshot cache contract is
12
12
  selected through `cacheContract` when the seed implements that contract. This
13
13
  is not a general Durable Object adapter. A seed requiring KV or other
14
14
  Cloudflare-only APIs cannot use Node.
15
- The import boundary rejects those APIs and new Cloudflare imports outside the
15
+ For Node, the import boundary rejects those APIs and new Cloudflare imports outside the
16
16
  platform binding/cache boundary. The one other file it admits is an exported
17
17
  seed's demo guard, `src/modules/demo/index.mjs`, and there only
18
18
  `import { env } from 'cloudflare:workers'` (it reads `RER_DEMO`).
19
19
 
20
+ The workerd engine admits exact `cloudflare:workers` static imports, literal
21
+ dynamic imports and re-exports, plus `HTMLRewriter`, `WebSocketPair`,
22
+ `crypto.subtle.timingSafeEqual` and `ctx.passThroughOnException`. Other
23
+ `cloudflare:` modules (including sockets), `require()` or arbitrary calls with
24
+ Cloudflare module strings, `email()`, `caches.default` and `request.cf` remain
25
+ outside the container boundary.
26
+ Other Cloudflare modules have no admitted host adapters; raw sockets would also
27
+ bypass the host's routed fetch egress. Native `email()` has no configured host
28
+ delivery, `caches.default` has no declared container cache contract, and the host
29
+ disables request CF metadata (`cf: false`). The module import rule admits native
30
+ ES module loading, not arbitrary calls carrying module strings. Admitting
31
+ `WebSocketPair` does not add HTTP upgrade transport or qualify a complete live
32
+ WebSocket flow through the container host.
33
+
34
+ The workerd source boundary permits Durable Object definitions, including export
35
+ aliases and indirect inheritance. Unbound definitions create no namespace. The
36
+ seed's Vite build selects and renders its configuration; before packaging, the
37
+ container builder checks each namespace in the emitted
38
+ `dist/server/wrangler.json`. It rejects `script_name` and `environment`, because
39
+ the host binds only local namespaces, and requires each configured class name in
40
+ the bundler's exports for the emitted Worker entry. This validates the binding
41
+ contract without inferring source class names. Workerd readiness alone does not
42
+ reject a missing class export; actual class behavior still needs runtime
43
+ qualification. Node's binding, retained-cache and demo-guard exceptions are
44
+ unchanged.
45
+
20
46
  The entrypoint holds a Linux kernel `flock` for the lifetime of the host. Each
21
47
  installation has one local data volume and one writer. The lock inode retains
22
48
  PID/heartbeat diagnostics and is never unlinked. The host applies hashed
@@ -21,15 +21,15 @@ export async function checkBoundary(root, { engine='node', cacheContract }={}) {
21
21
  if(module.startsWith('cloudflare:')){
22
22
  const imports=node.importClause?.namedBindings;
23
23
  const allowed=module==='cloudflare:workers'&&imports&&ts.isNamedImports(imports)&&imports.elements.every(element=>(demo&&!node.importClause.name&&!element.propertyName&&element.name.text==='env')||(bindings&&(element.propertyName??element.name).text==='env')||(cache&&(element.propertyName??element.name).text==='DurableObject'));
24
- if(!allowed)fail('Cloudflare import outside binding/cache contract');
24
+ if(!allowed&&!(engine==='workerd'&&module==='cloudflare:workers'))fail('Cloudflare import outside binding/cache contract');
25
25
  }
26
26
  }
27
- if(ts.isCallExpression(node)&&node.arguments.some(arg=>ts.isStringLiteral(arg)&&arg.text.startsWith('cloudflare:')))fail('Dynamic Cloudflare import');
28
- if(ts.isIdentifier(node)&&(['WebSocketPair','passThroughOnException','timingSafeEqual'].includes(node.text)||(node.text==='HTMLRewriter'&&engine!=='workerd')))fail(node.text);
27
+ if(ts.isCallExpression(node)&&node.arguments.some((arg,index)=>ts.isStringLiteral(arg)&&arg.text.startsWith('cloudflare:')&&!(engine==='workerd'&&node.expression.kind===ts.SyntaxKind.ImportKeyword&&index===0&&arg.text==='cloudflare:workers')))fail('Dynamic Cloudflare import');
28
+ if(ts.isIdentifier(node)&&engine!=='workerd'&&['WebSocketPair','passThroughOnException','timingSafeEqual','HTMLRewriter'].includes(node.text))fail(node.text);
29
29
  if(ts.isCallExpression(node)&&ts.isIdentifier(node.expression)&&node.expression.text==='email'&&!localNames.has('email'))fail('email()');
30
30
  if(ts.isPropertyAccessExpression(node)&&((node.expression.getText(tree)==='caches'&&node.name.text==='default')||(node.expression.getText(tree)==='request'&&node.name.text==='cf')))fail(node.getText(tree));
31
31
  if(ts.isElementAccessExpression(node)&&ts.isStringLiteral(node.argumentExpression)&&((node.expression.getText(tree)==='caches'&&node.argumentExpression.text==='default')||(node.expression.getText(tree)==='request'&&node.argumentExpression.text==='cf')))fail(node.getText(tree));
32
- if(ts.isHeritageClause(node)&&node.token===ts.SyntaxKind.ExtendsKeyword&&node.types.some(type=>/DurableObject/.test(type.expression.getText(tree)))&&!cache)fail('New Durable Object');
32
+ if(engine!=='workerd'&&ts.isHeritageClause(node)&&node.token===ts.SyntaxKind.ExtendsKeyword&&node.types.some(type=>/DurableObject/.test(type.expression.getText(tree)))&&!cache)fail('New Durable Object');
33
33
  ts.forEachChild(node,visit);
34
34
  }
35
35
  visit(tree);
@@ -1,11 +1,12 @@
1
- import { readFile, writeFile, readdir, cp, mkdir, rm } from 'node:fs/promises';
2
- import { join, resolve } from 'node:path';
1
+ import { readFile, writeFile, readdir, realpath, cp, mkdir, rm } from 'node:fs/promises';
2
+ import { dirname, join, resolve } from 'node:path';
3
3
  import { createRequire } from 'node:module';
4
4
  import { pathToFileURL } from 'node:url';
5
5
  import { createHash } from 'node:crypto';
6
6
  import { parseJsonc } from '../../cli/jsonc.mjs';
7
7
  import { portabilityPlan } from './portability-schema.mjs';
8
8
  import { checkBoundary } from './boundary.mjs';
9
+ import { localDurableObjects } from './durable-objects.mjs';
9
10
  import { readMigrationRewrites, withRewrites } from '../deploy-kit/migrations.mjs';
10
11
  const hash = source => createHash('sha256').update(source).digest('hex');
11
12
  export async function buildContainer(root, options={}) {
@@ -21,6 +22,13 @@ async function buildImage(root, { output = join(root,'.rer/container/image'), en
21
22
  const vite = await import(pathToFileURL(require.resolve('vite'))), loaded = await vite.loadConfigFromFile({ command:'build',mode:'production' },undefined,root);
22
23
  if (!loaded) throw new Error('Vite configuration missing');
23
24
  const config = loaded.config;
25
+ const outputExports = new Map();
26
+ if (engine === 'workerd') config.plugins = [...(config.plugins ?? []), {
27
+ name:'rer-container-exports',
28
+ async writeBundle(output,bundle) {
29
+ for (const chunk of Object.values(bundle)) if (chunk.type === 'chunk' && chunk.isEntry) outputExports.set(await realpath(resolve(root,output.dir ?? dirname(output.file),chunk.fileName)),new Set(chunk.exports));
30
+ },
31
+ }];
24
32
  if (engine === 'node') {
25
33
  const plugins = (await Promise.all(config.plugins.flat(Infinity))).filter(plugin => plugin && !plugin.name.startsWith('vite-plugin-cloudflare') && plugin.name !== 'tanstack-start-core:post-build');
26
34
  const bindingShim = resolve(import.meta.dirname,'bindings.mjs');
@@ -34,7 +42,10 @@ async function buildImage(root, { output = join(root,'.rer/container/image'), en
34
42
  // Apply the same local-only bundle guard before packaging any container image.
35
43
  await (await import('../../cli/dev-identity.mjs')).refuseDevLayerOutput(root);
36
44
  let workerConfig;
37
- if (engine === 'workerd') workerConfig = JSON.parse(await readFile(join(root,'dist/server/wrangler.json'),'utf8'));
45
+ if (engine === 'workerd') {
46
+ workerConfig = JSON.parse(await readFile(join(root,'dist/server/wrangler.json'),'utf8'));
47
+ localDurableObjects(workerConfig,outputExports.get(await realpath(resolve(root,'dist/server',workerConfig.main))));
48
+ }
38
49
  else workerConfig = parseJsonc(await readFile(join(root,'wrangler.jsonc'),'utf8'));
39
50
  const { unstable_splitSqlQuery:split } = require('wrangler');
40
51
  const migrations = {}, rewrites = await readMigrationRewrites(root);
@@ -0,0 +1,15 @@
1
+ // worker-engine binds every namespace to a class in this Worker. Never silently
2
+ // reinterpret a cross-worker namespace as a local one. Check the bundler's actual
3
+ // entry exports: workerd readiness alone does not reject missing class exports.
4
+ export function localDurableObjects(config, exports) {
5
+ const bindings=config.durable_objects?.bindings??[];
6
+ if(!Array.isArray(bindings))throw new Error('Container Durable Object bindings must be an array');
7
+ for(const binding of bindings) {
8
+ if(!binding||typeof binding.name!=='string'||!binding.name||typeof binding.class_name!=='string'||!binding.class_name)throw new Error('Container Durable Object binding requires name and class_name');
9
+ if(Object.hasOwn(binding,'script_name')||Object.hasOwn(binding,'environment'))throw new Error('Container Durable Object bindings do not support script_name or environment');
10
+ }
11
+ const classes=new Set(bindings.map(binding=>binding.class_name));
12
+ if(classes.size&&!exports)throw new Error('Built container Worker entry exports are unavailable');
13
+ for(const name of classes)if(!exports.has(name))throw new Error('Built container Worker does not export configured Durable Object class: '+name);
14
+ return classes;
15
+ }
@@ -23,6 +23,14 @@ it with these files and the seed's container image folder (workerd engine) to
23
23
  container that stops by itself ends its demo too.
24
24
  - `capacity.mjs`: `DemoCapacity` admits at most `max_instances` live demos.
25
25
  - `pages.mjs`: the start and ended pages (12ui designs), strict CSP.
26
+ `start-script.mjs` is the start page's script: once Turnstile passes it
27
+ posts the form with `Accept: application/json` (the Worker then answers
28
+ `{ location }` with the cookies, or `{ notice }` with the refusal's status)
29
+ and shows each step: the check, the private copy starting, the sign-in. A
30
+ refusal, a network failure or a start past 25 seconds is shown with Try
31
+ again, which runs a new check; progress is announced through a
32
+ `role="status"` region and failures through `role="alert"`. Without
33
+ JavaScript the form posts as before and gets the 303 or the page.
26
34
  - `remove.mjs`: `rer deploy --demo --remove --yes`. The deploy passes the
27
35
  demo's record (`plan.record`) to `wrangler deploy --message`; removal takes
28
36
  the Worker for the demo's only while it serves that version, the Custom
@@ -35,7 +43,9 @@ it with these files and the seed's container image folder (workerd engine) to
35
43
 
36
44
  `node --test modules/demo-host/tests/*.test.mjs` runs the Worker in workerd
37
45
  with its real Durable Objects and rate limit; Turnstile and the container
38
- platform are the only fakes. The end-to-end proof (`wrangler dev` with Docker)
46
+ platform are the only fakes. `start-page.test.mjs` drives the start page in
47
+ Chromium (default-seed's Playwright) through waiting, failure, Try again,
48
+ working and the signed-in landing. The end-to-end proof (`wrangler dev` with Docker)
39
49
  is in DEMO.md.
40
50
 
41
51
  Startup probes keep the existing 120-second budget, with a separate five-second
@@ -1,6 +1,8 @@
1
1
  // The demo host's two pages, from their 12ui designs: the start page (the
2
- // Turnstile managed widget submits the form by itself) and the ended page.
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:block;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}
13
- .button:disabled{opacity:.7;cursor:progress}.button:focus-visible,a:focus-visible{outline:3px solid #388c77;outline-offset:4px}
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}">${SCRIPT}</script><script nonce="${nonce}" src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>` : ''}</head>
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
- ${notice ? `<p class="notice" role="alert">${escape(notice)}</p>` : ''}<form id="start" method="post" action="/__demo/start"><div class="cf-turnstile" data-sitekey="${escape(env.TURNSTILE_SITE_KEY)}" data-size="flexible" data-callback="${notice ? 'rerDemoReady' : 'rerDemoStart'}"></div>
42
- <button class="button" type="submit" disabled>Start the demo</button><p class="note" id="status" role="status">Starts by itself once the check passes. Takes about ten seconds.</p></form>` });
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,7 +9,7 @@ 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
15
 
@@ -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 submits itself).
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. Every request with that cookie goes to the visitor's
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
- if (request.headers.get('origin') !== env.DEMO_ORIGIN) return startPage(env, { status: 403, notice: 'Start the demo from this page.' });
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 startPage(env, { status: 429, notice: 'Too many demos started from your network. Try again in a minute.' });
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 startPage(env, { status: 403, notice: 'The check did not pass. Try again.' });
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 startPage(env, { status: 503, notice: 'Every demo is in use right now. Try again in a few minutes.' });
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({ location: signedIn.location, 'cache-control': 'no-store', 'x-rer-demo-correlation': correlation });
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 startPage(env, { status: 502, headers: { 'x-rer-demo-correlation': correlation }, notice: 'The demo did not start. Try again.' });
70
+ return refuse(502, 'The demo did not start. Try again.', { 'x-rer-demo-correlation': correlation });
66
71
  }
67
72
  }
68
73
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runeditrun/rer",
3
- "version": "0.2.13",
3
+ "version": "0.2.15",
4
4
  "description": "The rer command: install, set up, run and launch Run Edit Run checkouts.",
5
5
  "license": "MIT",
6
6
  "type": "module",