shrike-guard 4.0.2 → 4.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/README.md +4 -4
- package/dist/anthropic/index.js +4 -1
- package/dist/anthropic/index.js.map +1 -1
- package/dist/anthropic/index.mjs +4 -1
- package/dist/anthropic/index.mjs.map +1 -1
- package/dist/api/index.js +4 -1
- package/dist/api/index.js.map +1 -1
- package/dist/api/index.mjs +4 -1
- package/dist/api/index.mjs.map +1 -1
- package/dist/gemini/index.js +4 -1
- package/dist/gemini/index.js.map +1 -1
- package/dist/gemini/index.mjs +4 -1
- package/dist/gemini/index.mjs.map +1 -1
- package/dist/index.d.mts +1 -4
- package/dist/index.d.ts +1 -4
- package/dist/index.js +4 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +4 -1
- package/dist/index.mjs.map +1 -1
- package/dist/openai/index.js +4 -1
- package/dist/openai/index.js.map +1 -1
- package/dist/openai/index.mjs +4 -1
- package/dist/openai/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/api/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/config.ts","../../src/version.ts","../../src/scanner.ts","../../src/api/base.ts","../../src/api/auth.ts","../../src/api/agents.ts","../../src/api/policies.ts","../../src/api/sandbox.ts"],"names":["randomUUID"],"mappings":";;;;;AA+BO,IAAM,gBAAA,GAAmB,sCAAA;AASzB,IAAM,QAAA,GAAW,YAAA;AAOLA,iBAAA;AACF,OAAA,CAAQ,GAAA,CAAI,eAAA,IAAmB,CAAA,OAAA,EAAUA,mBAAW,CAAE,KAAA,CAAM,CAAA,EAAG,CAAC,CAAC,CAAA;;;AC7C3E,IAAM,OAAA,GAAU,OAAA;ACyKvB,SAAS,YAAA,GAAuB;AAC9B,EAAA,OAAO,sCAAA,CAAuC,OAAA,CAAQ,OAAA,EAAS,CAAC,CAAA,KAAM;AACpE,IAAA,MA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CAAgB,KAAA,EAAO,CAAA,iBAAA,EAAoB,QAAQ,IAAI,OAAO,CAAA;AAAA,EAC5E;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,aAAa,QAAA,EAAiC;AAClD,IAAA,MAAM,IAAA,CAAK,OAAA,CAAc,QAAA,EAAU,CAAA,iBAAA,EAAoB,QAAQ,CAAA,CAAE,CAAA;AAAA,EACnE;AACF;;;AC1EO,IAAM,aAAA,GAAN,cAA4B,UAAA,CAAW;AAAA,EAC5C,WAAA,CAAY,OAAA,GAA6B,EAAC,EAAG;AAC3C,IAAA,KAAA,CAAM,OAAO,CAAA;AAAA,EACf;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,KAAK,OAAA,EAAkD;AAC3D,IAAA,OAAO,IAAA,CAAK,OAAA,CAAoB,MAAA,EAAQ,sBAAA,EAAwB,OAAO,CAAA;AAAA,EACzE;AACF","file":"index.js","sourcesContent":["/**\n * Configuration constants and types for the Shrike Guard SDK.\n */\n\nimport { randomUUID } from 'node:crypto';\n\n/**\n * Defines behavior when scan operations fail.\n */\nexport enum FailMode {\n /**\n * Allow the request to proceed (fail-open). Use this mode when\n * availability is prioritized over strict security.\n */\n OPEN = 'open',\n\n /**\n * Block the request and raise an exception (fail-closed). This is the\n * default behavior — matching the MCP server's security posture. Use\n * fail-open only when you've explicitly decided availability matters more.\n */\n CLOSED = 'closed',\n}\n\n/** Default timeout for scan requests in milliseconds */\nexport const DEFAULT_SCAN_TIMEOUT = 10000;\n\n/** Default fail mode - block requests when scan fails (fail-closed) */\nexport const DEFAULT_FAIL_MODE = FailMode.CLOSED;\n\n/** Default Shrike API endpoint (uses load balancer for scalability) */\nexport const DEFAULT_ENDPOINT = 'https://api.shrikesecurity.com/agent';\n\n/** Default rate limit (requests per minute) */\nexport const DEFAULT_RATE_LIMIT_PER_MINUTE = 100;\n\n// Note: All scanning is done via backend API (tier-based: community=L1-L4, pro=L1-L8)\n// No local patterns needed - backend handles all detection logic\n\n/** SDK identification */\nexport const SDK_NAME = 'typescript';\nexport const SDK_USER_AGENT = 'shrike-guard-typescript';\n\n/**\n * Session identity — persists for the lifetime of this SDK process.\n * Maps to L9's SessionCache key for multi-turn attack detection.\n */\nconst SESSION_ID = randomUUID();\nconst AGENT_ID = process.env.SHRIKE_AGENT_ID || `sdk-ts-${randomUUID().slice(0, 8)}`;\n\n/** Returns the stable session ID for this SDK process. */\nexport function getSessionId(): string {\n return SESSION_ID;\n}\n\n/** Returns the agent ID (from SHRIKE_AGENT_ID env or auto-generated). */\nexport function getAgentId(): string {\n return AGENT_ID;\n}\n\n/**\n * Approval information returned when a policy requires human sign-off.\n */\nexport interface ApprovalInfo {\n requires_approval: boolean;\n approval_id: string;\n approval_level: string;\n action_summary: string;\n policy_name: string;\n expires_in_seconds: number;\n threat_type?: string;\n severity?: string;\n owasp_category?: string;\n risk_factors?: string[];\n original_action?: string;\n}\n\n/**\n * Retry configuration for transient failure resilience.\n * Matches MCP server's RETRY_CONFIG for consistent behavior.\n */\nexport const RETRY_CONFIG = {\n maxRetries: 2,\n initialDelayMs: 200,\n maxDelayMs: 2000,\n backoffMultiplier: 2,\n retryableErrors: ['ECONNREFUSED', 'ECONNRESET', 'ETIMEDOUT', 'fetch failed'],\n};\n","/**\n * SDK version - keep in sync with package.json\n */\nexport const VERSION = '1.5.0';\n","/**\n * HTTP client for the Shrike scan API.\n * Includes retry with exponential backoff, session correlation,\n * approval workflow, 401 key refresh, and rate limiting.\n */\n\nimport {\n DEFAULT_ENDPOINT,\n DEFAULT_SCAN_TIMEOUT,\n DEFAULT_RATE_LIMIT_PER_MINUTE,\n SDK_NAME,\n RETRY_CONFIG,\n getSessionId,\n getAgentId,\n} from './config';\nimport type { ApprovalInfo } from './config';\nimport { AUTO_CHUNK_THRESHOLD, aggregateChunkResults, chunkContent } from './chunker';\nimport { ShrikeRateLimitError } from './errors';\nimport { RateLimiter } from './rateLimiter';\nimport { sanitizeScanResponse } from './sanitizer';\nimport { VERSION } from './version';\n\n/**\n * Phase 8b: Client-side size limits to fail fast before network round-trip.\n * These limits match the backend limits for consistency.\n */\nconst MAX_CONTENT_SIZE = 100 * 1024; // 100KB - matches backend MaxRequestBodySize\n\n/**\n * Result from a scan operation.\n */\n/**\n * Correlation pattern from L9 session-aware correlation engine.\n */\nexport interface CorrelationPattern {\n pattern_id: string;\n pattern_name: string;\n category: string;\n confidence: number;\n description: string;\n}\n\n/**\n * Governance action per Cooperative Governance 4-state contract (allow / warn / require_approval / block).\n * The `action` field is the server-authoritative signal for proceed-vs-refuse;\n * `isBlocked()` in this module consumes it directly.\n */\nexport type ScanAction = 'allow' | 'warn' | 'require_approval' | 'block';\n\n/**\n * Recovery guidance emitted by the backend on refuse verdicts.\n * `available_tools` names the MCP tools the caller can still invoke while\n * under quarantine (typically read-only surfaces like session_status).\n */\nexport interface ScanRecovery {\n instruction?: string;\n available_tools?: string[];\n patterns_triggered?: string[];\n [key: string]: unknown;\n}\n\n/**\n * Session-level state carried on every scan response (contract symmetry).\n * Fields are outcome state per the dashboard IP boundary — customer-visible.\n */\nexport interface ScanSessionState {\n session_risk_score?: number;\n session_turn_number?: number;\n session_patterns?: string[];\n session_locked?: boolean;\n [key: string]: unknown;\n}\n\n/**\n * A single policy violation as emitted by the /api/scan/enforce endpoint.\n * The sanitizer strips policy_id / policy_name / matched_pattern / other\n * attribution before this reaches callers; what remains here is the\n * customer-visible outcome surface.\n */\nexport interface ScanViolation {\n threat_type?: string;\n owasp_category?: string;\n severity?: string;\n action?: string;\n user_message?: string;\n suggested_action?: string;\n [key: string]: unknown;\n}\n\nexport interface ScanResult {\n safe: boolean;\n reason?: string;\n threat_type?: string;\n severity?: string;\n confidence?: number | string;\n violations?: ScanViolation[];\n guidance?: string;\n approval_info?: ApprovalInfo;\n /** Cooperative Governance action — server-authoritative proceed/refuse signal */\n action?: ScanAction;\n /** Refuse tier: allow / warn / require_approval / block */\n refuse_tier?: ScanAction;\n /** Recovery guidance, present on refuse verdicts */\n recovery?: ScanRecovery;\n /** L9 session correlation state — outcome, customer-visible */\n session_state?: ScanSessionState;\n /** Specialized scan input type, e.g. 'sql' / 'file_path' / 'a2a_message' */\n content_type?: string;\n /** Client-side session rotation guidance */\n client_session_rotation?: unknown;\n /** L9 session risk score (0.0-1.0), present when session correlation is active */\n session_risk_score?: number;\n /** L9 matched correlation patterns, present when multi-turn patterns are detected */\n correlation_patterns?: CorrelationPattern[];\n /**\n * True when this is a fail-open verdict returned without a completed scan —\n * i.e. `failMode: 'open'` was set and the backend was unreachable, so\n * enforcement was skipped. Lets a caller distinguish \"scanned and clean\"\n * from \"not scanned, allowed anyway.\"\n */\n degraded?: boolean;\n [key: string]: unknown;\n}\n\n/**\n * Build a fail-open ALLOW verdict. Returned only when `failMode === 'open'` is\n * explicitly set and the scan could not complete (timeout, backend error).\n * Marked `degraded: true` — centralize all fail-open returns through this so the\n * marker can never be forgotten on a new wrapper.\n */\nexport function failOpenResult(reason: string): ScanResult {\n return { safe: true, reason, degraded: true };\n}\n\n/**\n * Result of ScanClient.declareScope — the persisted scope row plus derived\n * active_until + expired fields. Mirrors the shape returned by\n * POST /api/v1/agent/scope/declare on the backend.\n */\nexport interface DeclareScopeResult {\n scope_id?: string;\n agent_id?: string;\n purpose?: string;\n allowed_tools?: string[];\n forbidden_tools?: string[];\n max_duration_seconds?: number;\n expires_at?: string;\n active_until?: string;\n expired?: boolean;\n created_at?: string;\n updated_at?: string;\n}\n\n/**\n * Options for the ScanClient.\n */\nexport interface ScanClientOptions {\n /** Shrike API key for authentication */\n apiKey: string;\n /** Shrike API endpoint URL */\n endpoint?: string;\n /** Request timeout in milliseconds */\n timeout?: number;\n /** Rate limit in requests per minute (default: 100) */\n rateLimitPerMinute?: number;\n /** Optional callback to refresh API key on 401. Return new key or null. */\n onKeyRefresh?: () => Promise<string | null>;\n}\n\n/**\n * Generate a UUID v4 string.\n */\nfunction generateUUID(): string {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n/**\n * Generate headers for scan API requests.\n */\nexport function getScanHeaders(\n shrikeApiKey: string,\n requestId?: string\n): Record<string, string> {\n return {\n Authorization: `Bearer ${shrikeApiKey}`,\n 'Content-Type': 'application/json',\n 'X-Shrike-SDK': SDK_NAME,\n 'X-Shrike-SDK-Version': VERSION,\n 'X-Shrike-Request-ID': requestId || generateUUID(),\n };\n}\n\n/** Check if an error is transient and retryable. */\nfunction isRetryableError(error: unknown): boolean {\n if (error instanceof Error) {\n const cause = 'cause' in error ? String((error as { cause?: unknown }).cause) : '';\n const errorStr = `${error.name} ${error.message} ${cause}`;\n return RETRY_CONFIG.retryableErrors.some((e) => errorStr.includes(e));\n }\n return false;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Fetch with retry for cold-start and transient failure resilience.\n * Matches MCP server's fetchWithRetry pattern.\n */\nasync function fetchWithRetry(\n url: string,\n options: RequestInit,\n timeoutMs: number,\n apiKey: string,\n onKeyRefresh?: () => Promise<string | null>\n): Promise<Response> {\n let lastError: Error | null = null;\n let delay = RETRY_CONFIG.initialDelayMs;\n\n for (let attempt = 0; attempt <= RETRY_CONFIG.maxRetries; attempt++) {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeoutMs);\n\n try {\n const response = await fetch(url, {\n ...options,\n signal: controller.signal,\n });\n clearTimeout(timeoutId);\n\n // On 401, try key refresh and retry once\n if (response.status === 401 && onKeyRefresh && attempt === 0) {\n const newKey = await onKeyRefresh();\n if (newKey && newKey !== apiKey) {\n const retryController = new AbortController();\n const retryTimeout = setTimeout(() => retryController.abort(), timeoutMs);\n try {\n const headers = {\n ...(options.headers as Record<string, string>),\n Authorization: `Bearer ${newKey}`,\n };\n const retryResponse = await fetch(url, {\n ...options,\n headers,\n signal: retryController.signal,\n });\n clearTimeout(retryTimeout);\n return retryResponse;\n } catch {\n clearTimeout(retryTimeout);\n // Fall through to return original 401\n }\n }\n }\n\n return response;\n } catch (error) {\n clearTimeout(timeoutId);\n lastError = error instanceof Error ? error : new Error(String(error));\n\n // Don't retry on abort (timeout) or non-retryable errors\n if (lastError.name === 'AbortError' || !isRetryableError(error)) {\n throw lastError;\n }\n\n if (attempt < RETRY_CONFIG.maxRetries) {\n await sleep(delay);\n delay = Math.min(delay * RETRY_CONFIG.backoffMultiplier, RETRY_CONFIG.maxDelayMs);\n }\n }\n }\n\n throw lastError || new Error('Fetch failed after retries');\n}\n\n/**\n * Build the session context object for backend requests.\n */\nfunction buildSessionContext(extraContext?: Record<string, unknown>): Record<string, unknown> {\n return {\n ...extraContext,\n session_id: getSessionId(),\n agent_id: getAgentId(),\n source_application: 'shrike-guard-ts',\n };\n}\n\n/**\n * HTTP client for the Shrike scan API.\n */\n/**\n * Decide whether a scan verdict should be enforced as a block.\n *\n * Prefers the server-authoritative `action` field emitted by\n * /api/scan/enforce. Falls back to the legacy\n * `safe` boolean for verdicts that predate the enforce endpoint (older\n * backends, circuit-breaker fail-open synthetic verdicts, cached responses).\n *\n * Behavior:\n * - action = \"block\" → true\n * - action = \"require_approval\" → true (held actions are refused at the\n * tool-call boundary; caller can re-issue\n * after approval lands)\n * - action = \"allow\" → false\n * - action = \"warn\" → false (advisory; caller should surface\n * via block-feedback but not refuse)\n * - action absent → fall back to `!safe`\n *\n * This helper is the ONLY place the SDK converts a verdict into a\n * proceed-vs-refuse decision. Every LLM wrapper (OpenAI, Anthropic, Gemini)\n * routes through it so behavior stays uniform.\n *\n * Contract-symmetry pin: mirrors Python `_is_blocked` in shrike_guard.scanner.\n * If either SDK diverges, that is a bug in one of the two.\n */\nexport function isBlocked(verdict: ScanResult | Record<string, unknown>): boolean {\n const action = (verdict as Record<string, unknown>).action;\n if (typeof action === 'string' && action.length > 0) {\n // Known non-blocking tiers proceed.\n if (action === 'allow' || action === 'warn') return false;\n // Known blocking tiers refuse.\n if (action === 'block' || action === 'require_approval') return true;\n // Unknown/future tier (e.g. a new \"quarantine\" the backend adds): do NOT\n // fail open on an unrecognized name — fall through to `safe`. A new\n // blocking tier also sets safe:false, so this fails closed until the\n // client learns the tier explicitly. Forward-compat contract, see\n // tests/unit/contract-forward-compat.test.ts.\n }\n const safe = (verdict as Record<string, unknown>).safe;\n if (typeof safe === 'boolean') {\n return !safe;\n }\n return false;\n}\n\n/**\n * When running without an API key, appends a signup hint to scan results\n * so agents/users know they can upgrade from regex-only to full scanning.\n */\nexport function maybeAddSignupHint(result: ScanResult, apiKey: string): ScanResult {\n if (apiKey) return result;\n // Don't override if backend already provided upgrade_hint\n if ((result as any).upgrade_hint) return result;\n return {\n ...result,\n _note: 'Running without API key (L1-L5 only). Register free for cognitive threat detection: npx shrike-mcp --signup',\n };\n}\n\nexport class ScanClient {\n private apiKey: string;\n private readonly endpoint: string;\n private readonly timeout: number;\n private readonly rateLimiter: RateLimiter;\n private readonly onKeyRefresh?: () => Promise<string | null>;\n\n constructor(options: ScanClientOptions) {\n this.apiKey = options.apiKey;\n this.endpoint = (options.endpoint || DEFAULT_ENDPOINT).replace(/\\/$/, '');\n this.timeout = options.timeout || DEFAULT_SCAN_TIMEOUT;\n this.rateLimiter = new RateLimiter(options.rateLimitPerMinute || DEFAULT_RATE_LIMIT_PER_MINUTE);\n this.onKeyRefresh = options.onKeyRefresh;\n\n if (!this.apiKey) {\n console.warn('[shrike-guard] No API key provided — running in free tier (regex-only).');\n console.warn('[shrike-guard] For full scanning (LLM analysis, session correlation): npx shrike-mcp --signup');\n }\n }\n\n /** Check rate limit before each request. */\n private checkRateLimit(): void {\n const result = this.rateLimiter.consume();\n if (!result.allowed) {\n throw new ShrikeRateLimitError(result.retryAfterMs!);\n }\n }\n\n /**\n * Scan a prompt for security threats.\n *\n * @param prompt - The user prompt to scan.\n * @param context - Optional conversation context for better analysis.\n * @returns Scan result with 'safe' boolean and additional details.\n * @throws Error if the request fails or times out.\n */\n async scan(prompt: string, context?: string): Promise<ScanResult> {\n // Client-side size validation to fail fast\n const totalSize = prompt.length + (context?.length || 0);\n if (totalSize > MAX_CONTENT_SIZE) {\n return {\n safe: false,\n reason: `Content too large (${Math.round(totalSize / 1024)}KB > ${MAX_CONTENT_SIZE / 1024}KB limit)`,\n threat_type: 'size_limit_exceeded',\n confidence: 1.0,\n violations: [\n {\n type: 'size_limit',\n description: `Content exceeds maximum size of ${MAX_CONTENT_SIZE / 1024}KB`,\n },\n ],\n };\n }\n\n // Auto-chunk large prompts. Below the threshold we keep the single-shot\n // path unchanged; above it we split on natural boundaries, scan each\n // chunk sequentially, and stop on the first block verdict. The\n // conversation_history context is NOT chunked — it rides on every scan\n // so downstream layers see the same session shape.\n if (prompt.length > AUTO_CHUNK_THRESHOLD) {\n return this.scanChunked(prompt, context);\n }\n\n this.checkRateLimit();\n\n const payload: Record<string, unknown> = {\n prompt,\n scan_type: 'full',\n context: buildSessionContext(),\n };\n if (context) {\n payload.conversation_history = context;\n }\n\n const response = await fetchWithRetry(\n `${this.endpoint}/api/scan/enforce`,\n {\n method: 'POST',\n headers: getScanHeaders(this.apiKey),\n body: JSON.stringify(payload),\n },\n this.timeout,\n this.apiKey,\n this.onKeyRefresh\n );\n\n if (!response.ok) {\n throw new Error(`Scan API returned error: ${response.status}`);\n }\n\n return maybeAddSignupHint(sanitizeScanResponse((await response.json()) as ScanResult), this.apiKey);\n }\n\n /**\n * Chunk-and-scan path for prompts above AUTO_CHUNK_THRESHOLD. Splits on\n * natural boundaries, scans sequentially, aggregates. Stops on the first\n * block verdict (fail-fast) so a compromised chunk doesn't pay for the\n * remaining scans.\n *\n * Known limit: same session ID rides every chunk, so L9 turn count\n * inflates by chunk-count. Fix post-launch via backend chunk_group field.\n */\n private async scanChunked(prompt: string, context?: string): Promise<ScanResult> {\n const chunks = chunkContent(prompt);\n const results: ScanResult[] = [];\n for (const chunk of chunks) {\n const chunkResult = await this.scan(chunk, context);\n results.push(chunkResult);\n const action = chunkResult.action || chunkResult.refuse_tier;\n if (action === 'block') {\n break;\n }\n }\n return maybeAddSignupHint(aggregateChunkResults(results), this.apiKey);\n }\n\n /**\n * Scan a SQL query for injection attacks.\n *\n * @param query - The SQL query to scan.\n * @param database - Optional database name for context.\n * @param allowDestructive - If true, allows DROP/TRUNCATE operations.\n * @returns Scan result with 'safe' boolean and additional details.\n */\n async scanSql(\n query: string,\n database?: string,\n allowDestructive = false\n ): Promise<ScanResult> {\n if (query.length > MAX_CONTENT_SIZE) {\n return {\n safe: false,\n reason: `SQL query too large (${Math.round(query.length / 1024)}KB > ${MAX_CONTENT_SIZE / 1024}KB limit)`,\n threat_type: 'size_limit_exceeded',\n confidence: 1.0,\n violations: [\n {\n type: 'size_limit',\n description: `Query exceeds maximum size of ${MAX_CONTENT_SIZE / 1024}KB`,\n },\n ],\n };\n }\n\n this.checkRateLimit();\n\n const toolContext: Record<string, unknown> = {};\n if (database) {\n toolContext.database = database;\n }\n if (allowDestructive) {\n toolContext.allow_destructive = 'true';\n }\n\n const payload = {\n content: query,\n content_type: 'sql',\n context: buildSessionContext(toolContext),\n };\n\n const response = await fetchWithRetry(\n `${this.endpoint}/api/scan/enforce/specialized`,\n {\n method: 'POST',\n headers: getScanHeaders(this.apiKey),\n body: JSON.stringify(payload),\n },\n this.timeout,\n this.apiKey,\n this.onKeyRefresh\n );\n\n if (!response.ok) {\n throw new Error(`SQL scan API returned error: ${response.status}`);\n }\n\n return maybeAddSignupHint(sanitizeScanResponse((await response.json()) as ScanResult), this.apiKey);\n }\n\n /**\n * Scan a file path for security risks.\n *\n * @param path - The file path to validate.\n * @param content - Optional file content to scan for secrets/PII.\n * @returns Scan result with 'safe' boolean and additional details.\n */\n async scanFile(path: string, content?: string): Promise<ScanResult> {\n const totalSize = path.length + (content?.length || 0);\n if (totalSize > MAX_CONTENT_SIZE) {\n return {\n safe: false,\n reason: `File content too large (${Math.round(totalSize / 1024)}KB > ${MAX_CONTENT_SIZE / 1024}KB limit)`,\n threat_type: 'size_limit_exceeded',\n confidence: 1.0,\n violations: [\n {\n type: 'size_limit',\n description: `Content exceeds maximum size of ${MAX_CONTENT_SIZE / 1024}KB`,\n },\n ],\n };\n }\n\n this.checkRateLimit();\n\n const contentType = content ? 'file_content' : 'file_path';\n const extraContext: Record<string, unknown> = {};\n if (content) {\n extraContext.file_content = content;\n }\n\n const payload = {\n content: path,\n content_type: contentType,\n context: buildSessionContext(extraContext),\n };\n\n const response = await fetchWithRetry(\n `${this.endpoint}/api/scan/enforce/specialized`,\n {\n method: 'POST',\n headers: getScanHeaders(this.apiKey),\n body: JSON.stringify(payload),\n },\n this.timeout,\n this.apiKey,\n this.onKeyRefresh\n );\n\n if (!response.ok) {\n throw new Error(`File scan API returned error: ${response.status}`);\n }\n\n return maybeAddSignupHint(sanitizeScanResponse((await response.json()) as ScanResult), this.apiKey);\n }\n\n /**\n * Scan an A2A (Agent-to-Agent) protocol message for security threats.\n *\n * @param message - The A2A message text content to scan.\n * @param options - Optional context: sender/receiver agent IDs, task ID, role.\n * @returns Scan result with 'safe' boolean and additional details.\n */\n async scanA2AMessage(\n message: string,\n options?: {\n senderAgentId?: string;\n receiverAgentId?: string;\n taskId?: string;\n role?: 'user' | 'agent';\n }\n ): Promise<ScanResult> {\n if (message.length > MAX_CONTENT_SIZE) {\n return {\n safe: false,\n reason: `Message too large (${Math.round(message.length / 1024)}KB > ${MAX_CONTENT_SIZE / 1024}KB limit)`,\n threat_type: 'size_limit_exceeded',\n confidence: 1.0,\n violations: [\n {\n type: 'size_limit',\n description: `Content exceeds maximum size of ${MAX_CONTENT_SIZE / 1024}KB`,\n },\n ],\n };\n }\n\n this.checkRateLimit();\n\n const extraContext: Record<string, unknown> = {};\n if (options?.senderAgentId) extraContext.sender_agent_id = options.senderAgentId;\n if (options?.receiverAgentId) extraContext.receiver_agent_id = options.receiverAgentId;\n if (options?.taskId) extraContext.task_id = options.taskId;\n if (options?.role) extraContext.role = options.role;\n\n const payload = {\n content: message,\n content_type: 'a2a_message',\n context: buildSessionContext(extraContext),\n };\n\n const response = await fetchWithRetry(\n `${this.endpoint}/api/scan/enforce/specialized`,\n {\n method: 'POST',\n headers: getScanHeaders(this.apiKey),\n body: JSON.stringify(payload),\n },\n this.timeout,\n this.apiKey,\n this.onKeyRefresh\n );\n\n if (!response.ok) {\n throw new Error(`A2A message scan API returned error: ${response.status}`);\n }\n\n return maybeAddSignupHint(sanitizeScanResponse((await response.json()) as ScanResult), this.apiKey);\n }\n\n /**\n * Scan an A2A AgentCard JSON for security threats.\n *\n * @param agentCard - The raw JSON string of the A2A AgentCard to scan.\n * @param verifySignature - Reserved for future JWS signature verification.\n * @returns Scan result with 'safe' boolean and additional details.\n */\n async scanAgentCard(\n agentCard: string,\n verifySignature = false\n ): Promise<ScanResult> {\n if (agentCard.length > MAX_CONTENT_SIZE) {\n return {\n safe: false,\n reason: `Agent card too large (${Math.round(agentCard.length / 1024)}KB > ${MAX_CONTENT_SIZE / 1024}KB limit)`,\n threat_type: 'size_limit_exceeded',\n confidence: 1.0,\n violations: [\n {\n type: 'size_limit',\n description: `Content exceeds maximum size of ${MAX_CONTENT_SIZE / 1024}KB`,\n },\n ],\n };\n }\n\n this.checkRateLimit();\n\n const extraContext: Record<string, unknown> = {};\n if (verifySignature) extraContext.verify_signature = 'true';\n\n const payload = {\n content: agentCard,\n content_type: 'agent_card',\n context: buildSessionContext(extraContext),\n };\n\n const response = await fetchWithRetry(\n `${this.endpoint}/api/scan/enforce/specialized`,\n {\n method: 'POST',\n headers: getScanHeaders(this.apiKey),\n body: JSON.stringify(payload),\n },\n this.timeout,\n this.apiKey,\n this.onKeyRefresh\n );\n\n if (!response.ok) {\n throw new Error(`Agent card scan API returned error: ${response.status}`);\n }\n\n return maybeAddSignupHint(sanitizeScanResponse((await response.json()) as ScanResult), this.apiKey);\n }\n\n /**\n * Declare (or refresh) the operating scope for a task-scoped agent.\n *\n * Once declared, every subsequent scan for the same agent_id is enforced\n * against the scope on the backend. Tool calls outside allowed_tools —\n * or explicitly on forbidden_tools — route to refuse_tier:\n * \"require_approval\" with threat_type: \"scope_violation\". Expired scopes\n * emit threat_type: \"scope_expired\". Absent a declaration, no scope\n * check runs; every existing SDK integration is unaffected until it\n * opts in.\n *\n * Wire contract mirrors ScanClient.declare_scope on the Python SDK and\n * scan_declare_scope on the shrike-mcp package — do not diverge without\n * updating those siblings.\n *\n * @param options.agentId - Agent identity this scope applies to.\n * @param options.allowedTools - Exact tool names permitted; [\"*\"] = any.\n * @param options.forbiddenTools - Optional. Wins over allowedTools.\n * @param options.purpose - Optional audit + dashboard label.\n * @param options.maxDurationSeconds - Optional TTL from created_at.\n * @param options.expiresAt - Optional ISO-8601 absolute expiry.\n * @returns The persisted scope row, including scope_id + active_until.\n */\n async declareScope(options: {\n agentId: string;\n allowedTools: string[];\n forbiddenTools?: string[];\n purpose?: string;\n maxDurationSeconds?: number;\n expiresAt?: string;\n }): Promise<DeclareScopeResult> {\n this.checkRateLimit();\n\n const payload: Record<string, unknown> = {\n agent_id: options.agentId,\n allowed_tools: options.allowedTools,\n };\n if (options.purpose !== undefined) payload.purpose = options.purpose;\n if (options.forbiddenTools !== undefined) payload.forbidden_tools = options.forbiddenTools;\n if (options.maxDurationSeconds !== undefined) {\n payload.max_duration_seconds = options.maxDurationSeconds;\n }\n if (options.expiresAt !== undefined) payload.expires_at = options.expiresAt;\n\n const response = await fetchWithRetry(\n `${this.endpoint}/api/v1/agent/scope/declare`,\n {\n method: 'POST',\n headers: getScanHeaders(this.apiKey),\n body: JSON.stringify(payload),\n },\n this.timeout,\n this.apiKey,\n this.onKeyRefresh\n );\n\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new Error(\n `declareScope failed: ${response.status}${text ? ` — ${text.trim()}` : ''}`\n );\n }\n\n return (await response.json()) as DeclareScopeResult;\n }\n}\n","/**\n * Base API client for Shrike backend.\n */\n\nimport { DEFAULT_ENDPOINT } from '../config';\nimport { getScanHeaders } from '../scanner';\n\n/**\n * Base options for API clients.\n */\nexport interface BaseClientOptions {\n /** API key for authentication */\n apiKey?: string;\n /** Base URL for the API */\n baseUrl?: string;\n /** Request timeout in milliseconds */\n timeout?: number;\n}\n\n/**\n * Base API client with common HTTP functionality.\n */\nexport class BaseClient {\n protected readonly apiKey: string;\n protected readonly baseUrl: string;\n protected readonly timeout: number;\n\n constructor(options: BaseClientOptions = {}) {\n this.apiKey = options.apiKey || '';\n this.baseUrl = (options.baseUrl || DEFAULT_ENDPOINT).replace(/\\/$/, '');\n this.timeout = options.timeout || 30000;\n }\n\n /**\n * Make an HTTP request to the API.\n */\n protected async request<T>(\n method: string,\n path: string,\n body?: unknown\n ): Promise<T> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(`${this.baseUrl}${path}`, {\n method,\n headers: getScanHeaders(this.apiKey),\n body: body ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n });\n\n if (!response.ok) {\n const errorBody = await response.json().catch(() => ({ message: response.statusText })) as { message?: string };\n throw new Error(errorBody.message || `API error: ${response.status}`);\n }\n\n return response.json() as Promise<T>;\n } finally {\n clearTimeout(timeoutId);\n }\n }\n\n protected get<T>(path: string): Promise<T> {\n return this.request<T>('GET', path);\n }\n\n protected post<T>(path: string, body?: unknown): Promise<T> {\n return this.request<T>('POST', path, body);\n }\n\n protected put<T>(path: string, body?: unknown): Promise<T> {\n return this.request<T>('PUT', path, body);\n }\n\n protected delete<T>(path: string): Promise<T> {\n return this.request<T>('DELETE', path);\n }\n}\n","/**\n * Authentication API client for Shrike.\n */\n\nimport { BaseClient, BaseClientOptions } from './base';\n\n/**\n * Registration request payload.\n */\nexport interface RegisterRequest {\n email: string;\n password: string;\n company_name?: string;\n}\n\n/**\n * Login request payload.\n */\nexport interface LoginRequest {\n email: string;\n password: string;\n}\n\n/**\n * Authentication response with tokens.\n */\nexport interface AuthResponse {\n access_token: string;\n refresh_token: string;\n token_type: string;\n expires_in: number;\n}\n\n/**\n * User profile response.\n */\nexport interface UserProfile {\n customer_id: string;\n email: string;\n company_name?: string;\n created_at: string;\n}\n\n/**\n * Authentication client for Shrike API.\n */\nexport class AuthClient extends BaseClient {\n constructor(options: BaseClientOptions = {}) {\n super(options);\n }\n\n /**\n * Register a new customer account.\n */\n async register(request: RegisterRequest): Promise<AuthResponse> {\n return this.request<AuthResponse>('POST', '/api/v1/auth/register', request);\n }\n\n /**\n * Login with email and password.\n */\n async login(request: LoginRequest): Promise<AuthResponse> {\n return this.request<AuthResponse>('POST', '/api/v1/auth/login', request);\n }\n\n /**\n * Refresh the access token using a refresh token.\n */\n async refresh(refreshToken: string): Promise<AuthResponse> {\n return this.request<AuthResponse>('POST', '/api/v1/auth/refresh', {\n refresh_token: refreshToken,\n });\n }\n\n /**\n * Logout and invalidate the current session.\n */\n async logout(): Promise<void> {\n await this.request<void>('POST', '/api/v1/auth/logout');\n }\n\n /**\n * Get the current user's profile.\n */\n async me(): Promise<UserProfile> {\n return this.request<UserProfile>('GET', '/api/v1/auth/me');\n }\n}\n","/**\n * Agent API client for Shrike.\n */\n\nimport { BaseClient, BaseClientOptions } from './base';\n\n/**\n * Agent registration request.\n */\nexport interface RegisterAgentRequest {\n name: string;\n description?: string;\n policy_id?: string;\n}\n\n/**\n * Agent details.\n */\nexport interface Agent {\n agent_id: string;\n customer_id: string;\n name: string;\n description?: string;\n api_key: string;\n policy_id?: string;\n status: 'active' | 'inactive';\n created_at: string;\n last_heartbeat?: string;\n}\n\n/**\n * Heartbeat response.\n */\nexport interface HeartbeatResponse {\n status: string;\n server_time: string;\n}\n\n/**\n * Agent policy.\n */\nexport interface AgentPolicy {\n policy_id: string;\n name: string;\n rules: PolicyRule[];\n}\n\n/**\n * Policy rule.\n */\nexport interface PolicyRule {\n type: string;\n action: 'block' | 'warn' | 'allow';\n threshold?: number;\n [key: string]: unknown;\n}\n\n/**\n * Agent management client for Shrike API.\n */\nexport class AgentClient extends BaseClient {\n constructor(options: BaseClientOptions = {}) {\n super(options);\n }\n\n /**\n * Register a new agent.\n * Requires a customer API key.\n */\n async register(request: RegisterAgentRequest): Promise<Agent> {\n return this.request<Agent>('POST', '/api/v1/agents/register', request);\n }\n\n /**\n * Send a heartbeat from an agent.\n * Requires an agent API key.\n */\n async heartbeat(): Promise<HeartbeatResponse> {\n return this.request<HeartbeatResponse>('POST', '/api/v1/agents/heartbeat');\n }\n\n /**\n * Get the policies assigned to this agent.\n * Requires an agent API key.\n */\n async getPolicies(): Promise<AgentPolicy[]> {\n return this.request<AgentPolicy[]>('GET', '/api/v1/agents/policies');\n }\n\n /**\n * List all agents for the current customer.\n * Requires a customer API key.\n */\n async list(): Promise<Agent[]> {\n return this.request<Agent[]>('GET', '/api/v1/agents');\n }\n\n /**\n * Get an agent by ID.\n */\n async getAgent(agentId: string): Promise<Agent> {\n return this.request<Agent>('GET', `/api/v1/agents/${agentId}`);\n }\n\n /**\n * Delete an agent.\n */\n async deleteAgent(agentId: string): Promise<void> {\n await this.request<void>('DELETE', `/api/v1/agents/${agentId}`);\n }\n}\n","/**\n * Policy API client for Shrike.\n */\n\nimport { BaseClient, BaseClientOptions } from './base';\n\n/**\n * Policy rule definition.\n */\nexport interface PolicyRule {\n type: 'prompt_injection' | 'pii_detection' | 'jailbreak' | 'sql_injection' | 'custom';\n action: 'block' | 'warn' | 'allow';\n threshold?: number;\n patterns?: string[];\n [key: string]: unknown;\n}\n\n/**\n * Policy definition.\n */\nexport interface Policy {\n policy_id: string;\n customer_id: string;\n name: string;\n description?: string;\n rules: PolicyRule[];\n is_default: boolean;\n created_at: string;\n updated_at: string;\n}\n\n/**\n * Create policy request.\n */\nexport interface CreatePolicyRequest {\n name: string;\n description?: string;\n rules: PolicyRule[];\n is_default?: boolean;\n}\n\n/**\n * Update policy request.\n */\nexport interface UpdatePolicyRequest {\n name?: string;\n description?: string;\n rules?: PolicyRule[];\n is_default?: boolean;\n}\n\n/**\n * Policy management client for Shrike API.\n */\nexport class PolicyClient extends BaseClient {\n constructor(options: BaseClientOptions = {}) {\n super(options);\n }\n\n /**\n * List all policies for the current customer.\n */\n async list(): Promise<Policy[]> {\n return this.request<Policy[]>('GET', '/api/v1/policies');\n }\n\n /**\n * Get a policy by ID.\n */\n async getPolicy(policyId: string): Promise<Policy> {\n return this.request<Policy>('GET', `/api/v1/policies/${policyId}`);\n }\n\n /**\n * Create a new policy.\n */\n async create(request: CreatePolicyRequest): Promise<Policy> {\n return this.request<Policy>('POST', '/api/v1/policies', request);\n }\n\n /**\n * Update an existing policy.\n */\n async update(policyId: string, request: UpdatePolicyRequest): Promise<Policy> {\n return this.request<Policy>('PUT', `/api/v1/policies/${policyId}`, request);\n }\n\n /**\n * Delete a policy.\n */\n async deletePolicy(policyId: string): Promise<void> {\n await this.request<void>('DELETE', `/api/v1/policies/${policyId}`);\n }\n}\n","/**\n * Sandbox API client for Shrike.\n */\n\nimport { BaseClient, BaseClientOptions } from './base';\nimport { ScanResult } from '../scanner';\n\n/**\n * Sandbox scan request.\n */\nexport interface SandboxScanRequest {\n prompt: string;\n context?: string;\n model?: string;\n}\n\n/**\n * Sandbox client for testing prompts without affecting production metrics.\n */\nexport class SandboxClient extends BaseClient {\n constructor(options: BaseClientOptions = {}) {\n super(options);\n }\n\n /**\n * Scan a prompt in sandbox mode.\n * This does not count against production quotas.\n */\n async scan(request: SandboxScanRequest): Promise<ScanResult> {\n return this.request<ScanResult>('POST', '/api/v1/sandbox/scan', request);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/config.ts","../../package.json","../../src/version.ts","../../src/scanner.ts","../../src/api/base.ts","../../src/api/auth.ts","../../src/api/agents.ts","../../src/api/policies.ts","../../src/api/sandbox.ts"],"names":["randomUUID"],"mappings":";;;;;AA+BO,IAAM,gBAAA,GAAmB,sCAAA;AASzB,IAAM,QAAA,GAAW,YAAA;AAOLA,iBAAA;AACF,OAAA,CAAQ,GAAA,CAAI,eAAA,IAAmB,CAAA,OAAA,EAAUA,mBAAW,CAAE,KAA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AAM,OAAO,OAAA,EAA+C;AAC1D,IAAA,OAAO,IAAA,CAAK,OAAA,CAAgB,MAAA,EAAQ,kBAAA,EAAoB,OAAO,CAAA;AAAA,EACjE;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,MAAA,CAAO,QAAA,EAAkB,OAAA,EAA+C;AAC5E,IAAA,OAAO,KAAK,OAAA,CAAgB,KAAA,EAAO,CAAA,iBAAA,EAAoB,QAAQ,IAAI,OAAO,CAAA;AAAA,EAC5E;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,aAAa,QAAA,EAAiC;AAClD,IAAA,MAAM,IAAA,CAAK,OAAA,CAAc,QAAA,EAAU,CAAA,iBAAA,EAAoB,QAAQ,CAAA,CAAE,CAAA;AAAA,EACnE;AACF;;;AC1EO,IAAM,aAAA,GAAN,cAA4B,UAAA,CAAW;AAAA,EAC5C,WAAA,CAAY,OAAA,GAA6B,EAAC,EAAG;AAC3C,IAAA,KAAA,CAAM,OAAO,CAAA;AAAA,EACf;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,KAAK,OAAA,EAAkD;AAC3D,IAAA,OAAO,IAAA,CAAK,OAAA,CAAoB,MAAA,EAAQ,sBAAA,EAAwB,OAAO,CAAA;AAAA,EACzE;AACF","file":"index.js","sourcesContent":["/**\n * Configuration constants and types for the Shrike Guard SDK.\n */\n\nimport { randomUUID } from 'node:crypto';\n\n/**\n * Defines behavior when scan operations fail.\n */\nexport enum FailMode {\n /**\n * Allow the request to proceed (fail-open). Use this mode when\n * availability is prioritized over strict security.\n */\n OPEN = 'open',\n\n /**\n * Block the request and raise an exception (fail-closed). This is the\n * default behavior — matching the MCP server's security posture. Use\n * fail-open only when you've explicitly decided availability matters more.\n */\n CLOSED = 'closed',\n}\n\n/** Default timeout for scan requests in milliseconds */\nexport const DEFAULT_SCAN_TIMEOUT = 10000;\n\n/** Default fail mode - block requests when scan fails (fail-closed) */\nexport const DEFAULT_FAIL_MODE = FailMode.CLOSED;\n\n/** Default Shrike API endpoint (uses load balancer for scalability) */\nexport const DEFAULT_ENDPOINT = 'https://api.shrikesecurity.com/agent';\n\n/** Default rate limit (requests per minute) */\nexport const DEFAULT_RATE_LIMIT_PER_MINUTE = 100;\n\n// Note: All scanning is done via backend API (tier-based: community=L1-L4, pro=L1-L8)\n// No local patterns needed - backend handles all detection logic\n\n/** SDK identification */\nexport const SDK_NAME = 'typescript';\nexport const SDK_USER_AGENT = 'shrike-guard-typescript';\n\n/**\n * Session identity — persists for the lifetime of this SDK process.\n * Maps to L9's SessionCache key for multi-turn attack detection.\n */\nconst SESSION_ID = randomUUID();\nconst AGENT_ID = process.env.SHRIKE_AGENT_ID || `sdk-ts-${randomUUID().slice(0, 8)}`;\n\n/** Returns the stable session ID for this SDK process. */\nexport function getSessionId(): string {\n return SESSION_ID;\n}\n\n/** Returns the agent ID (from SHRIKE_AGENT_ID env or auto-generated). */\nexport function getAgentId(): string {\n return AGENT_ID;\n}\n\n/**\n * Approval information returned when a policy requires human sign-off.\n */\nexport interface ApprovalInfo {\n requires_approval: boolean;\n approval_id: string;\n approval_level: string;\n action_summary: string;\n policy_name: string;\n expires_in_seconds: number;\n threat_type?: string;\n severity?: string;\n owasp_category?: string;\n risk_factors?: string[];\n original_action?: string;\n}\n\n/**\n * Retry configuration for transient failure resilience.\n * Matches MCP server's RETRY_CONFIG for consistent behavior.\n */\nexport const RETRY_CONFIG = {\n maxRetries: 2,\n initialDelayMs: 200,\n maxDelayMs: 2000,\n backoffMultiplier: 2,\n retryableErrors: ['ECONNREFUSED', 'ECONNRESET', 'ETIMEDOUT', 'fetch failed'],\n};\n","{\n \"name\": \"shrike-guard\",\n \"version\": \"4.0.3\",\n \"description\": \"Shrike SDK for AI agent action governance — drop-in wrapper for OpenAI, Anthropic, and Gemini that governs every tool call, prompt, and response server-side. Allow / approve / block. Free tier available.\",\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.js\"\n },\n \"./openai\": {\n \"types\": \"./dist/openai/index.d.ts\",\n \"import\": \"./dist/openai/index.mjs\",\n \"require\": \"./dist/openai/index.js\"\n },\n \"./anthropic\": {\n \"types\": \"./dist/anthropic/index.d.ts\",\n \"import\": \"./dist/anthropic/index.mjs\",\n \"require\": \"./dist/anthropic/index.js\"\n },\n \"./gemini\": {\n \"types\": \"./dist/gemini/index.d.ts\",\n \"import\": \"./dist/gemini/index.mjs\",\n \"require\": \"./dist/gemini/index.js\"\n },\n \"./api\": {\n \"types\": \"./dist/api/index.d.ts\",\n \"import\": \"./dist/api/index.mjs\",\n \"require\": \"./dist/api/index.js\"\n }\n },\n \"files\": [\n \"dist\",\n \"README.md\",\n \"CHANGELOG.md\",\n \"LICENSE\"\n ],\n \"scripts\": {\n \"build\": \"tsup\",\n \"test\": \"jest\",\n \"test:coverage\": \"jest --coverage\",\n \"lint\": \"eslint src --ext .ts\",\n \"typecheck\": \"tsc --noEmit\",\n \"prepublishOnly\": \"npm run build\"\n },\n \"keywords\": [\n \"action-governance\",\n \"ai-agents\",\n \"agent-security\",\n \"agent-governance\",\n \"tool-call-gating\",\n \"ai-governance\",\n \"openai\",\n \"anthropic\",\n \"claude\",\n \"gemini\",\n \"llm\",\n \"prompt-injection\",\n \"pii\",\n \"jailbreak\",\n \"ai-safety\"\n ],\n \"author\": \"Shrike Security <security@shrikesecurity.com>\",\n \"license\": \"Apache-2.0\",\n \"homepage\": \"https://shrikesecurity.com\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/Shrike-Security/shrike-guard-js\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/Shrike-Security/shrike-guard-js/issues\"\n },\n \"peerDependencies\": {\n \"@anthropic-ai/sdk\": \">=0.18.0\",\n \"@google/genai\": \">=1.0.0\",\n \"openai\": \">=4.0.0\"\n },\n \"peerDependenciesMeta\": {\n \"openai\": {\n \"optional\": true\n },\n \"@anthropic-ai/sdk\": {\n \"optional\": true\n },\n \"@google/genai\": {\n \"optional\": true\n }\n },\n \"devDependencies\": {\n \"@anthropic-ai/sdk\": \"^0.20.0\",\n \"@google/genai\": \"^2.12.0\",\n \"@types/jest\": \"^29.5.12\",\n \"@types/node\": \"^20.11.0\",\n \"jest\": \"^29.7.0\",\n \"openai\": \"^4.28.0\",\n \"ts-jest\": \"^29.1.2\",\n \"tsup\": \"^8.5.1\",\n \"typescript\": \"^5.3.3\"\n },\n \"engines\": {\n \"node\": \">=18.0.0\"\n }\n}\n","// SDK version — derived from package.json at build time (tsup/esbuild inlines\n// the JSON literal, resolveJsonModule is on), so it can never drift from the\n// published version. It was previously a hardcoded '1.5.0' that fell out of\n// sync with package.json (4.0.2) and mis-stamped X-Shrike-SDK-Version on every\n// scan. Guarded by tests/unit/version.test.ts. Mirrors the Python SDK, which\n// derives __version__ from installed distribution metadata.\nimport { version } from '../package.json';\n\nexport const VERSION: string = version;\n","/**\n * HTTP client for the Shrike scan API.\n * Includes retry with exponential backoff, session correlation,\n * approval workflow, 401 key refresh, and rate limiting.\n */\n\nimport {\n DEFAULT_ENDPOINT,\n DEFAULT_SCAN_TIMEOUT,\n DEFAULT_RATE_LIMIT_PER_MINUTE,\n SDK_NAME,\n RETRY_CONFIG,\n getSessionId,\n getAgentId,\n} from './config';\nimport type { ApprovalInfo } from './config';\nimport { AUTO_CHUNK_THRESHOLD, aggregateChunkResults, chunkContent } from './chunker';\nimport { ShrikeRateLimitError } from './errors';\nimport { RateLimiter } from './rateLimiter';\nimport { sanitizeScanResponse } from './sanitizer';\nimport { VERSION } from './version';\n\n/**\n * Phase 8b: Client-side size limits to fail fast before network round-trip.\n * These limits match the backend limits for consistency.\n */\nconst MAX_CONTENT_SIZE = 100 * 1024; // 100KB - matches backend MaxRequestBodySize\n\n/**\n * Result from a scan operation.\n */\n/**\n * Correlation pattern from L9 session-aware correlation engine.\n */\nexport interface CorrelationPattern {\n pattern_id: string;\n pattern_name: string;\n category: string;\n confidence: number;\n description: string;\n}\n\n/**\n * Governance action per Cooperative Governance 4-state contract (allow / warn / require_approval / block).\n * The `action` field is the server-authoritative signal for proceed-vs-refuse;\n * `isBlocked()` in this module consumes it directly.\n */\nexport type ScanAction = 'allow' | 'warn' | 'require_approval' | 'block';\n\n/**\n * Recovery guidance emitted by the backend on refuse verdicts.\n * `available_tools` names the MCP tools the caller can still invoke while\n * under quarantine (typically read-only surfaces like session_status).\n */\nexport interface ScanRecovery {\n instruction?: string;\n available_tools?: string[];\n patterns_triggered?: string[];\n [key: string]: unknown;\n}\n\n/**\n * Session-level state carried on every scan response (contract symmetry).\n * Fields are outcome state per the dashboard IP boundary — customer-visible.\n */\nexport interface ScanSessionState {\n session_risk_score?: number;\n session_turn_number?: number;\n session_patterns?: string[];\n session_locked?: boolean;\n [key: string]: unknown;\n}\n\n/**\n * A single policy violation as emitted by the /api/scan/enforce endpoint.\n * The sanitizer strips policy_id / policy_name / matched_pattern / other\n * attribution before this reaches callers; what remains here is the\n * customer-visible outcome surface.\n */\nexport interface ScanViolation {\n threat_type?: string;\n owasp_category?: string;\n severity?: string;\n action?: string;\n user_message?: string;\n suggested_action?: string;\n [key: string]: unknown;\n}\n\nexport interface ScanResult {\n safe: boolean;\n reason?: string;\n threat_type?: string;\n severity?: string;\n confidence?: number | string;\n violations?: ScanViolation[];\n guidance?: string;\n approval_info?: ApprovalInfo;\n /** Cooperative Governance action — server-authoritative proceed/refuse signal */\n action?: ScanAction;\n /** Refuse tier: allow / warn / require_approval / block */\n refuse_tier?: ScanAction;\n /** Recovery guidance, present on refuse verdicts */\n recovery?: ScanRecovery;\n /** L9 session correlation state — outcome, customer-visible */\n session_state?: ScanSessionState;\n /** Specialized scan input type, e.g. 'sql' / 'file_path' / 'a2a_message' */\n content_type?: string;\n /** Client-side session rotation guidance */\n client_session_rotation?: unknown;\n /** L9 session risk score (0.0-1.0), present when session correlation is active */\n session_risk_score?: number;\n /** L9 matched correlation patterns, present when multi-turn patterns are detected */\n correlation_patterns?: CorrelationPattern[];\n /**\n * True when this is a fail-open verdict returned without a completed scan —\n * i.e. `failMode: 'open'` was set and the backend was unreachable, so\n * enforcement was skipped. Lets a caller distinguish \"scanned and clean\"\n * from \"not scanned, allowed anyway.\"\n */\n degraded?: boolean;\n [key: string]: unknown;\n}\n\n/**\n * Build a fail-open ALLOW verdict. Returned only when `failMode === 'open'` is\n * explicitly set and the scan could not complete (timeout, backend error).\n * Marked `degraded: true` — centralize all fail-open returns through this so the\n * marker can never be forgotten on a new wrapper.\n */\nexport function failOpenResult(reason: string): ScanResult {\n return { safe: true, reason, degraded: true };\n}\n\n/**\n * Result of ScanClient.declareScope — the persisted scope row plus derived\n * active_until + expired fields. Mirrors the shape returned by\n * POST /api/v1/agent/scope/declare on the backend.\n */\nexport interface DeclareScopeResult {\n scope_id?: string;\n agent_id?: string;\n purpose?: string;\n allowed_tools?: string[];\n forbidden_tools?: string[];\n max_duration_seconds?: number;\n expires_at?: string;\n active_until?: string;\n expired?: boolean;\n created_at?: string;\n updated_at?: string;\n}\n\n/**\n * Options for the ScanClient.\n */\nexport interface ScanClientOptions {\n /** Shrike API key for authentication */\n apiKey: string;\n /** Shrike API endpoint URL */\n endpoint?: string;\n /** Request timeout in milliseconds */\n timeout?: number;\n /** Rate limit in requests per minute (default: 100) */\n rateLimitPerMinute?: number;\n /** Optional callback to refresh API key on 401. Return new key or null. */\n onKeyRefresh?: () => Promise<string | null>;\n}\n\n/**\n * Generate a UUID v4 string.\n */\nfunction generateUUID(): string {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n/**\n * Generate headers for scan API requests.\n */\nexport function getScanHeaders(\n shrikeApiKey: string,\n requestId?: string\n): Record<string, string> {\n return {\n Authorization: `Bearer ${shrikeApiKey}`,\n 'Content-Type': 'application/json',\n 'X-Shrike-SDK': SDK_NAME,\n 'X-Shrike-SDK-Version': VERSION,\n 'X-Shrike-Request-ID': requestId || generateUUID(),\n };\n}\n\n/** Check if an error is transient and retryable. */\nfunction isRetryableError(error: unknown): boolean {\n if (error instanceof Error) {\n const cause = 'cause' in error ? String((error as { cause?: unknown }).cause) : '';\n const errorStr = `${error.name} ${error.message} ${cause}`;\n return RETRY_CONFIG.retryableErrors.some((e) => errorStr.includes(e));\n }\n return false;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Fetch with retry for cold-start and transient failure resilience.\n * Matches MCP server's fetchWithRetry pattern.\n */\nasync function fetchWithRetry(\n url: string,\n options: RequestInit,\n timeoutMs: number,\n apiKey: string,\n onKeyRefresh?: () => Promise<string | null>\n): Promise<Response> {\n let lastError: Error | null = null;\n let delay = RETRY_CONFIG.initialDelayMs;\n\n for (let attempt = 0; attempt <= RETRY_CONFIG.maxRetries; attempt++) {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeoutMs);\n\n try {\n const response = await fetch(url, {\n ...options,\n signal: controller.signal,\n });\n clearTimeout(timeoutId);\n\n // On 401, try key refresh and retry once\n if (response.status === 401 && onKeyRefresh && attempt === 0) {\n const newKey = await onKeyRefresh();\n if (newKey && newKey !== apiKey) {\n const retryController = new AbortController();\n const retryTimeout = setTimeout(() => retryController.abort(), timeoutMs);\n try {\n const headers = {\n ...(options.headers as Record<string, string>),\n Authorization: `Bearer ${newKey}`,\n };\n const retryResponse = await fetch(url, {\n ...options,\n headers,\n signal: retryController.signal,\n });\n clearTimeout(retryTimeout);\n return retryResponse;\n } catch {\n clearTimeout(retryTimeout);\n // Fall through to return original 401\n }\n }\n }\n\n return response;\n } catch (error) {\n clearTimeout(timeoutId);\n lastError = error instanceof Error ? error : new Error(String(error));\n\n // Don't retry on abort (timeout) or non-retryable errors\n if (lastError.name === 'AbortError' || !isRetryableError(error)) {\n throw lastError;\n }\n\n if (attempt < RETRY_CONFIG.maxRetries) {\n await sleep(delay);\n delay = Math.min(delay * RETRY_CONFIG.backoffMultiplier, RETRY_CONFIG.maxDelayMs);\n }\n }\n }\n\n throw lastError || new Error('Fetch failed after retries');\n}\n\n/**\n * Build the session context object for backend requests.\n */\nfunction buildSessionContext(extraContext?: Record<string, unknown>): Record<string, unknown> {\n return {\n ...extraContext,\n session_id: getSessionId(),\n agent_id: getAgentId(),\n source_application: 'shrike-guard-ts',\n };\n}\n\n/**\n * HTTP client for the Shrike scan API.\n */\n/**\n * Decide whether a scan verdict should be enforced as a block.\n *\n * Prefers the server-authoritative `action` field emitted by\n * /api/scan/enforce. Falls back to the legacy\n * `safe` boolean for verdicts that predate the enforce endpoint (older\n * backends, circuit-breaker fail-open synthetic verdicts, cached responses).\n *\n * Behavior:\n * - action = \"block\" → true\n * - action = \"require_approval\" → true (held actions are refused at the\n * tool-call boundary; caller can re-issue\n * after approval lands)\n * - action = \"allow\" → false\n * - action = \"warn\" → false (advisory; caller should surface\n * via block-feedback but not refuse)\n * - action absent → fall back to `!safe`\n *\n * This helper is the ONLY place the SDK converts a verdict into a\n * proceed-vs-refuse decision. Every LLM wrapper (OpenAI, Anthropic, Gemini)\n * routes through it so behavior stays uniform.\n *\n * Contract-symmetry pin: mirrors Python `_is_blocked` in shrike_guard.scanner.\n * If either SDK diverges, that is a bug in one of the two.\n */\nexport function isBlocked(verdict: ScanResult | Record<string, unknown>): boolean {\n const action = (verdict as Record<string, unknown>).action;\n if (typeof action === 'string' && action.length > 0) {\n // Known non-blocking tiers proceed.\n if (action === 'allow' || action === 'warn') return false;\n // Known blocking tiers refuse.\n if (action === 'block' || action === 'require_approval') return true;\n // Unknown/future tier (e.g. a new \"quarantine\" the backend adds): do NOT\n // fail open on an unrecognized name — fall through to `safe`. A new\n // blocking tier also sets safe:false, so this fails closed until the\n // client learns the tier explicitly. Forward-compat contract, see\n // tests/unit/contract-forward-compat.test.ts.\n }\n const safe = (verdict as Record<string, unknown>).safe;\n if (typeof safe === 'boolean') {\n return !safe;\n }\n return false;\n}\n\n/**\n * When running without an API key, appends a signup hint to scan results\n * so agents/users know they can upgrade from regex-only to full scanning.\n */\nexport function maybeAddSignupHint(result: ScanResult, apiKey: string): ScanResult {\n if (apiKey) return result;\n // Don't override if backend already provided upgrade_hint\n if ((result as any).upgrade_hint) return result;\n return {\n ...result,\n _note: 'Running without API key (L1-L5 only). Register free for cognitive threat detection: npx shrike-mcp --signup',\n };\n}\n\nexport class ScanClient {\n private apiKey: string;\n private readonly endpoint: string;\n private readonly timeout: number;\n private readonly rateLimiter: RateLimiter;\n private readonly onKeyRefresh?: () => Promise<string | null>;\n\n constructor(options: ScanClientOptions) {\n this.apiKey = options.apiKey;\n this.endpoint = (options.endpoint || DEFAULT_ENDPOINT).replace(/\\/$/, '');\n this.timeout = options.timeout || DEFAULT_SCAN_TIMEOUT;\n this.rateLimiter = new RateLimiter(options.rateLimitPerMinute || DEFAULT_RATE_LIMIT_PER_MINUTE);\n this.onKeyRefresh = options.onKeyRefresh;\n\n if (!this.apiKey) {\n console.warn('[shrike-guard] No API key provided — running in free tier (regex-only).');\n console.warn('[shrike-guard] For full scanning (LLM analysis, session correlation): npx shrike-mcp --signup');\n }\n }\n\n /** Check rate limit before each request. */\n private checkRateLimit(): void {\n const result = this.rateLimiter.consume();\n if (!result.allowed) {\n throw new ShrikeRateLimitError(result.retryAfterMs!);\n }\n }\n\n /**\n * Scan a prompt for security threats.\n *\n * @param prompt - The user prompt to scan.\n * @param context - Optional conversation context for better analysis.\n * @returns Scan result with 'safe' boolean and additional details.\n * @throws Error if the request fails or times out.\n */\n async scan(prompt: string, context?: string): Promise<ScanResult> {\n // Client-side size validation to fail fast\n const totalSize = prompt.length + (context?.length || 0);\n if (totalSize > MAX_CONTENT_SIZE) {\n return {\n safe: false,\n reason: `Content too large (${Math.round(totalSize / 1024)}KB > ${MAX_CONTENT_SIZE / 1024}KB limit)`,\n threat_type: 'size_limit_exceeded',\n confidence: 1.0,\n violations: [\n {\n type: 'size_limit',\n description: `Content exceeds maximum size of ${MAX_CONTENT_SIZE / 1024}KB`,\n },\n ],\n };\n }\n\n // Auto-chunk large prompts. Below the threshold we keep the single-shot\n // path unchanged; above it we split on natural boundaries, scan each\n // chunk sequentially, and stop on the first block verdict. The\n // conversation_history context is NOT chunked — it rides on every scan\n // so downstream layers see the same session shape.\n if (prompt.length > AUTO_CHUNK_THRESHOLD) {\n return this.scanChunked(prompt, context);\n }\n\n this.checkRateLimit();\n\n const payload: Record<string, unknown> = {\n prompt,\n scan_type: 'full',\n context: buildSessionContext(),\n };\n if (context) {\n payload.conversation_history = context;\n }\n\n const response = await fetchWithRetry(\n `${this.endpoint}/api/scan/enforce`,\n {\n method: 'POST',\n headers: getScanHeaders(this.apiKey),\n body: JSON.stringify(payload),\n },\n this.timeout,\n this.apiKey,\n this.onKeyRefresh\n );\n\n if (!response.ok) {\n throw new Error(`Scan API returned error: ${response.status}`);\n }\n\n return maybeAddSignupHint(sanitizeScanResponse((await response.json()) as ScanResult), this.apiKey);\n }\n\n /**\n * Chunk-and-scan path for prompts above AUTO_CHUNK_THRESHOLD. Splits on\n * natural boundaries, scans sequentially, aggregates. Stops on the first\n * block verdict (fail-fast) so a compromised chunk doesn't pay for the\n * remaining scans.\n *\n * Known limit: same session ID rides every chunk, so L9 turn count\n * inflates by chunk-count. Fix post-launch via backend chunk_group field.\n */\n private async scanChunked(prompt: string, context?: string): Promise<ScanResult> {\n const chunks = chunkContent(prompt);\n const results: ScanResult[] = [];\n for (const chunk of chunks) {\n const chunkResult = await this.scan(chunk, context);\n results.push(chunkResult);\n const action = chunkResult.action || chunkResult.refuse_tier;\n if (action === 'block') {\n break;\n }\n }\n return maybeAddSignupHint(aggregateChunkResults(results), this.apiKey);\n }\n\n /**\n * Scan a SQL query for injection attacks.\n *\n * @param query - The SQL query to scan.\n * @param database - Optional database name for context.\n * @param allowDestructive - If true, allows DROP/TRUNCATE operations.\n * @returns Scan result with 'safe' boolean and additional details.\n */\n async scanSql(\n query: string,\n database?: string,\n allowDestructive = false\n ): Promise<ScanResult> {\n if (query.length > MAX_CONTENT_SIZE) {\n return {\n safe: false,\n reason: `SQL query too large (${Math.round(query.length / 1024)}KB > ${MAX_CONTENT_SIZE / 1024}KB limit)`,\n threat_type: 'size_limit_exceeded',\n confidence: 1.0,\n violations: [\n {\n type: 'size_limit',\n description: `Query exceeds maximum size of ${MAX_CONTENT_SIZE / 1024}KB`,\n },\n ],\n };\n }\n\n this.checkRateLimit();\n\n const toolContext: Record<string, unknown> = {};\n if (database) {\n toolContext.database = database;\n }\n if (allowDestructive) {\n toolContext.allow_destructive = 'true';\n }\n\n const payload = {\n content: query,\n content_type: 'sql',\n context: buildSessionContext(toolContext),\n };\n\n const response = await fetchWithRetry(\n `${this.endpoint}/api/scan/enforce/specialized`,\n {\n method: 'POST',\n headers: getScanHeaders(this.apiKey),\n body: JSON.stringify(payload),\n },\n this.timeout,\n this.apiKey,\n this.onKeyRefresh\n );\n\n if (!response.ok) {\n throw new Error(`SQL scan API returned error: ${response.status}`);\n }\n\n return maybeAddSignupHint(sanitizeScanResponse((await response.json()) as ScanResult), this.apiKey);\n }\n\n /**\n * Scan a file path for security risks.\n *\n * @param path - The file path to validate.\n * @param content - Optional file content to scan for secrets/PII.\n * @returns Scan result with 'safe' boolean and additional details.\n */\n async scanFile(path: string, content?: string): Promise<ScanResult> {\n const totalSize = path.length + (content?.length || 0);\n if (totalSize > MAX_CONTENT_SIZE) {\n return {\n safe: false,\n reason: `File content too large (${Math.round(totalSize / 1024)}KB > ${MAX_CONTENT_SIZE / 1024}KB limit)`,\n threat_type: 'size_limit_exceeded',\n confidence: 1.0,\n violations: [\n {\n type: 'size_limit',\n description: `Content exceeds maximum size of ${MAX_CONTENT_SIZE / 1024}KB`,\n },\n ],\n };\n }\n\n this.checkRateLimit();\n\n const contentType = content ? 'file_content' : 'file_path';\n const extraContext: Record<string, unknown> = {};\n if (content) {\n extraContext.file_content = content;\n }\n\n const payload = {\n content: path,\n content_type: contentType,\n context: buildSessionContext(extraContext),\n };\n\n const response = await fetchWithRetry(\n `${this.endpoint}/api/scan/enforce/specialized`,\n {\n method: 'POST',\n headers: getScanHeaders(this.apiKey),\n body: JSON.stringify(payload),\n },\n this.timeout,\n this.apiKey,\n this.onKeyRefresh\n );\n\n if (!response.ok) {\n throw new Error(`File scan API returned error: ${response.status}`);\n }\n\n return maybeAddSignupHint(sanitizeScanResponse((await response.json()) as ScanResult), this.apiKey);\n }\n\n /**\n * Scan an A2A (Agent-to-Agent) protocol message for security threats.\n *\n * @param message - The A2A message text content to scan.\n * @param options - Optional context: sender/receiver agent IDs, task ID, role.\n * @returns Scan result with 'safe' boolean and additional details.\n */\n async scanA2AMessage(\n message: string,\n options?: {\n senderAgentId?: string;\n receiverAgentId?: string;\n taskId?: string;\n role?: 'user' | 'agent';\n }\n ): Promise<ScanResult> {\n if (message.length > MAX_CONTENT_SIZE) {\n return {\n safe: false,\n reason: `Message too large (${Math.round(message.length / 1024)}KB > ${MAX_CONTENT_SIZE / 1024}KB limit)`,\n threat_type: 'size_limit_exceeded',\n confidence: 1.0,\n violations: [\n {\n type: 'size_limit',\n description: `Content exceeds maximum size of ${MAX_CONTENT_SIZE / 1024}KB`,\n },\n ],\n };\n }\n\n this.checkRateLimit();\n\n const extraContext: Record<string, unknown> = {};\n if (options?.senderAgentId) extraContext.sender_agent_id = options.senderAgentId;\n if (options?.receiverAgentId) extraContext.receiver_agent_id = options.receiverAgentId;\n if (options?.taskId) extraContext.task_id = options.taskId;\n if (options?.role) extraContext.role = options.role;\n\n const payload = {\n content: message,\n content_type: 'a2a_message',\n context: buildSessionContext(extraContext),\n };\n\n const response = await fetchWithRetry(\n `${this.endpoint}/api/scan/enforce/specialized`,\n {\n method: 'POST',\n headers: getScanHeaders(this.apiKey),\n body: JSON.stringify(payload),\n },\n this.timeout,\n this.apiKey,\n this.onKeyRefresh\n );\n\n if (!response.ok) {\n throw new Error(`A2A message scan API returned error: ${response.status}`);\n }\n\n return maybeAddSignupHint(sanitizeScanResponse((await response.json()) as ScanResult), this.apiKey);\n }\n\n /**\n * Scan an A2A AgentCard JSON for security threats.\n *\n * @param agentCard - The raw JSON string of the A2A AgentCard to scan.\n * @param verifySignature - Reserved for future JWS signature verification.\n * @returns Scan result with 'safe' boolean and additional details.\n */\n async scanAgentCard(\n agentCard: string,\n verifySignature = false\n ): Promise<ScanResult> {\n if (agentCard.length > MAX_CONTENT_SIZE) {\n return {\n safe: false,\n reason: `Agent card too large (${Math.round(agentCard.length / 1024)}KB > ${MAX_CONTENT_SIZE / 1024}KB limit)`,\n threat_type: 'size_limit_exceeded',\n confidence: 1.0,\n violations: [\n {\n type: 'size_limit',\n description: `Content exceeds maximum size of ${MAX_CONTENT_SIZE / 1024}KB`,\n },\n ],\n };\n }\n\n this.checkRateLimit();\n\n const extraContext: Record<string, unknown> = {};\n if (verifySignature) extraContext.verify_signature = 'true';\n\n const payload = {\n content: agentCard,\n content_type: 'agent_card',\n context: buildSessionContext(extraContext),\n };\n\n const response = await fetchWithRetry(\n `${this.endpoint}/api/scan/enforce/specialized`,\n {\n method: 'POST',\n headers: getScanHeaders(this.apiKey),\n body: JSON.stringify(payload),\n },\n this.timeout,\n this.apiKey,\n this.onKeyRefresh\n );\n\n if (!response.ok) {\n throw new Error(`Agent card scan API returned error: ${response.status}`);\n }\n\n return maybeAddSignupHint(sanitizeScanResponse((await response.json()) as ScanResult), this.apiKey);\n }\n\n /**\n * Declare (or refresh) the operating scope for a task-scoped agent.\n *\n * Once declared, every subsequent scan for the same agent_id is enforced\n * against the scope on the backend. Tool calls outside allowed_tools —\n * or explicitly on forbidden_tools — route to refuse_tier:\n * \"require_approval\" with threat_type: \"scope_violation\". Expired scopes\n * emit threat_type: \"scope_expired\". Absent a declaration, no scope\n * check runs; every existing SDK integration is unaffected until it\n * opts in.\n *\n * Wire contract mirrors ScanClient.declare_scope on the Python SDK and\n * scan_declare_scope on the shrike-mcp package — do not diverge without\n * updating those siblings.\n *\n * @param options.agentId - Agent identity this scope applies to.\n * @param options.allowedTools - Exact tool names permitted; [\"*\"] = any.\n * @param options.forbiddenTools - Optional. Wins over allowedTools.\n * @param options.purpose - Optional audit + dashboard label.\n * @param options.maxDurationSeconds - Optional TTL from created_at.\n * @param options.expiresAt - Optional ISO-8601 absolute expiry.\n * @returns The persisted scope row, including scope_id + active_until.\n */\n async declareScope(options: {\n agentId: string;\n allowedTools: string[];\n forbiddenTools?: string[];\n purpose?: string;\n maxDurationSeconds?: number;\n expiresAt?: string;\n }): Promise<DeclareScopeResult> {\n this.checkRateLimit();\n\n const payload: Record<string, unknown> = {\n agent_id: options.agentId,\n allowed_tools: options.allowedTools,\n };\n if (options.purpose !== undefined) payload.purpose = options.purpose;\n if (options.forbiddenTools !== undefined) payload.forbidden_tools = options.forbiddenTools;\n if (options.maxDurationSeconds !== undefined) {\n payload.max_duration_seconds = options.maxDurationSeconds;\n }\n if (options.expiresAt !== undefined) payload.expires_at = options.expiresAt;\n\n const response = await fetchWithRetry(\n `${this.endpoint}/api/v1/agent/scope/declare`,\n {\n method: 'POST',\n headers: getScanHeaders(this.apiKey),\n body: JSON.stringify(payload),\n },\n this.timeout,\n this.apiKey,\n this.onKeyRefresh\n );\n\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new Error(\n `declareScope failed: ${response.status}${text ? ` — ${text.trim()}` : ''}`\n );\n }\n\n return (await response.json()) as DeclareScopeResult;\n }\n}\n","/**\n * Base API client for Shrike backend.\n */\n\nimport { DEFAULT_ENDPOINT } from '../config';\nimport { getScanHeaders } from '../scanner';\n\n/**\n * Base options for API clients.\n */\nexport interface BaseClientOptions {\n /** API key for authentication */\n apiKey?: string;\n /** Base URL for the API */\n baseUrl?: string;\n /** Request timeout in milliseconds */\n timeout?: number;\n}\n\n/**\n * Base API client with common HTTP functionality.\n */\nexport class BaseClient {\n protected readonly apiKey: string;\n protected readonly baseUrl: string;\n protected readonly timeout: number;\n\n constructor(options: BaseClientOptions = {}) {\n this.apiKey = options.apiKey || '';\n this.baseUrl = (options.baseUrl || DEFAULT_ENDPOINT).replace(/\\/$/, '');\n this.timeout = options.timeout || 30000;\n }\n\n /**\n * Make an HTTP request to the API.\n */\n protected async request<T>(\n method: string,\n path: string,\n body?: unknown\n ): Promise<T> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(`${this.baseUrl}${path}`, {\n method,\n headers: getScanHeaders(this.apiKey),\n body: body ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n });\n\n if (!response.ok) {\n const errorBody = await response.json().catch(() => ({ message: response.statusText })) as { message?: string };\n throw new Error(errorBody.message || `API error: ${response.status}`);\n }\n\n return response.json() as Promise<T>;\n } finally {\n clearTimeout(timeoutId);\n }\n }\n\n protected get<T>(path: string): Promise<T> {\n return this.request<T>('GET', path);\n }\n\n protected post<T>(path: string, body?: unknown): Promise<T> {\n return this.request<T>('POST', path, body);\n }\n\n protected put<T>(path: string, body?: unknown): Promise<T> {\n return this.request<T>('PUT', path, body);\n }\n\n protected delete<T>(path: string): Promise<T> {\n return this.request<T>('DELETE', path);\n }\n}\n","/**\n * Authentication API client for Shrike.\n */\n\nimport { BaseClient, BaseClientOptions } from './base';\n\n/**\n * Registration request payload.\n */\nexport interface RegisterRequest {\n email: string;\n password: string;\n company_name?: string;\n}\n\n/**\n * Login request payload.\n */\nexport interface LoginRequest {\n email: string;\n password: string;\n}\n\n/**\n * Authentication response with tokens.\n */\nexport interface AuthResponse {\n access_token: string;\n refresh_token: string;\n token_type: string;\n expires_in: number;\n}\n\n/**\n * User profile response.\n */\nexport interface UserProfile {\n customer_id: string;\n email: string;\n company_name?: string;\n created_at: string;\n}\n\n/**\n * Authentication client for Shrike API.\n */\nexport class AuthClient extends BaseClient {\n constructor(options: BaseClientOptions = {}) {\n super(options);\n }\n\n /**\n * Register a new customer account.\n */\n async register(request: RegisterRequest): Promise<AuthResponse> {\n return this.request<AuthResponse>('POST', '/api/v1/auth/register', request);\n }\n\n /**\n * Login with email and password.\n */\n async login(request: LoginRequest): Promise<AuthResponse> {\n return this.request<AuthResponse>('POST', '/api/v1/auth/login', request);\n }\n\n /**\n * Refresh the access token using a refresh token.\n */\n async refresh(refreshToken: string): Promise<AuthResponse> {\n return this.request<AuthResponse>('POST', '/api/v1/auth/refresh', {\n refresh_token: refreshToken,\n });\n }\n\n /**\n * Logout and invalidate the current session.\n */\n async logout(): Promise<void> {\n await this.request<void>('POST', '/api/v1/auth/logout');\n }\n\n /**\n * Get the current user's profile.\n */\n async me(): Promise<UserProfile> {\n return this.request<UserProfile>('GET', '/api/v1/auth/me');\n }\n}\n","/**\n * Agent API client for Shrike.\n */\n\nimport { BaseClient, BaseClientOptions } from './base';\n\n/**\n * Agent registration request.\n */\nexport interface RegisterAgentRequest {\n name: string;\n description?: string;\n policy_id?: string;\n}\n\n/**\n * Agent details.\n */\nexport interface Agent {\n agent_id: string;\n customer_id: string;\n name: string;\n description?: string;\n api_key: string;\n policy_id?: string;\n status: 'active' | 'inactive';\n created_at: string;\n last_heartbeat?: string;\n}\n\n/**\n * Heartbeat response.\n */\nexport interface HeartbeatResponse {\n status: string;\n server_time: string;\n}\n\n/**\n * Agent policy.\n */\nexport interface AgentPolicy {\n policy_id: string;\n name: string;\n rules: PolicyRule[];\n}\n\n/**\n * Policy rule.\n */\nexport interface PolicyRule {\n type: string;\n action: 'block' | 'warn' | 'allow';\n threshold?: number;\n [key: string]: unknown;\n}\n\n/**\n * Agent management client for Shrike API.\n */\nexport class AgentClient extends BaseClient {\n constructor(options: BaseClientOptions = {}) {\n super(options);\n }\n\n /**\n * Register a new agent.\n * Requires a customer API key.\n */\n async register(request: RegisterAgentRequest): Promise<Agent> {\n return this.request<Agent>('POST', '/api/v1/agents/register', request);\n }\n\n /**\n * Send a heartbeat from an agent.\n * Requires an agent API key.\n */\n async heartbeat(): Promise<HeartbeatResponse> {\n return this.request<HeartbeatResponse>('POST', '/api/v1/agents/heartbeat');\n }\n\n /**\n * Get the policies assigned to this agent.\n * Requires an agent API key.\n */\n async getPolicies(): Promise<AgentPolicy[]> {\n return this.request<AgentPolicy[]>('GET', '/api/v1/agents/policies');\n }\n\n /**\n * List all agents for the current customer.\n * Requires a customer API key.\n */\n async list(): Promise<Agent[]> {\n return this.request<Agent[]>('GET', '/api/v1/agents');\n }\n\n /**\n * Get an agent by ID.\n */\n async getAgent(agentId: string): Promise<Agent> {\n return this.request<Agent>('GET', `/api/v1/agents/${agentId}`);\n }\n\n /**\n * Delete an agent.\n */\n async deleteAgent(agentId: string): Promise<void> {\n await this.request<void>('DELETE', `/api/v1/agents/${agentId}`);\n }\n}\n","/**\n * Policy API client for Shrike.\n */\n\nimport { BaseClient, BaseClientOptions } from './base';\n\n/**\n * Policy rule definition.\n */\nexport interface PolicyRule {\n type: 'prompt_injection' | 'pii_detection' | 'jailbreak' | 'sql_injection' | 'custom';\n action: 'block' | 'warn' | 'allow';\n threshold?: number;\n patterns?: string[];\n [key: string]: unknown;\n}\n\n/**\n * Policy definition.\n */\nexport interface Policy {\n policy_id: string;\n customer_id: string;\n name: string;\n description?: string;\n rules: PolicyRule[];\n is_default: boolean;\n created_at: string;\n updated_at: string;\n}\n\n/**\n * Create policy request.\n */\nexport interface CreatePolicyRequest {\n name: string;\n description?: string;\n rules: PolicyRule[];\n is_default?: boolean;\n}\n\n/**\n * Update policy request.\n */\nexport interface UpdatePolicyRequest {\n name?: string;\n description?: string;\n rules?: PolicyRule[];\n is_default?: boolean;\n}\n\n/**\n * Policy management client for Shrike API.\n */\nexport class PolicyClient extends BaseClient {\n constructor(options: BaseClientOptions = {}) {\n super(options);\n }\n\n /**\n * List all policies for the current customer.\n */\n async list(): Promise<Policy[]> {\n return this.request<Policy[]>('GET', '/api/v1/policies');\n }\n\n /**\n * Get a policy by ID.\n */\n async getPolicy(policyId: string): Promise<Policy> {\n return this.request<Policy>('GET', `/api/v1/policies/${policyId}`);\n }\n\n /**\n * Create a new policy.\n */\n async create(request: CreatePolicyRequest): Promise<Policy> {\n return this.request<Policy>('POST', '/api/v1/policies', request);\n }\n\n /**\n * Update an existing policy.\n */\n async update(policyId: string, request: UpdatePolicyRequest): Promise<Policy> {\n return this.request<Policy>('PUT', `/api/v1/policies/${policyId}`, request);\n }\n\n /**\n * Delete a policy.\n */\n async deletePolicy(policyId: string): Promise<void> {\n await this.request<void>('DELETE', `/api/v1/policies/${policyId}`);\n }\n}\n","/**\n * Sandbox API client for Shrike.\n */\n\nimport { BaseClient, BaseClientOptions } from './base';\nimport { ScanResult } from '../scanner';\n\n/**\n * Sandbox scan request.\n */\nexport interface SandboxScanRequest {\n prompt: string;\n context?: string;\n model?: string;\n}\n\n/**\n * Sandbox client for testing prompts without affecting production metrics.\n */\nexport class SandboxClient extends BaseClient {\n constructor(options: BaseClientOptions = {}) {\n super(options);\n }\n\n /**\n * Scan a prompt in sandbox mode.\n * This does not count against production quotas.\n */\n async scan(request: SandboxScanRequest): Promise<ScanResult> {\n return this.request<ScanResult>('POST', '/api/v1/sandbox/scan', request);\n }\n}\n"]}
|
package/dist/api/index.mjs
CHANGED
|
@@ -6,8 +6,11 @@ var SDK_NAME = "typescript";
|
|
|
6
6
|
randomUUID();
|
|
7
7
|
process.env.SHRIKE_AGENT_ID || `sdk-ts-${randomUUID().slice(0, 8)}`;
|
|
8
8
|
|
|
9
|
+
// package.json
|
|
10
|
+
var version = "4.0.3";
|
|
11
|
+
|
|
9
12
|
// src/version.ts
|
|
10
|
-
var VERSION =
|
|
13
|
+
var VERSION = version;
|
|
11
14
|
function generateUUID() {
|
|
12
15
|
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
|
|
13
16
|
const r = Math.random() * 16 | 0;
|
package/dist/api/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/config.ts","../../src/version.ts","../../src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B,CAAA;AAAA,EACzD;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,UAAU,QAAA,EAAmC;AACjD,IAAA,OAAO,IAAA,CAAK,OAAA,CAAgB,KAAA,EAAO,CAAA,iBAAA,EAAoB,QAAQ,CAAA,CAAE,CAAA;AAAA,EACnE;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,OAAO,OAAA,EAA+C;AAC1D,IAAA,OAAO,IAAA,CAAK,OAAA,CAAgB,MAAA,EAAQ,kBAAA,EAAoB,OAAO,CAAA;AAAA,EACjE;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,MAAA,CAAO,QAAA,EAAkB,OAAA,EAA+C;AAC5E,IAAA,OAAO,KAAK,OAAA,CAAgB,KAAA,EAAO,CAAA,iBAAA,EAAoB,QAAQ,IAAI,OAAO,CAAA;AAAA,EAC5E;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,aAAa,QAAA,EAAiC;AAClD,IAAA,MAAM,IAAA,CAAK,OAAA,CAAc,QAAA,EAAU,CAAA,iBAAA,EAAoB,QAAQ,CAAA,CAAE,CAAA;AAAA,EACnE;AACF;;;AC1EO,IAAM,aAAA,GAAN,cAA4B,UAAA,CAAW;AAAA,EAC5C,WAAA,CAAY,OAAA,GAA6B,EAAC,EAAG;AAC3C,IAAA,KAAA,CAAM,OAAO,CAAA;AAAA,EACf;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,KAAK,OAAA,EAAkD;AAC3D,IAAA,OAAO,IAAA,CAAK,OAAA,CAAoB,MAAA,EAAQ,sBAAA,EAAwB,OAAO,CAAA;AAAA,EACzE;AACF","file":"index.mjs","sourcesContent":["/**\n * Configuration constants and types for the Shrike Guard SDK.\n */\n\nimport { randomUUID } from 'node:crypto';\n\n/**\n * Defines behavior when scan operations fail.\n */\nexport enum FailMode {\n /**\n * Allow the request to proceed (fail-open). Use this mode when\n * availability is prioritized over strict security.\n */\n OPEN = 'open',\n\n /**\n * Block the request and raise an exception (fail-closed). This is the\n * default behavior — matching the MCP server's security posture. Use\n * fail-open only when you've explicitly decided availability matters more.\n */\n CLOSED = 'closed',\n}\n\n/** Default timeout for scan requests in milliseconds */\nexport const DEFAULT_SCAN_TIMEOUT = 10000;\n\n/** Default fail mode - block requests when scan fails (fail-closed) */\nexport const DEFAULT_FAIL_MODE = FailMode.CLOSED;\n\n/** Default Shrike API endpoint (uses load balancer for scalability) */\nexport const DEFAULT_ENDPOINT = 'https://api.shrikesecurity.com/agent';\n\n/** Default rate limit (requests per minute) */\nexport const DEFAULT_RATE_LIMIT_PER_MINUTE = 100;\n\n// Note: All scanning is done via backend API (tier-based: community=L1-L4, pro=L1-L8)\n// No local patterns needed - backend handles all detection logic\n\n/** SDK identification */\nexport const SDK_NAME = 'typescript';\nexport const SDK_USER_AGENT = 'shrike-guard-typescript';\n\n/**\n * Session identity — persists for the lifetime of this SDK process.\n * Maps to L9's SessionCache key for multi-turn attack detection.\n */\nconst SESSION_ID = randomUUID();\nconst AGENT_ID = process.env.SHRIKE_AGENT_ID || `sdk-ts-${randomUUID().slice(0, 8)}`;\n\n/** Returns the stable session ID for this SDK process. */\nexport function getSessionId(): string {\n return SESSION_ID;\n}\n\n/** Returns the agent ID (from SHRIKE_AGENT_ID env or auto-generated). */\nexport function getAgentId(): string {\n return AGENT_ID;\n}\n\n/**\n * Approval information returned when a policy requires human sign-off.\n */\nexport interface ApprovalInfo {\n requires_approval: boolean;\n approval_id: string;\n approval_level: string;\n action_summary: string;\n policy_name: string;\n expires_in_seconds: number;\n threat_type?: string;\n severity?: string;\n owasp_category?: string;\n risk_factors?: string[];\n original_action?: string;\n}\n\n/**\n * Retry configuration for transient failure resilience.\n * Matches MCP server's RETRY_CONFIG for consistent behavior.\n */\nexport const RETRY_CONFIG = {\n maxRetries: 2,\n initialDelayMs: 200,\n maxDelayMs: 2000,\n backoffMultiplier: 2,\n retryableErrors: ['ECONNREFUSED', 'ECONNRESET', 'ETIMEDOUT', 'fetch failed'],\n};\n","/**\n * SDK version - keep in sync with package.json\n */\nexport const VERSION = '1.5.0';\n","/**\n * HTTP client for the Shrike scan API.\n * Includes retry with exponential backoff, session correlation,\n * approval workflow, 401 key refresh, and rate limiting.\n */\n\nimport {\n DEFAULT_ENDPOINT,\n DEFAULT_SCAN_TIMEOUT,\n DEFAULT_RATE_LIMIT_PER_MINUTE,\n SDK_NAME,\n RETRY_CONFIG,\n getSessionId,\n getAgentId,\n} from './config';\nimport type { ApprovalInfo } from './config';\nimport { AUTO_CHUNK_THRESHOLD, aggregateChunkResults, chunkContent } from './chunker';\nimport { ShrikeRateLimitError } from './errors';\nimport { RateLimiter } from './rateLimiter';\nimport { sanitizeScanResponse } from './sanitizer';\nimport { VERSION } from './version';\n\n/**\n * Phase 8b: Client-side size limits to fail fast before network round-trip.\n * These limits match the backend limits for consistency.\n */\nconst MAX_CONTENT_SIZE = 100 * 1024; // 100KB - matches backend MaxRequestBodySize\n\n/**\n * Result from a scan operation.\n */\n/**\n * Correlation pattern from L9 session-aware correlation engine.\n */\nexport interface CorrelationPattern {\n pattern_id: string;\n pattern_name: string;\n category: string;\n confidence: number;\n description: string;\n}\n\n/**\n * Governance action per Cooperative Governance 4-state contract (allow / warn / require_approval / block).\n * The `action` field is the server-authoritative signal for proceed-vs-refuse;\n * `isBlocked()` in this module consumes it directly.\n */\nexport type ScanAction = 'allow' | 'warn' | 'require_approval' | 'block';\n\n/**\n * Recovery guidance emitted by the backend on refuse verdicts.\n * `available_tools` names the MCP tools the caller can still invoke while\n * under quarantine (typically read-only surfaces like session_status).\n */\nexport interface ScanRecovery {\n instruction?: string;\n available_tools?: string[];\n patterns_triggered?: string[];\n [key: string]: unknown;\n}\n\n/**\n * Session-level state carried on every scan response (contract symmetry).\n * Fields are outcome state per the dashboard IP boundary — customer-visible.\n */\nexport interface ScanSessionState {\n session_risk_score?: number;\n session_turn_number?: number;\n session_patterns?: string[];\n session_locked?: boolean;\n [key: string]: unknown;\n}\n\n/**\n * A single policy violation as emitted by the /api/scan/enforce endpoint.\n * The sanitizer strips policy_id / policy_name / matched_pattern / other\n * attribution before this reaches callers; what remains here is the\n * customer-visible outcome surface.\n */\nexport interface ScanViolation {\n threat_type?: string;\n owasp_category?: string;\n severity?: string;\n action?: string;\n user_message?: string;\n suggested_action?: string;\n [key: string]: unknown;\n}\n\nexport interface ScanResult {\n safe: boolean;\n reason?: string;\n threat_type?: string;\n severity?: string;\n confidence?: number | string;\n violations?: ScanViolation[];\n guidance?: string;\n approval_info?: ApprovalInfo;\n /** Cooperative Governance action — server-authoritative proceed/refuse signal */\n action?: ScanAction;\n /** Refuse tier: allow / warn / require_approval / block */\n refuse_tier?: ScanAction;\n /** Recovery guidance, present on refuse verdicts */\n recovery?: ScanRecovery;\n /** L9 session correlation state — outcome, customer-visible */\n session_state?: ScanSessionState;\n /** Specialized scan input type, e.g. 'sql' / 'file_path' / 'a2a_message' */\n content_type?: string;\n /** Client-side session rotation guidance */\n client_session_rotation?: unknown;\n /** L9 session risk score (0.0-1.0), present when session correlation is active */\n session_risk_score?: number;\n /** L9 matched correlation patterns, present when multi-turn patterns are detected */\n correlation_patterns?: CorrelationPattern[];\n /**\n * True when this is a fail-open verdict returned without a completed scan —\n * i.e. `failMode: 'open'` was set and the backend was unreachable, so\n * enforcement was skipped. Lets a caller distinguish \"scanned and clean\"\n * from \"not scanned, allowed anyway.\"\n */\n degraded?: boolean;\n [key: string]: unknown;\n}\n\n/**\n * Build a fail-open ALLOW verdict. Returned only when `failMode === 'open'` is\n * explicitly set and the scan could not complete (timeout, backend error).\n * Marked `degraded: true` — centralize all fail-open returns through this so the\n * marker can never be forgotten on a new wrapper.\n */\nexport function failOpenResult(reason: string): ScanResult {\n return { safe: true, reason, degraded: true };\n}\n\n/**\n * Result of ScanClient.declareScope — the persisted scope row plus derived\n * active_until + expired fields. Mirrors the shape returned by\n * POST /api/v1/agent/scope/declare on the backend.\n */\nexport interface DeclareScopeResult {\n scope_id?: string;\n agent_id?: string;\n purpose?: string;\n allowed_tools?: string[];\n forbidden_tools?: string[];\n max_duration_seconds?: number;\n expires_at?: string;\n active_until?: string;\n expired?: boolean;\n created_at?: string;\n updated_at?: string;\n}\n\n/**\n * Options for the ScanClient.\n */\nexport interface ScanClientOptions {\n /** Shrike API key for authentication */\n apiKey: string;\n /** Shrike API endpoint URL */\n endpoint?: string;\n /** Request timeout in milliseconds */\n timeout?: number;\n /** Rate limit in requests per minute (default: 100) */\n rateLimitPerMinute?: number;\n /** Optional callback to refresh API key on 401. Return new key or null. */\n onKeyRefresh?: () => Promise<string | null>;\n}\n\n/**\n * Generate a UUID v4 string.\n */\nfunction generateUUID(): string {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n/**\n * Generate headers for scan API requests.\n */\nexport function getScanHeaders(\n shrikeApiKey: string,\n requestId?: string\n): Record<string, string> {\n return {\n Authorization: `Bearer ${shrikeApiKey}`,\n 'Content-Type': 'application/json',\n 'X-Shrike-SDK': SDK_NAME,\n 'X-Shrike-SDK-Version': VERSION,\n 'X-Shrike-Request-ID': requestId || generateUUID(),\n };\n}\n\n/** Check if an error is transient and retryable. */\nfunction isRetryableError(error: unknown): boolean {\n if (error instanceof Error) {\n const cause = 'cause' in error ? String((error as { cause?: unknown }).cause) : '';\n const errorStr = `${error.name} ${error.message} ${cause}`;\n return RETRY_CONFIG.retryableErrors.some((e) => errorStr.includes(e));\n }\n return false;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Fetch with retry for cold-start and transient failure resilience.\n * Matches MCP server's fetchWithRetry pattern.\n */\nasync function fetchWithRetry(\n url: string,\n options: RequestInit,\n timeoutMs: number,\n apiKey: string,\n onKeyRefresh?: () => Promise<string | null>\n): Promise<Response> {\n let lastError: Error | null = null;\n let delay = RETRY_CONFIG.initialDelayMs;\n\n for (let attempt = 0; attempt <= RETRY_CONFIG.maxRetries; attempt++) {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeoutMs);\n\n try {\n const response = await fetch(url, {\n ...options,\n signal: controller.signal,\n });\n clearTimeout(timeoutId);\n\n // On 401, try key refresh and retry once\n if (response.status === 401 && onKeyRefresh && attempt === 0) {\n const newKey = await onKeyRefresh();\n if (newKey && newKey !== apiKey) {\n const retryController = new AbortController();\n const retryTimeout = setTimeout(() => retryController.abort(), timeoutMs);\n try {\n const headers = {\n ...(options.headers as Record<string, string>),\n Authorization: `Bearer ${newKey}`,\n };\n const retryResponse = await fetch(url, {\n ...options,\n headers,\n signal: retryController.signal,\n });\n clearTimeout(retryTimeout);\n return retryResponse;\n } catch {\n clearTimeout(retryTimeout);\n // Fall through to return original 401\n }\n }\n }\n\n return response;\n } catch (error) {\n clearTimeout(timeoutId);\n lastError = error instanceof Error ? error : new Error(String(error));\n\n // Don't retry on abort (timeout) or non-retryable errors\n if (lastError.name === 'AbortError' || !isRetryableError(error)) {\n throw lastError;\n }\n\n if (attempt < RETRY_CONFIG.maxRetries) {\n await sleep(delay);\n delay = Math.min(delay * RETRY_CONFIG.backoffMultiplier, RETRY_CONFIG.maxDelayMs);\n }\n }\n }\n\n throw lastError || new Error('Fetch failed after retries');\n}\n\n/**\n * Build the session context object for backend requests.\n */\nfunction buildSessionContext(extraContext?: Record<string, unknown>): Record<string, unknown> {\n return {\n ...extraContext,\n session_id: getSessionId(),\n agent_id: getAgentId(),\n source_application: 'shrike-guard-ts',\n };\n}\n\n/**\n * HTTP client for the Shrike scan API.\n */\n/**\n * Decide whether a scan verdict should be enforced as a block.\n *\n * Prefers the server-authoritative `action` field emitted by\n * /api/scan/enforce. Falls back to the legacy\n * `safe` boolean for verdicts that predate the enforce endpoint (older\n * backends, circuit-breaker fail-open synthetic verdicts, cached responses).\n *\n * Behavior:\n * - action = \"block\" → true\n * - action = \"require_approval\" → true (held actions are refused at the\n * tool-call boundary; caller can re-issue\n * after approval lands)\n * - action = \"allow\" → false\n * - action = \"warn\" → false (advisory; caller should surface\n * via block-feedback but not refuse)\n * - action absent → fall back to `!safe`\n *\n * This helper is the ONLY place the SDK converts a verdict into a\n * proceed-vs-refuse decision. Every LLM wrapper (OpenAI, Anthropic, Gemini)\n * routes through it so behavior stays uniform.\n *\n * Contract-symmetry pin: mirrors Python `_is_blocked` in shrike_guard.scanner.\n * If either SDK diverges, that is a bug in one of the two.\n */\nexport function isBlocked(verdict: ScanResult | Record<string, unknown>): boolean {\n const action = (verdict as Record<string, unknown>).action;\n if (typeof action === 'string' && action.length > 0) {\n // Known non-blocking tiers proceed.\n if (action === 'allow' || action === 'warn') return false;\n // Known blocking tiers refuse.\n if (action === 'block' || action === 'require_approval') return true;\n // Unknown/future tier (e.g. a new \"quarantine\" the backend adds): do NOT\n // fail open on an unrecognized name — fall through to `safe`. A new\n // blocking tier also sets safe:false, so this fails closed until the\n // client learns the tier explicitly. Forward-compat contract, see\n // tests/unit/contract-forward-compat.test.ts.\n }\n const safe = (verdict as Record<string, unknown>).safe;\n if (typeof safe === 'boolean') {\n return !safe;\n }\n return false;\n}\n\n/**\n * When running without an API key, appends a signup hint to scan results\n * so agents/users know they can upgrade from regex-only to full scanning.\n */\nexport function maybeAddSignupHint(result: ScanResult, apiKey: string): ScanResult {\n if (apiKey) return result;\n // Don't override if backend already provided upgrade_hint\n if ((result as any).upgrade_hint) return result;\n return {\n ...result,\n _note: 'Running without API key (L1-L5 only). Register free for cognitive threat detection: npx shrike-mcp --signup',\n };\n}\n\nexport class ScanClient {\n private apiKey: string;\n private readonly endpoint: string;\n private readonly timeout: number;\n private readonly rateLimiter: RateLimiter;\n private readonly onKeyRefresh?: () => Promise<string | null>;\n\n constructor(options: ScanClientOptions) {\n this.apiKey = options.apiKey;\n this.endpoint = (options.endpoint || DEFAULT_ENDPOINT).replace(/\\/$/, '');\n this.timeout = options.timeout || DEFAULT_SCAN_TIMEOUT;\n this.rateLimiter = new RateLimiter(options.rateLimitPerMinute || DEFAULT_RATE_LIMIT_PER_MINUTE);\n this.onKeyRefresh = options.onKeyRefresh;\n\n if (!this.apiKey) {\n console.warn('[shrike-guard] No API key provided — running in free tier (regex-only).');\n console.warn('[shrike-guard] For full scanning (LLM analysis, session correlation): npx shrike-mcp --signup');\n }\n }\n\n /** Check rate limit before each request. */\n private checkRateLimit(): void {\n const result = this.rateLimiter.consume();\n if (!result.allowed) {\n throw new ShrikeRateLimitError(result.retryAfterMs!);\n }\n }\n\n /**\n * Scan a prompt for security threats.\n *\n * @param prompt - The user prompt to scan.\n * @param context - Optional conversation context for better analysis.\n * @returns Scan result with 'safe' boolean and additional details.\n * @throws Error if the request fails or times out.\n */\n async scan(prompt: string, context?: string): Promise<ScanResult> {\n // Client-side size validation to fail fast\n const totalSize = prompt.length + (context?.length || 0);\n if (totalSize > MAX_CONTENT_SIZE) {\n return {\n safe: false,\n reason: `Content too large (${Math.round(totalSize / 1024)}KB > ${MAX_CONTENT_SIZE / 1024}KB limit)`,\n threat_type: 'size_limit_exceeded',\n confidence: 1.0,\n violations: [\n {\n type: 'size_limit',\n description: `Content exceeds maximum size of ${MAX_CONTENT_SIZE / 1024}KB`,\n },\n ],\n };\n }\n\n // Auto-chunk large prompts. Below the threshold we keep the single-shot\n // path unchanged; above it we split on natural boundaries, scan each\n // chunk sequentially, and stop on the first block verdict. The\n // conversation_history context is NOT chunked — it rides on every scan\n // so downstream layers see the same session shape.\n if (prompt.length > AUTO_CHUNK_THRESHOLD) {\n return this.scanChunked(prompt, context);\n }\n\n this.checkRateLimit();\n\n const payload: Record<string, unknown> = {\n prompt,\n scan_type: 'full',\n context: buildSessionContext(),\n };\n if (context) {\n payload.conversation_history = context;\n }\n\n const response = await fetchWithRetry(\n `${this.endpoint}/api/scan/enforce`,\n {\n method: 'POST',\n headers: getScanHeaders(this.apiKey),\n body: JSON.stringify(payload),\n },\n this.timeout,\n this.apiKey,\n this.onKeyRefresh\n );\n\n if (!response.ok) {\n throw new Error(`Scan API returned error: ${response.status}`);\n }\n\n return maybeAddSignupHint(sanitizeScanResponse((await response.json()) as ScanResult), this.apiKey);\n }\n\n /**\n * Chunk-and-scan path for prompts above AUTO_CHUNK_THRESHOLD. Splits on\n * natural boundaries, scans sequentially, aggregates. Stops on the first\n * block verdict (fail-fast) so a compromised chunk doesn't pay for the\n * remaining scans.\n *\n * Known limit: same session ID rides every chunk, so L9 turn count\n * inflates by chunk-count. Fix post-launch via backend chunk_group field.\n */\n private async scanChunked(prompt: string, context?: string): Promise<ScanResult> {\n const chunks = chunkContent(prompt);\n const results: ScanResult[] = [];\n for (const chunk of chunks) {\n const chunkResult = await this.scan(chunk, context);\n results.push(chunkResult);\n const action = chunkResult.action || chunkResult.refuse_tier;\n if (action === 'block') {\n break;\n }\n }\n return maybeAddSignupHint(aggregateChunkResults(results), this.apiKey);\n }\n\n /**\n * Scan a SQL query for injection attacks.\n *\n * @param query - The SQL query to scan.\n * @param database - Optional database name for context.\n * @param allowDestructive - If true, allows DROP/TRUNCATE operations.\n * @returns Scan result with 'safe' boolean and additional details.\n */\n async scanSql(\n query: string,\n database?: string,\n allowDestructive = false\n ): Promise<ScanResult> {\n if (query.length > MAX_CONTENT_SIZE) {\n return {\n safe: false,\n reason: `SQL query too large (${Math.round(query.length / 1024)}KB > ${MAX_CONTENT_SIZE / 1024}KB limit)`,\n threat_type: 'size_limit_exceeded',\n confidence: 1.0,\n violations: [\n {\n type: 'size_limit',\n description: `Query exceeds maximum size of ${MAX_CONTENT_SIZE / 1024}KB`,\n },\n ],\n };\n }\n\n this.checkRateLimit();\n\n const toolContext: Record<string, unknown> = {};\n if (database) {\n toolContext.database = database;\n }\n if (allowDestructive) {\n toolContext.allow_destructive = 'true';\n }\n\n const payload = {\n content: query,\n content_type: 'sql',\n context: buildSessionContext(toolContext),\n };\n\n const response = await fetchWithRetry(\n `${this.endpoint}/api/scan/enforce/specialized`,\n {\n method: 'POST',\n headers: getScanHeaders(this.apiKey),\n body: JSON.stringify(payload),\n },\n this.timeout,\n this.apiKey,\n this.onKeyRefresh\n );\n\n if (!response.ok) {\n throw new Error(`SQL scan API returned error: ${response.status}`);\n }\n\n return maybeAddSignupHint(sanitizeScanResponse((await response.json()) as ScanResult), this.apiKey);\n }\n\n /**\n * Scan a file path for security risks.\n *\n * @param path - The file path to validate.\n * @param content - Optional file content to scan for secrets/PII.\n * @returns Scan result with 'safe' boolean and additional details.\n */\n async scanFile(path: string, content?: string): Promise<ScanResult> {\n const totalSize = path.length + (content?.length || 0);\n if (totalSize > MAX_CONTENT_SIZE) {\n return {\n safe: false,\n reason: `File content too large (${Math.round(totalSize / 1024)}KB > ${MAX_CONTENT_SIZE / 1024}KB limit)`,\n threat_type: 'size_limit_exceeded',\n confidence: 1.0,\n violations: [\n {\n type: 'size_limit',\n description: `Content exceeds maximum size of ${MAX_CONTENT_SIZE / 1024}KB`,\n },\n ],\n };\n }\n\n this.checkRateLimit();\n\n const contentType = content ? 'file_content' : 'file_path';\n const extraContext: Record<string, unknown> = {};\n if (content) {\n extraContext.file_content = content;\n }\n\n const payload = {\n content: path,\n content_type: contentType,\n context: buildSessionContext(extraContext),\n };\n\n const response = await fetchWithRetry(\n `${this.endpoint}/api/scan/enforce/specialized`,\n {\n method: 'POST',\n headers: getScanHeaders(this.apiKey),\n body: JSON.stringify(payload),\n },\n this.timeout,\n this.apiKey,\n this.onKeyRefresh\n );\n\n if (!response.ok) {\n throw new Error(`File scan API returned error: ${response.status}`);\n }\n\n return maybeAddSignupHint(sanitizeScanResponse((await response.json()) as ScanResult), this.apiKey);\n }\n\n /**\n * Scan an A2A (Agent-to-Agent) protocol message for security threats.\n *\n * @param message - The A2A message text content to scan.\n * @param options - Optional context: sender/receiver agent IDs, task ID, role.\n * @returns Scan result with 'safe' boolean and additional details.\n */\n async scanA2AMessage(\n message: string,\n options?: {\n senderAgentId?: string;\n receiverAgentId?: string;\n taskId?: string;\n role?: 'user' | 'agent';\n }\n ): Promise<ScanResult> {\n if (message.length > MAX_CONTENT_SIZE) {\n return {\n safe: false,\n reason: `Message too large (${Math.round(message.length / 1024)}KB > ${MAX_CONTENT_SIZE / 1024}KB limit)`,\n threat_type: 'size_limit_exceeded',\n confidence: 1.0,\n violations: [\n {\n type: 'size_limit',\n description: `Content exceeds maximum size of ${MAX_CONTENT_SIZE / 1024}KB`,\n },\n ],\n };\n }\n\n this.checkRateLimit();\n\n const extraContext: Record<string, unknown> = {};\n if (options?.senderAgentId) extraContext.sender_agent_id = options.senderAgentId;\n if (options?.receiverAgentId) extraContext.receiver_agent_id = options.receiverAgentId;\n if (options?.taskId) extraContext.task_id = options.taskId;\n if (options?.role) extraContext.role = options.role;\n\n const payload = {\n content: message,\n content_type: 'a2a_message',\n context: buildSessionContext(extraContext),\n };\n\n const response = await fetchWithRetry(\n `${this.endpoint}/api/scan/enforce/specialized`,\n {\n method: 'POST',\n headers: getScanHeaders(this.apiKey),\n body: JSON.stringify(payload),\n },\n this.timeout,\n this.apiKey,\n this.onKeyRefresh\n );\n\n if (!response.ok) {\n throw new Error(`A2A message scan API returned error: ${response.status}`);\n }\n\n return maybeAddSignupHint(sanitizeScanResponse((await response.json()) as ScanResult), this.apiKey);\n }\n\n /**\n * Scan an A2A AgentCard JSON for security threats.\n *\n * @param agentCard - The raw JSON string of the A2A AgentCard to scan.\n * @param verifySignature - Reserved for future JWS signature verification.\n * @returns Scan result with 'safe' boolean and additional details.\n */\n async scanAgentCard(\n agentCard: string,\n verifySignature = false\n ): Promise<ScanResult> {\n if (agentCard.length > MAX_CONTENT_SIZE) {\n return {\n safe: false,\n reason: `Agent card too large (${Math.round(agentCard.length / 1024)}KB > ${MAX_CONTENT_SIZE / 1024}KB limit)`,\n threat_type: 'size_limit_exceeded',\n confidence: 1.0,\n violations: [\n {\n type: 'size_limit',\n description: `Content exceeds maximum size of ${MAX_CONTENT_SIZE / 1024}KB`,\n },\n ],\n };\n }\n\n this.checkRateLimit();\n\n const extraContext: Record<string, unknown> = {};\n if (verifySignature) extraContext.verify_signature = 'true';\n\n const payload = {\n content: agentCard,\n content_type: 'agent_card',\n context: buildSessionContext(extraContext),\n };\n\n const response = await fetchWithRetry(\n `${this.endpoint}/api/scan/enforce/specialized`,\n {\n method: 'POST',\n headers: getScanHeaders(this.apiKey),\n body: JSON.stringify(payload),\n },\n this.timeout,\n this.apiKey,\n this.onKeyRefresh\n );\n\n if (!response.ok) {\n throw new Error(`Agent card scan API returned error: ${response.status}`);\n }\n\n return maybeAddSignupHint(sanitizeScanResponse((await response.json()) as ScanResult), this.apiKey);\n }\n\n /**\n * Declare (or refresh) the operating scope for a task-scoped agent.\n *\n * Once declared, every subsequent scan for the same agent_id is enforced\n * against the scope on the backend. Tool calls outside allowed_tools —\n * or explicitly on forbidden_tools — route to refuse_tier:\n * \"require_approval\" with threat_type: \"scope_violation\". Expired scopes\n * emit threat_type: \"scope_expired\". Absent a declaration, no scope\n * check runs; every existing SDK integration is unaffected until it\n * opts in.\n *\n * Wire contract mirrors ScanClient.declare_scope on the Python SDK and\n * scan_declare_scope on the shrike-mcp package — do not diverge without\n * updating those siblings.\n *\n * @param options.agentId - Agent identity this scope applies to.\n * @param options.allowedTools - Exact tool names permitted; [\"*\"] = any.\n * @param options.forbiddenTools - Optional. Wins over allowedTools.\n * @param options.purpose - Optional audit + dashboard label.\n * @param options.maxDurationSeconds - Optional TTL from created_at.\n * @param options.expiresAt - Optional ISO-8601 absolute expiry.\n * @returns The persisted scope row, including scope_id + active_until.\n */\n async declareScope(options: {\n agentId: string;\n allowedTools: string[];\n forbiddenTools?: string[];\n purpose?: string;\n maxDurationSeconds?: number;\n expiresAt?: string;\n }): Promise<DeclareScopeResult> {\n this.checkRateLimit();\n\n const payload: Record<string, unknown> = {\n agent_id: options.agentId,\n allowed_tools: options.allowedTools,\n };\n if (options.purpose !== undefined) payload.purpose = options.purpose;\n if (options.forbiddenTools !== undefined) payload.forbidden_tools = options.forbiddenTools;\n if (options.maxDurationSeconds !== undefined) {\n payload.max_duration_seconds = options.maxDurationSeconds;\n }\n if (options.expiresAt !== undefined) payload.expires_at = options.expiresAt;\n\n const response = await fetchWithRetry(\n `${this.endpoint}/api/v1/agent/scope/declare`,\n {\n method: 'POST',\n headers: getScanHeaders(this.apiKey),\n body: JSON.stringify(payload),\n },\n this.timeout,\n this.apiKey,\n this.onKeyRefresh\n );\n\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new Error(\n `declareScope failed: ${response.status}${text ? ` — ${text.trim()}` : ''}`\n );\n }\n\n return (await response.json()) as DeclareScopeResult;\n }\n}\n","/**\n * Base API client for Shrike backend.\n */\n\nimport { DEFAULT_ENDPOINT } from '../config';\nimport { getScanHeaders } from '../scanner';\n\n/**\n * Base options for API clients.\n */\nexport interface BaseClientOptions {\n /** API key for authentication */\n apiKey?: string;\n /** Base URL for the API */\n baseUrl?: string;\n /** Request timeout in milliseconds */\n timeout?: number;\n}\n\n/**\n * Base API client with common HTTP functionality.\n */\nexport class BaseClient {\n protected readonly apiKey: string;\n protected readonly baseUrl: string;\n protected readonly timeout: number;\n\n constructor(options: BaseClientOptions = {}) {\n this.apiKey = options.apiKey || '';\n this.baseUrl = (options.baseUrl || DEFAULT_ENDPOINT).replace(/\\/$/, '');\n this.timeout = options.timeout || 30000;\n }\n\n /**\n * Make an HTTP request to the API.\n */\n protected async request<T>(\n method: string,\n path: string,\n body?: unknown\n ): Promise<T> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(`${this.baseUrl}${path}`, {\n method,\n headers: getScanHeaders(this.apiKey),\n body: body ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n });\n\n if (!response.ok) {\n const errorBody = await response.json().catch(() => ({ message: response.statusText })) as { message?: string };\n throw new Error(errorBody.message || `API error: ${response.status}`);\n }\n\n return response.json() as Promise<T>;\n } finally {\n clearTimeout(timeoutId);\n }\n }\n\n protected get<T>(path: string): Promise<T> {\n return this.request<T>('GET', path);\n }\n\n protected post<T>(path: string, body?: unknown): Promise<T> {\n return this.request<T>('POST', path, body);\n }\n\n protected put<T>(path: string, body?: unknown): Promise<T> {\n return this.request<T>('PUT', path, body);\n }\n\n protected delete<T>(path: string): Promise<T> {\n return this.request<T>('DELETE', path);\n }\n}\n","/**\n * Authentication API client for Shrike.\n */\n\nimport { BaseClient, BaseClientOptions } from './base';\n\n/**\n * Registration request payload.\n */\nexport interface RegisterRequest {\n email: string;\n password: string;\n company_name?: string;\n}\n\n/**\n * Login request payload.\n */\nexport interface LoginRequest {\n email: string;\n password: string;\n}\n\n/**\n * Authentication response with tokens.\n */\nexport interface AuthResponse {\n access_token: string;\n refresh_token: string;\n token_type: string;\n expires_in: number;\n}\n\n/**\n * User profile response.\n */\nexport interface UserProfile {\n customer_id: string;\n email: string;\n company_name?: string;\n created_at: string;\n}\n\n/**\n * Authentication client for Shrike API.\n */\nexport class AuthClient extends BaseClient {\n constructor(options: BaseClientOptions = {}) {\n super(options);\n }\n\n /**\n * Register a new customer account.\n */\n async register(request: RegisterRequest): Promise<AuthResponse> {\n return this.request<AuthResponse>('POST', '/api/v1/auth/register', request);\n }\n\n /**\n * Login with email and password.\n */\n async login(request: LoginRequest): Promise<AuthResponse> {\n return this.request<AuthResponse>('POST', '/api/v1/auth/login', request);\n }\n\n /**\n * Refresh the access token using a refresh token.\n */\n async refresh(refreshToken: string): Promise<AuthResponse> {\n return this.request<AuthResponse>('POST', '/api/v1/auth/refresh', {\n refresh_token: refreshToken,\n });\n }\n\n /**\n * Logout and invalidate the current session.\n */\n async logout(): Promise<void> {\n await this.request<void>('POST', '/api/v1/auth/logout');\n }\n\n /**\n * Get the current user's profile.\n */\n async me(): Promise<UserProfile> {\n return this.request<UserProfile>('GET', '/api/v1/auth/me');\n }\n}\n","/**\n * Agent API client for Shrike.\n */\n\nimport { BaseClient, BaseClientOptions } from './base';\n\n/**\n * Agent registration request.\n */\nexport interface RegisterAgentRequest {\n name: string;\n description?: string;\n policy_id?: string;\n}\n\n/**\n * Agent details.\n */\nexport interface Agent {\n agent_id: string;\n customer_id: string;\n name: string;\n description?: string;\n api_key: string;\n policy_id?: string;\n status: 'active' | 'inactive';\n created_at: string;\n last_heartbeat?: string;\n}\n\n/**\n * Heartbeat response.\n */\nexport interface HeartbeatResponse {\n status: string;\n server_time: string;\n}\n\n/**\n * Agent policy.\n */\nexport interface AgentPolicy {\n policy_id: string;\n name: string;\n rules: PolicyRule[];\n}\n\n/**\n * Policy rule.\n */\nexport interface PolicyRule {\n type: string;\n action: 'block' | 'warn' | 'allow';\n threshold?: number;\n [key: string]: unknown;\n}\n\n/**\n * Agent management client for Shrike API.\n */\nexport class AgentClient extends BaseClient {\n constructor(options: BaseClientOptions = {}) {\n super(options);\n }\n\n /**\n * Register a new agent.\n * Requires a customer API key.\n */\n async register(request: RegisterAgentRequest): Promise<Agent> {\n return this.request<Agent>('POST', '/api/v1/agents/register', request);\n }\n\n /**\n * Send a heartbeat from an agent.\n * Requires an agent API key.\n */\n async heartbeat(): Promise<HeartbeatResponse> {\n return this.request<HeartbeatResponse>('POST', '/api/v1/agents/heartbeat');\n }\n\n /**\n * Get the policies assigned to this agent.\n * Requires an agent API key.\n */\n async getPolicies(): Promise<AgentPolicy[]> {\n return this.request<AgentPolicy[]>('GET', '/api/v1/agents/policies');\n }\n\n /**\n * List all agents for the current customer.\n * Requires a customer API key.\n */\n async list(): Promise<Agent[]> {\n return this.request<Agent[]>('GET', '/api/v1/agents');\n }\n\n /**\n * Get an agent by ID.\n */\n async getAgent(agentId: string): Promise<Agent> {\n return this.request<Agent>('GET', `/api/v1/agents/${agentId}`);\n }\n\n /**\n * Delete an agent.\n */\n async deleteAgent(agentId: string): Promise<void> {\n await this.request<void>('DELETE', `/api/v1/agents/${agentId}`);\n }\n}\n","/**\n * Policy API client for Shrike.\n */\n\nimport { BaseClient, BaseClientOptions } from './base';\n\n/**\n * Policy rule definition.\n */\nexport interface PolicyRule {\n type: 'prompt_injection' | 'pii_detection' | 'jailbreak' | 'sql_injection' | 'custom';\n action: 'block' | 'warn' | 'allow';\n threshold?: number;\n patterns?: string[];\n [key: string]: unknown;\n}\n\n/**\n * Policy definition.\n */\nexport interface Policy {\n policy_id: string;\n customer_id: string;\n name: string;\n description?: string;\n rules: PolicyRule[];\n is_default: boolean;\n created_at: string;\n updated_at: string;\n}\n\n/**\n * Create policy request.\n */\nexport interface CreatePolicyRequest {\n name: string;\n description?: string;\n rules: PolicyRule[];\n is_default?: boolean;\n}\n\n/**\n * Update policy request.\n */\nexport interface UpdatePolicyRequest {\n name?: string;\n description?: string;\n rules?: PolicyRule[];\n is_default?: boolean;\n}\n\n/**\n * Policy management client for Shrike API.\n */\nexport class PolicyClient extends BaseClient {\n constructor(options: BaseClientOptions = {}) {\n super(options);\n }\n\n /**\n * List all policies for the current customer.\n */\n async list(): Promise<Policy[]> {\n return this.request<Policy[]>('GET', '/api/v1/policies');\n }\n\n /**\n * Get a policy by ID.\n */\n async getPolicy(policyId: string): Promise<Policy> {\n return this.request<Policy>('GET', `/api/v1/policies/${policyId}`);\n }\n\n /**\n * Create a new policy.\n */\n async create(request: CreatePolicyRequest): Promise<Policy> {\n return this.request<Policy>('POST', '/api/v1/policies', request);\n }\n\n /**\n * Update an existing policy.\n */\n async update(policyId: string, request: UpdatePolicyRequest): Promise<Policy> {\n return this.request<Policy>('PUT', `/api/v1/policies/${policyId}`, request);\n }\n\n /**\n * Delete a policy.\n */\n async deletePolicy(policyId: string): Promise<void> {\n await this.request<void>('DELETE', `/api/v1/policies/${policyId}`);\n }\n}\n","/**\n * Sandbox API client for Shrike.\n */\n\nimport { BaseClient, BaseClientOptions } from './base';\nimport { ScanResult } from '../scanner';\n\n/**\n * Sandbox scan request.\n */\nexport interface SandboxScanRequest {\n prompt: string;\n context?: string;\n model?: string;\n}\n\n/**\n * Sandbox client for testing prompts without affecting production metrics.\n */\nexport class SandboxClient extends BaseClient {\n constructor(options: BaseClientOptions = {}) {\n super(options);\n }\n\n /**\n * Scan a prompt in sandbox mode.\n * This does not count against production quotas.\n */\n async scan(request: SandboxScanRequest): Promise<ScanResult> {\n return this.request<ScanResult>('POST', '/api/v1/sandbox/scan', request);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/config.ts","../../package.json","../../src/version.ts","../../src/scanner.ts","../../src/api/base.ts","../../src/api/auth.ts","../../src/api/agents.ts","../../src/api/policies.ts","../../src/api/sandbox.ts"],"names":[],"mappings":";;;AA+BO,IAAM,gBAAA,GAAmB,sCAAA;AASzB,IAAM,QAAA,GAAW,YAAA;AAOL,UAAA;AACF,OAAA,CAAQ,GAAA,CAAI,eAAA,IAAmB,CAAA,OAAA,EAAU,YAAW,CAAE,KAAA,CAAM,CAAA,EAAG,CAAC,CAAC,CAAA;;;AC9ChF,IAAA,OAAA,GAAW,OAAA;;;ACMN,IAAM,OAAA,GAAkB,OAAA;ACoK/B,SAAS,YAAA,GAAuB;AAC9B,EAAA,OAAO,sCAAA,CAAuC,OAAA,CAAQ,OAAA,EAAS,CAAC,CAAA,KAAM;AACpE,IAAA,MAAM,CAAA,GAAK,IAAA,CAAK,MAAA,EAAO,GAAI,EAAA,GAAM,CAAA;AACjC,IAAA,MAAM,CAAA,GAAI,CAAA,KAAM,GAAA,GAAM,CAAA,GAAK,IAAI,CAAA,GAAO,CAAA;AACtC,IAAA,OAAO,CAAA,CAAE,SAAS,EAAE,CAAA;AAAA,EACtB,CAAC,CAAA;AACH;AAKO,SAAS,cAAA,CACd,cACA,SAAA,EACwB;AACxB,EAAA,OAAO;AAAA,IACL,aAAA,EAAe,UAAU,YAAY,CAAA,CAAA;AAAA,IACrC,cAAA,EAAgB,kBAAA;AAAA,IAChB,cAAA,EAAgB,QAAA;AAAA,IAChB,sBAAA,EAAwB,OAAA;AAAA,IACxB,qBAAA,EAAoC,YAAA;AAAa,GACnD;AACF;;;AC5KO,IAAM,aAAN,MAAiB;AAAA,EAKtB,WAAA,CAAY,OAAA,GAA6B,EAAC,EAAG;AAC3C,IAA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cesContent":["/**\n * Configuration constants and types for the Shrike Guard SDK.\n */\n\nimport { randomUUID } from 'node:crypto';\n\n/**\n * Defines behavior when scan operations fail.\n */\nexport enum FailMode {\n /**\n * Allow the request to proceed (fail-open). Use this mode when\n * availability is prioritized over strict security.\n */\n OPEN = 'open',\n\n /**\n * Block the request and raise an exception (fail-closed). This is the\n * default behavior — matching the MCP server's security posture. Use\n * fail-open only when you've explicitly decided availability matters more.\n */\n CLOSED = 'closed',\n}\n\n/** Default timeout for scan requests in milliseconds */\nexport const DEFAULT_SCAN_TIMEOUT = 10000;\n\n/** Default fail mode - block requests when scan fails (fail-closed) */\nexport const DEFAULT_FAIL_MODE = FailMode.CLOSED;\n\n/** Default Shrike API endpoint (uses load balancer for scalability) */\nexport const DEFAULT_ENDPOINT = 'https://api.shrikesecurity.com/agent';\n\n/** Default rate limit (requests per minute) */\nexport const DEFAULT_RATE_LIMIT_PER_MINUTE = 100;\n\n// Note: All scanning is done via backend API (tier-based: community=L1-L4, pro=L1-L8)\n// No local patterns needed - backend handles all detection logic\n\n/** SDK identification */\nexport const SDK_NAME = 'typescript';\nexport const SDK_USER_AGENT = 'shrike-guard-typescript';\n\n/**\n * Session identity — persists for the lifetime of this SDK process.\n * Maps to L9's SessionCache key for multi-turn attack detection.\n */\nconst SESSION_ID = randomUUID();\nconst AGENT_ID = process.env.SHRIKE_AGENT_ID || `sdk-ts-${randomUUID().slice(0, 8)}`;\n\n/** Returns the stable session ID for this SDK process. */\nexport function getSessionId(): string {\n return SESSION_ID;\n}\n\n/** Returns the agent ID (from SHRIKE_AGENT_ID env or auto-generated). */\nexport function getAgentId(): string {\n return AGENT_ID;\n}\n\n/**\n * Approval information returned when a policy requires human sign-off.\n */\nexport interface ApprovalInfo {\n requires_approval: boolean;\n approval_id: string;\n approval_level: string;\n action_summary: string;\n policy_name: string;\n expires_in_seconds: number;\n threat_type?: string;\n severity?: string;\n owasp_category?: string;\n risk_factors?: string[];\n original_action?: string;\n}\n\n/**\n * Retry configuration for transient failure resilience.\n * Matches MCP server's RETRY_CONFIG for consistent behavior.\n */\nexport const RETRY_CONFIG = {\n maxRetries: 2,\n initialDelayMs: 200,\n maxDelayMs: 2000,\n backoffMultiplier: 2,\n retryableErrors: ['ECONNREFUSED', 'ECONNRESET', 'ETIMEDOUT', 'fetch failed'],\n};\n","{\n \"name\": \"shrike-guard\",\n \"version\": \"4.0.3\",\n \"description\": \"Shrike SDK for AI agent action governance — drop-in wrapper for OpenAI, Anthropic, and Gemini that governs every tool call, prompt, and response server-side. Allow / approve / block. Free tier available.\",\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.js\"\n },\n \"./openai\": {\n \"types\": \"./dist/openai/index.d.ts\",\n \"import\": \"./dist/openai/index.mjs\",\n \"require\": \"./dist/openai/index.js\"\n },\n \"./anthropic\": {\n \"types\": \"./dist/anthropic/index.d.ts\",\n \"import\": \"./dist/anthropic/index.mjs\",\n \"require\": \"./dist/anthropic/index.js\"\n },\n \"./gemini\": {\n \"types\": \"./dist/gemini/index.d.ts\",\n \"import\": \"./dist/gemini/index.mjs\",\n \"require\": \"./dist/gemini/index.js\"\n },\n \"./api\": {\n \"types\": \"./dist/api/index.d.ts\",\n \"import\": \"./dist/api/index.mjs\",\n \"require\": \"./dist/api/index.js\"\n }\n },\n \"files\": [\n \"dist\",\n \"README.md\",\n \"CHANGELOG.md\",\n \"LICENSE\"\n ],\n \"scripts\": {\n \"build\": \"tsup\",\n \"test\": \"jest\",\n \"test:coverage\": \"jest --coverage\",\n \"lint\": \"eslint src --ext .ts\",\n \"typecheck\": \"tsc --noEmit\",\n \"prepublishOnly\": \"npm run build\"\n },\n \"keywords\": [\n \"action-governance\",\n \"ai-agents\",\n \"agent-security\",\n \"agent-governance\",\n \"tool-call-gating\",\n \"ai-governance\",\n \"openai\",\n \"anthropic\",\n \"claude\",\n \"gemini\",\n \"llm\",\n \"prompt-injection\",\n \"pii\",\n \"jailbreak\",\n \"ai-safety\"\n ],\n \"author\": \"Shrike Security <security@shrikesecurity.com>\",\n \"license\": \"Apache-2.0\",\n \"homepage\": \"https://shrikesecurity.com\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/Shrike-Security/shrike-guard-js\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/Shrike-Security/shrike-guard-js/issues\"\n },\n \"peerDependencies\": {\n \"@anthropic-ai/sdk\": \">=0.18.0\",\n \"@google/genai\": \">=1.0.0\",\n \"openai\": \">=4.0.0\"\n },\n \"peerDependenciesMeta\": {\n \"openai\": {\n \"optional\": true\n },\n \"@anthropic-ai/sdk\": {\n \"optional\": true\n },\n \"@google/genai\": {\n \"optional\": true\n }\n },\n \"devDependencies\": {\n \"@anthropic-ai/sdk\": \"^0.20.0\",\n \"@google/genai\": \"^2.12.0\",\n \"@types/jest\": \"^29.5.12\",\n \"@types/node\": \"^20.11.0\",\n \"jest\": \"^29.7.0\",\n \"openai\": \"^4.28.0\",\n \"ts-jest\": \"^29.1.2\",\n \"tsup\": \"^8.5.1\",\n \"typescript\": \"^5.3.3\"\n },\n \"engines\": {\n \"node\": \">=18.0.0\"\n }\n}\n","// SDK version — derived from package.json at build time (tsup/esbuild inlines\n// the JSON literal, resolveJsonModule is on), so it can never drift from the\n// published version. It was previously a hardcoded '1.5.0' that fell out of\n// sync with package.json (4.0.2) and mis-stamped X-Shrike-SDK-Version on every\n// scan. Guarded by tests/unit/version.test.ts. Mirrors the Python SDK, which\n// derives __version__ from installed distribution metadata.\nimport { version } from '../package.json';\n\nexport const VERSION: string = version;\n","/**\n * HTTP client for the Shrike scan API.\n * Includes retry with exponential backoff, session correlation,\n * approval workflow, 401 key refresh, and rate limiting.\n */\n\nimport {\n DEFAULT_ENDPOINT,\n DEFAULT_SCAN_TIMEOUT,\n DEFAULT_RATE_LIMIT_PER_MINUTE,\n SDK_NAME,\n RETRY_CONFIG,\n getSessionId,\n getAgentId,\n} from './config';\nimport type { ApprovalInfo } from './config';\nimport { AUTO_CHUNK_THRESHOLD, aggregateChunkResults, chunkContent } from './chunker';\nimport { ShrikeRateLimitError } from './errors';\nimport { RateLimiter } from './rateLimiter';\nimport { sanitizeScanResponse } from './sanitizer';\nimport { VERSION } from './version';\n\n/**\n * Phase 8b: Client-side size limits to fail fast before network round-trip.\n * These limits match the backend limits for consistency.\n */\nconst MAX_CONTENT_SIZE = 100 * 1024; // 100KB - matches backend MaxRequestBodySize\n\n/**\n * Result from a scan operation.\n */\n/**\n * Correlation pattern from L9 session-aware correlation engine.\n */\nexport interface CorrelationPattern {\n pattern_id: string;\n pattern_name: string;\n category: string;\n confidence: number;\n description: string;\n}\n\n/**\n * Governance action per Cooperative Governance 4-state contract (allow / warn / require_approval / block).\n * The `action` field is the server-authoritative signal for proceed-vs-refuse;\n * `isBlocked()` in this module consumes it directly.\n */\nexport type ScanAction = 'allow' | 'warn' | 'require_approval' | 'block';\n\n/**\n * Recovery guidance emitted by the backend on refuse verdicts.\n * `available_tools` names the MCP tools the caller can still invoke while\n * under quarantine (typically read-only surfaces like session_status).\n */\nexport interface ScanRecovery {\n instruction?: string;\n available_tools?: string[];\n patterns_triggered?: string[];\n [key: string]: unknown;\n}\n\n/**\n * Session-level state carried on every scan response (contract symmetry).\n * Fields are outcome state per the dashboard IP boundary — customer-visible.\n */\nexport interface ScanSessionState {\n session_risk_score?: number;\n session_turn_number?: number;\n session_patterns?: string[];\n session_locked?: boolean;\n [key: string]: unknown;\n}\n\n/**\n * A single policy violation as emitted by the /api/scan/enforce endpoint.\n * The sanitizer strips policy_id / policy_name / matched_pattern / other\n * attribution before this reaches callers; what remains here is the\n * customer-visible outcome surface.\n */\nexport interface ScanViolation {\n threat_type?: string;\n owasp_category?: string;\n severity?: string;\n action?: string;\n user_message?: string;\n suggested_action?: string;\n [key: string]: unknown;\n}\n\nexport interface ScanResult {\n safe: boolean;\n reason?: string;\n threat_type?: string;\n severity?: string;\n confidence?: number | string;\n violations?: ScanViolation[];\n guidance?: string;\n approval_info?: ApprovalInfo;\n /** Cooperative Governance action — server-authoritative proceed/refuse signal */\n action?: ScanAction;\n /** Refuse tier: allow / warn / require_approval / block */\n refuse_tier?: ScanAction;\n /** Recovery guidance, present on refuse verdicts */\n recovery?: ScanRecovery;\n /** L9 session correlation state — outcome, customer-visible */\n session_state?: ScanSessionState;\n /** Specialized scan input type, e.g. 'sql' / 'file_path' / 'a2a_message' */\n content_type?: string;\n /** Client-side session rotation guidance */\n client_session_rotation?: unknown;\n /** L9 session risk score (0.0-1.0), present when session correlation is active */\n session_risk_score?: number;\n /** L9 matched correlation patterns, present when multi-turn patterns are detected */\n correlation_patterns?: CorrelationPattern[];\n /**\n * True when this is a fail-open verdict returned without a completed scan —\n * i.e. `failMode: 'open'` was set and the backend was unreachable, so\n * enforcement was skipped. Lets a caller distinguish \"scanned and clean\"\n * from \"not scanned, allowed anyway.\"\n */\n degraded?: boolean;\n [key: string]: unknown;\n}\n\n/**\n * Build a fail-open ALLOW verdict. Returned only when `failMode === 'open'` is\n * explicitly set and the scan could not complete (timeout, backend error).\n * Marked `degraded: true` — centralize all fail-open returns through this so the\n * marker can never be forgotten on a new wrapper.\n */\nexport function failOpenResult(reason: string): ScanResult {\n return { safe: true, reason, degraded: true };\n}\n\n/**\n * Result of ScanClient.declareScope — the persisted scope row plus derived\n * active_until + expired fields. Mirrors the shape returned by\n * POST /api/v1/agent/scope/declare on the backend.\n */\nexport interface DeclareScopeResult {\n scope_id?: string;\n agent_id?: string;\n purpose?: string;\n allowed_tools?: string[];\n forbidden_tools?: string[];\n max_duration_seconds?: number;\n expires_at?: string;\n active_until?: string;\n expired?: boolean;\n created_at?: string;\n updated_at?: string;\n}\n\n/**\n * Options for the ScanClient.\n */\nexport interface ScanClientOptions {\n /** Shrike API key for authentication */\n apiKey: string;\n /** Shrike API endpoint URL */\n endpoint?: string;\n /** Request timeout in milliseconds */\n timeout?: number;\n /** Rate limit in requests per minute (default: 100) */\n rateLimitPerMinute?: number;\n /** Optional callback to refresh API key on 401. Return new key or null. */\n onKeyRefresh?: () => Promise<string | null>;\n}\n\n/**\n * Generate a UUID v4 string.\n */\nfunction generateUUID(): string {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n/**\n * Generate headers for scan API requests.\n */\nexport function getScanHeaders(\n shrikeApiKey: string,\n requestId?: string\n): Record<string, string> {\n return {\n Authorization: `Bearer ${shrikeApiKey}`,\n 'Content-Type': 'application/json',\n 'X-Shrike-SDK': SDK_NAME,\n 'X-Shrike-SDK-Version': VERSION,\n 'X-Shrike-Request-ID': requestId || generateUUID(),\n };\n}\n\n/** Check if an error is transient and retryable. */\nfunction isRetryableError(error: unknown): boolean {\n if (error instanceof Error) {\n const cause = 'cause' in error ? String((error as { cause?: unknown }).cause) : '';\n const errorStr = `${error.name} ${error.message} ${cause}`;\n return RETRY_CONFIG.retryableErrors.some((e) => errorStr.includes(e));\n }\n return false;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Fetch with retry for cold-start and transient failure resilience.\n * Matches MCP server's fetchWithRetry pattern.\n */\nasync function fetchWithRetry(\n url: string,\n options: RequestInit,\n timeoutMs: number,\n apiKey: string,\n onKeyRefresh?: () => Promise<string | null>\n): Promise<Response> {\n let lastError: Error | null = null;\n let delay = RETRY_CONFIG.initialDelayMs;\n\n for (let attempt = 0; attempt <= RETRY_CONFIG.maxRetries; attempt++) {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeoutMs);\n\n try {\n const response = await fetch(url, {\n ...options,\n signal: controller.signal,\n });\n clearTimeout(timeoutId);\n\n // On 401, try key refresh and retry once\n if (response.status === 401 && onKeyRefresh && attempt === 0) {\n const newKey = await onKeyRefresh();\n if (newKey && newKey !== apiKey) {\n const retryController = new AbortController();\n const retryTimeout = setTimeout(() => retryController.abort(), timeoutMs);\n try {\n const headers = {\n ...(options.headers as Record<string, string>),\n Authorization: `Bearer ${newKey}`,\n };\n const retryResponse = await fetch(url, {\n ...options,\n headers,\n signal: retryController.signal,\n });\n clearTimeout(retryTimeout);\n return retryResponse;\n } catch {\n clearTimeout(retryTimeout);\n // Fall through to return original 401\n }\n }\n }\n\n return response;\n } catch (error) {\n clearTimeout(timeoutId);\n lastError = error instanceof Error ? error : new Error(String(error));\n\n // Don't retry on abort (timeout) or non-retryable errors\n if (lastError.name === 'AbortError' || !isRetryableError(error)) {\n throw lastError;\n }\n\n if (attempt < RETRY_CONFIG.maxRetries) {\n await sleep(delay);\n delay = Math.min(delay * RETRY_CONFIG.backoffMultiplier, RETRY_CONFIG.maxDelayMs);\n }\n }\n }\n\n throw lastError || new Error('Fetch failed after retries');\n}\n\n/**\n * Build the session context object for backend requests.\n */\nfunction buildSessionContext(extraContext?: Record<string, unknown>): Record<string, unknown> {\n return {\n ...extraContext,\n session_id: getSessionId(),\n agent_id: getAgentId(),\n source_application: 'shrike-guard-ts',\n };\n}\n\n/**\n * HTTP client for the Shrike scan API.\n */\n/**\n * Decide whether a scan verdict should be enforced as a block.\n *\n * Prefers the server-authoritative `action` field emitted by\n * /api/scan/enforce. Falls back to the legacy\n * `safe` boolean for verdicts that predate the enforce endpoint (older\n * backends, circuit-breaker fail-open synthetic verdicts, cached responses).\n *\n * Behavior:\n * - action = \"block\" → true\n * - action = \"require_approval\" → true (held actions are refused at the\n * tool-call boundary; caller can re-issue\n * after approval lands)\n * - action = \"allow\" → false\n * - action = \"warn\" → false (advisory; caller should surface\n * via block-feedback but not refuse)\n * - action absent → fall back to `!safe`\n *\n * This helper is the ONLY place the SDK converts a verdict into a\n * proceed-vs-refuse decision. Every LLM wrapper (OpenAI, Anthropic, Gemini)\n * routes through it so behavior stays uniform.\n *\n * Contract-symmetry pin: mirrors Python `_is_blocked` in shrike_guard.scanner.\n * If either SDK diverges, that is a bug in one of the two.\n */\nexport function isBlocked(verdict: ScanResult | Record<string, unknown>): boolean {\n const action = (verdict as Record<string, unknown>).action;\n if (typeof action === 'string' && action.length > 0) {\n // Known non-blocking tiers proceed.\n if (action === 'allow' || action === 'warn') return false;\n // Known blocking tiers refuse.\n if (action === 'block' || action === 'require_approval') return true;\n // Unknown/future tier (e.g. a new \"quarantine\" the backend adds): do NOT\n // fail open on an unrecognized name — fall through to `safe`. A new\n // blocking tier also sets safe:false, so this fails closed until the\n // client learns the tier explicitly. Forward-compat contract, see\n // tests/unit/contract-forward-compat.test.ts.\n }\n const safe = (verdict as Record<string, unknown>).safe;\n if (typeof safe === 'boolean') {\n return !safe;\n }\n return false;\n}\n\n/**\n * When running without an API key, appends a signup hint to scan results\n * so agents/users know they can upgrade from regex-only to full scanning.\n */\nexport function maybeAddSignupHint(result: ScanResult, apiKey: string): ScanResult {\n if (apiKey) return result;\n // Don't override if backend already provided upgrade_hint\n if ((result as any).upgrade_hint) return result;\n return {\n ...result,\n _note: 'Running without API key (L1-L5 only). Register free for cognitive threat detection: npx shrike-mcp --signup',\n };\n}\n\nexport class ScanClient {\n private apiKey: string;\n private readonly endpoint: string;\n private readonly timeout: number;\n private readonly rateLimiter: RateLimiter;\n private readonly onKeyRefresh?: () => Promise<string | null>;\n\n constructor(options: ScanClientOptions) {\n this.apiKey = options.apiKey;\n this.endpoint = (options.endpoint || DEFAULT_ENDPOINT).replace(/\\/$/, '');\n this.timeout = options.timeout || DEFAULT_SCAN_TIMEOUT;\n this.rateLimiter = new RateLimiter(options.rateLimitPerMinute || DEFAULT_RATE_LIMIT_PER_MINUTE);\n this.onKeyRefresh = options.onKeyRefresh;\n\n if (!this.apiKey) {\n console.warn('[shrike-guard] No API key provided — running in free tier (regex-only).');\n console.warn('[shrike-guard] For full scanning (LLM analysis, session correlation): npx shrike-mcp --signup');\n }\n }\n\n /** Check rate limit before each request. */\n private checkRateLimit(): void {\n const result = this.rateLimiter.consume();\n if (!result.allowed) {\n throw new ShrikeRateLimitError(result.retryAfterMs!);\n }\n }\n\n /**\n * Scan a prompt for security threats.\n *\n * @param prompt - The user prompt to scan.\n * @param context - Optional conversation context for better analysis.\n * @returns Scan result with 'safe' boolean and additional details.\n * @throws Error if the request fails or times out.\n */\n async scan(prompt: string, context?: string): Promise<ScanResult> {\n // Client-side size validation to fail fast\n const totalSize = prompt.length + (context?.length || 0);\n if (totalSize > MAX_CONTENT_SIZE) {\n return {\n safe: false,\n reason: `Content too large (${Math.round(totalSize / 1024)}KB > ${MAX_CONTENT_SIZE / 1024}KB limit)`,\n threat_type: 'size_limit_exceeded',\n confidence: 1.0,\n violations: [\n {\n type: 'size_limit',\n description: `Content exceeds maximum size of ${MAX_CONTENT_SIZE / 1024}KB`,\n },\n ],\n };\n }\n\n // Auto-chunk large prompts. Below the threshold we keep the single-shot\n // path unchanged; above it we split on natural boundaries, scan each\n // chunk sequentially, and stop on the first block verdict. The\n // conversation_history context is NOT chunked — it rides on every scan\n // so downstream layers see the same session shape.\n if (prompt.length > AUTO_CHUNK_THRESHOLD) {\n return this.scanChunked(prompt, context);\n }\n\n this.checkRateLimit();\n\n const payload: Record<string, unknown> = {\n prompt,\n scan_type: 'full',\n context: buildSessionContext(),\n };\n if (context) {\n payload.conversation_history = context;\n }\n\n const response = await fetchWithRetry(\n `${this.endpoint}/api/scan/enforce`,\n {\n method: 'POST',\n headers: getScanHeaders(this.apiKey),\n body: JSON.stringify(payload),\n },\n this.timeout,\n this.apiKey,\n this.onKeyRefresh\n );\n\n if (!response.ok) {\n throw new Error(`Scan API returned error: ${response.status}`);\n }\n\n return maybeAddSignupHint(sanitizeScanResponse((await response.json()) as ScanResult), this.apiKey);\n }\n\n /**\n * Chunk-and-scan path for prompts above AUTO_CHUNK_THRESHOLD. Splits on\n * natural boundaries, scans sequentially, aggregates. Stops on the first\n * block verdict (fail-fast) so a compromised chunk doesn't pay for the\n * remaining scans.\n *\n * Known limit: same session ID rides every chunk, so L9 turn count\n * inflates by chunk-count. Fix post-launch via backend chunk_group field.\n */\n private async scanChunked(prompt: string, context?: string): Promise<ScanResult> {\n const chunks = chunkContent(prompt);\n const results: ScanResult[] = [];\n for (const chunk of chunks) {\n const chunkResult = await this.scan(chunk, context);\n results.push(chunkResult);\n const action = chunkResult.action || chunkResult.refuse_tier;\n if (action === 'block') {\n break;\n }\n }\n return maybeAddSignupHint(aggregateChunkResults(results), this.apiKey);\n }\n\n /**\n * Scan a SQL query for injection attacks.\n *\n * @param query - The SQL query to scan.\n * @param database - Optional database name for context.\n * @param allowDestructive - If true, allows DROP/TRUNCATE operations.\n * @returns Scan result with 'safe' boolean and additional details.\n */\n async scanSql(\n query: string,\n database?: string,\n allowDestructive = false\n ): Promise<ScanResult> {\n if (query.length > MAX_CONTENT_SIZE) {\n return {\n safe: false,\n reason: `SQL query too large (${Math.round(query.length / 1024)}KB > ${MAX_CONTENT_SIZE / 1024}KB limit)`,\n threat_type: 'size_limit_exceeded',\n confidence: 1.0,\n violations: [\n {\n type: 'size_limit',\n description: `Query exceeds maximum size of ${MAX_CONTENT_SIZE / 1024}KB`,\n },\n ],\n };\n }\n\n this.checkRateLimit();\n\n const toolContext: Record<string, unknown> = {};\n if (database) {\n toolContext.database = database;\n }\n if (allowDestructive) {\n toolContext.allow_destructive = 'true';\n }\n\n const payload = {\n content: query,\n content_type: 'sql',\n context: buildSessionContext(toolContext),\n };\n\n const response = await fetchWithRetry(\n `${this.endpoint}/api/scan/enforce/specialized`,\n {\n method: 'POST',\n headers: getScanHeaders(this.apiKey),\n body: JSON.stringify(payload),\n },\n this.timeout,\n this.apiKey,\n this.onKeyRefresh\n );\n\n if (!response.ok) {\n throw new Error(`SQL scan API returned error: ${response.status}`);\n }\n\n return maybeAddSignupHint(sanitizeScanResponse((await response.json()) as ScanResult), this.apiKey);\n }\n\n /**\n * Scan a file path for security risks.\n *\n * @param path - The file path to validate.\n * @param content - Optional file content to scan for secrets/PII.\n * @returns Scan result with 'safe' boolean and additional details.\n */\n async scanFile(path: string, content?: string): Promise<ScanResult> {\n const totalSize = path.length + (content?.length || 0);\n if (totalSize > MAX_CONTENT_SIZE) {\n return {\n safe: false,\n reason: `File content too large (${Math.round(totalSize / 1024)}KB > ${MAX_CONTENT_SIZE / 1024}KB limit)`,\n threat_type: 'size_limit_exceeded',\n confidence: 1.0,\n violations: [\n {\n type: 'size_limit',\n description: `Content exceeds maximum size of ${MAX_CONTENT_SIZE / 1024}KB`,\n },\n ],\n };\n }\n\n this.checkRateLimit();\n\n const contentType = content ? 'file_content' : 'file_path';\n const extraContext: Record<string, unknown> = {};\n if (content) {\n extraContext.file_content = content;\n }\n\n const payload = {\n content: path,\n content_type: contentType,\n context: buildSessionContext(extraContext),\n };\n\n const response = await fetchWithRetry(\n `${this.endpoint}/api/scan/enforce/specialized`,\n {\n method: 'POST',\n headers: getScanHeaders(this.apiKey),\n body: JSON.stringify(payload),\n },\n this.timeout,\n this.apiKey,\n this.onKeyRefresh\n );\n\n if (!response.ok) {\n throw new Error(`File scan API returned error: ${response.status}`);\n }\n\n return maybeAddSignupHint(sanitizeScanResponse((await response.json()) as ScanResult), this.apiKey);\n }\n\n /**\n * Scan an A2A (Agent-to-Agent) protocol message for security threats.\n *\n * @param message - The A2A message text content to scan.\n * @param options - Optional context: sender/receiver agent IDs, task ID, role.\n * @returns Scan result with 'safe' boolean and additional details.\n */\n async scanA2AMessage(\n message: string,\n options?: {\n senderAgentId?: string;\n receiverAgentId?: string;\n taskId?: string;\n role?: 'user' | 'agent';\n }\n ): Promise<ScanResult> {\n if (message.length > MAX_CONTENT_SIZE) {\n return {\n safe: false,\n reason: `Message too large (${Math.round(message.length / 1024)}KB > ${MAX_CONTENT_SIZE / 1024}KB limit)`,\n threat_type: 'size_limit_exceeded',\n confidence: 1.0,\n violations: [\n {\n type: 'size_limit',\n description: `Content exceeds maximum size of ${MAX_CONTENT_SIZE / 1024}KB`,\n },\n ],\n };\n }\n\n this.checkRateLimit();\n\n const extraContext: Record<string, unknown> = {};\n if (options?.senderAgentId) extraContext.sender_agent_id = options.senderAgentId;\n if (options?.receiverAgentId) extraContext.receiver_agent_id = options.receiverAgentId;\n if (options?.taskId) extraContext.task_id = options.taskId;\n if (options?.role) extraContext.role = options.role;\n\n const payload = {\n content: message,\n content_type: 'a2a_message',\n context: buildSessionContext(extraContext),\n };\n\n const response = await fetchWithRetry(\n `${this.endpoint}/api/scan/enforce/specialized`,\n {\n method: 'POST',\n headers: getScanHeaders(this.apiKey),\n body: JSON.stringify(payload),\n },\n this.timeout,\n this.apiKey,\n this.onKeyRefresh\n );\n\n if (!response.ok) {\n throw new Error(`A2A message scan API returned error: ${response.status}`);\n }\n\n return maybeAddSignupHint(sanitizeScanResponse((await response.json()) as ScanResult), this.apiKey);\n }\n\n /**\n * Scan an A2A AgentCard JSON for security threats.\n *\n * @param agentCard - The raw JSON string of the A2A AgentCard to scan.\n * @param verifySignature - Reserved for future JWS signature verification.\n * @returns Scan result with 'safe' boolean and additional details.\n */\n async scanAgentCard(\n agentCard: string,\n verifySignature = false\n ): Promise<ScanResult> {\n if (agentCard.length > MAX_CONTENT_SIZE) {\n return {\n safe: false,\n reason: `Agent card too large (${Math.round(agentCard.length / 1024)}KB > ${MAX_CONTENT_SIZE / 1024}KB limit)`,\n threat_type: 'size_limit_exceeded',\n confidence: 1.0,\n violations: [\n {\n type: 'size_limit',\n description: `Content exceeds maximum size of ${MAX_CONTENT_SIZE / 1024}KB`,\n },\n ],\n };\n }\n\n this.checkRateLimit();\n\n const extraContext: Record<string, unknown> = {};\n if (verifySignature) extraContext.verify_signature = 'true';\n\n const payload = {\n content: agentCard,\n content_type: 'agent_card',\n context: buildSessionContext(extraContext),\n };\n\n const response = await fetchWithRetry(\n `${this.endpoint}/api/scan/enforce/specialized`,\n {\n method: 'POST',\n headers: getScanHeaders(this.apiKey),\n body: JSON.stringify(payload),\n },\n this.timeout,\n this.apiKey,\n this.onKeyRefresh\n );\n\n if (!response.ok) {\n throw new Error(`Agent card scan API returned error: ${response.status}`);\n }\n\n return maybeAddSignupHint(sanitizeScanResponse((await response.json()) as ScanResult), this.apiKey);\n }\n\n /**\n * Declare (or refresh) the operating scope for a task-scoped agent.\n *\n * Once declared, every subsequent scan for the same agent_id is enforced\n * against the scope on the backend. Tool calls outside allowed_tools —\n * or explicitly on forbidden_tools — route to refuse_tier:\n * \"require_approval\" with threat_type: \"scope_violation\". Expired scopes\n * emit threat_type: \"scope_expired\". Absent a declaration, no scope\n * check runs; every existing SDK integration is unaffected until it\n * opts in.\n *\n * Wire contract mirrors ScanClient.declare_scope on the Python SDK and\n * scan_declare_scope on the shrike-mcp package — do not diverge without\n * updating those siblings.\n *\n * @param options.agentId - Agent identity this scope applies to.\n * @param options.allowedTools - Exact tool names permitted; [\"*\"] = any.\n * @param options.forbiddenTools - Optional. Wins over allowedTools.\n * @param options.purpose - Optional audit + dashboard label.\n * @param options.maxDurationSeconds - Optional TTL from created_at.\n * @param options.expiresAt - Optional ISO-8601 absolute expiry.\n * @returns The persisted scope row, including scope_id + active_until.\n */\n async declareScope(options: {\n agentId: string;\n allowedTools: string[];\n forbiddenTools?: string[];\n purpose?: string;\n maxDurationSeconds?: number;\n expiresAt?: string;\n }): Promise<DeclareScopeResult> {\n this.checkRateLimit();\n\n const payload: Record<string, unknown> = {\n agent_id: options.agentId,\n allowed_tools: options.allowedTools,\n };\n if (options.purpose !== undefined) payload.purpose = options.purpose;\n if (options.forbiddenTools !== undefined) payload.forbidden_tools = options.forbiddenTools;\n if (options.maxDurationSeconds !== undefined) {\n payload.max_duration_seconds = options.maxDurationSeconds;\n }\n if (options.expiresAt !== undefined) payload.expires_at = options.expiresAt;\n\n const response = await fetchWithRetry(\n `${this.endpoint}/api/v1/agent/scope/declare`,\n {\n method: 'POST',\n headers: getScanHeaders(this.apiKey),\n body: JSON.stringify(payload),\n },\n this.timeout,\n this.apiKey,\n this.onKeyRefresh\n );\n\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new Error(\n `declareScope failed: ${response.status}${text ? ` — ${text.trim()}` : ''}`\n );\n }\n\n return (await response.json()) as DeclareScopeResult;\n }\n}\n","/**\n * Base API client for Shrike backend.\n */\n\nimport { DEFAULT_ENDPOINT } from '../config';\nimport { getScanHeaders } from '../scanner';\n\n/**\n * Base options for API clients.\n */\nexport interface BaseClientOptions {\n /** API key for authentication */\n apiKey?: string;\n /** Base URL for the API */\n baseUrl?: string;\n /** Request timeout in milliseconds */\n timeout?: number;\n}\n\n/**\n * Base API client with common HTTP functionality.\n */\nexport class BaseClient {\n protected readonly apiKey: string;\n protected readonly baseUrl: string;\n protected readonly timeout: number;\n\n constructor(options: BaseClientOptions = {}) {\n this.apiKey = options.apiKey || '';\n this.baseUrl = (options.baseUrl || DEFAULT_ENDPOINT).replace(/\\/$/, '');\n this.timeout = options.timeout || 30000;\n }\n\n /**\n * Make an HTTP request to the API.\n */\n protected async request<T>(\n method: string,\n path: string,\n body?: unknown\n ): Promise<T> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(`${this.baseUrl}${path}`, {\n method,\n headers: getScanHeaders(this.apiKey),\n body: body ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n });\n\n if (!response.ok) {\n const errorBody = await response.json().catch(() => ({ message: response.statusText })) as { message?: string };\n throw new Error(errorBody.message || `API error: ${response.status}`);\n }\n\n return response.json() as Promise<T>;\n } finally {\n clearTimeout(timeoutId);\n }\n }\n\n protected get<T>(path: string): Promise<T> {\n return this.request<T>('GET', path);\n }\n\n protected post<T>(path: string, body?: unknown): Promise<T> {\n return this.request<T>('POST', path, body);\n }\n\n protected put<T>(path: string, body?: unknown): Promise<T> {\n return this.request<T>('PUT', path, body);\n }\n\n protected delete<T>(path: string): Promise<T> {\n return this.request<T>('DELETE', path);\n }\n}\n","/**\n * Authentication API client for Shrike.\n */\n\nimport { BaseClient, BaseClientOptions } from './base';\n\n/**\n * Registration request payload.\n */\nexport interface RegisterRequest {\n email: string;\n password: string;\n company_name?: string;\n}\n\n/**\n * Login request payload.\n */\nexport interface LoginRequest {\n email: string;\n password: string;\n}\n\n/**\n * Authentication response with tokens.\n */\nexport interface AuthResponse {\n access_token: string;\n refresh_token: string;\n token_type: string;\n expires_in: number;\n}\n\n/**\n * User profile response.\n */\nexport interface UserProfile {\n customer_id: string;\n email: string;\n company_name?: string;\n created_at: string;\n}\n\n/**\n * Authentication client for Shrike API.\n */\nexport class AuthClient extends BaseClient {\n constructor(options: BaseClientOptions = {}) {\n super(options);\n }\n\n /**\n * Register a new customer account.\n */\n async register(request: RegisterRequest): Promise<AuthResponse> {\n return this.request<AuthResponse>('POST', '/api/v1/auth/register', request);\n }\n\n /**\n * Login with email and password.\n */\n async login(request: LoginRequest): Promise<AuthResponse> {\n return this.request<AuthResponse>('POST', '/api/v1/auth/login', request);\n }\n\n /**\n * Refresh the access token using a refresh token.\n */\n async refresh(refreshToken: string): Promise<AuthResponse> {\n return this.request<AuthResponse>('POST', '/api/v1/auth/refresh', {\n refresh_token: refreshToken,\n });\n }\n\n /**\n * Logout and invalidate the current session.\n */\n async logout(): Promise<void> {\n await this.request<void>('POST', '/api/v1/auth/logout');\n }\n\n /**\n * Get the current user's profile.\n */\n async me(): Promise<UserProfile> {\n return this.request<UserProfile>('GET', '/api/v1/auth/me');\n }\n}\n","/**\n * Agent API client for Shrike.\n */\n\nimport { BaseClient, BaseClientOptions } from './base';\n\n/**\n * Agent registration request.\n */\nexport interface RegisterAgentRequest {\n name: string;\n description?: string;\n policy_id?: string;\n}\n\n/**\n * Agent details.\n */\nexport interface Agent {\n agent_id: string;\n customer_id: string;\n name: string;\n description?: string;\n api_key: string;\n policy_id?: string;\n status: 'active' | 'inactive';\n created_at: string;\n last_heartbeat?: string;\n}\n\n/**\n * Heartbeat response.\n */\nexport interface HeartbeatResponse {\n status: string;\n server_time: string;\n}\n\n/**\n * Agent policy.\n */\nexport interface AgentPolicy {\n policy_id: string;\n name: string;\n rules: PolicyRule[];\n}\n\n/**\n * Policy rule.\n */\nexport interface PolicyRule {\n type: string;\n action: 'block' | 'warn' | 'allow';\n threshold?: number;\n [key: string]: unknown;\n}\n\n/**\n * Agent management client for Shrike API.\n */\nexport class AgentClient extends BaseClient {\n constructor(options: BaseClientOptions = {}) {\n super(options);\n }\n\n /**\n * Register a new agent.\n * Requires a customer API key.\n */\n async register(request: RegisterAgentRequest): Promise<Agent> {\n return this.request<Agent>('POST', '/api/v1/agents/register', request);\n }\n\n /**\n * Send a heartbeat from an agent.\n * Requires an agent API key.\n */\n async heartbeat(): Promise<HeartbeatResponse> {\n return this.request<HeartbeatResponse>('POST', '/api/v1/agents/heartbeat');\n }\n\n /**\n * Get the policies assigned to this agent.\n * Requires an agent API key.\n */\n async getPolicies(): Promise<AgentPolicy[]> {\n return this.request<AgentPolicy[]>('GET', '/api/v1/agents/policies');\n }\n\n /**\n * List all agents for the current customer.\n * Requires a customer API key.\n */\n async list(): Promise<Agent[]> {\n return this.request<Agent[]>('GET', '/api/v1/agents');\n }\n\n /**\n * Get an agent by ID.\n */\n async getAgent(agentId: string): Promise<Agent> {\n return this.request<Agent>('GET', `/api/v1/agents/${agentId}`);\n }\n\n /**\n * Delete an agent.\n */\n async deleteAgent(agentId: string): Promise<void> {\n await this.request<void>('DELETE', `/api/v1/agents/${agentId}`);\n }\n}\n","/**\n * Policy API client for Shrike.\n */\n\nimport { BaseClient, BaseClientOptions } from './base';\n\n/**\n * Policy rule definition.\n */\nexport interface PolicyRule {\n type: 'prompt_injection' | 'pii_detection' | 'jailbreak' | 'sql_injection' | 'custom';\n action: 'block' | 'warn' | 'allow';\n threshold?: number;\n patterns?: string[];\n [key: string]: unknown;\n}\n\n/**\n * Policy definition.\n */\nexport interface Policy {\n policy_id: string;\n customer_id: string;\n name: string;\n description?: string;\n rules: PolicyRule[];\n is_default: boolean;\n created_at: string;\n updated_at: string;\n}\n\n/**\n * Create policy request.\n */\nexport interface CreatePolicyRequest {\n name: string;\n description?: string;\n rules: PolicyRule[];\n is_default?: boolean;\n}\n\n/**\n * Update policy request.\n */\nexport interface UpdatePolicyRequest {\n name?: string;\n description?: string;\n rules?: PolicyRule[];\n is_default?: boolean;\n}\n\n/**\n * Policy management client for Shrike API.\n */\nexport class PolicyClient extends BaseClient {\n constructor(options: BaseClientOptions = {}) {\n super(options);\n }\n\n /**\n * List all policies for the current customer.\n */\n async list(): Promise<Policy[]> {\n return this.request<Policy[]>('GET', '/api/v1/policies');\n }\n\n /**\n * Get a policy by ID.\n */\n async getPolicy(policyId: string): Promise<Policy> {\n return this.request<Policy>('GET', `/api/v1/policies/${policyId}`);\n }\n\n /**\n * Create a new policy.\n */\n async create(request: CreatePolicyRequest): Promise<Policy> {\n return this.request<Policy>('POST', '/api/v1/policies', request);\n }\n\n /**\n * Update an existing policy.\n */\n async update(policyId: string, request: UpdatePolicyRequest): Promise<Policy> {\n return this.request<Policy>('PUT', `/api/v1/policies/${policyId}`, request);\n }\n\n /**\n * Delete a policy.\n */\n async deletePolicy(policyId: string): Promise<void> {\n await this.request<void>('DELETE', `/api/v1/policies/${policyId}`);\n }\n}\n","/**\n * Sandbox API client for Shrike.\n */\n\nimport { BaseClient, BaseClientOptions } from './base';\nimport { ScanResult } from '../scanner';\n\n/**\n * Sandbox scan request.\n */\nexport interface SandboxScanRequest {\n prompt: string;\n context?: string;\n model?: string;\n}\n\n/**\n * Sandbox client for testing prompts without affecting production metrics.\n */\nexport class SandboxClient extends BaseClient {\n constructor(options: BaseClientOptions = {}) {\n super(options);\n }\n\n /**\n * Scan a prompt in sandbox mode.\n * This does not count against production quotas.\n */\n async scan(request: SandboxScanRequest): Promise<ScanResult> {\n return this.request<ScanResult>('POST', '/api/v1/sandbox/scan', request);\n }\n}\n"]}
|
package/dist/gemini/index.js
CHANGED
|
@@ -329,8 +329,11 @@ function sanitizeScanResponse(raw) {
|
|
|
329
329
|
return result;
|
|
330
330
|
}
|
|
331
331
|
|
|
332
|
+
// package.json
|
|
333
|
+
var version = "4.0.3";
|
|
334
|
+
|
|
332
335
|
// src/version.ts
|
|
333
|
-
var VERSION =
|
|
336
|
+
var VERSION = version;
|
|
334
337
|
function failOpenResult(reason) {
|
|
335
338
|
return { safe: true, reason, degraded: true };
|
|
336
339
|
}
|