From b2a6788c6e9030f940b1205fbbb7ba5483973dbe Mon Sep 17 00:00:00 2001 From: "jfrog-skills-release-bot[bot]" <276080306+jfrog-skills-release-bot[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 09:45:47 +0000 Subject: [PATCH] [patch] chore: sync modules to v0.18.0 --- .codex-plugin/plugin.json | 2 +- .github/scripts/sync-modules-vendor.json | 2 +- modules/core/agent-guard-check.mjs | 66 +-- modules/core/claude-launch.mjs | 618 ++++++++++++++++++++ modules/core/enforce-skill.mjs | 81 ++- modules/core/jf-user-agent.mjs | 2 +- modules/core/jfrog-ai-governance-config.mjs | 548 +++++++++++++++++ modules/core/local-shadow-trigger.mjs | 75 ++- modules/core/rewrite-mcp-json.mjs | 288 ++------- package.json | 2 +- 10 files changed, 1349 insertions(+), 335 deletions(-) create mode 100644 modules/core/claude-launch.mjs create mode 100755 modules/core/jfrog-ai-governance-config.mjs diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 7727457..9050d37 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "jfrog", - "version": "0.1.19", + "version": "0.1.20", "description": "JFrog skills and the JFrog MCP server for Codex \u2014 interact with the JFrog Platform.", "author": { "name": "JFrog", diff --git a/.github/scripts/sync-modules-vendor.json b/.github/scripts/sync-modules-vendor.json index 33b2f3f..7d9dd85 100644 --- a/.github/scripts/sync-modules-vendor.json +++ b/.github/scripts/sync-modules-vendor.json @@ -1,6 +1,6 @@ { "repo": "JFROG/jfrog-agent-hooks", - "pin": "jfrog-agent-hooks/v0.16.2", + "pin": "jfrog-agent-hooks/v0.18.0", "paths": [ "modules" ] diff --git a/modules/core/agent-guard-check.mjs b/modules/core/agent-guard-check.mjs index 5fb4cb9..7dde664 100644 --- a/modules/core/agent-guard-check.mjs +++ b/modules/core/agent-guard-check.mjs @@ -18,6 +18,7 @@ import process from "node:process"; import { isMainEntry } from "./entry.mjs"; import { jfInvocation } from "./jf-process.mjs"; +import { resolveAiGovernanceConfig } from "./jfrog-ai-governance-config.mjs"; import { skillsProductUserAgent } from "./jf-user-agent.mjs"; import { proxyFetch } from "./proxy-fetch.mjs"; @@ -62,15 +63,13 @@ function makeDebug(env, debug) { } /** - * Resolve credentials from Path A (environment variables) or Path B - * (JFrog CLI configuration). + * Resolve credentials from the JFrog CLI config of one server: `serverId`, or + * the AI Governance server from setup.json when none is given. * * Intentionally distinct from `jf-identity.mjs`: - * - package-resolution identity is always `jf config` and may use Basic auth; - * - Agent Guard's settings probe needs a Bearer access token, and mirrors the - * AG CLI by preferring JFROG_URL/JF_URL + access token when set. - * - When `serverId` is set: that jf server first, then env, never the default - * CLI server. Without `serverId`: env first, then default `jf config export`. + * - package-resolution identity is the jf default server and may use Basic auth; + * - Agent Guard's settings probe needs a Bearer access token for the AI + * Governance server. JFROG_URL/JF_URL credentials are not used. * Do not reuse getPlatformIdentity() here without preserving that contract. * * @param {{ @@ -85,42 +84,19 @@ function makeDebug(env, debug) { export function resolveAgentGuardCredentials(opts = {}) { const env = opts.env ?? process.env; const debug = makeDebug(env, opts.debug); - const explicitServerId = opts.serverId?.trim() || undefined; - const execFn = opts.execFileSyncFn ?? execFileSync; - - if (explicitServerId) { - const fromCli = resolveFromCliConfig({ - serverId: explicitServerId, - env, - execFileSyncFn: execFn, - debug, - platform: opts.platform, - }); - if (fromCli) return fromCli; - debug( - "Explicit server ID did not resolve via jf config; falling back to env credentials.", - ); - } - - const envUrl = envLookup(env, "JFROG_URL", "JF_URL"); - const envToken = envLookup(env, "JFROG_ACCESS_TOKEN", "JF_ACCESS_TOKEN"); - if (envUrl && envToken) { - debug("Using credentials from environment variables (Path A)."); - return { - baseUrl: envUrl, - token: envToken, - source: "environment variables", - }; + let serverId = opts.serverId?.trim() || undefined; + if (!serverId) { + const config = resolveAiGovernanceConfig({ env, log: { debug } }); + if (config.status !== "ok" && config.status !== "no_project") { + debug(`No AI Governance server (${config.status}).`); + return null; + } + serverId = config.serverId; } - debug( - "Environment credentials incomplete; trying JFrog CLI config (Path B).", - ); - - if (explicitServerId) return null; return resolveFromCliConfig({ - serverId: undefined, + serverId, env, - execFileSyncFn: execFn, + execFileSyncFn: opts.execFileSyncFn ?? execFileSync, debug, platform: opts.platform, }); @@ -128,20 +104,18 @@ export function resolveAgentGuardCredentials(opts = {}) { /** * @param {{ - * serverId?: string, + * serverId: string, * env?: NodeJS.ProcessEnv, * execFileSyncFn?: typeof execFileSync, * debug?: (message: string) => void, + * platform?: NodeJS.Platform, * }} opts */ function resolveFromCliConfig(opts) { const debug = opts.debug ?? (() => {}); const env = opts.env ?? process.env; const execFn = opts.execFileSyncFn ?? execFileSync; - const exportArgs = opts.serverId - ? ["config", "export", opts.serverId] - : ["config", "export"]; - const invocation = jfInvocation(exportArgs, { + const invocation = jfInvocation(["config", "export", opts.serverId], { env, platform: opts.platform, }); @@ -362,7 +336,7 @@ export async function runAgentGuardCheck(opts = {}) { return { code: EXIT_DISABLED, reason: - "Disabled: JFROG_URL/JF_URL + access token not set and no default JF CLI config found", + "Disabled: no AI Governance server with an access token in the JF CLI config", }; } diff --git a/modules/core/claude-launch.mjs b/modules/core/claude-launch.mjs new file mode 100644 index 0000000..ff5daeb --- /dev/null +++ b/modules/core/claude-launch.mjs @@ -0,0 +1,618 @@ +// How Claude Code started the session, as the Local Shadow scanner's Launch +// (agent-guard --launch-json -). Keys are the scanner's JSON keys; a key we +// can't learn is left out, and the scanner uses its default for it. +// +// Sources: +// 1. the SessionStart payload: cwd, permission_mode, agent_type +// 2. Claude's environment, which the hook inherits +// 3. Claude's command line, found by walking up the hook's parent processes +// 4. ~/.claude.json (trust) and the running Claude's version +// +// The launch can hold secrets (--settings text, MCP configs), so it goes to +// agent-guard on stdin and is never logged; only its key names are. + +import { execFileSync } from "node:child_process"; +import { readFileSync, readlinkSync } from "node:fs"; +import { homedir } from "node:os"; +import path from "node:path"; +import process from "node:process"; + +// Each env key the scanner reads, copied as is when set. +const LAUNCH_ENV_KEYS = Object.freeze([ + "CLAUDE_CODE_USE_POWERSHELL_TOOL", + "CLAUDE_CODE_DISABLE_DANGEROUS_RM_TIMEOUT", + "CLAUDE_CODE_DISABLE_BUNDLED_SKILLS", + "CLAUDE_CODE_DISABLE_WEB_FETCH", + "DISABLE_TELEMETRY", + "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", +]); + +// CLAUDE_CODE_ENTRYPOINT → the scanner's surface. +const SURFACES = Object.freeze({ + cli: "terminal", + "claude-vscode": "vscode", + "claude-desktop": "desktop", + "sdk-ts": "agent_sdk", + "sdk-py": "agent_sdk", + "sdk-cli": "agent_sdk", +}); + +// The env flag that selects each provider. Without one the provider is +// claude.ai or console, which the environment can't tell apart. +const PROVIDER_ENV = Object.freeze([ + ["CLAUDE_CODE_USE_BEDROCK", "bedrock"], + ["CLAUDE_CODE_USE_VERTEX", "agent_platform"], + ["CLAUDE_CODE_USE_FOUNDRY", "foundry"], +]); + +// How far up the process tree Claude may be: hook → shell → claude, plus +// wrappers such as npx or a version manager. +const MAX_ANCESTORS = 8; +const COMMAND_TIMEOUT_MS = 5_000; + +const isOn = (value) => + typeof value === "string" && + value !== "" && + value !== "0" && + value.toLowerCase() !== "false"; + +const text = (value) => + typeof value === "string" && value ? value : undefined; + +const VERSION = /\d+\.\d+\.\d+/; + +// Path functions for the platform the paths come from. +const pathFor = (platform) => (platform === "win32" ? path.win32 : path.posix); + +// Windows env keys are case-insensitive (`SystemRoot`), but a copied env object +// is a plain object. +function envValue(env, name) { + const key = Object.keys(env).find((k) => k.toUpperCase() === name); + return key ? env[key] : undefined; +} + +// The scanner's name for the OS. +export function scannerOS(platform, env = {}, readFileFn = readFileSync) { + if (platform === "darwin") return "macos"; + if (platform === "win32") return "windows"; + if (platform === "linux") { + if (env.WSL_DISTRO_NAME) return "wsl"; + try { + if (/microsoft/i.test(readFileFn("/proc/version", "utf8"))) return "wsl"; + } catch { + // no /proc/version: plain linux + } + } + return platform; +} + +// Fields from the SessionStart payload. +export function launchFromPayload(payload) { + const out = {}; + if (text(payload?.cwd)) out.cwd = payload.cwd; + if (text(payload?.permission_mode)) + out.permission_mode = payload.permission_mode; + if (text(payload?.agent_type)) out.agent = payload.agent_type; + return out; +} + +// Fields from Claude's environment. +export function launchFromEnv(env, platform) { + const out = {}; + if (text(env.CLAUDE_CONFIG_DIR)) out.config_dir = env.CLAUDE_CONFIG_DIR; + const launchEnv = {}; + for (const key of LAUNCH_ENV_KEYS) { + if (typeof env[key] === "string") launchEnv[key] = env[key]; + } + if (Object.keys(launchEnv).length) out.env = launchEnv; + const entrypoint = text(env.CLAUDE_CODE_ENTRYPOINT); + if (entrypoint) out.surface = SURFACES[entrypoint] ?? "unknown"; + const provider = PROVIDER_ENV.find(([key]) => isOn(env[key])); + if (provider) out.provider = provider[1]; + if (platform === "win32" && text(env.CLAUDE_CODE_GIT_BASH_PATH)) + out.git_bash = "true"; + return out; +} + +// A .claude.json projects key or a cwd, comparable: / separators, no trailing +// slash, and no case on Windows and macOS, whose file systems ignore it. +function trustKey(dir, platform) { + let key = dir.replaceAll("\\", "/"); + if (key.length > 1) key = key.replace(/\/+$/, ""); + return platform === "win32" || platform === "darwin" + ? key.toLowerCase() + : key; +} + +// The workspace's trust, as Claude decides it from .claude.json: "true" when +// the workspace or any folder above it has hasTrustDialogAccepted true (Claude +// doesn't ask in a folder under a trusted one); "false" when an entry says +// false and none above is trusted; nothing when no folder up to the root has +// an entry. +export function workspaceTrust( + cwd, + { + env, + home = homedir(), + platform = process.platform, + readFileFn = readFileSync, + }, +) { + if (!cwd) return undefined; + const file = path.join(env.CLAUDE_CONFIG_DIR || home, ".claude.json"); + let projects; + try { + projects = JSON.parse(readFileFn(file, "utf8"))?.projects; + } catch { + return undefined; + } + if (!projects || typeof projects !== "object") return undefined; + const accepted = new Map(); + for (const [key, entry] of Object.entries(projects)) { + const value = entry?.hasTrustDialogAccepted; + if (typeof value !== "boolean") continue; + const k = trustKey(key, platform); + accepted.set(k, accepted.get(k) === true || value); + } + let found; + for (let dir = trustKey(cwd, platform); ; ) { + const value = accepted.get(dir); + if (value === true) return "true"; + if (value === false) found = "false"; + const parent = path.posix.dirname(dir); + if (parent === dir || parent === ".") break; + dir = parent; + } + return found; +} + +// The running Claude's executable as an absolute path, or undefined. argv[0] +// is often a bare "claude" the shell found on PATH, so the OS is asked for +// the file the process runs: /proc on Linux, lsof's first txt file on macOS +// (ps prints argv[0] as typed), the process list on Windows. +function claudeExecutable({ pid, program }, { platform, execFn, readlinkFn }) { + const { isAbsolute } = pathFor(platform); + let exe; + try { + if (platform === "linux") exe = readlinkFn(`/proc/${pid}/exe`); + else if (platform !== "win32") { + const out = execFn( + "/usr/sbin/lsof", + ["-w", "-a", "-p", String(pid), "-d", "txt", "-Fn"], + { + encoding: "utf8", + timeout: COMMAND_TIMEOUT_MS, + stdio: ["ignore", "pipe", "ignore"], + }, + ); + exe = /^n(.+)$/m.exec(out)?.[1]; + } + } catch { + // fall back to argv[0] + } + if (exe && isAbsolute(exe)) return exe; + return program && isAbsolute(program) ? program : undefined; +} + +// The running Claude's version (see findClaude): the package.json next to +// cli.js for an npm install run by node, else ` --version` +// ("2.1.311 (Claude Code)"). Never a bare `claude` from PATH, which may be +// another install, or a file in the workspace on Windows. +export function claudeVersion( + claude, + { + platform = process.platform, + env = process.env, + execFn = execFileSync, + readFileFn = readFileSync, + readlinkFn = readlinkSync, + } = {}, +) { + if (!claude) return undefined; + try { + if (claude.script) { + const { dirname, join } = pathFor(platform); + const pkg = JSON.parse( + readFileFn(join(dirname(claude.script), "package.json"), "utf8"), + ); + return VERSION.exec(String(pkg?.version))?.[0]; + } + const exe = claudeExecutable(claude, { platform, execFn, readlinkFn }); + if (!exe) return undefined; + const out = execFn(exe, ["--version"], { + encoding: "utf8", + timeout: COMMAND_TIMEOUT_MS, + stdio: ["ignore", "pipe", "ignore"], + env, + windowsHide: true, + }); + return VERSION.exec(out)?.[0]; + } catch { + return undefined; + } +} + +// Splits a Windows command line by the CommandLineToArgvW rules. +export function splitWindowsCommandLine(line) { + const args = []; + let cur = ""; + let inQuotes = false; + let hasArg = false; + for (let i = 0; i < line.length; i++) { + const c = line[i]; + if (c === "\\") { + let n = 0; + while (line[i] === "\\") { + n++; + i++; + } + if (line[i] === '"') { + cur += "\\".repeat(Math.floor(n / 2)); + if (n % 2) cur += '"'; + else { + inQuotes = !inQuotes; + } + } else { + cur += "\\".repeat(n); + i--; + } + hasArg = true; + } else if (c === '"') { + inQuotes = !inQuotes; + hasArg = true; + } else if (/\s/.test(c) && !inQuotes) { + if (hasArg) args.push(cur); + cur = ""; + hasArg = false; + } else { + cur += c; + hasArg = true; + } + } + if (hasArg) args.push(cur); + return args; +} + +// The hook's ancestors, nearest first: [{ pid, argv, exe? }]. argv is exact on +// Linux and Windows; on macOS ps joins it with spaces, so it's rebuilt by +// psArgv. exe, the executable's full path, is known on Windows only. +export function listAncestors({ + pid = process.ppid, + platform = process.platform, + env = process.env, + execFn = execFileSync, + readFileFn = readFileSync, +} = {}) { + if (platform === "linux") return linuxAncestors(pid, readFileFn); + if (platform === "win32") return windowsAncestors(pid, env, execFn); + return psAncestors(pid, execFn); +} + +function linuxAncestors(pid, readFileFn) { + const out = []; + for (let i = 0; i < MAX_ANCESTORS && pid > 1; i++) { + try { + const argv = readFileFn(`/proc/${pid}/cmdline`, "utf8") + .split("\0") + .filter((a, idx, all) => idx < all.length - 1 || a !== ""); + out.push({ pid, argv }); + const status = readFileFn(`/proc/${pid}/status`, "utf8"); + pid = Number(/^PPid:\s*(\d+)/m.exec(status)?.[1] ?? 0); + } catch { + break; + } + } + return out; +} + +// ps for each ancestor only, so no other process's command line is read: its +// parent and program (comm), then its command line (args). +function psAncestors(pid, execFn) { + function ps(fields) { + return execFn("ps", ["-o", fields, "-p", String(pid)], { + encoding: "utf8", + timeout: COMMAND_TIMEOUT_MS, + stdio: ["ignore", "pipe", "ignore"], + }); + } + const ancestors = []; + for (let i = 0; i < MAX_ANCESTORS && pid > 1; i++) { + let head, args; + try { + head = ps("ppid=,comm="); + args = ps("args="); + } catch { + break; + } + const m = /^\s*(\d+)\s+(.*?)\s*$/s.exec(head); + if (!m) break; + ancestors.push({ pid, argv: psArgv(m[2], args.trim()) }); + pid = Number(m[1]); + } + return ancestors; +} + +const CLI_END = /[\\/]@anthropic-ai[\\/]claude-code[\\/]cli\.m?js(?=\s|$)/; + +// argv from macOS ps, which prints it joined with spaces, so a path with a +// space can't be split back on whitespace. comm is the program as it was +// started, spaces kept, and args starts with it. When the program isn't Claude +// itself, an npm install's cli.js is kept whole too: it runs from the nearest +// word before cli.js that starts a path (/, ~, ./ or ../). Only the other +// arguments are split on whitespace, so a value with a space in it is still +// cut. +export function psArgv(comm, args) { + let program = comm; + let rest = ""; + if (comm && (!args || args === comm || args.startsWith(`${comm} `))) { + rest = args.slice(comm.length).trim(); + } else { + [program = "", ...rest] = args.split(/\s+/); + rest = rest.join(" "); + } + const argv = [program]; + const end = isClaudeProgram(program) ? null : CLI_END.exec(rest); + if (end) { + const stop = end.index + end[0].length; + const words = [...rest.slice(0, stop).matchAll(/\S+/g)]; + const first = words.findLastIndex((w) => /^(?:[/~]|\.\.?\/)/.test(w[0])); + const start = words[first >= 0 ? first : words.length - 1].index; + argv.push(...splitWords(rest.slice(0, start)), rest.slice(start, stop)); + rest = rest.slice(stop); + } + argv.push(...splitWords(rest)); + return argv; +} + +function splitWords(s) { + return s.split(/\s+/).filter(Boolean); +} + +function isClaudeProgram(program) { + const name = path.basename(program.replaceAll("\\", "/")); + return name.replace(/\.exe$/i, "") === "claude"; +} + +// PowerShell by full path, never a bare name a workspace file could answer. +function powershellPath(env) { + const root = envValue(env, "SYSTEMROOT"); + const systemRoot = root && path.win32.isAbsolute(root) ? root : "C:\\Windows"; + return path.win32.join( + systemRoot, + "System32", + "WindowsPowerShell", + "v1.0", + "powershell.exe", + ); +} + +function windowsAncestors(pid, env, execFn) { + const script = [ + `$p = ${Number(pid)}`, + "$out = @()", + `for ($i = 0; $i -lt ${MAX_ANCESTORS}; $i++) {`, + ' $w = Get-CimInstance Win32_Process -Filter "ProcessId=$p"', + " if (-not $w) { break }", + " $out += [pscustomobject]@{ pid = $p; cmd = $w.CommandLine; exe = $w.ExecutablePath }", + " $p = $w.ParentProcessId", + "}", + "ConvertTo-Json -InputObject $out -Compress", + ].join("\n"); + const json = execFn( + powershellPath(env), + ["-NoProfile", "-NonInteractive", "-Command", script], + { + encoding: "utf8", + timeout: COMMAND_TIMEOUT_MS, + stdio: ["ignore", "pipe", "ignore"], + windowsHide: true, + }, + ); + return (JSON.parse(json) ?? []).map(({ pid: p, cmd, exe }) => ({ + pid: p, + argv: splitWindowsCommandLine(cmd ?? ""), + ...(text(exe) && { exe }), + })); +} + +// The running Claude among the ancestors, or null: its pid, its own arguments +// (after the program, or after cli.js for an npm install run by node), and +// what its version is read from: program (its executable, or argv[0]) or +// script (cli.js). +export function findClaude(ancestors) { + for (const { pid, argv, exe } of ancestors) { + if (!argv.length) continue; + if (isClaudeProgram(argv[0])) + return { pid, program: exe ?? argv[0], args: argv.slice(1) }; + const script = argv.findIndex((a) => + /[\\/]@anthropic-ai[\\/]claude-code[\\/]cli\.(js|mjs)$/.test(a), + ); + if (script >= 0) + return { pid, script: argv[script], args: argv.slice(script + 1) }; + } + return null; +} + +// Claude's own arguments, or null when no ancestor is Claude. +export function findClaudeArgs(ancestors) { + return findClaude(ancestors)?.args ?? null; +} + +// Claude's CLI flags → Launch keys. kind: bool (no value), one (one value), +// many (values until the next flag). +const FLAGS = Object.freeze({ + "--permission-mode": ["one", "permission_mode"], + "--dangerously-skip-permissions": ["bool", "dangerously_skip_permissions"], + "--allow-dangerously-skip-permissions": [ + "bool", + "allow_dangerously_skip_permissions", + ], + "-p": ["bool", "print"], + "--print": ["bool", "print"], + "--settings": ["one", "settings"], + "--setting-sources": ["one", "setting_sources"], + "--add-dir": ["many", "add_dirs"], + "--plugin-dir": ["many", "plugin_dirs"], + "--plugin-url": ["many", "plugin_urls"], + "--agent": ["one", "agent"], + "--agents": ["one", "agents_json"], + "--mcp-config": ["many", "mcp_config"], + "--strict-mcp-config": ["bool", "strict_mcp_config"], + "--allowedTools": ["many", "allowed_tools"], + "--allowed-tools": ["many", "allowed_tools"], + "--disallowedTools": ["many", "disallowed_tools"], + "--disallowed-tools": ["many", "disallowed_tools"], + "--tools": ["many", "tools"], + "--bare": ["bool", "bare"], + "--safe-mode": ["bool", "safe_mode"], + "--restricted": ["bool", "restricted"], + "--disable-slash-commands": ["bool", "disable_slash_commands"], + "--permission-prompt-tool": ["one", "permission_prompt_tool"], + "--permission-prompts": ["one", "permission_prompts"], + "--init": ["bool", "init"], + "--init-only": ["bool", "init_only"], + "--maintenance": ["bool", "maintenance"], +}); + +// A value that ps split on whitespace, joined back: inline JSON until it +// parses, and a tool rule like Bash(git log:*) until its parentheses close. +// Returns [value, next index]. +function takeValue(args, start) { + const first = args[start]; + if (first.startsWith("{") || first.startsWith("[")) + return takeJSONValue(args, start); + let value = first; + let end = start + 1; + while (openParens(value) > 0 && end < args.length) value += " " + args[end++]; + return [value, end]; +} + +function openParens(text) { + return (text.match(/\(/g) ?? []).length - (text.match(/\)/g) ?? []).length; +} + +function takeJSONValue(args, start) { + for (let end = start + 1; end <= args.length; end++) { + const candidate = args.slice(start, end).join(" "); + try { + JSON.parse(candidate); + return [candidate, end]; + } catch { + // keep joining + } + } + return [args[start], start + 1]; +} + +// A flag value that is inline JSON stays text; any other value is a file. +// Returns the file's text, or undefined when it can't be read. +function configText(value, cwd, readFileFn) { + if (value.trimStart().startsWith("{")) return value; + try { + return readFileFn(path.resolve(cwd ?? "", value), "utf8"); + } catch { + return undefined; + } +} + +// Parses Claude's arguments into Launch keys. Unknown flags and positional +// arguments (the prompt) are skipped. +export function launchFromArgs(args, { cwd, readFileFn = readFileSync } = {}) { + const out = {}; + const raw = {}; + for (let i = 0; i < args.length; ) { + const arg = args[i]; + const eq = arg.startsWith("--") ? arg.indexOf("=") : -1; + const name = eq > 0 ? arg.slice(0, eq) : arg; + const spec = Object.hasOwn(FLAGS, name) ? FLAGS[name] : undefined; + if (!spec) { + i++; + continue; + } + const [kind, key] = spec; + if (kind === "bool") { + raw[key] = true; + i++; + continue; + } + const values = []; + if (eq > 0) { + values.push(arg.slice(eq + 1)); + i++; + } else { + i++; + while (i < args.length && !args[i].startsWith("-")) { + const [value, next] = takeValue(args, i); + values.push(value); + i = next; + if (kind === "one") break; + } + } + if (!values.length) continue; + raw[key] = kind === "one" ? values[0] : [...(raw[key] ?? []), ...values]; + } + + for (const [key, value] of Object.entries(raw)) { + if (key === "settings") { + if (value.trimStart().startsWith("{")) out.settings_text = value; + else out.settings_path = path.resolve(cwd ?? "", value); + } else if (key === "mcp_config") { + const texts = value + .map((v) => configText(v, cwd, readFileFn)) + .filter(Boolean); + if (texts.length) out.mcp_config_text = texts; + } else if (key === "add_dirs" || key === "plugin_dirs") { + out[key] = value.map((dir) => path.resolve(cwd ?? "", dir)); + } else if (key === "allowed_tools" || key === "disallowed_tools") { + out[key] = value.flatMap((v) => + v + .split(/[\s,]+(?![^(]*\))/) + .map((t) => t.trim()) + .filter(Boolean), + ); + } else if (key === "tools") { + out.tools = value.join(" "); + } else { + out[key] = value; + } + } + return out; +} + +// The session's launch. Every source is best effort: a source that fails adds +// nothing. Fields from the command line win over the payload, except cwd and a +// payload permission_mode, which say what the session is now. +export function buildLaunch( + payload, + { + env = process.env, + platform = process.platform, + home = homedir(), + readFileFn = readFileSync, + listAncestorsFn = listAncestors, + claudeVersionFn = claudeVersion, + } = {}, +) { + const fromPayload = launchFromPayload(payload); + const cwd = fromPayload.cwd; + let claude = null; + let fromArgs = {}; + try { + claude = findClaude(listAncestorsFn({ platform, env })); + if (claude) fromArgs = launchFromArgs(claude.args, { cwd, readFileFn }); + } catch { + // no process list: no CLI flags, and no version + } + const launch = { + home, + os: scannerOS(platform, env, readFileFn), + ...launchFromEnv(env, platform), + ...fromArgs, + ...fromPayload, + }; + const trusted = workspaceTrust(cwd, { env, home, platform, readFileFn }); + if (trusted) launch.trusted = trusted; + const version = claudeVersionFn(claude, { platform, env, readFileFn }); + if (version) launch.claude_version = version; + return launch; +} diff --git a/modules/core/enforce-skill.mjs b/modules/core/enforce-skill.mjs index 965214e..f46e669 100644 --- a/modules/core/enforce-skill.mjs +++ b/modules/core/enforce-skill.mjs @@ -2,11 +2,13 @@ // Agent Guard launcher for the skill-governance hooks. // node enforce-skill.mjs --client [--prefer-offline] // -// Starts `npx @jfrog/agent-guard --enforce-skill --client [--server ]`. -// The server is the jf CLI one Agent Guard would pick on its own. The hook -// string is only `node` plus this file: VS Code (and Claude Code without Git -// Bash) runs hook strings with PowerShell on Windows, which cannot parse a POSIX -// env prefix or $(date). This process computes the deadline, bounds the npm +// Starts `npx @jfrog/agent-guard --enforce-skill --client --server +// [--project ]`. The server and project are the AI Governance ones +// from setup.json: the server is "" when none is set, and --project is left +// out when no project is saved or no server is sent. The hook string is only +// `node` plus this file: VS Code (and Claude Code without Git Bash) runs +// hook strings with PowerShell on Windows, which cannot parse a POSIX env +// prefix or $(date). This process computes the deadline, bounds the npm // fetch, then spawns npx. It does not read the verdict: Agent Guard's exit 0 // or 2 passes through with its stdout. // @@ -14,7 +16,7 @@ // arrive intact. Only when npm is not beside node.exe does it fall back to // npx.cmd under cmd.exe, and then it refuses an argument cmd.exe cannot carry // (%, ", CR/LF) rather than mangle it, except the optional server id, which it -// leaves out. +// empties, and the project, which it leaves out. // // Every other outcome (bad argv, spawn failure, signal, any other exit code) // fails open in the shape the client reads as "allow", see FAIL_OPEN. Agent @@ -34,11 +36,10 @@ import path from "node:path"; import process from "node:process"; import { isMainEntry } from "./entry.mjs"; +import { resolveAiGovernanceConfig } from "./jfrog-ai-governance-config.mjs"; import { createLogger } from "./logger.mjs"; import { AGENT_GUARD_PACKAGE, - listJfCliServers, - pickDefaultJfCliServer, resolveAgentGuardNpmRegistry, } from "./rewrite-mcp-json.mjs"; @@ -163,30 +164,40 @@ export function quoteCmdArg(arg) { } /** - * The jf CLI server Agent Guard picks when run without `--server`: the only - * one configured, or the default. With JFROG_URL set it uses env credentials - * instead, so there is nothing to pass. + * The AI Governance server and project saved in setup.json by /jfrog-init. + * When no server is set the launcher passes `--server ""`, which Agent Guard + * reads as no server set, so it allows the skill and contacts nothing. * * @param {NodeJS.ProcessEnv} [env] - * @returns {string} the server id, or "" when Agent Guard should choose + * @returns {{ serverId: string, project: string }} "" for each one not set */ -export function defaultServerId(env = process.env) { - if (env.JFROG_URL) return ""; - const picked = pickDefaultJfCliServer(listJfCliServers({ env })); - return "serverId" in picked ? picked.serverId : ""; +export function aiGovernanceTarget(env = process.env) { + const config = resolveAiGovernanceConfig({ env, log }); + if (config.status === "ok") { + return { serverId: config.serverId, project: config.project }; + } + return { + serverId: config.status === "no_project" ? config.serverId : "", + project: "", + }; } /** * Spawn plan for `npx --enforce-skill`. POSIX runs npx with no shell. Windows * runs npx-cli.js with node, falling back to npx.cmd under cmd.exe (not * ComSpec, which may be PowerShell) only when npm is not beside node.exe. - * The optional `serverId` follows `--client`; the cmd.exe fallback omits it when - * cmd.exe cannot carry it, since the id is never worth failing open over. + * `--server` and the id always follow `--client`, the id empty when none is + * set. `--project` and the project follow them, and are left out when there is + * no project or the server id is sent empty. The cmd.exe fallback sends an + * empty id when cmd.exe cannot carry the real one, so the flag is never absent + * and the id is never worth failing open over. It leaves out a project it + * cannot carry. * * @param {{ * client: string, * preferOffline?: boolean, * serverId?: string, + * project?: string, * env?: NodeJS.ProcessEnv, * nowSec?: number, * platform?: NodeJS.Platform, @@ -205,6 +216,11 @@ export function resolveEnforceSpawn(opts) { npm_config_fetch_retries: NPM_FETCH_RETRIES, npm_config_fetch_timeout: NPM_FETCH_TIMEOUT_MS, }; + // Without --project, Agent Guard takes the project from setup.json. It still + // reads these env vars when set, so drop them (AX-2405 removes that fallback + // in Agent Guard). + delete childEnv.JF_PROJECT; + delete childEnv.JFROG_PROJECT; // An inherited absolute deadline would pin this run to an earlier instant. if (Number.isFinite(opts.nowSec)) { childEnv.JF_AGENT_GUARD_ENFORCE_DEADLINE = String( @@ -225,14 +241,19 @@ export function resolveEnforceSpawn(opts) { opts.client, ); - const server = - opts.serverId && !opts.serverId.startsWith("--") - ? ["--server", opts.serverId] + // An id starting with `--` is sent empty, and a project starting with `--` + // or without its server is not sent. + const serverId = + opts.serverId && !opts.serverId.startsWith("--") ? opts.serverId : ""; + const server = ["--server", serverId]; + const project = + serverId && opts.project && !opts.project.startsWith("--") + ? ["--project", opts.project] : []; if (platform !== "win32") { return { command: "npx", - args: [...args, ...server], + args: [...args, ...server, ...project], shell: false, env: childEnv, }; @@ -241,16 +262,26 @@ export function resolveEnforceSpawn(opts) { if (cli) { return { command: execPath, - args: [cli, ...args, ...server], + args: [cli, ...args, ...server, ...project], shell: false, env: childEnv, }; } const quoted = args.map(quoteCmdArg); + let carriesServer = true; try { quoted.push(...server.map(quoteCmdArg)); } catch { - // cmd.exe cannot carry this id; Agent Guard resolves the server itself. + // cmd.exe cannot carry this id; send no server rather than fail open. + carriesServer = false; + quoted.push(...["--server", ""].map(quoteCmdArg)); + } + if (carriesServer) { + try { + quoted.push(...project.map(quoteCmdArg)); + } catch { + // cmd.exe cannot carry this project; Agent Guard reads it from setup.json. + } } return { command: "npx.cmd", @@ -314,7 +345,7 @@ export function runEnforceSkill(opts = {}) { try { plan = resolveEnforceSpawn({ ...parseEnforceArgs(argv), - serverId: defaultServerId(env), + ...aiGovernanceTarget(env), env, nowSec, platform: opts.platform, diff --git a/modules/core/jf-user-agent.mjs b/modules/core/jf-user-agent.mjs index 7719c6f..c1600e5 100644 --- a/modules/core/jf-user-agent.mjs +++ b/modules/core/jf-user-agent.mjs @@ -20,7 +20,7 @@ import { spawnJfSync } from "./jf-process.mjs"; // Plugin sync stamps this literal with the release semver (jfrog-sync-modules.py // stamp). Only `modules/` is vendored, so nothing outside this tree is readable // at runtime. Unstamped trees (this repo, local dev) report 0.0.0. -const PKG_VERSION = "0.16.2"; +const PKG_VERSION = "0.18.0"; /** Hooks release semver stamped at plugin sync ("0.0.0" when unstamped). */ export function hooksPackageVersion() { diff --git a/modules/core/jfrog-ai-governance-config.mjs b/modules/core/jfrog-ai-governance-config.mjs new file mode 100755 index 0000000..db7f8aa --- /dev/null +++ b/modules/core/jfrog-ai-governance-config.mjs @@ -0,0 +1,548 @@ +#!/usr/bin/env node +// jfrog-ai-governance-config.mjs — resolve and update the JFrog AI Governance +// server and project in ${JFROG_CLI_HOME_DIR:-~/.jfrog}/setup.json. +// +// Usage, commands, options and exit codes: see USAGE below (also printed on a +// usage error). +// +// Contract: +// - Exactly one entry has `isDefault`. A v1 file with a single entry is +// treated as its default and migrated (written back as v2) by `get`. +// - `set` on an ambiguous file (no clear default) needs no --force and +// leaves the target as the only default. +// - A file whose `version` is newer than this script knows is read, but +// never written. +// - Unknown keys are preserved on every write. +// - Writes are temp file + rename, no lock. +// - stderr: an `info:` line if deprecated env vars are set; `debug:` lines +// with JF_AGENT_GUARD_LOG_LEVEL=debug. +// - Self-contained (Node builtins only): copied verbatim into the hooks, +// which import resolveAiGovernanceConfig and run `server-id`. +// +// File shape: +// { "version", "servers": { "": { "jpdUrl", "currentActiveProject"?, +// "isDefault"? } } } + +import { spawnSync } from "node:child_process"; +import { randomBytes } from "node:crypto"; +import { + mkdirSync, + readFileSync, + realpathSync, + renameSync, + unlinkSync, + writeFileSync, +} from "node:fs"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const USAGE = `\ +Usage: jfrog-ai-governance-config.mjs [options] + +Commands: + get Print the AI Governance server and project as JSON: + {status, serverId?, jpdUrl?, project?, path?}. + status: ok | no_project | ambiguous | missing | corrupt + (corrupt: setup.json is not valid; path names it). + list Print every saved server as a JSON array of + {serverId, jpdUrl, project?, isDefault}. + set [project] Make the AI Governance server (jpdUrl + from \`jf config show\`). + Project omitted: keep the saved one. + server-id Print only the server id, for command substitution. + Prints nothing if the id is invalid (see set). + Always exits 0. + +Options: + --no-project set: save no project; clears a saved one (needs --force). + --force set: override the saved server or project, or + replace a corrupt file. Only when you know what + you are doing. + +Environment: + JF_AGENT_GUARD_LOG_LEVEL=debug Print debug lines on stderr. + +Exit codes: + 0 ok + 1 set failed (message on stderr) + 2 usage error +`; +const CURRENT_VERSION = 2; +const DEPRECATED_ENV = [ + "JFROG_URL", + "JF_URL", + "JFROG_ACCESS_TOKEN", + "JF_ACCESS_TOKEN", + "JF_PROJECT", + "JFROG_PROJECT", + "JF_SERVER", + "JFROG_SERVER_ID", + "JF_SERVER_ID", +]; +const NOOP_LOG = { debug() {} }; +// The charset the hooks accept for ids passed to agent-guard. The jf CLI does +// not limit server ids (it only rejects delete, use, show, clear): enforced here. +const SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/; +const SAFE_ID_RULE = + 'letters, digits, ".", "_" or "-", starting with a letter or digit, at most 128 characters'; + +// import.meta.url is symlink-resolved, argv[1] is not; compare real paths. +function isMainModule(moduleUrl) { + if (!process.argv[1]) return false; + try { + return fileURLToPath(moduleUrl) === realpathSync(process.argv[1]); + } catch { + return false; + } +} + +const isObject = (v) => + v !== null && typeof v === "object" && !Array.isArray(v); +const nonEmpty = (v) => typeof v === "string" && v !== ""; + +function aiGovernanceConfigPath(env) { + return join( + env.JFROG_CLI_HOME_DIR || join(homedir(), ".jfrog"), + "setup.json", + ); +} + +// A missing file has no entries. A file that exists but is unreadable, not a +// JSON object, or has a non-object `servers` is `corrupt` (and has no data). +function loadSetup(path, log) { + const corrupt = { data: null, entries: [], corrupt: true }; + let parsed; + try { + parsed = JSON.parse(readFileSync(path, "utf8")); + } catch (err) { + if (err.code === "ENOENT") { + log.debug(`no setup.json at ${path}`); + return { data: null, entries: [], absent: true }; + } + log.debug( + err instanceof SyntaxError + ? `${path} is not valid JSON` + : `could not read ${path}: ${err.code || err.message}`, + ); + return corrupt; + } + if (!isObject(parsed)) { + log.debug(`${path} is not a JSON object`); + return corrupt; + } + if (parsed.servers !== undefined && !isObject(parsed.servers)) { + log.debug(`${path}: "servers" is not an object`); + return corrupt; + } + const entries = Object.entries(parsed.servers ?? {}).filter(([, e]) => + isObject(e), + ); + return { data: parsed, entries }; +} + +const isNewer = (data) => + typeof data?.version === "number" && data.version > CURRENT_VERSION; + +// The entry `get` would select, or null when ambiguous. A lone entry without +// isDefault is the implied default. +function select(entries) { + const defaults = entries.filter(([, e]) => e.isDefault === true); + if (defaults.length === 1) { + return { id: defaults[0][0], entry: defaults[0][1], implied: false }; + } + if (defaults.length === 0 && entries.length === 1) { + return { id: entries[0][0], entry: entries[0][1], implied: true }; + } + return null; +} + +function writeAtomic(path, data) { + mkdirSync(dirname(path), { recursive: true, mode: 0o700 }); + const tmp = `${path}.${randomBytes(6).toString("hex")}.tmp`; + try { + // "wx" fails if anything (e.g. a planted symlink) already exists at tmp. + writeFileSync(tmp, JSON.stringify(data, null, 2) + "\n", { + flag: "wx", + mode: 0o644, + }); + renameSync(tmp, path); + } catch (err) { + try { + unlinkSync(tmp); + } catch { + // Never created or already renamed. + } + throw err; + } +} + +/** + * Select the AI Governance server from setup.json, migrating a lone v1 entry to v2. + * @param {object} [options] + * @param {NodeJS.ProcessEnv} [options.env] default process.env + * @param {{debug(message: string): void}} [options.log] default silent + * @returns {{status: "missing" | "ambiguous"} + * | {status: "corrupt", path: string} + * | {status: "ok" | "no_project", serverId: string, jpdUrl: string, project?: string}} + * corrupt: the file exists but is not a valid setup object. + */ +export function resolveAiGovernanceConfig({ + env = process.env, + log = NOOP_LOG, +} = {}) { + const path = aiGovernanceConfigPath(env); + log.debug(`reading ${path}`); + const { data, entries, corrupt } = loadSetup(path, log); + if (corrupt) return { status: "corrupt", path }; + if (entries.length === 0) { + log.debug("missing: no usable entries"); + return { status: "missing" }; + } + const sel = select(entries); + if (!sel) { + const marked = entries.filter(([, e]) => e.isDefault === true).length; + log.debug( + marked + ? `ambiguous: ${marked} entries marked isDefault` + : `ambiguous: ${entries.length} entries, none marked isDefault`, + ); + return { status: "ambiguous" }; + } + log.debug( + `default "${sel.id}" (${sel.implied ? "only entry, implied" : "explicit isDefault"})`, + ); + if (sel.implied && !isNewer(data)) { + try { + writeAtomic(path, { + ...data, + version: CURRENT_VERSION, + servers: { + ...data.servers, + [sel.id]: { ...sel.entry, isDefault: true }, + }, + }); + log.debug(`migrated ${path}: "${sel.id}" is now the default`); + } catch (err) { + log.debug(`migration write to ${path} failed: ${err.message}`); + } + } + const base = { serverId: sel.id, jpdUrl: sel.entry.jpdUrl }; + const project = sel.entry.currentActiveProject; + if (nonEmpty(project)) return { status: "ok", ...base, project }; + log.debug(`no_project: "${sel.id}" has no currentActiveProject`); + return { status: "no_project", ...base }; +} + +// Same as `get` but never migrates. +function listAiGovernanceConfig({ env = process.env, log = NOOP_LOG } = {}) { + const path = aiGovernanceConfigPath(env); + log.debug(`reading ${path}`); + return loadSetup(path, log) + .entries.map(([serverId, e]) => ({ + serverId, + jpdUrl: e.jpdUrl, + ...(nonEmpty(e.currentActiveProject) && { + project: e.currentActiveProject, + }), + isDefault: e.isDefault === true, + })) + .sort((a, b) => a.serverId.localeCompare(b.serverId)); +} + +// Platform root URL, or "" when `raw` is not an http(s) URL. A missing scheme +// means https. +function normalizeJpdUrl(raw) { + const s = raw.trim(); + try { + const url = new URL(/^[a-z][a-z\d+.-]*:\/\//i.test(s) ? s : `https://${s}`); + if (!["http:", "https:"].includes(url.protocol)) return ""; + return url.origin + url.pathname.replace(/(\/(artifactory|ui))*\/*$/, ""); + } catch { + return ""; + } +} + +// Returns the server list, or null when jf could not be run or its output +// was unusable (reported to the caller as "could not run jf", distinct from +// "server not configured"). jf is looked up on PATH only. +function loadJfServers(env, log) { + // On Windows an npm-installed jf is a .cmd shim, which only a shell can + // launch; the command is a constant, so passing it as one string is safe. + const opts = { encoding: "utf8", env, timeout: 30_000 }; + const r = + process.platform === "win32" + ? spawnSync("jf config show --format=json", { ...opts, shell: true }) + : spawnSync("jf", ["config", "show", "--format=json"], opts); + if (r.error || r.status !== 0) { + log.debug( + `jf config show failed: ${r.error?.message || `exit ${r.status}`}`, + ); + return null; + } + try { + const parsed = JSON.parse(r.stdout); + if (Array.isArray(parsed)) return parsed; + if (Array.isArray(parsed?.servers)) return parsed.servers; + } catch (err) { + log.debug(`jf config show output not parseable: ${err.message}`); + } + return null; +} + +/** + * Make serverId the AI Governance server. + * Without force it refuses to switch away from another default server, and to + * change or clear the saved non-empty project. An empty project is an error: + * pass noProject to save none. + * @param {string} serverId jf CLI server id + * @param {string} [project] undefined keeps the saved project (unless noProject) + * @param {object} [options] + * @param {boolean} [options.force] override the refusals above + * @param {boolean} [options.noProject] save no project; excludes a project + * @param {NodeJS.ProcessEnv} [options.env] default process.env + * @param {{debug(message: string): void}} [options.log] default silent + * @returns {{ok: true} | {ok: false, error: string}} + */ +export function setAiGovernanceConfig( + serverId, + project, + { force = false, noProject = false, env = process.env, log = NOOP_LOG } = {}, +) { + if (project === "") { + return { + ok: false, + error: "an empty project is not accepted; pass noProject to unset", + }; + } + if (noProject && project !== undefined) { + return { + ok: false, + error: "project and noProject are mutually exclusive", + }; + } + if (noProject) project = ""; + if (nonEmpty(project) && !SAFE_ID.test(project)) { + return { + ok: false, + error: `invalid project key ${JSON.stringify(project)}: ${SAFE_ID_RULE}`, + }; + } + if (!SAFE_ID.test(serverId)) { + return { + ok: false, + error: `invalid server id ${JSON.stringify(serverId)}: ${SAFE_ID_RULE}; re-add the server to the jf CLI under a valid id`, + }; + } + const path = aiGovernanceConfigPath(env); + const { data, entries, absent, corrupt } = loadSetup(path, log); + if (corrupt && !force) { + return refuse(`${path} is corrupt`, log); + } + if (isNewer(data)) { + return refuse( + `${path} was written by a newer version (${data.version}); refusing to modify it`, + log, + ); + } + const current = select(entries); + const previous = entries.find(([id]) => id === serverId)?.[1]; + // The project to protect is the target's own; it matters only when there is + // no default or the target is the default. + const existing = previous?.currentActiveProject; + const currentProject = current?.entry.currentActiveProject; + log.debug( + current + ? `current default: "${current.id}" (${nonEmpty(currentProject) ? `project "${currentProject}"` : "no project"})` + : "no current default", + ); + if (current && current.id !== serverId) { + if (!force) { + return refuse( + `the AI Governance server in ${path} is "${current.id}"; setting "${serverId}" would change it`, + log, + ); + } + log.debug(`switching default "${current.id}" -> "${serverId}" (--force)`); + } else if ( + previous && + project !== undefined && + project !== (existing ?? "") + ) { + if (!force && nonEmpty(existing)) { + const change = nonEmpty(project) ? `setting "${project}"` : "clearing it"; + return refuse( + `"${serverId}" uses project "${existing}"; ${change} would change it`, + log, + ); + } + log.debug( + nonEmpty(project) + ? `setting project of "${serverId}" to "${project}"` + : `clearing project of "${serverId}"`, + ); + } else if (current) { + log.debug(`"${serverId}" is already the default; refreshing`); + } else { + log.debug(`new default "${serverId}"`); + } + // The jf CLI is consulted only once the saved state allows the change, so a + // refusal names the saved server, not a missing jf config entry. + const jfServers = loadJfServers(env, log); + if (!jfServers) { + return { + ok: false, + error: + "could not run `jf config show`; is the JFrog CLI installed and on PATH?", + }; + } + const jpdUrlOf = (s) => + normalizeJpdUrl(`${s.url ?? ""}`.trim() || `${s.artifactoryUrl ?? ""}`); + const jf = jfServers.find( + (s) => isObject(s) && s.serverId === serverId && jpdUrlOf(s), + ); + log.debug( + `jf config show returned servers: ${jfServers + .filter(isObject) + .map((s) => s.serverId) + .join(", ")}`, + ); + if (!jf) { + log.debug(`"${serverId}" not found in jf config show`); + return { + ok: false, + error: `server "${serverId}" is not in the jf CLI config`, + }; + } + log.debug(`"${serverId}" -> ${jpdUrlOf(jf)}`); + const nextServers = Object.fromEntries( + entries.map(([id, e]) => { + const { isDefault: _drop, ...rest } = e; + return [id, rest]; + }), + ); + const { currentActiveProject: saved, ...kept } = previous ?? {}; + const nextProject = project === undefined ? saved : project; + nextServers[serverId] = { + ...kept, + jpdUrl: jpdUrlOf(jf), + ...(nonEmpty(nextProject) && { currentActiveProject: nextProject }), + isDefault: true, + }; + log.debug(`${absent ? "creating" : "updating"} ${path}`); + try { + writeAtomic(path, { + ...data, + version: CURRENT_VERSION, + servers: nextServers, + }); + } catch (err) { + log.debug(`write to ${path} failed: ${err.message}`); + return { ok: false, error: `write failed: ${err.message}` }; + } + log.debug(`wrote ${path}`); + return { ok: true }; +} + +function refuse(error, log) { + log.debug(`refused: ${error}`); + return { ok: false, error }; +} + +function usage() { + process.stderr.write(USAGE); + return 2; +} + +function main(argv, env) { + const [mode, ...rest] = argv; + const log = { + debug: (m) => + env.JF_AGENT_GUARD_LOG_LEVEL === "debug" && + process.stderr.write(`debug: ${m}\n`), + }; + + if (mode === "server-id") { + try { + const cfg = resolveAiGovernanceConfig({ env, log }); + if (cfg.status === "ok" || cfg.status === "no_project") { + if (!SAFE_ID.test(cfg.serverId)) { + log.debug( + `server-id: ${JSON.stringify(cfg.serverId)} not printed: invalid id (${SAFE_ID_RULE})`, + ); + } else { + process.stdout.write(`${cfg.serverId}\n`); + } + } + } catch { + // Always exit 0 with no output: callers use this in $(...). + } + return 0; + } + + const flags = ["--force", "--no-project"]; + const [serverId, project, ...extra] = rest.filter((a) => !flags.includes(a)); + const force = rest.includes("--force"); + const noProject = rest.includes("--no-project"); + const argsOk = + mode === "set" + ? nonEmpty(serverId) && !extra.length && !(noProject && project) + : !rest.length; + const stray = rest.some((a) => a.startsWith("-") && !flags.includes(a)); + const badProject = nonEmpty(project) && !SAFE_ID.test(project); + if (badProject) { + process.stderr.write( + `ai-governance-config: invalid project key ${JSON.stringify(project)}: ${SAFE_ID_RULE}\n`, + ); + } + const emptyProject = mode === "set" && project === ""; + if (emptyProject) { + process.stderr.write( + "ai-governance-config: an empty project is not accepted; use --no-project to unset\n", + ); + } + if ( + !["get", "list", "set"].includes(mode) || + !argsOk || + stray || + badProject || + emptyProject + ) { + return usage(); + } + + const used = DEPRECATED_ENV.filter((name) => nonEmpty(env[name])); + if (used.length) { + process.stderr.write( + `info: ${used.join(", ")} set but ignored (deprecated); AI Governance config comes from ${aiGovernanceConfigPath(env)}. Continuing normally without using them.\n`, + ); + } + + if (mode === "get") { + process.stdout.write( + JSON.stringify(resolveAiGovernanceConfig({ env, log }), null, 2) + "\n", + ); + return 0; + } + if (mode === "list") { + process.stdout.write( + JSON.stringify(listAiGovernanceConfig({ env, log }), null, 2) + "\n", + ); + return 0; + } + const result = setAiGovernanceConfig(serverId, project, { + force, + noProject, + env, + log, + }); + if (!result.ok) { + process.stderr.write(`ai-governance-config: ${result.error}\n`); + return 1; + } + return 0; +} + +if (isMainModule(import.meta.url)) { + process.exitCode = main(process.argv.slice(2), process.env); +} diff --git a/modules/core/local-shadow-trigger.mjs b/modules/core/local-shadow-trigger.mjs index 6fef733..d482f65 100644 --- a/modules/core/local-shadow-trigger.mjs +++ b/modules/core/local-shadow-trigger.mjs @@ -6,8 +6,11 @@ // 1. the default jf CLI server has an access token // 2. the backend says scanning is enabled (asked through `jf api`, see jpd-get.mjs) // 3. read the plugin version from plugin.json ("UNKNOWN" when unreadable) -// 4. start `agent-guard --local-shadow-scan --server [--session-id ] [--workspace ] -// --plugin-version --harness ` in the background +// 4. build the session's launch (claude-launch.mjs) +// 5. start `agent-guard --local-shadow-scan --server [--session-id ] [--workspace ] +// --plugin-version --harness [--launch-json -]` in the background, with the +// launch JSON on its stdin. The launch can hold secrets, so it never goes in argv +// and only its key names are logged. // The first step that fails ends the run. Each run appends its result to // ~/.jfrog/shadow/local-shadow-hook.log. Claude Code only; see README // "Local Shadow AI scan". @@ -25,6 +28,7 @@ import path from "node:path"; import process from "node:process"; import { fileURLToPath } from "node:url"; +import { buildLaunch } from "./claude-launch.mjs"; import { isMainEntry } from "./entry.mjs"; import { detectHarness, readStdin } from "./io.mjs"; import { @@ -55,6 +59,9 @@ export const RESULT = Object.freeze({ export const SCANNING_ENABLED_PATH = "/aisec/api/v1/local-shadow/scanning-enabled"; const REQUEST_TIMEOUT_MS = 30_000; +// How long the launch write to the scanner's stdin may take. agent-guard reads +// it at startup; through npx with a cold cache that can wait for a download. +const LAUNCH_WRITE_TIMEOUT_MS = 60_000; export const HOOK_LOG_FILE = "local-shadow-hook.log"; export const HOOK_LOG_MAX_BYTES = 5 * 1024 * 1024; const DIR_MODE = 0o700; @@ -117,8 +124,28 @@ async function checkScanningEnabled(identity, { env, timeoutMs, getFn }) { return failed("response has no boolean 'enabled'"); } +// Writes the launch to the scanner's stdin and closes it. Resolves once the OS +// has it, or with the error; it never rejects. +function writeLaunch(stdin, launch, timeoutMs) { + return new Promise((resolve) => { + const timer = setTimeout( + () => resolve("timed out writing the launch"), + timeoutMs, + ); + stdin.once("error", (err) => { + clearTimeout(timer); + resolve(safeErrorMessage(err)); + }); + stdin.end(JSON.stringify(launch), (err) => { + clearTimeout(timer); + resolve(err ? safeErrorMessage(err) : undefined); + }); + }); +} + // Starts `agent-guard --local-shadow-scan` in the background. Resolves as soon as -// the OS has started the process; it never waits for the scan to finish. +// the OS has started the process and has the launch; it never waits for the scan +// to finish. Returns the launch write error, if any. async function startScanner( env, platform, @@ -126,6 +153,7 @@ async function startScanner( serverId, session, pluginVersion, + launch, ) { const scanArgs = [ "--local-shadow-scan", @@ -136,6 +164,7 @@ async function startScanner( pluginVersion, "--harness", HARNESS_ID, + ...(launch ? ["--launch-json", "-"] : []), ]; const bin = resolveAgentGuardBin(env); const command = bin ?? resolveNpxCommand(platform); @@ -154,14 +183,18 @@ async function startScanner( ); const child = spawnFn(command, args, { ...buildNpxSpawnOptions(env, platform, { local: Boolean(bin) }), - stdio: "ignore", + stdio: launch ? ["pipe", "ignore", "ignore"] : "ignore", windowsHide: true, }); await new Promise((resolve, reject) => { child.once("spawn", resolve); child.once("error", reject); }); + const launchError = launch + ? await writeLaunch(child.stdin, launch, LAUNCH_WRITE_TIMEOUT_MS) + : undefined; child.unref(); + return launchError; } // Appends one JSON line to the trigger log. When the log reaches HOOK_LOG_MAX_BYTES @@ -178,17 +211,32 @@ export function appendHookLog(logPath, entry) { } } -// Steps 1-4 of the flow at the top. Returns the { result, error? } to log; -// an unreadable plugin version adds pluginVersionError. +// The launch to send, and what to log about it: its key names, or why there is +// none. +function launchFor(payload, buildLaunchFn) { + if (!payload) return { launch: undefined, note: {} }; + try { + const launch = buildLaunchFn(payload); + return { launch, note: { launchFields: Object.keys(launch).sort() } }; + } catch (err) { + return { launch: undefined, note: { launchError: safeErrorMessage(err) } }; + } +} + +// Steps 1-5 of the flow at the top. Returns the { result, error? } to log; +// an unreadable plugin version adds pluginVersionError, the launch adds +// launchFields or launchError. async function runChecksAndStartScanner({ env, session, + payload, getIdentityFn, getFn, timeoutMs, spawnFn, platform, pluginDir, + buildLaunchFn, }) { const { identity, cause } = getIdentityFn(); if ( @@ -225,15 +273,18 @@ async function runChecksAndStartScanner({ pluginVersionError = safeErrorMessage(err); } const versionNote = pluginVersionError ? { pluginVersionError } : {}; + const { launch, note } = launchFor(payload, buildLaunchFn); + let launchError; try { - await startScanner( + launchError = await startScanner( env, platform, spawnFn, identity.serverId, session, pluginVersion, + launch, ); } catch (err) { return { @@ -242,7 +293,12 @@ async function runChecksAndStartScanner({ ...versionNote, }; } - return { result: RESULT.SCANNER_STARTED, ...versionNote }; + return { + result: RESULT.SCANNER_STARTED, + ...versionNote, + ...note, + ...(launchError && { launchError }), + }; } // The stdin payload, or null when it isn't a JSON object. @@ -280,6 +336,8 @@ export async function runLocalShadowTrigger(trigger, overrides = {}) { const deps = { env: process.env, session: {}, + payload: undefined, + buildLaunchFn: buildLaunch, getIdentityFn: getPlatformIdentity, getFn: jpdGet, timeoutMs: REQUEST_TIMEOUT_MS, @@ -306,6 +364,7 @@ if (isMainEntry(import.meta.url)) { isNewSession(payload) && runLocalShadowTrigger(trigger, { session: parseSession(payload, process.env), + payload, }) ); }) diff --git a/modules/core/rewrite-mcp-json.mjs b/modules/core/rewrite-mcp-json.mjs index d09c7aa..15034ed 100644 --- a/modules/core/rewrite-mcp-json.mjs +++ b/modules/core/rewrite-mcp-json.mjs @@ -1,9 +1,9 @@ // Shared Agent Guard `--rewrite-mcp-json` runner for harness adapters. // // Harness plugins own path discovery; this module owns: -// resolve server/project → discover → skip-if-current → Step 0 gate → +// resolve AI Governance server/project → discover → skip-if-current → Step 0 gate → // spawn/timeout, soft-fail orchestration with structured outcomes. -// Server id is resolved once for both the gate and AG --server (always passed). +// The AI Governance server id is resolved once for both the gate and AG --server. // // Usage (from a thin Cursor/Claude script next to synced modules/): // import { runRewriteMcpJsonPipeline } from "./modules/core/rewrite-mcp-json.mjs"; @@ -19,7 +19,7 @@ // Local binary: JFROG_AGENT_GUARD_BIN=/path/to/agent-guard (skips npx). // Version pin: JFROG_AGENT_GUARD_VERSION (default DEFAULT_AGENT_GUARD_VERSION). -import { spawn, spawnSync } from "node:child_process"; +import { spawn } from "node:child_process"; import { createHash } from "node:crypto"; import { mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; import { homedir } from "node:os"; @@ -27,7 +27,7 @@ import path from "node:path"; import process from "node:process"; import { EXIT_ENABLED, runAgentGuardCheck } from "./agent-guard-check.mjs"; -import { jfInvocation } from "./jf-process.mjs"; +import { resolveAiGovernanceConfig } from "./jfrog-ai-governance-config.mjs"; import { createLogger } from "./logger.mjs"; const log = createLogger("rewrite-mcp-json"); @@ -64,9 +64,6 @@ export const DEFAULT_REWRITE_TIMEOUT_MS = 35_000; /** SIGTERM → SIGKILL escalation window for a child that ignores the first signal. */ export const DEFAULT_KILL_GRACE_MS = 2_000; -/** Newest setup.json "version" this code understands (best-effort on mismatch). */ -export const SUPPORTED_SETUP_FILE_VERSION = 1; - export const OUTCOME = Object.freeze({ DISABLED: "disabled", SKIPPED_CURRENT: "skipped_current", @@ -103,35 +100,6 @@ export function isRewriteForced(env = process.env) { return env[FORCE_ENV] === "1"; } -/** - * True when JFROG_URL/JF_URL + access token are set. - * Used by the gate (Path A); plugin rewrite always passes `--server` separately. - * @param {NodeJS.ProcessEnv} [env] - */ -export function hasJfrogUrlTokenEnv(env = process.env) { - const url = env.JFROG_URL?.trim() || env.JF_URL?.trim(); - const token = env.JFROG_ACCESS_TOKEN?.trim() || env.JF_ACCESS_TOKEN?.trim(); - return Boolean(url && token); -} - -/** - * @param {unknown} value - * @returns {value is Record} - */ -function isPlainObject(value) { - return typeof value === "object" && value !== null && !Array.isArray(value); -} - -/** - * @param {string} [url] - * @returns {string} - */ -export function normalizeJpdUrl(url) { - return String(url ?? "") - .trim() - .replace(/\/+$/, ""); -} - /** * @param {NodeJS.ProcessEnv} [env] * @returns {string} @@ -156,71 +124,21 @@ export function defaultRewriteMarkerPath(env = process.env) { } /** - * Mirror of Agent Guard `ActiveProjectFromSetupFile`: read - * `{JFROG_CLI_HOME}/setup.json` → servers[id].currentActiveProject. - * Never throws; returns "" when missing/unreadable/no match. - * - * @param {string} serverId - * @param {string} [jpdUrl] - * @param {{ - * env?: NodeJS.ProcessEnv, - * readFileSyncFn?: typeof readFileSync, - * setupPath?: string, - * }} [opts] - * @returns {string} + * @param {unknown} value + * @returns {value is Record} */ -export function activeProjectFromSetupFile(serverId, jpdUrl = "", opts = {}) { - const env = opts.env ?? process.env; - const readFn = opts.readFileSyncFn ?? readFileSync; - const setupPath = - opts.setupPath ?? path.join(resolveJfrogHomeDir(env), "setup.json"); - const wantUrl = normalizeJpdUrl(jpdUrl); - const id = String(serverId ?? "").trim(); - - let raw; - try { - raw = readFn(setupPath, "utf8"); - } catch (err) { - if (err?.code === "ENOENT") { - log.debug("setup file: not found", { path: setupPath }); - } - return ""; - } - - /** @type {{ version?: number, servers?: Record }} */ - let sf = {}; - try { - sf = JSON.parse(raw); - } catch { - return ""; - } - if (!isPlainObject(sf) || !isPlainObject(sf.servers)) return ""; - if ( - typeof sf.version === "number" && - sf.version !== SUPPORTED_SETUP_FILE_VERSION - ) { - // Best-effort parse (matches AG). - } - - const servers = sf.servers; - if (id) { - const entry = servers[id]; - const project = entry?.currentActiveProject?.trim?.() || ""; - if (project) { - const entryUrl = normalizeJpdUrl(entry.jpdUrl); - if (wantUrl === "" || entryUrl === wantUrl) return project; - } - } +function isPlainObject(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} - if (wantUrl) { - const ids = Object.keys(servers).sort(); - for (const sid of ids) { - const entry = servers[sid]; - const project = entry?.currentActiveProject?.trim?.() || ""; - if (project && normalizeJpdUrl(entry.jpdUrl) === wantUrl) return project; - } - } - return ""; +/** + * @param {string} [url] + * @returns {string} + */ +export function normalizeJpdUrl(url) { + return String(url ?? "") + .trim() + .replace(/\/+$/, ""); } /** @@ -279,116 +197,6 @@ export function pickDefaultJfCliServer(servers) { return { error: "no_default" }; } -/** - * @param {{ - * env?: NodeJS.ProcessEnv, - * spawnSyncFn?: typeof spawnSync, - * platform?: NodeJS.Platform, - * }} [opts] - * @returns {{ serverId: string, jpdUrl: string }[]} - */ -export function listJfCliServers(opts = {}) { - const env = opts.env ?? process.env; - const spawnSyncFn = opts.spawnSyncFn ?? spawnSync; - const invocation = jfInvocation(["config", "show", "--format=json"], { - env, - platform: opts.platform, - }); - if (!invocation.command) return []; - let res; - try { - res = spawnSyncFn(invocation.command, invocation.args, { - encoding: "utf8", - timeout: 5_000, - env, - stdio: ["ignore", "pipe", "pipe"], - windowsHide: true, - shell: invocation.shell, - }); - } catch { - return []; - } - if (res?.error || res.status !== 0) return []; - return parseJfConfigShowJson(res.stdout ?? ""); -} - -/** - * Resolve server for gate + rewrite. Always expects a concrete server id - * for plugin MCP (Shay): hint → jf config (one / isDefault) → env. - * - * @param {NodeJS.ProcessEnv} [env] - * @param {{ - * serverIdHint?: string, - * spawnSyncFn?: typeof spawnSync, - * }} [opts] - * @returns {{ - * serverId: string, - * jpdUrl: string, - * } | { - * error: "missing" | "no_default", - * }} - */ -export function resolveRewriteServer(env = process.env, opts = {}) { - const servers = listJfCliServers({ - env, - spawnSyncFn: opts.spawnSyncFn, - }); - - const hint = opts.serverIdHint?.trim(); - if (hint) { - const match = servers.find((s) => s.serverId === hint); - return { - serverId: hint, - jpdUrl: match?.jpdUrl ?? "", - }; - } - - const picked = pickDefaultJfCliServer(servers); - if (!("error" in picked)) return picked; - - const fromEnv = env.JF_SERVER?.trim() || env.JFROG_SERVER_ID?.trim() || ""; - if (fromEnv) { - const match = servers.find((s) => s.serverId === fromEnv); - return { serverId: fromEnv, jpdUrl: match?.jpdUrl ?? "" }; - } - return picked.error === "no_default" - ? { error: "no_default" } - : { error: "missing" }; -} - -/** - * Resolve JFrog project key: env → setup.json (AG-compatible) → "". - * @param {NodeJS.ProcessEnv} [env] - * @param {{ - * serverId?: string, - * jpdUrl?: string, - * readFileSyncFn?: typeof readFileSync, - * setupPath?: string, - * }} [opts] - * @returns {string} - */ -export function resolveRewriteProject(env = process.env, opts = {}) { - const fromEnv = env.JF_PROJECT?.trim() || env.JFROG_PROJECT?.trim() || ""; - if (fromEnv) return fromEnv; - return activeProjectFromSetupFile(opts.serverId ?? "", opts.jpdUrl ?? "", { - env, - readFileSyncFn: opts.readFileSyncFn, - setupPath: opts.setupPath, - }); -} - -/** - * @deprecated Use resolveRewriteServer. Kept for callers that only need the id. - * @param {NodeJS.ProcessEnv} [env] - * @param {{ serverIdHint?: string, spawnSyncFn?: typeof spawnSync }} [opts] - * @returns {string} - */ -export function resolveRewriteServerId(env = process.env, opts = {}) { - const resolved = resolveRewriteServer(env, opts); - if ("error" in resolved) return ""; - return resolved.serverId; -} - /** * @param {NodeJS.Platform} [platform] */ @@ -662,21 +470,14 @@ export function buildAgentGuardRewriteArgs(opts) { if (paths.length === 0) { throw new Error("rewrite-mcp-json requires at least one mcp.json path"); } - const project = opts.project?.trim() || resolveRewriteProject(env, {}); - if (!project) { - throw new Error("rewrite-mcp-json requires --project (or JF_PROJECT)"); - } + const project = opts.project?.trim(); + if (!project) throw new Error("rewrite-mcp-json requires --project"); assertSafeRewriteIdentifier(project, "project"); const args = ["--rewrite-mcp-json", ...paths, "--project", project]; - const server = - opts.serverId !== undefined - ? opts.serverId.trim() - : resolveRewriteServerId(env); - if (!server) { - throw new Error("rewrite-mcp-json requires --server (or JF_SERVER)"); - } + const server = opts.serverId?.trim(); + if (!server) throw new Error("rewrite-mcp-json requires --server"); assertSafeRewriteIdentifier(server, "server"); args.push("--server", server); @@ -939,7 +740,7 @@ export function redactUrlCredentials(text) { } /** - * Orchestration: kill switch → server/project → discover → skip-if-current → + * Orchestration: kill switch → AI Governance server/project → discover → skip-if-current → * Step 0 gate → rewrite. Server id is resolved once and reused for both the * gate and AG `--server` (always passed). Returns a structured result; exitCode * is 0 unless JF_AGENT_REWRITE_MCP_JSON_STRICT=1 and outcome is failed_*. @@ -949,7 +750,6 @@ export function redactUrlCredentials(text) { * allowRoots?: string[] | ((paths: string[]) => string[]), * env?: NodeJS.ProcessEnv, * spawnFn?: typeof spawn, - * spawnSyncFn?: typeof spawnSync, * timeoutMs?: number, * graceMs?: number, * platform?: NodeJS.Platform, @@ -959,9 +759,7 @@ export function redactUrlCredentials(text) { * writeFileSyncFn?: typeof writeFileSync, * mkdirSyncFn?: typeof mkdirSync, * statSyncFn?: typeof statSync, - * serverIdHint?: string, * markerPath?: string, - * setupPath?: string, * }} opts * @returns {Promise<{ exitCode: number, outcome: string, reason: string }>} */ @@ -974,19 +772,20 @@ export async function runRewriteMcpJsonPipeline(opts) { return pipelineResult(OUTCOME.DISABLED, DISABLE_ENV, env); } - const serverResolved = resolveRewriteServer(env, { - serverIdHint: opts.serverIdHint, - spawnSyncFn: opts.spawnSyncFn, - }); - if ("error" in serverResolved) { - const reason = - serverResolved.error === "no_default" - ? "multiple jf config servers and none isDefault" - : "no jf config server / JF_SERVER"; - log.info("rewrite skipped; missing server", { reason }); - return pipelineResult(OUTCOME.SKIPPED_NO_SERVER, reason, env); + const config = resolveAiGovernanceConfig({ env, log }); + if (config.status !== "ok") { + log.info("rewrite skipped; no AI Governance server and project", { + status: config.status, + }); + return pipelineResult( + config.status === "no_project" + ? OUTCOME.SKIPPED_NO_PROJECT + : OUTCOME.SKIPPED_NO_SERVER, + `AI Governance config: ${config.status}`, + env, + ); } - const { serverId, jpdUrl } = serverResolved; + const { serverId, project } = config; if (!isSafeRewriteIdentifier(serverId)) { log.info("rewrite skipped; unsafe server id", {}); return pipelineResult( @@ -995,23 +794,8 @@ export async function runRewriteMcpJsonPipeline(opts) { env, ); } - - const project = resolveRewriteProject(env, { - serverId, - jpdUrl, - readFileSyncFn: opts.readFileSyncFn, - setupPath: opts.setupPath, - }); - if (!project) { - log.info("rewrite skipped; missing project", {}); - return pipelineResult( - OUTCOME.SKIPPED_NO_PROJECT, - "missing JF_PROJECT / setup.json currentActiveProject", - env, - ); - } if (!isSafeRewriteIdentifier(project)) { - log.info("rewrite skipped; unsafe JF_PROJECT", {}); + log.info("rewrite skipped; unsafe project", {}); return pipelineResult( OUTCOME.SKIPPED_UNSAFE_PROJECT, "unsafe project", diff --git a/package.json b/package.json index de7efe7..6384eb2 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "codex-plugin", - "version": "0.1.19", + "version": "0.1.20", "private": true, "type": "module", "description": "JFrog skills and MCP server plugin for OpenAI Codex.",