Skip to content

feat: goja_nodejs libraries [WIP] #6241

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 3 commits into
base: dev
Choose a base branch
from

Conversation

dwisiswant0
Copy link
Member

@dwisiswant0 dwisiswant0 commented May 22, 2025

Proposed changes

Easy to extend JavaScript lib by bundling. #6181

Currently bundled:

assert
id: javascript-assert

info:
  name: JavaScript Assert Testing Template
  author: dwisiswant0
  severity: info
  description: A template demonstrating various assertion methods using Node.js assert module
  tags: js,test,assert

javascript:
  - code: |
      const assert = require('@core/assert');

      const obj1 = { a: 1, b: { c: 2 } };
      const obj2 = { a: 1, b: { c: 2 } };
      const obj3 = { a: 1, b: { c: 3 } };
      const arr1 = [1, 2, 3];
      const arr2 = [1, 2, 3];

      let result = {
        tests: []
      };

      // Basic assertion tests
      try {
        assert.strictEqual(1 + 1, 2);
        result.tests.push({ name: 'strictEqual', success: true });
      } catch (e) {
        result.tests.push({ name: 'strictEqual', success: false, error: e.message });
      }

      // Deep equality test
      assert.deepStrictEqual(obj1, obj2);
      try {
        result.tests.push({ name: 'deepStrictEqual', success: true });
      } catch (e) {
        result.tests.push({ name: 'deepStrictEqual', success: false, error: e.message });
      }

      // Array comparison
      try {
        assert.deepStrictEqual(arr1, arr2);
        result.tests.push({ name: 'arrayComparison', success: true });
      } catch (e) {
        result.tests.push({ name: 'arrayComparison', success: false, error: e.message });
      }

      // Not equal assertion
      try {
        assert.notDeepStrictEqual(obj1, obj3);
        result.tests.push({ name: 'notDeepStrictEqual', success: true });
      } catch (e) {
        result.tests.push({ name: 'notDeepStrictEqual', success: false, error: e.message });
      }

      // Type checking
      try {
        assert.ok(typeof obj1 === 'object');
        result.tests.push({ name: 'typeCheck', success: true });
      } catch (e) {
        result.tests.push({ name: 'typeCheck', success: false, error: e.message });
      }

      // Testing for thrown errors
      try {
        assert.throws(() => {
          throw new Error('Test error');
        }, Error);
        result.tests.push({ name: 'errorThrow', success: true });
      } catch (e) {
        result.tests.push({ name: 'errorThrow', success: false, error: e.message });
      }

      // Testing regex matches
      try {
        assert.match('hello world', /^hello/);
        result.tests.push({ name: 'regexMatch', success: true });
      } catch (e) {
        result.tests.push({ name: 'regexMatch', success: false, error: e.message });
      }

      dump_json({
        success: result.tests.every(test => test.success),
        data: result
      });
buffer
id: javascript-buffer

info:
  name: JavaScript Buffer
  author: dwisiswant0
  severity: info
  tags: js,test

javascript:
  - code: |
      const { Buffer } = require('@core/buffer');
      const buf1 = Buffer.from('Hello World', 'utf8');
      const buf2 = Buffer.alloc(10);
      const buf3 = Buffer.from([0x48, 0x65, 0x6c, 0x6c, 0x6f]);

      let result = {
        base64: buf1.toString('base64'),
        hex: buf1.toString('hex'),
        length: buf1.length,
        compare: Buffer.compare(buf1, buf3),
        concat: Buffer.concat([buf1, buf3]).toString(),
        includes: buf1.includes('World'),
        slice: buf1.slice(0, 5).toString()
      };

      buf2.write('Test');
      
      let containsPattern = buf1.indexOf('World') !== -1;

      dump_json({
        success: true,
        response: true,
        data: result,
        contains_pattern: containsPattern,
        modified_buffer: buf2.toString()
      })
crypto
id: javascript-crypto

info:
  name: JavaScript Crypto Operations Demo
  author: dwisiswant0
  severity: info
  description: Template demonstrating comprehensive cryptographic operations using crypto-js library
  tags: js,crypto,test

