@runeditrun/rer 0.2.31 → 0.2.33

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 (55) 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 +25 -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/demo-host/native/visitor.mjs +13 -0
  47. package/modules/demo-host/pages.mjs +2 -2
  48. package/modules/demo-host/worker.mjs +6 -1
  49. package/modules/dependencies/logout.mjs +3 -2
  50. package/modules/deploy-kit/owner-cli.mjs +5 -2
  51. package/modules/deploy-kit/owner.mjs +6 -4
  52. package/modules/deploy-kit/public-origin.mjs +17 -0
  53. package/modules/mail/src/core/validation.mjs +12 -3
  54. package/modules/mail/src/inbound/headers.mjs +6 -5
  55. package/package.json +1 -1
@@ -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
+ }
@@ -1,58 +1,65 @@
1
- import { constants } from 'node:fs';
2
- import { lstat, open, readdir, realpath } from 'node:fs/promises';
3
- import { basename, dirname, join, relative, resolve, parse } from 'node:path';
1
+ import { lstat, readdir, realpath } from 'node:fs/promises';
2
+ import { basename, dirname, join, relative, resolve } from 'node:path';
4
3
  import { blockedSignal } from './detector.mjs';
5
- import { denied, example, readable, skipped } from './policy.mjs';
4
+ import { denied, example, gitDirectory, readable, skipped, toolDirectory } from './policy.mjs';
6
5
  import { parseNames } from './parsers.mjs';
7
-
8
- // Caller-named roots are canonicalized once; below them, refuse symlink
9
- // ancestors as well as symlink entries before reading any file content.
10
- async function plainAncestors(path) {
11
- const root = parse(path).root;
12
- let current = root;
13
- for (const part of path.slice(root.length).split('/').filter(Boolean)) {
14
- current = join(current, part);
15
- if ((await lstat(current)).isSymbolicLink()) return false;
16
- }
17
- return true;
18
- }
6
+ import { configKeyLimit } from './config-policy.mjs';
7
+ import { readPlainFile } from './files.mjs';
8
+ import { repositoryBoundary } from './repository.mjs';
19
9
 
20
10
  async function namesFromFile(path, info, locator, pulumi) {
21
11
  if (!readable(locator) && !(pulumi && /\.(?:[cm]?[jt]sx?|py|go|cs)$/i.test(locator))) return [];
22
- // O_NOFOLLOW blocks a replaced leaf; compare the opened inode before reading.
23
- const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
24
- try {
25
- const opened = await file.stat();
26
- if (!opened.isFile() || opened.ino !== info.ino || opened.dev !== info.dev || !await plainAncestors(dirname(path))) throw Error('Changed scan input');
27
- return parseNames(locator, await file.readFile('utf8'));
28
- } finally { await file.close(); }
12
+ return parseNames(locator, await readPlainFile(path, info));
29
13
  }
30
14
 
