Skip to main content
Glama

js.extract_secrets

Extract potential API keys, tokens, and secrets from JavaScript source code using heuristic analysis for security testing.

Instructions

Heuristically extract potential API keys, tokens, and secrets from JS

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sourceYesJavaScript source code

Implementation Reference

  • The main handler function that heuristically extracts potential API keys, tokens, AWS keys, Google API keys, and secret candidates from JavaScript source code using various regex patterns. It categorizes and deduplicates findings and returns a structured result.
    async ({ source }: any): Promise<ToolResult> => {
      try {
        const secrets: any = {
          apiKeys: [],
          tokens: [],
          passwords: [],
          awsKeys: [],
          googleKeys: [],
          candidates: [],
        };
    
        // API Key patterns
        const apiKeyPatterns = [
          /(?:api[_-]?key|apikey)[\s:=]+["'`]([A-Za-z0-9_\-]{20,})["'`]/gi,
          /(?:secret[_-]?key|secretkey)[\s:=]+["'`]([A-Za-z0-9_\-]{20,})["'`]/gi,
        ];
    
        // Token patterns
        const tokenPatterns = [
          /(?:token|access[_-]?token)[\s:=]+["'`]([A-Za-z0-9_\-]{20,})["'`]/gi,
          /(?:bearer|authorization)[\s:]+["'`]?([A-Za-z0-9_\-\.]{20,})["'`]?/gi,
        ];
    
        // AWS keys
        const awsPattern = /AKIA[0-9A-Z]{16}/g;
    
        // Google API keys
        const googlePattern = /AIza[0-9A-Za-z\-_]{35}/g;
    
        // Extract matches
        apiKeyPatterns.forEach((pattern) => {
          let match: RegExpExecArray | null;
          while ((match = pattern.exec(source)) !== null) {
            secrets.apiKeys.push(match[1]);
          }
        });
    
        tokenPatterns.forEach((pattern) => {
          let match: RegExpExecArray | null;
          while ((match = pattern.exec(source)) !== null) {
            secrets.tokens.push(match[1]);
          }
        });
    
        const awsMatches = source.match(awsPattern) || [];
        secrets.awsKeys = Array.from(new Set(awsMatches));
    
        const googleMatches = source.match(googlePattern) || [];
        secrets.googleKeys = Array.from(new Set(googleMatches));
    
        // General long strings that might be secrets
        const candidatePattern = /["'`]([A-Za-z0-9_\-]{32,})["'`]/g;
        let candidateMatch: RegExpExecArray | null;
        while ((candidateMatch = candidatePattern.exec(source)) !== null) {
          const candidate = candidateMatch[1];
          // Filter out URLs and common false positives
          if (
            !candidate.startsWith('http') &&
            !candidate.includes('/') &&
            candidate.length < 200
          ) {
            secrets.candidates.push(candidate);
          }
        }
    
        // Deduplicate
        secrets.apiKeys = Array.from(new Set(secrets.apiKeys));
        secrets.tokens = Array.from(new Set(secrets.tokens));
        secrets.candidates = Array.from(new Set(secrets.candidates)).slice(0, 50);
    
        return formatToolResult(true, {
          ...secrets,
          summary: {
            totalApiKeys: secrets.apiKeys.length,
            totalTokens: secrets.tokens.length,
            totalAwsKeys: secrets.awsKeys.length,
            totalGoogleKeys: secrets.googleKeys.length,
            totalCandidates: secrets.candidates.length,
          },
        });
      } catch (error: any) {
        return formatToolResult(false, null, error.message);
      }
    }
  • The input schema for the tool, requiring a 'source' string parameter containing the JavaScript code to analyze.
    {
      description: 'Heuristically extract potential API keys, tokens, and secrets from JS',
      inputSchema: {
        type: 'object',
        properties: {
          source: { type: 'string', description: 'JavaScript source code' },
        },
        required: ['source'],
      },
    },
  • The server.tool() call that registers the 'js.extract_secrets' tool with its schema and inline handler function.
      'js.extract_secrets',
      {
        description: 'Heuristically extract potential API keys, tokens, and secrets from JS',
        inputSchema: {
          type: 'object',
          properties: {
            source: { type: 'string', description: 'JavaScript source code' },
          },
          required: ['source'],
        },
      },
      async ({ source }: any): Promise<ToolResult> => {
        try {
          const secrets: any = {
            apiKeys: [],
            tokens: [],
            passwords: [],
            awsKeys: [],
            googleKeys: [],
            candidates: [],
          };
    
          // API Key patterns
          const apiKeyPatterns = [
            /(?:api[_-]?key|apikey)[\s:=]+["'`]([A-Za-z0-9_\-]{20,})["'`]/gi,
            /(?:secret[_-]?key|secretkey)[\s:=]+["'`]([A-Za-z0-9_\-]{20,})["'`]/gi,
          ];
    
          // Token patterns
          const tokenPatterns = [
            /(?:token|access[_-]?token)[\s:=]+["'`]([A-Za-z0-9_\-]{20,})["'`]/gi,
            /(?:bearer|authorization)[\s:]+["'`]?([A-Za-z0-9_\-\.]{20,})["'`]?/gi,
          ];
    
          // AWS keys
          const awsPattern = /AKIA[0-9A-Z]{16}/g;
    
          // Google API keys
          const googlePattern = /AIza[0-9A-Za-z\-_]{35}/g;
    
          // Extract matches
          apiKeyPatterns.forEach((pattern) => {
            let match: RegExpExecArray | null;
            while ((match = pattern.exec(source)) !== null) {
              secrets.apiKeys.push(match[1]);
            }
          });
    
          tokenPatterns.forEach((pattern) => {
            let match: RegExpExecArray | null;
            while ((match = pattern.exec(source)) !== null) {
              secrets.tokens.push(match[1]);
            }
          });
    
          const awsMatches = source.match(awsPattern) || [];
          secrets.awsKeys = Array.from(new Set(awsMatches));
    
          const googleMatches = source.match(googlePattern) || [];
          secrets.googleKeys = Array.from(new Set(googleMatches));
    
          // General long strings that might be secrets
          const candidatePattern = /["'`]([A-Za-z0-9_\-]{32,})["'`]/g;
          let candidateMatch: RegExpExecArray | null;
          while ((candidateMatch = candidatePattern.exec(source)) !== null) {
            const candidate = candidateMatch[1];
            // Filter out URLs and common false positives
            if (
              !candidate.startsWith('http') &&
              !candidate.includes('/') &&
              candidate.length < 200
            ) {
              secrets.candidates.push(candidate);
            }
          }
    
          // Deduplicate
          secrets.apiKeys = Array.from(new Set(secrets.apiKeys));
          secrets.tokens = Array.from(new Set(secrets.tokens));
          secrets.candidates = Array.from(new Set(secrets.candidates)).slice(0, 50);
    
          return formatToolResult(true, {
            ...secrets,
            summary: {
              totalApiKeys: secrets.apiKeys.length,
              totalTokens: secrets.tokens.length,
              totalAwsKeys: secrets.awsKeys.length,
              totalGoogleKeys: secrets.googleKeys.length,
              totalCandidates: secrets.candidates.length,
            },
          });
        } catch (error: any) {
          return formatToolResult(false, null, error.message);
        }
      }
    );
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions 'heuristically extract,' implying an approximate or pattern-based method, but doesn't detail accuracy, limitations, output format, or performance characteristics (e.g., speed, resource usage). This leaves significant gaps for a tool performing security-sensitive extraction.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that directly states the tool's purpose without unnecessary words. It's front-loaded with the core action and resource, making it easy to understand at a glance.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a tool with no annotations and no output schema, the description is insufficient. It lacks details on behavioral traits (e.g., what 'heuristically' entails, error handling), usage context, and output expectations. Given the complexity of secret extraction and the absence of structured data, more comprehensive guidance is needed.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has 100% description coverage, with the 'source' parameter clearly documented as 'JavaScript source code.' The description adds no additional parameter semantics beyond this, as it doesn't specify format requirements, size limits, or examples. Given the high schema coverage, a baseline score of 3 is appropriate.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose with a specific verb ('extract') and resource ('potential API keys, tokens, and secrets'), and specifies the source material ('from JS'). However, it doesn't explicitly differentiate from sibling tools like 'js.analyze' or 'training.extract_from_writeup', which might have overlapping functionality.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention prerequisites, context (e.g., for security testing vs. code analysis), or compare it to siblings like 'js.analyze' or 'security.test_*' tools that might handle similar tasks.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/telmon95/VulneraMCP'

If you have feedback or need assistance with the MCP directory API, please join our Discord server