javascript:
  - code: |
      const crypto = require('@core/crypto');
      const { Buffer } = require('@core/buffer');
      
      const plainText = 'Hello, Nuclei!';
      const secretKey = 'nuclei-secret-key';
      const randomBytes = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
      
      const sha256Hash = crypto.createHash('sha256').update(plainText).digest('hex');
      const md5Hash = crypto.createHash('md5').update(plainText).digest('hex');
      
      const hmacSha256 = crypto.createHmac('sha256', secretKey)
        .update(plainText)
        .digest('hex');
      
      const cipher = crypto.createCipher('aes-256-cbc', secretKey);
      let encrypted = cipher.update(plainText, 'utf8', 'hex');
      encrypted += cipher.final('hex');
      
      const decipher = crypto.createDecipher('aes-256-cbc', secretKey);
      let decrypted = decipher.update(encrypted, 'hex', 'utf8');
      decrypted += decipher.final('utf8');
      
      const base64Encoded = Buffer.from(plainText).toString('base64');
      const base64Decoded = Buffer.from(base64Encoded, 'base64').toString('utf8');
      
      dump_json({
        plaintext: plainText,
        secret_key: secretKey,
        random_bytes: randomBytes.toString('hex'),
        hashes: {
          sha256: sha256Hash,
          md5: md5Hash
        },
        hmac_sha256: hmacSha256,
        encryption: {
          encrypted_hex: encrypted,
          decrypted: decrypted
        },
        base64: {
          encoded: base64Encoded,
          decoded: base64Decoded
        }
      });
events
id: javascript-events

info:
  name: JavaScript Events Module Test
  author: dwisiswant0
  severity: info
  description: Tests Node.js Events module functionality using various EventEmitter features
  tags: js,test

javascript:
  - code: |
      const { EventEmitter } = require('@core/events');

      class ProcessManager extends EventEmitter {
        constructor() {
          super();
          this.taskCount = 0;
          // Set max listeners to prevent memory leaks
          this.setMaxListeners(15);
        }

        executeTask(taskName) {
          this.taskCount++;
          this.emit('taskStart', { task: taskName, id: this.taskCount });
          
          // Execute task immediately
          if (taskName === 'risky-task') {
            this.emit('error', new Error('Task failed'));
          } else {
            this.emit('taskComplete', { task: taskName, id: this.taskCount });
          }
        }
      }

      const manager = new ProcessManager();
      let results = {
        startedTasks: [],
        completedTasks: [],
        errors: [],
        listenerCounts: {}
      };

      manager.on('taskStart', (data) => {
        results.startedTasks.push(data);
      });

      manager.once('taskComplete', (data) => {
        results.completedTasks.push(data);
      });

      manager.on('error', (error) => {
        results.errors.push(error.message);
      });

      const tempListener = () => console.log('Temporary');
      manager.on('taskComplete', tempListener);
      manager.removeListener('taskComplete', tempListener);

      manager.executeTask('normal-task');
      manager.executeTask('risky-task');

      results.listenerCounts = {
        taskStart: manager.listenerCount('taskStart'),
        taskComplete: manager.listenerCount('taskComplete'),
        error: manager.listenerCount('error')
      };

      results.eventNames = manager.eventNames();

      dump_json({
        success: true,
        data: results,
        validation: {
          hasStartEvents: results.startedTasks.length > 0,
          hasErrorEvents: results.errors.length > 0,
          hasListeners: Object.values(results.listenerCounts).some(count => count > 0)
        }
      });
punycode
id: javascript-punycode

info:
  name: JavaScript Punycode Operations
  author: dwisiswant0
  severity: info
  description: Template demonstrating various punycode operations for IDN and Unicode string handling
  tags: js,punycode,test

