batonpass-cli 0.5.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,55 @@
1
+ """Getting prose out of a stored body.
2
+
3
+ Some sources store a message as a JSON envelope rather than as text — billion
4
+ keeps `{"id":...,"role":"user","contentType":"text","text":"..."}` — and the
5
+ envelope sometimes escapes its newlines twice, so a reader sees `\\n` where a
6
+ human wrote a line break.
7
+
8
+ We unwrap at read time rather than rewrite the library, because rewriting would
9
+ mean re-archiving every source and every stored hash along with it. The rule is
10
+ narrow on purpose: only an object that actually carries a text-ish field is
11
+ unwrapped, so a tool result that happens to be JSON is left exactly as it is.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+
18
+ TEXT_KEYS = ("text", "content", "body", "message", "value", "prompt")
19
+ MAX_DEPTH = 3
20
+
21
+
22
+ def unwrap(text, depth: int = 0) -> str:
23
+ if not isinstance(text, str):
24
+ return text or ""
25
+ stripped = text.strip()
26
+ if not stripped or stripped[0] not in "{[" or depth >= MAX_DEPTH:
27
+ return text
28
+ try:
29
+ obj = json.loads(stripped)
30
+ except ValueError:
31
+ return text
32
+ if isinstance(obj, list) and obj and all(isinstance(x, str) for x in obj):
33
+ return "\n".join(obj)
34
+ if not isinstance(obj, dict):
35
+ return text
36
+ for key in TEXT_KEYS:
37
+ value = obj.get(key)
38
+ if isinstance(value, str) and value.strip():
39
+ return unescape(unwrap(value, depth + 1))
40
+ return text
41
+
42
+
43
+ def unescape(text: str) -> str:
44
+ """Undo a second round of escaping (`\\n` printed literally)."""
45
+ if not text:
46
+ return text
47
+ if "\\n" in text or "\\t" in text:
48
+ text = text.replace("\\r\\n", "\n").replace("\\n", "\n").replace("\\t", "\t")
49
+ return text
50
+
51
+
52
+ def clean(text) -> str:
53
+ # Order matters: unescaping first would rewrite `\n` *inside* the JSON
54
+ # string literal, which leaves invalid JSON and no prose at all.
55
+ return unescape(unwrap(text if isinstance(text, str) else (text or "")))
@@ -0,0 +1,92 @@
1
+ """All writes go through here, and all of them are INSERT OR IGNORE.
2
+
3
+ That single rule is why `archive` can be run a hundred times: the second run
4
+ produces zero new rows, and a half-finished run is simply resumed.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import sqlite3
10
+ from datetime import datetime, timezone
11
+
12
+ from .content import sha256_bytes, sha256_text
13
+
14
+
15
+ def now_iso() -> str:
16
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
17
+
18
+
19
+ def upsert_raw_source(conn, source_sha, device, adapter, adapter_ver, path, nbytes):
20
+ conn.execute(
21
+ "INSERT OR IGNORE INTO raw_source"
22
+ "(source_sha,device,adapter,adapter_ver,path,bytes,first_seen) VALUES(?,?,?,?,?,?,?)",
23
+ (source_sha, device, adapter, adapter_ver, path, nbytes, now_iso()),
24
+ )
25
+
26
+
27
+ def put_raw_record(conn, source_sha, seq, kind, payload_sha, codec_name="none") -> bool:
28
+ """The raw layer is content-addressed through `content` too.
29
+
30
+ Storing the payload inline looks simpler and is much worse: re-archiving a
31
+ source after its app touched the file would duplicate every byte, because
32
+ the source identity includes the file's mtime. With the payload living in
33
+ `content`, a second pass costs a refcount bump.
34
+ """
35
+ cur = conn.execute(
36
+ "INSERT OR IGNORE INTO raw_record(source_sha,seq,kind,payload,payload_sha,codec) "
37
+ "VALUES(?,?,?,?,?,?)",
38
+ (source_sha, seq, kind, None, payload_sha, codec_name),
39
+ )
40
+ return cur.rowcount > 0
41
+
42
+
43
+ def upsert_session(conn, row: dict) -> bool:
44
+ cur = conn.execute(
45
+ "INSERT OR IGNORE INTO session"
46
+ "(sid,source,source_sid,device,project_key,project_key_tier,cwd,title,created_at,updated_at,"
47
+ " msg_count,first_msg_at,last_msg_at,forked_from,artifact_refs,adapter_ver,content_hash)"
48
+ " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
49
+ (row.get("sid"), row.get("source"), row.get("source_sid"), row.get("device"),
50
+ row.get("project_key"), row.get("project_key_tier"), row.get("cwd"), row.get("title"),
51
+ row.get("created_at"), row.get("updated_at"), row.get("msg_count", 0),
52
+ row.get("first_msg_at"), row.get("last_msg_at"), row.get("forked_from"),
53
+ row.get("artifact_refs"), row.get("adapter_ver"), row.get("content_hash")),
54
+ )
55
+ return cur.rowcount > 0
56
+
57
+
58
+ def put_message(conn, mid, sid, seq, role, text_sha, model=None, ts=None, meta_json=None) -> bool:
59
+ cur = conn.execute(
60
+ "INSERT OR IGNORE INTO message(mid,sid,seq,role,text_sha,model,ts,meta_json) "
61
+ "VALUES(?,?,?,?,?,?,?,?)",
62
+ (mid, sid, seq, role, text_sha, model, ts, meta_json),
63
+ )
64
+ return cur.rowcount > 0
65
+
66
+
67
+ def put_part(conn, pid, mid, seq, kind, name=None, args_sha=None, result_sha=None,
68
+ is_error=0, ts=None) -> bool:
69
+ cur = conn.execute(
70
+ "INSERT OR IGNORE INTO part(pid,mid,seq,kind,name,args_sha,result_sha,is_error,ts) "
71
+ "VALUES(?,?,?,?,?,?,?,?,?)",
72
+ (pid, mid, seq, kind, name, args_sha, result_sha, 1 if is_error else 0, ts),
73
+ )
74
+ return cur.rowcount > 0
75
+
76
+
77
+ def session_key(source, source_sid, device) -> str:
78
+ return sha256_text("session|%s|%s|%s" % (source, device, source_sid))[:32]
79
+
80
+
81
+ def message_key(sid, seq) -> str:
82
+ return sha256_text("message|%s|%d" % (sid, seq))[:32]
83
+
84
+
85
+ def part_key(mid, seq) -> str:
86
+ return sha256_text("part|%s|%d" % (mid, seq))[:32]
87
+
88
+
89
+ def session_content_hash(conn, sid) -> str:
90
+ """Hash of the ordered message-text hashes — the cheap change detector."""
91
+ rows = conn.execute("SELECT text_sha FROM message WHERE sid=? ORDER BY seq", (sid,)).fetchall()
92
+ return sha256_text("".join((r[0] or "") for r in rows)) if rows else ""
@@ -0,0 +1,15 @@
1
+ """Tiered, append-only sync between machines.
2
+
3
+ A channel is a folder: a shared mount, a git remote, a USB stick, or a relay
4
+ mailbox. Each device writes only its own stream, so there is no lock, no
5
+ leader, and no merge. Pull is a resumable tail read, and the library stays
6
+ fully queryable while the channel is offline.
7
+ """
8
+
9
+ from .channel import device_name, init_channel, is_channel
10
+ from .pull import pull
11
+ from .push import push
12
+ from .status import status
13
+
14
+ __all__ = ["device_name", "init_channel", "is_channel",
15
+ "push", "pull", "status"]
@@ -0,0 +1,213 @@
1
+ """A channel is just a folder. Three transports fall out of that:
2
+
3
+ * a directory (a shared mount, an SSHFS, a USB stick),
4
+ * a git remote (push/pull the folder),
5
+ * a relay mailbox (the folder lives on the relay).
6
+
7
+ There is no server in the loop and no process to keep alive. If the folder is
8
+ reachable right now, sync works; if it isn't, everything already pulled stays
9
+ queryable, because the library is local.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import os
16
+ import socket
17
+ import uuid
18
+ from datetime import datetime, timezone
19
+
20
+ from . import wire
21
+
22
+ MARKER = "batonpass-channel.json"
23
+ SCHEMA = 1
24
+
25
+
26
+ def now_iso() -> str:
27
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
28
+
29
+
30
+ def device_name() -> str:
31
+ return os.environ.get("BATONPASS_DEVICE") or socket.gethostname().split(".")[0]
32
+
33
+
34
+ def _atomic_json(path, obj):
35
+ os.makedirs(os.path.dirname(path), exist_ok=True)
36
+ tmp = path + ".tmp%d" % os.getpid()
37
+ with open(tmp, "w", encoding="utf-8") as fh:
38
+ json.dump(obj, fh, ensure_ascii=False, indent=1, sort_keys=True)
39
+ fh.flush()
40
+ os.fsync(fh.fileno())
41
+ os.replace(tmp, path)
42
+
43
+
44
+ def init_channel(path: str, device: str = None) -> dict:
45
+ path = os.path.abspath(os.path.expanduser(path))
46
+ for sub in ("devices", "stream", "heads", "blobs"):
47
+ os.makedirs(os.path.join(path, sub), exist_ok=True)
48
+ marker = os.path.join(path, MARKER)
49
+ info = {"schema": SCHEMA, "created_at": now_iso(), "kind": "batonpass-channel"}
50
+ if not os.path.exists(marker):
51
+ info["id"] = uuid.uuid4().hex
52
+ _atomic_json(marker, info)
53
+ else:
54
+ with open(marker, encoding="utf-8") as fh:
55
+ try:
56
+ info = json.load(fh)
57
+ except ValueError:
58
+ info = {}
59
+ if not info.get("id"): # a channel from before ids
60
+ info["id"] = uuid.uuid4().hex
61
+ info.setdefault("schema", SCHEMA)
62
+ info.setdefault("created_at", now_iso())
63
+ info["kind"] = info.get("kind") or "batonpass-channel"
64
+ _atomic_json(marker, info)
65
+ if device:
66
+ heartbeat(path, device)
67
+ return {"path": path, "id": info["id"], "schema": info.get("schema", SCHEMA),
68
+ "created_at": info.get("created_at")}
69
+
70
+
71
+ def identity(path: str) -> str:
72
+ """The channel's own id, not its path.
73
+
74
+ Push watermarks are keyed by this, so a deleted or re-created channel
75
+ folder is recognised as a *different* channel and everything is pushed
76
+ again. Keying by path would have a library insist it had already sent
77
+ 713 sessions into an empty directory.
78
+ """
79
+ marker = os.path.join(os.path.abspath(os.path.expanduser(path)), MARKER)
80
+ try:
81
+ with open(marker, encoding="utf-8") as fh:
82
+ return json.load(fh).get("id") or ""
83
+ except (OSError, ValueError):
84
+ return ""
85
+
86
+
87
+ def is_channel(path: str) -> bool:
88
+ return os.path.exists(os.path.join(os.path.expanduser(path), MARKER))
89
+
90
+
91
+ def heartbeat(channel: str, device: str, extra: dict = None) -> dict:
92
+ """Per-device own file, rewritten in place — never a shared index."""
93
+ path = os.path.join(channel, "devices", "%s.json" % device)
94
+ prev = {}
95
+ if os.path.exists(path):
96
+ try:
97
+ with open(path, encoding="utf-8") as fh:
98
+ prev = json.load(fh)
99
+ except ValueError:
100
+ prev = {}
101
+ info = {
102
+ "device": device,
103
+ "hostname": socket.gethostname(),
104
+ "first_seen": prev.get("first_seen") or now_iso(),
105
+ "last_seen": now_iso(),
106
+ "pushes": int(prev.get("pushes") or 0) + 1,
107
+ "batonpass": (extra or {}).get("version") or prev.get("batonpass"),
108
+ "counts": (extra or {}).get("counts") or prev.get("counts"),
109
+ }
110
+ _atomic_json(path, info)
111
+ return info
112
+
113
+
114
+ def devices(channel: str) -> list:
115
+ out = []
116
+ ddir = os.path.join(channel, "devices")
117
+ if not os.path.isdir(ddir):
118
+ return out
119
+ for name in sorted(os.listdir(ddir)):
120
+ if not name.endswith(".json"):
121
+ continue
122
+ try:
123
+ with open(os.path.join(ddir, name), encoding="utf-8") as fh:
124
+ out.append(json.load(fh))
125
+ except (ValueError, OSError):
126
+ continue
127
+ return out
128
+
129
+
130
+ def write_head(channel: str, device: str, tier: str, stats: dict) -> dict:
131
+ """Each tier's own head file: how far this device has written, and its hash."""
132
+ path = os.path.join(channel, "heads", "%s.%s.json" % (device, tier))
133
+ prev = read_head(channel, device, tier)
134
+ head = {
135
+ "device": device,
136
+ "tier": tier,
137
+ "gen": int(prev.get("gen") or 0),
138
+ "lines": int(prev.get("lines") or 0) + int(stats.get("lines") or 0),
139
+ "bytes": wire.stream_bytes(channel, device, tier),
140
+ "live_bytes": int(prev.get("live_bytes") or 0),
141
+ "updated": now_iso(),
142
+ }
143
+ _atomic_json(path, head)
144
+ return head
145
+
146
+
147
+ def read_head(channel: str, device: str, tier: str) -> dict:
148
+ path = os.path.join(channel, "heads", "%s.%s.json" % (device, tier))
149
+ try:
150
+ with open(path, encoding="utf-8") as fh:
151
+ return json.load(fh)
152
+ except (OSError, ValueError):
153
+ return {}
154
+
155
+
156
+ # A stream is allowed to grow before it gets rewritten. Rewriting on every push
157
+ # would mean fsyncing the whole file every time; the point is to stop unbounded
158
+ # growth, not to keep the file minimal.
159
+ COMPACT_MIN = {"t0": 512 * 1024, "t1": 4 * 1024 * 1024, "t2": 32 * 1024 * 1024}
160
+
161
+
162
+ def compact(channel: str, device: str, tier: str, force: bool = False) -> dict:
163
+ """Rewrite one device's stream as the set of facts it describes.
164
+
165
+ The generation goes up, so every reader's offset — which is keyed on the
166
+ generation — stops applying and the file is re-read from zero. Re-reading
167
+ is safe by construction: imports are idempotent.
168
+ """
169
+ head = read_head(channel, device, tier)
170
+ size = wire.stream_bytes(channel, device, tier)
171
+ out = {"device": device, "tier": tier, "before": size, "after": size,
172
+ "gen": int(head.get("gen") or 0), "compacted": False}
173
+ if not os.path.exists(wire.stream_path(channel, device, tier)):
174
+ out["reason"] = "empty" # never a head file for a file that isn't there
175
+ return out
176
+ if not force:
177
+ if size <= COMPACT_MIN.get(tier, 4 * 1024 * 1024):
178
+ out["reason"] = "small"
179
+ return out
180
+ live = int(head.get("live_bytes") or 0)
181
+ if live and size < 2 * live:
182
+ out["reason"] = "not worth it yet"
183
+ return out
184
+ res = wire.compact_stream(channel, device, tier)
185
+ head = {
186
+ "device": device, "tier": tier,
187
+ "gen": int(head.get("gen") or 0) + 1,
188
+ "lines": res["lines_after"],
189
+ "bytes": res["after"],
190
+ "live_bytes": res["after"],
191
+ "compacted_at": now_iso(),
192
+ "updated": now_iso(),
193
+ }
194
+ _atomic_json(os.path.join(channel, "heads", "%s.%s.json" % (device, tier)), head)
195
+ out.update({"after": res["after"], "gen": head["gen"], "compacted": True,
196
+ "lines_before": res["lines_before"], "lines_after": res["lines_after"]})
197
+ return out
198
+
199
+
200
+ def read_heads(channel: str) -> list:
201
+ out = []
202
+ hdir = os.path.join(channel, "heads")
203
+ if not os.path.isdir(hdir):
204
+ return out
205
+ for name in sorted(os.listdir(hdir)):
206
+ if not name.endswith(".json"):
207
+ continue
208
+ try:
209
+ with open(os.path.join(hdir, name), encoding="utf-8") as fh:
210
+ out.append(json.load(fh))
211
+ except (ValueError, OSError):
212
+ continue
213
+ return out
@@ -0,0 +1,216 @@
1
+ """A channel is a folder on someone else's disk.
2
+
3
+ The whole point of the channel design is that you can put it on a cloud drive, a
4
+ shared volume or a USB stick. That is also the whole reason it needs this file:
5
+ whatever that drive's operator can read, they can read. So the payload is sealed
6
+ before it is written, and the channel marker says so.
7
+
8
+ What is sealed: every blob — message bodies, tool calls, the bulk of the bytes.
9
+ What is not: the catalog lines themselves (`stream/*/t0.jsonl`), because that is
10
+ where the dedupe keys live and objects have to stay comparable for compaction to
11
+ work. So an operator of the drive learns *that* you had 713 sessions with these
12
+ titles on these dates, not what was said in them. That is a real, small leak and
13
+ it is stated here rather than implied away.
14
+
15
+ Addressing stays on the plaintext sha256, so idempotency survives. The trade is
16
+ that someone holding a known plaintext can confirm it is in the channel — a
17
+ content-confirmation leak, not a content leak.
18
+
19
+ The key never goes into the channel. It comes from `BATONPASS_KEY`, or from
20
+ `~/.batonpass/key` (first line, mode 600). The salt is public and per-channel.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import base64
26
+ import hashlib
27
+ import hmac
28
+ import json
29
+ import os
30
+
31
+ MAGIC = b"BPC1"
32
+ ALGO = "aes-256-gcm"
33
+ SALT_BYTES = 16
34
+ _SCRYPT = dict(n=2 ** 14, r=8, p=1, maxmem=64 * 1024 * 1024, dklen=32)
35
+ _cache = {}
36
+
37
+
38
+ def available() -> bool:
39
+ try:
40
+ import cryptography # noqa: F401
41
+ return True
42
+ except ImportError:
43
+ return False
44
+
45
+
46
+ def _marker_path(channel: str) -> str:
47
+ from .channel import MARKER
48
+ return os.path.join(channel, MARKER)
49
+
50
+
51
+ def marker(channel: str) -> dict:
52
+ try:
53
+ with open(_marker_path(channel), encoding="utf-8") as fh:
54
+ return json.load(fh)
55
+ except (OSError, ValueError):
56
+ return {}
57
+
58
+
59
+ def enabled(channel: str) -> bool:
60
+ return marker(channel).get("enc") == ALGO
61
+
62
+
63
+ def new_salt() -> bytes:
64
+ return os.urandom(SALT_BYTES)
65
+
66
+
67
+ def _passphrase(required: bool) -> str:
68
+ text = (os.environ.get("BATONPASS_KEY") or "").strip()
69
+ if not text:
70
+ path = os.path.expanduser("~/.batonpass/key")
71
+ try:
72
+ with open(path, encoding="utf-8") as fh:
73
+ text = fh.readline().strip()
74
+ except OSError:
75
+ text = ""
76
+ if not text and required:
77
+ raise RuntimeError(
78
+ "this channel is encrypted; set BATONPASS_KEY (or put the passphrase "
79
+ "on the first line of ~/.batonpass/key)")
80
+ return text
81
+
82
+
83
+ def derive(passphrase: str, salt: bytes) -> bytes:
84
+ """scrypt, because a passphrase that travels through a cloud drive is a
85
+ passphrase that gets copied to a worse disk than the one it was typed on.
86
+
87
+ Via `cryptography`'s own binding rather than `hashlib.scrypt`: Apple's
88
+ system Python is built without it, and a key-derivation function that works
89
+ on one machine and not the next is exactly the class of bug this project
90
+ exists to avoid.
91
+ """
92
+ try:
93
+ from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
94
+ except ImportError: # pragma: no cover - crypto is required
95
+ return hashlib.scrypt(passphrase.encode("utf-8"), salt=salt,
96
+ n=_SCRYPT["n"], r=_SCRYPT["r"], p=_SCRYPT["p"],
97
+ dklen=_SCRYPT["dklen"])
98
+ return Scrypt(salt=salt, length=_SCRYPT["dklen"], n=_SCRYPT["n"],
99
+ r=_SCRYPT["r"], p=_SCRYPT["p"]).derive(passphrase.encode("utf-8"))
100
+
101
+
102
+ def key_for(channel: str):
103
+ """The channel's key, or None when the channel is not encrypted."""
104
+ info = marker(channel)
105
+ if info.get("enc") != ALGO:
106
+ return None
107
+ salt_hex = info.get("salt") or ""
108
+ if not salt_hex:
109
+ raise RuntimeError("channel says it is encrypted but carries no salt; "
110
+ "re-run `sync init` with the same passphrase")
111
+ passphrase = _passphrase(required=True)
112
+ tag = (salt_hex, passphrase)
113
+ if tag not in _cache:
114
+ _cache[tag] = derive(passphrase, bytes.fromhex(salt_hex))
115
+ return _cache[tag]
116
+
117
+
118
+ def seal(channel: str, data: bytes) -> bytes:
119
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
120
+
121
+ key = key_for(channel)
122
+ if key is None:
123
+ return data
124
+ nonce = os.urandom(12)
125
+ return MAGIC + nonce + AESGCM(key).encrypt(nonce, data, MAGIC)
126
+
127
+
128
+ def open_(channel: str, blob: bytes):
129
+ """Plaintext of a blob, or None if it cannot be opened with this key."""
130
+ if not blob.startswith(MAGIC):
131
+ return blob # written before the channel was sealed
132
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
133
+
134
+ try:
135
+ key = key_for(channel)
136
+ except RuntimeError:
137
+ return None
138
+ nonce, body = blob[len(MAGIC):len(MAGIC) + 12], blob[len(MAGIC) + 12:]
139
+ try:
140
+ return AESGCM(key).decrypt(nonce, body, MAGIC)
141
+ except Exception:
142
+ return None
143
+
144
+
145
+ def sealed_with(channel: str, blob: bytes) -> bool:
146
+ return blob.startswith(MAGIC)
147
+
148
+
149
+ # ── turning it on ─────────────────────────────────────────────────
150
+
151
+ def enable(channel: str) -> dict:
152
+ """Mark a channel encrypted and seal whatever blobs are already in it."""
153
+ if not available():
154
+ raise RuntimeError('encryption needs one optional dependency: '
155
+ 'pip install "batonpass-cli[crypto]"')
156
+ _passphrase(required=True)
157
+ info = marker(channel)
158
+ if info.get("enc") == ALGO:
159
+ return {"already": True, "sealed": 0, "skipped": 0}
160
+ if not info.get("salt"):
161
+ info["salt"] = new_salt().hex()
162
+ info["enc"] = ALGO
163
+ info["enc_at"] = _now()
164
+ tmp = _marker_path(channel) + ".tmp"
165
+ with open(tmp, "w", encoding="utf-8") as fh:
166
+ json.dump(info, fh, ensure_ascii=False, indent=1, sort_keys=True)
167
+ fh.flush()
168
+ os.fsync(fh.fileno())
169
+ os.replace(tmp, _marker_path(channel)) # key must exist before sealing
170
+ return {"already": False, "sealed": _seal_existing(channel), "skipped": 0}
171
+
172
+
173
+ def _seal_existing(channel: str) -> int:
174
+ root = os.path.join(channel, "blobs")
175
+ if not os.path.isdir(root):
176
+ return 0
177
+ n = 0
178
+ for sub in os.listdir(root):
179
+ ddir = os.path.join(root, sub)
180
+ if not os.path.isdir(ddir):
181
+ continue
182
+ for name in os.listdir(ddir):
183
+ path = os.path.join(ddir, name)
184
+ if name.endswith(".tmp") or not os.path.isfile(path):
185
+ continue
186
+ with open(path, "rb") as fh:
187
+ raw = fh.read()
188
+ if sealed_with(channel, raw):
189
+ continue
190
+ sealed = seal(channel, raw)
191
+ tmp = path + ".tmp%d" % os.getpid()
192
+ with open(tmp, "wb") as fh:
193
+ fh.write(sealed)
194
+ fh.flush()
195
+ os.fsync(fh.fileno())
196
+ os.replace(tmp, path)
197
+ n += 1
198
+ return n
199
+
200
+
201
+ def fingerprint(channel: str) -> str:
202
+ """Eight hex chars of the key — enough to tell two passphrases apart, not
203
+ enough to be worth attacking."""
204
+ key = key_for(channel)
205
+ if key is None:
206
+ return ""
207
+ return hmac.new(b"batonpass-fingerprint", key, hashlib.sha256).hexdigest()[:8]
208
+
209
+
210
+ def _now() -> str:
211
+ from .channel import now_iso
212
+ return now_iso()
213
+
214
+
215
+ def b64(b: bytes) -> str: # pragma: no cover - debugging aid
216
+ return base64.b64encode(b).decode("ascii")