liaison-sync 0.2.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.
- liaison/__init__.py +3 -0
- liaison/account.py +615 -0
- liaison/account_proto.py +371 -0
- liaison/account_server.py +684 -0
- liaison/account_store.py +86 -0
- liaison/autosave.py +542 -0
- liaison/capture.py +714 -0
- liaison/chatimport.py +204 -0
- liaison/cli.py +1110 -0
- liaison/conversations.py +229 -0
- liaison/cursor.py +265 -0
- liaison/exchange.py +262 -0
- liaison/handoff.py +192 -0
- liaison/identity.py +194 -0
- liaison/locate.py +138 -0
- liaison/mail.py +253 -0
- liaison/migrate.py +223 -0
- liaison/notes.py +124 -0
- liaison/opencode.py +159 -0
- liaison/registry.py +130 -0
- liaison/relay_client.py +238 -0
- liaison/relay_proto.py +285 -0
- liaison/relay_server.py +1228 -0
- liaison/relay_testsupport.py +112 -0
- liaison/relaysync.py +706 -0
- liaison/report.py +307 -0
- liaison/retrieval.py +143 -0
- liaison/rotation.py +333 -0
- liaison/schema.py +224 -0
- liaison/server.py +621 -0
- liaison/setup.py +499 -0
- liaison/store.py +356 -0
- liaison/sync.py +408 -0
- liaison/transport.py +181 -0
- liaison_sync-0.2.0.dist-info/METADATA +278 -0
- liaison_sync-0.2.0.dist-info/RECORD +39 -0
- liaison_sync-0.2.0.dist-info/WHEEL +5 -0
- liaison_sync-0.2.0.dist-info/entry_points.txt +5 -0
- liaison_sync-0.2.0.dist-info/top_level.txt +1 -0
liaison/__init__.py
ADDED
liaison/account.py
ADDED
|
@@ -0,0 +1,615 @@
|
|
|
1
|
+
"""The account flows a person actually runs: sign up, sign in, recover, revoke.
|
|
2
|
+
|
|
3
|
+
This module owns the order of operations. The relay enforces the rules, the
|
|
4
|
+
crypto lives in account_proto, and sync keeps using relaysync; here those three
|
|
5
|
+
are put together so a half-finished setup cannot look like a finished one.
|
|
6
|
+
|
|
7
|
+
The two setup paths differ in what they carry:
|
|
8
|
+
|
|
9
|
+
sign up makes a new group key on this device, claims the new vault for the
|
|
10
|
+
account, and seals the key under a recovery phrase shown once.
|
|
11
|
+
recover proves the phrase to the relay, receives the sealed key, opens it
|
|
12
|
+
here, and writes the sync configuration from it.
|
|
13
|
+
log in proves the password and enrols this device, but carries no key.
|
|
14
|
+
A device with no key gets one from `sync add` / `sync join`, or from
|
|
15
|
+
`account recover`. That is deliberate: a password reset should not
|
|
16
|
+
hand anyone the content key.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import contextlib
|
|
22
|
+
import os
|
|
23
|
+
import platform as _platform
|
|
24
|
+
import secrets
|
|
25
|
+
import socket
|
|
26
|
+
import time
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
from typing import Optional
|
|
29
|
+
|
|
30
|
+
from . import account_store, relaysync
|
|
31
|
+
from . import sync as foldersync
|
|
32
|
+
from .account_proto import (
|
|
33
|
+
device_auth, has_enc_key, new_device, new_enc_key, new_recovery_phrase, normalize_email,
|
|
34
|
+
parse_recovery_phrase, recovery_key, recovery_verifier, sign_claim,
|
|
35
|
+
unwrap_group_key, valid_password, wrap_group_key,
|
|
36
|
+
)
|
|
37
|
+
from .relay_client import Http, RelayError, RelayUnavailable, default_relay
|
|
38
|
+
from .relay_proto import b64d, b64e, derive_keys
|
|
39
|
+
|
|
40
|
+
AccountError = foldersync.SyncError
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _relay(value: str = "") -> str:
|
|
44
|
+
relay = (value or default_relay()).strip().rstrip("/")
|
|
45
|
+
if not relay:
|
|
46
|
+
raise AccountError("No relay is configured. Set LIAISON_RELAY, or pass --relay URL.")
|
|
47
|
+
return relay
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _device(name: str = "", platform: str = "") -> dict:
|
|
51
|
+
return new_device(name or socket.gethostname(), platform or _platform.system())
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _device_for(existing: Optional[dict], name: str = "", platform: str = "") -> dict:
|
|
55
|
+
"""Keep the key this machine already has, so signing in again is not a new device."""
|
|
56
|
+
if existing and existing.get("private_key") and existing.get("public_key"):
|
|
57
|
+
out = {
|
|
58
|
+
"device": existing["device"],
|
|
59
|
+
"private_key": existing["private_key"],
|
|
60
|
+
"public_key": existing["public_key"],
|
|
61
|
+
"name": name or existing.get("name", ""),
|
|
62
|
+
"platform": platform or existing.get("platform", ""),
|
|
63
|
+
}
|
|
64
|
+
if has_enc_key(existing):
|
|
65
|
+
out["enc_private_key"] = existing["enc_private_key"]
|
|
66
|
+
out["enc_public_key"] = existing["enc_public_key"]
|
|
67
|
+
else:
|
|
68
|
+
# Enrolled before key rotation existed: add the key it will receive on.
|
|
69
|
+
out["enc_private_key"], out["enc_public_key"] = new_enc_key()
|
|
70
|
+
return out
|
|
71
|
+
return _device(name, platform)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _payload(device: dict) -> dict:
|
|
75
|
+
return {"pub": device["public_key"], "name": device["name"], "platform": device["platform"],
|
|
76
|
+
"enc_pub": device["enc_public_key"]}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _http(relay: str, timeout: float = 30) -> Http:
|
|
80
|
+
return Http(relay, timeout=timeout)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _save_account(data: dict, root: Optional[Path] = None) -> dict:
|
|
84
|
+
data["updated"] = int(time.time())
|
|
85
|
+
account_store.save(data, root)
|
|
86
|
+
return data
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _sync_config(relay: str, key: bytes) -> dict:
|
|
90
|
+
return {"transport": "relay", "relay": relay, "device": secrets.token_hex(4),
|
|
91
|
+
"key": b64e(key), "cursor": 0, "exclude": [], "last_sync": "", "last_error": ""}
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _msg(exc: Exception) -> str:
|
|
95
|
+
"""The relay's message, without sync's promise where nothing will be retried."""
|
|
96
|
+
message = str(exc)
|
|
97
|
+
if isinstance(exc, RelayUnavailable):
|
|
98
|
+
message = message.replace("Nothing is lost; sync will catch up when it is reachable.",
|
|
99
|
+
"Nothing was changed. Check the address and your connection, "
|
|
100
|
+
"then run the command again.")
|
|
101
|
+
return message
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _enrolment_error(exc: Exception) -> str:
|
|
105
|
+
message = _msg(exc)
|
|
106
|
+
if "removed from the account" in message:
|
|
107
|
+
message += (" Run `liaison account logout` on this machine, then sign in or recover "
|
|
108
|
+
"again to get a new device key. Signing out deletes this machine's copy "
|
|
109
|
+
"of the vault key, so recover the vault with your phrase afterwards if "
|
|
110
|
+
"you still need it.")
|
|
111
|
+
return message
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _account_file(device: dict, relay: str, data: dict, vault: str = "") -> dict:
|
|
115
|
+
return {
|
|
116
|
+
"account": data["account"],
|
|
117
|
+
"email": data["email"],
|
|
118
|
+
"device": device["device"],
|
|
119
|
+
"public_key": device["public_key"],
|
|
120
|
+
"private_key": device["private_key"],
|
|
121
|
+
"enc_public_key": device["enc_public_key"],
|
|
122
|
+
"enc_private_key": device["enc_private_key"],
|
|
123
|
+
"relay": relay,
|
|
124
|
+
"vault": vault,
|
|
125
|
+
"name": device["name"],
|
|
126
|
+
"platform": device["platform"],
|
|
127
|
+
"created": int(time.time()),
|
|
128
|
+
"recovery": bool(data.get("recovery")),
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _require_email(email: Optional[str]) -> str:
|
|
133
|
+
if not email:
|
|
134
|
+
raise AccountError("That does not look like an email address.")
|
|
135
|
+
return email
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _require_password(value: object) -> str:
|
|
139
|
+
if not valid_password(value):
|
|
140
|
+
raise AccountError("A password needs at least 10 characters.")
|
|
141
|
+
return str(value)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
RESEND = "\0resend" # what a code prompt returns to ask for a new code
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class VerificationPending(AccountError):
|
|
148
|
+
"""The relay mailed a code and none was given. The sign-up is saved and can be finished."""
|
|
149
|
+
|
|
150
|
+
def __init__(self, email: str, ttl: int = 900):
|
|
151
|
+
self.email, self.ttl = email, ttl
|
|
152
|
+
super().__init__(f"A verification code was sent to {email}; it expires in {max(ttl // 60, 1)} "
|
|
153
|
+
f"minutes. Finish with `liaison account verify -e {email}`, or run "
|
|
154
|
+
"`liaison account signup` again for a new code.")
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def signup(email: str, password: str, relay: str = "", root: Optional[Path] = None,
|
|
158
|
+
name: str = "", platform: str = "", invite: str = "", code=None) -> dict:
|
|
159
|
+
"""Create an account, its first device, and the vault it owns.
|
|
160
|
+
|
|
161
|
+
A relay that checks email addresses answers that a code was mailed. `code` is then the
|
|
162
|
+
code itself, or a function called with a dict (email, ttl, left, error, expired) that
|
|
163
|
+
returns the code, RESEND for a new one, or "" to stop. With neither, VerificationPending
|
|
164
|
+
is raised and the sign-up stays saved for `verify`."""
|
|
165
|
+
existing = account_store.load(root)
|
|
166
|
+
if existing:
|
|
167
|
+
raise AccountError(f"This device is already signed in as {existing['email']}. If sign up "
|
|
168
|
+
f"did not finish, run `liaison account login -e {existing['email']}` to "
|
|
169
|
+
"complete it; otherwise run `liaison account logout` first.")
|
|
170
|
+
email = _require_email(normalize_email(email))
|
|
171
|
+
_require_password(password)
|
|
172
|
+
relay = _relay(relay)
|
|
173
|
+
if foldersync.load_config(root):
|
|
174
|
+
raise AccountError("Sync is already set up on this device. Run `liaison sync stop` "
|
|
175
|
+
"first, then sign up; the new account starts a new vault.")
|
|
176
|
+
# A sign-up still waiting for its code keeps its device key, so asking again for a code
|
|
177
|
+
# that did not arrive does not orphan the first one.
|
|
178
|
+
waiting = account_store.load_pending(root)
|
|
179
|
+
same = bool(waiting) and waiting["email"] == email and waiting["relay"].rstrip("/") == relay.rstrip("/")
|
|
180
|
+
device = _device_for(waiting["device"], name, platform) if same else _device(name, platform)
|
|
181
|
+
cfg = relaysync.start(relay=relay, root=root, _account_ok=True)
|
|
182
|
+
http = _http(relay)
|
|
183
|
+
body = {"email": email, "password": password, "device": _payload(device),
|
|
184
|
+
**({"invite": invite or os.environ.get("LIAISON_INVITE", "")}
|
|
185
|
+
if invite or os.environ.get("LIAISON_INVITE") else {})}
|
|
186
|
+
try:
|
|
187
|
+
data = http.request("POST", "/v1/account/signup", body)
|
|
188
|
+
except RelayError as exc:
|
|
189
|
+
relaysync.stop(root)
|
|
190
|
+
hint = (f" If the account was created anyway, `liaison account login -e {email}` finishes "
|
|
191
|
+
"setting it up." if isinstance(exc, RelayUnavailable) else "")
|
|
192
|
+
raise AccountError(_msg(exc) + hint)
|
|
193
|
+
if isinstance(data, dict) and data.get("pending"):
|
|
194
|
+
# The vault key is made after the address is proved, not before.
|
|
195
|
+
relaysync.stop(root)
|
|
196
|
+
ttl = int(data.get("ttl") or 900)
|
|
197
|
+
account_store.save_pending({"email": email, "relay": relay, "device": device,
|
|
198
|
+
"sent": int(time.time()), "ttl": ttl}, root)
|
|
199
|
+
data = _await_code(http, email, device, code, ttl, resend=lambda: http.request(
|
|
200
|
+
"POST", "/v1/account/signup", body))
|
|
201
|
+
cfg = relaysync.start(relay=relay, root=root, _account_ok=True)
|
|
202
|
+
return _finish_signup(http, device, relay, data, password, cfg, root, email)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def verify(email: str, password: str, code, relay: str = "", root: Optional[Path] = None) -> dict:
|
|
206
|
+
"""Finish a sign-up that was waiting for its emailed code, from the saved device key.
|
|
207
|
+
|
|
208
|
+
The password is asked for again because the vault and recovery phrase are set up
|
|
209
|
+
here, and the relay checks it when the recovery phrase is stored."""
|
|
210
|
+
existing = account_store.load(root)
|
|
211
|
+
if existing:
|
|
212
|
+
raise AccountError(f"This device is already signed in as {existing['email']}. "
|
|
213
|
+
"Run `liaison account logout` first.")
|
|
214
|
+
waiting = account_store.load_pending(root)
|
|
215
|
+
email = _require_email(normalize_email(email)) if email else (waiting or {}).get("email", "")
|
|
216
|
+
if not waiting or waiting["email"] != email:
|
|
217
|
+
raise AccountError("No sign-up for that address is waiting on this device. Run "
|
|
218
|
+
"`liaison account signup` to start one and get a code.")
|
|
219
|
+
_require_password(password)
|
|
220
|
+
relay = _relay(relay or waiting["relay"])
|
|
221
|
+
if foldersync.load_config(root):
|
|
222
|
+
raise AccountError("Sync is already set up on this device. Run `liaison sync stop` "
|
|
223
|
+
"first, then finish the sign-up; the new account starts a new vault.")
|
|
224
|
+
device = _device_for(waiting["device"], waiting["device"].get("name", ""),
|
|
225
|
+
waiting["device"].get("platform", ""))
|
|
226
|
+
http = _http(relay)
|
|
227
|
+
ttl = int(waiting.get("ttl") or 900)
|
|
228
|
+
state_sent = int(waiting.get("sent") or 0)
|
|
229
|
+
data = _await_code(http, email, device, code, ttl, sent=state_sent, resend=None)
|
|
230
|
+
cfg = relaysync.start(relay=relay, root=root, _account_ok=True)
|
|
231
|
+
return _finish_signup(http, device, relay, data, password, cfg, root, email)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def pending_email(root: Optional[Path] = None) -> str:
|
|
235
|
+
"""The address of a sign-up waiting for its code on this device, or ""."""
|
|
236
|
+
waiting = account_store.load_pending(root)
|
|
237
|
+
return waiting["email"] if waiting else ""
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _await_code(http: Http, email: str, device: dict, code, ttl: int, sent: float = 0,
|
|
241
|
+
resend=None) -> dict:
|
|
242
|
+
"""Send the emailed code to the relay until it is accepted, asking again while tries remain."""
|
|
243
|
+
sent = sent or time.time()
|
|
244
|
+
state = {"email": email, "ttl": ttl, "left": None, "error": "", "expired": False}
|
|
245
|
+
asked = 0
|
|
246
|
+
while True:
|
|
247
|
+
value = code(state) if callable(code) else (code if not asked else "")
|
|
248
|
+
asked += 1
|
|
249
|
+
if not value:
|
|
250
|
+
raise VerificationPending(email, ttl)
|
|
251
|
+
if value == RESEND:
|
|
252
|
+
if resend is None:
|
|
253
|
+
raise AccountError("Run `liaison account signup` again to get a new code.")
|
|
254
|
+
try:
|
|
255
|
+
resend()
|
|
256
|
+
except RelayError as exc:
|
|
257
|
+
raise AccountError(_msg(exc))
|
|
258
|
+
sent = time.time()
|
|
259
|
+
state.update(left=None, error="", expired=False)
|
|
260
|
+
continue
|
|
261
|
+
try:
|
|
262
|
+
return http.request("POST", "/v1/account/verify", {
|
|
263
|
+
"email": email, "code": str(value).strip()}, keys=device_auth(device))
|
|
264
|
+
except RelayError as exc:
|
|
265
|
+
if isinstance(exc, RelayUnavailable):
|
|
266
|
+
raise AccountError(_msg(exc))
|
|
267
|
+
left = exc.info.get("attempts_left") if isinstance(exc.info, dict) else None
|
|
268
|
+
expired = time.time() - sent > ttl
|
|
269
|
+
if isinstance(left, int) and left > 0 and callable(code):
|
|
270
|
+
state.update(left=left, error=_msg(exc), expired=expired)
|
|
271
|
+
continue
|
|
272
|
+
hint = (f" {left} attempt(s) left." if isinstance(left, int) and left > 0 else
|
|
273
|
+
" Run `liaison account signup` again to get a new code.")
|
|
274
|
+
raise AccountError(_msg(exc) + hint)
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _finish_signup(http: Http, device: dict, relay: str, data: object, password: str, cfg: dict,
|
|
278
|
+
root: Optional[Path], email: str) -> dict:
|
|
279
|
+
try:
|
|
280
|
+
_complete(data, "account")
|
|
281
|
+
except AccountError:
|
|
282
|
+
relaysync.stop(root)
|
|
283
|
+
raise AccountError("The relay's answer was incomplete. If the account was created anyway, "
|
|
284
|
+
f"`liaison account login -e {email}` finishes setting it up.")
|
|
285
|
+
local = _save_account(_account_file(device, relay, data), root)
|
|
286
|
+
with contextlib.suppress(AccountError, OSError):
|
|
287
|
+
account_store.remove_pending(root)
|
|
288
|
+
keys, phrase = _setup_vault(http, device, data["account"], password, cfg, local, root)
|
|
289
|
+
return {"account": data["account"], "email": email, "vault": keys.vault,
|
|
290
|
+
"device": device["device"], "phrase": phrase, "relay": relay}
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _complete(data: object, *needed: str) -> None:
|
|
294
|
+
"""The relay's answer must carry what the next step uses; a cut-off reply may not."""
|
|
295
|
+
if not isinstance(data, dict) or not all(data.get(k) for k in needed):
|
|
296
|
+
raise AccountError("The relay's answer was incomplete, so nothing was changed on this "
|
|
297
|
+
"device. Run the command again.")
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _setup_vault(http: Http, device: dict, account_id: str, password: str, cfg: dict,
|
|
301
|
+
local: dict, root: Optional[Path]):
|
|
302
|
+
"""Link this device's new vault to the account and seal its key under a fresh phrase.
|
|
303
|
+
|
|
304
|
+
Returns (keys, phrase). Used by sign up, and by a first sign in on an account whose
|
|
305
|
+
sign up died before it got this far."""
|
|
306
|
+
auth = device_auth(device)
|
|
307
|
+
phrase = new_recovery_phrase()
|
|
308
|
+
recovery = recovery_key(phrase)
|
|
309
|
+
keys = derive_keys(b64d(cfg["key"]))
|
|
310
|
+
wrap = wrap_group_key(account_id, keys.vault, b64d(cfg["key"]), recovery)
|
|
311
|
+
try:
|
|
312
|
+
http.request("POST", "/v1/account/vault", {
|
|
313
|
+
"vault": keys.vault, **sign_claim(keys, account_id, keys.vault, ts=http.now())}, keys=auth)
|
|
314
|
+
local["vault"] = keys.vault
|
|
315
|
+
http.request("POST", "/v1/account/recovery", {
|
|
316
|
+
"verifier": recovery_verifier(recovery), "wrap": wrap, "password": password, "base_version": 0,
|
|
317
|
+
"vault": keys.vault, **sign_claim(keys, account_id, keys.vault, ts=http.now())}, keys=auth)
|
|
318
|
+
local["recovery"] = True
|
|
319
|
+
_save_account(local, root)
|
|
320
|
+
except RelayError as exc:
|
|
321
|
+
_save_account(local, root)
|
|
322
|
+
raise AccountError(f"Your account was created, but setup did not finish: {_msg(exc)} "
|
|
323
|
+
"Run `liaison account login` again to finish it.")
|
|
324
|
+
return keys, phrase
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def login(email: str, password: str, relay: str = "", root: Optional[Path] = None,
|
|
328
|
+
name: str = "", platform: str = "") -> dict:
|
|
329
|
+
"""Sign this device in. It can sync once it also has the vault key."""
|
|
330
|
+
email = _require_email(normalize_email(email))
|
|
331
|
+
_require_password(password)
|
|
332
|
+
existing = account_store.load(root)
|
|
333
|
+
if existing and existing.get("email") != email:
|
|
334
|
+
raise AccountError(f"This device is already signed in as {existing['email']}. "
|
|
335
|
+
"Run `liaison account logout` first.")
|
|
336
|
+
relay = _relay(relay or (existing or {}).get("relay", ""))
|
|
337
|
+
device = _device_for(existing, name, platform)
|
|
338
|
+
try:
|
|
339
|
+
data = _http(relay).request("POST", "/v1/account/login", {
|
|
340
|
+
"email": email, "password": password, "device": _payload(device)})
|
|
341
|
+
except RelayError as exc:
|
|
342
|
+
raise AccountError(_enrolment_error(exc))
|
|
343
|
+
_complete(data, "account")
|
|
344
|
+
local = _save_account(_account_file(device, relay, data, data.get("vault") or ""), root)
|
|
345
|
+
out = {"account": data["account"], "email": email, "vault": local["vault"],
|
|
346
|
+
"device": device["device"], "relay": relay, "devices": data.get("devices", [])}
|
|
347
|
+
if not data.get("vault"):
|
|
348
|
+
# The account has no vault: a sign up that died before linking one. The password
|
|
349
|
+
# in hand is what setup needs, so finish it here rather than leave a dead end. A
|
|
350
|
+
# vault key the dead sign up already made on this device is the one to link.
|
|
351
|
+
cfg = foldersync.load_config(root)
|
|
352
|
+
if cfg is None:
|
|
353
|
+
cfg = relaysync.start(relay=relay, root=root, _account_ok=True)
|
|
354
|
+
if relaysync.is_relay(cfg) and str(cfg.get("relay", "")).rstrip("/") == relay.rstrip("/"):
|
|
355
|
+
local["recovery"] = bool(data.get("recovery"))
|
|
356
|
+
keys, phrase = _setup_vault(_http(relay), device, data["account"], password, cfg, local, root)
|
|
357
|
+
out.update(vault=keys.vault, phrase=phrase, finished_setup=True)
|
|
358
|
+
return out
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def recover(email: str, phrase: str, root: Optional[Path] = None, relay: str = "",
|
|
362
|
+
password: Optional[str] = None, name: str = "", platform: str = "",
|
|
363
|
+
force: bool = False) -> dict:
|
|
364
|
+
"""Rebuild this device from the recovery phrase, with no other device needed."""
|
|
365
|
+
email = _require_email(normalize_email(email))
|
|
366
|
+
canonical = parse_recovery_phrase(phrase)
|
|
367
|
+
if canonical is None:
|
|
368
|
+
raise AccountError("That is not a Liaison recovery phrase. It looks like "
|
|
369
|
+
"lsr1-word-word-... (twelve words).")
|
|
370
|
+
if password is not None:
|
|
371
|
+
_require_password(password)
|
|
372
|
+
existing = account_store.load(root)
|
|
373
|
+
if existing and existing.get("email") != email:
|
|
374
|
+
raise AccountError(f"This device is already signed in as {existing['email']}. "
|
|
375
|
+
"Run `liaison account logout` first.")
|
|
376
|
+
if foldersync.load_config(root) and not force:
|
|
377
|
+
raise AccountError("Sync is already set up on this device. Run `liaison sync stop` "
|
|
378
|
+
"first, or pass --force to replace it.")
|
|
379
|
+
relay = _relay(relay or (existing or {}).get("relay", ""))
|
|
380
|
+
device = _device_for(existing, name, platform)
|
|
381
|
+
recovery = recovery_key(canonical)
|
|
382
|
+
body = {"email": email, "verifier": recovery_verifier(recovery), "device": _payload(device)}
|
|
383
|
+
if password is not None:
|
|
384
|
+
body["password"] = password
|
|
385
|
+
try:
|
|
386
|
+
data = _http(relay).request("POST", "/v1/account/recover", body)
|
|
387
|
+
except RelayError as exc:
|
|
388
|
+
raise AccountError(_enrolment_error(exc))
|
|
389
|
+
_complete(data, "account")
|
|
390
|
+
blob = data.get("recovery_blob")
|
|
391
|
+
if not blob:
|
|
392
|
+
raise AccountError("This account has no recovery phrase set. Sign in with your password "
|
|
393
|
+
"on a device that still has the vault, then run "
|
|
394
|
+
"`liaison account recovery`.")
|
|
395
|
+
server_vault = data.get("vault") or ""
|
|
396
|
+
vault = server_vault or str(blob.get("vault", ""))
|
|
397
|
+
group_key = unwrap_group_key(data["account"], vault, blob, recovery)
|
|
398
|
+
if group_key is None:
|
|
399
|
+
raise AccountError("That recovery phrase does not open this account's vault. "
|
|
400
|
+
"Check the words and try again.")
|
|
401
|
+
keys = derive_keys(group_key)
|
|
402
|
+
if not server_vault:
|
|
403
|
+
try:
|
|
404
|
+
link = _http(relay)
|
|
405
|
+
link.request("POST", "/v1/account/vault", {
|
|
406
|
+
"vault": vault, **sign_claim(keys, data["account"], vault, ts=link.now())},
|
|
407
|
+
keys=device_auth(device))
|
|
408
|
+
except RelayError as exc:
|
|
409
|
+
_save_account(_account_file(device, relay, data), root)
|
|
410
|
+
raise AccountError(f"This device was enrolled, but the vault could not be "
|
|
411
|
+
f"linked to the account: {exc} Run the recovery again.")
|
|
412
|
+
cfg = foldersync.load_config(root)
|
|
413
|
+
if not cfg or force:
|
|
414
|
+
foldersync._save_config(_sync_config(relay, group_key), root)
|
|
415
|
+
with contextlib.suppress(OSError):
|
|
416
|
+
(Path(root or foldersync.default_root()) / "relay-seen.json").unlink()
|
|
417
|
+
relaysync._PUSHED_SIG.clear()
|
|
418
|
+
_save_account(_account_file(device, relay, data, vault), root)
|
|
419
|
+
return {"account": data["account"], "email": email, "vault": vault,
|
|
420
|
+
"device": device["device"], "relay": relay, "recovered": True}
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def status(root: Optional[Path] = None) -> dict:
|
|
424
|
+
local = account_store.load(root)
|
|
425
|
+
if not local:
|
|
426
|
+
return {"signed_in": False}
|
|
427
|
+
try:
|
|
428
|
+
data = _http(local["relay"], timeout=15).request(
|
|
429
|
+
"GET", "/v1/account", keys=device_auth(local))
|
|
430
|
+
except RelayError as exc:
|
|
431
|
+
raise AccountError(_msg(exc))
|
|
432
|
+
if data.get("vault") and data["vault"] != local.get("vault") and not _holds(local, root):
|
|
433
|
+
# Only adopt the relay's answer when this device has no key for the vault it
|
|
434
|
+
# knows. A device that does hold it learns about a rotation from `liaison
|
|
435
|
+
# sync`, which fetches and checks the new key before switching.
|
|
436
|
+
local["vault"] = data["vault"]
|
|
437
|
+
_save_account(local, root)
|
|
438
|
+
return {"signed_in": True, "local": local, **data}
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def _holds(local: dict, root: Optional[Path]) -> bool:
|
|
442
|
+
"""True when this device's sync key opens the vault account.json names."""
|
|
443
|
+
cfg = foldersync.load_config(root)
|
|
444
|
+
if not local.get("vault") or not relaysync.is_relay(cfg) or not cfg.get("key"):
|
|
445
|
+
return False
|
|
446
|
+
try:
|
|
447
|
+
return derive_keys(b64d(cfg["key"])).vault == local["vault"]
|
|
448
|
+
except (KeyError, ValueError, TypeError):
|
|
449
|
+
return False
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def devices(root: Optional[Path] = None) -> list[dict]:
|
|
453
|
+
return status(root).get("devices", [])
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def revoke(device: str, password: str, root: Optional[Path] = None, rotate: bool = True,
|
|
457
|
+
confirm=None) -> dict:
|
|
458
|
+
"""Remove a device. Needs the password again: a signed-in laptop alone is not enough.
|
|
459
|
+
|
|
460
|
+
By default the vault key is rotated in the same step, so the removed device's
|
|
461
|
+
copy of the key opens nothing written afterwards (see rotation.py). That needs
|
|
462
|
+
the vault key on this device. `rotate=False` only stops the device signing in.
|
|
463
|
+
Removing this device itself never rotates: it would be left without the key."""
|
|
464
|
+
local = account_store.load(root)
|
|
465
|
+
if not local:
|
|
466
|
+
raise AccountError("This device is not signed in.")
|
|
467
|
+
if rotate and device != local["device"]:
|
|
468
|
+
if not _holds(local, root):
|
|
469
|
+
raise AccountError("Removing a device also replaces the vault key, which needs the "
|
|
470
|
+
"vault key on this device, and this device does not have it. Run "
|
|
471
|
+
"the revoke on a device that syncs the vault, or pass --no-rotate "
|
|
472
|
+
"to only stop the device signing in (it keeps the key).")
|
|
473
|
+
from . import rotation
|
|
474
|
+
out = rotation.rotate(password, root, revoke=device, confirm=confirm)
|
|
475
|
+
if not out.get("rotated"):
|
|
476
|
+
return out
|
|
477
|
+
return {"revoked": device, "active": out.get("active"), "rotation": out}
|
|
478
|
+
try:
|
|
479
|
+
return _http(local["relay"]).request(
|
|
480
|
+
"POST", "/v1/account/revoke", {"device": device, "password": password},
|
|
481
|
+
keys=device_auth(local))
|
|
482
|
+
except RelayError as exc:
|
|
483
|
+
raise AccountError(_msg(exc))
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def rotate(password: str, root: Optional[Path] = None, confirm=None) -> dict:
|
|
487
|
+
"""Replace the vault key without removing anyone, for when the key may have leaked."""
|
|
488
|
+
from . import rotation
|
|
489
|
+
return rotation.rotate(password, root, confirm=confirm)
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
def change_password(current: str, new: str, root: Optional[Path] = None) -> dict:
|
|
493
|
+
local = account_store.load(root)
|
|
494
|
+
if not local:
|
|
495
|
+
raise AccountError("This device is not signed in.")
|
|
496
|
+
_require_password(new)
|
|
497
|
+
try:
|
|
498
|
+
return _http(local["relay"]).request("POST", "/v1/account/password",
|
|
499
|
+
{"current": current, "password": new},
|
|
500
|
+
keys=device_auth(local))
|
|
501
|
+
except RelayError as exc:
|
|
502
|
+
raise AccountError(_msg(exc))
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def set_recovery(root: Optional[Path] = None, phrase: str = "",
|
|
506
|
+
relay: str = "", password: str = "") -> str:
|
|
507
|
+
"""Seal the vault key under a fresh phrase. Returns the phrase, once."""
|
|
508
|
+
local = account_store.load(root)
|
|
509
|
+
if not local:
|
|
510
|
+
raise AccountError("This device is not signed in.")
|
|
511
|
+
cfg = foldersync.load_config(root)
|
|
512
|
+
if not relaysync.is_relay(cfg):
|
|
513
|
+
raise AccountError("Recovery needs the vault key on this device. Sign in on a device "
|
|
514
|
+
"that syncs this account, or use `liaison account recover`.")
|
|
515
|
+
keys = derive_keys(b64d(cfg["key"]))
|
|
516
|
+
if local.get("vault") and local["vault"] != keys.vault:
|
|
517
|
+
raise AccountError("This device syncs a different vault than this account. "
|
|
518
|
+
"Run `liaison account status` before setting a recovery phrase.")
|
|
519
|
+
canonical = parse_recovery_phrase(phrase) if phrase else new_recovery_phrase()
|
|
520
|
+
if canonical is None:
|
|
521
|
+
raise AccountError("That is not a Liaison recovery phrase.")
|
|
522
|
+
recovery = recovery_key(canonical)
|
|
523
|
+
wrap = wrap_group_key(local["account"], keys.vault, b64d(cfg["key"]), recovery)
|
|
524
|
+
auth = device_auth(local)
|
|
525
|
+
http = _http(relay or local["relay"])
|
|
526
|
+
try:
|
|
527
|
+
http.request("POST", "/v1/account/vault", {
|
|
528
|
+
"vault": keys.vault, **sign_claim(keys, local["account"], keys.vault, ts=http.now())}, keys=auth)
|
|
529
|
+
version = int(http.request("GET", "/v1/account", keys=auth).get("recovery_version", 0))
|
|
530
|
+
http.request("POST", "/v1/account/recovery", {
|
|
531
|
+
"verifier": recovery_verifier(recovery), "wrap": wrap, "password": password,
|
|
532
|
+
"base_version": version,
|
|
533
|
+
"vault": keys.vault, **sign_claim(keys, local["account"], keys.vault, ts=http.now())}, keys=auth)
|
|
534
|
+
except RelayError as exc:
|
|
535
|
+
raise AccountError(_msg(exc))
|
|
536
|
+
local["recovery"] = True
|
|
537
|
+
local["vault"] = keys.vault
|
|
538
|
+
_save_account(local, root)
|
|
539
|
+
return canonical
|
|
540
|
+
|
|
541
|
+
|
|
542
|
+
def delete_account(password: str, root: Optional[Path] = None) -> dict:
|
|
543
|
+
"""Erase the account and everything the relay holds for it, then sign this device out.
|
|
544
|
+
|
|
545
|
+
Entries already on this device stay; only the relay's copy, the account and the keys that
|
|
546
|
+
point at them go. Needs the password again and the vault key on this device."""
|
|
547
|
+
local = account_store.load(root)
|
|
548
|
+
if not local:
|
|
549
|
+
raise AccountError("This device is not signed in.")
|
|
550
|
+
auth = device_auth(local)
|
|
551
|
+
cfg = foldersync.load_config(root)
|
|
552
|
+
holds_key = False
|
|
553
|
+
if local.get("vault") and relaysync.is_relay(cfg) and cfg.get("key"):
|
|
554
|
+
try:
|
|
555
|
+
keys = derive_keys(b64d(cfg["key"]))
|
|
556
|
+
except (KeyError, ValueError, TypeError):
|
|
557
|
+
keys = None
|
|
558
|
+
if keys is not None and keys.vault == local["vault"]:
|
|
559
|
+
auth.group = keys
|
|
560
|
+
holds_key = True
|
|
561
|
+
try:
|
|
562
|
+
out = _http(local["relay"]).request("POST", "/v1/account/delete", {"password": password}, keys=auth)
|
|
563
|
+
except RelayError as exc:
|
|
564
|
+
raise AccountError(_msg(exc))
|
|
565
|
+
if holds_key:
|
|
566
|
+
relaysync.stop(root)
|
|
567
|
+
account_store.remove(root)
|
|
568
|
+
return {"email": str(local.get("email", "")), "items": int(out.get("items", 0))}
|
|
569
|
+
|
|
570
|
+
|
|
571
|
+
def logout(root: Optional[Path] = None, report: Optional[dict] = None) -> str:
|
|
572
|
+
"""Sign this device out. `report["relay_told"]` says whether the relay heard about it."""
|
|
573
|
+
local = account_store.load(root)
|
|
574
|
+
if not local:
|
|
575
|
+
raise AccountError("This device is not signed in.")
|
|
576
|
+
# Tell the relay first, so this device stops being a valid signer there. If the relay
|
|
577
|
+
# cannot be reached, or already removed this device, signing out locally still goes ahead.
|
|
578
|
+
told = False
|
|
579
|
+
try:
|
|
580
|
+
_http(local["relay"], timeout=10).request(
|
|
581
|
+
"POST", "/v1/account/logout", {}, keys=device_auth(local))
|
|
582
|
+
told = True
|
|
583
|
+
except (RelayError, ValueError):
|
|
584
|
+
pass
|
|
585
|
+
if report is not None:
|
|
586
|
+
report["relay_told"] = told
|
|
587
|
+
cfg = foldersync.load_config(root)
|
|
588
|
+
if local.get("vault") and relaysync.is_relay(cfg) and cfg.get("key"):
|
|
589
|
+
try:
|
|
590
|
+
same = derive_keys(b64d(cfg["key"])).vault == local["vault"]
|
|
591
|
+
except (KeyError, ValueError, TypeError):
|
|
592
|
+
same = False
|
|
593
|
+
if same:
|
|
594
|
+
relaysync.stop(root)
|
|
595
|
+
account_store.remove(root)
|
|
596
|
+
return str(local.get("email", ""))
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
def line(root: Optional[Path] = None) -> str:
|
|
600
|
+
"""One line for `liaison status`, without making a network call."""
|
|
601
|
+
local = account_store.load(root)
|
|
602
|
+
if not local:
|
|
603
|
+
return ""
|
|
604
|
+
cfg = foldersync.load_config(root)
|
|
605
|
+
if local.get("vault") and relaysync.is_relay(cfg) and cfg.get("key"):
|
|
606
|
+
try:
|
|
607
|
+
same = derive_keys(b64d(cfg["key"])).vault == local["vault"]
|
|
608
|
+
except (KeyError, ValueError, TypeError):
|
|
609
|
+
same = False
|
|
610
|
+
if not same:
|
|
611
|
+
return f"account: {local['email']} (signed in; this sync vault is a different one)"
|
|
612
|
+
elif not relaysync.is_relay(cfg):
|
|
613
|
+
return (f"account: {local['email']} (signed in; no vault key on this device. "
|
|
614
|
+
"`liaison account recover` or `liaison sync join CODE` adds it)")
|
|
615
|
+
return f"account: {local['email']}"
|