@runeditrun/rer 0.2.97 → 0.2.98

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -460,33 +460,49 @@ or use its stored device credential.
460
460
 
461
461
  ## Business device commands
462
462
 
463
- `rer business connect --code ABCD-1234 [--origin https://app.runeditrun.com]`
464
- redeems a browser-created code, prints a six-digit confirmation number for
465
- approval in the browser that created it, and waits in the foreground until the
466
- owner approves or refuses there or the code expires (ten minutes). It exits 0
467
- only once the computer is active: the credential is stored and the server has
468
- seen the computer. A refusal or expiry exits 1 with the server's reason.
469
- Interrupting it (Ctrl-C, or an agent's tool timeout) keeps the redeemed pairing:
470
- run `rer business connect` again to resume the same pairing and number; a new
471
- server pairing is never started until the old one is refused, expired or
472
- disconnected. The waiting line names the command that works from the agent's
473
- own shell: `rer` when it is on PATH, the launcher install.sh wrote, or
474
- `npx -y @runeditrun/rer` after an npx run. Pending tokens are kept until the
475
- code's expiry plus the ten minutes the server allows after an approval, so an
476
- approval near the code's end can still be collected.
477
-
478
- State lives in `$RER_BUSINESS_STATE_DIR` when it is set, and in `~/.rer/business`
479
- otherwise. `RER_STATE_DIR` is `rer demo`'s variable and Business never reads it.
480
- Connect also sends the computer's plain name (its host name's first word group,
481
- without the login name, at most 64 characters) and the folder it runs in, so the
482
- browser can show which computer this is and prefill the scan folder.
483
- Before redeeming the code (or collecting an approval), connect proves
484
- it can write that folder and that OS credential storage accepts a write; if
485
- either fails it stops, names the folder or the cause, and the code still works.
486
- Device credentials stay in macOS Keychain or Linux Secret Service; there is no
463
+ `rer business connect --business ID [--origin https://app.runeditrun.com] [--timeout 30]`
464
+ starts a pairing on this computer and prints two fixed lines first:
465
+
466
+ ```text
467
+ Code: WDJB-MJHT
468
+ Approve at: https://app.runeditrun.com/business/ID/pair#WDJB-MJHT
469
+ ```
470
+
471
+ Take the Business ID and origin from the Business Connect page's prompt. Show
472
+ the owner both lines exactly as printed. The owner opens the link signed in as
473
+ an owner of that Business, checks the code against this computer and approves
474
+ there. No code or confirmation number needs to come back through chat. The
475
+ code travels in the link's fragment, so it is not sent in a request URL.
476
+
477
+ Connect never prompts or requires a TTY. It checks state-folder writes and OS
478
+ credential storage before starting, then polls at the server's interval,
479
+ including any increased interval after `slow_down`. Without `--timeout`, it
480
+ waits until the pairing ends. `--timeout` accepts an integer from 0 to 900;
481
+ when the wait ends first, exit 75 means still waiting. Run the same command
482
+ again: it prints the same code and link and resumes the saved pairing.
483
+ Ctrl-C and SIGTERM also keep it, exiting 130 and 143. Exit 0 means the credential
484
+ was stored and the server has seen the connected computer; exit 1 means refusal,
485
+ expiry, an already-used pairing or another failure, and exit 2 means bad usage.
486
+ Network failures keep the pairing for retry. Terminal server refusals remove it.
487
+ Pairings are kept through the original deadline plus the ten-minute collection
488
+ window, so an approval near the code's end can still be collected.
489
+
490
+ State lives in `$RER_BUSINESS_STATE_DIR` when set, otherwise `~/.rer/business`.
491
+ `RER_STATE_DIR` belongs to `rer demo` and Business never reads it. The short-lived
492
+ device code and displayed code are kept only in private `pairing.json` (0600),
493
+ removed when pairing ends. Device credentials remain in macOS Keychain or Linux
494
+ Secret Service under the existing per-origin, per-Business account; there is no
487
495
  plaintext credential store. Linux needs `secret-tool` and an unlocked desktop
488
- Secret Service session. Every failure names its cause: the server's reason, the
489
- local system cause, or what to change.
496
+ Secret Service session. Connect refuses a state folder already connected to a
497
+ different origin or Business: disconnect first or use a separate
498
+ `RER_BUSINESS_STATE_DIR`. It reports this computer's plain name, working folder,
499
+ agent and OS (including WSL) for the owner to recognise.
500
+
501
+ For older Business pages, `rer business connect --code ABCD-1234 --origin URL`
502
+ keeps the browser-created code and six-digit confirmation-number flow unchanged
503
+ in 0.2.98. It cannot be combined with `--business` or `--timeout`. Removal is
504
+ planned for 0.2.99 after the production rollback target uses device pairing.
505
+ The install.sh form still passes either connect command through unchanged.
490
506
 
491
507
  The owner chooses three things on the computer's row in the browser: "Add rules
492
508
  so Claude Code never reads your secret files" (Claude Code user Read deny
@@ -508,12 +524,12 @@ pairing state are stored, so a storage failure cannot activate the computer.
508
524
  A service installed with `RER_BUSINESS_STATE_DIR` set keeps that folder. Background
509
525
  services use absolute Node and CLI paths. No model process is started.
510
526
 
511
- An agent can run `npx -y @runeditrun/rer business connect --code ABCD-1234 --origin URL`
527
+ An agent can run `npx -y @runeditrun/rer business connect --business ID --origin URL --timeout 30`
512
528
  directly, without a global installation. In Codex's workspace-write sandbox,
513
529
  allow network access, set `RER_BUSINESS_STATE_DIR="$PWD/.rer-business"` so state stays
514
530
  inside the working folder, and put npm's cache there too with
515
531
  `npm_config_cache="$PWD/.rer/npm"`. macOS refuses Keychain writes from inside
516
- that sandbox, so connect stops before redeeming and asks for this one command to
532
+ that sandbox, so connect stops before starting and asks for this one command to
517
533
  run outside the sandbox (in Codex, approve running that command outside the
518
534
  sandbox when it asks); later commands
519
535
  only read the credential and run inside the sandbox. Do not install a
