meshcoredecoder 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.
- cli.py +249 -0
- index.py +66 -0
- meshcoredecoder/__init__.py +8 -0
- meshcoredecoder/crypto/__init__.py +6 -0
- meshcoredecoder/crypto/channel_crypto.py +113 -0
- meshcoredecoder/crypto/ed25519_verifier.py +136 -0
- meshcoredecoder/crypto/key_manager.py +71 -0
- meshcoredecoder/decoder/__init__.py +26 -0
- meshcoredecoder/decoder/packet_decoder.py +500 -0
- meshcoredecoder/decoder/payload_decoders/__init__.py +22 -0
- meshcoredecoder/decoder/payload_decoders/ack.py +91 -0
- meshcoredecoder/decoder/payload_decoders/advert.py +281 -0
- meshcoredecoder/decoder/payload_decoders/anon_request.py +137 -0
- meshcoredecoder/decoder/payload_decoders/group_text.py +130 -0
- meshcoredecoder/decoder/payload_decoders/path.py +89 -0
- meshcoredecoder/decoder/payload_decoders/request.py +143 -0
- meshcoredecoder/decoder/payload_decoders/response.py +133 -0
- meshcoredecoder/decoder/payload_decoders/text_message.py +70 -0
- meshcoredecoder/decoder/payload_decoders/trace.py +156 -0
- meshcoredecoder/types/__init__.py +15 -0
- meshcoredecoder/types/crypto.py +67 -0
- meshcoredecoder/types/enums.py +60 -0
- meshcoredecoder/types/packet.py +139 -0
- meshcoredecoder/types/payloads.py +244 -0
- meshcoredecoder/utils/__init__.py +18 -0
- meshcoredecoder/utils/auth_token.py +234 -0
- meshcoredecoder/utils/enum_names.py +58 -0
- meshcoredecoder/utils/hex.py +38 -0
- meshcoredecoder-0.1.0.dist-info/METADATA +332 -0
- meshcoredecoder-0.1.0.dist-info/RECORD +34 -0
- meshcoredecoder-0.1.0.dist-info/WHEEL +5 -0
- meshcoredecoder-0.1.0.dist-info/entry_points.txt +2 -0
- meshcoredecoder-0.1.0.dist-info/licenses/LICENSE +21 -0
- meshcoredecoder-0.1.0.dist-info/top_level.txt +3 -0
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Packet-related type definitions
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from typing import List, Optional, Dict, Any
|
|
6
|
+
from .enums import RouteType, PayloadType, PayloadVersion
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class DecodedPacket:
|
|
10
|
+
"""Main decoded packet structure"""
|
|
11
|
+
def __init__(
|
|
12
|
+
self,
|
|
13
|
+
message_hash: str,
|
|
14
|
+
route_type: RouteType,
|
|
15
|
+
payload_type: PayloadType,
|
|
16
|
+
payload_version: PayloadVersion,
|
|
17
|
+
path_length: int,
|
|
18
|
+
payload: Dict[str, Any],
|
|
19
|
+
total_bytes: int,
|
|
20
|
+
is_valid: bool,
|
|
21
|
+
transport_codes: Optional[List[int]] = None,
|
|
22
|
+
path: Optional[List[str]] = None,
|
|
23
|
+
errors: Optional[List[str]] = None
|
|
24
|
+
):
|
|
25
|
+
# Packet metadata
|
|
26
|
+
self.message_hash = message_hash
|
|
27
|
+
|
|
28
|
+
# Header information
|
|
29
|
+
self.route_type = route_type
|
|
30
|
+
self.payload_type = payload_type
|
|
31
|
+
self.payload_version = payload_version
|
|
32
|
+
|
|
33
|
+
# Transport and routing
|
|
34
|
+
self.transport_codes = transport_codes
|
|
35
|
+
self.path_length = path_length
|
|
36
|
+
self.path = path
|
|
37
|
+
|
|
38
|
+
# Payload data
|
|
39
|
+
self.payload = payload
|
|
40
|
+
|
|
41
|
+
# Metadata
|
|
42
|
+
self.total_bytes = total_bytes
|
|
43
|
+
self.is_valid = is_valid
|
|
44
|
+
self.errors = errors or []
|
|
45
|
+
|
|
46
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
47
|
+
"""Convert to dictionary for JSON serialization"""
|
|
48
|
+
result = {
|
|
49
|
+
'messageHash': self.message_hash,
|
|
50
|
+
'routeType': self.route_type.value,
|
|
51
|
+
'payloadType': self.payload_type.value,
|
|
52
|
+
'payloadVersion': self.payload_version.value,
|
|
53
|
+
'pathLength': self.path_length,
|
|
54
|
+
'path': self.path,
|
|
55
|
+
'payload': {
|
|
56
|
+
'raw': self.payload.get('raw', ''),
|
|
57
|
+
'decoded': self.payload.get('decoded')
|
|
58
|
+
},
|
|
59
|
+
'totalBytes': self.total_bytes,
|
|
60
|
+
'isValid': self.is_valid
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
if self.transport_codes:
|
|
64
|
+
result['transportCodes'] = list(self.transport_codes)
|
|
65
|
+
|
|
66
|
+
if self.errors:
|
|
67
|
+
result['errors'] = self.errors
|
|
68
|
+
|
|
69
|
+
# Recursively convert decoded payload if it exists
|
|
70
|
+
if self.payload.get('decoded') and hasattr(self.payload['decoded'], 'to_dict'):
|
|
71
|
+
result['payload']['decoded'] = self.payload['decoded'].to_dict()
|
|
72
|
+
|
|
73
|
+
return result
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class PacketSegment:
|
|
77
|
+
"""Segment of packet structure"""
|
|
78
|
+
def __init__(
|
|
79
|
+
self,
|
|
80
|
+
name: str,
|
|
81
|
+
description: str,
|
|
82
|
+
start_byte: int,
|
|
83
|
+
end_byte: int,
|
|
84
|
+
value: str,
|
|
85
|
+
header_breakdown: Optional[Dict[str, Any]] = None
|
|
86
|
+
):
|
|
87
|
+
self.name = name
|
|
88
|
+
self.description = description
|
|
89
|
+
self.start_byte = start_byte
|
|
90
|
+
self.end_byte = end_byte
|
|
91
|
+
self.value = value
|
|
92
|
+
self.header_breakdown = header_breakdown
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class PayloadSegment:
|
|
96
|
+
"""Segment of payload structure"""
|
|
97
|
+
def __init__(
|
|
98
|
+
self,
|
|
99
|
+
name: str,
|
|
100
|
+
description: str,
|
|
101
|
+
start_byte: int,
|
|
102
|
+
end_byte: int,
|
|
103
|
+
value: str,
|
|
104
|
+
decrypted_message: Optional[str] = None
|
|
105
|
+
):
|
|
106
|
+
self.name = name
|
|
107
|
+
self.description = description
|
|
108
|
+
self.start_byte = start_byte
|
|
109
|
+
self.end_byte = end_byte
|
|
110
|
+
self.value = value
|
|
111
|
+
self.decrypted_message = decrypted_message
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class HeaderBreakdown:
|
|
115
|
+
"""Detailed header breakdown with bit-level fields"""
|
|
116
|
+
def __init__(
|
|
117
|
+
self,
|
|
118
|
+
full_binary: str,
|
|
119
|
+
fields: List[Dict[str, str]]
|
|
120
|
+
):
|
|
121
|
+
self.full_binary = full_binary
|
|
122
|
+
self.fields = fields
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class PacketStructure:
|
|
126
|
+
"""Interface for detailed structure analysis"""
|
|
127
|
+
def __init__(
|
|
128
|
+
self,
|
|
129
|
+
segments: List[PacketSegment],
|
|
130
|
+
total_bytes: int,
|
|
131
|
+
raw_hex: str,
|
|
132
|
+
message_hash: str,
|
|
133
|
+
payload: Dict[str, Any]
|
|
134
|
+
):
|
|
135
|
+
self.segments = segments
|
|
136
|
+
self.total_bytes = total_bytes
|
|
137
|
+
self.raw_hex = raw_hex
|
|
138
|
+
self.message_hash = message_hash
|
|
139
|
+
self.payload = payload
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Payload type definitions
|
|
3
|
+
Reference: https://github.com/meshcore-dev/MeshCore/blob/main/docs/payloads.md
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from typing import Dict, Optional, List, Any
|
|
7
|
+
from .enums import PayloadType, PayloadVersion, DeviceRole, RequestType
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class BasePayload:
|
|
11
|
+
"""Base payload interface"""
|
|
12
|
+
def __init__(
|
|
13
|
+
self,
|
|
14
|
+
payload_type: PayloadType,
|
|
15
|
+
version: PayloadVersion,
|
|
16
|
+
is_valid: bool,
|
|
17
|
+
errors: Optional[List[str]] = None
|
|
18
|
+
):
|
|
19
|
+
self.type = payload_type
|
|
20
|
+
self.version = version
|
|
21
|
+
self.is_valid = is_valid
|
|
22
|
+
self.errors = errors or []
|
|
23
|
+
|
|
24
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
25
|
+
"""Convert to dictionary for JSON serialization"""
|
|
26
|
+
result = {
|
|
27
|
+
'type': self.type.value,
|
|
28
|
+
'version': self.version.value,
|
|
29
|
+
'isValid': self.is_valid
|
|
30
|
+
}
|
|
31
|
+
if self.errors:
|
|
32
|
+
result['errors'] = self.errors
|
|
33
|
+
return result
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class AdvertPayload(BasePayload):
|
|
37
|
+
"""Advertisement payload"""
|
|
38
|
+
def __init__(
|
|
39
|
+
self,
|
|
40
|
+
public_key: str,
|
|
41
|
+
timestamp: int,
|
|
42
|
+
signature: str,
|
|
43
|
+
app_data: Dict[str, Any],
|
|
44
|
+
signature_valid: Optional[bool] = None,
|
|
45
|
+
signature_error: Optional[str] = None,
|
|
46
|
+
**kwargs
|
|
47
|
+
):
|
|
48
|
+
super().__init__(**kwargs)
|
|
49
|
+
self.public_key = public_key
|
|
50
|
+
self.timestamp = timestamp
|
|
51
|
+
self.signature = signature
|
|
52
|
+
self.signature_valid = signature_valid
|
|
53
|
+
self.signature_error = signature_error
|
|
54
|
+
self.app_data = app_data
|
|
55
|
+
|
|
56
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
57
|
+
"""Convert to dictionary for JSON serialization"""
|
|
58
|
+
result = super().to_dict()
|
|
59
|
+
result.update({
|
|
60
|
+
'publicKey': self.public_key,
|
|
61
|
+
'timestamp': self.timestamp,
|
|
62
|
+
'signature': self.signature,
|
|
63
|
+
'appData': {
|
|
64
|
+
'flags': self.app_data.get('flags'),
|
|
65
|
+
'deviceRole': self.app_data.get('device_role').value if isinstance(self.app_data.get('device_role'), DeviceRole) else self.app_data.get('device_role'),
|
|
66
|
+
'hasLocation': self.app_data.get('has_location', False),
|
|
67
|
+
'hasName': self.app_data.get('has_name', False)
|
|
68
|
+
}
|
|
69
|
+
})
|
|
70
|
+
if self.signature_valid is not None:
|
|
71
|
+
result['signatureValid'] = self.signature_valid
|
|
72
|
+
if self.signature_error:
|
|
73
|
+
result['signatureError'] = self.signature_error
|
|
74
|
+
|
|
75
|
+
# Add location if present
|
|
76
|
+
if self.app_data.get('location'):
|
|
77
|
+
result['appData']['location'] = self.app_data['location']
|
|
78
|
+
|
|
79
|
+
# Add name if present
|
|
80
|
+
if self.app_data.get('name'):
|
|
81
|
+
result['appData']['name'] = self.app_data['name']
|
|
82
|
+
|
|
83
|
+
return result
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class TracePayload(BasePayload):
|
|
87
|
+
"""Trace payload"""
|
|
88
|
+
def __init__(
|
|
89
|
+
self,
|
|
90
|
+
trace_tag: str,
|
|
91
|
+
auth_code: int,
|
|
92
|
+
flags: int,
|
|
93
|
+
path_hashes: List[str],
|
|
94
|
+
snr_values: Optional[List[float]] = None,
|
|
95
|
+
**kwargs
|
|
96
|
+
):
|
|
97
|
+
super().__init__(**kwargs)
|
|
98
|
+
self.trace_tag = trace_tag
|
|
99
|
+
self.auth_code = auth_code
|
|
100
|
+
self.flags = flags
|
|
101
|
+
self.path_hashes = path_hashes
|
|
102
|
+
self.snr_values = snr_values or []
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class GroupTextPayload(BasePayload):
|
|
106
|
+
"""Group text message payload"""
|
|
107
|
+
def __init__(
|
|
108
|
+
self,
|
|
109
|
+
channel_hash: str,
|
|
110
|
+
cipher_mac: str,
|
|
111
|
+
ciphertext: str,
|
|
112
|
+
ciphertext_length: int,
|
|
113
|
+
decrypted: Optional[Dict[str, Any]] = None,
|
|
114
|
+
**kwargs
|
|
115
|
+
):
|
|
116
|
+
super().__init__(**kwargs)
|
|
117
|
+
self.channel_hash = channel_hash
|
|
118
|
+
self.cipher_mac = cipher_mac
|
|
119
|
+
self.ciphertext = ciphertext
|
|
120
|
+
self.ciphertext_length = ciphertext_length
|
|
121
|
+
self.decrypted = decrypted
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class RequestPayload(BasePayload):
|
|
125
|
+
"""Request payload"""
|
|
126
|
+
def __init__(
|
|
127
|
+
self,
|
|
128
|
+
destination_hash: str,
|
|
129
|
+
source_hash: str,
|
|
130
|
+
cipher_mac: str,
|
|
131
|
+
ciphertext: str,
|
|
132
|
+
timestamp: int,
|
|
133
|
+
request_type: RequestType,
|
|
134
|
+
request_data: Optional[str] = None,
|
|
135
|
+
decrypted: Optional[Dict[str, Any]] = None,
|
|
136
|
+
**kwargs
|
|
137
|
+
):
|
|
138
|
+
super().__init__(**kwargs)
|
|
139
|
+
self.destination_hash = destination_hash
|
|
140
|
+
self.source_hash = source_hash
|
|
141
|
+
self.cipher_mac = cipher_mac
|
|
142
|
+
self.ciphertext = ciphertext
|
|
143
|
+
self.timestamp = timestamp
|
|
144
|
+
self.request_type = request_type
|
|
145
|
+
self.request_data = request_data
|
|
146
|
+
self.decrypted = decrypted
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
class TextMessagePayload(BasePayload):
|
|
150
|
+
"""Text message payload"""
|
|
151
|
+
def __init__(
|
|
152
|
+
self,
|
|
153
|
+
destination_hash: str,
|
|
154
|
+
source_hash: str,
|
|
155
|
+
cipher_mac: str,
|
|
156
|
+
ciphertext: str,
|
|
157
|
+
ciphertext_length: int,
|
|
158
|
+
decrypted: Optional[Dict[str, Any]] = None,
|
|
159
|
+
**kwargs
|
|
160
|
+
):
|
|
161
|
+
super().__init__(**kwargs)
|
|
162
|
+
self.destination_hash = destination_hash
|
|
163
|
+
self.source_hash = source_hash
|
|
164
|
+
self.cipher_mac = cipher_mac
|
|
165
|
+
self.ciphertext = ciphertext
|
|
166
|
+
self.ciphertext_length = ciphertext_length
|
|
167
|
+
self.decrypted = decrypted
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
class AnonRequestPayload(BasePayload):
|
|
171
|
+
"""Anonymous request payload"""
|
|
172
|
+
def __init__(
|
|
173
|
+
self,
|
|
174
|
+
destination_hash: str,
|
|
175
|
+
sender_public_key: str,
|
|
176
|
+
cipher_mac: str,
|
|
177
|
+
ciphertext: str,
|
|
178
|
+
ciphertext_length: int,
|
|
179
|
+
decrypted: Optional[Dict[str, Any]] = None,
|
|
180
|
+
**kwargs
|
|
181
|
+
):
|
|
182
|
+
super().__init__(**kwargs)
|
|
183
|
+
self.destination_hash = destination_hash
|
|
184
|
+
self.sender_public_key = sender_public_key
|
|
185
|
+
self.cipher_mac = cipher_mac
|
|
186
|
+
self.ciphertext = ciphertext
|
|
187
|
+
self.ciphertext_length = ciphertext_length
|
|
188
|
+
self.decrypted = decrypted
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
class AckPayload(BasePayload):
|
|
192
|
+
"""Acknowledgment payload"""
|
|
193
|
+
def __init__(
|
|
194
|
+
self,
|
|
195
|
+
checksum: str,
|
|
196
|
+
**kwargs
|
|
197
|
+
):
|
|
198
|
+
super().__init__(**kwargs)
|
|
199
|
+
self.checksum = checksum
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
class PathPayload(BasePayload):
|
|
203
|
+
"""Path payload"""
|
|
204
|
+
def __init__(
|
|
205
|
+
self,
|
|
206
|
+
path_length: int,
|
|
207
|
+
path_hashes: List[str],
|
|
208
|
+
extra_type: int,
|
|
209
|
+
extra_data: str,
|
|
210
|
+
**kwargs
|
|
211
|
+
):
|
|
212
|
+
super().__init__(**kwargs)
|
|
213
|
+
self.path_length = path_length
|
|
214
|
+
self.path_hashes = path_hashes
|
|
215
|
+
self.extra_type = extra_type
|
|
216
|
+
self.extra_data = extra_data
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
class ResponsePayload(BasePayload):
|
|
220
|
+
"""Response payload"""
|
|
221
|
+
def __init__(
|
|
222
|
+
self,
|
|
223
|
+
destination_hash: str,
|
|
224
|
+
source_hash: str,
|
|
225
|
+
cipher_mac: str,
|
|
226
|
+
ciphertext: str,
|
|
227
|
+
ciphertext_length: int,
|
|
228
|
+
decrypted: Optional[Dict[str, Any]] = None,
|
|
229
|
+
**kwargs
|
|
230
|
+
):
|
|
231
|
+
super().__init__(**kwargs)
|
|
232
|
+
self.destination_hash = destination_hash
|
|
233
|
+
self.source_hash = source_hash
|
|
234
|
+
self.cipher_mac = cipher_mac
|
|
235
|
+
self.ciphertext = ciphertext
|
|
236
|
+
self.ciphertext_length = ciphertext_length
|
|
237
|
+
self.decrypted = decrypted
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
# Union type for all payload types
|
|
241
|
+
PayloadData = (
|
|
242
|
+
AdvertPayload | TracePayload | GroupTextPayload | RequestPayload |
|
|
243
|
+
TextMessagePayload | AnonRequestPayload | AckPayload | PathPayload | ResponsePayload
|
|
244
|
+
)
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""Utility modules"""
|
|
2
|
+
from .hex import byte_to_hex, bytes_to_hex, number_to_hex, hex_to_bytes
|
|
3
|
+
from .enum_names import (
|
|
4
|
+
get_route_type_name, get_payload_type_name, get_payload_version_name,
|
|
5
|
+
get_device_role_name, get_request_type_name
|
|
6
|
+
)
|
|
7
|
+
from .auth_token import (
|
|
8
|
+
create_auth_token, verify_auth_token, parse_auth_token, decode_auth_token_payload,
|
|
9
|
+
AuthTokenPayload, AuthToken
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
'byte_to_hex', 'bytes_to_hex', 'number_to_hex', 'hex_to_bytes',
|
|
14
|
+
'get_route_type_name', 'get_payload_type_name', 'get_payload_version_name',
|
|
15
|
+
'get_device_role_name', 'get_request_type_name',
|
|
16
|
+
'create_auth_token', 'verify_auth_token', 'parse_auth_token', 'decode_auth_token_payload',
|
|
17
|
+
'AuthTokenPayload', 'AuthToken',
|
|
18
|
+
]
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Copyright (c) 2025 Michael Hart: https://github.com/michaelhart/meshcore-decoder
|
|
3
|
+
MIT License
|
|
4
|
+
|
|
5
|
+
Authentication token utilities (JWT-style)
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import base64
|
|
9
|
+
import json
|
|
10
|
+
from typing import Dict, Optional, Any
|
|
11
|
+
from datetime import datetime
|
|
12
|
+
from .hex import bytes_to_hex, hex_to_bytes
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class AuthTokenPayload:
|
|
16
|
+
"""JWT-style token payload for MeshCore authentication"""
|
|
17
|
+
def __init__(
|
|
18
|
+
self,
|
|
19
|
+
public_key: str,
|
|
20
|
+
iat: int,
|
|
21
|
+
exp: Optional[int] = None,
|
|
22
|
+
aud: Optional[str] = None,
|
|
23
|
+
**kwargs
|
|
24
|
+
):
|
|
25
|
+
self.public_key = public_key
|
|
26
|
+
self.iat = iat
|
|
27
|
+
self.exp = exp
|
|
28
|
+
self.aud = aud
|
|
29
|
+
# Add any custom claims
|
|
30
|
+
for key, value in kwargs.items():
|
|
31
|
+
setattr(self, key, value)
|
|
32
|
+
|
|
33
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
34
|
+
"""Convert to dictionary"""
|
|
35
|
+
result = {
|
|
36
|
+
'publicKey': self.public_key,
|
|
37
|
+
'iat': self.iat
|
|
38
|
+
}
|
|
39
|
+
if self.exp is not None:
|
|
40
|
+
result['exp'] = self.exp
|
|
41
|
+
if self.aud:
|
|
42
|
+
result['aud'] = self.aud
|
|
43
|
+
# Add custom claims
|
|
44
|
+
for key in dir(self):
|
|
45
|
+
if not key.startswith('_') and key not in ['public_key', 'iat', 'exp', 'aud', 'to_dict']:
|
|
46
|
+
value = getattr(self, key)
|
|
47
|
+
if not callable(value):
|
|
48
|
+
result[key] = value
|
|
49
|
+
return result
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class AuthToken:
|
|
53
|
+
"""Encoded auth token structure"""
|
|
54
|
+
def __init__(self, header: str, payload: str, signature: str):
|
|
55
|
+
self.header = header
|
|
56
|
+
self.payload = payload
|
|
57
|
+
self.signature = signature
|
|
58
|
+
|
|
59
|
+
def __str__(self) -> str:
|
|
60
|
+
return f"{self.header}.{self.payload}.{self.signature}"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def base64url_encode(data: bytes) -> str:
|
|
64
|
+
"""Base64url encode (URL-safe base64 without padding)"""
|
|
65
|
+
base64_str = base64.b64encode(data).decode('utf-8')
|
|
66
|
+
return base64_str.replace('+', '-').replace('/', '_').rstrip('=')
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def base64url_decode(str_data: str) -> bytes:
|
|
70
|
+
"""Base64url decode"""
|
|
71
|
+
# Add padding back
|
|
72
|
+
base64_str = str_data.replace('-', '+').replace('_', '/')
|
|
73
|
+
while len(base64_str) % 4:
|
|
74
|
+
base64_str += '='
|
|
75
|
+
return base64.b64decode(base64_str)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
async def create_auth_token(
|
|
79
|
+
payload_dict: Dict[str, Any],
|
|
80
|
+
private_key_hex: str,
|
|
81
|
+
public_key_hex: str
|
|
82
|
+
) -> str:
|
|
83
|
+
"""
|
|
84
|
+
Create a signed authentication token
|
|
85
|
+
|
|
86
|
+
Args:
|
|
87
|
+
payload_dict: Token payload containing claims
|
|
88
|
+
private_key_hex: 64-byte private key in hex format
|
|
89
|
+
public_key_hex: 32-byte public key in hex format
|
|
90
|
+
|
|
91
|
+
Returns:
|
|
92
|
+
JWT-style token string in format: header.payload.signature
|
|
93
|
+
"""
|
|
94
|
+
# Create header
|
|
95
|
+
header = {
|
|
96
|
+
'alg': 'Ed25519',
|
|
97
|
+
'typ': 'JWT'
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
# Ensure publicKey is in the payload (normalize to uppercase)
|
|
101
|
+
if 'publicKey' not in payload_dict:
|
|
102
|
+
payload_dict['publicKey'] = public_key_hex.upper()
|
|
103
|
+
else:
|
|
104
|
+
payload_dict['publicKey'] = payload_dict['publicKey'].upper()
|
|
105
|
+
|
|
106
|
+
# Ensure iat is set
|
|
107
|
+
if 'iat' not in payload_dict:
|
|
108
|
+
payload_dict['iat'] = int(datetime.now().timestamp())
|
|
109
|
+
|
|
110
|
+
# Encode header and payload
|
|
111
|
+
header_json = json.dumps(header, separators=(',', ':'))
|
|
112
|
+
payload_json = json.dumps(payload_dict, separators=(',', ':'))
|
|
113
|
+
|
|
114
|
+
header_bytes = header_json.encode('utf-8')
|
|
115
|
+
payload_bytes = payload_json.encode('utf-8')
|
|
116
|
+
|
|
117
|
+
header_encoded = base64url_encode(header_bytes)
|
|
118
|
+
payload_encoded = base64url_encode(payload_bytes)
|
|
119
|
+
|
|
120
|
+
# Create signing input: header.payload
|
|
121
|
+
signing_input = f"{header_encoded}.{payload_encoded}"
|
|
122
|
+
signing_input_bytes = signing_input.encode('utf-8')
|
|
123
|
+
signing_input_hex = bytes_to_hex(signing_input_bytes)
|
|
124
|
+
|
|
125
|
+
# Note: Signing with Ed25519 would go here
|
|
126
|
+
# For now, we'll return a placeholder signature
|
|
127
|
+
# signature_hex = await sign(signing_input_hex, private_key_hex, payload_dict['publicKey'])
|
|
128
|
+
signature_hex = "PLACEHOLDER_SIGNATURE_" + signing_input_hex[:16]
|
|
129
|
+
|
|
130
|
+
# Return token in JWT format: header.payload.signature
|
|
131
|
+
return f"{header_encoded}.{payload_encoded}.{signature_hex}"
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
async def verify_auth_token(
|
|
135
|
+
token: str,
|
|
136
|
+
expected_public_key_hex: Optional[str] = None
|
|
137
|
+
) -> Optional[AuthTokenPayload]:
|
|
138
|
+
"""
|
|
139
|
+
Verify and decode an authentication token
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
token: JWT-style token string
|
|
143
|
+
expected_public_key_hex: Expected public key in hex format (optional)
|
|
144
|
+
|
|
145
|
+
Returns:
|
|
146
|
+
Decoded payload if valid, None if invalid
|
|
147
|
+
"""
|
|
148
|
+
try:
|
|
149
|
+
# Parse token
|
|
150
|
+
parts = token.split('.')
|
|
151
|
+
if len(parts) != 3:
|
|
152
|
+
return None
|
|
153
|
+
|
|
154
|
+
header_encoded, payload_encoded, signature_hex = parts
|
|
155
|
+
|
|
156
|
+
# Decode header and payload
|
|
157
|
+
header_bytes = base64url_decode(header_encoded)
|
|
158
|
+
payload_bytes = base64url_decode(payload_encoded)
|
|
159
|
+
|
|
160
|
+
header_json = header_bytes.decode('utf-8')
|
|
161
|
+
payload_json = payload_bytes.decode('utf-8')
|
|
162
|
+
|
|
163
|
+
header = json.loads(header_json)
|
|
164
|
+
payload = json.loads(payload_json)
|
|
165
|
+
|
|
166
|
+
# Validate header
|
|
167
|
+
if header.get('alg') != 'Ed25519' or header.get('typ') != 'JWT':
|
|
168
|
+
return None
|
|
169
|
+
|
|
170
|
+
# Validate payload has required fields
|
|
171
|
+
if not payload.get('publicKey') or not payload.get('iat'):
|
|
172
|
+
return None
|
|
173
|
+
|
|
174
|
+
# Check if expected public key matches
|
|
175
|
+
if expected_public_key_hex and payload['publicKey'].upper() != expected_public_key_hex.upper():
|
|
176
|
+
return None
|
|
177
|
+
|
|
178
|
+
# Check expiration if present
|
|
179
|
+
if payload.get('exp'):
|
|
180
|
+
now = int(datetime.now().timestamp())
|
|
181
|
+
if now > payload['exp']:
|
|
182
|
+
return None # Token expired
|
|
183
|
+
|
|
184
|
+
# Note: Verify signature would go here
|
|
185
|
+
# For now, we'll just return the payload without verification
|
|
186
|
+
# verify_result = await verify(signature_hex, signing_input, payload['publicKey'])
|
|
187
|
+
# if not verify_result:
|
|
188
|
+
# return None
|
|
189
|
+
|
|
190
|
+
return AuthTokenPayload(**payload)
|
|
191
|
+
except Exception as error:
|
|
192
|
+
return None
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def parse_auth_token(token: str) -> Optional[AuthToken]:
|
|
196
|
+
"""
|
|
197
|
+
Parse a token without verifying (useful for debugging)
|
|
198
|
+
|
|
199
|
+
Args:
|
|
200
|
+
token: JWT-style token string
|
|
201
|
+
|
|
202
|
+
Returns:
|
|
203
|
+
Parsed token structure or None if invalid format
|
|
204
|
+
"""
|
|
205
|
+
try:
|
|
206
|
+
parts = token.split('.')
|
|
207
|
+
if len(parts) != 3:
|
|
208
|
+
return None
|
|
209
|
+
|
|
210
|
+
return AuthToken(header=parts[0], payload=parts[1], signature=parts[2])
|
|
211
|
+
except Exception:
|
|
212
|
+
return None
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def decode_auth_token_payload(token: str) -> Optional[Dict[str, Any]]:
|
|
216
|
+
"""
|
|
217
|
+
Decode token payload without verification (useful for debugging)
|
|
218
|
+
|
|
219
|
+
Args:
|
|
220
|
+
token: JWT-style token string
|
|
221
|
+
|
|
222
|
+
Returns:
|
|
223
|
+
Decoded payload or None if invalid format
|
|
224
|
+
"""
|
|
225
|
+
try:
|
|
226
|
+
parts = token.split('.')
|
|
227
|
+
if len(parts) != 3:
|
|
228
|
+
return None
|
|
229
|
+
|
|
230
|
+
payload_bytes = base64url_decode(parts[1])
|
|
231
|
+
payload_json = payload_bytes.decode('utf-8')
|
|
232
|
+
return json.loads(payload_json)
|
|
233
|
+
except Exception:
|
|
234
|
+
return None
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Copyright (c) 2025 Michael Hart: https://github.com/michaelhart/meshcore-decoder
|
|
3
|
+
MIT License
|
|
4
|
+
|
|
5
|
+
Utility functions to get human-readable names for enum values
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from ..types.enums import RouteType, PayloadType, PayloadVersion, DeviceRole, RequestType
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def get_route_type_name(route_type: RouteType) -> str:
|
|
12
|
+
"""Get human-readable name for RouteType enum value"""
|
|
13
|
+
try:
|
|
14
|
+
return route_type.name
|
|
15
|
+
except ValueError:
|
|
16
|
+
return f"Unknown ({route_type})"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def get_payload_type_name(payload_type: PayloadType) -> str:
|
|
20
|
+
"""Get human-readable name for PayloadType enum value"""
|
|
21
|
+
try:
|
|
22
|
+
return payload_type.name
|
|
23
|
+
except ValueError:
|
|
24
|
+
return f"Unknown ({payload_type})"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def get_payload_version_name(version: PayloadVersion) -> str:
|
|
28
|
+
"""Get human-readable name for PayloadVersion enum value"""
|
|
29
|
+
mapping = {
|
|
30
|
+
PayloadVersion.Version1: 'Version 1',
|
|
31
|
+
PayloadVersion.Version2: 'Version 2',
|
|
32
|
+
PayloadVersion.Version3: 'Version 3',
|
|
33
|
+
PayloadVersion.Version4: 'Version 4',
|
|
34
|
+
}
|
|
35
|
+
return mapping.get(version, f"Unknown ({version})")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def get_device_role_name(role: DeviceRole) -> str:
|
|
39
|
+
"""Get human-readable name for DeviceRole enum value"""
|
|
40
|
+
mapping = {
|
|
41
|
+
DeviceRole.ChatNode: 'Chat Node',
|
|
42
|
+
DeviceRole.Repeater: 'Repeater',
|
|
43
|
+
DeviceRole.RoomServer: 'Room Server',
|
|
44
|
+
DeviceRole.Sensor: 'Sensor',
|
|
45
|
+
}
|
|
46
|
+
return mapping.get(role, f"Unknown ({role})")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def get_request_type_name(request_type: RequestType) -> str:
|
|
50
|
+
"""Get human-readable name for RequestType enum value"""
|
|
51
|
+
mapping = {
|
|
52
|
+
RequestType.GetStats: 'Get Stats',
|
|
53
|
+
RequestType.Keepalive: 'Keepalive (deprecated)',
|
|
54
|
+
RequestType.GetTelemetryData: 'Get Telemetry Data',
|
|
55
|
+
RequestType.GetMinMaxAvgData: 'Get Min/Max/Avg Data',
|
|
56
|
+
RequestType.GetAccessList: 'Get Access List',
|
|
57
|
+
}
|
|
58
|
+
return mapping.get(request_type, f"Unknown ({request_type})")
|