mirror of
https://github.com/prompt-security/clawsec.git
synced 2026-06-13 05:28:02 +03:00
73dd63f714
* Add NanoClaw platform support to ClawSec ## Changes ### CI/CD Pipeline Updates - Added NanoClaw keywords to NVD CVE monitoring - Keywords: "NanoClaw", "WhatsApp-bot", "baileys" - GitHub pattern now matches NanoClaw repositories ### Documentation - Added NANOCLAW.md with integration guide - Documented platform-specific advisory schema - Credited 8-agent team that designed the integration ### Advisory Schema Enhancement - Added optional `platforms` field support - Enables platform-specific advisories (openclaw/nanoclaw) - Maintains backward compatibility (empty = all platforms) ## Team Credits Designed and implemented by specialized agent team: - pioneer-repo-scout: ClawSec architecture analysis - pioneer-nanoclaw-scout: NanoClaw architecture analysis - architect: Integration design - advisory-specialist: Feed integration - integrity-specialist: File integrity design - installer-specialist: Signature verification - tester: Test infrastructure - documenter: Documentation Total contribution: 3000+ lines of design + implementation code. ## Impact ClawSec now monitors for NanoClaw-specific security issues and can provide platform-targeted advisories. This enables NanoClaw to consume the advisory feed out-of-the-box for security monitoring. Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * Add clawsec-nanoclaw skill with full security suite Provides complete ClawSec integration for NanoClaw deployments including: Features: - 4 MCP tools for agent-initiated vulnerability checking - Advisory cache service with automatic feed fetching (6h interval) - Ed25519 signature verification for feed integrity - Platform-specific advisory filtering (nanoclaw/openclaw) - IPC-based container-to-host communication Components (1,730 lines): - MCP Tools (350 lines): clawsec_check_advisories, clawsec_check_skill_safety, clawsec_list_advisories, clawsec_verify_signature - Advisory Cache Manager (492 lines): Periodic fetching, signature verification - Signature Verification (387 lines): Ed25519 crypto utilities - Advisory Matching (289 lines): Skill-to-vulnerability correlation - IPC Handlers (212 lines): Host-side request processing - Complete documentation: SKILL.md, INSTALL.md with troubleshooting Architecture: - Container: MCP tools invoked by agents via Claude SDK - IPC Layer: Filesystem-based request/response for host operations - Host Service: Advisory cache with automatic refresh and verification - Feed Source: https://clawsec.prompt.security/advisories/feed.json Installation: NanoClaw users can now add ClawSec security by: 1. Copying skills/clawsec-nanoclaw to their deployment 2. Integrating MCP tools into container (3 line change) 3. Integrating IPC handlers into host (2 line change) 4. Starting cache service in host process (1 line change) No modifications to NanoClaw core required - ClawSec provides everything as an installable skill package, just like it does for OpenClaw. Updated NANOCLAW.md with complete installation instructions and documentation references. Team Credits: 8-agent collaborative design and implementation: - pioneer-repo-scout: ClawSec architecture analysis - pioneer-nanoclaw-scout: NanoClaw architecture analysis - architect: Integration design and coordination - advisory-specialist: Advisory feed integration - integrity-specialist: File integrity design - installer-specialist: Signature verification implementation - tester: Test infrastructure and validation - documenter: Documentation Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * Add security expansion: Skill signature verification + File integrity monitoring Implements Phase 1 (Skill Signature Verification) and Phase 2 (File Integrity Monitoring) for NanoClaw security enhancement. ## Phase 1: Skill Signature Verification (~490 lines) Adds Ed25519 signature verification for skill packages to prevent supply chain attacks. **New Files:** - host-services/skill-signature-handler.ts (217 lines): Core verification service - mcp-tools/signature-verification.ts (200 lines): clawsec_verify_skill_package tool - docs/SKILL_SIGNING.md (270 lines): Complete signing/verification guide **Features:** - Ed25519 signature verification using Node.js crypto - Pinned ClawSec public key with custom key override support - Auto-detection of .sig signature files - Package SHA-256 integrity hashing - Fail-closed error handling with detailed diagnostics - IPC-based container-to-host verification (5s timeout) **MCP Tool:** clawsec_verify_skill_package - Verifies skill packages before installation - Returns: valid, recommendation (install/block/review), signer, algorithm - Prevents installation of tampered/malicious packages ## Phase 2: File Integrity Monitoring (~1,765 lines) Ports OpenClaw's soul-guardian to NanoClaw for critical file protection. **New Files:** - guardian/integrity-monitor.ts (711 lines): Core monitoring engine - guardian/policy.json (55 lines): NanoClaw-specific protection policy - mcp-tools/integrity-tools.ts (260 lines): 4 MCP tools for agents - host-services/integrity-handler.ts (349 lines): IPC handler integration - docs/INTEGRITY.md (470 lines): User documentation **Features:** - SHA-256 baseline tracking with tamper-evident audit logs - Auto-restore for critical files (registered_groups.json, CLAUDE.md) - Alert-only mode for non-critical files - Intentional change approval workflow - Hash-chained audit logging - Symlink protection and atomic file operations - Unified diff generation for drift analysis **MCP Tools:** - clawsec_check_integrity: Check files for unauthorized changes - clawsec_approve_change: Approve legitimate modifications - clawsec_integrity_status: View monitoring status - clawsec_verify_audit: Verify audit log integrity **Protected Files:** - CRITICAL: registered_groups.json (prevents group hijacking) - HIGH: CLAUDE.md files (prevents instruction poisoning) - MEDIUM: Container/host code (alerts on changes) - IGNORED: Conversations (expected to change) ## Shared Enhancements (+129 lines) **Updated: lib/signatures.ts** Added 5 new crypto utilities: - verifyDetachedSignature(): File-based Ed25519 verification - verifyDetachedSignatureWithDetails(): Diagnostic variant with error details - loadPublicKey(): PEM validation and security enforcement - sha256File(): File hashing (shared utility) - verifyFileHashes(): Batch drift detection **Updated: lib/types.ts** Added TypeScript interfaces for: - VerifySkillSignatureRequest/Response (Phase 1 IPC) - IntegrityCheckRequest/Response (Phase 2 IPC) - VerifySkillPackageParams (Phase 1 MCP tool) **Updated: host-services/ipc-handlers.ts** Added IPC handlers: - verify_skill_signature (Phase 1) - integrity_check, integrity_approve, integrity_status, integrity_verify_audit (Phase 2) ## Total Delivery - **New Code**: ~2,958 lines - **Files Created**: 11 new files - **Files Modified**: 3 existing files - **Documentation**: 740 lines across 2 comprehensive guides ## Architecture **Phase 1:** Container agents → MCP tool → IPC → Host verifier → Ed25519 crypto **Phase 2:** Container agents → MCP tools → IPC → Host service → File monitoring **Storage:** - Phase 1: Stateless (no persistent storage) - Phase 2: /workspace/project/data/soul-guardian/ (host-only) **Security Model:** - Ed25519 signatures verified with pinned ClawSec public key - SHA-256 baselines stored on host (containers cannot modify) - Hash-chained audit logs for tamper detection - Fail-closed error handling throughout - IPC-only access (no direct container mounts) ## Team Credits Designed and implemented by 5-agent Opus 4.6 team: - signature-verification-lead: Phase 1 implementation - integrity-monitoring-lead: Phase 2 implementation - shared-crypto: Cryptographic utilities - mcp-tools-architect: MCP tool schema standards - ipc-handler-architect: IPC protocol standards Coordination approach: 1. Design phase: Each agent analyzed and proposed solutions 2. Coordination phase: Aligned on shared components (crypto, IPC, storage) 3. Implementation phase: Parallel execution with peer support 4. Result: Zero conflicts, exceeded targets, complete documentation ## Integration NanoClaw users can now install ClawSec security features: **1. MCP Tools** (container): ```typescript import { clawsecTools } from '../../../skills/clawsec-nanoclaw/mcp-tools/advisory-tools.js'; import { verifySkillPackage } from '../../../skills/clawsec-nanoclaw/mcp-tools/signature-verification.js'; import { integrityTools } from '../../../skills/clawsec-nanoclaw/mcp-tools/integrity-tools.js'; ``` **2. IPC Handlers** (host): ```typescript import { registerClawSecHandlers } from '../skills/clawsec-nanoclaw/host-services/ipc-handlers.js'; ``` **3. Services** (host): ```typescript import { SkillSignatureVerifier } from '../skills/clawsec-nanoclaw/host-services/skill-signature-handler.js'; import { IntegrityService } from '../skills/clawsec-nanoclaw/host-services/integrity-handler.js'; ``` See docs/SKILL_SIGNING.md and docs/INTEGRITY.md for complete integration guides. Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * Fix SKILL.md format: proper YAML frontmatter, remove ASCII diagrams, focus on when-to-use * chore: align with contributors guidelines - set version 0.0.1, add version to SKILL.md frontmatter, complete SBOM * fix: use specific NanoClaw repo URL instead of wildcard pattern Change github.com/*/NanoClaw to github.com/qwibitai/NanoClaw to avoid matching unrelated projects in CVE advisory scanning. * docs: merge NanoClaw support into main README, move NANOCLAW.md to skill README - Add NanoClaw platform section in main README - Update supported platforms list (OpenClaw + NanoClaw) - Add monitored keywords for NanoClaw (WhatsApp-bot, baileys) - Document platform-specific advisory schema - Move NANOCLAW.md to skills/clawsec-nanoclaw/README.md * fix: resolve ESLint and TypeScript errors in clawsec-nanoclaw skill Fix all CI failures from prepare-to-push.sh for the nanoclaw-integration branch: ESLint fixes: - Add missing Node.js globals (Buffer, AbortController, clearTimeout, RequestInit) to eslint.config.js for TypeScript files - Add ambient declarations for host-provided variables (server, writeIpcFile, TASKS_DIR, groupFolder) in MCP tool template files - Wrap bare case statements in ipc-handlers.ts in a proper exported function - Replace @ts-ignore with @ts-expect-error in signatures.ts - Prefix unused variables with underscore (affectedVersion, keyDer, safeBasename, groupFolder) - Add eslint-disable directives for intentional any usage in template files - Change any to unknown in types.ts where appropriate TypeScript fixes: - Replace glob import with ambient namespace declaration (glob not in repo deps) - Fix Hash.hexdigest() to Hash.digest('hex') in integrity-monitor.ts - Fix unreachable type comparison (recommendation === 'install') in advisory-tools.ts Comment syntax fixes: - Convert block comments containing '*/30 * * * *' cron expressions to line comments to prevent premature comment termination in integrity-handler.ts and integrity-tools.ts Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * fix: implement missing MCP tools and align documentation with code - Rewrote signature-verification.ts with actual server.tool() implementation (was template string) - Fixed tool naming: clawsec_verify_signature -> clawsec_verify_skill_package - Added missing clawsec_refresh_cache to all documentation - Updated skill.json mcp_tools array from 4 to 9 tools (added Phase 1 & 2 tools) - All 9 MCP tools now verified: 4 advisory + 1 signature + 4 integrity Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
418 lines
12 KiB
TypeScript
418 lines
12 KiB
TypeScript
/**
|
|
* ClawSec Advisory Cache Manager for NanoClaw
|
|
*
|
|
* Manages fetching, verifying, and caching the ClawSec advisory feed.
|
|
* Runs on the host side (not in container).
|
|
*
|
|
* Security:
|
|
* - Ed25519 signature verification using Node.js crypto
|
|
* - Fail-closed policy: invalid signature = reject feed
|
|
* - TLS 1.2+ enforcement with certificate validation
|
|
* - Public key embedded (not user-modifiable)
|
|
* - Cache stored in host-managed directory
|
|
*/
|
|
|
|
import crypto from 'node:crypto';
|
|
import fs from 'node:fs/promises';
|
|
import https from 'node:https';
|
|
import path from 'node:path';
|
|
|
|
// ClawSec public key (from clawsec-signing-public.pem)
|
|
const PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----
|
|
MCowBQYDK2VwAyEAS7nijfMcUoOBCj4yOXJX+GYGv2pFl2Yaha1P4v5Cm6A=
|
|
-----END PUBLIC KEY-----`;
|
|
|
|
const CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes
|
|
const FEED_URL = 'https://clawsec.prompt.security/advisories/feed.json';
|
|
const FETCH_TIMEOUT_MS = 10000;
|
|
|
|
export interface Advisory {
|
|
id: string;
|
|
severity: string;
|
|
type?: string;
|
|
title?: string;
|
|
description?: string;
|
|
action?: string;
|
|
published?: string;
|
|
updated?: string;
|
|
affected: string[];
|
|
}
|
|
|
|
export interface FeedPayload {
|
|
version: string;
|
|
updated?: string;
|
|
advisories: Advisory[];
|
|
}
|
|
|
|
export interface AdvisoryCache {
|
|
feed: FeedPayload;
|
|
fetchedAt: string;
|
|
verified: boolean;
|
|
publicKeyFingerprint: string;
|
|
}
|
|
|
|
interface Logger {
|
|
info(msg: string | object, ...args: unknown[]): void;
|
|
error(msg: string | object, ...args: unknown[]): void;
|
|
warn(msg: string | object, ...args: unknown[]): void;
|
|
}
|
|
|
|
export class AdvisoryCacheManager {
|
|
private cache: AdvisoryCache | null = null;
|
|
private refreshPromise: Promise<void> | null = null;
|
|
private cacheFile: string;
|
|
private logger: Logger;
|
|
|
|
constructor(dataDir: string, logger: Logger) {
|
|
this.cacheFile = path.join(dataDir, 'clawsec-advisory-cache.json');
|
|
this.logger = logger;
|
|
}
|
|
|
|
/**
|
|
* Initialize cache manager. Loads cache from disk and refreshes if stale.
|
|
*/
|
|
async initialize(): Promise<void> {
|
|
await this.loadCacheFromDisk();
|
|
|
|
if (!this.cache || this.isCacheStale()) {
|
|
try {
|
|
await this.refresh();
|
|
} catch (error) {
|
|
this.logger.error({ error }, 'Failed to initialize advisory cache');
|
|
// Continue with stale cache if available
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Refresh advisory cache from remote feed.
|
|
* Thread-safe: prevents concurrent refreshes.
|
|
*/
|
|
async refresh(): Promise<void> {
|
|
// Prevent concurrent refreshes
|
|
if (this.refreshPromise) {
|
|
return this.refreshPromise;
|
|
}
|
|
|
|
this.refreshPromise = this._doRefresh();
|
|
try {
|
|
await this.refreshPromise;
|
|
} finally {
|
|
this.refreshPromise = null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get current cache. Returns null if cache is stale or missing.
|
|
*/
|
|
getCache(): AdvisoryCache | null {
|
|
if (!this.cache || this.isCacheStale()) {
|
|
return null;
|
|
}
|
|
return this.cache;
|
|
}
|
|
|
|
/**
|
|
* Get cache even if stale (for fallback scenarios)
|
|
*/
|
|
getCacheAllowStale(): AdvisoryCache | null {
|
|
return this.cache;
|
|
}
|
|
|
|
private async _doRefresh(): Promise<void> {
|
|
try {
|
|
this.logger.info('Refreshing advisory cache from ClawSec feed');
|
|
|
|
const feed = await this.fetchAndVerifyFeed();
|
|
const fingerprint = this.calculateKeyFingerprint();
|
|
|
|
this.cache = {
|
|
feed,
|
|
fetchedAt: new Date().toISOString(),
|
|
verified: true,
|
|
publicKeyFingerprint: fingerprint,
|
|
};
|
|
|
|
await this.saveCacheToDisk();
|
|
this.logger.info({
|
|
advisories: feed.advisories.length,
|
|
updated: feed.updated,
|
|
}, 'Advisory cache refreshed successfully');
|
|
} catch (error) {
|
|
this.logger.error({ error }, 'Failed to refresh advisory cache');
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
private isCacheStale(): boolean {
|
|
if (!this.cache) return true;
|
|
const age = Date.now() - Date.parse(this.cache.fetchedAt);
|
|
return age > CACHE_TTL_MS;
|
|
}
|
|
|
|
private async fetchAndVerifyFeed(): Promise<FeedPayload> {
|
|
// Fetch feed and signature in parallel
|
|
const [payloadRaw, signatureRaw] = await Promise.all([
|
|
this.secureFetch(FEED_URL),
|
|
this.secureFetch(`${FEED_URL}.sig`),
|
|
]);
|
|
|
|
// Verify Ed25519 signature
|
|
if (!this.verifySignature(payloadRaw, signatureRaw)) {
|
|
throw new Error('Feed signature verification failed (Ed25519)');
|
|
}
|
|
|
|
// Parse and validate
|
|
const feed = JSON.parse(payloadRaw) as FeedPayload;
|
|
if (!this.isValidFeed(feed)) {
|
|
throw new Error('Invalid feed format');
|
|
}
|
|
|
|
return feed;
|
|
}
|
|
|
|
private async secureFetch(url: string): Promise<string> {
|
|
return new Promise((resolve, reject) => {
|
|
// Create secure HTTPS agent with TLS 1.2+ enforcement
|
|
const agent = new https.Agent({
|
|
minVersion: 'TLSv1.2',
|
|
rejectUnauthorized: true,
|
|
ciphers: 'TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256',
|
|
});
|
|
|
|
const req = https.get(url, {
|
|
agent,
|
|
timeout: FETCH_TIMEOUT_MS,
|
|
headers: {
|
|
'User-Agent': 'NanoClaw/1.0',
|
|
'Accept': 'application/json,text/plain',
|
|
},
|
|
}, (res) => {
|
|
if (res.statusCode !== 200) {
|
|
reject(new Error(`HTTP ${res.statusCode} from ${url}`));
|
|
return;
|
|
}
|
|
|
|
let data = '';
|
|
res.on('data', (chunk) => { data += chunk; });
|
|
res.on('end', () => resolve(data));
|
|
res.on('error', reject);
|
|
});
|
|
|
|
req.on('error', reject);
|
|
req.on('timeout', () => {
|
|
req.destroy();
|
|
reject(new Error(`Timeout fetching ${url}`));
|
|
});
|
|
});
|
|
}
|
|
|
|
private verifySignature(payload: string, signatureBase64: string): boolean {
|
|
try {
|
|
// Decode base64 signature
|
|
const trimmed = signatureBase64.trim();
|
|
let encoded = trimmed;
|
|
|
|
// Handle JSON-wrapped signature: {"signature": "base64..."}
|
|
if (trimmed.startsWith('{')) {
|
|
try {
|
|
const parsed = JSON.parse(trimmed);
|
|
if (typeof parsed.signature === 'string') {
|
|
encoded = parsed.signature;
|
|
}
|
|
} catch {
|
|
// Not JSON, use as-is
|
|
}
|
|
}
|
|
|
|
const normalized = encoded.replace(/\s+/g, '');
|
|
const sigBuffer = Buffer.from(normalized, 'base64');
|
|
|
|
// Verify Ed25519 signature using Node.js crypto
|
|
const publicKey = crypto.createPublicKey(PUBLIC_KEY_PEM);
|
|
return crypto.verify(
|
|
null, // algorithm null = Ed25519 raw mode
|
|
Buffer.from(payload, 'utf8'),
|
|
publicKey,
|
|
sigBuffer
|
|
);
|
|
} catch (error) {
|
|
this.logger.warn({ error }, 'Signature verification failed');
|
|
return false;
|
|
}
|
|
}
|
|
|
|
private isValidFeed(feed: unknown): feed is FeedPayload {
|
|
if (typeof feed !== 'object' || !feed) return false;
|
|
const f = feed as FeedPayload;
|
|
|
|
if (typeof f.version !== 'string' || !f.version.trim()) return false;
|
|
if (!Array.isArray(f.advisories)) return false;
|
|
|
|
// Validate each advisory
|
|
return f.advisories.every((a: unknown) => {
|
|
if (typeof a !== 'object' || !a) return false;
|
|
const advisory = a as Advisory;
|
|
|
|
return (
|
|
typeof advisory.id === 'string' &&
|
|
advisory.id.trim() !== '' &&
|
|
typeof advisory.severity === 'string' &&
|
|
advisory.severity.trim() !== '' &&
|
|
Array.isArray(advisory.affected) &&
|
|
advisory.affected.every(
|
|
(affected) => typeof affected === 'string' && affected.trim() !== ''
|
|
)
|
|
);
|
|
});
|
|
}
|
|
|
|
private calculateKeyFingerprint(): string {
|
|
const publicKey = crypto.createPublicKey(PUBLIC_KEY_PEM);
|
|
const der = publicKey.export({ type: 'spki', format: 'der' });
|
|
return crypto.createHash('sha256').update(der).digest('hex');
|
|
}
|
|
|
|
private async loadCacheFromDisk(): Promise<void> {
|
|
try {
|
|
const data = await fs.readFile(this.cacheFile, 'utf8');
|
|
const parsed = JSON.parse(data) as AdvisoryCache;
|
|
|
|
// Validate cache structure
|
|
if (this.isValidCache(parsed)) {
|
|
this.cache = parsed;
|
|
this.logger.info({
|
|
age: Date.now() - Date.parse(parsed.fetchedAt),
|
|
advisories: parsed.feed.advisories.length,
|
|
}, 'Loaded advisory cache from disk');
|
|
} else {
|
|
this.logger.warn('Invalid cache format on disk, discarding');
|
|
this.cache = null;
|
|
}
|
|
} catch {
|
|
this.cache = null;
|
|
}
|
|
}
|
|
|
|
private isValidCache(cache: unknown): cache is AdvisoryCache {
|
|
if (typeof cache !== 'object' || !cache) return false;
|
|
const c = cache as AdvisoryCache;
|
|
|
|
return (
|
|
this.isValidFeed(c.feed) &&
|
|
typeof c.fetchedAt === 'string' &&
|
|
typeof c.verified === 'boolean' &&
|
|
typeof c.publicKeyFingerprint === 'string'
|
|
);
|
|
}
|
|
|
|
private async saveCacheToDisk(): Promise<void> {
|
|
if (!this.cache) return;
|
|
|
|
try {
|
|
await fs.mkdir(path.dirname(this.cacheFile), { recursive: true });
|
|
|
|
// Atomic write: temp file then rename
|
|
const tempFile = `${this.cacheFile}.tmp`;
|
|
await fs.writeFile(tempFile, JSON.stringify(this.cache, null, 2), 'utf8');
|
|
await fs.rename(tempFile, this.cacheFile);
|
|
|
|
this.logger.info({ path: this.cacheFile }, 'Advisory cache saved to disk');
|
|
} catch (error) {
|
|
this.logger.error({ error }, 'Failed to save advisory cache to disk');
|
|
throw error;
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Helper: Match advisories against installed skills
|
|
*/
|
|
export function findAdvisoryMatches(
|
|
advisories: Advisory[],
|
|
skills: Array<{ name: string; version: string | null; dirName: string }>
|
|
): Array<{
|
|
advisory: Advisory;
|
|
skill: { name: string; version: string | null; dirName: string };
|
|
matchedAffected: string[];
|
|
}> {
|
|
const matches: Array<{
|
|
advisory: Advisory;
|
|
skill: { name: string; version: string | null; dirName: string };
|
|
matchedAffected: string[];
|
|
}> = [];
|
|
|
|
for (const advisory of advisories) {
|
|
for (const skill of skills) {
|
|
const matchedAffected: string[] = [];
|
|
|
|
for (const affected of advisory.affected) {
|
|
// Parse affected specifier: skill-name or skill-name@version
|
|
const atIndex = affected.lastIndexOf('@');
|
|
const affectedName = atIndex > 0 ? affected.slice(0, atIndex) : affected;
|
|
const _affectedVersion = atIndex > 0 ? affected.slice(atIndex + 1) : '*';
|
|
|
|
// Match by name or directory name
|
|
if (affectedName === skill.name || affectedName === skill.dirName) {
|
|
// TODO: implement version range matching
|
|
matchedAffected.push(affected);
|
|
}
|
|
}
|
|
|
|
if (matchedAffected.length > 0) {
|
|
matches.push({ advisory, skill, matchedAffected });
|
|
}
|
|
}
|
|
}
|
|
|
|
return matches;
|
|
}
|
|
|
|
/**
|
|
* Helper: Evaluate safety recommendation for a skill
|
|
*/
|
|
export function evaluateSkillSafety(advisories: Advisory[]): {
|
|
safe: boolean;
|
|
recommendation: 'install' | 'block' | 'review';
|
|
reason: string;
|
|
} {
|
|
if (advisories.length === 0) {
|
|
return { safe: true, recommendation: 'install', reason: 'No advisories found' };
|
|
}
|
|
|
|
const hasMalicious = advisories.some((a) => a.type === 'malicious');
|
|
const hasRemoveAction = advisories.some((a) => a.action === 'remove');
|
|
const hasCritical = advisories.some((a) => a.severity === 'critical');
|
|
const hasHigh = advisories.some((a) => a.severity === 'high');
|
|
|
|
if (hasMalicious || hasRemoveAction) {
|
|
return {
|
|
safe: false,
|
|
recommendation: 'block',
|
|
reason: 'Malicious skill or removal recommended',
|
|
};
|
|
}
|
|
|
|
if (hasCritical) {
|
|
return {
|
|
safe: false,
|
|
recommendation: 'block',
|
|
reason: 'Critical security advisory',
|
|
};
|
|
}
|
|
|
|
if (hasHigh) {
|
|
return {
|
|
safe: false,
|
|
recommendation: 'review',
|
|
reason: 'High severity advisory - user review recommended',
|
|
};
|
|
}
|
|
|
|
return {
|
|
safe: false,
|
|
recommendation: 'review',
|
|
reason: 'Advisory found - review before installing',
|
|
};
|
|
}
|