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

delminio-client / kit / en / cassaforte-client

raw · sha256 8dfa51837554679b71d57ea8ff3f088c8ca0c0521bc9b82183ae9224eac6c17a

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} list                                     the secrets you can request (names and notes, never values; \u201ctime-bound\u201d = opens with a single approval)\n  {cmd} NAME[,NAME\u2026] \"<why>\" -- command [arguments\u2026]\n        requests the secrets from the administrator, with the why: the request reaches their phone.\n        Granted, the command starts with the secrets in its environment variables (NAME=value).\n        If an open time-bound access covers them all, it starts at once, without asking.\n        The command reads the variables: to use them in arguments, go through a shell \u2014\n        -- bash -c 'curl -u \"admin:$NAME\" \u2026'\n  {cmd} open NAME[,NAME\u2026]|--larghe \"<why>\"\n        time-bound access: a single approval for the secrets marked \u201ctime-bound\u201d (--larghe: all of them), for the time the app says.\n  {cmd} windows | close                          the time-bound access opened from here \xb7 close it all\n  {cmd} propose NAME \"<what it is for>\"\n        proposes a secret that is not there yet: the administrator approves it by entering the value.\n  {cmd} deposit NAME[,NAME\u2026] \"<what it is for>\" [--larga] [--dal-file FILE]\n        puts a value in the vault without showing it: from stdin (one name) or from a NAME=value file.\n        It becomes a secret when the administrator accepts it in the app.",
30    "non_collegato": "\u274c this repository isn't connected to Delminio (.claude/delminio.sh): run the connection again.",
31    "non_risponde": "\u274c Delminio is not responding ({url}): {errore}",
32    "nessun_segreto": "This space's vault is empty: the admin adds secrets from the app (Vault). If you need one, propose it by name.",
33    "nessuna_cassaforte": "This space has no vault: the admin creates it from the app (Vault).",
34    "uso_chiedi": "usage: {cmd} NAME[,NAME\u2026] \"<why>\" -- command [arguments\u2026]",
35    "chiesta": "\U0001f511 Request sent to the admin: {nomi}. Tell them in the chat too: they grant it from the app, on their phone.",
36    "aspetto": "   Waiting for approval (up to {secondi} s)\u2026",
37    "ancora_niente": "\u23f3 Not granted yet. When the admin decides, the decision reaches you on the channel: then run the same command again, identical, and it picks up this request.",
38    "negata": "\u270b Denied by {chi}{parole}. The command didn't start.",
39    "scaduta": "\u231b The request expired before anyone approved it: the command didn't start. If it's still needed, run it again and the request starts over.",
40    "consegna_rotta": "\u274c What arrived can't be opened (encrypted data altered, or it wasn't for this request): the command didn't start.",
41    "firma_falsa": "\u274c What arrived doesn't carry the vault's signature: it wasn't sent by an admin's device. The command didn't start; tell the admin.",
42    "firma_cambiata": "\u274c The vault's signing key isn't the one seen the first time ({file}): the command didn't start. If the admin really did recreate the vault, delete that file.",
43    "nomi_diversi": "\u274c Names different from the ones requested arrived: the command didn't start; tell the admin.",
44    "nome_vietato": "\u274c {nome} is a variable that changes what a command runs: it can't be requested from the vault.",
45    "impronta": "   Request fingerprint: {impronta} \u2014 in the app the admin sees the same one.",
46    "concessa": "\u2705 Granted by {chi}: the command starts.",
47    "comando_mancante": "\u274c the command after \u201c--\u201d is missing",
48    "uso_proponi": "usage: {cmd} proponi NAME \"<what it is for>\"",
49    "proposta": "\U0001f4dd Proposed {nome}: the admin sees it in the app and, if they approve it, adds the value. Tell them in chat too.",
50    "segno_larga": " \xb7 time-bound",
51    "finestra_chiesta": "\U0001f511 Time-bound access requested from the administrator for {n} secrets ({minuti} minutes from approval). Tell them in chat too: they approve it in the app, on their phone.",
52    "finestra_aperta": "\u2705 Time-bound access opened by {chi} until {ora}: {nomi}. Commands with these secrets start without asking.",
53    "finestra_usata": "\U0001f511 From the open time-bound access (until {ora}): the command starts.",
54    "finestra_finita": "\u231b A time-bound access opened from here is gone (closed or ended).",
55    "finestre_nessuna": "No time-bound access opened from here.",
56    "finestra_riga": "  until {ora}  {nomi}",
57    "finestre_chiuse": "\U0001f512 Time-bound access closed: {n}.",
58    "nessuna_larga": "No secret is marked \u201ctime-bound\u201d: the administrator marks them in the app, one by one.",
59    "uso_apri": "usage: {cmd} open NAME[,NAME\u2026]|--larghe \"<why>\"",
60    "uso_deposita": "usage: {cmd} deposit NAME[,NAME\u2026] \"<what it is for>\" [--larga] [--dal-file FILE]   (one name only: the value from stdin)",
61    "deposito_senza_chiave": "The vault has no deposit key yet: the app creates it when the administrator opens the vault from their device. Tell them, then run it again.",
62    "deposito_firma": "\u274c The deposit key does not carry the vault's signature: I encrypt nothing for it. Warn the administrator.",
63    "deposito_vuoto": "\u274c {nome}: no value (empty stdin, or not in the file). Nothing deposited.",
64    "deposito_stdin": "\u274c With several names the value does not come from stdin: use --dal-file FILE.",
65    "depositato": "\U0001f4e5 Deposited {nome}, encrypted for the vault: it becomes a secret when the administrator accepts it in the app. Tell them in chat too.",
66    "non_concessa": "\u274c The secrets did not arrive (denied, expired or not granted yet): nothing to do.",
67    "chiesta_tua": "\U0001f511 Request sent to the user's phone: {nomi}. It's their secret: they grant it from the app, on their phone. Tell them in the chat too.",
68    "finestra_chiesta_tua": "\U0001f511 Time-bound access requested from the user for {n} of their secrets ({minuti} minutes from approval): they approve it in the app, on their phone. Tell them in chat too.",
69    "impronta_tua": "   Request fingerprint: {impronta} \u2014 in the app, on their phone, the user sees the same one."
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:]))