diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index aeaf5bf..7727457 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "jfrog", - "version": "0.1.18", + "version": "0.1.19", "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..99d30f3 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.17.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/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..9225a69 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.17.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/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 92bb8ec..de7efe7 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "codex-plugin", - "version": "0.1.18", + "version": "0.1.19", "private": true, "type": "module", "description": "JFrog skills and MCP server plugin for OpenAI Codex.",