Delminio — the client
Clonegit clone https://git.delminio.com/delminio-client2026.11.26-b027f1c · 26 Nov 2026

delminio-client / kit / it / cassaforte-client

raw · sha256 b8ec5525e2df6f69447edca9372f727da1d31a8841057cfb62073a3a582747cb

1#!/usr/bin/env python3
2# © 2026 Delminio — tutti i diritti riservati. Software proprietario: l'uso con Delminio è regolato dal contratto con cui si usa il servizio; la lettura e la verifica da LICENCE.
3"""La cassaforte da riga di comando (F747): un segreto arriva solo col sì della persona."""
4from __future__ import annotations
5import base64
6import hashlib
7import hmac
8import json
9import os
10import re
11import shlex
12import subprocess
13import sys
14import time
15import urllib.error
16import urllib.parse
17import urllib.request
18QUI = os.path.dirname(os.path.abspath(__file__))
19CMD = 'delminio cassaforte'
20ATTESA_S = int(os.environ.get('DELMINIO_CASSAFORTE_ATTESA', '100'))
21INFO = b'delminio-cassaforte-v1'
22FIRMA = b'delminio-cassaforte-firma-v1:'
23FIRMA_DEPOSITO = 'delminio-cassaforte-deposito-v1:'
24FIRMA_PASSAGGIO = 'delminio-cassaforte-passaggio-v1:'
25NOME_RE = re.compile('^[A-Z][A-Z0-9_]{0,63}$')
26NOMI_VIETATI = frozenset({'PATH', 'HOME', 'SHELL', 'IFS', 'ENV', 'BASH_ENV', 'CDPATH', 'PS4', 'PROMPT_COMMAND', 'SHELLOPTS', 'BASHOPTS', 'GLOBIGNORE', 'NODE_OPTIONS', 'NODE_PATH', 'PERL5OPT', 'PERL5LIB', 'PERLLIB', 'RUBYOPT', 'RUBYLIB', 'JAVA_TOOL_OPTIONS', '_JAVA_OPTIONS', 'GIT_SSH', 'GIT_SSH_COMMAND', 'GIT_EXEC_PATH', 'GIT_ASKPASS', 'SSH_ASKPASS', 'EDITOR', 'VISUAL', 'PAGER', 'BROWSER', 'TMPDIR', 'GIT_PROXY_COMMAND', 'GIT_TEMPLATE_DIR', 'ZDOTDIR', 'GCONV_PATH', 'NODE_EXTRA_CA_CERTS', 'SSL_CERT_FILE', 'SSL_CERT_DIR', 'REQUESTS_CA_BUNDLE', 'CURL_CA_BUNDLE', 'HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'NO_PROXY', 'http_proxy', 'https_proxy', 'all_proxy', 'no_proxy'})
27PREFISSI_VIETATI = ('LD_', 'DYLD_', 'PYTHON', 'BASH_FUNC_', 'GIT_CONFIG', 'LUA_')
28FRASI = {
29    "aiuto": "  {cmd} elenco                                   i segreti che si possono chiedere (nomi e note, mai valori; \xaba tempo\xbb = si apre con una sola approvazione)\n  {cmd} NOME[,NOME\u2026] \"<perch\xe9>\" -- comando [argomenti\u2026]\n        chiede i segreti all'amministratore, col perch\xe9: la richiesta arriva sul suo telefono.\n        Concessa, il comando parte coi segreti nelle sue variabili d'ambiente (NOME=valore).\n        Se un accesso a tempo aperto li copre tutti, parte subito, senza chiedere.\n        Le variabili le legge il comando: per usarle negli argomenti, passa da una shell \u2014\n        -- bash -c 'curl -u \"admin:$NOME\" \u2026'\n  {cmd} apri NOME[,NOME\u2026]|--larghe \"<perch\xe9>\"\n        l'accesso a tempo: una sola approvazione per i segreti segnati \xaba tempo\xbb (--larghe: tutti), per il tempo che dice l'app.\n  {cmd} finestre | chiudi                        gli accessi a tempo aperti da qui \xb7 chiuderli tutti\n  {cmd} proponi NOME \"<a cosa serve>\"\n        propone un segreto che non c'\xe8 ancora: l'amministratore lo approva mettendoci il valore.\n  {cmd} deposita NOME[,NOME\u2026] \"<a cosa serve>\" [--larga] [--dal-file FILE]\n        mette un valore nella cassaforte senza mostrarlo: da stdin (un nome) o da un file NOME=valore.\n        Diventa un segreto quando l'amministratore lo accetta dall'app.",
30    "non_collegato": "\u274c questo repo non \xe8 collegato a Delminio (.claude/delminio.sh): rilancia il collegamento.",
31    "non_risponde": "\u274c Delminio non risponde ({url}): {errore}",
32    "nessun_segreto": "La cassaforte di questo spazio \xe8 vuota: i segreti li aggiunge l'amministratore dall'app (Cassaforte). Se ne serve uno, proponilo col suo nome.",
33    "nessuna_cassaforte": "In questo spazio la cassaforte non c'\xe8: la crea l'amministratore dall'app (Cassaforte).",
34    "uso_chiedi": "uso: {cmd} NOME[,NOME\u2026] \"<perch\xe9>\" -- comando [argomenti\u2026]",
35    "chiesta": "\U0001f511 Richiesta mandata all'amministratore: {nomi}. Diglielo anche in chat: la concede dall'app, sul telefono.",
36    "aspetto": "   Aspetto l'approvazione fino a {secondi} s\u2026",
37    "ancora_niente": "\u23f3 Non ancora concessa. Quando l'amministratore decide, la decisione ti arriva sul canale: rilancia allora lo stesso comando, identico, e riprende questa richiesta.",
38    "negata": "\u270b Negata da {chi}{parole}. Il comando non \xe8 partito.",
39    "scaduta": "\u231b La richiesta \xe8 scaduta senza approvazione: il comando non \xe8 partito. Se serve ancora, rilancialo e la richiesta riparte.",
40    "consegna_rotta": "\u274c Ci\xf2 che \xe8 arrivato non si apre (cifrato alterato, o non era per questa richiesta): il comando non \xe8 partito.",
41    "firma_falsa": "\u274c Ci\xf2 che \xe8 arrivato non porta la firma della cassaforte: non l'ha mandato un dispositivo dell'amministratore. Il comando non \xe8 partito; avvisa l'amministratore.",
42    "firma_cambiata": "\u274c La chiave di firma della cassaforte non \xe8 quella vista la prima volta ({file}): il comando non \xe8 partito. Se l'amministratore ha davvero rifatto la cassaforte, cancella quel file.",
43    "nomi_diversi": "\u274c Sono arrivati nomi diversi da quelli chiesti: il comando non \xe8 partito; avvisa l'amministratore.",
44    "nome_vietato": "\u274c {nome} \xe8 una variabile che cambia cosa esegue un comando: non si chiede alla cassaforte.",
45    "impronta": "   Impronta della richiesta: {impronta} \u2014 nell'app l'amministratore vede la stessa.",
46    "concessa": "\u2705 Concessa da {chi}: parte il comando.",
47    "comando_mancante": "\u274c manca il comando dopo \xab--\xbb",
48    "uso_proponi": "uso: {cmd} proponi NOME \"<a cosa serve>\"",
49    "proposta": "\U0001f4dd Proposto {nome}: l'amministratore lo vede nell'app e, se lo approva, ci mette il valore. Diglielo anche in chat.",
50    "segno_larga": " \xb7 a tempo",
51    "finestra_chiesta": "\U0001f511 Accesso a tempo chiesto all'amministratore per {n} segreti ({minuti} minuti dall'approvazione). Diglielo anche in chat: lo approva dall'app, sul telefono.",
52    "finestra_aperta": "\u2705 Accesso a tempo aperto da {chi} fino alle {ora}: {nomi}. I comandi con questi segreti partono senza chiedere.",
53    "finestra_usata": "\U0001f511 Dall'accesso a tempo aperto (fino alle {ora}): parte il comando.",
54    "finestra_finita": "\u231b Un accesso a tempo aperto da qui non c'\xe8 pi\xf9 (chiuso o finito).",
55    "finestre_nessuna": "Nessun accesso a tempo aperto da qui.",
56    "finestra_riga": "  fino alle {ora}  {nomi}",
57    "finestre_chiuse": "\U0001f512 Accessi a tempo chiusi: {n}.",
58    "nessuna_larga": "Nessun segreto \xe8 segnato \xaba tempo\xbb: li segna l'amministratore dall'app, uno per uno.",
59    "uso_apri": "uso: {cmd} apri NOME[,NOME\u2026]|--larghe \"<perch\xe9>\"",
60    "uso_deposita": "uso: {cmd} deposita NOME[,NOME\u2026] \"<a cosa serve>\" [--larga] [--dal-file FILE]   (un nome solo: il valore da stdin)",
61    "deposito_senza_chiave": "La cassaforte non ha ancora la chiave dei depositi: la crea l'app quando l'amministratore la apre dal suo dispositivo. Diglielo, poi rilancia.",
62    "deposito_firma": "\u274c La chiave dei depositi non porta la firma della cassaforte: non ci cifro niente. Avvisa l'amministratore.",
63    "deposito_vuoto": "\u274c {nome}: nessun valore (stdin vuoto, o non c'\xe8 nel file). Non ho depositato niente.",
64    "deposito_stdin": "\u274c Con pi\xf9 nomi il valore non viene da stdin: usa --dal-file FILE.",
65    "depositato": "\U0001f4e5 Depositato {nome}, cifrato per la cassaforte: diventa un segreto quando l'amministratore lo accetta dall'app. Diglielo anche in chat.",
66    "non_concessa": "\u274c I segreti non sono arrivati (negati, scaduti o non ancora concessi): niente da fare.",
67    "chiesta_tua": "\U0001f511 Richiesta mandata al telefono del tuo utente: {nomi}. \xc8 un segreto suo: la concede lui dall'app, sul suo telefono. Diglielo anche in chat.",
68    "finestra_chiesta_tua": "\U0001f511 Accesso a tempo chiesto alla persona con cui lavori, per {n} segreti suoi ({minuti} minuti dall'approvazione): lo approva dall'app, sul telefono. Diglielo anche in chat.",
69    "impronta_tua": "   Impronta della richiesta: {impronta} \u2014 nell'app, sul suo telefono, il tuo utente vede la stessa."
70}
71
72def F(chiave: str, **sost) -> str:
73    t = FRASI.get(chiave, chiave)
74    for k, v in sost.items():
75        t = t.replace('{' + k + '}', str(v))
76    return t
77
78class Rifiuto(Exception):
79
80    def __init__(self, messaggio: str, stato: int=0):
81        super().__init__(messaggio)
82        self.stato = stato
83_P = 2 ** 255 - 19
84_A24 = 121665
85
86def x25519(k: bytes, u: bytes) -> bytes:
87    kk = bytearray(k)
88    kk[0] &= 248
89    kk[31] &= 127
90    kk[31] |= 64
91    n = int.from_bytes(bytes(kk), 'little')
92    x1 = int.from_bytes(u, 'little') & (1 << 255) - 1
93    x2, z2, x3, z3 = (1, 0, x1, 1)
94    swap = 0
95    for t in reversed(range(255)):
96        kt = n >> t & 1
97        if swap ^ kt:
98            x2, x3, z2, z3 = (x3, x2, z3, z2)
99        swap = kt
100        a, b = ((x2 + z2) % _P, (x2 - z2) % _P)
101        aa, bb = (a * a % _P, b * b % _P)
102        e = (aa - bb) % _P
103        c, d = ((x3 + z3) % _P, (x3 - z3) % _P)
104        da, cb = (d * a % _P, c * b % _P)
105        x3, z3 = ((da + cb) ** 2 % _P, x1 * (da - cb) ** 2 % _P)
106        x2, z2 = (aa * bb % _P, e * (aa + _A24 * e) % _P)
107    if swap:
108        x2, z2 = (x3, z3)
109    return (x2 * pow(z2, _P - 2, _P) % _P).to_bytes(32, 'little')
110_Q = 115792089210356248762697446949407573530086143415290314195533631308867097853951
111_B = 41058363725152142129326129780047268409114441015993725554835256314039467401291
112_N = 115792089210356248762697446949407573529996955224135760342422259061068512044369
113_G = (48439561293906451759052585252797914202762949526041747995844080717082404635286, 36134250956749795798585127919587881956611106672985015071877198253568414405109)
114
115def _somma(p1, p2):
116    if p1 is None:
117        return p2
118    if p2 is None:
119        return p1
120    if p1[0] == p2[0] and (p1[1] + p2[1]) % _Q == 0:
121        return None
122    if p1 == p2:
123        m = 3 * (p1[0] * p1[0] - 1) * pow(2 * p1[1], _Q - 2, _Q) % _Q
124    else:
125        m = (p2[1] - p1[1]) * pow(p2[0] - p1[0], _Q - 2, _Q) % _Q
126    x = (m * m - p1[0] - p2[0]) % _Q
127    return (x, (m * (p1[0] - x) - p1[1]) % _Q)
128
129def _per(k: int, p):
130    r = None
131    while k:
132        if k & 1:
133            r = _somma(r, p)
134        p = _somma(p, p)
135        k >>= 1
136    return r
137
138def verifica_firma(pub: bytes, messaggio: bytes, firma: bytes) -> bool:
139    if len(pub) != 65 or pub[0] != 4 or len(firma) != 64:
140        return False
141    x, y = (int.from_bytes(pub[1:33], 'big'), int.from_bytes(pub[33:], 'big'))
142    if not (x < _Q and y < _Q) or (y * y - x * x * x + 3 * x - _B) % _Q:
143        return False
144    r, s = (int.from_bytes(firma[:32], 'big'), int.from_bytes(firma[32:], 'big'))
145    if not (0 < r < _N and 0 < s < _N):
146        return False
147    z = int.from_bytes(hashlib.sha256(messaggio).digest(), 'big')
148    w = pow(s, _N - 2, _N)
149    punto = _somma(_per(z * w % _N, _G), _per(r * w % _N, (x, y)))
150    return punto is not None and punto[0] % _N == r
151
152def pubblica(privata: bytes) -> bytes:
153    return x25519(privata, 9 .to_bytes(32, 'little'))
154
155def hkdf(chiave: bytes, sale: bytes, info: bytes, lunghezza: int) -> bytes:
156    prk = hmac.new(sale, chiave, hashlib.sha256).digest()
157    out, blocco, i = (b'', b'', 1)
158    while len(out) < lunghezza:
159        blocco = hmac.new(prk, blocco + info + bytes([i]), hashlib.sha256).digest()
160        out += blocco
161        i += 1
162    return out[:lunghezza]
163
164def flusso(chiave: bytes, n: int) -> bytes:
165    out = b''
166    i = 0
167    while len(out) < n:
168        out += hmac.new(chiave, i.to_bytes(8, 'big'), hashlib.sha256).digest()
169        i += 1
170    return out[:n]
171
172def chiavi(condiviso: bytes, pub_client: bytes, eph: bytes, rid: str) -> tuple[bytes, bytes]:
173    k = hkdf(condiviso, pub_client + eph, INFO + b':' + rid.encode(), 64)
174    return (k[:32], k[32:])
175
176def apri(privata: bytes, pub_client: bytes, rid: str, consegna: dict, firma_pub: bytes, nomi: list[str]) -> dict:
177    eph, ct, tag, firma = (_b64d(consegna.get(x, '')) for x in ('eph', 'ct', 'tag', 'firma'))
178    if len(eph) != 32 or len(tag) != 32:
179        raise Rifiuto(F('consegna_rotta'))
180    if not verifica_firma(firma_pub, FIRMA + rid.encode() + pub_client + eph + ct + tag, firma):
181        raise Rifiuto(F('firma_falsa'))
182    condiviso = x25519(privata, eph)
183    if condiviso == bytes(32):
184        raise Rifiuto(F('consegna_rotta'))
185    k_cifra, k_tag = chiavi(condiviso, pub_client, eph, rid)
186    if not hmac.compare_digest(hmac.new(k_tag, eph + ct, hashlib.sha256).digest(), tag):
187        raise Rifiuto(F('consegna_rotta'))
188    chiaro = bytes((a ^ b for a, b in zip(ct, flusso(k_cifra, len(ct)))))
189    try:
190        valori = json.loads(chiaro.decode('utf-8'))
191    except (UnicodeDecodeError, ValueError):
192        raise Rifiuto(F('consegna_rotta')) from None
193    if not isinstance(valori, dict) or not all((isinstance(v, str) for v in valori.values())):
194        raise Rifiuto(F('consegna_rotta'))
195    if set(valori) != set(nomi):
196        raise Rifiuto(F('nomi_diversi'))
197    return valori
198
199def vietato(nome: str) -> bool:
200    return not NOME_RE.match(nome) or nome in NOMI_VIETATI or nome.startswith(PREFISSI_VIETATI)
201
202def _firme() -> tuple[str, dict]:
203    percorso = os.path.join(_sospese(), 'firme.json')
204    try:
205        with open(percorso, encoding='utf-8') as f:
206            return (percorso, json.load(f))
207    except (OSError, ValueError):
208        return (percorso, {})
209
210def _di_chi() -> str:
211    return hashlib.sha256(TOKEN.encode()).hexdigest()[:16]
212
213def _spazio() -> str:
214    try:
215        pezzo = TOKEN.split('.')[1]
216        cli = json.loads(base64.urlsafe_b64decode(pezzo + '=' * (-len(pezzo) % 4))).get('cli') or ''
217    except (IndexError, ValueError, AttributeError):
218        cli = ''
219    return URL if cli in ('', 'unico') else f'{URL}#{cli}'
220
221def _segue_la_catena(da: str, a: str, passaggi) -> bool:
222    passaggi = [x for x in passaggi or [] if isinstance(x, dict)]
223    adesso = da
224    for _ in range(len(passaggi)):
225        p = next((x for x in passaggi if x.get('da') == adesso), None)
226        try:
227            if p is None or not verifica_firma(_b64d(adesso), (FIRMA_PASSAGGIO + str(p.get('a'))).encode(), _b64d(str(p.get('firma') or ''))):
228                return False
229        except (ValueError, TypeError):
230            return False
231        adesso = str(p['a'])
232        if adesso == a:
233            return True
234    return False
235
236def firma_ricordata(pub_b64: str, passaggi=None) -> bytes:
237    percorso, note = _firme()
238    if not pub_b64:
239        raise Rifiuto(F('firma_falsa'))
240    vista = note.get(_spazio())
241    if vista and vista != pub_b64 and (not _segue_la_catena(vista, pub_b64, passaggi)):
242        raise Rifiuto(F('firma_cambiata', file=percorso))
243    return _b64d(pub_b64)
244
245def ricorda_firma(pub_b64: str) -> None:
246    percorso, note = _firme()
247    if note.get(_spazio()) == pub_b64:
248        return
249    note[_spazio()] = pub_b64
250    fd = os.open(percorso, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 384)
251    with os.fdopen(fd, 'w', encoding='utf-8') as f:
252        json.dump(note, f)
253
254def impronta_richiesta(pub: bytes) -> str:
255    h = hashlib.sha256(pub).hexdigest()[:8].upper()
256    return h[:4] + '-' + h[4:]
257
258def _b64(b: bytes) -> str:
259    return base64.b64encode(b).decode()
260
261def _b64d(s: str) -> bytes:
262    try:
263        return base64.b64decode(s.replace('-', '+').replace('_', '/') + '=' * (-len(s) % 4))
264    except (ValueError, TypeError):
265        return b''
266
267def _ambiente() -> tuple[str, str, str]:
268    try:
269        out = subprocess.run(['bash', os.path.join(QUI, 'delminio.sh'), 'ambiente'], capture_output=True, text=True, timeout=15).stdout.splitlines()
270    except (OSError, subprocess.TimeoutExpired):
271        out = []
272    url, file_token, sessione = (out + ['', '', ''])[:3]
273    try:
274        with open(file_token, encoding='utf-8') as f:
275            token = f.read().strip()
276    except OSError:
277        token = ''
278    if not url or not token:
279        raise Rifiuto(F('non_collegato'))
280    return (url.rstrip('/'), token, sessione)
281URL, TOKEN, SESSIONE = ('', '', '')
282
283def _http(metodo: str, percorso: str, corpo: dict | None=None) -> dict:
284    dati = json.dumps(corpo).encode() if corpo is not None else None
285    req = urllib.request.Request(f'{URL}/api/cassaforte{percorso}', data=dati, method=metodo, headers={'Authorization': f'Bearer {TOKEN}', 'Content-Type': 'application/json'})
286    try:
287        with urllib.request.urlopen(req, timeout=30) as r:
288            return json.loads(r.read().decode())
289    except urllib.error.HTTPError as e:
290        raw = e.read().decode()
291        try:
292            msg = json.loads(raw).get('error', raw)
293        except ValueError:
294            msg = raw
295        raise Rifiuto(f'❌ {msg}', e.code) from None
296    except (urllib.error.URLError, OSError) as e:
297        raise Rifiuto(F('non_risponde', url=URL, errore=e)) from None
298
299def _sospese() -> str:
300    d = os.path.join(os.environ.get('XDG_CACHE_HOME') or os.path.expanduser('~/.cache'), 'delminio-cassaforte')
301    os.makedirs(d, mode=448, exist_ok=True)
302    os.chmod(d, 448)
303    return d
304
305def _impronta(nomi: list[str], perche: str, comando: list[str]) -> str:
306    return hashlib.sha256(json.dumps([URL, nomi, perche, comando]).encode()).hexdigest()[:32]
307
308def _riprendi(chiave: str) -> dict | None:
309    try:
310        with open(os.path.join(_sospese(), chiave), encoding='utf-8') as f:
311            return json.load(f)
312    except (OSError, ValueError):
313        return None
314
315def _metti_da_parte(chiave: str, dati: dict) -> None:
316    percorso = os.path.join(_sospese(), chiave)
317    fd = os.open(percorso, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 384)
318    with os.fdopen(fd, 'w', encoding='utf-8') as f:
319        json.dump(dati, f)
320
321def _dimentica(chiave: str) -> None:
322    try:
323        os.remove(os.path.join(_sospese(), chiave))
324    except OSError:
325        pass
326
327def _finestre_dir() -> str:
328    run = os.environ.get('XDG_RUNTIME_DIR') or ''
329    d = os.path.join(run, 'delminio-cassaforte') if run and os.path.isdir(run) else os.path.join(_sospese(), 'finestre')
330    os.makedirs(d, mode=448, exist_ok=True)
331    os.chmod(d, 448)
332    return d
333
334def _ora(iso: str) -> str:
335    try:
336        from datetime import datetime
337        return datetime.fromisoformat(iso).astimezone().strftime('%H:%M')
338    except (TypeError, ValueError):
339        return '?'
340
341def _finestre() -> list[dict]:
342    from datetime import datetime, timezone
343    adesso = datetime.now(timezone.utc)
344    vive = []
345    cartella = _finestre_dir()
346    for nome in sorted(os.listdir(cartella)):
347        percorso = os.path.join(cartella, nome)
348        try:
349            with open(percorso, encoding='utf-8') as f:
350                w = json.load(f)
351            finita = datetime.fromisoformat(w['scade']) <= adesso
352        except (OSError, ValueError, KeyError, TypeError):
353            finita = True
354            w = {}
355        if finita:
356            try:
357                os.remove(percorso)
358            except OSError:
359                pass
360        elif w.get('spazio') == _spazio() and w.get('token') == _di_chi():
361            w['_file'] = percorso
362            vive.append(w)
363    return vive
364
365def _togli_finestra(w: dict) -> None:
366    try:
367        os.remove(w['_file'])
368    except (OSError, KeyError):
369        pass
370
371def _dalla_finestra(nomi: list[str], comando: str) -> dict | None:
372    for w in _finestre():
373        if not set(nomi) <= set(w['nomi']):
374            continue
375        try:
376            r = _http('GET', '/richiesta/' + urllib.parse.quote(w['id']) + '?comando=' + urllib.parse.quote(comando[:500]))
377        except Rifiuto as e:
378            if e.stato != 404:
379                raise
380            continue
381        if not r.get('consegna'):
382            _togli_finestra(w)
383            print(F('finestra_finita'), file=sys.stderr)
384            continue
385        firma_pub = r.get('firma_pub') or ''
386        valori = apri(_b64d(w['privata']), _b64d(w['pub']), w['id'], r['consegna'], firma_ricordata(firma_pub, r.get('passaggi')), w['nomi'])
387        print(F('finestra_usata', ora=_ora(w['scade'])), file=sys.stderr)
388        return {n: valori[n] for n in nomi}
389    return None
390
391def elenco() -> int:
392    d = _http('GET', '/elenco')
393    if not d.get('esiste'):
394        print(F('nessuna_cassaforte'))
395        return 0
396    if not d.get('segreti'):
397        print(F('nessun_segreto'))
398        return 0
399    for s in d['segreti']:
400        print(f"  {s['nome']}" + (F('segno_larga') if s.get('larga') else '') + (f" — {s['nota']}" if s.get('nota') else ''))
401    return 0
402
403def proponi(argomenti: list[str]) -> int:
404    if len(argomenti) < 2:
405        raise Rifiuto(F('uso_proponi', cmd=CMD))
406    nome = argomenti[0].strip()
407    if vietato(nome):
408        raise Rifiuto(F('nome_vietato', nome=nome))
409    _http('POST', '/proponi', {'nome': nome, 'nota': ' '.join(argomenti[1:]), 'sessione': SESSIONE})
410    print(F('proposta', nome=nome))
411    return 0
412
413def _nomi(testo: str) -> list[str]:
414    nomi = list(dict.fromkeys((n for n in testo.replace(' ', ',').split(',') if n)))
415    for n in nomi:
416        if vietato(n):
417            raise Rifiuto(F('nome_vietato', nome=n))
418    return nomi
419
420def _attendi(nomi: list[str], perche: str, comando: list[str], finestra: bool):
421    chiave = _impronta(nomi, perche, (['--finestra'] if finestra else []) + comando)
422    sospesa = _riprendi(chiave)
423    gia = None
424    if sospesa is not None:
425        try:
426            gia = _http('GET', '/richiesta/' + urllib.parse.quote(sospesa['id']))
427        except Rifiuto as e:
428            if e.stato != 404:
429                raise
430            _dimentica(chiave)
431            sospesa = None
432        if sospesa is not None and (not gia.get('consegna')) and (gia.get('stato') in ('scaduta', 'ritirata', 'chiusa')):
433            _dimentica(chiave)
434            sospesa, gia = (None, None)
435    if sospesa is None:
436        privata = os.urandom(32)
437        pub = pubblica(privata)
438        r = _http('POST', '/chiedi', {'nomi': nomi, 'perche': perche, 'comando': shlex.join(comando), 'sessione': SESSIONE, 'pub': _b64(pub), 'finestra': finestra})
439        sospesa = {'id': r['id'], 'privata': _b64(privata), 'pub': _b64(pub), 'tua': r.get('decide') == 'tu'}
440        _metti_da_parte(chiave, sospesa)
441        tua = sospesa['tua']
442        minuti = (r.get('finestra_s') or 0) // 60
443        if finestra:
444            print(F('finestra_chiesta_tua', n=len(nomi), minuti=minuti) if tua else F('finestra_chiesta', n=len(nomi), minuti=minuti), file=sys.stderr)
445        else:
446            print(F('chiesta_tua', nomi=', '.join(nomi)) if tua else F('chiesta', nomi=', '.join(nomi)), file=sys.stderr)
447    imp = impronta_richiesta(_b64d(sospesa['pub']))
448    print(F('impronta_tua', impronta=imp) if sospesa.get('tua') else F('impronta', impronta=imp), file=sys.stderr)
449    print(F('aspetto', secondi=ATTESA_S), file=sys.stderr)
450    fine = time.monotonic() + ATTESA_S
451    while True:
452        r = gia if gia is not None else _http('GET', '/richiesta/' + urllib.parse.quote(sospesa['id']))
453        gia = None
454        stato = r.get('stato')
455        if r.get('consegna'):
456            _dimentica(chiave)
457            firma_pub = r.get('firma_pub') or ''
458            valori = apri(_b64d(sospesa['privata']), _b64d(sospesa['pub']), sospesa['id'], r['consegna'], firma_ricordata(firma_pub, r.get('passaggi')), nomi)
459            ricorda_firma(firma_pub)
460            return (sospesa, r, valori)
461        if stato == 'negata':
462            _dimentica(chiave)
463            parole = r.get('parole') or ''
464            print(F('negata', chi=r.get('deciso_da') or '?', parole=f': «{parole}»' if parole else ''), file=sys.stderr)
465            return 3
466        if stato in ('scaduta', 'ritirata', 'chiusa'):
467            _dimentica(chiave)
468            print(F('scaduta'), file=sys.stderr)
469            return 3
470        if time.monotonic() > fine:
471            print(F('ancora_niente'), file=sys.stderr)
472            return 4
473        time.sleep(2)
474
475def valori(nomi: list[str], perche: str, comando: str) -> dict:
476    global URL, TOKEN, SESSIONE
477    if not URL:
478        URL, TOKEN, SESSIONE = _ambiente()
479    nomi = _nomi(','.join(nomi))
480    dalla = _dalla_finestra(nomi, comando)
481    if dalla is not None:
482        return dalla
483    esito = _attendi(nomi, perche, shlex.split(comando) or [comando], False)
484    if isinstance(esito, int):
485        raise Rifiuto(F('non_concessa'), esito)
486    print(F('concessa', chi=esito[1].get('deciso_da') or '?'), file=sys.stderr)
487    return esito[2]
488
489def chiedi(argomenti: list[str]) -> int:
490    if '--' not in argomenti or argomenti.index('--') < 2:
491        raise Rifiuto(F('uso_chiedi', cmd=CMD))
492    i = argomenti.index('--')
493    nomi = _nomi(argomenti[0])
494    perche = ' '.join(argomenti[1:i])
495    comando = argomenti[i + 1:]
496    if not comando:
497        raise Rifiuto(F('comando_mancante'))
498    dati = _dalla_finestra(nomi, shlex.join(comando))
499    if dati is None:
500        esito = _attendi(nomi, perche, comando, False)
501        if isinstance(esito, int):
502            return esito
503        print(F('concessa', chi=esito[1].get('deciso_da') or '?'), file=sys.stderr)
504        dati = esito[2]
505    sys.stderr.flush()
506    os.execvpe(comando[0], comando, dict(os.environ, **dati))
507
508def apri_finestra(argomenti: list[str]) -> int:
509    if len(argomenti) < 2:
510        raise Rifiuto(F('uso_apri', cmd=CMD))
511    if argomenti[0] == '--larghe':
512        nomi = [s['nome'] for s in _http('GET', '/elenco').get('segreti', []) if s.get('larga')]
513        if not nomi:
514            raise Rifiuto(F('nessuna_larga'))
515    else:
516        nomi = _nomi(argomenti[0])
517    esito = _attendi(nomi, ' '.join(argomenti[1:]), [], True)
518    if isinstance(esito, int):
519        return esito
520    sospesa, r, _ = esito
521    scade = r.get('scade') or ''
522    percorso = os.path.join(_finestre_dir(), 'finestra-' + hashlib.sha256(_spazio().encode()).hexdigest()[:8] + '-' + re.sub('[^A-Za-z0-9_-]', '', sospesa['id']) + '.json')
523    fd = os.open(percorso, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 384)
524    with os.fdopen(fd, 'w', encoding='utf-8') as f:
525        json.dump({**sospesa, 'nomi': nomi, 'scade': scade, 'spazio': _spazio(), 'token': _di_chi()}, f)
526    print(F('finestra_aperta', chi=r.get('deciso_da') or '?', ora=_ora(scade), nomi=', '.join(nomi)), file=sys.stderr)
527    return 0
528
529def finestre() -> int:
530    vive = _finestre()
531    if not vive:
532        print(F('finestre_nessuna'))
533    for w in vive:
534        print(F('finestra_riga', ora=_ora(w['scade']), nomi=', '.join(w['nomi'])))
535    return 0
536
537def chiudi() -> int:
538    n = 0
539    for w in _finestre():
540        try:
541            _http('POST', '/richiesta/' + urllib.parse.quote(w['id']) + '/chiudi', {})
542        except Rifiuto as e:
543            if e.stato != 404:
544                raise
545        _togli_finestra(w)
546        n += 1
547    print(F('finestre_chiuse', n=n))
548    return 0
549
550def _da_file(percorso: str, nomi: list[str]) -> dict:
551    trovati = {}
552    with open(percorso, encoding='utf-8') as f:
553        for riga in f:
554            riga = riga.strip()
555            k, uguale, v = riga.partition('=')
556            if uguale and k.strip() in nomi:
557                trovati[k.strip()] = v.strip().strip('\'"')
558    return trovati
559
560def cifra_deposito(pub: bytes, nome: str, valore: str) -> dict:
561    privata = os.urandom(32)
562    eph = pubblica(privata)
563    condiviso = x25519(privata, pub)
564    if condiviso == bytes(32):
565        raise Rifiuto(F('deposito_firma'))
566    k = hkdf(condiviso, pub + eph, INFO + b':deposito:' + nome.encode(), 64)
567    dati = valore.encode('utf-8')
568    ct = bytes((a ^ b for a, b in zip(dati, flusso(k[:32], len(dati)))))
569    tag = hmac.new(k[32:], eph + ct, hashlib.sha256).digest()
570    return {'eph': _b64(eph), 'ct': _b64(ct), 'tag': _b64(tag)}
571
572def deposita(argomenti: list[str]) -> int:
573    larga = '--larga' in argomenti
574    argomenti = [a for a in argomenti if a != '--larga']
575    file = None
576    if '--dal-file' in argomenti:
577        i = argomenti.index('--dal-file')
578        if i + 1 >= len(argomenti):
579            raise Rifiuto(F('uso_deposita', cmd=CMD))
580        file = argomenti[i + 1]
581        argomenti = argomenti[:i] + argomenti[i + 2:]
582    if len(argomenti) < 2:
583        raise Rifiuto(F('uso_deposita', cmd=CMD))
584    nomi, nota = (_nomi(argomenti[0]), ' '.join(argomenti[1:]))
585    d = _http('GET', '/elenco')
586    if not d.get('esiste'):
587        raise Rifiuto(F('nessuna_cassaforte'))
588    dep = d.get('deposito') or {}
589    if not dep.get('pub'):
590        raise Rifiuto(F('deposito_senza_chiave'))
591    fp = firma_ricordata(dep.get('firma_pub') or '', dep.get('passaggi'))
592    if not verifica_firma(fp, (FIRMA_DEPOSITO + dep['pub']).encode(), _b64d(dep.get('firma') or '')):
593        raise Rifiuto(F('deposito_firma'))
594    ricorda_firma(dep['firma_pub'])
595    if file:
596        trovati = _da_file(file, nomi)
597    elif len(nomi) == 1:
598        trovati = {nomi[0]: sys.stdin.read().rstrip('\n')}
599    else:
600        raise Rifiuto(F('deposito_stdin'))
601    for n in nomi:
602        if not trovati.get(n):
603            raise Rifiuto(F('deposito_vuoto', nome=n))
604    pub = _b64d(dep['pub'])
605    for n in nomi:
606        _http('POST', '/proponi', {'nome': n, 'nota': nota, 'sessione': SESSIONE, 'larga': larga, 'deposito': cifra_deposito(pub, n, trovati[n]), 'per': dep['pub']})
607        print(F('depositato', nome=n))
608    return 0
609
610def main(argv: list[str]) -> int:
611    global URL, TOKEN, SESSIONE
612    if not argv or argv[0] in ('aiuto', 'help', '-h', '--help'):
613        print(F('aiuto', cmd=CMD))
614        return 0
615    try:
616        URL, TOKEN, SESSIONE = _ambiente()
617        gesti = {'elenco': lambda: elenco(), 'proponi': lambda: proponi(argv[1:]), 'apri': lambda: apri_finestra(argv[1:]), 'finestre': lambda: finestre(), 'chiudi': lambda: chiudi(), 'deposita': lambda: deposita(argv[1:])}
618        if argv[0] in gesti:
619            return gesti[argv[0]]()
620        return chiedi(argv)
621    except Rifiuto as e:
622        print(str(e), file=sys.stderr)
623        return 1
624if __name__ == '__main__':
625    sys.exit(main(sys.argv[1:]))