@runeditrun/rer 0.2.19 → 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.
- package/README.md +7 -7
- package/cli/README.md +22 -21
- package/cli/adapter.mjs +5 -0
- package/cli/container.mjs +7 -2
- package/cli/contract.mjs +3 -4
- package/cli/delivery-declarations.mjs +36 -0
- package/cli/demo-host.mjs +2 -2
- package/cli/demo.mjs +16 -5
- package/cli/deploy-command.mjs +3 -0
- package/cli/deploy.mjs +4 -1
- package/cli/detached-server.mjs +2 -2
- package/cli/dev-identity.mjs +1 -1
- package/cli/export.mjs +1 -1
- package/cli/inspect.mjs +13 -13
- package/cli/lifecycle.mjs +16 -49
- package/cli/listen.mjs +31 -0
- package/cli/local.mjs +12 -18
- package/cli/main.mjs +5 -0
- package/cli/managed-server.mjs +26 -44
- package/cli/output.mjs +1 -1
- package/cli/parse.mjs +3 -3
- package/cli/port.mjs +20 -20
- package/cli/production-auth.mjs +38 -0
- package/cli/server-proxy.mjs +2 -6
- package/cli/server-registry.mjs +7 -2
- package/cli/setup-input.mjs +3 -0
- package/global/CHANGELOG.md +9 -0
- package/global/README.md +7 -7
- package/global/cli/install.mjs +4 -28
- package/global/cli/path-link.mjs +25 -21
- package/global/launch/dev.mjs +1 -1
- package/global/launch/facts.mjs +11 -14
- package/global/launch/failure.mjs +20 -0
- package/global/launch/render.mjs +2 -6
- package/global/launch/worker.mjs +3 -3
- package/global/main.mjs +1 -1
- package/modules/container/build.mjs +2 -2
- package/modules/container/demo-egress.mjs +35 -0
- package/modules/container/worker-engine.mjs +3 -3
- package/modules/d1-transport/index.d.mts +9 -0
- package/modules/d1-transport/index.mjs +124 -0
- package/modules/delivery-producer/bindings.mjs +140 -0
- package/modules/delivery-producer/declarations.mjs +49 -0
- package/modules/demo/README.md +34 -0
- package/modules/demo/effects.mjs +73 -0
- package/modules/demo/index.d.mts +15 -0
- package/modules/demo/index.mjs +63 -0
- package/modules/demo/label.d.mts +2 -0
- package/modules/demo/label.mjs +24 -0
- package/modules/demo/responses.mjs +26 -0
- package/modules/demo/sockets.mjs +13 -0
- package/modules/demo/vite.d.mts +2 -0
- package/modules/demo/vite.mjs +19 -0
- package/modules/demo-host/README.md +5 -1
- package/modules/demo-host/container.mjs +4 -4
- package/modules/demo-host/pages.mjs +1 -1
- package/modules/demo-host/worker.mjs +1 -1
- package/modules/deploy-kit/owner.mjs +2 -2
- package/modules/deploy-kit/r2-objects.mjs +8 -5
- package/modules/job-queue/storage.mjs +4 -1
- package/modules/mail/README.md +19 -86
- package/modules/mail/src/core/validation.mjs +0 -1
- package/modules/mail/src/development/index.d.mts +1 -6
- package/modules/mail/src/development/index.mjs +3 -16
- package/modules/operator-auth/README.md +10 -9
- package/modules/operator-auth/csp.mjs +1 -2
- package/modules/operator-auth/dev/cli-session.mjs +32 -0
- package/modules/operator-auth/dev/index.mjs +18 -11
- package/modules/operator-auth/identity/email-link/index.mjs +3 -0
- package/modules/operator-auth/page.mjs +1 -1
- package/modules/operator-auth/signin/index.d.mts +1 -1
- package/modules/portability/README.md +6 -0
- package/modules/portability/catalogue.mjs +1 -1
- package/modules/portability/copies.mjs +17 -2
- package/modules/portability/index.mjs +2 -0
- package/modules/portability/storage.mjs +5 -1
- package/onboarding/README.md +8 -11
- package/onboarding/adapter-auth.mjs +6 -38
- package/onboarding/adapter-labels.mjs +1 -1
- package/onboarding/adapter.mjs +8 -11
- package/onboarding/app-fetch.mjs +1 -1
- package/onboarding/dependency-approval.mjs +5 -15
- package/onboarding/dev-identity.mjs +1 -1
- package/onboarding/operator-install.mjs +6 -7
- package/onboarding/operator-installer.mjs +5 -5
- package/onboarding/operator-prerequisites.mjs +4 -5
- package/onboarding/port-probe.mjs +38 -0
- package/onboarding/process-diagnostics.mjs +36 -20
- package/onboarding/server.mjs +1 -1
- package/onboarding/ui/app.js +1 -1
- package/operations/README.md +3 -0
- package/package.json +4 -2
- package/scripts/publish-check/public_hygiene.py +31 -10
- package/modules/mail/src/development/viewer-html.mjs +0 -42
- package/modules/mail/src/development/viewer.mjs +0 -72
- package/modules/operator-auth/dev/badge.mjs +0 -44
|
@@ -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,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,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
|
|
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
|
|
@@ -6,9 +6,9 @@ import { finishStart } from './startup.mjs';
|
|
|
6
6
|
|
|
7
7
|
// One visitor's demo: a Durable Object (newUniqueId) and its container, the
|
|
8
8
|
// seed's image from `rer build --platform container` on the workerd engine.
|
|
9
|
-
// The container starts with
|
|
10
|
-
// engine
|
|
11
|
-
// through the existing signed owner claim. The demo ends at its hour or after
|
|
9
|
+
// The container starts with public internet in demo mode. withDemo simulates
|
|
10
|
+
// external effects; the engine also refuses direct mail/SMS transports. The
|
|
11
|
+
// front signs the owner in through the existing signed owner claim. The demo ends at its hour or after
|
|
12
12
|
// 15 idle minutes: the alarm destroys the container and deletes everything.
|
|
13
13
|
// The platform stops a container about two minutes after its Durable Object's
|
|
14
14
|
// last event, when the object is evicted, and the exit watcher goes with it.
|
|
@@ -76,7 +76,7 @@ export class DemoContainer extends DurableObject {
|
|
|
76
76
|
await this.ctx.storage.put({ ends, seen: now, correlation, started: this.started, startDeadline: deadline });
|
|
77
77
|
report(correlation, this.started, 'start');
|
|
78
78
|
if (this.stopped) throw new Error('container-stopped');
|
|
79
|
-
this.container.start({ enableInternet:
|
|
79
|
+
this.container.start({ enableInternet: true, env: { ...settings, RER_DEMO: '1', [originVar]: origin, RER_INGRESS_ORIGIN: origin,
|
|
80
80
|
SESSION_SECRET: random(), SETUP_TOKEN: random(), OWNER_EMAIL: OWNER, RER_OWNER_CLAIM_ISSUER: origin, RER_OWNER_CLAIM_INSTALLATION_ID: id,
|
|
81
81
|
RER_OWNER_CLAIM_PUBLIC_KEYS: JSON.stringify(keys.publicKeys), RER_DEMO_EXPIRES: endsLocal } });
|
|
82
82
|
// A container that stops by itself ends the demo too.
|
|
@@ -37,7 +37,7 @@ export function startPage(env, { status = 200, notice, pending = false, headers
|
|
|
37
37
|
const name = escape(env.DEMO_NAME);
|
|
38
38
|
return html(env, { page: 'start', title: `Try ${env.DEMO_NAME}`, status, headers, turnstile: true, refresh: pending, body: `<h1 id="title">Try ${name}</h1>
|
|
39
39
|
<p class="intro">Your own copy of ${name}, signed in as its owner, with sample data.</p>
|
|
40
|
-
<ul><li>
|
|
40
|
+
<ul><li>Public checks run live. Messages and account changes are simulated.</li><li>It ends after an hour, or 15 idle minutes.</li><li>Then it is deleted. Nobody else can see it.</li></ul>
|
|
41
41
|
<p class="notice" id="notice" role="alert"${notice ? '' : ' hidden'}>${notice ? escape(notice) : ''}</p><form id="start" method="post" action="/__demo/start" data-auto="${notice || pending ? '0' : '1'}"${pending ? ' data-resume="1" data-state="working"' : ''}><div class="cf-turnstile" data-sitekey="${escape(env.TURNSTILE_SITE_KEY)}" data-size="flexible" data-callback="rerDemoVerified" data-before-interactive-callback="rerDemoInteractive" data-after-interactive-callback="rerDemoChecking" data-expired-callback="rerDemoExpired" data-error-callback="rerDemoCheckFailed"></div>
|
|
42
42
|
<button class="button" type="submit"${pending ? ' disabled' : ''}><span class="spinner" aria-hidden="true"></span><span class="label">${pending ? 'Starting your demo…' : 'Start the demo'}</span></button>
|
|
43
43
|
<ol class="steps" aria-hidden="true"><li data-at="done">Checking you're human</li><li data-at="now">Starting a private copy</li><li data-at="next">Signing you in</li></ol>
|
|
@@ -22,7 +22,7 @@ function demoId(request, env) {
|
|
|
22
22
|
try { return env.DEMO.idFromString(value); } catch { return null; }
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
-
// The demo's end in the visitor's time zone,
|
|
25
|
+
// The demo's end in the visitor's time zone, retained in runtime settings.
|
|
26
26
|
function localTime(time, timeZone = 'UTC') {
|
|
27
27
|
const parts = Object.fromEntries(new Intl.DateTimeFormat('en-US', { timeZone, hourCycle: 'h23', year: 'numeric', month: '2-digit', day: '2-digit',
|
|
28
28
|
hour: '2-digit', minute: '2-digit', second: '2-digit', timeZoneName: 'longOffset' }).formatToParts(time).map(part => [part.type, part.value]));
|
|
@@ -101,8 +101,8 @@ function entries(declaration, key) {
|
|
|
101
101
|
assert(Array.isArray(list) && list.every(item => item && typeof item === 'object' && !Array.isArray(item) && Object.keys(item).every(k => ENTRY_KEYS[key].includes(k))), 'invalid-owner-declaration');
|
|
102
102
|
return list;
|
|
103
103
|
}
|
|
104
|
-
/* RER_DEV_KEY opens local dev identity and RER_DEMO turns on demo mode (
|
|
105
|
-
*
|
|
104
|
+
/* RER_DEV_KEY opens local dev identity and RER_DEMO turns on demo mode (mocked
|
|
105
|
+
* third-party effects, throwaway data); they and every key a seed adapter declares local-only
|
|
106
106
|
* never become a deployed binding, secret or secret source. */
|
|
107
107
|
export const LOCAL_ONLY_KEYS = Object.freeze(['RER_DEV_KEY', 'RER_DEMO', 'RER_MODELS_KEY', 'RER_MODELS_SERVICE', '.rer/local/models.json']);
|
|
108
108
|
export function localOnlyBinding(declaration, localOnlyKeys = []) {
|
|
@@ -22,15 +22,18 @@ export async function* r2ObjectPages(api, bucket) {
|
|
|
22
22
|
const data = await api.envelope(`/r2/buckets/${bucket}/objects?per_page=1000${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ''}`);
|
|
23
23
|
const rows = data.result, info = data.result_info;
|
|
24
24
|
assert(Array.isArray(rows) && rows.length <= 1000 && rows.every(row => typeof row?.key === 'string' && row.key.length), 'invalid-r2-object-list');
|
|
25
|
-
// Empty object listings may omit pagination or return null. Only that
|
|
26
|
-
// shape proves completion without explicit pagination evidence.
|
|
27
|
-
if (rows.length === 0 && info == null) { yield rows; return; }
|
|
28
|
-
assert(info && typeof info.is_truncated === 'boolean' && (!info.delimited || Array.isArray(info.delimited) && !info.delimited.length), 'provider-incomplete-pagination');
|
|
29
25
|
assert(new Set(rows.map(row => row.key)).size === rows.length, 'invalid-r2-object-list');
|
|
26
|
+
// Cloudflare may omit pagination (or return null) on any terminal page
|
|
27
|
+
// shorter than the requested limit. A full page cannot prove completion.
|
|
28
|
+
if (info == null) {
|
|
29
|
+
assert(rows.length < 1000, 'provider-incomplete-pagination');
|
|
30
|
+
yield rows; return;
|
|
31
|
+
}
|
|
32
|
+
assert(typeof info.is_truncated === 'boolean' && (!info.delimited || Array.isArray(info.delimited) && !info.delimited.length), 'provider-incomplete-pagination');
|
|
30
33
|
if (info.is_truncated) {
|
|
31
34
|
assert(rows.length > 0 && typeof info.cursor === 'string' && info.cursor.length > 0 && info.cursor.length <= 4096 && !seen.has(info.cursor), 'provider-invalid-cursor');
|
|
32
35
|
cursor = info.cursor; seen.add(cursor);
|
|
33
|
-
}
|
|
36
|
+
} else assert(info.cursor == null || info.cursor === '', 'provider-invalid-cursor');
|
|
34
37
|
yield rows;
|
|
35
38
|
if (!info.is_truncated) return;
|
|
36
39
|
}
|
|
@@ -20,7 +20,7 @@ export async function readJson(path, fallback) {
|
|
|
20
20
|
// Lamport's bakery lock: publish choosing before reading tickets, then wait for
|
|
21
21
|
// every earlier (number,id). Unique records avoid the stale-unlink/new-lock race
|
|
22
22
|
// of a single reclaimable lock file. Every publication is atomic and complete.
|
|
23
|
-
export async function transaction(directory, owner, action) {
|
|
23
|
+
export async function transaction(directory, owner, action, { validateState } = {}) {
|
|
24
24
|
const locks = join(directory, 'locks');
|
|
25
25
|
await mkdir(locks, { recursive: true, mode: 0o700 });
|
|
26
26
|
const id = randomUUID(), path = join(locks, `${id}.json`);
|
|
@@ -55,6 +55,9 @@ export async function transaction(directory, owner, action) {
|
|
|
55
55
|
while ((await participants()).some(record => record.id !== id && (record.choosing
|
|
56
56
|
|| record.number < number || (record.number === number && record.id < id)))) await delay(20);
|
|
57
57
|
const statePath = join(directory, 'state.json');
|
|
58
|
+
// Registry custody checks must share the writer's lock and precede any
|
|
59
|
+
// state read, so an atomic replacement cannot invalidate their inode.
|
|
60
|
+
await validateState?.(statePath);
|
|
58
61
|
const state = await readJson(statePath, { version: 1, sequence: 0, queued: [], running: [] });
|
|
59
62
|
if (state.version !== 1 || !Array.isArray(state.queued) || !Array.isArray(state.running)) throw Error('Invalid job queue state');
|
|
60
63
|
const result = await action(state);
|