Skip to content

[Feature] NerdyData search engine - #723

Merged
dogancanbakir merged 5 commits into
projectdiscovery:mainfrom
nerdydata:feature/nerdydata
Apr 25, 2026
Merged

dogancanbakir merged 5 commits into
projectdiscovery:mainfrom
nerdydata:feature/nerdydata

Conversation

@davidbielik

@davidbielik davidbielik commented Apr 7, 2026 •

Copy link
Copy Markdown
Contributor

[Feature] NerdyData search engine

NerdyData has been around since 2012, and is a popular crawler and search engine for web source code.

NerdyData scans millions of websites, fully renders javascript in a headless browser, and makes the following code fingerprints available for search:

  • HTML, CSS, Javascript
  • HTTP Headers
  • Cookie names
  • Global window variables
  • Network request URLs and body content

Feature:

New files

  • sources/agent/nerdydata/nerdydata.go — Agent implementation with cursor-based pagination and retry logic
  • sources/agent/nerdydata/request.go — URL builder; wraps plain strings as code-search JSON, passes through raw JSON objects unchanged
  • sources/agent/nerdydata/response.go — Response types (Response, Site)

Modified files

  • sources/keys.go — Added NerdyDataToken field
  • sources/provider.go — Added NerdyData provider config, env var (NERDYDATA_API_KEY), and HasKeys()
    support
  • sources/session.go — Added nerdydata rate limit entry
  • uncover.go — Registered agent in New() switch and AllAgents()
  • runner/options.go — Added -nd/-nerdydata CLI flag
  • integration-tests/ — Added nerdydataTestcases and registered in test map

API details

Local test instructions

# build and test e2e                                                                           
go build
export NERDYDATA_API_KEY=<your-key>                                             
go run ./cmd/uncover -nerdydata jquery -silent -limit 
go run ./cmd/uncover -e nerdydata -q jquery -silent -limit 5
                                                       
# integration tests     
cd integration-tests && bash run.sh                                                                                                                                                    
go run ./integration-tests -tests nerdydata

# Provider config test (verifies YAML config path works)
echo 'nerdydata:\n  - <your-key>' >> ~/.config/uncover/provider-config.yaml
unset NERDYDATA_API_KEY
go run ./cmd/uncover -nerdydata jquery -silent -limit 5
image image image image

Summary by CodeRabbit

  • New Features

    • Added NerdyData as a supported search provider with a CLI flag to enable searches and built-in rate limiting.
  • Tests

    • Added integration tests covering NerdyData provider flow and execution.
  • Documentation

    • Updated docs and examples to include NerdyData configuration, example provider config, and API key setup instructions.

@neo-by-projectdiscovery-dev

neo-by-projectdiscovery-dev Bot commented Apr 7, 2026 •

Copy link
Copy Markdown

Neo - PR Security Review

No security issues found

Comment @pdneo help for available commands. · Open in Neo

@coderabbitai

coderabbitai Bot commented Apr 7, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds NerdyData as a supported search provider: docs/config updates, an integration test, CLI flag and engine handling, provider key loading, rate-limit entry, a new NerdyData agent package (request/response types, pagination and retry logic), and service registration.

Changes

Cohort / File(s) Summary
Documentation & Config
README.md
Documented NerdyData support; added nerdydata section to example provider-config.yaml and export NERDYDATA_API_KEY example.
Integration Tests
integration-tests/integration-test.go, integration-tests/source-test.go
Registered nerdydata test suite; added nerdydataTestcases requiring NERDYDATA_API_KEY, writes provider token config, runs uncover with -nerdydata, and asserts results.
CLI Options
runner/options.go
Added NerdyData field and --nerdydata/-nd flag; included nerdydata in engine auto-selection, validation, and query appending.
Service Registration
uncover.go
Imported nerdydata agent package, registered &nerdydata.Agent{} and added "nerdydata" to AllAgents().
Agent Implementation
sources/agent/nerdydata/nerdydata.go, .../request.go, .../response.go
New package with Agent (Name, Query) implementing paginated queries, 202-retry/backoff behavior, request builder that encodes search JSON or code search, and Response/Site structs for unmarshalling and emitting results.
Provider & Keys
sources/provider.go, sources/keys.go
Added Provider.NerdyData []string, load NERDYDATA_API_KEY into provider, select token into Keys.NerdyDataToken, and extended Keys.Empty() to include the new token.
Rate Limiting
sources/session.go
Added nerdydata entry to DefaultRateLimits (MaxCount: 1, Duration: 1s).

