@runeditrun/rer 0.2.18 → 0.2.20

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 (113) hide show
  1. package/README.md +7 -7
  2. package/cli/README.md +22 -21
  3. package/cli/adapter.mjs +5 -0
  4. package/cli/container.mjs +7 -2
  5. package/cli/contract.mjs +6 -4
  6. package/cli/delivery-declarations.mjs +36 -0
  7. package/cli/demo-host.mjs +2 -2
  8. package/cli/demo.mjs +16 -5
  9. package/cli/deploy-command.mjs +4 -1
  10. package/cli/deploy.mjs +4 -1
  11. package/cli/detached-server.mjs +2 -2
  12. package/cli/dev-identity.mjs +1 -1
  13. package/cli/export.mjs +1 -1
  14. package/cli/inspect.mjs +17 -15
  15. package/cli/lifecycle.mjs +16 -49
  16. package/cli/listen.mjs +31 -0
  17. package/cli/local.mjs +12 -18
  18. package/cli/main.mjs +7 -0
  19. package/cli/managed-server.mjs +26 -44
  20. package/cli/output.mjs +1 -1
  21. package/cli/parse.mjs +8 -7
  22. package/cli/port.mjs +20 -20
  23. package/cli/production-auth.mjs +38 -0
  24. package/cli/server-proxy.mjs +2 -6
  25. package/cli/server-registry.mjs +7 -2
  26. package/cli/setup-input.mjs +3 -0
  27. package/cli/signin.mjs +41 -0
  28. package/global/CHANGELOG.md +18 -0
  29. package/global/README.md +7 -7
  30. package/global/cli/install.mjs +4 -28
  31. package/global/cli/path-link.mjs +25 -21
  32. package/global/launch/dev.mjs +1 -1
  33. package/global/launch/facts.mjs +11 -14
  34. package/global/launch/failure.mjs +20 -0
  35. package/global/launch/render.mjs +2 -6
  36. package/global/launch/worker.mjs +3 -3
  37. package/global/main.mjs +3 -3
  38. package/modules/container/build.mjs +2 -2
  39. package/modules/container/demo-egress.mjs +35 -0
  40. package/modules/container/worker-engine.mjs +3 -3
  41. package/modules/d1-transport/index.d.mts +9 -0
  42. package/modules/d1-transport/index.mjs +124 -0
  43. package/modules/delivery-producer/bindings.mjs +140 -0
  44. package/modules/delivery-producer/declarations.mjs +49 -0
  45. package/modules/demo/README.md +34 -0
  46. package/modules/demo/effects.mjs +73 -0
  47. package/modules/demo/index.d.mts +15 -0
  48. package/modules/demo/index.mjs +63 -0
  49. package/modules/demo/label.d.mts +2 -0
  50. package/modules/demo/label.mjs +24 -0
  51. package/modules/demo/responses.mjs +26 -0
  52. package/modules/demo/sockets.mjs +13 -0
  53. package/modules/demo/vite.d.mts +2 -0
  54. package/modules/demo/vite.mjs +19 -0
  55. package/modules/demo-host/README.md +5 -1
  56. package/modules/demo-host/container.mjs +4 -4
  57. package/modules/demo-host/pages.mjs +1 -1
  58. package/modules/demo-host/worker.mjs +1 -1
  59. package/modules/deploy-kit/README.md +2 -0
  60. package/modules/deploy-kit/owner-cli.mjs +5 -2
  61. package/modules/deploy-kit/owner-signin.mjs +34 -0
  62. package/modules/deploy-kit/owner.mjs +2 -2
  63. package/modules/deploy-kit/r2-objects.mjs +8 -5
  64. package/modules/job-queue/storage.mjs +4 -1
  65. package/modules/mail/README.md +62 -87
  66. package/modules/mail/src/adapters/rer/contract.mjs +22 -0
  67. package/modules/mail/src/adapters/rer/index.mjs +30 -0
  68. package/modules/mail/src/core/transport.mjs +1 -1
  69. package/modules/mail/src/core/validation.mjs +6 -3
  70. package/modules/mail/src/development/index.d.mts +1 -6
  71. package/modules/mail/src/development/index.mjs +3 -16
  72. package/modules/mail/src/sender.mjs +2 -1
  73. package/modules/operator-auth/README.md +53 -9
  74. package/modules/operator-auth/accounts/email-change.mjs +34 -0
  75. package/modules/operator-auth/accounts/owner-signin.mjs +50 -0
  76. package/modules/operator-auth/accounts/schema/owner-signin.sql +10 -0
  77. package/modules/operator-auth/csp.mjs +1 -2
  78. package/modules/operator-auth/dev/cli-session.mjs +32 -0
  79. package/modules/operator-auth/dev/index.mjs +18 -11
  80. package/modules/operator-auth/identity/email-link/confirmation.mjs +3 -3
  81. package/modules/operator-auth/identity/email-link/index.mjs +4 -1
  82. package/modules/operator-auth/index.d.mts +8 -2
  83. package/modules/operator-auth/owner-signin-grant.mjs +10 -0
  84. package/modules/operator-auth/page.mjs +1 -1
  85. package/modules/operator-auth/routes.mjs +11 -1
  86. package/modules/operator-auth/service.mjs +4 -0
  87. package/modules/operator-auth/signin/index.d.mts +1 -1
  88. package/modules/portability/README.md +6 -0
  89. package/modules/portability/catalogue.mjs +1 -1
  90. package/modules/portability/copies.mjs +17 -2
  91. package/modules/portability/index.mjs +2 -0
  92. package/modules/portability/provider-data.mjs +1 -1
  93. package/modules/portability/storage.mjs +5 -1
  94. package/onboarding/README.md +8 -11
  95. package/onboarding/adapter-auth.mjs +6 -38
  96. package/onboarding/adapter-labels.mjs +1 -1
  97. package/onboarding/adapter.mjs +8 -11
  98. package/onboarding/app-fetch.mjs +1 -1
  99. package/onboarding/dependency-approval.mjs +5 -15
  100. package/onboarding/dev-identity.mjs +1 -1
  101. package/onboarding/operator-install.mjs +6 -7
  102. package/onboarding/operator-installer.mjs +5 -5
  103. package/onboarding/operator-prerequisites.mjs +4 -5
  104. package/onboarding/port-probe.mjs +38 -0
  105. package/onboarding/process-diagnostics.mjs +36 -20
  106. package/onboarding/server.mjs +1 -1
  107. package/onboarding/ui/app.js +1 -1
  108. package/operations/README.md +3 -0
  109. package/package.json +4 -2
  110. package/scripts/publish-check/public_hygiene.py +31 -10
  111. package/modules/mail/src/development/viewer-html.mjs +0 -42
  112. package/modules/mail/src/development/viewer.mjs +0 -72
  113. package/modules/operator-auth/dev/badge.mjs +0 -44
