tingping-core 0.1.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.
- tingping_core/__init__.py +131 -0
- tingping_core/adapter.py +60 -0
- tingping_core/collapse.py +109 -0
- tingping_core/drivers/__init__.py +5 -0
- tingping_core/drivers/_jwt.py +27 -0
- tingping_core/drivers/apns.py +226 -0
- tingping_core/drivers/base.py +67 -0
- tingping_core/drivers/socket.py +131 -0
- tingping_core/drivers/webpush.py +170 -0
- tingping_core/encryption.py +48 -0
- tingping_core/engine.py +491 -0
- tingping_core/errors.py +27 -0
- tingping_core/frames.py +100 -0
- tingping_core/hmac_auth.py +68 -0
- tingping_core/idempotency.py +38 -0
- tingping_core/jsonutil.py +125 -0
- tingping_core/models.py +35 -0
- tingping_core/offline_store.py +105 -0
- tingping_core/protocol.py +56 -0
- tingping_core/py.typed +0 -0
- tingping_core/router.py +283 -0
- tingping_core/scheduler.py +75 -0
- tingping_core/send_input.py +60 -0
- tingping_core/testing.py +129 -0
- tingping_core/ulid.py +41 -0
- tingping_core/validation.py +313 -0
- tingping_core-0.1.0.dist-info/METADATA +192 -0
- tingping_core-0.1.0.dist-info/RECORD +31 -0
- tingping_core-0.1.0.dist-info/WHEEL +4 -0
- tingping_core-0.1.0.dist-info/licenses/LICENSE +202 -0
- tingping_core-0.1.0.dist-info/licenses/NOTICE +4 -0
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""tingping-core: the self-hosted push notification server for Python (FastAPI).
|
|
2
|
+
|
|
3
|
+
from tingping_core import TingPingEngine, InMemoryStorageAdapter, create_router
|
|
4
|
+
|
|
5
|
+
engine = TingPingEngine(InMemoryStorageAdapter(), producer_secrets={"tp_live_key": "secret"})
|
|
6
|
+
app.include_router(create_router(engine, authenticate=my_auth))
|
|
7
|
+
|
|
8
|
+
See PROTOCOL.md in the repository for the wire protocol shared with the npm packages.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from .adapter import InMemoryStorageAdapter, PushStorageAdapter
|
|
12
|
+
from .collapse import BurstCollapser, CollapsedMessage, CollapseFormatter, collapse_bucket_key
|
|
13
|
+
from .drivers.base import DriverResult, PushContext, PushDriver
|
|
14
|
+
from .drivers.socket import SocketRegistry, SocketSession, SocketTransport
|
|
15
|
+
from .encryption import generate_encryption_key, open_payload, seal_payload
|
|
16
|
+
from .engine import EngineStats, TingPingEngine
|
|
17
|
+
from .errors import TingPingError
|
|
18
|
+
from .frames import (
|
|
19
|
+
PONG_FRAME,
|
|
20
|
+
FittedPayload,
|
|
21
|
+
NotificationFrame,
|
|
22
|
+
build_notification_frame,
|
|
23
|
+
error_frame,
|
|
24
|
+
fit_payload,
|
|
25
|
+
ready_frame,
|
|
26
|
+
truncate_frame,
|
|
27
|
+
)
|
|
28
|
+
from .hmac_auth import compute_signature, verify_signed_request
|
|
29
|
+
from .idempotency import IdempotencyCache
|
|
30
|
+
from .jsonutil import dumps, js_number, parse_json_body
|
|
31
|
+
from .models import ClientIdentity, DeviceRegistration
|
|
32
|
+
from .offline_store import BufferedFrame, InMemoryOfflineStore, OfflineStore
|
|
33
|
+
from .protocol import PLATFORMS, CloseCode, Platform, Priority
|
|
34
|
+
from .router import Authenticate, AuthRequest, create_app, create_router
|
|
35
|
+
from .scheduler import AsyncioScheduler, ManualScheduler, Scheduler
|
|
36
|
+
from .send_input import build_dispatch_body
|
|
37
|
+
from .ulid import encode_ulid, new_event_id, new_message_id, ulid
|
|
38
|
+
from .validation import (
|
|
39
|
+
DispatchRequest,
|
|
40
|
+
parse_client_frame,
|
|
41
|
+
validate_dispatch,
|
|
42
|
+
validate_register,
|
|
43
|
+
validate_unregister,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
__version__ = "0.1.0"
|
|
47
|
+
|
|
48
|
+
_APNS_NAMES = (
|
|
49
|
+
"ApnsConfig",
|
|
50
|
+
"ApnsDriver",
|
|
51
|
+
"apns_collapse_id",
|
|
52
|
+
"build_apns_request",
|
|
53
|
+
"create_apns_jwt",
|
|
54
|
+
"is_apns_device_token",
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def __getattr__(name: str) -> object:
|
|
59
|
+
# Drivers with optional dependencies load on first use.
|
|
60
|
+
if name in ("VapidConfig", "WebPushDriver", "generate_vapid_keys"):
|
|
61
|
+
from .drivers import webpush
|
|
62
|
+
|
|
63
|
+
return getattr(webpush, name)
|
|
64
|
+
if name in _APNS_NAMES:
|
|
65
|
+
from .drivers import apns
|
|
66
|
+
|
|
67
|
+
return getattr(apns, name)
|
|
68
|
+
raise AttributeError(f"module 'tingping_core' has no attribute {name!r}")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
__all__ = [
|
|
72
|
+
"PLATFORMS",
|
|
73
|
+
"PONG_FRAME",
|
|
74
|
+
"AsyncioScheduler",
|
|
75
|
+
"AuthRequest",
|
|
76
|
+
"Authenticate",
|
|
77
|
+
"BufferedFrame",
|
|
78
|
+
"BurstCollapser",
|
|
79
|
+
"ClientIdentity",
|
|
80
|
+
"CloseCode",
|
|
81
|
+
"CollapseFormatter",
|
|
82
|
+
"CollapsedMessage",
|
|
83
|
+
"DeviceRegistration",
|
|
84
|
+
"DispatchRequest",
|
|
85
|
+
"DriverResult",
|
|
86
|
+
"EngineStats",
|
|
87
|
+
"FittedPayload",
|
|
88
|
+
"IdempotencyCache",
|
|
89
|
+
"InMemoryOfflineStore",
|
|
90
|
+
"InMemoryStorageAdapter",
|
|
91
|
+
"ManualScheduler",
|
|
92
|
+
"NotificationFrame",
|
|
93
|
+
"OfflineStore",
|
|
94
|
+
"Platform",
|
|
95
|
+
"Priority",
|
|
96
|
+
"PushContext",
|
|
97
|
+
"PushDriver",
|
|
98
|
+
"PushStorageAdapter",
|
|
99
|
+
"Scheduler",
|
|
100
|
+
"SocketRegistry",
|
|
101
|
+
"SocketSession",
|
|
102
|
+
"SocketTransport",
|
|
103
|
+
"TingPingEngine",
|
|
104
|
+
"TingPingError",
|
|
105
|
+
"__version__",
|
|
106
|
+
"build_dispatch_body",
|
|
107
|
+
"build_notification_frame",
|
|
108
|
+
"collapse_bucket_key",
|
|
109
|
+
"compute_signature",
|
|
110
|
+
"create_app",
|
|
111
|
+
"create_router",
|
|
112
|
+
"dumps",
|
|
113
|
+
"encode_ulid",
|
|
114
|
+
"error_frame",
|
|
115
|
+
"fit_payload",
|
|
116
|
+
"generate_encryption_key",
|
|
117
|
+
"js_number",
|
|
118
|
+
"new_event_id",
|
|
119
|
+
"new_message_id",
|
|
120
|
+
"open_payload",
|
|
121
|
+
"parse_client_frame",
|
|
122
|
+
"parse_json_body",
|
|
123
|
+
"ready_frame",
|
|
124
|
+
"seal_payload",
|
|
125
|
+
"truncate_frame",
|
|
126
|
+
"ulid",
|
|
127
|
+
"validate_dispatch",
|
|
128
|
+
"validate_register",
|
|
129
|
+
"validate_unregister",
|
|
130
|
+
"verify_signed_request",
|
|
131
|
+
]
|
tingping_core/adapter.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Connects tingping to the host's database (PROTOCOL.md §8)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from abc import ABC, abstractmethod
|
|
6
|
+
|
|
7
|
+
from .models import DeviceRegistration
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class PushStorageAdapter(ABC):
|
|
11
|
+
"""Five async methods over your own device table.
|
|
12
|
+
|
|
13
|
+
Implementations must be safe to call concurrently. Wrap blocking database
|
|
14
|
+
drivers with ``asyncio.to_thread``.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
@abstractmethod
|
|
18
|
+
async def save_device(self, record: DeviceRegistration) -> None:
|
|
19
|
+
"""Inserts or replaces the registration identified by ``record.token``."""
|
|
20
|
+
|
|
21
|
+
@abstractmethod
|
|
22
|
+
async def remove_device(self, token: str) -> None:
|
|
23
|
+
"""Deletes a registration. Unknown tokens are not an error."""
|
|
24
|
+
|
|
25
|
+
@abstractmethod
|
|
26
|
+
async def get_devices_by_user_id(self, user_id: str) -> list[DeviceRegistration]:
|
|
27
|
+
"""All devices registered to a user."""
|
|
28
|
+
|
|
29
|
+
@abstractmethod
|
|
30
|
+
async def get_devices_by_tenant_id(self, tenant_id: str) -> list[DeviceRegistration]:
|
|
31
|
+
"""All devices of every user in a tenant / organization."""
|
|
32
|
+
|
|
33
|
+
@abstractmethod
|
|
34
|
+
async def get_devices_by_topic(self, topic: str) -> list[DeviceRegistration]:
|
|
35
|
+
"""All devices subscribed to a pub/sub topic."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class InMemoryStorageAdapter(PushStorageAdapter):
|
|
39
|
+
"""A process-local adapter for tests, demos and single-instance deployments."""
|
|
40
|
+
|
|
41
|
+
def __init__(self) -> None:
|
|
42
|
+
self._devices: dict[str, DeviceRegistration] = {}
|
|
43
|
+
|
|
44
|
+
async def save_device(self, record: DeviceRegistration) -> None:
|
|
45
|
+
self._devices[record.token] = record.copy()
|
|
46
|
+
|
|
47
|
+
async def remove_device(self, token: str) -> None:
|
|
48
|
+
self._devices.pop(token, None)
|
|
49
|
+
|
|
50
|
+
async def get_devices_by_user_id(self, user_id: str) -> list[DeviceRegistration]:
|
|
51
|
+
return [d.copy() for d in self._devices.values() if d.user_id == user_id]
|
|
52
|
+
|
|
53
|
+
async def get_devices_by_tenant_id(self, tenant_id: str) -> list[DeviceRegistration]:
|
|
54
|
+
return [d.copy() for d in self._devices.values() if d.tenant_id == tenant_id]
|
|
55
|
+
|
|
56
|
+
async def get_devices_by_topic(self, topic: str) -> list[DeviceRegistration]:
|
|
57
|
+
return [d.copy() for d in self._devices.values() if topic in d.topics]
|
|
58
|
+
|
|
59
|
+
def __len__(self) -> int:
|
|
60
|
+
return len(self._devices)
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Burst collapse (PROTOCOL.md §7.6): one delivery per collapse_key + target per window."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from collections.abc import Callable, Sequence
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from .scheduler import AsyncioScheduler, Cancelable, Scheduler
|
|
11
|
+
from .validation import DispatchRequest, NotificationPayload
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class CollapsedMessage:
|
|
16
|
+
#: The latest event, with merged priority (and formatter output, if any).
|
|
17
|
+
dispatch: DispatchRequest
|
|
18
|
+
#: How many events were merged (≥ 1).
|
|
19
|
+
collapsed_count: int
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
#: Overrides "latest event wins": receives the merged events oldest-first (at most
|
|
23
|
+
#: the last 1000) and the count; returns ``(notification, data)``.
|
|
24
|
+
CollapseFormatter = Callable[[Sequence[DispatchRequest], int], "tuple[NotificationPayload | None, dict[str, Any]]"]
|
|
25
|
+
|
|
26
|
+
_MAX_RETAINED_EVENTS = 1000
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def collapse_bucket_key(dispatch: DispatchRequest) -> str:
|
|
30
|
+
target = dispatch["target"]
|
|
31
|
+
return json.dumps(
|
|
32
|
+
[dispatch["options"]["collapse_key"], target["user_id"], target["tenant_id"], target["topic"]],
|
|
33
|
+
ensure_ascii=False,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass
|
|
38
|
+
class _Bucket:
|
|
39
|
+
latest: DispatchRequest
|
|
40
|
+
count: int
|
|
41
|
+
priority: str
|
|
42
|
+
timer: Cancelable
|
|
43
|
+
events: list[DispatchRequest] = field(default_factory=list)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class BurstCollapser:
|
|
47
|
+
def __init__(
|
|
48
|
+
self,
|
|
49
|
+
on_flush: Callable[[CollapsedMessage], None],
|
|
50
|
+
formatter: CollapseFormatter | None = None,
|
|
51
|
+
scheduler: Scheduler | None = None,
|
|
52
|
+
) -> None:
|
|
53
|
+
self._on_flush = on_flush
|
|
54
|
+
self._formatter = formatter
|
|
55
|
+
self._scheduler: Scheduler = scheduler or AsyncioScheduler()
|
|
56
|
+
self._buckets: dict[str, _Bucket] = {}
|
|
57
|
+
|
|
58
|
+
def submit(self, dispatch: DispatchRequest) -> None:
|
|
59
|
+
key = dispatch["options"]["collapse_key"]
|
|
60
|
+
window = dispatch["options"]["collapse_window_ms"]
|
|
61
|
+
if key is None or window <= 0:
|
|
62
|
+
self._on_flush(CollapsedMessage(dispatch, 1))
|
|
63
|
+
return
|
|
64
|
+
bucket_key = collapse_bucket_key(dispatch)
|
|
65
|
+
bucket = self._buckets.get(bucket_key)
|
|
66
|
+
if bucket is not None:
|
|
67
|
+
bucket.latest = dispatch
|
|
68
|
+
bucket.count += 1
|
|
69
|
+
if dispatch["options"]["priority"] == "high":
|
|
70
|
+
bucket.priority = "high"
|
|
71
|
+
if self._formatter is not None:
|
|
72
|
+
bucket.events.append(dispatch)
|
|
73
|
+
if len(bucket.events) > _MAX_RETAINED_EVENTS:
|
|
74
|
+
bucket.events.pop(0)
|
|
75
|
+
return
|
|
76
|
+
timer = self._scheduler.call_later(window, lambda: self._flush_bucket(bucket_key))
|
|
77
|
+
self._buckets[bucket_key] = _Bucket(
|
|
78
|
+
latest=dispatch,
|
|
79
|
+
count=1,
|
|
80
|
+
priority=dispatch["options"]["priority"],
|
|
81
|
+
timer=timer,
|
|
82
|
+
events=[dispatch] if self._formatter is not None else [],
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
def flush_all(self) -> None:
|
|
86
|
+
for key in list(self._buckets):
|
|
87
|
+
self._flush_bucket(key)
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def pending_buckets(self) -> int:
|
|
91
|
+
return len(self._buckets)
|
|
92
|
+
|
|
93
|
+
def _flush_bucket(self, bucket_key: str) -> None:
|
|
94
|
+
bucket = self._buckets.pop(bucket_key, None)
|
|
95
|
+
if bucket is None:
|
|
96
|
+
return
|
|
97
|
+
bucket.timer.cancel()
|
|
98
|
+
latest = bucket.latest
|
|
99
|
+
notification = latest["notification"]
|
|
100
|
+
data = latest["data"]
|
|
101
|
+
if self._formatter is not None:
|
|
102
|
+
notification, data = self._formatter(bucket.events, bucket.count)
|
|
103
|
+
merged: DispatchRequest = {
|
|
104
|
+
**latest,
|
|
105
|
+
"notification": notification,
|
|
106
|
+
"data": data,
|
|
107
|
+
"options": {**latest["options"], "priority": "high" if bucket.priority == "high" else "normal"},
|
|
108
|
+
}
|
|
109
|
+
self._on_flush(CollapsedMessage(merged, bucket.count))
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""ES256 JSON Web Tokens for VAPID and APNs."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from cryptography.hazmat.primitives import hashes
|
|
9
|
+
from cryptography.hazmat.primitives.asymmetric import ec
|
|
10
|
+
from cryptography.hazmat.primitives.asymmetric.utils import decode_dss_signature
|
|
11
|
+
|
|
12
|
+
from ..jsonutil import dumps
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def b64url(data: bytes) -> str:
|
|
16
|
+
return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def b64url_decode(text: str) -> bytes:
|
|
20
|
+
return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def es256_jwt(header: dict[str, Any], claims: dict[str, Any], key: ec.EllipticCurvePrivateKey) -> str:
|
|
24
|
+
signing_input = f"{b64url(dumps(header).encode())}.{b64url(dumps(claims).encode())}"
|
|
25
|
+
der = key.sign(signing_input.encode("ascii"), ec.ECDSA(hashes.SHA256()))
|
|
26
|
+
r, s = decode_dss_signature(der)
|
|
27
|
+
return f"{signing_input}.{b64url(r.to_bytes(32, 'big') + s.to_bytes(32, 'big'))}"
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
"""Direct APNs over HTTP/2 with token (``.p8``) auth (PROTOCOL.md §7.3).
|
|
2
|
+
|
|
3
|
+
Needs the ``apns`` extra: ``pip install "tingping-core[apns]"``.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import hashlib
|
|
9
|
+
import re
|
|
10
|
+
from collections.abc import Callable
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from typing import TYPE_CHECKING, Any, Literal
|
|
13
|
+
from urllib.parse import quote
|
|
14
|
+
|
|
15
|
+
from cryptography.hazmat.primitives import serialization
|
|
16
|
+
from cryptography.hazmat.primitives.asymmetric import ec
|
|
17
|
+
|
|
18
|
+
from ..encryption import seal_payload
|
|
19
|
+
from ..frames import NotificationFrame, fit_payload
|
|
20
|
+
from ..jsonutil import dumps, loads
|
|
21
|
+
from ..models import DeviceRegistration
|
|
22
|
+
from ..protocol import PUSH_PAYLOAD_LIMIT_BYTES
|
|
23
|
+
from ..ulid import now_ms
|
|
24
|
+
from ._jwt import es256_jwt
|
|
25
|
+
from .base import DriverResult, PushContext, PushDriver
|
|
26
|
+
|
|
27
|
+
if TYPE_CHECKING:
|
|
28
|
+
import httpx
|
|
29
|
+
|
|
30
|
+
PRODUCTION_ORIGIN = "https://api.push.apple.com"
|
|
31
|
+
SANDBOX_ORIGIN = "https://api.sandbox.push.apple.com"
|
|
32
|
+
_JWT_REFRESH_MS = 50 * 60 * 1000
|
|
33
|
+
_GONE_REASONS = {"BadDeviceToken", "Unregistered", "DeviceTokenNotForTopic"}
|
|
34
|
+
_TOKEN_REASONS = {"ExpiredProviderToken", "InvalidProviderToken"}
|
|
35
|
+
_APNS_TOKEN = re.compile(r"^(?:[0-9a-fA-F]{2}){32,100}$")
|
|
36
|
+
#: Characters encodeURIComponent leaves alone, so both servers build the same path.
|
|
37
|
+
_URI_COMPONENT_SAFE = "-_.!~*'()"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True)
|
|
41
|
+
class ApnsConfig:
|
|
42
|
+
#: 10-character Apple Developer Team ID.
|
|
43
|
+
team_id: str
|
|
44
|
+
#: 10-character Key ID of the ``.p8`` key.
|
|
45
|
+
key_id: str
|
|
46
|
+
#: Contents of the ``.p8`` file (PEM).
|
|
47
|
+
private_key: str
|
|
48
|
+
#: The app's bundle identifier, sent as ``apns-topic``.
|
|
49
|
+
bundle_id: str
|
|
50
|
+
environment: Literal["production", "sandbox"] = "production"
|
|
51
|
+
#: Overrides the APNs origin (e.g. a local test server).
|
|
52
|
+
endpoint: str | None = None
|
|
53
|
+
#: ``alert``: visible (encrypted when the device has a key). ``silent``: always background wake-ups.
|
|
54
|
+
mode: Literal["alert", "silent"] = "alert"
|
|
55
|
+
#: Placeholder shown until the Notification Service Extension decrypts the payload.
|
|
56
|
+
encrypted_alert: dict[str, str] | None = None
|
|
57
|
+
request_timeout_ms: int = 10_000
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass(frozen=True)
|
|
61
|
+
class ApnsRequest:
|
|
62
|
+
path: str
|
|
63
|
+
headers: dict[str, str]
|
|
64
|
+
payload: dict[str, Any]
|
|
65
|
+
body: str
|
|
66
|
+
#: The driver result when APNs answers 200.
|
|
67
|
+
on_success: Literal["delivered", "wakeup"]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def is_apns_device_token(token: str) -> bool:
|
|
71
|
+
"""64–200 hex characters, even length. Other ``ios`` tokens are WebSocket-only."""
|
|
72
|
+
return _APNS_TOKEN.match(token) is not None
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def apns_collapse_id(collapse_key: str) -> str:
|
|
76
|
+
raw = collapse_key.encode("utf-8")
|
|
77
|
+
return collapse_key if len(raw) <= 64 else hashlib.sha256(raw).hexdigest()
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def build_apns_request(
|
|
81
|
+
device: DeviceRegistration,
|
|
82
|
+
frame: NotificationFrame,
|
|
83
|
+
context: PushContext,
|
|
84
|
+
*,
|
|
85
|
+
bundle_id: str,
|
|
86
|
+
mode: str = "alert",
|
|
87
|
+
encrypted_alert: dict[str, str] | None = None,
|
|
88
|
+
) -> ApnsRequest:
|
|
89
|
+
"""Builds the APNs request for a frame. Pure apart from the nonce of encrypted payloads."""
|
|
90
|
+
background = mode == "silent" or frame["notification"] is None
|
|
91
|
+
headers = {
|
|
92
|
+
"apns-topic": bundle_id,
|
|
93
|
+
"apns-push-type": "background" if background else "alert",
|
|
94
|
+
"apns-priority": "10" if not background and context.priority == "high" else "5",
|
|
95
|
+
"apns-expiration": "0" if context.ttl_seconds == 0 else str(frame["timestamp"] // 1000 + context.ttl_seconds),
|
|
96
|
+
}
|
|
97
|
+
if context.collapse_key is not None:
|
|
98
|
+
headers["apns-collapse-id"] = apns_collapse_id(context.collapse_key)
|
|
99
|
+
path = "/3/device/" + quote(device.token, safe=_URI_COMPONENT_SAFE)
|
|
100
|
+
|
|
101
|
+
if background:
|
|
102
|
+
wake: dict[str, Any] = {"aps": {"content-available": 1}, "tp_wake": {"message_id": frame["message_id"]}}
|
|
103
|
+
return ApnsRequest(path, headers, wake, dumps(wake), "wakeup")
|
|
104
|
+
|
|
105
|
+
built: dict[str, Any] = {}
|
|
106
|
+
key = device.encryption_key
|
|
107
|
+
|
|
108
|
+
def build(f: dict[str, Any]) -> str:
|
|
109
|
+
nonlocal built
|
|
110
|
+
if key is not None:
|
|
111
|
+
placeholder = encrypted_alert or {"title": "New notification"}
|
|
112
|
+
built = {
|
|
113
|
+
"aps": {
|
|
114
|
+
"alert": {"title": placeholder["title"], "body": placeholder.get("body", "")},
|
|
115
|
+
"mutable-content": 1,
|
|
116
|
+
},
|
|
117
|
+
"tp_enc": seal_payload(key, dumps(f)),
|
|
118
|
+
}
|
|
119
|
+
else:
|
|
120
|
+
notification = f.get("notification") or {}
|
|
121
|
+
aps: dict[str, Any] = {
|
|
122
|
+
"alert": {"title": notification.get("title", ""), "body": notification.get("body", "")},
|
|
123
|
+
"sound": "default",
|
|
124
|
+
}
|
|
125
|
+
if f.get("collapse_key") is not None:
|
|
126
|
+
aps["thread-id"] = f["collapse_key"]
|
|
127
|
+
built = {"aps": aps, "tp": f}
|
|
128
|
+
return dumps(built)
|
|
129
|
+
|
|
130
|
+
fitted = fit_payload(frame, build, PUSH_PAYLOAD_LIMIT_BYTES)
|
|
131
|
+
return ApnsRequest(path, headers, built, fitted.payload, "delivered" if fitted.level == 0 else "wakeup")
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def create_apns_jwt(team_id: str, key_id: str, private_key: str | ec.EllipticCurvePrivateKey, issued_at_s: int) -> str:
|
|
135
|
+
key = _load_key(private_key) if isinstance(private_key, str) else private_key
|
|
136
|
+
return es256_jwt({"alg": "ES256", "kid": key_id}, {"iss": team_id, "iat": issued_at_s}, key)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _load_key(pem: str) -> ec.EllipticCurvePrivateKey:
|
|
140
|
+
key = serialization.load_pem_private_key(pem.encode(), password=None)
|
|
141
|
+
if not isinstance(key, ec.EllipticCurvePrivateKey):
|
|
142
|
+
raise ValueError("the APNs key must be an EC (P-256) private key")
|
|
143
|
+
return key
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
class ApnsDriver(PushDriver):
|
|
147
|
+
name = "apns"
|
|
148
|
+
|
|
149
|
+
def __init__(
|
|
150
|
+
self,
|
|
151
|
+
config: ApnsConfig,
|
|
152
|
+
*,
|
|
153
|
+
now: Callable[[], int] = now_ms,
|
|
154
|
+
client: httpx.AsyncClient | None = None,
|
|
155
|
+
) -> None:
|
|
156
|
+
for field in ("team_id", "key_id", "private_key", "bundle_id"):
|
|
157
|
+
if not getattr(config, field):
|
|
158
|
+
raise ValueError(f"apns.{field} is required")
|
|
159
|
+
self.config = config
|
|
160
|
+
self._key = _load_key(config.private_key)
|
|
161
|
+
self._now = now
|
|
162
|
+
self._origin = config.endpoint or (SANDBOX_ORIGIN if config.environment == "sandbox" else PRODUCTION_ORIGIN)
|
|
163
|
+
self._client = client
|
|
164
|
+
self._owns_client = client is None
|
|
165
|
+
self._jwt: tuple[str, int] | None = None
|
|
166
|
+
|
|
167
|
+
def supports(self, device: DeviceRegistration) -> bool:
|
|
168
|
+
return device.platform == "ios" and is_apns_device_token(device.token)
|
|
169
|
+
|
|
170
|
+
async def send(self, device: DeviceRegistration, frame: NotificationFrame, context: PushContext) -> DriverResult:
|
|
171
|
+
request = build_apns_request(
|
|
172
|
+
device,
|
|
173
|
+
frame,
|
|
174
|
+
context,
|
|
175
|
+
bundle_id=self.config.bundle_id,
|
|
176
|
+
mode=self.config.mode,
|
|
177
|
+
encrypted_alert=self.config.encrypted_alert,
|
|
178
|
+
)
|
|
179
|
+
try:
|
|
180
|
+
status, body = await self._post(request)
|
|
181
|
+
except Exception as error: # noqa: BLE001 - reported as a failed delivery
|
|
182
|
+
return DriverResult.failed("APNs request failed", error)
|
|
183
|
+
if status == 200:
|
|
184
|
+
return DriverResult(request.on_success)
|
|
185
|
+
reason = _reason_of(body)
|
|
186
|
+
if status == 410 or reason in _GONE_REASONS:
|
|
187
|
+
return DriverResult.gone(reason or f"APNs responded {status}")
|
|
188
|
+
if reason in _TOKEN_REASONS:
|
|
189
|
+
self._jwt = None
|
|
190
|
+
return DriverResult.failed(f"APNs responded {status}" + (f" ({reason})" if reason else ""))
|
|
191
|
+
|
|
192
|
+
def provider_token(self) -> str:
|
|
193
|
+
now = self._now()
|
|
194
|
+
if self._jwt is None or now - self._jwt[1] > _JWT_REFRESH_MS:
|
|
195
|
+
self._jwt = (create_apns_jwt(self.config.team_id, self.config.key_id, self._key, now // 1000), now)
|
|
196
|
+
return self._jwt[0]
|
|
197
|
+
|
|
198
|
+
async def _post(self, request: ApnsRequest) -> tuple[int, str]:
|
|
199
|
+
import httpx
|
|
200
|
+
|
|
201
|
+
if self._client is None:
|
|
202
|
+
self._client = httpx.AsyncClient(http2=True, timeout=self.config.request_timeout_ms / 1000)
|
|
203
|
+
response = await self._client.post(
|
|
204
|
+
self._origin + request.path,
|
|
205
|
+
headers={
|
|
206
|
+
"authorization": f"bearer {self.provider_token()}",
|
|
207
|
+
"content-type": "application/json",
|
|
208
|
+
**request.headers,
|
|
209
|
+
},
|
|
210
|
+
content=request.body.encode("utf-8"),
|
|
211
|
+
)
|
|
212
|
+
return response.status_code, response.text
|
|
213
|
+
|
|
214
|
+
async def close(self) -> None:
|
|
215
|
+
client, self._client = self._client, None
|
|
216
|
+
if client is not None and self._owns_client:
|
|
217
|
+
await client.aclose()
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _reason_of(body: str) -> str:
|
|
221
|
+
try:
|
|
222
|
+
parsed = loads(body)
|
|
223
|
+
except ValueError:
|
|
224
|
+
return ""
|
|
225
|
+
reason = parsed.get("reason") if isinstance(parsed, dict) else None
|
|
226
|
+
return reason if isinstance(reason, str) else ""
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""The push driver interface (PROTOCOL.md §7.2, §7.3)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from abc import ABC, abstractmethod
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Literal
|
|
8
|
+
|
|
9
|
+
from ..frames import NotificationFrame
|
|
10
|
+
from ..models import DeviceRegistration
|
|
11
|
+
from ..protocol import Priority
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class PushContext:
|
|
16
|
+
ttl_seconds: int
|
|
17
|
+
priority: Priority
|
|
18
|
+
collapse_key: str | None
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True)
|
|
22
|
+
class DriverResult:
|
|
23
|
+
"""Outcome of a push attempt.
|
|
24
|
+
|
|
25
|
+
- ``delivered``: the OS can show the complete notification; the buffered frame is dropped.
|
|
26
|
+
- ``wakeup``: only a wake-up or truncated payload was sent; the frame stays buffered.
|
|
27
|
+
- ``gone``: the token is permanently invalid; the device is removed.
|
|
28
|
+
- ``failed``: transient or unknown failure; the frame stays buffered.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
status: Literal["delivered", "wakeup", "gone", "failed"]
|
|
32
|
+
reason: str | None = None
|
|
33
|
+
error: BaseException | None = None
|
|
34
|
+
|
|
35
|
+
@classmethod
|
|
36
|
+
def delivered(cls) -> DriverResult:
|
|
37
|
+
return cls("delivered")
|
|
38
|
+
|
|
39
|
+
@classmethod
|
|
40
|
+
def wakeup(cls) -> DriverResult:
|
|
41
|
+
return cls("wakeup")
|
|
42
|
+
|
|
43
|
+
@classmethod
|
|
44
|
+
def gone(cls, reason: str) -> DriverResult:
|
|
45
|
+
return cls("gone", reason)
|
|
46
|
+
|
|
47
|
+
@classmethod
|
|
48
|
+
def failed(cls, reason: str, error: BaseException | None = None) -> DriverResult:
|
|
49
|
+
return cls("failed", reason, error)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class PushDriver(ABC):
|
|
53
|
+
"""A push transport. Custom drivers (e.g. an Android relay) take precedence over built-ins."""
|
|
54
|
+
|
|
55
|
+
#: Short name used in events and logs, e.g. ``webpush``.
|
|
56
|
+
name: str = "custom"
|
|
57
|
+
|
|
58
|
+
@abstractmethod
|
|
59
|
+
def supports(self, device: DeviceRegistration) -> bool:
|
|
60
|
+
"""Whether this driver can reach the device."""
|
|
61
|
+
|
|
62
|
+
@abstractmethod
|
|
63
|
+
async def send(self, device: DeviceRegistration, frame: NotificationFrame, context: PushContext) -> DriverResult:
|
|
64
|
+
"""Sends one frame. Exceptions count as ``failed``."""
|
|
65
|
+
|
|
66
|
+
async def close(self) -> None: # noqa: B027 - optional hook
|
|
67
|
+
"""Releases connections. Called by ``TingPingEngine.close()``."""
|