@runeditrun/rer 0.2.29 → 0.2.31

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 (71) hide show
  1. package/README.md +16 -0
  2. package/cli/README.md +17 -0
  3. package/cli/business/command.mjs +27 -0
  4. package/cli/business/detector.mjs +42 -0
  5. package/cli/business/parsers-config.mjs +91 -0
  6. package/cli/business/parsers-infrastructure.mjs +68 -0
  7. package/cli/business/parsers-packages.mjs +84 -0
  8. package/cli/business/parsers-pulumi.mjs +64 -0
  9. package/cli/business/parsers-syntax.mjs +113 -0
  10. package/cli/business/parsers-terraform.mjs +53 -0
  11. package/cli/business/parsers.mjs +62 -0
  12. package/cli/business/policy.mjs +46 -0
  13. package/cli/business/scan.mjs +67 -0
  14. package/cli/contract.mjs +2 -2
  15. package/cli/demo-build.mjs +23 -0
  16. package/cli/demo-host.mjs +10 -70
  17. package/cli/demo-native.mjs +74 -0
  18. package/cli/lifecycle.mjs +1 -1
  19. package/cli/main.mjs +1 -0
  20. package/cli/parse.mjs +1 -1
  21. package/cli/release.mjs +5 -2
  22. package/global/CHANGELOG.md +30 -0
  23. package/global/README.md +16 -0
  24. package/global/main.mjs +3 -0
  25. package/modules/container/README.md +2 -15
  26. package/modules/container/host.mjs +1 -3
  27. package/modules/container/ingress.mjs +1 -15
  28. package/modules/container/worker-engine.mjs +2 -3
  29. package/modules/demo-host/README.md +23 -156
  30. package/modules/demo-host/build.mjs +49 -0
  31. package/modules/demo-host/capacity.mjs +8 -2
  32. package/modules/demo-host/claim.mjs +2 -2
  33. package/modules/demo-host/diagnostics.mjs +1 -18
  34. package/modules/demo-host/native/alarms.mjs +51 -0
  35. package/modules/demo-host/native/bindings.mjs +24 -0
  36. package/modules/demo-host/native/bridge.mjs +17 -0
  37. package/modules/demo-host/native/config.mjs +35 -0
  38. package/modules/demo-host/native/cron.mjs +31 -0
  39. package/modules/demo-host/native/d1.mjs +37 -0
  40. package/modules/demo-host/native/deploy-r2.mjs +43 -0
  41. package/modules/demo-host/native/isolate.mjs +36 -0
  42. package/modules/demo-host/native/loader.mjs +30 -0
  43. package/modules/demo-host/native/namespace.mjs +35 -0
  44. package/modules/demo-host/native/prepare.mjs +35 -0
  45. package/modules/demo-host/native/queues.mjs +62 -0
  46. package/modules/demo-host/native/r2-client.mjs +37 -0
  47. package/modules/demo-host/native/r2.mjs +43 -0
  48. package/modules/demo-host/native/resources.mjs +37 -0
  49. package/modules/demo-host/native/seed-object.mjs +22 -0
  50. package/modules/demo-host/native/sql.mjs +17 -0
  51. package/modules/demo-host/native/visitor.mjs +147 -0
  52. package/modules/demo-host/native/worker.mjs +22 -0
  53. package/modules/demo-host/pages.mjs +1 -1
  54. package/modules/demo-host/plan.mjs +9 -30
  55. package/modules/demo-host/remove.mjs +13 -23
  56. package/modules/demo-host/upgrade.mjs +41 -0
  57. package/modules/demo-host/worker.mjs +3 -4
  58. package/modules/owner-claim/verify.d.mts +5 -0
  59. package/modules/release/README.md +11 -1
  60. package/modules/release/github-verify.mjs +30 -26
  61. package/modules/release/produce.mjs +2 -2
  62. package/modules/release/source-verification.mjs +2 -2
  63. package/modules/release/verify-workflow.mjs +23 -0
  64. package/package.json +1 -1
  65. package/modules/demo-host/container.mjs +0 -221
  66. package/modules/demo-host/entrypoint.sh +0 -9
  67. package/modules/demo-host/image.mjs +0 -18
  68. package/modules/demo-host/placement.mjs +0 -37
  69. package/modules/demo-host/prepare.mjs +0 -28
  70. package/modules/demo-host/startup.mjs +0 -27
  71. package/modules/demo-host/template.mjs +0 -71
