validin-sdk 0.2.0__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/PKG-INFO +16 -11
  2. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/README.md +15 -10
  3. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/__init__.py +1 -1
  4. validin_sdk-0.3.0/src/validin/_config.py +45 -0
  5. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/cli/commands/account.py +2 -2
  6. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/cli/commands/intel.py +1 -1
  7. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/cli/commands/projects.py +3 -3
  8. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/cli/commands/setup.py +7 -7
  9. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/cli/commands/threats.py +1 -1
  10. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/cli/commands/yara.py +2 -2
  11. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/cli/config.py +7 -36
  12. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/cli/main.py +4 -2
  13. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/cli/onboarding.py +4 -2
  14. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/cli/render.py +1 -7
  15. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/cli/runner.py +45 -35
  16. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/client.py +14 -5
  17. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/indicator.py +6 -9
  18. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/pivots_api.py +4 -14
  19. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin_sdk.egg-info/PKG-INFO +16 -11
  20. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin_sdk.egg-info/SOURCES.txt +1 -0
  21. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/LICENSE +0 -0
  22. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/pyproject.toml +0 -0
  23. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/setup.cfg +0 -0
  24. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/setup.py +0 -0
  25. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/_clock.py +0 -0
  26. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/_dates.py +0 -0
  27. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/_inputs.py +0 -0
  28. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/_pacing.py +0 -0
  29. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/_record.py +0 -0
  30. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/annotation_record.py +0 -0
  31. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/bulk_api.py +0 -0
  32. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/certificate_record.py +0 -0
  33. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/cli/__init__.py +0 -0
  34. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/cli/commands/__init__.py +0 -0
  35. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/cli/commands/bulk.py +0 -0
  36. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/cli/commands/lookups.py +0 -0
  37. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/cli/commands/opendirs.py +0 -0
  38. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/cli/commands/scans.py +0 -0
  39. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/cli/commands/submit.py +0 -0
  40. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/cli/completion.py +0 -0
  41. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/cli/term.py +0 -0
  42. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/content.py +0 -0
  43. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/dns_record.py +0 -0
  44. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/enriched_indicator.py +0 -0
  45. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/errors.py +0 -0
  46. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/host_response_record.py +0 -0
  47. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/lookalike_record.py +0 -0
  48. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/open_directories_api.py +0 -0
  49. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/open_directory.py +0 -0
  50. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/osint_api.py +0 -0
  51. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/osint_record.py +0 -0
  52. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/pivot_record.py +0 -0
  53. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/project.py +0 -0
  54. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/projects_api.py +0 -0
  55. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/registration.py +0 -0
  56. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/registration_record.py +0 -0
  57. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/result_set.py +0 -0
  58. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/scan.py +0 -0
  59. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/scan_record.py +0 -0
  60. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/subdomain_record.py +0 -0
  61. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/threat_record.py +0 -0
  62. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/threats_api.py +0 -0
  63. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin/yara_match_record.py +0 -0
  64. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin_sdk.egg-info/dependency_links.txt +0 -0
  65. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin_sdk.egg-info/entry_points.txt +0 -0
  66. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin_sdk.egg-info/requires.txt +0 -0
  67. {validin_sdk-0.2.0 → validin_sdk-0.3.0}/src/validin_sdk.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: validin-sdk
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: A lightweight Python SDK for the Validin API
5
5
  Author-email: Elliot Roe <elliot@validin.com>, Sreekar Madabushi <sreekar@validin.com>
6
6
  Classifier: Programming Language :: Python :: 3
@@ -33,7 +33,7 @@ from validin import Client
33
33
 
34
34
  ## Configuration
35
35
 
36
- The client requires an API key. The simplest approach is to set environment variables:
36
+ Run `validin setup` once to save your API key and endpoint. Python scripts running as the same user can then call `Client()`. For CI or a one-off session, set environment variables:
37
37
 
38
38
  ```bash
39
39
  export VALIDIN_API_KEY="your-api-key"
@@ -53,12 +53,12 @@ from validin import Client
53
53
  client = Client(api_key="your-api-key", base_url="https://your-enterprise-endpoint.example.com")
54
54
  ```
55
55
 
56
- If `base_url` is not provided, the client defaults to `https://app.validin.com`.
56
+ For each setting, the SDK checks constructor arguments, environment variables, then the saved config. The fallback endpoint is `https://app.validin.com`.
57
57
 
58
58
  ## Data and Privacy
59
59
 
60
60
  The SDK, the `validin` CLI and the agent skills talk to one server: the Validin API at
61
- `https://app.validin.com`, or the endpoint set in `VALIDIN_BASE_URL` / `base_url`. Requests use
61
+ `https://app.validin.com`, or the endpoint you configure. Requests use
62
62
  HTTPS. Nothing is sent anywhere else, and there is no telemetry or usage reporting.
63
63
 
64
64
  **Sent to the Validin API**, only as part of the request you make:
@@ -75,7 +75,7 @@ infrastructure, not your machine. The SDK never contacts the hosts it looks up.
75
75
 
76
76
  **Stored on your machine:**
77
77
 
78
- - `validin setup` saves your API key and endpoint to `~/.validin/config.json`. The file is
78
+ - `validin setup` saves your API key, endpoint and default output format to `~/.validin/config.json`. The file is
79
79
  readable only by you (mode `0600`) in a directory only you can open (`0700`). Setting
80
80
  `VALIDIN_API_KEY` instead keeps the key out of that file.
81
81
  - Shell completion, if you enable it, writes a completion script and adds one line to your
@@ -108,12 +108,18 @@ Installing the package also installs a `validin` command:
108
108
  ```bash
109
109
  validin setup # save your API key
110
110
  validin dns example.com
111
- validin lookalikes acme.com -o list | validin reputation -
111
+ validin lookalikes acme.com -o list | validin reputation
112
112
  validin pivots example.com # where a value was seen on other hosts (links, certs, redirects...)
113
113
  validin threat show sdbot # named threats, their indicators and reports
114
114
  validin commands --json # every command, option and output field
115
115
  ```
116
116
 
117
+ Omit the indicators to read them from a pipe or file, as in `validin dns < domains.txt`. When you give indicators as arguments, stdin is not read, so the CLI works inside `while read` loops.
118
+
119
+ The CLI uses the format you choose in `validin setup` for terminals, pipes and redirected files.
120
+ The default is `table`. Use `--json` or `-o FORMAT` to override it for one command.
121
+ Scripts that read JSON should request it explicitly, for example `validin dns example.com --json | jq .count`.
122
+
117
123
  ### Shell completion
118
124
 
119
125
  Tab-complete commands, subcommands, options and option values (`--mode`, `--tag`, `-o`, ...)
@@ -160,8 +166,7 @@ codex plugin add validin@validin
160
166
  **Other agents** (Cursor, Windsurf, Cline, ...): the skills are plain Markdown. Point your
161
167
  agent's rules file or `AGENTS.md` at `skills/<name>/SKILL.md`.
162
168
 
