tba-primitives-identity 0.4.0.dev2__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.
@@ -0,0 +1,301 @@
1
+ """Core identity primitives for the TBA identity package suite."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .base64url import base64url_decode, base64url_encode
6
+ from .clock import (
7
+ Clock,
8
+ FrozenClock,
9
+ SystemClock,
10
+ parse_time,
11
+ unix_seconds,
12
+ utc_now,
13
+ utc_now_iso,
14
+ )
15
+ from .entity_keys import normalize_entity, tenant_key
16
+ from .digests import digest_bytes, digest_text, sha256_text_digest, token_hash
17
+ from .constant_time import bytes_equal, text_equal
18
+ from .claims import (
19
+ ClaimDisclosureMode,
20
+ ClaimIdentifier,
21
+ ClaimLabel,
22
+ ClaimNameKind,
23
+ ClaimSourceKind,
24
+ ClaimType,
25
+ ClaimValueType,
26
+ RegisteredClaim,
27
+ )
28
+ from .digests import constant_time_digest_equal, sha256_digest
29
+ from .artifacts import (
30
+ ArtifactKind,
31
+ AttestationKind,
32
+ CredentialFormat,
33
+ IdentityDocumentKind,
34
+ LifecycleStatus,
35
+ ManifestKind,
36
+ PresentationKind,
37
+ ProtectedEnvelopeKind,
38
+ TokenKind,
39
+ VerificationOutcome,
40
+ )
41
+ from .media_types import (
42
+ APPLICATION_CWT,
43
+ APPLICATION_DC_SD_JWT,
44
+ APPLICATION_EAT_CWT,
45
+ APPLICATION_EAT_JWT,
46
+ APPLICATION_JWT,
47
+ APPLICATION_AT_JWT,
48
+ APPLICATION_WIT_JWT,
49
+ APPLICATION_WPT_JWT,
50
+ APPLICATION_VC_JWT,
51
+ APPLICATION_VP_JWT,
52
+ APPLICATION_VC_COSE,
53
+ APPLICATION_VP_COSE,
54
+ APPLICATION_COSE,
55
+ APPLICATION_DID_JSON,
56
+ APPLICATION_DID_LD_JSON,
57
+ APPLICATION_VC,
58
+ APPLICATION_VP,
59
+ MediaType,
60
+ )
61
+ from .nonces import MIN_NONCE_BYTES, generate_nonce, nonce_equal, validate_nonce
62
+ from .protocol_tags import (
63
+ PROTOCOL_TAGS,
64
+ normalize_protocol_tag,
65
+ normalize_protocol_tags,
66
+ )
67
+ from .uris import require_absolute_uri
68
+ from .errors import (
69
+ IdentityAuthorizationError,
70
+ IdentityConfigurationError,
71
+ IdentityError,
72
+ IdentityValidationError,
73
+ InvalidKeyError,
74
+ InvalidRefreshTokenError,
75
+ InvalidTokenError,
76
+ RefreshTokenError,
77
+ RefreshTokenReuseError,
78
+ )
79
+ from .path_safety import safe_display_path, sanitize_local_paths
80
+ from .http import headers_from_scope, json_response, read_http_body, replay_http_body
81
+ from .jsonrpc import jsonrpc_error
82
+ from .primitives import (
83
+ Audience,
84
+ ClientId,
85
+ ClientRef,
86
+ CeremonyId,
87
+ CredentialExternalId,
88
+ CredentialRef,
89
+ IdentityRef,
90
+ WalletRef,
91
+ WorkloadRef,
92
+ ArtifactRef,
93
+ CredentialId,
94
+ AuthenticatorId,
95
+ IdentityId,
96
+ TokenId,
97
+ PresentationId,
98
+ AttestationId,
99
+ ManifestId,
100
+ CertificateId,
101
+ WalletId,
102
+ WalletInstanceId,
103
+ WorkloadId,
104
+ WorkloadReferenceId,
105
+ WorkloadCredentialId,
106
+ WorkloadEntitlementId,
107
+ WorkloadSubscriptionId,
108
+ TrustMaterialId,
109
+ TrustDomainId,
110
+ CredentialTypeId,
111
+ StatusListId,
112
+ TransactionId,
113
+ KeyId,
114
+ Issuer,
115
+ PrincipalId,
116
+ PrincipalRef,
117
+ RealmId,
118
+ RealmRef,
119
+ RelyingPartyId,
120
+ Scope,
121
+ ScopeValue,
122
+ Subject,
123
+ TenantId,
124
+ TenantRef,
125
+ UserHandleId,
126
+ new_client_id,
127
+ new_credential_id,
128
+ new_opaque_id,
129
+ new_prefixed_id,
130
+ new_principal_id,
131
+ new_realm_id,
132
+ new_tenant_id,
133
+ )
134
+ from .standards import StandardOwner, describe_owner
135
+ from .json_canonicalization import canonical_json_bytes, canonicalize
136
+ from .normalization import (
137
+ clean_mapping,
138
+ clean_tuple,
139
+ new_model_id,
140
+ normal_tuple,
141
+ pick_fields,
142
+ required_text,
143
+ row_active,
144
+ row_value,
145
+ str_tuple,
146
+ )
147
+ from .patterns import matches_dotted_pattern
148
+ from .redaction import SECRET_FIELD_TOKENS, redact_sensitive_mapping
149
+ from .typing import StrUUID, uuid_str
150
+ from .versions import semver_key, version_in_range
151
+
152
+ __all__ = [
153
+ "APPLICATION_CWT",
154
+ "APPLICATION_DC_SD_JWT",
155
+ "APPLICATION_EAT_CWT",
156
+ "APPLICATION_EAT_JWT",
157
+ "APPLICATION_JWT",
158
+ "APPLICATION_AT_JWT",
159
+ "APPLICATION_WIT_JWT",
160
+ "APPLICATION_WPT_JWT",
161
+ "APPLICATION_VC_JWT",
162
+ "APPLICATION_VP_JWT",
163
+ "APPLICATION_VC_COSE",
164
+ "APPLICATION_VP_COSE",
165
+ "APPLICATION_COSE",
166
+ "APPLICATION_DID_JSON",
167
+ "APPLICATION_DID_LD_JSON",
168
+ "APPLICATION_VC",
169
+ "APPLICATION_VP",
170
+ "ArtifactKind",
171
+ "AttestationId",
172
+ "AttestationKind",
173
+ "Audience",
174
+ "Clock",
175
+ "ClaimType",
176
+ "ClaimValueType",
177
+ "ClaimDisclosureMode",
178
+ "ClaimIdentifier",
179
+ "ClaimLabel",
180
+ "ClaimNameKind",
181
+ "ClaimSourceKind",
182
+ "RegisteredClaim",
183
+ "ClientId",
184
+ "ClientRef",
185
+ "CeremonyId",
186
+ "CredentialExternalId",
187
+ "CredentialRef",
188
+ "IdentityRef",
189
+ "WalletRef",
190
+ "WorkloadRef",
191
+ "ArtifactRef",
192
+ "CredentialId",
193
+ "AuthenticatorId",
194
+ "CredentialFormat",
195
+ "CredentialTypeId",
196
+ "CertificateId",
197
+ "FrozenClock",
198
+ "IdentityAuthorizationError",
199
+ "IdentityConfigurationError",
200
+ "IdentityError",
201
+ "IdentityValidationError",
202
+ "InvalidKeyError",
203
+ "InvalidRefreshTokenError",
204
+ "InvalidTokenError",
205
+ "Issuer",
206
+ "IdentityId",
207
+ "IdentityDocumentKind",
208
+ "KeyId",
209
+ "LifecycleStatus",
210
+ "ManifestId",
211
+ "ManifestKind",
212
+ "MediaType",
213
+ "MIN_NONCE_BYTES",
214
+ "parse_time",
215
+ "PrincipalId",
216
+ "PrincipalRef",
217
+ "PresentationId",
218
+ "PresentationKind",
219
+ "ProtectedEnvelopeKind",
220
+ "RealmId",
221
+ "RealmRef",
222
+ "RelyingPartyId",
223
+ "Scope",
224
+ "ScopeValue",
225
+ "SECRET_FIELD_TOKENS",
226
+ "StandardOwner",
227
+ "StrUUID",
228
+ "Subject",
229
+ "SystemClock",
230
+ "TenantId",
231
+ "TenantRef",
232
+ "UserHandleId",
233
+ "TokenId",
234
+ "TokenKind",
235
+ "TransactionId",
236
+ "TrustDomainId",
237
+ "VerificationOutcome",
238
+ "WalletId",
239
+ "WalletInstanceId",
240
+ "WorkloadId",
241
+ "WorkloadReferenceId",
242
+ "WorkloadCredentialId",
243
+ "WorkloadEntitlementId",
244
+ "WorkloadSubscriptionId",
245
+ "TrustMaterialId",
246
+ "base64url_decode",
247
+ "base64url_encode",
248
+ "constant_time_digest_equal",
249
+ "bytes_equal",
250
+ "text_equal",
251
+ "digest_bytes",
252
+ "digest_text",
253
+ "canonicalize",
254
+ "canonical_json_bytes",
255
+ "describe_owner",
256
+ "generate_nonce",
257
+ "headers_from_scope",
258
+ "json_response",
259
+ "jsonrpc_error",
260
+ "matches_dotted_pattern",
261
+ "clean_mapping",
262
+ "clean_tuple",
263
+ "new_model_id",
264
+ "normal_tuple",
265
+ "nonce_equal",
266
+ "normalize_protocol_tag",
267
+ "normalize_protocol_tags",
268
+ "normalize_entity",
269
+ "pick_fields",
270
+ "redact_sensitive_mapping",
271
+ "required_text",
272
+ "RefreshTokenError",
273
+ "RefreshTokenReuseError",
274
+ "read_http_body",
275
+ "replay_http_body",
276
+ "row_active",
277
+ "row_value",
278
+ "safe_display_path",
279
+ "sanitize_local_paths",
280
+ "sha256_text_digest",
281
+ "sha256_digest",
282
+ "str_tuple",
283
+ "new_client_id",
284
+ "new_credential_id",
285
+ "new_opaque_id",
286
+ "new_prefixed_id",
287
+ "new_principal_id",
288
+ "new_realm_id",
289
+ "new_tenant_id",
290
+ "tenant_key",
291
+ "token_hash",
292
+ "validate_nonce",
293
+ "require_absolute_uri",
294
+ "PROTOCOL_TAGS",
295
+ "unix_seconds",
296
+ "utc_now",
297
+ "utc_now_iso",
298
+ "uuid_str",
299
+ "semver_key",
300
+ "version_in_range",
301
+ ]
@@ -0,0 +1,118 @@
1
+ """Dependency-light taxonomy for identity and security artifacts."""
2
+
3
+ from enum import Enum
4
+
5
+
6
+ class ArtifactKind(str, Enum):
7
+ CREDENTIAL = "credential"
8
+ TOKEN = "token"
9
+ PRESENTATION = "presentation"
10
+ ATTESTATION = "attestation"
11
+ MANIFEST = "manifest"
12
+ CERTIFICATE = "certificate"
13
+ IDENTITY_DOCUMENT = "identity-document"
14
+ PROTECTED_ENVELOPE = "protected-envelope"
15
+ STATUS = "status"
16
+
17
+
18
+ class CredentialFormat(str, Enum):
19
+ W3C_VCDM = "w3c-vcdm"
20
+ SD_JWT_VC = "sd-jwt-vc"
21
+ ISO_MDOC = "iso-mdoc"
22
+ X509 = "x509"
23
+ X509_SVID = "x509-svid"
24
+ JWT_SVID = "jwt-svid"
25
+ WIT = "wit"
26
+ WIT_SVID = "wit-svid"
27
+ CWT_SVID_EXTENSION = "cwt-svid-extension"
28
+ VC_JOSE = "vc-jose"
29
+ VC_COSE = "vc-cose"
30
+
31
+
32
+ class TokenKind(str, Enum):
33
+ ACCESS = "access"
34
+ REFRESH = "refresh"
35
+ ID = "id"
36
+ SECURITY_EVENT = "security-event"
37
+ ENTITY_ATTESTATION = "entity-attestation"
38
+ WORKLOAD_IDENTITY = "workload-identity"
39
+ PROOF = "proof"
40
+ CONTINUATION = "continuation"
41
+ JWT = "jwt"
42
+ CWT = "cwt"
43
+ OIDC_ID_TOKEN = "oidc-id-token"
44
+ JWT_SVID = "jwt-svid"
45
+ WORKLOAD_IDENTITY_TOKEN = "workload-identity-token"
46
+ WORKLOAD_PROOF_TOKEN = "workload-proof-token"
47
+ CWT_SVID_EXTENSION = "cwt-svid-extension"
48
+
49
+
50
+ class PresentationKind(str, Enum):
51
+ W3C_VP = "w3c-vp"
52
+ SD_JWT = "sd-jwt"
53
+ ISO_MDOC = "iso-mdoc"
54
+ VC_JOSE = "vc-jose"
55
+ VC_COSE = "vc-cose"
56
+ WORKLOAD_AUTHENTICATION = "workload-authentication"
57
+
58
+
59
+ class IdentityDocumentKind(str, Enum):
60
+ DID_DOCUMENT = "did-document"
61
+ SPIFFE_SVID = "spiffe-svid"
62
+
63
+
64
+ class ProtectedEnvelopeKind(str, Enum):
65
+ JWS = "jws"
66
+ JWE = "jwe"
67
+ COSE_SIGN = "cose-sign"
68
+ COSE_SIGN1 = "cose-sign1"
69
+ COSE_ENCRYPT = "cose-encrypt"
70
+ COSE_ENCRYPT0 = "cose-encrypt0"
71
+ COSE_MAC = "cose-mac"
72
+ COSE_MAC0 = "cose-mac0"
73
+
74
+
75
+ class AttestationKind(str, Enum):
76
+ ENTITY = "entity"
77
+ WALLET = "wallet"
78
+ KEY = "key"
79
+ PLATFORM = "platform"
80
+
81
+
82
+ class ManifestKind(str, Enum):
83
+ CORIM = "corim"
84
+ COMID = "comid"
85
+ COSWID = "coswid"
86
+ COTL = "cotl"
87
+ COTS = "cots"
88
+ TRUST_BUNDLE = "trust-bundle"
89
+ STATUS_LIST = "status-list"
90
+
91
+
92
+ class VerificationOutcome(str, Enum):
93
+ VALID = "valid"
94
+ INVALID = "invalid"
95
+ INDETERMINATE = "indeterminate"
96
+
97
+
98
+ class LifecycleStatus(str, Enum):
99
+ PENDING = "pending"
100
+ ACTIVE = "active"
101
+ SUSPENDED = "suspended"
102
+ REVOKED = "revoked"
103
+ EXPIRED = "expired"
104
+ SUPERSEDED = "superseded"
105
+
106
+
107
+ __all__ = [
108
+ "ArtifactKind",
109
+ "AttestationKind",
110
+ "CredentialFormat",
111
+ "IdentityDocumentKind",
112
+ "LifecycleStatus",
113
+ "ManifestKind",
114
+ "PresentationKind",
115
+ "ProtectedEnvelopeKind",
116
+ "TokenKind",
117
+ "VerificationOutcome",
118
+ ]
@@ -0,0 +1,21 @@
1
+ """Base64url helpers shared by identity packages."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+
7
+
8
+ def base64url_encode(data: bytes | bytearray | memoryview) -> str:
9
+ """Return unpadded base64url text for byte-oriented data."""
10
+
11
+ return base64.urlsafe_b64encode(bytes(data)).rstrip(b"=").decode("ascii")
12
+
13
+
14
+ def base64url_decode(value: str) -> bytes:
15
+ """Decode unpadded base64url text into bytes."""
16
+
17
+ padding = "=" * (-len(value) % 4)
18
+ return base64.urlsafe_b64decode((value + padding).encode("ascii"))
19
+
20
+
21
+ __all__ = ["base64url_decode", "base64url_encode"]
@@ -0,0 +1,133 @@
1
+ """Primitive claim taxonomy shared across token and credential families."""
2
+
3
+ from dataclasses import dataclass
4
+ from enum import StrEnum
5
+ from typing import TypeAlias
6
+
7
+
8
+ class ClaimType(StrEnum):
9
+ IDENTITY = "identity"
10
+ AUTHENTICATION = "authentication"
11
+ AUTHORIZATION = "authorization"
12
+ ASSURANCE = "assurance"
13
+ CREDENTIAL = "credential"
14
+ ATTESTATION = "attestation"
15
+ SECURITY_EVENT = "security-event"
16
+ WORKLOAD = "workload"
17
+ TRANSACTION = "transaction"
18
+ PROTOCOL = "protocol"
19
+
20
+
21
+ class ClaimValueType(StrEnum):
22
+ STRING = "string"
23
+ STRING_LIST = "string-list"
24
+ NUMBER = "number"
25
+ BOOLEAN = "boolean"
26
+ URI = "uri"
27
+ TIMESTAMP = "timestamp"
28
+ JSON_OBJECT = "json-object"
29
+ JSON_VALUE = "json-value"
30
+ BYTES = "bytes"
31
+
32
+
33
+ class ClaimNameKind(StrEnum):
34
+ """Registration form of a claim identifier, not its semantic purpose."""
35
+
36
+ REGISTERED = "registered"
37
+ SPECIFICATION = "specification"
38
+ PROFILE = "profile"
39
+ PRIVATE = "private"
40
+ URI = "uri"
41
+ INTEGER_LABEL = "integer-label"
42
+ NAMESPACED = "namespaced"
43
+
44
+
45
+ class ClaimSourceKind(StrEnum):
46
+ SUBJECT = "subject"
47
+ SESSION = "session"
48
+ CREDENTIAL = "credential"
49
+ ATTESTATION = "attestation"
50
+ DERIVED = "derived"
51
+ PROVIDER = "provider"
52
+ PRIVATE = "private"
53
+
54
+
55
+ class ClaimDisclosureMode(StrEnum):
56
+ ALWAYS = "always"
57
+ REQUESTED = "requested"
58
+ CONSENTED = "consented"
59
+ SELECTIVE = "selective"
60
+ NEVER = "never"
61
+
62
+
63
+ ClaimLabel: TypeAlias = str | int
64
+
65
+
66
+ @dataclass(frozen=True, slots=True)
67
+ class ClaimIdentifier:
68
+ """Carrier-neutral claim identifier.
69
+
70
+ ``label`` supports both JSON string names and CWT/COSE integer labels.
71
+ ``namespace`` covers mdoc namespaces and URI/profile qualified families.
72
+ """
73
+
74
+ label: ClaimLabel
75
+ kind: ClaimNameKind = ClaimNameKind.SPECIFICATION
76
+ namespace: str | None = None
77
+ registry: str | None = None
78
+
79
+ def __post_init__(self) -> None:
80
+ if isinstance(self.label, bool) or not isinstance(self.label, (str, int)):
81
+ raise TypeError("claim label must be a string or integer")
82
+ if isinstance(self.label, str) and not self.label:
83
+ raise ValueError("claim label must not be empty")
84
+ if self.kind is ClaimNameKind.INTEGER_LABEL and not isinstance(self.label, int):
85
+ raise ValueError("integer-label claims require an integer label")
86
+ if self.kind is ClaimNameKind.NAMESPACED and not self.namespace:
87
+ raise ValueError("namespaced claims require a namespace")
88
+
89
+
90
+ class RegisteredClaim(StrEnum):
91
+ ISSUER = "iss"
92
+ SUBJECT = "sub"
93
+ AUDIENCE = "aud"
94
+ EXPIRATION = "exp"
95
+ NOT_BEFORE = "nbf"
96
+ ISSUED_AT = "iat"
97
+ JWT_ID = "jti"
98
+ AUTH_TIME = "auth_time"
99
+ NONCE = "nonce"
100
+ AUTH_CONTEXT = "acr"
101
+ AUTH_METHODS = "amr"
102
+ AUTHORIZED_PARTY = "azp"
103
+ CONFIRMATION = "cnf"
104
+ SCOPE = "scope"
105
+ CLIENT_ID = "client_id"
106
+ VERIFIED_CLAIMS = "verified_claims"
107
+ PLACE_OF_BIRTH = "place_of_birth"
108
+ NATIONALITIES = "nationalities"
109
+ BIRTH_FAMILY_NAME = "birth_family_name"
110
+ BIRTH_GIVEN_NAME = "birth_given_name"
111
+ BIRTH_MIDDLE_NAME = "birth_middle_name"
112
+ SALUTATION = "salutation"
113
+ TITLE = "title"
114
+ MSISDN = "msisdn"
115
+ ALSO_KNOWN_AS = "also_known_as"
116
+ ADDRESS_COUNTRY_CODE = "address.country_code"
117
+ CREDENTIAL_TYPE = "vct"
118
+ CREDENTIAL_STATUS = "status"
119
+ SECURITY_EVENTS = "events"
120
+ TRANSACTION_ID = "txn"
121
+ EAT_PROFILE = "eat_profile"
122
+
123
+
124
+ __all__ = [
125
+ "ClaimDisclosureMode",
126
+ "ClaimIdentifier",
127
+ "ClaimLabel",
128
+ "ClaimNameKind",
129
+ "ClaimSourceKind",
130
+ "ClaimType",
131
+ "ClaimValueType",
132
+ "RegisteredClaim",
133
+ ]
@@ -0,0 +1,59 @@
1
+ """Clock primitives shared by identity packages."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from datetime import datetime, timezone
7
+ from typing import Protocol
8
+
9
+ UTC = timezone.utc
10
+
11
+
12
+ class Clock(Protocol):
13
+ def now(self) -> datetime:
14
+ """Return an aware UTC timestamp."""
15
+
16
+
17
+ @dataclass(frozen=True, slots=True)
18
+ class SystemClock:
19
+ def now(self) -> datetime:
20
+ return datetime.now(UTC)
21
+
22
+
23
+ @dataclass(frozen=True, slots=True)
24
+ class FrozenClock:
25
+ value: datetime
26
+
27
+ def now(self) -> datetime:
28
+ if self.value.tzinfo is None:
29
+ return self.value.replace(tzinfo=UTC)
30
+ return self.value.astimezone(UTC)
31
+
32
+
33
+ def unix_seconds(clock: Clock | None = None) -> int:
34
+ active = clock or SystemClock()
35
+ return int(active.now().timestamp())
36
+
37
+
38
+ def utc_now(clock: Clock | None = None) -> datetime:
39
+ active = clock or SystemClock()
40
+ return active.now().astimezone(UTC)
41
+
42
+
43
+ def utc_now_iso(clock: Clock | None = None) -> str:
44
+ return utc_now(clock).isoformat()
45
+
46
+
47
+ def parse_time(value: str) -> datetime:
48
+ return datetime.fromisoformat(value.replace("Z", "+00:00"))
49
+
50
+
51
+ __all__ = [
52
+ "Clock",
53
+ "FrozenClock",
54
+ "SystemClock",
55
+ "parse_time",
56
+ "unix_seconds",
57
+ "utc_now",
58
+ "utc_now_iso",
59
+ ]
@@ -0,0 +1,15 @@
1
+ """Constant-time comparisons for secret-adjacent byte and text values."""
2
+
3
+ from __future__ import annotations
4
+ import hmac
5
+
6
+
7
+ def bytes_equal(left: bytes, right: bytes) -> bool:
8
+ return hmac.compare_digest(left, right)
9
+
10
+
11
+ def text_equal(left: str, right: str) -> bool:
12
+ return hmac.compare_digest(left.encode(), right.encode())
13
+
14
+
15
+ __all__ = ["bytes_equal", "text_equal"]
@@ -0,0 +1,55 @@
1
+ """Digest helpers shared by identity packages."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import hmac
7
+ from typing import Literal
8
+
9
+ DigestAlgorithm = Literal["sha256", "sha384", "sha512"]
10
+
11
+
12
+ def digest_bytes(data: bytes, algorithm: DigestAlgorithm = "sha256") -> bytes:
13
+ try:
14
+ return hashlib.new(algorithm, data).digest()
15
+ except ValueError as exc:
16
+ raise ValueError(f"unsupported digest algorithm: {algorithm}") from exc
17
+
18
+
19
+ def digest_text(value: str, algorithm: DigestAlgorithm = "sha256") -> str:
20
+ return digest_bytes(value.encode("utf-8"), algorithm).hex()
21
+
22
+
23
+ def sha256_text_digest(value: str) -> str:
24
+ """Return the SHA-256 hex digest of UTF-8 text."""
25
+
26
+ return hashlib.sha256(value.encode("utf-8")).hexdigest()
27
+
28
+
29
+ def token_hash(token: object) -> str:
30
+ """Return the stable token/storage identifier digest for a token-like value."""
31
+
32
+ return sha256_text_digest(str(token))
33
+
34
+
35
+ def sha256_digest(value: bytes) -> bytes:
36
+ """Return the raw SHA-256 digest of bytes."""
37
+
38
+ return hashlib.sha256(value).digest()
39
+
40
+
41
+ def constant_time_digest_equal(left: bytes, right: bytes) -> bool:
42
+ """Compare digests without data-dependent early exit."""
43
+
44
+ return hmac.compare_digest(left, right)
45
+
46
+
47
+ __all__ = [
48
+ "DigestAlgorithm",
49
+ "constant_time_digest_equal",
50
+ "digest_bytes",
51
+ "digest_text",
52
+ "sha256_digest",
53
+ "sha256_text_digest",
54
+ "token_hash",
55
+ ]