@runeditrun/rer 0.2.24 → 0.2.26

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.
Files changed (65) hide show
  1. package/README.md +16 -7
  2. package/cli/browser-runtime.mjs +65 -0
  3. package/cli/demo-host.mjs +31 -5
  4. package/cli/deploy-claim-request.mjs +5 -4
  5. package/cli/deploy-command.mjs +3 -3
  6. package/cli/deploy-inputs.mjs +2 -1
  7. package/cli/deploy.mjs +16 -4
  8. package/cli/export.mjs +1 -1
  9. package/cli/hosted-mail.mjs +23 -0
  10. package/cli/hosted-output.mjs +6 -2
  11. package/cli/hydration/browser.mjs +3 -9
  12. package/cli/inspect.mjs +3 -1
  13. package/cli/lifecycle.mjs +4 -1
  14. package/global/CHANGELOG.md +36 -0
  15. package/global/README.md +16 -7
  16. package/global/browser-runtime.mjs +45 -0
  17. package/global/cli/layout.mjs +8 -4
  18. package/global/main.mjs +13 -3
  19. package/install.sh +56 -3
  20. package/modules/container/README.md +11 -0
  21. package/modules/container/build.mjs +2 -1
  22. package/modules/container/demo-egress.mjs +15 -2
  23. package/modules/container/image-variables.mjs +27 -0
  24. package/modules/container/worker-engine.mjs +2 -2
  25. package/modules/delivery-producer/declarations.mjs +6 -1
  26. package/modules/delivery-producer/mail.mjs +66 -0
  27. package/modules/demo/label.mjs +5 -2
  28. package/modules/demo-host/README.md +9 -2
  29. package/modules/demo-host/certificate.mjs +56 -0
  30. package/modules/demo-host/measurement.mjs +19 -0
  31. package/modules/demo-host/operator.mjs +11 -6
  32. package/modules/demo-host/plan.mjs +1 -1
  33. package/modules/demo-host/worker.mjs +2 -0
  34. package/modules/deploy-kit/README.md +6 -4
  35. package/modules/deploy-kit/asset-health.mjs +28 -0
  36. package/modules/deploy-kit/d1-import.mjs +22 -4
  37. package/modules/deploy-kit/diagnostics.mjs +30 -0
  38. package/modules/deploy-kit/health.mjs +2 -23
  39. package/modules/deploy-kit/migration-ledger.mjs +6 -2
  40. package/modules/deploy-kit/migration-retry.mjs +91 -0
  41. package/modules/deploy-kit/migrations.mjs +9 -5
  42. package/modules/deploy-kit/owner-cli.mjs +6 -3
  43. package/modules/deploy-kit/owner-remove.mjs +87 -65
  44. package/modules/deploy-kit/provider-transport.mjs +28 -5
  45. package/modules/deploy-kit/provider.mjs +9 -6
  46. package/modules/deploy-kit/worker.mjs +5 -2
  47. package/modules/mail/README.md +18 -2
  48. package/modules/mail/src/adapters/rer/contract.mjs +5 -2
  49. package/modules/mail/src/adapters/rer/list-headers.mjs +44 -0
  50. package/modules/mail/src/core/validation.mjs +5 -2
  51. package/modules/mail/src/sender.mjs +1 -1
  52. package/modules/mail/src/unsubscribe/index.mjs +5 -5
  53. package/modules/operator-auth/README.md +10 -2
  54. package/modules/operator-auth/config.mjs +1 -0
  55. package/modules/operator-auth/conformance/presentation.mjs +2 -2
  56. package/modules/operator-auth/identity/email-link/confirmation.mjs +2 -1
  57. package/modules/operator-auth/identity/email-link/expiry.mjs +8 -0
  58. package/modules/operator-auth/identity/email-link/index.mjs +2 -1
  59. package/modules/operator-auth/identity/email-link/message.mjs +3 -2
  60. package/modules/operator-auth/index.d.mts +2 -0
  61. package/modules/portability/README.md +7 -2
  62. package/modules/portability/import-staging.mjs +45 -0
  63. package/modules/portability/import.mjs +8 -8
  64. package/modules/portability/storage.mjs +5 -2
  65. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
1
  // Where a user install lives. Data: ${XDG_DATA_HOME:-$HOME/.local/share}/rer,
2
2
  // as immutable versions/<version>-<digest8> directories and a `current` link.
3
- // Launcher: $HOME/.local/bin/rer, a POSIX sh script that runs node from PATH.
3
+ // Launcher: $HOME/.local/bin/rer, using the installer's private Node when present.
4
4
  import { readFile, lstat } from 'node:fs/promises';
5
5
  import { homedir } from 'node:os';
6
6
  import { join } from 'node:path';