163
- The skills need the CLI installed (`pip install validin-sdk==0.2.0`) and `VALIDIN_API_KEY` set in the
164
- agent's environment.
169
+ The skills need the CLI installed (`pip install validin-sdk==0.3.0`) and access to a saved API key or `VALIDIN_API_KEY` in the agent's environment.
165
170
 
166
171
  ## Core Concepts
167
172
 
@@ -507,7 +512,7 @@ Feed a row's `value` back in to pivot again.
507
512
  Supports bulk queries. Options: `category`, `limit`, `first_seen`, `last_seen`, `lookback`, `annotate`,
508
513
  `wildcard`. Categories are case-insensitive and accept the `HOST-X` / `X-IP` forms. Known names per
509
514
  type are in `validin.PIVOT_CATEGORIES`. An IP takes only `LOCATION_IP4` (redirects to it). An unknown category returns
510
- no records rather than an error. 32/40/64-hex strings are treated as hashes.
515
+ no records rather than an error. An even-length string of 18 or more hexadecimal characters is inferred as a hash.
511
516
 
512
517
  ---
513
518
 
@@ -741,8 +746,8 @@ and saved JSON fixtures before upgrading:
741
746
  - `CertificateObservation.to_dict()` omits `type` and `time`; those attributes
742
747
  remain accessible on the object. `HostResponse.to_dict()` omits `type`;
743
748
  its `time` field remains. Use the enclosing record's type for record dispatch.
744
- - `host_responses()` accepts domains, IPs, CIDRs, and explicit hash indicators;
745
- free-text strings now raise `ValueError`. Use `pivots()` for text searches.
749
+ - `host_responses()` accepts domains, IPs, CIDRs, and hashes.
750
+ Free-text strings raise `ValueError`. Use `pivots()` for text searches.
746
751
  - Bulk lookups report per-indicator API failures, including 404s, in
747
752
  `ResultSet.errors` instead of silently skipping missing indicators.
748
753
  Authentication and rate-limit failures still stop the batch.
@@ -19,7 +19,7 @@ from validin import Client
19
19
 
20
20
  ## Configuration
21
21
 
22
- The client requires an API key. The simplest approach is to set environment variables:
22
+ Run `validin setup` once to save your API key and endpoint. Python scripts running as the same user can then call `Client()`. For CI or a one-off session, set environment variables:
23
23
 
24
24
  ```bash
25
25
  export VALIDIN_API_KEY="your-api-key"
@@ -39,12 +39,12 @@ from validin import Client
39
39
  client = Client(api_key="your-api-key", base_url="https://your-enterprise-endpoint.example.com")
40
40
  ```
41
41
 
42
- If `base_url` is not provided, the client defaults to `https://app.validin.com`.
42
+ For each setting, the SDK checks constructor arguments, environment variables, then the saved config. The fallback endpoint is `https://app.validin.com`.
43
43
 
44
44
  ## Data and Privacy
45
45
 
46
46
  The SDK, the `validin` CLI and the agent skills talk to one server: the Validin API at
47
- `https://app.validin.com`, or the endpoint set in `VALIDIN_BASE_URL` / `base_url`. Requests use
47
+ `https://app.validin.com`, or the endpoint you configure. Requests use
48
48
  HTTPS. Nothing is sent anywhere else, and there is no telemetry or usage reporting.
49
49
 
50
50
  **Sent to the Validin API**, only as part of the request you make:
@@ -61,7 +61,7 @@ infrastructure, not your machine. The SDK never contacts the hosts it looks up.
61
61
 
62
62
  **Stored on your machine:**
63
63
 
64
- - `validin setup` saves your API key and endpoint to `~/.validin/config.json`. The file is
64
+ - `validin setup` saves your API key, endpoint and default output format to `~/.validin/config.json`. The file is
65
65
  readable only by you (mode `0600`) in a directory only you can open (`0700`). Setting
66
66
  `VALIDIN_API_KEY` instead keeps the key out of that file.
67
67
  - Shell completion, if you enable it, writes a completion script and adds one line to your
@@ -94,12 +94,18 @@ Installing the package also installs a `validin` command:
94
94
  ```bash
95
95
  validin setup # save your API key
96
96
  validin dns example.com
97
- validin lookalikes acme.com -o list | validin reputation -
97
+ validin lookalikes acme.com -o list | validin reputation
98
98
  validin pivots example.com # where a value was seen on other hosts (links, certs, redirects...)
99
99
  validin threat show sdbot # named threats, their indicators and reports
100
100
  validin commands --json # every command, option and output field
101
101
  ```
102
102
 
103
+ Omit the indicators to read them from a pipe or file, as in `validin dns < domains.txt`. When you give indicators as arguments, stdin is not read, so the CLI works inside `while read` loops.
104
+
105
+ The CLI uses the format you choose in `validin setup` for terminals, pipes and redirected files.
106
+ The default is `table`. Use `--json` or `-o FORMAT` to override it for one command.
107
+ Scripts that read JSON should request it explicitly, for example `validin dns example.com --json | jq .count`.
108
+
103
109
  ### Shell completion
104
110
 
105
111
  Tab-complete commands, subcommands, options and option values (`--mode`, `--tag`, `-o`, ...)
@@ -146,8 +152,7 @@ codex plugin add validin@validin
146
152
  **Other agents** (Cursor, Windsurf, Cline, ...): the skills are plain Markdown. Point your
147
153
  agent's rules file or `AGENTS.md` at `skills/<name>/SKILL.md`.
148
154
 
149
- The skills need the CLI installed (`pip install validin-sdk==0.2.0`) and `VALIDIN_API_KEY` set in the
150
- agent's environment.
155
+ The skills need the CLI installed (`pip install validin-sdk==0.3.0`) and access to a saved API key or `VALIDIN_API_KEY` in the agent's environment.
151
156
 
152
157
  ## Core Concepts
153
158
 
@@ -493,7 +498,7 @@ Feed a row's `value` back in to pivot again.
493
498
  Supports bulk queries. Options: `category`, `limit`, `first_seen`, `last_seen`, `lookback`, `annotate`,
494
499
  `wildcard`. Categories are case-insensitive and accept the `HOST-X` / `X-IP` forms. Known names per
495
500
  type are in `validin.PIVOT_CATEGORIES`. An IP takes only `LOCATION_IP4` (redirects to it). An unknown category returns
496
- no records rather than an error. 32/40/64-hex strings are treated as hashes.
501
+ no records rather than an error. An even-length string of 18 or more hexadecimal characters is inferred as a hash.
497
502
 
498
503
  ---
499
504
 
@@ -727,8 +732,8 @@ and saved JSON fixtures before upgrading:
727
732
  - `CertificateObservation.to_dict()` omits `type` and `time`; those attributes
728
733
  remain accessible on the object. `HostResponse.to_dict()` omits `type`;
729
734
  its `time` field remains. Use the enclosing record's type for record dispatch.