@@ -0,0 +1,46 @@
1
+ import { basename } from 'node:path';
2
+
3
+ const outputs = new Set(['node_modules', 'vendor', '.git', 'dist', 'build', 'target', 'coverage', '.next', '.nuxt', '.output', '.cache', '.venv', 'venv', '__pycache__', '.terraform', '.pulumi', '.wrangler', '.rer', '.seed', 'playwright-report', 'test-results']);
4
+
5
+ export const skipped = path => path.split('/').some(part => outputs.has(part.toLowerCase()));
6
+
7
+ const stores = new Set(['secrets', '.ssh', '.aws', '.gnupg', 'keychains', 'keychain', 'browser profiles', 'browser-profiles', '.mozilla', '.password-store', '.1password']);
8
+
9
+ function browserStore(path) {
10
+ // Recognize browser data locations, rather than projects or arbitrary
11
+ // directories named profiles, Firefox, Chromium or Safari.
12
+ return /(?:^|\/)\.config\/(?:google-chrome(?:-[^/]+)?|chromium|brave-browser|bravesoftware\/brave-browser|microsoft-edge(?:-[^/]+)?)(?:\/|$)/.test(path) ||
13
+ /(?:^|\/)library\/application support\/(?:google\/chrome(?: [^/]+)?|chromium|bravesoftware\/brave-browser|microsoft edge(?: [^/]+)?|firefox)(?:\/|$)/.test(path) ||
14
+ /(?:^|\/)appdata\/(?:local\/(?:google\/chrome|chromium|bravesoftware\/brave-browser|microsoft\/edge)\/user data|roaming\/mozilla\/firefox)(?:\/|$)/.test(path) ||
15
+ /(?:^|\/)library\/(?:safari|containers\/com\.apple\.safari|group containers\/[^/]*\.com\.apple\.safari)(?:\/|$)/.test(path);
16
+ }
17
+
18
+ function passwordExport(name) {
19
+ return /^(?:1password|bitwarden|lastpass|dashlane|keeper|enpass|nordpass|keepass)(?:[._ -](?:exports?|backups?|credentials?|passwords?|logins?).*)?\.(?:csv|json|zip|txt|xml)$/.test(name) ||
20
+ /^(?:password-manager|passwords?|vault|logins)[._ -](?:exports?|backups?)(?:[._ -].*)?\.(?:csv|json|zip|txt|xml)$/.test(name) ||
21
+ /^(?:passwords?|logins)\.csv$/.test(name);
22
+ }
23
+
24
+ // Specific stores apply to absolute ancestors, including those of explicit
25
+ // roots. Filename rules apply only to the file, never to its parent projects.
26
+ // Denied directories are enumerated for metadata only, never file content.
27
+ export function denied(path) {
28
+ const lower = path.toLowerCase(), name = basename(lower);
29
+ return lower.split('/').some(part => stores.has(part) || /\.(?:opvault|agilekeychain)$/.test(part)) || browserStore(lower) ||
30
+ /\.(?:pem|key|p12|pfx|keychain|keychain-db|kdbx|kdb|1pux|1pif|opvault|agilekeychain)$/.test(name) ||
31
+ /^id_/.test(name) || /^credentials/.test(name) || /^service-account.*\.json$/.test(name) ||
32
+ /^\.env/.test(name) && !/\.(?:example|sample)$/.test(name) ||
33
+ /^\.dev\.vars(?:$|\.)/.test(name) || /\.tfvars(?:\.json)?$/.test(name) || /kubeconfig/.test(name) || passwordExport(name);
34
+ }
35
+
36
+ export const example = path => /(?:^|[./_-])(?:examples?|samples?|templates?)(?:[./_-]|$)/i.test(path);
37
+
38
+ // Only recognised source/config formats are opened. Executable IaC is lexed,
39
+ // never imported, and arbitrary documents and binary files are left untouched.
40
+ export function readable(path) {
41
+ const name = basename(path).toLowerCase();
42
+ return /\.(?:jsonc?|ya?ml|toml|tf|hcl)(?:\.(?:example|sample|template|tpl))?$/.test(name) ||
43
+ ['gemfile', 'go.mod', 'jenkinsfile'].includes(name) || /^requirements.*\.txt$/.test(name) ||
44
+ example(path) && /(?:env|config|settings)/i.test(path) ||
45
+ /(?:^|\/)(?:pulumi[^/]*|infra(?:structure)?)(?:\/|\.)/i.test(path) && /\.(?:[cm]?[jt]s|tsx|py|go|cs)$/.test(name);
46
+ }
@@ -0,0 +1,67 @@
1
+ import { constants } from 'node:fs';
2
+ import { lstat, open, readdir, realpath } from 'node:fs/promises';
3
+ import { basename, dirname, join, relative, resolve, parse } from 'node:path';
4
+ import { blockedSignal } from './detector.mjs';
5
+ import { denied, example, readable, skipped } from './policy.mjs';
6
+ import { parseNames } from './parsers.mjs';
7
+
8
+ // Caller-named roots are canonicalized once; below them, refuse symlink
9
+ // ancestors as well as symlink entries before reading any file content.
10
+ async function plainAncestors(path) {
11
+ const root = parse(path).root;
12
+ let current = root;
13
+ for (const part of path.slice(root.length).split('/').filter(Boolean)) {
14
+ current = join(current, part);
15
+ if ((await lstat(current)).isSymbolicLink()) return false;
16
+ }
17
+ return true;
18
+ }
19
+
20
+ async function namesFromFile(path, info, locator, pulumi) {
21
+ if (!readable(locator) && !(pulumi && /\.(?:[cm]?[jt]sx?|py|go|cs)$/i.test(locator))) return [];
22
+ // O_NOFOLLOW blocks a replaced leaf; compare the opened inode before reading.
23
+ const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
24
+ try {
25
+ const opened = await file.stat();
26
+ if (!opened.isFile() || opened.ino !== info.ino || opened.dev !== info.dev || !await plainAncestors(dirname(path))) throw Error('Changed scan input');
27
+ return parseNames(locator, await file.readFile('utf8'));
28
+ } finally { await file.close(); }
29
+ }
30
+
31
+ export async function scan(directories) {
32
+ const result = { schema: 'rer-business-signals/1', source: 'local', signals: [], withheld: 0 };
33
+ const observedAt = new Date().toISOString(), seen = new Set();
34
+ const roots = [...new Set(directories.map(path => resolve(path)))];
35
+ function emit(signal) {
36
+ if (blockedSignal(signal)) { result.withheld++; return; }
37
+ result.signals.push(signal);
38
+ }
39
+ for (const requested of roots) {
40
+ const root = await realpath(requested);
41
+ const rootInfo = await lstat(root), base = rootInfo.isDirectory() ? root : dirname(root), repo = basename(base);
42
+ async function walk(path, pulumi = false) {
43
+ if (skipped(relative(root, path)) || seen.has(path)) return;
44
+ seen.add(path);
45
+ const info = await lstat(path);
46
+ if (info.isSymbolicLink()) return;
47
+ if (info.isDirectory()) {
48
+ const names = (await readdir(path)).sort();
49
+ pulumi ||= names.some(name => /^Pulumi\.ya?ml$/i.test(name));
50
+ for (const name of names) await walk(join(path, name), pulumi);
51
+ } else if (info.isFile()) {
52
+ const locator = relative(base, path).split('\\').join('/');
53
+ const common = { locator, repo, class: example(locator) ? 'trace' : 'live-use', observedAt };
54
+ // A caller-named store remains metadata-only even when it is an alias.
55
+ if (denied(path) || denied(join(requested, relative(root, path)))) {
56
+ emit({ kind: 'secret-file', value: basename(path), ...common, size: info.size, mtime: info.mtime.toISOString() });
57
+ return;
58
+ }
59
+ for (const name of await namesFromFile(path, info, locator, pulumi)) {
60
+ emit({ ...common, kind: name.kind, value: name.value, class: name.class ?? common.class });
61
+ }
62
+ }
63
+ }
64
+ await walk(root);
65
+ }
66
+ return result;
67
+ }
package/cli/contract.mjs CHANGED
@@ -11,7 +11,7 @@ const definitions = {
11
11
  build: [['--site'], 'Production build with private local settings excluded and restored. --site instead writes the static run site (homepage, /run, docs) to its declared folder and prints that folder.'],
12
12
  verify: [[], 'Run the complete internal verification target.'],
13
13
  reset: [['--yes'], 'Confirmed removal of the declared local inventory only.'],
14
- deploy: [['--environment', '--dry-run', '--site', '--demo', '--host', '--env-file', '--image', '--bind-address', '--http-port', '--https-port', '--remove', '--yes', '--set-secret', '--unset-secret'], 'Owner-account deployment and health; dry run performs local validation/build only. Declared secrets come from the environment or --env-file (an owned 0600 KEY=VALUE file); a new Worker gets the local setup owner and fresh generated secrets when they are not given. After a healthy deploy rer claims the setup owner on the hosted app with the one-time setup token, then removes the token. --set-secret NAME (value from the environment or --env-file) and --unset-secret NAME change one secret of the deployed Worker without a build and record its new version. --remove --yes deletes what this environment\'s deploy record says rer created (Worker, D1, R2, KV, queues), reads back that each is gone, and touches nothing else. --site deploys the run site instead: an assets-only Worker on its custom domain with www redirected; with --dry-run it builds the site and prints the plan with no provider request. --demo deploys the hosted demo instead (deploy-demo.json): a front Worker on demo.<domain> giving each visitor their own signed-in, throwaway container of this seed with real public reads/checks and simulated external writes; --dry-run writes it to .rer/demo-host with no provider request; --demo --remove --yes deletes that demo (its Worker, demo.<domain> Custom Domain and Container application, each only while the record its deploy left proves it the demo\'s), reads back that each is gone, and is a no-op once it is.'],
14
+ deploy: [['--environment', '--dry-run', '--site', '--demo', '--host', '--env-file', '--image', '--bind-address', '--http-port', '--https-port', '--remove', '--yes', '--set-secret', '--unset-secret'], 'Owner-account deployment and health; dry run performs local validation/build only. Declared secrets come from the environment or --env-file (an owned 0600 KEY=VALUE file); a new Worker gets the local setup owner and fresh generated secrets when they are not given. After a healthy deploy rer claims the setup owner on the hosted app with the one-time setup token, then removes the token. --set-secret NAME (value from the environment or --env-file) and --unset-secret NAME change one secret of the deployed Worker without a build and record its new version. --remove --yes deletes what this environment\'s deploy record says rer created (Worker, D1, R2, KV, queues), reads back that each is gone, and touches nothing else. --site deploys the run site instead: an assets-only Worker on its custom domain with www redirected; with --dry-run it builds the site and prints the plan with no provider request. --demo deploys the hosted demo instead (deploy-demo.json): a front Worker on demo.<domain> giving each visitor their own signed-in, throwaway native Worker isolate of this seed with real public reads/checks and simulated external writes; --dry-run writes it to .rer/demo-host with no provider request; --demo --remove --yes deletes that demo (its Worker, demo.<domain> Custom Domain, each only while the record its deploy left proves it the demo\'s), reads back that each is gone, and is a no-op once it is.'],
15
15
  export: [['--target', '--output', '--origin', '--session-file'], 'Complete supported installation archive with integrity and exclusions.'],
16
16
  import: [['--target', '--input', '--journal', '--origin', '--session-file', '--yes', '--legacy-v1', '--acknowledge-unverified-metadata', '--output'], 'Confirmed atomic restore into an empty destination; --journal LATER_ARCHIVE also fences rows that installation erased since. Backup-only local v1 recovery requires --legacy-v1 --acknowledge-unverified-metadata and a new --output v2 archive; --journal requires normal v2 import.'],
17
17
  doctor: [[], 'Read-only installed tool, configuration and state diagnostics.'],
@@ -26,5 +26,5 @@ export const demoVerb = Object.freeze({ flags: [...commonFlags, '--port', '--hos
26
26
  // sign the owner in to, so no seed declares it and check does not ask for it.
27
27
  export const signinVerb = Object.freeze({ flags: [...commonFlags, '--environment', '--env-file'], effects: 'A one-time sign-in link for the hosted owner, without mail. Uses the Cloudflare credentials that deployed --environment (default production; from the environment or --env-file) to write a single-use grant for the recorded owner into that deployment\'s auth database, then prints the link once to this terminal; it is never saved. The link works once, only for that owner, expires within 15 minutes, and its use is recorded in the owner\'s audit log. Signed in this way, the owner can correct a wrong email in settings.' });
28
28
  export const aliases = Object.fromEntries([...Object.keys(verbs).filter(v => v !== 'install'), 'release', 'deps', 'rer'].map(name => [name, name === 'deps' ? 'install' : name === 'rer' ? null : name]));
29
- export const releaseFlags = ['--repo', '--project', '--repository', '--output', '--ref', '--public-base', '--dry-run', '--local-verify', '--tag', '--clean-history', '--onto', '--env-file', '--allow-placeholder-mark', '--no-queue'];
29
+ export const releaseFlags = ['--repo', '--project', '--repository', '--output', '--ref', '--public-base', '--dry-run', '--local-verify', '--verify-workflow', '--tag', '--clean-history', '--onto', '--env-file', '--allow-placeholder-mark', '--no-queue'];
30
30
  export const requiredHooks = ['preview', 'dependencies', 'build', 'migrate', 'start', 'health', 'owner', 'signIn', 'verify', 'deploy', 'portability', 'state', 'settings', 'input'];
@@ -0,0 +1,23 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { shared } from './shared.mjs';
6
+
7
+ export async function demoBundle(project, operation, declaration, output) {
8
+ const { root } = project;
9
+ const { withoutLocalVariables } = await shared('local/build.mjs');
10
+ const { buildEnvironment } = await shared('local/environment.mjs');
11
+ const seed = await readFile(join(root, 'seed.json'), 'utf8').then(JSON.parse).catch(() => ({}));
12
+ const declared = Array.isArray(seed.env) ? seed.env.map(item => item.name) : Object.keys(seed.env ?? {});
13
+ await withoutLocalVariables(root, async () => {
14
+ const builder = fileURLToPath(new URL('../modules/demo-host/build.mjs', import.meta.url));
15
+ const child = spawn(process.execPath, [builder, root, output, JSON.stringify(declaration)], {
16
+ cwd: root, stdio: 'inherit', env: buildEnvironment([...declared, ...(declaration.secrets ?? []).flatMap(item => [item.binding, item.environment])]),
17
+ });
18
+ const abort = () => child.kill('SIGTERM');
19
+ process.once('SIGTERM', abort); process.once('SIGINT', abort);
20
+ try { await new Promise((resolve, reject) => { child.once('error', reject); child.once('exit', code => code === 0 ? resolve() : reject(new Error('Demo build failed'))); }); }
21
+ finally { process.off('SIGTERM', abort); process.off('SIGINT', abort); if (child.exitCode === null && child.signalCode === null) child.kill('SIGTERM'); }
22
+ }, { nested: operation.token, settings: [...(project.adapter?.settings ?? []), ...(project.privateInputs ?? [])] });
23
+ }
package/cli/demo-host.mjs CHANGED
@@ -1,83 +1,23 @@
1
- import { cp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
2
- import { randomBytes } from 'node:crypto';
3
- import { createRequire } from 'node:module';
4
- import { dirname, join } from 'node:path';
1
+ import { readFile } from 'node:fs/promises';
5
2
  import { contained } from './project.mjs';
6
- import { invalid, missing, refuse, RerError } from './errors.mjs';
7
- import { imageFolder } from './container.mjs';
8
- import { prepareDemoImage } from '../modules/demo-host/image.mjs';
9
- import { DEMO_FILES, INSTANCE_TYPES, demoPlan } from '../modules/demo-host/plan.mjs';
10
- import { awaitCertificates } from '../modules/demo-host/certificate.mjs';
11
- import { MEASUREMENT_COOKIE, MEASUREMENT_HEADER, TESTING_SECRET } from '../modules/demo-host/measurement.mjs';
3
+ import { invalid, missing, RerError } from './errors.mjs';
4
+ import { demoPlan } from '../modules/demo-host/plan.mjs';
12
5
 
13
- // `rer deploy --demo [--dry-run]`: the seed's hosted demo at demo.<domain>
14
- // (modules/demo-host), from deploy-demo.json. It writes .rer/demo-host/: the
15
- // front Worker, its wrangler.json and the container image folder (workerd
16
- // engine). --dry-run stops there, so `wrangler dev` can serve that folder with
17
- // Docker; a deploy runs `wrangler deploy` on it with the Turnstile secret and
18
- // the demo's record as the version message, then waits for every demo host's
19
- // certificate. On Turnstile's testing secret (a test host) it also sets the
20
- // measurement token starts must carry, and says where it is. `--remove --yes` removes
21
- // what that record proves is the demo's (modules/demo-host/remove.mjs).
22
6
  export async function demoHostCommand(project, options, store, signal, out, operation) {
23
7
  const read = async path => { try { return JSON.parse(await readFile(await contained(project.root, path), 'utf8')); } catch (error) { if (error instanceof RerError) throw error; throw invalid(`Missing or malformed ${path}.`); } };
24
8
  const app = await read(project.adapter.deploy?.declaration ?? 'deploy.json'), declaration = await read('deploy-demo.json');
25
- if (!(app.platforms ?? ['workers']).includes('container')) throw refuse('A hosted demo runs the seed\'s container image: declare "container" in deploy.json platforms first.');
9
+ // Old releases wrote sizing and mode selectors. Consume their removal here
10
+ // so pinning this release needs no per-seed declaration edit.
11
+ const { instanceType: retiredSize, mode: retiredMode, ...nativeDeclaration } = declaration;
12
+ if (retiredSize !== undefined || retiredMode !== undefined) store.report('Hosted demos now use the native Loader host; remove the retired instanceType and mode keys from deploy-demo.json.');
26
13
  let plan;
27
- try { plan = demoPlan({ project: app.project, environment: options.environment ?? 'production', compatibilityDate: app.compatibilityDate, originVar: app.originVar, hostVariables: app.container?.hostVariables, declaration, turnstileSiteKey: process.env.TURNSTILE_SITE_KEY?.trim() }); }
28
- 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), "ownerEmail" (the demo owner's address; default owner@demo.invalid) and plain "settings".`); }
14
+ try { plan = demoPlan({ project: app.project, environment: options.environment ?? 'production', compatibilityDate: app.compatibilityDate, originVar: app.originVar, hostVariables: app.container?.hostVariables, declaration: nativeDeclaration, turnstileSiteKey: process.env.TURNSTILE_SITE_KEY?.trim() }); }
15
+ catch (error) { throw invalid(`The demo deploy declaration is invalid (${error.message}). deploy-demo.json holds version, domain, name, and optionally maxInstances, ownerEmail and plain settings.`); }
29
16
  if (options.remove) return removeDemo(plan, store, signal);
30
17
  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.');
31
18
  const supplied = process.env.RER_DEMO_MEASUREMENT_TOKEN?.trim();
32
19
  if (supplied && (supplied.length < 32 || supplied.length > 512 || /[\s;,]/.test(supplied))) throw invalid('RER_DEMO_MEASUREMENT_TOKEN must contain 32 to 512 characters, with no spaces, semicolons or commas.');
33
- const folder = join(project.root, '.rer', 'demo-host');
34
- await rm(folder, { recursive: true, force: true });
35
- await mkdir(folder, { recursive: true, mode: 0o700 });
36
- await store.step('Building the demo container image (workerd engine)');
37
- await imageFolder(project, operation, { ...app, secrets: [...(app.secrets ?? []), { binding: 'RER_DEMO_OPERATOR_TOKEN' }, { binding: 'RER_DEMO_MEASUREMENT_TOKEN' }, { binding: 'TURNSTILE_SECRET_KEY' }] }, { output: join(folder, 'image'), engine: 'workerd' });
38
- await prepareDemoImage(join(folder, 'image'));
39
- for (const file of DEMO_FILES) await cp(new URL(`../modules/demo-host/${file}`, import.meta.url), join(folder, file));
40
- await writeFile(join(folder, 'wrangler.json'), JSON.stringify(plan.wrangler, null, 2) + '\n');
41
- const summary = { worker: plan.worker, origin: plan.origin, hostname: plan.hostname, hostnames: plan.hostnames, routes: plan.wrangler.routes, folder: '.rer/demo-host', maxInstances: plan.maxInstances, settings: plan.settings, instanceType: plan.instanceType, startsPerIpPerMinute: 3, minutes: 60, idleMinutes: 15, enableInternet: true };
42
- const human = [`Demo plan: Worker ${summary.worker} on ${summary.hostnames.join(', ')} (custom domains; workers.dev off), written to ${summary.folder}`,
43
- ` one container per visitor (${summary.instanceType}, at most ${summary.maxInstances} at once, public internet, RER_DEMO=1), 3 starts per IP per minute behind Turnstile`,
44
- ` each demo ends after 60 minutes or 15 idle minutes; its container is destroyed and its state deleted`];
45
- if (options.dryRun) {
46
- if (options.json) out.event('demo', summary); else for (const line of human) out.human(line);
47
- store.report('deploy --demo: dry run complete; no deployment occurred and no provider request was made.');
48
- return { dryRun: true, deployed: false, demo: summary };
49
- }
50
- const names = ['CLOUDFLARE_ACCOUNT_ID', 'CLOUDFLARE_API_TOKEN', 'TURNSTILE_SITE_KEY', 'TURNSTILE_SECRET_KEY'];
51
- if (names.some(name => !process.env[name]?.trim())) throw missing(`${names.join(', ')} are required; see DEMO.md "Hosting the demo".`);
52
- if (!options.json) for (const line of human) out.human(line);
53
- // Production hosts keep the real human check and never take a measurement token.
54
- const measurement = TESTING_SECRET.test(process.env.TURNSTILE_SECRET_KEY.trim()) ? supplied || randomBytes(32).toString('base64url') : null;
55
- const secrets = join(folder, '.secrets.json');
56
- await writeFile(secrets, JSON.stringify({ TURNSTILE_SECRET_KEY: process.env.TURNSTILE_SECRET_KEY.trim(), ...(process.env.RER_DEMO_OPERATOR_TOKEN ? { RER_DEMO_OPERATOR_TOKEN: process.env.RER_DEMO_OPERATOR_TOKEN } : {}),
57
- ...(measurement ? { RER_DEMO_MEASUREMENT_TOKEN: measurement } : {}) }), { mode: 0o600 });
58
- try {
59
- const require = createRequire(join(project.root, 'package.json'));
60
- const manifest = require.resolve('wrangler/package.json');
61
- const wrangler = join(dirname(manifest), JSON.parse(await readFile(manifest, 'utf8')).bin.wrangler);
62
- await store.run('Deploying the demo Worker and its container image', process.execPath, [wrangler, 'deploy', '--config', 'wrangler.json', '--secrets-file', '.secrets.json', '--message', plan.record], { cwd: folder, signal });
63
- } finally { await rm(secrets, { force: true }); }
64
- await store.step(`Waiting for the certificate on ${plan.hostnames.join(', ')}`);
65
- try { await awaitCertificates({ hostnames: plan.hostnames, report: line => store.report(line) }); }
66
- catch (error) {
67
- if (error.message !== 'demo-certificate-timeout') throw error;
68
- throw new RerError('deploy_refused', `The demo is deployed, but its certificate is not active 10 minutes later (${error.hosts.join('; ')}). Run the deploy again to wait again; nothing needs removing.`, 1);
69
- }
70
- let measured;
71
- if (measurement) {
72
- // Output redaction masks credentials, so a token rer made goes to a private file.
73
- const file = '.rer/demo-host/measurement-token';
74
- if (!supplied) await writeFile(join(project.root, file), measurement + '\n', { mode: 0o600 });
75
- measured = { cookie: MEASUREMENT_COOKIE, header: MEASUREMENT_HEADER, token: supplied ? 'RER_DEMO_MEASUREMENT_TOKEN' : file };
76
- const how = `send it as the cookie ${MEASUREMENT_COOKIE}=<token> on ${plan.hostname} or the header ${MEASUREMENT_HEADER}: <token>`;
77
- if (options.json) out.event('demo-measurement', measured);
78
- else out.human(`Test host: it starts demos only with the measurement token in ${supplied ? 'RER_DEMO_MEASUREMENT_TOKEN' : file}; ${how}.`);
79
- }
80
- return { dryRun: false, deployed: true, origin: plan.origin, demo: summary, ...(measured ? { measurement: measured } : {}) };
20
+ return (await import('./demo-native.mjs')).nativeDemoCommand(project, options, store, signal, out, operation, app, plan);
81
21
  }
82
22
 
83
23
  async function removeDemo(plan, store, signal) {
@@ -0,0 +1,74 @@
1
+ import { cp, mkdir, writeFile, rm, readFile } from 'node:fs/promises';
2
+ import { join, dirname } from 'node:path';
3
+ import { createRequire } from 'node:module';
4
+ import { randomBytes } from 'node:crypto';
5
+ import { demoBundle } from './demo-build.mjs';
6
+ import { upgradeDemo } from '../modules/demo-host/upgrade.mjs';
7
+ import { missing, invalid } from './errors.mjs';
8
+ import { DEMO_FILES } from '../modules/demo-host/plan.mjs';
9
+ import { cloudflare } from '../modules/deploy-kit/provider.mjs';
10
+ import { demoBucketName, prepareBucket } from '../modules/demo-host/native/deploy-r2.mjs';
11
+ import { RUNTIME_FILES } from '../modules/demo-host/native/config.mjs';
12
+ import { prepareNative } from '../modules/demo-host/native/prepare.mjs';
13
+ import { TESTING_SECRET } from '../modules/demo-host/measurement.mjs';
14
+ import { awaitCertificates } from '../modules/demo-host/certificate.mjs';
15
+
16
+ export async function nativeDemoCommand(project, options, store, signal, out, operation, app, plan) {
17
+ const folder = join(project.root, '.rer/demo-host');
18
+ await rm(folder, { recursive: true, force: true });
19
+ await mkdir(join(folder, 'modules/demo-host/native'), { recursive: true, mode: 0o700 });
20
+ await store.step('Building the native demo Worker bundle and static assets');
21
+ await demoBundle(project, operation, app, join(folder, 'bundle'));
22
+ for (const file of DEMO_FILES) await cp(new URL(`../modules/demo-host/${file}`, import.meta.url), join(folder, 'modules/demo-host', file));
23
+ for (const file of RUNTIME_FILES) await cp(new URL(`../modules/demo-host/native/${file}.mjs`, import.meta.url), join(folder, `modules/demo-host/native/${file}.mjs`));
24
+ for (const directory of ['deploy-kit']) await cp(new URL(`../modules/${directory}/`, import.meta.url), join(folder, 'modules', directory), { recursive: true });
25
+ await mkdir(join(folder, 'modules/container'), { recursive: true });
26
+ for (const file of ['migrations.mjs', 'demo-egress.mjs']) await cp(new URL(`../modules/container/${file}`, import.meta.url), join(folder, 'modules/container', file));
27
+ // Runtime imports use the same module topology as the maintained source.
28
+ const bundle = await prepareNative(folder);
29
+ const config = { ...plan.wrangler, main: 'modules/demo-host/native/worker.mjs', compatibility_flags: ['nodejs_compat'],
30
+ assets: { directory: './assets', binding: 'ASSETS', run_worker_first: true }, worker_loaders: [{ binding: 'LOADER' }],
31
+ };
32
+ if (bundle.bindings.buckets.length) config.r2_buckets = [{ binding: 'NATIVE_BUCKET', bucket_name: demoBucketName(plan.worker) }];
33
+ config.vars.NATIVE_SOURCE_DIGEST = bundle.digest;
34
+ if (process.env.RER_NATIVE_TEST_TTL_MS && TESTING_SECRET.test(process.env.TURNSTILE_SECRET_KEY ?? '')) {
35
+ if (!/^[1-9][0-9]{2,6}$/.test(process.env.RER_NATIVE_TEST_TTL_MS)) throw invalid('RER_NATIVE_TEST_TTL_MS must be positive milliseconds');
36
+ config.vars.NATIVE_TEST_TTL_MS = process.env.RER_NATIVE_TEST_TTL_MS;
37
+ }
38
+ await writeFile(join(folder, 'wrangler.json'), JSON.stringify(config, null, 2) + '\n');
39
+ const summary = { worker: plan.worker, origin: plan.origin, mode: 'loader', digest: bundle.digest, modules: Object.keys(bundle.modules).length, minutes: 60, idleMinutes: 15 };
40
+ if (options.dryRun) {
41
+ if (options.json) out.event('demo', { ...summary, hostnames: plan.hostnames, routes: config.routes });
42
+ else out.human(`Native demo plan: ${plan.origin} (Worker Loader), written to .rer/demo-host`);
43
+ return { dryRun: true, deployed: false, demo: summary };
44
+ }
45
+ const required = ['CLOUDFLARE_ACCOUNT_ID', 'CLOUDFLARE_API_TOKEN', 'TURNSTILE_SITE_KEY', 'TURNSTILE_SECRET_KEY'];
46
+ if (required.some(name => !process.env[name]?.trim())) throw missing(`${required.join(', ')} are required`);
47
+ const api = cloudflare({ accountId: process.env.CLOUDFLARE_ACCOUNT_ID, token: process.env.CLOUDFLARE_API_TOKEN });
48
+ config.migrations = await upgradeDemo({ api, plan });
49
+ if (bundle.bindings.buckets.length) {
50
+ const statePath = join(project.root, '.rer/demo-buckets', plan.worker + '.json');
51
+ const pending = await readFile(statePath, 'utf8').then(JSON.parse).catch(error => { if (error.code === 'ENOENT') return null; throw error; });
52
+ const bucket = await prepareBucket(api, plan, pending);
53
+ await mkdir(dirname(statePath), { recursive: true, mode: 0o700 });
54
+ await writeFile(statePath, JSON.stringify({ record: plan.record, bucket }), { mode: 0o600 });
55
+ config.vars.NATIVE_BUCKET_CREATED = bucket.creation_date;
56
+ await writeFile(join(folder, 'wrangler.json'), JSON.stringify(config, null, 2) + '\n');
57
+ }
58
+ await writeFile(join(folder, 'wrangler.json'), JSON.stringify(config, null, 2) + '\n');
59
+ const testing = TESTING_SECRET.test(process.env.TURNSTILE_SECRET_KEY);
60
+ const measurement = testing ? process.env.RER_DEMO_MEASUREMENT_TOKEN || randomBytes(32).toString('base64url') : undefined;
61
+ const secrets = { TURNSTILE_SECRET_KEY: process.env.TURNSTILE_SECRET_KEY, ...(measurement ? { RER_DEMO_MEASUREMENT_TOKEN: measurement } : {}),
62
+ ...(process.env.RER_DEMO_OPERATOR_TOKEN ? { RER_DEMO_OPERATOR_TOKEN: process.env.RER_DEMO_OPERATOR_TOKEN } : {}) };
63
+ const secretFile = join(folder, '.secrets.json');
64
+ await writeFile(secretFile, JSON.stringify(secrets), { mode: 0o600 });
65
+ try {
66
+ const require = createRequire(join(project.root, 'package.json')), manifest = require.resolve('wrangler/package.json');
67
+ const wrangler = join(dirname(manifest), JSON.parse(await readFile(manifest, 'utf8')).bin.wrangler);
68
+ await store.run('Deploying the native demo host', process.execPath, [wrangler, 'deploy', '--config', 'wrangler.json', '--secrets-file', '.secrets.json', '--message', plan.record], { cwd: folder, signal });
69
+ } finally { await rm(secretFile, { force: true }); }
70
+ if (measurement) await writeFile(join(folder, 'measurement-token'), measurement, { mode: 0o600 });
71
+ await awaitCertificates({ hostnames: plan.hostnames, report: line => store.report(line) });
72
+ out.human(`Native demo deployed: ${plan.origin} (Worker Loader, one SQLite Durable Object per visitor; edge static assets).`);
73
+ return { deployed: true, demo: summary };
74
+ }
package/cli/lifecycle.mjs CHANGED
@@ -86,7 +86,7 @@ async function runLifecycle(project, options, out, deployRedaction) {
86
86
  const adapter = project.adapter;
87
87
  // The run site: static pages built from edition identity, never the app build.
88
88
  if (options.site) return await (await import('./site.mjs')).siteCommand(project, options, store, signal, out);
89
- // The hosted demo: a front Worker and the seed's container image on demo.<domain>.
89
+ // The hosted demo: a native Worker Loader host on demo.<domain>.
90
90
  if (options.verb === 'deploy' && options.demo) return await (await import('./demo-host.mjs')).demoHostCommand(project, options, store, signal, out, operation);
91
91
  if (options.verb === 'install') {
92
92
  const { dependencyEnvironment } = await shared('dependency-environment.mjs');
package/cli/main.mjs CHANGED
@@ -6,6 +6,7 @@ import { check, describe } from './inspect.mjs';
6
6
  import { selectNodeRuntime } from './node-runtime.mjs';
7
7
 
8
8
  export async function main(argv = process.argv.slice(2)) {
9
+ if (argv[0] === 'business') return (await import('./business/command.mjs')).businessCommand(argv.slice(1));
9
10
  // Every runtime a seed's hooks start inherits this: Wrangler and the Cloudflare
10
11
  // Vite plugin otherwise serve the Local Explorer, which reads and writes the
11
12
  // store without the dev key.
package/cli/parse.mjs CHANGED
@@ -85,7 +85,7 @@ export function parse(argv, cwd = process.cwd(), { independent = false, deferTai
85
85
  if (options.environment !== undefined && !/^[a-z][a-z0-9-]{0,39}$/.test(options.environment)) throw invalid('Provide a valid deployment environment name.');
86
86
  for (const key of ['setSecret', 'unsetSecret']) if (options[key] !== undefined && !/^[A-Z][A-Z0-9_]{0,63}$/.test(options[key])) throw invalid('Name a declared secret binding, such as SESSION_SECRET.');
87
87
  if(verb==='deploy'&&options.demo&&(options.site||['platform','image','bindAddress','httpPort','httpsPort','envFile','host','setSecret','unsetSecret'].some(key=>options[key]!==undefined)))throw invalid('--demo takes only --environment, --dry-run and --remove --yes: the hosted demo is its own Worker on demo.<domain>.');
88
- if(verb==='deploy'&&options.demo&&options.remove&&(options.dryRun||!options.yes))throw invalid(options.dryRun?'Use --remove and --dry-run on separate runs.':'deploy --demo --remove deletes the hosted demo\'s Worker, its demo.<domain> Custom Domain and its Container application. Add --yes to confirm.');
88
+ if(verb==='deploy'&&options.demo&&options.remove&&(options.dryRun||!options.yes))throw invalid(options.dryRun?'Use --remove and --dry-run on separate runs.':'deploy --demo --remove deletes the hosted demo\'s Worker, its demo.<domain> Custom Domain. Add --yes to confirm.');
89
89
  if ((options.remove || options.setSecret || options.unsetSecret) && options.site) throw invalid('--remove, --set-secret and --unset-secret act on the application Worker, not the run site.');
90
90
  if (options.origin !== undefined) {
91
91
  let url; try { url = new URL(options.origin); } catch { throw invalid('Provide a valid credential-free origin.'); }
package/cli/release.mjs CHANGED
@@ -19,6 +19,9 @@ Without --tag, write a preview. This command never pushes, uploads or deploys.
19
19
  --dry-run Run the real gates and suppress local tag creation.
20
20
  --local-verify Run the seed's full verification locally instead of
21
21
  requiring its exact commit's green GitHub Verify.
22
+ --verify-workflow NAME_OR_FILE
23
+ Override the seed's declared GitHub verification workflow
24
+ by name or file (case-insensitive).
22
25
  --clean-history Prepare a parentless public export.
23
26
  --onto GITHUB_URL#BRANCH
24
27
  Prepare a public child of the destination's current branch;
@@ -53,8 +56,8 @@ export async function dispatchRelease(args) {
53
56
  else if (args[index] === '--dry-run') options.dryRun = true;
54
57
  else if (args[index] === '--allow-placeholder-mark') options.allowPlaceholderMark = true;
55
58
  else if (args[index] === '--local-verify') options.localVerify = true;
56
- else if (['--repo', '--project', '--repository', '--output', '--ref', '--env-file', '--onto', '--public-base'].includes(args[index]) && args[index + 1] && !args[index + 1].startsWith('--'))
57
- options[args[index] === '--env-file' ? 'envFile' : args[index] === '--public-base' ? 'publicBase' : args[index].slice(2)] = args[++index];
59
+ else if (['--repo', '--project', '--repository', '--output', '--ref', '--env-file', '--onto', '--public-base', '--verify-workflow'].includes(args[index]) && args[index + 1] && !args[index + 1].startsWith('--'))
60
+ options[args[index] === '--env-file' ? 'envFile' : args[index] === '--public-base' ? 'publicBase' : args[index] === '--verify-workflow' ? 'verifyWorkflow' : args[index].slice(2)] = args[++index];
58
61
  else throw Error('Invalid release arguments');
59
62
  }
60
63
  if(args.includes('--no-queue')){const {shared}=await import('./shared.mjs');const {commandPolicy}=await shared('queue.mjs');const policy=await commandPolicy();try{if(!policy.ci)throw Error('Original CI required');}finally{await policy.close();}}
@@ -1,5 +1,35 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.31
4
+
5
+ - **Each seed's verify workflow.** For a GitHub source, `rer release` takes the verify workflow from `--verify-workflow NAME_OR_FILE`. If that is absent, it uses the selected commit's `rer-project.json` `verifyWorkflow`, then `.github/workflows/verify.yml`/`verify.yaml`, then exactly one workflow named `verify`, in that order. Names, full file paths and basenames match case-insensitively. An explicit selection must resolve uniquely and never falls through. An ambiguous selection blocks and lists the candidates with the `--verify-workflow` remedy. The exact-SHA run checks are unchanged. `gates.verify` in the receipt and site provenance records `workflowFile`, `workflowName`, `workflowId`, `runId` and `runUrl`. `operations.verify` is unchanged.
6
+ - **`rer business scan [DIR...] [--json]`.** Names-only discovery of package, environment, CI, infrastructure and configuration names in local directories, outside RER checkouts too. It needs no install, project code or network. It prints one JSON document, `{schema: "rer-business-signals/1", source: "local", signals, withheld}`, and each signal has a relative `locator`, a `repo` basename, a `live-use`/`trace` class and `observedAt`. Secret files are never opened and contribute only filename, path, size and mtime. Sensitive-looking outbound names are dropped and counted in `withheld`.
7
+ - **Opt-in import door.** import-kit's `createImportDoorHandler` (`modules/import-kit/src/door/`) is a D1-only door that a seed may mount under POST `/api/rer/import/{uploads,plan,apply,status,reconcile,undo}`.
8
+ - It returns 404 until the owner opts in through `writeImportDoorSettings`.
9
+ - Every request needs a fresh single-use ES256 grant, lasting at most five minutes, from the owner-claim key ring.
10
+ - Uploads are resumable and SHA-256 checked. Plan makes no writes, and apply runs bounded batches bound to the owner's approved plan fingerprint.
11
+ - Bounded catch-up stays strictly below 5% of the baseline. Reconcile and owner undo are included.
12
+ - Base mounts it in no seed.
13
+
14
+ ### Upgrade notes
15
+
16
+ - Update the exact rer package pin, or refresh vendored operating commands, to receive these changes.
17
+ - A seed whose verify workflow is not `verify.yml`/`verify.yaml` or named `verify` sets `"verifyWorkflow"` in `rer-project.json`, or passes `--verify-workflow`. It no longer needs `--local-verify` for a GitHub release.
18
+ - The import door is opt-in: a seed mounts the handler, applies `importDoorSchema` in a new numbered migration, and copies import-kit's `CONTRACT.md` and `src/door/README.md`. See "Optional grant-authorised import door" in SEED-COMMAND-CONTRACT.md.
19
+
20
+ ## 0.2.30
21
+
22
+ - **Hosted demos run as native Workers.** `rer deploy --demo` gives each visitor their own Worker Loader isolate of the seed's ordinary production bundle, with SQLite Durable Object storage and static files served at the edge, instead of a Cloudflare Container. Docker and the Containers permission are no longer needed for a new demo host. Portable container hosting (`rer build`/`rer deploy --platform container`, Node/workerd and SSH) is unchanged; only the hosted-demo image, runtime and placement code are removed.
23
+ - **Seed bindings in native demos.** The seed's Wrangler configuration supplies every D1, R2 bucket, queue and local Durable Object class: D1s and seed DOs get separate SQLite facets per visitor, R2 keys are prefixed by visitor and binding, and alarms deliver UTC crons, seed DO alarms and durable queue batches (ack/retry, delays, dead letters). Own-host reads keep the visitor's context, and a narrow resource bridge keeps seeds away from front admission and diagnostics. Unsupported bindings are refused by name at demo build.
24
+ - **Demo egress guard.** Native visitors' outbound requests go through the same `demo-egress` guard as before: direct mail/SMS provider APIs (SendGrid, Resend, Twilio, Mailgun, Postmark) and SMTP ports are refused, and reads of the demo's own hosts stay inside that visitor's copy.
25
+ - **Removal.** `rer deploy --demo --remove --yes` empties and removes the demo-owned R2 bucket and deletes the demo's Worker and Custom Domains covered by its ownership record, reading back their absence; an existing legacy Container application is removed only when its namespace proves ownership.
26
+
27
+ ### Upgrade notes
28
+
29
+ - Pin rer 0.2.30 and run the same demo workflow. The Worker id and `demo.<domain>` stay the same. The first deploy verifies the previous version's ownership record, removes its Container application by exact id and migrates `DemoContainer` to `NativeDemo` (keeping `DemoCapacity`). Visitor copies that are running end during the upgrade. That one deploy's token still needs Containers: Edit; later deploys do not.
30
+ - `deploy.json` no longer needs `"container"` in `platforms` for a hosted demo. Retired sizing and mode keys in `deploy-demo.json` (such as `instanceType`) are consumed with a migration notice; remove them when next editing the file.
31
+ - Worker Loader/Facets access on Workers Paid is required; no Workers for Platforms subscription is needed.
32
+
3
33
  ## 0.2.29
4
34
 
5
35
  - **Placeholder mark (SC-14).** While a seed's logo, favicon or app mark is byte-equal to Base's placeholder mark, `rer check --profile first-party`, `rer build --site` and `rer deploy --site` print one warning naming the files (a `placeholder_mark` warning event under `--json`) and still succeed. `rer release` refuses the placeholder unless `--allow-placeholder-mark` is given; the receipt then records `placeholderMark: { allowed: true, files }`. Base's own projects are exempt.
package/global/README.md CHANGED
@@ -296,3 +296,19 @@ No global package manager installation or sudo is needed. Independent projects
296
296
  continue to run their declared commands with their own tools. Server and job
297
297
  state default to `$HOME/.rer/servers` and `$HOME/.rer/jobs`; supplied
298
298
  `RER_SERVERS_DIR` and `RER_JOBS_DIR` take precedence and are passed to older pins.
299
+
300
+ ## Inspect local business signals
301
+
302
+ `rer business scan [DIR...] [--json]` scans the current directory or the named
303
+ local directories without installing dependencies, executing project code or
304
+ using the network. It works outside RER checkouts. Both forms print one JSON
305
+ document: `{schema: "rer-business-signals/1", source: "local", signals: [...],
306
+ withheld: N}`. Signals identify package, environment, CI, infrastructure and
307
+ configuration names with a relative `locator`, repository basename `repo`,
308
+ `class` (`live-use` or `trace`) and `observedAt`.
309
+
310
+ Only names leave the scanner. Secret files are never opened and contribute
311
+ `secret-file` metadata (filename, path, size and modification time).
312
+ Sensitive-looking outbound names are dropped and counted in `withheld`.
313
+ Symlinks, generated outputs and dependency trees are skipped; unsupported
314
+ formats and syntax may yield no signals.
package/global/main.mjs CHANGED
@@ -17,6 +17,8 @@ pins (installed first by any verb when node_modules holds another), else its ven
17
17
  to 10 minutes on a first launch, or rerun it to reattach. rer dev --stop stops it.
18
18
  rer list [DIR] The checkouts in DIR (default: here), newest first, with whether rer dev can
19
19
  launch them, whether they are set up, and their running URL. --json for data.
20
+ rer business scan [DIR...] [--json]
21
+ Discover local package, config and infrastructure names without secret values.
20
22
  rer door ... The opt-in front door: every checkout at http://NAME.localhost:PORT, started
21
23
  on its first visit and stopped when idle. rer door --help for its verbs.
22
24
  rer cli status This rer: version, contents digest, install channel, launcher and other rer
@@ -50,6 +52,7 @@ export async function main(argv) {
50
52
  // verb never inherits it.
51
53
  delete process.env[localDefaults];
52
54
  if (verb === 'update') return (await import('./update/command.mjs')).update(argv.slice(1));
55
+ if (verb === 'business') return (await import('../cli/business/command.mjs')).businessCommand(argv.slice(1));
53
56
  const notice = await import('./update/notice.mjs');
54
57
  if (verb !== 'doctor' && notice.wantsNotice(argv)) await notice.updateNotice();
55
58
  if (!verb || verb === '--help' || verb === '-h' || verb === 'help') { process.stdout.write(help); return 0; }
@@ -33,13 +33,7 @@ The host forwards WebSocket upgrades through the same ingress and app session
33
33
  checks as HTTP. An app response with status 101 and a `WebSocketPair` is bridged
34
34
  in both directions, preserving text and binary messages, selected protocols,
35
35
  cookies and close codes. Refused upgrades retain their HTTP response; other
36
- upgrade protocols receive 400. Hosted demo routing selects the visitor's own
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.
36
+ upgrade protocols receive 400.
43
37
 
44
38
  The workerd source boundary permits Durable Object definitions, including export
45
39
  aliases and indirect inheritance. Unbound definitions create no namespace. The
@@ -77,7 +71,7 @@ Managed mail's `MAIL_PROVIDER`, `MAIL_FROM` and `MAIL_RELAY_URL` are public
77
71
  configuration. Keep them in the mail spec's public variables and Wrangler `vars`,
78
72
  and remove them from `deploy.json` secrets. For migration, the image builder
79
73
  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.
74
+ and prints that correction. Runtime settings override their image defaults.
81
75
  API keys, tokens and other secrets in image variables remain refused.
82
76
 
83
77
  `rer deploy --platform container --host ssh://user@host --env-file FILE` uses
@@ -90,13 +84,6 @@ headers from other peers are discarded. `RER_SSH_IDENTITY` and
90
84
  are logged. Local loopback origins support a disposable SSH Docker host for
91
85
  qualification. Owner hosting/account setup remains an owner step.
92
86
 
93
- An isolated front can set `RER_INGRESS_ORIGIN` to its primary public origin and
94
- `RER_INGRESS_ORIGINS` to a JSON array of allowed HTTPS origins. It must overwrite
95
- `x-rer-ingress-origin` on each forwarded request with its validated public
96
- origin. The container accepts that header only with a fixed primary origin and
97
- an exact allowlist match, then strips it before the app. Requests without the
98
- header, including health probes and owner claims, use the primary origin.
99
-
100
87
  A seed can package its own scoped Node runner with a declaration such as:
101
88
 
102
89
  ```json
@@ -12,13 +12,11 @@ export async function startHost({ root = '/app', data = '/data', settings = proc
12
12
  const release = await recordVolumeOwner(data);
13
13
  let engine, server, timer, idleTimer, runner, closing, closeWebSockets, lastMinute = -1, lastRequest=Date.now();
14
14
  try {
15
- const origins = settings.RER_INGRESS_ORIGINS === undefined ? undefined : JSON.parse(settings.RER_INGRESS_ORIGINS);
16
- if (origins !== undefined && (!Array.isArray(origins) || origins.some(value => { try { const url = new URL(value); return typeof value !== 'string' || url.protocol !== 'https:' || url.origin !== value; } catch { return true; } }))) throw new Error('Invalid ingress origins');
17
15
  const create = manifest.engine === 'node' ? (await import('./node-engine.mjs')).nodeEngine : (await import('./worker-engine.mjs')).workerEngine;
18
16
  engine = await create({ root,data,manifest,settings,edge });
19
17
  const schedules = (manifest.config.triggers?.crons ?? []).map(cron => [cron,parseCron(cron)]);
20
18
  const tick = async time => { for (const [cron, expression] of schedules) if (cronMatches(expression, new Date(time))) await engine.scheduled({ cron,scheduledTime:time }); await engine.drain(); };
21
- const requestFrom = req => incoming(req, { trustedProxy:settings.TRUSTED_PROXY, origin:settings.RER_INGRESS_ORIGIN, origins, maxRequestBytes:manifest.maxRequestBytes });
19
+ const requestFrom = req => incoming(req, { trustedProxy:settings.TRUSTED_PROXY, maxRequestBytes:manifest.maxRequestBytes });
22
20
  server = createServer(async (req, res) => {
23
21
  try {
24
22
  lastRequest=Date.now();
@@ -1,26 +1,12 @@
1
1
  import { Readable } from 'node:stream';
2
2
  import { lookup } from 'node:dns/promises';
3
3
  import { isIP } from 'node:net';
4
- // `origin` (RER_INGRESS_ORIGIN) fixes the public origin for a container whose only
5
- // peer is its own front, such as a hosted demo's Durable Object. That front can
6
- // select another explicitly allowed HTTPS origin with x-rer-ingress-origin.
7
- export async function incoming(req, { trustedProxy, origin, origins, maxRequestBytes = 25 * 1024 * 1024 } = {}) {
4
+ export async function incoming(req, { trustedProxy, maxRequestBytes = 25 * 1024 * 1024 } = {}) {
8
5
  const headers = new Headers(); for (const [name, value] of Object.entries(req.headers)) if (value !== undefined) headers.set(name, Array.isArray(value) ? value.join(',') : value);
9
6
  const peer = req.socket.remoteAddress?.replace('::ffff:', '') ?? '';
10
7
  const trusted = trustedProxy && (isIP(trustedProxy) ? peer===trustedProxy : (await lookup(trustedProxy,{all:true})).some(item=>item.address.replace('::ffff:','')===peer));
11
8
  let host = req.headers.host, proto = 'http', address = peer;
12
9
  if (trusted) { host = req.headers['x-forwarded-host'] ?? host; proto = req.headers['x-forwarded-proto'] ?? proto; address = req.headers['x-forwarded-for']?.split(',').at(-1)?.trim() ?? peer; }
13
- if (origin) {
14
- const requested = req.headers['x-rer-ingress-origin'];
15
- let fixed = new URL(origin);
16
- if (requested !== undefined) {
17
- let selected;
18
- try { selected = new URL(requested); } catch {}
19
- if (!Array.isArray(origins) || !origins.includes(requested) || selected?.protocol !== 'https:' || selected.origin !== requested) throw Object.assign(new Error('Invalid ingress origin'), { status: 400 });
20
- fixed = selected;
21
- }
22
- host = fixed.host; proto = fixed.protocol.slice(0, -1);
23
- }
24
10
  for (const name of ['cf-connecting-ip','x-forwarded-host','x-forwarded-proto','x-forwarded-for','forwarded','x-rer-original-url','x-rer-ingress-origin']) headers.delete(name);
25
11
  if (!['http', 'https'].includes(proto) || typeof host !== 'string' || !/^(?:[a-zA-Z0-9.-]+|\[[0-9a-fA-F:]+\])(?::[0-9]+)?$/.test(host)) throw new Error('Invalid ingress origin');
26
12
  headers.set('cf-connecting-ip', address); headers.set('host', host);
@@ -19,9 +19,8 @@ export async function workerEngine({ root, data, manifest, settings, edge }) {
19
19
  };
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
- { name:'egress',modules:[{ type:'ESModule',path:join(import.meta.dirname,'demo-egress.mjs') }],modulesRoot:import.meta.dirname,
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] } } } } }],
22
+ { name:'egress',modules:true,script:'export default {fetch(request,env){return env.NETWORK.fetch(request)}}',
23
+ serviceBindings:{ NETWORK:{ network:{ allow:['public'],tlsOptions:{ trustBrowserCas:true,trustedCertificates:[...rootCertificates] } } } } }],
25
24
  }));
26
25
  await mf.ready; const databases = {}, objects = {};
27
26
  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); }