@runeditrun/rer 0.2.30 → 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 (64) hide show
  1. package/README.md +110 -0
  2. package/cli/README.md +49 -0
  3. package/cli/business/api.mjs +61 -0
  4. package/cli/business/command.mjs +51 -0
  5. package/cli/business/config-policy.mjs +25 -0
  6. package/cli/business/connect.mjs +50 -0
  7. package/cli/business/detector.mjs +42 -0
  8. package/cli/business/discovery-task.mjs +180 -0
  9. package/cli/business/files.mjs +25 -0
  10. package/cli/business/keychain.mjs +113 -0
  11. package/cli/business/lease.mjs +68 -0
  12. package/cli/business/local-commands.mjs +82 -0
  13. package/cli/business/outbound.mjs +29 -0
  14. package/cli/business/parsers-config.mjs +91 -0
  15. package/cli/business/parsers-infrastructure.mjs +68 -0
  16. package/cli/business/parsers-packages.mjs +84 -0
  17. package/cli/business/parsers-pulumi.mjs +64 -0
  18. package/cli/business/parsers-syntax.mjs +115 -0
  19. package/cli/business/parsers-terraform.mjs +53 -0
  20. package/cli/business/parsers.mjs +68 -0
  21. package/cli/business/permissions.mjs +143 -0
  22. package/cli/business/policy.mjs +52 -0
  23. package/cli/business/progress.mjs +18 -0
  24. package/cli/business/prompts.mjs +12 -0
  25. package/cli/business/questions.mjs +98 -0
  26. package/cli/business/repository.mjs +17 -0
  27. package/cli/business/scan-command.mjs +27 -0
  28. package/cli/business/scan.mjs +74 -0
  29. package/cli/business/service.mjs +152 -0
  30. package/cli/business/state.mjs +46 -0
  31. package/cli/business/supervisor.mjs +92 -0
  32. package/cli/business/vendors/README.md +101 -0
  33. package/cli/business/vendors/calendly.mjs +80 -0
  34. package/cli/business/vendors/common.mjs +103 -0
  35. package/cli/business/vendors/index.mjs +75 -0
  36. package/cli/business/vendors/pagerduty.mjs +70 -0
  37. package/cli/business/vendors/sentry.mjs +84 -0
  38. package/cli/business/vendors/uptimerobot.mjs +20 -0
  39. package/cli/contract.mjs +1 -1
  40. package/cli/deploy-command.mjs +3 -2
  41. package/cli/deploy-inputs.mjs +9 -0
  42. package/cli/deploy.mjs +3 -2
  43. package/cli/main.mjs +1 -0
  44. package/cli/release.mjs +5 -2
  45. package/global/CHANGELOG.md +30 -0
  46. package/global/README.md +110 -0
  47. package/global/cli/describe.mjs +20 -0
  48. package/global/cli/install.mjs +3 -3
  49. package/global/cli/repo-command.mjs +53 -0
  50. package/global/cli/repository-contract.mjs +7 -0
  51. package/global/cli/repository.mjs +84 -0
  52. package/global/launch/prepare.mjs +9 -6
  53. package/global/main.mjs +23 -0
  54. package/install.sh +7 -0
  55. package/modules/deploy-kit/owner-cli.mjs +5 -2
  56. package/modules/deploy-kit/owner.mjs +6 -4
  57. package/modules/deploy-kit/public-origin.mjs +17 -0
  58. package/modules/owner-claim/verify.d.mts +5 -0
  59. package/modules/release/README.md +11 -1
  60. package/modules/release/github-verify.mjs +30 -26
  61. package/modules/release/produce.mjs +2 -2
  62. package/modules/release/source-verification.mjs +2 -2
  63. package/modules/release/verify-workflow.mjs +23 -0
  64. package/package.json +1 -1