730
- - `host_responses()` accepts domains, IPs, CIDRs, and explicit hash indicators;
731
- free-text strings now raise `ValueError`. Use `pivots()` for text searches.
735
+ - `host_responses()` accepts domains, IPs, CIDRs, and hashes.
736
+ Free-text strings raise `ValueError`. Use `pivots()` for text searches.
732
737
  - Bulk lookups report per-indicator API failures, including 404s, in
733
738
  `ResultSet.errors` instead of silently skipping missing indicators.
734
739
  Authentication and rate-limit failures still stop the batch.
@@ -10,7 +10,7 @@ from __future__ import annotations
10
10
  from importlib import import_module
11
11
  from typing import TYPE_CHECKING, Any
12
12
 
13
- __version__ = "0.2.0"
13
+ __version__ = "0.3.0"
14
14
 
15
15
  # public name -> submodule that defines it
16
16
  _EXPORTS = {
@@ -0,0 +1,45 @@
1
+ """Connection settings shared by the Python client and the CLI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ from typing import Any, Optional
9
+
10
+ DEFAULT_BASE_URL = "https://app.validin.com"
11
+ ENV_API_KEY = "VALIDIN_API_KEY"
12
+ ENV_ENDPOINT = "VALIDIN_BASE_URL"
13
+
14
+
15
+ def get_config_path() -> Path:
16
+ return Path.home() / ".validin" / "config.json"
17
+
18
+
19
+ def load_config() -> dict[str, Any]:
20
+ path = get_config_path()
21
+ try:
22
+ with path.open() as f:
23
+ data = json.load(f)
24
+ except (ValueError, OSError):
25
+ return {}
26
+ return data if isinstance(data, dict) else {}
27
+
28
+
29
+ def resolve_connection(api_key: Optional[str], endpoint: Optional[str],
30
+ config: Optional[dict[str, Any]] = None) -> dict[str, Any]:
31
+ env_key = os.environ.get(ENV_API_KEY)
32
+ env_endpoint = os.environ.get(ENV_ENDPOINT)
33
+ if config is None:
34
+ config = {} if (api_key or env_key) and (endpoint or env_endpoint) else load_config()
35
+
36
+ def pick(argument, env_value, field, default=None):
37
+ for source, value in (("flag", argument), ("env", env_value),
38
+ ("config", config.get(field)), ("default", default)):
39
+ if isinstance(value, str) and value:
40
+ return value, source
41
+ return None, None
42
+
43
+ key, key_source = pick(api_key, env_key, "api_key")
44
+ url, url_source = pick(endpoint, env_endpoint, "endpoint", DEFAULT_BASE_URL)
45
+ return {"api_key": key, "base_url": url, "api_key_source": key_source, "endpoint_source": url_source}
@@ -114,7 +114,7 @@ def _commands(client, ctx):
114
114
  described = [c.describe() for c in all_commands()]
115
115
  described.append({
116
116
  "name": "setup",
117
- "summary": "Interactive: save an API key and endpoint to the config file and offer shell "
117
+ "summary": "Save your API key, endpoint and default output format. Set up shell "
118
118
  "tab completion. Needs a terminal; "
119
119
  "agents should set VALIDIN_API_KEY instead.",
120
120
  "interactive": True,
@@ -129,7 +129,7 @@ def _commands(client, ctx):
129
129
  "csv": "one result per row; nested values JSON-encoded",
130
130
  "list": "the command's list_field, one unique value per line (for piping)",
131
131
  },
132
- "default_format": "table on a terminal, json otherwise",
132
+ "default_format": ctx.settings["output_format"],
133
133
  "exit_codes": {str(k): v for k, v in EXIT_CODES.items()},
134
134
  "environment": {"VALIDIN_API_KEY": "API key", "VALIDIN_BASE_URL": "API endpoint"},
135
135
  }}})
@@ -40,7 +40,7 @@ CRAWL = Command(
40
40
  "validin crawl 203.0.113.0/24 --lookback 7 -o jsonl",
41
41
  "validin crawl example.com --json | jq -r '.results[].response.body_hash' | validin content -",
42
42
  "validin crawl fc742437c62fa1e248680e0035bafbc55923423b -o list # IPs serving this body",
43
- "validin crawl e4c0c878065037deb4ae --as hash # header_hash: not 32/40/64 hex, so say --as",
43
+ "validin crawl e4c0c878065037deb4ae # header hash",
44
44
  ),
45
45
  )
46
46
 
@@ -378,7 +378,7 @@ DELETE_ALERTS = Command(
378
378
  name="delete-alerts",
379
379
  summary="Delete alert records by alert_rowid (from `validin project alerts --json`).",
380
380
  handler=_delete_alerts,
381
- positional=[PROJECT, Positional("alert_rowid", "alert_rowid values; '-' reads them from stdin.", nargs="+")],
381
+ positional=[PROJECT, Positional("alert_rowid", "alert_rowid values; omit to read stdin, one per line.", nargs="*")],
382
382
  columns=("key", "action", "requested", "deleted"),
383
383
  fields=("key", "key_type", "type", "action", "requested", "deleted"),
384
384
  list_field="key",
@@ -426,7 +426,7 @@ SHARE = Command(
426
426
  summary="Share a project with existing users by user_id or email (enterprise). "
427
427
  "Current members keep their permissions.",
428
428
  handler=_share,
429
- positional=[PROJECT, Positional("user", "user_id or email; '-' reads them from stdin.", nargs="+")],
429
+ positional=[PROJECT, Positional("user", "user_id or email; omit to read stdin, one per line.", nargs="*")],
430
430
  options=[Option(["--permission"], "Permission for the new members (default: view).",
431
431
  {"choices": SHARE_PERMISSIONS, "default": "view"}),
432
432
  Option(["--alert"], "Send them the project's alerts.", {"action": "store_true"}),
@@ -573,7 +573,7 @@ RESOURCE_DELETE = Command(
573
573
  name="resource-delete",
574
574
  summary="Delete reference links from a project; links it doesn't have are ignored.",
575
575
  handler=_resource_delete,
576
- positional=[PROJECT, Positional("url", "URLs to delete; '-' reads them from stdin.", nargs="+")],
576
+ positional=[PROJECT, Positional("url", "URLs to delete; omit to read stdin, one per line.", nargs="*")],
577
577
  columns=("key", "action"),
578
578
  fields=(*RESOURCE_FIELDS, "action"),
579
579
  list_field="key",
@@ -5,19 +5,19 @@ from __future__ import annotations
5
5
  import sys
6
6
 
7
7
  from validin.cli import render
8
- from validin.cli.config import ENV_API_KEY
8
+ from validin._config import ENV_API_KEY, load_config
9
+ from validin.cli.config import output_format
9
10
  from validin.cli.runner import EXIT_OK, EXIT_USAGE
10
11
 
11
12
 
12
13
  def register(subparsers) -> None:
13
14
  p = subparsers.add_parser(
14
15
  "setup",
15
- help="Interactively save your API key and endpoint, and set up tab completion "
16
+ help="Interactively save your API key, endpoint and output format, and set up tab completion "
16
17
  "(needs a terminal).",
17
- description="Prompts for an API key (input hidden) and endpoint, verifies them against "
18
- f"the API, and saves them to ~/.validin/config.json. Then offers tab completion "
19
- "for bash, zsh or fish (rerun it to refresh). In scripts or agents, "
20
- f"set {ENV_API_KEY} instead.",
18
+ description="Verify your API key and endpoint, choose a default output format, "
19
+ "and save these settings to ~/.validin/config.json. You can also enable "
20
+ f"shell completion. For unattended setup, set {ENV_API_KEY} in the environment.",
21
21
  )
22
22
  p.set_defaults(setup=True)
23
23
 
@@ -29,7 +29,7 @@ def run(stdin=None, stdout=None, stderr=None) -> int:
29
29
  {"code": "not_interactive", "status": None,
30
30
  "message": "`validin setup` is interactive and needs a terminal.",
31
31
  "hint": f"Set {ENV_API_KEY} (and optionally VALIDIN_BASE_URL) instead."},
32
- render.default_format(stdout), stderr,
32
+ output_format(load_config()), stderr,
33
33
  )
34
34
  return EXIT_USAGE
35
35
 
@@ -13,7 +13,7 @@ GROUP_FIELDS = ("key", "key_type", "type", "first_seen", "last_seen", "threat_ke
13
13
  "description_references", "mitre_ttps", "activity_period", "activity", "last_updated")
14
14
 
15
15
  THREAT_KEYS = Positional("threat_key", "Threat key(s), e.g. sdbot (see `validin threat list`); "
16
- "'-' reads them from stdin.", nargs="+")
16
+ "omit to read stdin, one per line.", nargs="*")
17
17
 
18
18
 
19
19
  def _list(client, ctx):
@@ -9,7 +9,7 @@ from validin.cli.runner import Command, Group, Option, Positional, usage_error
9
9
  PROJECT = Option(["-p", "--project"], "Project id that holds the rules.",
10
10
  {"required": True, "metavar": "ID"})
11
11
  RULE = Positional("rule", "Rule id (see `validin yara list`).")
12
- SOURCE_FILE = Positional("file", "File with the full YARA source; '-' reads stdin.")
12
+ SOURCE_FILE = Positional("file", "File with the full YARA source. Omit to read stdin.", nargs="?")
13
13
  VERSION = Option(["--version"], "Rule version (default: the latest).", {"type": int, "metavar": "N"})
14
14
  SOURCES = Option(["--source"], f"Content to match; repeatable ({', '.join(YARA_SOURCES)}; default: all).",
15
15
  {"action": "append", "choices": YARA_SOURCES})
@@ -241,7 +241,7 @@ DELETE_MATCHES = Command(
241
241
  name="delete-matches",
242
242
  summary="Delete a rule's matches by row ID (the row_ids field of `validin yara matches --json`).",
243
243
  handler=_delete_matches,
244
- positional=[RULE, Positional("row_id", "Match row IDs; '-' reads them from stdin.", nargs="+")],
244
+ positional=[RULE, Positional("row_id", "Match row IDs; omit to read stdin, one per line.", nargs="*")],
245
245
  options=[PROJECT],
246
246
  columns=("key", "action", "requested", "deleted"),
247
247
  fields=("key", "key_type", "type", "rule_id", "project_id", "action", "requested", "deleted"),
@@ -5,30 +5,16 @@ from __future__ import annotations
5
5
  import json
6
6
  import os
7
7
  import tempfile
8
- from pathlib import Path
9
8
  from typing import Any, Optional
10
9
 
11
- _DEFAULT_ENDPOINT = "https://app.validin.com"
10
+ from validin._config import get_config_path, load_config, resolve_connection
12
11
 
13
- # Same variable names the SDK's Client reads, so one environment serves both.
14
- ENV_API_KEY = "VALIDIN_API_KEY"
15
- ENV_ENDPOINT = "VALIDIN_BASE_URL"
12
+ OUTPUT_FORMATS = ("table", "json", "jsonl", "csv", "list")
16
13
 
17
14
 
18
- def get_config_path() -> Path:
19
- return Path.home() / ".validin" / "config.json"
20
-
21
-
22
- def load_config() -> dict[str, Any]:
23
- path = get_config_path()
24
- if not path.exists():
25
- return {}
26
- try:
27
- with path.open() as f:
28
- data = json.load(f)
29
- except (json.JSONDecodeError, OSError):
30
- return {}
31
- return data if isinstance(data, dict) else {}
15
+ def output_format(config: dict[str, Any]) -> str:
16
+ value = config.get("output_format")
17
+ return value if value in OUTPUT_FORMATS else "table"
32
18
 
33
19
 
34
20
  def save_config(data: dict[str, Any]) -> None:
@@ -64,23 +50,8 @@ def resolve_settings(
64
50
  """
65
51
  file_cfg = load_config()
66
52
 
67
- def pick(flag_value, env_name, cfg_name, default=None):
68
- for source, value in (
69
- ("flag", flag_value),
70
- ("env", os.environ.get(env_name)),
71
- ("config", file_cfg.get(cfg_name)),
72
- ("default", default),
73
- ):
74
- if value:
75
- return value, source
76
- return None, None
77
-
78
- key, key_source = pick(api_key, ENV_API_KEY, "api_key")
79
- base_url, endpoint_source = pick(endpoint, ENV_ENDPOINT, "endpoint", _DEFAULT_ENDPOINT)
80
53
  return {
81
- "api_key": key,
82
- "api_key_source": key_source,
83
- "base_url": base_url,
84
- "endpoint_source": endpoint_source,
54
+ **resolve_connection(api_key, endpoint, file_cfg),
55
+ "output_format": output_format(file_cfg),
85
56
  "config_path": str(get_config_path()),
86
57
  }
@@ -7,6 +7,8 @@ import sys
7
7
  from typing import List, Optional
8
8
 
9
9
  from validin.cli import render
10
+ from validin._config import load_config
11
+ from validin.cli.config import output_format
10
12
  from validin.cli.runner import EXIT_USAGE, Group, add_command, add_group, common_parent, execute
11
13
 
12
14
 
@@ -30,7 +32,7 @@ def _format_from_argv(argv: List[str]) -> str:
30
32
  return argv[i + 1]
31
33
  if arg.startswith("--output="):
32
34
  return arg.split("=", 1)[1]
33
- return render.default_format()
35
+ return output_format(load_config())
34
36
 
35
37
 
36
38
  def build_parser() -> argparse.ArgumentParser:
@@ -40,7 +42,7 @@ def build_parser() -> argparse.ArgumentParser:
40
42
  parser = _Parser(
41
43
  prog="validin",
42
44
  description="Validin threat intelligence from the command line. "
43
- "Output is a table on a terminal and JSON when piped; "
45
+ "Choose your default output format with validin setup. "
44
46
  "`validin commands --json` describes everything for scripts and agents.",
45
47
  epilog="examples:\n"
46
48
  " validin setup\n"
@@ -8,7 +8,8 @@ from typing import Any, Optional, Tuple
8
8
  import requests
9
9
 
10
10
  from validin.cli import term
11
- from validin.cli.config import _DEFAULT_ENDPOINT, get_config_path, load_config, save_config
11
+ from validin._config import DEFAULT_BASE_URL, get_config_path, load_config
12
+ from validin.cli.config import OUTPUT_FORMATS, output_format, save_config
12
13
  from validin.errors import ApiError
13
14
 
14
15
  _VERIFY_PATH = "api/profile/usage"
@@ -66,7 +67,7 @@ def run_setup(intro: bool = True) -> Optional[dict[str, Any]]:
66
67
  print()
67
68
 
68
69
  key = _ask_key(cfg.get("api_key"))
69
- endpoint = term.prompt("API endpoint", cfg.get("endpoint") or _DEFAULT_ENDPOINT)
70
+ endpoint = term.prompt("API endpoint", cfg.get("endpoint") or DEFAULT_BASE_URL)
70
71
 
71
72
  while True:
72
73
  with term.Spinner(f"Verifying credentials against {endpoint}"):
@@ -92,6 +93,7 @@ def run_setup(intro: bool = True) -> Optional[dict[str, Any]]:
92
93
 
93
94
  cfg["api_key"] = key
94
95
  cfg["endpoint"] = endpoint
96
+ cfg["output_format"] = term.select("Default output format", OUTPUT_FORMATS, current=output_format(cfg))
95
97
  save_config(cfg)
96
98
  print(f"{term.CHECK} Saved to {term.dim(str(get_config_path()))}")
97
99
  offer_completion()
@@ -23,8 +23,6 @@ import shutil
23
23
  import sys
24
24
  from typing import Any, Iterable, Optional, Sequence, TextIO
25
25
 
26
- FORMATS = ("table", "json", "jsonl", "csv", "list")
27
-
28
26
 
29
27
  def is_tty(stream: TextIO) -> bool:
30
28
  try:
@@ -33,10 +31,6 @@ def is_tty(stream: TextIO) -> bool:
33
31
  return False
34
32
 
35
33
 
36
- def default_format(stream: TextIO = None) -> str:
37
- return "table" if is_tty(stream or sys.stdout) else "json"
38
-
39
-
40
34
  def color_enabled(stream: TextIO) -> bool:
41
35
  return is_tty(stream) and not os.environ.get("NO_COLOR")
42
36
 
@@ -224,7 +218,7 @@ def _write_summary(envelope: dict, err: TextIO) -> None:
224
218
  count = envelope.get("count", 0)
225
219
  note = f"{count} result{'s' if count != 1 else ''}"
226
220
  if envelope.get("truncated"):
227
- note += " (truncated by the API limit; raise --limit or narrow the query)"
221
+ note = f"* {note} (truncated by the API limit; raise --limit or narrow the query)"
228
222
  err.write(note + "\n")
229
223
 
230
224
 
@@ -9,10 +9,9 @@ every command behaves the same way for people and for agents.
9
9
  from __future__ import annotations
10
10
 
11
11
  import argparse
12
- import re
13
12
  import sys
14
13
  from dataclasses import dataclass, field
15
- from typing import Any, Callable, Iterable, List, Optional, Sequence, TextIO
14
+ from typing import Any, Callable, Iterable, Iterator, List, Optional, Sequence, TextIO
16
15
 
17
16
  # `requests` is imported lazily (in execute): building the parser for --help
18
17
  # and shell completion shouldn't pay ~100ms for it.
@@ -20,7 +19,8 @@ from validin.errors import ApiError, AuthError
20
19
  from validin.indicator import Indicator, IndicatorType, infer_indicator_type
21
20
  from validin.result_set import ResultSet
22
21
  from validin.cli import render
23
- from validin.cli.config import ENV_API_KEY, resolve_settings
22
+ from validin._config import ENV_API_KEY
23
+ from validin.cli.config import OUTPUT_FORMATS, resolve_settings
24
24
 
25
25
  # Exit codes (documented in `validin commands`).
26
26
  EXIT_OK = 0 # success, including zero results
@@ -114,7 +114,7 @@ class Positional:
114
114
 
115
115
  name: str
116
116
  help: str
117
- # argparse nargs ("+" for one or more); None means exactly one.
117
+ # argparse nargs. None means exactly one argument.
118
118
  nargs: Optional[str] = None
119
119
 
120
120
 
@@ -156,10 +156,10 @@ class Command:
156
156
  data["indicators"] = {
157
157
  "types": [t.value for t in self.indicator_types],
158
158
  "multiple": True,
159
- "stdin": "pass '-' to read one indicator per line",
159
+ "stdin": "omit indicators or pass '-' alone to read stdin, one per line",
160
160
  }
161
161
  if self.positionals:
162
- data["arguments"] = [{"name": p.name, "help": p.help, **({"multiple": True} if p.nargs else {})}
162
+ data["arguments"] = [{"name": p.name, "help": p.help, **({"multiple": True} if p.nargs in ("*", "+") else {})}
163
163
  for p in self.positionals]
164
164
  data["options"] = [o.describe() for o in self.options]
165
165
  data["output"] = {
@@ -196,11 +196,11 @@ class Context:
196
196
  # Where notes and warnings go (stderr unless a caller redirects it).
197
197
  err: Optional[TextIO] = None
198
198
 
199
- def read_text(self, path: str) -> str:
199
+ def read_text(self, path: Optional[str]) -> str:
200
200
  """Contents of a file argument; '-' reads stdin."""
201
- if path == "-":
201
+ if path in (None, "-"):
202
202
  if self.stdin is None or render.is_tty(self.stdin):
203
- raise usage_error("'-' reads from stdin, but nothing is piped in.")
203
+ raise usage_error("Provide a file or pipe its contents to stdin.")
204
204
  return self.stdin.read()
205
205
  try:
206
206
  with open(path, encoding="utf-8") as f:
@@ -212,7 +212,7 @@ class Context:
212
212
  """Positional values where '-' reads one per line from stdin ('#' lines skipped)."""
213
213
  if self.stdin is None:
214
214
  return [v for v in values if v != "-"]
215
- return read_indicators(values, self.stdin)
215
+ return _read_values(values, self.stdin)
216
216
 
217
217
  @property
218
218
  def targets(self) -> Any:
@@ -226,8 +226,8 @@ def common_parent() -> argparse.ArgumentParser:
226
226
  """Flags every command accepts, placed after the command name."""
227
227
  parent = argparse.ArgumentParser(add_help=False)
228
228
  group = parent.add_argument_group("output and connection")
229
- group.add_argument("-o", "--output", choices=render.FORMATS, default=None,
230
- help="Output format (default: table on a terminal, json when piped).")
229
+ group.add_argument("-o", "--output", choices=OUTPUT_FORMATS, default=None,
230
+ help="Output format (overrides the default saved by validin setup).")
231
231
  group.add_argument("--json", dest="output", action="store_const", const="json",
232
232
  help="Shorthand for -o json.")
233
233
  group.add_argument("--api-key", default=None, metavar="KEY",
@@ -267,8 +267,8 @@ def add_command(subparsers, command: Command, parent: argparse.ArgumentParser) -
267
267
  p.add_argument(positional.name, help=positional.help, metavar=positional.name.upper(), **extra)
268
268
  if command.indicator_types:
269
269
  names = "|".join(t.value for t in command.indicator_types)
270
- p.add_argument("indicators", nargs="+", metavar="INDICATOR",
271
- help=f"One or more indicators ({names}); '-' reads them from stdin.")
270
+ p.add_argument("indicators", nargs="*", metavar="INDICATOR",
271
+ help=f"Indicators ({names}). Omit to read stdin, one per line; stdin is not read when indicators are given.")
272
272
  p.add_argument("--as", dest="as_type", default=None, metavar="TYPE",
273
273
  choices=[t.value for t in command.indicator_types],
274
274
  help="Treat every indicator as this type instead of inferring it.")
@@ -279,35 +279,39 @@ def add_command(subparsers, command: Command, parent: argparse.ArgumentParser) -
279
279
 
280
280
  # -- execution ----------------------------------------------------------------
281
281
 
282
+ def _stdin_values(stdin: TextIO) -> Iterator[str]:
283
+ for line in stdin:
284
+ value = line.strip()
285
+ if value and not value.startswith("#"):
286
+ yield value
287
+
288
+
282
289
  def read_indicators(values: Sequence[str], stdin: TextIO) -> List[str]:
290
+ # Never peek at stdin when arguments are given: in `while read x; do validin dns "$x"; done`
291
+ # it holds the loop's input, and agents or cron may leave it open without ever closing it.
292
+ if any(value != "-" for value in values):
293
+ if "-" in values:
294
+ raise usage_error("Indicators supplied on the command line and stdin. Use one input source.")
295
+ return list(dict.fromkeys(values))
296
+ return _read_values(values, stdin)
297
+
298
+
299
+ def _read_values(values: Sequence[str], stdin: TextIO) -> List[str]:
283
300
  out: List[str] = []
284
- for value in values:
301
+ if not values and render.is_tty(stdin):
302
+ raise usage_error("Provide input as arguments or pipe it to stdin.")
303
+ for value in values or ("-",):
285
304
  if value == "-":
286
305
  if render.is_tty(stdin):
287
306
  raise usage_error("'-' reads indicators from stdin, but stdin is a terminal.",
288
307
  hint="Pipe indicators in, e.g. `cat iocs.txt | validin dns -`.")
289
- for line in stdin:
290
- line = line.strip()
291
- if line and not line.startswith("#"):
292
- out.append(line)
308
+ out.extend(_stdin_values(stdin))
293
309
  else:
294
310
  out.append(value)
295
311
  # Keep order, drop exact duplicates.
296
312
  return list(dict.fromkeys(out))
297
313
 
298
314
 
299
- _HASH_RE = re.compile(r"[0-9a-fA-F]{32}|[0-9a-fA-F]{40}|[0-9a-fA-F]{64}")
300
-
301
-
302
- def _infer(value: str, allowed: Sequence[IndicatorType]) -> IndicatorType:
303
- """Like the SDK's inference, plus MD5/SHA-1/SHA-256 where a command takes hashes."""
304
- # Hex hashes are also valid domain values, so check them first where a
305
- # command takes hashes.
306
- if IndicatorType.HASH in allowed and _HASH_RE.fullmatch(value):
307
- return IndicatorType.HASH
308
- return infer_indicator_type(value)
309
-
310
-
311
315
  def parse_indicators(raw: Sequence[str], allowed: Sequence[IndicatorType],
312
316
  as_type: Optional[str], normalize: Optional[Callable[[str], str]] = None) -> tuple:
313
317
  indicators, errors = [], []
@@ -315,7 +319,10 @@ def parse_indicators(raw: Sequence[str], allowed: Sequence[IndicatorType],
315
319
  if normalize:
316
320
  value = normalize(value)
317
321
  try:
318
- kind = IndicatorType(as_type) if as_type else _infer(value, allowed)
322
+ kind = IndicatorType(as_type) if as_type else infer_indicator_type(value)
323
+ if not as_type and kind not in allowed and kind == IndicatorType.HASH and IndicatorType.STRING in allowed:
324
+ # A hex-only value where hashes aren't taken is a text token (TXT record, verification code).
325
+ kind = IndicatorType.STRING
319
326
  indicator = Indicator(value, kind)
320
327
  except ValueError as exc:
321
328
  errors.append({"indicator": value, "code": "invalid_indicator", "status": None,
@@ -389,17 +396,20 @@ def execute(args: argparse.Namespace, *, stdin: TextIO = None, out: TextIO = Non
389
396
 
390
397
  stdin, out, err = stdin or sys.stdin, out or sys.stdout, err or sys.stderr
391
398
  command: Command = args.handler_command
392
- fmt = args.output or render.default_format(out)
399
+ settings = resolve_settings(api_key=args.api_key, endpoint=args.endpoint)
400
+ fmt = args.output or settings["output_format"]
393
401
 
394
402
  try:
395
403
  check_date_window(args)
396
- settings = resolve_settings(api_key=args.api_key, endpoint=args.endpoint)
397
404
  ctx = Context(args=args, settings=settings, stdin=stdin, fmt=fmt, err=err)
398
405
 
399
406
  if command.indicator_types:
400
407
  raw = read_indicators(args.indicators, stdin)
408
+ as_type = args.as_type
409
+ if command.name == "registration" and args.field and not as_type:
410
+ as_type = IndicatorType.STRING.value
401
411
  ctx.indicators, ctx.input_errors = parse_indicators(
402
- raw, command.indicator_types, args.as_type, command.normalize)
412
+ raw, command.indicator_types, as_type, command.normalize)
403
413
  if not ctx.indicators:
404
414
  if ctx.input_errors and len(ctx.input_errors) == 1:
405
415
  only = ctx.input_errors[0]
@@ -2,7 +2,6 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- import os
6
5
  import re
7
6
  from collections.abc import Callable, Sequence
8
7
  from datetime import date, datetime, timezone
@@ -12,6 +11,7 @@ from urllib.parse import urljoin
12
11
 
13
12
  import requests
14
13
 
14
+ from ._config import DEFAULT_BASE_URL, resolve_connection
15
15
  from ._dates import date_window, normalize_date
16
16
  from ._inputs import is_many as _is_bulk
17
17
  from . import _clock as time_module
@@ -39,7 +39,6 @@ from .scan_record import ScanRecord
39
39
  from .subdomain_record import SubdomainRecord
40
40
  from .yara_match_record import YaraMatchRecord
41
41
 
42
- DEFAULT_BASE_URL = "https://app.validin.com"
43
42
  DEFAULT_BULK_MAX_RETRIES = 2
44
43
  DEFAULT_BULK_RETRY_BACKOFF_SECONDS = 0.5
45
44
  DEFAULT_BULK_RETRY_STATUS_CODES = frozenset({408, 425, 429, 500, 502, 503, 504})
@@ -84,7 +83,8 @@ class Client(ProjectsMixin, OpenDirectoriesMixin, BulkMixin, PivotsMixin, OsintM
84
83
  bulk_retry_backoff_seconds: float = DEFAULT_BULK_RETRY_BACKOFF_SECONDS,
85
84
  bulk_retry_status_codes: Optional[Iterable[int]] = None,
86
85
  ) -> None:
87
- resolved_key = api_key or os.getenv("VALIDIN_API_KEY")
86
+ settings = resolve_connection(api_key, base_url)
87
+ resolved_key = settings["api_key"]
88
88
  if not resolved_key:
89
89
  raise ValueError("api_key is required")
90
90
  if bulk_max_retries < 0:
@@ -92,8 +92,7 @@ class Client(ProjectsMixin, OpenDirectoriesMixin, BulkMixin, PivotsMixin, OsintM
92
92
  if bulk_retry_backoff_seconds < 0:
93
93
  raise ValueError("bulk_retry_backoff_seconds must be >= 0")
94
94
 
95
- resolved_base = base_url or os.getenv("VALIDIN_BASE_URL") or DEFAULT_BASE_URL
96
- self.base_url = _ensure_scheme(resolved_base).rstrip("/") + "/"
95
+ self.base_url = _ensure_scheme(settings["base_url"]).rstrip("/") + "/"
97
96
  self.timeout = timeout
98
97
  self.bulk_max_retries = int(bulk_max_retries)
99
98
  self.bulk_retry_backoff_seconds = float(bulk_retry_backoff_seconds)
@@ -678,6 +677,11 @@ class Client(ProjectsMixin, OpenDirectoriesMixin, BulkMixin, PivotsMixin, OsintM
678
677
  lookback=lookback, annotate=annotate, wildcard=wildcard,
679
678
  include_fields=include_fields, field=field,
680
679
  )
680
+ if _is_bulk(indicator) and field is not None:
681
+ # A field value is literal text even when it resembles a hash.
682
+ return self._run_bulk_query(indicator, run, coerce=lambda item: (
683
+ item if isinstance(item, Indicator) else Indicator(str(item), IndicatorType.STRING)
684
+ ))
681
685
  return self._run_bulk_query(indicator, run) if _is_bulk(indicator) else run(indicator)
682
686
 
683
687
  def get_registration_history(
@@ -1040,6 +1044,11 @@ class Client(ProjectsMixin, OpenDirectoriesMixin, BulkMixin, PivotsMixin, OsintM
1040
1044
  wildcard: Optional[bool],
1041
1045
  ) -> tuple[Indicator, Optional[bool]]:
1042
1046
  indicator = self._coerce_indicator(value)
1047
+ if indicator.type == IndicatorType.HASH and not isinstance(value, Indicator):
1048
+ # Inferred, not requested: a hex-only value here is a text token (TXT record, verification code).
1049
+ indicator = Indicator(indicator.value, IndicatorType.STRING)
1050
+ if indicator.type == IndicatorType.HASH:
1051
+ raise UnsupportedIndicatorError("Hash indicators are unsupported for DNS and registration history")
1043
1052
  return _normalize_string_wildcard(indicator, wildcard)
1044
1053
 
1045
1054
  def _coerce_content_hash(self, value: Union[Indicator, str, HostResponse], kind: str = "html") -> str:
@@ -30,12 +30,9 @@ class IndicatorType(str, Enum):
30
30
  return cls.STRING
31
31
 
32
32
 
33
- # Validin indexes domain names using these 39 characters. A value is only
34
- # typed as a domain when it can reasonably name one: the portal's
35
- # SerJudy::Util.valid_domain? rules, plus at least two labels so single words
36
- # (a registrar such as "MarkMonitor", a TXT token) stay strings.
33
+ # Require a dotted name so single words such as registrar names stay strings.
37
34
  _DOMAIN_CHARS = re.compile(r"[a-z0-9._-]+")
38
- _DIGIT = re.compile(r"[0-9]")
35
+ _HEX_CHARS = re.compile(r"[0-9a-fA-F]+")
39
36
 
40
37
 
41
38
  def _is_domain_value(value: str) -> bool:
@@ -60,10 +57,7 @@ def _is_domain_value(value: str) -> bool:
60
57
  # Underscores are allowed below the registered name (_dmarc, _domainkey).
61
58
  if index >= len(labels) - 2 and "_" in label:
62
59
  return False
63
- tld = labels[-1]
64
- if len(tld) < 2 or tld[0].isdigit():
65
- return False
66
- return tld.startswith("xn--") or not _DIGIT.search(tld)
60
+ return True
67
61
 
68
62
 
69
63
  def _is_cidr(value: str) -> bool:
@@ -93,6 +87,9 @@ def infer_indicator_type(value: str) -> IndicatorType:
93
87
  if _is_cidr(value):
94
88
  return IndicatorType.CIDR
95
89
 
90
+ if len(value) > 16 and len(value) % 2 == 0 and _HEX_CHARS.fullmatch(value):
91
+ return IndicatorType.HASH
92
+
96
93
  if _is_domain_value(value):
97
94
  return IndicatorType.DOMAIN
98
95
 
@@ -30,7 +30,6 @@ PIVOT_CATEGORIES: Dict[str, tuple] = {
30
30
  }
31
31
 
32
32
  _CATEGORY = re.compile(r"\A[A-Z0-9_]+\Z")
33
- _HEX_HASH = re.compile(r"\A(?:[0-9a-fA-F]{32}|[0-9a-fA-F]{40}|[0-9a-fA-F]{64})\Z")
34
33
 
35
34
 
36
35
  def normalize_pivot_category(category: str) -> str:
@@ -88,9 +87,8 @@ class PivotsMixin:
88
87
  - **String:** hosts whose server banner, title, certificate fields... contain it.
89
88
 
90
89
  ``category`` (e.g. ``"TITLE"``, ``"BODY_SHA1"``) limits the lookup to one
91
- category; an IP takes only ``LOCATION_IP4``, and a CIDR takes none. A value of 32, 40 or 64 hex
92
- characters is looked up as a hash; pass ``Indicator(value,
93
- IndicatorType.HASH)`` for other hashes (header or banner hashes).
90
+ category; an IP takes only ``LOCATION_IP4``, and a CIDR takes none. Hex strings of even length
91
+ greater than 16 are inferred as hashes.
94
92
  Returns :class:`PivotRecord` objects.
95
93
  """
96
94
  category_name = normalize_pivot_category(category) if category is not None else None
@@ -102,19 +100,11 @@ class PivotsMixin:
102
100
  return self._build_pivot_result_set(payload, indicator_obj)
103
101
 
104
102
  if is_many(indicator, (str, bytes, Indicator)):
105
- return self._run_bulk_query(indicator, run, coerce=self._coerce_pivot_indicator)
106
- return run(self._coerce_pivot_indicator(indicator))
103
+ return self._run_bulk_query(indicator, run)
104
+ return run(self._coerce_indicator(indicator))
107
105
 
108
106
  # -- helpers ----------------------------------------------------------
109
107
 
110
- def _coerce_pivot_indicator(self, value: Union[Indicator, str]) -> Indicator:
111
- if isinstance(value, Indicator):
112
- return value
113
- text = str(value)
114
- if _HEX_HASH.match(text):
115
- return Indicator(text, IndicatorType.HASH)
116
- return Indicator.from_str(text)
117
-
118
108
  @staticmethod
119
109
  def _pivots_request(indicator: Indicator, category: Optional[str]) -> tuple:
120
110
  value = indicator.value # domains, IPs and hex hashes are path-safe
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: validin-sdk
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: A lightweight Python SDK for the Validin API
5
5
  Author-email: Elliot Roe <elliot@validin.com>, Sreekar Madabushi <sreekar@validin.com>
6
6
  Classifier: Programming Language :: Python :: 3
@@ -33,7 +33,7 @@ from validin import Client
33
33
 
34
34
  ## Configuration
35
35
 
36
- The client requires an API key. The simplest approach is to set environment variables:
36
+ Run `validin setup` once to save your API key and endpoint. Python scripts running as the same user can then call `Client()`. For CI or a one-off session, set environment variables:
37
37
 
38
38
  ```bash
39
39
  export VALIDIN_API_KEY="your-api-key"
@@ -53,12 +53,12 @@ from validin import Client
53
53
  client = Client(api_key="your-api-key", base_url="https://your-enterprise-endpoint.example.com")
54
54
  ```
55
55
 
56
- If `base_url` is not provided, the client defaults to `https://app.validin.com`.
56
+ For each setting, the SDK checks constructor arguments, environment variables, then the saved config. The fallback endpoint is `https://app.validin.com`.
57
57
 
58
58
  ## Data and Privacy
59
59
 
60
60
  The SDK, the `validin` CLI and the agent skills talk to one server: the Validin API at
61
- `https://app.validin.com`, or the endpoint set in `VALIDIN_BASE_URL` / `base_url`. Requests use
61
+ `https://app.validin.com`, or the endpoint you configure. Requests use
62
62
  HTTPS. Nothing is sent anywhere else, and there is no telemetry or usage reporting.
63
63
 
64
64
  **Sent to the Validin API**, only as part of the request you make:
@@ -75,7 +75,7 @@ infrastructure, not your machine. The SDK never contacts the hosts it looks up.
75
75
 
76
76
  **Stored on your machine:**
77
77
 
78
- - `validin setup` saves your API key and endpoint to `~/.validin/config.json`. The file is
78
+ - `validin setup` saves your API key, endpoint and default output format to `~/.validin/config.json`. The file is
79
79
  readable only by you (mode `0600`) in a directory only you can open (`0700`). Setting
80
80
  `VALIDIN_API_KEY` instead keeps the key out of that file.
81
81
  - Shell completion, if you enable it, writes a completion script and adds one line to your
@@ -108,12 +108,18 @@ Installing the package also installs a `validin` command:
108
108
  ```bash
109
109
  validin setup # save your API key
110
110
  validin dns example.com
111
- validin lookalikes acme.com -o list | validin reputation -
111
+ validin lookalikes acme.com -o list | validin reputation
112
112
  validin pivots example.com # where a value was seen on other hosts (links, certs, redirects...)
113
113
  validin threat show sdbot # named threats, their indicators and reports
114
114
  validin commands --json # every command, option and output field
115
115
  ```
116
116
 
117
+ Omit the indicators to read them from a pipe or file, as in `validin dns < domains.txt`. When you give indicators as arguments, stdin is not read, so the CLI works inside `while read` loops.
118
+
119
+ The CLI uses the format you choose in `validin setup` for terminals, pipes and redirected files.
120
+ The default is `table`. Use `--json` or `-o FORMAT` to override it for one command.
121
+ Scripts that read JSON should request it explicitly, for example `validin dns example.com --json | jq .count`.
122
+
117
123
  ### Shell completion
118
124
 
119
125
  Tab-complete commands, subcommands, options and option values (`--mode`, `--tag`, `-o`, ...)
@@ -160,8 +166,7 @@ codex plugin add validin@validin
160
166
  **Other agents** (Cursor, Windsurf, Cline, ...): the skills are plain Markdown. Point your
161
167
  agent's rules file or `AGENTS.md` at `skills/<name>/SKILL.md`.
162
168
 
163
- The skills need the CLI installed (`pip install validin-sdk==0.2.0`) and `VALIDIN_API_KEY` set in the
164
- agent's environment.
169
+ The skills need the CLI installed (`pip install validin-sdk==0.3.0`) and access to a saved API key or `VALIDIN_API_KEY` in the agent's environment.
165
170
 
166
171
  ## Core Concepts
167
172
 
@@ -507,7 +512,7 @@ Feed a row's `value` back in to pivot again.
507
512
  Supports bulk queries. Options: `category`, `limit`, `first_seen`, `last_seen`, `lookback`, `annotate`,
508
513
  `wildcard`. Categories are case-insensitive and accept the `HOST-X` / `X-IP` forms. Known names per
509
514
  type are in `validin.PIVOT_CATEGORIES`. An IP takes only `LOCATION_IP4` (redirects to it). An unknown category returns
510
- no records rather than an error. 32/40/64-hex strings are treated as hashes.
515
+ no records rather than an error. An even-length string of 18 or more hexadecimal characters is inferred as a hash.
511
516
 
512
517
  ---
513
518
 
@@ -741,8 +746,8 @@ and saved JSON fixtures before upgrading:
741
746
  - `CertificateObservation.to_dict()` omits `type` and `time`; those attributes
742
747
  remain accessible on the object. `HostResponse.to_dict()` omits `type`;
743
748
  its `time` field remains. Use the enclosing record's type for record dispatch.
744
- - `host_responses()` accepts domains, IPs, CIDRs, and explicit hash indicators;
745
- free-text strings now raise `ValueError`. Use `pivots()` for text searches.
749
+ - `host_responses()` accepts domains, IPs, CIDRs, and hashes.
750
+ Free-text strings raise `ValueError`. Use `pivots()` for text searches.
746
751
  - Bulk lookups report per-indicator API failures, including 404s, in
747
752
  `ResultSet.errors` instead of silently skipping missing indicators.
748
753
  Authentication and rate-limit failures still stop the batch.
@@ -5,6 +5,7 @@ setup.cfg
5
5
  setup.py
6
6
  src/validin/__init__.py
7
7
  src/validin/_clock.py
8
+ src/validin/_config.py
8
9
  src/validin/_dates.py
9
10
  src/validin/_inputs.py
10
11
  src/validin/_pacing.py
File without changes
File without changes
File without changes
File without changes