@runeditrun/rer 0.2.31 → 0.2.32

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.
Files changed (49) hide show
  1. package/README.md +94 -0
  2. package/cli/README.md +32 -0
  3. package/cli/business/api.mjs +61 -0
  4. package/cli/business/command.mjs +44 -20
  5. package/cli/business/config-policy.mjs +25 -0
  6. package/cli/business/connect.mjs +50 -0
  7. package/cli/business/discovery-task.mjs +180 -0
  8. package/cli/business/files.mjs +25 -0
  9. package/cli/business/keychain.mjs +113 -0
  10. package/cli/business/lease.mjs +68 -0
  11. package/cli/business/local-commands.mjs +82 -0
  12. package/cli/business/outbound.mjs +29 -0
  13. package/cli/business/parsers-syntax.mjs +3 -1
  14. package/cli/business/parsers.mjs +9 -3
  15. package/cli/business/permissions.mjs +143 -0
  16. package/cli/business/policy.mjs +7 -1
  17. package/cli/business/progress.mjs +18 -0
  18. package/cli/business/prompts.mjs +12 -0
  19. package/cli/business/questions.mjs +98 -0
  20. package/cli/business/repository.mjs +17 -0
  21. package/cli/business/scan-command.mjs +27 -0
  22. package/cli/business/scan.mjs +42 -35
  23. package/cli/business/service.mjs +152 -0
  24. package/cli/business/state.mjs +46 -0
  25. package/cli/business/supervisor.mjs +92 -0
  26. package/cli/business/vendors/README.md +101 -0
  27. package/cli/business/vendors/calendly.mjs +80 -0
  28. package/cli/business/vendors/common.mjs +103 -0
  29. package/cli/business/vendors/index.mjs +75 -0
  30. package/cli/business/vendors/pagerduty.mjs +70 -0
  31. package/cli/business/vendors/sentry.mjs +84 -0
  32. package/cli/business/vendors/uptimerobot.mjs +20 -0
  33. package/cli/deploy-command.mjs +3 -2
  34. package/cli/deploy-inputs.mjs +9 -0
  35. package/cli/deploy.mjs +3 -2
  36. package/global/CHANGELOG.md +13 -0
  37. package/global/README.md +94 -0
  38. package/global/cli/describe.mjs +20 -0
  39. package/global/cli/install.mjs +3 -3
  40. package/global/cli/repo-command.mjs +53 -0
  41. package/global/cli/repository-contract.mjs +7 -0
  42. package/global/cli/repository.mjs +84 -0
  43. package/global/launch/prepare.mjs +9 -6
  44. package/global/main.mjs +22 -2
  45. package/install.sh +7 -0
  46. package/modules/deploy-kit/owner-cli.mjs +5 -2
  47. package/modules/deploy-kit/owner.mjs +6 -4
  48. package/modules/deploy-kit/public-origin.mjs +17 -0
  49. package/package.json +1 -1
