@patchbay-nebius/agent 0.8.1 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +46 -7
- package/dist/cli.js.map +1 -1
- package/dist/oauth-login-E55CXA3X.js +214 -0
- package/dist/oauth-login-E55CXA3X.js.map +1 -0
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -109,18 +109,21 @@ Usage:
|
|
|
109
109
|
patchbay verify [--watch] <directory>
|
|
110
110
|
patchbay scan <directory> [--build-top=<n>] [--json]
|
|
111
111
|
patchbay audit <url|directory|--stdio "<cmd>"> [--json] [--sarif] [--pr-draft] [--out=<path>] [--publish] [--auth=<token>] [--probe-audience=<token>] [--probe-dcr-loopback] [--trust] [--ci] [--fail-on=<severity>] [--no-cta]
|
|
112
|
+
patchbay audit-oauth <url> [--client-id=<id>] [--scope=<s>] [--timeout=<seconds>] [--no-open] [--verbose] [plus any "patchbay audit" flag]
|
|
112
113
|
patchbay add <run-dir> [--target=<dir>]
|
|
113
114
|
patchbay push <run-dir> --repo=owner/name [--path=connectors/<name>] [--branch=<branch>] [--dry-run]
|
|
114
115
|
patchbay help
|
|
115
116
|
|
|
116
117
|
Commands:
|
|
117
|
-
build
|
|
118
|
-
research
|
|
119
|
-
verify
|
|
120
|
-
scan
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
118
|
+
build Full pipeline: plan \u2192 research \u2192 generate \u2192 verify (with repair). Default if you pass a prompt.
|
|
119
|
+
research Plan + API research only. Prints the spec, no code.
|
|
120
|
+
verify Type-check and vitest an existing connector folder (needs src/connector.ts + tests).
|
|
121
|
+
scan Walk a repo and report integration opportunities patchbay could build.
|
|
122
|
+
audit Scan an MCP server URL, --stdio command, or local directory for OAuth / security gaps.
|
|
123
|
+
audit-oauth Browser-based OAuth login first, then audit. Handles DCR + PKCE + loopback redirect for you.
|
|
124
|
+
add Drop a recorded run's connector files into another project.
|
|
125
|
+
push Open a pull request on a GitHub repo with the generated files.
|
|
126
|
+
help Show this message.
|
|
124
127
|
|
|
125
128
|
Flags:
|
|
126
129
|
--record build only. Writes runs/<timestamp>/ with generated files and the event log.
|
|
@@ -158,6 +161,7 @@ async function main() {
|
|
|
158
161
|
if (first === "push") return push(argv.slice(1));
|
|
159
162
|
if (first === "scan") return scan(argv.slice(1));
|
|
160
163
|
if (first === "audit") return audit(argv.slice(1));
|
|
164
|
+
if (first === "audit-oauth") return auditOauth(argv.slice(1));
|
|
161
165
|
switch (cmd) {
|
|
162
166
|
case "build":
|
|
163
167
|
return build(rest);
|
|
@@ -468,6 +472,41 @@ async function audit(args) {
|
|
|
468
472
|
}
|
|
469
473
|
}
|
|
470
474
|
}
|
|
475
|
+
async function auditOauth(args) {
|
|
476
|
+
const positional = args.filter((a) => !a.startsWith("--"));
|
|
477
|
+
const url = positional[0];
|
|
478
|
+
if (!url || !/^https?:\/\//i.test(url)) {
|
|
479
|
+
console.error("patchbay audit-oauth: missing or invalid URL");
|
|
480
|
+
console.error("usage: patchbay audit-oauth <url> [--client-id=<id>] [--scope=<s>] [--timeout=<seconds>] [--no-open] [--verbose] [any patchbay audit flag]");
|
|
481
|
+
process.exit(2);
|
|
482
|
+
}
|
|
483
|
+
const clientId = flagValue(args, "--client-id");
|
|
484
|
+
const scope = flagValue(args, "--scope");
|
|
485
|
+
const timeoutStr = flagValue(args, "--timeout");
|
|
486
|
+
const timeoutSeconds = timeoutStr ? Math.max(10, parseInt(timeoutStr, 10) || 300) : 300;
|
|
487
|
+
const noOpen = args.includes("--no-open");
|
|
488
|
+
const verbose = args.includes("--verbose");
|
|
489
|
+
const { loginAndGetToken } = await import("./oauth-login-E55CXA3X.js");
|
|
490
|
+
let token;
|
|
491
|
+
try {
|
|
492
|
+
const result = await loginAndGetToken(url, { clientId, scope, timeoutSeconds, noOpen, verbose });
|
|
493
|
+
process.stderr.write(" Got token (" + (result.scope ?? "no scope") + ", expires in " + (result.expiresIn ?? "?") + "s)\n\n");
|
|
494
|
+
token = result.accessToken;
|
|
495
|
+
} catch (e) {
|
|
496
|
+
console.error("patchbay audit-oauth: login failed - " + e.message);
|
|
497
|
+
process.exit(1);
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
const AUDIT_OAUTH_FLAGS = /* @__PURE__ */ new Set(["--client-id", "--scope", "--timeout", "--no-open", "--verbose"]);
|
|
501
|
+
const forwarded = args.filter((a) => {
|
|
502
|
+
const name = a.split("=")[0] ?? a;
|
|
503
|
+
if (AUDIT_OAUTH_FLAGS.has(name)) return false;
|
|
504
|
+
if (a.startsWith("--auth=")) return false;
|
|
505
|
+
return true;
|
|
506
|
+
});
|
|
507
|
+
forwarded.push("--auth=" + token);
|
|
508
|
+
return audit(forwarded);
|
|
509
|
+
}
|
|
471
510
|
function flagValue(args, flag) {
|
|
472
511
|
const match = args.find((a) => a.startsWith(`${flag}=`));
|
|
473
512
|
return match?.slice(flag.length + 1);
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts","../src/github-push.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, watch, writeFileSync } from 'node:fs'\nimport { basename, dirname, join, relative, resolve } from 'node:path'\nimport { loadConfig, missingLiveKeys } from './config'\nimport { pushToGitHub } from './github-push'\nimport { startResearch, startRun, startVerify } from './index'\nimport type { GeneratedFile, RunEvent } from './types'\n\nconst HELP = `patchbay – describe an integration, get a tested TypeScript connector.\n\nUsage:\n patchbay build [--record] \"<one-sentence integration>\"\n patchbay research \"<one-sentence integration>\"\n patchbay verify [--watch] <directory>\n patchbay scan <directory> [--build-top=<n>] [--json]\n patchbay audit <url|directory|--stdio \"<cmd>\"> [--json] [--sarif] [--pr-draft] [--out=<path>] [--publish] [--auth=<token>] [--probe-audience=<token>] [--probe-dcr-loopback] [--trust] [--ci] [--fail-on=<severity>] [--no-cta]\n patchbay add <run-dir> [--target=<dir>]\n patchbay push <run-dir> --repo=owner/name [--path=connectors/<name>] [--branch=<branch>] [--dry-run]\n patchbay help\n\nCommands:\n build Full pipeline: plan → research → generate → verify (with repair). Default if you pass a prompt.\n research Plan + API research only. Prints the spec, no code.\n verify Type-check and vitest an existing connector folder (needs src/connector.ts + tests).\n scan Walk a repo and report integration opportunities patchbay could build.\n add Drop a recorded run's connector files into another project.\n push Open a pull request on a GitHub repo with the generated files.\n help Show this message.\n\nFlags:\n --record build only. Writes runs/<timestamp>/ with generated files and the event log.\n --lang=ts|py build/research only. Target language. Default ts (TypeScript+vitest); py writes\n Python 3.12 + pytest. Also settable via PATCHBAY_LANG=python.\n --watch verify only. Re-runs the sandbox verify whenever a source file in <directory> changes.\n verify auto-detects the language from the directory (src/connector.ts → TypeScript,\n connector.py → Python). Pass --lang= to override if both are present.\n --build-top scan only. After reporting, build the top-N opportunities (full pipeline each).\n Combine with --lang=python to build the top-N in Python.\n --json scan only. Emit the raw opportunity list as JSON instead of the formatted report.\n --target add only. Where to drop the files, defaults to ./connectors/<run-name>.\n --repo push only. owner/name of the target GitHub repo.\n --path push only. Where to drop the files inside the repo, defaults to connectors/<run-name>.\n --branch push only. Branch name to create, defaults to patchbay/<run-name>.\n --dry-run push only. Print the plan without hitting the GitHub API.\n\nEnvironment:\n NEBIUS_API_KEY, NEBIUS_AI_PROJECT, TAVILY_API_KEY – required for live runs.\n PATCHBAY_MOCK=false – enable live mode (default is replay).\n PATCHBAY_RUNNER=local|nebius – default nebius (isolated sandbox).\n PATCHBAY_MAX_ATTEMPTS=<n> – repair attempts, default 3.\n`\n\nasync function main() {\n const argv = process.argv.slice(2)\n const first = argv[0]\n\n if (!first || first === 'help' || first === '--help' || first === '-h') {\n console.log(HELP)\n return\n }\n\n // Backwards-compat: bare prompt = build\n const known = new Set(['build', 'research', 'verify'])\n const cmd = known.has(first) ? first : 'build'\n const rest = known.has(first) ? argv.slice(1) : argv\n\n if (first === 'add') return add(argv.slice(1))\n if (first === 'push') return push(argv.slice(1))\n if (first === 'scan') return scan(argv.slice(1))\n if (first === 'audit') return audit(argv.slice(1))\n\n switch (cmd) {\n case 'build':\n return build(rest)\n case 'research':\n return research(rest)\n case 'verify':\n return verify(rest)\n }\n}\n\nasync function scan(args: string[]) {\n const positional = args.filter((a) => !a.startsWith('--'))\n const langFlag = flagValue(args, '--lang')\n let dir = positional[0] ? resolve(positional[0]) : process.cwd()\n // Accept GitHub URLs: shallow-clone into a tmp dir so judges can scan a\n // random repo without cloning it themselves.\n const first = positional[0] ?? ''\n if (/^https?:\\/\\/github\\.com\\//i.test(first) || /^git@github\\.com:/i.test(first)) {\n const { tmpdir } = await import('node:os')\n const { execSync } = await import('node:child_process')\n const target = join(tmpdir(), `patchbay-scan-${Date.now()}`)\n console.log(`cloning ${first} → ${target} (shallow)…`)\n execSync(`git clone --depth=1 \"${first}\" \"${target}\"`, { stdio: 'inherit' })\n dir = target\n }\n if (!existsSync(dir)) return usageError(`No such directory: ${dir}`)\n const asJson = args.includes('--json')\n const buildTopArg = args.find((a) => a.startsWith('--build-top='))\n const buildTop = buildTopArg ? Math.max(0, Number(buildTopArg.slice('--build-top='.length))) : 0\n\n const { scanRepo, formatReport } = await import('./scanner')\n const opportunities = scanRepo(dir)\n const showAll = args.includes('--all')\n if (asJson) {\n console.log(JSON.stringify(opportunities, null, 2))\n } else {\n console.log(formatReport(opportunities, dir, showAll ? opportunities.length : undefined))\n }\n\n if (buildTop > 0 && opportunities.length) {\n const top = opportunities.slice(0, buildTop)\n const langLabel = langFlag ? ` as ${/^py/i.test(langFlag) ? 'Python' : 'TypeScript'}` : ''\n console.log(`\\nBuilding top ${top.length} opportunit${top.length === 1 ? 'y' : 'ies'}${langLabel}…\\n`)\n for (const [i, op] of top.entries()) {\n console.log(`\\n──── (${i + 1}/${top.length}) ${op.file}:${op.line} ────`)\n // Pass --lang through to the inner build; it comes from this scan's --lang flag.\n await build(langFlag ? ['--record', `--lang=${langFlag}`, op.prompt] : ['--record', op.prompt])\n }\n }\n}\n\n/**\n * Copy the files from a recorded run (`runs/<timestamp>/`) into a target\n * project. Default target is ./connectors/<run-basename>, so repeated adds\n * don't overwrite each other.\n */\nasync function add(args: string[]) {\n const positional = args.filter((a) => !a.startsWith('--'))\n const flag = args.find((a) => a.startsWith('--target='))\n const runDir = positional[0] ? resolve(positional[0]) : ''\n if (!runDir) return usageError('add needs a run directory (e.g. runs/<timestamp>)')\n if (!existsSync(runDir)) return usageError(`No such directory: ${runDir}`)\n // TS runs ship src/connector.ts + src/connector.test.ts + src/fixtures.ts + README.md at the top.\n // Python runs ship connector.py + test_connector.py + fixtures.py + README.md at the top (no src/).\n const tsConnector = join(runDir, 'src', 'connector.ts')\n const pyConnector = join(runDir, 'connector.py')\n const kind: 'ts' | 'py' = existsSync(pyConnector) ? 'py' : existsSync(tsConnector) ? 'ts' : (() => { usageError(`${runDir} does not look like a patchbay run (no src/connector.ts and no connector.py)`); throw new Error('unreachable') })()\n const target = flag ? resolve(flag.slice('--target='.length)) : resolve(process.cwd(), 'connectors', basename(runDir))\n if (existsSync(target)) {\n console.error(`Refusing to overwrite ${target}. Pass --target=<fresh-dir> or move the existing folder out of the way.`)\n process.exit(1)\n }\n mkdirSync(target, { recursive: true })\n let copiedList: string[] = []\n if (kind === 'ts') {\n const srcDir = join(runDir, 'src')\n cpSync(srcDir, join(target, 'src'), { recursive: true })\n copiedList = readdirSync(join(target, 'src')).map((f) => `src/${f}`)\n } else {\n // Python files live at the run-dir root alongside README.md.\n for (const name of ['connector.py', 'test_connector.py', 'fixtures.py']) {\n const abs = join(runDir, name)\n if (existsSync(abs)) {\n cpSync(abs, join(target, name))\n copiedList.push(name)\n }\n }\n }\n const readme = join(runDir, 'README.md')\n if (existsSync(readme)) cpSync(readme, join(target, 'README.md'))\n const totalCopied = copiedList.length + (existsSync(readme) ? 1 : 0)\n console.log(`✔ Copied ${totalCopied} ${kind === 'py' ? 'Python' : 'TypeScript'} files to ${target}`)\n for (const name of copiedList) console.log(` ${name}`)\n if (existsSync(readme)) console.log(' README.md')\n console.log(`\\nTests should already pass unchanged — the connector is self-contained and uses an injected ${kind === 'py' ? 'async transport' : 'fetch'}.`)\n if (kind === 'py') {\n console.log(`Make sure pytest + pytest-asyncio are available where you run the tests (or wire them into your existing suite).`)\n } else {\n console.log(`Add vitest and typescript as dev deps where you'll run them, or wire this into your existing suite.`)\n }\n}\n\nasync function build(args: string[]) {\n const record = args.includes('--record')\n const langFlag = flagValue(args, '--lang')\n const prompt = args.filter((a) => a !== '--record' && !a.startsWith('--lang')).join(' ').trim()\n if (!prompt) return usageError('build needs a prompt')\n\n const config = loadConfig(withLangEnv(process.env, langFlag))\n const missing = missingLiveKeys(config)\n if (config.mock || missing.length) {\n console.log(`Replay mode (${config.mock ? 'PATCHBAY_MOCK is not \"false\"' : `missing ${missing.join(', ')}`})`)\n }\n\n const events: RunEvent[] = []\n for await (const event of startRun(prompt, config)) {\n events.push(event)\n printEvent(event)\n }\n\n if (record) {\n const dir = join(process.cwd(), 'runs', new Date().toISOString().replace(/[:.]/g, '-'))\n const result = events.find((e) => e.type === 'result')\n for (const file of result?.type === 'result' ? result.files : []) {\n mkdirSync(dirname(join(dir, file.path)), { recursive: true })\n writeFileSync(join(dir, file.path), file.content)\n }\n mkdirSync(dir, { recursive: true })\n writeFileSync(join(dir, 'run.json'), JSON.stringify({ prompt, origin: 'live', events }, null, 2))\n console.log(`\\nRecorded to ${dir}`)\n }\n}\n\nasync function research(args: string[]) {\n const langFlag = flagValue(args, '--lang')\n const prompt = args.filter((a) => !a.startsWith('--lang')).join(' ').trim()\n if (!prompt) return usageError('research needs a prompt')\n const config = loadConfig(withLangEnv(process.env, langFlag))\n const missing = missingLiveKeys(config)\n if (config.mock || missing.length) {\n console.log(`Replay mode (${config.mock ? 'PATCHBAY_MOCK is not \"false\"' : `missing ${missing.join(', ')}`}) – returning cached research`)\n }\n for await (const event of startResearch(prompt, config)) {\n printEvent(event)\n if (event.type === 'spec') {\n console.log('\\nSpec:')\n console.log(JSON.stringify(event.spec, null, 2))\n }\n }\n}\n\nasync function verify(args: string[]) {\n const watchMode = args.includes('--watch')\n const langFlag = flagValue(args, '--lang')\n const positional = args.filter((a) => !a.startsWith('--'))\n const dir = positional[0] ? resolve(positional[0]) : ''\n if (!dir) return usageError('verify needs a directory')\n const dirFiles = collectFiles(dir)\n const hasTs = dirFiles.some((f) => f.path === 'src/connector.ts')\n const hasPy = dirFiles.some((f) => f.path === 'connector.py')\n if (!hasTs && !hasPy) {\n return usageError(`No connector found under ${dir} (expected src/connector.ts for TypeScript or connector.py for Python)`)\n }\n // Auto-detect: a Python connector.py beats the TS fallback.\n // Explicit --lang overrides detection in case someone has both.\n const detectedLang = hasPy && !hasTs ? 'py' : hasPy && hasTs ? undefined : 'ts'\n const effectiveLangFlag = langFlag ?? detectedLang\n if (!effectiveLangFlag) {\n return usageError(`${dir} contains both src/connector.ts and connector.py; pass --lang=ts or --lang=py to pick one`)\n }\n const config = loadConfig(withLangEnv(process.env, effectiveLangFlag))\n const missing = missingLiveKeys(config)\n if (config.mock || missing.length) {\n console.error(`verify needs live keys. Set PATCHBAY_MOCK=false and provide ${missing.join(', ') || 'the missing env vars'}.`)\n process.exit(1)\n }\n\n const runOnce = async () => {\n const files = collectFiles(dir)\n console.log(`\\nVerifying ${files.length} files from ${dir}`)\n for await (const event of startVerify(files, config)) printEvent(event)\n }\n\n await runOnce()\n if (!watchMode) return\n\n console.log(`\\nWatching ${dir} for .ts changes. Ctrl+C to exit.`)\n let running = false\n let rerun = false\n // Native fs.watch is good enough: debounced to avoid thrashing when an editor\n // saves multiple files in quick succession.\n let pending: NodeJS.Timeout | null = null\n const trigger = () => {\n if (pending) clearTimeout(pending)\n pending = setTimeout(async () => {\n pending = null\n if (running) { rerun = true; return }\n running = true\n try { await runOnce() } finally {\n running = false\n if (rerun) { rerun = false; trigger() }\n }\n }, 400)\n }\n watch(dir, { recursive: true }, (_, filename) => {\n if (filename && (filename.endsWith('.ts') || filename.endsWith('.json'))) trigger()\n })\n await new Promise(() => {}) // keep the process alive\n}\n\nasync function push(args: string[]) {\n const positional = args.filter((a) => !a.startsWith('--'))\n const runDir = positional[0] ? resolve(positional[0]) : ''\n if (!runDir) return usageError('push needs a run directory')\n const repo = flagValue(args, '--repo')\n if (!repo) return usageError('push needs --repo=owner/name')\n const target = flagValue(args, '--path') ?? `connectors/${basename(runDir)}`\n const branch = flagValue(args, '--branch')\n const dryRun = args.includes('--dry-run')\n const token = process.env.GH_TOKEN || process.env.GITHUB_TOKEN\n if (!token && !dryRun) {\n return usageError('push needs GH_TOKEN (or GITHUB_TOKEN) in the environment, with repo scope on the target.')\n }\n try {\n const result = await pushToGitHub({\n runDir, repo, token: token ?? '', targetPath: target,\n ...(branch ? { branch } : {}),\n dryRun,\n })\n console.log(dryRun ? '✔ Dry run:' : '✔ Opened pull request:')\n console.log(` URL: ${result.prUrl}`)\n console.log(` branch: ${result.branch} (base: ${result.base})`)\n console.log(` files: ${result.files.length} under ${target}/`)\n for (const path of result.files) console.log(` ${path}`)\n } catch (error) {\n console.error(error instanceof Error ? error.message : String(error))\n process.exit(1)\n }\n}\n\nasync function audit(args: string[]) {\n const positional = args.filter((a) => !a.startsWith('--'))\n const stdioCmd = flagValue(args, '--stdio')\n const target = stdioCmd ?? positional[0]\n if (!target) {\n console.error('patchbay audit: missing target (url, directory, or --stdio \"<command>\")')\n console.error('usage: patchbay audit <url|dir> [--stdio \"<cmd>\"] [--json] [--sarif] [--pr-draft] [--out=<path>] [--auth=<token>] [--probe-audience=<token>] [--probe-dcr-loopback] [--trust] [--ci] [--no-cta]')\n process.exit(2)\n }\n const asJson = args.includes('--json')\n const asSarif = args.includes('--sarif')\n const asPrDraft = args.includes('--pr-draft')\n const outPath = flagValue(args, '--out')\n const authToken = flagValue(args, '--auth') ?? process.env.PATCHBAY_AUDIT_TOKEN\n const probeAudienceToken = flagValue(args, '--probe-audience') ?? process.env.PATCHBAY_PROBE_AUDIENCE_TOKEN\n const probeMissingAudToken = flagValue(args, '--probe-missing-aud') ?? process.env.PATCHBAY_PROBE_MISSING_AUD_TOKEN\n const probeDcrLoopback = args.includes('--probe-dcr-loopback') || process.env.PATCHBAY_PROBE_DCR_LOOPBACK === '1'\n const probeHeadlessOauth = args.includes('--probe-headless-oauth') || process.env.PATCHBAY_PROBE_HEADLESS_OAUTH === '1'\n const trustCurrentManifest = args.includes('--trust')\n const publish = args.includes('--publish')\n const ci = args.includes('--ci')\n const failOnRaw = flagValue(args, '--fail-on')\n const noCta = args.includes('--no-cta')\n const stdio = Boolean(stdioCmd)\n\n const FAIL_SEVERITIES = ['critical', 'high', 'medium', 'low', 'info'] as const\n type FailSeverity = typeof FAIL_SEVERITIES[number]\n let failOn: FailSeverity | undefined\n if (failOnRaw) {\n if (!(FAIL_SEVERITIES as readonly string[]).includes(failOnRaw)) {\n console.error(`patchbay audit: --fail-on must be one of ${FAIL_SEVERITIES.join(', ')}`)\n process.exit(2)\n }\n failOn = failOnRaw as FailSeverity\n }\n\n const { auditTarget, renderTerminal, renderJson, renderSarif, renderMarkdown } = await import('@patchbay-nebius/audit-core')\n const resolved = stdio ? target : (/^https?:\\/\\//i.test(target) ? target : resolve(target))\n const report = await auditTarget(resolved, { authToken, trustCurrentManifest, probeAudienceToken, probeMissingAudToken, probeDcrLoopback, probeHeadlessOauth, stdio })\n\n if (publish) {\n try {\n const base = process.env.PATCHBAY_PUBLISH_URL || 'https://patchbay-mcp.dev'\n const res = await fetch(`${base}/api/report`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(report),\n })\n if (res.ok) {\n const j = (await res.json()) as { url?: string; id?: string }\n if (j.url) console.error(`Published report: ${j.url}`)\n } else {\n console.error(`Publish failed: HTTP ${res.status}`)\n }\n } catch (e) {\n console.error(`Publish failed: ${(e as Error).message}`)\n }\n }\n\n let rendered: string\n if (asJson) rendered = renderJson(report)\n else if (asSarif) rendered = renderSarif(report)\n else if (asPrDraft) rendered = renderMarkdown(report)\n else rendered = renderTerminal(report, { showCta: !noCta })\n\n if (outPath) {\n writeFileSync(resolve(outPath), rendered, 'utf8')\n console.error(`wrote ${rendered.length} bytes to ${outPath}`)\n } else {\n console.log(rendered)\n }\n\n if (ci && (report.summary.critical > 0 || report.summary.high > 0)) {\n process.exit(1)\n }\n\n if (failOn) {\n // Exit 1 if there is at least one finding at or above `failOn` severity.\n // Order: critical > high > medium > low > info. --fail-on=high counts crit + high.\n const idx = FAIL_SEVERITIES.indexOf(failOn)\n const triggerSeverities = FAIL_SEVERITIES.slice(0, idx + 1)\n const total = triggerSeverities.reduce((n, s) => n + (report.summary[s] ?? 0), 0)\n if (total > 0) {\n console.error(`patchbay: ${total} finding(s) at severity ${failOn} or higher. Exiting 1.`)\n process.exit(1)\n }\n }\n}\n\nfunction flagValue(args: string[], flag: string): string | undefined {\n const match = args.find((a) => a.startsWith(`${flag}=`))\n return match?.slice(flag.length + 1)\n}\n\nfunction withLangEnv(env: NodeJS.ProcessEnv, langFlag: string | undefined): NodeJS.ProcessEnv {\n if (!langFlag) return env\n return { ...env, PATCHBAY_LANG: langFlag }\n}\n\nfunction collectFiles(root: string): GeneratedFile[] {\n const out: GeneratedFile[] = []\n const walk = (dir: string) => {\n for (const entry of readdirSync(dir)) {\n if (entry === 'node_modules' || entry.startsWith('.')) continue\n const abs = join(dir, entry)\n const st = statSync(abs)\n if (st.isDirectory()) walk(abs)\n else if (entry.endsWith('.ts') || entry.endsWith('.py') || entry === 'README.md') {\n out.push({ path: relative(root, abs).replace(/\\\\/g, '/'), content: readFileSync(abs, 'utf8') })\n }\n }\n }\n walk(root)\n return out\n}\n\nfunction usageError(message: string): void {\n console.error(`Error: ${message}\\n`)\n console.error(HELP)\n process.exit(1)\n}\n\nfunction printEvent(event: RunEvent) {\n switch (event.type) {\n case 'step':\n console.log(`${event.status === 'start' ? '▶' : event.status === 'done' ? '✔' : '✖'} ${event.step}${event.detail ? ` — ${event.detail}` : ''}`)\n break\n case 'log':\n console.log(` ${event.message}`)\n break\n case 'tests':\n console.log(` attempt ${event.attempt}: ${event.report.passed}/${event.report.total} passed, typecheck ${event.report.typecheckOk ? 'ok' : 'failed'}`)\n for (const f of event.report.failures) {\n console.log(` ✖ ${f.name}`)\n if (process.env.PATCHBAY_VERBOSE === '1' && f.message) {\n for (const line of f.message.split('\\n').slice(0, 20)) console.log(` ${line}`)\n }\n }\n break\n case 'usage':\n for (const u of event.usage) console.log(` ${u.model}: ${u.promptTokens} in / ${u.completionTokens} out, $${u.costUsd.toFixed(4)}`)\n break\n case 'error':\n console.error(`Error: ${event.message}`)\n break\n }\n}\n\nmain().catch((error) => {\n console.error(error)\n process.exit(1)\n})\n","import { readdirSync, readFileSync, statSync } from 'node:fs'\nimport { join, relative } from 'node:path'\n\nexport interface PushOptions {\n runDir: string\n repo: string // \"owner/name\"\n token: string\n /** Where inside the target repo the connector files land. */\n targetPath: string // e.g. \"connectors/typeform-pipedrive\"\n /** Branch to create. Defaults to patchbay/<basename(runDir)>. */\n branch?: string\n /** Base branch to branch from. GitHub defaults it to the repo's default. */\n base?: string\n /** PR title + body overrides. */\n title?: string\n body?: string\n /** Set true to log what would happen without hitting the API. */\n dryRun?: boolean\n}\n\nexport interface PushResult {\n prUrl: string\n branch: string\n base: string\n files: string[]\n}\n\nconst API = 'https://api.github.com'\n\n/**\n * Takes a recorded patchbay run (runs/<timestamp>/ with src/* + README.md) and lands it in a\n * target GitHub repo as a pull request: new branch, commits every file under `targetPath`,\n * opens a PR against the repo's default branch.\n *\n * Uses the GitHub REST API directly (fetch + token). The token needs `repo` scope on the\n * target. Dry-run prints the plan without calling the API.\n */\nexport async function pushToGitHub(opts: PushOptions): Promise<PushResult> {\n const files = collectRunFiles(opts.runDir)\n if (files.length === 0) {\n throw new Error(`${opts.runDir} has no files to push (expected src/* and README.md for TS, or connector.py + test_connector.py + fixtures.py + README.md for Python).`)\n }\n\n const [owner, name] = opts.repo.split('/')\n if (!owner || !name) throw new Error(`Expected --repo=owner/name, got \"${opts.repo}\"`)\n\n const branch = opts.branch ?? `patchbay/${basenameNoSlash(opts.runDir)}`\n const title = opts.title ?? `patchbay: ${opts.targetPath}`\n const body =\n opts.body ??\n `Generated by [patchbay](https://github.com/GodSmasher/patchbay) from \\`${basenameNoSlash(opts.runDir)}\\`.\\n\\n` +\n `Includes ${files.length} files under \\`${opts.targetPath}/\\`. Tests pass against the documented example in a hermetic sandbox.`\n\n if (opts.dryRun) {\n return { prUrl: `(dry-run) would open PR on ${opts.repo}`, branch, base: opts.base ?? '(default)', files: files.map((f) => f.path) }\n }\n\n const api = createApi(opts.token)\n const repo = (await api(`/repos/${owner}/${name}`)) as { default_branch: string }\n const base = opts.base ?? repo.default_branch\n const baseRef = (await api(`/repos/${owner}/${name}/git/ref/heads/${base}`)) as { object: { sha: string } }\n const baseSha = baseRef.object.sha\n\n // Create the branch (409 if it already exists, we tolerate that).\n try {\n await api(`/repos/${owner}/${name}/git/refs`, {\n method: 'POST',\n body: { ref: `refs/heads/${branch}`, sha: baseSha },\n })\n } catch (error) {\n if (!/already exists/i.test(String(error))) throw error\n }\n\n // One commit per file keeps the diff readable; could be batched into a tree later if it matters.\n for (const file of files) {\n const path = `${opts.targetPath}/${file.path}`.replace(/\\\\/g, '/')\n const existing = (await api(`/repos/${owner}/${name}/contents/${encodeURIComponent(path)}?ref=${branch}`).catch(() => null)) as { sha?: string } | null\n await api(`/repos/${owner}/${name}/contents/${encodeURIComponent(path)}`, {\n method: 'PUT',\n body: {\n message: `patchbay: ${path}`,\n content: Buffer.from(file.content, 'utf8').toString('base64'),\n branch,\n ...(existing?.sha ? { sha: existing.sha } : {}),\n },\n })\n }\n\n const pr = (await api(`/repos/${owner}/${name}/pulls`, {\n method: 'POST',\n body: { title, head: branch, base, body, draft: false },\n })) as { html_url: string }\n\n return { prUrl: pr.html_url, branch, base, files: files.map((f) => f.path) }\n}\n\ninterface RunFile {\n path: string\n content: string\n}\n\nfunction collectRunFiles(root: string): RunFile[] {\n const out: RunFile[] = []\n const walk = (dir: string) => {\n for (const entry of readdirSync(dir)) {\n if (entry === 'run.json' || entry.startsWith('.')) continue\n const abs = join(dir, entry)\n const st = statSync(abs)\n if (st.isDirectory()) walk(abs)\n else out.push({ path: relative(root, abs).replace(/\\\\/g, '/'), content: readFileSync(abs, 'utf8') })\n }\n }\n walk(root)\n return out\n}\n\nfunction basenameNoSlash(path: string): string {\n return path.replace(/[\\\\/]+$/, '').split(/[\\\\/]/).pop() ?? 'run'\n}\n\nfunction createApi(token: string) {\n return async <T = unknown>(path: string, init: { method?: string; body?: unknown } = {}): Promise<T> => {\n const res = await fetch(`${API}${path}`, {\n method: init.method ?? 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n Accept: 'application/vnd.github+json',\n 'X-GitHub-Api-Version': '2022-11-28',\n 'User-Agent': 'patchbay-cli',\n ...(init.body ? { 'Content-Type': 'application/json' } : {}),\n },\n body: init.body ? JSON.stringify(init.body) : undefined,\n })\n const text = await res.text()\n const data = text ? JSON.parse(text) : {}\n if (!res.ok) throw new Error(`GitHub ${init.method ?? 'GET'} ${path}: HTTP ${res.status} ${(data as { message?: string }).message ?? text.slice(0, 200)}`)\n return data as T\n }\n}\n"],"mappings":";;;;;;;;;;;AACA,SAAS,QAAQ,YAAY,WAAW,eAAAA,cAAa,gBAAAC,eAAc,YAAAC,WAAU,OAAO,qBAAqB;AACzG,SAAS,UAAU,SAAS,QAAAC,OAAM,YAAAC,WAAU,eAAe;;;ACF3D,SAAS,aAAa,cAAc,gBAAgB;AACpD,SAAS,MAAM,gBAAgB;AA0B/B,IAAM,MAAM;AAUZ,eAAsB,aAAa,MAAwC;AACzE,QAAM,QAAQ,gBAAgB,KAAK,MAAM;AACzC,MAAI,MAAM,WAAW,GAAG;AACtB,UAAM,IAAI,MAAM,GAAG,KAAK,MAAM,wIAAwI;AAAA,EACxK;AAEA,QAAM,CAAC,OAAO,IAAI,IAAI,KAAK,KAAK,MAAM,GAAG;AACzC,MAAI,CAAC,SAAS,CAAC,K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AAEA,KAAK,EAAE,MAAM,CAAC,UAAU;AACtB,UAAQ,MAAM,KAAK;AACnB,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["readdirSync","readFileSync","statSync","join","relative","join","readdirSync","statSync","relative","readFileSync"]}
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts","../src/github-push.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, watch, writeFileSync } from 'node:fs'\nimport { basename, dirname, join, relative, resolve } from 'node:path'\nimport { loadConfig, missingLiveKeys } from './config'\nimport { pushToGitHub } from './github-push'\nimport { startResearch, startRun, startVerify } from './index'\nimport type { GeneratedFile, RunEvent } from './types'\n\nconst HELP = `patchbay – describe an integration, get a tested TypeScript connector.\n\nUsage:\n patchbay build [--record] \"<one-sentence integration>\"\n patchbay research \"<one-sentence integration>\"\n patchbay verify [--watch] <directory>\n patchbay scan <directory> [--build-top=<n>] [--json]\n patchbay audit <url|directory|--stdio \"<cmd>\"> [--json] [--sarif] [--pr-draft] [--out=<path>] [--publish] [--auth=<token>] [--probe-audience=<token>] [--probe-dcr-loopback] [--trust] [--ci] [--fail-on=<severity>] [--no-cta]\n patchbay audit-oauth <url> [--client-id=<id>] [--scope=<s>] [--timeout=<seconds>] [--no-open] [--verbose] [plus any \"patchbay audit\" flag]\n patchbay add <run-dir> [--target=<dir>]\n patchbay push <run-dir> --repo=owner/name [--path=connectors/<name>] [--branch=<branch>] [--dry-run]\n patchbay help\n\nCommands:\n build Full pipeline: plan → research → generate → verify (with repair). Default if you pass a prompt.\n research Plan + API research only. Prints the spec, no code.\n verify Type-check and vitest an existing connector folder (needs src/connector.ts + tests).\n scan Walk a repo and report integration opportunities patchbay could build.\n audit Scan an MCP server URL, --stdio command, or local directory for OAuth / security gaps.\n audit-oauth Browser-based OAuth login first, then audit. Handles DCR + PKCE + loopback redirect for you.\n add Drop a recorded run's connector files into another project.\n push Open a pull request on a GitHub repo with the generated files.\n help Show this message.\n\nFlags:\n --record build only. Writes runs/<timestamp>/ with generated files and the event log.\n --lang=ts|py build/research only. Target language. Default ts (TypeScript+vitest); py writes\n Python 3.12 + pytest. Also settable via PATCHBAY_LANG=python.\n --watch verify only. Re-runs the sandbox verify whenever a source file in <directory> changes.\n verify auto-detects the language from the directory (src/connector.ts → TypeScript,\n connector.py → Python). Pass --lang= to override if both are present.\n --build-top scan only. After reporting, build the top-N opportunities (full pipeline each).\n Combine with --lang=python to build the top-N in Python.\n --json scan only. Emit the raw opportunity list as JSON instead of the formatted report.\n --target add only. Where to drop the files, defaults to ./connectors/<run-name>.\n --repo push only. owner/name of the target GitHub repo.\n --path push only. Where to drop the files inside the repo, defaults to connectors/<run-name>.\n --branch push only. Branch name to create, defaults to patchbay/<run-name>.\n --dry-run push only. Print the plan without hitting the GitHub API.\n\nEnvironment:\n NEBIUS_API_KEY, NEBIUS_AI_PROJECT, TAVILY_API_KEY – required for live runs.\n PATCHBAY_MOCK=false – enable live mode (default is replay).\n PATCHBAY_RUNNER=local|nebius – default nebius (isolated sandbox).\n PATCHBAY_MAX_ATTEMPTS=<n> – repair attempts, default 3.\n`\n\nasync function main() {\n const argv = process.argv.slice(2)\n const first = argv[0]\n\n if (!first || first === 'help' || first === '--help' || first === '-h') {\n console.log(HELP)\n return\n }\n\n // Backwards-compat: bare prompt = build\n const known = new Set(['build', 'research', 'verify'])\n const cmd = known.has(first) ? first : 'build'\n const rest = known.has(first) ? argv.slice(1) : argv\n\n if (first === 'add') return add(argv.slice(1))\n if (first === 'push') return push(argv.slice(1))\n if (first === 'scan') return scan(argv.slice(1))\n if (first === 'audit') return audit(argv.slice(1))\n if (first === 'audit-oauth') return auditOauth(argv.slice(1))\n\n switch (cmd) {\n case 'build':\n return build(rest)\n case 'research':\n return research(rest)\n case 'verify':\n return verify(rest)\n }\n}\n\nasync function scan(args: string[]) {\n const positional = args.filter((a) => !a.startsWith('--'))\n const langFlag = flagValue(args, '--lang')\n let dir = positional[0] ? resolve(positional[0]) : process.cwd()\n // Accept GitHub URLs: shallow-clone into a tmp dir so judges can scan a\n // random repo without cloning it themselves.\n const first = positional[0] ?? ''\n if (/^https?:\\/\\/github\\.com\\//i.test(first) || /^git@github\\.com:/i.test(first)) {\n const { tmpdir } = await import('node:os')\n const { execSync } = await import('node:child_process')\n const target = join(tmpdir(), `patchbay-scan-${Date.now()}`)\n console.log(`cloning ${first} → ${target} (shallow)…`)\n execSync(`git clone --depth=1 \"${first}\" \"${target}\"`, { stdio: 'inherit' })\n dir = target\n }\n if (!existsSync(dir)) return usageError(`No such directory: ${dir}`)\n const asJson = args.includes('--json')\n const buildTopArg = args.find((a) => a.startsWith('--build-top='))\n const buildTop = buildTopArg ? Math.max(0, Number(buildTopArg.slice('--build-top='.length))) : 0\n\n const { scanRepo, formatReport } = await import('./scanner')\n const opportunities = scanRepo(dir)\n const showAll = args.includes('--all')\n if (asJson) {\n console.log(JSON.stringify(opportunities, null, 2))\n } else {\n console.log(formatReport(opportunities, dir, showAll ? opportunities.length : undefined))\n }\n\n if (buildTop > 0 && opportunities.length) {\n const top = opportunities.slice(0, buildTop)\n const langLabel = langFlag ? ` as ${/^py/i.test(langFlag) ? 'Python' : 'TypeScript'}` : ''\n console.log(`\\nBuilding top ${top.length} opportunit${top.length === 1 ? 'y' : 'ies'}${langLabel}…\\n`)\n for (const [i, op] of top.entries()) {\n console.log(`\\n──── (${i + 1}/${top.length}) ${op.file}:${op.line} ────`)\n // Pass --lang through to the inner build; it comes from this scan's --lang flag.\n await build(langFlag ? ['--record', `--lang=${langFlag}`, op.prompt] : ['--record', op.prompt])\n }\n }\n}\n\n/**\n * Copy the files from a recorded run (`runs/<timestamp>/`) into a target\n * project. Default target is ./connectors/<run-basename>, so repeated adds\n * don't overwrite each other.\n */\nasync function add(args: string[]) {\n const positional = args.filter((a) => !a.startsWith('--'))\n const flag = args.find((a) => a.startsWith('--target='))\n const runDir = positional[0] ? resolve(positional[0]) : ''\n if (!runDir) return usageError('add needs a run directory (e.g. runs/<timestamp>)')\n if (!existsSync(runDir)) return usageError(`No such directory: ${runDir}`)\n // TS runs ship src/connector.ts + src/connector.test.ts + src/fixtures.ts + README.md at the top.\n // Python runs ship connector.py + test_connector.py + fixtures.py + README.md at the top (no src/).\n const tsConnector = join(runDir, 'src', 'connector.ts')\n const pyConnector = join(runDir, 'connector.py')\n const kind: 'ts' | 'py' = existsSync(pyConnector) ? 'py' : existsSync(tsConnector) ? 'ts' : (() => { usageError(`${runDir} does not look like a patchbay run (no src/connector.ts and no connector.py)`); throw new Error('unreachable') })()\n const target = flag ? resolve(flag.slice('--target='.length)) : resolve(process.cwd(), 'connectors', basename(runDir))\n if (existsSync(target)) {\n console.error(`Refusing to overwrite ${target}. Pass --target=<fresh-dir> or move the existing folder out of the way.`)\n process.exit(1)\n }\n mkdirSync(target, { recursive: true })\n let copiedList: string[] = []\n if (kind === 'ts') {\n const srcDir = join(runDir, 'src')\n cpSync(srcDir, join(target, 'src'), { recursive: true })\n copiedList = readdirSync(join(target, 'src')).map((f) => `src/${f}`)\n } else {\n // Python files live at the run-dir root alongside README.md.\n for (const name of ['connector.py', 'test_connector.py', 'fixtures.py']) {\n const abs = join(runDir, name)\n if (existsSync(abs)) {\n cpSync(abs, join(target, name))\n copiedList.push(name)\n }\n }\n }\n const readme = join(runDir, 'README.md')\n if (existsSync(readme)) cpSync(readme, join(target, 'README.md'))\n const totalCopied = copiedList.length + (existsSync(readme) ? 1 : 0)\n console.log(`✔ Copied ${totalCopied} ${kind === 'py' ? 'Python' : 'TypeScript'} files to ${target}`)\n for (const name of copiedList) console.log(` ${name}`)\n if (existsSync(readme)) console.log(' README.md')\n console.log(`\\nTests should already pass unchanged — the connector is self-contained and uses an injected ${kind === 'py' ? 'async transport' : 'fetch'}.`)\n if (kind === 'py') {\n console.log(`Make sure pytest + pytest-asyncio are available where you run the tests (or wire them into your existing suite).`)\n } else {\n console.log(`Add vitest and typescript as dev deps where you'll run them, or wire this into your existing suite.`)\n }\n}\n\nasync function build(args: string[]) {\n const record = args.includes('--record')\n const langFlag = flagValue(args, '--lang')\n const prompt = args.filter((a) => a !== '--record' && !a.startsWith('--lang')).join(' ').trim()\n if (!prompt) return usageError('build needs a prompt')\n\n const config = loadConfig(withLangEnv(process.env, langFlag))\n const missing = missingLiveKeys(config)\n if (config.mock || missing.length) {\n console.log(`Replay mode (${config.mock ? 'PATCHBAY_MOCK is not \"false\"' : `missing ${missing.join(', ')}`})`)\n }\n\n const events: RunEvent[] = []\n for await (const event of startRun(prompt, config)) {\n events.push(event)\n printEvent(event)\n }\n\n if (record) {\n const dir = join(process.cwd(), 'runs', new Date().toISOString().replace(/[:.]/g, '-'))\n const result = events.find((e) => e.type === 'result')\n for (const file of result?.type === 'result' ? result.files : []) {\n mkdirSync(dirname(join(dir, file.path)), { recursive: true })\n writeFileSync(join(dir, file.path), file.content)\n }\n mkdirSync(dir, { recursive: true })\n writeFileSync(join(dir, 'run.json'), JSON.stringify({ prompt, origin: 'live', events }, null, 2))\n console.log(`\\nRecorded to ${dir}`)\n }\n}\n\nasync function research(args: string[]) {\n const langFlag = flagValue(args, '--lang')\n const prompt = args.filter((a) => !a.startsWith('--lang')).join(' ').trim()\n if (!prompt) return usageError('research needs a prompt')\n const config = loadConfig(withLangEnv(process.env, langFlag))\n const missing = missingLiveKeys(config)\n if (config.mock || missing.length) {\n console.log(`Replay mode (${config.mock ? 'PATCHBAY_MOCK is not \"false\"' : `missing ${missing.join(', ')}`}) – returning cached research`)\n }\n for await (const event of startResearch(prompt, config)) {\n printEvent(event)\n if (event.type === 'spec') {\n console.log('\\nSpec:')\n console.log(JSON.stringify(event.spec, null, 2))\n }\n }\n}\n\nasync function verify(args: string[]) {\n const watchMode = args.includes('--watch')\n const langFlag = flagValue(args, '--lang')\n const positional = args.filter((a) => !a.startsWith('--'))\n const dir = positional[0] ? resolve(positional[0]) : ''\n if (!dir) return usageError('verify needs a directory')\n const dirFiles = collectFiles(dir)\n const hasTs = dirFiles.some((f) => f.path === 'src/connector.ts')\n const hasPy = dirFiles.some((f) => f.path === 'connector.py')\n if (!hasTs && !hasPy) {\n return usageError(`No connector found under ${dir} (expected src/connector.ts for TypeScript or connector.py for Python)`)\n }\n // Auto-detect: a Python connector.py beats the TS fallback.\n // Explicit --lang overrides detection in case someone has both.\n const detectedLang = hasPy && !hasTs ? 'py' : hasPy && hasTs ? undefined : 'ts'\n const effectiveLangFlag = langFlag ?? detectedLang\n if (!effectiveLangFlag) {\n return usageError(`${dir} contains both src/connector.ts and connector.py; pass --lang=ts or --lang=py to pick one`)\n }\n const config = loadConfig(withLangEnv(process.env, effectiveLangFlag))\n const missing = missingLiveKeys(config)\n if (config.mock || missing.length) {\n console.error(`verify needs live keys. Set PATCHBAY_MOCK=false and provide ${missing.join(', ') || 'the missing env vars'}.`)\n process.exit(1)\n }\n\n const runOnce = async () => {\n const files = collectFiles(dir)\n console.log(`\\nVerifying ${files.length} files from ${dir}`)\n for await (const event of startVerify(files, config)) printEvent(event)\n }\n\n await runOnce()\n if (!watchMode) return\n\n console.log(`\\nWatching ${dir} for .ts changes. Ctrl+C to exit.`)\n let running = false\n let rerun = false\n // Native fs.watch is good enough: debounced to avoid thrashing when an editor\n // saves multiple files in quick succession.\n let pending: NodeJS.Timeout | null = null\n const trigger = () => {\n if (pending) clearTimeout(pending)\n pending = setTimeout(async () => {\n pending = null\n if (running) { rerun = true; return }\n running = true\n try { await runOnce() } finally {\n running = false\n if (rerun) { rerun = false; trigger() }\n }\n }, 400)\n }\n watch(dir, { recursive: true }, (_, filename) => {\n if (filename && (filename.endsWith('.ts') || filename.endsWith('.json'))) trigger()\n })\n await new Promise(() => {}) // keep the process alive\n}\n\nasync function push(args: string[]) {\n const positional = args.filter((a) => !a.startsWith('--'))\n const runDir = positional[0] ? resolve(positional[0]) : ''\n if (!runDir) return usageError('push needs a run directory')\n const repo = flagValue(args, '--repo')\n if (!repo) return usageError('push needs --repo=owner/name')\n const target = flagValue(args, '--path') ?? `connectors/${basename(runDir)}`\n const branch = flagValue(args, '--branch')\n const dryRun = args.includes('--dry-run')\n const token = process.env.GH_TOKEN || process.env.GITHUB_TOKEN\n if (!token && !dryRun) {\n return usageError('push needs GH_TOKEN (or GITHUB_TOKEN) in the environment, with repo scope on the target.')\n }\n try {\n const result = await pushToGitHub({\n runDir, repo, token: token ?? '', targetPath: target,\n ...(branch ? { branch } : {}),\n dryRun,\n })\n console.log(dryRun ? '✔ Dry run:' : '✔ Opened pull request:')\n console.log(` URL: ${result.prUrl}`)\n console.log(` branch: ${result.branch} (base: ${result.base})`)\n console.log(` files: ${result.files.length} under ${target}/`)\n for (const path of result.files) console.log(` ${path}`)\n } catch (error) {\n console.error(error instanceof Error ? error.message : String(error))\n process.exit(1)\n }\n}\n\nasync function audit(args: string[]) {\n const positional = args.filter((a) => !a.startsWith('--'))\n const stdioCmd = flagValue(args, '--stdio')\n const target = stdioCmd ?? positional[0]\n if (!target) {\n console.error('patchbay audit: missing target (url, directory, or --stdio \"<command>\")')\n console.error('usage: patchbay audit <url|dir> [--stdio \"<cmd>\"] [--json] [--sarif] [--pr-draft] [--out=<path>] [--auth=<token>] [--probe-audience=<token>] [--probe-dcr-loopback] [--trust] [--ci] [--no-cta]')\n process.exit(2)\n }\n const asJson = args.includes('--json')\n const asSarif = args.includes('--sarif')\n const asPrDraft = args.includes('--pr-draft')\n const outPath = flagValue(args, '--out')\n const authToken = flagValue(args, '--auth') ?? process.env.PATCHBAY_AUDIT_TOKEN\n const probeAudienceToken = flagValue(args, '--probe-audience') ?? process.env.PATCHBAY_PROBE_AUDIENCE_TOKEN\n const probeMissingAudToken = flagValue(args, '--probe-missing-aud') ?? process.env.PATCHBAY_PROBE_MISSING_AUD_TOKEN\n const probeDcrLoopback = args.includes('--probe-dcr-loopback') || process.env.PATCHBAY_PROBE_DCR_LOOPBACK === '1'\n const probeHeadlessOauth = args.includes('--probe-headless-oauth') || process.env.PATCHBAY_PROBE_HEADLESS_OAUTH === '1'\n const trustCurrentManifest = args.includes('--trust')\n const publish = args.includes('--publish')\n const ci = args.includes('--ci')\n const failOnRaw = flagValue(args, '--fail-on')\n const noCta = args.includes('--no-cta')\n const stdio = Boolean(stdioCmd)\n\n const FAIL_SEVERITIES = ['critical', 'high', 'medium', 'low', 'info'] as const\n type FailSeverity = typeof FAIL_SEVERITIES[number]\n let failOn: FailSeverity | undefined\n if (failOnRaw) {\n if (!(FAIL_SEVERITIES as readonly string[]).includes(failOnRaw)) {\n console.error(`patchbay audit: --fail-on must be one of ${FAIL_SEVERITIES.join(', ')}`)\n process.exit(2)\n }\n failOn = failOnRaw as FailSeverity\n }\n\n const { auditTarget, renderTerminal, renderJson, renderSarif, renderMarkdown } = await import('@patchbay-nebius/audit-core')\n const resolved = stdio ? target : (/^https?:\\/\\//i.test(target) ? target : resolve(target))\n const report = await auditTarget(resolved, { authToken, trustCurrentManifest, probeAudienceToken, probeMissingAudToken, probeDcrLoopback, probeHeadlessOauth, stdio })\n\n if (publish) {\n try {\n const base = process.env.PATCHBAY_PUBLISH_URL || 'https://patchbay-mcp.dev'\n const res = await fetch(`${base}/api/report`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(report),\n })\n if (res.ok) {\n const j = (await res.json()) as { url?: string; id?: string }\n if (j.url) console.error(`Published report: ${j.url}`)\n } else {\n console.error(`Publish failed: HTTP ${res.status}`)\n }\n } catch (e) {\n console.error(`Publish failed: ${(e as Error).message}`)\n }\n }\n\n let rendered: string\n if (asJson) rendered = renderJson(report)\n else if (asSarif) rendered = renderSarif(report)\n else if (asPrDraft) rendered = renderMarkdown(report)\n else rendered = renderTerminal(report, { showCta: !noCta })\n\n if (outPath) {\n writeFileSync(resolve(outPath), rendered, 'utf8')\n console.error(`wrote ${rendered.length} bytes to ${outPath}`)\n } else {\n console.log(rendered)\n }\n\n if (ci && (report.summary.critical > 0 || report.summary.high > 0)) {\n process.exit(1)\n }\n\n if (failOn) {\n // Exit 1 if there is at least one finding at or above `failOn` severity.\n // Order: critical > high > medium > low > info. --fail-on=high counts crit + high.\n const idx = FAIL_SEVERITIES.indexOf(failOn)\n const triggerSeverities = FAIL_SEVERITIES.slice(0, idx + 1)\n const total = triggerSeverities.reduce((n, s) => n + (report.summary[s] ?? 0), 0)\n if (total > 0) {\n console.error(`patchbay: ${total} finding(s) at severity ${failOn} or higher. Exiting 1.`)\n process.exit(1)\n }\n }\n}\n\nasync function auditOauth(args: string[]) {\n const positional = args.filter((a) => !a.startsWith('--'))\n const url = positional[0]\n if (!url || !/^https?:\\/\\//i.test(url)) {\n console.error('patchbay audit-oauth: missing or invalid URL')\n console.error('usage: patchbay audit-oauth <url> [--client-id=<id>] [--scope=<s>] [--timeout=<seconds>] [--no-open] [--verbose] [any patchbay audit flag]')\n process.exit(2)\n }\n const clientId = flagValue(args, '--client-id')\n const scope = flagValue(args, '--scope')\n const timeoutStr = flagValue(args, '--timeout')\n const timeoutSeconds = timeoutStr ? Math.max(10, parseInt(timeoutStr, 10) || 300) : 300\n const noOpen = args.includes('--no-open')\n const verbose = args.includes('--verbose')\n\n const { loginAndGetToken } = await import('./oauth-login')\n let token: string\n try {\n const result = await loginAndGetToken(url, { clientId, scope, timeoutSeconds, noOpen, verbose })\n process.stderr.write(' Got token (' + (result.scope ?? 'no scope') + ', expires in ' + (result.expiresIn ?? '?') + 's)\\n\\n')\n token = result.accessToken\n } catch (e) {\n console.error('patchbay audit-oauth: login failed - ' + (e as Error).message)\n process.exit(1)\n return\n }\n\n // Delegate to the existing audit path with the token wired in. Strip\n // audit-oauth-only flags so the audit arg parser does not choke.\n const AUDIT_OAUTH_FLAGS = new Set(['--client-id', '--scope', '--timeout', '--no-open', '--verbose'])\n const forwarded = args.filter((a) => {\n const name = a.split('=')[0] ?? a\n if (AUDIT_OAUTH_FLAGS.has(name)) return false\n if (a.startsWith('--auth=')) return false // we are supplying the auth\n return true\n })\n forwarded.push('--auth=' + token)\n return audit(forwarded)\n}\n\nfunction flagValue(args: string[], flag: string): string | undefined {\n const match = args.find((a) => a.startsWith(`${flag}=`))\n return match?.slice(flag.length + 1)\n}\n\nfunction withLangEnv(env: NodeJS.ProcessEnv, langFlag: string | undefined): NodeJS.ProcessEnv {\n if (!langFlag) return env\n return { ...env, PATCHBAY_LANG: langFlag }\n}\n\nfunction collectFiles(root: string): GeneratedFile[] {\n const out: GeneratedFile[] = []\n const walk = (dir: string) => {\n for (const entry of readdirSync(dir)) {\n if (entry === 'node_modules' || entry.startsWith('.')) continue\n const abs = join(dir, entry)\n const st = statSync(abs)\n if (st.isDirectory()) walk(abs)\n else if (entry.endsWith('.ts') || entry.endsWith('.py') || entry === 'README.md') {\n out.push({ path: relative(root, abs).replace(/\\\\/g, '/'), content: readFileSync(abs, 'utf8') })\n }\n }\n }\n walk(root)\n return out\n}\n\nfunction usageError(message: string): void {\n console.error(`Error: ${message}\\n`)\n console.error(HELP)\n process.exit(1)\n}\n\nfunction printEvent(event: RunEvent) {\n switch (event.type) {\n case 'step':\n console.log(`${event.status === 'start' ? '▶' : event.status === 'done' ? '✔' : '✖'} ${event.step}${event.detail ? ` — ${event.detail}` : ''}`)\n break\n case 'log':\n console.log(` ${event.message}`)\n break\n case 'tests':\n console.log(` attempt ${event.attempt}: ${event.report.passed}/${event.report.total} passed, typecheck ${event.report.typecheckOk ? 'ok' : 'failed'}`)\n for (const f of event.report.failures) {\n console.log(` ✖ ${f.name}`)\n if (process.env.PATCHBAY_VERBOSE === '1' && f.message) {\n for (const line of f.message.split('\\n').slice(0, 20)) console.log(` ${line}`)\n }\n }\n break\n case 'usage':\n for (const u of event.usage) console.log(` ${u.model}: ${u.promptTokens} in / ${u.completionTokens} out, $${u.costUsd.toFixed(4)}`)\n break\n case 'error':\n console.error(`Error: ${event.message}`)\n break\n }\n}\n\nmain().catch((error) => {\n console.error(error)\n process.exit(1)\n})\n","import { readdirSync, readFileSync, statSync } from 'node:fs'\nimport { join, relative } from 'node:path'\n\nexport interface PushOptions {\n runDir: string\n repo: string // \"owner/name\"\n token: string\n /** Where inside the target repo the connector files land. */\n targetPath: string // e.g. \"connectors/typeform-pipedrive\"\n /** Branch to create. Defaults to patchbay/<basename(runDir)>. */\n branch?: string\n /** Base branch to branch from. GitHub defaults it to the repo's default. */\n base?: string\n /** PR title + body overrides. */\n title?: string\n body?: string\n /** Set true to log what would happen without hitting the API. */\n dryRun?: boolean\n}\n\nexport interface PushResult {\n prUrl: string\n branch: string\n base: string\n files: string[]\n}\n\nconst API = 'https://api.github.com'\n\n/**\n * Takes a recorded patchbay run (runs/<timestamp>/ with src/* + README.md) and lands it in a\n * target GitHub repo as a pull request: new branch, commits every file under `targetPath`,\n * opens a PR against the repo's default branch.\n *\n * Uses the GitHub REST API directly (fetch + token). The token needs `repo` scope on the\n * target. Dry-run prints the plan without calling the API.\n */\nexport async function pushToGitHub(opts: PushOptions): Promise<PushResult> {\n const files = collectRunFiles(opts.runDir)\n if (files.length === 0) {\n throw new Error(`${opts.runDir} has no files to push (expected src/* and README.md for TS, or connector.py + test_connector.py + fixtures.py + README.md for Python).`)\n }\n\n const [owner, name] = opts.repo.split('/')\n if (!owner || !name) throw new Error(`Expected --repo=owner/name, got \"${opts.repo}\"`)\n\n const branch = opts.branch ?? `patchbay/${basenameNoSlash(opts.runDir)}`\n const title = opts.title ?? `patchbay: ${opts.targetPath}`\n const body =\n opts.body ??\n `Generated by [patchbay](https://github.com/GodSmasher/patchbay) from \\`${basenameNoSlash(opts.runDir)}\\`.\\n\\n` +\n `Includes ${files.length} files under \\`${opts.targetPath}/\\`. Tests pass against the documented example in a hermetic sandbox.`\n\n if (opts.dryRun) {\n return { prUrl: `(dry-run) would open PR on ${opts.repo}`, branch, base: opts.base ?? '(default)', files: files.map((f) => f.path) }\n }\n\n const api = createApi(opts.token)\n const repo = (await api(`/repos/${owner}/${name}`)) as { default_branch: string }\n const base = opts.base ?? repo.default_branch\n const baseRef = (await api(`/repos/${owner}/${name}/git/ref/heads/${base}`)) as { object: { sha: string } }\n const baseSha = baseRef.object.sha\n\n // Create the branch (409 if it already exists, we tolerate that).\n try {\n await api(`/repos/${owner}/${name}/git/refs`, {\n method: 'POST',\n body: { ref: `refs/heads/${branch}`, sha: baseSha },\n })\n } catch (error) {\n if (!/already exists/i.test(String(error))) throw error\n }\n\n // One commit per file keeps the diff readable; could be batched into a tree later if it matters.\n for (const file of files) {\n const path = `${opts.targetPath}/${file.path}`.replace(/\\\\/g, '/')\n const existing = (await api(`/repos/${owner}/${name}/contents/${encodeURIComponent(path)}?ref=${branch}`).catch(() => null)) as { sha?: string } | null\n await api(`/repos/${owner}/${name}/contents/${encodeURIComponent(path)}`, {\n method: 'PUT',\n body: {\n message: `patchbay: ${path}`,\n content: Buffer.from(file.content, 'utf8').toString('base64'),\n branch,\n ...(existing?.sha ? { sha: existing.sha } : {}),\n },\n })\n }\n\n const pr = (await api(`/repos/${owner}/${name}/pulls`, {\n method: 'POST',\n body: { title, head: branch, base, body, draft: false },\n })) as { html_url: string }\n\n return { prUrl: pr.html_url, branch, base, files: files.map((f) => f.path) }\n}\n\ninterface RunFile {\n path: string\n content: string\n}\n\nfunction collectRunFiles(root: string): RunFile[] {\n const out: RunFile[] = []\n const walk = (dir: string) => {\n for (const entry of readdirSync(dir)) {\n if (entry === 'run.json' || entry.startsWith('.')) continue\n const abs = join(dir, entry)\n const st = statSync(abs)\n if (st.isDirectory()) walk(abs)\n else out.push({ path: relative(root, abs).replace(/\\\\/g, '/'), content: readFileSync(abs, 'utf8') })\n }\n }\n walk(root)\n return out\n}\n\nfunction basenameNoSlash(path: string): string {\n return path.replace(/[\\\\/]+$/, '').split(/[\\\\/]/).pop() ?? 'run'\n}\n\nfunction createApi(token: string) {\n return async <T = unknown>(path: string, init: { method?: string; body?: unknown } = {}): Promise<T> => {\n const res = await fetch(`${API}${path}`, {\n method: init.method ?? 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n Accept: 'application/vnd.github+json',\n 'X-GitHub-Api-Version': '2022-11-28',\n 'User-Agent': 'patchbay-cli',\n ...(init.body ? { 'Content-Type': 'application/json' } : {}),\n },\n body: init.body ? JSON.stringify(init.body) : undefined,\n })\n const text = await res.text()\n const data = text ? JSON.parse(text) : {}\n if (!res.ok) throw new Error(`GitHub ${init.method ?? 'GET'} ${path}: HTTP ${res.status} ${(data as { message?: string }).message ?? text.slice(0, 200)}`)\n return data as T\n }\n}\n"],"mappings":";;;;;;;;;;;AACA,SAAS,QAAQ,YAAY,WAAW,eAAAA,cAAa,gBAAAC,eAAc,YAAAC,WAAU,OAAO,qBAAqB;AACzG,SAAS,UAAU,SAAS,QAAAC,OAAM,YAAAC,WAAU,eAAe;;;ACF3D,SAAS,aAAa,cAAc,gBAAgB;AACpD,SAAS,MAAM,gBAAgB;AA0B/B,IAAM,MAAM;AAUZ,eAAsB,aAAa,MAAwC;AACzE,QAAM,QAAQ,gBAAgB,KAAK,MAAM;AACzC,MAAI,MAAM,WAAW,GAAG;AACtB,UAAM,IAAI,MAAM,GAAG,KAAK,MAAM,wIAAwI;AAAA,EACxK;AAEA,QAAM,CAAC,OAAO,IAAI,IAAI,KAAK,KAAK,MAAM,GAAG;AACzC,MAAI,CAAC,SAAS,CAAC,KAAM,OAAM,IAAI,MAAM,oCAAoC,KAAK,IAAI,GAAG;AAErF,QAAM,SAAS,KAAK,UAAU,YAAY,gBAAgB,KAAK,MAAM,CAAC;AACtE,QAAM,QAAQ,KAAK,SAAS,aAAa,KAAK,UAAU;AACxD,QAAM,OACJ,KAAK,QACL,0EAA0E,gBAAgB,KAAK,MAAM,CAAC;AAAA;AAAA,WACxF,MAAM,MAAM,kBAAkB,KAAK,UAAU;AAE7D,MAAI,KAAK,QAAQ;AACf,WAAO,EAAE,OAAO,8BAA8B,KAAK,IAAI,IAAI,QAAQ,MAAM,KAAK,QAAQ,aAAa,OAAO,MAAM,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE;AAAA,EACrI;AAEA,QAAM,MAAM,UAAU,KAAK,KAAK;AAChC,QAAM,OAAQ,MAAM,IAAI,UAAU,KAAK,IAAI,IA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I,MAAM,IAAI,GAAG,MAAM,SAAS,WAAM,MAAM,MAAM,KAAK,EAAE,EAAE;AAC9I;AAAA,IACF,KAAK;AACH,cAAQ,IAAI,OAAO,MAAM,OAAO,EAAE;AAClC;AAAA,IACF,KAAK;AACH,cAAQ,IAAI,eAAe,MAAM,OAAO,KAAK,MAAM,OAAO,MAAM,IAAI,MAAM,OAAO,KAAK,sBAAsB,MAAM,OAAO,cAAc,OAAO,QAAQ,EAAE;AACxJ,iBAAW,KAAK,MAAM,OAAO,UAAU;AACrC,gBAAQ,IAAI,gBAAW,EAAE,IAAI,EAAE;AAC/B,YAAI,QAAQ,IAAI,qBAAqB,OAAO,EAAE,SAAS;AACrD,qBAAW,QAAQ,EAAE,QAAQ,MAAM,IAAI,EAAE,MAAM,GAAG,EAAE,EAAG,SAAQ,IAAI,YAAY,IAAI,EAAE;AAAA,QACvF;AAAA,MACF;AACA;AAAA,IACF,KAAK;AACH,iBAAW,KAAK,MAAM,MAAO,SAAQ,IAAI,OAAO,EAAE,KAAK,KAAK,EAAE,YAAY,SAAS,EAAE,gBAAgB,UAAU,EAAE,QAAQ,QAAQ,CAAC,CAAC,EAAE;AACrI;AAAA,IACF,KAAK;AACH,cAAQ,MAAM,UAAU,MAAM,OAAO,EAAE;AACvC;AAAA,EACJ;AACF;AAEA,KAAK,EAAE,MAAM,CAAC,UAAU;AACtB,UAAQ,MAAM,KAAK;AACnB,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["readdirSync","readFileSync","statSync","join","relative","join","readdirSync","statSync","relative","readFileSync"]}
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
// src/oauth-login.ts
|
|
2
|
+
import { createHash, randomBytes } from "crypto";
|
|
3
|
+
import { createServer } from "http";
|
|
4
|
+
import { spawn } from "child_process";
|
|
5
|
+
import { URL, URLSearchParams } from "url";
|
|
6
|
+
async function loginAndGetToken(mcpUrl, opts = {}) {
|
|
7
|
+
const verbose = Boolean(opts.verbose);
|
|
8
|
+
const log = (msg) => {
|
|
9
|
+
if (verbose) process.stderr.write("[audit-oauth] " + msg + "\n");
|
|
10
|
+
};
|
|
11
|
+
const mcp = new URL(mcpUrl);
|
|
12
|
+
const prmUrl = new URL("/.well-known/oauth-protected-resource", mcp.origin).toString();
|
|
13
|
+
log("PRM: " + prmUrl);
|
|
14
|
+
const prm = await fetchJson(prmUrl);
|
|
15
|
+
const authServerIssuer = pickAuthServer(prm, mcp);
|
|
16
|
+
log("authorization_servers[0]: " + authServerIssuer);
|
|
17
|
+
const asMetadataUrl = asMetadataUrlFor(authServerIssuer);
|
|
18
|
+
log("AS metadata: " + asMetadataUrl);
|
|
19
|
+
const as = await fetchJson(asMetadataUrl);
|
|
20
|
+
const authzEndpoint = requireString(as, "authorization_endpoint");
|
|
21
|
+
const tokenEndpoint = requireString(as, "token_endpoint");
|
|
22
|
+
const registrationEndpoint = typeof as.registration_endpoint === "string" ? as.registration_endpoint : void 0;
|
|
23
|
+
let clientId = opts.clientId;
|
|
24
|
+
if (!clientId) {
|
|
25
|
+
if (!registrationEndpoint) {
|
|
26
|
+
throw new Error(
|
|
27
|
+
"This AS does not advertise a registration_endpoint. Pass --client-id=<existing-id> or register a client manually before using audit-oauth."
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
log("DCR: " + registrationEndpoint);
|
|
31
|
+
}
|
|
32
|
+
const host = opts.callbackHost ?? "127.0.0.1";
|
|
33
|
+
const { server, url: redirectUri, waitForCode } = await startLoopbackListener(host);
|
|
34
|
+
log("loopback: " + redirectUri);
|
|
35
|
+
try {
|
|
36
|
+
if (!clientId) {
|
|
37
|
+
const dcr = await fetchJson(registrationEndpoint, {
|
|
38
|
+
method: "POST",
|
|
39
|
+
headers: { "content-type": "application/json" },
|
|
40
|
+
body: JSON.stringify({
|
|
41
|
+
client_name: "patchbay audit-oauth",
|
|
42
|
+
redirect_uris: [redirectUri],
|
|
43
|
+
token_endpoint_auth_method: "none",
|
|
44
|
+
grant_types: ["authorization_code"],
|
|
45
|
+
response_types: ["code"],
|
|
46
|
+
application_type: "native"
|
|
47
|
+
})
|
|
48
|
+
});
|
|
49
|
+
if (typeof dcr.client_id !== "string") {
|
|
50
|
+
throw new Error("DCR response missing client_id: " + JSON.stringify(dcr).slice(0, 400));
|
|
51
|
+
}
|
|
52
|
+
clientId = dcr.client_id;
|
|
53
|
+
log("client_id: " + clientId);
|
|
54
|
+
}
|
|
55
|
+
const codeVerifier = base64url(randomBytes(32));
|
|
56
|
+
const codeChallenge = base64url(createHash("sha256").update(codeVerifier).digest());
|
|
57
|
+
const state = base64url(randomBytes(16));
|
|
58
|
+
const authorizeUrl = new URL(authzEndpoint);
|
|
59
|
+
authorizeUrl.searchParams.set("response_type", "code");
|
|
60
|
+
authorizeUrl.searchParams.set("client_id", clientId);
|
|
61
|
+
authorizeUrl.searchParams.set("redirect_uri", redirectUri);
|
|
62
|
+
authorizeUrl.searchParams.set("state", state);
|
|
63
|
+
authorizeUrl.searchParams.set("code_challenge", codeChallenge);
|
|
64
|
+
authorizeUrl.searchParams.set("code_challenge_method", "S256");
|
|
65
|
+
authorizeUrl.searchParams.set("resource", mcp.toString());
|
|
66
|
+
const scope = opts.scope ?? pickFirstScope(as);
|
|
67
|
+
if (scope) authorizeUrl.searchParams.set("scope", scope);
|
|
68
|
+
if (!opts.noOpen) openUrl(authorizeUrl.toString());
|
|
69
|
+
process.stderr.write(
|
|
70
|
+
"\n Waiting for browser login at " + mcp.origin + " ...\n If nothing opened, visit this URL:\n " + authorizeUrl.toString() + "\n\n"
|
|
71
|
+
);
|
|
72
|
+
const timeoutMs = (opts.timeoutSeconds ?? 300) * 1e3;
|
|
73
|
+
const callback = await waitForCode(timeoutMs, state);
|
|
74
|
+
log("token exchange: " + tokenEndpoint);
|
|
75
|
+
const body = new URLSearchParams({
|
|
76
|
+
grant_type: "authorization_code",
|
|
77
|
+
code: callback.code,
|
|
78
|
+
redirect_uri: redirectUri,
|
|
79
|
+
client_id: clientId,
|
|
80
|
+
code_verifier: codeVerifier,
|
|
81
|
+
resource: mcp.toString()
|
|
82
|
+
});
|
|
83
|
+
const tokenRes = await fetch(tokenEndpoint, {
|
|
84
|
+
method: "POST",
|
|
85
|
+
headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
|
|
86
|
+
body: body.toString()
|
|
87
|
+
});
|
|
88
|
+
const tokenJson = await tokenRes.json().catch(() => ({}));
|
|
89
|
+
if (!tokenRes.ok || typeof tokenJson.access_token !== "string") {
|
|
90
|
+
throw new Error("Token exchange failed (HTTP " + tokenRes.status + "): " + (tokenJson.error_description ?? tokenJson.error ?? JSON.stringify(tokenJson).slice(0, 300)));
|
|
91
|
+
}
|
|
92
|
+
log("token received (" + (tokenJson.token_type ?? "bearer") + ", expires_in=" + (tokenJson.expires_in ?? "?") + ")");
|
|
93
|
+
return {
|
|
94
|
+
accessToken: tokenJson.access_token,
|
|
95
|
+
tokenType: tokenJson.token_type ?? "Bearer",
|
|
96
|
+
expiresIn: tokenJson.expires_in,
|
|
97
|
+
scope: tokenJson.scope,
|
|
98
|
+
clientId,
|
|
99
|
+
authServerIssuer
|
|
100
|
+
};
|
|
101
|
+
} finally {
|
|
102
|
+
server.close();
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
function pickAuthServer(prm, mcp) {
|
|
106
|
+
const list = prm.authorization_servers;
|
|
107
|
+
if (Array.isArray(list) && typeof list[0] === "string" && list[0].length) return list[0];
|
|
108
|
+
return mcp.origin;
|
|
109
|
+
}
|
|
110
|
+
function asMetadataUrlFor(issuer) {
|
|
111
|
+
const u = new URL(issuer);
|
|
112
|
+
const prefix = u.origin + "/.well-known/oauth-authorization-server";
|
|
113
|
+
const rest = u.pathname === "/" || u.pathname === "" ? "" : u.pathname;
|
|
114
|
+
return prefix + rest;
|
|
115
|
+
}
|
|
116
|
+
function pickFirstScope(as) {
|
|
117
|
+
const s = as.scopes_supported;
|
|
118
|
+
if (Array.isArray(s) && typeof s[0] === "string" && s[0].length) return s[0];
|
|
119
|
+
return void 0;
|
|
120
|
+
}
|
|
121
|
+
function requireString(obj, field) {
|
|
122
|
+
const v = obj[field];
|
|
123
|
+
if (typeof v !== "string" || !v) throw new Error('AS metadata missing required field "' + field + '"');
|
|
124
|
+
return v;
|
|
125
|
+
}
|
|
126
|
+
async function fetchJson(url, init) {
|
|
127
|
+
const r = await fetch(url, init);
|
|
128
|
+
if (!r.ok) throw new Error("Fetch " + url + " failed: HTTP " + r.status);
|
|
129
|
+
return await r.json();
|
|
130
|
+
}
|
|
131
|
+
function base64url(buf) {
|
|
132
|
+
return buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
133
|
+
}
|
|
134
|
+
async function startLoopbackListener(host) {
|
|
135
|
+
let resolveCallback = () => {
|
|
136
|
+
};
|
|
137
|
+
let rejectCallback = () => {
|
|
138
|
+
};
|
|
139
|
+
const callback = new Promise((res, rej) => {
|
|
140
|
+
resolveCallback = res;
|
|
141
|
+
rejectCallback = rej;
|
|
142
|
+
});
|
|
143
|
+
const server = createServer((req, res) => {
|
|
144
|
+
if (!req.url || !req.url.startsWith("/callback")) {
|
|
145
|
+
res.writeHead(404, { "content-type": "text/plain" }).end("not found");
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
try {
|
|
149
|
+
const u = new URL(req.url, "http://localhost");
|
|
150
|
+
const err = u.searchParams.get("error");
|
|
151
|
+
if (err) {
|
|
152
|
+
const desc = u.searchParams.get("error_description") ?? "";
|
|
153
|
+
res.writeHead(400, { "content-type": "text/html" }).end(renderHtml(false, err + (desc ? ": " + desc : "")));
|
|
154
|
+
rejectCallback(new Error("Authorization error: " + err + (desc ? " - " + desc : "")));
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
const code = u.searchParams.get("code");
|
|
158
|
+
const state = u.searchParams.get("state");
|
|
159
|
+
if (!code) {
|
|
160
|
+
res.writeHead(400, { "content-type": "text/html" }).end(renderHtml(false, "Missing code parameter."));
|
|
161
|
+
rejectCallback(new Error("Missing code parameter in callback"));
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
res.writeHead(200, { "content-type": "text/html" }).end(renderHtml(true, "You can close this tab and return to the terminal."));
|
|
165
|
+
resolveCallback({ code });
|
|
166
|
+
void state;
|
|
167
|
+
} catch (e) {
|
|
168
|
+
res.writeHead(500, { "content-type": "text/plain" }).end(e.message);
|
|
169
|
+
rejectCallback(e);
|
|
170
|
+
}
|
|
171
|
+
});
|
|
172
|
+
await new Promise((res) => server.listen(0, host, res));
|
|
173
|
+
const addr = server.address();
|
|
174
|
+
if (!addr || typeof addr !== "object") throw new Error("Could not bind loopback listener");
|
|
175
|
+
const port = addr.port;
|
|
176
|
+
const hostForUrl = host === "[::1]" || host === "::1" ? "[::1]" : host;
|
|
177
|
+
const url = "http://" + hostForUrl + ":" + port + "/callback";
|
|
178
|
+
return {
|
|
179
|
+
server,
|
|
180
|
+
url,
|
|
181
|
+
waitForCode: async (timeoutMs, expectedState) => {
|
|
182
|
+
const timeout = new Promise(
|
|
183
|
+
(_, rej) => setTimeout(() => rej(new Error("Timed out after " + Math.round(timeoutMs / 1e3) + "s waiting for browser callback")), timeoutMs)
|
|
184
|
+
);
|
|
185
|
+
const got = await Promise.race([callback, timeout]);
|
|
186
|
+
void expectedState;
|
|
187
|
+
return got;
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
function renderHtml(ok, message) {
|
|
192
|
+
const color = ok ? "#15803d" : "#b91c1c";
|
|
193
|
+
return '<!doctype html><meta charset="utf-8"><title>patchbay audit-oauth</title><body style="font:16px system-ui;max-width:520px;margin:4rem auto;padding:1rem;color:#111"><h1 style="color:' + color + '">' + (ok ? "Login complete" : "Login failed") + "</h1><p>" + escapeHtml(message) + '</p><p style="color:#6b7280;font-size:14px">patchbay audit-oauth \xB7 you can close this tab</p></body>';
|
|
194
|
+
}
|
|
195
|
+
function escapeHtml(s) {
|
|
196
|
+
return s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
|
|
197
|
+
}
|
|
198
|
+
function openUrl(url) {
|
|
199
|
+
const platform = process.platform;
|
|
200
|
+
try {
|
|
201
|
+
if (platform === "darwin") {
|
|
202
|
+
spawn("open", [url], { stdio: "ignore", detached: true }).unref();
|
|
203
|
+
} else if (platform === "win32") {
|
|
204
|
+
spawn("cmd", ["/c", "start", '""', url], { stdio: "ignore", detached: true }).unref();
|
|
205
|
+
} else {
|
|
206
|
+
spawn("xdg-open", [url], { stdio: "ignore", detached: true }).unref();
|
|
207
|
+
}
|
|
208
|
+
} catch {
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
export {
|
|
212
|
+
loginAndGetToken
|
|
213
|
+
};
|
|
214
|
+
//# sourceMappingURL=oauth-login-E55CXA3X.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/oauth-login.ts"],"sourcesContent":["/**\n * Browser-based OAuth 2.1 native app flow (RFC 8252) for `patchbay audit-oauth`.\n *\n * Given an MCP server URL that requires authentication, we:\n * 1. Discover PRM (RFC 9728) and AS metadata (RFC 8414).\n * 2. Register a transient public client via DCR (RFC 7591) if the AS supports it.\n * Falls back to a user-supplied client_id when it does not.\n * 3. Open the user's browser at /authorize with PKCE S256, a fresh state,\n * and the MCP URL as the RFC 8707 `resource` parameter.\n * 4. Serve a one-shot loopback HTTP listener on 127.0.0.1:<random> that\n * catches the redirect and exits as soon as it has the code.\n * 5. Exchange the code at /token and return the bearer.\n *\n * Nothing persists. The DCR client, code_verifier and loopback port are\n * all throwaway, so a subsequent audit-oauth against the same server\n * registers a fresh client.\n */\nimport { createHash, randomBytes } from 'node:crypto'\nimport { createServer, type Server } from 'node:http'\nimport { spawn } from 'node:child_process'\nimport { URL, URLSearchParams } from 'node:url'\n\nexport interface LoginResult {\n accessToken: string\n tokenType: string\n expiresIn?: number\n scope?: string\n clientId: string\n authServerIssuer: string\n}\n\nexport interface LoginOptions {\n /** Explicit scope string. Default: first value in AS `scopes_supported`, else omitted. */\n scope?: string\n /** Pre-registered client id, bypasses DCR. */\n clientId?: string\n /** Max seconds to wait for the user to complete the browser flow. Default 300. */\n timeoutSeconds?: number\n /** Print discovery URLs and request shapes for debugging. */\n verbose?: boolean\n /** Override callback host. Default 127.0.0.1. Only loopback is allowed. */\n callbackHost?: '127.0.0.1' | '[::1]' | 'localhost'\n /** Skip opening the browser (print the URL and wait). Default false. */\n noOpen?: boolean\n}\n\nexport async function loginAndGetToken(mcpUrl: string, opts: LoginOptions = {}): Promise<LoginResult> {\n const verbose = Boolean(opts.verbose)\n const log = (msg: string): void => { if (verbose) process.stderr.write('[audit-oauth] ' + msg + '\\n') }\n\n const mcp = new URL(mcpUrl)\n\n // Step 1: PRM\n const prmUrl = new URL('/.well-known/oauth-protected-resource', mcp.origin).toString()\n log('PRM: ' + prmUrl)\n const prm = await fetchJson(prmUrl)\n const authServerIssuer = pickAuthServer(prm, mcp)\n log('authorization_servers[0]: ' + authServerIssuer)\n\n // Step 2: AS metadata\n const asMetadataUrl = asMetadataUrlFor(authServerIssuer)\n log('AS metadata: ' + asMetadataUrl)\n const as = await fetchJson(asMetadataUrl)\n const authzEndpoint = requireString(as, 'authorization_endpoint')\n const tokenEndpoint = requireString(as, 'token_endpoint')\n const registrationEndpoint = typeof as.registration_endpoint === 'string' ? as.registration_endpoint : undefined\n\n // Step 3: client registration\n let clientId = opts.clientId\n if (!clientId) {\n if (!registrationEndpoint) {\n throw new Error(\n 'This AS does not advertise a registration_endpoint. Pass --client-id=<existing-id> ' +\n 'or register a client manually before using audit-oauth.',\n )\n }\n log('DCR: ' + registrationEndpoint)\n }\n\n // Step 4: start loopback listener. We need the port before we can register\n // the redirect_uri or build the authorize URL, so bind first, read .address(),\n // then register with that URL.\n const host = opts.callbackHost ?? '127.0.0.1'\n const { server, url: redirectUri, waitForCode } = await startLoopbackListener(host)\n log('loopback: ' + redirectUri)\n\n try {\n if (!clientId) {\n const dcr = await fetchJson(registrationEndpoint!, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n client_name: 'patchbay audit-oauth',\n redirect_uris: [redirectUri],\n token_endpoint_auth_method: 'none',\n grant_types: ['authorization_code'],\n response_types: ['code'],\n application_type: 'native',\n }),\n })\n if (typeof dcr.client_id !== 'string') {\n throw new Error('DCR response missing client_id: ' + JSON.stringify(dcr).slice(0, 400))\n }\n clientId = dcr.client_id\n log('client_id: ' + clientId)\n }\n\n // Step 5: PKCE\n const codeVerifier = base64url(randomBytes(32))\n const codeChallenge = base64url(createHash('sha256').update(codeVerifier).digest())\n const state = base64url(randomBytes(16))\n\n // Step 6: authorize URL\n const authorizeUrl = new URL(authzEndpoint)\n authorizeUrl.searchParams.set('response_type', 'code')\n authorizeUrl.searchParams.set('client_id', clientId!)\n authorizeUrl.searchParams.set('redirect_uri', redirectUri)\n authorizeUrl.searchParams.set('state', state)\n authorizeUrl.searchParams.set('code_challenge', codeChallenge)\n authorizeUrl.searchParams.set('code_challenge_method', 'S256')\n authorizeUrl.searchParams.set('resource', mcp.toString())\n const scope = opts.scope ?? pickFirstScope(as)\n if (scope) authorizeUrl.searchParams.set('scope', scope)\n\n // Step 7: open browser (unless --no-open)\n if (!opts.noOpen) openUrl(authorizeUrl.toString())\n process.stderr.write(\n '\\n Waiting for browser login at ' + mcp.origin + ' ...\\n' +\n ' If nothing opened, visit this URL:\\n ' + authorizeUrl.toString() + '\\n\\n',\n )\n\n // Step 8: wait for callback\n const timeoutMs = (opts.timeoutSeconds ?? 300) * 1000\n const callback = await waitForCode(timeoutMs, state)\n\n // Step 9: exchange code for token\n log('token exchange: ' + tokenEndpoint)\n const body = new URLSearchParams({\n grant_type: 'authorization_code',\n code: callback.code,\n redirect_uri: redirectUri,\n client_id: clientId!,\n code_verifier: codeVerifier,\n resource: mcp.toString(),\n })\n const tokenRes = await fetch(tokenEndpoint, {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },\n body: body.toString(),\n })\n const tokenJson = await tokenRes.json().catch(() => ({})) as {\n access_token?: string; token_type?: string; expires_in?: number; scope?: string; error?: string; error_description?: string\n }\n if (!tokenRes.ok || typeof tokenJson.access_token !== 'string') {\n throw new Error('Token exchange failed (HTTP ' + tokenRes.status + '): ' + (tokenJson.error_description ?? tokenJson.error ?? JSON.stringify(tokenJson).slice(0, 300)))\n }\n log('token received (' + (tokenJson.token_type ?? 'bearer') + ', expires_in=' + (tokenJson.expires_in ?? '?') + ')')\n\n return {\n accessToken: tokenJson.access_token,\n tokenType: tokenJson.token_type ?? 'Bearer',\n expiresIn: tokenJson.expires_in,\n scope: tokenJson.scope,\n clientId: clientId!,\n authServerIssuer,\n }\n } finally {\n server.close()\n }\n}\n\n// --- helpers --------------------------------------------------------------\n\nfunction pickAuthServer(prm: Record<string, unknown>, mcp: URL): string {\n const list = prm.authorization_servers\n if (Array.isArray(list) && typeof list[0] === 'string' && list[0].length) return list[0]\n // Fallback: assume AS lives at the MCP origin. Spec-noncompliant but common.\n return mcp.origin\n}\n\nfunction asMetadataUrlFor(issuer: string): string {\n // RFC 8414 non-standard-path handling: metadata lives at\n // <issuer>/.well-known/oauth-authorization-server, with the issuer's path\n // (if any) inserted after .well-known. For an issuer \"https://as.example/tenant\"\n // the metadata is at \"https://as.example/.well-known/oauth-authorization-server/tenant\".\n // When the issuer is bare origin, drop the trailing-slash case.\n const u = new URL(issuer)\n const prefix = u.origin + '/.well-known/oauth-authorization-server'\n const rest = u.pathname === '/' || u.pathname === '' ? '' : u.pathname\n return prefix + rest\n}\n\nfunction pickFirstScope(as: Record<string, unknown>): string | undefined {\n const s = as.scopes_supported\n if (Array.isArray(s) && typeof s[0] === 'string' && s[0].length) return s[0]\n return undefined\n}\n\nfunction requireString(obj: Record<string, unknown>, field: string): string {\n const v = obj[field]\n if (typeof v !== 'string' || !v) throw new Error('AS metadata missing required field \"' + field + '\"')\n return v\n}\n\nasync function fetchJson(url: string, init?: RequestInit): Promise<Record<string, unknown>> {\n const r = await fetch(url, init)\n if (!r.ok) throw new Error('Fetch ' + url + ' failed: HTTP ' + r.status)\n return (await r.json()) as Record<string, unknown>\n}\n\nfunction base64url(buf: Buffer): string {\n return buf.toString('base64').replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\ninterface LoopbackListener {\n server: Server\n url: string\n waitForCode(timeoutMs: number, expectedState: string): Promise<{ code: string }>\n}\n\nasync function startLoopbackListener(host: string): Promise<LoopbackListener> {\n let resolveCallback: (v: { code: string }) => void = () => {}\n let rejectCallback: (e: Error) => void = () => {}\n const callback = new Promise<{ code: string }>((res, rej) => { resolveCallback = res; rejectCallback = rej })\n\n const server = createServer((req, res) => {\n if (!req.url || !req.url.startsWith('/callback')) {\n res.writeHead(404, { 'content-type': 'text/plain' }).end('not found')\n return\n }\n try {\n const u = new URL(req.url, 'http://localhost')\n const err = u.searchParams.get('error')\n if (err) {\n const desc = u.searchParams.get('error_description') ?? ''\n res.writeHead(400, { 'content-type': 'text/html' }).end(renderHtml(false, err + (desc ? ': ' + desc : '')))\n rejectCallback(new Error('Authorization error: ' + err + (desc ? ' - ' + desc : '')))\n return\n }\n const code = u.searchParams.get('code')\n const state = u.searchParams.get('state')\n if (!code) {\n res.writeHead(400, { 'content-type': 'text/html' }).end(renderHtml(false, 'Missing code parameter.'))\n rejectCallback(new Error('Missing code parameter in callback'))\n return\n }\n res.writeHead(200, { 'content-type': 'text/html' }).end(renderHtml(true, 'You can close this tab and return to the terminal.'))\n resolveCallback({ code })\n void state\n } catch (e) {\n res.writeHead(500, { 'content-type': 'text/plain' }).end((e as Error).message)\n rejectCallback(e as Error)\n }\n })\n\n await new Promise<void>((res) => server.listen(0, host, res))\n const addr = server.address()\n if (!addr || typeof addr !== 'object') throw new Error('Could not bind loopback listener')\n const port = addr.port\n // IPv6 literals need brackets in URLs. Node reports 127.0.0.1 as \"127.0.0.1\" and [::1] as \"::1\".\n const hostForUrl = host === '[::1]' || host === '::1' ? '[::1]' : host\n const url = 'http://' + hostForUrl + ':' + port + '/callback'\n\n return {\n server,\n url,\n waitForCode: async (timeoutMs: number, expectedState: string): Promise<{ code: string }> => {\n const timeout = new Promise<{ code: string }>((_, rej) =>\n setTimeout(() => rej(new Error('Timed out after ' + Math.round(timeoutMs / 1000) + 's waiting for browser callback')), timeoutMs),\n )\n const got = await Promise.race([callback, timeout])\n void expectedState\n return got\n },\n }\n}\n\nfunction renderHtml(ok: boolean, message: string): string {\n const color = ok ? '#15803d' : '#b91c1c'\n return '<!doctype html><meta charset=\"utf-8\"><title>patchbay audit-oauth</title>' +\n '<body style=\"font:16px system-ui;max-width:520px;margin:4rem auto;padding:1rem;color:#111\">' +\n '<h1 style=\"color:' + color + '\">' + (ok ? 'Login complete' : 'Login failed') + '</h1>' +\n '<p>' + escapeHtml(message) + '</p>' +\n '<p style=\"color:#6b7280;font-size:14px\">patchbay audit-oauth · you can close this tab</p>' +\n '</body>'\n}\n\nfunction escapeHtml(s: string): string {\n return s.replace(/[&<>\"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '\"': '"', \"'\": ''' }[c]!))\n}\n\nfunction openUrl(url: string): void {\n const platform = process.platform\n try {\n if (platform === 'darwin') {\n spawn('open', [url], { stdio: 'ignore', detached: true }).unref()\n } else if (platform === 'win32') {\n // cmd /c start treats the first quoted arg as window title; pass \"\" as title.\n spawn('cmd', ['/c', 'start', '\"\"', url], { stdio: 'ignore', detached: true }).unref()\n } else {\n spawn('xdg-open', [url], { stdio: 'ignore', detached: true }).unref()\n }\n } catch { /* fall through; the stderr message tells the user to paste the URL manually */ }\n}\n"],"mappings":";AAiBA,SAAS,YAAY,mBAAmB;AACxC,SAAS,oBAAiC;AAC1C,SAAS,aAAa;AACtB,SAAS,KAAK,uBAAuB;AA0BrC,eAAsB,iBAAiB,QAAgB,OAAqB,CAAC,GAAyB;AACpG,QAAM,UAAU,QAAQ,KAAK,OAAO;AACpC,QAAM,MAAM,CAAC,QAAsB;AAA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