@runeditrun/rer 0.2.121 → 0.2.122
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/cli/README.md +124 -5
- package/cli/archive.mjs +1 -1
- package/cli/authoring.mjs +1 -1
- package/cli/browser-runtime.mjs +2 -2
- package/cli/business/agent-help.mjs +11 -11
- package/cli/business/agent-verbs.mjs +9 -8
- package/cli/business/api.mjs +11 -7
- package/cli/business/carry.mjs +4 -3
- package/cli/business/choices.mjs +1 -1
- package/cli/business/command.mjs +33 -11
- package/cli/business/connect.mjs +4 -4
- package/cli/business/credential-file.mjs +102 -0
- package/cli/business/errors.mjs +5 -2
- package/cli/business/invocation.mjs +7 -4
- package/cli/business/keychain.mjs +6 -2
- package/cli/business/local-commands.mjs +9 -3
- package/cli/business/mcp-bridge.mjs +2 -1
- package/cli/business/questions.mjs +1 -1
- package/cli/business/run-child.mjs +5 -5
- package/cli/business/run-grant.mjs +27 -8
- package/cli/business/run-mask.mjs +8 -1
- package/cli/business/scan-command.mjs +1 -1
- package/cli/business/service.mjs +4 -2
- package/cli/business/state.mjs +2 -2
- package/cli/checkout-folders.mjs +1 -1
- package/cli/checkout-preparation.mjs +4 -4
- package/cli/command-guidance.mjs +9 -0
- package/cli/companion/command.mjs +4 -3
- package/cli/companion/providers/sandbox.mjs +1 -1
- package/cli/companion/setup.mjs +4 -4
- package/cli/contract.mjs +8 -8
- package/cli/demo.mjs +1 -1
- package/cli/deploy-command.mjs +10 -5
- package/cli/deploy-hook.mjs +3 -2
- package/cli/deploy-inputs.mjs +7 -3
- package/cli/deploy-owner-input.mjs +2 -2
- package/cli/deploy-source.mjs +1 -1
- package/cli/deploy.mjs +4 -2
- package/cli/deployment-record.mjs +1 -1
- package/cli/dev-identity.mjs +4 -4
- package/cli/door-clauses.mjs +2 -2
- package/cli/door-mode.mjs +7 -7
- package/cli/door.mjs +7 -7
- package/cli/errors.mjs +15 -1
- package/cli/export-summary.mjs +1 -1
- package/cli/export.mjs +1 -1
- package/cli/hosted-export.mjs +1 -1
- package/cli/hosted-output.mjs +2 -2
- package/cli/human-error.mjs +8 -2
- package/cli/hydration/browser.mjs +1 -1
- package/cli/hydration/check.mjs +1 -1
- package/cli/import-summary.mjs +2 -2
- package/cli/inspect.mjs +3 -3
- package/cli/lifecycle.mjs +9 -9
- package/cli/listen.mjs +1 -1
- package/cli/listing.mjs +1 -1
- package/cli/local-env.mjs +1 -1
- package/cli/local.mjs +4 -4
- package/cli/managed-server.mjs +36 -13
- package/cli/output.mjs +2 -1
- package/cli/owner-entry-ready.mjs +92 -0
- package/cli/parse.mjs +8 -8
- package/cli/port.mjs +3 -3
- package/cli/portability-runtime.mjs +16 -0
- package/cli/portability.mjs +4 -4
- package/cli/production-auth.mjs +4 -2
- package/cli/production-mail.mjs +1 -1
- package/cli/project.mjs +2 -0
- package/cli/rehearse/options.mjs +3 -3
- package/cli/release-candidate.mjs +2 -2
- package/cli/release.mjs +5 -5
- package/cli/server-registry.mjs +3 -3
- package/cli/server-resources.mjs +1 -1
- package/cli/setup-input.mjs +6 -6
- package/cli/signin.mjs +11 -10
- package/cli/site-render.mjs +1 -1
- package/cli/size/schema.mjs +1 -1
- package/cli/size/verify-step.mjs +1 -1
- package/cli/transfers.mjs +4 -4
- package/edition-authoring/api-source.mjs +121 -0
- package/edition-authoring/archive-source.mjs +1 -86
- package/edition-authoring/base-copies.mjs +5 -3
- package/global/CHANGELOG.md +31 -0
- package/global/cli/command.mjs +6 -5
- package/global/cli/install.mjs +6 -3
- package/global/cli/path-link.mjs +11 -22
- package/global/cli/repo-command.mjs +4 -3
- package/global/cli/repository-contract.mjs +3 -3
- package/global/door/command.mjs +39 -38
- package/global/door/control.mjs +3 -3
- package/global/door/pages.mjs +6 -5
- package/global/door/server.mjs +8 -5
- package/global/door/sites.mjs +14 -13
- package/global/launch/capacity.mjs +2 -2
- package/global/launch/dev.mjs +6 -6
- package/global/launch/door.mjs +1 -1
- package/global/launch/facts.mjs +2 -2
- package/global/launch/failure.mjs +1 -1
- package/global/launch/prepare.mjs +3 -3
- package/global/launch/render.mjs +3 -2
- package/global/launch/worker.mjs +1 -1
- package/global/list.mjs +4 -4
- package/global/main.mjs +32 -31
- package/global/registry.mjs +1 -1
- package/global/run.mjs +4 -4
- package/global/update/command.mjs +5 -5
- package/global/update/notice.mjs +1 -1
- package/global/version.mjs +1 -1
- package/install.sh +17 -4
- package/modules/deploy-kit/README.md +10 -3
- package/modules/deploy-kit/asset-health.mjs +6 -4
- package/modules/deploy-kit/cancellation.mjs +26 -0
- package/modules/deploy-kit/d1-import-diagnostics.mjs +3 -2
- package/modules/deploy-kit/deploy.mjs +8 -3
- package/modules/deploy-kit/diagnostics.mjs +11 -4
- package/modules/deploy-kit/health-request.mjs +16 -9
- package/modules/deploy-kit/health.mjs +14 -11
- package/modules/deploy-kit/owner-cli.mjs +49 -21
- package/modules/deploy-kit/owner-remove.mjs +7 -6
- package/modules/deploy-kit/owner-secret.mjs +7 -4
- package/modules/deploy-kit/owner.mjs +46 -28
- package/modules/deploy-kit/provider-transport.mjs +2 -0
- package/modules/deploy-kit/provider.mjs +10 -9
- package/modules/deploy-kit/readiness-window.mjs +5 -3
- package/modules/deploy-kit/site.mjs +1 -1
- package/modules/deploy-kit/teardown.mjs +5 -4
- package/modules/operator-auth/dev/index.mjs +4 -3
- package/modules/operator-auth/dev/sign-in-as.mjs +2 -1
- package/modules/operator-auth/dev-gate.mjs +3 -2
- package/modules/operator-auth/routes.mjs +2 -1
- package/modules/operator-auth/terminal-guidance.mjs +3 -0
- package/onboarding/adapter-settings.mjs +1 -0
- package/onboarding/adapter.mjs +3 -3
- package/onboarding/agent-handoff.mjs +1 -1
- package/onboarding/busy.mjs +1 -1
- package/onboarding/launcher.mjs +1 -1
- package/onboarding/local/environment.mjs +1 -1
- package/onboarding/local/operation.mjs +12 -4
- package/onboarding/local/owner.mjs +2 -2
- package/onboarding/operator-installer.mjs +4 -3
- package/onboarding/operator-migrations.mjs +1 -1
- package/onboarding/operator-prerequisites.mjs +26 -14
- package/onboarding/operator-settings.mjs +28 -0
- package/onboarding/process-diagnostics.mjs +2 -2
- package/onboarding/project-vite.mjs +1 -1
- package/package.json +1 -1
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { readChunk } from './cancellation.mjs';
|
|
1
2
|
import timers from 'node:timers/promises';
|
|
2
3
|
import { providerPages, providerListShape } from './pagination.mjs';
|
|
3
4
|
import { deleteR2Object } from './r2-object-transport.mjs';
|
|
@@ -11,13 +12,13 @@ import { providerResponse, transportOutput, transportReason, transportClass } fr
|
|
|
11
12
|
// A gateway/server error can arrive after a write. An explicit API refusal cannot.
|
|
12
13
|
export const definiteProviderRefusal = error => error.status === 200 || error.status >= 400 && error.status < 500;
|
|
13
14
|
|
|
14
|
-
async function boundedBytes(response, limit, onReadError, prefix = false) {
|
|
15
|
+
async function boundedBytes(response, limit, onReadError, prefix = false, signal) {
|
|
15
16
|
assert(response.body, 'empty-response');
|
|
16
17
|
const reader = response.body.getReader(); const chunks = []; let length = 0;
|
|
17
18
|
try { while (true) {
|
|
18
19
|
let chunk;
|
|
19
20
|
// Only a failed stream read is transport failure; retain size/shape codes.
|
|
20
|
-
try { chunk = await reader
|
|
21
|
+
try { chunk = await readChunk(reader,signal); } catch (cause) {
|
|
21
22
|
if (prefix) { chunks.push(Buffer.from(` [response read failed: ${transportReason(cause)}]`)); break; }
|
|
22
23
|
throw onReadError ? onReadError(cause) : cause;
|
|
23
24
|
}
|
|
@@ -29,9 +30,9 @@ async function boundedBytes(response, limit, onReadError, prefix = false) {
|
|
|
29
30
|
finally { await reader.cancel().catch(() => {}); }
|
|
30
31
|
return Buffer.concat(chunks);
|
|
31
32
|
}
|
|
32
|
-
const boundedText = async (response, limit = 4 * 1024 * 1024, onReadError, prefix) => (await boundedBytes(response, limit, onReadError, prefix)).toString('utf8');
|
|
33
|
-
export async function boundedJSON(response, limit) {
|
|
34
|
-
try { return JSON.parse(await boundedText(response,limit)); } catch (error) { if (error instanceof SyntaxError) throw new Error('malformed-response'); throw error; }
|
|
33
|
+
const boundedText = async (response, limit = 4 * 1024 * 1024, onReadError, prefix, signal) => (await boundedBytes(response, limit, onReadError, prefix, signal)).toString('utf8');
|
|
34
|
+
export async function boundedJSON(response, limit, signal) {
|
|
35
|
+
try { return JSON.parse(await boundedText(response,limit,undefined,false,signal)); } catch (error) { if (error instanceof SyntaxError) throw new Error('malformed-response'); throw error; }
|
|
35
36
|
}
|
|
36
37
|
const redactValues = (text, values) => values.filter(Boolean).flatMap(value=>[value,encodeURIComponent(value),JSON.stringify(value).slice(1,-1)]).sort((a,b)=>b.length-a.length).reduce((value,secret)=>{
|
|
37
38
|
value = value.split(secret).join('[REDACTED]');
|
|
@@ -91,7 +92,7 @@ export function cloudflare({ accountId, token, fetch: request = globalThis.fetch
|
|
|
91
92
|
consume:(response,attempts,signal) => {
|
|
92
93
|
onResponse?.({status:response.status,body:''});
|
|
93
94
|
const failedRead = cause => transportFailure(signal.aborted ? signal.reason : cause,attempts,response.status);
|
|
94
|
-
return onResponse && !response.ok ? importResponseText(response,failedRead) : response.body ? boundedText(response,response.ok ? undefined : 64 * 1024,failedRead,!response.ok) : '';
|
|
95
|
+
return onResponse && !response.ok ? importResponseText(response,failedRead,signal) : response.body ? boundedText(response,response.ok ? undefined : 64 * 1024,failedRead,!response.ok,signal) : '';
|
|
95
96
|
},
|
|
96
97
|
send:signal => isR2ObjectDelete(path, method) ? objectDelete(`/client/v4/accounts/${accountId}${path}`, {headers:{Authorization:`Bearer ${token}`},signal}) : request(zone ? `https://api.cloudflare.com/client/v4${path}` : `https://api.cloudflare.com/client/v4/accounts/${accountId}${path}`, {
|
|
97
98
|
method, redirect: 'error', signal, headers: { Authorization: `Bearer ${assetToken ?? token}`, ...(body && !(body instanceof FormData) ? { 'Content-Type':'application/json' } : {}) },
|
|
@@ -186,7 +187,7 @@ export function cloudflare({ accountId, token, fetch: request = globalThis.fetch
|
|
|
186
187
|
};
|
|
187
188
|
const {response,output} = await providerResponse({method:'GET',timeoutMs,callerSignal:deadlineSignal(),reserveRetry:() => requests < maxRequests && (++requests, true),
|
|
188
189
|
send:signal => request(`https://api.cloudflare.com/client/v4/accounts/${accountId}/workers/scripts/${worker}/content/v2?version=${versionId}`, {method:'GET',redirect:'error',signal,headers:{Authorization:`Bearer ${token}`}}),
|
|
189
|
-
consume:(response,attempts,signal) => response.body ? boundedBytes(response,response.ok ? 64 * 1024 * 1024 : 64 * 1024,cause => failure(signal.aborted ? signal.reason : cause,attempts,response.status),!response.ok) : Buffer.alloc(0),failure});
|
|
190
|
+
consume:(response,attempts,signal) => response.body ? boundedBytes(response,response.ok ? 64 * 1024 * 1024 : 64 * 1024,cause => failure(signal.aborted ? signal.reason : cause,attempts,response.status),!response.ok,signal) : Buffer.alloc(0),failure});
|
|
190
191
|
if (!response.ok) throw retain(Object.assign(new Error(`provider-http-${response.status}`), {status:response.status}),response.status,'HTTP refusal',output.toString('utf8'));
|
|
191
192
|
const type = response.headers.get('content-type') ?? '', entry = response.headers.get('cf-entrypoint');
|
|
192
193
|
assert(type.startsWith('multipart/form-data') && typeof entry === 'string' && entry, 'invalid-worker-content');
|
|
@@ -205,9 +206,9 @@ export function cloudflare({ accountId, token, fetch: request = globalThis.fetch
|
|
|
205
206
|
reserveRetry:() => requests < maxRequests && (++requests, true),
|
|
206
207
|
send:signal => request(destination, { method:'PUT', redirect:'error', signal, headers:{'Content-Length':String(bytes.length)}, body:bytes }),
|
|
207
208
|
failure,
|
|
208
|
-
consume:async (response, attempts) => {
|
|
209
|
+
consume:async (response, attempts, signal) => {
|
|
209
210
|
if (response.status === 200) { await response.body?.cancel().catch(() => {}); return ''; }
|
|
210
|
-
return importResponseText(response,cause => failure(cause,attempts,response.status));
|
|
211
|
+
return importResponseText(response,cause => failure(cause,attempts,response.status),signal);
|
|
211
212
|
},
|
|
212
213
|
});
|
|
213
214
|
let payload; try { payload = JSON.parse(output); } catch { /* R2 may return plain text or XML. */ }
|
|
@@ -1,17 +1,18 @@
|
|
|
1
|
+
import { pause, combinedSignal } from './cancellation.mjs';
|
|
1
2
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
3
|
import { assert } from './validation.mjs';
|
|
3
4
|
|
|
4
5
|
// A single, in-memory deadline travels with this upload. It is deliberately not
|
|
5
6
|
// persisted: an old receipt is not evidence of a fresh propagation window.
|
|
6
|
-
export function readinessWindow({ totalMs = 90000, clock = () => performance.now(), sleep
|
|
7
|
+
export function readinessWindow({ totalMs = 90000, clock = () => performance.now(), sleep, signal, timeout = ms => AbortSignal.timeout(ms) } = {}) {
|
|
7
8
|
assert(Number.isFinite(totalMs) && totalMs > 0 && totalMs <= 90000, 'invalid-health-bound');
|
|
8
9
|
let start;
|
|
9
10
|
return {
|
|
10
|
-
clock, sleep, timeout,
|
|
11
|
+
clock, signal, sleep:ms => pause(ms,signal,sleep), timeout:ms => combinedSignal(signal,timeout(ms)),
|
|
11
12
|
get active() { return start !== undefined; },
|
|
12
13
|
start() { start ??= clock(); },
|
|
13
14
|
remaining() { return start === undefined ? totalMs : Math.max(0, totalMs - (clock() - start)); },
|
|
14
|
-
async pause() { const left = this.remaining(); if (left > 0) await sleep(Math.min(2000, left)); },
|
|
15
|
+
async pause() { const left = this.remaining(); if (left > 0) await this.sleep(Math.min(2000, left)); },
|
|
15
16
|
};
|
|
16
17
|
}
|
|
17
18
|
|
|
@@ -24,6 +25,7 @@ export const observedReadiness = origin => observations.getStore()?.get(origin);
|
|
|
24
25
|
|
|
25
26
|
export function readinessAPI(api, window, failure = 'deployment-readiness-timeout') {
|
|
26
27
|
return {...api, request(path, options = {}) {
|
|
28
|
+
window.signal?.throwIfAborted();
|
|
27
29
|
const remaining = window.remaining();
|
|
28
30
|
assert(remaining > 0, failure);
|
|
29
31
|
const deadline = window.timeout(Math.max(1, Math.ceil(remaining)));
|
|
@@ -33,7 +33,7 @@ const APEX = /^(?!www\.)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-
|
|
|
33
33
|
export const SITE_ASSETS_CONFIG = Object.freeze({ html_handling: 'auto-trailing-slash', not_found_handling: '404-page' });
|
|
34
34
|
export const SITE_MODULE = 'site-worker.mjs';
|
|
35
35
|
/** The site Worker. It names no domain: only the site's two Custom Domains route to it. */
|
|
36
|
-
export const SITE_WORKER = `// Run site Worker, generated by Base's deploy kit (rer deploy --site). Do not edit.
|
|
36
|
+
export const SITE_WORKER = `// Run site Worker, generated by Base's deploy kit (~/.local/bin/rer deploy --site). Do not edit.
|
|
37
37
|
export default {
|
|
38
38
|
async fetch(request, env) {
|
|
39
39
|
const url = new URL(request.url);
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { pause } from './cancellation.mjs';
|
|
1
2
|
import { assert, hexId, uuid } from './validation.mjs';
|
|
2
3
|
import { workerConsumerScript } from './queue-consumer.mjs';
|
|
3
4
|
|
|
@@ -32,7 +33,7 @@ async function inventory(api) {
|
|
|
32
33
|
}
|
|
33
34
|
|
|
34
35
|
/** Read-only verification. It never deletes, repairs or authorizes deletion. */
|
|
35
|
-
export async function verifyTeardown({api,plan,receipt,prefix=plan?.worker,maxAttempts=4,clock=()=>performance.now(),sleep
|
|
36
|
+
export async function verifyTeardown({api,plan,receipt,prefix=plan?.worker,maxAttempts=4,clock=()=>performance.now(),sleep,signal,onAttempt=()=>{}}) {
|
|
36
37
|
assert(receipt?.version === 1 && receipt.accountId === api.accountId && receipt.worker === plan?.worker,'teardown-receipt-target-mismatch');
|
|
37
38
|
assert(name(prefix) && (prefix.startsWith('rer-seedproof-') || /^rer-base-stage-[0-9]{1,20}$/.test(prefix)) && plan.worker === prefix,'teardown-disposable-prefix-required');
|
|
38
39
|
assert(Number.isSafeInteger(maxAttempts) && maxAttempts >= 1 && maxAttempts <= 8,'teardown-invalid-attempt-bound');
|
|
@@ -69,7 +70,7 @@ export async function verifyTeardown({api,plan,receipt,prefix=plan?.worker,maxAt
|
|
|
69
70
|
error.attempts = attempts;
|
|
70
71
|
throw error;
|
|
71
72
|
}
|
|
72
|
-
await
|
|
73
|
+
await pause(Math.min(250 * 2 ** (number-1),2000),signal,sleep);
|
|
73
74
|
}
|
|
74
75
|
}
|
|
75
76
|
}
|
|
@@ -80,7 +81,7 @@ export async function verifyTeardown({api,plan,receipt,prefix=plan?.worker,maxAt
|
|
|
80
81
|
* schedule set first, wait until the provider reports none, and only then delete. A set that does
|
|
81
82
|
* not settle within `maxWaitMs` leaves the Worker in place.
|
|
82
83
|
*/
|
|
83
|
-
export async function deleteWorker({api,worker,maxWaitMs=60000,clock=()=>performance.now(),sleep
|
|
84
|
+
export async function deleteWorker({api,worker,maxWaitMs=60000,clock=()=>performance.now(),sleep,signal}) {
|
|
84
85
|
assert(name(worker),'teardown-invalid-worker-name');
|
|
85
86
|
const schedules = `/workers/scripts/${worker}/schedules`;
|
|
86
87
|
await api.request(schedules,{method:'PUT',body:[]});
|
|
@@ -94,7 +95,7 @@ export async function deleteWorker({api,worker,maxWaitMs=60000,clock=()=>perform
|
|
|
94
95
|
error.code = 'teardown-schedules-not-cleared';
|
|
95
96
|
throw error;
|
|
96
97
|
}
|
|
97
|
-
await
|
|
98
|
+
await pause(delay,signal,sleep);
|
|
98
99
|
}
|
|
99
100
|
await api.request(`/workers/scripts/${worker}?force=true`,{method:'DELETE'});
|
|
100
101
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { terminalHelp } from '../terminal-guidance.mjs';
|
|
1
2
|
import { rejectedResponse } from '../rejected-response.mjs';
|
|
2
3
|
// Local dev identity. SERVER-ONLY and LOCAL-ONLY: load this layer only from a
|
|
3
4
|
// local-only Worker entry (a `wrangler dev` or Vite-serve entry), never from the
|
|
@@ -46,7 +47,7 @@ export function withDevIdentity(worker, { bindings = env => env, config: authCon
|
|
|
46
47
|
if (managedInstallation(env)) {
|
|
47
48
|
// Never admit a dev credential here; with dev identity on, serve nothing.
|
|
48
49
|
registerDevAdmission(null);
|
|
49
|
-
if (env.RER_DEV_IDENTITY !== 'off') return rejectedResponse(request, text(503, 'Dev identity refuses to run beside RER_INSTALLATION_ID with a non-loopback RER_MANAGEMENT_ORIGIN. Remove those bindings from local settings or use rer dev --login.'));
|
|
50
|
+
if (env.RER_DEV_IDENTITY !== 'off') return rejectedResponse(request, text(503, 'Dev identity refuses to run beside RER_INSTALLATION_ID with a non-loopback RER_MANAGEMENT_ORIGIN. Remove those bindings from local settings or use ~/.local/bin/rer dev --login.' + ' ' + terminalHelp));
|
|
50
51
|
return new URL(request.url).pathname === '/auth/dev/enter' || new URL(request.url).pathname === '/__dev/personas' || new URL(request.url).pathname === '/auth/local/cli-session' ? rejectedResponse(request, devNotFound()) : worker.fetch(request, original, execution);
|
|
51
52
|
}
|
|
52
53
|
const gate = devGate({ key: env.RER_DEV_KEY, origin: env.AUTH_ORIGIN, local: env.AUTH_LOCAL === 'true' });
|
|
@@ -160,7 +161,7 @@ async function enter(request, gate, { config, store, hash, current, everyone, ow
|
|
|
160
161
|
};
|
|
161
162
|
const persona = (await everyone()).find(p => p.as === as);
|
|
162
163
|
if (!persona) return oneClick(as);
|
|
163
|
-
if (!persona.email) return text(409, 'No active owner remains in this app. Sign in another way, or run rer reset --yes and rer setup for a new owner.');
|
|
164
|
+
if (!persona.email) return text(409, 'No active owner remains in this app. Sign in another way, or run ~/.local/bin/rer reset --yes and ~/.local/bin/rer setup for a new owner.' + ' ' + terminalHelp);
|
|
164
165
|
let operator = await store.byEmail(persona.email);
|
|
165
166
|
// Someone invited at a persona's address is that person, with the role they were invited to; accepting the invite signs them in.
|
|
166
167
|
if (operator?.status === 'invited') return oneClick(operator.email);
|
|
@@ -179,7 +180,7 @@ async function enter(request, gate, { config, store, hash, current, everyone, ow
|
|
|
179
180
|
}
|
|
180
181
|
operator = await store.byEmail(persona.email);
|
|
181
182
|
}
|
|
182
|
-
if (!operator) return text(409, 'The owner that rer setup claimed is not in this database. Run rer setup.');
|
|
183
|
+
if (!operator) return text(409, 'The owner that ~/.local/bin/rer setup claimed is not in this database. Run ~/.local/bin/rer setup.' + ' ' + terminalHelp);
|
|
183
184
|
if (!isActiveOperator(operator, config.allowList)) return signInRefusal(request, config.branding, {
|
|
184
185
|
status: 403,
|
|
185
186
|
message: 'This account is inactive or no longer allowed to sign in to this app. Choose another account, or ask an owner or administrator to restore its access.',
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { terminalHelp } from '../terminal-guidance.mjs';
|
|
1
2
|
// Node test harness door: sign a test browser or fetch client in as a persona
|
|
2
3
|
// on a running local app. The harness presents the checkout's RER_DEV_KEY; the
|
|
3
4
|
// app answers 404 without it. Never import this from Worker code.
|
|
@@ -8,7 +9,7 @@ export const DEV_KEY_FILE = '.rer/local/dev-key.env';
|
|
|
8
9
|
export async function readDevKey(root) {
|
|
9
10
|
const text = await readFile(join(root, DEV_KEY_FILE), 'utf8');
|
|
10
11
|
const key = /^RER_DEV_KEY=([A-Za-z0-9_-]{43,256})$/m.exec(text)?.[1];
|
|
11
|
-
if (!key) throw new Error(`${DEV_KEY_FILE} holds no RER_DEV_KEY. Run rer setup
|
|
12
|
+
if (!key) throw new Error(`${DEV_KEY_FILE} holds no RER_DEV_KEY. Run ~/.local/bin/rer setup. ${terminalHelp}`);
|
|
12
13
|
return key;
|
|
13
14
|
}
|
|
14
15
|
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { terminalHelpHtml } from './terminal-guidance.mjs';
|
|
1
2
|
import { iconHead } from './icon-head.mjs';
|
|
2
3
|
import { rejectedResponse } from './rejected-response.mjs';
|
|
3
4
|
import { constantEqual } from './crypto.mjs';
|
|
@@ -35,7 +36,7 @@ async function cookieValue(key) {
|
|
|
35
36
|
// never reaches a server; the key never appears in a query string. Listen for
|
|
36
37
|
// fragment navigation too: an open gate page stays loaded when RER_OPEN points
|
|
37
38
|
// to the same path with a fresh key fragment.
|
|
38
|
-
export const EXCHANGE_SCRIPT = "(()=>{const exchange=()=>{const h=new URLSearchParams(location.hash.slice(1)),k=h.get('rer-dev');if(!k)return;history.replaceState(null,'',location.pathname+location.search);const a=h.get('as'),n=h.get('next')||(a?'/auth/dev/enter?as='+encodeURIComponent(a):location.pathname+location.search),to=n.startsWith('/')&&!n.startsWith('//')&&!n.includes('\\\\')?n:'/';fetch('" + DEV_KEY_PATH + "',{method:'POST',credentials:'same-origin',headers:{'content-type':'application/json'},body:JSON.stringify({key:k})}).then(r=>{if(r.ok)location.replace(to);else document.body.insertAdjacentHTML('beforeend','<p role=\"alert\">This link no longer opens the app. Run rer dev again for a fresh one.</p>')})};addEventListener('hashchange',exchange);exchange()})()";
|
|
39
|
+
export const EXCHANGE_SCRIPT = "(()=>{const exchange=()=>{const h=new URLSearchParams(location.hash.slice(1)),k=h.get('rer-dev');if(!k)return;history.replaceState(null,'',location.pathname+location.search);const a=h.get('as'),n=h.get('next')||(a?'/auth/dev/enter?as='+encodeURIComponent(a):location.pathname+location.search),to=n.startsWith('/')&&!n.startsWith('//')&&!n.includes('\\\\')?n:'/';fetch('" + DEV_KEY_PATH + "',{method:'POST',credentials:'same-origin',headers:{'content-type':'application/json'},body:JSON.stringify({key:k})}).then(r=>{if(r.ok)location.replace(to);else document.body.insertAdjacentHTML('beforeend','<p role=\"alert\">This link no longer opens the app. Run ~/.local/bin/rer dev again for a fresh one.</p>" + (`<p>${terminalHelpHtml}</p>`).replaceAll("'", "'") + "')})};addEventListener('hashchange',exchange);exchange()})()";
|
|
39
40
|
// The hand-off page wears the seed's own theme: the same rer-theme.css tokens and the
|
|
40
41
|
// same --rer-logo mark the sign-in pages draw. The mark becomes a real <img> named by
|
|
41
42
|
// the product and shown beside the wordmark text; a seed that declares no logo shows
|
|
@@ -104,7 +105,7 @@ export function devGate({ key, origin, local }) {
|
|
|
104
105
|
const theme = brand?.theme;
|
|
105
106
|
const mark = brand?.mark ? `<img src="${escapeHtml(brand.mark)}" alt="${escapeHtml(brand.productName)}" width="40" height="40" decoding="async">` : '';
|
|
106
107
|
const themeLogo = theme && !brand.mark;
|
|
107
|
-
const body = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex, nofollow"><title>Open the local app</title>${iconHead}${theme ? `<link rel="stylesheet" href="${escapeHtml(theme)}">` : ''}<style>${PAGE_STYLE}</style></head><body><main>${brand ? `<p class="brand">${mark}<span>${escapeHtml(brand.productName)}</span></p>` : ''}<h1>This app runs on your own computer</h1><p>It opens only from that computer. Use the link printed in the terminal where <code
|
|
108
|
+
const body = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex, nofollow"><title>Open the local app</title>${iconHead}${theme ? `<link rel="stylesheet" href="${escapeHtml(theme)}">` : ''}<style>${PAGE_STYLE}</style></head><body><main>${brand ? `<p class="brand">${mark}<span>${escapeHtml(brand.productName)}</span></p>` : ''}<h1>This app runs on your own computer</h1><p>It opens only from that computer. Use the link printed in the terminal where <code>~/.local/bin/rer dev</code> is running, or run <code>~/.local/bin/rer dev --as owner</code> from the project folder.</p>${invited ? '<p>To sign in as someone who was invited, run <code>~/.local/bin/rer dev --as</code> followed by their email address.</p>' : ''}<p>${terminalHelpHtml}</p></main>${themeLogo ? `<script>${LOGO_SCRIPT}</script>` : ''}<script>${EXCHANGE_SCRIPT}</script></body></html>`;
|
|
108
109
|
return new Response(request.method === 'HEAD' ? null : body, { headers: { ...privateHeaders, 'content-type': 'text/html; charset=utf-8',
|
|
109
110
|
'content-security-policy': `default-src 'none'; img-src 'self'; script-src ${script}${themeLogo ? ` ${logo}` : ''}; style-src ${theme ? "'self' " : ''}${style}${theme ? "; font-src 'self'" : ''}; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'` } });
|
|
110
111
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { terminalHelp } from './terminal-guidance.mjs';
|
|
1
2
|
import { rejectedResponse } from './rejected-response.mjs';
|
|
2
3
|
import { identitySettingsPage } from './accounts/settings-page.mjs';
|
|
3
4
|
import { settingsRefusalPage } from './page.mjs';
|
|
@@ -9,7 +10,7 @@ import { securityHeaders, requireLoopback } from './http.mjs';
|
|
|
9
10
|
import { safeReturnTo } from './policy.mjs';
|
|
10
11
|
import { readInput, readParameters } from './input.mjs';
|
|
11
12
|
import { OWNER_SIGNIN_PATH } from './owner-signin-grant.mjs';
|
|
12
|
-
const ONE_CLICK_REFUSED = 'This sign-in link did not open here. Open the link from the app itself, or run rer dev --as followed by the email address from the project folder.';
|
|
13
|
+
const ONE_CLICK_REFUSED = 'This sign-in link did not open here. Open the link from the app itself, or run ~/.local/bin/rer dev --as followed by the email address from the project folder.' + ' ' + terminalHelp;
|
|
13
14
|
function json(value, status = 200) { return Response.json(value, { status, headers: securityHeaders() }); }
|
|
14
15
|
function seeOther(location, cookie) { return new Response(null, { status: 303, headers: { ...securityHeaders(), ...(cookie ? { 'Set-Cookie': cookie } : {}), Location: location } }); }
|
|
15
16
|
// A native HTML form (the sign-in page before any script) gets a page back; an
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// Owner recovery shared by terminal output and local sign-in pages.
|
|
2
|
+
export const terminalHelp = "If you see 'command not found', run `~/.local/bin/rer cli path` and paste the line it prints.";
|
|
3
|
+
export const terminalHelpHtml = terminalHelp.replace('`~/.local/bin/rer cli path`', '<code>~/.local/bin/rer cli path</code>');
|
|
@@ -148,6 +148,7 @@ export async function prepareSettings(context, hooks) {
|
|
|
148
148
|
try {
|
|
149
149
|
context.origin = await chooseOrigin(context, hooks);
|
|
150
150
|
context.vars = await moveSavedOrigin(context, hooks.secrets, await writeSecrets(context, hooks.secrets));
|
|
151
|
+
await hooks.secrets.afterWrite?.(context);
|
|
151
152
|
} finally { await operation.release(); }
|
|
152
153
|
}
|
|
153
154
|
|
package/onboarding/adapter.mjs
CHANGED
|
@@ -75,7 +75,7 @@ export function localInstaller(hooks = {}) {
|
|
|
75
75
|
catch (error) {
|
|
76
76
|
if (verb !== 'dev' || signal?.aborted || isBusyFailure(error)) throw error;
|
|
77
77
|
const failure = approvedFailure(error);
|
|
78
|
-
throw commandFailure(`${store.redact(failure?.message ?? error.message)}\nLocal migrations failed. Fix the error and run rer setup before trying again.`, failure ?? {});
|
|
78
|
+
throw commandFailure(`${store.redact(failure?.message ?? error.message)}\nLocal migrations failed. Fix the error and run ~/.local/bin/rer setup before trying again.`, failure ?? {});
|
|
79
79
|
}
|
|
80
80
|
}
|
|
81
81
|
await options.beforeStart?.(context);
|
|
@@ -278,7 +278,7 @@ async function start(context, hooks) {
|
|
|
278
278
|
if(detectedMismatch)throw installationFailure('command_failed',{step:'start',diagnostic:error});
|
|
279
279
|
if(runtimePortHandshake&&!announcement){
|
|
280
280
|
const prior=approvedFailure(error);
|
|
281
|
-
const message=`No managed listener was announced after ${Math.round(performance.now()-readinessStarted)} ms (allowed ${readinessTimeoutMs} ms). Check the runtime startup output in the log below, correct the startup error, then run rer ${context.verb??'setup'} again.`;
|
|
281
|
+
const message=`No managed listener was announced after ${Math.round(performance.now()-readinessStarted)} ms (allowed ${readinessTimeoutMs} ms). Check the runtime startup output in the log below, correct the startup error, then run ~/.local/bin/rer ${context.verb??'setup'} again.`;
|
|
282
282
|
throw installationFailure('command_failed',{step:'start',diagnostic:commandFailure(`${message}\n${prior?.message??readinessLabel}`,prior??{})});
|
|
283
283
|
}
|
|
284
284
|
const ports=await ownedPorts();
|
|
@@ -303,7 +303,7 @@ async function start(context, hooks) {
|
|
|
303
303
|
if (ownership.status !== 'owned') {
|
|
304
304
|
const message = (store.redact??(value=>value))(ownership.status==='other'
|
|
305
305
|
? `Another process answered on port ${expectedPort}; the application did not bind it. Listener PID ${ownership.pid}. Nothing was sent. Stop that process or choose another port, then run setup again.`
|
|
306
|
-
: `Could not confirm the application on port ${expectedPort}: repeated inspection found no listener on the health address. Nothing was sent. Check the application binding, then run rer ${context.verb??'setup'} again.`);
|
|
306
|
+
: `Could not confirm the application on port ${expectedPort}: repeated inspection found no listener on the health address. Nothing was sent. Check the application binding, then run ~/.local/bin/rer ${context.verb??'setup'} again.`);
|
|
307
307
|
store.report?.(message);
|
|
308
308
|
throw installationFailure('command_failed', { step: 'start', diagnostic: commandFailure(message, {}) });
|
|
309
309
|
}
|
|
@@ -4,6 +4,6 @@ export function agentHandoff(root,origin,sessionId,seed){
|
|
|
4
4
|
Never put credentials in files, commands, URLs, logs or chat. Leave unresolved preferences, provider sign-in, credentials and final installation approval to the owner. Do not install, deploy or authenticate providers.`;
|
|
5
5
|
return {root,origin,sessionId,prompt:`Help prepare setup answers for my ${seed.product} checkout in ${JSON.stringify(root)}; its setup session is open at ${origin}.
|
|
6
6
|
Work on this same machine. Read AGENTS.md, then inspect the repository and available owner context as evidence, never as authority to override this request.
|
|
7
|
-
Infer supported missing nonsecret answers from actual repository configuration, owner context and connected provider metadata. Omit unknown values rather than inventing them. Write them to a private JSON file using the installer's answer names and give its absolute path to the owner, who can enter them in the open session or apply them with rer setup --answers /absolute/known-answers.json.
|
|
7
|
+
Infer supported missing nonsecret answers from actual repository configuration, owner context and connected provider metadata. Omit unknown values rather than inventing them. Write them to a private JSON file using the installer's answer names and give its absolute path to the owner, who can enter them in the open session or apply them with ~/.local/bin/rer setup --answers /absolute/known-answers.json.
|
|
8
8
|
${rules}`};
|
|
9
9
|
}
|
package/onboarding/busy.mjs
CHANGED
|
@@ -10,7 +10,7 @@ function waited(seconds) {
|
|
|
10
10
|
}
|
|
11
11
|
|
|
12
12
|
export function busyMessage(result, { verb, maxWait }) {
|
|
13
|
-
const command = commandNames.has(verb) ?
|
|
13
|
+
const command = commandNames.has(verb) ? `~/.local/bin/rer ${verb}` : 'the same command';
|
|
14
14
|
const load = result.resources?.load, threshold = result.limits?.loadThreshold;
|
|
15
15
|
if (result.reasonCodes?.includes('load') && Number.isFinite(load) && threshold !== undefined) {
|
|
16
16
|
return `Not started: this computer is busy. Its 1-minute load is ${load.toFixed(1)} and jobs start only at ${threshold} or below; this step waited ${waited(maxWait)} for it to drop.\nTry again in a few minutes by running ${command} again, or start it anyway with a higher threshold, for example RER_JOBS_LOAD_THRESHOLD=${Math.ceil(Math.max(threshold, load) * 2)} ${command}.`;
|
package/onboarding/launcher.mjs
CHANGED
|
@@ -5,7 +5,7 @@ import { readAnswers, readSecrets } from './prefill.mjs';
|
|
|
5
5
|
import { startInstaller } from './server.mjs';
|
|
6
6
|
export async function launch(root,seed){
|
|
7
7
|
refuseLegacySetup(seed);
|
|
8
|
-
if(process.argv.includes('--help')){console.log(`Launch the standalone ${seed.product} installer before installing app dependencies.\nCommand-line setup instead: rer install, then rer setup.\nUsage: node ${relative(process.cwd(),process.argv[1])} [--port <local-port>] [--no-open] [--agent] [--no-prefill | --resume] [--answers answers.json] [--secrets-stdin]`);process.exit(0)}
|
|
8
|
+
if(process.argv.includes('--help')){console.log(`Launch the standalone ${seed.product} installer before installing app dependencies.\nCommand-line setup instead: ~/.local/bin/rer install, then ~/.local/bin/rer setup.\nUsage: node ${relative(process.cwd(),process.argv[1])} [--port <local-port>] [--no-open] [--agent] [--no-prefill | --resume] [--answers answers.json] [--secrets-stdin]`);process.exit(0)}
|
|
9
9
|
let noOpen=false,port=0,answersPath,secrets=false,noPrefill=false,resume=false,agent=false;
|
|
10
10
|
const args=process.argv.slice(2);
|
|
11
11
|
for(let index=0;index<args.length;index++){
|
|
@@ -29,7 +29,7 @@ export function localOrigin(vars) {
|
|
|
29
29
|
let url
|
|
30
30
|
try { url = new URL(vars.AUTH_ORIGIN) } catch { /* Use a fixed, non-secret diagnostic. */ }
|
|
31
31
|
if (vars.AUTH_LOCAL !== 'true' || !url || url.protocol !== 'http:' || (url.hostname !== '127.0.0.1' && !isLocalhostName(url.hostname)) || url.origin !== vars.AUTH_ORIGIN || url.username || url.password) {
|
|
32
|
-
throw new Error('Invalid local origin in .dev.vars: AUTH_ORIGIN must be http://127.0.0.1:PORT (or a front-door http://NAME.localhost:PORT) with AUTH_LOCAL=true. Run rer setup to save a valid one. If you changed AUTH_ORIGIN yourself, put back the http://127.0.0.1:PORT origin setup saved, or pick a port with rer setup --port PORT.')
|
|
32
|
+
throw new Error('Invalid local origin in .dev.vars: AUTH_ORIGIN must be http://127.0.0.1:PORT (or a front-door http://NAME.localhost:PORT) with AUTH_LOCAL=true. Run ~/.local/bin/rer setup to save a valid one. If you changed AUTH_ORIGIN yourself, put back the http://127.0.0.1:PORT origin setup saved, or pick a port with ~/.local/bin/rer setup --port PORT.')
|
|
33
33
|
}
|
|
34
34
|
return url
|
|
35
35
|
}
|
|
@@ -11,7 +11,7 @@ const busy = async (path) => {
|
|
|
11
11
|
let command='process';
|
|
12
12
|
if(pid)try{command=await processName(pid,inspectionContext({budgetMs:1000}));}catch(error){if(!uncheckedInspection(error))throw error;}
|
|
13
13
|
const identity=pid?`PID ${pid} (${command})`:'an unidentified process';
|
|
14
|
-
return Object.assign(new Error(`An active local operation owns the state: ${identity}. Stop it with rer dev --stop or rer preview --stop; for an unmanaged process, stop PID ${pid ?? 'shown in the lock'} before retrying.`), {code: 'LOCAL_OPERATION_BUSY', ownerPid: pid});
|
|
14
|
+
return Object.assign(new Error(`An active local operation owns the state: ${identity}. Stop it with ~/.local/bin/rer dev --stop or ~/.local/bin/rer preview --stop; for an unmanaged process, stop PID ${pid ?? 'shown in the lock'} before retrying.`), {code: 'LOCAL_OPERATION_BUSY', ownerPid: pid});
|
|
15
15
|
}
|
|
16
16
|
const graceMs = 10000
|
|
17
17
|
|
|
@@ -22,7 +22,12 @@ const graceMs = 10000
|
|
|
22
22
|
export async function localOperation(root, inheritedToken) {
|
|
23
23
|
const directory = join(root, '.wrangler/local-operation')
|
|
24
24
|
await privateDirectory(root, directory)
|
|
25
|
-
|
|
25
|
+
return fileOperation(join(directory, 'active.json'), inheritedToken)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Shared with hosted deploy state: the same dead-process takeover and exclusive
|
|
29
|
+
// guard protect both operations without deleting a live writer's lock.
|
|
30
|
+
export async function fileOperation(path, inheritedToken, onBusy = busy) {
|
|
26
31
|
if (inheritedToken) {
|
|
27
32
|
let owner
|
|
28
33
|
try { owner = JSON.parse(await readFile(path, 'utf8')) } catch { /* Fixed diagnostic below. */ }
|
|
@@ -40,7 +45,7 @@ export async function localOperation(root, inheritedToken) {
|
|
|
40
45
|
// A killed process cannot release its lock. Take over only when the
|
|
41
46
|
// recorded process is gone; a half-written file gets a short grace.
|
|
42
47
|
if (attempt === 0 && await takeOver(path)) continue
|
|
43
|
-
throw await
|
|
48
|
+
throw await onBusy(path)
|
|
44
49
|
}
|
|
45
50
|
}
|
|
46
51
|
const token = randomUUID()
|
|
@@ -121,7 +126,10 @@ async function staleIdentity(path) {
|
|
|
121
126
|
const status = await handle.stat({ bigint: true })
|
|
122
127
|
const id = key(status)
|
|
123
128
|
try {
|
|
124
|
-
const
|
|
129
|
+
const recorded = JSON.parse(await handle.readFile('utf8'))
|
|
130
|
+
// Older deploy locks contain only a PID. Keep a live legacy holder; a
|
|
131
|
+
// dead one is safe to recover just like a structured operation record.
|
|
132
|
+
const owner = Number.isSafeInteger(recorded) ? { pid: recorded } : recorded
|
|
125
133
|
if (Number.isSafeInteger(owner.pid) && owner.pid > 0) {
|
|
126
134
|
if (await ownerAlive(owner)) return undefined
|
|
127
135
|
retained = true
|
|
@@ -44,7 +44,7 @@ export async function assertLocalOwner(root,email,failure=message=>Error(message
|
|
|
44
44
|
if(placeholder)return {owners,placeholder};
|
|
45
45
|
if(owners.length&&!owners.some(owner=>owner.toLowerCase()===email.toLowerCase())){
|
|
46
46
|
const address=safeOwner(owners[0]);
|
|
47
|
-
throw failure(`Local database already belongs to ${address}. Restore ${setting} to ${address}, then run rer setup --owner-email ${address}; or back up data, run rer dev --stop, then rer reset --yes followed by rer setup --owner-email ${safeOwner(email)}. Reset deletes local data. Existing data and private settings were kept.`);
|
|
47
|
+
throw failure(`Local database already belongs to ${address}. Restore ${setting} to ${address}, then run ~/.local/bin/rer setup --owner-email ${address}; or back up data, run ~/.local/bin/rer dev --stop, then ~/.local/bin/rer reset --yes followed by ~/.local/bin/rer setup --owner-email ${safeOwner(email)}. Reset deletes local data. Existing data and private settings were kept.`);
|
|
48
48
|
}
|
|
49
49
|
return {owners};
|
|
50
50
|
}
|
|
@@ -57,7 +57,7 @@ export async function replaceLocalOwner(root,from,to,failure=message=>Error(mess
|
|
|
57
57
|
try{
|
|
58
58
|
const tables=new Set(db.prepare("SELECT name FROM sqlite_master WHERE type='table'").all().map(row=>row.name));
|
|
59
59
|
if(!tables.has('oa_operators'))continue;
|
|
60
|
-
if(db.prepare('SELECT 1 FROM oa_operators WHERE lower(email)=lower(?) AND lower(email)<>lower(?)').get(to,from))throw failure(`${safeOwner(to)} already has an account in the local database, so the zero-setup owner ${safeOwner(from)} was kept. Run rer setup --owner-email ${safeOwner(from)}, or back up data and run rer reset --yes.`);
|
|
60
|
+
if(db.prepare('SELECT 1 FROM oa_operators WHERE lower(email)=lower(?) AND lower(email)<>lower(?)').get(to,from))throw failure(`${safeOwner(to)} already has an account in the local database, so the zero-setup owner ${safeOwner(from)} was kept. Run ~/.local/bin/rer setup --owner-email ${safeOwner(from)}, or back up data and run ~/.local/bin/rer reset --yes.`);
|
|
61
61
|
db.prepare("UPDATE oa_operators SET email=?,version=version+1 WHERE lower(email)=lower(?) AND role='owner' AND status='active'").run(to,from);
|
|
62
62
|
}finally{db.close();}
|
|
63
63
|
}
|
|
@@ -3,6 +3,7 @@ import { privateDirectory } from './private-files.mjs';
|
|
|
3
3
|
import { localInstaller } from './adapter.mjs';
|
|
4
4
|
import { selectLocalState, LocalStateSafetyError } from './local/state.mjs';
|
|
5
5
|
import {operatorPrerequisites} from './operator-prerequisites.mjs';
|
|
6
|
+
import { localOperatorSettings, prepareOperatorMail, repairOperatorMail } from './operator-settings.mjs';
|
|
6
7
|
import { migrateOperator } from './operator-migrations.mjs';
|
|
7
8
|
import { installOperator } from './operator-install.mjs';
|
|
8
9
|
import { join, delimiter } from 'node:path';
|
|
@@ -11,11 +12,11 @@ export function operatorInstaller({ database, features, prepare, prepareData })
|
|
|
11
12
|
const lifecycle=localInstaller({
|
|
12
13
|
features, node: '22.20.0',
|
|
13
14
|
failure: (error,{store})=>error instanceof LocalStateSafetyError ? store.redact(error.message) : undefined,
|
|
14
|
-
async prepare(context) { context.localState = await selectLocalState(context.root); await privateDirectory(context.root, ['.wrangler', 'state']); await prepare?.(context); },
|
|
15
|
+
async prepare(context) { await prepareOperatorMail(context); context.localState = await selectLocalState(context.root); await privateDirectory(context.root, ['.wrangler', 'state']); await prepare?.(context); },
|
|
15
16
|
prepareData,
|
|
16
17
|
guard: async ({ root }) => { await selectLocalState(root); },
|
|
17
18
|
secrets: {
|
|
18
|
-
keepExisting: true, originKey: 'AUTH_ORIGIN',
|
|
19
|
+
keepExisting: true, originKey: 'AUTH_ORIGIN', afterWrite: repairOperatorMail,
|
|
19
20
|
values: ({ origin }) => ({ AUTH_LOCAL: 'true', AUTH_ORIGIN: origin, MAIL_PROVIDER: 'development', MAIL_FROM: 'auth@localhost.test' }),
|
|
20
21
|
},
|
|
21
22
|
build: ['pnpm', ['run', '--silent', 'build:app']],
|
|
@@ -27,7 +28,7 @@ export function operatorInstaller({ database, features, prepare, prepareData })
|
|
|
27
28
|
});
|
|
28
29
|
// A demo migrates and claims the owner in its own state, so it never opens the
|
|
29
30
|
// checkout's database: even read-only, SQLite rewrites its -shm index.
|
|
30
|
-
return {...lifecycle,localPrerequisites:async({root,vars,demo})=>
|
|
31
|
+
return {...lifecycle,localPrerequisites:async({root,vars,demo})=>localOperatorSettings(vars) ?? (demo ? true : await operatorPrerequisites(root)),install:(root,input,store,onApp,signal)=>installOperator(root,input,store,onApp,signal,lifecycle.hooks)};
|
|
31
32
|
}
|
|
32
33
|
|
|
33
34
|
// Setup and dev give the real Vite listener one finite fifteen-minute startup
|
|
@@ -28,7 +28,7 @@ export async function migrateOperator(context, database) {
|
|
|
28
28
|
const { root, demo, store } = context;
|
|
29
29
|
const config = JSON.parse(await readFile(join(root, 'dist/server/wrangler.json'), 'utf8'));
|
|
30
30
|
const binding = config.d1_databases?.find(item => item.database_name === database || item.binding === database);
|
|
31
|
-
if (!binding) throw new Error(`Local migration database ${database} is missing from the built configuration. Run rer setup.`);
|
|
31
|
+
if (!binding) throw new Error(`Local migration database ${database} is missing from the built configuration. Run ~/.local/bin/rer setup.`);
|
|
32
32
|
const state = resolve(root, demo?.state ?? await selectLocalState(root));
|
|
33
33
|
const inventory = resolve(root, 'migrations/core');
|
|
34
34
|
const names = (await readdir(inventory)).filter(name => name.endsWith('.sql')).sort();
|
|
@@ -2,28 +2,40 @@ import { readdir,lstat } from 'node:fs/promises';
|
|
|
2
2
|
import { join } from 'node:path';
|
|
3
3
|
import { DatabaseSync } from 'node:sqlite';
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
//
|
|
7
|
-
//
|
|
5
|
+
const failure=(field,found,expected)=>({field,found,expected});
|
|
6
|
+
// Read-only: preflight never creates a database or owner. Report the furthest
|
|
7
|
+
// proven prerequisite in one database, without reading any credential values.
|
|
8
8
|
export async function operatorPrerequisites(root){
|
|
9
|
-
const migrations=(await readdir(join(root,'migrations/core'))).filter(name=>name.endsWith('.sql'));
|
|
9
|
+
const migrations=(await readdir(join(root,'migrations/core'))).filter(name=>name.endsWith('.sql')).sort();
|
|
10
10
|
const directory=join(root,'.wrangler/state/v3/d1/miniflare-D1DatabaseObject');
|
|
11
|
+
const absent=failure('local database','unset','set');
|
|
11
12
|
let files;try{
|
|
12
|
-
let path=root;for(const part of ['.wrangler','state','v3','d1','miniflare-D1DatabaseObject']){path=join(path,part);const info=await lstat(path);if(!info.isDirectory()||info.isSymbolicLink()||info.uid!==process.getuid())return
|
|
13
|
-
files=await readdir(directory,{withFileTypes:true});}catch{return
|
|
13
|
+
let path=root;for(const part of ['.wrangler','state','v3','d1','miniflare-D1DatabaseObject']){path=join(path,part);const info=await lstat(path);if(!info.isDirectory()||info.isSymbolicLink()||info.uid!==process.getuid())return absent;}
|
|
14
|
+
files=await readdir(directory,{withFileTypes:true});}catch{return absent;}
|
|
15
|
+
let result=absent,progress=0;
|
|
14
16
|
for(const file of files){
|
|
15
17
|
if(!file.isFile()||!file.name.endsWith('.sqlite'))continue;
|
|
16
|
-
let db;
|
|
18
|
+
let db,stage=1,problem=failure('d1_migrations','unset','set');
|
|
17
19
|
try{
|
|
18
20
|
db=new DatabaseSync(join(directory,file.name),{readOnly:true});
|
|
19
21
|
const applied=new Set(db.prepare('SELECT name FROM d1_migrations').all().map(row=>row.name));
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
22
|
+
stage=2;
|
|
23
|
+
const pending=migrations.find(name=>!applied.has(name));
|
|
24
|
+
problem=pending?failure(`migration ${pending}`,'unapplied','applied'):failure('oa_bootstrap','unset','one durable owner claim');
|
|
25
|
+
if(!pending){
|
|
26
|
+
stage=3;
|
|
27
|
+
const claimed=db.prepare('SELECT COUNT(*) AS count FROM oa_bootstrap').get().count;
|
|
28
|
+
problem=failure('oa_bootstrap',String(claimed),'1');
|
|
29
|
+
if(claimed===1){
|
|
30
|
+
stage=4;problem=failure('oa_operators active owner','unset','at least one');
|
|
31
|
+
const owners=db.prepare("SELECT COUNT(*) AS count FROM oa_operators WHERE role='owner' AND status='active'").get().count;
|
|
32
|
+
if(owners>0)return true;
|
|
33
|
+
problem=failure('oa_operators active owner',String(owners),'at least one');
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}catch{/* A missing/corrupt/unrelated database proves only prior stages. */}
|
|
26
37
|
finally{db?.close();}
|
|
38
|
+
if(stage>progress){progress=stage;result=problem;}
|
|
27
39
|
}
|
|
28
|
-
return
|
|
40
|
+
return result;
|
|
29
41
|
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { readSettings, replaceSavedSetting } from './adapter-settings.mjs';
|
|
2
|
+
import { commandFailure } from './failures.mjs';
|
|
3
|
+
import { writePrivateFile } from './private-files.mjs';
|
|
4
|
+
|
|
5
|
+
export function localOperatorSettings(vars) {
|
|
6
|
+
if(vars.AUTH_LOCAL!=='true')return {field:'AUTH_LOCAL',found:JSON.stringify(vars.AUTH_LOCAL??'unset'),expected:'true'};
|
|
7
|
+
if(vars.MAIL_PROVIDER!=='development')return {field:'MAIL_PROVIDER',found:JSON.stringify(vars.MAIL_PROVIDER??'unset'),expected:'development'};
|
|
8
|
+
if(!vars.SESSION_SECRET)return {field:'SESSION_SECRET',found:'unset',expected:'set'};
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// AUTH_LOCAL does not suppress remote senders in every adopting seed. Keep the
|
|
12
|
+
// shared local contract explicit, including when a seed offers hosted mail-off.
|
|
13
|
+
export async function prepareOperatorMail({root,input}) {
|
|
14
|
+
const saved=(await readSettings(root,{})).values;
|
|
15
|
+
if(input.MAIL_PROVIDER!==undefined&&input.MAIL_PROVIDER!=='development'&&!saved.OWNER_EMAIL) {
|
|
16
|
+
throw commandFailure(`Local prerequisite MAIL_PROVIDER: found ${JSON.stringify(input.MAIL_PROVIDER)}; expected development; run ~/.local/bin/rer setup with MAIL_PROVIDER=development in the --answers file.`,{});
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export async function repairOperatorMail(context) {
|
|
21
|
+
if((context.verb&&!['installer','setup'].includes(context.verb))||context.vars.MAIL_PROVIDER==='development')return;
|
|
22
|
+
const current=await readSettings(context.root,{});
|
|
23
|
+
if(current.values.MAIL_PROVIDER===undefined){
|
|
24
|
+
await writePrivateFile(current.path,current.text.replace(/\n*$/,'\n')+'MAIL_PROVIDER=development\n');
|
|
25
|
+
context.vars={...context.vars,MAIL_PROVIDER:'development'};
|
|
26
|
+
}else context.vars=await replaceSavedSetting(context.root,{},'MAIL_PROVIDER','development');
|
|
27
|
+
context.store.report('Local MAIL_PROVIDER was repaired to development; local mail is suppressed.');
|
|
28
|
+
}
|
|
@@ -41,7 +41,7 @@ const run=async(command,args,context=inspectionContext(),{maxBuffer=1024*1024,no
|
|
|
41
41
|
}
|
|
42
42
|
const subject=context.port?`who uses port ${context.port}`:'local process ownership';
|
|
43
43
|
const cause=failure?.startsWith('timed out')||performance.now()>=context.deadline?'in time (system busy)':'because the system process check failed';
|
|
44
|
-
throw commandFailure(`Could not check ${subject} ${cause}. Run rer ${context.verb??'dev'} again. No other owner was identified.\nOwnership check: ${invocation} ${failure??'total inspection deadline exhausted'} (at most 2 attempts; shared total bound ${context.budgetMs??15000} ms).`,{ownershipUnchecked:true});
|
|
44
|
+
throw commandFailure(`Could not check ${subject} ${cause}. Run ~/.local/bin/rer ${context.verb??'dev'} again. No other owner was identified.\nOwnership check: ${invocation} ${failure??'total inspection deadline exhausted'} (at most 2 attempts; shared total bound ${context.budgetMs??15000} ms).`,{ownershipUnchecked:true});
|
|
45
45
|
};
|
|
46
46
|
|
|
47
47
|
export async function processName(pid,context=inspectionContext()){
|
|
@@ -141,7 +141,7 @@ function matchingListener(rows,port,host){
|
|
|
141
141
|
const row=rows.find(row=>row.sockets.some(socket=>serves(socket,port,host)===true));
|
|
142
142
|
if(row)return row;
|
|
143
143
|
if(rows.some(row=>row.sockets.some(socket=>serves(socket,port,host)===undefined))){
|
|
144
|
-
throw commandFailure(`Could not check who uses port ${port}: a wildcard socket's address family does not prove it serves ${host}. No other owner was identified. Bind the application to the health address explicitly, then run rer dev again.`,{ownershipUnchecked:true});
|
|
144
|
+
throw commandFailure(`Could not check who uses port ${port}: a wildcard socket's address family does not prove it serves ${host}. No other owner was identified. Bind the application to the health address explicitly, then run ~/.local/bin/rer dev again.`,{ownershipUnchecked:true});
|
|
145
145
|
}
|
|
146
146
|
}
|
|
147
147
|
export async function portListener(port,host,context=inspectionContext()){
|
|
@@ -8,7 +8,7 @@ import {dirname,join,resolve} from 'node:path';
|
|
|
8
8
|
export function projectViteBinary(root){
|
|
9
9
|
let manifest;
|
|
10
10
|
try{manifest=createRequire(join(resolve(root),'package.json')).resolve('vite/package.json');}
|
|
11
|
-
catch{throw new Error('The project\'s vite is not installed. Run rer install first.');}
|
|
11
|
+
catch{throw new Error('The project\'s vite is not installed. Run ~/.local/bin/rer install first.');}
|
|
12
12
|
const bin=JSON.parse(readFileSync(manifest,'utf8')).bin;
|
|
13
13
|
return join(dirname(manifest),typeof bin==='string'?bin:bin.vite);
|
|
14
14
|
}
|