javascript:
  - code: |
      const punycode = require('@core/punycode');

      const testCases = {
        unicode_domain: 'mañana.com',
        cjk_chars: '添加.com',
        complex_idn: 'üñîçødé.com',
        emoji_domain: '🌍.com',
        ascii: 'xn--maana-pta.com'
      };

      const results = {
        original_strings: testCases,
        encoding_results: {},
        decoding_results: {},
        domain_analysis: {}
      };

      for (const [key, value] of Object.entries(testCases)) {
        const parts = value.split('.');
        const encoded = parts.map(part => {
          try {
            return punycode.encode(part);
          } catch (e) {
            return part;
          }
        }).join('.');

        const decoded = parts.map(part => {
          try {
            return part.startsWith('xn--') ? punycode.decode(part.slice(4)) : part;
          } catch (e) {
            return part;
          }
        }).join('.');

        results.encoding_results[key] = encoded;
        results.decoding_results[key] = decoded;
        results.domain_analysis[key] = {
          is_ascii: /^[\x00-\x7F]+$/.test(value),
          contains_idn: value.includes('xn--'),
          unicode_length: value.length,
          ascii_length: encoded.length
        };
      }

      results.punycode_info = {
        ucs2: {
          decode: punycode.ucs2.decode('Hello ⚡').join(','),
          encode: punycode.ucs2.encode([72, 101, 108, 108, 111, 32, 9889])
        },
        version: punycode.version
      };

      dump_json(results);
string_decoder
id: javascript-string-decoder

info:
  name: JavaScript StringDecoder Operations
  author: dwisiswant0
  severity: info
  description: Template demonstrating various string decoder operations using string_decoder module
  tags: js,string-decoder,test

javascript:
  - code: |
      const StringDecoder = require('@core/string_decoder').StringDecoder;
      const Buffer = require('@core/buffer').Buffer;

      const utf8Decoder = new StringDecoder('utf8');
      const utf16leDecoder = new StringDecoder('utf16le');
      const base64Decoder = new StringDecoder('base64');

      const testBuffer = Buffer.from('Hello 👋 World! 🌍', 'utf8');
      const utf16Buffer = Buffer.from('48656c6c6f20f09f918b20576f726c6421', 'hex');
      const incompleteBuffer = Buffer.from([0xE2, 0x82]); // Incomplete UTF-8 sequence

      const results = {
        utf8Basic: utf8Decoder.write(testBuffer),
        incompleteSeq: {
          firstWrite: utf8Decoder.write(incompleteBuffer),
          end: utf8Decoder.end(), // Get any remaining incomplete sequence
        },
        utf16leTest: utf16leDecoder.write(utf16Buffer),
        base64Test: {
          encoded: Buffer.from('SGVsbG8gV29ybGQh').toString('base64'),
          decoded: base64Decoder.write(Buffer.from('SGVsbG8gV29ybGQh', 'base64')),
        },
        incrementalDecode: {
          part1: utf8Decoder.write(Buffer.from('Hello')),
          part2: utf8Decoder.write(Buffer.from(' World')),
          final: utf8Decoder.end()
        }
      };

      dump_json(results);
url
id: javascript-url

info:
  name: JavaScript URL Operations
  author: dwisiswant0
  severity: info
  description: Template demonstrating various URL operations using url module
  tags: js,url,test

javascript:
  - code: |
      const url = require('@core/url');
      const urls = {
        simple: 'https://example.com/path?query=123#hash',
        complex: 'https://user:[email protected]:8080/p/a/t/h?query=string&foo=bar#hash',
        relative: '/foo/bar?baz=qux#fragment',
        withAuth: 'http://username:[email protected]/',
        withIPv6: 'http://[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:8080/path',
        withEncoded: 'https://example.com/path%20with%20spaces?q=hello%20world'
      };

      const results = {
        parsed: url.parse(urls.complex, true),
        formatted: url.format({
          protocol: 'https',
          hostname: 'example.com',
          pathname: '/api/v1/users',
          query: { id: '123', filter: 'active' }
        }),
        parseNoQuery: url.parse(urls.simple, false),
        parseWithQuery: url.parse(urls.simple, true),
        resolved: {
          case1: url.resolve('https://example.com/', '/path'),
          case2: url.resolve('https://example.com/base/', '../other'),
          case3: url.resolve('https://example.com/base/', 'https://other.com/')
        },
        special: {
          ipv6: url.parse(urls.withIPv6),
          auth: url.parse(urls.withAuth),
          encoded: url.parse(urls.withEncoded)
        },
        components: {
          protocol: url.parse(urls.complex).protocol,
          hostname: url.parse(urls.complex).hostname,
          port: url.parse(urls.complex).port,
          pathname: url.parse(urls.complex).pathname,
          query: url.parse(urls.complex, true).query,
          hash: url.parse(urls.complex).hash
        }
      };

      dump_json(results);
