elsehold 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,33 @@
1
+ Metadata-Version: 2.4
2
+ Name: elsehold
3
+ Version: 0.1.0
4
+ Summary: Create, verify, restore and repair Elsehold file-backup fragments offline.
5
+ Author-email: Residual Labs <contact@residual-labs.fr>
6
+ Project-URL: Homepage, https://elsehold.residual-labs.fr/
7
+ Project-URL: Documentation, https://elsehold.residual-labs.fr/a-propos
8
+ Keywords: backup,restore,erasure coding,xor,sha256,offline
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+
12
+ # Elsehold CLI for Python
13
+
14
+ Elsehold makes four backup fragments from one local file. Any three intact, distinct fragments from the same backup can restore the original. The CLI works offline and verifies the reconstructed SHA-256.
15
+
16
+ [Try Elsehold in the browser](https://elsehold.residual-labs.fr/) · [Download the offline HTML](https://elsehold.residual-labs.fr/elsehold.html)
17
+
18
+ ![A file split into four recovery fragments on separate storage locations](https://elsehold.residual-labs.fr/illustrations/01-sauvegarde-repartie.webp)
19
+
20
+ ```sh
21
+ pipx install elsehold
22
+ ```
23
+
24
+ ```sh
25
+ elsehold split photo.jpg --out fragments
26
+ elsehold verify A.ehpart B.ehpart P.ehpart
27
+ elsehold restore A.ehpart B.ehpart P.ehpart --out restored
28
+ elsehold repair C A.ehpart B.ehpart P.ehpart --out replacement
29
+ ```
30
+
31
+ In the last three commands, use the fragment filenames printed by `split`. The output commands refuse to overwrite existing files. The CLI supports files from 1 byte to 32 MiB. Fragments contain plaintext. Place them on storage you trust.
32
+
33
+ The Python build reads and writes the same `.ehpart` v1 format as the browser and Node.js versions. Python 3.10 or later. [Residual Labs](https://residual-labs.fr/)
@@ -0,0 +1,6 @@
1
+ elsehold_cli.py,sha256=yvjXxTBb2E9uIQozP2lnBwyo27hnn3sei0ixrE4raYM,8344
2
+ elsehold-0.1.0.dist-info/METADATA,sha256=S5AhWWgg8M4bh0lse_m7Tw0eX5_YxCd7FgcIzVyR86s,1631
3
+ elsehold-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
4
+ elsehold-0.1.0.dist-info/entry_points.txt,sha256=nv5l681FxGSyGQ3jr9vvGQtT62RF9J-N_Z0qCDd-DZg,47
5
+ elsehold-0.1.0.dist-info/top_level.txt,sha256=VUE44IdtiFY5AyIhzo32H-k05JzQQNuBnUrnXefBYP8,13
6
+ elsehold-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ elsehold = elsehold_cli:main
@@ -0,0 +1 @@
1
+ elsehold_cli
elsehold_cli.py ADDED
@@ -0,0 +1,221 @@
1
+ """Elsehold command line and version-one fragment codec."""
2
+
3
+ import argparse
4
+ from hashlib import sha256
5
+ from itertools import combinations
6
+ import json
7
+ import os
8
+ from pathlib import Path
9
+ import re
10
+ import secrets
11
+ import stat
12
+ import struct
13
+ import sys
14
+ import unicodedata
15
+
16
+
17
+ __version__ = "0.1.0"
18
+ ROLES = ("A", "B", "C", "P")
19
+ MASKS = dict(zip(ROLES, (1, 2, 4, 7)))
20
+ META_KEYS = ("version", "id", "name", "size", "blockSize", "fileHash")
21
+ MAGIC = b"ELSEHOLD"
22
+ MAX_FILE = 32 * 1024 * 1024
23
+ MAX_HEADER = 4096
24
+ MAX_PART = (MAX_FILE + 2) // 3 + MAX_HEADER + 12
25
+ JS_WHITESPACE = "\t\n\v\f\r \u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff"
26
+ UNSAFE = re.compile(r'[\x00-\x1f\x7f\u202a-\u202e\u2066-\u2069<>:"/\\|?*]')
27
+ RESERVED = re.compile(r"^(?:CON|PRN|AUX|NUL|COM[1-9¹²³]|LPT[1-9¹²³])(?:\.|$)", re.IGNORECASE | re.ASCII)
28
+
29
+
30
+ def digest(data):
31
+ return sha256(data).hexdigest()
32
+
33
+
34
+ def safe_name(name):
35
+ name = UNSAFE.sub("_", unicodedata.normalize("NFC", name)).strip(JS_WHITESPACE)
36
+ name = name.strip(". ")[:180].rstrip(". ")
37
+ if RESERVED.match(name):
38
+ name = "_" + name
39
+ return name or "fichier-restaure"
40
+
41
+
42
+ def read_local(path, maximum):
43
+ with path.open("rb") as stream:
44
+ info = os.fstat(stream.fileno())
45
+ if not stat.S_ISREG(info.st_mode) or not 1 <= info.st_size <= maximum:
46
+ raise ValueError(f"Invalid file or size: {path}")
47
+ data = stream.read(info.st_size + 1)
48
+ if len(data) != info.st_size:
49
+ raise ValueError(f"File size changed during reading: {path}")
50
+ return data
51
+
52
+
53
+ def write_new(path, data):
54
+ stream = path.open("xb")
55
+ try:
56
+ with stream:
57
+ stream.write(data)
58
+ except OSError:
59
+ path.unlink()
60
+ raise
61
+
62
+
63
+ def hex_value(value, length):
64
+ return isinstance(value, str) and len(value) == length and re.fullmatch(r"[a-f0-9]+", value)
65
+
66
+
67
+ def read_part(path):
68
+ data = read_local(path, MAX_PART)
69
+ if len(data) < 14 or data[:8] != MAGIC:
70
+ raise ValueError(f"Invalid Elsehold signature: {path}")
71
+ header_size = struct.unpack_from("<I", data, 8)[0]
72
+ offset = 12 + header_size
73
+ if not 2 <= header_size <= MAX_HEADER or offset >= len(data):
74
+ raise ValueError(f"Invalid header length: {path}")
75
+ try:
76
+ header = json.loads(data[12:offset].decode("utf-8-sig"))
77
+ except (UnicodeError, ValueError, RecursionError) as error:
78
+ raise ValueError(f"Unreadable fragment header: {path}") from error
79
+ if not isinstance(header, dict) or type(header.get("version")) is not int or header["version"] != 1:
80
+ raise ValueError(f"Unsupported fragment version: {path}")
81
+ role, name = header.get("role"), header.get("name")
82
+ size, block = header.get("size"), header.get("blockSize")
83
+ if (
84
+ role not in ROLES or type(header.get("mask")) is not int or header["mask"] != MASKS[role]
85
+ or not hex_value(header.get("id"), 32)
86
+ or not hex_value(header.get("fileHash"), 64) or not hex_value(header.get("partHash"), 64)
87
+ or not isinstance(name, str) or name != safe_name(name)
88
+ or type(size) is not int or not 1 <= size <= MAX_FILE
89
+ or type(block) is not int or block != (size + 2) // 3
90
+ ):
91
+ raise ValueError(f"Inconsistent fragment header: {path}")
92
+ payload = data[offset:]
93
+ if len(payload) != block or digest(payload) != header["partHash"]:
94
+ raise ValueError(f"Invalid fragment size or SHA-256: {path}")
95
+ return header, payload
96
+
97
+
98
+ def xor_blocks(blocks, size):
99
+ result = 0
100
+ for block in blocks:
101
+ result ^= int.from_bytes(block, "little")
102
+ return result.to_bytes(size, "little")
103
+
104
+
105
+ def decode(paths):
106
+ first = None
107
+ parts = {}
108
+ for path in paths:
109
+ header, payload = read_part(path)
110
+ meta = {key: header[key] for key in META_KEYS}
111
+ if first is None:
112
+ first = meta
113
+ if first != meta:
114
+ raise ValueError("Fragments are from different backups or have inconsistent headers.")
115
+ role = header["role"]
116
+ if role in parts and parts[role] != payload:
117
+ raise ValueError(f"Conflicting copies of fragment {role}.")
118
+ parts[role] = payload
119
+ if len(parts) < 3:
120
+ raise ValueError("Three distinct, intact fragments from one backup are required.")
121
+ for available in combinations((role for role in ROLES if role in parts), 3):
122
+ selected = {role: parts[role] for role in available}
123
+ missing = next((role for role in ROLES[:3] if role not in selected), None)
124
+ if missing is not None:
125
+ selected[missing] = xor_blocks(selected.values(), first["blockSize"])
126
+ data = b"".join(selected[role] for role in ROLES[:3])[:first["size"]]
127
+ if digest(data) == first["fileHash"]:
128
+ return first, data
129
+ raise ValueError("Restored file SHA-256 does not match.")
130
+
131
+
132
+ def encode(meta, role, payload):
133
+ header = dict(meta, role=role, mask=MASKS[role], partHash=digest(payload))
134
+ packed_header = json.dumps(header, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
135
+ tail = f".{meta['id'][:8]}-{role}.ehpart"
136
+ stem = meta["name"]
137
+ while len((stem + tail).encode("utf-8")) > 240:
138
+ stem = stem[:-1]
139
+ return stem + tail, MAGIC + struct.pack("<I", len(packed_header)) + packed_header + payload
140
+
141
+
142
+ def make_parts(data, meta, roles):
143
+ size = meta["blockSize"]
144
+ chunks = [data[i * size:(i + 1) * size].ljust(size, b"\x00") for i in range(3)]
145
+ blocks = dict(zip(ROLES, chunks))
146
+ if "P" in roles:
147
+ blocks["P"] = xor_blocks(chunks, size)
148
+ return [encode(meta, role, blocks[role]) for role in roles]
149
+
150
+
151
+ def export_parts(parts, directory):
152
+ directory.mkdir(parents=True, exist_ok=True)
153
+ paths = []
154
+ try:
155
+ for name, payload in parts:
156
+ path = directory / name
157
+ write_new(path, payload)
158
+ paths.append(path)
159
+ except OSError:
160
+ for path in paths:
161
+ path.unlink()
162
+ raise
163
+ for path in paths:
164
+ print(path)
165
+
166
+
167
+ def main(argv=None):
168
+ parser = argparse.ArgumentParser(
169
+ prog="elsehold",
170
+ description="Create, verify, restore and repair Elsehold fragments offline.",
171
+ epilog="Fragments contain plaintext. File size limit: 32 MiB.",
172
+ )
173
+ parser.add_argument("--version", action="version", version=__version__)
174
+ subs = parser.add_subparsers(dest="command")
175
+ split = subs.add_parser("split", help="create four fragments")
176
+ split.add_argument("file", type=Path)
177
+ split.add_argument("--out", type=Path, required=True)
178
+ for command, help_text in (
179
+ ("verify", "verify the reconstructed file against its SHA-256"),
180
+ ("restore", "restore a file from its fragments"),
181
+ ("repair", "recreate one role from a verified file"),
182
+ ):
183
+ sub = subs.add_parser(command, help=help_text)
184
+ if command == "repair":
185
+ sub.add_argument("role", choices=ROLES)
186
+ sub.add_argument("parts", nargs="+", type=Path)
187
+ if command != "verify":
188
+ sub.add_argument("--out", type=Path, required=True)
189
+ args = parser.parse_args(argv)
190
+ if not args.command:
191
+ parser.print_help()
192
+ return 0
193
+ try:
194
+ if args.command == "split":
195
+ data = read_local(args.file, MAX_FILE)
196
+ meta = {
197
+ "version": 1, "id": secrets.token_hex(16), "name": safe_name(args.file.name),
198
+ "size": len(data), "blockSize": (len(data) + 2) // 3, "fileHash": digest(data),
199
+ }
200
+ export_parts(make_parts(data, meta, ROLES), args.out)
201
+ else:
202
+ if not 3 <= len(args.parts) <= 4:
203
+ raise ValueError("Supply three or four fragment files.")
204
+ meta, data = decode(args.parts)
205
+ if args.command == "verify":
206
+ print(f"{meta['fileHash']} {meta['name']}")
207
+ elif args.command == "restore":
208
+ args.out.mkdir(parents=True, exist_ok=True)
209
+ output = args.out / meta["name"]
210
+ write_new(output, data)
211
+ print(output)
212
+ else:
213
+ export_parts(make_parts(data, meta, (args.role,)), args.out)
214
+ except (OSError, ValueError) as error:
215
+ print(f"elsehold: {error}", file=sys.stderr)
216
+ return 1
217
+ return 0
218
+
219
+
220
+ if __name__ == "__main__":
221
+ sys.exit(main())