datap 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.
btsh/codec.py ADDED
@@ -0,0 +1,120 @@
1
+ """Codec helpers: apply the speaker's codec, and read the negotiated one.
2
+
3
+ ``apply_codec`` is what makes the claim "it speaks the device codec" testable:
4
+ a PCM burst goes through the same lossy transform a Bluetooth speaker applies
5
+ (SBC via ffmpeg), and the modem must still recover the frame byte for byte.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ import shutil
13
+ import subprocess
14
+ import tempfile
15
+
16
+ FFMPEG = os.environ.get("BTSH_FFMPEG", "ffmpeg")
17
+
18
+
19
+ class CodecError(Exception):
20
+ """Raised when a codec transform cannot be applied."""
21
+
22
+
23
+ def ffmpeg_available() -> bool:
24
+ return shutil.which(FFMPEG) is not None
25
+
26
+
27
+ _CODEC_ARGS = {
28
+ "sbc": ["-c:a", "sbc"],
29
+ "none": None,
30
+ }
31
+
32
+
33
+ def apply_codec(pcm: bytes, codec: str = "sbc", bitrate: int = 200_000, sample_rate: int = 48000) -> bytes:
34
+ """Push PCM through ``codec`` and return PCM of the same length."""
35
+ if codec in ("", "none", None):
36
+ return pcm
37
+ if codec not in _CODEC_ARGS:
38
+ raise CodecError(f"unsupported codec: {codec}")
39
+ if not ffmpeg_available():
40
+ raise CodecError("ffmpeg not found (set BTSH_FFMPEG)")
41
+ with tempfile.TemporaryDirectory(prefix="btsh-codec-") as workdir:
42
+ source = os.path.join(workdir, "in.raw")
43
+ encoded = os.path.join(workdir, "out.sbc")
44
+ decoded = os.path.join(workdir, "out.raw")
45
+ with open(source, "wb") as handle:
46
+ handle.write(pcm)
47
+ enc = subprocess.run(
48
+ [
49
+ FFMPEG, "-hide_banner", "-loglevel", "error", "-y",
50
+ "-f", "s16le", "-ar", str(sample_rate), "-ac", "1", "-i", source,
51
+ *_CODEC_ARGS[codec], "-b:a", str(bitrate), encoded,
52
+ ],
53
+ capture_output=True,
54
+ )
55
+ if enc.returncode != 0:
56
+ raise CodecError(f"encode failed: {enc.stderr.decode(errors='replace').strip()}")
57
+ dec = subprocess.run(
58
+ [
59
+ FFMPEG, "-hide_banner", "-loglevel", "error", "-y", "-i", encoded,
60
+ "-f", "s16le", "-ar", str(sample_rate), "-ac", "1", decoded,
61
+ ],
62
+ capture_output=True,
63
+ )
64
+ if dec.returncode != 0:
65
+ raise CodecError(f"decode failed: {dec.stderr.decode(errors='replace').strip()}")
66
+ with open(decoded, "rb") as handle:
67
+ out = handle.read()
68
+ if len(out) < len(pcm):
69
+ out = out + b"\x00" * (len(pcm) - len(out))
70
+ return out[: len(pcm)]
71
+
72
+
73
+ def bluez_nodes() -> list[dict]:
74
+ """List PipeWire nodes backed by BlueZ, with their negotiated codec."""
75
+ try:
76
+ proc = subprocess.run(["pw-dump"], capture_output=True, timeout=10)
77
+ except (FileNotFoundError, subprocess.TimeoutExpired) as exc:
78
+ raise CodecError(f"pw-dump unavailable: {exc}") from exc
79
+ if proc.returncode != 0:
80
+ raise CodecError("pw-dump failed (no PipeWire session?)")
81
+ try:
82
+ objects = json.loads(proc.stdout)
83
+ except json.JSONDecodeError as exc:
84
+ raise CodecError("could not parse pw-dump output") from exc
85
+ nodes: list[dict] = []
86
+ for obj in objects:
87
+ props = (obj.get("info") or {}).get("props") or {}
88
+ name = str(props.get("node.name", ""))
89
+ codec = props.get("api.bluez5.codec")
90
+ if not codec and not name.startswith("bluez_"):
91
+ continue
92
+ nodes.append(
93
+ {
94
+ "id": obj.get("id"),
95
+ "node": name,
96
+ "description": props.get("node.description", ""),
97
+ "codec": codec or "",
98
+ "profile": props.get("api.bluez5.profile", ""),
99
+ "transport": props.get("api.bluez5.transport", ""),
100
+ "media_class": props.get("media.class", ""),
101
+ "device": props.get("device.name", ""),
102
+ }
103
+ )
104
+ nodes.sort(key=lambda item: (item["device"], item["node"]))
105
+ return nodes
106
+
107
+
108
+ def pick_node(nodes: list[dict], direction: str, device: str | None = None) -> dict | None:
109
+ """Return the first node whose media class matches ``direction``.
110
+
111
+ ``direction`` is ``"out"`` (what we play into) or ``"in"`` (what we record).
112
+ """
113
+ wanted = "Audio/Sink" if direction == "out" else "Audio/Source"
114
+ for node in nodes:
115
+ if node["media_class"] != wanted:
116
+ continue
117
+ if device and device.lower() not in (node["device"] + " " + node["node"]).lower():
118
+ continue
119
+ return node
120
+ return None
btsh/crypto.py ADDED
@@ -0,0 +1,233 @@
1
+ """Encryption primitives, standard library only, so every target OS runs them.
2
+
3
+ - X25519 (RFC 7748) for key agreement
4
+ - ChaCha20-Poly1305 (RFC 8439) for authenticated encryption
5
+ - HKDF-SHA256 (RFC 5869) to turn a shared secret into a key
6
+ - ``seal``/``open_sealed``: an anonymous sealed box (ephemeral key + nonce)
7
+
8
+ Everything is checked against the RFC test vectors in ``tests/test_crypto.py``.
9
+ It is textbook code, not audited code: good enough to keep a Bluetooth link
10
+ confidential, not a replacement for libsodium if the threat model is serious.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import base64
16
+ import hashlib
17
+ import hmac
18
+ import os
19
+
20
+ P = 2**255 - 19
21
+ A24 = 121665
22
+ BASE_POINT = b"\x09" + b"\x00" * 31
23
+ SEAL_INFO = b"btsh-sealed-v1"
24
+ TAG_LEN = 16
25
+
26
+
27
+ class CryptoError(Exception):
28
+ """Raised when a sealed box cannot be opened or fails authentication."""
29
+
30
+
31
+ # -- X25519 -------------------------------------------------------------
32
+ def x25519(scalar: bytes, point: bytes) -> bytes:
33
+ if len(scalar) != 32 or len(point) != 32:
34
+ raise ValueError("x25519 wants 32 byte arguments")
35
+ k = bytearray(scalar)
36
+ k[0] &= 248
37
+ k[31] &= 127
38
+ k[31] |= 64
39
+ scalar_int = int.from_bytes(k, "little")
40
+ # RFC 7748: the most significant bit of the received u coordinate is masked
41
+ x1 = (int.from_bytes(point, "little") & ((1 << 255) - 1)) % P
42
+ x2, z2, x3, z3 = 1, 0, x1, 1
43
+ swap = 0
44
+ for bit_index in range(254, -1, -1):
45
+ bit = (scalar_int >> bit_index) & 1
46
+ swap ^= bit
47
+ if swap:
48
+ x2, x3 = x3, x2
49
+ z2, z3 = z3, z2
50
+ swap = bit
51
+ a = (x2 + z2) % P
52
+ aa = a * a % P
53
+ b = (x2 - z2) % P
54
+ bb = b * b % P
55
+ e = (aa - bb) % P
56
+ c = (x3 + z3) % P
57
+ d = (x3 - z3) % P
58
+ da = d * a % P
59
+ cb = c * b % P
60
+ x3 = (da + cb) % P
61
+ x3 = x3 * x3 % P
62
+ z3 = (da - cb) % P
63
+ z3 = z3 * z3 % P
64
+ z3 = z3 * x1 % P
65
+ x2 = aa * bb % P
66
+ z2 = e * (aa + A24 * e) % P
67
+ if swap:
68
+ x2, x3 = x3, x2
69
+ z2, z3 = z3, z2
70
+ return (x2 * pow(z2, P - 2, P) % P).to_bytes(32, "little")
71
+
72
+
73
+ def x25519_base(scalar: bytes) -> bytes:
74
+ return x25519(scalar, BASE_POINT)
75
+
76
+
77
+ # -- HKDF-SHA256 --------------------------------------------------------
78
+ def hkdf(secret: bytes, salt: bytes, info: bytes, length: int = 32) -> bytes:
79
+ if not salt:
80
+ salt = b"\x00" * hashlib.sha256().digest_size
81
+ prk = hmac.new(salt, secret, hashlib.sha256).digest()
82
+ output = b""
83
+ block = b""
84
+ counter = 1
85
+ while len(output) < length:
86
+ block = hmac.new(prk, block + info + bytes([counter]), hashlib.sha256).digest()
87
+ output += block
88
+ counter += 1
89
+ return output[:length]
90
+
91
+
92
+ # -- ChaCha20-Poly1305 (RFC 8439) ---------------------------------------
93
+ def _rotl(value: int, count: int) -> int:
94
+ return ((value << count) & 0xFFFFFFFF) | (value >> (32 - count))
95
+
96
+
97
+ def _quarter_round(state: list[int], a: int, b: int, c: int, d: int) -> None:
98
+ state[a] = (state[a] + state[b]) & 0xFFFFFFFF
99
+ state[d] = _rotl(state[d] ^ state[a], 16)
100
+ state[c] = (state[c] + state[d]) & 0xFFFFFFFF
101
+ state[b] = _rotl(state[b] ^ state[c], 12)
102
+ state[a] = (state[a] + state[b]) & 0xFFFFFFFF
103
+ state[d] = _rotl(state[d] ^ state[a], 8)
104
+ state[c] = (state[c] + state[d]) & 0xFFFFFFFF
105
+ state[b] = _rotl(state[b] ^ state[c], 7)
106
+
107
+
108
+ def chacha20_block(key: bytes, counter: int, nonce: bytes) -> bytes:
109
+ if len(key) != 32 or len(nonce) != 12:
110
+ raise ValueError("chacha20 wants a 32 byte key and a 12 byte nonce")
111
+ constants = (0x61707865, 0x3320646E, 0x79622D32, 0x6B206574)
112
+ state = list(constants)
113
+ state += [int.from_bytes(key[index : index + 4], "little") for index in range(0, 32, 4)]
114
+ state.append(counter & 0xFFFFFFFF)
115
+ state += [int.from_bytes(nonce[index : index + 4], "little") for index in range(0, 12, 4)]
116
+ working = list(state)
117
+ for _ in range(10):
118
+ _quarter_round(working, 0, 4, 8, 12)
119
+ _quarter_round(working, 1, 5, 9, 13)
120
+ _quarter_round(working, 2, 6, 10, 14)
121
+ _quarter_round(working, 3, 7, 11, 15)
122
+ _quarter_round(working, 0, 5, 10, 15)
123
+ _quarter_round(working, 1, 6, 11, 12)
124
+ _quarter_round(working, 2, 7, 8, 13)
125
+ _quarter_round(working, 3, 4, 9, 14)
126
+ out = [(working[index] + state[index]) & 0xFFFFFFFF for index in range(16)]
127
+ return b"".join(word.to_bytes(4, "little") for word in out)
128
+
129
+
130
+ def chacha20(key: bytes, nonce: bytes, data: bytes, counter: int = 0) -> bytes:
131
+ out = bytearray()
132
+ for offset in range(0, len(data), 64):
133
+ block = chacha20_block(key, counter + offset // 64, nonce)
134
+ chunk = data[offset : offset + 64]
135
+ out += bytes(left ^ right for left, right in zip(chunk, block))
136
+ return bytes(out)
137
+
138
+
139
+ def poly1305(key: bytes, message: bytes) -> bytes:
140
+ if len(key) != 32:
141
+ raise ValueError("poly1305 wants a 32 byte key")
142
+ r = int.from_bytes(key[:16], "little") & 0x0FFFFFFC0FFFFFFC0FFFFFFC0FFFFFFF
143
+ s = int.from_bytes(key[16:], "little")
144
+ p = (1 << 130) - 5
145
+ accumulator = 0
146
+ for offset in range(0, len(message), 16):
147
+ chunk = message[offset : offset + 16]
148
+ accumulator = (accumulator + int.from_bytes(chunk + b"\x01", "little")) * r % p
149
+ return ((accumulator + s) & ((1 << 128) - 1)).to_bytes(16, "little")
150
+
151
+
152
+ def _padded(data: bytes) -> bytes:
153
+ return data + b"\x00" * ((16 - len(data) % 16) % 16)
154
+
155
+
156
+ def aead_seal(key: bytes, nonce: bytes, plaintext: bytes, aad: bytes = b"") -> bytes:
157
+ poly_key = chacha20_block(key, 0, nonce)[:32]
158
+ ciphertext = chacha20(key, nonce, plaintext, counter=1)
159
+ mac_data = _padded(aad) + _padded(ciphertext) + len(aad).to_bytes(8, "little") + len(ciphertext).to_bytes(8, "little")
160
+ return ciphertext + poly1305(poly_key, mac_data)
161
+
162
+
163
+ def aead_open(key: bytes, nonce: bytes, sealed: bytes, aad: bytes = b"") -> bytes:
164
+ if len(sealed) < TAG_LEN:
165
+ raise CryptoError("sealed box too short")
166
+ ciphertext, tag = sealed[:-TAG_LEN], sealed[-TAG_LEN:]
167
+ poly_key = chacha20_block(key, 0, nonce)[:32]
168
+ mac_data = _padded(aad) + _padded(ciphertext) + len(aad).to_bytes(8, "little") + len(ciphertext).to_bytes(8, "little")
169
+ if not hmac.compare_digest(poly1305(poly_key, mac_data), tag):
170
+ raise CryptoError("authentication failed")
171
+ return chacha20(key, nonce, ciphertext, counter=1)
172
+
173
+
174
+ # -- identities ---------------------------------------------------------
175
+ class Identity:
176
+ """A long-lived X25519 keypair; the fingerprint is what humans compare."""
177
+
178
+ def __init__(self, secret: bytes | None = None) -> None:
179
+ self.secret = secret or os.urandom(32)
180
+ if len(self.secret) != 32:
181
+ raise ValueError("identity secret must be 32 bytes")
182
+ self.public = x25519_base(self.secret)
183
+
184
+ @classmethod
185
+ def from_file(cls, path: str) -> "Identity":
186
+ with open(os.path.expanduser(path), "rb") as handle:
187
+ return cls(handle.read().strip())
188
+
189
+ def save(self, path: str) -> None:
190
+ path = os.path.expanduser(path)
191
+ directory = os.path.dirname(path) or "."
192
+ os.makedirs(directory, exist_ok=True)
193
+ temporary = f"{path}.tmp"
194
+ with open(temporary, "wb") as handle:
195
+ handle.write(self.secret)
196
+ os.chmod(temporary, 0o600)
197
+ os.replace(temporary, path)
198
+
199
+ @property
200
+ def fingerprint(self) -> str:
201
+ return hashlib.sha256(self.public).hexdigest()[:16]
202
+
203
+ def __repr__(self) -> str:
204
+ return f"Identity({self.fingerprint})"
205
+
206
+
207
+ def seal(recipient_public: bytes, message: bytes, aad: bytes = b"") -> bytes:
208
+ """Anonymous sealed box: ephemeral X25519 + ChaCha20-Poly1305."""
209
+ if len(recipient_public) != 32:
210
+ raise ValueError("recipient public key must be 32 bytes")
211
+ ephemeral = os.urandom(32)
212
+ ephemeral_public = x25519_base(ephemeral)
213
+ shared = x25519(ephemeral, recipient_public)
214
+ key = hkdf(shared, ephemeral_public + recipient_public, SEAL_INFO)
215
+ nonce = os.urandom(12)
216
+ return ephemeral_public + nonce + aead_seal(key, nonce, message, aad)
217
+
218
+
219
+ def open_sealed(identity: Identity, box: bytes, aad: bytes = b"") -> bytes:
220
+ if len(box) < 32 + 12 + TAG_LEN:
221
+ raise CryptoError("sealed box too short")
222
+ ephemeral_public, nonce, rest = box[:32], box[32:44], box[44:]
223
+ shared = x25519(identity.secret, ephemeral_public)
224
+ key = hkdf(shared, ephemeral_public + identity.public, SEAL_INFO)
225
+ return aead_open(key, nonce, rest, aad)
226
+
227
+
228
+ def b64encode(data: bytes) -> str:
229
+ return base64.b64encode(data).decode()
230
+
231
+
232
+ def b64decode(text: str) -> bytes:
233
+ return base64.b64decode(text.encode())
btsh/framing.py ADDED
@@ -0,0 +1,96 @@
1
+ """Wire framing shared by both ends of the acoustic link.
2
+
3
+ offset size field
4
+ 0 1 version (1)
5
+ 1 1 frame type
6
+ 2 1 sequence number (mod 256)
7
+ 3 1 flags (START / END)
8
+ 4 2 payload length (big endian)
9
+ 6 n payload
10
+ 6+n 4 crc32 over version..payload
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import struct
16
+ import zlib
17
+ from dataclasses import dataclass
18
+
19
+ MAGIC = b"BS"
20
+ VERSION = 1
21
+ HEADER_LEN = 6
22
+ CRC_LEN = 4
23
+ MAX_PAYLOAD = 240
24
+
25
+ FT_DATA = 0
26
+ FT_ACK = 1
27
+ FT_NAK = 2
28
+ FT_HELLO = 4
29
+ FT_HELLO_ACK = 5
30
+ FT_BYE = 6
31
+
32
+ FLAG_START = 0x01
33
+ FLAG_END = 0x02
34
+
35
+ TYPE_NAMES = {
36
+ FT_DATA: "DATA",
37
+ FT_ACK: "ACK",
38
+ FT_NAK: "NAK",
39
+ FT_HELLO: "HELLO",
40
+ FT_HELLO_ACK: "HELLO_ACK",
41
+ FT_BYE: "BYE",
42
+ }
43
+
44
+
45
+ class FrameError(Exception):
46
+ """Raised on a malformed or corrupted wire frame."""
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class Frame:
51
+ ftype: int
52
+ seq: int
53
+ payload: bytes = b""
54
+ flags: int = 0
55
+
56
+ @property
57
+ def type_name(self) -> str:
58
+ return TYPE_NAMES.get(self.ftype, str(self.ftype))
59
+
60
+ def __str__(self) -> str: # pragma: no cover - debugging aid
61
+ return f"<{self.type_name} seq={self.seq} flags={self.flags} n={len(self.payload)}>"
62
+
63
+
64
+ def peek_header(header: bytes) -> tuple[int, int, int, int]:
65
+ """Return (payload_len, ftype, seq, flags) from a 6 byte header."""
66
+ if len(header) != HEADER_LEN:
67
+ raise FrameError("bad header length")
68
+ version, ftype, seq, flags, payload_len = struct.unpack(">BBBBH", header)
69
+ if version != VERSION:
70
+ raise FrameError(f"bad version {version}")
71
+ if payload_len > MAX_PAYLOAD:
72
+ raise FrameError(f"payload too long ({payload_len})")
73
+ return payload_len, ftype, seq, flags
74
+
75
+
76
+ def pack(frame: Frame) -> bytes:
77
+ payload = frame.payload
78
+ if len(payload) > MAX_PAYLOAD:
79
+ raise FrameError(f"payload too long ({len(payload)} > {MAX_PAYLOAD})")
80
+ header = struct.pack(">BBBBH", VERSION, frame.ftype, frame.seq & 0xFF, frame.flags & 0xFF, len(payload))
81
+ body = header + payload
82
+ return body + struct.pack(">I", zlib.crc32(body) & 0xFFFFFFFF)
83
+
84
+
85
+ def unpack(wire: bytes) -> Frame:
86
+ if len(wire) < HEADER_LEN + CRC_LEN:
87
+ raise FrameError("frame too short")
88
+ payload_len, ftype, seq, flags = peek_header(wire[:HEADER_LEN])
89
+ expected = HEADER_LEN + payload_len + CRC_LEN
90
+ if len(wire) < expected:
91
+ raise FrameError("truncated frame")
92
+ body = wire[: HEADER_LEN + payload_len]
93
+ (crc,) = struct.unpack(">I", wire[HEADER_LEN + payload_len : expected])
94
+ if zlib.crc32(body) & 0xFFFFFFFF != crc:
95
+ raise FrameError("crc mismatch")
96
+ return Frame(ftype=ftype, seq=seq, payload=body[HEADER_LEN:], flags=flags)