@@ -0,0 +1,113 @@
1
+ import { spawn } from 'node:child_process';
2
+
3
+ const service = 'com.runeditrun.business';
4
+ const unavailable = () => new Error('OS credential storage is unavailable or locked. Unlock macOS Keychain or install and unlock Linux Secret Service (secret-tool); otherwise use the wizard or Managed. No credential was written to a file.');
5
+
6
+ // All process output stays in memory. In particular, never attach a child error:
7
+ // OS tools may put credential material in their diagnostics.
8
+ function execute(command, args, input, env) {
9
+ return new Promise((resolve, reject) => {
10
+ const child = spawn(command, args, { env, stdio: ['pipe', 'pipe', 'pipe'] });
11
+ const out = [], err = []; let size = 0, failed = false;
12
+ const timer = setTimeout(() => { failed = true; child.kill('SIGKILL'); }, 30000);
13
+ const collect = list => chunk => { size += chunk.length; if (size > 262144) { failed = true; child.kill('SIGKILL'); } else list.push(chunk); };
14
+ child.stdout.on('data', collect(out)); child.stderr.on('data', collect(err));
15
+ child.stdin.on('error', () => {});
16
+ child.on('error', () => { clearTimeout(timer); reject(unavailable()); });
17
+ child.on('close', code => {
18
+ clearTimeout(timer);
19
+ if (failed || code === null) reject(unavailable());
20
+ else resolve({ code, stdout: Buffer.concat(out).toString('utf8'), stderr: Buffer.concat(err).toString('utf8') });
21
+ });
22
+ child.stdin.end(input);
23
+ });
24
+ }
25
+
26
+ function checkedHandle(handle) {
27
+ if (typeof handle !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9:._/-]{0,253}$/.test(handle)) throw new Error('Invalid credential handle.');
28
+ return handle;
29
+ }
30
+
31
+ function checkedSecret(secret) {
32
+ if (typeof secret !== 'string' || !secret.length || Buffer.byteLength(secret) > 65536 || /[\x00-\x1f\x7f]/.test(secret)) throw new Error('Enter a nonempty, single-line credential.');
33
+ return secret;
34
+ }
35
+
36
+ /** Secrets cross only stdin/stdout pipes, never arguments, files, or exceptions.
37
+ * run is a process-edge seam for tests, not a selectable storage backend.
38
+ */
39
+ export function createCredentialStore({ platform = process.platform, env = process.env, run } = {}) {
40
+ const command = run ?? ((binary, args, input) => execute(binary, args, input, env));
41
+ if (!['darwin', 'linux'].includes(platform)) throw unavailable();
42
+ const call = async (...args) => { try { return await command(...args); } catch { throw unavailable(); } };
43
+ const macArgs = handle => ['-s', service, '-a', handle];
44
+ const linuxArgs = handle => ['application', service, 'handle', handle];
45
+ async function get(handle) {
46
+ checkedHandle(handle);
47
+ const result = platform === 'darwin'
48
+ ? await call('/usr/bin/security', ['find-generic-password', ...macArgs(handle), '-w'])
49
+ : await call('secret-tool', ['lookup', ...linuxArgs(handle)]);
50
+ if (platform === 'darwin' && result.code === 44 || platform === 'linux' && result.code === 1 && !result.stderr.trim()) return null;
51
+ if (result.code !== 0) throw unavailable();
52
+ return result.stdout.replace(/\r?\n$/, '');
53
+ }
54
+ return {
55
+ get,
56
+ async set(handle, secret) {
57
+ checkedHandle(handle); checkedSecret(secret);
58
+ if (platform === 'darwin') {
59
+ // Interactive security receives the hex password on stdin. Hex also avoids
60
+ // its command tokenizer interpreting quotes/backslashes in a vendor key.
61
+ const hex = Buffer.from(secret, 'utf8').toString('hex');
62
+ const result = await call('/usr/bin/security', ['-q', '-p', ''], `add-generic-password -U -s ${service} -a ${handle} -X ${hex}\n`);
63
+ if (result.code !== 0 || result.stderr.trim()) throw unavailable();
64
+ } else {
65
+ const result = await call('secret-tool', ['store', '--label=Run Edit Run Business', ...linuxArgs(handle)], secret);
66
+ if (result.code !== 0) throw unavailable();
67
+ }
68
+ // security's interactive exit status alone does not establish command success.
69
+ if (await get(handle) !== secret) throw unavailable();
70
+ return handle;
71
+ },
72
+ async delete(handle) {
73
+ checkedHandle(handle);
74
+ if (await get(handle) === null) return;
75
+ const result = platform === 'darwin'
76
+ ? await call('/usr/bin/security', ['delete-generic-password', ...macArgs(handle)])
77
+ : await call('secret-tool', ['clear', ...linuxArgs(handle)]);
78
+ if (result.code !== 0 && !(platform === 'darwin' && result.code === 44)) throw unavailable();
79
+ },
80
+ };
81
+ }
82
+
83
+ /** Credentials require a terminal that can hide input; keys are never echoed. */
84
+ export async function readSecret({ input = process.stdin, output = process.stderr } = {}) {
85
+ if (!input.isTTY || typeof input.setRawMode !== 'function') throw new Error('A terminal with hidden input is required.');
86
+ return new Promise((resolve, reject) => {
87
+ let secret = '', done = false; const wasRaw = input.isRaw, wasFlowing = input.readableFlowing === true;
88
+ function finish(error) {
89
+ if (done) return; done = true;
90
+ input.off('data', data); input.off('end', ended); input.off('error', ended);
91
+ process.off('SIGTERM', terminated); process.off('SIGINT', interrupted);
92
+ // A fresh stdin has readableFlowing === null, but isPaused() is false.
93
+ // Stop the read we started so the terminal does not keep the command alive.
94
+ input.setRawMode(Boolean(wasRaw)); if (!wasFlowing) input.pause(); output.write('\n');
95
+ if (error) reject(error); else { try { resolve(checkedSecret(secret)); } catch (e) { reject(e); } }
96
+ }
97
+ const interrupted = () => finish(new Error('Credential entry cancelled.'));
98
+ const terminated = () => finish(new Error('Credential entry interrupted.'));
99
+ const ended = () => finish(new Error('Credential input ended before confirmation.'));
100
+ function data(chunk) {
101
+ for (const character of chunk.toString('utf8')) {
102
+ if (character === '\x03' || character === '\x04') { interrupted(); return; }
103
+ if (character === '\r' || character === '\n') { finish(); return; }
104
+ if (character === '\x7f' || character === '\b') secret = Array.from(secret).slice(0, -1).join('');
105
+ else if (!/[\x00-\x1f]/.test(character)) secret += character;
106
+ if (Buffer.byteLength(secret) > 65536) { finish(new Error('Credential input is too long.')); return; }
107
+ }
108
+ }
109
+ input.setRawMode(true); output.write('Credential (hidden): ');
110
+ input.on('data', data); input.once('end', ended); input.once('error', ended);
111
+ process.once('SIGTERM', terminated); process.once('SIGINT', interrupted); input.resume();
112
+ });
113
+ }
@@ -0,0 +1,68 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { ApiError, identifier, taskPath } from './api.mjs';
3
+ import { saveProgress } from './progress.mjs';
4
+
5
+ export class Lease {
6
+ constructor(api, claim, progress, outerSignal) {
7
+ identifier(claim.task.id); identifier(claim.grant?.id);
8
+ if (!Number.isSafeInteger(claim.fence) || claim.fence < 1 || claim.task.fence !== claim.fence
9
+ || claim.grant.task_id !== claim.task.id || claim.grant.fence !== claim.fence || claim.heartbeat_interval_seconds !== 60) throw Error('Business server returned an invalid task grant.');
10
+ this.api = api; this.claim = claim; this.progress = progress;
11
+ this.checkpoint = claim.task.checkpoint ?? {}; this.cursor = 0;
12
+ this.controller = new AbortController(); this.signal = AbortSignal.any([outerSignal, this.controller.signal]);
13
+ this.tail = Promise.resolve(); this.expires = Date.parse(claim.lease_expires_at);
14
+ if (!Number.isFinite(this.expires) || this.expires <= Date.now()) throw new ApiError(409);
15
+ this.timer = setInterval(() => { void this.heartbeat().catch(error => this.controller.abort(error)); }, 60_000);
16
+ this.deadline = setInterval(() => { if (Date.now() >= this.expires) this.controller.abort(new ApiError(409)); }, 500);
17
+ }
18
+ serial(work) {
19
+ const operation = this.tail.then(work);
20
+ this.tail = operation.catch(() => {});
21
+ return operation;
22
+ }
23
+ async token() {
24
+ if (!this.bearer || Date.now() >= this.bearerUntil - 60_000) {
25
+ const minted = await this.api.mintToken('tasks', { taskId: this.claim.task.id, signal: this.signal });
26
+ this.bearer = minted.access_token; this.bearerUntil = Date.parse(minted.expires_at);
27
+ }
28
+ return this.bearer;
29
+ }
30
+ async post(destination, body, { releasing = false } = {}) {
31
+ if (!releasing) this.signal.throwIfAborted();
32
+ const token = releasing ? this.bearer : await this.token();
33
+ if (!token) throw Error('Business task bearer is unavailable.');
34
+ return this.api.post(destination, { ...body, client_event_id: body.client_event_id ?? randomUUID(), fence: this.claim.fence, grant_id: this.claim.grant.id },
35
+ { token, ...(releasing ? { timeout: 5_000 } : { signal: this.signal }) });
36
+ }
37
+ send(destination, body) { return this.serial(() => this.post(destination, body)); }
38
+ heartbeat() {
39
+ return this.serial(async () => {
40
+ const result = await this.post(taskPath(this.claim.task.id, 'heartbeat'), { checkpoint: this.checkpoint, cursor: this.cursor });
41
+ const expires = Date.parse(result.lease_expires_at);
42
+ if (!Number.isFinite(expires) || expires <= Date.now()) throw new ApiError(409);
43
+ this.expires = expires;
44
+ this.cursor = Number.isSafeInteger(result.cursor) ? result.cursor : this.cursor;
45
+ if (result.cancel_requested || result.controls?.some(control => control.kind === 'cancel' || control.instruction === 'pause')) {
46
+ this.controller.abort(Error('Business task was paused or cancelled in the browser.'));
47
+ this.signal.throwIfAborted();
48
+ }
49
+ // Controls contain only closed enums. A requested checkpoint is already
50
+ // acknowledged by this heartbeat; no free-form instruction is executed.
51
+ return result;
52
+ });
53
+ }
54
+ async checkpointSaved(checkpoint) {
55
+ this.checkpoint = checkpoint;
56
+ this.progress.current = { kind: this.claim.task.kind, checkpoint, uploadedBytes: checkpoint.bytes_done ?? 0 };
57
+ await saveProgress(this.progress);
58
+ await this.heartbeat();
59
+ }
60
+ async complete() { clearInterval(this.timer); return this.serial(() => this.post(taskPath(this.claim.task.id, 'complete'), { outputs: {} })); }
61
+ async release(reason = 'handover') {
62
+ clearInterval(this.timer);
63
+ await this.tail;
64
+ if (!this.bearer) await this.token();
65
+ return this.post(taskPath(this.claim.task.id, 'release'), { reason, checkpoint: this.checkpoint }, { releasing: true });
66
+ }
67
+ async close() { clearInterval(this.timer); clearInterval(this.deadline); await this.tail; }
68
+ }
@@ -0,0 +1,82 @@
1
+ import { readFile, writeFile, unlink, rm, rmdir, lstat } from 'node:fs/promises';
2
+ import { dirname, join } from 'node:path';
3
+ import { loadState, saveState, stateDirectory, credentialHandle } from './state.mjs';
4
+ import { createCredentialStore, readSecret } from './keychain.mjs';
5
+ import { removeService, serviceStatus } from './service.mjs';
6
+ import { removePermissions } from './permissions.mjs';
7
+ import { pause } from './api.mjs';
8
+ import { loadProgress } from './progress.mjs';
9
+ import { VENDORS } from './vendors/index.mjs';
10
+
11
+ export async function paired() {
12
+ const state = await loadState();
13
+ if (!state?.origin || !state.businessId || !state.executorId) throw Error('This computer is not paired. Run rer business connect --code CODE.');
14
+ const credential = await createCredentialStore().get(credentialHandle(state.origin));
15
+ if (!credential) throw Error('Business device credential is missing. Reconnect in your browser.');
16
+ return { state, credential };
17
+ }
18
+
19
+ export async function vendorKey(action, vendor) {
20
+ if (!['add', 'remove'].includes(action) || !VENDORS.includes(vendor)) throw Error('Choose add or remove and a shipped vendor: sentry, uptimerobot, pagerduty, calendly.');
21
+ const { state } = await paired(), store = createCredentialStore(), handle = `vendor:${vendor}:read`;
22
+ if (action === 'add') {
23
+ let secret = await readSecret();
24
+ try { await store.set(handle, secret); } finally { secret = undefined; }
25
+ state.vendorHandles = [...new Set([...(state.vendorHandles ?? []), handle])];
26
+ } else {
27
+ await store.delete(handle);
28
+ state.vendorHandles = (state.vendorHandles ?? []).filter(item => item !== handle);
29
+ }
30
+ await saveState(state);
31
+ process.stdout.write(`${vendor}:read ${action === 'add' ? 'stored in OS keychain' : 'removed'}.\n`);
32
+ }
33
+
34
+ async function stopSupervisor(directory) {
35
+ const lock = join(directory, 'run.lock');
36
+ try { await lstat(lock); } catch (error) { if (error.code === 'ENOENT') return; throw error; }
37
+ await writeFile(join(directory, 'disconnect'), '', { mode: 0o600 });
38
+ for (let attempt = 0; attempt < 100; attempt++) {
39
+ try {
40
+ const pid = Number(await readFile(lock, 'utf8'));
41
+ if (Number.isSafeInteger(pid) && pid > 0) {
42
+ try { process.kill(pid, 0); }
43
+ catch (error) { if (error.code !== 'ESRCH') throw error; await unlink(lock); return; }
44
+ }
45
+ } catch (error) { if (error.code === 'ENOENT') return; throw error; }
46
+ await pause(100);
47
+ }
48
+ throw Error('Business supervisor is still stopping. Retry disconnect shortly.');
49
+ }
50
+
51
+ export async function disconnect() {
52
+ const state = await loadState(), directory = stateDirectory();
53
+ await removeService();
54
+ await stopSupervisor(directory);
55
+ await removePermissions();
56
+ if (state) {
57
+ const store = createCredentialStore();
58
+ for (const handle of state.vendorHandles ?? []) await store.delete(handle);
59
+ if (state.origin) await store.delete(credentialHandle(state.origin));
60
+ }
61
+ await rm(directory, { recursive: true, force: true });
62
+ // Remove only an empty parent; other rer commands may own it.
63
+ await rmdir(dirname(directory)).catch(error => { if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error.code)) throw error; });
64
+ process.stdout.write('Business disconnected. Local service, credentials and added permissions removed.\n');
65
+ }
66
+
67
+ export async function status({ json = false } = {}) {
68
+ const state = await loadState();
69
+ if (!state) {
70
+ process.stdout.write(json ? JSON.stringify({ paired: false, service: 'not_installed', current_task: null, checkpoint: null }) + '\n' : 'Business: not paired.\nService: not installed.\nTask: none.\nCheckpoint: none.\n'); return;
71
+ }
72
+ const stored = state.origin && await createCredentialStore().get(credentialHandle(state.origin));
73
+ const service = await serviceStatus();
74
+ const active = (await loadProgress()).current;
75
+ if (json) {
76
+ process.stdout.write(JSON.stringify({ paired: Boolean(stored), service: service.running ? 'running' : service.installed ? 'stopped' : 'not_installed', current_task: ['discover.local', 'export.vendor'].includes(active?.kind) ? active.kind : null, checkpoint: active?.checkpoint ? { saved: true, uploaded_bytes: Number.isSafeInteger(active.uploadedBytes) ? active.uploadedBytes : 0 } : null }) + '\n');
77
+ return;
78
+ }
79
+ process.stdout.write(`Business: ${stored ? 'paired' : 'credential missing'}.\nService: ${service.running ? 'running' : service.installed ? 'installed, stopped' : 'not installed'}.\n`);
80
+ process.stdout.write(`Task: ${['discover.local', 'export.vendor'].includes(active?.kind) ? active.kind : 'none'}.\n`);
81
+ process.stdout.write(`Checkpoint: ${active?.checkpoint ? 'saved' : 'none'}${Number.isSafeInteger(active?.uploadedBytes) ? `; ${active.uploadedBytes} bytes uploaded` : ''}.\n`);
82
+ }
@@ -0,0 +1,29 @@
1
+ import { sensitive, blockedSignal } from './detector.mjs';
2
+
3
+ export function assertOutbound(value, knownSecrets = []) {
4
+ function visit(item) {
5
+ if (typeof item === 'string') {
6
+ // Vendor records can contain ordinary line breaks. Inspect their text without
7
+ // changing the bytes that will be uploaded. All credential/entropy rules apply.
8
+ if (sensitive(item.replace(/[\r\n\t]/g, ' ')) || knownSecrets.some(secret => secret && item.includes(secret))) {
9
+ throw Error('Business outbound detector refused secret-shaped content.');
10
+ }
11
+ } else if (Array.isArray(item)) item.forEach(visit);
12
+ else if (item && typeof item === 'object') for (const [key, entry] of Object.entries(item)) { visit(key); visit(entry); }
13
+ }
14
+ visit(value);
15
+ }
16
+
17
+ export function assertChunk(bytes, knownSecrets) {
18
+ // Chunks may be fragments of a JSON document. The detector sees the complete
19
+ // UTF-8 text before any network write, including names and record values.
20
+ assertOutbound(Buffer.from(bytes).toString('utf8'), knownSecrets);
21
+ }
22
+
23
+ // Names-only signals share the scanner's field-aware path policy. A locator
24
+ // joins ordinary directory names; credential shapes still apply across its
25
+ // entire spelling, and entropy is checked within each path segment.
26
+ export function assertSignals(document) {
27
+ assertOutbound({ schema: document.schema, source: document.source, withheld: document.withheld });
28
+ if (document.signals.some(blockedSignal)) throw Error('Business outbound detector refused secret-shaped content.');
29
+ }
@@ -29,7 +29,9 @@ export function comments(source, slash = false) {
29
29
  if (quote === "'" && next === "'") { clean += next; i++; }
30
30
  else quote = '';
31
31
  }