Sequence Diagram

sequenceDiagram
    participant Client as Client
    participant Service as Service
    participant Agent as NerdyDataAgent
    participant RateLimiter as RateLimiter
    participant API as NerdyDataAPI
    participant Stream as ResultStream

    Client->>Service: Start nerdydata query
    Service->>Agent: Query(session, query)

    loop per page
        Agent->>RateLimiter: Take("nerdydata")
        RateLimiter-->>Agent: Permit
        Agent->>API: GET (api_key header, page cursor)
        alt 202 Accepted
            API-->>Agent: 202 Accepted
            Agent->>Agent: Backoff & retry
        else 200 OK
            API-->>Agent: 200 + JSON
            Agent->>Agent: Unmarshal Response
            loop per Site
                Agent->>Stream: Emit Result{Host, Url, Raw}
            end
            alt next_page present
                Agent->>Agent: set cursor = next_page
            else
                Agent->>Stream: Close channel
            end
        else error
            API-->>Agent: Error
            Agent->>Stream: Emit Result{Error} & Close channel
        end
    end

    Stream-->>Service: Streamed results
    Service-->>Client: Return results
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I nibble docs and hop through code,
A NerdyData trail along the node,
Cursors hum and retries play,
Tokens jump, pages give way,
Results pour in — hooray, hooray!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% 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 pull request title '[Feature] NerdyData search engine' clearly and concisely describes the main change: adding NerdyData as a new search engine/source to the uncover tool.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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 and usage tips.

@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: 4

🧹 Nitpick comments (1)
sources/agent/nerdydata/request.go (1)

27-32: Consider handling the json.Marshal error.

While json.Marshal is unlikely to fail for this simple map structure, ignoring the error silently could mask unexpected issues in edge cases. Consider logging or returning an error if marshaling fails.

🔧 Proposed defensive handling
-		wrapped, _ := json.Marshal(map[string]any{
+		wrapped, err := json.Marshal(map[string]any{
 			"all": []map[string]string{
 				{"type": "code", "value": r.Query},
 			},
 		})
+		if err != nil {
+			// Fallback: use query as-is (should never happen)
+			params.Set("search", r.Query)
+			params.Set("facets", "false")
+			if r.Page != "" {
+				params.Set("page", r.Page)
+			}
+			return baseURL + baseEndpoint + "?" + params.Encode()
+		}
 		params.Set("search", string(wrapped))
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@sources/agent/nerdydata/request.go` around lines 27 - 32, Handle the error
returned by json.Marshal instead of discarding it: check the error from
json.Marshal when creating wrapped (which includes r.Query), and on failure
either return the error from the enclosing function or log it before returning
so you don't call params.Set("search", string(wrapped)) with an invalid value;
update the code around the json.Marshal call (wrapped, err := json.Marshal(...))
and the subsequent params.Set usage to only proceed when err == nil.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@integration-tests/source-test.go`:
- Line 300: The os.WriteFile call currently discards its error; update the
NerdyData test setup where ConfigFile is written with []byte(nerdydataToken) to
check the returned error and fail the test on error (e.g., if err :=
os.WriteFile(ConfigFile, []byte(nerdydataToken), 0644); err != nil {
t.Fatalf("failed to write config file: %v", err) } or use your test
helper/assertion equivalent), ensuring the test surface reports setup failures
instead of silently continuing.

In `@README.md`:
- Line 53: Replace the tracked NerdyData link in the README entry
"**[NerdyData](https://www.nerdydata.com/?utm_source=projectdiscovery/uncover)**"
with the canonical provider URL by removing the utm_source query string so it
becomes "**[NerdyData](https://www.nerdydata.com/)**"; update the Markdown link
text in README.md accordingly to keep docs neutral and stable.

In `@sources/agent/nerdydata/nerdydata.go`:
- Around line 44-48: The 202 handling currently loops forever; change the logic
in the function handling the HTTP response (the block that checks
resp.StatusCode == http.StatusAccepted) to implement a bounded retry: add a
maxRetries counter (e.g., max202Retries) and an increasing backoff delay
(exponential with jitter) between retries, incrementing the counter each time
you close resp.Body and retry; if maxRetries is exceeded return a clear error
instead of continuing forever. Use the existing request context (ctx) or check
ctx.Done() during sleeps so retries are cancelable, and ensure resp.Body.Close()
is still called on each attempt.

In `@sources/provider.go`:
- Line 180: The code appends an empty NERDYDATA_API_KEY when the env var is
present but blank; update the logic so provider.NerdyData is only appended when
the value is non-empty by changing the call/site around provider.NerdyData =
appendIfExists(provider.NerdyData, "NERDYDATA_API_KEY") (or modify
appendIfExists) to treat empty strings as missing (use os.LookupEnv or check
value != "" before appending) so blank env values are skipped.

---

Nitpick comments:
In `@sources/agent/nerdydata/request.go`:
- Around line 27-32: Handle the error returned by json.Marshal instead of
discarding it: check the error from json.Marshal when creating wrapped (which
includes r.Query), and on failure either return the error from the enclosing
function or log it before returning so you don't call params.Set("search",
string(wrapped)) with an invalid value; update the code around the json.Marshal
call (wrapped, err := json.Marshal(...)) and the subsequent params.Set usage to
only proceed when err == nil.
🪄 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: 0e0e3a3e-6a85-4f24-aad2-00a4ed46183c

📥 Commits

Reviewing files that changed from the base of the PR and between 404e642 and 6c44bc2.

📒 Files selected for processing (11)
  • README.md
  • integration-tests/integration-test.go
  • integration-tests/source-test.go
  • runner/options.go
  • sources/agent/nerdydata/nerdydata.go
  • sources/agent/nerdydata/request.go
  • sources/agent/nerdydata/response.go
  • sources/keys.go
  • sources/provider.go
  • sources/session.go
  • uncover.go

return errors.New("missing NerdyData api key")
}
nerdydataToken := fmt.Sprintf(`nerdydata: [%s]`, token)
_ = os.WriteFile(ConfigFile, []byte(nerdydataToken), 0644)

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.

