diff --git a/.github/scripts/sync-modules-integrity.json b/.github/scripts/sync-modules-integrity.json index 7c14456..bf4bf21 100644 --- a/.github/scripts/sync-modules-integrity.json +++ b/.github/scripts/sync-modules-integrity.json @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "pin": "jfrog-agent-hooks/v0.19.0", + "pin": "jfrog-agent-hooks/v0.20.0", "files": { "assets/agents-conf-fingerprints.json": "beb9bf4670de4abbd9af6b714be6ae669a1c477cdf4cd63b6bca7f757326717d", "assets/agents-default-conf.json": "774e1bfd5bb1e2f38de06c9ce53b92e12ddd36b82c159e4a3113f4c038bfc3bb", @@ -9,24 +9,25 @@ "copilot-session-start.mjs": "eda00194f19dd4758919aaecdb41b18db173a3de34c9d3c63d597212727ba073", "core/agent-guard-check.mjs": "94aba0170e13d953b972863396a4ca90785908c05a0b29372a43de52b86236b7", "core/agents-config.mjs": "4ccdf26dbb3d6a7a9c99bf807843cd2c098b53988d6927d3be7662ae4780fb22", - "core/claude-launch.mjs": "8e5bf6a9a2999769e10029d9f5ad30f6e6b9f058a66f6f442d982775499360ea", + "core/claude-launch.mjs": "2bb1369f001747b602ea80d0b0074f10243125431185ea21925f3fa9085dffb7", "core/enforce-skill.mjs": "f8bf35a60fad9d58f4eb406663e248e0a656f9bd9a147042f72a7e70aa294661", "core/entry.mjs": "0b0b218448151d7a06743c37e684d0933ab76225be5761f648627f4db02c1f17", "core/io.mjs": "44eab271b86756e1e47fa7122f29361a5277a1524159059400b0a57d1b7aee09", "core/jf-identity.mjs": "c017b452c32a5c4ad319e4b48286bd85d030afb443236c1ba1dbee912fe03fec", "core/jf-process.mjs": "baf07b81defaf02e7107171e14f820e84abc4021a6fec6d3842ecf86148c86d3", - "core/jf-user-agent.mjs": "cb7989569a994a1506f8d3f0f7c19fae617746e0f0089ea02e3a59ff8cb5c042", + "core/jf-user-agent.mjs": "69393de3c522e7a82a2eec4e73e81becd39b7a2c0cd1587d3855342b9461a741", "core/jfrog-ai-governance-config.mjs": "e538d39a1b8f91912e5f74620749f90226efcb461bd94f8ef2371e2ff42296db", "core/jpd-get.mjs": "6b5d02479c2a1acd61c2be064c58edeb5a252c2a9aaac03a0d0f16fda06afcc3", - "core/local-shadow-trigger.mjs": "ccf80029f5360070bfdaed5c329a4b78c31600fbff6c79215d41f29b413c1c29", + "core/json-file.mjs": "5103f5f26ed014982cf215dfdc44ffe5099b0751f99b7cb858548722a4c43dce", + "core/local-shadow-trigger.mjs": "31665e723401e040eca2a783118a962c99d748af6d0fb20fb034b7a3d015a1d1", "core/logger.mjs": "1ebdffcdf4af14b19e3ee8e82cfeb377fb9961a09d4e9d6ecdc922d07b0848c2", "core/proxy-fetch.mjs": "f172959e2f90cde1816d67be85dffda739e861a4c28c209125c0b0eca590ec59", - "core/rewrite-mcp-json.mjs": "4a00f7dabbb4e03acd1eddd5c0c4cea4fe27627716274c8ddc2e83092592457d", + "core/rewrite-mcp-json.mjs": "279dd8cb34e5b68098960c6ec924a3229f054bcbfba931befc1df0aa71c65c88", "core/run-capability.mjs": "9fac890b7fd4866f9d3322469b2a7301e28cebfa3faebd77857f9f79d2d1c532", "core/scaffold-fingerprint.mjs": "23ce9d0afae26a9bdc295ac5f5f2f18be3a8e45e682e0fe000b1a8f6cc289b19", "core/telemetry-contract.mjs": "acb1483522e10a962a4d6f94d8ba41d8940d6efe2528dbd97bd2c0a02a0021e4", "core/telemetry-runner.mjs": "aec9f0b3f6ed9f2598f8d7526853dbaa056209bcfec8f6eb73f77a560ffb3cb8", - "core/telemetry-worker.mjs": "d40c49f4c73e76f43a34133d361da35fe027d655598acea3630ca0e028c678ff", + "core/telemetry-worker.mjs": "9cc26f9f17c9c9b43a9fdda370c6623f98636116f65298ced1112044453f626d", "cursor-session-start.mjs": "6d40df1d4aa661139ece0d8af8e77442a45e710b4096d4254aef19c85811fbf8", "package-resolution/onboarding/package-resolution-onboarding-procedure.md": "53b71301a1fcacd187a30239b780dd4fff451a6d03612d6dbb05aa35b7735c8c", "package-resolution/onboarding/session-start-nudge.md": "58dd0b94944c71f9071adad1524cf457ca6a54863809fb8ed7504229fe6fedd5", diff --git a/.github/scripts/sync-modules-vendor.json b/.github/scripts/sync-modules-vendor.json index ed3f3c8..3855f2f 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/marketplace.json b/marketplace.json index 805f57a..4c3a31a 100644 --- a/marketplace.json +++ b/marketplace.json @@ -9,7 +9,7 @@ { "name": "jfrog", "description": "JFrog Platform integration with MCP, security skills, and supply-chain best practices", - "version": "1.2.2", + "version": "1.2.3", "license": "Apache-2.0", "source": "plugin", "categories": [ diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json index a91e4af..b5468c2 100644 --- a/plugin/.claude-plugin/plugin.json +++ b/plugin/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "jfrog", "description": "JFrog Platform integration with MCP, security skills, and supply-chain best practices", - "version": "1.2.2", + "version": "1.2.3", "license": "Apache-2.0", "author": { "name": "JFrog", diff --git a/plugin/modules/core/claude-launch.mjs b/plugin/modules/core/claude-launch.mjs index ff5daeb..8d681dc 100644 --- a/plugin/modules/core/claude-launch.mjs +++ b/plugin/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/plugin/modules/core/jf-user-agent.mjs b/plugin/modules/core/jf-user-agent.mjs index a274ea3..d57a0d9 100644 --- a/plugin/modules/core/jf-user-agent.mjs +++ b/plugin/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/plugin/modules/core/json-file.mjs b/plugin/modules/core/json-file.mjs new file mode 100644 index 0000000..9d0b8f8 --- /dev/null +++ b/plugin/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/plugin/modules/core/local-shadow-trigger.mjs b/plugin/modules/core/local-shadow-trigger.mjs index 76cf4ab..d664cba 100644 --- a/plugin/modules/core/local-shadow-trigger.mjs +++ b/plugin/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/plugin/modules/core/rewrite-mcp-json.mjs b/plugin/modules/core/rewrite-mcp-json.mjs index ec3080a..cb368d7 100644 --- a/plugin/modules/core/rewrite-mcp-json.mjs +++ b/plugin/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/plugin/modules/core/telemetry-worker.mjs b/plugin/modules/core/telemetry-worker.mjs index f5b33a8..6350884 100644 --- a/plugin/modules/core/telemetry-worker.mjs +++ b/plugin/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