@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.
- 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 +6 -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 +4 -1
- 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 +17 -15
- package/cli/lifecycle.mjs +16 -49
- package/cli/listen.mjs +31 -0
- package/cli/local.mjs +12 -18
- package/cli/main.mjs +7 -0
- package/cli/managed-server.mjs +26 -44
- package/cli/output.mjs +1 -1
- package/cli/parse.mjs +8 -7
- 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/cli/signin.mjs +41 -0
- package/global/CHANGELOG.md +18 -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 +3 -3
- 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/README.md +2 -0
- package/modules/deploy-kit/owner-cli.mjs +5 -2
- package/modules/deploy-kit/owner-signin.mjs +34 -0
- 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 +62 -87
- package/modules/mail/src/adapters/rer/contract.mjs +22 -0
- package/modules/mail/src/adapters/rer/index.mjs +30 -0
- package/modules/mail/src/core/transport.mjs +1 -1
- package/modules/mail/src/core/validation.mjs +6 -3
- package/modules/mail/src/development/index.d.mts +1 -6
- package/modules/mail/src/development/index.mjs +3 -16
- package/modules/mail/src/sender.mjs +2 -1
- package/modules/operator-auth/README.md +53 -9
- package/modules/operator-auth/accounts/email-change.mjs +34 -0
- package/modules/operator-auth/accounts/owner-signin.mjs +50 -0
- package/modules/operator-auth/accounts/schema/owner-signin.sql +10 -0
- 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/confirmation.mjs +3 -3
- package/modules/operator-auth/identity/email-link/index.mjs +4 -1
- package/modules/operator-auth/index.d.mts +8 -2
- package/modules/operator-auth/owner-signin-grant.mjs +10 -0
- package/modules/operator-auth/page.mjs +1 -1
- package/modules/operator-auth/routes.mjs +11 -1
- package/modules/operator-auth/service.mjs +4 -0
- 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/provider-data.mjs +1 -1
- 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
package/cli/lifecycle.mjs
CHANGED
|
@@ -11,10 +11,10 @@ import { missing, refuse, RerError, lifecycleError } from './errors.mjs';
|
|
|
11
11
|
import { executeDeclared } from './independent.mjs';
|
|
12
12
|
import { transfer } from './transfers.mjs';
|
|
13
13
|
import { runtimeFrontDoor } from './runtime-front-door.mjs';
|
|
14
|
-
import { localCliSessionProof, localSettingKeys
|
|
14
|
+
import { localCliSessionProof, localSettingKeys } from './settings.mjs';
|
|
15
15
|
import { rememberSetupAnswers } from './setup-answers.mjs';
|
|
16
|
-
import { ensureDevKey,
|
|
17
|
-
import { announceDoorRoute
|
|
16
|
+
import { ensureDevKey, refuseDevLayerOutput } from './dev-identity.mjs';
|
|
17
|
+
import { announceDoorRoute } from './door-mode.mjs';
|
|
18
18
|
|
|
19
19
|
export async function runCommand(project, options, out) {
|
|
20
20
|
if (options.verb === 'deploy' && !options.site && !options.demo) {
|
|
@@ -27,6 +27,8 @@ export async function runCommand(project, options, out) {
|
|
|
27
27
|
}
|
|
28
28
|
|
|
29
29
|
async function runLifecycle(project, options, out, deployRedaction) {
|
|
30
|
+
if (project.profile === 'first-party' && ['build','deploy'].includes(options.verb) && !options.demo && !options.site && process.env.RER_DEMO) throw refuse('Production build and deploy refuse the local-only RER_DEMO environment binding. Unset it before retrying.');
|
|
31
|
+
if(project.profile==='first-party'&&options.verb==='outbox')throw refuse('Captured mail has been retired. Run rer dev and open its RER_OPEN link.');
|
|
30
32
|
if(project.profile==='first-party'&&['dev','preview'].includes(options.verb))return (await import('./managed-server.mjs')).managedServer(project,options,out);
|
|
31
33
|
const cancellation = new AbortController(), signal = cancellation.signal;
|
|
32
34
|
let termination, operation, store, temporary, proxy, failed = false;
|
|
@@ -46,17 +48,16 @@ async function runLifecycle(project, options, out, deployRedaction) {
|
|
|
46
48
|
if (!project.adapter?.run) throw refuse('The first-party command adapter is unavailable. Restore the shared lifecycle adapter.');
|
|
47
49
|
if (options.forwarded.length) throw refuse('First-party commands do not accept arbitrary forwarded arguments. Run rer VERB --help.');
|
|
48
50
|
await stateSafety(project);
|
|
49
|
-
if(options.verb==='setup')await refuseLegacyProcess(project);
|
|
50
|
-
if (
|
|
51
|
+
if(options.verb==='setup')await refuseLegacyProcess(project,{verb:options.verb});
|
|
52
|
+
if (options.verb === 'setup') {
|
|
51
53
|
selected = await selectedOrigin(project, options, { setup: options.verb === 'setup' });
|
|
52
54
|
if (options.verb === 'setup') {input = await setupInput(project, options, selected.vars, signal, { origin: selected.url });await dependencyInputs({project,input,origin:selected.url});}
|
|
53
|
-
|
|
54
|
-
if (options.verb !== 'outbox' && !selected.door) await availablePort(selected.host, selected.port, { root: project.root, saved: !selected.explicitPort && selected.savedOrigin !== undefined });
|
|
55
|
+
if (!selected.door) await availablePort(selected.host, selected.port, { root: project.root, saved: !selected.explicitPort && selected.savedOrigin !== undefined, verb:options.verb });
|
|
55
56
|
if (options.verb === 'setup') announcePort(out, options, selected);
|
|
56
57
|
}
|
|
57
58
|
const { localOperation } = await shared('local/operation.mjs');
|
|
58
59
|
// The run site reads no local state: it builds beside a running rer dev.
|
|
59
|
-
if (
|
|
60
|
+
if (!options.site) try { operation = await localOperation(project.root, process.env.RER_LOCAL_OPERATION); } catch (error) { throw refuse(error.message); }
|
|
60
61
|
const { recoverInterrupted } = await shared('local/recovery.mjs');
|
|
61
62
|
if (operation) await recoverInterrupted(project.root, operation);
|
|
62
63
|
if (project.ownerReplacement) await replaceOwner(project, options, out);
|
|
@@ -66,7 +67,7 @@ async function runLifecycle(project, options, out, deployRedaction) {
|
|
|
66
67
|
// Nested public commands stream into their caller's capture and keep their
|
|
67
68
|
// own log separate, including the browser install/setup/preview journey.
|
|
68
69
|
const capture = ['.seed', 'installer', ...(process.env.RER_LOCAL_OPERATION || process.env.RER_ONBOARDING_PROCESS_OWNER ? [`commands-${process.pid}`] : [])];
|
|
69
|
-
const directory = project.profile === 'first-party' &&
|
|
70
|
+
const directory = project.profile === 'first-party' && options.verb !== 'doctor' ? await privateDirectory(project.root, capture) : (temporary = await mkdtemp(join(tmpdir(), 'rer-command-')));
|
|
70
71
|
const state = { logs: [] };
|
|
71
72
|
store = await createCommands(directory, state, { terminal: text => out.progress(text), onWaiting: options.json ? details => out.event('waiting', details) : undefined, queue: ['install','setup','build','verify','deploy','export','import'].includes(options.verb)?{verb:options.verb,originalCI:process.env.CI==='true'}:undefined });
|
|
72
73
|
store.state = state;
|
|
@@ -101,30 +102,19 @@ async function runLifecycle(project, options, out, deployRedaction) {
|
|
|
101
102
|
if (options.verb === 'deploy') {
|
|
102
103
|
if (typeof adapter.deploy !== 'function') throw refuse('Owner-account deploy declaration is missing.');
|
|
103
104
|
const link = async (origin, appSetupToken) => linkDependencies({project,input:project.setupSeed?await savedSetupAnswers(project,project.setupSeed.model):undefined,origin,store,signal,appSetupToken});
|
|
104
|
-
return await (await import('./deploy-command.mjs')).deployCommand({ adapter, root: project.root, options, store, signal, operationToken: operation.token, localOnlyKeys: adapter.localOnlyKeys ?? [], checkBuild: () => refuseDevLayerOutput(project.root, adapter.devIdentity), setupManifest: project.setupManifest, linkDependencies: link });
|
|
105
|
+
return await (await import('./deploy-command.mjs')).deployCommand({ adapter, root: project.root, options, store, signal, operationToken: operation.token, localOnlyKeys: adapter.localOnlyKeys ?? [], checkBuild: () => refuseDevLayerOutput(project.root, adapter.devIdentity), setupManifest: project.setupManifest, setupSeed: project.setupSeed, linkDependencies: link });
|
|
105
106
|
}
|
|
106
|
-
|
|
107
|
-
// outbox reads present it. Captured logs redact it.
|
|
108
|
-
const devKey = adapter.devIdentity ? options.verb === 'setup' ? await ensureDevKey(project.root) : await readDevKey(project.root) : null;
|
|
107
|
+
const devKey = adapter.devIdentity && options.verb === 'setup' ? await ensureDevKey(project.root) : null;
|
|
109
108
|
if (devKey) store.addSecrets?.([devKey]);
|
|
110
109
|
let app;
|
|
111
110
|
if (options.verb === 'setup') { proxy = await runtimeFrontDoor({ ...selected, devKey: devKey ?? undefined, origin: selected.url }); if (selected.door) await announceDoorRoute(selected, proxy); }
|
|
112
|
-
// The outbox of a door-mode checkout is read from its running server's own
|
|
113
|
-
// proxy, never through the door: with no such server nothing is sent. A key
|
|
114
|
-
// is sent only once the door has proved it is this account's.
|
|
115
|
-
if (options.verb === 'outbox' && selected?.door) {
|
|
116
|
-
const running = await runningRecord(project.root);
|
|
117
|
-
if (!running?.door) throw new RerError('outbox_unavailable', 'The local application outbox is unavailable. Start rer dev first.', 1);
|
|
118
|
-
if (devKey) await verifyDoorFor(selected.url);
|
|
119
|
-
await routeRunning(running);
|
|
120
|
-
}
|
|
121
111
|
const { appFetch } = await shared('app-fetch.mjs');
|
|
122
112
|
const emailKey = localSettingKeys(project).email;
|
|
123
113
|
await adapter.run(project.root, input ?? { [emailKey]: options.ownerEmail ?? selected?.vars[emailKey] }, store,
|
|
124
114
|
child => { app = child; }, signal,
|
|
125
|
-
{ verb: options.verb, ownerKey: emailKey, selectedOrigin: selected?.url, runtimePort: proxy?.runtimePort, operationToken: operation?.token, dev: adapter.dev, privateSettings: [...adapter.settings, '.rer/local/models.json', ...(project.privateInputs??[])],
|
|
115
|
+
{ verb: options.verb, ownerKey: emailKey, selectedOrigin: selected?.url, runtimePort: proxy?.runtimePort, operationToken: operation?.token, dev: adapter.dev, privateSettings: [...adapter.settings, '.rer/local/models.json', ...(project.privateInputs??[])], devKey: devKey ?? undefined });
|
|
126
116
|
if (['setup', 'build'].includes(options.verb)) await refuseDevLayerOutput(project.root, adapter.devIdentity);
|
|
127
|
-
const url = selected?.url
|
|
117
|
+
const url = selected?.url;
|
|
128
118
|
if (options.verb === 'setup') {
|
|
129
119
|
// Only a connected provider leaves first setup open; a native claim with
|
|
130
120
|
// every optional dependency unanswered has already closed it.
|
|
@@ -138,16 +128,8 @@ async function runLifecycle(project, options, out, deployRedaction) {
|
|
|
138
128
|
}
|
|
139
129
|
await store.stop(app);
|
|
140
130
|
await rememberSetupAnswers(project, input);
|
|
141
|
-
if (options.json) out.event('setup-ready', { url,
|
|
142
|
-
else
|
|
143
|
-
else { out.human(`RER_SETUP_READY ${url}`); signInInstructions(out, signInUrl); out.human(`Finish first-run setup at ${url}/setup after sign-in.`); out.human('Next: rer dev'); }
|
|
144
|
-
} else if (options.verb === 'outbox') {
|
|
145
|
-
const response = await appFetch(signInUrl, { headers: devKey ? { [DEV_KEY_HEADER]: devKey } : {}, signal: AbortSignal.any([signal, AbortSignal.timeout(5000)]) }).catch(() => ({ ok: false }));
|
|
146
|
-
if (!response.ok) throw new RerError('outbox_unavailable', 'The local application outbox is unavailable. Start rer dev first.', 1);
|
|
147
|
-
await response.body?.cancel();
|
|
148
|
-
const open = devKey ? openUrl(url, devKey, { path: '/__dev/key', next: '/__dev/outbox' }) : signInUrl;
|
|
149
|
-
if (options.json) out.event('outbox', { signInUrl, ...(devKey ? { openUrl: open } : {}) }); else { signInInstructions(out, signInUrl); if (devKey) out.human(`RER_OPEN ${open}`); }
|
|
150
|
-
if (options.open && !options.json && !options.nonInteractive) await store.run('Opening local outbox', process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'explorer.exe' : 'xdg-open', [open], { cwd: project.root, signal });
|
|
131
|
+
if (options.json) out.event('setup-ready', { url, setupUrl: url+'/setup' });
|
|
132
|
+
else { out.human(`RER_SETUP_READY ${url}`); out.human(`Next: rer dev opens ${url} signed in as the owner; first-run setup finishes at ${url}/setup.`); }
|
|
151
133
|
} else if (options.verb !== 'build') throw refuse('The requested first-party capability is unavailable.');
|
|
152
134
|
return {};
|
|
153
135
|
} catch (error) {
|
|
@@ -169,16 +151,6 @@ async function runLifecycle(project, options, out, deployRedaction) {
|
|
|
169
151
|
}
|
|
170
152
|
}
|
|
171
153
|
|
|
172
|
-
// This checkout's running server, from the shared registry (routeRunning
|
|
173
|
-
// checks that it is alive and holds its proxy port).
|
|
174
|
-
async function runningRecord(root) {
|
|
175
|
-
const { readJson } = await import('../modules/job-queue/storage.mjs');
|
|
176
|
-
const { serversDirectory } = await import('./server-registry.mjs');
|
|
177
|
-
const { realpath } = await import('node:fs/promises');
|
|
178
|
-
const checkout = await realpath(root), state = await readJson(join(serversDirectory(), 'state.json'), { running: [] });
|
|
179
|
-
return (state.running ?? []).find(record => record.checkout === checkout);
|
|
180
|
-
}
|
|
181
|
-
|
|
182
154
|
// Under the local operation, before the app starts: the zero-setup owner's
|
|
183
155
|
// row and saved owner setting become the real owner's, and one line says so.
|
|
184
156
|
async function replaceOwner(project, options, out) {
|
|
@@ -203,8 +175,3 @@ function announcePort(out, options, selected) {
|
|
|
203
175
|
if (options.json) out.event('port', { port: selected.port, ...(moved ? { movedFrom: moved.from } : {}) });
|
|
204
176
|
else out.human(line);
|
|
205
177
|
}
|
|
206
|
-
|
|
207
|
-
function signInInstructions(out, url) {
|
|
208
|
-
out.human(`RER_SIGN_IN ${url}`);
|
|
209
|
-
out.human('Open the outbox, choose the newest sign-in message and follow its link. No email was sent.');
|
|
210
|
-
}
|
package/cli/listen.mjs
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
2
|
+
import { refuse } from './errors.mjs';
|
|
3
|
+
import { shared } from './shared.mjs';
|
|
4
|
+
import { busyPortMessage } from './port.mjs';
|
|
5
|
+
|
|
6
|
+
// Bind the actual serving socket, including the race after a successful
|
|
7
|
+
// preflight. Only a positive listener observation names another process.
|
|
8
|
+
export async function listen(server, host, port) {
|
|
9
|
+
let context;
|
|
10
|
+
for (;;) {
|
|
11
|
+
try {
|
|
12
|
+
await new Promise((resolve, reject) => {
|
|
13
|
+
const ready = () => { cleanup(); resolve(); }, failed = error => { cleanup(); reject(error); };
|
|
14
|
+
const cleanup = () => { server.removeListener('listening', ready); server.removeListener('error', failed); };
|
|
15
|
+
server.once('listening', ready); server.once('error', failed);
|
|
16
|
+
try { server.listen(port, host); } catch (error) { failed(error); }
|
|
17
|
+
});
|
|
18
|
+
return;
|
|
19
|
+
} catch (error) {
|
|
20
|
+
if (error.code !== 'EADDRINUSE') throw refuse(`Could not listen on ${host} port ${port}: ${error.code === 'EACCES' ? 'permission denied' : error.code ?? 'socket error'}. Check the address and permissions, then run rer dev again or use rer setup --port PORT with a free port.`);
|
|
21
|
+
const unavailable = async listener => refuse(await busyPortMessage({ port, host, root: process.cwd(), context, listener: listener ?? null }));
|
|
22
|
+
if (context && performance.now() >= context.deadline) throw await unavailable();
|
|
23
|
+
const { inspectionContext } = await shared('process-diagnostics.mjs');
|
|
24
|
+
const { probePort } = await shared('port-probe.mjs');
|
|
25
|
+
context ??= inspectionContext({ port });
|
|
26
|
+
const result = await probePort(host, port, { context });
|
|
27
|
+
if (!result.available) throw await unavailable(result.listener);
|
|
28
|
+
await delay(Math.min(100, Math.max(0, context.deadline - performance.now())));
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
package/cli/local.mjs
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { lstat, readdir, rm } from 'node:fs/promises';
|
|
2
2
|
import { resolve, relative } from 'node:path';
|
|
3
|
-
import { createServer } from 'node:net';
|
|
4
3
|
import { createInterface } from 'node:readline/promises';
|
|
5
4
|
import { contained } from './project.mjs';
|
|
6
5
|
import { shared } from './shared.mjs';
|
|
@@ -39,19 +38,14 @@ export async function selectedOrigin(project, options, { setup = false } = {}) {
|
|
|
39
38
|
return { url, host, port, vars, savedOrigin: previous?.origin, moved, explicitPort: options.port !== undefined, ...(taken ? { skipped: defaultPort } : {}) };
|
|
40
39
|
}
|
|
41
40
|
|
|
42
|
-
export async function availablePort(host, port, { root, saved = false } = {}) {
|
|
43
|
-
const {
|
|
44
|
-
const
|
|
45
|
-
const
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
}
|
|
51
|
-
finally { if (socket.listening) await new Promise(resolve => socket.close(resolve)); }
|
|
52
|
-
// A server on every address (*:port) lets a bind to 127.0.0.1 succeed.
|
|
53
|
-
const listener = await portListener(port, host, context);
|
|
54
|
-
if (listener) throw refuse(await busyPortMessage({ port, host, root, saved, context, listener }));
|
|
41
|
+
export async function availablePort(host, port, { root, saved = false, verb = 'dev' } = {}) {
|
|
42
|
+
const { inspectionContext } = await shared('process-diagnostics.mjs');
|
|
43
|
+
const { probePort } = await shared('port-probe.mjs');
|
|
44
|
+
const context = inspectionContext({port,verb});
|
|
45
|
+
const result = await probePort(host, port, { context });
|
|
46
|
+
if (result.available) return;
|
|
47
|
+
if (result.code && result.code !== 'EADDRINUSE') throw refuse(`Port ${port} cannot be used on ${host}: ${result.code}. Check the address or use rer setup --port PORT with a free port, then run rer dev again.`);
|
|
48
|
+
throw refuse(await busyPortMessage({ port, host, root, saved, context, listener: result.listener ?? null }));
|
|
55
49
|
}
|
|
56
50
|
|
|
57
51
|
export {setupInput} from './setup-input.mjs';
|
|
@@ -72,7 +66,7 @@ async function safeTree(project, path) {
|
|
|
72
66
|
|
|
73
67
|
export async function reset(project, options, out) {
|
|
74
68
|
await stateSafety(project);
|
|
75
|
-
await refuseLegacyProcess(project,{reset:true});
|
|
69
|
+
await refuseLegacyProcess(project,{reset:true,verb:'reset'});
|
|
76
70
|
const { strandedOriginals } = await shared('local/recovery.mjs');
|
|
77
71
|
if ((await strandedOriginals(project.root)).length) throw refuse('An interrupted build holds private settings. Run rer build to recover them before reviewing reset.');
|
|
78
72
|
// The seed's own safety check (legacy data it still has to recover, for
|
|
@@ -104,12 +98,12 @@ export async function reset(project, options, out) {
|
|
|
104
98
|
return { paths: inventory };
|
|
105
99
|
}
|
|
106
100
|
|
|
107
|
-
export async function refuseLegacyProcess(project,{reset=false}={}) {
|
|
101
|
+
export async function refuseLegacyProcess(project,{reset=false,verb='dev'}={}) {
|
|
108
102
|
let selected;try{selected=await selectedOrigin(project,{});}catch(error){if(!reset)throw error;}
|
|
109
103
|
// Confirmed reset can recover malformed settings; checkout/state custody is
|
|
110
104
|
// still checked even when there is no usable saved origin.
|
|
111
|
-
const {localProcessConflict}=await shared('process-diagnostics.mjs');
|
|
105
|
+
const {localProcessConflict,inspectionContext}=await shared('process-diagnostics.mjs');
|
|
112
106
|
// The front door holds a door origin's port, not this checkout.
|
|
113
|
-
const conflict=await localProcessConflict(project.root,selected?.door?undefined:selected?.savedOrigin);
|
|
107
|
+
const conflict=await localProcessConflict(project.root,selected?.door?undefined:selected?.savedOrigin,inspectionContext({verb}));
|
|
114
108
|
if(conflict)throw refuse(`A local process holds ${conflict.reason}: PID ${conflict.pid} (${conflict.command}). Stop it with kill -TERM ${conflict.pid}, then retry. Use rer dev --stop or rer preview --stop for a registered server.`);
|
|
115
109
|
}
|
package/cli/main.mjs
CHANGED
|
@@ -39,8 +39,15 @@ export async function main(argv = process.argv.slice(2)) {
|
|
|
39
39
|
if (!options.json) out.human(JSON.stringify(result, null, 2));
|
|
40
40
|
out.result(result.ok, result.ok ? 0 : 3, { diagnostics: result }); return result.ok ? 0 : 3;
|
|
41
41
|
}
|
|
42
|
+
// The owner link is printed once to this terminal: never through the logged lifecycle.
|
|
43
|
+
if (options.verb === 'signin') { out.result(true, 0, await (await import('./signin.mjs')).signinCommand(project, options, out)); return 0; }
|
|
42
44
|
// A checkout without a declared run site refuses --site before any effect.
|
|
43
45
|
if (options.site) (await import('./site.mjs')).declaredSite(project);
|
|
46
|
+
if (options.verb === 'deploy' && !options.site && !options.demo && !options.remove && !options.setSecret && !options.unsetSecret) {
|
|
47
|
+
const { deliveryDeclarationClauses } = await import('./delivery-declarations.mjs');
|
|
48
|
+
const failures = (await deliveryDeclarationClauses(project.root)).filter(clause => !clause.ok);
|
|
49
|
+
if (failures.length) throw new RerError('invalid_deployment_declaration', failures.map(clause => clause.message).join('\n'), 1);
|
|
50
|
+
}
|
|
44
51
|
const bounded=await (await import('./bounded.mjs')).boundedCommand(project,options,argv,out);
|
|
45
52
|
if(bounded)return bounded.exitCode;
|
|
46
53
|
if(options.platform==='container' && !['export','import'].includes(options.verb)) { const result = await (await import('./container.mjs')).containerCommand(project,options,out); out.result(true,0,result); return 0; }
|
package/cli/managed-server.mjs
CHANGED
|
@@ -14,29 +14,22 @@ import { tools } from './inspect.mjs';
|
|
|
14
14
|
import { invalid,missing,refuse,RerError,lifecycleError } from './errors.mjs';
|
|
15
15
|
import { processInfo } from '../modules/job-queue/processes.mjs';
|
|
16
16
|
import { declaredCrons,runScheduled } from './scheduled.mjs';
|
|
17
|
-
import {
|
|
18
|
-
import { readDevKey,requireDevKey,refuseManagedInstallation,resolvePersona,openUrl
|
|
17
|
+
import { demoGuarded,demoPreflight } from './demo.mjs';
|
|
18
|
+
import { readDevKey,requireDevKey,refuseManagedInstallation,resolvePersona,openUrl } from './dev-identity.mjs';
|
|
19
19
|
import { announceDoorRoute,claimSavedName,moveCheckout,routeRunning,verifyDoorFor } from './door-mode.mjs';
|
|
20
20
|
|
|
21
|
-
//
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
// serves no outbox (a seed's preview without one) is not pointed at it.
|
|
25
|
-
// A seed that declares a run site also gets RER_SITE: its static run site
|
|
26
|
-
// (homepage, /run, docs) served locally on its own port, after the ready lines.
|
|
27
|
-
// A demo adds RER_DEMO_ENDS_ON_STOP: its own data folder, deleted when it stops.
|
|
28
|
-
export function ready(out,url,dev,json=false,outbox=true,siteUrl,demo){
|
|
29
|
-
const signInUrl=url+'/__dev/outbox',open=dev&&(dev.identity||outbox);
|
|
30
|
-
if(json){out.event('ready',{url,...(outbox?{signInUrl}:{}),...(dev?{signedInAs:dev.signedInAs??null,...(open?{openUrl:dev.openUrl}:{})}:{}),...(siteUrl?{siteUrl}:{}),...(demo?{demo}:{})});return;}
|
|
21
|
+
// Dev opens through the local identity exchange. Preview serves production output.
|
|
22
|
+
export function ready(out,url,dev,json=false,siteUrl,demo){
|
|
23
|
+
if(json){out.event('ready',{url,...(dev?{signedInAs:dev.signedInAs??null,openUrl:dev.openUrl}:{}),...(siteUrl?{siteUrl}:{}),...(demo?{demo}:{})});return;}
|
|
31
24
|
out.human(`RER_READY ${url}`);
|
|
32
|
-
if(dev
|
|
33
|
-
|
|
34
|
-
out.human(
|
|
35
|
-
|
|
36
|
-
out.human(
|
|
25
|
+
if(dev){
|
|
26
|
+
if(dev.signedInAs)out.human(`RER_SIGNED_IN ${dev.signedInAs}`);
|
|
27
|
+
else if(dev.ownerLeft)out.human('No active owner remains in this app. Use rer dev --as PERSONA with an active operator, or rer reset --yes and rer setup for a new owner.');
|
|
28
|
+
out.human(`RER_OPEN ${dev.openUrl}`);
|
|
29
|
+
out.human("Open that link on this computer. Its fragment holds this checkout's dev key, which the page keeps only as a cookie; never share the link.");
|
|
37
30
|
}
|
|
38
31
|
if(siteUrl)out.human(`RER_SITE ${siteUrl}`);
|
|
39
|
-
if(demo){out.human(`RER_DEMO_ENDS_ON_STOP ${demo.state}`);out.human(`This demo runs on its own data in that folder, which is deleted when it stops: rer demo --stop, Ctrl-C, or at its end (${demo.ends.slice(11,16)}).
|
|
32
|
+
if(demo){out.human(`RER_DEMO_ENDS_ON_STOP ${demo.state}`);out.human(`This demo runs on its own data in that folder, which is deleted when it stops: rer demo --stop, Ctrl-C, or at its end (${demo.ends.slice(11,16)}). Public reads and checks run for real; external writes are simulated. This checkout's own data is untouched.`);}
|
|
40
33
|
}
|
|
41
34
|
export async function managedServer(project,options,out,{clock={}}={}){
|
|
42
35
|
const registry=await serverRegistry(project.root),controller=new AbortController();
|
|
@@ -74,7 +67,6 @@ export async function managedServer(project,options,out,{clock={}}={}){
|
|
|
74
67
|
await registry.existing(mode,options);
|
|
75
68
|
if(options.verb==='dev' && (running.models??'fake')!==(options.models??'fake'))throw refuse('Stop the running dev server before changing --models mode.');
|
|
76
69
|
if(options.modelsService)throw refuse('Stop the running dev server before saving live-dev credentials.');
|
|
77
|
-
if(options.verb==='dev'&&Boolean(running.login)!==Boolean(options.login))throw refuse(`The running dev server ${running.login?'uses':'does not use'} --login. Stop it with rer dev --stop to change sign-in mode.`);
|
|
78
70
|
// A door-mode server is probed on its own proxy, never through the door.
|
|
79
71
|
await claimSavedName(project,running.url);
|
|
80
72
|
await routeRunning(running);
|
|
@@ -84,8 +76,8 @@ export async function managedServer(project,options,out,{clock={}}={}){
|
|
|
84
76
|
if(devIdentity)devKey=await requireDevKey(project.root);
|
|
85
77
|
// A key is sent (or printed) for a door origin only once the door proves it is ours.
|
|
86
78
|
if(devIdentity)await verifyDoorFor(running.url);
|
|
87
|
-
const dev=devIdentity&&await devReady(running.url,devKey,options,controller.signal);
|
|
88
|
-
await emitReady(out,options,project.root,running.url,dev,
|
|
79
|
+
const dev=devIdentity&&options.verb==='dev'&&await devReady(running.url,devKey,options,controller.signal);
|
|
80
|
+
await emitReady(out,options,project.root,running.url,dev,running.siteUrl,running.demo);return {reused:true};
|
|
89
81
|
}
|
|
90
82
|
await registry.serve(async action=>{
|
|
91
83
|
if(action==='status')return {...activity?.snapshot(),url:selected?.url,probe:proxy?.probe,siteUrl:site?.url,demo};
|
|
@@ -93,7 +85,7 @@ export async function managedServer(project,options,out,{clock={}}={}){
|
|
|
93
85
|
throw Error('Unknown management operation');
|
|
94
86
|
});
|
|
95
87
|
await stateSafety(project);
|
|
96
|
-
await refuseLegacyProcess(project);
|
|
88
|
+
await refuseLegacyProcess(project,{verb:options.verb});
|
|
97
89
|
const {localOperation}=await shared('local/operation.mjs');
|
|
98
90
|
try{operation=await localOperation(project.root);}catch(error){throw refuse(error.message);}
|
|
99
91
|
const {recoverInterrupted}=await shared('local/recovery.mjs');await recoverInterrupted(project.root,operation);
|
|
@@ -101,15 +93,15 @@ export async function managedServer(project,options,out,{clock={}}={}){
|
|
|
101
93
|
const seed=project.adapter.setup?await loadInstallerSeed(project.root,project.adapter):undefined;project.setupManifest=seed?.manifest;
|
|
102
94
|
const keys=localSettingKeys(project);
|
|
103
95
|
selected=await selectedOrigin(project,options);
|
|
104
|
-
if(!selected.door)await availablePort(selected.host,selected.port,{root:project.root,saved:!selected.explicitPort&&selected.savedOrigin!==undefined});
|
|
96
|
+
if(!selected.door)await availablePort(selected.host,selected.port,{root:project.root,saved:!selected.explicitPort&&selected.savedOrigin!==undefined,verb:options.verb});
|
|
105
97
|
if(!selected.vars[keys.email])throw missing('Private owner settings are missing. Run rer setup first.');
|
|
106
98
|
if(devIdentity&&!devKey)devKey=await requireDevKey(project.root);
|
|
107
|
-
if(devIdentity&&options.verb==='dev'
|
|
108
|
-
if(
|
|
109
|
-
await
|
|
99
|
+
if(devIdentity&&options.verb==='dev')refuseManagedInstallation(selected.vars,process.env);
|
|
100
|
+
if(options.demo)demo=await demoPreflight(project,selected.vars,options.idleTimeout);
|
|
101
|
+
else if(project.adapter.localPrerequisites&&!await project.adapter.localPrerequisites({root:project.root,vars:selected.vars,email:selected.vars[keys.email],demo:false}))throw missing('Local migrations, owner or local authentication/mail settings are missing. Run rer setup first.');
|
|
102
|
+
await registry.update({url:selected.url,host:selected.host,port:selected.port,models:options.models??'fake'});
|
|
110
103
|
const {privateDirectory}=await shared('private-files.mjs');
|
|
111
|
-
if(
|
|
112
|
-
else await privateDirectory(project.root,['.wrangler','state']);
|
|
104
|
+
if(!demo)await privateDirectory(project.root,['.wrangler','state']);
|
|
113
105
|
const directory=await privateDirectory(project.root,['.seed','installer',...(process.env.RER_ONBOARDING_PROCESS_OWNER?[`commands-${process.pid}`]:[])]);
|
|
114
106
|
const {createCommands}=await shared('commands.mjs');const state={logs:[]};
|
|
115
107
|
store=await createCommands(directory,state,{terminal:text=>out.progress(text),onWaiting:options.json?details=>out.event('waiting',details):undefined,custodyToken:registry.custodyToken(),queue:{verb:options.verb,originalCI:process.env.CI==='true'}});
|
|
@@ -122,7 +114,7 @@ export async function managedServer(project,options,out,{clock={}}={}){
|
|
|
122
114
|
proxy=await runtimeFrontDoor({host:selected.host,port:selected.port,activity,door:selected.door,devKey:devKey??undefined,origin:selected.url});const internal=proxy.runtimePort;
|
|
123
115
|
if(selected.door)await announceDoorRoute(selected,proxy,registry);
|
|
124
116
|
const modelsLive = options.verb==='dev' ? await prepareLiveModels(project.root,options,store,controller.signal) : undefined;
|
|
125
|
-
const adapterOptions={modelsLive,demo,selectedOrigin:selected.url,operationToken:operation.token,privateSettings:project.adapter.settings,runtimePort:internal,devKey:devKey??undefined,devLogin:
|
|
117
|
+
const adapterOptions={modelsLive,demo,selectedOrigin:selected.url,operationToken:operation.token,privateSettings:project.adapter.settings,runtimePort:internal,devKey:devKey??undefined,devLogin:false,scheduled:crons.length>0};
|
|
126
118
|
const input={[keys.email]:selected.vars[keys.email]};
|
|
127
119
|
if(options.verb==='preview')await productionBuild(project,()=>store.run('Building fixed production output',process.execPath,[fileURLToPath(new URL('../bin/rer.mjs',import.meta.url)),'build','--cwd',project.root,'--json'],{cwd:project.root,phase:'build',signal:controller.signal,env:{...process.env,RER_LOCAL_OPERATION:operation.token},afterCommand:()=>recoverInterrupted(project.root,operation)}),text=>store.report(text));
|
|
128
120
|
await serverResources(project.root);
|
|
@@ -136,12 +128,11 @@ export async function managedServer(project,options,out,{clock={}}={}){
|
|
|
136
128
|
// A key is sent (or printed) for a door origin only once the door proves it is ours.
|
|
137
129
|
if(devKey)await verifyDoorFor(selected.url);
|
|
138
130
|
if(demo)await demoGuarded(selected.url,demo.state,controller.signal);
|
|
139
|
-
const dev=devIdentity&&await devReady(selected.url,devKey,options,controller.signal);
|
|
140
|
-
const outbox=await outboxServed(selected.url,devKey,controller.signal);
|
|
131
|
+
const dev=devIdentity&&options.verb==='dev'&&await devReady(selected.url,devKey,options,controller.signal);
|
|
141
132
|
if(options.verb==='dev'&&project.adapter.site){
|
|
142
133
|
const {devSite}=await import('./site.mjs');
|
|
143
134
|
try {
|
|
144
|
-
site=await devSite(project,store,controller.signal,{host:selected.host,port:
|
|
135
|
+
site=await devSite(project,store,controller.signal,{host:selected.host,port:proxy.port});
|
|
145
136
|
await registry.update({siteUrl:site.url});
|
|
146
137
|
} catch(error) {
|
|
147
138
|
if(error.code!=='site_private_data')throw error;
|
|
@@ -149,7 +140,7 @@ export async function managedServer(project,options,out,{clock={}}={}){
|
|
|
149
140
|
if(options.json)out.event('warning',{code:error.code,message});else out.progress(`Warning: ${message}\n`);
|
|
150
141
|
}
|
|
151
142
|
}
|
|
152
|
-
activity.ready();await emitReady(out,options,project.root,selected.url,dev,
|
|
143
|
+
activity.ready();await emitReady(out,options,project.root,selected.url,dev,site?.url,demo);
|
|
153
144
|
if(crons.length){
|
|
154
145
|
out.progress(`Running ${crons.length===1?'the scheduled trigger':'the scheduled triggers'} locally: ${crons.join(' | ')}\n`);
|
|
155
146
|
void runScheduled({crons,url:`http://127.0.0.1:${internal}`,path:options.verb==='preview'?'/cdn-cgi/local/scheduled':undefined,signal:scheduling.signal,report:run=>reportScheduled(out,options,run)});
|
|
@@ -166,26 +157,17 @@ function reportScheduled(out,options,run){
|
|
|
166
157
|
const at=new Date().toISOString().replace(/\.\d+Z$/,'Z'),outcome=run.skipped?`skipped (${error})`:run.ok?`ok ${run.ms}ms`:`failed (${run.status?`HTTP ${run.status}`:error}) ${run.ms}ms`;
|
|
167
158
|
if(options.json)out.event('scheduled',{at,cron:run.cron,ok:run.ok,skipped:Boolean(run.skipped),status:run.status,ms:run.ms,...(error?{error}:{})});else out.human(`RER_SCHEDULED ${at} "${run.cron}" ${outcome}${error&&run.status?` — ${error}`:''}`);
|
|
168
159
|
}
|
|
169
|
-
// GET, not HEAD: a seed's outbox route need not answer HEAD. The body is never read.
|
|
170
|
-
async function outboxServed(url,devKey,signal){
|
|
171
|
-
const {appFetch}=await shared('app-fetch.mjs');
|
|
172
|
-
const response=await appFetch(url+'/__dev/outbox',{headers:devKey?{[DEV_KEY_HEADER]:devKey}:{},signal});
|
|
173
|
-
await response.body?.cancel();
|
|
174
|
-
return response.ok;
|
|
175
|
-
}
|
|
176
160
|
// dev also keeps its RER_OPEN link in owner-only .rer/local/open-url (0600),
|
|
177
161
|
// which reset removes with the rest of .rer/local, for a person or agent that
|
|
178
162
|
// did not keep the terminal output.
|
|
179
|
-
async function emitReady(out,options,root,url,dev,
|
|
163
|
+
async function emitReady(out,options,root,url,dev,siteUrl,demo){
|
|
180
164
|
if(options.verb==='dev'&&dev?.openUrl){
|
|
181
165
|
const {privateDirectory,writePrivateFile}=await shared('private-files.mjs');
|
|
182
166
|
await writePrivateFile(join(await privateDirectory(root,['.rer','local']),'open-url'),dev.openUrl+'\n');
|
|
183
167
|
}
|
|
184
|
-
ready(out,url,dev||undefined,options.json,
|
|
168
|
+
ready(out,url,dev||undefined,options.json,siteUrl,demo);
|
|
185
169
|
}
|
|
186
170
|
async function devReady(url,key,options,signal){
|
|
187
|
-
if(options.verb==='preview')return {openUrl:openUrl(url,key,{path:'/__dev/key',next:'/__dev/outbox'})};
|
|
188
|
-
if(options.login)return {openUrl:openUrl(url,key,{path:'/__dev/key',next:'/__dev/outbox'})};
|
|
189
171
|
const as=options.as??'owner',persona=await resolvePersona(url,key,as,signal);
|
|
190
172
|
// The owner persona names the owner the session will actually have (the
|
|
191
173
|
// remaining owner once the setup owner has left), or none when none is left.
|
package/cli/output.mjs
CHANGED
|
@@ -16,7 +16,7 @@ export function output(options) {
|
|
|
16
16
|
result(ok, exitCode, details = {}) {
|
|
17
17
|
if (finished) throw Error('Duplicate CLI result'); finished = true;
|
|
18
18
|
if (structuredResult) this.event('result', { ok, exitCode, ...details });
|
|
19
|
-
else if (!['describe', 'check', 'dev', 'preview', '
|
|
19
|
+
else if (!['describe', 'check', 'dev', 'preview', 'setup'].includes(options.verb) || !ok) this.human(`${options.verb}: ${ok ? 'complete' : 'failed'} (exit ${exitCode})`);
|
|
20
20
|
},
|
|
21
21
|
error(error) {
|
|
22
22
|
if (structuredResult) this.event('error', { code: error.code, message: error.message, exitCode: error.exitCode });
|
package/cli/parse.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { resolve } from 'node:path';
|
|
2
|
-
import { commonFlags, serverDefaults, verbs } from './contract.mjs';
|
|
2
|
+
import { commonFlags, serverDefaults, signinVerb, verbs } from './contract.mjs';
|
|
3
3
|
import { invalid, refuse } from './errors.mjs';
|
|
4
4
|
import { isLoopbackHost } from '../modules/operator-auth/loopback.mjs';
|
|
5
|
-
const booleans = new Set(['--help', '--json', '--non-interactive', '--yes', '--dry-run', '--
|
|
5
|
+
const booleans = new Set(['--help', '--json', '--non-interactive', '--yes', '--dry-run', '--stop', '--detach', '--foreground', '--no-queue', '--login', '--legacy-v1', '--acknowledge-unverified-metadata', '--door', '--direct', '--site', '--remove', '--demo']);
|
|
6
6
|
export const mailbox = value => typeof value === 'string' && value.length <= 254 && /^[a-zA-Z0-9.!+_%\-]+@[a-zA-Z0-9\-]+(?:\.[a-zA-Z0-9\-]+)+$/.test(value);
|
|
7
7
|
// A loopback host: the shared predicate (including `*.localhost` door names),
|
|
8
8
|
// plus `::1` as --host and a bracket-stripped hostname spell it.
|
|
@@ -22,7 +22,7 @@ export function parse(argv, cwd = process.cwd(), { independent = false, deferTai
|
|
|
22
22
|
// Independent projects own verb names; only the common wrapper flags apply
|
|
23
23
|
// to unknown names. Profile resolution rejects undeclared commands later.
|
|
24
24
|
if (!/^[a-z][a-z0-9-]*$/.test(verb)) throw invalid('Unknown rer command. Run rer --help.');
|
|
25
|
-
const allowed = new Set(independent ? [...commonFlags,...(['install','setup','build','verify','deploy','release','export','import','dev','preview'].includes(verb)?['--no-queue']:[])] : verbs[verb]?.flags ?? commonFlags), options = { verb, cwd: resolve(cwd), forwarded: [], supplied: new Set() };
|
|
25
|
+
const allowed = new Set(independent ? [...commonFlags,...(['install','setup','build','verify','deploy','release','export','import','dev','preview'].includes(verb)?['--no-queue']:[])] : (verbs[verb] ?? (verb === 'signin' ? signinVerb : undefined))?.flags ?? commonFlags), options = { verb, cwd: resolve(cwd), forwarded: [], supplied: new Set() };
|
|
26
26
|
let separator = false;
|
|
27
27
|
for (let i = 0; i < args.length; i++) {
|
|
28
28
|
const flag = args[i];
|
|
@@ -54,8 +54,8 @@ export function parse(argv, cwd = process.cwd(), { independent = false, deferTai
|
|
|
54
54
|
if(options.door&&['--port','--host'].some(flag=>options.supplied.has(flag)))throw invalid('--door cannot be combined with --port or --host, which always serve directly.');
|
|
55
55
|
if(options.models!==undefined && !['fake','live'].includes(options.models))throw invalid('--models takes fake or live.');
|
|
56
56
|
if(options.modelsService!==undefined && options.models!=='live')throw invalid('--models-service requires --models live.');
|
|
57
|
-
if(options.as!==undefined &&
|
|
58
|
-
if(options.demo&&['--door','--direct','--as','--
|
|
57
|
+
if(options.as!==undefined && !/^[a-z][a-z0-9-]{0,39}$/.test(options.as))throw invalid('--as takes a persona name such as owner, signed-out or admin.');
|
|
58
|
+
if(options.demo&&['--door','--direct','--as','--models','--models-service'].some(flag=>options.supplied.has(flag)))throw invalid('A demo opens signed in as the owner on its own data: --demo takes only --port, --host, --idle-timeout, --stop, --detach and --foreground.');
|
|
59
59
|
if(['dev','preview'].includes(verb) && !options.stop){
|
|
60
60
|
// A demo ends one hour after it starts unless --idle-timeout says otherwise.
|
|
61
61
|
const value=options.idleTimeout??(options.demo?'3600':process.env.RER_SERVER_IDLE_SECONDS??String(serverDefaults.idleSeconds));
|
|
@@ -89,8 +89,9 @@ export function parse(argv, cwd = process.cwd(), { independent = false, deferTai
|
|
|
89
89
|
}
|
|
90
90
|
|
|
91
91
|
export function help(verb) {
|
|
92
|
-
if (!verb) return `Usage: rer VERB [FLAGS]\nCommands: ${Object.keys(verbs).join(', ')}, release\nRun rer VERB --help for flags.\n`;
|
|
93
|
-
|
|
92
|
+
if (!verb) return `Usage: rer VERB [FLAGS]\nCommands: ${Object.keys(verbs).join(', ')}, signin, release\nRun rer VERB --help for flags.\n`;
|
|
93
|
+
const known = verbs[verb] ?? (verb === 'signin' ? signinVerb : undefined);
|
|
94
|
+
return `Usage: rer ${verb} [FLAGS]\nFlags: ${(known?.flags ?? commonFlags).join(', ')}\n${known?.effects ?? 'Execute the declared OPERATIONS v2 argv with explicit arguments after --.'}\n`;
|
|
94
95
|
}
|
|
95
96
|
|
|
96
97
|
function distance(a,b){let row=Array.from({length:b.length+1},(_,i)=>i);for(let i=1;i<=a.length;i++){const next=[i];for(let j=1;j<=b.length;j++)next[j]=Math.min(next[j-1]+1,row[j]+1,row[j-1]+(a[i-1]===b[j-1]?0:1));row=next;}return row[b.length];}
|
package/cli/port.mjs
CHANGED
|
@@ -1,29 +1,22 @@
|
|
|
1
|
-
import { createServer } from 'node:net';
|
|
2
1
|
import { realpath } from 'node:fs/promises';
|
|
3
2
|
import { join } from 'node:path';
|
|
3
|
+
import { createServer } from 'node:net';
|
|
4
4
|
import { readJson } from '../modules/job-queue/storage.mjs';
|
|
5
5
|
import { serversDirectory, stopInstruction } from './server-registry.mjs';
|
|
6
6
|
import { shared } from './shared.mjs';
|
|
7
7
|
|
|
8
8
|
export const defaultPort = 8787;
|
|
9
9
|
|
|
10
|
-
async function bindable(host, port) {
|
|
11
|
-
const socket = createServer();
|
|
12
|
-
try { await new Promise((resolve, reject) => { socket.once('error', reject); socket.listen(port, host, resolve); }); return true; }
|
|
13
|
-
catch { return false; }
|
|
14
|
-
finally { if (socket.listening) await new Promise(resolve => socket.close(resolve)); }
|
|
15
|
-
}
|
|
16
|
-
|
|
17
10
|
// The first port from `from` that nothing listens on, on any address, and that
|
|
18
11
|
// this host can bind. Another checkout's server may listen on every address,
|
|
19
12
|
// which a bind to 127.0.0.1 alone does not notice.
|
|
20
13
|
export async function firstFreePort(host, from = defaultPort, context) {
|
|
21
|
-
const {
|
|
22
|
-
|
|
23
|
-
|
|
14
|
+
const { inspectionContext } = await shared('process-diagnostics.mjs');
|
|
15
|
+
const { probePort } = await shared('port-probe.mjs');
|
|
16
|
+
context ??= inspectionContext({verb:'setup'});
|
|
24
17
|
for (let port = from; port <= 65535; port++) {
|
|
25
|
-
if (
|
|
26
|
-
if (
|
|
18
|
+
if ((await probePort(host, port, { context, anyAddress: true })).available) return port;
|
|
19
|
+
if (performance.now() >= context.deadline) throw Error('Could not find a free port in time (system busy). Run rer setup again.');
|
|
27
20
|
}
|
|
28
21
|
throw Error(`No free port from ${from} upward.`);
|
|
29
22
|
}
|
|
@@ -32,7 +25,7 @@ export async function firstFreePort(host, from = defaultPort, context) {
|
|
|
32
25
|
// command that stops it), else the process and its working directory.
|
|
33
26
|
export async function portHolder(port, host, root, env = process.env, context, observed) {
|
|
34
27
|
const { portListener } = await shared('process-diagnostics.mjs');
|
|
35
|
-
const listener = observed
|
|
28
|
+
const listener = observed !== undefined ? observed : await portListener(port, host, context);
|
|
36
29
|
if (!listener) return undefined;
|
|
37
30
|
const state = await readJson(join(serversDirectory(env), 'state.json'), { running: [] }).catch(() => ({ running: [] }));
|
|
38
31
|
const record = (state.running ?? []).find(item => item.owner?.pid === listener.pid && item.port === port);
|
|
@@ -42,18 +35,25 @@ export async function portHolder(port, host, root, env = process.env, context, o
|
|
|
42
35
|
// The refusal for a busy port. For a checkout that wants to move, it names the
|
|
43
36
|
// holder and gives the exact command that moves this checkout to a free port.
|
|
44
37
|
export async function busyPortMessage({ port, host, root, saved, env = process.env, context, listener }) {
|
|
45
|
-
const { inspectionContext } = await shared('process-diagnostics.mjs');
|
|
38
|
+
const { inspectionContext, uncheckedInspection } = await shared('process-diagnostics.mjs');
|
|
46
39
|
context ??= inspectionContext();
|
|
47
|
-
const holder = await portHolder(port, host, root, env, context, listener);
|
|
40
|
+
const holder = await portHolder(port, host, root, env, context, listener).catch(error => { if (!uncheckedInspection(error)) throw error; });
|
|
41
|
+
// Let the OS select and prove the recovery port by binding it. Optional
|
|
42
|
+
// ownership inspection must never consume the budget for this instruction.
|
|
43
|
+
const socket = createServer();
|
|
44
|
+
let next;
|
|
45
|
+
try {
|
|
46
|
+
await new Promise((resolve, reject) => { socket.once('error', reject); socket.listen({ host, port: 0, exclusive: true }, resolve); });
|
|
47
|
+
next = socket.address().port;
|
|
48
|
+
} finally { if (socket.listening) await new Promise(resolve => socket.close(resolve)); }
|
|
49
|
+
const move = `\nTo move this checkout to a free port and keep its data, run this in its folder:\n rer setup --port ${next}`;
|
|
48
50
|
|
|
49
51
|
const kind = saved ? `Port ${port} is saved for this checkout but is` : `Port ${port} is`;
|
|
50
|
-
if (!holder) return `${kind} unavailable for binding
|
|
51
|
-
if (holder.own) return `${kind} held by this checkout's own ${holder.server.mode} server (PID ${holder.pid}). Stop it with: ${stopInstruction(holder.server)}`;
|
|
52
|
-
const next = await firstFreePort(host, port + 1, context).catch(() => undefined);
|
|
52
|
+
if (!holder) return `${kind} still unavailable for binding on ${host} after retrying; no listener was identified. Run rer dev or rer setup again.${move}`;
|
|
53
|
+
if (holder.own) return `${kind} held by this checkout's own ${holder.server.mode} server for ${holder.checkout} (PID ${holder.pid}). Stop it with: ${stopInstruction(holder.server)}${move}`;
|
|
53
54
|
const who = holder.server
|
|
54
55
|
? `the ${holder.server.mode} server for ${holder.checkout} (PID ${holder.pid})`
|
|
55
56
|
: `PID ${holder.pid} (${holder.command})${holder.cwd ? ` running in ${holder.cwd}` : ''}`;
|
|
56
|
-
const move = next ? `\nTo move this checkout to a free port and keep its data, run this in its folder:\n rer setup --port ${next}` : '';
|
|
57
57
|
const stop = holder.server ? `\nOr stop that server first: ${stopInstruction(holder.server)}` : `\nOr stop it with: kill -TERM ${holder.pid}`;
|
|
58
58
|
return `${kind} in use by ${who}.${move}${stop}`;
|
|
59
59
|
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { refuse } from './errors.mjs';
|
|
2
|
+
import { mailbox } from './parse.mjs';
|
|
3
|
+
import { main as owner } from '../modules/deploy-kit/owner-cli.mjs';
|
|
4
|
+
import { hookState } from './deploy-hook-record.mjs';
|
|
5
|
+
import { savedSetupAnswers } from './setup-answers.mjs';
|
|
6
|
+
import { validateRerConfig } from '../modules/mail/src/adapters/rer/contract.mjs';
|
|
7
|
+
|
|
8
|
+
// Validate the shared email/identity contract using the bindings that will reach
|
|
9
|
+
// the runtime. Independently authored authentication remains the adapter's job.
|
|
10
|
+
export async function requireProductionAuth({ root, declaration, env, setupManifest, setupSeed, adapter, declarationPath, options = {} }) {
|
|
11
|
+
const dependencies = setupManifest?.dependencies?.filter(item => item.interface === 'oidc-provider@1') ?? [];
|
|
12
|
+
const bindings = { ...declaration.vars };
|
|
13
|
+
for (const secret of declaration.secrets ?? []) if (env[secret.environment]?.trim()) bindings[secret.binding] = env[secret.environment];
|
|
14
|
+
if (!setupManifest?.steps?.some(step => step.type === 'owner-claim') && !dependencies.length && !('MAIL_PROVIDER' in bindings) && !declaration.secrets?.some(item => item.binding === 'MAIL_API_KEY')) return;
|
|
15
|
+
const provider = bindings.MAIL_PROVIDER;
|
|
16
|
+
let mailSelected = ['resend', 'sendgrid', 'cloudflare', 'rer'].includes(provider) && mailbox(bindings.MAIL_FROM);
|
|
17
|
+
if (provider === 'rer') {
|
|
18
|
+
try { validateRerConfig({ relayUrl: bindings.MAIL_RELAY_URL }); } catch { mailSelected = false; }
|
|
19
|
+
}
|
|
20
|
+
const required = ['MAIL_API_KEY', ...(provider === 'cloudflare' ? ['MAIL_ACCOUNT_ID'] : [])];
|
|
21
|
+
if (mailSelected && required.every(key => bindings[key]?.trim())) return;
|
|
22
|
+
if (mailSelected && !options.dryRun && declarationPath) {
|
|
23
|
+
try {
|
|
24
|
+
const state = await hookState(root, options.environment ?? 'production');
|
|
25
|
+
const existing = await owner(['inspect', '--declaration', declarationPath, '--environment', options.environment ?? 'production', ...(state ? ['--state', state] : [])], env, { cwd: root, localOnlyKeys: adapter?.localOnlyKeys });
|
|
26
|
+
if (required.every(key => bindings[key]?.trim() || existing.liveSecrets.includes(key))) return;
|
|
27
|
+
} catch (error) {
|
|
28
|
+
if (!['missing-owner-receipt', 'missing-input'].includes(error.message)) throw refuse(`Production sign-in could not verify the existing deployment and its mail secrets${/^[a-z][a-z0-9-]{0,80}$/.test(error.message)?` (${error.message})`:''}. Restore provider access and the owned deployment record before retrying.`);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
const answers = setupSeed ? await savedSetupAnswers({ root, adapter, setupManifest }, setupSeed.model) : undefined;
|
|
32
|
+
// Link approval and live post-link status are checked by linkDependencies;
|
|
33
|
+
// selecting an issuer never bypasses that existing setup requirement.
|
|
34
|
+
if (dependencies.some(item => {
|
|
35
|
+
try { const value = answers?.[item.address] ?? bindings[item.address], issuer = new URL(value); return issuer.protocol === 'https:' && issuer.origin === value && !issuer.username && !issuer.password; } catch { return false; }
|
|
36
|
+
})) return;
|
|
37
|
+
throw refuse('Production sign-in is not configured. Configure outbound email (MAIL_PROVIDER, MAIL_FROM and MAIL_API_KEY; Cloudflare also needs MAIL_ACCOUNT_ID, RER needs MAIL_RELAY_URL), or select and approve an Auth SSO install through the declared oidc-provider@1 setup dependency. Local dev and demo use automatic RER_OPEN sign-in. Nothing was built or uploaded.');
|
|
38
|
+
}
|
package/cli/server-proxy.mjs
CHANGED
|
@@ -2,7 +2,7 @@ import http from 'node:http';
|
|
|
2
2
|
import net from 'node:net';
|
|
3
3
|
import { createHmac, randomUUID, timingSafeEqual } from 'node:crypto';
|
|
4
4
|
import { posix } from 'node:path';
|
|
5
|
-
import {
|
|
5
|
+
import { listen } from './listen.mjs';
|
|
6
6
|
import { loopback } from './parse.mjs';
|
|
7
7
|
import { fontResponseHeaders } from './font-cache.mjs';
|
|
8
8
|
|
|
@@ -79,11 +79,7 @@ export async function trafficProxy({host,port,target,activity,door,devKey,origin
|
|
|
79
79
|
}
|
|
80
80
|
upstream.on('error',()=>socket.destroy());socket.on('error',()=>upstream.destroy());socket.on('close',()=>upstream.destroy());upstream.on('close',()=>socket.destroy());
|
|
81
81
|
});
|
|
82
|
-
|
|
83
|
-
catch(error){
|
|
84
|
-
if(['EADDRINUSE','EACCES'].includes(error.code))throw refuse(`Requested port ${port} is unavailable. Stop its owner or choose an explicit free port; rer does not drift.`);
|
|
85
|
-
throw error;
|
|
86
|
-
}
|
|
82
|
+
await listen(server,host,port);
|
|
87
83
|
return {probe,port:server.address().port,async close(){for(const socket of sockets)socket.destroy();await new Promise(resolve=>server.close(resolve));}};
|
|
88
84
|
}
|
|
89
85
|
function doorAdmits(req,door){
|