@@ -0,0 +1,115 @@
1
+ // These readers describe syntax only. They never resolve a tag, alias, include,
2
+ // interpolation or executable expression. Unsupported syntax contributes no value.
3
+ export const identifier = /^[A-Za-z_][A-Za-z0-9_.-]*$/;
4
+ export const packageName = /^(?:@[a-z0-9_.-]+\/)?[a-z0-9][a-z0-9_.-]*(?:\/[a-z0-9][a-z0-9_.-]*)*$/i;
5
+
6
+ export function literal(source) {
7
+ const value = source.trim();
8
+ if (value.startsWith('"')) {
9
+ try { const parsed = JSON.parse(value); return typeof parsed === 'string' ? parsed : undefined; } catch { return undefined; }
10
+ }
11
+ if (value.startsWith("'")) return /^'(?:[^']|'')*'$/.test(value) ? value.slice(1, -1).replace(/''/g, "'") : undefined;
12
+ return /^[^\s\[\]{},#'"`]+$/.test(value) ? value : undefined;
13
+ }
14
+
15
+ // Keep offsets/newlines, so a removed comment cannot join adjacent tokens.
16
+ // In YAML/TOML, # starts comments; // only starts comments in JSON/HCL/code.
17
+ export function comments(source, slash = false) {
18
+ let clean = '', quote = '', block = false, comment = '';
19
+ const traces = [];
20
+ for (let i = 0; i < source.length; i++) {
21
+ const char = source[i], next = source[i + 1];
22
+ if (block) {
23
+ if (char === '*' && next === '/') { traces.push(comment); comment = ''; block = false; clean += ' '; i++; }
24
+ else { comment += char; clean += char === '\n' ? '\n' : ' '; }
25
+ } else if (quote) {
26
+ clean += char;
27
+ if (char === '\\' && quote !== "'") { clean += next ?? ''; i++; }
28
+ else if (char === quote) {
29
+ if (quote === "'" && next === "'") { clean += next; i++; }
30
+ else quote = '';
31
+ }
32
+ } else if (char === '"' || char === "'" || (slash && char === '`')) {
33
+ quote = char; clean += char;
34
+ }
35
+ else if (slash && char === '/' && next === '*') { block = true; clean += ' '; i++; }
36
+ else if (char === '#' || (slash && char === '/' && next === '/')) {
37
+ const start = i + (char === '#' ? 1 : 2);
38
+ let end = source.indexOf('\n', start); if (end === -1) end = source.length;
39
+ traces.push(source.slice(start, end)); clean += ' '.repeat(end - i); i = end - 1;
40
+ } else clean += char;
41
+ }
42
+ if (block) traces.push(comment);
43
+ return { clean, traces };
44
+ }
45
+
46
+ // Split delimiters outside strings and flow collections. No regexp can safely
47
+ // split an inline table containing a quoted comma or colon.
48
+ export function splitOutside(source, delimiter) {
49
+ const result = []; let start = 0, quote = '', depth = 0;
50
+ for (let i = 0; i < source.length; i++) {
51
+ const char = source[i];
52
+ if (quote) {
53
+ if (char === '\\' && quote === '"') i++;
54
+ else if (char === quote) {
55
+ if (quote === "'" && source[i + 1] === "'") i++;
56
+ else quote = '';
57
+ }
58
+ } else if (char === '"' || char === "'") quote = char;
59
+ else if (char === '[' || char === '{') depth++;
60
+ else if (char === ']' || char === '}') depth--;
61
+ else if (char === delimiter && depth === 0) { result.push(source.slice(start, i)); start = i + 1; }
62
+ }
63
+ result.push(source.slice(start)); return result;
64
+ }
65
+
66
+ export function keyParts(source, dotted = false) {
67
+ const pieces = dotted ? splitOutside(source, '.') : [source];
68
+ const result = pieces.map(piece => {
69
+ const trimmed = piece.trim(), value = literal(trimmed);
70
+ return value && (/^["']/.test(trimmed) || identifier.test(value)) ? value : undefined;
71
+ });
72
+ return result.length && result.every(part => part !== undefined) ? result : undefined;
73
+ }
74
+
75
+ export function flowEntries(source, path, delimiter, entries, depth = 0) {
76
+ if (depth > 48) return;
77
+ const value = source.trim();
78
+ if (value.startsWith('{') && value.endsWith('}')) {
79
+ for (const pair of splitOutside(value.slice(1, -1), ',')) {
80
+ const parts = splitOutside(pair, delimiter); if (parts.length < 2) continue;
81
+ const keys = keyParts(parts.shift(), delimiter === '='); if (!keys) continue;
82
+ const child = [...path, ...keys], raw = parts.join(delimiter).trim();
83
+ entries.push({ path: child, value: literal(raw) }); flowEntries(raw, child, delimiter, entries, depth + 1);
84
+ }
85
+ } else if (value.startsWith('[') && value.endsWith(']')) {
86
+ for (const item of splitOutside(value.slice(1, -1), ',')) {
87
+ const child = [...path, '[]']; entries.push({ path: child, value: literal(item) });
88
+ flowEntries(item, child, delimiter, entries, depth + 1);
89
+ }
90
+ }
91
+ }
92
+
93
+ export function jsonEntries(source) {
94
+ let root;
95
+ try { root = JSON.parse(source); } catch { return []; }
96
+ const entries = [], pending = [{ value: root, path: [] }];
97
+ while (pending.length) {
98
+ const { value, path } = pending.pop(); if (path.length > 48) continue;
99
+ if (Array.isArray(value)) {
100
+ for (const child of value) {
101
+ const next = [...path, '[]']; entries.push({ path: next, value: typeof child === 'string' ? child : undefined });
102
+ if (child && typeof child === 'object') pending.push({ path: next, value: child });
103
+ }
104
+ } else if (value && typeof value === 'object') {
105
+ for (const [key, child] of Object.entries(value)) {
106
+ // JSON object keys are names, including quoted names with spaces. The
107
+ // caller applies its output detector to every candidate, including keys.
108
+ if (!key) continue;
109
+ const next = [...path, key]; entries.push({ path: next, value: typeof child === 'string' ? child : undefined });
110
+ if (child && typeof child === 'object') pending.push({ path: next, value: child });
111
+ }
112
+ }
113
+ }
114
+ return entries;
115
+ }
@@ -0,0 +1,53 @@
1
+ function tokens(source) {
2
+ const result = [];
3
+ for (let i = 0; i < source.length;) {
4
+ if (/\s/.test(source[i])) { i++; continue; }
5
+ if (source.slice(i, i + 2) === '<<') {
6
+ const marker = /^<<-?([A-Za-z_][A-Za-z0-9_]*)[^\S\n]*\r?\n/.exec(source.slice(i));
7
+ if (marker) {
8
+ i += marker[0].length;
9
+ while (i < source.length) {
10
+ let end = source.indexOf('\n', i); if (end === -1) end = source.length;
11
+ const line = source.slice(i, end).trim(); i = end + 1;
12
+ if (line === marker[1]) break;
13
+ }
14
+ continue;
15
+ }
16
+ }
17
+ if (source[i] === '"') {
18
+ let end = i + 1;
19
+ for (; end < source.length; end++) {
20
+ if (source[end] === '\\') end++;
21
+ else if (source[end] === '"') { end++; break; }
22
+ }
23
+ let value; try { value = JSON.parse(source.slice(i, end)); } catch { /* Opaque malformed string. */ }
24
+ result.push({ type: 'string', value }); i = end; continue;
25
+ }
26
+ const word = /^[A-Za-z_][A-Za-z0-9_-]*/.exec(source.slice(i));
27
+ if (word) { result.push({ type: 'word', value: word[0] }); i += word[0].length; }
28
+ else { result.push({ type: source[i], value: source[i] }); i++; }
29
+ }
30
+ return result;
31
+ }
32
+
33
+ export function terraformNames(source, add) {
34
+ const syntax = tokens(source), stack = [];
35
+ for (let i = 0; i < syntax.length; i++) {
36
+ const token = syntax[i];
37
+ if (token.type === '{') { stack.push(syntax[i - 1]?.value === 'required_providers'); continue; }
38
+ if (token.type === '}') { stack.pop(); continue; }
39
+ if (token.type !== 'word') continue;
40
+ if (['provider', 'resource', 'data'].includes(token.value) && syntax[i + 1]?.type === 'string') {
41
+ const label = syntax[i + 1].value, next = i + (token.value === 'provider' ? 2 : 3);
42
+ if (typeof label === 'string' && /^[A-Za-z][A-Za-z0-9_-]*$/.test(label) && syntax[next]?.type === '{'
43
+ && (token.value === 'provider' || syntax[i + 2]?.type === 'string')) {
44
+ add(token.value === 'provider' ? 'iac-provider' : 'iac-resource', label);
45
+ }
46
+ }
47
+ if (stack.at(-1) && syntax[i + 1]?.type === '=' && syntax[i + 2]?.type === '{') add('iac-provider', token.value);
48
+ if (stack.includes(true) && token.value === 'source' && syntax[i + 1]?.type === '=' && syntax[i + 2]?.type === 'string') {
49
+ const value = syntax[i + 2].value;
50
+ if (typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9_.-]*(?:\/[A-Za-z0-9][A-Za-z0-9_.-]*){1,2}$/.test(value)) add('iac-provider', value);
51
+ }
52
+ }
53
+ }
@@ -0,0 +1,68 @@
1
+ import { comments, jsonEntries } from './parsers-syntax.mjs';
2
+ import { configNames, tomlEntries, yamlEntries } from './parsers-config.mjs';
3
+ import { environmentNames, packageNames } from './parsers-packages.mjs';
4
+ import { infrastructureDocument, infrastructureNames } from './parsers-infrastructure.mjs';
5
+ import { pulumiNames } from './parsers-pulumi.mjs';
6
+ import { configuration, configKeyLimit } from './config-policy.mjs';
7
+
8
+ const examples = /(?:^|[/.\-_])(?:examples?|samples?|templates?|fixtures?)(?:[/.\-_]|$)/i;
9
+ const manifests = /^(?:package\.json|composer\.json|requirements[^/]*\.txt|pyproject\.toml|gemfile|go\.mod|cargo\.toml)$/;
10
+ const code = /\.(?:[cm]?[jt]sx?|py|go|cs)$/i;
11
+
12
+ function entriesFor(pathname, source) {
13
+ if (/\.jsonc?(?:\.(?:example|sample|template|tpl))?$/i.test(pathname)) return jsonEntries(source);
14
+ if (/\.toml(?:\.(?:example|sample|template|tpl))?$/i.test(pathname)) return tomlEntries(source);
15
+ if (/\.ya?ml(?:\.(?:example|sample|template|tpl))?$/i.test(pathname)) return yamlEntries(source);
16
+ return [];
17
+ }
18
+
19
+ // No I/O, evaluation or diagnostics containing input. Each extractor emits a
20
+ // narrow syntactic name at its source, rather than redacting scalar values later.
21
+ export function parseNames(relativePath, text) {
22
+ if (typeof relativePath !== 'string' || typeof text !== 'string') return [];
23
+ const pathname = relativePath.replace(/\\/g, '/'), filename = pathname.split('/').at(-1).toLowerCase();
24
+ const ci = /(?:^|\/)(?:\.github\/workflows\/|\.circleci\/|\.gitlab-ci(?:[./-]|$)|azure-pipelines[./-]|\.travis[./-]|jenkinsfile$|bitbucket-pipelines[./-]|\.buildkite\/)/i.test(pathname);
25
+ const env = /(?:^|\/)(?:\.?env(?:[.\-_]|$)|[^/]*(?:env|config|settings)[^/]*(?:example|sample|template))/i.test(pathname);
26
+ const helm = /(?:^|\/)(?:charts?|helm)\/.*(?:^|\/)templates\//i.test(pathname)
27
+ || /(?:^|\/)(?:charts?|helm)\/templates\//i.test(pathname);
28
+ const explicitExample = /(?:^|[/.\-_])(?:examples?|samples?|fixtures?)(?:[/.\-_]|$)/i.test(pathname);
29
+ const manifest = manifests.test(filename), classification = examples.test(pathname) && (!helm || explicitExample) ? 'trace' : 'live-use';
30
+ const result = [], seen = new Set(), configKeys = new Set();
31
+ const emit = evidenceClass => (kind, value) => {
32
+ if (typeof value !== 'string' || !value || value.length > 512 || /[\r\n\0]/.test(value)) return;
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
+ }
38
+ if (!seen.has(key)) { seen.add(key); result.push({ kind, value, class: evidenceClass }); }
39
+ };
40
+ const parse = (source, evidenceClass, isComment) => {
41
+ const entries = entriesFor(pathname, source);
42
+ const deployed = !isComment && !explicitExample && (ci || infrastructureDocument(pathname, entries));
43
+ const add = emit(deployed ? 'live-use' : evidenceClass);
44
+ if (manifest) packageNames(filename, source, entries, add);
45
+ if (env) environmentNames(source, add);
46
+ if (!manifest && configuration(pathname)) configNames(entries, add);
47
+ infrastructureNames(pathname, source, entries, ci, add);
48
+ if (code.test(pathname)) pulumiNames(pathname, source, add);
49
+ // Commented-out env declarations are useful traces even in config files.
50
+ if (isComment && !manifest) environmentNames(source, add);
51
+ };
52
+ try {
53
+ const templateTraces = [];
54
+ const templateClean = text.replace(/\{\{\s*\/\*([\s\S]*?)\*\/\s*\}\}/g, (whole, content) => {
55
+ templateTraces.push(content); return whole.replace(/[^\n]/g, ' ');
56
+ });
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));
59
+ parse(clean, classification, false);
60
+ // Group consecutive comment lines so commented TOML/YAML sections retain
61
+ // their structural context. Comments never inherit live-use classification.
62
+ if (traces.length) parse(traces.join('\n'), 'trace', true);
63
+ for (const trace of templateTraces) parse(trace, 'trace', true);
64
+ } catch {
65
+ // Invalid/unsupported syntax is not permission to expose its scalar text.
66
+ }
67
+ return result;
68
+ }
@@ -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
+ }
@@ -0,0 +1,52 @@
1
+ import { basename } from 'node:path';
2
+
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']);
5
+
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
+ }
12
+
13
+ const stores = new Set(['secrets', '.ssh', '.aws', '.gnupg', 'keychains', 'keychain', 'browser profiles', 'browser-profiles', '.mozilla', '.password-store', '.1password']);
14
+
15
+ function browserStore(path) {
16
+ // Recognize browser data locations, rather than projects or arbitrary
17
+ // directories named profiles, Firefox, Chromium or Safari.
18
+ return /(?:^|\/)\.config\/(?:google-chrome(?:-[^/]+)?|chromium|brave-browser|bravesoftware\/brave-browser|microsoft-edge(?:-[^/]+)?)(?:\/|$)/.test(path) ||
19
+ /(?:^|\/)library\/application support\/(?:google\/chrome(?: [^/]+)?|chromium|bravesoftware\/brave-browser|microsoft edge(?: [^/]+)?|firefox)(?:\/|$)/.test(path) ||
20
+ /(?:^|\/)appdata\/(?:local\/(?:google\/chrome|chromium|bravesoftware\/brave-browser|microsoft\/edge)\/user data|roaming\/mozilla\/firefox)(?:\/|$)/.test(path) ||
21
+ /(?:^|\/)library\/(?:safari|containers\/com\.apple\.safari|group containers\/[^/]*\.com\.apple\.safari)(?:\/|$)/.test(path);
22
+ }
23
+
24
+ function passwordExport(name) {
25
+ return /^(?:1password|bitwarden|lastpass|dashlane|keeper|enpass|nordpass|keepass)(?:[._ -](?:exports?|backups?|credentials?|passwords?|logins?).*)?\.(?:csv|json|zip|txt|xml)$/.test(name) ||
26
+ /^(?:password-manager|passwords?|vault|logins)[._ -](?:exports?|backups?)(?:[._ -].*)?\.(?:csv|json|zip|txt|xml)$/.test(name) ||
27
+ /^(?:passwords?|logins)\.csv$/.test(name);
28
+ }
29
+
30
+ // Specific stores apply to absolute ancestors, including those of explicit
31
+ // roots. Filename rules apply only to the file, never to its parent projects.
32
+ // Denied directories are enumerated for metadata only, never file content.
33
+ export function denied(path) {
34
+ const lower = path.toLowerCase(), name = basename(lower);
35
+ return lower.split('/').some(part => stores.has(part) || /\.(?:opvault|agilekeychain)$/.test(part)) || browserStore(lower) ||
36
+ /\.(?:pem|key|p12|pfx|keychain|keychain-db|kdbx|kdb|1pux|1pif|opvault|agilekeychain)$/.test(name) ||
37
+ /^id_/.test(name) || /^credentials/.test(name) || /^service-account.*\.json$/.test(name) ||
38
+ /^\.env/.test(name) && !/\.(?:example|sample)$/.test(name) ||
39
+ /^\.dev\.vars(?:$|\.)/.test(name) || /\.tfvars(?:\.json)?$/.test(name) || /kubeconfig/.test(name) || passwordExport(name);
40
+ }
41
+
42
+ export const example = path => /(?:^|[./_-])(?:examples?|samples?|templates?)(?:[./_-]|$)/i.test(path);
43
+
44
+ // Only recognised source/config formats are opened. Executable IaC is lexed,
45
+ // never imported, and arbitrary documents and binary files are left untouched.
46
+ export function readable(path) {
47
+ const name = basename(path).toLowerCase();
48
+ return /\.(?:jsonc?|ya?ml|toml|tf|hcl)(?:\.(?:example|sample|template|tpl))?$/.test(name) ||
49
+ ['gemfile', 'go.mod', 'jenkinsfile'].includes(name) || /^requirements.*\.txt$/.test(name) ||
50
+ example(path) && /(?:env|config|settings)/i.test(path) ||
51
+ /(?:^|\/)(?:pulumi[^/]*|infra(?:structure)?)(?:\/|\.)/i.test(path) && /\.(?:[cm]?[jt]s|tsx|py|go|cs)$/.test(name);
52
+ }
@@ -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
+ }
@@ -0,0 +1,17 @@
1
+ import { lstat } from 'node:fs/promises';
2
+ import { basename, dirname, join, resolve } from 'node:path';
3
+ import { readPlainFile } from './files.mjs';
4
+
5
+ export async function repositoryBoundary(path, metadataOnly) {
6
+ const marker = join(path, '.git');
7
+ let info;
8
+ try { info = await lstat(marker); }
9
+ catch (error) { if (error.code === 'ENOENT') return null; throw error; }
10
+ if (info.isDirectory()) return 'repository';
11
+ if (!info.isFile() || metadataOnly) return null;
12
+ const pointer = (await readPlainFile(marker, info)).match(/^gitdir:[ \t]*(.+?)[ \t]*(?:\r?\n)?$/);
13
+ if (!pointer) return null;
14
+ // Inspect only the pointer's shape. Never follow it or emit its path.
15
+ const gitdir = resolve(path, pointer[1]);
16
+ return basename(dirname(gitdir)) === 'worktrees' ? 'linkedWorktree' : 'repository';
17
+ }
@@ -0,0 +1,27 @@
1
+ import { scan } from './scan.mjs';
2
+
3
+ const usage = 'Usage: rer business scan [DIR...] [--json]\nNames-only local discovery; returns rer-business-signals/1 JSON. No network calls.\n';
4
+
5
+ export async function scanCommand(argv) {
6
+ if (!argv.length || argv.length === 1 && ['--help', '-h'].includes(argv[0]) || argv[0] === 'scan' && argv.slice(1).some(arg => ['--help', '-h'].includes(arg))) {
7
+ process.stdout.write(usage); return 0;
8
+ }
9
+ if (argv[0] !== 'scan') { process.stderr.write(usage); return 2; }
10
+ const directories = [];
11
+ let positional = false, json = false;
12
+ for (const arg of argv.slice(1)) {
13
+ if (!positional && arg === '--') { positional = true; continue; }
14
+ if (!positional && arg === '--json' && !json) { json = true; continue; }
15
+ if (!positional && arg.startsWith('-') || !arg.trim()) { process.stderr.write(usage); return 2; }
16
+ directories.push(arg);
17
+ }
18
+ try {
19
+ const result = await scan(directories.length ? directories : [process.cwd()]);
20
+ process.stdout.write(JSON.stringify(result) + '\n');
21
+ return 0;
22
+ } catch {
23
+ // Node/format errors can contain input paths, keys or source excerpts.
24
+ process.stderr.write('Business scan could not read a local input. No scan document was emitted.\n');
25
+ return 1;
26
+ }
27
+ }