diff --git a/.cursor-plugin/marketplace.json b/.cursor-plugin/marketplace.json index 05ddfec..eb13ddd 100644 --- a/.cursor-plugin/marketplace.json +++ b/.cursor-plugin/marketplace.json @@ -6,7 +6,7 @@ }, "metadata": { "description": "JFrog Platform plugins for Cursor", - "version": "0.7.2", + "version": "0.7.3", "pluginRoot": "plugins" }, "plugins": [ diff --git a/.github/scripts/sync-modules-vendor.json b/.github/scripts/sync-modules-vendor.json index 196f133..ec5921f 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.19.0", + "pin": "jfrog-agent-hooks/v0.20.0", "paths": [ "modules" ] diff --git a/plugins/jfrog/.cursor-plugin/plugin.json b/plugins/jfrog/.cursor-plugin/plugin.json index ba8a5b6..f81776c 100644 --- a/plugins/jfrog/.cursor-plugin/plugin.json +++ b/plugins/jfrog/.cursor-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "jfrog", "displayName": "JFrog Platform", - "version": "0.7.2", + "version": "0.7.3", "description": "JFrog Platform integration with MCP, security skills, Agent Package Resolution, supply-chain best practices, and JFrog Agent Guard governance for adding, removing, and listing MCP servers.", "author": { "name": "JFrog", diff --git a/plugins/jfrog/modules/core/claude-launch.mjs b/plugins/jfrog/modules/core/claude-launch.mjs index ff5daeb..8d681dc 100644 --- a/plugins/jfrog/modules/core/claude-launch.mjs +++ b/plugins/jfrog/modules/core/claude-launch.mjs @@ -3,7 +3,7 @@ // can't learn is left out, and the scanner uses its default for it. // // Sources: -// 1. the SessionStart payload: cwd, permission_mode, agent_type +// 1. the hook payload (SessionStart or UserPromptSubmit): 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 @@ -86,7 +86,7 @@ export function scannerOS(platform, env = {}, readFileFn = readFileSync) { return platform; } -// Fields from the SessionStart payload. +// Fields from the hook payload (SessionStart or UserPromptSubmit). export function launchFromPayload(payload) { const out = {}; if (text(payload?.cwd)) out.cwd = payload.cwd; diff --git a/plugins/jfrog/modules/core/jf-user-agent.mjs b/plugins/jfrog/modules/core/jf-user-agent.mjs index a274ea3..d57a0d9 100644 --- a/plugins/jfrog/modules/core/jf-user-agent.mjs +++ b/plugins/jfrog/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.19.0"; +const PKG_VERSION = "0.20.0"; /** Hooks release semver stamped at plugin sync ("0.0.0" when unstamped). */ export function hooksPackageVersion() { diff --git a/plugins/jfrog/modules/core/json-file.mjs b/plugins/jfrog/modules/core/json-file.mjs new file mode 100644 index 0000000..9d0b8f8 --- /dev/null +++ b/plugins/jfrog/modules/core/json-file.mjs @@ -0,0 +1,30 @@ +// JSON state files shared by the hooks' background work. + +import { mkdirSync, renameSync, unlinkSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import process from "node:process"; + +/** + * Write JSON through a temp file and a rename, so a reader never sees half a + * file. Throws when the file can't be written; the temp file is removed. + * @param {string} file + * @param {unknown} data + */ +export function writeJsonAtomic(file, data) { + mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); + const tmp = `${file}.${process.pid}.tmp`; + try { + writeFileSync(tmp, `${JSON.stringify(data, null, 2)}\n`, { + encoding: "utf8", + mode: 0o600, + }); + renameSync(tmp, file); + } catch (err) { + try { + unlinkSync(tmp); + } catch { + /* ignore */ + } + throw err; + } +} diff --git a/plugins/jfrog/modules/core/local-shadow-trigger.mjs b/plugins/jfrog/modules/core/local-shadow-trigger.mjs index 76cf4ab..d664cba 100644 --- a/plugins/jfrog/modules/core/local-shadow-trigger.mjs +++ b/plugins/jfrog/modules/core/local-shadow-trigger.mjs @@ -1,19 +1,23 @@ #!/usr/bin/env node // Local Shadow AI trigger. -// node local-shadow-trigger.mjs session_start runs once per new session (SessionStart hook) +// node local-shadow-trigger.mjs session_start SessionStart hook (any source) +// node local-shadow-trigger.mjs user_prompt_submit UserPromptSubmit hook (every prompt) // // Flow: // 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) +// 2. the backend says scanning is enabled (asked through `jf api`, see jpd-get.mjs); +// the answer is reused for an hour (SCANNING_CACHE_FILE); a 404 counts as off // 3. read the plugin version from plugin.json ("UNKNOWN" when unreadable) // 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". +// The first step that fails ends the run. The hook doesn't decide when a session +// scans: agent-guard scans a session at most once an hour (a run that died is +// retried after about 6 minutes) and skips a session that is already being scanned. +// Each run appends its result to ~/.jfrog/shadow/local-shadow-hook.log. +// Claude Code only; see README "Local Shadow AI scan". import { spawn } from "node:child_process"; import { @@ -39,6 +43,7 @@ import { } from "./jf-identity.mjs"; import { axesFromAdapterIde, envWithHookUserAgent } from "./jf-user-agent.mjs"; import { jpdGet } from "./jpd-get.mjs"; +import { writeJsonAtomic } from "./json-file.mjs"; import { GOVERNANCE_AGENT_GUARD_SPEC, buildNpxSpawnOptions, @@ -64,6 +69,12 @@ const REQUEST_TIMEOUT_MS = 30_000; 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; +// Each jf server's scanning-enabled answer is reused for an hour, so prompts don't +// ask the backend again; turning scanning on or off takes effect within the hour. +export const SCANNING_CACHE_FILE = "local-shadow-hook-cache.json"; +export const SCANNING_CACHE_TTL_MS = 60 * 60 * 1000; +// Any change to the cache format bumps it; a file in another version is ignored. +const SCANNING_CACHE_VERSION = 1; const DIR_MODE = 0o700; const FILE_MODE = 0o600; export const UNKNOWN_PLUGIN_VERSION = "UNKNOWN"; @@ -103,6 +114,84 @@ export function readPluginVersion(pluginDir = PLUGIN_DIR) { return version; } +// The cached answers, one { server_id, shadow_ai_enabled, last_updated_at } per +// jf server: [] when the cache file is missing or in another version. Throws +// when it can't be read or isn't JSON. +function readScanningCache(file) { + let text; + try { + text = readFileSync(file, "utf8"); + } catch (err) { + if (err?.code === "ENOENT") return []; + throw err; + } + const cache = JSON.parse(text); + return cache?.version === SCANNING_CACHE_VERSION && + Array.isArray(cache.servers) + ? cache.servers + : []; +} + +// Whether a cached answer was updated within the last SCANNING_CACHE_TTL_MS. A +// time in the future means the clock moved back, so it isn't fresh. +function isFresh(entry, nowMs) { + const age = nowMs - Date.parse(entry?.last_updated_at); + return age >= 0 && age < SCANNING_CACHE_TTL_MS; +} + +// Wraps getFn: the scanning-enabled request is answered from the cache when it +// holds a fresh answer for this jf server id, and each new true/false answer is +// cached, dropping the stale ones. A 404 (no endpoint on this server) is cached +// as off; other failures are not cached. note gets what the +// hook line logs: scanningEnabledFromCache, and scanningCacheError when the +// cache can't be read or written (the backend is then asked on every prompt). +function withScanningCache(getFn, file, nowMs, note) { + return async (apiPath, identity, options) => { + let servers = []; + try { + servers = readScanningCache(file); + } catch (err) { + note.scanningCacheError = `read: ${safeErrorMessage(err)}`; + } + const cached = servers.find( + (entry) => entry?.server_id === identity.serverId, + ); + note.scanningEnabledFromCache = + typeof cached?.shadow_ai_enabled === "boolean" && isFresh(cached, nowMs); + if (note.scanningEnabledFromCache) { + return { status: 200, body: { enabled: cached.shadow_ai_enabled } }; + } + const answer = await getFn(apiPath, identity, options); + const enabled = + answer.status === 404 + ? false + : answer.status === 200 + ? answer.body?.enabled + : undefined; + if (typeof enabled === "boolean") { + try { + writeJsonAtomic(file, { + version: SCANNING_CACHE_VERSION, + servers: [ + ...servers.filter( + (entry) => + entry?.server_id !== identity.serverId && isFresh(entry, nowMs), + ), + { + server_id: identity.serverId, + shadow_ai_enabled: enabled, + last_updated_at: new Date(nowMs).toISOString(), + }, + ], + }); + } catch (err) { + note.scanningCacheError = `write: ${safeErrorMessage(err)}`; + } + } + return answer; + }; +} + // Asks the backend whether scanning is enabled for this account. // Returns null when enabled, otherwise the { result, error } to log. async function checkScanningEnabled(identity, { env, timeoutMs, getFn }) { @@ -173,7 +262,6 @@ async function startScanner( : quoteSpawnArgs( [ "--yes", - "--prefer-offline", "--registry", resolveAgentGuardNpmRegistry(env), GOVERNANCE_AGENT_GUARD_SPEC, @@ -225,7 +313,7 @@ function launchFor(payload, buildLaunchFn) { // 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. +// launchFields or launchError. The scanning-enabled check fills cacheNote. async function runChecksAndStartScanner({ env, session, @@ -237,6 +325,8 @@ async function runChecksAndStartScanner({ platform, pluginDir, buildLaunchFn, + now, + cacheNote, }) { const { identity, cause } = getIdentityFn(); if ( @@ -261,7 +351,12 @@ async function runChecksAndStartScanner({ const notEnabled = await checkScanningEnabled(identity, { env, timeoutMs, - getFn, + getFn: withScanningCache( + getFn, + path.join(shadowDir(env), SCANNING_CACHE_FILE), + now(), + cacheNote, + ), }); if (notEnabled) return notEnabled; @@ -311,16 +406,8 @@ export function parsePayload(input) { } } -// Claude Code also fires SessionStart on resume, /clear and compaction; those -// don't scan. New sessions are "startup" (Claude, Codex) or "new" (VS Code -// Copilot). No source always scans. -const NEW_SESSION_SOURCES = new Set([undefined, "startup", "new"]); -export function isNewSession(payload) { - return NEW_SESSION_SOURCES.has(payload?.source); -} - -// The session a scan is for, from the SessionStart payload: its session_id and cwd (the -// project dir when the payload has no cwd). Either may be missing. +// The session a scan is for, from the SessionStart or UserPromptSubmit payload: its +// session_id and cwd (the project dir when the payload has no cwd). Either may be missing. export function parseSession(payload, env) { const text = (value) => typeof value === "string" && value ? value : undefined; @@ -331,7 +418,7 @@ export function parseSession(payload, env) { } // One trigger run: the checks, then one line in local-shadow-hook.log. -// trigger is session_start. +// trigger is session_start or user_prompt_submit. export async function runLocalShadowTrigger(trigger, overrides = {}) { const deps = { env: process.env, @@ -344,24 +431,31 @@ export async function runLocalShadowTrigger(trigger, overrides = {}) { spawnFn: spawn, platform: process.platform, pluginDir: PLUGIN_DIR, + now: Date.now, ...overrides, }; - const outcome = await runChecksAndStartScanner(deps); + const cacheNote = {}; + const outcome = await runChecksAndStartScanner({ ...deps, cacheNote }); appendHookLog(path.join(shadowDir(deps.env), HOOK_LOG_FILE), { trigger, ...outcome, + ...cacheNote, }); } +// Whether this hook input is from this plugin's harness. Cursor also runs +// Claude's hooks; only Claude Code scans, on any SessionStart source. +export function shouldTrigger(input) { + return detectHarness(input) === HARNESS_ID; +} + if (isMainEntry(import.meta.url)) { const trigger = process.argv[2]; readStdin() .then((input) => { const payload = parsePayload(input); - // Cursor also runs Claude's hooks; only this plugin's harness scans. return ( - detectHarness(input) === HARNESS_ID && - isNewSession(payload) && + shouldTrigger(input) && runLocalShadowTrigger(trigger, { session: parseSession(payload, process.env), payload, diff --git a/plugins/jfrog/modules/core/rewrite-mcp-json.mjs b/plugins/jfrog/modules/core/rewrite-mcp-json.mjs index ec3080a..cb368d7 100644 --- a/plugins/jfrog/modules/core/rewrite-mcp-json.mjs +++ b/plugins/jfrog/modules/core/rewrite-mcp-json.mjs @@ -61,7 +61,7 @@ export const DEFAULT_AGENT_GUARD_VERSION = "1.23.0"; * version. Not overridable from the environment: the governed machine must not * pick which build governs it. Bump deliberately, like the rewrite pin above. */ -export const GOVERNANCE_AGENT_GUARD_VERSION = "1.27.0"; +export const GOVERNANCE_AGENT_GUARD_VERSION = "1.28.0"; export const GOVERNANCE_AGENT_GUARD_SPEC = `${AGENT_GUARD_PACKAGE}@${GOVERNANCE_AGENT_GUARD_VERSION}`; /** * Shared budget for rewriting all discovered files in one hook invocation. diff --git a/plugins/jfrog/modules/core/telemetry-worker.mjs b/plugins/jfrog/modules/core/telemetry-worker.mjs index f5b33a8..6350884 100644 --- a/plugins/jfrog/modules/core/telemetry-worker.mjs +++ b/plugins/jfrog/modules/core/telemetry-worker.mjs @@ -24,7 +24,6 @@ import { mkdirSync, openSync, readFileSync, - renameSync, statSync, unlinkSync, writeFileSync, @@ -36,6 +35,7 @@ import { fileURLToPath } from "node:url"; import { getAgentsConfigSection } from "./agents-config.mjs"; import { isMainEntry } from "./entry.mjs"; +import { writeJsonAtomic } from "./json-file.mjs"; import { parseHttpStatus, runJf } from "./jpd-get.mjs"; import { createLogger, setLogContext } from "./logger.mjs"; import { proxyFetch } from "./proxy-fetch.mjs"; @@ -115,31 +115,6 @@ function receiptLockPath(dir, harness) { return path.join(dir, `receipt-${harness}.lock`); } -/** - * Write JSON through a temp file and a rename, so a reader never sees half a - * file. - * @param {string} file - * @param {unknown} data - */ -export function writeJsonAtomic(file, data) { - mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); - const tmp = `${file}.${process.pid}.tmp`; - try { - writeFileSync(tmp, `${JSON.stringify(data, null, 2)}\n`, { - encoding: "utf8", - mode: 0o600, - }); - renameSync(tmp, file); - } catch (err) { - try { - unlinkSync(tmp); - } catch { - /* ignore */ - } - throw err; - } -} - /** * Exclusive-create lock, taken over when older than 60 s (a crashed worker). * Same pattern as the APR heartbeat lock; the age comes from the timestamp