mailset 0.7.0__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.
mailset/_core.py ADDED
@@ -0,0 +1,518 @@
1
+ """How a client reaches Mailset: signed calls, tried again after a network
2
+ failure or a 5xx, the credential checked before anything is sent, and
3
+ passkey approvals. ``SyncCore`` runs on ``httpx.Client``, ``AsyncCore`` on
4
+ ``httpx.AsyncClient``; everything they share is in ``_CoreBase``."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import asyncio
9
+ import inspect
10
+ import json
11
+ import os
12
+ import random
13
+ import time
14
+ from typing import Any, Awaitable, Callable, Dict, Mapping, Optional, Tuple, Union
15
+ from urllib.parse import quote
16
+
17
+ import httpx
18
+
19
+ from ._convert import from_wire, register, to_wire
20
+ from ._credentials import Credential
21
+ from ._errors import (
22
+ MailsetError,
23
+ PasskeyPurpose,
24
+ PermissionDeniedError,
25
+ error,
26
+ error_of,
27
+ malformed,
28
+ purpose_of,
29
+ unreachable,
30
+ )
31
+ from ._platform import client_header, notice
32
+ from ._resources import COMMAND_PATH, COMMANDS
33
+ from ._typing import TypedDict
34
+
35
+ __all__ = ["Approval", "AsyncCore", "SyncCore"]
36
+
37
+ DEFAULT_API = "https://mailset.app"
38
+ DEFAULT_TIMEOUT = 30.0
39
+ DEFAULT_MAX_RETRIES = 2
40
+
41
+
42
+ class Approval(TypedDict):
43
+ """An approval waiting for someone's passkey."""
44
+
45
+ id: str
46
+ """Pass it as ``approval`` once approved."""
47
+
48
+ url: str
49
+ """Where whoever approves opens it, on a device with their passkey."""
50
+
51
+ expires_at: int
52
+ """When it stops waiting, in ms since the epoch."""
53
+
54
+ purpose: PasskeyPurpose
55
+ """What it approves."""
56
+
57
+
58
+ register(Approval, "_Approval", {"purpose": "_PasskeyPurpose"})
59
+ register(PasskeyPurpose, "_PasskeyPurpose")
60
+
61
+ OnApproval = Callable[[Approval], Union[None, Awaitable[None]]]
62
+ """Called when a command needs a passkey: hand ``approval.url`` to whoever
63
+ approves. The call goes on once they do."""
64
+
65
+ _GRANT_FLAGS = {
66
+ "read": "--read --mailbox <address>",
67
+ "send": "--send --mailbox <address>",
68
+ "campaigns": "--campaigns",
69
+ }
70
+ """What ``mailset keys create`` asks for each grant."""
71
+
72
+
73
+ def _sleep_seconds(tries: int, retry_after: Optional[str]) -> float:
74
+ """How long to wait before try ``tries + 1``: what ``Retry-After`` asks
75
+ (20 s at most), or a doubling pause with jitter."""
76
+ if retry_after:
77
+ try:
78
+ asked = float(retry_after)
79
+ except ValueError:
80
+ asked = -1.0
81
+ if asked >= 0 and asked != float("inf"):
82
+ return min(asked, 20.0)
83
+ return min(8.0, 0.5 * 2.0**tries) * (0.5 + random.random() / 2)
84
+
85
+
86
+ def _sleep(seconds: float) -> None:
87
+ time.sleep(seconds)
88
+
89
+
90
+ async def _async_sleep(seconds: float) -> None:
91
+ await asyncio.sleep(seconds)
92
+
93
+
94
+ class _CoreBase:
95
+ """What both cores share: the credential, where Mailset is, and how a
96
+ request and its answer read."""
97
+
98
+ def __init__(
99
+ self,
100
+ credential: Credential,
101
+ *,
102
+ base_url: Optional[str],
103
+ org: Optional[str],
104
+ timeout: Optional[float],
105
+ max_retries: Optional[int],
106
+ on_approval: Optional[OnApproval],
107
+ clock: Optional[Callable[[], float]],
108
+ ) -> None:
109
+ self.credential = credential
110
+ self.base_url = (
111
+ base_url or os.environ.get("MAILSET_API") or credential.api or DEFAULT_API
112
+ ).rstrip("/")
113
+ self.org = org
114
+ self.timeout = DEFAULT_TIMEOUT if timeout is None else float(timeout)
115
+ self.max_retries = max(0, DEFAULT_MAX_RETRIES if max_retries is None else int(max_retries))
116
+ self.on_approval = on_approval
117
+ self.clock = clock or time.time
118
+ self.client = client_header()
119
+
120
+ def __repr__(self) -> str:
121
+ return f"<{type(self).__name__} {self.credential.name} {self.base_url}>"
122
+
123
+ def now_ms(self) -> int:
124
+ return int(round(self.clock() * 1000))
125
+
126
+ def _request(
127
+ self, method: str, path: str, body: Any
128
+ ) -> Tuple[str, bytes]:
129
+ data = (
130
+ b""
131
+ if body is None
132
+ else json.dumps(body, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
133
+ )
134
+ return f"{self.base_url}{path}", data
135
+
136
+ def _headers(self, method: str, path: str, data: bytes) -> Dict[str, str]:
137
+ headers = {
138
+ "mailset-client": self.client,
139
+ **self.credential.headers(method, path, data, self.now_ms()),
140
+ }
141
+ if method == "POST":
142
+ headers["content-type"] = "application/json"
143
+ return headers
144
+
145
+ def _timeout(self, timeout: Optional[float]) -> httpx.Timeout:
146
+ return httpx.Timeout(self.timeout if timeout is None else float(timeout))
147
+
148
+ @staticmethod
149
+ def _reply(response: httpx.Response, command: Optional[str]) -> Any:
150
+ """Mailset's answer: its data, or its refusal raised."""
151
+ status = response.status_code
152
+ try:
153
+ reply = json.loads(response.content)
154
+ except ValueError:
155
+ raise unreachable(status=status, command=command) from None
156
+ if isinstance(reply, dict) and reply.get("ok") is True:
157
+ return reply.get("data")
158
+ refusal = (
159
+ error_of(reply.get("error"), status=status, command=command)
160
+ if isinstance(reply, dict)
161
+ else None
162
+ )
163
+ raise refusal or unreachable(status=status, command=command)
164
+
165
+ def _body(self, input: Any, org: Optional[str], approval: Optional[str]) -> Dict[str, Any]:
166
+ body: Dict[str, Any] = {"input": input if input is not None else {}}
167
+ org = org or self.org
168
+ if org:
169
+ body["org"] = org
170
+ if approval:
171
+ body["approval"] = approval
172
+ return body
173
+
174
+ def _mismatch(self, command: str) -> Optional[MailsetError]:
175
+ """A command this credential can't run, refused before anything is sent."""
176
+ info = COMMANDS.get(command)
177
+ held = self.credential.kind
178
+ if info is None or held in info[0]:
179
+ return None
180
+ if held == "key":
181
+ needs = "MAILSET_TOKEN"
182
+ message = (
183
+ f"{command} needs an API token (MAILSET_TOKEN): an app key (MAILSET_KEY) "
184
+ 'can’t run it. Make a token with: npx @mailset/cli tokens create "<name>"'
185
+ )
186
+ else:
187
+ needs = "MAILSET_KEY"
188
+ message = (
189
+ f"{command} answers only for an app key (MAILSET_KEY), and this is an API "
190
+ "token. Make a key with: npx @mailset/cli keys create --send --mailbox <address>"
191
+ )
192
+ return PermissionDeniedError("forbidden", message, command=command, needs=needs)
193
+
194
+ def _grant_refusal(self, refusal: MailsetError, command: str) -> MailsetError:
195
+ """Mailset's "the grant doesn't allow that", said with the grant this command needs."""
196
+ info = COMMANDS.get(command)
197
+ grant = info[1] if info else None
198
+ flags = _GRANT_FLAGS.get(grant or "")
199
+ if (
200
+ refusal.code != "forbidden"
201
+ or self.credential.kind != "key"
202
+ or not flags
203
+ or "grant" not in refusal.message.lower()
204
+ ):
205
+ return refusal
206
+ return PermissionDeniedError(
207
+ "forbidden",
208
+ f"{command} needs a key with the {grant} grant, or an API token (MAILSET_TOKEN). "
209
+ f"Make one with: npx @mailset/cli keys create {flags}",
210
+ status=refusal.status,
211
+ command=command,
212
+ needs=f"MAILSET_KEY with the {grant} grant",
213
+ )
214
+
215
+ def _wants_approval(self, refusal: MailsetError, approval: Optional[str]) -> bool:
216
+ return (
217
+ refusal.code == "step_up_required"
218
+ and refusal.purpose is not None
219
+ and self.on_approval is not None
220
+ and not approval
221
+ )
222
+
223
+ def _approval_body(self, purpose: Mapping[str, Any]) -> Dict[str, Any]:
224
+ if self.credential.kind == "key":
225
+ raise PermissionDeniedError(
226
+ "forbidden",
227
+ "An approval needs an API token (MAILSET_TOKEN): a person approves it "
228
+ "with their passkey, and an app key is no person.",
229
+ needs="MAILSET_TOKEN",
230
+ )
231
+ found = purpose_of(dict(purpose)) if isinstance(purpose, Mapping) else None
232
+ if found is None:
233
+ raise error("invalid_input", "A purpose has a kind and an id.")
234
+ return dict(found)
235
+
236
+ @staticmethod
237
+ def _approval_of(started: Any, body: Dict[str, Any]) -> Approval:
238
+ if (
239
+ not isinstance(started, dict)
240
+ or not isinstance(started.get("id"), str)
241
+ or not isinstance(started.get("approveUrl"), str)
242
+ or not isinstance(started.get("expiresAt"), (int, float))
243
+ ):
244
+ raise malformed()
245
+ purpose = purpose_of(body) or PasskeyPurpose(kind=body["kind"], id=body["id"], org=None)
246
+ return Approval(
247
+ id=started["id"],
248
+ url=started["approveUrl"],
249
+ expires_at=int(started["expiresAt"]),
250
+ purpose=purpose,
251
+ )
252
+
253
+ @staticmethod
254
+ def _approval_path(approval: Union[Approval, str]) -> Tuple[str, str]:
255
+ id = approval if isinstance(approval, str) else approval["id"]
256
+ return id, f"/v1/approvals/{quote(id, safe='')}"
257
+
258
+ @staticmethod
259
+ def _approval_state(view: Any) -> Optional[str]:
260
+ state = view.get("state") if isinstance(view, dict) else None
261
+ if state == "denied":
262
+ raise PermissionDeniedError("forbidden", "That approval was refused.")
263
+ if state == "expired":
264
+ raise PermissionDeniedError(
265
+ "forbidden", "That approval expired before anyone approved it."
266
+ )
267
+ return state if isinstance(state, str) else None
268
+
269
+ @staticmethod
270
+ def _too_late() -> MailsetError:
271
+ return error("expired", "Nobody approved it in time.")
272
+
273
+
274
+ class SyncCore(_CoreBase):
275
+ """Calls Mailset with ``httpx.Client``, blocking."""
276
+
277
+ def __init__(self, credential: Credential, *, http_client: Optional[httpx.Client], **options: Any):
278
+ super().__init__(credential, **options)
279
+ self.http = http_client or httpx.Client()
280
+ self.owns_http = http_client is None
281
+
282
+ def close(self) -> None:
283
+ if self.owns_http:
284
+ self.http.close()
285
+
286
+ def raw(
287
+ self,
288
+ method: str,
289
+ path: str,
290
+ body: Any,
291
+ *,
292
+ command: Optional[str] = None,
293
+ timeout: Optional[float] = None,
294
+ ) -> Any:
295
+ """One request, signed, tried again after a network failure or a 5xx."""
296
+ url, data = self._request(method, path, body)
297
+ tries = 0
298
+ while True:
299
+ try:
300
+ response = self.http.request(
301
+ method,
302
+ url,
303
+ content=data if method == "POST" else None,
304
+ headers=self._headers(method, path, data),
305
+ timeout=self._timeout(timeout),
306
+ )
307
+ except httpx.TransportError as failure:
308
+ if tries >= self.max_retries:
309
+ raise unreachable(
310
+ command=command, timed_out=isinstance(failure, httpx.TimeoutException)
311
+ ) from failure
312
+ _sleep(_sleep_seconds(tries, None))
313
+ tries += 1
314
+ continue
315
+ notice(response.headers.get("mailset-notice"))
316
+ if response.status_code >= 500 and tries < self.max_retries:
317
+ _sleep(_sleep_seconds(tries, response.headers.get("retry-after")))
318
+ tries += 1
319
+ continue
320
+ return self._reply(response, command)
321
+
322
+ def call(
323
+ self,
324
+ command: str,
325
+ input: Any,
326
+ *,
327
+ org: Optional[str] = None,
328
+ approval: Optional[str] = None,
329
+ timeout: Optional[float] = None,
330
+ ) -> Any:
331
+ """One command: refused here when this credential can't run it, else
332
+ signed and sent, through a passkey approval when ``on_approval`` is set."""
333
+ wrong = self._mismatch(command)
334
+ if wrong:
335
+ raise wrong
336
+ try:
337
+ return self.raw(
338
+ "POST",
339
+ f"{COMMAND_PATH}{command}",
340
+ self._body(input, org, approval),
341
+ command=command,
342
+ timeout=timeout,
343
+ )
344
+ except MailsetError as refusal:
345
+ if self._wants_approval(refusal, approval) and refusal.purpose:
346
+ pending = self.request_approval(refusal.purpose)
347
+ answered = self.on_approval(pending) if self.on_approval else None
348
+ if inspect.isawaitable(answered):
349
+ close = getattr(answered, "close", None)
350
+ if callable(close):
351
+ close()
352
+ raise TypeError(
353
+ "on_approval returned an awaitable: use AsyncMailset for an async callback"
354
+ ) from None
355
+ approved = self.wait_approval(pending)
356
+ return self.call(command, input, org=org, approval=approved, timeout=timeout)
357
+ better = self._grant_refusal(refusal, command)
358
+ if better is refusal:
359
+ raise
360
+ raise better from refusal
361
+
362
+ def command(
363
+ self,
364
+ command: str,
365
+ params: Optional[Mapping[str, Any]],
366
+ given: str,
367
+ answer: str,
368
+ org: Optional[str],
369
+ approval: Optional[str],
370
+ timeout: Optional[float],
371
+ ) -> Any:
372
+ """A generated method's call: its dict as the command's input, in
373
+ camelCase, and its answer in snake_case, as the specs say."""
374
+ data = self.call(
375
+ command,
376
+ to_wire(given, params or {}, given=True),
377
+ org=org,
378
+ approval=approval,
379
+ timeout=timeout,
380
+ )
381
+ return from_wire(answer, data)
382
+
383
+ def request_approval(self, purpose: Mapping[str, Any]) -> Approval:
384
+ body = self._approval_body(purpose)
385
+ return self._approval_of(self.raw("POST", "/v1/approvals", body), body)
386
+
387
+ def wait_approval(
388
+ self, approval: Union[Approval, str], *, timeout: float = 600.0, every: float = 2.0
389
+ ) -> str:
390
+ id, path = self._approval_path(approval)
391
+ until = time.monotonic() + timeout
392
+ while time.monotonic() < until:
393
+ if self._approval_state(self.raw("GET", path, None)) == "approved":
394
+ return id
395
+ _sleep(every)
396
+ raise self._too_late()
397
+
398
+
399
+ class AsyncCore(_CoreBase):
400
+ """Calls Mailset with ``httpx.AsyncClient``."""
401
+
402
+ def __init__(
403
+ self, credential: Credential, *, http_client: Optional[httpx.AsyncClient], **options: Any
404
+ ):
405
+ super().__init__(credential, **options)
406
+ self.http = http_client or httpx.AsyncClient()
407
+ self.owns_http = http_client is None
408
+
409
+ async def close(self) -> None:
410
+ if self.owns_http:
411
+ await self.http.aclose()
412
+
413
+ async def raw(
414
+ self,
415
+ method: str,
416
+ path: str,
417
+ body: Any,
418
+ *,
419
+ command: Optional[str] = None,
420
+ timeout: Optional[float] = None,
421
+ ) -> Any:
422
+ """One request, signed, tried again after a network failure or a 5xx."""
423
+ url, data = self._request(method, path, body)
424
+ tries = 0
425
+ while True:
426
+ try:
427
+ response = await self.http.request(
428
+ method,
429
+ url,
430
+ content=data if method == "POST" else None,
431
+ headers=self._headers(method, path, data),
432
+ timeout=self._timeout(timeout),
433
+ )
434
+ except httpx.TransportError as failure:
435
+ if tries >= self.max_retries:
436
+ raise unreachable(
437
+ command=command, timed_out=isinstance(failure, httpx.TimeoutException)
438
+ ) from failure
439
+ await _async_sleep(_sleep_seconds(tries, None))
440
+ tries += 1
441
+ continue
442
+ notice(response.headers.get("mailset-notice"))
443
+ if response.status_code >= 500 and tries < self.max_retries:
444
+ await _async_sleep(_sleep_seconds(tries, response.headers.get("retry-after")))
445
+ tries += 1
446
+ continue
447
+ return self._reply(response, command)
448
+
449
+ async def call(
450
+ self,
451
+ command: str,
452
+ input: Any,
453
+ *,
454
+ org: Optional[str] = None,
455
+ approval: Optional[str] = None,
456
+ timeout: Optional[float] = None,
457
+ ) -> Any:
458
+ """One command: refused here when this credential can't run it, else
459
+ signed and sent, through a passkey approval when ``on_approval`` is set."""
460
+ wrong = self._mismatch(command)
461
+ if wrong:
462
+ raise wrong
463
+ try:
464
+ return await self.raw(
465
+ "POST",
466
+ f"{COMMAND_PATH}{command}",
467
+ self._body(input, org, approval),
468
+ command=command,
469
+ timeout=timeout,
470
+ )
471
+ except MailsetError as refusal:
472
+ if self._wants_approval(refusal, approval) and refusal.purpose:
473
+ pending = await self.request_approval(refusal.purpose)
474
+ answered = self.on_approval(pending) if self.on_approval else None
475
+ if inspect.isawaitable(answered):
476
+ await answered
477
+ approved = await self.wait_approval(pending)
478
+ return await self.call(command, input, org=org, approval=approved, timeout=timeout)
479
+ better = self._grant_refusal(refusal, command)
480
+ if better is refusal:
481
+ raise
482
+ raise better from refusal
483
+
484
+ async def command(
485
+ self,
486
+ command: str,
487
+ params: Optional[Mapping[str, Any]],
488
+ given: str,
489
+ answer: str,
490
+ org: Optional[str],
491
+ approval: Optional[str],
492
+ timeout: Optional[float],
493
+ ) -> Any:
494
+ """A generated method's call: its dict as the command's input, in
495
+ camelCase, and its answer in snake_case, as the specs say."""
496
+ data = await self.call(
497
+ command,
498
+ to_wire(given, params or {}, given=True),
499
+ org=org,
500
+ approval=approval,
501
+ timeout=timeout,
502
+ )
503
+ return from_wire(answer, data)
504
+
505
+ async def request_approval(self, purpose: Mapping[str, Any]) -> Approval:
506
+ body = self._approval_body(purpose)
507
+ return self._approval_of(await self.raw("POST", "/v1/approvals", body), body)
508
+
509
+ async def wait_approval(
510
+ self, approval: Union[Approval, str], *, timeout: float = 600.0, every: float = 2.0
511
+ ) -> str:
512
+ id, path = self._approval_path(approval)
513
+ until = time.monotonic() + timeout
514
+ while time.monotonic() < until:
515
+ if self._approval_state(await self.raw("GET", path, None)) == "approved":
516
+ return id
517
+ await _async_sleep(every)
518
+ raise self._too_late()
@@ -0,0 +1,171 @@
1
+ """``MAILSET_KEY`` and ``MAILSET_TOKEN``: reading them, and signing with them."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import binascii
7
+ import hashlib
8
+ import json
9
+ import os
10
+ from typing import Any, Dict, Mapping, Optional
11
+ from urllib.parse import urlsplit
12
+
13
+ from cryptography.hazmat.primitives import hashes
14
+ from cryptography.hazmat.primitives.asymmetric import ec
15
+ from cryptography.hazmat.primitives.asymmetric.utils import decode_dss_signature
16
+
17
+ from ._errors import refused
18
+
19
+ __all__ = ["Credential", "credential_from", "sign_request"]
20
+
21
+ KEY_PREFIX = "msk1_"
22
+ TOKEN_PREFIX = "mst_"
23
+
24
+ NO_CREDENTIAL = (
25
+ "No credential: set MAILSET_KEY (an app key: npx @mailset/cli keys create "
26
+ "--send --mailbox <address>) or MAILSET_TOKEN (an API token: npx @mailset/cli "
27
+ 'tokens create "<name>"), or pass key or token.'
28
+ )
29
+ NOT_A_KEY = (
30
+ "That isn’t a MAILSET_KEY. Make one with: npx @mailset/cli keys create "
31
+ "--send --mailbox <address>"
32
+ )
33
+ NOT_A_TOKEN = (
34
+ 'That isn’t a MAILSET_TOKEN. Make one with: npx @mailset/cli tokens create "<name>"'
35
+ )
36
+
37
+
38
+ def b64url(data: bytes) -> str:
39
+ """base64url with no padding, as Mailset writes it."""
40
+ return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
41
+
42
+
43
+ def b64url_decode(text: str) -> Optional[bytes]:
44
+ """base64url, padded or not, or None when it isn't."""
45
+ try:
46
+ return base64.b64decode(text + "=" * (-len(text) % 4), altchars=b"-_", validate=True)
47
+ except (binascii.Error, ValueError):
48
+ return None
49
+
50
+
51
+ class Credential:
52
+ """A credential, decoded: which kind it is, its API, its session token
53
+ and the key that signs. Its string form says only its kind."""
54
+
55
+ __slots__ = ("kind", "api", "_token", "_key")
56
+
57
+ def __init__(self, kind: str, api: Optional[str], token: str, key: ec.EllipticCurvePrivateKey):
58
+ self.kind = kind
59
+ """``key`` (a MAILSET_KEY) or ``token`` (a MAILSET_TOKEN)."""
60
+ self.api = api
61
+ self._token = token
62
+ self._key = key
63
+
64
+ @property
65
+ def name(self) -> str:
66
+ """``MAILSET_KEY`` or ``MAILSET_TOKEN``."""
67
+ return "MAILSET_KEY" if self.kind == "key" else "MAILSET_TOKEN"
68
+
69
+ def __repr__(self) -> str:
70
+ return f"<{self.name}>"
71
+
72
+ __str__ = __repr__
73
+
74
+ def headers(self, method: str, path: str, body: bytes, now_ms: int) -> Dict[str, str]:
75
+ """``Authorization``, ``ms-time`` and ``ms-proof`` for one try of a request."""
76
+ return {
77
+ "authorization": f"Bearer {self._token}",
78
+ **sign_request(self._key, method, path, body, now_ms),
79
+ }
80
+
81
+
82
+ def sign_request(
83
+ key: ec.EllipticCurvePrivateKey, method: str, path: str, body: bytes, now_ms: int
84
+ ) -> Dict[str, str]:
85
+ """The proof that this key made this request now: ``ms-time``, and
86
+ ``ms-proof``, an ECDSA P-256 SHA-256 signature (raw r||s, base64url)
87
+ over the method, the path with its query, the time and the body's digest."""
88
+ digest = b64url(hashlib.sha256(body).digest())
89
+ message = f"ms-proof-v1\n{method.upper()}\n{path}\n{now_ms}\n{digest}"
90
+ der = key.sign(message.encode("utf-8"), ec.ECDSA(hashes.SHA256()))
91
+ r, s = decode_dss_signature(der)
92
+ return {
93
+ "ms-time": str(now_ms),
94
+ "ms-proof": b64url(r.to_bytes(32, "big") + s.to_bytes(32, "big")),
95
+ }
96
+
97
+
98
+ def _filled(value: Any) -> bool:
99
+ return isinstance(value, str) and value != ""
100
+
101
+
102
+ def _private_key(jwk: Any, *, curve_named: bool) -> Optional[ec.EllipticCurvePrivateKey]:
103
+ """The P-256 key in a JWK, or None when it isn't one."""
104
+ if not isinstance(jwk, Mapping) or jwk.get("kty") != "EC":
105
+ return None
106
+ if curve_named and jwk.get("crv") != "P-256":
107
+ return None
108
+ if not (_filled(jwk.get("d")) and _filled(jwk.get("x")) and _filled(jwk.get("y"))):
109
+ return None
110
+ scalar = b64url_decode(str(jwk["d"]))
111
+ if not scalar:
112
+ return None
113
+ try:
114
+ return ec.derive_private_key(int.from_bytes(scalar, "big"), ec.SECP256R1())
115
+ except ValueError:
116
+ return None
117
+
118
+
119
+ def _payload(text: str, prefix: str) -> Optional[Dict[str, Any]]:
120
+ data = b64url_decode(text[len(prefix) :])
121
+ if data is None:
122
+ return None
123
+ try:
124
+ parsed = json.loads(data.decode("utf-8"))
125
+ except (UnicodeDecodeError, ValueError):
126
+ return None
127
+ return parsed if isinstance(parsed, dict) else None
128
+
129
+
130
+ def _valid_url(value: str) -> bool:
131
+ try:
132
+ parts = urlsplit(value)
133
+ except ValueError:
134
+ return False
135
+ return bool(parts.scheme and parts.netloc)
136
+
137
+
138
+ def decode(text: str) -> Optional[Credential]:
139
+ """A ``MAILSET_KEY`` or an API token, whichever the text is, or None.
140
+ Says nothing about why: the text is a secret."""
141
+ value = text.strip()
142
+ if value.startswith(KEY_PREFIX):
143
+ payload = _payload(value, KEY_PREFIX)
144
+ if payload is None:
145
+ return None
146
+ api, token = payload.get("api"), payload.get("token")
147
+ if not (_filled(api) and _valid_url(str(api)) and _filled(token)):
148
+ return None
149
+ key = _private_key(payload.get("privateKey"), curve_named=True)
150
+ return Credential("key", str(api), str(token), key) if key else None
151
+ if value.startswith(TOKEN_PREFIX):
152
+ payload = _payload(value, TOKEN_PREFIX)
153
+ if payload is None or not _filled(payload.get("token")):
154
+ return None
155
+ key = _private_key(payload.get("privateKey"), curve_named=False)
156
+ api = payload.get("api")
157
+ if key is None:
158
+ return None
159
+ return Credential("token", api if isinstance(api, str) else None, payload["token"], key)
160
+ return None
161
+
162
+
163
+ def credential_from(key: Optional[str], token: Optional[str]) -> Credential:
164
+ """The credential given, else ``MAILSET_KEY``, else ``MAILSET_TOKEN``."""
165
+ text = key or token or os.environ.get("MAILSET_KEY") or os.environ.get("MAILSET_TOKEN")
166
+ if not text:
167
+ raise refused(NO_CREDENTIAL)
168
+ found = decode(text)
169
+ if found is not None:
170
+ return found
171
+ raise refused(NOT_A_TOKEN if text.strip().startswith(TOKEN_PREFIX) else NOT_A_KEY)