passwork-bridge 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.
@@ -0,0 +1,4 @@
1
+ # SPDX-License-Identifier: AGPL-3.0-only
2
+ """Passwork Bridge command-line client."""
3
+
4
+ __version__ = "0.1.0"
@@ -0,0 +1,4 @@
1
+ # SPDX-License-Identifier: AGPL-3.0-only
2
+ from .cli import main
3
+
4
+ raise SystemExit(main())
passwork_bridge/cli.py ADDED
@@ -0,0 +1,243 @@
1
+ # SPDX-License-Identifier: AGPL-3.0-only
2
+ """``passwork-bridge send`` and ``passwork-bridge get``: encrypt on this machine, hand the server ciphertext only."""
3
+
4
+ import argparse
5
+ import getpass
6
+ import os
7
+ import re
8
+ import sys
9
+ import unicodedata
10
+ import urllib.parse
11
+ from collections.abc import Sequence
12
+
13
+ from . import __version__
14
+ from .client import DEFAULT_SERVER, ApiError, Client
15
+ from .crypto import (
16
+ ROLES,
17
+ DecryptError,
18
+ MessageBinding,
19
+ b64url_encode,
20
+ check_sequence,
21
+ decrypt_text,
22
+ encrypt_text,
23
+ generate_key,
24
+ new_message_id,
25
+ open_deletion,
26
+ open_message,
27
+ parse_key,
28
+ peek_message,
29
+ )
30
+
31
+ PROG = "passwork-bridge"
32
+ ISSUES = "https://github.com/passwork-europe/bridge/issues"
33
+ MAX_TEXT_BYTES = 50 * 1024 # what the web client accepts
34
+ DURATION = re.compile(r"^(\d+)([smhd]?)$")
35
+ UNITS = {"": 1, "s": 1, "m": 60, "h": 3600, "d": 86400}
36
+ BRIDGE_PATH = re.compile(r"^(.*)/b/([A-Za-z0-9_-]+)$")
37
+ SEALED_FIELD = {"text": "body", "file": "header"} # docs/api.md, the claim's messages
38
+ NOT_A_BRIDGE = "The server's answer is not what a Bridge sends."
39
+
40
+
41
+ class UsageError(Exception):
42
+ pass
43
+
44
+
45
+ def parse_duration(text: str) -> int:
46
+ match = DURATION.match(text.strip().lower())
47
+ if match is None:
48
+ raise argparse.ArgumentTypeError("use a number with s, m, h or d, for example 30m, 1h, 1d")
49
+ seconds = int(match.group(1)) * UNITS[match.group(2)]
50
+ if seconds < 60:
51
+ raise argparse.ArgumentTypeError("at least 1 minute")
52
+ return seconds
53
+
54
+
55
+ def parse_views(text: str) -> int:
56
+ if not text.isdigit() or int(text) < 1:
57
+ raise argparse.ArgumentTypeError("a whole number, 1 or more")
58
+ return int(text)
59
+
60
+
61
+ def parse_link(link: str) -> tuple[str, str, str]:
62
+ """Splits ``https://host/b/<id>#<key>`` into the server, the bridge id and the encoded key."""
63
+ parsed = urllib.parse.urlsplit(link.strip())
64
+ match = BRIDGE_PATH.match(parsed.path)
65
+ if not parsed.scheme or not parsed.netloc or match is None or not parsed.fragment:
66
+ raise UsageError("That is not a Bridge link (https://host/b/<id>#<key>).")
67
+ return f"{parsed.scheme}://{parsed.netloc}{match.group(1)}", match.group(2), parsed.fragment
68
+
69
+
70
+ def read_link(argument: str | None) -> str:
71
+ """The link from standard input. An argument is refused: the link carries the key, and arguments show in shell history and ``ps``."""
72
+ if argument not in (None, "-"):
73
+ raise UsageError(f"Do not put the link on the command line, it carries the key: pipe it in, e.g. echo \"$LINK\" | {PROG} get")
74
+ if argument is None and sys.stdin.isatty():
75
+ line = getpass.getpass("Link: ")
76
+ if not line.strip():
77
+ raise UsageError("No link given.")
78
+ return line
79
+ try:
80
+ line = sys.stdin.buffer.readline().decode("utf-8")
81
+ except UnicodeDecodeError:
82
+ raise UsageError("Standard input is not valid UTF-8.") from None
83
+ if not line.strip():
84
+ raise UsageError("Standard input holds no link.")
85
+ return line
86
+
87
+
88
+ # Characters that can rewrite the terminal or the order of what is read, besides newline and tab: C0 and C1 controls
89
+ # (escape sequences, OSC 52 clipboard writes, hidden text) and the bidirectional overrides that make text read backwards.
90
+ _BIDI = {*range(0x202A, 0x202F), *range(0x2066, 0x206A)}
91
+
92
+
93
+ def printable(text: str, keep: str = "\n\t") -> str:
94
+ """The text with terminal control characters written out (``\\x1b``), so a secret cannot drive the terminal.
95
+
96
+ What the server says goes through it with ``keep=""``: one line, so it cannot pass for a line of this program."""
97
+ out = []
98
+ for char in text:
99
+ if char in keep or (unicodedata.category(char) != "Cc" and ord(char) not in _BIDI):
100
+ out.append(char)
101
+ else:
102
+ out.append(char.encode("unicode_escape").decode("ascii"))
103
+ return "".join(out)
104
+
105
+
106
+ def write_secret(text: str) -> None:
107
+ """A terminal gets the text with its controls written out; a pipe or a file gets it as it is, in UTF-8 whatever the
108
+ locale (a Windows pipe would otherwise use the code page and fail on characters outside it)."""
109
+ if sys.stdout.isatty():
110
+ print(printable(text))
111
+ else:
112
+ sys.stdout.flush()
113
+ sys.stdout.buffer.write(text.encode() + b"\n")
114
+ sys.stdout.buffer.flush()
115
+
116
+
117
+ def read_secret() -> str:
118
+ """The secret from standard input, or hidden typing on a terminal; never from an argument (shell history, ``ps``)."""
119
+ if sys.stdin.isatty():
120
+ text = getpass.getpass("Secret: ")
121
+ else:
122
+ try:
123
+ text = sys.stdin.buffer.read().decode("utf-8")
124
+ except UnicodeDecodeError:
125
+ raise UsageError("Standard input is not valid UTF-8.") from None
126
+ if text.endswith("\n"):
127
+ text = text[:-1]
128
+ if text.endswith("\r"):
129
+ text = text[:-1]
130
+ if not text.strip():
131
+ raise UsageError("The secret is empty.")
132
+ if len(text.encode()) > MAX_TEXT_BYTES:
133
+ raise UsageError(f"The secret is longer than {MAX_TEXT_BYTES // 1024} KB.")
134
+ return text
135
+
136
+
137
+ def send(args: argparse.Namespace) -> int:
138
+ text = read_secret()
139
+ client = Client(args.server)
140
+ key = generate_key()
141
+ created = client.create_bridge(args.ttl, args.views)
142
+ try:
143
+ bridge_id, owner_token, expires_at = created["bridgeId"], created["ownerToken"], created["expiresAt"]
144
+ except (KeyError, TypeError):
145
+ raise ApiError("The server's answer is missing fields.") from None
146
+ if not all(isinstance(field, str) for field in (bridge_id, owner_token, expires_at)):
147
+ raise ApiError(NOT_A_BRIDGE)
148
+ try:
149
+ # the ciphertext is bound to the bridge and the message, so it is made once the bridge exists
150
+ message_id = new_message_id()
151
+ client.post_text(bridge_id, owner_token, message_id, encrypt_text(key, text, MessageBinding(bridge_id, message_id, "owner")))
152
+ except BaseException:
153
+ try:
154
+ client.delete_bridge(bridge_id, owner_token)
155
+ except ApiError:
156
+ pass
157
+ raise
158
+ link = f"{client.server}/b/{urllib.parse.quote(bridge_id, safe='')}#{b64url_encode(key)}"
159
+ print(link)
160
+ if sys.stderr.isatty():
161
+ views = "view" if args.views == 1 else "views"
162
+ print(f"Opens {args.views} {views}, then it is gone. Expires {printable(expires_at, keep='')}.", file=sys.stderr)
163
+ return 0
164
+
165
+
166
+ def get(args: argparse.Namespace) -> int:
167
+ server, bridge_id, encoded_key = parse_link(read_link(args.link))
168
+ key = parse_key(encoded_key)
169
+ client = Client(server)
170
+ try:
171
+ messages = client.claim(bridge_id)["view"]["messages"] # spends one view; the answer already holds what the bridge holds
172
+ listed = [(m["id"], m["from"], m["kind"], m[SEALED_FIELD[m["kind"]]]) for m in messages]
173
+ except (KeyError, TypeError):
174
+ raise ApiError(NOT_A_BRIDGE) from None
175
+ if not all(isinstance(field, str) for entry in listed for field in entry) or any(role not in ROLES for _, role, _, _ in listed):
176
+ raise ApiError(NOT_A_BRIDGE)
177
+ # docs/format.md §5: every writing device's messages must run from 0 without a hole; a number the owner removed on
178
+ # purpose is covered by a deletion mark, which is not a text. Only what opens counts: the place of a message is the one
179
+ # that was authenticated, and a mark is skipped only once it has opened, so a flag or a number changed on the way leaves
180
+ # a hole (and a text that does not decrypt), not a message that is gone.
181
+ entries = []
182
+ marks = set()
183
+ for message_id, role, kind, envelope in listed:
184
+ binding = MessageBinding(bridge_id, message_id, role)
185
+ try:
186
+ if kind != "text":
187
+ place = open_message(key, envelope, binding, "file-header")[1]
188
+ removes = None
189
+ elif peek_message(envelope)[1]:
190
+ place, removes = open_deletion(key, envelope, binding)
191
+ marks.add(message_id)
192
+ else:
193
+ place = open_message(key, envelope, binding, "text")[1]
194
+ removes = None
195
+ except DecryptError:
196
+ continue
197
+ entries.append((message_id, place, removes))
198
+ if check_sequence(entries):
199
+ print("warning: a message may be missing, repeated or out of order: the server could have removed or moved it.", file=sys.stderr)
200
+ texts = [(i, e) for i, role, kind, e in listed if kind == "text" and role == "owner" and i not in marks]
201
+ if not texts:
202
+ raise UsageError("This bridge holds no text.")
203
+ for message_id, body in texts:
204
+ write_secret(decrypt_text(key, body, MessageBinding(bridge_id, message_id, "owner")))
205
+ return 0
206
+
207
+
208
+ def build_parser() -> argparse.ArgumentParser:
209
+ parser = argparse.ArgumentParser(prog=PROG, description="Share a secret as a one-time, end-to-end encrypted link.")
210
+ parser.add_argument("--version", action="version", version=f"{PROG} {__version__}")
211
+ commands = parser.add_subparsers(dest="command", required=True)
212
+
213
+ server_help = f"Bridge server (default: $BRIDGE_SERVER or {DEFAULT_SERVER})"
214
+ sender = commands.add_parser("send", help="encrypt a secret and print its link", description="Encrypts on this machine and prints the link; the key never leaves it except inside the link.")
215
+ sender.add_argument("--ttl", type=parse_duration, default=86400, metavar="TIME", help="lifetime, such as 30m, 1h, 1d (default 1d; the server caps it)")
216
+ sender.add_argument("--views", type=parse_views, default=1, metavar="N", help="how many times it can be opened (default 1)")
217
+ sender.add_argument("--server", default=os.environ.get("BRIDGE_SERVER", DEFAULT_SERVER), help=server_help)
218
+ sender.set_defaults(run=send)
219
+
220
+ reader = commands.add_parser("get", help="open a link and print the secret (spends one view)")
221
+ reader.add_argument("link", nargs="?", help=argparse.SUPPRESS) # only "-" is accepted: the link carries the key and is read from standard input
222
+ reader.set_defaults(run=get)
223
+ return parser
224
+
225
+
226
+ def main(argv: Sequence[str] | None = None) -> int:
227
+ args, stray = build_parser().parse_known_args(argv)
228
+ if stray:
229
+ # Said without the value: it may be a secret, and argparse would print it.
230
+ print(f"{PROG}: the secret and the link are read from standard input, never from the command line (see `{PROG} --help`).", file=sys.stderr)
231
+ return 2
232
+ try:
233
+ return int(args.run(args))
234
+ except (UsageError, ApiError, DecryptError) as error:
235
+ # an ApiError may carry the server's own words
236
+ print(f"{PROG}: {printable(str(error), keep='')}", file=sys.stderr)
237
+ return 2 if isinstance(error, UsageError) else 1
238
+ except KeyboardInterrupt:
239
+ return 130
240
+ except Exception as error:
241
+ # The message is left out: it may quote the server's answer or a piece of the secret.
242
+ print(f"{PROG}: unexpected {type(error).__name__}; please report it at {ISSUES}", file=sys.stderr)
243
+ return 1
@@ -0,0 +1,100 @@
1
+ # SPDX-License-Identifier: AGPL-3.0-only
2
+ """A minimal client for the Bridge HTTP API (docs/api.md); standard library only."""
3
+
4
+ import json
5
+ import urllib.error
6
+ import urllib.parse
7
+ import urllib.request
8
+ from typing import Any
9
+
10
+ from . import __version__
11
+
12
+ DEFAULT_SERVER = "https://bridge.passwork.pro"
13
+ TIMEOUT_SECONDS = 30
14
+ LOOPBACK = {"localhost", "127.0.0.1", "::1"}
15
+ # A claim holds at most 1000 messages of at most 256 KiB each (the server's defaults), as base64url in JSON.
16
+ MAX_ANSWER_BYTES = 300 * 1024 * 1024
17
+ MAX_ERROR_BYTES = 64 * 1024
18
+
19
+
20
+ class ApiError(Exception):
21
+ def __init__(self, message: str, status: int | None = None) -> None:
22
+ super().__init__(message)
23
+ self.status = status
24
+
25
+
26
+ def normalize_server(server: str) -> str:
27
+ """Accepts https URLs, and http only for loopback (a secret never leaves in clear text)."""
28
+ parsed = urllib.parse.urlsplit(server.strip())
29
+ if parsed.scheme not in ("http", "https") or not parsed.hostname:
30
+ raise ApiError(f"Not a server address: {server!r}.")
31
+ if parsed.scheme == "http" and parsed.hostname not in LOOPBACK:
32
+ raise ApiError("Refusing to talk to a server over plain http; use https.")
33
+ if parsed.username or parsed.password or parsed.query or parsed.fragment:
34
+ raise ApiError("The server address must not carry credentials, a query or a fragment.")
35
+ return f"{parsed.scheme}://{parsed.netloc}{parsed.path.rstrip('/')}"
36
+
37
+
38
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
39
+ def redirect_request(self, *args: Any, **kwargs: Any) -> None:
40
+ return None
41
+
42
+
43
+ _opener = urllib.request.build_opener(_NoRedirect)
44
+
45
+
46
+ class Client:
47
+ def __init__(self, server: str = DEFAULT_SERVER) -> None:
48
+ self.server = normalize_server(server)
49
+
50
+ def _call(self, method: str, path: str, body: dict[str, Any] | None = None, token: str | None = None) -> Any:
51
+ headers = {"user-agent": f"passwork-bridge-cli/{__version__}", "accept": "application/json"}
52
+ data = None
53
+ if body is not None:
54
+ data = json.dumps(body).encode()
55
+ headers["content-type"] = "application/json"
56
+ if token is not None:
57
+ headers["authorization"] = f"Bearer {token}"
58
+ request = urllib.request.Request(f"{self.server}/api{path}", data=data, headers=headers, method=method)
59
+ try:
60
+ with _opener.open(request, timeout=TIMEOUT_SECONDS) as response:
61
+ raw = response.read(MAX_ANSWER_BYTES + 1)
62
+ except urllib.error.HTTPError as error:
63
+ raise ApiError(_message(error), error.code) from None
64
+ except (urllib.error.URLError, TimeoutError, OSError) as error:
65
+ raise ApiError(f"Could not reach {self.server}: {getattr(error, 'reason', error)}") from None
66
+ if len(raw) > MAX_ANSWER_BYTES:
67
+ raise ApiError("The server's answer is larger than a Bridge sends.")
68
+ try:
69
+ return json.loads(raw) if raw else None
70
+ except ValueError:
71
+ raise ApiError("The server sent an answer that is not valid JSON.") from None
72
+
73
+ def create_bridge(self, ttl_seconds: int, max_views: int) -> dict[str, Any]:
74
+ return _object(self._call("POST", "/bridges", {"ttlSeconds": ttl_seconds, "maxViews": max_views, "mode": "secret"}))
75
+
76
+ def post_text(self, bridge_id: str, owner_token: str, message_id: str, ciphertext: str) -> Any:
77
+ path = f"/bridges/{urllib.parse.quote(bridge_id, safe='')}/messages"
78
+ return self._call("POST", path, {"id": message_id, "kind": "text", "body": ciphertext}, owner_token)
79
+
80
+ def delete_bridge(self, bridge_id: str, owner_token: str) -> None:
81
+ self._call("DELETE", f"/bridges/{urllib.parse.quote(bridge_id, safe='')}", token=owner_token)
82
+
83
+ def claim(self, bridge_id: str) -> dict[str, Any]:
84
+ return _object(self._call("POST", f"/bridges/{urllib.parse.quote(bridge_id, safe='')}/claims"))
85
+
86
+
87
+ def _object(answer: Any) -> dict[str, Any]:
88
+ if not isinstance(answer, dict):
89
+ raise ApiError("The server's answer is not what a Bridge sends.")
90
+ return answer
91
+
92
+
93
+ def _message(error: urllib.error.HTTPError) -> str:
94
+ try:
95
+ body = json.loads(error.read(MAX_ERROR_BYTES))
96
+ if isinstance(body, dict) and isinstance(body.get("message"), str):
97
+ return f"{body['message']} (HTTP {error.code})"
98
+ except ValueError:
99
+ pass
100
+ return f"The server answered HTTP {error.code}."
@@ -0,0 +1,329 @@
1
+ # SPDX-License-Identifier: AGPL-3.0-only
2
+ """Bridge's zero-knowledge primitives, version 3 of the format (docs/format.md), byte-compatible with ``web/src/crypto/``.
3
+
4
+ The 32-byte link key never encrypts: an AES-256-GCM key for messages is derived from it with HKDF-SHA-256, and one more
5
+ for the chunks of each file. A message is padded to a size class, sealed in an envelope
6
+ ``version ‖ suite ‖ flags ‖ sender ‖ seq ‖ iv ‖ ciphertext ‖ tag`` and bound, through additional data with length-prefixed
7
+ fields, to its bridge, its own id, the side that wrote it, its kind and its place in its writer's run, so a relay that
8
+ replays it under another id, moves it to another bridge or relabels its side gets nothing out of it.
9
+ """
10
+
11
+ import base64
12
+ import binascii
13
+ import os
14
+ import secrets
15
+ import struct
16
+ from collections.abc import Iterable
17
+ from dataclasses import dataclass
18
+
19
+ from cryptography.exceptions import InvalidTag
20
+ from cryptography.hazmat.primitives import hashes
21
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
22
+ from cryptography.hazmat.primitives.kdf.hkdf import HKDF
23
+
24
+ VERSION = 3
25
+ SUITE_AES_GCM = 1
26
+ FLAG_LAST_CHUNK = 0x01
27
+ FLAG_PADDED = 0x02
28
+ FLAG_DELETION = 0x04
29
+ FLAGS_KNOWN = FLAG_LAST_CHUNK | FLAG_PADDED | FLAG_DELETION
30
+
31
+ IV_BYTES = 12
32
+ TAG_BYTES = 16
33
+ KEY_BYTES = 32
34
+ SENDER_BYTES = 8
35
+ SEQ_BYTES = 4
36
+ HEAD_BYTES = 3
37
+ MESSAGE_HEAD_BYTES = HEAD_BYTES + SENDER_BYTES + SEQ_BYTES + IV_BYTES
38
+ CHUNK_OVERHEAD = HEAD_BYTES + TAG_BYTES
39
+
40
+ PAD_BUCKETS = (256, 1024, 4096)
41
+ MESSAGE_KEY_INFO = b"passwork-bridge/v3/key/message"
42
+ FILE_KEY_INFO = b"passwork-bridge/v3/key/file"
43
+ MESSAGE_LABEL = b"passwork-bridge/message"
44
+ FILE_CHUNK_LABEL = b"passwork-bridge/file"
45
+
46
+ ROLES = {"owner": 1, "guest": 2}
47
+ PARTS = {"text": 1, "file-header": 2, "deletion": 3}
48
+ _ALPHABET = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_")
49
+
50
+
51
+ class DecryptError(Exception):
52
+ """The ciphertext or the key in the link is not valid."""
53
+
54
+
55
+ class UnsupportedVersionError(DecryptError):
56
+ """It was made by another version or suite of Bridge: a different client, not a wrong key."""
57
+
58
+
59
+ def b64url_encode(data: bytes) -> str:
60
+ return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")
61
+
62
+
63
+ def b64url_decode(text: str) -> bytes:
64
+ try:
65
+ text.encode("ascii")
66
+ raw = base64.b64decode(
67
+ text.replace("-", "+").replace("_", "/") + "=" * (-len(text) % 4),
68
+ validate=True,
69
+ )
70
+ except (UnicodeEncodeError, binascii.Error) as error:
71
+ raise DecryptError("Invalid base64url encoding.") from error
72
+ if b64url_encode(raw) != text:
73
+ raise DecryptError("Invalid base64url encoding.")
74
+ return raw
75
+
76
+
77
+ def generate_key() -> bytes:
78
+ return secrets.token_bytes(KEY_BYTES)
79
+
80
+
81
+ def parse_key(encoded: str) -> bytes:
82
+ try:
83
+ key = b64url_decode(encoded)
84
+ except DecryptError as error:
85
+ raise DecryptError("The link is malformed or the encryption key is missing.") from error
86
+ if len(key) != KEY_BYTES:
87
+ raise DecryptError("The link is malformed or the encryption key is missing.")
88
+ return key
89
+
90
+
91
+ # ------------------------------------------------------------------ subkeys
92
+
93
+
94
+ def _hkdf(link_key: bytes, info: bytes) -> bytes:
95
+ return HKDF(algorithm=hashes.SHA256(), length=KEY_BYTES, salt=None, info=info).derive(link_key)
96
+
97
+
98
+ def message_key(link_key: bytes) -> bytes:
99
+ return _hkdf(link_key, MESSAGE_KEY_INFO)
100
+
101
+
102
+ def file_key(link_key: bytes, nonce: str) -> bytes:
103
+ return _hkdf(link_key, FILE_KEY_INFO + b"\x00" + nonce.encode("ascii"))
104
+
105
+
106
+ # ------------------------------------------------------------------ padding
107
+
108
+
109
+ def _padme(n: int) -> int:
110
+ exponent = n.bit_length() - 1
111
+ mantissa_bits = exponent.bit_length()
112
+ zero_bits = exponent - mantissa_bits
113
+ mask = (1 << zero_bits) - 1
114
+ return (n + mask) & ~mask
115
+
116
+
117
+ def padded_length(length: int) -> int:
118
+ needed = 4 + length
119
+ for bucket in PAD_BUCKETS:
120
+ if needed <= bucket:
121
+ return bucket
122
+ return _padme(needed)
123
+
124
+
125
+ def pad(data: bytes) -> bytes:
126
+ return struct.pack(">I", len(data)) + data + bytes(padded_length(len(data)) - 4 - len(data))
127
+
128
+
129
+ def unpad(padded: bytes) -> bytes:
130
+ if len(padded) < 4:
131
+ raise DecryptError("Invalid padding.")
132
+ (length,) = struct.unpack(">I", padded[:4])
133
+ if length > len(padded) - 4 or padded_length(length) != len(padded) or any(padded[4 + length :]):
134
+ raise DecryptError("Invalid padding.")
135
+ return padded[4 : 4 + length]
136
+
137
+
138
+ # --------------------------------------------------------------- the envelope
139
+
140
+
141
+ def _lp(data: bytes) -> bytes:
142
+ if len(data) > 0xFFFF:
143
+ raise DecryptError("A field is too long.")
144
+ return struct.pack(">H", len(data)) + data
145
+
146
+
147
+ @dataclass(frozen=True)
148
+ class MessageBinding:
149
+ """What a message's ciphertext is bound to besides the key (docs/format.md §2.1)."""
150
+
151
+ bridge_id: str
152
+ message_id: str
153
+ role: str
154
+
155
+
156
+ @dataclass(frozen=True)
157
+ class Position:
158
+ """A writing device's random name on a bridge, and the place of a message in its run."""
159
+
160
+ sender: bytes
161
+ seq: int
162
+
163
+
164
+ _runs: dict[str, tuple[bytes, int]] = {}
165
+
166
+
167
+ def reserve_position(bridge_id: str) -> Position:
168
+ """The place of the next message this process writes to ``bridge_id``."""
169
+ sender, next_seq = _runs.get(bridge_id, (secrets.token_bytes(SENDER_BYTES), 0))
170
+ _runs[bridge_id] = (sender, next_seq + 1)
171
+ return Position(sender, next_seq)
172
+
173
+
174
+ def new_message_id() -> str:
175
+ """22 base64url characters (128 random bits), chosen by the sender because the ciphertext is bound to it."""
176
+ return secrets.token_urlsafe(16)
177
+
178
+
179
+ def _check_id(message_id: str) -> None:
180
+ if len(message_id) != 22 or not set(message_id) <= _ALPHABET:
181
+ raise DecryptError("Invalid message id.")
182
+
183
+
184
+ def message_flags(part: str) -> int:
185
+ return FLAG_PADDED | FLAG_DELETION if part == "deletion" else FLAG_PADDED
186
+
187
+
188
+ def message_aad(binding: MessageBinding, part: str, flags: int, position: Position) -> bytes:
189
+ _check_id(binding.message_id)
190
+ return (
191
+ MESSAGE_LABEL
192
+ + bytes([0, VERSION, SUITE_AES_GCM, flags])
193
+ + _lp(binding.bridge_id.encode())
194
+ + _lp(binding.message_id.encode())
195
+ + bytes([ROLES[binding.role], PARTS[part]])
196
+ + position.sender
197
+ + struct.pack(">I", position.seq)
198
+ )
199
+
200
+
201
+ def seal_message(
202
+ link_key: bytes,
203
+ part: str,
204
+ data: bytes,
205
+ binding: MessageBinding,
206
+ position: Position | None = None,
207
+ iv: bytes | None = None,
208
+ ) -> str:
209
+ """A message as base64url. ``iv`` is for the test vectors only: a real caller never passes one."""
210
+ position = position or reserve_position(binding.bridge_id)
211
+ iv = iv or os.urandom(IV_BYTES)
212
+ flags = message_flags(part)
213
+ sealed = AESGCM(message_key(link_key)).encrypt(iv, pad(data), message_aad(binding, part, flags, position))
214
+ head = bytes([VERSION, SUITE_AES_GCM, flags]) + position.sender + struct.pack(">I", position.seq)
215
+ return b64url_encode(head + iv + sealed)
216
+
217
+
218
+ def check_head(data: bytes, minimum: int) -> int:
219
+ if len(data) < HEAD_BYTES:
220
+ raise DecryptError("Invalid ciphertext length: too short.")
221
+ if data[0] != VERSION:
222
+ raise UnsupportedVersionError("This was made with a different version of Bridge, or was altered on the way. Update Bridge and open the link again.")
223
+ if data[1] != SUITE_AES_GCM:
224
+ raise UnsupportedVersionError("This was made with an encryption suite this version of Bridge does not know.")
225
+ if data[2] & ~FLAGS_KNOWN:
226
+ raise DecryptError("Invalid ciphertext: unknown flags.")
227
+ if len(data) < minimum:
228
+ raise DecryptError("Invalid ciphertext length: too short.")
229
+ return data[2]
230
+
231
+
232
+ def open_message(link_key: bytes, encoded: str, binding: MessageBinding, part: str) -> tuple[bytes, Position]:
233
+ data = b64url_decode(encoded)
234
+ flags = check_head(data, MESSAGE_HEAD_BYTES + TAG_BYTES)
235
+ if flags != message_flags(part):
236
+ raise DecryptError("The message could not be decrypted: wrong key or altered data.")
237
+ position = Position(data[3 : 3 + SENDER_BYTES], struct.unpack(">I", data[11:15])[0])
238
+ iv = data[15 : 15 + IV_BYTES]
239
+ try:
240
+ padded = AESGCM(message_key(link_key)).decrypt(iv, data[MESSAGE_HEAD_BYTES:], message_aad(binding, part, flags, position))
241
+ except InvalidTag as error:
242
+ raise DecryptError("The message could not be decrypted: wrong key or altered data.") from error
243
+ return unpad(padded), position
244
+
245
+
246
+ def encrypt_text(key: bytes, text: str, binding: MessageBinding, position: Position | None = None) -> str:
247
+ return seal_message(key, "text", text.encode(), binding, position)
248
+
249
+
250
+ def decrypt_text(key: bytes, encoded: str, binding: MessageBinding) -> str:
251
+ data, _ = open_message(key, encoded, binding, "text")
252
+ try:
253
+ return data.decode()
254
+ except UnicodeDecodeError as error:
255
+ raise DecryptError("Invalid text.") from error
256
+
257
+
258
+ # ------------------------------------------------------------------- chunks
259
+
260
+
261
+ def chunk_iv(index: int, last: bool) -> bytes:
262
+ return bytes(7) + struct.pack(">I", index) + bytes([1 if last else 0])
263
+
264
+
265
+ def chunk_aad(nonce: str, index: int, count: int, flags: int) -> bytes:
266
+ return FILE_CHUNK_LABEL + bytes([0, VERSION, SUITE_AES_GCM, flags]) + _lp(nonce.encode()) + struct.pack(">II", index, count)
267
+
268
+
269
+ def seal_chunk(link_key: bytes, plain: bytes, nonce: str, index: int, count: int) -> bytes:
270
+ last = index == count - 1
271
+ flags = FLAG_LAST_CHUNK if last else 0
272
+ sealed = AESGCM(file_key(link_key, nonce)).encrypt(chunk_iv(index, last), plain, chunk_aad(nonce, index, count, flags))
273
+ return bytes([VERSION, SUITE_AES_GCM, flags]) + sealed
274
+
275
+
276
+ def open_chunk(link_key: bytes, data: bytes, nonce: str, index: int, count: int) -> bytes:
277
+ flags = check_head(data, CHUNK_OVERHEAD)
278
+ last = index == count - 1
279
+ if flags != (FLAG_LAST_CHUNK if last else 0):
280
+ raise DecryptError("The chunk could not be decrypted: wrong key or altered data.")
281
+ try:
282
+ return AESGCM(file_key(link_key, nonce)).decrypt(chunk_iv(index, last), data[HEAD_BYTES:], chunk_aad(nonce, index, count, flags))
283
+ except InvalidTag as error:
284
+ raise DecryptError("The chunk could not be decrypted: wrong key or altered data.") from error
285
+
286
+
287
+ # ------------------------------------------------------- order and deletion
288
+
289
+
290
+ def peek_message(encoded: str) -> tuple[Position, bool]:
291
+ """Who wrote a message envelope, in which place, and whether it is a deletion mark; nothing here is authenticated."""
292
+ data = b64url_decode(encoded)
293
+ flags = check_head(data, MESSAGE_HEAD_BYTES + TAG_BYTES)
294
+ return Position(data[3 : 3 + SENDER_BYTES], struct.unpack(">I", data[11:15])[0]), bool(flags & FLAG_DELETION)
295
+
296
+
297
+ def open_deletion(link_key: bytes, encoded: str, binding: MessageBinding) -> tuple[Position, Position]:
298
+ """The authenticated place of a deletion mark, and the place of the message it removes."""
299
+ data, place = open_message(link_key, encoded, binding, "deletion")
300
+ if len(data) != SENDER_BYTES + SEQ_BYTES:
301
+ raise DecryptError("Invalid deletion mark.")
302
+ return place, Position(data[:SENDER_BYTES], struct.unpack(">I", data[SENDER_BYTES:])[0])
303
+
304
+
305
+ def check_sequence(entries: Iterable[tuple[str, Position, Position | None]]) -> set[str]:
306
+ """``entries`` are (id, place, place it removes if it is a deletion mark) in list order. Returns 'missing', 'repeated'
307
+ and 'reordered' as found: each writing device's numbers must run from 0 without a hole, a repeat or a step backwards,
308
+ and a number a deletion mark covers counts as present."""
309
+ problems: set[str] = set()
310
+ seen_ids: set[str] = set()
311
+ last: dict[bytes, int] = {}
312
+ present: dict[bytes, set[int]] = {}
313
+ for entry_id, place, removes in entries:
314
+ if entry_id in seen_ids:
315
+ continue
316
+ seen_ids.add(entry_id)
317
+ have = present.setdefault(place.sender, set())
318
+ if place.seq in have:
319
+ problems.add("repeated")
320
+ elif place.seq < last.get(place.sender, -1):
321
+ problems.add("reordered")
322
+ have.add(place.seq)
323
+ last[place.sender] = max(last.get(place.sender, -1), place.seq)
324
+ if removes is not None:
325
+ present.setdefault(removes.sender, set()).add(removes.seq)
326
+ for numbers in present.values():
327
+ if numbers and set(range(max(numbers) + 1)) - numbers:
328
+ problems.add("missing")
329
+ return problems