clicker4ai 1.0.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.
- clicker4ai/__init__.py +3 -0
- clicker4ai/__main__.py +8 -0
- clicker4ai/auth.py +497 -0
- clicker4ai/cli.py +1052 -0
- clicker4ai/config.py +299 -0
- clicker4ai/events.py +345 -0
- clicker4ai/files.py +198 -0
- clicker4ai/history.py +194 -0
- clicker4ai/library.py +261 -0
- clicker4ai/main.py +1082 -0
- clicker4ai/passkey.py +573 -0
- clicker4ai/projects.py +273 -0
- clicker4ai/prompt.py +28 -0
- clicker4ai/quiet.py +126 -0
- clicker4ai/quiet_hook.py +33 -0
- clicker4ai/rpc.py +659 -0
- clicker4ai/scope.py +108 -0
- clicker4ai/sdk_update.py +390 -0
- clicker4ai/search.py +310 -0
- clicker4ai/sessions.py +1770 -0
- clicker4ai/term_attach.py +167 -0
- clicker4ai/terminal.py +288 -0
- clicker4ai/transcript.py +159 -0
- clicker4ai/trust.py +223 -0
- clicker4ai/watch.py +107 -0
- clicker4ai/web/app.js +5444 -0
- clicker4ai/web/icon-180.png +0 -0
- clicker4ai/web/icon-512.png +0 -0
- clicker4ai/web/index.html +28 -0
- clicker4ai/web/manifest.json +13 -0
- clicker4ai/web/style.css +1014 -0
- clicker4ai/web/transport.js +210 -0
- clicker4ai/web/vendor/xterm/addon-fit.js +2 -0
- clicker4ai/web/vendor/xterm/xterm.css +218 -0
- clicker4ai/web/vendor/xterm/xterm.js +2 -0
- clicker4ai-1.0.0.dist-info/METADATA +1113 -0
- clicker4ai-1.0.0.dist-info/RECORD +41 -0
- clicker4ai-1.0.0.dist-info/WHEEL +4 -0
- clicker4ai-1.0.0.dist-info/entry_points.txt +2 -0
- clicker4ai-1.0.0.dist-info/licenses/LICENSE +661 -0
- clicker4ai-1.0.0.dist-info/licenses/NOTICE +35 -0
clicker4ai/__init__.py
ADDED
clicker4ai/__main__.py
ADDED
clicker4ai/auth.py
ADDED
|
@@ -0,0 +1,497 @@
|
|
|
1
|
+
"""Per-device sessions and one-time pairing codes.
|
|
2
|
+
|
|
3
|
+
Login flow: a one-time pairing code (printed by the server at start or by
|
|
4
|
+
`c4ai pair`) is redeemed once → the server creates a device
|
|
5
|
+
session and sets its random token as a cookie. There is no long-lived
|
|
6
|
+
master token.
|
|
7
|
+
|
|
8
|
+
Storage (data dir is 0700, files 0600, written atomically):
|
|
9
|
+
devices.json {"devices": [{id, name, token_sha256, created_at, last_seen,
|
|
10
|
+
roots?, manage_devices, terminal, passkey,
|
|
11
|
+
require_passkey, locked, quiet_exempt, files,
|
|
12
|
+
files_upload}]}
|
|
13
|
+
pairing.json {"codes": [{code_sha256, expires_at, roots?, manage_devices,
|
|
14
|
+
terminal, require_passkey, quiet_exempt, files,
|
|
15
|
+
files_upload}]}
|
|
16
|
+
|
|
17
|
+
A pairing code carries the grants chosen when it was issued (CLI only):
|
|
18
|
+
`roots` limits the device to those directories (see scope.py; absent = the
|
|
19
|
+
whole allowed_roots), `manage_devices` lets it list and revoke other
|
|
20
|
+
devices in the app and `terminal` allows True View (the real Claude Code
|
|
21
|
+
TUI — effectively a shell, so off by default). All can be changed later
|
|
22
|
+
from the CLI.
|
|
23
|
+
|
|
24
|
+
Device names are unique (case-folded): a second iPhone is stored as
|
|
25
|
+
"iPhone 2", and renaming onto a taken name is refused. A name may not be
|
|
26
|
+
another device's id either, so the CLI can take either one (`resolve`).
|
|
27
|
+
|
|
28
|
+
A device paired with `require_passkey` (the default for pairing codes and
|
|
29
|
+
passkey logins) may do nothing but register a passkey until it has one —
|
|
30
|
+
see `needs_passkey`; turning the requirement off is left to the CLI.
|
|
31
|
+
|
|
32
|
+
A device can be *locked*: the cookie stays in the browser and the record
|
|
33
|
+
keeps its grants, but every request is refused until a passkey unlocks it
|
|
34
|
+
(passkey.py). Getting back in then needs both the cookie and the owner's
|
|
35
|
+
biometrics, and a locked session does not slide its idle expiry — a device
|
|
36
|
+
left locked still ages out after SESSION_IDLE_SECS. The server also locks
|
|
37
|
+
a device carrying a passkey on its own once it has not been heard from for
|
|
38
|
+
`idle_lock_secs` (config `lock_idle_minutes`), so an app reopened later —
|
|
39
|
+
or a stolen cookie — needs the passkey again.
|
|
40
|
+
|
|
41
|
+
Only SHA-256 hashes of session tokens and pairing codes are stored, so a
|
|
42
|
+
leaked file grants no access. Both files are shared with the CLI process
|
|
43
|
+
(`pair`, `devices`, `revoke`); access is serialized with an flock and the
|
|
44
|
+
server reloads devices.json when the file changes (mtime/inode), so a CLI
|
|
45
|
+
revoke takes effect on the next request. An unreadable or corrupt
|
|
46
|
+
devices.json (as opposed to a missing one) is not taken for "no devices":
|
|
47
|
+
every device is refused until the file is fixed, but nothing writes over
|
|
48
|
+
it and the incognito sweep holds off (DeviceStore.read_error).
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
from __future__ import annotations
|
|
52
|
+
|
|
53
|
+
import contextlib
|
|
54
|
+
import fcntl
|
|
55
|
+
import hashlib
|
|
56
|
+
import hmac
|
|
57
|
+
import json
|
|
58
|
+
import logging
|
|
59
|
+
import os
|
|
60
|
+
import re
|
|
61
|
+
import secrets
|
|
62
|
+
import time
|
|
63
|
+
from pathlib import Path
|
|
64
|
+
|
|
65
|
+
from .config import DATA_DIR, secure_dir, write_private
|
|
66
|
+
|
|
67
|
+
DEVICES_PATH = DATA_DIR / "devices.json"
|
|
68
|
+
PAIRING_PATH = DATA_DIR / "pairing.json"
|
|
69
|
+
LOCK_PATH = DATA_DIR / ".auth.lock"
|
|
70
|
+
|
|
71
|
+
log = logging.getLogger("clicker4ai.auth")
|
|
72
|
+
|
|
73
|
+
SESSION_IDLE_SECS = 30 * 24 * 3600 # device session expires after 30 idle days
|
|
74
|
+
PAIRING_TTL_SECS = 120 # one-time pairing code lifetime
|
|
75
|
+
LAST_SEEN_WRITE_SECS = 300 # persist last_seen at most this often
|
|
76
|
+
NAME_MAX = 64
|
|
77
|
+
|
|
78
|
+
# Pairing codes: 10 chars of Crockford-style base32 (no 0/1/I/L/O/U),
|
|
79
|
+
# shown as XXXXX-XXXXX — typable on a phone, ~50 bits, 2 min, single use.
|
|
80
|
+
_CODE_ALPHABET = "23456789ABCDEFGHJKMNPQRSTVWXYZ"
|
|
81
|
+
_CODE_LEN = 10
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _sha256(value: str) -> str:
|
|
85
|
+
return hashlib.sha256(value.encode()).hexdigest()
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@contextlib.contextmanager
|
|
89
|
+
def _locked():
|
|
90
|
+
secure_dir(DATA_DIR)
|
|
91
|
+
fd = os.open(LOCK_PATH, os.O_RDWR | os.O_CREAT, 0o600)
|
|
92
|
+
try:
|
|
93
|
+
fcntl.flock(fd, fcntl.LOCK_EX)
|
|
94
|
+
yield
|
|
95
|
+
finally:
|
|
96
|
+
fcntl.flock(fd, fcntl.LOCK_UN)
|
|
97
|
+
os.close(fd)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
# passkey.py keeps its own file (passkeys.json) in the same data dir and
|
|
101
|
+
# under this same lock, so CLI and server never interleave writes.
|
|
102
|
+
file_lock = _locked
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _read_json(path: Path, key: str) -> list[dict]:
|
|
106
|
+
try:
|
|
107
|
+
data = json.loads(path.read_text())
|
|
108
|
+
except (OSError, json.JSONDecodeError):
|
|
109
|
+
return []
|
|
110
|
+
items = data.get(key) if isinstance(data, dict) else None
|
|
111
|
+
return [x for x in items if isinstance(x, dict)] if isinstance(items, list) else []
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
# ---------------- pairing codes ----------------
|
|
115
|
+
|
|
116
|
+
def normalize_code(raw: str) -> str:
|
|
117
|
+
return re.sub(r"[^0-9A-Z]", "", (raw or "").upper())
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def issue_pairing_code(ttl: float = PAIRING_TTL_SECS, roots: list[str] | None = None,
|
|
121
|
+
manage_devices: bool = False, terminal: bool = False,
|
|
122
|
+
require_passkey: bool = True, quiet_exempt: bool = False,
|
|
123
|
+
files: bool = False, files_upload: bool = False) -> str:
|
|
124
|
+
"""Create a one-time pairing code; returns it formatted XXXXX-XXXXX.
|
|
125
|
+
`roots` must already be validated (scope.validate_roots): None means
|
|
126
|
+
the whole allowed_roots, a list limits it, and an empty list means no
|
|
127
|
+
folders at all — which is what the CLI hands out by default.
|
|
128
|
+
`files_upload` implies `files`, as in `devices set`."""
|
|
129
|
+
code = "".join(secrets.choice(_CODE_ALPHABET) for _ in range(_CODE_LEN))
|
|
130
|
+
now = time.time()
|
|
131
|
+
entry = {"code_sha256": _sha256(code), "expires_at": now + ttl,
|
|
132
|
+
"manage_devices": bool(manage_devices), "terminal": bool(terminal),
|
|
133
|
+
"require_passkey": bool(require_passkey),
|
|
134
|
+
"quiet_exempt": bool(quiet_exempt),
|
|
135
|
+
"files": bool(files or files_upload), "files_upload": bool(files_upload)}
|
|
136
|
+
if roots is not None:
|
|
137
|
+
entry["roots"] = list(roots)
|
|
138
|
+
with _locked():
|
|
139
|
+
codes = [c for c in _read_json(PAIRING_PATH, "codes")
|
|
140
|
+
if c.get("expires_at", 0) > now]
|
|
141
|
+
codes.append(entry)
|
|
142
|
+
write_private(PAIRING_PATH, {"codes": codes})
|
|
143
|
+
return f"{code[:5]}-{code[5:]}"
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def redeem_pairing_code(raw: str) -> dict | None:
|
|
147
|
+
"""Consume a pairing code → its grants {"roots", "manage_devices",
|
|
148
|
+
"terminal", "require_passkey", "quiet_exempt", "files", "files_upload"}.
|
|
149
|
+
Succeeds only once, and only before the code expires; else None."""
|
|
150
|
+
code = normalize_code(raw)
|
|
151
|
+
if len(code) != _CODE_LEN:
|
|
152
|
+
return None
|
|
153
|
+
digest = _sha256(code)
|
|
154
|
+
now = time.time()
|
|
155
|
+
with _locked():
|
|
156
|
+
codes = _read_json(PAIRING_PATH, "codes")
|
|
157
|
+
live = [c for c in codes if c.get("expires_at", 0) > now]
|
|
158
|
+
hit = next((c for c in live
|
|
159
|
+
if hmac.compare_digest(str(c.get("code_sha256", "")), digest)), None)
|
|
160
|
+
if hit is not None:
|
|
161
|
+
live.remove(hit)
|
|
162
|
+
if hit is not None or len(live) != len(codes):
|
|
163
|
+
write_private(PAIRING_PATH, {"codes": live})
|
|
164
|
+
if hit is None:
|
|
165
|
+
return None
|
|
166
|
+
return {"roots": hit.get("roots"), # None = all, [] = none
|
|
167
|
+
"manage_devices": bool(hit.get("manage_devices")),
|
|
168
|
+
"terminal": bool(hit.get("terminal")),
|
|
169
|
+
"require_passkey": bool(hit.get("require_passkey", True)),
|
|
170
|
+
"quiet_exempt": bool(hit.get("quiet_exempt")),
|
|
171
|
+
"files": bool(hit.get("files")),
|
|
172
|
+
"files_upload": bool(hit.get("files_upload"))}
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
# ---------------- device sessions ----------------
|
|
176
|
+
|
|
177
|
+
class DevicesUnreadable(RuntimeError):
|
|
178
|
+
"""devices.json exists but cannot be read or parsed: saving the empty
|
|
179
|
+
list we fell back to would wipe every other device."""
|
|
180
|
+
|
|
181
|
+
def device_name_from_ua(ua: str) -> str:
|
|
182
|
+
ua = ua or ""
|
|
183
|
+
for needle, name in (("iPhone", "iPhone"), ("iPad", "iPad"),
|
|
184
|
+
("Android", "Android"), ("Macintosh", "Mac"),
|
|
185
|
+
("Windows", "Windows"), ("Linux", "Linux")):
|
|
186
|
+
if needle in ua:
|
|
187
|
+
return name
|
|
188
|
+
return "Unknown device"
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _clean_name(name: str) -> str:
|
|
192
|
+
name = " ".join(str(name or "").split())
|
|
193
|
+
return name[:NAME_MAX]
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def needs_passkey(device: dict) -> bool:
|
|
197
|
+
"""A device that must carry a passkey but has none yet: everything
|
|
198
|
+
except registering one (and signing out) is refused."""
|
|
199
|
+
return bool(device.get("require_passkey")) and not device.get("passkey")
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
class DeviceStore:
|
|
203
|
+
"""devices.json, cached in memory and reloaded when the file changes."""
|
|
204
|
+
|
|
205
|
+
def __init__(self, path: Path = DEVICES_PATH):
|
|
206
|
+
self.path = path
|
|
207
|
+
# (st_mtime_ns, st_ino): writes are atomic renames, so the inode
|
|
208
|
+
# changes on every save even within one mtime tick
|
|
209
|
+
self._stamp: tuple[int, int] | None = None
|
|
210
|
+
self._devices: list[dict] = []
|
|
211
|
+
# Set by the server (0 = off, and always off in the CLI): lock a
|
|
212
|
+
# device with a passkey after this long without a request.
|
|
213
|
+
self.idle_lock_secs = 0
|
|
214
|
+
# device id -> last request, in memory; last_seen is written only
|
|
215
|
+
# every LAST_SEEN_WRITE_SECS (half a shorter idle lock) and covers
|
|
216
|
+
# a server restart
|
|
217
|
+
self._active: dict[str, float] = {}
|
|
218
|
+
# why devices.json could not be read (None = fine or missing)
|
|
219
|
+
self.read_error: str | None = None
|
|
220
|
+
|
|
221
|
+
def _reload_if_changed(self) -> None:
|
|
222
|
+
stamp = self._file_stamp()
|
|
223
|
+
if stamp == self._stamp:
|
|
224
|
+
return
|
|
225
|
+
try:
|
|
226
|
+
data = json.loads(self.path.read_text()) if stamp else {}
|
|
227
|
+
items = data.get("devices", []) if isinstance(data, dict) else None
|
|
228
|
+
if not isinstance(items, list):
|
|
229
|
+
raise ValueError("no \"devices\" list")
|
|
230
|
+
except FileNotFoundError:
|
|
231
|
+
items = [] # removed between stat and read
|
|
232
|
+
except (OSError, ValueError) as e:
|
|
233
|
+
# refuse everyone rather than take it for "no devices"; the stamp
|
|
234
|
+
# stays old, so the next call reads again (a chmod fix keeps it)
|
|
235
|
+
if self.read_error is None:
|
|
236
|
+
log.warning("%s unreadable, every device refused until fixed: %s",
|
|
237
|
+
self.path, e)
|
|
238
|
+
self.read_error = str(e)
|
|
239
|
+
self._devices = []
|
|
240
|
+
return
|
|
241
|
+
if self.read_error is not None:
|
|
242
|
+
log.warning("%s readable again", self.path)
|
|
243
|
+
self.read_error = None
|
|
244
|
+
self._devices = [x for x in items if isinstance(x, dict)]
|
|
245
|
+
self._stamp = stamp
|
|
246
|
+
|
|
247
|
+
def check_readable(self) -> None:
|
|
248
|
+
"""Raise DevicesUnreadable before anything is spent on a write
|
|
249
|
+
that would fail (a one-time pairing code)."""
|
|
250
|
+
self._reload_if_changed()
|
|
251
|
+
if self.read_error is not None:
|
|
252
|
+
raise DevicesUnreadable(f"{self.path.name} unreadable: {self.read_error}")
|
|
253
|
+
|
|
254
|
+
def _file_stamp(self) -> tuple[int, int] | None:
|
|
255
|
+
try:
|
|
256
|
+
st = self.path.stat()
|
|
257
|
+
except OSError:
|
|
258
|
+
return None
|
|
259
|
+
return st.st_mtime_ns, st.st_ino
|
|
260
|
+
|
|
261
|
+
def _save(self) -> None:
|
|
262
|
+
if self.read_error is not None:
|
|
263
|
+
raise DevicesUnreadable(f"{self.path.name} unreadable: {self.read_error}")
|
|
264
|
+
write_private(self.path, {"devices": self._devices})
|
|
265
|
+
self._stamp = self._file_stamp()
|
|
266
|
+
|
|
267
|
+
def _prune(self, now: float) -> bool:
|
|
268
|
+
before = len(self._devices)
|
|
269
|
+
self._devices = [d for d in self._devices
|
|
270
|
+
if now - d.get("last_seen", 0) < SESSION_IDLE_SECS]
|
|
271
|
+
return len(self._devices) != before
|
|
272
|
+
|
|
273
|
+
def _taken(self) -> set[str]:
|
|
274
|
+
"""Every name and id in use, case-folded: a name must not read as
|
|
275
|
+
another device's id, since the CLI accepts either."""
|
|
276
|
+
return ({_clean_name(d.get("name", "")).casefold() for d in self._devices}
|
|
277
|
+
| {str(d.get("id", "")).casefold() for d in self._devices})
|
|
278
|
+
|
|
279
|
+
def _unique_name(self, name: str) -> str:
|
|
280
|
+
"""Names are unique, so two iPhones become "iPhone" and "iPhone 2"
|
|
281
|
+
rather than an unreadable pair. Assumes the caller holds the lock."""
|
|
282
|
+
base = _clean_name(name) or "Unknown device"
|
|
283
|
+
taken = self._taken()
|
|
284
|
+
if base.casefold() not in taken:
|
|
285
|
+
return base
|
|
286
|
+
for n in range(2, 100):
|
|
287
|
+
candidate = _clean_name(f"{base} {n}")
|
|
288
|
+
if candidate.casefold() not in taken:
|
|
289
|
+
return candidate
|
|
290
|
+
return _clean_name(f"{base} {secrets.token_hex(2)}")
|
|
291
|
+
|
|
292
|
+
def create(self, name: str, roots: list[str] | None = None,
|
|
293
|
+
manage_devices: bool = False, terminal: bool = False,
|
|
294
|
+
require_passkey: bool = False, quiet_exempt: bool = False,
|
|
295
|
+
files: bool = False, files_upload: bool = False) -> tuple[str, dict]:
|
|
296
|
+
"""New device session → (raw cookie token, device record).
|
|
297
|
+
`roots` None means the whole allowed_roots, a list limits it, and
|
|
298
|
+
an empty list means no folders at all (a passkey login)."""
|
|
299
|
+
token = secrets.token_urlsafe(32)
|
|
300
|
+
now = time.time()
|
|
301
|
+
dev = {
|
|
302
|
+
"id": "", # id and name are filled under the lock,
|
|
303
|
+
"name": "", # where both are checked against every other
|
|
304
|
+
"token_sha256": _sha256(token),
|
|
305
|
+
"created_at": now,
|
|
306
|
+
"last_seen": now,
|
|
307
|
+
"manage_devices": bool(manage_devices),
|
|
308
|
+
"terminal": bool(terminal),
|
|
309
|
+
"require_passkey": bool(require_passkey),
|
|
310
|
+
"quiet_exempt": bool(quiet_exempt),
|
|
311
|
+
"files": bool(files or files_upload),
|
|
312
|
+
"files_upload": bool(files_upload),
|
|
313
|
+
}
|
|
314
|
+
if roots is not None:
|
|
315
|
+
dev["roots"] = list(roots)
|
|
316
|
+
with _locked():
|
|
317
|
+
self._reload_if_changed()
|
|
318
|
+
self._prune(now)
|
|
319
|
+
taken = self._taken()
|
|
320
|
+
dev["id"] = next(i for i in iter(lambda: secrets.token_hex(4), None)
|
|
321
|
+
if i not in taken)
|
|
322
|
+
dev["name"] = self._unique_name(name)
|
|
323
|
+
self._devices.append(dev)
|
|
324
|
+
self._save()
|
|
325
|
+
return token, dev
|
|
326
|
+
|
|
327
|
+
def verify(self, token: str | None) -> dict | None:
|
|
328
|
+
"""Device record for a cookie token, or None (unknown / expired).
|
|
329
|
+
Slides the idle expiry forward — except for a locked device, whose
|
|
330
|
+
clock keeps running so it cannot be kept alive by an app sitting
|
|
331
|
+
on the lock screen. Callers must check `locked` themselves."""
|
|
332
|
+
if not token:
|
|
333
|
+
return None
|
|
334
|
+
digest = _sha256(token)
|
|
335
|
+
now = time.time()
|
|
336
|
+
self._reload_if_changed()
|
|
337
|
+
dev = next((d for d in self._devices
|
|
338
|
+
if hmac.compare_digest(str(d.get("token_sha256", "")), digest)), None)
|
|
339
|
+
if dev is None or now - dev.get("last_seen", 0) >= SESSION_IDLE_SECS:
|
|
340
|
+
return None
|
|
341
|
+
if dev.get("locked"):
|
|
342
|
+
return dev
|
|
343
|
+
if self.idle_lock_secs and dev.get("passkey"):
|
|
344
|
+
last = max(self._active.get(dev["id"], 0), dev.get("last_seen", 0))
|
|
345
|
+
if now - last >= self.idle_lock_secs:
|
|
346
|
+
self.set_locked(dev["id"], True)
|
|
347
|
+
return {**dev, "locked": True}
|
|
348
|
+
self._active[dev["id"]] = now
|
|
349
|
+
# a short idle lock needs a fresher last_seen, or a restart (which
|
|
350
|
+
# forgets _active) would lock a phone that was just in use
|
|
351
|
+
every = min(LAST_SEEN_WRITE_SECS, self.idle_lock_secs / 2) \
|
|
352
|
+
if self.idle_lock_secs else LAST_SEEN_WRITE_SECS
|
|
353
|
+
if now - dev.get("last_seen", 0) >= every:
|
|
354
|
+
with _locked():
|
|
355
|
+
self._reload_if_changed()
|
|
356
|
+
fresh = next((d for d in self._devices if d.get("id") == dev["id"]), None)
|
|
357
|
+
if fresh is None:
|
|
358
|
+
return None # revoked meanwhile
|
|
359
|
+
fresh["last_seen"] = now
|
|
360
|
+
self._prune(now)
|
|
361
|
+
self._save()
|
|
362
|
+
dev = fresh
|
|
363
|
+
return dev
|
|
364
|
+
|
|
365
|
+
def _update(self, device_id: str, fn) -> bool:
|
|
366
|
+
with _locked():
|
|
367
|
+
self._reload_if_changed()
|
|
368
|
+
dev = next((d for d in self._devices if d.get("id") == device_id), None)
|
|
369
|
+
if dev is None:
|
|
370
|
+
return False
|
|
371
|
+
fn(dev)
|
|
372
|
+
self._save()
|
|
373
|
+
return True
|
|
374
|
+
|
|
375
|
+
def set_roots(self, device_id: str, roots: list[str] | None) -> bool:
|
|
376
|
+
"""Limit a device to `roots` (validated). None = whole
|
|
377
|
+
allowed_roots, a list limits it, an empty list = no folders."""
|
|
378
|
+
def fn(dev: dict) -> None:
|
|
379
|
+
if roots is None:
|
|
380
|
+
dev.pop("roots", None)
|
|
381
|
+
else:
|
|
382
|
+
dev["roots"] = list(roots)
|
|
383
|
+
return self._update(device_id, fn)
|
|
384
|
+
|
|
385
|
+
def set_grants(self, device_id: str, *, roots: list[str] | None | bool = False,
|
|
386
|
+
add_roots: list[str] | None = None, manage: bool | None = None,
|
|
387
|
+
terminal: bool | None = None,
|
|
388
|
+
require_passkey: bool | None = None,
|
|
389
|
+
quiet_exempt: bool | None = None, files: bool | None = None,
|
|
390
|
+
files_upload: bool | None = None) -> dict | None:
|
|
391
|
+
"""Change several grants in one write (the CLI's `devices set`).
|
|
392
|
+
`roots` False = keep, None = whole allowed_roots, a list limits it
|
|
393
|
+
([] = no folders); `add_roots` appends instead, and is ignored on a
|
|
394
|
+
device that already has every root. None elsewhere = keep. Returns
|
|
395
|
+
the updated device, or None when there is no such device."""
|
|
396
|
+
out: list = [None]
|
|
397
|
+
def fn(dev: dict) -> None:
|
|
398
|
+
if roots is None:
|
|
399
|
+
dev.pop("roots", None)
|
|
400
|
+
elif roots is not False:
|
|
401
|
+
dev["roots"] = list(roots)
|
|
402
|
+
if add_roots and dev.get("roots") is not None:
|
|
403
|
+
own = dev["roots"]
|
|
404
|
+
dev["roots"] = own + [r for r in add_roots if r not in own]
|
|
405
|
+
for key, val in (("manage_devices", manage), ("terminal", terminal),
|
|
406
|
+
("require_passkey", require_passkey),
|
|
407
|
+
("quiet_exempt", quiet_exempt), ("files", files),
|
|
408
|
+
("files_upload", files_upload)):
|
|
409
|
+
if val is not None:
|
|
410
|
+
dev[key] = bool(val)
|
|
411
|
+
out[0] = dict(dev)
|
|
412
|
+
return out[0] if self._update(device_id, fn) else None
|
|
413
|
+
|
|
414
|
+
def set_terminal(self, device_id: str, on: bool) -> bool:
|
|
415
|
+
return self._update(device_id, lambda dev: dev.__setitem__("terminal", bool(on)))
|
|
416
|
+
|
|
417
|
+
def name_taken(self, name: str, except_id: str | None = None) -> bool:
|
|
418
|
+
"""Is another device already called this, or has it as its id?
|
|
419
|
+
Compared case-folded and whitespace-collapsed, so "My iPhone" and
|
|
420
|
+
"my iphone" clash."""
|
|
421
|
+
wanted = _clean_name(name).casefold()
|
|
422
|
+
self._reload_if_changed()
|
|
423
|
+
return any((_clean_name(d.get("name", "")).casefold() == wanted
|
|
424
|
+
or str(d.get("id", "")).casefold() == wanted)
|
|
425
|
+
and d.get("id") != except_id for d in self._devices)
|
|
426
|
+
|
|
427
|
+
def resolve(self, ref: str) -> str | None:
|
|
428
|
+
"""Device id for an id or a name (the CLI takes either). An exact
|
|
429
|
+
id wins; names compare like name_taken."""
|
|
430
|
+
self._reload_if_changed()
|
|
431
|
+
if any(d.get("id") == ref for d in self._devices):
|
|
432
|
+
return ref
|
|
433
|
+
wanted = _clean_name(ref).casefold()
|
|
434
|
+
return next((d.get("id") for d in self._devices
|
|
435
|
+
if _clean_name(d.get("name", "")).casefold() == wanted), None)
|
|
436
|
+
|
|
437
|
+
def set_name(self, device_id: str, name: str) -> bool:
|
|
438
|
+
"""Rename a device. The caller checks name_taken first."""
|
|
439
|
+
clean = _clean_name(name)
|
|
440
|
+
if not clean:
|
|
441
|
+
return False
|
|
442
|
+
return self._update(device_id, lambda dev: dev.__setitem__("name", clean))
|
|
443
|
+
|
|
444
|
+
def set_locked(self, device_id: str, on: bool) -> bool:
|
|
445
|
+
"""Lock (or unlock) a device session without touching its grants.
|
|
446
|
+
Unlocking counts as activity, so the idle lock does not fire again
|
|
447
|
+
at once — also when the CLI unlocks, which cannot reach _active."""
|
|
448
|
+
def fn(dev: dict) -> None:
|
|
449
|
+
dev["locked"] = bool(on)
|
|
450
|
+
if not on:
|
|
451
|
+
dev["last_seen"] = time.time()
|
|
452
|
+
return self._update(device_id, fn)
|
|
453
|
+
|
|
454
|
+
def set_passkey(self, device_id: str, on: bool) -> bool:
|
|
455
|
+
"""Mark that this device session carries a passkey — risky actions
|
|
456
|
+
on it then need a fresh confirmation (passkey.needs_stepup)."""
|
|
457
|
+
return self._update(device_id, lambda dev: dev.__setitem__("passkey", bool(on)))
|
|
458
|
+
|
|
459
|
+
def set_require_passkey(self, device_id: str, on: bool) -> bool:
|
|
460
|
+
return self._update(device_id,
|
|
461
|
+
lambda dev: dev.__setitem__("require_passkey", bool(on)))
|
|
462
|
+
|
|
463
|
+
def clear_passkey(self, device_ids, still_used: set[str]) -> None:
|
|
464
|
+
"""After a credential is removed: devices left without any key lose
|
|
465
|
+
the passkey mark, or they would keep asking for a step-up (or wait
|
|
466
|
+
on an unlock) that nothing can give."""
|
|
467
|
+
for device_id in device_ids:
|
|
468
|
+
if device_id not in still_used:
|
|
469
|
+
self.set_passkey(device_id, False)
|
|
470
|
+
|
|
471
|
+
def revoke(self, device_id: str) -> bool:
|
|
472
|
+
with _locked():
|
|
473
|
+
self._reload_if_changed()
|
|
474
|
+
before = len(self._devices)
|
|
475
|
+
self._devices = [d for d in self._devices if d.get("id") != device_id]
|
|
476
|
+
changed = len(self._devices) != before
|
|
477
|
+
if changed:
|
|
478
|
+
self._save()
|
|
479
|
+
return changed
|
|
480
|
+
|
|
481
|
+
def list(self) -> list[dict]:
|
|
482
|
+
"""Public view of live devices (no hashes)."""
|
|
483
|
+
self._reload_if_changed()
|
|
484
|
+
now = time.time()
|
|
485
|
+
return [{
|
|
486
|
+
"id": d.get("id"), "name": d.get("name"),
|
|
487
|
+
"created_at": d.get("created_at"), "last_seen": d.get("last_seen"),
|
|
488
|
+
"roots": d.get("roots"), # None = all, [] = none
|
|
489
|
+
"manage_devices": bool(d.get("manage_devices")),
|
|
490
|
+
"terminal": bool(d.get("terminal")),
|
|
491
|
+
"passkey": bool(d.get("passkey")),
|
|
492
|
+
"require_passkey": bool(d.get("require_passkey")),
|
|
493
|
+
"locked": bool(d.get("locked")),
|
|
494
|
+
"quiet_exempt": bool(d.get("quiet_exempt")),
|
|
495
|
+
"files": bool(d.get("files")),
|
|
496
|
+
"files_upload": bool(d.get("files_upload")),
|
|
497
|
+
} for d in self._devices if now - d.get("last_seen", 0) < SESSION_IDLE_SECS]
|