31
15
  export async function scan(directories) {
32
- const result = { schema: 'rer-business-signals/1', source: 'local', signals: [], withheld: 0 };
33
- const observedAt = new Date().toISOString(), seen = new Set();
16
+ const result = { schema: 'rer-business-signals/1', source: 'local', configKeyLimit, signals: [], withheld: 0,
17
+ skipped: { linkedWorktrees: 0, toolDirectories: 0, generatedDirectories: 0, gitDirectories: 0 } };
18
+ const observedAt = new Date().toISOString(), seen = new Set(), grouped = new Map();
34
19
  const roots = [...new Set(directories.map(path => resolve(path)))];
35
20
  function emit(signal) {
36
21
  if (blockedSignal(signal)) { result.withheld++; return; }
37
- result.signals.push(signal);
22
+ // Denied files retain their own locator, size and mtime, even when names match.
23
+ if (signal.kind === 'secret-file') { result.signals.push(signal); return; }
24
+ const key = JSON.stringify([signal.kind, signal.value, signal.repo, signal.class]);
25
+ const existing = grouped.get(key);
26
+ if (existing) existing.count++;
27
+ else {
28
+ const counted = { ...signal, count: 1 };
29
+ grouped.set(key, counted);
30
+ result.signals.push(counted);
31
+ }
38
32
  }
39
33
  for (const requested of roots) {
40
34
  const root = await realpath(requested);
41
- const rootInfo = await lstat(root), base = rootInfo.isDirectory() ? root : dirname(root), repo = basename(base);
42
- async function walk(path, pulumi = false) {
43
- if (skipped(relative(root, path)) || seen.has(path)) return;
44
- seen.add(path);
35
+ const rootInfo = await lstat(root), base = rootInfo.isDirectory() ? root : dirname(root);
36
+ if (rootInfo.isDirectory() && (gitDirectory(basename(root)) || gitDirectory(basename(requested)))) {
37
+ throw Error('Git metadata cannot be a scan root');
38
+ }
39
+ async function walk(path, repository, pulumi = false) {
40
+ if (seen.has(path)) return;
45
41
  const info = await lstat(path);
46
42
  if (info.isSymbolicLink()) return;
43
+ const rootRelative = relative(root, path), requestedPath = join(requested, rootRelative);
44
+ const skip = toolDirectory(rootRelative) ? 'toolDirectories' :
45
+ gitDirectory(rootRelative) ? 'gitDirectories' : skipped(rootRelative);
46
+ if (skip) {
47
+ if (info.isDirectory()) result.skipped[skip]++;
48
+ return;
49
+ }
50
+ const boundary = info.isDirectory() && rootRelative ? await repositoryBoundary(path, denied(path) || denied(requestedPath)) : null;
51
+ if (boundary === 'linkedWorktree') { result.skipped.linkedWorktrees++; return; }
52
+ seen.add(path);
47
53
  if (info.isDirectory()) {
54
+ if (boundary === 'repository') { repository = path; pulumi = false; }
48
55
  const names = (await readdir(path)).sort();
49
56
  pulumi ||= names.some(name => /^Pulumi\.ya?ml$/i.test(name));
50
- for (const name of names) await walk(join(path, name), pulumi);
57
+ for (const name of names) await walk(join(path, name), repository, pulumi);
51
58
  } else if (info.isFile()) {
52
- const locator = relative(base, path).split('\\').join('/');
53
- const common = { locator, repo, class: example(locator) ? 'trace' : 'live-use', observedAt };
59
+ const locator = relative(repository, path).split('\\').join('/');
60
+ const common = { locator, repo: basename(repository), class: example(locator) ? 'trace' : 'live-use', observedAt };
54
61
  // A caller-named store remains metadata-only even when it is an alias.
55
- if (denied(path) || denied(join(requested, relative(root, path)))) {
62
+ if (denied(path) || denied(requestedPath)) {
56
63
  emit({ kind: 'secret-file', value: basename(path), ...common, size: info.size, mtime: info.mtime.toISOString() });
57
64
  return;
58
65
  }
@@ -61,7 +68,7 @@ export async function scan(directories) {
61
68
  }
62
69
  }
63
70
  }
64
- await walk(root);
71
+ await walk(root, base);
65
72
  }
66
73
  return result;
67
74
  }
@@ -0,0 +1,152 @@
1
+ import { execFile, spawn } from 'node:child_process';
2
+ import { mkdir, readFile, writeFile, rename, unlink, realpath, stat, lstat, rmdir } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { dirname, join, isAbsolute } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { createHash, randomUUID } from 'node:crypto';
7
+
8
+ const label = 'com.runeditrun.business', unit = 'rer-business.service';
9
+ const digest = text => createHash('sha256').update(text).digest('hex');
10
+ const xml = value => String(value).replace(/[<>&"']/g, char => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;', "'": '&apos;' })[char]);
11
+ const unitValue = value => `"${String(value).replace(/[%\\"\n\r\t]/g, char => ({ '%': '%%', '\\': '\\\\', '"': '\\"', '\n': '\\n', '\r': '\\r', '\t': '\\t' })[char])}"`;
12
+
13
+ function execute(binary, args) {
14
+ return new Promise(resolve => execFile(binary, args, { timeout: 30000, maxBuffer: 65536 }, (error, stdout) => resolve({ code: error ? (typeof error.code === 'number' ? error.code : -1) : 0, stdout: stdout ?? '' })));
15
+ }
16
+ function options(input = {}) {
17
+ const home = input.home ?? homedir(), platform = input.platform ?? process.platform;
18
+ if (!isAbsolute(home) || !['darwin', 'linux'].includes(platform)) throw new Error('Business background services require macOS or Linux and an absolute home directory.');
19
+ const stateDir = input.stateDir ?? join(home, '.rer', 'business');
20
+ if (!isAbsolute(stateDir)) throw new Error('Business service state directory must be absolute.');
21
+ return { ...input, home, platform, stateDir, run: input.run ?? execute };
22
+ }
23
+ function servicePath({ home, platform }) {
24
+ return platform === 'darwin' ? join(home, 'Library', 'LaunchAgents', `${label}.plist`) : join(home, '.config', 'systemd', 'user', unit);
25
+ }
26
+ async function readOptional(path) {
27
+ try {
28
+ const info = await lstat(path);
29
+ if (!info.isFile() || info.isSymbolicLink()) throw new Error('Business service path is not a regular file.');
30
+ return await readFile(path, 'utf8');
31
+ } catch (e) { if (e.code === 'ENOENT') return null; throw e; }
32
+ }
33
+ async function atomic(path, text) {
34
+ const temporary = `${path}.${randomUUID()}.tmp`;
35
+ try { await writeFile(temporary, text, { mode: 0o600, flag: 'wx' }); await rename(temporary, path); }
36
+ finally { await unlink(temporary).catch(e => { if (e.code !== 'ENOENT') throw e; }); }
37
+ }
38
+ async function checkedRun(run, binary, args, operation) {
39
+ let result;
40
+ try { result = await run(binary, args); } catch { throw new Error(`Could not ${operation} the Business background service.`); }
41
+ if (result.code !== 0) throw new Error(`Could not ${operation} the Business background service. Check your user service manager and retry.`);
42
+ }
43
+ async function missingParents(directory, home) {
44
+ const missing = [];
45
+ for (let path = directory; path !== home && path !== dirname(path); path = dirname(path)) {
46
+ try { await lstat(path); break; } catch (e) { if (e.code !== 'ENOENT') throw e; missing.push(path); }
47
+ }
48
+ return missing;
49
+ }
50
+ async function removeEmpty(paths) {
51
+ for (const path of [...new Set(paths)].sort((a, b) => b.length - a.length)) await rmdir(path).catch(e => {
52
+ if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(e.code)) throw e;
53
+ });
54
+ }
55
+
56
+ /** Call only after specific service-install consent. No credentials are placed
57
+ * in the unit, process arguments, environment, or service receipt.
58
+ */
59
+ export async function installService(input = {}) {
60
+ if (input.consent !== true) throw new Error('Installing the Business background service requires explicit consent.');
61
+ const o = options(input), path = servicePath(o), receiptPath = join(o.stateDir, 'service.json');
62
+ const node = await realpath(input.nodePath ?? process.execPath);
63
+ const entrypoint = await realpath(input.entrypoint ?? fileURLToPath(new URL('../../bin/rer.mjs', import.meta.url)));
64
+ if (!isAbsolute(node) || !isAbsolute(entrypoint) || !(await stat(node)).isFile() || !(await stat(entrypoint)).isFile()) throw new Error('Business requires an absolute Node executable and rer entrypoint.');
65
+ const log = join(o.stateDir, 'service.log'), errorLog = join(o.stateDir, 'service-error.log');
66
+ const environmentPath = `${dirname(node)}:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin`;
67
+ const text = o.platform === 'darwin'
68
+ ? `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0"><dict>\n<key>Label</key><string>${label}</string>\n<key>ProgramArguments</key><array>${[node, entrypoint, 'business', 'run'].map(arg => `<string>${xml(arg)}</string>`).join('')}</array>\n<key>EnvironmentVariables</key><dict><key>HOME</key><string>${xml(o.home)}</string><key>PATH</key><string>${xml(environmentPath)}</string></dict>\n<key>WorkingDirectory</key><string>${xml(o.home)}</string>\n<key>RunAtLoad</key><true/><key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>\n<key>ThrottleInterval</key><integer>30</integer><key>Umask</key><integer>63</integer>\n<key>StandardOutPath</key><string>${xml(log)}</string><key>StandardErrorPath</key><string>${xml(errorLog)}</string>\n</dict></plist>\n`
69
+ : `[Unit]\nDescription=Run Edit Run Business executor\nAfter=network-online.target\n\n[Service]\nType=simple\nExecStart=${[node, entrypoint, 'business', 'run'].map(value => unitValue(value).replaceAll('$', () => '$$')).join(' ')}\nWorkingDirectory=${unitValue(o.home)}\nEnvironment=${unitValue(`HOME=${o.home}`)} ${unitValue(`PATH=${environmentPath}`)}\nRestart=on-failure\nRestartSec=30\nUMask=0077\n\n[Install]\nWantedBy=default.target\n`;
70
+ const existing = await readOptional(path), oldReceipt = await readOptional(receiptPath);
71
+ if (existing !== null && (!oldReceipt || JSON.parse(oldReceipt).hash !== digest(existing))) throw new Error('A background service already exists at the Business service path; it was not overwritten.');
72
+ if (oldReceipt && existing !== null && existing !== text) throw new Error('Remove the existing Business service before changing its installation paths.');
73
+ const createdDirectories = oldReceipt ? JSON.parse(oldReceipt).createdDirectories ?? [] : [...await missingParents(dirname(path), o.home), ...await missingParents(o.stateDir, o.home)];
74
+ await mkdir(o.stateDir, { recursive: true, mode: 0o700 });
75
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
76
+ // Write ownership before installation so an interrupted install is removable.
77
+ await atomic(receiptPath, JSON.stringify({ version: 1, platform: o.platform, path, hash: digest(text), createdDirectories }) + '\n');
78
+ if (existing === null) await writeFile(path, text, { flag: 'wx', mode: 0o600 });
79
+ if (o.platform === 'darwin') {
80
+ const target = `gui/${process.getuid()}`;
81
+ // A repeated connect can reuse the already-loaded, exactly-owned service.
82
+ const loaded = await o.run('/bin/launchctl', ['print', `${target}/${label}`]);
83
+ if (loaded.code !== 0) await checkedRun(o.run, '/bin/launchctl', ['bootstrap', target, path], 'start');
84
+ } else {
85
+ await checkedRun(o.run, 'systemctl', ['--user', 'daemon-reload'], 'reload');
86
+ await checkedRun(o.run, 'systemctl', ['--user', 'enable', '--now', unit], 'start');
87
+ }
88
+ return { installed: true, platform: o.platform, path };
89
+ }
90
+
91
+ /** Removes only receipt-bound files. An edited/replaced unit is left for the
92
+ * owner instead of unlinking somebody else's service.
93
+ */
94
+ export async function removeService(input = {}) {
95
+ const o = options(input), receiptPath = join(o.stateDir, 'service.json');
96
+ const raw = await readOptional(receiptPath);
97
+ if (raw === null) return { removed: false };
98
+ const receipt = JSON.parse(raw), path = servicePath(o), existing = await readOptional(path);
99
+ if (receipt.version !== 1 || receipt.platform !== o.platform || receipt.path !== path || existing !== null && digest(existing) !== receipt.hash) throw new Error('The Business service file changed outside rer; it was left intact.');
100
+ if (o.platform === 'darwin') {
101
+ const target = `gui/${process.getuid()}/${label}`;
102
+ const loaded = await o.run('/bin/launchctl', ['print', target]);
103
+ if (loaded.code === 0) await checkedRun(o.run, '/bin/launchctl', ['bootout', target], 'stop');
104
+ } else {
105
+ await checkedRun(o.run, 'systemctl', ['--user', 'disable', '--now', unit], 'stop');
106
+ }
107
+ if (existing !== null) {
108
+ if (await readOptional(path) !== existing) throw new Error('The Business service changed while disconnecting; retry after checking it.');
109
+ await unlink(path);
110
+ }
111
+ if (o.platform === 'linux') await checkedRun(o.run, 'systemctl', ['--user', 'daemon-reload'], 'reload');
112
+ for (const name of ['service.log', 'service-error.log', 'service.json']) await unlink(join(o.stateDir, name)).catch(e => { if (e.code !== 'ENOENT') throw e; });
113
+ const allowedDirectories = new Set();
114
+ for (const start of [dirname(path), o.stateDir]) for (let dir = start; dir !== o.home && dir !== dirname(dir); dir = dirname(dir)) allowedDirectories.add(dir);
115
+ await removeEmpty((receipt.createdDirectories ?? []).filter(dir => allowedDirectories.has(dir)));
116
+ return { removed: true };
117
+ }
118
+
119
+ export async function serviceStatus(input = {}) {
120
+ const o = options(input), raw = await readOptional(join(o.stateDir, 'service.json'));
121
+ if (raw === null) return { installed: false, running: false };
122
+ const receipt = JSON.parse(raw), path = servicePath(o), existing = await readOptional(path);
123
+ if (receipt.version !== 1 || receipt.path !== path || receipt.platform !== o.platform || existing !== null && digest(existing) !== receipt.hash) throw new Error('The Business service file changed outside rer.');
124
+ if (existing === null) return { installed: false, running: false };
125
+ const result = o.platform === 'darwin'
126
+ ? await o.run('/bin/launchctl', ['print', `gui/${process.getuid()}/${label}`])
127
+ : await o.run('systemctl', ['--user', 'is-active', '--quiet', unit]);
128
+ return { installed: true, running: result.code === 0 && (o.platform !== 'darwin' || /(?:^|\n)\s*state = running\s*(?:\n|$)/.test(result.stdout ?? '')) };
129
+ }
130
+
131
+ /** The caller holds an export lease only within this callback. -w also makes
132
+ * caffeinate stop if the executor is killed before its finally block runs.
133
+ */
134
+ export async function withExportAwake(work, { consent = false, platform = process.platform, signal } = {}) {
135
+ if (platform !== 'darwin') return work();
136
+ if (consent !== true) throw new Error('Keeping this Mac awake for an export requires explicit consent.');
137
+ signal?.throwIfAborted();
138
+ const child = spawn('/usr/bin/caffeinate', ['-i', '-w', String(process.pid)], { stdio: 'ignore' });
139
+ const closed = new Promise(resolve => child.once('close', resolve));
140
+ const stop = () => { if (child.exitCode === null && !child.killed) child.kill('SIGTERM'); };
141
+ const onExit = () => stop();
142
+ try {
143
+ await new Promise((resolve, reject) => { child.once('spawn', resolve); child.once('error', () => reject(new Error('Could not keep this Mac awake for the export.'))); });
144
+ signal?.addEventListener('abort', stop, { once: true }); process.once('exit', onExit);
145
+ signal?.throwIfAborted();
146
+ return await work();
147
+ } finally {
148
+ signal?.removeEventListener('abort', stop); process.off('exit', onExit);
149
+ stop();
150
+ if (child.pid) await closed;
151
+ }
152
+ }
@@ -0,0 +1,46 @@
1
+ import { mkdir, readFile, writeFile, rename, chmod, open, unlink } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { homedir } from 'node:os';
4
+ import { createHash, randomUUID } from 'node:crypto';
5
+
6
+ export const stateDirectory = () => join(homedir(), '.rer', 'business');
7
+ export const credentialHandle = origin => `device:${createHash('sha256').update(origin).digest('hex')}`;
8
+
9
+ export async function loadState() {
10
+ try { return JSON.parse(await readFile(join(stateDirectory(), 'state.json'), 'utf8')); }
11
+ catch (error) { if (error.code === 'ENOENT') return null; throw error; }
12
+ }
13
+
14
+ // Only non-secret configuration and progress belong here. Credentials and task
15
+ // grants remain in the keychain and memory, respectively.
16
+ export async function saveState(state) {
17
+ const directory = stateDirectory();
18
+ await mkdir(directory, { recursive: true, mode: 0o700 });
19
+ await chmod(directory, 0o700);
20
+ const temporary = join(directory, `${randomUUID()}.tmp`);
21
+ try {
22
+ await writeFile(temporary, JSON.stringify(state) + '\n', { mode: 0o600, flag: 'wx' });
23
+ await rename(temporary, join(directory, 'state.json'));
24
+ } finally { await unlink(temporary).catch(error => { if (error.code !== 'ENOENT') throw error; }); }
25
+ }
26
+
27
+ export async function lockSupervisor() {
28
+ const directory = stateDirectory();
29
+ await mkdir(directory, { recursive: true, mode: 0o700 });
30
+ const path = join(directory, 'run.lock');
31
+ for (let attempt = 0; attempt < 2; attempt++) {
32
+ try {
33
+ const file = await open(path, 'wx', 0o600);
34
+ await file.writeFile(String(process.pid)); await file.close();
35
+ return async () => { await unlink(path).catch(error => { if (error.code !== 'ENOENT') throw error; }); };
36
+ } catch (error) {
37
+ if (error.code !== 'EEXIST') throw error;
38
+ const pid = Number(await readFile(path, 'utf8'));
39
+ if (!Number.isSafeInteger(pid) || pid <= 0) throw Error('Business supervisor lock is invalid.');
40
+ try { process.kill(pid, 0); throw Error('A Business supervisor is already running.'); }
41
+ catch (check) { if (check.code !== 'ESRCH') throw check; }
42
+ await unlink(path);
43
+ }
44
+ }
45
+ throw Error('Could not acquire Business supervisor lock.');
46
+ }
@@ -0,0 +1,92 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { access, unlink } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { Api, taskPath, pause } from './api.mjs';
5
+ import { paired } from './local-commands.mjs';
6
+ import { createCredentialStore } from './keychain.mjs';
7
+ import { nextQuestions } from './questions.mjs';
8
+ import { lockSupervisor, stateDirectory, credentialHandle } from './state.mjs';
9
+ import { loadProgress, saveProgress } from './progress.mjs';
10
+ import { Lease } from './lease.mjs';
11
+ import { runDiscovery } from './discovery-task.mjs';
12
+
13
+ const kinds = new Set(['discover.local', 'export.vendor']);
14
+ const unavailableReasons = new Set(['ambiguous-target-installation', 'no-linked-installation', 'installation-import-origin-unavailable', 'installation-owner-claim-unconfigured', 'connected-seed-import-required']);
15
+
16
+ export async function run({ once = false } = {}) {
17
+ const { state, credential } = await paired(), api = new Api(state.origin, credential), directory = stateDirectory();
18
+ const parked = new Set(), unlock = await lockSupervisor(), stop = new AbortController();
19
+ const interrupted = () => stop.abort(Error('Business supervisor stopped.'));
20
+ process.once('SIGTERM', interrupted); process.once('SIGINT', interrupted);
21
+ const monitor = setInterval(() => { access(join(directory, 'disconnect')).then(interrupted, () => {}); }, 250);
22
+ let progress;
23
+ try {
24
+ progress = await loadProgress();
25
+ await unlink(join(directory, 'disconnect')).catch(error => { if (error.code !== 'ENOENT') throw error; });
26
+ do {
27
+ if (!progress.pendingClaim) {
28
+ const summaries = await nextQuestions(api, stop.signal);
29
+ const selected = summaries.find(task => kinds.has(task.kind) && ['ready','leased'].includes(task.state) && !parked.has(task.task_id));
30
+ if (!selected) { if (once) { process.stdout.write('Nothing yet.\n'); return; } await pause(25_000, stop.signal); continue; }
31
+ progress.pendingClaim = { claim_id: randomUUID(), task_id: selected.task_id };
32
+ await saveProgress(progress);
33
+ }
34
+ let claimed;
35
+ try { claimed = await api.post('/api/business/executors/claim', { ...progress.pendingClaim, wait_seconds: 25 }, { signal: stop.signal }); }
36
+ catch (error) {
37
+ if (error.status !== 409) throw error;
38
+ progress = {}; await saveProgress(progress);
39
+ if (once) throw error;
40
+ await pause(25_000, stop.signal); continue;
41
+ }
42
+ if (!claimed.task || claimed.task.state !== 'leased' || claimed.task.fence !== claimed.fence || Date.parse(claimed.lease_expires_at) <= Date.now()) {
43
+ progress = {}; await saveProgress(progress);
44
+ if (once && !claimed.task) { process.stdout.write('Nothing yet.\n'); return; }
45
+ continue;
46
+ }
47
+ if (!kinds.has(claimed.task.kind) || claimed.task.kind_version !== 1) throw Error('Business server returned an unimplemented task kind.');
48
+ const lease = new Lease(api, claimed, progress, stop.signal);
49
+ let finished = false, released = false, failure;
50
+ try {
51
+ progress.current = { kind: claimed.task.kind, checkpoint: claimed.task.checkpoint, uploadedBytes: claimed.task.checkpoint?.bytes_done ?? 0 };
52
+ await saveProgress(progress);
53
+ if (claimed.task.kind === 'export.vendor') {
54
+ // A destination is not upload authority. Keep vendor keys local until
55
+ // the seed's signed import grant and chunk transport are connected.
56
+ await lease.send(taskPath(claimed.task.id, 'events'), { event: { kind: 'question', payload: { question: 'connected_runner_required' } } });
57
+ parked.add(claimed.task.id);
58
+ if (claimed.grant.available === false && claimed.grant.destination === `unavailable:${claimed.grant.reason}`) {
59
+ const reason = unavailableReasons.has(claimed.grant.reason) ? claimed.grant.reason : 'connected-seed-import-required';
60
+ throw Error(`Business vendor export unavailable: ${reason}. Task released as paused.`);
61
+ }
62
+ throw Error('Business vendor export needs a connected seed upload grant and execution-input contract.');
63
+ }
64
+ const result = await runDiscovery({ task: claimed.task, grant: claimed.grant, checkpoint: claimed.task.checkpoint, signal: lease.signal,
65
+ send: (destination, body) => lease.send(destination, body), saveCheckpoint: checkpoint => lease.checkpointSaved(checkpoint), stateDir: directory });
66
+ await lease.complete(); finished = true;
67
+ await result.cleanup();
68
+ process.stdout.write('Business discover.local completed and checked by the server.\n');
69
+ } catch (error) { failure = lease.signal.aborted ? lease.signal.reason : error; }
70
+ finally {
71
+ if (!finished && failure?.status !== 401) {
72
+ try { await lease.release(stop.signal.aborted ? 'handover' : parked.has(claimed.task.id) ? 'paused' : 'failed'); released = true; }
73
+ catch (error) { if (error.status === 401) failure = error; }
74
+ }
75
+ await lease.close();
76
+ if (finished || released) { progress = {}; await saveProgress(progress); }
77
+ }
78
+ if (failure) {
79
+ if (failure.status === 401 || once || !parked.has(claimed.task.id)) throw failure;
80
+ process.stderr.write(failure.message + '\n');
81
+ }
82
+ if (once) return;
83
+ } while (!stop.signal.aborted);
84
+ } catch (error) {
85
+ if (error.status === 401) {
86
+ await createCredentialStore().delete(credentialHandle(state.origin));
87
+ process.stderr.write('Business pairing expired or was revoked. Supervisor stopped.\n');
88
+ } else if (!stop.signal.aborted) throw error;
89
+ } finally {
90
+ clearInterval(monitor); process.off('SIGTERM', interrupted); process.off('SIGINT', interrupted); await unlock();
91
+ }
92
+ }
@@ -0,0 +1,101 @@
1
+ # Shipped vendor exports
2
+
3
+ `exportVendor(vendor, {key, inputs, checkpoint, signal})` is an async generator.
4
+ It yields `{name, bytes: Buffer, checkpoint}`. Keys remain in memory and are
5
+ attached only to GET requests on the adapter's fixed HTTPS origin. Redirects,
6
+ caller origins, arbitrary paths and credential-bearing pagination are refused.
7
+ No export runs merely by importing these modules. No account export was run
8
+ during implementation.
9
+
10
+ `VENDORS` is the closed vendor enum. `VENDOR_CAPABILITIES` describes the adapter,
11
+ required vendor-key capability, native importer format, layout and read scopes.
12
+ These adapters cannot verify that a supplied key itself has read-only scope;
13
+ the owner must create the documented read-only key where the vendor offers one.
14
+
15
+ ## Transport and resume
16
+
17
+ Upload bytes only to the task grant's seed destination. They contain private,
18
+ untrusted vendor data and must never appear in CLI output, events or model
19
+ context. The caller applies its outbound secret detector and computes SHA-256,
20
+ enforces the grant quota, and atomically acknowledges the item before persisting
21
+ its checkpoint. Checkpoints contain progress, source IDs, cursor strings, file
22
+ metadata and hashes, never response records. They are less than 128 KiB.
23
+
24
+ An interrupted upload is retried under the same task/fence, deterministic name
25
+ and SHA-256. Resume with exactly the acknowledged checkpoint and original
26
+ inputs; object key ordering does not affect input identity. An unacknowledged
27
+ page may be fetched again, so source edits during interruption can change it:
28
+ the seed must reject a conflicting hash under the same name, and the owner must
29
+ restart that export. This is an API export, not a vendor snapshot transaction.
30
+
31
+ For `layout: 'concatenate'`, concatenate the numbered `000001.part` items in
32
+ sequence to the metadata's `output` filename. Some PagerDuty items have empty
33
+ bytes: they checkpoint schedule discovery and must still be acknowledged.
34
+ Fragments are deliberately not standalone JSON. For `layout: 'files'`, retain
35
+ the given filenames; Calendly ends with `manifest.json`, matching Dial's folder
36
+ import. Never treat a partial stream as a completed bundle.
37
+
38
+ Every item is at most 1 MiB. Exports are bounded to 1,000 requests, one request
39
+ per second, 30 seconds per request, 2 MiB/499 API records for Sentry,
40
+ 512 KiB/500 records for PagerDuty, and 8 MiB/2,500 records for UptimeRobot and
41
+ Calendly. The output bound includes JSON framing and Calendly's manifest.
42
+ Limits stop rather than truncate. AbortSignal stops waits, HTTP reads and
43
+ emission. HTTP errors contain only a fixed code and numeric status; network,
44
+ parsing and unexpected errors never expose response text, URLs or key values.
45
+ 429 stops with `RATE_LIMITED`; there is no hidden retry loop.
46
+
47
+ ## Inputs and native coverage
48
+
49
+ * `sentry`: `organization: {id, slug, region: 'us'|'de'}`, `start`, `end`, and
50
+ optional `events: [{project, eventId}]`. Self-hosted origins are unsupported.
51
+ Projects, releases and all-status issues are paginated; issues use the current
52
+ organization issues API filtered by project and window. Event details are
53
+ fetched only for the explicitly selected IDs, must fall in the window and
54
+ form a complete local cursor chain. A fixed omissions list declares that all
55
+ other event history and unsupported Sentry features remain outside the export.
56
+ Projects/releases are not time-filtered. Spool counts one manifest record in
57
+ addition to the API records. At most 49 projects fit its 100-collection bound.
58
+ * `uptimerobot`: no additional inputs. Exports v3 monitor response pages,
59
+ including their original `data` and `nextLink` envelopes. History, contacts
60
+ and status pages are not fetched.
61
+ * `pagerduty`: `start`/`end` (or `since`/`until`). Exports users, schedule details
62
+ with layers/final coverage, overrides for the window and escalation policies.
63
+ Schedule listing only discovers IDs and is not duplicated in the bundle.
64
+ Overrides retain full boundaries with `overflow=true` and add `schedule_id`,
65
+ as Oncall's documented bundle requires. Credential-bearing response fields
66
+ refuse the export. Incident history and paging configuration are not fetched.
67
+ * `calendly`: optional `asOf` timestamp (recommended for a repeatable catch-up).
68
+ An omitted timestamp is captured at first invocation and retained on resume.
69
+ Downloads the current user, event types, availability schedules, per-type
70
+ availability, future scheduled events including cancellations, and invitees.
71
+ Like Dial's downloader, this is the current user's scope, at most 100 event
72
+ types and 500 scheduled events. Every original page receives a manifest hash.
73
+ No past booking history or arbitrary referenced resource is fetched.
74
+
75
+ ## Primary-source provenance
76
+
77
+ Implementation preserves the response formats and flow in these seed sources;
78
+ it adds streaming, bounded resume and fixed-origin transport rather than running
79
+ their file-writing command wrappers.
80
+
81
+ * [Dial downloader at 6014c99875dd002545e194ab23a7852d30e94e01](https://github.com/just-every/run-dial/blob/6014c99875dd002545e194ab23a7852d30e94e01/scripts/move-in/download.mjs).
82
+ * [Uptime guide at 157686b52ecc652d64250a30ec224f1a47355a6c](https://github.com/just-every/run-uptime/blob/157686b52ecc652d64250a30ec224f1a47355a6c/docs/moving-from-uptimerobot.md).
83
+ * [Oncall guide at 4f928effc3ce735f3d246bb8a3c4bbb8436cae6b](https://github.com/just-every/run-oncall/blob/4f928effc3ce735f3d246bb8a3c4bbb8436cae6b/docs/move-in.md).
84
+ * Spool's proposal-cited `app/docs/SENTRY-SWITCHING.md` and
85
+ `app/src/domain/sentry-import/source.ts`, local source commit
86
+ `39cbaf67de3bc8174bf941a6922bb92ff31110de`. Spool supplied a bundle contract,
87
+ not an existing downloader. This adapter implements that contract against
88
+ the official APIs below.
89
+ * Sentry: [projects](https://docs.sentry.io/api/organizations/list-an-organizations-projects/),
90
+ [releases](https://docs.sentry.io/api/releases/list-an-organizations-releases/),
91
+ [organization issues](https://docs.sentry.io/api/events/list-an-organizations-issues/),
92
+ [event details](https://docs.sentry.io/api/events/retrieve-an-event-for-a-project/),
93
+ [pagination](https://docs.sentry.io/api/pagination/),
94
+ [regional domains](https://docs.sentry.io/api/).
95
+ * [PagerDuty overrides](https://docs.pagerduty.com/developer/api/reference/rest/schedules/list-schedule-overrides)
96
+ is a window-bounded response, not an offset-paginated list.
97
+
98
+ Seed documentation and official APIs were inspected on 16 October 2026.
99
+ These sources document shapes; no real-account parity or migration success is
100
+ claimed. Parent integration must provide seed assembly and transport under the
101
+ actual import grant protocol, plus network-edge acceptance coverage.
@@ -0,0 +1,80 @@
1
+ import { object, list, id, timestamp, reference, cursor, assertCount, hash, shape, fail } from './common.mjs';
2
+
3
+ export const origin = 'https://api.calendly.com';
4
+ const queries = ['user','count','event_type','min_start_time','page_token'];
5
+ export const route = url => /^\/(?:users\/me|event_types|user_availability_schedules|event_type_availability_schedules|scheduled_events(?:\/[a-zA-Z0-9_-]+\/invitees)?)$/u.test(url.pathname) && [...url.searchParams.keys()].every(x => queries.includes(x));
6
+ function identity(uri, kind) {
7
+ const url = reference(uri, origin, new RegExp(`^/${kind}/[a-zA-Z0-9_-]+$`, 'u'));
8
+ return id(url.pathname.split('/').at(-1));
9
+ }
10
+ function nextToken(body, path, previous) {
11
+ object(body.pagination);
12
+ const next = body.pagination.next_page;
13
+ if (next == null) {
14
+ if (body.pagination.next_page_token != null) return cursor(body.pagination.next_page_token);
15
+ return null;
16
+ }
17
+ const url = reference(next, origin, new RegExp(`^${path}$`, 'u'), queries);
18
+ const token = cursor(url.searchParams.get('page_token'));
19
+ if (!token || token === previous) fail('INVALID_PAGINATION');
20
+ return token;
21
+ }
22
+ export async function* run(ctx) {
23
+ const s = ctx.state ?? { phase: 0, user: null, types: [], events: [], index: 0, token: null, seen: [], files: [], asOf: timestamp(ctx.inputs.asOf ?? new Date().toISOString()) };
24
+ shape(s, ['phase','user','types','events','index','token','seen','files','asOf']);
25
+ assertCount(s.phase, 7); assertCount(s.index, 500); timestamp(s.asOf); cursor(s.token);
26
+ if (!Array.isArray(s.types) || s.types.length > 100 || !Array.isArray(s.events) || s.events.length > 500 || !Array.isArray(s.files) || s.files.length > 600 || !Array.isArray(s.seen) || s.seen.length > 600) fail('INVALID_CHECKPOINT');
27
+ s.types.forEach(id); s.events.forEach(id); if (s.user !== null) id(s.user);
28
+ s.seen.forEach(cursor);
29
+ for (const file of s.files) {
30
+ shape(file, ['name','resource','page','size','sha256','capturedAt']);
31
+ if (typeof file.name !== 'string' || !/^(?:user|event_types|schedules|event_availability|scheduled_events|invitees)-\d{6}\.json$/u.test(file.name) || !['user','event_types','schedules','event_availability','scheduled_events','invitees'].includes(file.resource) || !/^[a-f0-9]{64}$/u.test(file.sha256) || file.capturedAt !== s.asOf) fail('INVALID_CHECKPOINT');
32
+ assertCount(file.page, 600); assertCount(file.size, 1024 * 1024);
33
+ }
34
+ while (s.phase < 7) {
35
+ if (s.phase === 3 && s.index >= s.types.length) { s.phase = 4; s.index = 0; }
36
+ if (s.phase === 5 && s.index >= s.events.length) s.phase = 6;
37
+ if (s.phase === 6) {
38
+ s.phase = 7;
39
+ yield ctx.item(JSON.stringify({ version: 1, capturedAt: s.asOf, files: s.files }) + '\n', s, 'manifest.json');
40
+ break;
41
+ }
42
+ const resource = ['user','event_types','schedules','event_availability','scheduled_events','invitees'][s.phase];
43
+ const path = ['/users/me','/event_types','/user_availability_schedules','/event_type_availability_schedules','/scheduled_events',`/scheduled_events/${s.events[s.index]}/invitees`][s.phase];
44
+ const query = new URLSearchParams();
45
+ if (s.phase !== 0) query.set('count', '100');
46
+ if ([1,2,4].includes(s.phase)) query.set('user', `${origin}/users/${id(s.user)}`);
47
+ if (s.phase === 3) query.set('event_type', `${origin}/event_types/${id(s.types[s.index])}`);
48
+ if (s.phase === 4) query.set('min_start_time', s.asOf);
49
+ if (s.token !== null) query.set('page_token', s.token);
50
+ const { body } = await ctx.get(path + (query.size ? `?${query}` : ''));
51
+ object(body);
52
+ const rows = s.phase === 0 ? [object(body.resource)] : list(body.collection);
53
+ if (rows.some(row => Buffer.byteLength(JSON.stringify(row)) > 512 * 1024)) fail('RECORD_BYTE_LIMIT');
54
+ ctx.records(rows.length);
55
+ if (s.phase === 0) s.user = identity(rows[0].uri, 'users');
56
+ if (s.phase === 1 || s.phase === 4) {
57
+ const values = s.phase === 1 ? s.types : s.events;
58
+ const kind = s.phase === 1 ? 'event_types' : 'scheduled_events';
59
+ for (const row of rows) {
60
+ const value = identity(row.uri, kind);
61
+ if (values.includes(value)) fail('DUPLICATE_ID');
62
+ values.push(value);
63
+ }
64
+ if (values.length > (s.phase === 1 ? 100 : 500)) fail('RECORD_LIMIT');
65
+ }
66
+ const next = s.phase === 0 ? null : nextToken(body, path, s.token);
67
+ if (next !== null && (next === s.token || s.seen.includes(next))) fail('PAGINATION_CYCLE');
68
+ const name = `${resource}-${String(s.files.length + 1).padStart(6,'0')}.json`;
69
+ const bytes = Buffer.from(JSON.stringify(body) + '\n');
70
+ if (s.files.length >= 600) fail('FILE_LIMIT');
71
+ s.files.push({ name, resource, page: s.seen.length + 1, size: bytes.length, sha256: hash(bytes), capturedAt: s.asOf });
72
+ s.token = next;
73
+ if (next === null) {
74
+ s.seen = [];
75
+ if (s.phase === 3 || s.phase === 5) s.index++;
76
+ else { s.phase++; s.index = 0; }
77
+ } else s.seen.push(next);
78
+ yield ctx.item(bytes, s, name);
79
+ }
80
+ }