@@ -0,0 +1,124 @@
1
+ const wide = /[^\u0000-\u00ff]/;
2
+ const encoder = new TextEncoder();
3
+ const bytes = text => encoder.encode(text).byteLength;
4
+ const escaped = text => text.replace(/[^\u0000-\u00ff]/g, c => '\\u' + c.charCodeAt(0).toString(16).padStart(4, '0'));
5
+ export const RPC_LIMIT = 32 * 1024 * 1024;
6
+
7
+ // SQLite parameter tokens, excluding quoted strings/identifiers and comments.
8
+ // Keep explicit indexes and repeated names: bind() addresses SQLite slots.
9
+ function parameters(sql) {
10
+ const tokens = [], names = new Map(); let slot = 0;
11
+ const pattern = /'(?:[^']|'')*'|"(?:[^"]|"")*"|`(?:[^`]|``)*`|\[[^\]]*\]|--[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/|\?\d*|[:@$][\w\u0080-\uffff]+(?:::[\w\u0080-\uffff]+)*(?:\([^)]*\))?/g;
12
+ for (const match of sql.matchAll(pattern)) {
13
+ const token = match[0];
14
+ if (!'?:@$'.includes(token[0])) continue;
15
+ let index;
16
+ if (token[0] === '?') index = token.length > 1 ? Number(token.slice(1)) : slot + 1;
17
+ else { if (!names.has(token)) names.set(token, slot + 1); index = names.get(token); }
18
+ slot = Math.max(slot, index);
19
+ tokens.push({ start: match.index, end: match.index + token.length, index: index - 1 });
20
+ }
21
+ return tokens;
22
+ }
23
+
24
+ /** Keep wide bound text out of D1's single batch JSON string. JSON containers
25
+ * passed directly to json_each can be escaped in place; other text is quoted
26
+ * and decoded in SQLite. Stored values and transaction boundaries are unchanged.
27
+ * Values whose encoding exceeds D1's bind ceiling remain native; rpcBytes then
28
+ * accounts for their effect on the ENTIRE call, never just that parameter. */
29
+ export function wireSql(statement) {
30
+ const { sql, params = [] } = statement;
31
+ if (!params.some(value => typeof value === 'string' && wide.test(value))) return { sql, params };
32
+ const tokens = parameters(sql), values = [...params], replacements = new Set();
33
+ for (let index = 0; index < params.length; index++) {
34
+ const value = params[index];
35
+ if (typeof value !== 'string' || !wide.test(value)) continue;
36
+ const uses = tokens.filter(token => token.index === index);
37
+ if (!uses.length) continue;
38
+ const json = uses.every(token => /\bjson_each\s*\(\s*$/i.test(sql.slice(0, token.start)));
39
+ const encoded = escaped(json ? value : JSON.stringify(value));
40
+ if (bytes(encoded) > 2_000_000) continue;
41
+ values[index] = encoded;
42
+ if (!json) replacements.add(index);
43
+ }
44
+ let query = '', position = 0;
45
+ for (const token of tokens) {
46
+ query += sql.slice(position, token.start);
47
+ const original = sql.slice(token.start, token.end);
48
+ query += replacements.has(token.index) ? `json_extract(${original},'$')` : original;
49
+ position = token.end;
50
+ }
51
+ const result = { sql: query + sql.slice(position), params: values };
52
+ // Encoding is a transport representation, never permission to exceed D1's
53
+ // SQL budget. Each encoded value was checked against its bind ceiling above.
54
+ // Native text remains an admissible choice;
55
+ // the complete call below still accounts for its two-byte representation.
56
+ if (bytes(result.sql) > 100_000) return { sql, params };
57
+ return result;
58
+ }
59
+
60
+ /** A conservative size of D1's JSON request plus RPC envelope. A single wide
61
+ * character makes workerd serialize every UTF-16 code unit in the call at two
62
+ * bytes. UTF-8 also matters independently for provider payload limits. */
63
+ export function rpcSize(statements) {
64
+ let utf8 = 2, units = 2, hasWide = false;
65
+ const add = text => { utf8 += bytes(text); units += text.length; hasWide ||= wide.test(text); };
66
+ for (const statement of statements) {
67
+ add('{"sql":' + JSON.stringify(statement.sql) + ',"params":[');
68
+ for (const value of statement.params ?? []) {
69
+ if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {
70
+ // D1 sends binary bindings as numeric arrays. Four bytes per element is
71
+ // conservative and avoids constructing a second large byte array.
72
+ const size = 3 + value.byteLength * 4; utf8 += size; units += size;
73
+ } else add(JSON.stringify(value) + ',');
74
+ }
75
+ add(']},');
76
+ }
77
+ return { utf8, units, hasWide };
78
+ }
79
+ export const rpcSizeBytes = ({ utf8, units, hasWide }) => 4096 + Math.max(utf8, units * (hasWide ? 2 : 1));
80
+ export const rpcBytes = statements => rpcSizeBytes(rpcSize(statements));
81
+
82
+ export function wireBatch(statements) {
83
+ const encoded = statements.map(wireSql);
84
+ // Dense CJK may be smaller as native two-byte text than as six-byte escapes.
85
+ // Choose for the whole call: one native wide value affects every statement.
86
+ return rpcBytes(statements) < rpcBytes(encoded) ? statements : encoded;
87
+ }
88
+
89
+ /** Adapt only D1's prepare/batch boundary; native statements supplied by a
90
+ * caller remain usable (e.g. an erasure batch shared with product mutations). */
91
+ export function wireDatabase(db) {
92
+ const statements = new WeakMap();
93
+ const prepare = (sql, params = []) => {
94
+ const original = { sql, params }, query = wireBatch([original])[0];
95
+ const native = params.length ? db.prepare(query.sql).bind(...query.params) : db.prepare(sql);
96
+ const wrapped = new Proxy(native, { get(target, key) {
97
+ if (key === 'bind') return (...values) => prepare(sql, values);
98
+ const value = target[key];
99
+ if (['all', 'first', 'run', 'raw'].includes(key) && typeof value === 'function') return (...args) => {
100
+ if (rpcBytes([query]) > RPC_LIMIT) throw new Error('D1_RPC_TRANSPORT_LIMIT');
101
+ return value.apply(target, args);
102
+ };
103
+ return typeof value === 'function' ? value.bind(target) : value;
104
+ } });
105
+ statements.set(wrapped, { native, query, original });
106
+ return wrapped;
107
+ };
108
+ return new Proxy(db, { get(target, key) {
109
+ if (key === 'prepare') return prepare;
110
+ if (key === 'batch') return members => {
111
+ const known = members.map(member => statements.get(member));
112
+ const queries = wireBatch(known.filter(Boolean).map(member => member.original));
113
+ if (rpcBytes(queries) > RPC_LIMIT) throw new Error('D1_RPC_TRANSPORT_LIMIT');
114
+ let index = 0;
115
+ return db.batch(members.map((member, i) => {
116
+ if (!known[i]) return member;
117
+ const query = queries[index++];
118
+ return query.params?.length ? db.prepare(query.sql).bind(...query.params) : db.prepare(query.sql);
119
+ }));
120
+ };
121
+ const value = target[key];
122
+ return typeof value === 'function' ? value.bind(target) : value;
123
+ } });
124
+ }
@@ -0,0 +1,140 @@
1
+ /** Binding projection for the frozen CandidateDeploymentSpec, not a provider plan. */
2
+ export const bindingPattern = /^[A-Z][A-Z0-9_]{0,63}$/;
3
+ const classPattern = /^[$A-Z_a-z][$\w]*$/;
4
+ export function object(value, label) {
5
+ if (!value || typeof value !== 'object' || Array.isArray(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) throw Error(`Invalid ${label}: expected an object`);
6
+ return value;
7
+ }
8
+ export function keys(value, allowed, label) {
9
+ object(value, label);
10
+ for (const key of Object.keys(value)) if (!allowed.includes(key)) throw Error(`Unsupported ${label} field: ${key}`);
11
+ return value;
12
+ }
13
+ export function array(value, label) {
14
+ if (!Array.isArray(value)) throw Error(`Invalid ${label}: expected an array`);
15
+ return value;
16
+ }
17
+ export function string(value, label, pattern) {
18
+ if (typeof value !== 'string' || !value.trim() || (pattern && !pattern.test(value))) throw Error(`Invalid ${label}`);
19
+ return value;
20
+ }
21
+ export function strings(value, label, pattern) {
22
+ array(value, label).forEach(item => string(item, label, pattern));
23
+ if (new Set(value).size !== value.length) throw Error(`Duplicate ${label}`);
24
+ return [...value];
25
+ }
26
+ const list = (config, key) => config[key] === undefined ? [] : array(config[key], key);
27
+ const unsupported = ['services','vectorize','hyperdrive','dispatch_namespaces','mtls_certificates','workflows','pipelines','secrets_store_secrets','artifacts','ratelimits','ai','browser','images','ai_search','ai_search_namespaces','agent_memory','vpc_services','vpc_networks','worker_loaders','version_metadata','text_blobs','data_blobs','wasm_modules','containers','exports','cloudchamber','connect','unsafe_hello_world','flagship'];
28
+ // These fields configure builds, local development, or broker-owned deployment identity.
29
+ // Unknown top-level fields fail closed, including future native binding families.
30
+ const metadata = ['$schema','name','main','account_id','compatibility_date','compatibility_flags','workers_dev','preview_urls','route','routes','zone_id','usage_model','placement','limits','observability','tail_consumers','build','no_bundle','find_additional_modules','rules','base_dir','tsconfig','minify','define','alias','jsx_factory','jsx_fragment','keep_vars','send_metrics','dev','legacy_env','env','upload_source_maps','site','legacy_assets','configPath','userConfigPath','topLevelName','pages_build_output_dir','preserve_file_names','definedEnvironments','python_modules'];
31
+ function empty(value) {
32
+ return value === undefined || (Array.isArray(value) ? value.length === 0 : value && typeof value === 'object' && Object.keys(value).length === 0);
33
+ }
34
+ export function validateWranglerShape(config) {
35
+ keys(config, [...metadata,...unsupported,'vars','d1_databases','r2_buckets','kv_namespaces','analytics_engine_datasets','queues','durable_objects','migrations','triggers','send_email','assets','unsafe','logfwdr'], 'Wrangler');
36
+ for (const key of unsupported) if (!empty(config[key])) throw Error(`Unsupported deployment binding: ${key}; an explicit consumer contract is required`);
37
+ for (const key of ['tail_consumers','site','legacy_assets','env']) if (!empty(config[key])) throw Error(`Unsupported deployment configuration: ${key}`);
38
+ for (const key of ['unsafe','logfwdr']) {
39
+ if (config[key] === undefined) continue;
40
+ keys(config[key], ['bindings'], key);
41
+ if (list(config[key], 'bindings').length) throw Error(`Unsupported deployment binding: ${key}`);
42
+ }
43
+ if (config.assets !== undefined) {
44
+ keys(config.assets, ['directory','binding','run_worker_first','html_handling','not_found_handling'], 'assets');
45
+ if (config.assets.binding !== undefined && config.assets.binding !== 'ASSETS') throw Error('Unsupported assets binding: consumer requires ASSETS');
46
+ if (config.assets.run_worker_first !== undefined && config.assets.run_worker_first !== true) throw Error('Unsupported assets run_worker_first: consumer runs Worker first');
47
+ for (const key of ['html_handling','not_found_handling']) if (config.assets[key] !== undefined) throw Error(`Unsupported assets option: ${key}`);
48
+ }
49
+ }
50
+ const emailPattern = /^[^\s@<>\x00-\x1f\x7f]+@[^\s@<>\x00-\x1f\x7f]+\.[^\s@<>\x00-\x1f\x7f]+$/;
51
+ export function validateEmailSending(value) {
52
+ const names = new Set();
53
+ return array(value, 'emailSending').map(item => {
54
+ keys(item, ['binding','destinationAddress','allowedDestinationAddresses','allowedSenderAddresses'], 'emailSending');
55
+ string(item.binding, 'email binding', bindingPattern);
56
+ if (names.has(item.binding)) throw Error(`Duplicate email binding: ${item.binding}`);
57
+ names.add(item.binding);
58
+ if (item.destinationAddress !== undefined && item.allowedDestinationAddresses !== undefined) throw Error(`Conflicting email recipient restrictions: ${item.binding}`);
59
+ const result = {binding:item.binding};
60
+ if (item.destinationAddress !== undefined) result.destinationAddress = string(item.destinationAddress, 'email destinationAddress', emailPattern);
61
+ for (const key of ['allowedDestinationAddresses','allowedSenderAddresses']) if (item[key] !== undefined) {
62
+ const addresses = strings(item[key], `email ${key}`, emailPattern);
63
+ if (!addresses.length) throw Error(`Empty email ${key}`);
64
+ result[key] = addresses;
65
+ }
66
+ return result;
67
+ });
68
+ }
69
+ export function wranglerBindings(config) {
70
+ validateWranglerShape(config);
71
+ const resources = [];
72
+ for (const [field,kind,allowed] of [
73
+ ['d1_databases','d1',['binding','database_name','database_id','preview_database_id','migrations_dir','migrations_table','remote']],
74
+ ['r2_buckets','r2',['binding','bucket_name','preview_bucket_name','jurisdiction','remote']],
75
+ ['kv_namespaces','kv',['binding','id','preview_id','remote']],
76
+ ['analytics_engine_datasets','analytics_engine',['binding','dataset']],
77
+ ]) for (const item of list(config, field)) {
78
+ keys(item, allowed, field);
79
+ // A candidate requests installation-local resources. Geography cannot be erased.
80
+ if (item.jurisdiction !== undefined) throw Error(`Unsupported ${field} jurisdiction`);
81
+ resources.push({kind,binding:string(item.binding, `${field} binding`, bindingPattern)});
82
+ }
83
+ const queues = config.queues === undefined ? {} : keys(config.queues, ['producers','consumers'], 'queues');
84
+ const producers = list(queues, 'producers');
85
+ const queueNames = new Map();
86
+ for (const item of producers) {
87
+ keys(item, ['binding','queue'], 'queue producer');
88
+ const binding = string(item.binding, 'queue binding', bindingPattern);
89
+ string(item.queue, 'queue name');
90
+ if (queueNames.has(item.queue)) throw Error(`Ambiguous queue name: ${item.queue}`);
91
+ queueNames.set(item.queue, binding);
92
+ resources.push({kind:'queue',binding});
93
+ }
94
+ // Preserve the established d1, r2, queue, kv, analytics ordering.
95
+ resources.sort((a,b) => ['d1','r2','queue','kv','analytics_engine'].indexOf(a.kind) - ['d1','r2','queue','kv','analytics_engine'].indexOf(b.kind));
96
+ const queueBinding = name => {
97
+ if (!queueNames.has(name)) throw Error('Queue consumer must reference declared producer binding');
98
+ return queueNames.get(name);
99
+ };
100
+ const queueConsumers = list(queues, 'consumers').map(item => {
101
+ keys(item, ['queue','max_batch_size','max_batch_timeout','max_retries','dead_letter_queue'], 'queue consumer');
102
+ return {binding:queueBinding(item.queue), maxBatchSize:item.max_batch_size === undefined ? 10 : item.max_batch_size, maxBatchTimeout:item.max_batch_timeout === undefined ? 5 : item.max_batch_timeout, maxRetries:item.max_retries === undefined ? 3 : item.max_retries, ...(item.dead_letter_queue === undefined ? {} : {deadLetterBinding:queueBinding(item.dead_letter_queue)})};
103
+ });
104
+ const durable = config.durable_objects === undefined ? {} : keys(config.durable_objects, ['bindings'], 'durable_objects');
105
+ const durableObjects = list(durable, 'bindings').map(item => {
106
+ keys(item, ['name','class_name','script_name','environment'], 'Durable Object binding');
107
+ if (item.script_name !== undefined || item.environment !== undefined) throw Error('External Durable Object bindings require an explicit delivery contract');
108
+ return {binding:string(item.name, 'Durable Object binding', bindingPattern),className:string(item.class_name, 'Durable Object class', classPattern)};
109
+ });
110
+ const durableObjectMigrations = list(config, 'migrations').map(item => {
111
+ keys(item, ['tag','new_sqlite_classes','new_classes','deleted_classes','renamed_classes','transferred_classes'], 'Durable Object migration');
112
+ const result = {tag:item.tag,newSqliteClasses:item.new_sqlite_classes === undefined ? [] : item.new_sqlite_classes};
113
+ for (const [from,to] of [['new_classes','newClasses'],['deleted_classes','deletedClasses'],['renamed_classes','renamedClasses']]) if (item[from] !== undefined) result[to] = item[from];
114
+ if (item.transferred_classes !== undefined) result.transferredClasses = array(item.transferred_classes, 'transferred_classes').map(transfer => {
115
+ keys(transfer, ['from','from_script','to'], 'Durable Object transfer');
116
+ return {from:transfer.from,fromScript:transfer.from_script,to:transfer.to};
117
+ });
118
+ return result;
119
+ });
120
+ const emailSending = validateEmailSending(list(config, 'send_email').map(item => {
121
+ keys(item, ['name','destination_address','allowed_destination_addresses','allowed_sender_addresses'], 'send_email');
122
+ return {binding:item.name,...(item.destination_address === undefined ? {} : {destinationAddress:item.destination_address}),...(item.allowed_destination_addresses === undefined ? {} : {allowedDestinationAddresses:item.allowed_destination_addresses}),...(item.allowed_sender_addresses === undefined ? {} : {allowedSenderAddresses:item.allowed_sender_addresses})};
123
+ }));
124
+ return {resources,durableObjects,durableObjectMigrations,queueConsumers,...(emailSending.length ? {emailSending} : {})};
125
+ }
126
+ export function validateDurableMigrations(value) {
127
+ const tags = new Set();
128
+ for (const item of array(value, 'durableObjectMigrations')) {
129
+ keys(item, ['tag','newSqliteClasses','newClasses','deletedClasses','renamedClasses','transferredClasses'], 'Durable Object migration');
130
+ string(item.tag, 'Durable Object migration tag', /^[\w.-]+$/);
131
+ if (tags.has(item.tag)) throw Error('Duplicate Durable Object migration tag');
132
+ tags.add(item.tag);
133
+ for (const key of ['newSqliteClasses','newClasses','deletedClasses']) if (item[key] !== undefined) strings(item[key], key, classPattern);
134
+ for (const key of ['renamedClasses','transferredClasses']) if (item[key] !== undefined) for (const row of array(item[key], key)) {
135
+ keys(row, key === 'renamedClasses' ? ['from','to'] : ['from','to','fromScript'], key);
136
+ string(row.from, `${key} from`, classPattern); string(row.to, `${key} to`, classPattern);
137
+ if (key === 'transferredClasses') string(row.fromScript, 'transfer fromScript', /^[-a-z0-9]{1,63}$/);
138
+ }
139
+ }
140
+ }
@@ -0,0 +1,49 @@
1
+ import {array, bindingPattern, keys, string, strings} from './bindings.mjs';
2
+
3
+ const pathPattern = /^\/[A-Za-z0-9/_.~-]*$/;
4
+ const status = (value, label) => {
5
+ if (!Number.isInteger(value) || value < 100 || value > 599) throw Error(`Invalid ${label}`);
6
+ };
7
+
8
+ /** Preserve source-owned preview and setup declarations, without authorizing effects. */
9
+ export function validateDeclarations(spec) {
10
+ if (spec.providerEffects !== undefined) {
11
+ if (strings(spec.providerEffects, 'providerEffects', /^[a-z][a-z0-9-]{0,63}$/).length > 32) throw Error('Too many provider effects');
12
+ }
13
+ if (spec.surfaces !== undefined) {
14
+ keys(spec.surfaces, ['app','page','websitePreview'], 'surfaces');
15
+ if (!spec.surfaces.app) throw Error('Surfaces require an app');
16
+ const origins = new Map();
17
+ for (const [name, surface] of Object.entries(spec.surfaces)) {
18
+ keys(surface, ['path','hostnameVariable','originVariable','readiness'], 'surface');
19
+ string(surface.path, 'surface path', pathPattern);
20
+ if (surface.hostnameVariable !== undefined && surface.originVariable !== undefined) throw Error('Surface must choose one address variable');
21
+ for (const field of ['hostnameVariable','originVariable']) if (surface[field] !== undefined) string(surface[field], field, bindingPattern);
22
+ if (surface.originVariable !== undefined) {
23
+ const previous = origins.get(surface.originVariable);
24
+ if (previous !== undefined) throw Error(`Duplicate originVariable ${surface.originVariable} on surfaces.${previous} and surfaces.${name}`);
25
+ origins.set(surface.originVariable, name);
26
+ }
27
+ if (surface.readiness !== undefined) {
28
+ const probes = array(surface.readiness, 'surface readiness');
29
+ if (!probes.length || probes.length > 32) throw Error('Invalid readiness probe count');
30
+ for (const probe of probes) {
31
+ keys(probe, ['path','statuses','pendingSetupStatuses'], 'readiness probe');
32
+ string(probe.path, 'readiness path', pathPattern);
33
+ for (const field of ['statuses','pendingSetupStatuses']) if (field === 'statuses' || probe[field] !== undefined) {
34
+ const codes = array(probe[field], field);
35
+ if (!codes.length || codes.length > 16 || new Set(codes).size !== codes.length) throw Error(`Invalid ${field}`);
36
+ codes.forEach(code => status(code, field));
37
+ }
38
+ }
39
+ }
40
+ }
41
+ }
42
+ if (spec.initialSetup !== undefined) {
43
+ keys(spec.initialSetup, ['path','pendingStatus','completeStatus'], 'initialSetup');
44
+ string(spec.initialSetup.path, 'initial setup path', pathPattern);
45
+ status(spec.initialSetup.pendingStatus, 'pending setup status');
46
+ status(spec.initialSetup.completeStatus, 'complete setup status');
47
+ if (spec.initialSetup.pendingStatus === spec.initialSetup.completeStatus) throw Error('Setup statuses must differ');
48
+ }
49
+ }
@@ -0,0 +1,34 @@
1
+ # Demo mode
2
+
3
+ Import `withDemo` first in the Worker entry and wrap the worker with
4
+ `withDemo(worker, { seed })`. It changes behavior only with `RER_DEMO=1`.
5
+ Production build/deploy refuses that setting; ordinary builds keep real effects.
6
+
7
+ - Public internet reads and checks run for real: pages, feeds, previews and
8
+ monitor probes against any URL. GET, HEAD and OPTIONS use the real network.
9
+ A check using POST uses `fetchDemoRead(url, init)` to declare read intent.
10
+ Redirects pass through the same policy at every hop.
11
+ - Third-party writes are mocked: external POST, PUT, PATCH and DELETE, message
12
+ APIs and webhook URLs return success without contacting their destination.
13
+ Common mail, SMS and chat providers receive their normal success envelope;
14
+ generic JSON writes receive their submitted resource with a generated ID.
15
+ For an SDK, binding or another non-HTTP transport use
16
+ `demoEffect(() => realSend(), () => providerSuccess)` around the effect.
17
+ Without `RER_DEMO` this always executes `realSend`. A seed with a richer
18
+ provider response should supply its own exact success shape this way.
19
+ - Mail in local dev and demo is silently suppressed. There is no outbox or
20
+ blocked-send UI. Logs contain only the mocked request's method and host.
21
+ - `seed(env, { ownerEmail, now })` runs once after the owner exists and must
22
+ be idempotent. Its only table is the demo's throwaway `rer_demo` marker.
23
+ - Base adds ` Demo` to the document title, including client-side navigation.
24
+ Put `data-rer-name` on the product's text label, for example
25
+ `<span data-rer-name>Uptime</span>`, to show **Uptime Demo** in its nav.
26
+ The same attribute shows **Uptime Dev** under the local dev wrapper. No bar,
27
+ layout offset or timer is injected. CSS adds the label suffix without
28
+ changing the application's hydrated text; CSP allows exact hashes only.
29
+
30
+ Public sockets, WebSockets and event streams remain usable for checks. The
31
+ local sockets guard and hosted egress retain a small direct mail/SMS denylist;
32
+ use the effect helper for such sends. Hosted demos keep their isolated
33
+ container, Turnstile, per-IP start limit, TTL/idle end and maximum instances.
34
+ See [adoption and hosting](../../export/DEMO.md).
@@ -0,0 +1,73 @@
1
+ import { isLoopbackHost } from '../operator-auth/http.mjs';
2
+ import { effectSuccess } from './responses.mjs';
3
+
4
+ const readRequests = new WeakSet();
5
+ let installed = false;
6
+
7
+ // Read intent stays in memory, never in a header the remote server could use.
8
+ export function fetchDemoRead(input, init) {
9
+ const request = new Request(input, init);
10
+ readRequests.add(request);
11
+ return globalThis.fetch(request);
12
+ }
13
+
14
+ function isEffect(request, url) {
15
+ if (isLoopbackHost(url.hostname) || readRequests.has(request)) return false;
16
+ if (!['GET', 'HEAD', 'OPTIONS'].includes(request.method)) return true;
17
+ // Some message APIs deliver even with GET. Public page/monitor GETs stay real.
18
+ return url.hostname === 'hooks.slack.com'
19
+ || ['discord.com', 'discordapp.com'].includes(url.hostname) && url.pathname.startsWith('/api/webhooks/')
20
+ || url.hostname === 'slack.com' && url.pathname === '/api/chat.postMessage'
21
+ || url.hostname === 'api.telegram.org' && /\/(?:sendMessage|sendPhoto|sendDocument)$/.test(url.pathname);
22
+ }
23
+
24
+ export function guardConnect(address) {
25
+ const name = String(address?.hostname ?? 'localhost');
26
+ const url = typeof address === 'string' ? new URL(`http://${address}`) : new URL(`http://${name.includes(':') && !name.startsWith('[') ? `[${name}]` : name}:${address?.port}`);
27
+ if (!isLoopbackHost(url.hostname) && [25, 465, 587, 2525].includes(Number(url.port))) throw new TypeError('Demo direct mail transport is disabled; wrap the send with demoEffect.');
28
+ }
29
+
30
+ export function installDemoEffects() {
31
+ if (installed) return;
32
+ installed = true;
33
+ const send = globalThis.fetch;
34
+ globalThis.fetch = async function demoFetch(input, init) {
35
+ const read = input instanceof Request && readRequests.has(input);
36
+ let request = new Request(input, init);
37
+ if (read) readRequests.add(request);
38
+ const follow = request.redirect === 'follow';
39
+ for (let hops = 0; ; hops++) {
40
+ const url = new URL(request.url);
41
+ if (isEffect(request, url)) {
42
+ console.info(`rer_demo_mock ${request.method} ${url.host}`);
43
+ return effectSuccess(request);
44
+ }
45
+ if (!follow) return send(request);
46
+ const response = await send(request.clone(), { redirect: 'manual' });
47
+ const location = response.headers.get('location');
48
+ if (![301, 302, 303, 307, 308].includes(response.status) || location === null) return response;
49
+ if (hops === 20) throw new TypeError('fetch failed: too many redirects');
50
+ await response.body?.cancel();
51
+ const next = new URL(location, url);
52
+ const get = response.status === 303 && !['GET', 'HEAD'].includes(request.method) || [301, 302].includes(response.status) && request.method === 'POST';
53
+ const headers = new Headers(request.headers);
54
+ if (get) for (const name of ['content-type', 'content-length', 'content-encoding', 'content-language', 'content-location']) headers.delete(name);
55
+ if (next.origin !== url.origin) for (const name of ['authorization', 'cookie', 'proxy-authorization']) headers.delete(name);
56
+ request = new Request(next, { method: get ? 'GET' : request.method, headers, body: get ? null : request.body, redirect: 'manual', signal: request.signal });
57
+ if (read) readRequests.add(request);
58
+ }
59
+ };
60
+ if (typeof globalThis.navigator?.sendBeacon === 'function') globalThis.navigator.sendBeacon = () => true;
61
+ const net = globalThis.process?.getBuiltinModule?.('node:net');
62
+ if (net?.Socket) {
63
+ const open = net.Socket.prototype.connect;
64
+ net.Socket.prototype.connect = function connect(...args) {
65
+ const [first, second] = Array.isArray(args[0]) ? args[0] : args;
66
+ const options = first !== null && typeof first === 'object' ? first : { port: first, host: typeof second === 'string' ? second : undefined };
67
+ if (options.path !== undefined && options.port === undefined) return open.apply(this, args);
68
+ try { guardConnect({ hostname: options.host, port: options.port }); }
69
+ catch (error) { queueMicrotask(() => this.destroy(error)); return this; }
70
+ return open.apply(this, args);
71
+ };
72
+ }
73
+ }
@@ -0,0 +1,15 @@
1
+ /** A seed's idempotent demo data, run once after the owner exists. */
2
+ export type SeedDemo<Env> = (env: Env, context: { ownerEmail: string; now: Date }) => Promise<void>;
3
+ export interface DemoOptions<Env> {
4
+ seed?: SeedDemo<Env>;
5
+ /** The D1 binding for the demo's seeding marker (default DB). */
6
+ binding?: string;
7
+ /** The active owner's email, or null before one exists (default: Base operator-auth's owner). */
8
+ owner?: (env: Env) => Promise<string | null>;
9
+ }
10
+ /** Demo mode for a seed's Worker; returns the worker unchanged unless RER_DEMO=1. Import it first. */
11
+ export function withDemo<Env, Handler extends { fetch?: (request: never, env: Env, execution: never) => unknown }>(worker: Handler, options?: DemoOptions<Env>): Handler;
12
+ /** Real public checks that use a write-shaped HTTP method (such as POST probes). */
13
+ export function fetchDemoRead(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
14
+ /** Mock a non-HTTP send only in a demo, otherwise run the real send. */
15
+ export function demoEffect<Result>(send: () => Result | Promise<Result>, success: Result | (() => Result | Promise<Result>)): Promise<Result>;
@@ -0,0 +1,63 @@
1
+ // Import first in the Worker entry. Production build/deploy rejects RER_DEMO.
2
+ import { env } from 'cloudflare:workers';
3
+ import { installDemoEffects, guardConnect as checkConnect } from './effects.mjs';
4
+ import { decorateLabel } from './label.mjs';
5
+
6
+ const on = env?.RER_DEMO === '1';
7
+ if (on) installDemoEffects();
8
+ let database = 'DB';
9
+ const db = () => env[database];
10
+
11
+ /** Direct mail transports are denied; use demoEffect around non-HTTP sends. */
12
+ export function guardConnect(address) { if (on) checkConnect(address); }
13
+
14
+ /** Non-HTTP effects (bindings, SDKs): supply the provider's success shape. */
15
+ export async function demoEffect(send, success) {
16
+ return on ? (typeof success === 'function' ? success() : success) : send();
17
+ }
18
+
19
+ /** A public read/check which uses POST, for example a monitor or DNS query. */
20
+ export { fetchDemoRead } from './effects.mjs';
21
+
22
+ let tables;
23
+ function ready() {
24
+ return tables ??= db().batch([
25
+ db().prepare('CREATE TABLE IF NOT EXISTS rer_demo (name TEXT PRIMARY KEY NOT NULL, value TEXT NOT NULL)'),
26
+ ]).catch(error => { tables = undefined; throw error; });
27
+ }
28
+
29
+ // Base operator-auth's owner; a seed with its own accounts passes `owner`.
30
+ async function operatorOwner(bindings) {
31
+ const row = await bindings[database].prepare("SELECT email FROM oa_operators WHERE role = 'owner' AND status = 'active' ORDER BY created_at LIMIT 1").first();
32
+ return row?.email ?? null;
33
+ }
34
+
35
+ let seeded = false, seeding;
36
+ async function seedOnce(bindings, seed, owner) {
37
+ if (seeded) return;
38
+ await ready();
39
+ if (!seed) { seeded = true; return; }
40
+ if (await db().prepare("SELECT 1 FROM rer_demo WHERE name = 'seeded'").first()) { seeded = true; return; }
41
+ const ownerEmail = await owner(bindings);
42
+ if (!ownerEmail) return;
43
+ const now = new Date();
44
+ await seed(bindings, { ownerEmail, now });
45
+ await db().prepare("INSERT OR IGNORE INTO rer_demo(name, value) VALUES ('seeded', ?)").bind(now.toISOString()).run();
46
+ seeded = true;
47
+ }
48
+
49
+ /** Adds demo data and product labels; all effects are real without RER_DEMO. */
50
+ export function withDemo(worker, { seed, binding = 'DB', owner = operatorOwner } = {}) {
51
+ if (!on) return worker;
52
+ database = binding;
53
+ const prepared = bindings => seeding ??= seedOnce(bindings, seed, owner).finally(() => { seeding = undefined; });
54
+ return {
55
+ ...worker,
56
+ async fetch(request, bindings, execution) {
57
+ await prepared(bindings);
58
+ return decorateLabel(await worker.fetch(request, bindings, execution), 'Demo');
59
+ },
60
+ ...(worker.scheduled ? { async scheduled(controller, bindings, execution) { await prepared(bindings); return worker.scheduled(controller, bindings, execution); } } : {}),
61
+ ...(worker.queue ? { async queue(batch, bindings, execution) { await prepared(bindings); return worker.queue(batch, bindings, execution); } } : {}),
62
+ };
63
+ }
@@ -0,0 +1,2 @@
1
+ /** Suffix the document title and the text marked data-rer-name, without a bar. */
2
+ export function decorateLabel(response: Response, mode: 'Demo' | 'Dev'): Promise<Response>;
@@ -0,0 +1,24 @@
1
+ import { allow, sha256 } from '../operator-auth/csp.mjs';
2
+
3
+ // CSS leaves React's text alone during hydration. The title observer handles
4
+ // client-side route changes, whose head manager writes a fresh title.
5
+ export async function decorateLabel(response, mode) {
6
+ if (!response.body || !response.headers.get('content-type')?.toLowerCase().startsWith('text/html')) return response;
7
+ const suffix = mode === 'Demo' ? 'Demo' : 'Dev';
8
+ const style = `[data-rer-name]::after{content:" ${suffix}"}`;
9
+ const script = `(()=>{const suffix=${JSON.stringify(suffix)},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})})()`;
10
+ const html = await response.text();
11
+ if (html.includes('data-rer-label=')) return new Response(html, response);
12
+ const headers = new Headers(response.headers);
13
+ let policy = headers.get('content-security-policy');
14
+ if (policy) {
15
+ policy = allow(policy, 'style-src', await sha256(style));
16
+ headers.set('content-security-policy', allow(policy, 'script-src', await sha256(script)));
17
+ }
18
+ headers.delete('content-length');
19
+ headers.delete('etag');
20
+ const addition = `<style data-rer-label="${suffix}">${style}</style><script>${script}</script>`;
21
+ const titled = html.replace(/(<title\b[^>]*>)([\s\S]*?)(<\/title>)/i, (_, open, title, close) => `${open}${title.replace(/ (?:Demo|Dev)$/, '')} ${suffix}${close}`);
22
+ const body = /<\/head\s*>/i.test(titled) ? titled.replace(/<\/head\s*>/i, `${addition}</head>`) : addition + titled;
23
+ return new Response(body, { status: response.status, statusText: response.statusText, headers });
24
+ }
@@ -0,0 +1,26 @@
1
+ // Used only by the RER_DEMO guard. Never log credentials, recipients or bodies.
2
+ export async function effectSuccess(request) {
3
+ const url = new URL(request.url), host = url.hostname, path = url.pathname;
4
+ const id = `demo_${crypto.randomUUID()}`;
5
+ const json = (body, status = 200, headers = {}) => Response.json(body, { status, headers });
6
+ if (host === 'api.sendgrid.com' && path === '/v3/mail/send') return new Response(null, { status: 202, headers: { 'x-message-id': id } });
7
+ if (host === 'api.resend.com') return json({ id });
8
+ if (host === 'api.twilio.com') return json({ sid: `SM${crypto.randomUUID().replaceAll('-', '')}`, status: 'queued', error_code: null, error_message: null }, 201);
9
+ if (host === 'api.postmarkapp.com') return json({ ErrorCode: 0, Message: 'OK', MessageID: id, SubmittedAt: new Date().toISOString() });
10
+ if (host.endsWith('mailgun.net')) return json({ id: `<${id}@demo.invalid>`, message: 'Queued. Thank you.' });
11
+ if (host === 'slack.com') return json({ ok: true, channel: 'demo', ts: `${Math.floor(Date.now() / 1000)}.000001`, message: { type: 'message', text: 'Message sent' } });
12
+ if (host === 'hooks.slack.com' || host.endsWith('.webhook.office.com') || host.endsWith('.logic.azure.com')) return new Response(host === 'hooks.slack.com' ? 'ok' : '1');
13
+ if (host === 'api.stripe.com') {
14
+ const form = new URLSearchParams(await request.text());
15
+ if (path === '/v1/checkout/sessions') return json({ id, object: 'checkout.session', status: 'complete', payment_status: 'paid', url: (form.get('success_url') ?? form.get('return_url'))?.replaceAll('{CHECKOUT_SESSION_ID}', id) });
16
+ return json({ id, object: path.split('/')[2]?.replace(/s$/, ''), status: 'succeeded', paid: true, client_secret: `${id}_secret_demo` });
17
+ }
18
+ if (/\/(?:oauth2?|auth)\/(?:v\d+\/)?token\/?$/i.test(path) || path.endsWith('/oauth/access_token')) return json({ access_token: id, token_type: 'Bearer', expires_in: 3600, refresh_token: `demo_${crypto.randomUUID()}` });
19
+ let resource = {};
20
+ if (request.headers.get('content-type')?.includes('application/json')) {
21
+ try { const body = await request.json(); if (body && typeof body === 'object' && !Array.isArray(body)) resource = body; } catch { /* Empty sends are valid too. */ }
22
+ }
23
+ if (host === 'api.linear.app') return json({ data: { issueCreate: { success: true, issue: { ...resource.variables?.input, id, identifier: 'DEMO-1', url: 'https://demo.invalid/issue/DEMO-1' } } } });
24
+ if (request.method === 'DELETE') return new Response(null, { status: 204 });
25
+ return json({ ...resource, id, ok: true, success: true, status: 'sent', messageId: id, message_id: id, data: { id } }, host === 'api.github.com' || host === 'graph.microsoft.com' ? 201 : 200);
26
+ }
@@ -0,0 +1,13 @@
1
+ // `rer demo` resolves the Worker's `cloudflare:sockets` imports here (vite.mjs):
2
+ // Public probes work; direct mail transports are denied as a second defense.
3
+ import { guardConnect } from './index.mjs';
4
+
5
+ // Vite would resolve a static import of it back to this file; a computed
6
+ // specifier reaches the runtime's own module.
7
+ const runtime = 'cloudflare:sockets';
8
+ const { connect: open } = await import(/* @vite-ignore */ runtime);
9
+
10
+ export function connect(address, options) {
11
+ guardConnect(address);
12
+ return open(address, options);
13
+ }
@@ -0,0 +1,2 @@
1
+ /** Under `rer demo`, resolves the Worker's `cloudflare:sockets` imports to demo mode's guarded connect. */
2
+ export function demoSockets(): { name: string; apply: 'serve'; enforce: 'pre'; config(): object | undefined; resolveId(id: string): string | undefined };
@@ -0,0 +1,19 @@
1
+ import { fileURLToPath } from 'node:url';
2
+
3
+ // A module namespace cannot be patched at runtime, so under `rer demo`
4
+ // (RER_DEMO=1) Vite hands the Worker's `cloudflare:sockets` imports the guarded
5
+ // connect in sockets.mjs instead. A seed lists it first in vite.config's plugins.
6
+ export function demoSockets() {
7
+ const guarded = fileURLToPath(new URL('./sockets.mjs', import.meta.url));
8
+ const on = () => process.env.RER_DEMO === '1';
9
+ return {
10
+ name: 'rer-demo-sockets',
11
+ apply: 'serve',
12
+ enforce: 'pre',
13
+ // Vite resolves a Worker's builtin import only when an alias names it.
14
+ config: () => on() ? { resolve: { alias: [{ find: /^cloudflare:sockets$/, replacement: 'cloudflare:sockets' }] } } : undefined,
15
+ resolveId(id) {
16
+ if (on() && id === 'cloudflare:sockets') return guarded;
17
+ },
18
+ };
19
+ }
@@ -17,7 +17,7 @@ it with these files and the seed's container image folder (workerd engine) to
17
17
  with that cookie goes to the visitor's Durable Object; nothing else reaches
18
18
  a container.
19
19
  - `container.mjs`: `DemoContainer`, one per visitor (`newUniqueId`, checked
20
- with `idFromString`). It starts the container with `enableInternet: false`,
20
+ with `idFromString`). It starts the container with public internet enabled,
21
21
  `RER_DEMO=1`, the fixed origin (`RER_INGRESS_ORIGIN` and the seed's origin
22
22
  variable), fresh `SESSION_SECRET` and `SETUP_TOKEN`,
23
23
  `OWNER_EMAIL=owner@demo.invalid` and the owner claim's issuer, installation
@@ -25,6 +25,10 @@ it with these files and the seed's container image folder (workerd engine) to
25
25
  (`claim.mjs`) to `/auth/owner-claim`. Its alarm ends the demo at its hour or
26
26
  after 15 idle minutes: `destroy()`, `deleteAll()` and the place released. A
27
27
  container that stops by itself ends its demo too.
28
+ Public internet reads and checks run against real services. The app's demo
29
+ guard simulates effects on people and third-party accounts, while the
30
+ container egress independently refuses direct mail/SMS provider transports
31
+ and SMTP ports. Public-address filtering and TLS remain enforced.
28
32
  The platform stops a container about two minutes after its Durable Object's
29
33
  last event, when it evicts the object (and the object's exit watcher with
30
34
  it). So the alarm stays in flight until the demo's next check, at most three