⚠️ Potential issue | 🟡 Minor

Handle config write errors in the NerdyData testcase.

Line 300 ignores os.WriteFile errors, which can hide test setup failures.

Proposed fix
-	_ = os.WriteFile(ConfigFile, []byte(nerdydataToken), 0644)
+	if err := os.WriteFile(ConfigFile, []byte(nerdydataToken), 0644); err != nil {
+		return err
+	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@integration-tests/source-test.go` at line 300, The os.WriteFile call
currently discards its error; update the NerdyData test setup where ConfigFile
is written with []byte(nerdydataToken) to check the returned error and fail the
test on error (e.g., if err := os.WriteFile(ConfigFile, []byte(nerdydataToken),
0644); err != nil { t.Fatalf("failed to write config file: %v", err) } or use
your test helper/assertion equivalent), ensuring the test surface reports setup
failures instead of silently continuing.

Comment thread README.md Resolved
Comment thread sources/agent/nerdydata/nerdydata.go Resolved
Comment thread sources/provider.go Resolved
@dogancanbakir
dogancanbakir requested a review from knakul853 April 7, 2026 11:59

@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.

🧹 Nitpick comments (1)
sources/agent/nerdydata/nerdydata.go (1)

42-54: Consider reducing the exponential backoff base value.

The current backoff formula 30*(1<<attempt) yields wait times of 30s, 60s, 120s, 240s, and 480s per retry, totaling ~15 minutes in the worst case. This is unusually aggressive for client-side retry logic and may significantly impact user experience when the NerdyData API is under load.

Additionally, the time.Sleep doesn't respect context cancellation, so a cancelled operation will still block until the sleep completes.

♻️ Suggested improvement with shorter backoff and cancellation support
+import "context"
+
 func (agent *Agent) Query(session *sources.Session, query *sources.Query) (chan sources.Result, error) {
+	ctx := context.Background() // or accept context as parameter
 	// ... existing validation ...
 
 	go func() {
 		defer close(results)
 
 		const maxRetries = 5
 		// ...
 		for attempt := 0; attempt < maxRetries; attempt++ {
 			resp, err = agent.queryURL(session, nerdydataRequest.buildURL(), session.Keys.NerdyDataToken)
 			// ... error handling ...
 			if resp.StatusCode != http.StatusAccepted {
 				break
 			}
 			resp.Body.Close()
-			time.Sleep(time.Duration(30*(1<<attempt)) * time.Second)
+			backoff := time.Duration(2*(1<<attempt)) * time.Second // 2s, 4s, 8s, 16s, 32s
+			select {
+			case <-ctx.Done():
+				results <- sources.Result{Source: agent.Name(), Error: ctx.Err()}
+				return
+			case <-time.After(backoff):
+			}
 		}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@sources/agent/nerdydata/nerdydata.go` around lines 42 - 54, The retry backoff
in the loop that calls agent.queryURL(session, nerdydataRequest.buildURL(),
session.Keys.NerdyDataToken) is too large and ignores cancellation; replace the
current exponential multiplier 30*(1<<attempt) with a much smaller base and a
max cap (e.g., base 2–5 seconds with a maxBackoff), and change the unconditional
time.Sleep to a context-aware wait (select on time.After(backoff) and
ctx.Done()) so retries stop promptly if the calling context is cancelled; keep
the existing retry loop structure, using attempt/maxRetries and closing
resp.Body before waiting.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@sources/agent/nerdydata/nerdydata.go`:
- Around line 42-54: The retry backoff in the loop that calls
agent.queryURL(session, nerdydataRequest.buildURL(),
session.Keys.NerdyDataToken) is too large and ignores cancellation; replace the
current exponential multiplier 30*(1<<attempt) with a much smaller base and a
max cap (e.g., base 2–5 seconds with a maxBackoff), and change the unconditional
time.Sleep to a context-aware wait (select on time.After(backoff) and
ctx.Done()) so retries stop promptly if the calling context is cancelled; keep
the existing retry loop structure, using attempt/maxRetries and closing
resp.Body before waiting.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: f6a6a622-c7b9-4489-80f0-27b9c96e61ab

📥 Commits

Reviewing files that changed from the base of the PR and between 6c44bc2 and 291a026.

📒 Files selected for processing (1)
  • sources/agent/nerdydata/nerdydata.go

@davidbielik

Copy link
Copy Markdown
Contributor Author

Hi @knakul853 @ShubhamRasal Let me know if you'd also like an API key to test this out with as you review, or if you have any questions.

@dogancanbakir

Copy link
Copy Markdown
Member

@davidbielik Could you share the API key with the reviewers? My discord handle is the same as GitHub one.

Comment thread sources/agent/nerdydata/nerdydata.go Outdated
Comment on lines +63 to +64
case <-ctx.Done():
results <- sources.Result{Source: agent.Name(), Error: ctx.Err()}

@ShubhamRasal ShubhamRasal Apr 24, 2026 •

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.

nit: ctx := context.Background() at nerdydata.go:31 means the select { case <-ctx.Done(): … } at line
67 can never fire. So the "retries abort on cancellation" behavior isn't actually happening

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks - just removed

@ShubhamRasal ShubhamRasal 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.

Suggested a small fix, we can drop the ctx for now. This needs a refactor across all providers, tracked here: #724

@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 the current code and only fix it if needed.

Inline comments:
In `@sources/agent/nerdydata/nerdydata.go`:
- Around line 44-86: The resp.Body.Close() calls are redundant and their errors
are ignored; consolidate cleanup to a single explicit discard of the Close()
error. After the retry loop and once you decide to stop using resp (before any
returns or decoding), call _ = resp.Body.Close() exactly once (or ensure a
single defer/cleanup path) and remove the other resp.Body.Close() calls; update
the 202 retry-exhausted and non-200 error paths to rely on that single cleanup
and ensure the json.Decoder use happens before closing (use symbols resp,
queryURL, nerdydataRequest.buildURL, Response, maxRetries to locate the logic).
🪄 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: 8d8e0cb5-9d36-427f-a094-877bbefb1ed4

📥 Commits

Reviewing files that changed from the base of the PR and between 155c887 and 5c71b52.

📒 Files selected for processing (1)
  • sources/agent/nerdydata/nerdydata.go

Comment on lines +44 to +86
for attempt := 0; attempt < maxRetries; attempt++ {
resp, err = agent.queryURL(session, nerdydataRequest.buildURL(), session.Keys.NerdyDataToken)
if err != nil {
results <- sources.Result{Source: agent.Name(), Error: err}
return
}
if resp.StatusCode != http.StatusAccepted {
break
}
// 202 = server-side timeout; back off and retry with same cursor
resp.Body.Close()
backoff := baseBackoff * (1 << attempt)
if backoff > maxBackoff {
backoff = maxBackoff
}
time.Sleep(backoff)
}
if resp.StatusCode == http.StatusAccepted {
resp.Body.Close()
results <- sources.Result{
Source: agent.Name(),
Error: fmt.Errorf("server returned 202 after %d retries", maxRetries),
}
return
}

if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
results <- sources.Result{
Source: agent.Name(),
Error: fmt.Errorf("unexpected status %d: %s", resp.StatusCode, body),
}
return
}

var apiResponse Response
if err := json.NewDecoder(resp.Body).Decode(&apiResponse); err != nil {
resp.Body.Close()
results <- sources.Result{Source: agent.Name(), Error: err}
return
}
resp.Body.Close()

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.

⚠️ Potential issue | 🟡 Minor

Tighten the 202 cleanup path.

The last accepted response is already closed inside the retry loop, so the post-loop Close() is redundant. All of the Close() calls in this block also ignore their errors, which is what the linter is flagging. Please collapse this into a single cleanup point or explicitly discard the error once with _ = resp.Body.Close() so the intent is clear.

♻️ Suggested cleanup
 				if resp.StatusCode != http.StatusAccepted {
 					break
 				}
 				// 202 = server-side timeout; back off and retry with same cursor
-				resp.Body.Close()
+				_ = resp.Body.Close()
 				backoff := baseBackoff * (1 << attempt)
 				if backoff > maxBackoff {
 					backoff = maxBackoff
 				}
 				time.Sleep(backoff)
 			}
 			if resp.StatusCode == http.StatusAccepted {
-				resp.Body.Close()
 				results <- sources.Result{
 					Source: agent.Name(),
 					Error:  fmt.Errorf("server returned 202 after %d retries", maxRetries),
 				}
 				return
 			}
 
 			if resp.StatusCode != http.StatusOK {
 				body, _ := io.ReadAll(resp.Body)
-				resp.Body.Close()
+				_ = resp.Body.Close()
 				results <- sources.Result{
 					Source: agent.Name(),
 					Error:  fmt.Errorf("unexpected status %d: %s", resp.StatusCode, body),
 				}
 				return
 			}
@@
 			var apiResponse Response
 			if err := json.NewDecoder(resp.Body).Decode(&apiResponse); err != nil {
-				resp.Body.Close()
+				_ = resp.Body.Close()
 				results <- sources.Result{Source: agent.Name(), Error: err}
 				return
 			}
-			resp.Body.Close()
+			_ = resp.Body.Close()
🧰 Tools
🪛 golangci-lint (2.11.4)

[error] 54-54: Error return value of resp.Body.Close is not checked

(errcheck)


[error] 62-62: Error return value of resp.Body.Close is not checked

(errcheck)


[error] 72-72: Error return value of resp.Body.Close is not checked

(errcheck)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@sources/agent/nerdydata/nerdydata.go` around lines 44 - 86, The
resp.Body.Close() calls are redundant and their errors are ignored; consolidate
cleanup to a single explicit discard of the Close() error. After the retry loop
and once you decide to stop using resp (before any returns or decoding), call _
= resp.Body.Close() exactly once (or ensure a single defer/cleanup path) and
remove the other resp.Body.Close() calls; update the 202 retry-exhausted and
non-200 error paths to rely on that single cleanup and ensure the json.Decoder
use happens before closing (use symbols resp, queryURL,
nerdydataRequest.buildURL, Response, maxRetries to locate the logic).

@dogancanbakir
dogancanbakir merged commit 92e6147 into projectdiscovery:main Apr 25, 2026
1 check passed
@davidbielik
davidbielik deleted the feature/nerdydata branch April 27, 2026 14:28
M0dred pushed a commit to M0dred/uncover that referenced this pull request Nov 20, 2026
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.

4 participants