Skip to content

add nuclei/http js client - #7568

Merged
Mzack9999 merged 4 commits into
devfrom
7567-js-http
Jul 27, 2026
Merged

add nuclei/http js client#7568
Mzack9999 merged 4 commits into
devfrom
7567-js-http

Conversation

@Mzack9999

@Mzack9999 Mzack9999 commented Jul 22, 2026

Copy link
Copy Markdown
Member

Closes #7567
Closes #4679

Add require('nuclei/http'), an httpx-shaped JS HTTP client for multi-step HTTP in code instead of YAML string soup or one-off DSL helpers.

  • Client/Options/Response with Get, Head, Post, Request, SetHeader
  • Cookies, redirects, body size cap; dial + host policy via fastdialer/protocolstate
  • DecodeNTLM / NegotiateNTLM as library helpers (addresses NTLM Dsl Function #4679 via JS helpers, not DSL)
  • Unit tests (~93%) and JS integration YAMLs (get, client flow, network-policy deny)

Summary by CodeRabbit

  • New Features
    • Added HTTP client capabilities for JavaScript templates (GET/HEAD/POST/custom requests) with configurable timeouts, redirect handling, max response size, cookie behavior, and default headers/allowlisting.
    • Exposed a structured HTTP Response (status, final URL, body, and flattened headers with case-insensitive lookup).
    • Added NTLM authentication helpers to decode challenges and generate negotiation messages.
  • Tests
    • Added JavaScript integration cases for HTTP GET/flows and denied-target behavior.
    • Added runtime unit tests covering redirects, cookies, body limits, headers, denylisting, and missing execution context.
    • Added NTLM decoding/safety and parsing regression tests.
  • Chores
    • Registered an additional embedded HTTP helper library for template use.

@Mzack9999 Mzack9999 self-assigned this Jul 22, 2026
@coderabbitai

coderabbitai Bot commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: aa43aa73-4743-4c85-a8c2-53fb8ad42629

📥 Commits

Reviewing files that changed from the base of the PR and between 51625f9 and bdb4aa0.

📒 Files selected for processing (1)
  • internal/tests/integration/javascript_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/tests/integration/javascript_test.go

Walkthrough

Adds a Goja-backed JavaScript HTTP client with redirects, cookies, headers, limits, host policy, response handling, NTLM helpers, compiler registration, unit tests, and integration tests for HTTP templates.

Changes

JavaScript HTTP capabilities

Layer / File(s) Summary
HTTP client runtime and response contract
pkg/js/libs/http/http.go, pkg/js/libs/http/response.go, pkg/js/compiler/pool.go
Adds configurable HTTP clients and package helpers for GET, HEAD, POST, and generic requests, plus protocolstate-aware dialing, redirects, cookies, headers, response limits, and response accessors.
HTTP client behavior validation
pkg/js/libs/http/http_test.go
Tests request methods, redirects, cookies, headers, body limits, host denial, URL validation, fastdialer use, options, response headers, and execution IDs.
JavaScript template integration
internal/tests/integration/javascript_http_test.go, internal/tests/integration/javascript_test.go
Adds local HTTP endpoints and integration cases for HTTP GET, client flows, and denied-target execution.
NTLM parsing and negotiation
pkg/js/libs/http/ntlm.go, pkg/js/libs/http/ntlm_test.go
Adds NTLM Type-1 message generation, Type-2 decoding, AV-pair parsing, UTF-16LE handling, timestamp conversion, and validation tests.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant JSTemplate
  participant HTTPClient
  participant ProtocolState
  participant LocalHTTPServer
  JSTemplate->>HTTPClient: Request(method, URL, body)
  HTTPClient->>ProtocolState: Validate execution ID and target
  HTTPClient->>LocalHTTPServer: Send HTTP request
  LocalHTTPServer-->>HTTPClient: Return status, headers, and body
  HTTPClient-->>JSTemplate: Return Response
Loading

Suggested reviewers: dogancanbakir, ice3man543

Poem

I’m a rabbit with packets to hop,
Through redirects that tumble and stop.
Cookies tucked tight,
Headers set right,
NTLM bytes now dance in a crop!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 9.09% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is concise and accurately names the main change: adding the nuclei/http JavaScript client.
Linked Issues check ✅ Passed The PR delivers the requested nuclei/http client plus NTLM helpers and tests, matching #7567 and #4679.
Out of Scope Changes check ✅ Passed The added tests and NTLM helpers are directly tied to the requested HTTP client and NTLM support.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch 7567-js-http

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (3)
internal/tests/integration/javascript_http_test.go (1)

51-76: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Duplicate Execute bodies for javascriptHTTPGet and javascriptHTTPClientFlow.

Both methods are identical apart from type name. Could share a helper, though the duplication is small and low-risk.

♻️ Optional helper extraction
+func runJSHTTPServerTest(filePath string) error {
+	ts := startJSHTTPServer()
+	defer ts.Close()
+	hostPort := strings.TrimPrefix(ts.URL, "http://")
+	results, err := runSignedNucleiTemplateAndGetResults(filePath, hostPort, debug)
+	if err != nil {
+		return err
+	}
+	return expectResultsCount(results, 1)
+}
+
 type javascriptHTTPGet struct{}
 
 func (j *javascriptHTTPGet) Execute(filePath string) error {
-	ts := startJSHTTPServer()
-	defer ts.Close()
-	hostPort := strings.TrimPrefix(ts.URL, "http://")
-	results, err := runSignedNucleiTemplateAndGetResults(filePath, hostPort, debug)
-	if err != nil {
-		return err
-	}
-	return expectResultsCount(results, 1)
+	return runJSHTTPServerTest(filePath)
 }
 
 type javascriptHTTPClientFlow struct{}
 
 func (j *javascriptHTTPClientFlow) Execute(filePath string) error {
-	ts := startJSHTTPServer()
-	defer ts.Close()
-	hostPort := strings.TrimPrefix(ts.URL, "http://")
-	results, err := runSignedNucleiTemplateAndGetResults(filePath, hostPort, debug)
-	if err != nil {
-		return err
-	}
-	return expectResultsCount(results, 1)
+	return runJSHTTPServerTest(filePath)
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/tests/integration/javascript_http_test.go` around lines 51 - 76,
Extract the shared server setup, template execution, error propagation, and
result-count validation from javascriptHTTPGet.Execute and
javascriptHTTPClientFlow.Execute into a helper, then have both Execute methods
delegate to it while preserving the existing behavior.
pkg/js/libs/http/http.go (1)

369-384: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use a typed context key instead of a raw string.

ctx.Value("executionId") uses a bare string key; go vet/staticcheck (SA1029) flag this pattern because it risks collisions with keys from other packages. The test helper withExec mirrors this exact pattern but explicitly suppresses the linter (//nolint:staticcheck // SA1029) — the fix belongs here at the production call site so the test doesn't need to keep mirroring an anti-pattern.

♻️ Suggested typed context key
+type contextKey string
+
+const executionIDContextKey contextKey = "executionId"
+
 func executionIDFrom(ctx context.Context, c *Client) string {
 	if c != nil && c.nj != nil {
 		if id := c.nj.ExecutionId(); id != "" {
 			return id
 		}
 	}
 	if ctx == nil {
 		return ""
 	}
-	if v := ctx.Value("executionId"); v != nil {
+	if v := ctx.Value(executionIDContextKey); v != nil {
 		if id, ok := v.(string); ok {
 			return id
 		}
 	}
 	return ""
 }

As per coding guidelines, **/*.go changes should pass static analysis (go vet ./...); while SA1029 is a staticcheck rule rather than go vet, it's the same category of Go static-analysis hygiene this guideline is aimed at.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/js/libs/http/http.go` around lines 369 - 384, Replace the raw
"executionId" key used by executionIDFrom with a package-private typed
context-key symbol, and use that symbol for the ctx.Value lookup. Update the
test helper withExec to use the same production key rather than relying on the
linter suppression, preserving the existing execution ID fallback behavior.

Source: Coding guidelines

pkg/js/libs/http/ntlm_test.go (1)

30-85: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extend buildType2 to cover AvId 9 and a no-VERSION header.

Coverage gap tied to the two ntlm.go findings: no test emits an AvId=9 (MsvAvTargetName) pair or a 48-byte (no-VERSION) challenge, so the AV-pair-8/9 mismap and the unconditional VERSION read in parseNTLMMessage aren't caught by the suite. Consider adding a headerLen parameter/variant to buildType2 and one test per scenario.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/js/libs/http/ntlm_test.go` around lines 30 - 85, Extend buildType2 to
optionally emit AvId 9 (MsvAvTargetName) and construct a 48-byte challenge
without the VERSION field, while preserving the existing 56-byte behavior. Add
focused tests covering AvId 9 parsing and no-VERSION header parsing so both
scenarios exercise parseNTLMMessage.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@pkg/js/libs/http/ntlm.go`:
- Around line 117-123: Gate the VERSION parsing in the ProductVersion extraction
logic on confirmed VERSION presence rather than len(data) alone. Use the
NTLMSSP_NEGOTIATE_VERSION bit in NegotiateFlags, or ensure offset 48 plus 8
bytes precedes the smallest non-zero targetNameOffset/targetInfoOffset, while
preserving the existing ProductVersion empty check and formatting.
- Around line 144-163: Update the AV-pair switch to treat ID 8 as
MsvAvSingleHost without decoding it as text, and add ID 9 as MsvAvTargetName
that populates info.TargetName using the existing conditional behavior. Keep the
existing handling for all other AV IDs unchanged.

---

Nitpick comments:
In `@internal/tests/integration/javascript_http_test.go`:
- Around line 51-76: Extract the shared server setup, template execution, error
propagation, and result-count validation from javascriptHTTPGet.Execute and
javascriptHTTPClientFlow.Execute into a helper, then have both Execute methods
delegate to it while preserving the existing behavior.

In `@pkg/js/libs/http/http.go`:
- Around line 369-384: Replace the raw "executionId" key used by executionIDFrom
with a package-private typed context-key symbol, and use that symbol for the
ctx.Value lookup. Update the test helper withExec to use the same production key
rather than relying on the linter suppression, preserving the existing execution
ID fallback behavior.

In `@pkg/js/libs/http/ntlm_test.go`:
- Around line 30-85: Extend buildType2 to optionally emit AvId 9
(MsvAvTargetName) and construct a 48-byte challenge without the VERSION field,
while preserving the existing 56-byte behavior. Add focused tests covering AvId
9 parsing and no-VERSION header parsing so both scenarios exercise
parseNTLMMessage.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: f2affae5-ac6e-4b13-a723-2005f4a66345

📥 Commits

Reviewing files that changed from the base of the PR and between 1709267 and e0224a4.

⛔ Files ignored due to path filters (6)
  • internal/tests/integration/testdata/protocols/javascript/http-client-flow.yaml is excluded by !**/*.yaml
  • internal/tests/integration/testdata/protocols/javascript/http-denied.yaml is excluded by !**/*.yaml
  • internal/tests/integration/testdata/protocols/javascript/http-get.yaml is excluded by !**/*.yaml
  • pkg/js/generated/go/libhttp/http.go is excluded by !**/generated/**
  • pkg/js/generated/ts/http.ts is excluded by !**/generated/**
  • pkg/js/generated/ts/index.ts is excluded by !**/generated/**
📒 Files selected for processing (8)
  • internal/tests/integration/javascript_http_test.go
  • internal/tests/integration/javascript_test.go
  • pkg/js/compiler/pool.go
  • pkg/js/libs/http/http.go
  • pkg/js/libs/http/http_test.go
  • pkg/js/libs/http/ntlm.go
  • pkg/js/libs/http/ntlm_test.go
  • pkg/js/libs/http/response.go

Comment thread pkg/js/libs/http/ntlm.go Outdated
Comment thread pkg/js/libs/http/ntlm.go
Comment thread pkg/js/libs/http/http.go Dismissed
Comment thread pkg/js/libs/http/http.go Dismissed

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@pkg/js/libs/http/ntlm.go`:
- Around line 115-116: Update the target-info validation in the NTLM parsing
flow around parseAVPairs to perform offset-plus-length bounds checks using
uint64 arithmetic, avoiding int conversion of untrusted uint32 values. Only
convert targetInfoOffset and targetInfoLen to int after confirming the range
fits within len(data), then preserve the existing parseAVPairs behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2e0edf7c-e291-4745-aa6d-09697e782d7a

📥 Commits

Reviewing files that changed from the base of the PR and between e0224a4 and f2d0cb3.

📒 Files selected for processing (2)
  • pkg/js/libs/http/ntlm.go
  • pkg/js/libs/http/ntlm_test.go

Comment thread pkg/js/libs/http/ntlm.go Outdated

@dwisiswant0 dwisiswant0 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

banger.

(too large didn't review so I'm just gonna ask this instead:) does this respect our sandbox network policy?

@dwisiswant0

Copy link
Copy Markdown
Member

banger.

(too large didn't review so I'm just gonna ask this instead:) does this respect our sandbox network policy?

@coderabbitai answer this.

@coderabbitai

coderabbitai Bot commented Jul 26, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

ast-grep outline pkg/js/libs/http/http.go --items all
printf '\n--- policy-related symbols and tests ---\n'
rg -n -C 5 -i 'protocolstate|executionid|allow|deny|redirect|fastdialer|dialcontext|checkredirect' \
  pkg/js/libs/http/http.go pkg/js/libs/http/http_test.go internal/tests/integration/javascript_http_test.go
printf '\n--- implementation ---\n'
sed -n '1,460p' pkg/js/libs/http/http.go

Length of output: 45421


@dwisiswant0 Yes. The JS client is execution-scoped and uses the existing protocolstate/fastdialer path rather than a direct dialer:

  • It requires an executionId; otherwise requests fail.
  • It calls protocolstate.IsHostAllowed(executionID, hostname) before the initial request.
  • Both HTTP and TLS connections go through protocolstate.GetDialersWithId(executionID).Fastdialer.
  • Followed redirects are independently host-policy checked in CheckRedirect before the redirect request proceeds.
  • The PR includes coverage for both a denied initial target and a redirect to a denied target.

So require('nuclei/http') does respect the sandbox network policy, including redirects. 🐇

@Mzack9999
Mzack9999 merged commit e557207 into dev Jul 27, 2026
19 checks passed
@Mzack9999
Mzack9999 deleted the 7567-js-http branch July 27, 2026 11:47
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.

add nuclei/http js client NTLM Dsl Function

3 participants