32
- } else if (char === '"' || char === "'" || (slash && char === '`')) { quote = char; clean += char; }
32
+ } else if (char === '"' || char === "'" || (slash && char === '`')) {
33
+ quote = char; clean += char;
34
+ }
33
35
  else if (slash && char === '/' && next === '*') { block = true; clean += ' '; i++; }
34
36
  else if (char === '#' || (slash && char === '/' && next === '/')) {
35
37
  const start = i + (char === '#' ? 1 : 2);
@@ -3,6 +3,7 @@ import { configNames, tomlEntries, yamlEntries } from './parsers-config.mjs';
3
3
  import { environmentNames, packageNames } from './parsers-packages.mjs';
4
4
  import { infrastructureDocument, infrastructureNames } from './parsers-infrastructure.mjs';
5
5
  import { pulumiNames } from './parsers-pulumi.mjs';
6
+ import { configuration, configKeyLimit } from './config-policy.mjs';
6
7
 
7
8
  const examples = /(?:^|[/.\-_])(?:examples?|samples?|templates?|fixtures?)(?:[/.\-_]|$)/i;
8
9
  const manifests = /^(?:package\.json|composer\.json|requirements[^/]*\.txt|pyproject\.toml|gemfile|go\.mod|cargo\.toml)$/;
@@ -26,10 +27,14 @@ export function parseNames(relativePath, text) {
26
27
  || /(?:^|\/)(?:charts?|helm)\/templates\//i.test(pathname);
27
28
  const explicitExample = /(?:^|[/.\-_])(?:examples?|samples?|fixtures?)(?:[/.\-_]|$)/i.test(pathname);
28
29
  const manifest = manifests.test(filename), classification = examples.test(pathname) && (!helm || explicitExample) ? 'trace' : 'live-use';
29
- const result = [], seen = new Set();
30
+ const result = [], seen = new Set(), configKeys = new Set();
30
31
  const emit = evidenceClass => (kind, value) => {
31
32
  if (typeof value !== 'string' || !value || value.length > 512 || /[\r\n\0]/.test(value)) return;
32
33
  const key = `${evidenceClass}\0${kind}\0${value}`;
34
+ if (kind === 'config-key' && !configKeys.has(value)) {
35
+ if (configKeys.size >= configKeyLimit) return;
36
+ configKeys.add(value);
37
+ }
33
38
  if (!seen.has(key)) { seen.add(key); result.push({ kind, value, class: evidenceClass }); }
34
39
  };
35
40
  const parse = (source, evidenceClass, isComment) => {
@@ -38,7 +43,7 @@ export function parseNames(relativePath, text) {
38
43
  const add = emit(deployed ? 'live-use' : evidenceClass);
39
44
  if (manifest) packageNames(filename, source, entries, add);
40
45
  if (env) environmentNames(source, add);
41
- if (!manifest && !code.test(pathname)) configNames(entries, add);
46
+ if (!manifest && configuration(pathname)) configNames(entries, add);
42
47
  infrastructureNames(pathname, source, entries, ci, add);
43
48
  if (code.test(pathname)) pulumiNames(pathname, source, add);
44
49
  // Commented-out env declarations are useful traces even in config files.
@@ -49,7 +54,8 @@ export function parseNames(relativePath, text) {
49
54
  const templateClean = text.replace(/\{\{\s*\/\*([\s\S]*?)\*\/\s*\}\}/g, (whole, content) => {
50
55
  templateTraces.push(content); return whole.replace(/[^\n]/g, ' ');
51
56
  });
52
- const { clean, traces } = comments(templateClean, filename === 'go.mod' || /\.(?:jsonc?|tf|hcl|[cm]?[jt]sx?|go|cs)(?:\.(?:example|sample|template|tpl))?$/i.test(pathname));
57
+ const { clean, traces } = comments(templateClean,
58
+ filename === 'go.mod' || /\.(?:jsonc?|tf|hcl|[cm]?[jt]sx?|go|cs)(?:\.(?:example|sample|template|tpl))?$/i.test(pathname));
53
59
  parse(clean, classification, false);
54
60
  // Group consecutive comment lines so commented TOML/YAML sections retain
55
61
  // their structural context. Comments never inherit live-use classification.
@@ -0,0 +1,143 @@
1
+ import { mkdir, readFile, writeFile, unlink, rename, lstat, open, rmdir } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import { join, dirname, isAbsolute } from 'node:path';
4
+ import { createHash, randomUUID } from 'node:crypto';
5
+
6
+ export const BUSINESS_DENY_RULES = Object.freeze([
7
+ 'Read(**/secrets/**)', 'Read(**/.ssh/**)', 'Read(**/.aws/**)', 'Read(**/.gnupg/**)',
8
+ 'Read(**/.env)', 'Read(**/.env.*)', 'Read(**/*.pem)', 'Read(**/*.key)',
9
+ 'Read(**/*.p12)', 'Read(**/*.pfx)', 'Read(**/id_*)', 'Read(**/*.tfvars)',
10
+ 'Read(**/*kubeconfig*)', 'Read(**/credentials*)', 'Read(**/service-account*.json)',
11
+ 'Read(**/*.keychain*)', 'Read(**/keychains/**)', 'Read(**/Keychains/**)',
12
+ 'Read(**/Google/Chrome/**)', 'Read(**/Chromium/**)', 'Read(**/.mozilla/**)',
13
+ 'Read(**/*.1pux)', 'Read(**/*.1pif)', 'Read(**/*.kdbx)', 'Read(**/*.opvault/**)',
14
+ 'Read(**/.password-store/**)',
15
+ ]);
16
+
17
+ const hash = text => text === null ? null : createHash('sha256').update(text).digest('hex');
18
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
19
+ function paths({ home = homedir(), stateDir = join(home, '.rer', 'business') } = {}) {
20
+ if (!isAbsolute(home) || !isAbsolute(stateDir)) throw new Error('Business permission paths must be absolute.');
21
+ return { settings: join(home, '.claude', 'settings.json'), receipt: join(stateDir, 'permissions.json'), stateDir };
22
+ }
23
+ async function readOptional(path) {
24
+ try {
25
+ const info = await lstat(path);
26
+ if (!info.isFile() || info.isSymbolicLink() || info.size > 1048576) throw new Error('Claude settings or Business permission receipt is not a supported regular file.');
27
+ return await readFile(path, 'utf8');
28
+ } catch (e) { if (e.code === 'ENOENT') return null; throw e; }
29
+ }
30
+ async function atomic(path, text) {
31
+ const temporary = `${path}.${randomUUID()}.tmp`;
32
+ try { await writeFile(temporary, text, { flag: 'wx', mode: 0o600 }); await rename(temporary, path); }
33
+ finally { await unlink(temporary).catch(e => { if (e.code !== 'ENOENT') throw e; }); }
34
+ }
35
+ function parseSettings(text) {
36
+ let value;
37
+ try { value = text === null ? {} : JSON.parse(text); }
38
+ catch { throw new Error('Claude user settings are invalid JSON; no permissions were changed.'); }
39
+ if (!object(value) || value.permissions !== undefined && !object(value.permissions) || value.permissions?.deny !== undefined && (!Array.isArray(value.permissions.deny) || value.permissions.deny.some(rule => typeof rule !== 'string'))) throw new Error('Claude permissions.deny must be an array of strings; no permissions were changed.');
40
+ return value;
41
+ }
42
+ async function lock(settings, work) {
43
+ const path = `${settings}.rer-business.lock`, token = JSON.stringify({ pid: process.pid, id: randomUUID() });
44
+ let handle;
45
+ try { handle = await open(path, 'wx', 0o600); }
46
+ catch (e) {
47
+ if (e.code !== 'EEXIST') throw e;
48
+ let holder;
49
+ try { holder = JSON.parse(await readOptional(path)); } catch { throw new Error('Claude settings have a permission-change lock; check it before retrying.'); }
50
+ if (!Number.isSafeInteger(holder?.pid) || holder.pid <= 0) throw new Error('Claude settings have an invalid permission-change lock.');
51
+ try { process.kill(holder.pid, 0); } catch (error) {
52
+ if (error.code === 'ESRCH') { await unlink(path); return lock(settings, work); }
53
+ }
54
+ throw new Error('Another process is changing Claude permissions; retry when it finishes.');
55
+ }
56
+ try { await handle.writeFile(token); await handle.close(); return await work(); }
57
+ finally { await handle.close().catch(() => {}); if (await readOptional(path) === token) await unlink(path); }
58
+ }
59
+ async function replaceSettings(path, before, after) {
60
+ const temporary = `${path}.${randomUUID()}.tmp`;
61
+ try {
62
+ if (after !== null) await writeFile(temporary, after, { flag: 'wx', mode: 0o600 });
63
+ // Do not replace a snapshot if another rer invocation or editor changed it
64
+ // while the new document/receipt was being prepared.
65
+ if (await readOptional(path) !== before) throw new Error('Claude settings changed concurrently; no replacement was made. Retry the permission change.');
66
+ if (after === null) await unlink(path); else await rename(temporary, path);
67
+ } finally { await unlink(temporary).catch(e => { if (e.code !== 'ENOENT') throw e; }); }
68
+ }
69
+ function receiptFrom(text, settings) {
70
+ let receipt;
71
+ try { receipt = JSON.parse(text); } catch { throw new Error('Business permission receipt is invalid; Claude settings were left intact.'); }
72
+ if (!object(receipt) || receipt.version !== 1 || receipt.settings !== settings || !Array.isArray(receipt.added) || receipt.added.some(rule => !BUSINESS_DENY_RULES.includes(rule)) || !['prepared', 'active'].includes(receipt.phase)) throw new Error('Business permission receipt is invalid; Claude settings were left intact.');
73
+ return receipt;
74
+ }
75
+ async function recover(p, receipt, current) {
76
+ if (receipt.phase !== 'prepared') return receipt;
77
+ if (hash(current) === receipt.afterHash) {
78
+ receipt.phase = 'active'; await atomic(p.receipt, JSON.stringify(receipt) + '\n'); return receipt;
79
+ }
80
+ if (hash(current) === receipt.beforeHash) { await unlink(p.receipt); return null; }
81
+ throw new Error('Claude settings changed during an interrupted permission installation. Keep the settings intact and resolve the Business permission receipt before retrying.');
82
+ }
83
+
84
+ /** Explicit opt-in only. The receipt records introduced rules, never a copy of
85
+ * settings (which can contain unrelated credentials or private configuration).
86
+ */
87
+ export async function installPermissions(input = {}) {
88
+ if (input.consent !== true) throw new Error('Changing Claude user permissions requires explicit consent.');
89
+ const p = paths(input);
90
+ let createdDirectory = false;
91
+ try { await lstat(dirname(p.settings)); } catch (e) { if (e.code !== 'ENOENT') throw e; createdDirectory = true; }
92
+ await mkdir(dirname(p.settings), { recursive: true, mode: 0o700 });
93
+ await mkdir(p.stateDir, { recursive: true, mode: 0o700 });
94
+ return lock(p.settings, async () => {
95
+ const before = await readOptional(p.settings), old = await readOptional(p.receipt);
96
+ if (old !== null) {
97
+ const receipt = await recover(p, receiptFrom(old, p.settings), before);
98
+ if (receipt) return { installed: true, added: receipt.added.length };
99
+ }
100
+ const settings = parseSettings(before), existing = settings.permissions?.deny ?? [];
101
+ const added = BUSINESS_DENY_RULES.filter(rule => !existing.includes(rule));
102
+ if (!added.length) return { installed: false, added: 0 };
103
+ const receipt = { version: 1, settings: p.settings, phase: 'prepared', added, createdDirectory,
104
+ createdSettings: before === null, createdPermissions: settings.permissions === undefined,
105
+ createdDeny: settings.permissions?.deny === undefined, beforeHash: hash(before) };
106
+ settings.permissions ??= {}; settings.permissions.deny = [...existing, ...added];
107
+ const after = JSON.stringify(settings, null, 2) + '\n'; receipt.afterHash = hash(after);
108
+ await atomic(p.receipt, JSON.stringify(receipt) + '\n');
109
+ await replaceSettings(p.settings, before, after);
110
+ receipt.phase = 'active'; await atomic(p.receipt, JSON.stringify(receipt) + '\n');
111
+ return { installed: true, added: added.length };
112
+ });
113
+ }
114
+
115
+ /** Re-read current settings and subtract only our additions; preserve all
116
+ * preexisting rules and unrelated edits rather than restoring an old document.
117
+ */
118
+ export async function removePermissions(input = {}) {
119
+ const p = paths(input);
120
+ if (await readOptional(p.receipt) === null) return { removed: false };
121
+ const originalReceipt = receiptFrom(await readOptional(p.receipt), p.settings);
122
+ await mkdir(dirname(p.settings), { recursive: true, mode: 0o700 });
123
+ const result = await lock(p.settings, async () => {
124
+ const raw = await readOptional(p.receipt);
125
+ if (raw === null) return { removed: false };
126
+ const before = await readOptional(p.settings), receipt = await recover(p, receiptFrom(raw, p.settings), before);
127
+ if (!receipt) return { removed: false };
128
+ if (before !== null) {
129
+ const settings = parseSettings(before), rules = settings.permissions?.deny;
130
+ if (rules) {
131
+ for (const rule of receipt.added) { const index = rules.indexOf(rule); if (index >= 0) rules.splice(index, 1); }
132
+ if (receipt.createdDeny && !rules.length) delete settings.permissions.deny;
133
+ if (receipt.createdPermissions && !Object.keys(settings.permissions).length) delete settings.permissions;
134
+ }
135
+ const after = receipt.createdSettings && !Object.keys(settings).length ? null : JSON.stringify(settings, null, 2) + '\n';
136
+ await replaceSettings(p.settings, before, after);
137
+ }
138
+ await unlink(p.receipt);
139
+ return { removed: true };
140
+ });
141
+ if (originalReceipt.createdDirectory) await rmdir(dirname(p.settings)).catch(e => { if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(e.code)) throw e; });
142
+ return result;
143
+ }
@@ -1,8 +1,14 @@
1
1
  import { basename } from 'node:path';
2
2
 
3
3
  const outputs = new Set(['node_modules', 'vendor', '.git', 'dist', 'build', 'target', 'coverage', '.next', '.nuxt', '.output', '.cache', '.venv', 'venv', '__pycache__', '.terraform', '.pulumi', '.wrangler', '.rer', '.seed', 'playwright-report', 'test-results']);
4
+ const tools = new Set(['.claude', '.codex', '.cursor', '.worktrees', '.idea', '.vscode', '.vscode-insiders', '.windsurf', '.continue', '.zed', '.aider', '.gemini', '.opencode']);
4
5
 
5
- export const skipped = path => path.split('/').some(part => outputs.has(part.toLowerCase()));
6
+ export const toolDirectory = path => path.split('/').some(part => tools.has(part.toLowerCase()));
7
+ export const gitDirectory = path => path.split('/').some(part => part.toLowerCase() === '.git');
8
+ export function skipped(path) {
9
+ const part = path.split('/').find(part => outputs.has(part.toLowerCase()));
10
+ return part ? part.toLowerCase() === '.git' ? 'gitDirectories' : 'generatedDirectories' : null;
11
+ }
6
12
 
7
13
  const stores = new Set(['secrets', '.ssh', '.aws', '.gnupg', 'keychains', 'keychain', 'browser profiles', 'browser-profiles', '.mozilla', '.password-store', '.1password']);
8
14
 
@@ -0,0 +1,18 @@
1
+ import { mkdir, readFile, writeFile, rename, unlink } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { stateDirectory } from './state.mjs';
5
+
6
+ export async function loadProgress() {
7
+ try { return JSON.parse(await readFile(join(stateDirectory(), 'progress.json'), 'utf8')); }
8
+ catch (error) { if (error.code === 'ENOENT') return {}; throw error; }
9
+ }
10
+ export async function saveProgress(progress) {
11
+ const directory = stateDirectory();
12
+ await mkdir(directory, { recursive: true, mode: 0o700 });
13
+ const temporary = join(directory, `${randomUUID()}.tmp`);
14
+ try {
15
+ await writeFile(temporary, JSON.stringify(progress), { flag: 'wx', mode: 0o600 });
16
+ await rename(temporary, join(directory, 'progress.json'));
17
+ } finally { await unlink(temporary).catch(error => { if (error.code !== 'ENOENT') throw error; }); }
18
+ }
@@ -0,0 +1,12 @@
1
+ import { createInterface } from 'node:readline/promises';
2
+
3
+ // Consent can never be inferred from a flag, a prior pairing, or a default.
4
+ export async function consent(question) {
5
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
6
+ process.stderr.write(`${question} Run connect in a terminal to answer yes.\n`);
7
+ return false;
8
+ }
9
+ const terminal = createInterface({ input: process.stdin, output: process.stdout });
10
+ try { return (await terminal.question(`${question} [yes/no] `)).trim().toLowerCase() === 'yes'; }
11
+ finally { terminal.close(); }
12
+ }
@@ -0,0 +1,98 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { Api, identifier } from './api.mjs';
3
+ import { sensitive } from './detector.mjs';
4
+ import { paired } from './local-commands.mjs';
5
+
6
+ const protocolVersion = '2025-11-25';
7
+ const headers = { Accept: 'application/json, text/event-stream', 'MCP-Protocol-Version': protocolVersion };
8
+ export const classifications = ['uses', 'sells', 'both', 'product-dependency'];
9
+
10
+ export async function mcpClient(api, { taskId, signal } = {}) {
11
+ const minted = await api.mintToken('mcp', { taskId, signal });
12
+ const options = { token: minted.access_token, signal, headers };
13
+ let sequence = 0;
14
+ async function rpc(method, params, notification = false) {
15
+ const result = await api.post('/api/business/mcp', { jsonrpc: '2.0', ...(!notification ? { id: ++sequence } : {}), method, params }, options);
16
+ if (notification) return;
17
+ if (!result || result.error || result.id !== sequence) throw Error('Business MCP operation was refused.');
18
+ return result.result;
19
+ }
20
+ const initialized = await rpc('initialize', { protocolVersion, capabilities: {}, clientInfo: { name: 'rer-business', version: '1.0.0' } });
21
+ if (initialized.protocolVersion !== protocolVersion) throw Error('Business MCP protocol revision is unsupported.');
22
+ await rpc('notifications/initialized', {}, true);
23
+ return async (name, args = {}) => {
24
+ const result = await rpc('tools/call', { name, arguments: args });
25
+ if (result?.isError || !result?.structuredContent) throw Error('Business task action is unavailable. Use the browser to check its requirements.');
26
+ return result.structuredContent;
27
+ };
28
+ }
29
+
30
+ export async function nextQuestions(api, signal) {
31
+ const tool = await mcpClient(api, { signal });
32
+ const result = await tool('next_question');
33
+ if (!Array.isArray(result.tasks)) throw Error('Business server returned invalid task summaries.');
34
+ return result.tasks;
35
+ }
36
+ const ownerKinds = new Set(['signup.checkout','connect.cloudflare','connect.github','consent.grant','confirm.inventory','plan.review','wave.approve','switchoff.cancel','cutover.billing','rollback.billing']);
37
+ export const ownerLink = state => `${state.origin}/business/${encodeURIComponent(identifier(state.businessId))}`;
38
+
39
+ function classification(task) {
40
+ const toolId = identifier(task.question?.tool_id), vendorId = task.question?.vendor_id;
41
+ const schema = task.question?.answer_schema, vendors = schema?.properties?.vendor_id?.enum;
42
+ const usages = schema?.properties?.usage?.enum;
43
+ if (!Array.isArray(vendors) || !vendors.length || vendors.some(value => typeof value !== 'string' || !/^[a-z][a-z0-9-]{0,79}$/.test(value) || sensitive(value))
44
+ || !vendors.includes('none') || !vendors.includes(vendorId) || sensitive(toolId)
45
+ || !Array.isArray(usages) || usages.length !== classifications.length || classifications.some(value => !usages.includes(value))
46
+ || schema.properties.confidence?.type !== 'number' || schema.properties.confidence.minimum !== 0 || schema.properties.confidence.maximum !== 1)
47
+ throw Error('Business classification metadata was refused.');
48
+ return { toolId, vendorId, vendors };
49
+ }
50
+
51
+ export async function next() {
52
+ const signal = AbortSignal.timeout(55_000);
53
+ const { state, credential } = await paired();
54
+ const tasks = await nextQuestions(new Api(state.origin, credential), signal);
55
+ const item = tasks.find(task => task.kind === 'classify.row' || task.runner === 'owner' || ownerKinds.has(task.kind));
56
+ if (!item) { process.stdout.write('Nothing yet.\n'); return; }
57
+ const id = identifier(item.task_id);
58
+ if (sensitive(id)) throw Error('Business task identifier was refused by the outbound detector.');
59
+ if (item.runner === 'owner' || ownerKinds.has(item.kind)) {
60
+ process.stdout.write(`Owner: ${id}\nAnswer in your browser: ${ownerLink(state)}\n`); return;
61
+ }
62
+ const { toolId, vendorId, vendors } = classification(item);
63
+ process.stdout.write(`Agent: ${id}\nTool: ${toolId}\nSuggested vendor: ${vendorId}\nVendors: ${vendors.join(' | ')}\nSuggest how this tool is used. The owner confirms in the browser.\nUsage: ${classifications.join(' | ')}\nRun: rer business answer ${id} <vendor_id|none> <usage> [confidence]\n`);
64
+ }
65
+
66
+ export async function answer(id, vendorId, choice, rawConfidence = '1') {
67
+ identifier(id);
68
+ // Reject free text before even looking up the question or minting a bearer.
69
+ if (typeof vendorId !== 'string' || !/^[a-z][a-z0-9-]{0,79}$/.test(vendorId) || sensitive(vendorId)) throw Error('Choose a catalogue vendor id from rer business next, or none.');
70
+ if (!classifications.includes(choice)) throw Error(`Choose an enum: ${classifications.join(', ')}.`);
71
+ if (!/^(?:0(?:\.\d+)?|1(?:\.0+)?)$/.test(rawConfidence)) throw Error('Choose a numeric confidence between 0 and 1.');
72
+ const confidence = Number(rawConfidence);
73
+ const { state, credential } = await paired(), api = new Api(state.origin, credential), signal = AbortSignal.timeout(55_000);
74
+ const summary = await (await mcpClient(api, { signal }))('explain_task', { task_id: id });
75
+ if (summary.runner === 'owner' || ownerKinds.has(summary.kind)) throw Error(`This item requires the owner in the browser: ${ownerLink(state)}`);
76
+ if (summary.kind !== 'classify.row' || summary.runner !== 'executor') throw Error('This item does not accept a CLI classification answer.');
77
+ const { vendors } = classification(summary);
78
+ if (!vendors.includes(vendorId)) throw Error('Choose a catalogue vendor id from this question, or none.');
79
+ const tool = await mcpClient(api, { taskId: id, signal });
80
+ let lease = summary;
81
+ if (summary.state === 'ready') lease = await tool('answer', { task_id: id, action: 'claim', client_event_id: randomUUID(), fence: summary.fence });
82
+ if (typeof lease.grant_id !== 'string') throw Error('Business did not return a grant for this question.');
83
+ try {
84
+ await tool('answer', { task_id: id, action: 'complete', client_event_id: randomUUID(), fence: lease.fence, grant_id: lease.grant_id, outputs: { vendor_id: vendorId, usage: choice, confidence } });
85
+ } catch (error) {
86
+ try { await tool('answer', { task_id: id, action: 'release', client_event_id: randomUUID(), fence: lease.fence, grant_id: lease.grant_id, reason: 'failed' }); } catch { /* Expiry/revocation still fences the lease. */ }
87
+ throw error;
88
+ }
89
+ process.stdout.write('Business answer submitted for server validation.\n');
90
+ }
91
+
92
+ export async function token() {
93
+ const { state, credential } = await paired();
94
+ const result = await new Api(state.origin, credential).mintToken('mcp');
95
+ // Claude headersHelper consumes this directly; never run this in an agent
96
+ // transcript. Vendor credentials cannot be retrieved through this command.
97
+ process.stdout.write(JSON.stringify({ Authorization: `Bearer ${result.access_token}` }) + '\n');
98
+ }