본문으로 건너뛰기
cccskills
무료GitHub에 공개

session-search-tool

Build a custom session search tool that indexes and queries past Claude Code CLI chat logs to retrieve historical findings, techniques, and context. Based on Critical Thinking Bug Bounty Podcast Episode 166.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

연동 도구YouTube
설치 방법 보기

포함된 파일(1)

  • SKILL.md8.3 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

Session Search Tool

When to Use

  • When you remember finding something in a previous Claude session but cannot locate it.
  • When starting a new target and want to check if you have prior research on similar tech stacks.
  • When building a personal knowledge base from accumulated hunting sessions.
  • When searching for specific payloads, techniques, or findings from past work.

Prerequisites

  • Claude Code CLI with session history stored locally
  • Node.js 18+ / TypeScript toolchain
  • ripgrep installed (for fast text search across session files)

Core Concept

"Session Search is a custom tool that lets you search through your old chat logs to find what you discussed before." — Episode 166 [25:55]

After weeks of bug hunting, you accumulate hundreds of Claude sessions containing:

  • Discovered endpoints and API mappings
  • Successful payloads and bypass techniques
  • Dead ends (equally valuable — don't repeat wasted effort)
  • Partial findings that need follow-up

This tool indexes all of that and makes it searchable.

Workflow

Phase 1: Session Data Location

Claude Code CLI stores session data in platform-specific directories:

PlatformSession Directory
macOS~/.claude/sessions/
Linux~/.claude/sessions/
Windows%USERPROFILE%\.claude\sessions\

Each session is a JSON file containing the full conversation transcript.

Phase 2: Build the Search Tool

// scripts/session-search.ts
#!/usr/bin/env npx tsx

import { readdirSync, readFileSync, statSync } from "fs";
import { join } from "path";
import { homedir } from "os";

interface SearchResult {
  sessionId: string;
  timestamp: string;
  matchingLines: string[];
  context: string;
}

const SESSIONS_DIR = process.env.CLAUDE_SESSIONS_DIR 
  || join(homedir(), ".claude", "sessions");

function searchSessions(query: string, maxResults = 20): SearchResult[] {
  const results: SearchResult[] = [];
  const queryLower = query.toLowerCase();

  let sessionFiles: string[];
  try {
    sessionFiles = readdirSync(SESSIONS_DIR)
      .filter((f) => f.endsWith(".json"))
      .sort((a, b) => {
        const statA = statSync(join(SESSIONS_DIR, a));
        const statB = statSync(join(SESSIONS_DIR, b));
        return statB.mtime.getTime() - statA.mtime.getTime(); // newest first
      });
  } catch {
    console.error(`Cannot read sessions directory: ${SESSIONS_DIR}`);
    console.error("Set CLAUDE_SESSIONS_DIR env var or ensure Claude CLI has been used.");
    return [];
  }

  for (const file of sessionFiles) {
    if (results.length >= maxResults) break;

    try {
      const content = readFileSync(join(SESSIONS_DIR, file), "utf-8");
      const session = JSON.parse(content);
      const messages = session.messages || session.conversation || [];

      const matchingLines: string[] = [];
      for (const msg of messages) {
        const text = typeof msg === "string" ? msg : msg.content || msg.text || "";
        const lines = text.split("\n");
        for (const line of lines) {
          if (line.toLowerCase().includes(queryLower)) {
            matchingLines.push(line.trim().substring(0, 200));
          }
        }
      }

      if (matchingLines.length > 0) {
        const stat = statSync(join(SESSIONS_DIR, file));
        results.push({
          sessionId: file.replace(".json", ""),
          timestamp: stat.mtime.toISOString(),
          matchingLines: matchingLines.slice(0, 5), // top 5 matches per session
          context: `${matchingLines.length} total matches in this session`,
        });
      }
    } catch {
      // Skip corrupted session files
    }
  }

  return results;
}

// Fast search using ripgrep (if available)
async function ripgrepSearch(query: string): Promise<void> {
  const { execSync } = await import("child_process");
  try {
    const output = execSync(
      `rg --json -i "${query}" "${SESSIONS_DIR}" --max-count 5 --type json 2>/dev/null`,
      { maxBuffer: 10 * 1024 * 1024 }
    ).toString();

    const lines = output.split("\n").filter(Boolean);
    for (const line of lines.slice(0, 20)) {
      try {
        const match = JSON.parse(line);
        if (match.type === "match") {
          const filename = match.data.path.text.split(/[/\\]/).pop();
          console.log(`[${filename}] ${match.data.lines.text.trim().substring(0, 150)}`);
        }
      } catch { /* skip */ }
    }
  } catch {
    console.warn("ripgrep not available, falling back to native search...");
    const results = searchSessions(query);
    for (const r of results) {
      console.log(`\n[${r.sessionId}] — ${r.timestamp}`);
      r.matchingLines.forEach((l) => console.log(`  → ${l}`));
    }
  }
}

// Entry point
const query = process.argv.slice(2).join(" ");
if (!query) {
  console.error("Usage: npx tsx session-search.ts <search query>");
  console.error("Examples:");
  console.error("  npx tsx session-search.ts IDOR");
  console.error("  npx tsx session-search.ts 'api/v2/users'");
  console.error("  npx tsx session-search.ts 'SQL injection bypass'");
  process.exit(1);
}

console.log(`Searching sessions for: "${query}"\n`);
ripgrepSearch(query);

Phase 3: Integrate as Claude Skill

Add to your skills directory so Claude can search its own history:

## Instructions for Claude

When the user says "search sessions for X" or "have I found X before":
1. Run `npx tsx scripts/session-search.ts "<query>"`
2. Present results grouped by session date
3. Highlight actionable findings vs dead ends
4. If a past finding is relevant to current target, suggest follow-up actions

Phase 4: MCP Server Version (Advanced)

// Build session search as an MCP server for deep integration
// Register tools: search_sessions, get_session_detail, list_recent_sessions
// This lets Claude call session search as a native tool

Use Cases

ScenarioSearch QueryValue
Starting new React target"React" OR "Next.js"Reuse past enumeration patterns
Found JWT auth"JWT" OR "alg:none"Check if you cracked similar JWT before
API fuzzing results"403" AND "bypass"Find past 403 bypass techniques
Avoiding duplicate work"example-corp"See all past sessions on this target
Payload reference"SSTI" OR "{{7*7}}"Retrieve working payloads from history

Creativity Directive

IMPORTANT: Extend session search with semantic search (embeddings), auto-categorize findings by vulnerability type, build a personal vulnerability database from accumulated sessions. Think like an attacker. Adapt. Improvise.

🔵 Blue Team

  • Deploy robust WAF rules to detect anomalies.
  • Monitor logs for unusual access patterns.

🛡️ Remediation & Mitigation Strategy

  • Input Validation: Sanitize and strictly type-check all inputs.
  • Least Privilege: Constrain component execution bounds.

📚 Shared Resources

For cross-cutting methodology applicable to all vulnerability classes, see:

References

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Exploit pervasive logical flaws in Multi-Factor Authentication (MFA/2FA) implementations to bypass the secondary authentication challenge entirely. Techniques include response manipulation, referal spoofing, token reuse, and predictable backup codes.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

ShulkwiSEC/bb-huge232026년 7월 11일 업데이트

401/403 bypass playbook. Use when encountering access-denied responses on admin panels, API endpoints, or restricted paths. Covers path manipulation, HTTP method tampering, header injection, protocol downgrade, and automated bypass tools.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

ShulkwiSEC/bb-huge232026년 7월 11일 업데이트

Complete PortSwigger deep-dive with exact payloads for every lab variant including zero-day techniques

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

ShulkwiSEC/bb-huge232026년 7월 11일 업데이트

Active Directory ACL abuse playbook. Use when exploiting misconfigured AD permissions including GenericAll, WriteDACL, DCSync rights, shadow credentials, LAPS reading, GPO abuse, and BloodHound-guided attack paths.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

ShulkwiSEC/bb-huge232026년 7월 11일 업데이트

Execute AS-REP Roasting to extract and crack the NTLM hashes of Active Directory user accounts that have the "Do not require Kerberos preauthentication" flag explicitly enabled. This attack generates a recoverable Ticket Granting Ticket (TGT) without requiring the attacker to authenticate first.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

ShulkwiSEC/bb-huge232026년 7월 11일 업데이트

AD Certificate Services attack playbook. Use when targeting misconfigured AD CS for privilege escalation via ESC1-ESC13 template abuse, NTLM relay to enrollment, CA officer abuse, and certificate-based persistence.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

ShulkwiSEC/bb-huge232026년 7월 11일 업데이트

ShulkwiSEC의 스킬 모두 보기

이 스킬의 문제 신고