noresponse 1.0.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.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 NoResponse
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,39 @@
1
+ Metadata-Version: 2.4
2
+ Name: noresponse
3
+ Version: 1.0.0
4
+ Summary: Server-side NoResponse Identity Intelligence SDK
5
+ License-Expression: Apache-2.0
6
+ Requires-Python: >=3.11
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Dynamic: license-file
10
+
11
+ # NoResponse Python SDK
12
+
13
+ Install it with `pip install noresponse` (Python 3.11 or later) and import `noresponse_sdk`. To work on the SDK, install it from source with `pip install -e sdks/python` and run `python -m unittest discover -s sdks/python/tests -v`.
14
+
15
+ ```python
16
+ import os
17
+ from noresponse_sdk import Client
18
+
19
+ client = Client(
20
+ api_key=os.environ["NORESPONSE_API_KEY"],
21
+ base_url=os.environ["NORESPONSE_API_URL"], # https://api.noresponse.org in production
22
+ )
23
+ assessment = client.assess_signup(
24
+ account_id="usr_123",
25
+ email="person@example.com", # email, username or phone: at least one
26
+ name="Jane A. Doe", # optional, used only for matching
27
+ ip="73.162.18.45", # optional, the signup's public IP
28
+ idempotency_key="signup-usr_123-0000001",
29
+ )
30
+ # Pending means no recommendation: never allow. Enforce your own fallback policy.
31
+ ```
32
+
33
+ `client.assess(account_id=..., identifiers={...}, idempotency_key=...)` takes the identifiers mapping directly (`email`, `username`, `phone`, `name`, `ip`). Also supports `client.get_assessment(assessment_id)` and `client.query_assessments(account_id=..., limit=..., cursor=...)`; each takes `response_mode="detailed"` (with the `detailed` key scope) to add `risk.details` and `signals`, and refuses `raw`.
34
+
35
+ For signed webhooks call `verify_webhook(raw_body, list_of_raw_header_pairs, secrets_by_key_id)`. It checks the `v1=` HMAC-SHA256 signature over the raw bytes, the 300-second window and the event id, refuses repeated or case-variant headers, and returns the typed `WebhookEvent`. An `assessment.updated` event's `data` is the full assessment as `get_assessment` returns it; `webhook_assessment(event)` returns it as a typed `Assessment`. `webhook_verification_response(event)` echoes a verified registration challenge.
36
+
37
+ Only call the API from a trusted backend. All recommendations are advisory and not calibrated probabilities. The SDK does not turn a timeout, pending assessment, blocked source or absence of evidence into an allow decision. See [example rules](../docs/example-rules.md) for turning an assessment into an action.
38
+
39
+ Every request, response, summary, detail, signal and webhook type is a TypedDict in `noresponse_sdk.generated_models`, generated from the provider OpenAPI contract. See [provider onboarding](../docs/provider-onboarding.md) for key rotation, webhook verification, retries and staging setup.
@@ -0,0 +1,29 @@
1
+ # NoResponse Python SDK
2
+
3
+ Install it with `pip install noresponse` (Python 3.11 or later) and import `noresponse_sdk`. To work on the SDK, install it from source with `pip install -e sdks/python` and run `python -m unittest discover -s sdks/python/tests -v`.
4
+
5
+ ```python
6
+ import os
7
+ from noresponse_sdk import Client
8
+
9
+ client = Client(
10
+ api_key=os.environ["NORESPONSE_API_KEY"],
11
+ base_url=os.environ["NORESPONSE_API_URL"], # https://api.noresponse.org in production
12
+ )
13
+ assessment = client.assess_signup(
14
+ account_id="usr_123",
15
+ email="person@example.com", # email, username or phone: at least one
16
+ name="Jane A. Doe", # optional, used only for matching
17
+ ip="73.162.18.45", # optional, the signup's public IP
18
+ idempotency_key="signup-usr_123-0000001",
19
+ )
20
+ # Pending means no recommendation: never allow. Enforce your own fallback policy.
21
+ ```
22
+
23
+ `client.assess(account_id=..., identifiers={...}, idempotency_key=...)` takes the identifiers mapping directly (`email`, `username`, `phone`, `name`, `ip`). Also supports `client.get_assessment(assessment_id)` and `client.query_assessments(account_id=..., limit=..., cursor=...)`; each takes `response_mode="detailed"` (with the `detailed` key scope) to add `risk.details` and `signals`, and refuses `raw`.
24
+
25
+ For signed webhooks call `verify_webhook(raw_body, list_of_raw_header_pairs, secrets_by_key_id)`. It checks the `v1=` HMAC-SHA256 signature over the raw bytes, the 300-second window and the event id, refuses repeated or case-variant headers, and returns the typed `WebhookEvent`. An `assessment.updated` event's `data` is the full assessment as `get_assessment` returns it; `webhook_assessment(event)` returns it as a typed `Assessment`. `webhook_verification_response(event)` echoes a verified registration challenge.
26
+
27
+ Only call the API from a trusted backend. All recommendations are advisory and not calibrated probabilities. The SDK does not turn a timeout, pending assessment, blocked source or absence of evidence into an allow decision. See [example rules](../docs/example-rules.md) for turning an assessment into an action.
28
+
29
+ Every request, response, summary, detail, signal and webhook type is a TypedDict in `noresponse_sdk.generated_models`, generated from the provider OpenAPI contract. See [provider onboarding](../docs/provider-onboarding.md) for key rotation, webhook verification, retries and staging setup.
@@ -0,0 +1,39 @@
1
+ Metadata-Version: 2.4
2
+ Name: noresponse
3
+ Version: 1.0.0
4
+ Summary: Server-side NoResponse Identity Intelligence SDK
5
+ License-Expression: Apache-2.0
6
+ Requires-Python: >=3.11
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Dynamic: license-file
10
+
11
+ # NoResponse Python SDK
12
+
13
+ Install it with `pip install noresponse` (Python 3.11 or later) and import `noresponse_sdk`. To work on the SDK, install it from source with `pip install -e sdks/python` and run `python -m unittest discover -s sdks/python/tests -v`.
14
+
15
+ ```python
16
+ import os
17
+ from noresponse_sdk import Client
18
+
19
+ client = Client(
20
+ api_key=os.environ["NORESPONSE_API_KEY"],
21
+ base_url=os.environ["NORESPONSE_API_URL"], # https://api.noresponse.org in production
22
+ )
23
+ assessment = client.assess_signup(
24
+ account_id="usr_123",
25
+ email="person@example.com", # email, username or phone: at least one
26
+ name="Jane A. Doe", # optional, used only for matching
27
+ ip="73.162.18.45", # optional, the signup's public IP
28
+ idempotency_key="signup-usr_123-0000001",
29
+ )
30
+ # Pending means no recommendation: never allow. Enforce your own fallback policy.
31
+ ```
32
+
33
+ `client.assess(account_id=..., identifiers={...}, idempotency_key=...)` takes the identifiers mapping directly (`email`, `username`, `phone`, `name`, `ip`). Also supports `client.get_assessment(assessment_id)` and `client.query_assessments(account_id=..., limit=..., cursor=...)`; each takes `response_mode="detailed"` (with the `detailed` key scope) to add `risk.details` and `signals`, and refuses `raw`.
34
+
35
+ For signed webhooks call `verify_webhook(raw_body, list_of_raw_header_pairs, secrets_by_key_id)`. It checks the `v1=` HMAC-SHA256 signature over the raw bytes, the 300-second window and the event id, refuses repeated or case-variant headers, and returns the typed `WebhookEvent`. An `assessment.updated` event's `data` is the full assessment as `get_assessment` returns it; `webhook_assessment(event)` returns it as a typed `Assessment`. `webhook_verification_response(event)` echoes a verified registration challenge.
36
+
37
+ Only call the API from a trusted backend. All recommendations are advisory and not calibrated probabilities. The SDK does not turn a timeout, pending assessment, blocked source or absence of evidence into an allow decision. See [example rules](../docs/example-rules.md) for turning an assessment into an action.
38
+
39
+ Every request, response, summary, detail, signal and webhook type is a TypedDict in `noresponse_sdk.generated_models`, generated from the provider OpenAPI contract. See [provider onboarding](../docs/provider-onboarding.md) for key rotation, webhook verification, retries and staging setup.
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ noresponse.egg-info/PKG-INFO
5
+ noresponse.egg-info/SOURCES.txt
6
+ noresponse.egg-info/dependency_links.txt
7
+ noresponse.egg-info/top_level.txt
8
+ noresponse_sdk/__init__.py
9
+ noresponse_sdk/generated_models.py
10
+ noresponse_sdk/py.typed
11
+ tests/test_generate_models.py
12
+ tests/test_provider_demo.py
13
+ tests/test_sdk.py
@@ -0,0 +1 @@
1
+ noresponse_sdk
@@ -0,0 +1,236 @@
1
+ """NoResponse Identity Intelligence SDK (server-side, pre-release).
2
+
3
+ No SDK operation enforces a signup decision: the provider handles pending,
4
+ step-up, 429/503 and timeouts according to its own policy.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import hashlib
9
+ import hmac
10
+ import json
11
+ import re
12
+ import time
13
+ from typing import Any, Callable, Literal, Mapping, Sequence, cast
14
+ from urllib.error import HTTPError
15
+ from urllib.parse import urlsplit
16
+ from urllib.request import Request, urlopen
17
+
18
+ from .generated_models import Assessment, AssessmentList, WebhookEvent
19
+
20
+ _ASSESSMENT_ID = re.compile(r"asm_[0-9A-HJKMNP-TV-Z]{26}\Z")
21
+ _IDEMPOTENCY = re.compile(r"[A-Za-z0-9._:-]{16,128}\Z")
22
+ _WEBHOOK_KEY = re.compile(r"whk_[A-Za-z0-9]{8,64}\Z")
23
+ _WEBHOOK_SIGNATURE = re.compile(r"v1=[0-9a-f]{64}\Z")
24
+ _HEADERS = ("nr-webhook-id", "nr-webhook-timestamp", "nr-webhook-key-id", "nr-webhook-signature")
25
+ _MAX_ERROR_BODY = 65536
26
+ _LOOKUP_IDENTIFIERS = {"email", "username", "phone"}
27
+ _MATCH_IDENTIFIERS = {"name", "ip"}
28
+ _EVENT_TYPES = ("assessment.updated", "endpoint.verification")
29
+
30
+
31
+ class NoResponseError(Exception):
32
+ def __init__(self, status: int, retry_after: int | None = None,
33
+ problem: dict[str, Any] | None = None):
34
+ detail = (problem or {}).get("title") or (problem or {}).get("detail")
35
+ message = f"NoResponse returned HTTP {status}"
36
+ if detail:
37
+ message += f": {detail}"
38
+ super().__init__(message)
39
+ self.status = status
40
+ self.retry_after = retry_after
41
+ self.problem = problem
42
+
43
+
44
+ class Client:
45
+ """Use tenant API credentials only from trusted server processes."""
46
+
47
+ def __init__(self, *, api_key: str, base_url: str, timeout: float = 5.0,
48
+ transport: Callable[..., Any] = urlopen):
49
+ if not api_key:
50
+ raise ValueError("api_key required")
51
+ url = urlsplit(base_url)
52
+ if url.username or url.password or url.query or url.fragment or not url.hostname:
53
+ raise ValueError("Invalid base_url")
54
+ if url.scheme != "https" and not (url.scheme == "http" and url.hostname in ("localhost", "127.0.0.1")):
55
+ raise ValueError("HTTPS required outside localhost")
56
+ if timeout <= 0:
57
+ raise ValueError("timeout must be positive")
58
+ self._url = base_url.rstrip("/")
59
+ self._key = api_key
60
+ self._timeout = timeout
61
+ self._transport = transport
62
+
63
+ def _call(self, method: str, path: str, body: Mapping[str, Any] | None = None,
64
+ idempotency_key: str | None = None) -> dict[str, Any]:
65
+ data = json.dumps(body, separators=(",", ":"), ensure_ascii=False).encode("utf-8") if body is not None else None
66
+ headers = {"Accept": "application/json"}
67
+ if data is not None:
68
+ headers["Content-Type"] = "application/json"
69
+ if idempotency_key is not None:
70
+ headers["Idempotency-Key"] = idempotency_key
71
+ req = Request(self._url + path, data=data, headers=headers, method=method)
72
+ req.add_unredirected_header("Authorization", "Bearer " + self._key)
73
+ try:
74
+ with self._transport(req, timeout=self._timeout) as response:
75
+ return json.loads(response.read())
76
+ except HTTPError as error:
77
+ retry = error.headers.get("Retry-After") if error.headers else None
78
+ retry_after = int(retry) if retry and retry.isdecimal() and int(retry) > 0 else None
79
+ problem = None
80
+ try:
81
+ body = error.read(_MAX_ERROR_BODY + 1)
82
+ if len(body) <= _MAX_ERROR_BODY:
83
+ parsed = json.loads(body or b"null")
84
+ problem = parsed if isinstance(parsed, dict) else None
85
+ except (ValueError, OSError):
86
+ problem = None
87
+ raise NoResponseError(error.code, retry_after, problem) from error
88
+
89
+ def assess(self, *, account_id: str, identifiers: Mapping[str, str],
90
+ idempotency_key: str, deadline_ms: int | None = None,
91
+ policy_context: Mapping[str, str] | None = None,
92
+ request_id: str | None = None,
93
+ response_mode: Literal["standard", "detailed"] | None = None) -> Assessment:
94
+ """identifiers takes email, username, phone, name and ip; name and ip need a lookup identifier."""
95
+ if not account_id or not set(identifiers) & _LOOKUP_IDENTIFIERS \
96
+ or not set(identifiers) <= _LOOKUP_IDENTIFIERS | _MATCH_IDENTIFIERS:
97
+ raise ValueError("account_id and at least one of email, username or phone required")
98
+ name = identifiers.get("name")
99
+ if name is not None and not 1 <= len(name) <= 128:
100
+ raise ValueError("name must be 1-128 characters")
101
+ if not _IDEMPOTENCY.fullmatch(idempotency_key):
102
+ raise ValueError("Idempotency-Key must be 16-128 safe characters")
103
+ if deadline_ms is not None and (type(deadline_ms) is not int or not 50 <= deadline_ms <= 500):
104
+ raise ValueError("deadline_ms must be an integer from 50 to 500")
105
+ if response_mode not in (None, "standard", "detailed"):
106
+ raise ValueError("response_mode must be standard or detailed; raw is never served")
107
+ body: dict[str, Any] = {"account_id": account_id, "identifiers": dict(identifiers)}
108
+ if deadline_ms is not None:
109
+ body["deadline_ms"] = deadline_ms
110
+ if policy_context is not None:
111
+ body["policy_context"] = dict(policy_context)
112
+ if request_id is not None:
113
+ body["request_id"] = request_id
114
+ if response_mode is not None:
115
+ body["response_mode"] = response_mode
116
+ return cast(Assessment, self._call("POST", "/v1/assessments", body, idempotency_key))
117
+
118
+ def assess_signup(self, *, account_id: str, idempotency_key: str,
119
+ email: str | None = None, username: str | None = None,
120
+ phone: str | None = None, name: str | None = None,
121
+ ip: str | None = None, deadline_ms: int | None = None,
122
+ region: str | None = None,
123
+ response_mode: Literal["standard", "detailed"] | None = None) -> Assessment:
124
+ identifiers = {key: value for key, value in
125
+ (("email", email), ("username", username), ("phone", phone),
126
+ ("name", name), ("ip", ip)) if value is not None}
127
+ policy = {"flow": "signup"}
128
+ if region is not None:
129
+ policy["region"] = region
130
+ return self.assess(account_id=account_id, identifiers=identifiers,
131
+ idempotency_key=idempotency_key, deadline_ms=deadline_ms,
132
+ policy_context=policy, response_mode=response_mode)
133
+
134
+ def get_assessment(self, assessment_id: str, *,
135
+ response_mode: Literal["standard", "detailed"] | None = None) -> Assessment:
136
+ if not _ASSESSMENT_ID.fullmatch(assessment_id):
137
+ raise ValueError("Invalid assessment_id")
138
+ if response_mode not in (None, "standard", "detailed"):
139
+ raise ValueError("response_mode must be standard or detailed")
140
+ suffix = f"?response_mode={response_mode}" if response_mode else ""
141
+ return cast(Assessment, self._call("GET", f"/v1/assessments/{assessment_id}{suffix}"))
142
+
143
+ def query_assessments(self, *, account_id: str, limit: int | None = None,
144
+ cursor: str | None = None,
145
+ response_mode: Literal["standard", "detailed"] | None = None) -> AssessmentList:
146
+ if not account_id or (limit is not None and (type(limit) is not int or not 1 <= limit <= 50)):
147
+ raise ValueError("Invalid assessment query")
148
+ if response_mode not in (None, "standard", "detailed"):
149
+ raise ValueError("response_mode must be standard or detailed")
150
+ body: dict[str, Any] = {"account_id": account_id}
151
+ if limit is not None:
152
+ body["limit"] = limit
153
+ if cursor is not None:
154
+ body["cursor"] = cursor
155
+ if response_mode is not None:
156
+ body["response_mode"] = response_mode
157
+ return cast(AssessmentList, self._call("POST", "/v1/assessments/query", body))
158
+
159
+
160
+ def verify_webhook(raw_body: bytes, header_pairs: Sequence[tuple[str, str]],
161
+ secrets: Mapping[str, bytes], *, now_seconds: int | None = None) -> WebhookEvent:
162
+ """Verify the signature over raw bytes and return the typed event.
163
+
164
+ Duplicate and case-variant headers are refused. For assessment.updated the
165
+ event's data is the assessment exactly as GET returns it;
166
+ webhook_assessment(event) returns it as a typed Assessment.
167
+ """
168
+ values: dict[str, str] = {}
169
+ for key, value in header_pairs:
170
+ key = key.lower()
171
+ if key not in _HEADERS:
172
+ continue
173
+ if key in values:
174
+ raise ValueError("Duplicate webhook header")
175
+ values[key] = value
176
+ if any(not values.get(key) for key in _HEADERS):
177
+ raise ValueError("Missing webhook header")
178
+ timestamp = values["nr-webhook-timestamp"]
179
+ now = int(time.time()) if now_seconds is None else now_seconds
180
+ if not re.fullmatch(r"[0-9]{1,12}", timestamp) or abs(now - int(timestamp)) > 300:
181
+ raise ValueError("Invalid webhook timestamp")
182
+ key_id = values["nr-webhook-key-id"]
183
+ if not _WEBHOOK_KEY.fullmatch(key_id) or key_id not in secrets:
184
+ raise ValueError("Unknown webhook key")
185
+ signature = values["nr-webhook-signature"]
186
+ if not _WEBHOOK_SIGNATURE.fullmatch(signature):
187
+ raise ValueError("Malformed webhook signature")
188
+ signed = timestamp.encode("ascii") + b"." + raw_body
189
+ expected = "v1=" + hmac.new(secrets[key_id], signed, hashlib.sha256).hexdigest()
190
+ if not hmac.compare_digest(signature, expected):
191
+ raise ValueError("Invalid webhook signature")
192
+ try:
193
+ event = json.loads(raw_body)
194
+ except (UnicodeDecodeError, json.JSONDecodeError) as error:
195
+ raise ValueError("Invalid webhook JSON") from error
196
+ if not isinstance(event, dict) or _envelope(event)[0] != values["nr-webhook-id"]:
197
+ raise ValueError("Webhook event ID mismatch")
198
+ if _envelope(event)[1] not in _EVENT_TYPES:
199
+ raise ValueError("Unknown webhook event")
200
+ return cast(WebhookEvent, event)
201
+
202
+
203
+ def _envelope(event: Mapping[str, Any]) -> tuple[Any, Any, Any]:
204
+ """id, type and data, from the v1 names or the earlier event_id/event_type."""
205
+ event_id = event.get("id", event.get("event_id"))
206
+ event_type = event.get("type", event.get("event_type"))
207
+ return event_id, event_type, event.get("data")
208
+
209
+
210
+ def webhook_assessment(event: Mapping[str, Any]) -> Assessment:
211
+ """The typed assessment of a verified assessment.updated event.
212
+
213
+ Raises ValueError for any other event, and for data that is not a full
214
+ assessment (for example an expiry notice or a pre-v1 pointer payload).
215
+ """
216
+ _, event_type, data = _envelope(event)
217
+ if event_type != "assessment.updated":
218
+ raise ValueError("Not an assessment event")
219
+ if (not isinstance(data, dict) or not isinstance(data.get("assessment_id"), str)
220
+ or type(data.get("assessment_version")) is not int
221
+ or not isinstance(data.get("status"), str)
222
+ or not isinstance(data.get("created_at"), str)
223
+ or not isinstance(data.get("incomplete_sources"), list)
224
+ or not isinstance(data.get("timing"), dict)):
225
+ raise ValueError("Webhook data is not a full assessment")
226
+ return cast(Assessment, data)
227
+
228
+
229
+ def webhook_verification_response(event: Mapping[str, Any]) -> bytes:
230
+ _, event_type, data = _envelope(event)
231
+ if event_type != "endpoint.verification":
232
+ raise ValueError("Not a verification challenge")
233
+ challenge = data.get("challenge") if isinstance(data, dict) else None
234
+ if not isinstance(challenge, str) or not re.fullmatch(r"[A-Za-z0-9_-]{43}", challenge):
235
+ raise ValueError("Invalid verification challenge")
236
+ return json.dumps({"challenge": challenge}, separators=(",", ":")).encode("utf-8")