@runeditrun/rer 0.2.119 → 0.2.121
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 +89 -0
- package/cli/browser-runtime.mjs +32 -17
- package/cli/business/agent-args.mjs +60 -0
- package/cli/business/agent-help.mjs +53 -0
- package/cli/business/agent-output.mjs +38 -0
- package/cli/business/agent-table.mjs +32 -0
- package/cli/business/agent-verbs.mjs +132 -0
- package/cli/business/agent-wait.mjs +28 -0
- package/cli/business/command.mjs +18 -2
- package/cli/business/mcp-bridge.mjs +58 -0
- package/cli/business/questions.mjs +32 -9
- package/cli/business/run-child.mjs +42 -0
- package/cli/business/run-grant.mjs +65 -0
- package/cli/business/run-mask.mjs +21 -0
- package/cli/deploy-inputs.mjs +13 -0
- package/cli/deploy-settings.mjs +14 -0
- package/cli/deploy-variables.mjs +7 -1
- package/cli/deploy.mjs +2 -2
- package/cli/inspect.mjs +6 -1
- package/cli/lifecycle.mjs +1 -1
- package/cli/parse.mjs +11 -1
- package/global/CHANGELOG.md +31 -0
- package/global/browser-runtime.mjs +9 -5
- package/global/run.mjs +1 -1
- package/modules/deploy-kit/README.md +1 -0
- package/modules/deploy-kit/owner-cli.mjs +6 -4
- package/modules/deploy-kit/owner-secret-copy.mjs +2 -1
- package/modules/deploy-kit/owner-secret.mjs +1 -1
- package/modules/deploy-kit/owner.mjs +3 -2
- package/modules/deploy-kit/validation.mjs +1 -0
- package/modules/deploy-kit/worker.mjs +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { createInterface } from 'node:readline';
|
|
2
|
+
import { Api } from './api.mjs';
|
|
3
|
+
import { mcpClient } from './questions.mjs';
|
|
4
|
+
import { paired } from './local-commands.mjs';
|
|
5
|
+
import { describe } from './errors.mjs';
|
|
6
|
+
|
|
7
|
+
const protocolVersion = '2025-11-25';
|
|
8
|
+
const forwarded = /^(tools|resources|prompts|completion|logging)\//;
|
|
9
|
+
|
|
10
|
+
/** A local stdio MCP server for an agent (Claude Code, Codex): newline-delimited JSON-RPC in, the same out. Calls go to the
|
|
11
|
+
* Business MCP with a bearer minted from this computer's pairing and minted again when it nears expiry or is refused, so the
|
|
12
|
+
* agent never holds a token. Only protocol messages are written to stdout; everything else goes to stderr. */
|
|
13
|
+
export async function bridge({ input = process.stdin, output = process.stdout, errors = process.stderr } = {}) {
|
|
14
|
+
let session;
|
|
15
|
+
const connection = () => session ??= (async () => {
|
|
16
|
+
const { state, credential } = await paired();
|
|
17
|
+
return mcpClient(new Api(state.origin, credential));
|
|
18
|
+
})().catch(error => { session = undefined; throw error; });
|
|
19
|
+
const send = message => output.write(JSON.stringify({ jsonrpc: '2.0', ...message }) + '\n');
|
|
20
|
+
const fail = (id, code, text) => send({ id, error: { code, message: text } });
|
|
21
|
+
|
|
22
|
+
async function handle(message) {
|
|
23
|
+
const { id, method, params } = message;
|
|
24
|
+
if (typeof method !== 'string') return;
|
|
25
|
+
if (id === undefined || id === null) return; // A notification needs no answer.
|
|
26
|
+
try {
|
|
27
|
+
if (method === 'ping') return send({ id, result: {} });
|
|
28
|
+
const upstream = await connection();
|
|
29
|
+
if (method === 'initialize') {
|
|
30
|
+
const { capabilities, instructions } = upstream.initialized;
|
|
31
|
+
return send({ id, result: { protocolVersion, capabilities: capabilities ?? {}, serverInfo: { name: 'rer-business', version: '1.0.0' }, ...(typeof instructions === 'string' ? { instructions } : {}) } });
|
|
32
|
+
}
|
|
33
|
+
if (!forwarded.test(method)) return fail(id, -32601, `Method not found: ${method.slice(0, 80)}`);
|
|
34
|
+
const response = await upstream.exchange(method, params ?? {});
|
|
35
|
+
if (response.error) {
|
|
36
|
+
const { code, message: text, data } = response.error;
|
|
37
|
+
return send({ id, error: { code: Number.isInteger(code) ? code : -32000, message: describe(Error(String(text ?? 'Business refused the request.'))), ...(data !== undefined ? { data } : {}) } });
|
|
38
|
+
}
|
|
39
|
+
send({ id, result: response.result });
|
|
40
|
+
} catch (error) {
|
|
41
|
+
errors.write(describe(error) + '\n');
|
|
42
|
+
fail(id, -32000, describe(error));
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const pending = new Set();
|
|
47
|
+
const lines = createInterface({ input, crlfDelay: Infinity });
|
|
48
|
+
for await (const line of lines) {
|
|
49
|
+
if (!line.trim()) continue;
|
|
50
|
+
let message;
|
|
51
|
+
try { message = JSON.parse(line); } catch { fail(null, -32700, 'Parse error'); continue; }
|
|
52
|
+
if (message === null || typeof message !== 'object' || Array.isArray(message)) { fail(null, -32600, 'Invalid request'); continue; }
|
|
53
|
+
const work = handle(message).finally(() => pending.delete(work));
|
|
54
|
+
pending.add(work);
|
|
55
|
+
}
|
|
56
|
+
await Promise.all(pending);
|
|
57
|
+
return 0;
|
|
58
|
+
}
|
|
@@ -9,24 +9,47 @@ const protocolVersion = '2025-11-25';
|
|
|
9
9
|
const headers = { Accept: 'application/json, text/event-stream', 'MCP-Protocol-Version': protocolVersion };
|
|
10
10
|
export const classifications = ['uses', 'sells', 'both', 'product-dependency'];
|
|
11
11
|
|
|
12
|
+
/** One MCP session on the Business server. The returned function calls a tool and returns its structuredContent (it throws when
|
|
13
|
+
* the tool refuses); `.call` returns the raw tool result, `.exchange` the raw JSON-RPC response for any method, `.initialized` the
|
|
14
|
+
* server's initialize result. The short-lived bearer is minted again within 30 seconds of expiry, and once on a 401. */
|
|
12
15
|
export async function mcpClient(api, { taskId, signal } = {}) {
|
|
13
|
-
|
|
14
|
-
const
|
|
16
|
+
let minted = await api.mintToken('mcp', { taskId, signal });
|
|
17
|
+
const remint = async () => { minted = await api.mintToken('mcp', { taskId, signal }); };
|
|
15
18
|
let sequence = 0;
|
|
19
|
+
async function post(body) {
|
|
20
|
+
if (Date.parse(minted.expires_at) - Date.now() < 30_000) await remint();
|
|
21
|
+
const send = () => api.post('/api/business/mcp', body, { token: minted.access_token, signal, headers });
|
|
22
|
+
try { return await send(); } catch (error) {
|
|
23
|
+
if (error.status !== 401) throw error;
|
|
24
|
+
await remint();
|
|
25
|
+
return send();
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
async function exchange(method, params, notification = false) {
|
|
29
|
+
const id = ++sequence;
|
|
30
|
+
const result = await post({ jsonrpc: '2.0', ...(!notification ? { id } : {}), method, params });
|
|
31
|
+
if (notification) return null;
|
|
32
|
+
if (!result || result.id !== id || !result.error === !result.result) throw Error('Business MCP operation was refused.');
|
|
33
|
+
return result;
|
|
34
|
+
}
|
|
16
35
|
async function rpc(method, params, notification = false) {
|
|
17
|
-
const result = await
|
|
18
|
-
if (
|
|
19
|
-
|
|
20
|
-
return result.result;
|
|
36
|
+
const result = await exchange(method, params, notification);
|
|
37
|
+
if (result?.error) throw Error('Business MCP operation was refused.');
|
|
38
|
+
return result?.result;
|
|
21
39
|
}
|
|
22
40
|
const initialized = await rpc('initialize', { protocolVersion, capabilities: {}, clientInfo: { name: 'rer-business', version: '1.0.0' } });
|
|
23
41
|
if (initialized.protocolVersion !== protocolVersion) throw Error('Business MCP protocol revision is unsupported.');
|
|
24
42
|
await rpc('notifications/initialized', {}, true);
|
|
25
|
-
|
|
26
|
-
const
|
|
43
|
+
const call = async (name, args = {}) => {
|
|
44
|
+
const response = await exchange('tools/call', { name, arguments: args });
|
|
45
|
+
if (response.error) throw Error(`Business MCP refused ${name}${typeof response.error.message === 'string' ? `: ${response.error.message.slice(0, 300)}` : ''}.`);
|
|
46
|
+
return response.result;
|
|
47
|
+
};
|
|
48
|
+
return Object.assign(async (name, args = {}) => {
|
|
49
|
+
const result = await call(name, args);
|
|
27
50
|
if (result?.isError || !result?.structuredContent) throw Error('Business task action is unavailable. Use the browser to check its requirements.');
|
|
28
51
|
return result.structuredContent;
|
|
29
|
-
};
|
|
52
|
+
}, { call, exchange, initialized });
|
|
30
53
|
}
|
|
31
54
|
|
|
32
55
|
export async function nextQuestions(api, signal) {
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { constants } from 'node:os';
|
|
3
|
+
import { commandMask } from './run-mask.mjs';
|
|
4
|
+
|
|
5
|
+
export const signalCode = signal => 128 + (constants.signals[signal] ?? 1);
|
|
6
|
+
export function childEnvironment(source, credential, account) {
|
|
7
|
+
const env = Object.fromEntries(Object.entries(source).filter(([key]) => !/^(?:CLOUDFLARE_|CF_|MANAGED_CLOUDFLARE_)/i.test(key)));
|
|
8
|
+
return { ...env, CLOUDFLARE_API_TOKEN: credential, CLOUDFLARE_ACCOUNT_ID: account };
|
|
9
|
+
}
|
|
10
|
+
/** Own one process group, forward interruption, and bound its lifetime to the credential's server expiry. */
|
|
11
|
+
export async function runChild(command, lease, { signal, source = process.env, output = process.stdout, errors = process.stderr } = {}) {
|
|
12
|
+
const values = [lease.credential, lease.account_id], stdout = commandMask(values, output), stderr = commandMask(values, errors);
|
|
13
|
+
let child, escalation, expiry, stopped;
|
|
14
|
+
const stop = reason => {
|
|
15
|
+
stopped ??= reason;
|
|
16
|
+
if (!child?.pid) return;
|
|
17
|
+
const send = sig => { try { if (process.platform === 'win32') child.kill(sig); else process.kill(-child.pid, sig); } catch (error) { if (error.code !== 'ESRCH') throw error; } };
|
|
18
|
+
send(reason);
|
|
19
|
+
escalation ??= setTimeout(() => send('SIGKILL'), 3000);
|
|
20
|
+
};
|
|
21
|
+
const interrupt = () => stop(signal.reason?.signal ?? 'SIGTERM');
|
|
22
|
+
try {
|
|
23
|
+
if (signal?.aborted) return { code: signalCode(signal.reason?.signal ?? 'SIGTERM'), signal: signal.reason?.signal };
|
|
24
|
+
child = spawn(command[0], command.slice(1), { env: childEnvironment(source, lease.credential, lease.account_id),
|
|
25
|
+
stdio: ['inherit', 'pipe', 'pipe'], shell: false, detached: process.platform !== 'win32' });
|
|
26
|
+
child.stdout.on('data', stdout.write); child.stderr.on('data', stderr.write);
|
|
27
|
+
signal?.addEventListener('abort', interrupt, { once: true });
|
|
28
|
+
if (signal?.aborted) interrupt();
|
|
29
|
+
expiry = setTimeout(() => stop('SIGTERM'), Math.max(1, Date.parse(lease.credential_expires_at) - Date.now()));
|
|
30
|
+
const result = await new Promise(resolve => {
|
|
31
|
+
let spawnError;
|
|
32
|
+
child.on('error', error => { spawnError = error; });
|
|
33
|
+
child.on('close', (code, exitSignal) => resolve(spawnError ? { code: spawnError.code === 'ENOENT' ? 127 : 126, spawnError: spawnError.code }
|
|
34
|
+
: { code: code ?? signalCode(exitSignal ?? stopped ?? 'SIGTERM'), signal: exitSignal }));
|
|
35
|
+
});
|
|
36
|
+
if (result.spawnError) errors.write(`Command could not start (${String(result.spawnError).replace(/[^A-Z0-9_]/g, '')}).\n`);
|
|
37
|
+
return result;
|
|
38
|
+
} finally {
|
|
39
|
+
clearTimeout(expiry); clearTimeout(escalation); signal?.removeEventListener('abort', interrupt);
|
|
40
|
+
stdout.end(); stderr.end();
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { Api, identifier } from './api.mjs';
|
|
3
|
+
import { paired } from './local-commands.mjs';
|
|
4
|
+
import { runChild, signalCode } from './run-child.mjs';
|
|
5
|
+
|
|
6
|
+
const route = '/api/business/executors/cloudflare-token';
|
|
7
|
+
const usage = 'Usage: rer business run --grant G -- <command> [args...]\n';
|
|
8
|
+
function validLease(value, state, grant, id) {
|
|
9
|
+
return value?.lease_id === id && value.grant_id === grant && value.business_id === state.businessId && value.executor_id === state.executorId
|
|
10
|
+
&& /^[a-f0-9]{32}$/.test(value.account_id) && typeof value.credential === 'string' && value.credential.length >= 16 && value.credential.length <= 4096
|
|
11
|
+
&& !/[\s\x00-\x1f\x7f]/.test(value.credential) && value.cleanup_status === 'active' && value.provider_credential_revoked === false
|
|
12
|
+
&& Number.isFinite(Date.parse(value.credential_expires_at)) && Date.parse(value.credential_expires_at) > Date.now()
|
|
13
|
+
&& Date.parse(value.credential_expires_at) <= Date.now() + 900_000;
|
|
14
|
+
}
|
|
15
|
+
async function cleanup(api, id) {
|
|
16
|
+
try {
|
|
17
|
+
const value = await api.post(`${route}/${id}/revoke`, {}, { quiet: true, timeout: 15000 });
|
|
18
|
+
if (value?.lease_id === id && ['revoked', 'expired'].includes(value.cleanup_status)
|
|
19
|
+
&& (value.cleanup_status !== 'revoked' || value.provider_credential_revoked === true)) return value.cleanup_status;
|
|
20
|
+
} catch { /* A lost acknowledgement is unconfirmed, never success. */ }
|
|
21
|
+
return 'unconfirmed';
|
|
22
|
+
}
|
|
23
|
+
export async function cleanupCommand(args) {
|
|
24
|
+
if (args.length < 1 || args.length > 2 || args[1] !== undefined && args[1] !== '--status' || !/^[a-f0-9-]{36}$/.test(args[0])) {
|
|
25
|
+
process.stderr.write('Usage: rer business cleanup LEASE [--status]\n'); return 2;
|
|
26
|
+
}
|
|
27
|
+
const {state, credential} = await paired(), api = new Api(state.origin, credential), id = args[0];
|
|
28
|
+
try {
|
|
29
|
+
const value = args[1] ? await api.request('GET', `${route}/${id}`, undefined, { quiet: true }) : null;
|
|
30
|
+
const status = args[1] ? value?.lease_id === id && ['issuing','active','revoked','unconfirmed','expired'].includes(value.cleanup_status) ? value.cleanup_status : 'unconfirmed' : await cleanup(api, id);
|
|
31
|
+
process.stderr.write(`Cloud credential cleanup: ${status}. Lease ${id}.\n`);
|
|
32
|
+
return ['revoked','expired'].includes(status) ? 0 : 1;
|
|
33
|
+
} catch { process.stderr.write(`Cloud credential cleanup: unconfirmed. Lease ${id}.\n`); return 1; }
|
|
34
|
+
}
|
|
35
|
+
export async function grantCommand(args) {
|
|
36
|
+
if (args[0] !== '--grant' || !args[1] || args[2] !== '--' || !args[3]) { process.stderr.write(usage); return 2; }
|
|
37
|
+
try { identifier(args[1]); } catch { process.stderr.write(usage); return 2; }
|
|
38
|
+
const {state, credential} = await paired(), api = new Api(state.origin, credential), id = randomUUID();
|
|
39
|
+
const stop = new AbortController(), handlers = new Map();
|
|
40
|
+
for (const signal of ['SIGINT','SIGTERM','SIGHUP']) {
|
|
41
|
+
const handler = () => { if (!stop.signal.aborted) stop.abort({signal}); };
|
|
42
|
+
handlers.set(signal, handler); process.on(signal, handler);
|
|
43
|
+
}
|
|
44
|
+
let lease, code = 1, exitSignal;
|
|
45
|
+
try {
|
|
46
|
+
// No automatic retry: a lost response may already have minted a child. Cleanup uses the preselected lease id.
|
|
47
|
+
lease = await api.post(route, {grant_id: args[1], lease_id: id}, {quiet: true, signal: stop.signal});
|
|
48
|
+
if (!validLease(lease, state, args[1], id) || lease.credential === credential) throw Error('invalid credential exchange');
|
|
49
|
+
const result = await runChild(args.slice(3), lease, {signal: stop.signal});
|
|
50
|
+
code = result.code; exitSignal = result.signal;
|
|
51
|
+
} catch {
|
|
52
|
+
code = stop.signal.aborted ? signalCode(stop.signal.reason.signal) : 1;
|
|
53
|
+
process.stderr.write('Business command refused or its credential exchange failed. Check pairing, selected account, deploy action, grant and Cloudflare consent in Business.\n');
|
|
54
|
+
} finally {
|
|
55
|
+
const status = await cleanup(api, id);
|
|
56
|
+
const expiry = lease && Number.isFinite(Date.parse(lease.credential_expires_at)) ? new Date(lease.credential_expires_at).toISOString() : 'the server-enforced expiry (at most 15 minutes)';
|
|
57
|
+
process.stderr.write(`Cloud credential cleanup: ${status}. Lease ${id}.${status === 'unconfirmed' ? ` Credential expiry: ${expiry}. Retry: rer business cleanup ${id}.` : ''}\n`);
|
|
58
|
+
lease = undefined;
|
|
59
|
+
for (const [signal, handler] of handlers) process.removeListener(signal, handler);
|
|
60
|
+
}
|
|
61
|
+
// Keep the child's exit status even if cleanup is unconfirmed; cleanup has its own explicit status above.
|
|
62
|
+
exitSignal ??= stop.signal.reason?.signal;
|
|
63
|
+
if (exitSignal && process.platform !== 'win32') { process.kill(process.pid, exitSignal); await new Promise(resolve => setImmediate(resolve)); }
|
|
64
|
+
return code;
|
|
65
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
2
|
+
|
|
3
|
+
/** Keep a possible credential prefix across writes; neither chunk boundaries nor EOF release it. */
|
|
4
|
+
export function commandMask(values, output) {
|
|
5
|
+
const secrets = [...new Set(values.filter(value => typeof value === 'string' && value).flatMap(value =>
|
|
6
|
+
[value, encodeURIComponent(value), Buffer.from(value).toString('base64'), Buffer.from(value).toString('base64url')]))].sort((a, b) => b.length - a.length);
|
|
7
|
+
const decoder = new StringDecoder('utf8');
|
|
8
|
+
let pending = '';
|
|
9
|
+
function replace(text) { for (const secret of secrets) text = text.split(secret).join('[credential]'); return text; }
|
|
10
|
+
function write(chunk) {
|
|
11
|
+
pending = replace(pending + decoder.write(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)));
|
|
12
|
+
let held = 0;
|
|
13
|
+
for (const secret of secrets) for (let count = Math.min(secret.length - 1, pending.length); count > held; count--)
|
|
14
|
+
if (pending.endsWith(secret.slice(0, count))) { held = count; break; }
|
|
15
|
+
const ready = pending.slice(0, pending.length - held);
|
|
16
|
+
pending = pending.slice(pending.length - held);
|
|
17
|
+
if (ready) output.write(ready);
|
|
18
|
+
}
|
|
19
|
+
return { write, end() { pending = replace(pending + decoder.end()); if (pending) output.write('[credential]'); pending = ''; },
|
|
20
|
+
text: replace };
|
|
21
|
+
}
|
package/cli/deploy-inputs.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import { shared } from './shared.mjs';
|
|
|
4
4
|
import { invalid, refuse } from './errors.mjs';
|
|
5
5
|
import { readDeployEnvFile } from '../modules/deploy-kit/env-file.mjs';
|
|
6
6
|
import { publicOrigin } from '../modules/deploy-kit/public-origin.mjs';
|
|
7
|
+
import { switchableDefaults, switchableDeclarationHelp } from './deploy-settings.mjs';
|
|
7
8
|
import { keptSecrets, rotations, savedSecrets } from './deploy-secrets.mjs';
|
|
8
9
|
|
|
9
10
|
// The values a Workers deploy reads for its declared secrets: this process's
|
|
@@ -20,6 +21,7 @@ export async function deployEnvironment({ root, options, declaration, setupManif
|
|
|
20
21
|
catch (error) { throw invalid(`The --env-file ${options.envFile} could not be used: ${error.code === 'ENOENT' ? 'no such file' : error.message}.`); }
|
|
21
22
|
Object.assign(env, values);
|
|
22
23
|
}
|
|
24
|
+
await applyPublicAssignments(env, options, declaration, setupManifest);
|
|
23
25
|
const originSetting = declaration.publicOriginSetting;
|
|
24
26
|
if (originSetting !== undefined && env[originSetting] === undefined && settings) {
|
|
25
27
|
const { readSettings } = await shared('adapter-settings.mjs');
|
|
@@ -76,6 +78,7 @@ export async function withDeployEnvironment(project, options, out, run) {
|
|
|
76
78
|
const { createRedaction } = await shared('redaction.mjs');
|
|
77
79
|
const { declaredSettings, settingKinds, undeclaredNotice } = await import('./deploy-settings.mjs');
|
|
78
80
|
const declared = await declaredSettings(project), kinds = await settingKinds(declared);
|
|
81
|
+
await applyPublicAssignments(env, options, declared.declaration ?? {}, declared.setupManifest);
|
|
79
82
|
const redaction = createRedaction();
|
|
80
83
|
const supplied = Object.entries(env).filter(([key, value]) => saved[key] !== value);
|
|
81
84
|
redaction.addSecrets([...kinds.privateValues(env), ...supplied.filter(([key, value]) => !kinds.shown(key, value)).map(([, value]) => value)]);
|
|
@@ -97,3 +100,13 @@ export function deployAgain(options) {
|
|
|
97
100
|
const quote = value => /^[a-zA-Z0-9_./-]+$/.test(value) ? value : `'${String(value).replaceAll("'", "'\"'\"'")}'`;
|
|
98
101
|
return `rer deploy --environment ${quote(options.environment ?? 'production')}${options.envFile ? ` --env-file ${quote(options.envFile)}` : ''}${options.cwd ? ` --cwd ${quote(relative(process.cwd(), options.cwd) || '.')}` : ''}${options.dryRun ? ' --dry-run' : ''}`;
|
|
99
102
|
}
|
|
103
|
+
|
|
104
|
+
async function applyPublicAssignments(env, options, declaration, setupManifest) {
|
|
105
|
+
if (options.setSecretValues && declaration.project) {
|
|
106
|
+
const defaults = await switchableDefaults(declaration, setupManifest);
|
|
107
|
+
for (const [binding, value] of Object.entries(options.setSecretValues)) {
|
|
108
|
+
if (!Object.hasOwn(defaults, binding)) throw invalid(`--set-secret NAME=VALUE accepts only declared switchable public settings. ${switchableDeclarationHelp()} Supply credentials through the environment or an owned 0600 --env-file.`);
|
|
109
|
+
env[declaration.secrets.find(item => item.binding === binding).environment] = value;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
package/cli/deploy-settings.mjs
CHANGED
|
@@ -49,3 +49,17 @@ export async function declaredSettings(project) {
|
|
|
49
49
|
export function undeclaredNotice(names, path) {
|
|
50
50
|
return `Undeclared --env-file settings stay out of rer's output: ${names.join(', ')}. To print one, declare it as a non-secret setting: add its name to "publicSettings" in ${path}.`;
|
|
51
51
|
}
|
|
52
|
+
|
|
53
|
+
// Opt-in transport for a public choice with an explicit reset value. Keep this
|
|
54
|
+
// distinct from setup select fields: old declarations keep their exact plans.
|
|
55
|
+
export async function switchableDefaults(declaration, setupManifest) {
|
|
56
|
+
const kinds = await settingKinds({ declaration, setupManifest });
|
|
57
|
+
return Object.fromEntries((Array.isArray(declaration.secrets) ? declaration.secrets : []).filter(item =>
|
|
58
|
+
item?.optional === true && Array.isArray(declaration.publicSettings) && declaration.publicSettings.includes(item.binding) &&
|
|
59
|
+
kinds.shown(item.binding, declaration.vars?.[item.binding]) && kinds.shown(item.environment, declaration.vars?.[item.binding])
|
|
60
|
+
).map(item => [item.binding, declaration.vars[item.binding]]));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function switchableDeclarationHelp(path = 'deploy.json') {
|
|
64
|
+
return `For a switchable public setting such as MAIL_PROVIDER, declare its name in publicSettings, its default in vars, and a secrets entry with binding, environment and optional: true in ${path}; keep the same public default in Wrangler vars. Credentials remain secrets.`;
|
|
65
|
+
}
|
package/cli/deploy-variables.mjs
CHANGED
|
@@ -7,6 +7,7 @@ import { tomlEntries } from './business/parsers-config.mjs';
|
|
|
7
7
|
import { imageVariableSecrets } from '../modules/container/image-variables.mjs';
|
|
8
8
|
import { publicMailSender, validateMailSenders } from '../modules/delivery-producer/mail.mjs';
|
|
9
9
|
import { deliveryDeclarationSources } from './delivery-declarations.mjs';
|
|
10
|
+
import { switchableDefaults, switchableDeclarationHelp } from './deploy-settings.mjs';
|
|
10
11
|
|
|
11
12
|
const id = 'deploy.vars-secrets';
|
|
12
13
|
const lineAt = (source, offset) => source.slice(0, offset).split('\n').length;
|
|
@@ -71,6 +72,7 @@ export async function deployVariableClause(root, adapter) {
|
|
|
71
72
|
privateSender ||= [...(spec.secretNames ?? []), ...(spec.optionalSecretNames ?? [])].includes('MAIL_FROM');
|
|
72
73
|
senders.push({ source: `${path} publicVariables.MAIL_FROM`, value: spec.publicVariables?.MAIL_FROM });
|
|
73
74
|
}
|
|
75
|
+
const defaults = await switchableDefaults(declaration);
|
|
74
76
|
const overlaps = [];
|
|
75
77
|
for (const path of deployConfigPaths(adapter)) {
|
|
76
78
|
for (const entry of await variableEntries(root, path)) {
|
|
@@ -78,12 +80,16 @@ export async function deployVariableClause(root, adapter) {
|
|
|
78
80
|
if (binding === 'MAIL_FROM') senders.push(entry);
|
|
79
81
|
const matched = new Set(imageVariableSecrets({ [binding]: value }, secrets).map(secret => secret.binding));
|
|
80
82
|
if (!matched.has(binding)) continue;
|
|
83
|
+
if (Object.hasOwn(defaults, binding)) {
|
|
84
|
+
if (value !== defaults[binding]) throw Error(`${binding}: ${entry.source} must match the public default in ${declarationPath} vars.${binding}.`);
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
81
87
|
if (binding === 'MAIL_FROM' && publicSender && !privateSender) continue;
|
|
82
88
|
for (const [index, secret] of secrets.entries()) if (secret.binding === binding) overlaps.push(
|
|
83
89
|
`${binding}: ${entry.location} and ${declarationPath}:${secretLocations.get(index)} (secrets)`);
|
|
84
90
|
}
|
|
85
91
|
}
|
|
86
92
|
validateMailSenders(senders);
|
|
87
|
-
return overlaps.length ? { id, ok: false, message: overlaps.join('\n') + '\nremove it from wrangler vars; the deploy sets it as a secret' } : { id, ok: true };
|
|
93
|
+
return overlaps.length ? { id, ok: false, message: overlaps.join('\n') + '\nremove it from wrangler vars; the deploy sets it as a secret. ' + switchableDeclarationHelp(declarationPath) } : { id, ok: true };
|
|
88
94
|
} catch (error) { return { id, ok: false, message: error.message }; }
|
|
89
95
|
}
|
package/cli/deploy.mjs
CHANGED
|
@@ -3,7 +3,7 @@ import { mailOffSignInCommand } from './production-mail.mjs';
|
|
|
3
3
|
import { readFile } from 'node:fs/promises';
|
|
4
4
|
import { deployDiagnostic, migrationFailure, providerFailure, assetFailure } from '../modules/deploy-kit/diagnostics.mjs';
|
|
5
5
|
import { shared } from './shared.mjs';
|
|
6
|
-
import { settingKinds } from './deploy-settings.mjs';
|
|
6
|
+
import { settingKinds, switchableDeclarationHelp } from './deploy-settings.mjs';
|
|
7
7
|
import { contained } from './project.mjs';
|
|
8
8
|
import { missing, invalid, refuse, RerError } from './errors.mjs';
|
|
9
9
|
import { localOnlyBinding } from '../modules/deploy-kit/owner.mjs';
|
|
@@ -155,7 +155,7 @@ function secretChangeInputs(declaration, options, env, again) {
|
|
|
155
155
|
const declared = Array.isArray(declaration.secrets) ? declaration.secrets : [], flag = options.setSecret ? '--set-secret' : '--unset-secret';
|
|
156
156
|
const named = (options.setSecret ?? options.unsetSecret).split(',');
|
|
157
157
|
const undeclared = named.filter(name => !declared.some(item => item?.binding === name));
|
|
158
|
-
if (undeclared.length) throw invalid(`${flag} names ${undeclared.join(', ')}, which the deploy declaration does not list as ${undeclared.length > 1 ? 'secrets' : 'a secret'}${declared.length ? ` (it declares ${declared.map(item => item.binding).join(', ')})` : ''}. Nothing was changed.`);
|
|
158
|
+
if (undeclared.length) throw invalid(`${flag} names ${undeclared.join(', ')}, which the deploy declaration does not list as ${undeclared.length > 1 ? 'secrets' : 'a secret'}${declared.length ? ` (it declares ${declared.map(item => item.binding).join(', ')})` : ''}. ${switchableDeclarationHelp()} Nothing was changed.`);
|
|
159
159
|
if (!options.setSecret) return;
|
|
160
160
|
const absent = named.map(name => declared.find(item => item.binding === name).environment).filter(name => !env[name]?.trim());
|
|
161
161
|
if (absent.length) throw missing(`${flag} ${options.setSecret} needs a value for each secret; ${absent.join(', ')} ${absent.length > 1 ? 'are' : 'is'} not set. Set ${absent.length > 1 ? 'them' : 'it'} in the environment or in an --env-file file (owned, mode 0600, one line per secret), then run ${again} ${flag} ${options.setSecret} again. Nothing was changed.`);
|
package/cli/inspect.mjs
CHANGED
|
@@ -59,6 +59,7 @@ export async function describe(project) {
|
|
|
59
59
|
local: { state: project.adapter?.state, settings: project.adapter?.settings ?? [], installerState: '.seed/installer', ...await localState(project), origin: await savedOrigin(project), ...(project.adapter?.devIdentity ? { devIdentity: true, devKey: '.rer/local/dev-key.env' } : {}) },
|
|
60
60
|
// This pin serves a checkout through the machine's front door (rer door).
|
|
61
61
|
door: { protocol: doorProtocol },
|
|
62
|
+
browser: await browserDoctor(project.root, project.adapter?.browser),
|
|
62
63
|
};
|
|
63
64
|
}
|
|
64
65
|
|
|
@@ -241,7 +242,7 @@ export async function doctor(project, store, signal) {
|
|
|
241
242
|
if (directory) { usePnpm(directory); try { pnpm = await probePnpm(project.root, store, signal); pnpmIssues.length = 0; } catch (error) { if (signal?.aborted) throw error; pnpmIssues.push(store.redact(error.message)); } }
|
|
242
243
|
}
|
|
243
244
|
}
|
|
244
|
-
const browser = project.profile === 'first-party' ? await browserDoctor(project.root) : undefined;
|
|
245
|
+
const browser = project.profile === 'first-party' ? await browserDoctor(project.root, project.adapter?.browser) : undefined;
|
|
245
246
|
const aiIssues = await localAiDiagnostics(project,process.env);
|
|
246
247
|
const dependencies=project.profile==='first-party'?await dependencyDoctor(project.root):[];
|
|
247
248
|
const expectedNode = await projectNodePin(project.root);
|
|
@@ -264,6 +265,10 @@ export async function doctor(project, store, signal) {
|
|
|
264
265
|
}
|
|
265
266
|
const setupNeeded = firstParty ? !(await localState(project)).prepared : false;
|
|
266
267
|
const warnings = project.profile === 'first-party' ? await cacheWarnings(project.root) : [];
|
|
268
|
+
if (firstParty) {
|
|
269
|
+
const variables = await deployVariableClause(project.root, project.adapter);
|
|
270
|
+
if (!variables.ok) warnings.push(`Deployment declaration: ${variables.message}`);
|
|
271
|
+
}
|
|
267
272
|
return { dependencies, warnings, browser, operations: diagnostic, ok: browser?.ok !== false && !aiIssues.length && dependencies.every(d=>d.ok) && diagnostic.ok && stateValid && !inputs.length && (project.profile !== 'first-party' || (Boolean(expectedPnpm) && process.versions.node === expectedNode && pnpm === expectedPnpm)),
|
|
268
273
|
node: { actual: process.versions.node, expected: expectedNode },
|
|
269
274
|
pnpm: project.profile === 'first-party' ? { actual: pnpm, expected: expectedPnpm ?? null, ...(pnpmIssues.length ? { issue: [...new Set(pnpmIssues)].join('\n') } : {}) } : undefined,
|
package/cli/lifecycle.mjs
CHANGED
|
@@ -113,7 +113,7 @@ async function runLifecycle(project, options, out, deployRedaction) {
|
|
|
113
113
|
if (options.verb === 'verify') {
|
|
114
114
|
const target = adapter.verify;
|
|
115
115
|
if (!Array.isArray(target)) throw refuse('A complete internal verification target is missing.');
|
|
116
|
-
await ensureChromium(project.root, store, signal);
|
|
116
|
+
await ensureChromium(project.root, store, signal, project.adapter?.browser);
|
|
117
117
|
await store.run('Verifying application', target[0], target[1], { cwd: project.root, signal, env: { ...process.env, RER_LOCAL_OPERATION: operation.token } });
|
|
118
118
|
await store.step('Serving the production build as rer deploy hosts it');
|
|
119
119
|
const declaration = adapter.deployDeclaration ?? adapter.deploy?.declaration;
|
package/cli/parse.mjs
CHANGED
|
@@ -91,7 +91,17 @@ export function parse(argv, cwd = process.cwd(), { independent = false, deferTai
|
|
|
91
91
|
if (options.profile !== undefined && options.profile !== 'first-party') throw invalid('The supported explicit profile is first-party.');
|
|
92
92
|
if (options.environment !== undefined && !/^[a-z][a-z0-9-]{0,39}$/.test(options.environment)) throw invalid('Provide a valid deployment environment name.');
|
|
93
93
|
for (const key of ['setSecret', 'unsetSecret']) if (options[key] !== undefined) {
|
|
94
|
-
const
|
|
94
|
+
const entries = options[key].split(',');
|
|
95
|
+
const assignments = key === 'setSecret' ? entries.filter(entry => entry.includes('=')) : [];
|
|
96
|
+
if (assignments.length) {
|
|
97
|
+
options.setSecretValues = {};
|
|
98
|
+
for (const entry of assignments) {
|
|
99
|
+
const at = entry.indexOf('='), name = entry.slice(0, at), value = entry.slice(at + 1);
|
|
100
|
+
if (!value.trim() || value.length > 1024 || /[\u0000-\u001f\u007f]/.test(value) || Object.hasOwn(options.setSecretValues, name)) throw invalid('--set-secret NAME=VALUE requires one nonempty public setting value per binding.');
|
|
101
|
+
options.setSecretValues[name] = value;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
const names = [...new Set(entries.map(entry => key === 'setSecret' ? entry.split('=', 1)[0] : entry))];
|
|
95
105
|
if (names.length > 16 || !names.every(name => /^[A-Z][A-Z0-9_]{0,63}$/.test(name))) throw invalid(`--${key === 'setSecret' ? '' : 'un'}set-secret names declared secret bindings, repeated or separated by commas, such as SESSION_SECRET or MAIL_API_KEY,MAIL_FROM.`);
|
|
96
106
|
options[key] = names.join(',');
|
|
97
107
|
}
|
package/global/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,36 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.121
|
|
4
|
+
|
|
5
|
+
Signed: Run Edit Run fleet, 2026-11-16.
|
|
6
|
+
|
|
7
|
+
### Browser prerequisites by declared use
|
|
8
|
+
|
|
9
|
+
- `rer doctor` and `rer describe` inspect the checkout's Playwright registry without downloading or launching a browser. Missing executables include their purpose and a browser-only install command using that checkout's resolved CLI.
|
|
10
|
+
- Headless verification provisions only `chromium-headless-shell` when the Playwright pin supplies it, otherwise Chromium. An adapter declaring `browser: { headless: false }` also requires full Chromium; `rer run` honors `--headed` and `--debug` in Playwright scripts and forwarded arguments. `rer install` installs dependencies without browsers; verification and declared Playwright runs acquire the required browser on first use. The installed launcher also provisions missing browsers for older checkout pins.
|
|
11
|
+
|
|
12
|
+
### Switchable public deployment settings
|
|
13
|
+
|
|
14
|
+
- Seeds can opt a public selector such as `MAIL_PROVIDER` into in-place changes by declaring it in `publicSettings`, giving it a public default in `vars`, and retaining an optional secret transport with its environment mapping. Wrangler defaults must agree. `rer check` accepts this combination and reports conflicting defaults; `rer doctor` explains a refused overlap. Managed specs retain the selector as public, outside secret names.
|
|
15
|
+
- `rer deploy --set-secret NAME=VALUE` accepts assignments only for opted-in public settings. Name-only inputs still use the declared environment mapping; credentials come from the environment or an owned 0600 `--env-file` and remain masked. Unsetting the selector restores its declared public default in the grouped Worker version, and a plain deploy preserves a held override. Existing ownership, grouped-version and recovery handling remains in use.
|
|
16
|
+
|
|
17
|
+
These changes require seed adoption and the explicit deployment declaration where applicable. This preparation establishes no provider delivery, deployment, seed adoption or production result. The source diff changes no portability, import-kit, product migrations or archive format identity.
|
|
18
|
+
|
|
19
|
+
## 0.2.120
|
|
20
|
+
|
|
21
|
+
### Commands under an approved Business grant
|
|
22
|
+
|
|
23
|
+
- `rer business run --grant G -- <command> [args...]` exchanges this computer's pairing and explicit grant for a short-lived scoped Cloudflare child credential. It removes inherited Cloudflare credential aliases, passes arguments without a shell and preserves the child's exit code or Unix terminating signal. Existing `run [--once]` check-ins remain available.
|
|
24
|
+
- The wrapper masks the credential and common encoded forms in output, interrupts the command at credential expiry and requests cleanup after completion or interruption. Cleanup reports revoked, expired or unconfirmed separately from the child result; `rer business cleanup LEASE [--status]` retries revocation or reads its status. This environment boundary is not a sandbox: run trusted software, and an unconfirmed cleanup can leave the credential usable until server expiry.
|
|
25
|
+
|
|
26
|
+
### Agent commands and stdio MCP
|
|
27
|
+
|
|
28
|
+
- Paired agents can call Business tools for installed apps, changes, updates, domains, imports, profiles, plans and owner sign-in actions, subject to the server's available tools and the owner's grants. `rer business tools` discovers tools and `rer business call TOOL` reaches tools without a dedicated verb. Flags accept structured JSON or file input; `--json` returns structured results.
|
|
29
|
+
- Change and update following supports bounded waits. A change request can wait for its preview and, with explicit `--publish`, request publication and wait for live. Refusals, unavailable tools and unfinished waits retain distinct outcomes and actionable guidance.
|
|
30
|
+
- `rer business mcp` forwards newline-delimited JSON-RPC over stdio to the Business MCP. The paired client refreshes its short-lived bearer near expiry and once after a 401; protocol output stays on stdout and diagnostics on stderr.
|
|
31
|
+
|
|
32
|
+
These CLI changes require the matching Business server, pairing, owner approvals and grants. This preparation establishes no live-provider, Managed deployment, seed adoption or production result. The actual source diff changes no portability, import-kit, product migrations or archive format identity; the browser advice change is not included.
|
|
33
|
+
|
|
3
34
|
## 0.2.119
|
|
4
35
|
|
|
5
36
|
### Large installation archive inventories
|
|
@@ -1,14 +1,18 @@
|
|
|
1
1
|
// An older checkout pin still runs its own verbs. The installed launcher
|
|
2
2
|
// supplies the browser prerequisite those pins did not yet provision.
|
|
3
|
-
import { browserDoctor, ensureChromium } from '../cli/browser-runtime.mjs';
|
|
3
|
+
import { browserDoctor, browsersPresent, ensureChromium } from '../cli/browser-runtime.mjs';
|
|
4
|
+
import { resolveProject } from '../cli/project.mjs';
|
|
4
5
|
import { output } from '../cli/output.mjs';
|
|
5
6
|
import { RerError } from '../cli/errors.mjs';
|
|
6
7
|
import { shared } from '../cli/shared.mjs';
|
|
7
8
|
|
|
8
9
|
export async function browserPreflight(root, argv) {
|
|
9
10
|
const verb = argv[0], out = output({ verb, json: argv.includes('--json') });
|
|
11
|
+
let use;
|
|
12
|
+
try { use = (await resolveProject(root)).adapter?.browser; } catch { /* The checkout's command reports invalid declarations. */ }
|
|
13
|
+
if (argv.includes('--headed') || argv.includes('--debug')) use = { ...use, headless: false };
|
|
10
14
|
if (verb === 'doctor') {
|
|
11
|
-
const browser = await browserDoctor(root);
|
|
15
|
+
const browser = await browserDoctor(root, use);
|
|
12
16
|
if (browser.ok) return;
|
|
13
17
|
const diagnostics = { browser, ok: false, scope: 'browser-prerequisite' };
|
|
14
18
|
if (!argv.includes('--json')) out.human(JSON.stringify(diagnostics, null, 2));
|
|
@@ -16,7 +20,7 @@ export async function browserPreflight(root, argv) {
|
|
|
16
20
|
return 3;
|
|
17
21
|
}
|
|
18
22
|
// Installed browsers need no download, and no log.
|
|
19
|
-
if (
|
|
23
|
+
if (await browsersPresent(root, use)) return;
|
|
20
24
|
const cancellation = new AbortController();
|
|
21
25
|
const state = { logs: [], step: 'Checking the checkout’s Playwright browsers' };
|
|
22
26
|
let store, termination;
|
|
@@ -30,7 +34,7 @@ export async function browserPreflight(root, argv) {
|
|
|
30
34
|
store.setCommandSignal(cancellation.signal);
|
|
31
35
|
// A fresh vendored pin installs its own dependencies; verify will acquire
|
|
32
36
|
// their browser on first need. Package pins have already been bootstrapped.
|
|
33
|
-
await ensureChromium(root, store, cancellation.signal, { required: verb === 'verify' });
|
|
37
|
+
await ensureChromium(root, store, cancellation.signal, { ...use, required: verb === 'verify' });
|
|
34
38
|
} catch (error) {
|
|
35
39
|
const failure = termination ? new RerError('cancelled', `Stopped by ${termination} after owned children were stopped.`, termination === 'SIGINT' ? 130 : 143) : await browserStepError(error, store, state, root);
|
|
36
40
|
out.error(failure); out.result(false, failure.exitCode);
|
|
@@ -47,5 +51,5 @@ async function browserStepError(error, store, state, root) {
|
|
|
47
51
|
const { checkoutPath, stepDiagnostic, stepFailureText } = await shared('step-failure.mjs');
|
|
48
52
|
const step = approvedFailure(error)?.step ?? stepDiagnostic({ name: state.step, output: state.logs, log: store ? store.redact(checkoutPath(root, store.logPath)) : null });
|
|
49
53
|
const cause = error instanceof RerError ? `\n${error.message}` : /^[A-Z][A-Z0-9_]{1,63}$/.test(error?.code ?? '') ? `\nCause: ${error.code}` : '';
|
|
50
|
-
return new RerError(error instanceof RerError ? error.code : 'browser_install_failed', `${stepFailureText(step)}${cause}\
|
|
54
|
+
return new RerError(error instanceof RerError ? error.code : 'browser_install_failed', `${stepFailureText(step)}${cause}\nRetry the browser-only install command shown above.`, error instanceof RerError ? error.exitCode : 1, { step });
|
|
51
55
|
}
|
package/global/run.mjs
CHANGED
|
@@ -66,7 +66,7 @@ export async function runScript(args) {
|
|
|
66
66
|
await projectNode(target.root, process.env);
|
|
67
67
|
} catch (error) { if (!(error instanceof RerError)) throw error; process.stderr.write(error.message + '\n'); return error.exitCode; }
|
|
68
68
|
if (args[0] && /\bplaywright\b/.test(scripts[args[0]] ?? '')) {
|
|
69
|
-
const code = await (await import('./browser-runtime.mjs')).browserPreflight(target.root, ['run']);
|
|
69
|
+
const code = await (await import('./browser-runtime.mjs')).browserPreflight(target.root, ['run', ...(scripts[args[0]].match(/--(?:headed|debug)\b/g) ?? []), ...args.slice(1)]);
|
|
70
70
|
if (code !== undefined) return code;
|
|
71
71
|
}
|
|
72
72
|
const { toolCommand } = await shared('tool-command.mjs');
|
|
@@ -135,6 +135,7 @@ change adds no retries and does not increase any timeout.
|
|
|
135
135
|
- **Inputs.** Declared secrets come from the environment, then `--env-file FILE` (an owned 0600 file of `KEY=VALUE` lines), which wins. For a secret the Worker does not hold yet, rer supplies the setup manifest's owner email (`emailField`) from the local setup's private settings, and for each secret field the manifest generates (`generate`) the value rer keeps for this environment in `.rer/deploy/<environment>.secrets.env` (0600, ignored by Git), else a fresh random value, which rer keeps once the Worker holds it (the one-time setup token is always fresh and never kept); a value the Worker already holds is kept. The build runs with the checkout's local settings files moved aside, and a `dist/` holding a `.dev.vars*`, `.env*` or `*.env` file is refused by name before any provider request. A still-missing secret stops the run before any write with a message that names it, unless its declaration says `"optional": true`: then the deploy binds nothing for it and reports it as not set, and `--set-secret` adds it later.
|
|
136
136
|
- **Hosted owner.** After deploy and health pass, rer claims the setup owner on the hosted app: it POSTs the setup token to the seed's standard owner step (`hooks.owner`, by default `/auth/bootstrap`). 303 means claimed; `409 already_initialized` means an owner was already claimed and is kept. Then rer deletes the token secret from the Worker, records the new Worker version in the state file, and lists the token in `retiredSecrets`, so later plans no longer declare it. The build fingerprint still names it, and the recorded claim stays as recorded, so an untouched repeat deploy writes nothing. A Worker that still holds a token rer did not upload in this run (an older deploy) first gets a fresh token through the same recorded secret change. Dependency approvals that need the token run before the claim. A seed with an owner step function, an identity-provider claim, or no declared token secret claims its owner its own way.
|
|
137
137
|
- **Several secrets at once.** `rer deploy --set-secret MAIL_API_KEY --set-secret MAIL_FROM` or `rer deploy --set-secret MAIL_API_KEY,MAIL_FROM` (likewise `--unset-secret A,B`) changes all of them in one new Worker version or none: a group of secrets is never half set. Every named secret must be declared and, for `--set-secret`, have its value in the environment or `--env-file`; otherwise rer names each missing one and changes nothing. One secret uses Cloudflare's secret call. Several are one copy of the live version through the Versions API (its own modules, assets and compatibility settings, every other binding inherited), then deployed at 100%: Cloudflare's per-secret calls each make a version, and its settings call can add secrets but not remove them (measured 17 October 2026). The copy carries a marker rer records first, so a copy whose answer was lost is recognised, and one uploaded but not deployed is deployed by the same command run again.
|
|
138
|
+
- **Public setting transport.** A name explicitly listed in `publicSettings`, with a string default in `vars` and an optional `secrets` entry, uses that entry only as override transport. Its public default is bound when the override is absent; `--unset-secret` restores it through the existing version-copy path, even for one setting. The matching Wrangler default remains public for managed-spec generation. Credential bindings, credential aliases and credential-shaped defaults cannot opt in. See [the declaration and commands](../../cli/README.md).
|
|
138
139
|
- **Secret changes.** `rer deploy --set-secret NAME` (value from the environment or `--env-file`, under the declaration's environment name), `--unset-secret NAME` and `--rotate-secret NAME[,NAME]` (a fresh value for a secret rer generates, kept in `.rer/deploy/<environment>.secrets.env` once set) change declared secrets of the recorded Worker without a build. Before writing, rer records the starting version and the exact live names of all other secrets, never their values. Accepted or ambiguous writes retain that intent until readback confirms the change; explicit refusals clear it. An ambiguous failure, or a later command's preflight, can clear an unapplied intent only when the live deployment still matches the receipt and the newest listed version matches it too. A surviving intent blocks further mutations until consistency returns; retry the same command then. Recovery requires the recorded immediate successor (or the recorded confirming rotation's successor), the receipt's script etag and fingerprint, the intended binding's presence, and an unchanged set of other secret names. Ambiguous rotations require a confirming PUT before reporting success. Older intents without names may recover only from the exact starting version's historical bindings, with its id, etag and fingerprint verified; unavailable or malformed historical bindings refuse adoption. Each historical binding must have an exact provider type supported by this kit; unrecognized types cannot prove that a name was not a secret. Added, removed or renamed other secrets refuse deploy and removal before writes. Values remain opaque: these checks cannot distinguish an otherwise identical outside change to the pending binding.
|
|
139
140
|
- **Installation key custody.** The setup manifest generates `INSTALLATION_KEY` independently of `SESSION_SECRET`. Hosted deployment keeps it in the same private, Git-ignored `.rer/deploy/<environment>.secrets.env`, before its first upload; `INSTALLATION_KEY_PREVIOUS` is optional and never generated by setup. `rer deploy --rotate-secret INSTALLATION_KEY` first saves a new/current and old/previous pair there, publishes both bindings in one Worker version, then reseals every dependency-key row through the recorded D1 database and verifies that every row opens with the current key. Only then does it remove the previous Worker binding. Routine rotation uses only the current/previous pair; older retired keys require explicit reopen. By default, every retired key remains in the same private file as `SESSION_SECRET`, in `INSTALLATION_KEY_RETIRED=<kid>:<value>[,<kid>:<value>...]`; retired keys never enter routine Worker bindings or archives. Resealing uses the [D1 transactional batch API](https://developers.cloudflare.com/api/resources/d1/subresources/database/methods/query/). Worker receipt and D1 identity checks precede database access. Any failure retains both saved values; rerun the same rotation command to resume with that exact pair. A D1 backup or Time Travel restore older than a rotation needs the corresponding retired key: `rer deploy --reopen-installation-key KID` publishes current plus only that retired key as previous, reseals and verifies every row through the same recorded D1, then removes the previous binding while retaining all retired custody. CLI-side reopen rekey uses every validated retired key in private custody to open mixed mid-rotation snapshots; only the selected pair is published to the Worker. Before opening rows, rekey reports the D1 `key_ids` tail and custody availability for every history ID. A whole pre-rotation restore with an unavailable tail reports `installation_key_unavailable`; a known row ID without its key reports `installation_key_version_unknown` only after the tail custody check succeeds. Failures retain the reopen marker and exact pair; repeat that command to finish. Missing retired custody refuses with `installation_key_unavailable` before provider writes: recover the private file before reopening. Back up private custody securely for as long as older database recovery points exist. Retain each retired key until no D1 Time Travel recovery point or exported backup predates the completed rotation that retired it or otherwise needs that key. After any rotation or reopen has finished, edit `.rer/deploy/<environment>.secrets.env` and remove only its `<kid>:<value>` entry from `INSTALLATION_KEY_RETIRED`, keeping valid comma separators; remove the assignment if no entries remain. Preserve the current key, all other entries and the file's owned 0600 permissions. There is no per-key removal command; reopening a removed ID refuses before provider writes unless its custody is restored. Base before #367 cannot open sealed keys; roll forward to sealing-capable code. The CLI has neither a Base-version capability receipt nor a code rollback operation, so out-of-band provider rollbacks cannot be checked here; current Base rejects sealed envelopes passed to plaintext signing with `installation_key_sealed_rollback`. Other deployment changes wait for completion. Manual installation-key set/unset, a conflicting supplied current key and a supplied previous key are refused. Without the current private key, restore custody from the deploying checkout before rotating. Neither keys nor database ciphertext appear in output.
|
|
140
141
|
- **Removal.** `rer deploy --remove --yes` deletes what the state file says rer created for this environment: the Worker (schedules first; its Durable Objects go with it) and each D1, R2, KV and queue that is still the one rer created, after checking all of them before the first delete. A replaced or uncertain resource refuses the whole removal, except a D1 or KV whose create answer was lost: under this environment's derived name it is deleted once confirmed empty (a D1 with no tables, a KV namespace with no keys); one holding data is refused as `uncertain-resource-not-empty`, and an uncertain queue, whose backlog rer cannot read, as `uncertain-resource-unverifiable` (delete it by hand if it is the empty one from the interrupted run).
|
|
@@ -18,6 +18,7 @@ import { ownerRekey } from './owner-rekey.mjs';
|
|
|
18
18
|
import { refuseLocalModels } from './local-only.mjs';
|
|
19
19
|
import { validateMigrations } from './migrations.mjs';
|
|
20
20
|
import { publicOrigin } from './public-origin.mjs';
|
|
21
|
+
import { switchableDefaults } from '../../cli/deploy-settings.mjs';
|
|
21
22
|
|
|
22
23
|
export const cronNotice = 'This Worker has a Cron Trigger. Cloudflare may take up to about two hours to start its first scheduled run on some accounts.';
|
|
23
24
|
const usage = 'usage: owner-cli.mjs deploy|dry-run|local-plan|health|remove|inspect|record-owner|signin|rekey|settle --declaration <file> --environment <name> [--product <dir>] [--state <file>] [--outcome claimed|kept] | secret ... --set NAME [--set NAME]|--unset NAME [--unset NAME]';
|
|
@@ -59,11 +60,12 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
|
|
|
59
60
|
assert(typeof declaration?.project === 'string','missing-owner-project');
|
|
60
61
|
// Validate even direct kit invocations before any provider request or write.
|
|
61
62
|
publicOrigin(declaration, env);
|
|
63
|
+
const publicDefaults = await switchableDefaults(declaration);
|
|
62
64
|
let artifact;
|
|
63
65
|
if (command === 'dry-run' || command === 'local-plan') {
|
|
64
66
|
artifact = await packageBuild({root,source:{sha:'0'.repeat(40),tree:'0'.repeat(40)},runIdentity:{id:'0',attempt:'1'},productDirectory:values.product});
|
|
65
67
|
const worker = ownerWorkerName(declaration.project,values.environment);
|
|
66
|
-
const plan = ownerPlan({project:declaration.project,environment:values.environment,worker,origin:`https://${worker}.example.invalid`},declaration,artifact,{localOnlyKeys,env});
|
|
68
|
+
const plan = ownerPlan({project:declaration.project,environment:values.environment,worker,origin:`https://${worker}.example.invalid`},declaration,artifact,{localOnlyKeys,env,publicDefaults});
|
|
67
69
|
if (command === 'local-plan') for (const item of plan.d1) validateMigrations(item.migrations);
|
|
68
70
|
// Print names only: configuration values and migration SQL stay local.
|
|
69
71
|
// Return before constructing a provider client or resolving an account.
|
|
@@ -112,7 +114,7 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
|
|
|
112
114
|
const named = [...new Set(values.set ?? values.unset)], declared = Array.isArray(declaration.secrets) ? declaration.secrets : [];
|
|
113
115
|
const undeclared = named.filter(binding => !declared.some(entry => entry?.binding === binding));
|
|
114
116
|
if (undeclared.length) { const error = new Error('undeclared-secret'); error.resource = undeclared.map(binding => `secret:${binding}`).join(', '); throw error; }
|
|
115
|
-
const changes = named.map(binding => ({binding, value:values.set === undefined ? undefined : env[declared.find(entry => entry?.binding === binding).environment]}));
|
|
117
|
+
const changes = named.map(binding => ({binding, value:values.set === undefined ? undefined : env[declared.find(entry => entry?.binding === binding).environment], ...(values.unset !== undefined && Object.hasOwn(publicDefaults,binding) ? {publicDefault:publicDefaults[binding]} : {})}));
|
|
116
118
|
return {ok:true,...await ownerSecret({api,target,statePath,changes,fetch,healthOptions,settle}).catch(error => { throw api.annotateFailure(error,'secrets'); })};
|
|
117
119
|
}
|
|
118
120
|
// A secret rer retired (the spent setup token) is no longer part of the plan.
|
|
@@ -145,7 +147,7 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
|
|
|
145
147
|
}
|
|
146
148
|
const current = retiredSecrets.length && Array.isArray(declaration.secrets) ? {...declaration,secrets:declaration.secrets.filter(item => !retiredSecrets.includes(item?.binding))} : declaration;
|
|
147
149
|
artifact ??= await ownerArtifact(root,values.product);
|
|
148
|
-
const plan = ownerPlan(target,current,artifact,{localOnlyKeys,env});
|
|
150
|
+
const plan = ownerPlan(target,current,artifact,{localOnlyKeys,env,publicDefaults});
|
|
149
151
|
if (command === 'dry-run') {
|
|
150
152
|
const checked = withScopeHints(api);
|
|
151
153
|
const exists = await workerSettings(checked,target.worker) !== null;
|
|
@@ -162,7 +164,7 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
|
|
|
162
164
|
// Dispatch is the provider's: on some accounts a new Cron starts only at the account scheduler's next refresh.
|
|
163
165
|
if (plan.crons.length) notice(cronNotice);
|
|
164
166
|
// The fingerprint names every declared secret, retired ones too: an untouched repeat after the claim is a no-op.
|
|
165
|
-
const declaredSecrets = current === declaration ? plan.secrets : ownerPlan(target,declaration,artifact,{localOnlyKeys,env}).secrets;
|
|
167
|
+
const declaredSecrets = current === declaration ? plan.secrets : ownerPlan(target,declaration,artifact,{localOnlyKeys,env,publicDefaults}).secrets;
|
|
166
168
|
const window = readinessWindow({...(healthOptions?.now ? {clock:healthOptions.now} : {}), ...(healthOptions?.sleep ? {sleep:healthOptions.sleep} : {}), ...healthOptions?.readiness});
|
|
167
169
|
requestWindow = window;
|
|
168
170
|
const {receipt,created,sentSecrets,unsetSecrets,freshUpload} = await ownerDeploy({api,target,plan,artifact,statePath,env,fetch,healthOptions,readiness:{...healthOptions?.readiness,window},settle,declaredSecrets}).catch(error => {
|
|
@@ -17,7 +17,8 @@ export async function uploadSecretCopy(api, worker, live, {changes, marker}) {
|
|
|
17
17
|
const named = new Set(changes.map(change => change.binding));
|
|
18
18
|
const metadata = {main_module:entry, compatibility_date:runtime.compatibility_date, compatibility_flags:runtime.compatibility_flags ?? [],
|
|
19
19
|
bindings:[...bindings.filter(row => !named.has(row.name)).map(row => ({type:'inherit',name:row.name})),
|
|
20
|
-
...changes.
|
|
20
|
+
...changes.flatMap(change => change.value !== undefined ? [{type:'secret_text',name:change.binding,text:change.value}]
|
|
21
|
+
: change.publicDefault !== undefined ? [{type:'plain_text',name:change.binding,text:change.publicDefault}] : [])],
|
|
21
22
|
keep_assets:true, annotations:{'workers/message':copyMessage(marker)}};
|
|
22
23
|
const data = new FormData();
|
|
23
24
|
data.set('metadata', new Blob([JSON.stringify(metadata)], {type:'application/json'}));
|