zlib
id: javascript-zlib

info:
  name: JavaScript Zlib Operations Demo
  author: dwisiswant0
  severity: info
  description: Template demonstrating comprehensive zlib compression/decompression operations using browserify-zlib
  tags: js,zlib,test

javascript:
  - code: |
      const zlib = require('@core/zlib');
      const { Buffer } = require('@core/buffer');

      const sampleText = 'Hello, Nuclei! This is a test string for compression.'.repeat(10);
      const inputBuffer = Buffer.from(sampleText);

      // Gzip compression
      const gzipBuffer = zlib.gzipSync(inputBuffer);
      const gzipBase64 = gzipBuffer.toString('base64');
      const unzippedGzip = zlib.gunzipSync(gzipBuffer).toString();

      // Deflate compression
      const deflateBuffer = zlib.deflateSync(inputBuffer);
      const deflateBase64 = deflateBuffer.toString('base64');
      const inflatedDeflate = zlib.inflateSync(deflateBuffer).toString();

      // Raw Deflate (without headers)
      const rawDeflateBuffer = zlib.deflateRawSync(inputBuffer);
      const rawDeflateBase64 = rawDeflateBuffer.toString('base64');
      const inflatedRawDeflate = zlib.inflateRawSync(rawDeflateBuffer).toString();

      // Brotli compression (if supported by the environment)
      let brotliResults = {};
      if (typeof zlib.brotliCompress === 'function') {
        const brotliBuffer = zlib.brotliCompressSync(inputBuffer);
        const brotliBase64 = brotliBuffer.toString('base64');
        const decompressedBrotli = zlib.brotliDecompressSync(brotliBuffer).toString();
        brotliResults = {
          compressed_base64: brotliBase64,
          decompressed: decompressedBrotli,
          compression_ratio: ((brotliBuffer.length / inputBuffer.length) * 100).toFixed(2) + '%'
        };
      }

      // Calculate compression ratios
      const gzipRatio = ((gzipBuffer.length / inputBuffer.length) * 100).toFixed(2) + '%';
      const deflateRatio = ((deflateBuffer.length / inputBuffer.length) * 100).toFixed(2) + '%';
      const rawDeflateRatio = ((rawDeflateBuffer.length / inputBuffer.length) * 100).toFixed(2) + '%';

      dump_json({
        original: {
          text: sampleText,
          size: inputBuffer.length
        },
        gzip: {
          compressed_base64: gzipBase64,
          decompressed: unzippedGzip,
          compression_ratio: gzipRatio
        },
        deflate: {
          compressed_base64: deflateBase64,
          decompressed: inflatedDeflate,
          compression_ratio: deflateRatio
        },
        raw_deflate: {
          compressed_base64: rawDeflateBase64,
          decompressed: inflatedRawDeflate,
          compression_ratio: rawDeflateRatio
        },
        brotli: brotliResults
      });

Checklist

  • Pull request is created against the dev branch
  • All checks passed (lint, unit/integration/regression tests etc.) with my changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have added necessary documentation (if appropriate)

Copy link
Contributor

coderabbitai bot commented May 22, 2025

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@dwisiswant0 dwisiswant0 force-pushed the dwisiswant0/feat/goja-nodejs-libraries branch from 1a9bd08 to c601bd5 Compare May 28, 2025 15:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant