@runeditrun/rer 0.2.97 → 0.2.99
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 +44 -28
- package/cli/business/api.mjs +15 -9
- package/cli/business/command.mjs +31 -13
- package/cli/business/connect.mjs +134 -4
- package/cli/business/device.mjs +10 -0
- package/cli/business/questions.mjs +2 -2
- package/cli/business/state.mjs +45 -3
- package/cli/business/supervisor.mjs +46 -7
- package/cli/business/vendor-door.mjs +3 -2
- package/global/CHANGELOG.md +41 -0
- package/global/README.md +44 -28
- package/global/cli/repo-command.mjs +3 -3
- package/global/launch/capture.mjs +36 -0
- package/global/launch/dev.mjs +4 -3
- package/global/launch/failure.mjs +1 -1
- package/global/launch/render.mjs +9 -0
- package/global/launch/state.mjs +4 -2
- package/global/launch/steps.mjs +24 -45
- package/global/launch/worker.mjs +9 -6
- package/modules/owner-claim/README.md +5 -4
- package/modules/owner-claim/index.d.mts +1 -1
- package/modules/owner-claim/index.mjs +2 -1
- package/onboarding/redaction-wrapped.mjs +38 -0
- package/onboarding/redaction.mjs +8 -2
- package/package.json +1 -1
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 --
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
code
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
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.
|
|
489
|
-
|
|
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 a later release 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 --
|
|
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
|
|
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
|
package/cli/business/api.mjs
CHANGED
|
@@ -14,15 +14,16 @@ 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, { state, link } = {}) {
|
|
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
|
+
this.state = state; this.link = link;
|
|
22
23
|
}
|
|
23
24
|
}
|
|
24
25
|
|
|
25
|
-
async function refusal(response) {
|
|
26
|
+
async function refusal(response, quiet = false) {
|
|
26
27
|
let text = '';
|
|
27
28
|
try { text = (await response.text()).slice(0, 4096); } catch { /* The status alone is the reason. */ }
|
|
28
29
|
let body = null;
|
|
@@ -30,7 +31,11 @@ async function refusal(response) {
|
|
|
30
31
|
const line = value => typeof value === 'string' && value.trim() ? redact(value).replace(/\s+/g, ' ').trim().slice(0, 300) : null;
|
|
31
32
|
const reason = body && typeof body === 'object' ? line(body.error) ?? line(body.message) : /^\s*</.test(text) ? null : line(text);
|
|
32
33
|
const requestId = body && typeof body === 'object' && typeof body.requestId === 'string' && /^[A-Za-z0-9_.:-]{1,80}$/.test(body.requestId) ? body.requestId : null;
|
|
33
|
-
|
|
34
|
+
const code = typeof body?.code === 'string' && /^[a-z][a-z0-9_]{0,79}$/.test(body.code) ? body.code : null;
|
|
35
|
+
// Pairing responses can echo secrets, including the short user code. Only
|
|
36
|
+
// the bounded machine code is needed by that flow, never server prose.
|
|
37
|
+
return new ApiError(response.status, quiet ? null : reason, quiet ? null : requestId, code,
|
|
38
|
+
quiet ? {} : { state: body?.state === 'waiting_for_owner' ? body.state : undefined, link: line(body?.link) });
|
|
34
39
|
}
|
|
35
40
|
|
|
36
41
|
const network = {
|
|
@@ -62,12 +67,12 @@ export class Api {
|
|
|
62
67
|
|| !Number.isFinite(Date.parse(result.expires_at)) || Date.parse(result.expires_at) <= Date.now()) throw Error('Business server returned an invalid scoped bearer.');
|
|
63
68
|
return result;
|
|
64
69
|
}
|
|
65
|
-
async post(path, body, { token = this.credential, signal, timeout = 30_000, headers = {} } = {}) {
|
|
66
|
-
return this.request('POST', path, body, { token, signal, timeout, headers });
|
|
70
|
+
async post(path, body, { token = this.credential, signal, timeout = 30_000, headers = {}, withStatus = false, quiet = false } = {}) {
|
|
71
|
+
return this.request('POST', path, body, { token, signal, timeout, headers, withStatus, quiet });
|
|
67
72
|
}
|
|
68
73
|
async get(path) { return this.request('GET', path); }
|
|
69
74
|
async delete(path) { return this.request('DELETE', path); }
|
|
70
|
-
async request(method, path, body, { token = this.credential, signal, timeout = 30_000, headers = {} } = {}) {
|
|
75
|
+
async request(method, path, body, { token = this.credential, signal, timeout = 30_000, headers = {}, withStatus = false, quiet = false } = {}) {
|
|
71
76
|
if (!path.startsWith('/api/business/') || path.includes('..') || path.includes('?') || path.includes('#')) throw Error('Invalid Business route.');
|
|
72
77
|
let response;
|
|
73
78
|
try {
|
|
@@ -77,7 +82,7 @@ export class Api {
|
|
|
77
82
|
...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(timeout)]) : AbortSignal.timeout(timeout),
|
|
78
83
|
});
|
|
79
84
|
} catch (error) { if (signal?.aborted) throw signal.reason; throw unreachable(this.origin, error); }
|
|
80
|
-
if (!response.ok) throw await refusal(response);
|
|
85
|
+
if (!response.ok) throw await refusal(response, quiet);
|
|
81
86
|
// Successful bodies are untrusted: callers validate them and print only fields they template.
|
|
82
87
|
if (response.status === 202 && response.headers.get('content-length') === '0' || response.status === 204) return null;
|
|
83
88
|
const text = await response.text();
|
|
@@ -85,7 +90,8 @@ export class Api {
|
|
|
85
90
|
if (text.length > 2_000_000) throw Error('Business response exceeded the limit.');
|
|
86
91
|
let result;
|
|
87
92
|
try { result = JSON.parse(text); } catch { throw Error('Business server returned an invalid response.'); }
|
|
88
|
-
|
|
93
|
+
const value = result && Object.hasOwn(result, 'data') ? result.data : result;
|
|
94
|
+
return withStatus ? { status: response.status, body: value } : value;
|
|
89
95
|
}
|
|
90
96
|
}
|
|
91
97
|
|
package/cli/business/command.mjs
CHANGED
|
@@ -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
|
|
20
|
-
|
|
21
|
-
|
|
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,22 @@ In an agent sandbox that writes only inside its working folder, use RER_BUSINESS
|
|
|
46
47
|
`;
|
|
47
48
|
|
|
48
49
|
const verbHelp = {
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
50
|
+
run: `Usage: rer business run [--once]
|
|
51
|
+
Work this computer's tasks and check in every 25 seconds until stopped.
|
|
52
|
+
When Business needs the owner's catch-up approval or export details,
|
|
53
|
+
print the owner step and keep waiting between check-ins. --once returns then.
|
|
54
|
+
Exits 0 completed, idle or waiting for the owner; 1 failed; 2 usage.
|
|
55
|
+
`,
|
|
56
|
+
connect: `Usage: rer business connect --business ID [--origin URL] [--timeout SECONDS]
|
|
57
|
+
Pair this computer with a Business. Prints a code and a link: the owner opens the
|
|
58
|
+
link in a signed-in browser, checks the code and approves. Waits for that (up to
|
|
59
|
+
the code's 10 minutes), then keeps the credential in OS credential storage.
|
|
60
|
+
--business ID The Business to join; the Connect prompt names it.
|
|
61
|
+
--origin URL Business platform address (default: https://app.runeditrun.com).
|
|
62
|
+
--timeout SECONDS Wait at most this long, then exit 75 with the pairing kept;
|
|
63
|
+
run the same command again to keep waiting (same code).
|
|
64
|
+
--code CODE Older Business pages: redeem a code made in the browser.
|
|
65
|
+
Exits 0 connected, 1 ended (refused, expired or failed), 2 usage, 75 still waiting.
|
|
58
66
|
`,
|
|
59
67
|
token: `Usage: rer business token
|
|
60
68
|
Print an MCP Authorization header object for this computer's paired Business.
|
|
@@ -74,10 +82,20 @@ export async function businessCommand(argv) {
|
|
|
74
82
|
const options = {};
|
|
75
83
|
for (let index = 0; index < args.length; index += 2) {
|
|
76
84
|
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();
|
|
85
|
+
if (!['--code', '--origin', '--business', '--timeout'].includes(name) || !args[index + 1] || args[index + 1].startsWith('--') || Object.hasOwn(options, name.slice(2))) return invalid();
|
|
78
86
|
options[name.slice(2)] = args[index + 1];
|
|
79
87
|
}
|
|
80
88
|
if (options.code !== undefined && !/^[A-Za-z0-9]{4}-?[A-Za-z0-9]{4}$/.test(options.code)) return invalid();
|
|
89
|
+
if (options.code !== undefined && (options.business !== undefined || options.timeout !== undefined)) return invalid();
|
|
90
|
+
if (options.timeout !== undefined) {
|
|
91
|
+
if (!/^\d{1,3}$/.test(options.timeout) || Number(options.timeout) > 900) return invalid();
|
|
92
|
+
options.timeout = Number(options.timeout);
|
|
93
|
+
}
|
|
94
|
+
try {
|
|
95
|
+
if (options.business !== undefined) identifier(options.business);
|
|
96
|
+
if (options.origin !== undefined && options.business !== undefined) originUrl(options.origin);
|
|
97
|
+
} catch { return invalid(); }
|
|
98
|
+
if (options.origin !== undefined && options.code === undefined && options.business === undefined) originUrl(options.origin);
|
|
81
99
|
await connect(options);
|
|
82
100
|
} else if (verb === 'vendor-key' && args.length === 2) await vendorKey(...args);
|
|
83
101
|
else if (verb === 'answer' && [3, 4].includes(args.length)) await answer(...args);
|
package/cli/business/connect.mjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { homedir } from 'node:os';
|
|
2
2
|
import { join } from 'node:path';
|
|
3
3
|
import { Api, originUrl, identifier, pause } from './api.mjs';
|
|
4
|
-
import { loadState, saveState, credentialHandle, deviceCredentialHandle, loadPending, savePending, clearPending, checkStateWritable } from './state.mjs';
|
|
4
|
+
import { loadState, saveState, credentialHandle, deviceCredentialHandle, loadPending, savePending, clearPending, checkStateWritable, lockPairing } from './state.mjs';
|
|
5
5
|
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,19 @@ 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(
|
|
26
|
+
export async function connect(options = {}) {
|
|
27
|
+
if (options.business !== undefined) return connectDevice(options);
|
|
28
|
+
const pending = await loadPending();
|
|
29
|
+
// Approval can outlive the original code deadline. A legacy command must
|
|
30
|
+
// not discard a device pairing that is still within its collection window.
|
|
31
|
+
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.');
|
|
32
|
+
if (pending?.flow === 'device' && options.code === undefined) return connectDevice(options);
|
|
33
|
+
return connectLegacy(options);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Removal of the browser-created --code flow is planned for a later release,
|
|
37
|
+
// once the production rollback target uses device pairing.
|
|
38
|
+
async function connectLegacy({ code, origin } = {}) {
|
|
27
39
|
const stored = await loadState();
|
|
28
40
|
let pending = await loadPending();
|
|
29
41
|
origin = originUrl(origin ?? stored?.origin ?? pending?.origin);
|
|
@@ -37,7 +49,7 @@ export async function connect({ code, origin } = {}) {
|
|
|
37
49
|
}
|
|
38
50
|
if (pending && Date.parse(pending.expires_at) <= Date.now()) { await clearPending(); pending = null; }
|
|
39
51
|
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:
|
|
52
|
+
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
53
|
// Refuse before redeeming the one-use code or collecting an approval when this
|
|
42
54
|
// session cannot keep the pairing or store the device credential.
|
|
43
55
|
await checkStateWritable();
|
|
@@ -114,6 +126,124 @@ export async function connect({ code, origin } = {}) {
|
|
|
114
126
|
}
|
|
115
127
|
}
|
|
116
128
|
|
|
129
|
+
const shortCode = /^[2-9A-HJKMNP-Z]{4}-[2-9A-HJKMNP-Z]{4}$/;
|
|
130
|
+
const intervalValid = value => Number.isInteger(value) && value >= 1 && value <= 60;
|
|
131
|
+
const secretValid = (value, prefix) => typeof value === 'string' && value.startsWith(prefix) && /^[A-Za-z0-9_-]+$/.test(value) && value.length > prefix.length && value.length <= 512;
|
|
132
|
+
const timestampValid = value => typeof value === 'string' && Number.isFinite(Date.parse(value));
|
|
133
|
+
const pairingRoute = '/api/business/executors/device-pairings';
|
|
134
|
+
const terminalPairing = new Map([
|
|
135
|
+
['pairing_denied', [410, 'refused in the browser']],
|
|
136
|
+
['pairing_expired', [410, 'expired']],
|
|
137
|
+
['pairing_used', [410, 'already used']],
|
|
138
|
+
['pairing_unknown', [401, 'unknown']],
|
|
139
|
+
['business_paused', [409, 'paused because the Business is paused']],
|
|
140
|
+
]);
|
|
141
|
+
|
|
142
|
+
function validateDevicePairing(value, origin, businessId) {
|
|
143
|
+
const uri = `${origin}/business/${encodeURIComponent(businessId)}/pair`;
|
|
144
|
+
if (!value || !secretValid(value.device_code, 'bz_pairing_') || typeof value.user_code !== 'string' || !shortCode.test(value.user_code)
|
|
145
|
+
|| value.verification_uri !== uri || value.business_id !== businessId
|
|
146
|
+
|| value.verification_uri_complete !== undefined && value.verification_uri_complete !== `${uri}#${value.user_code}`
|
|
147
|
+
|| !intervalValid(value.interval) || !timestampValid(value.expires_at)) throw Error('Business server returned an invalid device pairing response.');
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
async function connectDevice({ business, origin, timeout } = {}) {
|
|
151
|
+
const stop = new AbortController();
|
|
152
|
+
const interrupt = () => stop.abort('SIGINT'), terminate = () => stop.abort('SIGTERM');
|
|
153
|
+
process.on('SIGINT', interrupt); process.on('SIGTERM', terminate);
|
|
154
|
+
let pending, resume, timer, unlock;
|
|
155
|
+
try {
|
|
156
|
+
await checkStateWritable({ codeExists: false });
|
|
157
|
+
unlock = await lockPairing(stop.signal);
|
|
158
|
+
const stored = await loadState();
|
|
159
|
+
pending = await loadPending();
|
|
160
|
+
origin = originUrl(origin ?? stored?.origin ?? pending?.origin);
|
|
161
|
+
business = identifier(business ?? pending?.businessId);
|
|
162
|
+
if (stored) {
|
|
163
|
+
if (stored.revoked) throw Error(`This computer was ${revokedText(stored)}`);
|
|
164
|
+
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.`);
|
|
165
|
+
const credential = await createCredentialStore().get(deviceCredentialHandle(stored));
|
|
166
|
+
if (!credential) throw Error('This computer\'s Business credential is missing from OS credential storage. Run disconnect, then connect again.');
|
|
167
|
+
await unlock(); unlock = undefined;
|
|
168
|
+
return await connected(new Api(origin, credential), stored, { reconnecting: true });
|
|
169
|
+
}
|
|
170
|
+
if (pending && Date.parse(pending.flow === 'device' ? pending.keep_until : pending.expires_at) <= Date.now()) { await clearPending(); pending = null; }
|
|
171
|
+
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.');
|
|
172
|
+
if (pending) {
|
|
173
|
+
validateDevicePairing({ ...pending, business_id: pending.businessId }, origin, business);
|
|
174
|
+
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.');
|
|
175
|
+
}
|
|
176
|
+
// Both probes precede even the unauthenticated start. Keychain / Secret
|
|
177
|
+
// Service handling and the device credential's account are unchanged.
|
|
178
|
+
const store = createCredentialStore();
|
|
179
|
+
resume = `${rerCommand()} business connect --business ${business} --origin ${origin}${timeout === undefined ? '' : ` --timeout ${timeout}`}`;
|
|
180
|
+
try { await store.check(); }
|
|
181
|
+
catch (error) {
|
|
182
|
+
const outside = error.sandboxRefused ? ` Approve this command outside the sandbox: ${resume}. Every other business command runs inside the sandbox.` : '';
|
|
183
|
+
throw Error(`${error.message}${outside} ${pending ? 'The saved pairing was kept.' : 'Nothing was sent; no pairing was started.'}`);
|
|
184
|
+
}
|
|
185
|
+
const api = new Api(origin);
|
|
186
|
+
if (!pending) {
|
|
187
|
+
const name = deviceName(), folder = workingFolder();
|
|
188
|
+
const response = await api.post(pairingRoute, {
|
|
189
|
+
business_id: business, os: operatingSystem(), agent_kind: agentKind(), capabilities,
|
|
190
|
+
...(name ? { device_name: name } : {}), ...(folder ? { working_folder: folder } : {}),
|
|
191
|
+
}, { signal: stop.signal, withStatus: true, quiet: true });
|
|
192
|
+
const result = response?.body;
|
|
193
|
+
validateDevicePairing(result, origin, business);
|
|
194
|
+
if (response.status !== 201 || !Number.isInteger(result.expires_in) || result.expires_in < 1 || result.expires_in > 900
|
|
195
|
+
|| 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.');
|
|
196
|
+
pending = { flow: 'device', origin, businessId: business, device_code: result.device_code, user_code: result.user_code,
|
|
197
|
+
verification_uri: result.verification_uri, interval: result.interval, expires_at: result.expires_at,
|
|
198
|
+
keep_until: new Date(Date.parse(result.expires_at) + approvalWindow).toISOString(), next_poll_at: Date.now() + result.interval * 1000 };
|
|
199
|
+
await savePending(pending);
|
|
200
|
+
}
|
|
201
|
+
await unlock(); unlock = undefined;
|
|
202
|
+
// One write puts the fixed lines first, even without a TTY. Never echo the
|
|
203
|
+
// code elsewhere in prose or errors; the fragment is not sent to a server.
|
|
204
|
+
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`);
|
|
205
|
+
if (timeout !== undefined) timer = setTimeout(() => stop.abort('timeout'), timeout * 1000);
|
|
206
|
+
while (!stop.signal.aborted) {
|
|
207
|
+
if (Date.now() >= Date.parse(pending.keep_until)) { await clearPending(); throw Error('Business pairing expired (pairing_expired). Run connect again.'); }
|
|
208
|
+
await pause(Math.max(0, (pending.next_poll_at ?? Date.now() + pending.interval * 1000) - Date.now()), stop.signal);
|
|
209
|
+
const response = await api.post(`${pairingRoute}/poll`, { device_code: pending.device_code }, { signal: stop.signal, withStatus: true, quiet: true });
|
|
210
|
+
const result = response?.body;
|
|
211
|
+
if (response?.status === 200 && result?.status === 'paired') {
|
|
212
|
+
// The one successful response is consumed even when a local write fails.
|
|
213
|
+
try {
|
|
214
|
+
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.');
|
|
215
|
+
const folder = workingFolder();
|
|
216
|
+
const state = { version: 1, credentialVersion: 2, origin, businessId: business, executorId: identifier(result.executor_id), vendorHandles: [], awakeConsent: false, ...(folder ? { workingFolder: folder } : {}) };
|
|
217
|
+
const handle = credentialHandle(origin, business);
|
|
218
|
+
await store.set(handle, result.device_credential);
|
|
219
|
+
try { await saveState(state); } catch (error) { await store.delete(handle); throw error; }
|
|
220
|
+
await clearPending();
|
|
221
|
+
process.stdout.write('Approved. Device credential stored in OS credential storage.\n');
|
|
222
|
+
return await connected(new Api(origin, result.device_credential), state);
|
|
223
|
+
} finally { await clearPending(); }
|
|
224
|
+
}
|
|
225
|
+
if (response?.status !== 202 || !['authorization_pending', 'slow_down'].includes(result?.status)
|
|
226
|
+
|| !intervalValid(result.interval) || result.interval < pending.interval || !timestampValid(result.expires_at)
|
|
227
|
+
|| result.status === 'slow_down' && result.interval < Math.min(60, pending.interval + 5)) throw Error('Business server returned an invalid device pairing status.');
|
|
228
|
+
pending = { ...pending, interval: result.interval, next_poll_at: Date.now() + result.interval * 1000 };
|
|
229
|
+
await savePending(pending);
|
|
230
|
+
}
|
|
231
|
+
} catch (error) {
|
|
232
|
+
if (!stop.signal.aborted) {
|
|
233
|
+
const ended = terminalPairing.get(error.code);
|
|
234
|
+
if (ended && error.status === ended[0]) { await clearPending(); throw Error(`Business pairing ${ended[1]} (${error.code}). Run connect again.`); }
|
|
235
|
+
throw error;
|
|
236
|
+
}
|
|
237
|
+
} finally {
|
|
238
|
+
clearTimeout(timer);
|
|
239
|
+
process.off('SIGINT', interrupt); process.off('SIGTERM', terminate);
|
|
240
|
+
await unlock?.();
|
|
241
|
+
}
|
|
242
|
+
if (!pending) throw new Stopped('Stopped before starting a Business pairing. Run connect again.', stop.signal.reason === 'SIGTERM' ? 143 : 130);
|
|
243
|
+
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);
|
|
244
|
+
throw new Stopped(`Stopped waiting for approval. The pairing is saved: run ${resume} to resume it.`, stop.signal.reason === 'SIGTERM' ? 143 : 130);
|
|
245
|
+
}
|
|
246
|
+
|
|
117
247
|
// The first device-authenticated request activates the computer and applies
|
|
118
248
|
// the owner's choices; later choices reach it through run and next.
|
|
119
249
|
async function connected(api, state, options) {
|
package/cli/business/device.mjs
CHANGED
|
@@ -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
|
|
@@ -122,7 +122,7 @@ export async function next() {
|
|
|
122
122
|
if (!item) {
|
|
123
123
|
// Nothing to answer here; say whether run has work, or what it waits for.
|
|
124
124
|
const work = tasks.find(task => Object.hasOwn(runWork, task.kind) && task.state === 'ready');
|
|
125
|
-
if (work) { process.stdout.write(`Ready for run: ${runWork[work.kind]}. Start it with: ${businessCommand('run')}\n`); return; }
|
|
125
|
+
if (work) { process.stdout.write(`Ready for run: ${runWork[work.kind]}. Start it with: ${businessCommand('run --once')}\n`); return; }
|
|
126
126
|
process.stdout.write(`${waitingFor(state)}\nNothing yet.\n`); return;
|
|
127
127
|
}
|
|
128
128
|
const id = identifier(item.task_id);
|
|
@@ -142,7 +142,7 @@ export async function next() {
|
|
|
142
142
|
+ (vendor && !keyed(vendor) ? `Vendor key: none; ${name} is read from its public page, with no key.\n`
|
|
143
143
|
: stored ? `Vendor key: the owner's read-only ${name} key is stored in this computer's OS credential storage. To replace it, ${keyStep(vendor)}\n`
|
|
144
144
|
: `Vendor key: ${keyStep(vendor)}${vendor ? '' : `\n where <vendor> is the tool this step reads: ${Object.keys(vendorNames).filter(keyed).join(' | ')}`}\n`)
|
|
145
|
-
+ `Then run: ${businessCommand('run')}\n`);
|
|
145
|
+
+ `Then run: ${businessCommand('run --once')}\n`);
|
|
146
146
|
return;
|
|
147
147
|
}
|
|
148
148
|
const { toolId, vendorId, vendors } = classification(item);
|
package/cli/business/state.mjs
CHANGED
|
@@ -3,6 +3,7 @@ import { readFileSync, unlinkSync } from 'node:fs';
|
|
|
3
3
|
import { dirname, join, resolve } from 'node:path';
|
|
4
4
|
import { homedir } from 'node:os';
|
|
5
5
|
import { createHash, randomUUID } from 'node:crypto';
|
|
6
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
6
7
|
import { localCause } from './errors.mjs';
|
|
7
8
|
|
|
8
9
|
// RER_BUSINESS_STATE_DIR names the folder itself, for agent sandboxes that may write only
|
|
@@ -61,7 +62,7 @@ async function saveJson(name, value) {
|
|
|
61
62
|
* Folders made only for the check are removed again, so a refused connect
|
|
62
63
|
* leaves nothing behind.
|
|
63
64
|
*/
|
|
64
|
-
export async function checkStateWritable() {
|
|
65
|
+
export async function checkStateWritable({ codeExists = true } = {}) {
|
|
65
66
|
const directory = stateDirectory(), probe = join(directory, `${randomUUID()}.tmp`), created = [];
|
|
66
67
|
for (let path = directory; path !== dirname(path); path = dirname(path)) {
|
|
67
68
|
try { await lstat(path); break; } catch (error) { if (error.code !== 'ENOENT') break; created.push(path); }
|
|
@@ -77,7 +78,7 @@ export async function checkStateWritable() {
|
|
|
77
78
|
const fix = chosenStateDirectory()
|
|
78
79
|
? 'Allow writes to that folder in this session, or set RER_BUSINESS_STATE_DIR to a folder this session can write'
|
|
79
80
|
: 'Allow writes to that folder, or set RER_BUSINESS_STATE_DIR to a folder this session can write (in Codex, one inside the working folder, such as RER_BUSINESS_STATE_DIR="$PWD/.rer-business")';
|
|
80
|
-
throw Error(`Business cannot save its state in ${directory}: ${localCause(error) ?? error.message}. Nothing was sent, so the pairing code still works. ${fix}, then run connect again.`);
|
|
81
|
+
throw Error(`Business cannot save its state in ${directory}: ${localCause(error) ?? error.message}. ${codeExists ? 'Nothing was sent, so the pairing code still works.' : 'Nothing was sent.'} ${fix}, then run connect again.`);
|
|
81
82
|
} finally {
|
|
82
83
|
for (const path of created) await rmdir(path).catch(() => {});
|
|
83
84
|
}
|
|
@@ -85,7 +86,7 @@ export async function checkStateWritable() {
|
|
|
85
86
|
|
|
86
87
|
// Files this CLI writes in its state folder. A folder named by RER_BUSINESS_STATE_DIR
|
|
87
88
|
// may hold other things, so only these are removed from it.
|
|
88
|
-
const owned = /^(?:(?:state|pairing|progress|permissions|service|carried)\.json|run\.lock|disconnect|service(?:-error)?\.log|discovery-[A-Za-z0-9_.:-]+\.(?:json|tmp)|export-[0-9a-f]{32}\.bundle|.*[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.tmp(?:\.check)?)$/;
|
|
89
|
+
const owned = /^(?:(?:state|pairing|progress|permissions|service|carried)\.json|(?:run|pairing)\.lock|disconnect|service(?:-error)?\.log|discovery-[A-Za-z0-9_.:-]+\.(?:json|tmp)|export-[0-9a-f]{32}\.bundle|.*[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.tmp(?:\.check)?)$/;
|
|
89
90
|
/** After a revocation whose local cleanup was refused, keep only what a later
|
|
90
91
|
* disconnect needs to finish: the state and the receipts of what remains. */
|
|
91
92
|
export async function removeWorkFiles(keep = ['state.json', 'permissions.json', 'service.json']) {
|
|
@@ -153,3 +154,44 @@ export async function lockSupervisor() {
|
|
|
153
154
|
}
|
|
154
155
|
throw Error('Could not acquire Business supervisor lock.');
|
|
155
156
|
}
|
|
157
|
+
|
|
158
|
+
/** Serialize the pending read, start and save. Contenders wait, then resume
|
|
159
|
+
* the saved pairing; the lock never covers the foreground approval wait. */
|
|
160
|
+
export async function lockPairing(signal) {
|
|
161
|
+
const directory = stateDirectory(), path = join(directory, 'pairing.lock'), created = [];
|
|
162
|
+
for (let parent = directory; parent !== dirname(parent); parent = dirname(parent)) {
|
|
163
|
+
try { await lstat(parent); break; } catch (error) { if (error.code !== 'ENOENT') break; created.push(parent); }
|
|
164
|
+
}
|
|
165
|
+
const cleanDirectories = async () => { for (const parent of created) await rmdir(parent).catch(() => {}); };
|
|
166
|
+
let file;
|
|
167
|
+
try {
|
|
168
|
+
while (true) {
|
|
169
|
+
signal?.throwIfAborted();
|
|
170
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
171
|
+
try { file = await open(path, 'wx', 0o600); }
|
|
172
|
+
catch (error) {
|
|
173
|
+
if (error.code === 'ENOENT') continue; // A failed starter removed its empty folder.
|
|
174
|
+
if (error.code !== 'EEXIST') throw error;
|
|
175
|
+
if (await liveSupervisor(path)) await delay(50, undefined, { signal });
|
|
176
|
+
else await unlink(path).catch(error => { if (error.code !== 'ENOENT') throw error; });
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
try { await file.writeFile(String(process.pid)); } finally { await file.close(); }
|
|
180
|
+
const refresh = setInterval(() => { const now = new Date(); utimes(path, now, now).catch(() => {}); }, 30_000);
|
|
181
|
+
refresh.unref();
|
|
182
|
+
const exit = () => { try { if (readFileSync(path, 'utf8') === String(process.pid)) unlinkSync(path); } catch { /* Already gone. */ } };
|
|
183
|
+
process.once('exit', exit);
|
|
184
|
+
let released = false;
|
|
185
|
+
return async () => {
|
|
186
|
+
if (released) return;
|
|
187
|
+
released = true;
|
|
188
|
+
clearInterval(refresh); process.off('exit', exit); exit();
|
|
189
|
+
await cleanDirectories();
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
} catch (error) {
|
|
193
|
+
if (file) await unlink(path).catch(() => {});
|
|
194
|
+
await cleanDirectories();
|
|
195
|
+
throw error;
|
|
196
|
+
}
|
|
197
|
+
}
|