urlscope 0.1.3rc1__py3-none-any.whl

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.
urlscope/__init__.py ADDED
@@ -0,0 +1,54 @@
1
+ from ._client import UrlscopeClient
2
+ from ._exceptions import (
3
+ APIError,
4
+ AuthenticationError,
5
+ NotFoundError,
6
+ RateLimitError,
7
+ ScanDeletedError,
8
+ ScanTimeoutError,
9
+ UrlscopeError,
10
+ ValidationError,
11
+ )
12
+ from ._sync import SyncClient
13
+ from .models import (
14
+ BrandMatch,
15
+ CertificateInfo,
16
+ PageInfo,
17
+ QuotaInfo,
18
+ QuotaWindow,
19
+ ScanLists,
20
+ ScanResult,
21
+ SearchResponse,
22
+ SearchResultItem,
23
+ SubmissionResponse,
24
+ TaskInfo,
25
+ Verdicts,
26
+ )
27
+
28
+ __version__ = "0.1.3rc1"
29
+
30
+ __all__ = [
31
+ "UrlscopeClient",
32
+ "SyncClient",
33
+ "SubmissionResponse",
34
+ "ScanResult",
35
+ "TaskInfo",
36
+ "PageInfo",
37
+ "QuotaInfo",
38
+ "QuotaWindow",
39
+ "Verdicts",
40
+ "BrandMatch",
41
+ "ScanLists",
42
+ "CertificateInfo",
43
+ "SearchResponse",
44
+ "SearchResultItem",
45
+ "UrlscopeError",
46
+ "AuthenticationError",
47
+ "NotFoundError",
48
+ "ScanDeletedError",
49
+ "ValidationError",
50
+ "RateLimitError",
51
+ "ScanTimeoutError",
52
+ "APIError",
53
+ "__version__",
54
+ ]
urlscope/_client.py ADDED
@@ -0,0 +1,158 @@
1
+ import asyncio
2
+ import logging
3
+ import time
4
+ from typing import Any, Literal
5
+
6
+ from ._exceptions import NotFoundError, ScanDeletedError, ScanTimeoutError
7
+ from ._http import _HTTPTransport
8
+ from .models import QuotaInfo, ScanResult, SearchResponse, SubmissionResponse
9
+
10
+ LOGGER = logging.getLogger("urlscope")
11
+
12
+
13
+ class UrlscopeClient:
14
+ def __init__(
15
+ self,
16
+ api_key: str | None = None,
17
+ *,
18
+ base_url: str = "https://urlscan.io",
19
+ timeout: float = 30.0,
20
+ max_retries: int = 5,
21
+ ) -> None:
22
+ self._transport = _HTTPTransport(
23
+ api_key,
24
+ base_url=base_url,
25
+ timeout=timeout,
26
+ max_retries=max_retries,
27
+ )
28
+
29
+ async def __aenter__(self) -> "UrlscopeClient":
30
+ await self._transport.__aenter__()
31
+ return self
32
+
33
+ async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
34
+ await self._transport.__aexit__(exc_type, exc, tb)
35
+
36
+ async def aclose(self) -> None:
37
+ await self._transport.aclose()
38
+
39
+ async def submit(
40
+ self,
41
+ url: str,
42
+ *,
43
+ visibility: Literal["public", "unlisted", "private"] | None = None,
44
+ tags: list[str] | None = None,
45
+ custom_agent: str | None = None,
46
+ referer: str | None = None,
47
+ override_safety: bool | None = None,
48
+ country: str | None = None,
49
+ ) -> SubmissionResponse:
50
+ if tags is not None and len(tags) > 10:
51
+ raise ValueError("tags must contain at most 10 items")
52
+
53
+ payload = {
54
+ "url": url,
55
+ "visibility": visibility,
56
+ "tags": tags,
57
+ "customagent": custom_agent,
58
+ "referer": referer,
59
+ "overrideSafety": override_safety,
60
+ "country": country,
61
+ }
62
+ response = await self._transport._request(
63
+ "POST",
64
+ "/api/v1/scan/",
65
+ json={key: value for key, value in payload.items() if value is not None},
66
+ )
67
+ return SubmissionResponse.model_validate(response.json())
68
+
69
+ async def get_result(self, uuid: str) -> ScanResult:
70
+ response = await self._transport._request("GET", f"/api/v1/result/{uuid}/")
71
+ return ScanResult.model_validate(response.json())
72
+
73
+ async def search(
74
+ self,
75
+ query: str = "*",
76
+ *,
77
+ size: int = 100,
78
+ search_after: list[Any] | None = None,
79
+ ) -> SearchResponse:
80
+ params: dict[str, Any] = {
81
+ "q": query,
82
+ "size": size,
83
+ }
84
+ if search_after is not None:
85
+ params["search_after"] = ",".join(str(value) for value in search_after)
86
+
87
+ response = await self._transport._request(
88
+ "GET",
89
+ "/api/v1/search/",
90
+ params=params,
91
+ )
92
+ return SearchResponse.model_validate(response.json())
93
+
94
+ async def get_screenshot(self, uuid: str) -> bytes:
95
+ response = await self._transport._request("GET", f"/screenshots/{uuid}.png")
96
+ return response.content
97
+
98
+ async def get_dom(self, uuid: str) -> str:
99
+ response = await self._transport._request("GET", f"/dom/{uuid}/")
100
+ return response.text
101
+
102
+ async def get_quotas(self) -> QuotaInfo:
103
+ response = await self._transport._request("GET", "/api/v1/quotas")
104
+ return QuotaInfo.model_validate(response.json())
105
+
106
+ async def submit_and_wait(
107
+ self,
108
+ url: str,
109
+ *,
110
+ visibility: Literal["public", "unlisted", "private"] | None = None,
111
+ tags: list[str] | None = None,
112
+ custom_agent: str | None = None,
113
+ referer: str | None = None,
114
+ override_safety: bool | None = None,
115
+ country: str | None = None,
116
+ poll_interval: float = 5.0,
117
+ initial_wait: float = 10.0,
118
+ poll_timeout: float = 300.0,
119
+ ) -> ScanResult:
120
+ submission = await self.submit(
121
+ url,
122
+ visibility=visibility,
123
+ tags=tags,
124
+ custom_agent=custom_agent,
125
+ referer=referer,
126
+ override_safety=override_safety,
127
+ country=country,
128
+ )
129
+ started_at = time.monotonic()
130
+
131
+ if initial_wait > 0:
132
+ LOGGER.debug(
133
+ "Waiting %.3f seconds before polling result for scan %s",
134
+ initial_wait,
135
+ submission.uuid,
136
+ )
137
+ await asyncio.sleep(initial_wait)
138
+
139
+ while True:
140
+ elapsed = time.monotonic() - started_at
141
+ if elapsed > poll_timeout:
142
+ message = (
143
+ f"Scan {submission.uuid} still pending after "
144
+ f"{poll_timeout} seconds"
145
+ )
146
+ raise ScanTimeoutError(
147
+ message,
148
+ uuid=submission.uuid,
149
+ )
150
+
151
+ try:
152
+ LOGGER.debug("Polling result for scan %s", submission.uuid)
153
+ return await self.get_result(submission.uuid)
154
+ except NotFoundError:
155
+ LOGGER.debug("Scan %s is still pending", submission.uuid)
156
+ await asyncio.sleep(poll_interval)
157
+ except ScanDeletedError:
158
+ raise
@@ -0,0 +1,52 @@
1
+ class UrlscopeError(Exception):
2
+ """Base exception for all urlscope errors."""
3
+
4
+
5
+ class AuthenticationError(UrlscopeError):
6
+ """Raised when API authentication fails."""
7
+
8
+
9
+ class ValidationError(UrlscopeError):
10
+ """Raised when the API rejects a request as invalid."""
11
+
12
+
13
+ class NotFoundError(UrlscopeError):
14
+ """Raised when a scan is not found or is still pending."""
15
+
16
+
17
+ class ScanDeletedError(UrlscopeError):
18
+ """Raised when a scan has been deleted."""
19
+
20
+
21
+ class RateLimitError(UrlscopeError):
22
+ """Raised when API rate limits are exceeded after retries."""
23
+
24
+ def __init__(
25
+ self,
26
+ message: str,
27
+ *,
28
+ retry_after: float | None = None,
29
+ scope: str | None = None,
30
+ window: str | None = None,
31
+ ) -> None:
32
+ super().__init__(message)
33
+ self.retry_after = retry_after
34
+ self.scope = scope
35
+ self.window = window
36
+
37
+
38
+ class ScanTimeoutError(UrlscopeError):
39
+ """Raised when polling exceeds the configured timeout."""
40
+
41
+ def __init__(self, message: str, *, uuid: str) -> None:
42
+ super().__init__(message)
43
+ self.uuid = uuid
44
+
45
+
46
+ class APIError(UrlscopeError):
47
+ """Raised for unexpected API HTTP errors."""
48
+
49
+ def __init__(self, status_code: int, message: str) -> None:
50
+ super().__init__(message)
51
+ self.status_code = status_code
52
+ self.message = message
urlscope/_http.py ADDED
@@ -0,0 +1,155 @@
1
+ import asyncio
2
+ import logging
3
+ import os
4
+ import random
5
+ from typing import Any
6
+
7
+ import httpx
8
+
9
+ from ._exceptions import (
10
+ APIError,
11
+ AuthenticationError,
12
+ NotFoundError,
13
+ RateLimitError,
14
+ ScanDeletedError,
15
+ ValidationError,
16
+ )
17
+
18
+ LOGGER = logging.getLogger("urlscope")
19
+ if not LOGGER.handlers:
20
+ LOGGER.addHandler(logging.NullHandler())
21
+
22
+
23
+ class _HTTPTransport:
24
+ def __init__(
25
+ self,
26
+ api_key: str | None = None,
27
+ *,
28
+ base_url: str = "https://urlscan.io",
29
+ timeout: float = 30.0,
30
+ max_retries: int = 5,
31
+ ) -> None:
32
+ resolved_api_key = api_key or os.getenv("URLSCAN_API_KEY")
33
+ if not resolved_api_key:
34
+ raise AuthenticationError(
35
+ "API key is required. Pass api_key or set URLSCAN_API_KEY."
36
+ )
37
+
38
+ self.base_url = base_url.rstrip("/")
39
+ self.timeout = timeout
40
+ self.max_retries = max_retries
41
+ self._client = httpx.AsyncClient(
42
+ base_url=self.base_url,
43
+ timeout=self.timeout,
44
+ headers={"API-Key": resolved_api_key},
45
+ )
46
+
47
+ async def __aenter__(self) -> "_HTTPTransport":
48
+ await self._client.__aenter__()
49
+ return self
50
+
51
+ async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
52
+ await self._client.__aexit__(exc_type, exc, tb)
53
+
54
+ async def aclose(self) -> None:
55
+ await self._client.aclose()
56
+
57
+ async def _request(
58
+ self,
59
+ method: str,
60
+ path: str,
61
+ **kwargs: Any,
62
+ ) -> httpx.Response:
63
+ retries = 0
64
+
65
+ while True:
66
+ response = await self._client.request(method, path, **kwargs)
67
+
68
+ if response.status_code == 429:
69
+ if retries >= self.max_retries:
70
+ retry_after = self._parse_retry_after(response)
71
+ scope = response.headers.get("X-Rate-Limit-Scope")
72
+ window = response.headers.get("X-Rate-Limit-Window")
73
+ LOGGER.warning(
74
+ "Rate limit exhausted after %s retries for %s %s",
75
+ retries,
76
+ method,
77
+ path,
78
+ )
79
+ raise RateLimitError(
80
+ self._extract_error_message(response),
81
+ retry_after=retry_after,
82
+ scope=scope,
83
+ window=window,
84
+ )
85
+
86
+ retries += 1
87
+ delay = self._compute_retry_delay(response, retries)
88
+ LOGGER.debug(
89
+ "Retrying %s %s after HTTP 429 in %.3f seconds (attempt %s/%s)",
90
+ method,
91
+ path,
92
+ delay,
93
+ retries,
94
+ self.max_retries,
95
+ )
96
+ await asyncio.sleep(delay)
97
+ continue
98
+
99
+ self._raise_for_status(response)
100
+ return response
101
+
102
+ def _raise_for_status(self, response: httpx.Response) -> None:
103
+ status_code = response.status_code
104
+ if status_code < 400:
105
+ return
106
+
107
+ message = self._extract_error_message(response)
108
+ if status_code == 400:
109
+ raise ValidationError(message)
110
+ if status_code in {401, 403}:
111
+ raise AuthenticationError(message)
112
+ if status_code == 404:
113
+ raise NotFoundError(message)
114
+ if status_code == 410:
115
+ raise ScanDeletedError(message)
116
+ raise APIError(status_code, message)
117
+
118
+ def _compute_retry_delay(self, response: httpx.Response, attempt: int) -> float:
119
+ retry_after = self._parse_retry_after(response)
120
+ if retry_after is not None:
121
+ base_delay = retry_after
122
+ else:
123
+ base_delay = 2.0 * (2 ** (attempt - 1))
124
+
125
+ jitter_multiplier = random.uniform(0.75, 1.25)
126
+ return max(0.0, base_delay * jitter_multiplier)
127
+
128
+ @staticmethod
129
+ def _parse_retry_after(response: httpx.Response) -> float | None:
130
+ raw_value = response.headers.get("X-Rate-Limit-Reset-After")
131
+ if raw_value is None:
132
+ return None
133
+
134
+ try:
135
+ return float(raw_value)
136
+ except ValueError:
137
+ return None
138
+
139
+ @staticmethod
140
+ def _extract_error_message(response: httpx.Response) -> str:
141
+ try:
142
+ payload = response.json()
143
+ except ValueError:
144
+ payload = None
145
+
146
+ if isinstance(payload, dict):
147
+ for key in ("message", "description", "detail", "error"):
148
+ value = payload.get(key)
149
+ if isinstance(value, str) and value:
150
+ return value
151
+
152
+ if response.text:
153
+ return response.text
154
+
155
+ return f"HTTP {response.status_code}"
urlscope/_sync.py ADDED
@@ -0,0 +1,165 @@
1
+ import asyncio
2
+ from typing import Any, Literal
3
+
4
+ from ._client import UrlscopeClient
5
+ from .models import QuotaInfo, ScanResult, SearchResponse, SubmissionResponse
6
+
7
+
8
+ class SyncClient:
9
+ def __init__(
10
+ self,
11
+ api_key: str | None = None,
12
+ *,
13
+ base_url: str = "https://urlscan.io",
14
+ timeout: float = 30.0,
15
+ max_retries: int = 5,
16
+ ) -> None:
17
+ self._api_key = api_key
18
+ self._base_url = base_url
19
+ self._timeout = timeout
20
+ self._max_retries = max_retries
21
+
22
+ def __enter__(self) -> "SyncClient":
23
+ return self
24
+
25
+ def __exit__(self, *args: Any) -> None:
26
+ return None
27
+
28
+ def close(self) -> None:
29
+ return None
30
+
31
+ def submit(
32
+ self,
33
+ url: str,
34
+ *,
35
+ visibility: Literal["public", "unlisted", "private"] | None = None,
36
+ tags: list[str] | None = None,
37
+ custom_agent: str | None = None,
38
+ referer: str | None = None,
39
+ override_safety: bool | None = None,
40
+ country: str | None = None,
41
+ ) -> SubmissionResponse:
42
+ async def _run() -> SubmissionResponse:
43
+ async with UrlscopeClient(
44
+ self._api_key,
45
+ base_url=self._base_url,
46
+ timeout=self._timeout,
47
+ max_retries=self._max_retries,
48
+ ) as client:
49
+ return await client.submit(
50
+ url,
51
+ visibility=visibility,
52
+ tags=tags,
53
+ custom_agent=custom_agent,
54
+ referer=referer,
55
+ override_safety=override_safety,
56
+ country=country,
57
+ )
58
+
59
+ return asyncio.run(_run())
60
+
61
+ def get_result(self, uuid: str) -> ScanResult:
62
+ async def _run() -> ScanResult:
63
+ async with UrlscopeClient(
64
+ self._api_key,
65
+ base_url=self._base_url,
66
+ timeout=self._timeout,
67
+ max_retries=self._max_retries,
68
+ ) as client:
69
+ return await client.get_result(uuid)
70
+
71
+ return asyncio.run(_run())
72
+
73
+ def submit_and_wait(
74
+ self,
75
+ url: str,
76
+ *,
77
+ visibility: Literal["public", "unlisted", "private"] | None = None,
78
+ tags: list[str] | None = None,
79
+ custom_agent: str | None = None,
80
+ referer: str | None = None,
81
+ override_safety: bool | None = None,
82
+ country: str | None = None,
83
+ poll_interval: float = 5.0,
84
+ initial_wait: float = 10.0,
85
+ poll_timeout: float = 300.0,
86
+ ) -> ScanResult:
87
+ async def _run() -> ScanResult:
88
+ async with UrlscopeClient(
89
+ self._api_key,
90
+ base_url=self._base_url,
91
+ timeout=self._timeout,
92
+ max_retries=self._max_retries,
93
+ ) as client:
94
+ return await client.submit_and_wait(
95
+ url,
96
+ visibility=visibility,
97
+ tags=tags,
98
+ custom_agent=custom_agent,
99
+ referer=referer,
100
+ override_safety=override_safety,
101
+ country=country,
102
+ poll_interval=poll_interval,
103
+ initial_wait=initial_wait,
104
+ poll_timeout=poll_timeout,
105
+ )
106
+
107
+ return asyncio.run(_run())
108
+
109
+ def search(
110
+ self,
111
+ query: str = "*",
112
+ *,
113
+ size: int = 100,
114
+ search_after: list[Any] | None = None,
115
+ ) -> SearchResponse:
116
+ async def _run() -> SearchResponse:
117
+ async with UrlscopeClient(
118
+ self._api_key,
119
+ base_url=self._base_url,
120
+ timeout=self._timeout,
121
+ max_retries=self._max_retries,
122
+ ) as client:
123
+ return await client.search(
124
+ query,
125
+ size=size,
126
+ search_after=search_after,
127
+ )
128
+
129
+ return asyncio.run(_run())
130
+
131
+ def get_screenshot(self, uuid: str) -> bytes:
132
+ async def _run() -> bytes:
133
+ async with UrlscopeClient(
134
+ self._api_key,
135
+ base_url=self._base_url,
136
+ timeout=self._timeout,
137
+ max_retries=self._max_retries,
138
+ ) as client:
139
+ return await client.get_screenshot(uuid)
140
+
141
+ return asyncio.run(_run())
142
+
143
+ def get_dom(self, uuid: str) -> str:
144
+ async def _run() -> str:
145
+ async with UrlscopeClient(
146
+ self._api_key,
147
+ base_url=self._base_url,
148
+ timeout=self._timeout,
149
+ max_retries=self._max_retries,
150
+ ) as client:
151
+ return await client.get_dom(uuid)
152
+
153
+ return asyncio.run(_run())
154
+
155
+ def get_quotas(self) -> QuotaInfo:
156
+ async def _run() -> QuotaInfo:
157
+ async with UrlscopeClient(
158
+ self._api_key,
159
+ base_url=self._base_url,
160
+ timeout=self._timeout,
161
+ max_retries=self._max_retries,
162
+ ) as client:
163
+ return await client.get_quotas()
164
+
165
+ return asyncio.run(_run())
@@ -0,0 +1,27 @@
1
+ from ._quota import QuotaInfo, QuotaWindow
2
+ from ._result import (
3
+ BrandMatch,
4
+ CertificateInfo,
5
+ PageInfo,
6
+ ScanLists,
7
+ ScanResult,
8
+ TaskInfo,
9
+ Verdicts,
10
+ )
11
+ from ._search import SearchResponse, SearchResultItem
12
+ from ._submission import SubmissionResponse
13
+
14
+ __all__ = [
15
+ "SubmissionResponse",
16
+ "ScanResult",
17
+ "TaskInfo",
18
+ "PageInfo",
19
+ "Verdicts",
20
+ "BrandMatch",
21
+ "ScanLists",
22
+ "CertificateInfo",
23
+ "SearchResponse",
24
+ "SearchResultItem",
25
+ "QuotaInfo",
26
+ "QuotaWindow",
27
+ ]
@@ -0,0 +1,62 @@
1
+ from typing import Any
2
+
3
+ from pydantic import AliasChoices, BaseModel, ConfigDict, Field, computed_field
4
+
5
+
6
+ class QuotaWindow(BaseModel):
7
+ model_config = ConfigDict(extra="allow", populate_by_name=True)
8
+
9
+ scope: str | None = None
10
+ action: str
11
+ window: str
12
+ limit: int
13
+ used: int | None = None
14
+ remaining: int | None = None
15
+ percent: float | int | None = None
16
+
17
+
18
+ class _QuotaPeriod(BaseModel):
19
+ model_config = ConfigDict(extra="allow", populate_by_name=True)
20
+
21
+ limit: int
22
+ used: int | None = None
23
+ remaining: int | None = None
24
+ percent: float | int | None = None
25
+
26
+
27
+ class QuotaInfo(BaseModel):
28
+ model_config = ConfigDict(extra="allow", populate_by_name=True)
29
+
30
+ scope: str | None = Field(
31
+ default=None,
32
+ validation_alias=AliasChoices("scope", "source"),
33
+ )
34
+ limits: dict[str, Any]
35
+
36
+ @computed_field
37
+ def quotas(self) -> list[QuotaWindow]:
38
+ windows: list[QuotaWindow] = []
39
+
40
+ for action, value in self.limits.items():
41
+ if not isinstance(value, dict):
42
+ continue
43
+
44
+ for window_name in ("minute", "hour", "day"):
45
+ raw_window = value.get(window_name)
46
+ if not isinstance(raw_window, dict):
47
+ continue
48
+
49
+ period = _QuotaPeriod.model_validate(raw_window)
50
+ windows.append(
51
+ QuotaWindow(
52
+ scope=self.scope,
53
+ action=action,
54
+ window=window_name,
55
+ limit=period.limit,
56
+ used=period.used,
57
+ remaining=period.remaining,
58
+ percent=period.percent,
59
+ )
60
+ )
61
+
62
+ return windows
@@ -0,0 +1,96 @@
1
+ from datetime import datetime
2
+ from typing import Any
3
+
4
+ from pydantic import BaseModel, ConfigDict, Field
5
+
6
+
7
+ class TaskInfo(BaseModel):
8
+ model_config = ConfigDict(extra="allow", populate_by_name=True)
9
+
10
+ uuid: str
11
+ url: str
12
+ domain: str | None = None
13
+ apex_domain: str | None = Field(default=None, alias="apexDomain")
14
+ time: datetime
15
+ method: str | None = None
16
+ visibility: str
17
+ tags: list[str] | None = None
18
+ options: dict[str, Any] | None = None
19
+
20
+
21
+ class PageInfo(BaseModel):
22
+ model_config = ConfigDict(extra="allow", populate_by_name=True)
23
+
24
+ url: str
25
+ domain: str | None = None
26
+ apex_domain: str | None = Field(default=None, alias="apexDomain")
27
+ ip: str | None = None
28
+ asn: str | None = None
29
+ asnname: str | None = None
30
+ country: str | None = None
31
+ city: str | None = None
32
+ server: str | None = None
33
+ title: str | None = None
34
+ status: str | None = None
35
+ mime_type: str | None = Field(default=None, alias="mimeType")
36
+ tls_issuer: str | None = Field(default=None, alias="tlsIssuer")
37
+ tls_valid_from: datetime | None = Field(default=None, alias="tlsValidFrom")
38
+ tls_valid_days: int | None = Field(default=None, alias="tlsValidDays")
39
+ tls_age_days: int | None = Field(default=None, alias="tlsAgeDays")
40
+ umbrella_rank: int | None = Field(default=None, alias="umbrellaRank")
41
+ redirected: str | None = None
42
+ ptr: str | None = None
43
+
44
+
45
+ class BrandMatch(BaseModel):
46
+ model_config = ConfigDict(extra="allow", populate_by_name=True)
47
+
48
+ key: str
49
+ name: str
50
+ country: list[str] | None = None
51
+ vertical: list[str] | None = None
52
+
53
+
54
+ class Verdicts(BaseModel):
55
+ model_config = ConfigDict(extra="allow", populate_by_name=True)
56
+
57
+ score: int | None = None
58
+ categories: list[str] | None = None
59
+ brands: list[BrandMatch] | None = None
60
+ malicious: bool | None = None
61
+
62
+
63
+ class CertificateInfo(BaseModel):
64
+ model_config = ConfigDict(extra="allow", populate_by_name=True)
65
+
66
+ subject: str | None = None
67
+ issuer: str | None = None
68
+ valid_from: datetime | None = Field(default=None, alias="validFrom")
69
+ valid_to: datetime | None = Field(default=None, alias="validTo")
70
+ san_list: list[str] | None = Field(default=None, alias="sanList")
71
+
72
+
73
+ class ScanLists(BaseModel):
74
+ model_config = ConfigDict(extra="allow", populate_by_name=True)
75
+
76
+ ips: list[str] | None = None
77
+ domains: list[str] | None = None
78
+ urls: list[str] | None = None
79
+ countries: list[str] | None = None
80
+ asns: list[int] | None = None
81
+ servers: list[str] | None = None
82
+ hashes: list[str] | None = None
83
+ certificates: list[CertificateInfo] | None = None
84
+ link_domains: list[str] | None = Field(default=None, alias="linkDomains")
85
+
86
+
87
+ class ScanResult(BaseModel):
88
+ model_config = ConfigDict(extra="allow", populate_by_name=True)
89
+
90
+ task: TaskInfo
91
+ page: PageInfo
92
+ verdicts: Verdicts | None = None
93
+ stats: dict[str, Any] | None = None
94
+ lists: ScanLists | None = None
95
+ data: dict[str, Any] | None = None
96
+ meta: dict[str, Any] | None = None
@@ -0,0 +1,21 @@
1
+ from typing import Any
2
+
3
+ from pydantic import BaseModel, ConfigDict, Field
4
+
5
+
6
+ class SearchResultItem(BaseModel):
7
+ model_config = ConfigDict(extra="allow", populate_by_name=True)
8
+
9
+ id: str = Field(alias="_id")
10
+ sort: list[Any] | None = None
11
+ page: dict[str, Any] | None = None
12
+ task: dict[str, Any] | None = None
13
+ stats: dict[str, Any] | None = None
14
+
15
+
16
+ class SearchResponse(BaseModel):
17
+ model_config = ConfigDict(extra="allow", populate_by_name=True)
18
+
19
+ results: list[SearchResultItem]
20
+ total: int
21
+ has_more: bool
@@ -0,0 +1,16 @@
1
+ from typing import Any
2
+
3
+ from pydantic import BaseModel, ConfigDict
4
+
5
+
6
+ class SubmissionResponse(BaseModel):
7
+ model_config = ConfigDict(extra="allow", populate_by_name=True)
8
+
9
+ message: str
10
+ uuid: str
11
+ result: str
12
+ api: str
13
+ visibility: str
14
+ url: str
15
+ country: str | None = None
16
+ options: dict[str, Any] | None = None
urlscope/py.typed ADDED
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,176 @@
1
+ Metadata-Version: 2.4
2
+ Name: urlscope
3
+ Version: 0.1.3rc1
4
+ Summary: Python wrapper for the urlscan.io API.
5
+ Author: Jan Wychowaniak
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.10
9
+ Requires-Dist: httpx
10
+ Requires-Dist: pydantic>=2
11
+ Provides-Extra: dev
12
+ Requires-Dist: mypy; extra == 'dev'
13
+ Requires-Dist: pytest; extra == 'dev'
14
+ Requires-Dist: pytest-asyncio; extra == 'dev'
15
+ Requires-Dist: respx; extra == 'dev'
16
+ Requires-Dist: ruff; extra == 'dev'
17
+ Description-Content-Type: text/markdown
18
+
19
+ # urlscope
20
+
21
+ `urlscope` is an async-first Python wrapper for the urlscan.io API. It provides typed Pydantic models for common API responses, automatic API key handling, built-in retry logic for rate limits, and a sync convenience wrapper for scripts.
22
+
23
+ ## Installation
24
+
25
+ ```bash
26
+ pip install urlscope
27
+ ```
28
+
29
+ Set your API key before making requests:
30
+
31
+ ```bash
32
+ export URLSCAN_API_KEY="your-api-key-here"
33
+ ```
34
+
35
+ ## Quickstart
36
+
37
+ ### Async submit and wait
38
+
39
+ ```python
40
+ import asyncio
41
+ from urlscope import UrlscopeClient
42
+
43
+
44
+ async def main() -> None:
45
+ async with UrlscopeClient() as client:
46
+ result = await client.submit_and_wait(
47
+ "https://example.com",
48
+ visibility="public",
49
+ )
50
+ print(result.task.uuid)
51
+ print(result.page.url)
52
+ print(result.verdicts.score if result.verdicts else None)
53
+
54
+
55
+ asyncio.run(main())
56
+ ```
57
+
58
+ ### Sync usage
59
+
60
+ ```python
61
+ from urlscope import SyncClient
62
+
63
+
64
+ with SyncClient() as client:
65
+ result = client.get_result("scan-uuid-here")
66
+ print(result.page.url)
67
+ ```
68
+
69
+ ### Search
70
+
71
+ ```python
72
+ import asyncio
73
+ from urlscope import UrlscopeClient
74
+
75
+
76
+ async def main() -> None:
77
+ async with UrlscopeClient() as client:
78
+ response = await client.search("domain:example.com", size=10)
79
+ for item in response.results:
80
+ print(item.id, item.page.get("url") if item.page else None)
81
+
82
+ # Cursor-based pagination is handled via the previous item's sort key.
83
+ if response.has_more and response.results and response.results[-1].sort:
84
+ next_page = await client.search(
85
+ "domain:example.com",
86
+ size=10,
87
+ search_after=response.results[-1].sort,
88
+ )
89
+ print(len(next_page.results))
90
+
91
+
92
+ asyncio.run(main())
93
+ ```
94
+
95
+ ### Download artifacts
96
+
97
+ ```python
98
+ import asyncio
99
+ from urlscope import UrlscopeClient
100
+
101
+
102
+ async def main() -> None:
103
+ async with UrlscopeClient() as client:
104
+ screenshot = await client.get_screenshot("scan-uuid-here")
105
+ dom = await client.get_dom("scan-uuid-here")
106
+ print(len(screenshot), len(dom))
107
+
108
+
109
+ asyncio.run(main())
110
+ ```
111
+
112
+ ### Check quotas
113
+
114
+ ```python
115
+ import asyncio
116
+ from urlscope import UrlscopeClient
117
+
118
+
119
+ async def main() -> None:
120
+ async with UrlscopeClient() as client:
121
+ quotas = await client.get_quotas()
122
+ for q in quotas.quotas[:5]:
123
+ print(q.scope, q.action, q.window, q.remaining, q.limit)
124
+
125
+
126
+ asyncio.run(main())
127
+ ```
128
+
129
+ ### Error handling
130
+
131
+ ```python
132
+ import asyncio
133
+ from urlscope import RateLimitError, ScanTimeoutError, UrlscopeClient
134
+
135
+
136
+ async def main() -> None:
137
+ async with UrlscopeClient() as client:
138
+ try:
139
+ await client.submit_and_wait("https://example.com", poll_timeout=120.0)
140
+ except ScanTimeoutError as exc:
141
+ print(exc.uuid)
142
+ except RateLimitError as exc:
143
+ print(exc.retry_after, exc.scope, exc.window)
144
+
145
+
146
+ asyncio.run(main())
147
+ ```
148
+
149
+ ## API Reference
150
+
151
+ Primary clients:
152
+
153
+ - `UrlscopeClient`: async interface for submit, result retrieval, polling, search, artifacts, and quotas
154
+ - `SyncClient`: sync wrapper with the same method surface for scripts and simple integrations
155
+
156
+ Key response models:
157
+
158
+ - `SubmissionResponse`
159
+ - `ScanResult`, `TaskInfo`, `PageInfo`, `Verdicts`, `BrandMatch`, `ScanLists`, `CertificateInfo`
160
+ - `SearchResponse`, `SearchResultItem`
161
+ - `QuotaInfo`, `QuotaWindow`
162
+
163
+ Key exceptions:
164
+
165
+ - `UrlscopeError`
166
+ - `AuthenticationError`
167
+ - `ValidationError`
168
+ - `NotFoundError`
169
+ - `ScanDeletedError`
170
+ - `RateLimitError`
171
+ - `ScanTimeoutError`
172
+ - `APIError`
173
+
174
+ ## License
175
+
176
+ MIT
@@ -0,0 +1,15 @@
1
+ urlscope/__init__.py,sha256=7lS7evi57y2ZSr8QG69AXCQRhC9BxRFxmGNXT9Y05Rs,999
2
+ urlscope/_client.py,sha256=zU8c5Sve3meoH5NcFDgCGWoQG8jP35X3k3mf1mNSx1k,5139
3
+ urlscope/_exceptions.py,sha256=BMcs1exudqxg0zAH0uF8KhlCOUeBuAyPDJlJuO1gwTE,1363
4
+ urlscope/_http.py,sha256=odwEgDtI_rSSCyWT2HqRxQ7irCVPvV2xPyvqcUE1OR4,4765
5
+ urlscope/_sync.py,sha256=4dcMvtHguiav326gzQu5WWCy98vFUMuAtXettwfg3BA,5165
6
+ urlscope/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
7
+ urlscope/models/__init__.py,sha256=PGGzx2apccVjKnuw_Gs6QmIpqkUbsevPb2lJktZafC8,523
8
+ urlscope/models/_quota.py,sha256=CNeTaIGKq0fUvfo1tIsbfbnXlGuY1ZDaT8RlfijE6YQ,1764
9
+ urlscope/models/_result.py,sha256=yFhM23Yy8FD634QxPkBccu-aurBr4-VvRplasGRx_7Y,3045
10
+ urlscope/models/_search.py,sha256=8xu5L9EKGG3TGxDk310llaR842t9Cd-tKvGf3WCwWzo,539
11
+ urlscope/models/_submission.py,sha256=NuG2lsmXsA3mdeCAMw5w9n5yGtHMuZnQAY4O_67nuhA,341
12
+ urlscope-0.1.3rc1.dist-info/METADATA,sha256=o0nkvoJUgOB8AZXdES4_8-UojFxeB9U8xGQ0ErG4moc,4034
13
+ urlscope-0.1.3rc1.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
14
+ urlscope-0.1.3rc1.dist-info/licenses/LICENSE,sha256=gPEDZLErAQZwnXA7rVAJQ8hBHEVb5Fbzarxi1PaXw0M,1072
15
+ urlscope-0.1.3rc1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jan Wychowaniak
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.