@@ -14,15 +14,15 @@ export function originUrl(value = 'https://app.runeditrun.com') {
14
14
  // The server's own reason travels with its status: platform errors answer
15
15
  // {error, requestId}. It is shown as one bounded line of text, never as markup.
16
16
  export class ApiError extends Error {
17
- constructor(status, reason = null, requestId = null) {
17
+ constructor(status, reason = null, requestId = null, code = null) {
18
18
  const said = reason ? ` The server said: ${reason}${/[.!?]$/.test(reason) ? '' : '.'}` : '';
19
19
  const reference = requestId ? ` Reference ${requestId}.` : '';
20
20
  super((status === 401 ? 'Business pairing was revoked or expired. Reconnect in your browser.' : `Business server refused the request (HTTP ${status}).`) + said + reference);
21
- this.status = status; this.reason = reason; this.requestId = requestId;
21
+ this.status = status; this.reason = reason; this.requestId = requestId; this.code = code;
22
22
  }
23
23
  }
24
24
 
25
- async function refusal(response) {
25
+ async function refusal(response, quiet = false) {
26
26
  let text = '';
27
27
  try { text = (await response.text()).slice(0, 4096); } catch { /* The status alone is the reason. */ }
28
28
  let body = null;
@@ -30,7 +30,10 @@ async function refusal(response) {
30
30
  const line = value => typeof value === 'string' && value.trim() ? redact(value).replace(/\s+/g, ' ').trim().slice(0, 300) : null;
31
31
  const reason = body && typeof body === 'object' ? line(body.error) ?? line(body.message) : /^\s*</.test(text) ? null : line(text);
32
32
  const requestId = body && typeof body === 'object' && typeof body.requestId === 'string' && /^[A-Za-z0-9_.:-]{1,80}$/.test(body.requestId) ? body.requestId : null;
33
- return new ApiError(response.status, reason, requestId);
33
+ const code = typeof body?.code === 'string' && /^[a-z][a-z0-9_]{0,79}$/.test(body.code) ? body.code : null;
34
+ // Pairing responses can echo secrets, including the short user code. Only
35
+ // the bounded machine code is needed by that flow, never server prose.
36
+ return new ApiError(response.status, quiet ? null : reason, quiet ? null : requestId, code);
34
37
  }
35
38
 
36
39
  const network = {
@@ -62,12 +65,12 @@ export class Api {
62
65
  || !Number.isFinite(Date.parse(result.expires_at)) || Date.parse(result.expires_at) <= Date.now()) throw Error('Business server returned an invalid scoped bearer.');
63
66
  return result;
64
67
  }
65
- async post(path, body, { token = this.credential, signal, timeout = 30_000, headers = {} } = {}) {
66
- return this.request('POST', path, body, { token, signal, timeout, headers });
68
+ async post(path, body, { token = this.credential, signal, timeout = 30_000, headers = {}, withStatus = false, quiet = false } = {}) {
69
+ return this.request('POST', path, body, { token, signal, timeout, headers, withStatus, quiet });
67
70
  }
68
71
  async get(path) { return this.request('GET', path); }
69
72
  async delete(path) { return this.request('DELETE', path); }
70
- async request(method, path, body, { token = this.credential, signal, timeout = 30_000, headers = {} } = {}) {
73
+ async request(method, path, body, { token = this.credential, signal, timeout = 30_000, headers = {}, withStatus = false, quiet = false } = {}) {
71
74
  if (!path.startsWith('/api/business/') || path.includes('..') || path.includes('?') || path.includes('#')) throw Error('Invalid Business route.');
72
75
  let response;
73
76
  try {
@@ -77,7 +80,7 @@ export class Api {
77
80
  ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(timeout)]) : AbortSignal.timeout(timeout),
78
81
  });
79
82
  } catch (error) { if (signal?.aborted) throw signal.reason; throw unreachable(this.origin, error); }
80
- if (!response.ok) throw await refusal(response);
83
+ if (!response.ok) throw await refusal(response, quiet);
81
84
  // Successful bodies are untrusted: callers validate them and print only fields they template.
82
85
  if (response.status === 202 && response.headers.get('content-length') === '0' || response.status === 204) return null;
83
86
  const text = await response.text();
@@ -85,7 +88,8 @@ export class Api {
85
88
  if (text.length > 2_000_000) throw Error('Business response exceeded the limit.');
86
89
  let result;
87
90
  try { result = JSON.parse(text); } catch { throw Error('Business server returned an invalid response.'); }
88
- return result && Object.hasOwn(result, 'data') ? result.data : result;
91
+ const value = result && Object.hasOwn(result, 'data') ? result.data : result;
92
+ return withStatus ? { status: response.status, body: value } : value;
89
93
  }
90
94
  }
91
95
 
@@ -5,6 +5,7 @@ import { vendorKey, disconnect, status } from './local-commands.mjs';
5
5
  import { next, answer, token } from './questions.mjs';
6
6
  import { run } from './supervisor.mjs';
7
7
  import { describe } from './errors.mjs';
8
+ import { identifier, originUrl } from './api.mjs';
8
9
 
9
10
  const usage = `Set up your business: rer business connect
10
11
  Business keeps your business name, logo and brand colour together for the apps
@@ -16,9 +17,9 @@ Advanced commands (Usage: rer business VERB)
16
17
  --hosting managed|assisted|self_host (default: managed)
17
18
  --wait-seconds 0..240 (default: 240); --json
18
19
  scan [DIR...] [--json] Names-only local discovery
19
- connect [--code CODE] [--origin URL]
20
- Pair this computer, waiting until the owner approves in the browser
21
- (up to the code's 10 minutes); run it again to resume
20
+ connect --business ID [--origin URL] [--timeout SECONDS]
21
+ Print a code and link for the owner to approve in a signed-in browser
22
+ Older Business pages: connect --code CODE [--origin URL]
22
23
  Connect carries the Business name into local apps
23
24
  run [--once] Work this computer's tasks: the folder scan the owner allows, then
24
25
  vendor exports into each app's import door (a preview the owner
@@ -46,15 +47,16 @@ In an agent sandbox that writes only inside its working folder, use RER_BUSINESS
46
47
  `;
47
48
 
48
49
  const verbHelp = {
49
- connect: `Usage: rer business connect [--code CODE] [--origin URL]
50
- Pair this computer with Business, waiting for the owner to approve the comparison
51
- number in their browser (up to the code's 10 minutes). Run again to resume.
52
-
53
- --code CODE Pairing code created in the Business browser.
54
- --origin URL Business platform address (default: https://app.runeditrun.com).
55
- Without a code, prints the path to create one or resumes this computer's pairing.
56
- Carries the Business name into local app files for supporting apps to read.
57
- Choose this computer's permissions and background service in the browser.
50
+ connect: `Usage: rer business connect --business ID [--origin URL] [--timeout SECONDS]
51
+ Pair this computer with a Business. Prints a code and a link: the owner opens the
52
+ link in a signed-in browser, checks the code and approves. Waits for that (up to
53
+ the code's 10 minutes), then keeps the credential in OS credential storage.
54
+ --business ID The Business to join; the Connect prompt names it.
55
+ --origin URL Business platform address (default: https://app.runeditrun.com).
56
+ --timeout SECONDS Wait at most this long, then exit 75 with the pairing kept;
57
+ run the same command again to keep waiting (same code).
58
+ --code CODE Older Business pages: redeem a code made in the browser.
59
+ Exits 0 connected, 1 ended (refused, expired or failed), 2 usage, 75 still waiting.
58
60
  `,
59
61
  token: `Usage: rer business token
60
62
  Print an MCP Authorization header object for this computer's paired Business.
@@ -74,10 +76,19 @@ export async function businessCommand(argv) {
74
76
  const options = {};
75
77
  for (let index = 0; index < args.length; index += 2) {
76
78
  const name = args[index];
77
- if (!['--code', '--origin'].includes(name) || !args[index + 1] || args[index + 1].startsWith('--') || Object.hasOwn(options, name.slice(2))) return invalid();
79
+ if (!['--code', '--origin', '--business', '--timeout'].includes(name) || !args[index + 1] || args[index + 1].startsWith('--') || Object.hasOwn(options, name.slice(2))) return invalid();
78
80
  options[name.slice(2)] = args[index + 1];
79
81
  }
80
82
  if (options.code !== undefined && !/^[A-Za-z0-9]{4}-?[A-Za-z0-9]{4}$/.test(options.code)) return invalid();
83
+ if (options.code !== undefined && (options.business !== undefined || options.timeout !== undefined)) return invalid();
84
+ if (options.timeout !== undefined) {
85
+ if (!/^\d{1,3}$/.test(options.timeout) || Number(options.timeout) > 900) return invalid();
86
+ options.timeout = Number(options.timeout);
87
+ }
88
+ try {
89
+ if (options.business !== undefined) identifier(options.business);
90
+ if (options.origin !== undefined && options.code === undefined) originUrl(options.origin);
91
+ } catch { return invalid(); }
81
92
  await connect(options);
82
93
  } else if (verb === 'vendor-key' && args.length === 2) await vendorKey(...args);
83
94
  else if (verb === 'answer' && [3, 4].includes(args.length)) await answer(...args);
@@ -6,7 +6,7 @@ import { createCredentialStore } from './keychain.mjs';
6
6
  import { applyChoices } from './choices.mjs';
7
7
  import { rerCommand, businessCommand } from './invocation.mjs';
8
8
  import { Stopped } from './errors.mjs';
9
- import { agentKind, deviceName, workingFolder } from './device.mjs';
9
+ import { agentKind, deviceName, workingFolder, operatingSystem } from './device.mjs';
10
10
  import { revokedText } from './local-commands.mjs';
11
11
 
12
12
  // Approval moves the server's pairing expiry to ten minutes after approval, and
@@ -23,7 +23,18 @@ const nothingSent = 'Nothing was sent, so the pairing code still works.';
23
23
  * approves or refuses in the browser, or the code expires. Exit 0 means the
24
24
  * computer is active: its credential is stored and the server has seen it.
25
25
  */
26
- export async function connect({ code, origin } = {}) {
26
+ export async function connect(options = {}) {
27
+ const pending = await loadPending();
28
+ // Approval can outlive the original code deadline. A legacy command must
29
+ // not discard a device pairing that is still within its collection window.
30
+ if (pending?.flow === 'device' && options.code !== undefined && Date.parse(pending.keep_until) > Date.now()) throw Error('Business is already waiting for a device pairing. Resume that command, or run business disconnect before using another code.');
31
+ if (options.business !== undefined || pending?.flow === 'device' && options.code === undefined) return connectDevice(options);
32
+ return connectLegacy(options);
33
+ }
34
+
35
+ // Compatibility with browser-created codes is retained through 0.2.98 and
36
+ // removed in 0.2.99, once the production rollback target uses device pairing.
37
+ async function connectLegacy({ code, origin } = {}) {
27
38
  const stored = await loadState();
28
39
  let pending = await loadPending();
29
40
  origin = originUrl(origin ?? stored?.origin ?? pending?.origin);
@@ -37,7 +48,7 @@ export async function connect({ code, origin } = {}) {
37
48
  }
38
49
  if (pending && Date.parse(pending.expires_at) <= Date.now()) { await clearPending(); pending = null; }
39
50
  if (pending && (pending.origin !== origin || code && pending.code !== code)) throw Error(`Business is already waiting for approval of another code${pending.origin === origin ? '' : ` at ${pending.origin}`}. Run ${rerCommand()} business connect to resume it, or ${rerCommand()} business disconnect to drop it before using another code.`);
40
- if (!pending && !code) throw Error(`Set up your business: Business shares your business name, logo and brand colour with apps that support it. Open ${origin}/business; sign up free there if you have no account. Choose what to share there. Back in this terminal, run this same command again with --code followed by the code you copied from that page.`);
51
+ if (!pending && !code) throw Error(`Set up your business: open ${origin}/business and take the prompt from the Business Connect page. It names the Business to join with --business.`);
41
52
  // Refuse before redeeming the one-use code or collecting an approval when this
42
53
  // session cannot keep the pairing or store the device credential.
43
54
  await checkStateWritable();
@@ -114,6 +125,119 @@ export async function connect({ code, origin } = {}) {
114
125
  }
115
126
  }
116
127
 
128
+ const shortCode = /^[2-9A-HJKMNP-Z]{4}-[2-9A-HJKMNP-Z]{4}$/;
129
+ const intervalValid = value => Number.isInteger(value) && value >= 1 && value <= 60;
130
+ const secretValid = (value, prefix) => typeof value === 'string' && value.startsWith(prefix) && /^[A-Za-z0-9_-]+$/.test(value) && value.length > prefix.length && value.length <= 512;
131
+ const timestampValid = value => typeof value === 'string' && Number.isFinite(Date.parse(value));
132
+ const pairingRoute = '/api/business/executors/device-pairings';
133
+ const terminalPairing = new Map([
134
+ ['pairing_denied', [410, 'refused in the browser']],
135
+ ['pairing_expired', [410, 'expired']],
136
+ ['pairing_used', [410, 'already used']],
137
+ ['pairing_unknown', [401, 'unknown']],
138
+ ['business_paused', [409, 'paused because the Business is paused']],
139
+ ]);
140
+
141
+ function validateDevicePairing(value, origin, businessId) {
142
+ const uri = `${origin}/business/${encodeURIComponent(businessId)}/pair`;
143
+ if (!value || !secretValid(value.device_code, 'bz_pairing_') || !shortCode.test(value.user_code)
144
+ || value.verification_uri !== uri || value.business_id !== businessId
145
+ || value.verification_uri_complete !== undefined && value.verification_uri_complete !== `${uri}#${value.user_code}`
146
+ || !intervalValid(value.interval) || !timestampValid(value.expires_at)) throw Error('Business server returned an invalid device pairing response.');
147
+ }
148
+
149
+ async function connectDevice({ business, origin, timeout } = {}) {
150
+ const stored = await loadState();
151
+ let pending = await loadPending();
152
+ origin = originUrl(origin ?? stored?.origin ?? pending?.origin);
153
+ business = identifier(business ?? pending?.businessId);
154
+ if (stored) {
155
+ if (stored.revoked) throw Error(`This computer was ${revokedText(stored)}`);
156
+ if (stored.origin !== origin || stored.businessId !== business) throw Error(`This state folder is connected to Business ${identifier(stored.businessId)} at ${originUrl(stored.origin)}. Run disconnect, or use another RER_BUSINESS_STATE_DIR.`);
157
+ const credential = await createCredentialStore().get(deviceCredentialHandle(stored));
158
+ if (!credential) throw Error('This computer\'s Business credential is missing from OS credential storage. Run disconnect, then connect again.');
159
+ return connected(new Api(origin, credential), stored, { reconnecting: true });
160
+ }
161
+ if (pending && Date.parse(pending.flow === 'device' ? pending.keep_until : pending.expires_at) <= Date.now()) { await clearPending(); pending = null; }
162
+ if (pending && (pending.flow !== 'device' || pending.origin !== origin || pending.businessId !== business)) throw Error('Business is already waiting for another pairing. Resume that command, or run business disconnect before joining another Business.');
163
+ if (pending) {
164
+ validateDevicePairing({ ...pending, business_id: pending.businessId }, origin, business);
165
+ if (!timestampValid(pending.keep_until) || Date.parse(pending.keep_until) > Date.parse(pending.expires_at) + approvalWindow) throw Error('The saved Business pairing is invalid. Run business disconnect, then connect again.');
166
+ }
167
+ // Both probes precede even the unauthenticated start. Keychain / Secret
168
+ // Service handling and the device credential's account are unchanged.
169
+ await checkStateWritable();
170
+ const store = createCredentialStore();
171
+ const resume = `${rerCommand()} business connect --business ${business} --origin ${origin}${timeout === undefined ? '' : ` --timeout ${timeout}`}`;
172
+ try { await store.check(); }
173
+ catch (error) {
174
+ const outside = error.sandboxRefused ? ` Approve this command outside the sandbox: ${resume}. Every other business command runs inside the sandbox.` : '';
175
+ throw Error(`${error.message}${outside} ${pending ? 'The saved pairing was kept.' : 'Nothing was sent; no pairing was started.'}`);
176
+ }
177
+ const stop = new AbortController();
178
+ const interrupt = () => stop.abort('SIGINT'), terminate = () => stop.abort('SIGTERM');
179
+ process.on('SIGINT', interrupt); process.on('SIGTERM', terminate);
180
+ let timer;
181
+ try {
182
+ const api = new Api(origin);
183
+ if (!pending) {
184
+ const name = deviceName(), folder = workingFolder();
185
+ const response = await api.post(pairingRoute, {
186
+ business_id: business, os: operatingSystem(), agent_kind: agentKind(), capabilities,
187
+ ...(name ? { device_name: name } : {}), ...(folder ? { working_folder: folder } : {}),
188
+ }, { signal: stop.signal, withStatus: true, quiet: true });
189
+ const result = response?.body;
190
+ validateDevicePairing(result, origin, business);
191
+ if (response.status !== 201 || !Number.isInteger(result.expires_in) || result.expires_in < 1 || result.expires_in > 900
192
+ || Date.parse(result.expires_at) <= Date.now() || Date.parse(result.expires_at) > Date.now() + 900_000) throw Error('Business server returned an invalid device pairing lifetime.');
193
+ pending = { flow: 'device', origin, businessId: business, device_code: result.device_code, user_code: result.user_code,
194
+ verification_uri: result.verification_uri, interval: result.interval, expires_at: result.expires_at,
195
+ keep_until: new Date(Date.parse(result.expires_at) + approvalWindow).toISOString(), next_poll_at: Date.now() + result.interval * 1000 };
196
+ await savePending(pending);
197
+ }
198
+ // One write puts the fixed lines first, even without a TTY. Never echo the
199
+ // code elsewhere in prose or errors; the fragment is not sent to a server.
200
+ process.stdout.write(`Code: ${pending.user_code}\nApprove at: ${pending.verification_uri}#${pending.user_code}\nOpen the link signed in as an owner, check the code, then approve.\nWaiting until ${clock(pending.expires_at)}. Keep this command running.\nRun this same command again to keep waiting (same code).\n`);
201
+ if (timeout !== undefined) timer = setTimeout(() => stop.abort('timeout'), timeout * 1000);
202
+ while (!stop.signal.aborted) {
203
+ if (Date.now() >= Date.parse(pending.keep_until)) { await clearPending(); throw Error('Business pairing expired (pairing_expired). Run connect again.'); }
204
+ await pause(Math.max(0, (pending.next_poll_at ?? Date.now() + pending.interval * 1000) - Date.now()), stop.signal);
205
+ const response = await api.post(`${pairingRoute}/poll`, { device_code: pending.device_code }, { signal: stop.signal, withStatus: true, quiet: true });
206
+ const result = response?.body;
207
+ if (response?.status === 200 && result?.status === 'paired') {
208
+ // The one successful response is consumed even when a local write fails.
209
+ try {
210
+ if (!secretValid(result.device_credential, 'bz_device_') || result.business_id !== business || !timestampValid(result.idle_expires_at)) throw Error('Business server returned an invalid device credential.');
211
+ const folder = workingFolder();
212
+ const state = { version: 1, credentialVersion: 2, origin, businessId: business, executorId: identifier(result.executor_id), vendorHandles: [], awakeConsent: false, ...(folder ? { workingFolder: folder } : {}) };
213
+ const handle = credentialHandle(origin, business);
214
+ await store.set(handle, result.device_credential);
215
+ try { await saveState(state); } catch (error) { await store.delete(handle); throw error; }
216
+ await clearPending();
217
+ process.stdout.write('Approved. Device credential stored in OS credential storage.\n');
218
+ return await connected(new Api(origin, result.device_credential), state);
219
+ } finally { await clearPending(); }
220
+ }
221
+ if (response?.status !== 202 || !['authorization_pending', 'slow_down'].includes(result?.status)
222
+ || !intervalValid(result.interval) || result.interval < pending.interval || !timestampValid(result.expires_at)
223
+ || result.status === 'slow_down' && result.interval < Math.min(60, pending.interval + 5)) throw Error('Business server returned an invalid device pairing status.');
224
+ pending = { ...pending, interval: result.interval, next_poll_at: Date.now() + result.interval * 1000 };
225
+ await savePending(pending);
226
+ }
227
+ } catch (error) {
228
+ if (!stop.signal.aborted) {
229
+ const ended = terminalPairing.get(error.code);
230
+ if (ended && error.status === ended[0]) { await clearPending(); throw Error(`Business pairing ${ended[1]} (${error.code}). Run connect again.`); }
231
+ throw error;
232
+ }
233
+ } finally {
234
+ clearTimeout(timer);
235
+ process.off('SIGINT', interrupt); process.off('SIGTERM', terminate);
236
+ }
237
+ if (stop.signal.reason === 'timeout') throw new Stopped(`Still waiting for approval until ${clock(pending.expires_at)}. Run this same command again to keep waiting (same code).`, 75);
238
+ throw new Stopped(`Stopped waiting for approval. The pairing is saved: run ${resume} to resume it.`, stop.signal.reason === 'SIGTERM' ? 143 : 130);
239
+ }
240
+
117
241
  // The first device-authenticated request activates the computer and applies
118
242
  // the owner's choices; later choices reach it through run and next.
119
243
  async function connected(api, state, options) {
@@ -1,4 +1,14 @@
1
1
  import { hostname, userInfo } from 'node:os';
2
+ import { readFileSync } from 'node:fs';
3
+
4
+ export function operatingSystem() {
5
+ if (process.platform === 'darwin') return 'macos';
6
+ if (process.platform === 'win32') return 'windows';
7
+ if (process.platform !== 'linux') return 'other';
8
+ if (process.env.WSL_DISTRO_NAME) return 'wsl';
9
+ try { if (/microsoft/i.test(readFileSync('/proc/sys/kernel/osrelease', 'utf8'))) return 'wsl'; } catch { /* Ordinary Linux without procfs. */ }
10
+ return 'linux';
11
+ }
2
12
 
3
13
  /** A plain name for this computer, from its host name: the first label only,
4
14
  * words instead of dashes, the login name removed, at most 64 characters, and
@@ -1,5 +1,25 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.98
4
+
5
+ ### Connecting a computer to a Business
6
+
7
+ - `rer business connect` now pairs like a TV. Run `rer business connect --business ID [--origin URL] [--timeout SECONDS]`: the computer starts the pairing and prints two fixed lines first, `Code: WDJB-MJHT` and `Approve at: <origin>/business/ID/pair#WDJB-MJHT`. Show the owner both lines. The owner opens the link signed in as an owner of that Business, checks the code and approves there; the computer polls and receives its credential once. Nothing is pasted back into an agent chat, and the code travels in the link's fragment, so it is not sent in a request URL.
8
+ - The command never prompts and needs no terminal. It checks that it can write its state folder and that OS credential storage accepts a write before it starts. Credentials stay in macOS Keychain or Linux Secret Service as before. A state folder already connected to a different origin or Business is refused: disconnect first or use a separate `RER_BUSINESS_STATE_DIR`.
9
+ - Exit code 75 means still waiting: `--timeout` (0 to 900 seconds) ran out before the owner approved and the pairing is kept. Run the same command again: it prints the same code and link and resumes the saved pairing. Without `--timeout` it waits until the pairing ends. Exit 0 means the credential is stored and the server has seen the computer; 1 means the pairing was refused, expired, already used or failed; 2 means bad usage; Ctrl-C and SIGTERM keep the pairing and exit 130 and 143.
10
+ - `rer business connect --code CODE` (the browser-created code with a six-digit confirmation number) works unchanged in this release. It cannot be combined with `--business` or `--timeout`.
11
+
12
+ ### The private dev sign-in key in captured logs
13
+
14
+ - `rer dev` no longer writes the owner's private dev sign-in key (`rer-dev=<key>`) into rer's captured files: `server.log`, `reuse.log`, `launch.log` and the launch events. Every launch capture writer goes through the shared redaction, including keys in JSON field names and values, keys wrapped across lines and URL-encoded keys. The detached capture owner now stays alive with the server so its output stays redacted for the server's whole run. The private sign-in link is still delivered to the caller, read from `.rer/local` only at hand-off.
15
+ - `rer setup <owner/repo>` writes its `launch.log` through the same redaction, also when setup fails.
16
+ - Captured output that mixes text and JSON progress lines is written in order: JSON events are no longer glued onto a held text tail.
17
+
18
+ ### Owner claim after setup
19
+
20
+ - A seed whose hidden setup token has been retired no longer loses sign-in. Before, the owner-claim module answered 503 `invalid_configuration` for every route once the setup token was gone, so seeds that build the claim handler on every request (such as Lamp, Balm, Cabin, Lanyard and Willow) answered errors on owner sessions and all other auth routes after setup. Now owner sessions and the other auth routes keep working, and only `/auth/owner-claim` answers 409 `claim_unavailable`, for every method. Origin, email and database checks, signature checks and claim replay protection are unchanged.
21
+ - A refreshing seed refreshes to 0.2.98 to receive this; it needs no seed code edit for this part. `modules/owner-claim/README.md` now says the handler is safe to construct per request.
22
+
3
23
  ## 0.2.97
4
24
 
5
25
  ### Seed-door decision relay
package/global/README.md CHANGED
@@ -460,33 +460,49 @@ or use its stored device credential.
460
460
 
461
461
  ## Business device commands
462
462
 
463
- `rer business connect --code ABCD-1234 [--origin https://app.runeditrun.com]`
464
- redeems a browser-created code, prints a six-digit confirmation number for
465
- approval in the browser that created it, and waits in the foreground until the
466
- owner approves or refuses there or the code expires (ten minutes). It exits 0
467
- only once the computer is active: the credential is stored and the server has
468
- seen the computer. A refusal or expiry exits 1 with the server's reason.
469
- Interrupting it (Ctrl-C, or an agent's tool timeout) keeps the redeemed pairing:
470
- run `rer business connect` again to resume the same pairing and number; a new
471
- server pairing is never started until the old one is refused, expired or
472
- disconnected. The waiting line names the command that works from the agent's
473
- own shell: `rer` when it is on PATH, the launcher install.sh wrote, or
474
- `npx -y @runeditrun/rer` after an npx run. Pending tokens are kept until the
475
- code's expiry plus the ten minutes the server allows after an approval, so an
476
- approval near the code's end can still be collected.
477
-
478
- State lives in `$RER_BUSINESS_STATE_DIR` when it is set, and in `~/.rer/business`
479
- otherwise. `RER_STATE_DIR` is `rer demo`'s variable and Business never reads it.
480
- Connect also sends the computer's plain name (its host name's first word group,
481
- without the login name, at most 64 characters) and the folder it runs in, so the
482
- browser can show which computer this is and prefill the scan folder.
483
- Before redeeming the code (or collecting an approval), connect proves
484
- it can write that folder and that OS credential storage accepts a write; if
485
- either fails it stops, names the folder or the cause, and the code still works.
486
- Device credentials stay in macOS Keychain or Linux Secret Service; there is no
463
+ `rer business connect --business ID [--origin https://app.runeditrun.com] [--timeout 30]`
464
+ starts a pairing on this computer and prints two fixed lines first:
465
+
466
+ ```text
467
+ Code: WDJB-MJHT
468
+ Approve at: https://app.runeditrun.com/business/ID/pair#WDJB-MJHT
469
+ ```
470
+
471
+ Take the Business ID and origin from the Business Connect page's prompt. Show
472
+ the owner both lines exactly as printed. The owner opens the link signed in as
473
+ an owner of that Business, checks the code against this computer and approves
474
+ there. No code or confirmation number needs to come back through chat. The
475
+ code travels in the link's fragment, so it is not sent in a request URL.
476
+
477
+ Connect never prompts or requires a TTY. It checks state-folder writes and OS
478
+ credential storage before starting, then polls at the server's interval,
479
+ including any increased interval after `slow_down`. Without `--timeout`, it
480
+ waits until the pairing ends. `--timeout` accepts an integer from 0 to 900;
481
+ when the wait ends first, exit 75 means still waiting. Run the same command
482
+ again: it prints the same code and link and resumes the saved pairing.
483
+ Ctrl-C and SIGTERM also keep it, exiting 130 and 143. Exit 0 means the credential
484
+ was stored and the server has seen the connected computer; exit 1 means refusal,
485
+ expiry, an already-used pairing or another failure, and exit 2 means bad usage.
486
+ Network failures keep the pairing for retry. Terminal server refusals remove it.
487
+ Pairings are kept through the original deadline plus the ten-minute collection
488
+ window, so an approval near the code's end can still be collected.
489
+
490
+ State lives in `$RER_BUSINESS_STATE_DIR` when set, otherwise `~/.rer/business`.
491
+ `RER_STATE_DIR` belongs to `rer demo` and Business never reads it. The short-lived
492
+ device code and displayed code are kept only in private `pairing.json` (0600),
493
+ removed when pairing ends. Device credentials remain in macOS Keychain or Linux
494
+ Secret Service under the existing per-origin, per-Business account; there is no
487
495
  plaintext credential store. Linux needs `secret-tool` and an unlocked desktop
488
- Secret Service session. Every failure names its cause: the server's reason, the
489
- local system cause, or what to change.
496
+ Secret Service session. Connect refuses a state folder already connected to a
497
+ different origin or Business: disconnect first or use a separate
498
+ `RER_BUSINESS_STATE_DIR`. It reports this computer's plain name, working folder,
499
+ agent and OS (including WSL) for the owner to recognise.
500
+
501
+ For older Business pages, `rer business connect --code ABCD-1234 --origin URL`
502
+ keeps the browser-created code and six-digit confirmation-number flow unchanged
503
+ in 0.2.98. It cannot be combined with `--business` or `--timeout`. Removal is
504
+ planned for 0.2.99 after the production rollback target uses device pairing.
505
+ The install.sh form still passes either connect command through unchanged.
490
506
 
491
507
  The owner chooses three things on the computer's row in the browser: "Add rules
492
508
  so Claude Code never reads your secret files" (Claude Code user Read deny
@@ -508,12 +524,12 @@ pairing state are stored, so a storage failure cannot activate the computer.
508
524
  A service installed with `RER_BUSINESS_STATE_DIR` set keeps that folder. Background
509
525
  services use absolute Node and CLI paths. No model process is started.
510
526
 
511
- An agent can run `npx -y @runeditrun/rer business connect --code ABCD-1234 --origin URL`
527
+ An agent can run `npx -y @runeditrun/rer business connect --business ID --origin URL --timeout 30`
512
528
  directly, without a global installation. In Codex's workspace-write sandbox,
513
529
  allow network access, set `RER_BUSINESS_STATE_DIR="$PWD/.rer-business"` so state stays
514
530
  inside the working folder, and put npm's cache there too with
515
531
  `npm_config_cache="$PWD/.rer/npm"`. macOS refuses Keychain writes from inside
516
- that sandbox, so connect stops before redeeming and asks for this one command to
532
+ that sandbox, so connect stops before starting and asks for this one command to
517
533
  run outside the sandbox (in Codex, approve running that command outside the
518
534
  sandbox when it asks); later commands
519
535
  only read the credential and run inside the sandbox. Do not install a
@@ -1,4 +1,3 @@
1
- import { createWriteStream } from 'node:fs';
2
1
  import { realpath } from 'node:fs/promises';
3
2
  import { join } from 'node:path';
4
3
  import { parse } from '../../cli/parse.mjs';
@@ -9,6 +8,7 @@ import { checkoutRepository, runCommand } from './repository.mjs';
9
8
  import { ownRoot } from '../package-info.mjs';
10
9
  import { prepare } from '../launch/prepare.mjs';
11
10
  import { launchDirectory } from '../launch/state.mjs';
11
+ import { captureFile } from '../launch/capture.mjs';
12
12
 
13
13
  export async function repoCommand(request) {
14
14
  const { verb, directory, args } = request;
@@ -22,7 +22,7 @@ export async function repoCommand(request) {
22
22
  if (verb === 'setup') {
23
23
  await (await import('../../cli/business/carry.mjs')).refreshCheckout(root);
24
24
  const state = await launchDirectory(root), children = new Set(), controller = new AbortController();
25
- const log = createWriteStream(join(state, 'launch.log'), { flags: 'a', mode: 0o600 });
25
+ const log = await captureFile(root, join(state, 'launch.log'));
26
26
  const handlers = new Map(['SIGINT', 'SIGTERM'].map(signal => [signal, () => { controller.abort(); for (const child of children) child.kill(signal); }]));
27
27
  for (const [signal, handler] of handlers) process.on(signal, handler);
28
28
  try {
@@ -31,7 +31,7 @@ export async function repoCommand(request) {
31
31
  await result.release?.();
32
32
  } finally {
33
33
  for (const [signal, handler] of handlers) process.off(signal, handler);
34
- log.end();
34
+ await log.close();
35
35
  }
36
36
  } else {
37
37
  if (verb === 'dev' && !args.includes('--json')) process.stdout.write(`Restart: ${next('dev')}\n`);
@@ -0,0 +1,36 @@
1
+ import { open } from 'node:fs/promises';
2
+ import { readDevKey } from '../../cli/dev-identity.mjs';
3
+ import { createRedaction } from '../../onboarding/redaction.mjs';
4
+
5
+ // The generated key is not in the launcher's environment. Setup may create it
6
+ // after capture begins, so register it before each queued write until it exists.
7
+ export function launchRedaction(root) {
8
+ const redaction = createRedaction({ wrappedSecrets: true });
9
+ let key;
10
+ const clean = value => typeof value === 'string' ? redaction.redact(value)
11
+ : Array.isArray(value) ? value.map(clean)
12
+ : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).map(([name, item]) => [redaction.redact(name), clean(item)])) : value;
13
+ return {
14
+ ...redaction, clean,
15
+ async refresh() { if (!key) { key = await readDevKey(root); if (key) redaction.addSecrets([key]); } },
16
+ };
17
+ }
18
+
19
+ // Both server streams and preparation output pass here before reaching disk.
20
+ // JSON is redacted by value, preserving parseable progress events.
21
+ export async function captureFile(root, path) {
22
+ const redaction = launchRedaction(root), file = await open(path, 'a', 0o600);
23
+ let queued = Promise.resolve(), writes = Promise.resolve();
24
+ const append = text => { writes = writes.then(() => file.appendFile(text)); void writes.catch(() => {}); };
25
+ const stream = redaction.stream(append);
26
+ const queue = action => { queued = queued.then(async () => { await redaction.refresh(); action(); }); void queued.catch(() => {}); };
27
+ return {
28
+ write(text) { queue(() => stream.write(text)); },
29
+ line(text) {
30
+ let event; try { event = JSON.parse(text); } catch {}
31
+ if (event && typeof event === 'object') queue(() => stream.write(JSON.stringify(redaction.clean(event)) + '\n'));
32
+ else queue(() => stream.write(text + '\n'));
33
+ },
34
+ async close() { try { await queued; stream.end(); await writes; } finally { await file.close(); } },
35
+ };
36
+ }
@@ -5,7 +5,7 @@
5
5
  // --detach and --foreground override the choice.
6
6
  import { spawn } from 'node:child_process';
7
7
  import { randomUUID } from 'node:crypto';
8
- import { createWriteStream, existsSync } from 'node:fs';
8
+ import { existsSync } from 'node:fs';
9
9
  import { open, realpath, stat } from 'node:fs/promises';
10
10
  import { join } from 'node:path';
11
11
  import { setTimeout as delay } from 'node:timers/promises';
@@ -24,6 +24,7 @@ import { shellQuote } from '../../cli/node-runtime-cache.mjs';
24
24
  import { showBudget } from '../../cli/run-transfers.mjs';
25
25
  import { stopLaunch } from './stop.mjs';
26
26
  import { launchDirectory, liveWorker } from './state.mjs';
27
+ import { captureFile } from './capture.mjs';
27
28
 
28
29
  const workerPath = fileURLToPath(new URL('./worker.mjs', import.meta.url));
29
30
 
@@ -82,13 +83,13 @@ async function foreground(target, devArgs, directory, out, doorStart) {
82
83
  const code = await follow(directory, holder.token, out, { quiet: true });
83
84
  if (code !== 0) return code;
84
85
  }
85
- const log = createWriteStream(join(directory, 'launch.log'), { flags: 'a', mode: 0o600 });
86
+ const log = await captureFile(target.root, join(directory, 'launch.log'));
86
87
  let prepared;
87
88
  // The same progress lines as a detached launch while install or setup runs.
88
89
  const heartbeat = setInterval(() => out.heartbeat(), 1000);
89
90
  try { prepared = await prepare({ root: target.root, args: devArgs, env: process.env, report: fields => out.phase(fields), directory, log: text => log.write(text + '\n'), children: new Set(), doorStart }); }
90
91
  catch (failure) { if (!(failure instanceof LaunchFailure)) throw failure; out.failure(failure); return failure.exitCode; }
91
- finally { clearInterval(heartbeat); log.end(); }
92
+ finally { clearInterval(heartbeat); await log.close(); }
92
93
  Object.assign(process.env, prepared.added);
93
94
  return delegateDev(target);
94
95
  }
@@ -12,7 +12,7 @@ export class LaunchFailure extends Error {
12
12
  export function workerFailure(error, { root, env = process.env }) {
13
13
  const redaction = createRedaction();
14
14
  redaction.addSecrets([...credentialValues(env), ...credentialValues(error?.event)]);
15
- const redact = text => redaction.redact(String(text).replace(/([#&]rer-dev=)[^&\s"'<>]+/g, '$1[REDACTED]'));
15
+ const redact = text => redaction.redact(String(text));
16
16
  const clean = value => typeof value === 'string' ? redact(value)
17
17
  : Array.isArray(value) ? value.map(clean)
18
18
  : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).map(([key, item]) => [key, clean(item)])) : value;
@@ -3,6 +3,8 @@ import { humanError } from '../../cli/human-error.mjs';
3
3
  // seconds (a `progress` event with --json), then the dispatcher's ready lines.
4
4
  import { readySummary } from '../../cli/ready-summary.mjs';
5
5
  import { launchSummary } from '../../cli/run-transfers.mjs';
6
+ import { contained } from '../../cli/project.mjs';
7
+ import { shared } from '../../cli/shared.mjs';
6
8
 
7
9
  const elapsed = ms => { const s = Math.round(ms / 1000); return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m ${s % 60}s`; };
8
10
  const quiet = 20000;
@@ -26,6 +28,13 @@ export function printer({ json, stopHint, keyless = false, root }) {
26
28
  // The dispatcher's ready event, as its own human ready lines.
27
29
  async ready(ready, { log, pid }) {
28
30
  if (keyless) { const { openUrl, ...rest } = ready; ready = rest; }
31
+ else if (root && ready.openUrl && new URLSearchParams(new URL(ready.openUrl).hash.slice(1)).get('rer-dev') === '[REDACTED]') {
32
+ // The journal never transports the credential. Only the caller's final
33
+ // handoff reads the private link the dispatcher saved inside .rer/local.
34
+ const { readPrivateFile } = await shared('private-files.mjs');
35
+ const openUrl = (await readPrivateFile(await contained(root, '.rer/local/open-url', { privateFile: true }))).trim();
36
+ ready = { ...ready, openUrl, ...(ready.ownerOpenUrl ? { ownerOpenUrl: openUrl } : {}) };
37
+ }
29
38
  if (json) { event('server', { pid, log }); process.stdout.write(JSON.stringify(ready) + '\n'); return; }
30
39
  const out = root
31
40
  ? [...readySummary(ready), ...await launchSummary(root), '', 'Details for tools and troubleshooting:', `RER_READY ${ready.url}`]
@@ -13,6 +13,7 @@ import { appendFile, link, mkdir, readFile, readdir, realpath, rm, writeFile } f
13
13
  import { join } from 'node:path';
14
14
  import { processInfo } from '../../modules/job-queue/processes.mjs';
15
15
  import { serversDirectory } from '../registry.mjs';
16
+ import { launchRedaction } from './capture.mjs';
16
17
 
17
18
  import { launchPath } from '../../cli/checkout-preparation.mjs';
18
19
  export { launchPath };
@@ -115,9 +116,10 @@ export async function releaseLaunch(directory, token) {
115
116
  if (holder?.token === token) await rm(join(directory, 'worker.json'), { force: true });
116
117
  }
117
118
 
118
- export function eventLog(directory, token) {
119
+ export function eventLog(directory, token, root = process.cwd()) {
119
120
  const path = join(directory, `events-${token}.jsonl`);
120
- return { path, write: event => appendFile(path, JSON.stringify({ at: Date.now(), ...event }) + '\n', { mode: 0o600 }) };
121
+ const redaction = launchRedaction(root);
122
+ return { path, async write(event) { await redaction.refresh(); await appendFile(path, JSON.stringify(redaction.clean({ at: Date.now(), ...event })) + '\n', { mode: 0o600 }); } };
121
123
  }
122
124
 
123
125
  // { state: 'running' | 'done' | 'failed', ... } for the last install or setup
@@ -1,11 +1,9 @@
1
1
  // Run the pinned dispatcher's public verbs as children, reading its --json
2
2
  // events: install and setup to completion, and dev until its `ready` event.
3
3
  import { spawn } from 'node:child_process';
4
- import { createReadStream } from 'node:fs';
5
- import { open, stat } from 'node:fs/promises';
6
4
  import { createInterface } from 'node:readline';
7
- import { setTimeout as delay } from 'node:timers/promises';
8
5
  import { LaunchFailure } from './failure.mjs';
6
+ import { captureFile } from './capture.mjs';
9
7
 
10
8
  function events(line) { try { const value = JSON.parse(line); return value && typeof value === 'object' ? value : undefined; } catch { return undefined; } }
11
9
 
@@ -42,54 +40,35 @@ export async function runVerb(entry, args, { root, env, note, log, children, sig
42
40
  if (code !== 0) throw failureFrom(code, error, output);
43
41
  }
44
42
 
45
- // Follow a growing log file from an offset, line by line.
46
- async function follow(path, from, onLine, stopped) {
47
- let offset = from, rest = '';
48
- while (!stopped()) {
49
- const size = (await stat(path)).size;
50
- if (size > offset) {
51
- const handle = await open(path, 'r');
52
- try {
53
- const { buffer, bytesRead } = await handle.read({ buffer: Buffer.alloc(size - offset), position: offset });
54
- offset += bytesRead; rest += buffer.subarray(0, bytesRead).toString('utf8');
55
- } finally { await handle.close(); }
56
- const parts = rest.split('\n'); rest = parts.pop();
57
- for (const line of parts) if (onLine(line)) return;
58
- }
59
- await delay(200);
60
- }
61
- }
62
-
63
- // Start `dev` detached into its own process group with its output in a private
64
- // log, and return its ready event once it prints one. The server outlives this
65
- // process and stops on rer dev --stop or its idle timeout.
43
+ // Keep the worker as the capture owner for the server's whole lifetime. Raw
44
+ // output is parsed in memory; only redacted bytes reach either captured log.
66
45
  export async function startServer(entry, args, { root, env, logPath, children, signal, note = () => {} }) {
67
46
  signal?.throwIfAborted();
68
- const handle = await open(logPath, 'a', 0o600), from = (await handle.stat()).size;
69
- let child, exit, spawnError;
70
- // Listening before anything is awaited: a spawn that fails reports it on the next tick.
71
- try {
72
- child = spawn(process.execPath, [entry, 'dev', ...args, '--json'], { cwd: root, env, detached: true, stdio: ['ignore', handle.fd, handle.fd] });
73
- child.once('error', failure => { spawnError = failure; exit ??= 1; });
74
- child.once('exit', (code, name) => { exit = code ?? (name ? 128 : 1); });
75
- } finally { await handle.close(); }
47
+ const capture = await captureFile(root, logPath);
48
+ let child;
49
+ try { child = spawn(process.execPath, [entry, 'dev', ...args, '--json'], { cwd: root, env, detached: true, stdio: ['ignore', 'pipe', 'pipe'] }); }
50
+ catch (error) { await capture.close(); throw error; }
76
51
  own(children, child, signal);
77
- let ready, error, output = '';
78
- await follow(logPath, from, line => {
52
+ let ready, error, output = '', spawnError, resolveReady;
53
+ const announced = new Promise(resolve => { resolveReady = resolve; });
54
+ const lines = createInterface({ input: child.stdout });
55
+ lines.on('line', line => {
79
56
  const event = events(line);
80
- if (event?.event === 'ready') { ready = event; return true; }
57
+ capture.line(line);
58
+ if (event?.event === 'ready') { ready = event; resolveReady(); }
81
59
  if (event?.event === 'error') error = event;
82
- // rer dev --door / --direct: where the checkout moved.
83
60
  if (event?.event === 'moved') note(`moved this checkout from ${event.from} to ${event.to}; its data is kept`);
84
61
  if (!event) output = (output + line + '\n').slice(-8192);
85
- return false;
86
- }, () => exit !== undefined);
87
- if (!ready) {
88
- // Read whatever the exiting dispatcher wrote last.
89
- for await (const line of createInterface({ input: createReadStream(logPath, { start: from }) })) { const event = events(line); if (event?.event === 'ready') ready = event; if (event?.event === 'error') error = event; }
90
- }
91
- children.delete(child);
62
+ });
63
+ child.stderr.on('data', data => { output = (output + data).slice(-8192); capture.write(data); });
64
+ child.once('error', failure => { spawnError = failure; });
65
+ const closed = new Promise((resolve, reject) => child.once('close', async (code, name) => {
66
+ children.delete(child);
67
+ try { await capture.close(); resolve(code ?? (name ? 128 : 1)); } catch (error) { reject(error); }
68
+ }));
69
+ // A write failure must also reach the worker after it has announced readiness.
70
+ void closed.catch(() => {});
71
+ const exit = await Promise.race([announced, closed]);
92
72
  if (!ready) throw failureFrom(exit, error, spawnError ? `rer could not run in ${root}: ${spawnError.code ?? spawnError.message}.` : output);
93
- child.unref();
94
- return { ready, pid: child.pid, reused: exit === 0 };
73
+ return { ready, pid: child.pid, closed };
95
74
  }
@@ -6,7 +6,6 @@
6
6
  // claimed the launch, the stop request it reads right after claiming. Either
7
7
  // way no further step starts, the running one is signalled, and the launch
8
8
  // reports that it was stopped instead of ready.
9
- import { createWriteStream } from 'node:fs';
10
9
  import { realpath } from 'node:fs/promises';
11
10
  import { join } from 'node:path';
12
11
  import { processInfo } from '../../modules/job-queue/processes.mjs';
@@ -15,9 +14,10 @@ import { LaunchFailure, workerFailure } from './failure.mjs';
15
14
  import { prepare } from './prepare.mjs';
16
15
  import { claimLaunch, eventLog, launchDirectory, liveWorker, releaseLaunch, serverRecord, stopRequest } from './state.mjs';
17
16
  import { startServer } from './steps.mjs';
17
+ import { captureFile } from './capture.mjs';
18
18
 
19
19
  const [root, token, argsJSON, requestedAtText, mode] = process.argv.slice(2), args = JSON.parse(argsJSON), requestedAt = Number(requestedAtText), doorStart = mode === 'door-start';
20
- const checkout = await realpath(root), directory = await launchDirectory(checkout), events = eventLog(directory, token);
20
+ const checkout = await realpath(root), directory = await launchDirectory(checkout), events = eventLog(directory, token, root);
21
21
  // Listening before the claim: a stop may signal this worker as soon as it is the holder.
22
22
  const children = new Set(), stopping = new AbortController();
23
23
  const stop = () => { stopping.abort(); for (const child of children) child.kill('SIGTERM'); };
@@ -27,8 +27,9 @@ if (!await claimLaunch(directory, token)) {
27
27
  const holder = await liveWorker(directory);
28
28
  await events.write({ event: 'redirect', token: holder?.token });
29
29
  } else {
30
- const logFile = createWriteStream(join(directory, 'launch.log'), { flags: 'a', mode: 0o600 });
30
+ const logFile = await captureFile(root, join(directory, 'launch.log'));
31
31
  const log = text => logFile.write(text + '\n');
32
+ let started;
32
33
  try {
33
34
  if (await stopRequest.covers(directory, requestedAt)) stop();
34
35
  stopping.signal.throwIfAborted();
@@ -37,7 +38,6 @@ if (!await claimLaunch(directory, token)) {
37
38
  // A server rer started logs to server.log; asking a running one for its
38
39
  // ready lines goes to reuse.log, and names server.log only when rer started it.
39
40
  const serverLog = join(directory, 'server.log');
40
- let started;
41
41
  try { started = await startServer(prepared.entry, args, { root, env: { ...process.env, ...prepared.added }, logPath: prepared.own ? join(directory, 'reuse.log') : serverLog, children, signal: stopping.signal, note: message => events.write({ event: 'phase', phase: 'note', message }) }); }
42
42
  finally { await prepared.release?.(); }
43
43
  const record = (await liveServers(process.env)).find(item => item.checkout === checkout);
@@ -45,7 +45,7 @@ if (!await claimLaunch(directory, token)) {
45
45
  // The server's PID, and the process rer spawned for it (the same one unless
46
46
  // the pin re-runs itself under its own Node), each with its start time.
47
47
  const identity = async id => ({ pid: id, start: (await processInfo(id))?.start });
48
- if (!prepared.own) await serverRecord.write(directory, { ...await identity(pid), spawned: await identity(started.pid) });
48
+ if (!prepared.own) await serverRecord.write(directory, { ...await identity(pid), spawned: await identity(process.pid) });
49
49
  const ours = !prepared.own || (await serverRecord.read(directory))?.pid === pid;
50
50
  // A stop that arrived while the server came up finds it registered and
51
51
  // stops it; this launch reports the stop rather than a server about to end.
@@ -57,6 +57,9 @@ if (!await claimLaunch(directory, token)) {
57
57
  await events.write({ event: 'failed', exitCode: failure.exitCode, message: failure.message, error: failure.event });
58
58
  } finally {
59
59
  await releaseLaunch(directory, token);
60
- logFile.end();
60
+ await logFile.close();
61
61
  }
62
+ // Release preparation custody at ready, but continue redacting output until
63
+ // the registered server exits. Repeated launches can prepare independently.
64
+ await started?.closed;
62
65
  }
@@ -22,9 +22,9 @@ permanently prevents another claim, including after the consumed claim expires.
22
22
  origin, canonical owner email and public signing-key ring. Claims are never a
23
23
  configuration source.
24
24
  3. Mount this handler before the operator-auth dispatcher; it owns only
25
- `/auth/owner-claim`. Continue protecting application routes with real
26
- operator-auth sessions. Never expose a server function taking authConfig or
27
- verified payload fields from browser input.
25
+ `/auth/owner-claim` and is safe to construct per request. Continue protecting
26
+ application routes with real operator-auth sessions. Never expose a server
27
+ function taking authConfig or verified payload fields from browser input.
28
28
  4. Declare the release setup manifest's owner claim step with
29
29
  `type: 'owner-claim'`, `mode: 'signed'`, `emailField` naming the public
30
30
  owner-email setup field, `path: '/auth/owner-claim'`, and `tokenField` naming
@@ -71,7 +71,8 @@ key rotation may overlap old and new kids for the five-minute window, then remov
71
71
  the old kid. Public keys are EC/P-256 JWKs, never private JWKs; missing/unknown kids
72
72
  and untrusted issuers fail. Config is snapshotted when the handler is created.
73
73
  Remove the hidden setup token after successful bootstrap as part of ordinary
74
- application secret maintenance; never delete either admission ledger.
74
+ application secret maintenance; the claim route then answers 409 `claim_unavailable`
75
+ for every method. Never delete either admission ledger.
75
76
 
76
77
  ## Wire and browser transport
77
78
 
@@ -16,7 +16,7 @@ export class OwnerClaimError extends Error { constructor(code?: string, status?:
16
16
  export function verifyOwnerClaim(token: string, config: OwnerClaimConfig & { /** Epoch seconds. */ now?: number }): Promise<Readonly<OwnerClaim>>;
17
17
  export interface OwnerClaimHandlerOptions extends OwnerClaimConfig {
18
18
  db: Database;
19
- /** Includes the server-only hidden SETUP_TOKEN and SESSION_SECRET. */
19
+ /** Includes server-only SESSION_SECRET and optional SETUP_TOKEN; after token retirement the claim route returns 409. */
20
20
  authConfig: AuthConfig;
21
21
  clientIp: (request: Request) => string | Promise<string>;
22
22
  /** Milliseconds, default Date.now. */
@@ -10,11 +10,12 @@ export { OwnerClaimError, verifyOwnerClaim } from './verify.mjs';
10
10
  export function createOwnerClaimHandler({ db, authConfig, clientIp, clock = Date.now, ...input }) {
11
11
  const config = configureClaim(input);
12
12
  const auth = configure(authConfig);
13
- if (auth.origin !== config.appOrigin || auth.OWNER_EMAIL !== config.expectedEmail || !auth.SETUP_TOKEN
13
+ if (auth.origin !== config.appOrigin || auth.OWNER_EMAIL !== config.expectedEmail
14
14
  || typeof clientIp !== 'function' || typeof clock !== 'function' || !db?.prepare || !db?.batch) throw new OwnerClaimError('invalid_configuration', 503);
15
15
  return async request => {
16
16
  const url = new URL(request.url);
17
17
  if (url.pathname !== '/auth/owner-claim') return null;
18
+ if (!auth.SETUP_TOKEN) return Response.json({ error: 'claim_unavailable' }, { status: 409, headers: securityHeaders() });
18
19
  try {
19
20
  requireOrigin(request, auth);
20
21
  // Credential URLs are never accepted, including legacy query transport.
@@ -0,0 +1,38 @@
1
+ // A terminal may wrap a registered credential inside its bytes. Retain the
2
+ // original offsets so both complete masks and streaming holds cover the wrap.
3
+ export function compactSecretText(text) {
4
+ const offsets = [], ends = [], characters = [];
5
+ for (let at = 0; at < text.length;) {
6
+ const start = at;
7
+ let character = text[at++];
8
+ // URL encoders may escape even unreserved ASCII, or encode a URL twice.
9
+ // Decode with source offsets so mixed encoded/plain key bytes also match.
10
+ if (character === '%' && /^[0-9a-f]{2}/i.test(text.slice(at, at + 2))) {
11
+ character = String.fromCharCode(parseInt(text.slice(at, at + 2), 16)); at += 2;
12
+ if (character === '%' && /^[0-9a-f]{2}/i.test(text.slice(at, at + 2))) { character = String.fromCharCode(parseInt(text.slice(at, at + 2), 16)); at += 2; }
13
+ }
14
+ if (!/\s/.test(character)) { offsets.push(start); ends.push(at); characters.push(character); }
15
+ }
16
+ const compact = characters.join('');
17
+ return {
18
+ ranges(secrets) {
19
+ const ranges = [];
20
+ for (const secret of secrets) {
21
+ if (/\s/.test(secret)) continue;
22
+ let at = 0;
23
+ while ((at = compact.indexOf(secret, at)) >= 0) { ranges.push([offsets[at], ends[at + secret.length - 1]]); at++; }
24
+ }
25
+ return ranges;
26
+ },
27
+ prefix(secrets, minimum) {
28
+ let cutoff = text.length;
29
+ for (const secret of secrets) {
30
+ if (/\s/.test(secret)) continue;
31
+ for (let at = Math.max(0, compact.length - secret.length + 1); at <= compact.length - minimum; at++) {
32
+ if (secret.startsWith(compact.slice(at))) { cutoff = Math.min(cutoff, offsets[at]); break; }
33
+ }
34
+ }
35
+ return cutoff;
36
+ },
37
+ };
38
+ }
@@ -1,5 +1,6 @@
1
1
  import { StringDecoder } from 'node:string_decoder';
2
2
  import { jwtRanges, jwtHold } from './redaction-jwt.mjs';
3
+ import { compactSecretText } from './redaction-wrapped.mjs';
3
4
 
4
5
  const MASK = '[REDACTED]';
5
6
  const PEM_BEGIN = /-----BEGIN [A-Z0-9 ]{0,64}PRIVATE KEY(?: BLOCK)?-----/g;
@@ -13,6 +14,7 @@ const CREDENTIAL_NAME = new RegExp(`(?:^|[_.-])(?:${CREDENTIAL_WORD})s?(?:$|[_.-
13
14
  // Base's maintained Node 22 runtime. These names require a real case boundary.
14
15
  const CAMEL_CREDENTIAL_NAME = /[A-Za-z0-9](?:Token|Secret|Credential|Key|Pat|Dsn|Auth|Pass|Passwd|Password|Pwd|Signature|Sig|Cookie)s?(?:$|[_.-]|[A-Z0-9])/;
15
16
  const FIELD_NAME = '(?:api[_-]?key|access[_-]?token|auth[_-]?token|token|password|secret|signature|sig|key|pat|dsn|auth|pass)';
17
+ const DEV_FIELD = '(?<![A-Za-z0-9])rer-dev';
16
18
  // A field name may follow `_` or `-` (DB_PASSWORD, client_secret, x-api-key),
17
19
  // but not a letter or digit inside an ordinary word.
18
20
  const FIELD = '(?<![A-Za-z0-9])' + FIELD_NAME;
@@ -34,6 +36,7 @@ const NOT_FLAG = '(?!(?:' + FLAG_WORDS + ')(?:[\\s"\'<>;&,)\\]}]|$))';
34
36
  const DOUBLE_QUOTED = /"(?:\\[^\r\n]|[^"\\\r\n])*(?:\\(?=[\r\n]|$))?/.source;
35
37
  const SINGLE_QUOTED = /'(?:\\[^\r\n]|[^'\\\r\n])*(?:\\(?=[\r\n]|$))?/.source;
36
38
  const PRIVATE_VALUE = `(?:${DOUBLE_QUOTED}(?:"|(?=[\\r\\n]|$))|${SINGLE_QUOTED}(?:'|(?=[\\r\\n]|$))|[^\\s"'<>;&]+)`;
39
+ const DEV_KEY_PATTERN = new RegExp(DEV_FIELD + '["\']?\\s*[=:]\\s*(' + PRIVATE_VALUE + ')', 'gi');
37
40
  const FIELD_VALUE = '["\']?\\s*[=:]\\s*' + NOT_FLAG + PRIVATE_VALUE;
38
41
  // These deploy flags take a binding name, never the secret value. Explicitly
39
42
  // registered private bytes remain redacted by the exact-value pass.
@@ -80,7 +83,7 @@ const privateAssignment = match => !AMBIGUOUS_FIELD.test(match[1]) || match[2].r
80
83
  // stream, has nothing more to arrive, so a trailing bare field name, dash run
81
84
  // or plain host:port is ordinary diagnostic text there.
82
85
  const PREFIX_TAIL = '["\']?\\s*(?:[=:]\\s*)?["\']?$';
83
- const FIELD_PREFIX = new RegExp('(?:\\b(?:Bearer|Basic)|' + FIELD + ')' + PREFIX_TAIL, 'i');
86
+ const FIELD_PREFIX = new RegExp('(?:\\b(?:Bearer|Basic)|' + FIELD + '|' + DEV_FIELD + ')' + PREFIX_TAIL, 'i');
84
87
  const CAMEL_PREFIX = new RegExp(CAMEL_CONTEXT + PREFIX_TAIL);
85
88
  const CLI_PREFIX_HOLD = new RegExp(CLI_PREFIX + FIELD_NAME + '\\s+$', 'i');
86
89
  // Keep a quoted value's opening field until its closing quote arrives, even
@@ -145,7 +148,7 @@ function controlCleaner() {
145
148
  const cleanText = text => controlCleaner().write(String(text));
146
149
 
147
150
  // Keep every value for this session, even after its credential scope is cleared.
148
- export function createRedaction({mask = MASK} = {}) {
151
+ export function createRedaction({mask = MASK, wrappedSecrets = false} = {}) {
149
152
  const secrets = new Set();
150
153
  let longest = 1;
151
154
  // Each known value is registered with the encodings and parts a tool may print
@@ -175,6 +178,7 @@ export function createRedaction({mask = MASK} = {}) {
175
178
  const ranges = text => {
176
179
  const assignments = [...text.matchAll(CAMEL_PATTERN), ...text.matchAll(CLI_PATTERN)].filter(privateAssignment);
177
180
  const found = [...text.matchAll(PATTERNS), ...assignments].map(match => [match.index, match.index + match[0].length]);
181
+ for (const match of text.matchAll(DEV_KEY_PATTERN)) found.push([match.index + match[0].length - match[1].length, match.index + match[0].length]);
178
182
  found.push(...jwtRanges(text));
179
183
  for (const begin of text.matchAll(PEM_BEGIN)) {
180
184
  const end = [...text.slice(begin.index + begin[0].length).matchAll(PEM_END)][0];
@@ -184,6 +188,7 @@ export function createRedaction({mask = MASK} = {}) {
184
188
  let from = 0, at;
185
189
  while ((at = text.indexOf(secret, from)) >= 0) { found.push([at, at + secret.length]); from = at + 1; }
186
190
  }
191
+ if (wrappedSecrets) found.push(...compactSecretText(text).ranges(secrets));
187
192
  return found.sort((a,b) => a[0]-b[0]);
188
193
  };
189
194
  const replace = text => {
@@ -200,6 +205,7 @@ export function createRedaction({mask = MASK} = {}) {
200
205
  // unterminated private-key block stays held there.
201
206
  const incompleteStart = (text, minimumPrefix=1, complete=false) => {
202
207
  let cutoff = text.length;
208
+ if (wrappedSecrets) cutoff = Math.min(cutoff, compactSecretText(text).prefix(secrets, minimumPrefix));
203
209
  for (const secret of secrets) {
204
210
  // The earliest start whose remaining text begins this secret is its longest held prefix.
205
211
  for (let at=Math.max(0,text.length-secret.length+1); at<=text.length-minimumPrefix; at++) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runeditrun/rer",
3
- "version": "0.2.97",
3
+ "version": "0.2.98",
4
4
  "description": "The rer command: install, set up, run and launch Run Edit Run checkouts.",
5
5
  "license": "MIT",
6
6
  "type": "module",