@@ -15,14 +15,18 @@ export function layout(env = process.env) {
15
15
  const marker = '# rer launcher, written by `rer cli install` (@runeditrun/rer). Do not edit.';
16
16
  const quote = value => `'${value.replaceAll("'", `'\\''`)}'`;
17
17
 
18
- // No absolute Node path is baked in, so a Node upgrade never breaks it.
18
+ // The managed runtime stays inside the install root; npx installs use PATH.
19
19
  export function launcherScript(data) {
20
20
  return `#!/bin/sh
21
21
  ${marker}
22
- # It runs the installed version with the node on PATH.
22
+ # It uses the installer's private Node when present, otherwise Node on PATH.
23
23
  root=${quote(data)}
24
+ if [ -x "$root/node/bin/node" ]; then
25
+ PATH="$root/node/bin:$PATH"
26
+ export PATH
27
+ fi
24
28
  if ! command -v node >/dev/null 2>&1; then
25
- echo "rer: node is not on PATH. Install Node 22 or later, then run rer again." >&2
29
+ echo "rer: Node is missing. Run: curl -fsSL https://runeditrun.com/install.sh | sh" >&2
26
30
  exit 127
27
31
  fi
28
32
  exec node "$root/current/global/rer.mjs" "$@"
package/global/main.mjs CHANGED
@@ -36,7 +36,7 @@ import, doctor, describe, check, release. Run rer VERB --help in a checkout for
36
36
 
37
37
  // The checkout verbs that install the pinned package before they run when
38
38
  // node_modules holds another version or none (dev installs it in its launch).
39
- const installsFirst = new Set([...Object.keys(verbs), 'signin', 'release'].filter(verb => verb !== 'dev'));
39
+ const installsFirst = new Set([...Object.keys(verbs), 'signin', 'release'].filter(verb => !['dev', 'doctor'].includes(verb)));
40
40
 
41
41
  export async function main(argv) {
42
42
  handleBrokenPipes();
@@ -51,7 +51,7 @@ export async function main(argv) {
51
51
  delete process.env[localDefaults];
52
52
  if (verb === 'update') return (await import('./update/command.mjs')).update(argv.slice(1));
53
53
  const notice = await import('./update/notice.mjs');
54
- if (notice.wantsNotice(argv)) await notice.updateNotice();
54
+ if (verb !== 'doctor' && notice.wantsNotice(argv)) await notice.updateNotice();
55
55
  if (!verb || verb === '--help' || verb === '-h' || verb === 'help') { process.stdout.write(help); return 0; }
56
56
  if (verb === 'cli') return (await import('./cli/command.mjs')).cliCommand(argv.slice(1));
57
57
  if (verb === 'list') return (await import('./list.mjs')).listCommand(argv.slice(1));
@@ -65,6 +65,13 @@ export async function main(argv) {
65
65
  const { jobsDirectory } = await import('../modules/job-queue/config.mjs');
66
66
  process.env.RER_SERVERS_DIR = serversDirectory(process.env);
67
67
  process.env.RER_JOBS_DIR = jobsDirectory(process.env);
68
+ if ((mode !== 'bundled' || pinnedPackage(target.root)) && verb === 'doctor' && !argv.includes('--help')) {
69
+ const { parse } = await import('../cli/parse.mjs');
70
+ try { parse(target.args, target.root); }
71
+ catch (error) { process.stderr.write(error.message + '\n'); return error.exitCode ?? 2; }
72
+ const code = await (await import('./browser-runtime.mjs')).browserPreflight(target.root, target.args);
73
+ if (code !== undefined) return code;
74
+ }
68
75
  const bootstrap = pinnedPackage(target.root)?.ready === false && installsFirst.has(verb);
69
76
  if ((bootstrap || ['install', 'setup', 'dev', 'preview', 'build', 'verify'].includes(verb)) && !argv.includes('--help') && !argv.includes('--stop')) {
70
77
  const { parse } = await import('../cli/parse.mjs');
@@ -98,9 +105,12 @@ export async function main(argv) {
98
105
  const { installPinned } = await import('./launch/install-pinned.mjs'), { LaunchFailure } = await import('./launch/failure.mjs');
99
106
  try { await installPinned(target.root); }
100
107
  catch (failure) { if (!(failure instanceof LaunchFailure)) throw failure; process.stderr.write(failure.message + '\n'); return failure.exitCode; }
101
- return delegate(target, target.args);
102
108
  }
103
109
  if (mode === 'package' && installsFirst.has(verb)) await (await import('./launch/install-pinned.mjs')).settledPin(target.root);
110
+ if (first && dispatcher(target.root).mode !== 'bundled' && ['install', 'verify'].includes(verb) && !argv.includes('--help') && !argv.includes('--site')) {
111
+ const code = await (await import('./browser-runtime.mjs')).browserPreflight(target.root, target.args);
112
+ if (code !== undefined) return code;
113
+ }
104
114
  if (verb === 'dev' && mode && mode !== 'package' && !argv.includes('--help')) return (await import('./launch/dev.mjs')).launchDev(target);
105
115
  // Every other server start or queued job on a vendored pin gets the person
106
116
  // defaults too (a pinned package applies its own).
package/install.sh CHANGED
@@ -12,8 +12,8 @@
12
12
  # `npx -y @runeditrun/rer cli install`. A failure leaves any previous install
13
13
  # selected and working. It never edits shell profiles.
14
14
  #
15
- # Needs curl, tar and Node (the package's minimum). macOS or Linux on x64 or
16
- # arm64; on Windows, run it inside WSL2.
15
+ # Needs curl and tar. If Node 22 or later is absent, installs the pinned official
16
+ # Node release in rer's own data directory. macOS/Linux x64/arm64; Windows: WSL2.
17
17
 
18
18
  # Everything runs from main, so a partly downloaded script does nothing.
19
19
  main() {
@@ -29,7 +29,7 @@ main() {
29
29
  x86_64 | amd64 | arm64 | aarch64) ;;
30
30
  *) fail "this processor ($(uname -m)) is not supported; rer runs on x64 and arm64." ;;
31
31
  esac
32
- for tool in curl tar node; do
32
+ for tool in curl tar; do
33
33
  command -v "$tool" >/dev/null 2>&1 || fail "$tool is required. Install it, then run this again."
34
34
  done
35
35
 
@@ -39,6 +39,11 @@ main() {
39
39
  trap 'rm -rf "$work"' EXIT
40
40
  trap 'exit 130' INT TERM
41
41
 
42
+ # Bootstrap before reading npm metadata; no npm global install or PATH links.
43
+ if ! command -v node >/dev/null 2>&1 || ! node -e 'process.exit(Number(process.versions.node.split(".")[0]) >= 22 ? 0 : 1)' >/dev/null 2>&1; then
44
+ install_node
45
+ fi
46
+
42
47
  curl -fsSL --proto '=http,https' -H 'Accept: application/json' "$registry/@runeditrun%2frer" -o "$work/metadata.json" \
43
48
  || fail "could not read $package from $registry."
44
49
  # Writes version, tarball URL, integrity, file count and unpacked size, one per line.
@@ -136,6 +141,54 @@ NODE
136
141
  || fail "rer cli install failed; any previous install is still selected."
137
142
  }
138
143
 
144
+ install_node() {
145
+ node_version=22.20.0
146
+ case "$(uname -s)" in Darwin) node_os=darwin ;; Linux) node_os=linux ;; esac
147
+ case "$(uname -m)" in x86_64 | amd64) node_arch=x64 ;; arm64 | aarch64) node_arch=arm64 ;; esac
148
+ node_name="node-v$node_version-$node_os-$node_arch"
149
+ data="${XDG_DATA_HOME:-$HOME/.local/share}/rer"
150
+ node_home="$data/runtimes/$node_name"
151
+ if [ ! -x "$node_home/bin/node" ] || [ "$("$node_home/bin/node" --version 2>/dev/null)" != "v$node_version" ]; then
152
+ printf 'Installing Node %s in %s from the checksum-verified nodejs.org release.\n' "$node_version" "$node_home"
153
+ archive="$node_name.tar.gz"
154
+ release="https://nodejs.org/dist/v$node_version"
155
+ curl -fsSL --proto '=https' "$release/SHASUMS256.txt" -o "$work/SHASUMS256.txt" \
156
+ || fail "could not download Node $node_version checksums from nodejs.org."
157
+ curl -fL --proto '=https' "$release/$archive" -o "$work/$archive" \
158
+ || fail "could not download Node $node_version from nodejs.org."
159
+ expected=$(awk -v file="$archive" '$2 == file { print $1 }' "$work/SHASUMS256.txt")
160
+ [ "${#expected}" -eq 64 ] || fail "nodejs.org gives no unique SHA-256 for $archive."
161
+ case "$expected" in *[!0-9a-f]*) fail "nodejs.org gives an invalid SHA-256 for $archive." ;; esac
162
+ if command -v shasum >/dev/null 2>&1; then
163
+ actual=$(shasum -a 256 "$work/$archive")
164
+ elif command -v sha256sum >/dev/null 2>&1; then
165
+ actual=$(sha256sum "$work/$archive")
166
+ else
167
+ fail 'SHA-256 verification needs shasum or sha256sum. Install one, then run this again.'
168
+ fi
169
+ [ "${actual%% *}" = "$expected" ] || fail "Node $node_version does not match nodejs.org's SHA-256; nothing was installed."
170
+ mkdir "$work/node"
171
+ tar -xzf "$work/$archive" -C "$work/node" || fail "could not unpack Node $node_version."
172
+ [ "$("$work/node/$node_name/bin/node" --version)" = "v$node_version" ] || fail "Node $node_version cannot run on this system."
173
+ mkdir -p "$data/runtimes"
174
+ # Move only into our prefix, and never overlay an existing runtime.
175
+ [ ! -e "$node_home" ] || fail "the private Node runtime at $node_home is damaged; remove that directory and run this again."
176
+ mv "$work/node/$node_name" "$node_home"
177
+ fi
178
+ # A private link lets future launchers and updates find the managed runtime.
179
+ # Node's rename replaces an existing symlink atomically on macOS and Linux.
180
+ "$node_home/bin/node" - "$data" "$node_name" <<'NODE' || exit 1
181
+ var fs = require('fs'), path = require('path');
182
+ var root = process.argv[2], temporary = path.join(root, '.node-' + process.pid);
183
+ try {
184
+ fs.symlinkSync(path.join('runtimes', process.argv[3]), temporary);
185
+ fs.renameSync(temporary, path.join(root, 'node'));
186
+ } finally { try { fs.unlinkSync(temporary); } catch (error) { if (error.code !== 'ENOENT') throw error; } }
187
+ NODE
188
+ PATH="$node_home/bin:$PATH"
189
+ export PATH
190
+ }
191
+
139
192
  fail() {
140
193
  printf 'rer install: %s\n' "$*" >&2
141
194
  exit 1
@@ -35,6 +35,11 @@ in both directions, preserving text and binary messages, selected protocols,
35
35
  cookies and close codes. Refused upgrades retain their HTTP response; other
36
36
  upgrade protocols receive 400. Hosted demo routing selects the visitor's own
37
37
  container before forwarding the upgrade, including on declared secondary hosts.
38
+ In a hosted demo (`RER_DEMO=1` with `RER_INGRESS_ORIGIN`), the workerd demo
39
+ egress serves the app's own fetch of any of its ingress origins through this
40
+ container's ingress, never the network: the front admits only the visitor's
41
+ cookie, so this is how the app reads its own public pages. Other destinations
42
+ keep the demo egress and its refusals.
38
43
 
39
44
  The workerd source boundary permits Durable Object definitions, including export
40
45
  aliases and indirect inheritance. Unbound definitions create no namespace. The
@@ -68,6 +73,12 @@ SQLite stays on the Docker host's local filesystem; host-shared checkout mounts
68
73
  are not used for database storage. Back up with export before deleting a volume. Build
69
74
  uses the ordinary private-file custody and command admission boundary. Secrets
70
75
  are provided at runtime, never baked into the image or transferred in archives.
76
+ Managed mail's `MAIL_PROVIDER`, `MAIL_FROM` and `MAIL_RELAY_URL` are public
77
+ configuration. Keep them in the mail spec's public variables and Wrangler `vars`,
78
+ and remove them from `deploy.json` secrets. For migration, the image builder
79
+ accepts those legacy secret declarations when the managed-mail spec declares them public,
80
+ and prints that correction. Demo runtime settings override their image defaults.
81
+ API keys, tokens and other secrets in image variables remain refused.
71
82
 
72
83
  `rer deploy --platform container --host ssh://user@host --env-file FILE` uses
73
84
  strict SSH host-key checking and a Linux host with Python 3 and Docker. FILE must
@@ -8,6 +8,7 @@ import { checkBoundary } from './boundary.mjs';
8
8
  import { localDurableObjects } from './durable-objects.mjs';
9
9
  import { readMigrationRewrites, withRewrites } from '../deploy-kit/migrations.mjs';
10
10
  import { containerMigrationInventory } from './migration-inventory.mjs';
11
+ import { checkImageVariables } from './image-variables.mjs';
11
12
  export async function buildContainer(root, options={}) {
12
13
  const previous=process.cwd();process.chdir(root);
13
14
  try{return await buildImage(root,options);}finally{process.chdir(previous);}
@@ -74,7 +75,7 @@ async function buildImage(root, { output = join(root,'.rer/container/image'), en
74
75
  const entry = engine === 'workerd' ? 'dist/server/'+workerConfig.main : 'dist/server/index.mjs';
75
76
  await readFile(join(root,entry));
76
77
  if (engine === 'node' && workerConfig.kv_namespaces?.length) throw new Error('Node container does not support KV');
77
- for (const secret of declaration.secrets ?? []) if (Object.hasOwn(workerConfig.vars ?? {},secret.binding)) throw new Error('Secret declared as an image variable: '+secret.binding);
78
+ await checkImageVariables(root,workerConfig.vars ?? {},declaration.secrets ?? []);
78
79
  const manifest = { version:1,engine,entry,cacheContract,runner,config:workerConfig,migrations,portabilityMigrations:await portabilityPlan(split),maxRequestBytes:25*1024*1024 };
79
80
  await rm(output,{recursive:true,force:true}); await mkdir(join(output,'app'),{recursive:true});
80
81
  await cp(join(root,'dist'),join(output,'app/dist'),{recursive:true}); await writeFile(join(output,'app/container.json'),JSON.stringify(manifest,null,2)+'\n');
@@ -6,6 +6,18 @@ const transports = new Set([
6
6
  ]);
7
7
  const mailPorts = new Set(['25', '465', '587', '2525']);
8
8
 
9
+ // The demo's own hosts (RER_INGRESS_ORIGIN and RER_INGRESS_ORIGINS, from
10
+ // deploy-demo.json) reach the front only with the visitor's cookie, so the
11
+ // app's own read of one would leave the container and meet the start page.
12
+ // SELF is this container's ingress: the same visitor's demo, no network.
13
+ const STRIPPED = ['cf-connecting-ip', 'x-forwarded-host', 'x-forwarded-proto', 'x-forwarded-for', 'forwarded', 'x-rer-original-url', 'x-rer-ingress-origin'];
14
+ function local(request, url) {
15
+ const headers = new Headers(request.headers);
16
+ for (const name of STRIPPED) headers.delete(name);
17
+ headers.set('cf-connecting-ip', '127.0.0.1'); headers.set('x-rer-original-url', url.href);
18
+ return new Request(request, { headers, redirect: 'manual' });
19
+ }
20
+
9
21
  function check(url) {
10
22
  const host = url.hostname.toLowerCase().replace(/\.$/, '');
11
23
  if (transports.has(host) || mailPorts.has(url.port)) throw new TypeError('Demo direct messaging transport refused');
@@ -17,10 +29,11 @@ export default {
17
29
  const redirect = request.redirect;
18
30
  for (let hops = 0; ; hops++) {
19
31
  const url = new URL(request.url);
20
- check(url);
32
+ const own = JSON.parse(env.RER_DEMO_ORIGINS ?? '[]').includes(url.origin);
33
+ if (!own) check(url);
21
34
  // Check every redirect before contacting its destination, including when
22
35
  // an otherwise public URL redirects into a messaging provider.
23
- const response = await env.NETWORK.fetch(new Request(request.clone(), { redirect: 'manual' }));
36
+ const response = own ? await env.SELF.fetch(local(request.clone(), url)) : await env.NETWORK.fetch(new Request(request.clone(), { redirect: 'manual' }));
24
37
  const location = response.headers.get('location');
25
38
  if (![301, 302, 303, 307, 308].includes(response.status) || location === null || redirect === 'manual') return response;
26
39
  await response.body?.cancel();
@@ -0,0 +1,27 @@
1
+ import {readFile} from 'node:fs/promises';
2
+ import {deliveryDeclarationSources} from '../../cli/delivery-declarations.mjs';
3
+ import {sourcePath} from '../delivery-producer/migrations.mjs';
4
+ import {usesManagedMail,validateMailSpec} from '../delivery-producer/mail.mjs';
5
+
6
+ /** Admit only the managed-mail contract's public config through legacy secret declarations. */
7
+ export async function checkImageVariables(root,vars,secrets) {
8
+ const overlaps=secrets.filter(secret=>Object.hasOwn(vars,secret.binding));
9
+ if (!overlaps.length) return;
10
+ const publicMail=new Set(),privateNames=new Set();
11
+ for (const [candidate,select] of deliveryDeclarationSources) {
12
+ const path=await sourcePath(root,candidate,{optional:true});
13
+ if (!path) continue;
14
+ const spec=select(JSON.parse(await readFile(path,'utf8')));
15
+ if (!spec) continue;
16
+ for (const name of [...(spec.secretNames ?? []),...(spec.optionalSecretNames ?? [])]) privateNames.add(name);
17
+ if (!usesManagedMail(spec.mail)) continue;
18
+ const names=spec.publicVariableNames ?? Object.keys(spec.publicVariables ?? {});
19
+ const publicVariables=Object.fromEntries(Object.entries(vars).filter(([name])=>names.includes(name)));
20
+ validateMailSpec({...spec,publicVariables,secretNames:spec.secretNames ?? []});
21
+ for (const name of ['MAIL_PROVIDER','MAIL_FROM','MAIL_RELAY_URL']) if (typeof publicVariables[name] === 'string') publicMail.add(name);
22
+ }
23
+ for (const {binding} of overlaps) if (!publicMail.has(binding) || privateNames.has(binding)) {
24
+ throw new Error('Secret declared as an image variable: '+binding);
25
+ }
26
+ console.warn(overlaps.map(secret=>secret.binding).join(', ')+' are public mail configuration, not secrets. Remove these bindings from deploy.json secrets; keep them in the mail spec public variables and Wrangler vars. Accepting the legacy declaration; runtime demo settings override the image defaults.');
27
+ }
@@ -20,8 +20,8 @@ export async function workerEngine({ root, data, manifest, settings, edge }) {
20
20
  const mf = new Miniflare(convertV4MiniflareOptions({ host:'127.0.0.1',port:0,cf:false,resourcePersistencePath:data,unsafeLocalExplorer:false,
21
21
  workers:[{ name:'ingress',modules:true,script:`export default {fetch(request,env){const observed=request.headers.get('x-rer-original-url');if(!observed)return new Response(null,{status:400});const url=new URL(observed),headers=new Headers(request.headers);headers.delete('x-rer-original-url');headers.set('host',url.host);return env.APP.fetch(new Request(url,{method:request.method,headers,redirect:'manual',...(!['GET','HEAD'].includes(request.method)?{body:request.body}:{})}))}}`,serviceBindings:{ APP:'app' } }, app,
22
22
  { name:'egress',modules:[{ type:'ESModule',path:join(import.meta.dirname,'demo-egress.mjs') }],modulesRoot:import.meta.dirname,
23
- bindings:{ RER_DEMO:settings.RER_DEMO ?? '' },
24
- serviceBindings:{ NETWORK:{ network:{ allow:['public'],tlsOptions:{ trustBrowserCas:true,trustedCertificates:[...rootCertificates] } } } } }],
23
+ bindings:{ RER_DEMO:settings.RER_DEMO ?? '', RER_DEMO_ORIGINS:JSON.stringify(settings.RER_DEMO === '1' && settings.RER_INGRESS_ORIGIN ? [settings.RER_INGRESS_ORIGIN, ...JSON.parse(settings.RER_INGRESS_ORIGINS ?? '[]')] : []) },
24
+ serviceBindings:{ SELF:'ingress', NETWORK:{ network:{ allow:['public'],tlsOptions:{ trustBrowserCas:true,trustedCertificates:[...rootCertificates] } } } } }],
25
25
  }));
26
26
  await mf.ready; const databases = {}, objects = {};
27
27
  for (const [binding, plan] of Object.entries(manifest.migrations)) { const db = await mf.getD1Database(binding, 'app'); databases[binding] = db; await migrate(db, plan); await ensurePortabilitySchema(db, manifest.portabilityMigrations); }
@@ -1,6 +1,10 @@
1
1
  import {array, bindingPattern, keys, string, strings} from './bindings.mjs';
2
2
 
3
3
  const pathPattern = /^\/[A-Za-z0-9/_.~-]*$/;
4
+ const validSignIn = value => value && typeof value === 'object' && !Array.isArray(value)
5
+ && Object.keys(value).every(key => ['path','loginHint'].includes(key))
6
+ && typeof value.path === 'string' && /^\/(?!\/)[a-zA-Z0-9/_-]*$/.test(value.path)
7
+ && typeof value.loginHint === 'boolean';
4
8
  const status = (value, label) => {
5
9
  if (!Number.isInteger(value) || value < 100 || value > 599) throw Error(`Invalid ${label}`);
6
10
  };
@@ -15,8 +19,9 @@ export function validateDeclarations(spec) {
15
19
  if (!spec.surfaces.app) throw Error('Surfaces require an app');
16
20
  const origins = new Map();
17
21
  for (const [name, surface] of Object.entries(spec.surfaces)) {
18
- keys(surface, ['path','hostnameVariable','originVariable','readiness'], 'surface');
22
+ keys(surface, ['path','hostnameVariable','originVariable','readiness','signIn'], 'surface');
19
23
  string(surface.path, 'surface path', pathPattern);
24
+ if (surface.signIn !== undefined && (name !== 'app' || !validSignIn(surface.signIn))) throw Error('Invalid project sign-in declaration');
20
25
  if (surface.hostnameVariable !== undefined && surface.originVariable !== undefined) throw Error('Surface must choose one address variable');
21
26
  for (const field of ['hostnameVariable','originVariable']) if (surface[field] !== undefined) string(surface[field], field, bindingPattern);
22
27
  if (surface.originVariable !== undefined) {
@@ -0,0 +1,66 @@
1
+ import {keys, strings} from './bindings.mjs';
2
+
3
+ const publicNames = ['MAIL_PROVIDER', 'MAIL_FROM', 'MAIL_RELAY_URL'];
4
+ const providerLabels = {rer: 'RER managed mail', resend: 'Resend', sendgrid: 'SendGrid', cloudflare: 'Cloudflare Email Sending'};
5
+
6
+ /** Managed mail is an explicit capability, independent of direct provider adapters. */
7
+ export function usesManagedMail(mail) {
8
+ if (mail === undefined) return false;
9
+ keys(mail, ['providers'], 'mail');
10
+ const providers = strings(mail.providers, 'mail providers', /^(rer|resend|sendgrid|cloudflare)$/);
11
+ if (!providers.length) throw Error('Mail requires at least one provider');
12
+ return providers.includes('rer');
13
+ }
14
+
15
+ /** Compose these fields into the seed's committed setup manifest before packaging. */
16
+ export function generateMailSetupFields(mail) {
17
+ usesManagedMail(mail);
18
+ if (!mail) throw Error('Mail setup requires a provider declaration');
19
+ const condition = provider => ({field: 'MAIL_PROVIDER', equals: provider});
20
+ const presentations = mail.providers.map(provider => ({when: condition(provider), required: true}));
21
+ return [
22
+ {name: 'MAIL_PROVIDER', label: 'Mail provider', kind: 'select', required: true, default: mail.providers[0],
23
+ options: mail.providers.map(value => ({value, label: providerLabels[value]}))},
24
+ {name: 'MAIL_FROM', label: 'Sender address', kind: 'text', required: false, presentations},
25
+ ...(mail.providers.includes('rer') ? [
26
+ {name: 'MAIL_RELAY_URL', label: 'Managed mail relay URL', kind: 'url', required: true, when: condition('rer')}
27
+ ] : []),
28
+ {name: 'MAIL_API_KEY', label: 'Mail API key', kind: 'secret', input: 'entered', ownerVisible: true,
29
+ required: false, presentations: structuredClone(presentations)},
30
+ ...(mail.providers.includes('cloudflare') ? [
31
+ {name: 'MAIL_ACCOUNT_ID', label: 'Cloudflare account ID', kind: 'text', required: true, when: condition('cloudflare')}
32
+ ] : [])
33
+ ];
34
+ }
35
+
36
+ export function validateMailSpec(spec) {
37
+ if (!usesManagedMail(spec.mail)) return;
38
+ for (const name of publicNames) {
39
+ if (!Object.hasOwn(spec.publicVariables, name)) throw Error(`Managed mail requires public ${name}`);
40
+ }
41
+ if (![...spec.secretNames, ...(spec.optionalSecretNames ?? [])].includes('MAIL_API_KEY')) {
42
+ throw Error('Managed mail requires secret MAIL_API_KEY');
43
+ }
44
+ }
45
+
46
+ /** Check the selected installer's effective fields for RER's assigned provider. */
47
+ export function validateMailSetup(mail, manifest) {
48
+ if (!usesManagedMail(mail) || !manifest) return;
49
+ const provider = manifest.fields.find(field => field.name === 'MAIL_PROVIDER');
50
+ if (provider?.kind !== 'select' || !provider.options.some(option => option.value === 'rer')) {
51
+ throw Error('Managed mail setup requires a MAIL_PROVIDER select with the rer option');
52
+ }
53
+ const matches = condition => condition.field === 'MAIL_PROVIDER'
54
+ && (condition.nonEmpty === true || condition.equals === 'rer');
55
+ for (const name of [...publicNames, 'MAIL_API_KEY']) {
56
+ const field = manifest.fields.find(item => item.name === name);
57
+ if (!field || (name === 'MAIL_API_KEY' ? field.kind !== 'secret' : field.kind === 'secret')) {
58
+ throw Error(`Managed mail setup requires ${name === 'MAIL_API_KEY' ? 'secret' : 'public'} ${name}`);
59
+ }
60
+ const presentation = field.presentations?.find(item => matches(item.when));
61
+ if ((field.when && !matches(field.when)) || (field.presentations && !presentation)
62
+ || (presentation?.required ?? field.required) !== true) {
63
+ throw Error(`Managed mail setup requires ${name} with provider rer`);
64
+ }
65
+ }
66
+ }
@@ -4,7 +4,7 @@ import { allow, sha256 } from '../operator-auth/csp.mjs';
4
4
  // client-side route changes, whose head manager writes a fresh title. The script
5
5
  // is one constant text (so one constant CSP hash); the suffix reaches it as data
6
6
  // on the label's style element, never as code.
7
- const SCRIPT = "(()=>{const suffix=document.querySelector('style[data-rer-label]').dataset.rerLabel,update=()=>{const title=document.title.replace(/ (?:Demo|Dev)$/,'')+' '+suffix;if(document.title!==title)document.title=title};update();new MutationObserver(update).observe(document.head,{childList:true,subtree:true,characterData:true})})()";
7
+ const SCRIPT = "(()=>{const suffix=document.querySelector('style[data-rer-label]').dataset.rerLabel,update=()=>{const base=document.title.replace(/\\s*(?:Demo|Dev)$/,''),title=(base?base+' ':'')+suffix;if(document.title!==title)document.title=title};update();new MutationObserver(update).observe(document.head,{childList:true,subtree:true,characterData:true})})()";
8
8
 
9
9
  export async function decorateLabel(response, mode) {
10
10
  if (!response.body || !response.headers.get('content-type')?.toLowerCase().startsWith('text/html')) return response;
@@ -21,7 +21,10 @@ export async function decorateLabel(response, mode) {
21
21
  headers.delete('content-length');
22
22
  headers.delete('etag');
23
23
  const addition = `<style data-rer-label="${suffix}">${style}</style><script>${SCRIPT}</script>`;
24
- const titled = html.replace(/(<title\b[^>]*>)([\s\S]*?)(<\/title>)/i, (_, open, title, close) => `${open}${title.replace(/ (?:Demo|Dev)$/, '')} ${suffix}${close}`);
24
+ const titled = html.replace(/(<title\b[^>]*>)([\s\S]*?)(<\/title>)/i, (_, open, title, close) => {
25
+ const base = title.replace(/\s*(?:Demo|Dev)$/, '');
26
+ return `${open}${base ? `${base} ` : ''}${suffix}${close}`;
27
+ });
25
28
  const body = /<\/head\s*>/i.test(titled) ? titled.replace(/<\/head\s*>/i, `${addition}</head>`) : addition + titled;
26
29
  return new Response(body, { status: response.status, statusText: response.statusText, headers });
27
30
  }
@@ -26,8 +26,11 @@ start page.
26
26
  held (at most 1.5 seconds) until the start changes, so the page learns of the
27
27
  sign-in at once; a slow status read answers pending. Each admission logs
28
28
  `demo_admitted` with the request's user agent and network owner, so a held
29
- place can be joined to whoever started it (automated browsers pass
30
- Turnstile's always-pass testing keys on test hosts). A request
29
+ place can be joined to whoever started it. On Turnstile's testing secret (a
30
+ test host) a start must also carry the deploy's measurement token
31
+ (`measurement.mjs`: cookie `rer_demo_measure` or header
32
+ `x-rer-demo-measurement`), since automated browsers pass those keys; a
33
+ test host without a token admits nobody. A request
31
34
  with that cookie goes to the visitor's Durable Object; nothing else reaches
32
35
  a container.
33
36
  - `container.mjs`: `DemoContainer`, one per visitor (`newUniqueId`, checked
@@ -48,6 +51,10 @@ start page.
48
51
  exact idle/absolute deadline without keeping a timer in flight. Requests
49
52
  check both deadlines before refreshing activity. A container found stopped
50
53
  ends the demo and answers the ended page (410).
54
+ - `certificate.mjs`: after `wrangler deploy`, the CLI waits for each demo
55
+ hostname's certificate, a TLS handshake that verifies for that name at the
56
+ address public DNS over HTTPS gives (10 minutes at most), and logs each
57
+ attempt. A failed or unverified handshake never counts as active.
51
58
  - `capacity.mjs`: `DemoCapacity` counts unexpired reservation rows inside a
52
59
  storage transaction, excluding diagnostics and expired rows. A lost start
53
60
  handoff expires after one minute; a successful claim extends the reservation
@@ -0,0 +1,56 @@
1
+ import { connect } from 'node:tls';
2
+
3
+ // A new Custom Domain answers TLS only once Cloudflare has issued its
4
+ // certificate: about 153 s on a fresh zone (dm-lanyard-1, October 2026), with
5
+ // browsers seeing ERR_SSL_VERSION_OR_CIPHER_MISMATCH meanwhile. After the
6
+ // deploy, wait on every demo hostname for a handshake that verifies the
7
+ // certificate for that name, so the deploy's readback and first visitors
8
+ // meet a working host. Addresses come from public DNS over HTTPS, so a local
9
+ // resolver's cached "no such host" for a new name cannot stall the wait. A
10
+ // failed or unverified handshake is never success: the wait ends in an error
11
+ // naming the last thing each host answered.
12
+ export async function awaitCertificates({ hostnames, report, resolve = publicAddress, port = 443, ca, timeout = 10 * 60_000, interval = 10_000, attemptTimeout = 10_000 }) {
13
+ const deadline = Date.now() + timeout, pending = new Set(hostnames), last = new Map();
14
+ for (let attempt = 1; ; attempt++) {
15
+ for (const hostname of pending) {
16
+ let seen;
17
+ try {
18
+ const address = await resolve(hostname, attemptTimeout);
19
+ if (!address) seen = 'not in public DNS yet';
20
+ else {
21
+ const certificate = await handshake({ address, hostname, port, ca, timeout: attemptTimeout });
22
+ pending.delete(hostname);
23
+ report(`TLS on ${hostname} verified (${certificate.protocol}, certificate valid to ${certificate.validTo}).`);
24
+ continue;
25
+ }
26
+ } catch (error) { seen = error.code ?? error.message; }
27
+ last.set(hostname, seen);
28
+ report(`Waiting for the certificate on ${hostname}: ${seen} (attempt ${attempt}).`);
29
+ }
30
+ if (!pending.size) return;
31
+ if (Date.now() + interval >= deadline) {
32
+ throw Object.assign(new Error('demo-certificate-timeout'), { hosts: [...pending].map(hostname => `${hostname}: ${last.get(hostname)}`) });
33
+ }
34
+ await new Promise(done => setTimeout(done, interval));
35
+ }
36
+ }
37
+
38
+ function handshake({ address, hostname, port, ca, timeout }) {
39
+ return new Promise((resolve, reject) => {
40
+ const socket = connect({ host: address, port, servername: hostname, rejectUnauthorized: true, ...(ca ? { ca } : {}), timeout });
41
+ socket.once('secureConnect', () => {
42
+ const certificate = socket.getPeerCertificate(), protocol = socket.getProtocol(), authorized = socket.authorized;
43
+ socket.destroy();
44
+ if (!authorized) reject(Object.assign(new Error('certificate not verified'), { code: socket.authorizationError ?? 'UNVERIFIED' }));
45
+ else resolve({ protocol, validTo: certificate.valid_to });
46
+ });
47
+ socket.once('timeout', () => { socket.destroy(); reject(Object.assign(new Error('handshake timed out'), { code: 'ETIMEDOUT' })); });
48
+ socket.once('error', reject);
49
+ });
50
+ }
51
+
52
+ async function publicAddress(hostname, timeout) {
53
+ const response = await fetch(`https://cloudflare-dns.com/dns-query?name=${encodeURIComponent(hostname)}&type=A`, { headers: { accept: 'application/dns-json' }, signal: AbortSignal.timeout(timeout) });
54
+ if (!response.ok) throw new Error(`public DNS answered ${response.status}`);
55
+ return (await response.json()).Answer?.find(record => record.type === 1)?.data ?? null;
56
+ }
@@ -0,0 +1,19 @@
1
+ import { equalSecret } from './operator.mjs';
2
+
3
+ // A test host runs on one of Cloudflare's Turnstile testing secrets, which pass
4
+ // (or fail) every visitor alike, so automated browsers took real places within
5
+ // minutes of a new certificate (gr-base-164). There a start must carry the
6
+ // deploy's measurement token, which `rer deploy --demo` hands the operator
7
+ // (RER_DEMO_MEASUREMENT_TOKEN, or .rer/demo-host/measurement-token): the cookie
8
+ // rer_demo_measure or the header x-rer-demo-measurement. A host with
9
+ // a real Turnstile secret never asks for it.
10
+ export const TESTING_SECRET = /^[123]x0{31}AA$/;
11
+ export const MEASUREMENT_COOKIE = 'rer_demo_measure', MEASUREMENT_HEADER = 'x-rer-demo-measurement';
12
+
13
+ export const testHost = env => TESTING_SECRET.test(env.TURNSTILE_SECRET_KEY ?? '');
14
+
15
+ /** Whether a start on a test host carries this deploy's token; a test host without one admits nobody. */
16
+ export async function measured(request, env) {
17
+ const cookie = (request.headers.get('cookie') ?? '').split(';').map(part => part.trim()).find(part => part.startsWith(`${MEASUREMENT_COOKIE}=`))?.slice(MEASUREMENT_COOKIE.length + 1);
18
+ return equalSecret(env.RER_DEMO_MEASUREMENT_TOKEN, request.headers.get(MEASUREMENT_HEADER) ?? cookie);
19
+ }
@@ -2,16 +2,21 @@ import { startPage } from './pages.mjs';
2
2
 
3
3
  // This credential belongs to the demo HOST operator, never a demo's signed-in
4
4
  // owner. It is supplied only as an Authorization header, never a URL/cookie.
5
- export async function operatorPage(request, env, correlation) {
6
- const expected = env.RER_DEMO_OPERATOR_TOKEN;
7
- const authorization = request.headers.get('authorization') ?? '';
8
- const supplied = authorization.startsWith('Bearer ') ? authorization.slice(7) : '';
9
- if (!expected || expected.length < 32 || !supplied || supplied.length > 512) return new Response('Unauthorized', { status: 401 });
5
+ /** A supplied credential against its secret, compared in constant time over their digests. */
6
+ export async function equalSecret(expected, supplied) {
7
+ if (!expected || expected.length < 32 || !supplied || supplied.length > 512) return false;
10
8
  const digest = value => crypto.subtle.digest('SHA-256', new TextEncoder().encode(value));
11
9
  const [a, b] = await Promise.all([digest(expected), digest(supplied)]);
12
10
  let unequal = 0; const av = new Uint8Array(a), bv = new Uint8Array(b);
13
11
  for (let i = 0; i < av.length; i++) unequal |= av[i] ^ bv[i];
14
- if (unequal) return new Response('Unauthorized', { status: 401 });
12
+ return unequal === 0;
13
+ }
14
+
15
+ export async function operatorPage(request, env, correlation) {
16
+ const expected = env.RER_DEMO_OPERATOR_TOKEN;
17
+ const authorization = request.headers.get('authorization') ?? '';
18
+ const supplied = authorization.startsWith('Bearer ') ? authorization.slice(7) : '';
19
+ if (!await equalSecret(expected, supplied)) return new Response('Unauthorized', { status: 401 });
15
20
  const record = await env.CAPACITY.get(env.CAPACITY.idFromName('diagnostics')).diagnostic(correlation);
16
21
  return startPage(env, { status: record ? 200 : 404, notice: record ? `Operator diagnostic: ${JSON.stringify(record)}` : 'No retained diagnostic for this start.' });
17
22
  }
@@ -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', 'startup.mjs', 'placement.mjs', 'capacity.mjs', 'claim.mjs', 'pages.mjs', 'start-script.mjs', 'diagnostics.mjs', 'operator.mjs'];
12
+ export const DEMO_FILES = ['worker.mjs', 'container.mjs', 'startup.mjs', 'placement.mjs', 'capacity.mjs', 'claim.mjs', 'pages.mjs', 'start-script.mjs', 'diagnostics.mjs', 'operator.mjs', 'measurement.mjs'];
13
13
  const FRONT_SET = /^(?:RER_.*|SESSION_SECRET|SETUP_TOKEN|OWNER_EMAIL)$/;
14
14
  const SECRET = /SECRET|TOKEN|PASSWORD|_KEY$/;
15
15
  // Cloudflare Containers' predefined instance types, smallest first (developers.cloudflare.com/containers/platform-details/limits).
@@ -6,6 +6,7 @@
6
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
7
7
  // container; nothing else on this host is reachable.
8
8
  import { operatorPage } from './operator.mjs';
9
+ import { measured, testHost } from './measurement.mjs';
9
10
  import { bounded, category, report } from './diagnostics.mjs';
10
11
  import { startPage, demoCookie, clearCookie } from './pages.mjs';
11
12
 
@@ -80,6 +81,7 @@ async function start(request, env, ctx) {
80
81
  const correlation = crypto.randomUUID();
81
82
  const refuse = (status, notice, headers = {}) => refusal(request, env, status, notice, { 'x-rer-demo-correlation': correlation, ...headers });
82
83
  if (request.headers.get('origin') !== env.DEMO_ORIGIN) return refuse(403, 'Start the demo from this page.');
84
+ if (testHost(env) && !await measured(request, env)) return refuse(403, 'This is a test host: it starts demos only for its operator\'s measurement runs.');
83
85
  let demo;
84
86
  const started = Date.now();
85
87
  try {
@@ -40,7 +40,7 @@ The maintained default-seed `/health` returns the existing `status: 'ok'` plus t
40
40
  } }
41
41
  ```
42
42
 
43
- Assets upload with `run_worker_first: true` (`RUN_WORKER_FIRST` in `render.mjs`). Every request reaches the Worker first, so the seed's routing, origin admission, `no-store` document policy and private-path refusals decide what is served, and the Base delivery producer accepts no other setting. A built file therefore reaches the browser only through the Worker: seed entries call `staticAssetResponse(request, env)` from `foundation/runtime/static-assets.ts` first. After the deploy identity passes, health requests one built file (the first artifact asset that is neither an HTML document nor under a dot path) once, without credentials, and fails with `asset-http-failed` unless it answers 200; the result is recorded as `health.asset`. `rer verify` serves the local build with the same setting (`cli/hosted-output.mjs`).
43
+ Assets upload with `run_worker_first: true` (`RUN_WORKER_FIRST` in `render.mjs`). Every request reaches the Worker first, so the seed's routing, origin admission, `no-store` document policy and private-path refusals decide what is served, and the Base delivery producer accepts no other setting. A built file therefore reaches the browser only through the Worker: seed entries call `staticAssetResponse(request, env)` from `foundation/runtime/static-assets.ts` first. After the deploy identity passes, health requests one built file (the first artifact asset that is neither an HTML document nor under a dot path) without credentials, retries a 5xx or transport failure once within the existing readiness deadline, and fails with `asset-http-failed` unless it answers 200; the result is recorded as `health.asset`. `rer verify` serves the local build with the same setting (`cli/hosted-output.mjs`).
44
44
 
45
45
  The controller supplies the two public variables and Cloudflare version-metadata binding. The parent owns default-seed source/types, package scripts, shared manifests and workflows. Keep the staged-deploy descriptor blocked until the three-stage isolation and actual build/health integration pass; the original deploy-then-health executor cannot safely run installation/build with its credentials.
46
46
 
@@ -52,7 +52,7 @@ Cron reads require the documented `result: {schedules: [...]}` envelope, includi
52
52
 
53
53
  `workerConsumerScript(consumer)` (also exported from `index.mjs`) decodes Worker consumer identities from either documented `script_name` or the observed GET response string `script`. It returns the exact name using the plan's resource-name grammar, or `null` for missing, malformed, conflicting, or non-Worker identities. If both fields are present, each must be valid and both must agree; a malformed alias is never ignored. Reconciliation checks every consumer on queues with a requested consumer before any trigger write and rejects foreign or duplicate consumers. Writes continue to use the documented `script_name` request field. Read-only health and retained-receipt repeats accept either response variant without repairs.
54
54
 
55
- D1/Queue/DO account listings fully paginate with bounded page/request budgets. R2 follows provider cursors. Missing pagination evidence, duplicate names, permission errors, partial success, redirects and transport failures fail visibly. Requests go only to Cloudflare's exact account API. Requests have a 30-second timeout and bounded response size. Before any HTTP status, GET/HEAD reads and writes that provably failed before connecting (DNS failure, connection refusal or connect timeout) may retry once, sharing the original timeout and request budget. The first read reserves half the timeout for a retry; caller deadlines and cancellation still apply. HTTP responses, failed response-body reads and ambiguous write failures are never replayed. Asset upload tokens are used only on the documented same-account assets endpoint.
55
+ D1/Queue/DO account listings fully paginate with bounded page/request budgets. R2 follows provider cursors. Missing pagination evidence, duplicate names, permission errors, partial success, redirects and transport failures fail visibly. Requests go only to Cloudflare's exact account API. Requests have a 30-second timeout and bounded response size. Before any HTTP status, GET/HEAD reads and writes that provably failed before connecting (DNS failure, connection refusal or connect timeout) may retry once, sharing the original timeout and request budget. The first read reserves half the timeout for a retry; caller deadlines and cancellation still apply. Other HTTP responses, failed response-body reads and ambiguous write failures are not replayed. Two scoped exceptions share the original request timeout and budget: content-addressed asset session/upload requests retry a 5xx or transport failure (including a broken response body) once; owner-account removal retries GET/DELETE 5xx responses up to three attempts, with bounded backoff, and treats a retried DELETE 404 as absent before the normal absence readback. Final asset failures name the built path and HTTP status (or missing status). Removal failures name the count and resources still present or not yet confirmed absent, retain their ownership proof, and give the same removal command to finish. Asset upload tokens are used only on the documented same-account assets endpoint.
56
56
 
57
57
  The first receipt binds source commit SHA and tree, artifact/config SHA-256, effective deployment fingerprint, account/Worker, actual resource IDs, migration hashes, secret names and active provider deployment/version/etag. It contains no secret value. The CLI creates it exclusively at mode 0600 before the first health request; it is an identity receipt, not a claim that health passed (health attempts are added afterwards, see below). A failed health request still exits nonzero, while the retained identity allows the next explicit invocation to authenticate state without another upload. For the second deployment use the **same artifact, run/attempt and receipt**. Current provider state must match the prior receipt. The kit performs no resource creation, Worker/asset upload, SQL mutation, Cron/consumer update, or secret rewrite when unchanged. Read-only D1 queries use the provider's POST query transport; a POST is not by itself a database mutation. The receipt remains byte-identical on a repeat. Missing resources, drift or stale state fail without repair during this repeat.
58
58
 
@@ -200,7 +200,9 @@ No Single Redirect (dynamic redirect ruleset) permission is needed. Base's refer
200
200
 
201
201
  ## Migration safety
202
202
 
203
- SQL files have ordered unique names and SHA-256 identities. `d1_migrations` holds controller history with ordered IDs, names, timestamps, SHA-256 hashes and states. Native archives already exclude this installation table. Standard Wrangler name-only inserts remain possible, but their missing hashes/states block subsequent Base deployment pending reviewed adoption. Applied entries must be an unchanged prefix of the desired set. A new migration gets an `applying` claim before its SQL and completion marker are submitted together through the [Cloudflare D1 SQL import API](https://developers.cloudflare.com/api/resources/d1/subresources/database/methods/import/), using the same whole-file protocol as Wrangler to preserve compound trigger bodies and atomic SQL/completion. Uploads use bounded HTTPS R2 destinations, without account credentials; polling is bounded and signed URLs and import response text are never diagnostic output. Any interrupted, failed or uncertain outcome remains blocked and must be inspected explicitly; the kit never automatically retries, rolls back user data, or marks an unknown outcome successful. Readback checks every final identity.
203
+ SQL files have ordered unique names and SHA-256 identities. `d1_migrations` holds controller history with ordered IDs, names, timestamps, SHA-256 hashes and states. Native archives already exclude this installation table. Standard Wrangler name-only inserts remain possible, but their missing hashes/states block subsequent Base deployment pending reviewed adoption. Applied entries must be an unchanged prefix of the desired set. A new migration gets an `applying` claim before its SQL and completion marker are submitted together through the [Cloudflare D1 SQL import API](https://developers.cloudflare.com/api/resources/d1/subresources/database/methods/import/), using the same whole-file protocol as Wrangler to preserve compound trigger bodies and atomic SQL/completion. Uploads use bounded HTTPS R2 destinations, without account credentials; polling is bounded and signed URLs are never diagnostic output. A failed import keeps Cloudflare's own codes and messages on the error (`providerRefusal`, which `rer deploy` prints, with credentials and URLs removed and each message cut to 300 characters) and names the migration it was running.
204
+
205
+ An import that did not complete leaves its `applying` claim. The next deploy of the same migration bytes runs it again only when it proves none of it applied (`migration-retry.mjs`): the import is atomic, so the migration's effects that would make a second run fail (a CREATE without IF NOT EXISTS, ADD COLUMN, RENAME) and that last to the end of the file must all be absent. Then no attempt committed, and one that commits late makes the re-run fail whole instead of applying twice. A migration with no such effect, or with any of them present, stays refused as `uncertain-migration-claim`; the message names the migration, what is present, and the exact step: undo what is present and deploy again, or confirm by hand and delete or complete its claim with `wrangler d1 execute`. The kit never re-runs a migration whose effects may be present, rolls back user data, or marks an unknown outcome successful. Any other unconfirmed or changed history is still `changed-or-uncertain-migration-history`. Readback checks every final identity.
204
206
 
205
207
  A seed that had to rewrite a migration it already released declares the rewrite
206
208
  in `migrations/rewrites.json`: `{ "version": 1, "rewrites": [{ "migration":
@@ -221,7 +223,7 @@ without treating quoted semicolons as terminators or changing migration hashes.
221
223
 
222
224
  A lexical guard rejects standalone transaction/resource control statements (`BEGIN`, `COMMIT`, `END`, `ROLLBACK`, `SAVEPOINT`, `RELEASE`, `ATTACH`, `DETACH`, `VACUUM`) at statement boundaries, including after a trigger. Bare `ROLLBACK` is also refused in conflict clauses and `RAISE`, which can roll back a batch without a standalone control statement. SQLite `CREATE [TEMP|TEMPORARY] TRIGGER` bodies and nested `CASE ... END` expressions are supported; quoted text and comments cannot create statement boundaries. Both ledger names are reserved in bare, double-quoted, backtick and bracket identifiers, including schema-qualified references. [SQLite also accepts single-quoted identifiers](https://www.sqlite.org/lang_keywords.html), so exact controller ledger names are reserved in every token, including data strings, relation names, virtual-table options and introspection arguments. Comments and longer descriptive strings remain allowed. This intentionally conservative policy does not attempt to authorize arbitrary SQLite name grammars. Incomplete quotes, block comments, parentheses, CASE expressions or trigger bodies and NUL bytes fail closed; trigger header expressions must close before BEGIN and body expressions before their statement semicolon. This guard protects controller custody; SQLite still validates application SQL syntax.
223
225
 
224
- The old kit `_rer_deploy_migrations` ledger is moved atomically into `d1_migrations` only after every applied name/hash/state proves an exact desired-history prefix. An ordinary deploy performs this one-time metadata transition even for unchanged code; subsequent redeploys write nothing, and health remains read-only. Existing Wrangler `d1_migrations` records lack content hashes. Automatic adoption would fabricate historical certainty, so those installations require separately reviewed history/hash adoption before this kit proceeds unless their ordered rows exactly match a prefix already attested by the old kit ledger. That transition preserves their IDs and timestamps. The kit can extend its own previous migrations while retaining existing application rows. Local SQLite tests prove failure rollback in the test transport; the provider's actual failure atomicity, retained data, and two-deploy no-mutation behavior remain live proof obligations. The conservative `applying` claim prevents automatic replay even if a remote response is lost.
226
+ The old kit `_rer_deploy_migrations` ledger is moved atomically into `d1_migrations` only after every applied name/hash/state proves an exact desired-history prefix. An ordinary deploy performs this one-time metadata transition even for unchanged code; subsequent redeploys write nothing, and health remains read-only. Existing Wrangler `d1_migrations` records lack content hashes. Automatic adoption would fabricate historical certainty, so those installations require separately reviewed history/hash adoption before this kit proceeds unless their ordered rows exactly match a prefix already attested by the old kit ledger. That transition preserves their IDs and timestamps. The kit can extend its own previous migrations while retaining existing application rows. Local SQLite tests prove failure rollback in the test transport; the provider's actual failure atomicity, retained data, and two-deploy no-mutation behavior remain live proof obligations. An `applying` claim, including one left by a lost remote response, is re-run only on the proof above.
225
227
 
226
228
  ## Local operations and source templates
227
229