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

delminio-client / kit / en / firme-client

raw · sha256 380cced6efc7202607d185f4e21b85b6590e08f6430c080b59361fdda19971e8

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"""Le firme delle modifiche da un terminale, dai ganci git e da una CI (B923)."""
4from __future__ import annotations
5import base64
6import datetime
7import hashlib
8import json
9import os
10import re
11import shutil
12import subprocess
13import sys
14import tempfile
15import urllib.error
16import urllib.request
17CMD = 'delminio firme'
18URL = os.environ.get('DELMINIO_URL', '').rstrip('/')
19TOKEN = os.environ.get('DELMINIO_TOKEN', '')
20STATO = os.environ.get('DELMINIO_STATO', '')
21MASSIMO = 20000
22COMMIT_MAX = 500
23RAMO_MAX = 200
24APP_ANDROID = ('jG9UXQXhlWwgZvpNwGNDmhcDbR_94LnCQOAcyOOgJqg',)
25PROVE_TEMPO = 900
26COMANDI = {
27    "carta": {
28        "catena": "catena",
29        "chain": "catena",
30        "check": "controlla",
31        "checks": "prove",
32        "ci": "ci",
33        "controlla": "controlla",
34        "description": "descrizione",
35        "descrizione": "descrizione",
36        "esporta": "esporta",
37        "export": "esporta",
38        "prove": "prove",
39        "report": "resoconto",
40        "resoconto": "resoconto",
41        "review": "revisione",
42        "revisione": "revisione"
43    }
44}
45FRASI = {
46    "ci_gitlab_passi": "Then, once: Settings \u2192 CI/CD \u2192 Variables, a DELMINIO_FIRME variable (masked) with the key the administrator creates in Delminio, under Sign-offs \u2192 The CI key; and Settings \u2192 Merge requests \u2192 \u201cPipelines must succeed\u201d, or merging stays possible even with the check red.",
47    "ci_gitlab": "With GitLab there is a single file for the whole repo ({file}), and I won't touch it: add this job.",
48    "ci_passi_forgejo": "On Forgejo (or Gitea), three steps to do by hand, once:\n  1. A runner: Actions only run if the service has one (in the repo, Settings \u2192 Actions \u2192 Runners). The file asks for a runner labelled docker: if yours has another label, change \u201cruns-on\u201d in the file.\n  2. The secret: Settings \u2192 Actions \u2192 Secrets, name DELMINIO_FIRME, value the key the administrator creates in Delminio, under Sign-offs \u2192 The CI key.\n  3. The gate: Settings \u2192 Branches \u2192 a protection rule on branch {ramo}, with three things: the required status check \u201cdelminio-firme / controlla (pull_request)\u201d (on Forgejo the name carries the file and the event: \u201ccontrolla\u201d alone matches nothing, and merging stays blocked even with the sign-offs); direct push turned off, so the branch is entered only through a pull request; the rule applied to administrators too. Without this rule the CI goes red, but merging stays possible.\nOn pull requests from a fork there are no secrets: there the check can't run.",
49    "ci_gh_manca": "The GitHub CLI (gh) is not on this computer: the secret and the branch rule are still to be done by hand.",
50    "ci_gh_non_collegato": "The GitHub CLI is here, but not signed in to an account (gh auth login): the secret and the branch rule are still to be done by hand.",
51    "ci_gh_quale_repo": "The GitHub CLI does not recognise the repository in this folder ({errore}): the secret and the branch rule are still to be done by hand.",
52    "ci_gh_permessi": "On {repo} your GitHub account is not an admin: the secret and the branch rule are set by someone who is, by hand or by running this command again.",
53    "ci_gh_privato": "\u274c GitHub does not enforce branch rules on private repositories of a free account: on {repo} the check will be red, but merging will still be possible. You need a GitHub plan that enforces them (Team, or Pro for a personal account), or a git service of your own.",
54    "ci_gh_regola_no": "\u274c The rule on the {ramo} branch was not set ({errore}). By hand: Settings \u2192 Branches \u2192 a rule on the {ramo} branch with the \u201ccontrolla\u201d check required and \u201cDo not allow bypassing the above settings\u201d.",
55    "ci_gh_regole_altre": "The {ramo} branch already has its own rules: I leave them as they are and only add what is missing.",
56    "ci_gh_regola_ok": "\u2705 On {repo}, the {ramo} branch requires the \u201ccontrolla\u201d check before every merge, and the rule applies to admins too.",
57    "ci_gh_segreto_c_e": "\u2705 The DELMINIO_FIRME secret is already on {repo}. GitHub shows its value to no one: if the CI says the key is not valid, set it again.",
58    "ci_gh_segreto_tu": "The DELMINIO_FIRME secret is missing, and a person sets it, not an agent: in their own terminal, in this repository, they type {cmd} and paste the key the administrator creates in Delminio, under Sign-offs \u2192 The CI key.",
59    "ci_gh_segreto_incolla": "Now the DELMINIO_FIRME secret: paste the key the administrator creates in Delminio, under Sign-offs \u2192 The CI key. It is not shown while you paste it, and it goes only to GitHub.",
60    "ci_gh_segreto_fatto": "\u2705 The DELMINIO_FIRME secret is on {repo}.",
61    "ci_gh_segreto_no": "\u274c The secret was not set ({errore}): in the repository, Settings \u2192 Secrets and variables \u2192 Actions, name DELMINIO_FIRME.",
62    "ci_passi_github": "On GitHub, two steps to do by hand, once:\n  1. The secret: in the repo, Settings \u2192 Secrets and variables \u2192 Actions \u2192 New repository secret. Name DELMINIO_FIRME, value the key the administrator creates in Delminio, under Sign-offs \u2192 The CI key.\n  2. The gate: Settings \u2192 Branches (or Rules) \u2192 a rule on branch {ramo} that requires the \u201ccontrolla\u201d check before merging, for admins too (\u201cDo not allow bypassing the above settings\u201d). The check shows up in the list after the first pull request. Without this rule the CI goes red, but merging stays possible.\nOn pull requests from a fork GitHub doesn't hand out secrets: there the check can't run.",
63    "ci_esiste_diverso": "\u26a0\ufe0f  {file} is already there and differs from what I'd write: I'm leaving it alone. If you changed it yourselves, that's fine; if not, remove it and run me again.",
64    "ci_gia_pronto": "\u2705 {file} is already there, and it's the right one.",
65    "ci_scritto": "\u2705 Wrote {file}: commit it and push it like any other file.",
66    "ci_commento": "Delminio change sign-off: each pull request checks the sign-offs of its branch, each push to the main branch that nothing got in without them. Written by \u201cdelminio signoffs ci\u201d; the key lives in the service's secrets, named DELMINIO_FIRME.",
67    "ci_dentro_casa": "\u26a0\ufe0f  This Delminio lives at {url}, an address on your network: the machines of a CI on the internet (GitHub, GitLab.com) can't reach it. The check only works with a CI running inside your network (a runner of your own), or with a Delminio reachable from outside.",
68    "ci_quale": "I can't tell this repo's git service. Tell me which: delminio signoffs ci github, forgejo (Gitea too) or gitlab.",
69    "dell_autore": "by the author: it does not count",
70    "chi_non_detto": "another session",
71    "revisione_dell_autore": "The review of {commit} is recorded, but you are the author: what counts is the reviewer's, with their agent.",
72    "uso": "usage: {cmd} check [<range>] \xb7 {cmd} description [<range>] \xb7 {cmd} report [<range>] [<file>] \xb7 {cmd} export [<file>] \xb7 {cmd} chain <file> [<earlier copy>] \xb7 {cmd} review <commit|range> clean|findings [N] \xb7 {cmd} checks \xb7 {cmd} ci [github|forgejo|gitlab]",
73    "senza_motore": "\u274c Delminio's address or the key is missing: in a CI you need DELMINIO_URL and DELMINIO_TOKEN (the read key the administrator creates in Sign-offs).",
74    "non_risponde": "\u274c Delminio does not answer ({url}): {errore}",
75    "assenti": "Change sign-off is not available in this space: the licence does not include it.",
76    "intestazione": "The person's words to the agent, recorded by Delminio (change sign-off):",
77    "non_registrata": "not recorded in Delminio",
78    "controlli": "The checks before the commit:",
79    "zona": "\u26a0\ufe0f  This change touches a sign-off zone ({zone}): it must be signed in the Delminio app, under Sign-offs, before it goes ahead.",
80    "nascosto": "[hidden]",
81    "troncata": "[\u2026 {n} more characters not copied here]",
82    "nessun_commit": "No commits in {intervallo}.",
83    "intervallo_illeggibile": "\u274c I can't read the commits in {intervallo}: git can't find it ({errore}). With nothing to check this isn't a pass: the CI needs the whole history (fetch-depth: 0), and after a force push the previous commit is gone.",
84    "firmata": "  \u2705 {commit} signed \u2014 {soggetto}",
85    "da_firmare": "  \u274c {commit} to sign ({zone}): still missing {manca} \u2014 {soggetto}",
86    "respinta": "  \u274c {commit} rejected \u2014 {soggetto}",
87    "libera": "  \xb7 {commit} outside the sign-off zones \u2014 {soggetto}",
88    "senza": "  \u274c {commit} with no recorded sign-off: nobody answers for it in Delminio. It was made on a computer not connected to Delminio, skipping its checks, with sign-off switched off, or the network dropped at the commit: make it again on a connected computer (git commit --amend --no-edit) \u2014 {soggetto}",
89    "senza_in_zona": "  \u274c {commit} touches a sign-off zone ({zone}) with no recorded sign-off: it was made on a computer not connected to Delminio, skipping its checks, with sign-off switched off, or the network dropped at the commit. Make it again on a connected computer (git commit --amend --no-edit) \u2014 {soggetto}",
90    "merge_pulito": "  \xb7 {commit} merge with no changes of its own \u2014 {soggetto}",
91    "unita": "  \u2705 {commit} comes from branch {ramo}: its {n} changes are signed \u2014 {soggetto}",
92    "unita_da_firmare": "  \u274c {commit} comes from branch {ramo}: {n} of its changes still need signing \u2014 {soggetto}",
93    "unita_mancano": "  \u274c {commit} comes from branch {ramo}, but {n} of its commits have no recorded sign-off \u2014 {soggetto}",
94    "unita_scoperta": "  \u274c {commit} comes from branch {ramo} and touches a sign-off zone ({zone}) that its recorded changes do not carry: the recorded files are not the commit's. Redo the commits from a connected computer \u2014 {soggetto}",
95    "parole_non_tornano": "  \u274c {commit}: the words of request {id} do not match its fingerprint \u2014 the message was changed",
96    "parole_ignote": "  \u274c {commit}: request {id} is not the one Delminio recorded",
97    "esito": "{firmate} signed \xb7 {da_firmare} to sign \xb7 {libere} outside the zones \xb7 {senza} with no recorded sign-off \xb7 {rotte} with changed words \xb7 {urgenti} let in as urgent.",
98    "urgente": "  \u26a1 {commit} let in as urgent \u2014 {soggetto} (let through by {da} on {quando}: \u201c{perche}\u201d; sign-offs are given afterwards)",
99    "gov_urgenza": "{quando} \u2014 {chi} lets commit {commit} into {repo} as urgent: \u201c{perche}\u201d",
100    "esportata": "The chain is in {file}: {anelli} links, {esito}.",
101    "catena_rotta": "broken at link {anello}",
102    "revisione_registrata": "Your review of {commit} is recorded: you can now sign it from the app, under Sign-offs.",
103    "revisione_senza_sessione": "Your agent records the review, from its session: ask it to review the commit and to run \u201c{cmd} review <commit> clean\u201d itself (or \u201cfindings N\u201d). From a terminal outside a session it isn't recorded, because the review is yours and the model's you chose.",
104    "descr_parole": "### What the person asked for",
105    "descr_nessuna_parola": "_No recorded request: changes made by hand._",
106    "descr_fatti": "### The facts",
107    "descr_commit": "{n} commits, {file} files",
108    "descr_assistito": "With the agent: {con}",
109    "descr_zona": "Sign-off zone {codice} \u201c{cosa}\u201d: {servono} signatures, reviewed by {chi}",
110    "descr_chiunque": "anyone in the space",
111    "descr_controllo": "Check {codice} `{comando}` \u2192 exit {uscita}",
112    "descr_revisione": "Review by {chi}, with {revisore}: {esito}, {rilievi} findings ({indipendente})",
113    "indipendente": "independent",
114    "stessa_sessione": "from the session that wrote it: does not count",
115    "indipendente_stesso_modello": "independent, same model as the author",
116    "descr_stati": "Sign-off: {stati}",
117    "stato_firmata": "signed",
118    "stato_unita": "signed on the branch",
119    "stato_libera": "outside the zones",
120    "stato_pulito": "merges",
121    "stato_senza": "with no recorded sign-off",
122    "stato_da_firmare": "to sign",
123    "stato_respinta": "rejected",
124    "stato_zona": "in a zone with no recorded sign-off",
125    "res_titolo": "# Change sign-off \u2014 {remoto} \u2014 {intervallo}",
126    "res_generato": "Written on {quando} by Delminio. The sign-off chain: {anelli} links, {esito}.",
127    "res_stato": "Status: {riga}",
128    "res_unita": "Merged into the main branch from branch {ramo}: the signatures are on its {n} commits.",
129    "res_autore": "Accountable: {autore} \xb7 with {con} \xb7 {quando}",
130    "res_a_mano": "no agent (by hand)",
131    "res_zona": "Sign-off zone {codice} \u201c{cosa}\u201d: {servono} signatures",
132    "res_firma": "Signed by {persona}, {significato}, {quando}{parole}",
133    "significato_autore": "as author",
134    "significato_revisione": "as reviewer",
135    "significato_respinta": "rejected",
136    "res_nessuna_firma": "No signatures yet.",
137    "res_richiesta": "Request {id} (fingerprint {impronta}\u2026): {torna}",
138    "res_torna": "the words match the recorded fingerprint",
139    "res_non_torna": "the words do NOT match the fingerprint: the message was changed",
140    "res_file": "{n} files: {elenco}",
141    "res_come_verificare": "The chain can be checked without Delminio: \u201cdelminio signoffs export\u201d, then, inside the repository, \u201cdelminio signoffs chain <file> [<earlier copy>]\u201d, which also checks the anchors written in the commits and that the earlier copy is still its beginning. The words of each request are in the commit message, and their fingerprint (sha256) is the one Delminio recorded when the person wrote them.",
142    "res_scritto": "The report is in {file}: {commit} commits.",
143    "ripresa": "  \u2705 {commit} is a change from branch {ramo}, redone (rebase or cherry-pick), with its signatures \u2014 {soggetto}",
144    "ripresa_da_firmare": "  \u274c {commit} is a change from branch {ramo}, redone (rebase or cherry-pick), still to sign \u2014 {soggetto}",
145    "repo_senza_firme": "This repository has no change sign-off: nothing to check. The administrator turns it on per repository, from Sign-offs.",
146    "repo_sconosciuto": "\u274c Delminio doesn't know this repository ({remoto}): the check doesn't know what to look at, so it won't say green. In a CI the variable DELMINIO_FIRME_REPO gives the repository as it is connected to Delminio: \u201cdelminio signoffs ci\u201d writes it in the file. Run it again from a connected computer (if the file is already there, remove it first) and commit the new one.",
147    "scartata": "  \u274c {commit} discarded: it is no longer signed \u2014 {soggetto}",
148    "manca_prove": "the zone's checks on this commit",
149    "manca_autore": "the author's signature",
150    "manca_persone": "the reviewer's review, with their agent, and their signature",
151    "parole_tolte": "  \u274c {commit}: request {id}, which Delminio linked to this commit, is not in the message \u2014 the words were removed",
152    "ancora_rotta": "\u274c REWRITTEN: link {anello} is no longer the one commit {commit} anchored (anchors that don't match: {n}). The people who hold Delminio's database changed the chain after that commit",
153    "catena_ancorata": "intact, and anchored in {n} commits of this repository",
154    "catena_non_ancorata": "intact, but no commit in this copy of the repository anchors it: until the first one, the people who hold the database could rewrite it without it showing",
155    "gov_accese": "{quando} \u2014 {chi} switches sign-off on in the space",
156    "gov_spente": "{quando} \u2014 {chi} switches sign-off off in the space: nothing is recorded until it is switched back on",
157    "gov_repo_si": "{quando} \u2014 {chi} switches sign-off on in repository {repo}",
158    "gov_repo_no": "{quando} \u2014 {chi} switches sign-off off in repository {repo}: nothing is recorded there until it is switched back on",
159    "gov_chiave_si": "{quando} \u2014 {chi} creates the read key \u201c{etichetta}\u201d",
160    "gov_chiave_no": "{quando} \u2014 {chi} revokes the read key \u201c{etichetta}\u201d",
161    "gov_zona_nata": "{quando} \u2014 {chi} creates zone {codice}: {zona}",
162    "gov_zona_ritirata": "{quando} \u2014 {chi} withdraws zone {codice}",
163    "gov_zona_cambiata": "{quando} \u2014 {chi} changes zone {codice}: from {prima} to {dopo}",
164    "gov_zona_detta": "{dove}, {servono} signatures, reviewed by {chi}, checks `{comando}`",
165    "res_governo": "## Who governed sign-off",
166    "res_unito_da": "Into the main branch by {chi}, on {quando} (git says so: the person who merges doesn't go through Delminio)",
167    "res_git_dice": "Git says the author is {autore}: not verified, Delminio did not see this commit being made",
168    "res_non_in_catena": "\u274c this change is not in the chain: Delminio's database says things the chain does not",
169    "res_zona_dopo": "{quando}: zone {zone} was created after the commit, and applies to it too",
170    "res_prova_mancante": "Check {codice} `{comando}` \u2192 not run on this commit",
171    "res_firme_diverse": "\u274c Delminio's database shows different signatures ({motore}): the chain is what counts, and the database has been changed",
172    "res_scartata": "Discarded on {quando}: {perche}",
173    "res_parole_altrove": "The words are in commit {commit} of branch {ramo}, which this copy of the repository doesn't have: git fetch origin {ramo} (on GitHub they also stay in refs/pull/*/head)",
174    "copia_diversa": "\u274c {file} is not the beginning of this chain: link {anello} is different. The chain was rewritten after that copy",
175    "copia_uguale": "{file}: its {anelli} links are the beginning of this chain, unchanged",
176    "prova_non_accettata": "\u26a0\ufe0f  the check for sign-off zone {codice} is new or changed, and nobody on this machine has accepted it yet \u2014 I didn't run it:\n     {comando}\n   Read it and, if you trust it, from your own terminal: delminio accept. Then: delminio signoffs checks\n   Without the check having run, this commit can't be signed.",
177    "prova_fallita": "\u274c the check for sign-off zone {codice} did not pass on this commit (exit {uscita}): it can't be signed until it passes on a redone commit.\n     {comando}",
178    "prova_passata": "\u2705 the check for sign-off zone {codice} passed on this commit.",
179    "prove_albero_diverso": "\u26a0\ufe0f  the checks of the sign-off zone ({zone}) did not run: the files here are not the same as commit {commit}, and would test something else. When they are: delminio signoffs checks",
180    "prove_solo_testa": "Checks run on the commit that is here now (HEAD), with the files equal to the commit. For an earlier commit: git rebase --exec \"delminio signoffs checks\" <base>",
181    "prove_registrate": "The checks of {commit} are recorded: {esito}.",
182    "prove_nessuna": "No sign-off zone asks for checks on {commit}.",
183    "res_passkey": "with {persona}'s passkey \u201c{nome}\u201d, added on {quando} (confirmed with {come}): the device signature matches",
184    "res_passkey_non_torna": "\u274c the device signature does NOT match ({perche}): this sign-off wasn't given by {persona}'s passkey",
185    "res_passkey_cieca": "\u26a0\ufe0f the device signature can't be checked here: it needs Python's cryptography module or the openssl command",
186    "res_senza_passkey_prima": "signed in the app before sign-offs required a passkey",
187    "res_senza_passkey_dopo": "\u274c signed without a passkey after sign-offs require one: no device gave this sign-off",
188    "res_persona": "{persona} has been in the space since {quando}, {da}",
189    "res_persona_invitata": "invited by {chi}",
190    "res_persona_da_sempre": "from before who invites was recorded",
191    "res_passkey_mail": "email",
192    "res_passkey_password": "password",
193    "gov_passkey": "{quando} \u2014 from here every sign-off requires the passkey of the signer's device",
194    "gov_persona_entrata": "{quando} \u2014 {persona} joins the space as {ruolo}, invited by {chi}",
195    "gov_persona_spenta": "{quando} \u2014 {persona} leaves the space (account turned off)",
196    "gov_persona_riaccesa": "{quando} \u2014 {persona} is back in the space (account turned on)",
197    "gov_passkey_nuova": "{quando} \u2014 {persona} adds the passkey \u201c{nome}\u201d for {rp}, confirmed with {come}",
198    "gov_passkey_revocata": "{quando} \u2014 {chi} revokes {persona}'s passkey \u201c{nome}\u201d",
199    "perche_chiave": "the passkey isn't in the chain, or isn't the signer's",
200    "perche_revocata": "the passkey was revoked",
201    "perche_commit": "the device signed other commits",
202    "perche_sfida": "the device signed other words, another meaning or another person",
203    "perche_origine": "signed from another address",
204    "perche_persona": "without the person's fingerprint or PIN",
205    "perche_firma": "the cryptographic signature doesn't match the public key"
206}
207
208def F(chiave: str, **sost) -> str:
209    t = FRASI.get(chiave, chiave)
210    for k, v in sost.items():
211        t = t.replace('{' + k + '}', str(v))
212    return t
213
214class Rifiuto(Exception):
215
216    def __init__(self, messaggio: str, codice: int=0):
217        super().__init__(messaggio)
218        self.codice = codice
219
220def forma(testo: str) -> str:
221    return '\n'.join((r.rstrip() for r in (testo or '').strip().splitlines())).strip()
222
223def impronta(testo: str) -> str:
224    return hashlib.sha256(forma(testo).encode('utf-8')).hexdigest()
225
226def verifica_catena(anelli: list) -> object:
227    prima = ''
228    for i, a in enumerate(anelli):
229        atteso = hashlib.sha256((prima + '\n' + a.get('tipo', '') + '\n' + a.get('contenuto', '')).encode('utf-8')).hexdigest()
230        if a.get('prima', '') != prima or a.get('impronta') != atteso:
231            return a.get('seq', i + 1)
232        prima = atteso
233    return None
234
235def git(*a: str) -> str:
236    r = subprocess.run(['git', *a], capture_output=True, text=True, encoding='utf-8', errors='replace')
237    return r.stdout.strip() if r.returncode == 0 else ''
238
239def chiedi(metodo: str, percorso: str, corpo=None, attesa: int=30) -> dict:
240    if not URL or not TOKEN:
241        raise Rifiuto(F('senza_motore'))
242    req = urllib.request.Request(URL + percorso, method=metodo, data=json.dumps(corpo).encode() if corpo is not None else None, headers={'Authorization': 'Bearer ' + TOKEN, 'Content-Type': 'application/json'})
243    try:
244        return json.loads(urllib.request.urlopen(req, timeout=attesa).read())
245    except urllib.error.HTTPError as e:
246        try:
247            perche = json.loads(e.read()).get('error') or str(e)
248        except Exception:
249            perche = str(e)
250        raise Rifiuto(F('assenti') if e.code == 404 and perche == 'Not Found' else '❌ ' + perche, e.code) from None
251    except Exception as e:
252        raise Rifiuto(F('non_risponde', url=URL, errore=e)) from None
253_VUOTO = []
254
255def _albero_vuoto() -> str:
256    if not _VUOTO:
257        r = subprocess.run(['git', 'hash-object', '-t', 'tree', '--stdin'], input=b'', capture_output=True)
258        _VUOTO.append(r.stdout.decode().strip())
259    return _VUOTO[0]
260
261def _patch(da: str, a: str) -> str:
262    d = subprocess.run(['git', '-c', 'diff.noprefix=false', '-c', 'diff.mnemonicPrefix=false', 'diff', '--no-color', '--no-ext-diff', '--binary', da, a], capture_output=True)
263    if d.returncode or not d.stdout.strip():
264        return ''
265    p = subprocess.run(['git', 'patch-id', '--stable'], input=d.stdout, capture_output=True)
266    return (p.stdout.split() or [b''])[0].decode()
267
268def _genitori(h: str) -> list:
269    return git('rev-list', '--parents', '-n', '1', h).split()[1:]
270
271def _principale() -> str:
272    r = git('symbolic-ref', '-q', 'refs/remotes/origin/HEAD')
273    if r:
274        return r
275    for n in ('refs/remotes/origin/main', 'refs/remotes/origin/master'):
276        if git('rev-parse', '-q', '--verify', n):
277            return n
278    return ''
279
280def _ramo(h: str, nome: str='') -> dict | None:
281    principale = _principale()
282    base = git('merge-base', principale, h) if principale else ''
283    if not base:
284        return None
285    commit = git('rev-list', '--no-merges', '--reverse', f'{base}..{h}').split()[-RAMO_MAX:]
286    return {'nome': nome, 'patch': _patch(base, h) if commit else '', 'commit': commit}
287
288def _file(h: str) -> list:
289    file = git('diff-tree', '--no-commit-id', '--name-only', '-r', '-z', '--root', h).split('\x00')
290    return [f for f in file if f.strip()][:400]
291
292def segni(h: str) -> dict:
293    gen = _genitori(h)
294    return {'albero': git('rev-parse', h + '^{tree}'), 'patch': _patch(gen[0] if gen else _albero_vuoto(), h), 'file': _file(h)}
295
296def _parole_nel_messaggio(msg: str) -> tuple[dict, dict]:
297    dette = dict(re.findall('^Delminio-(?:Request|Richiesta): (\\d+) ([0-9a-f]{64})\\s*$', msg, re.M))
298    testi, corrente = ({}, None)
299    for r in msg.splitlines():
300        m = re.match('^\\[(\\d+)\\] ', r)
301        if m:
302            corrente = m.group(1)
303            testi[corrente] = []
304        elif corrente and (r == '>' or r.startswith('> ')):
305            testi[corrente].append(r[2:] if r.startswith('> ') else '')
306        else:
307            corrente = None
308    return (dette, {k: '\n'.join(v) for k, v in testi.items()})
309
310def _parole_rotte(h: str, msg: str, carta: dict | None) -> list:
311    dette, testi = _parole_nel_messaggio(msg)
312    registrate = {x['impronta']: x for x in (carta or {}).get('richieste') or []}
313    rotte = []
314    for rid, imp in dette.items():
315        if impronta(testi.get(rid) or '') != imp:
316            rotte.append((rid, 'non_tornano'))
317        elif carta is not None and imp not in registrate:
318            rotte.append((rid, 'ignote'))
319    scritte = set(dette.values())
320    for imp, x in registrate.items():
321        if imp not in scritte:
322            rotte.append((str(x.get('id') or '?'), 'tolte'))
323    return rotte
324
325def intervallo_di(a: list) -> str:
326    if a:
327        return a[0]
328    if git('rev-parse', '-q', '--verify', '@{upstream}'):
329        return '@{upstream}..HEAD'
330    p = _principale()
331    return f'{p}..HEAD' if p else 'HEAD~1..HEAD'
332
333def _merge_pulito(h: str) -> bool:
334    return len(_genitori(h)) > 1 and (not git('diff-tree', '--cc', '--no-commit-id', '--name-only', '-r', h))
335
336class SenzaFirme(Exception):
337
338    def __init__(self, sconosciuto: bool=False):
339        super().__init__()
340        self.sconosciuto = sconosciuto
341
342def leggi(intervallo: str, promuovi: bool=False) -> list:
343    r = subprocess.run(['git', 'rev-list', '--reverse', intervallo], capture_output=True, text=True, encoding='utf-8', errors='replace')
344    if r.returncode != 0:
345        raise Rifiuto(F('intervallo_illeggibile', intervallo=intervallo, errore=(r.stderr.strip().splitlines() or ['?'])[0][:200]))
346    voluti = r.stdout.split()[-COMMIT_MAX:]
347    if not voluti:
348        return []
349    remoto = _remoto()
350    puliti = {h for h in voluti if _merge_pulito(h)}
351    da_chiedere = [h for h in voluti if h not in puliti]
352    d = chiedi('POST', '/api/carta/commit', {'hash': da_chiedere or voluti[:1], 'remoto': remoto, 'promuovi': promuovi, 'segni': {h: {'file': _file(h)} for h in da_chiedere} if promuovi else {}})
353    if d.get('repo_senza_firme'):
354        raise SenzaFirme(bool(d.get('repo_sconosciuto')))
355    carte = d.get('carte') or {} if da_chiedere else {}
356    urgenze = dict(d.get('urgenze') or {}) if da_chiedere else {}
357    senza = [h for h in da_chiedere if carte.get(h) is None]
358    fuori = {}
359    if senza:
360        d2 = chiedi('POST', '/api/carta/commit', {'hash': senza, 'segni': {h: segni(h) for h in senza}, 'remoto': remoto, 'promuovi': promuovi})
361        fuori = d2.get('fuori') or {}
362        urgenze.update(d2.get('urgenze') or {})
363    out = []
364    for h in voluti:
365        msg = git('log', '-1', '--format=%B', h)
366        out.append({'hash': h, 'msg': msg, 'soggetto': (msg.strip().splitlines() or [''])[0][:70], 'pulito': h in puliti, 'carta': carte.get(h), 'fuori': fuori.get(h) or {}, 'urgenza': urgenze.get(h)})
367    return out
368PASSANO = ('firmata', 'libera', 'unita', 'pulito', 'urgente')
369
370def _mancano(k: dict) -> str:
371    nomi = {'prove': F('manca_prove'), 'autore': F('manca_autore'), 'persone': F('manca_persone')}
372    return ', '.join((nomi.get(m, m) for m in k.get('mancano') or []))
373
374def esito(c: dict) -> tuple[str, str]:
375    st, riga = _esito(c)
376    u = c.get('urgenza')
377    if u and st in ('da_firmare', 'zona', 'senza'):
378        return ('urgente', F('urgente', commit=c['hash'][:10], soggetto=c['soggetto'], da=u.get('da') or '?', quando=_quando(u.get('quando') or ''), perche=u.get('perche') or ''))
379    return (st, riga)
380
381def _esito(c: dict) -> tuple[str, str]:
382    corto, sogg = (c['hash'][:10], c['soggetto'])
383    if c['pulito']:
384        return ('pulito', F('merge_pulito', commit=corto, soggetto=sogg))
385    k = c['carta']
386    if k is not None:
387        st = k['stato']
388        if st == 'firmata':
389            return (st, F('firmata', commit=corto, soggetto=sogg))
390        if st == 'libera':
391            return (st, F('libera', commit=corto, soggetto=sogg))
392        if st == 'respinta':
393            return (st, F('respinta', commit=corto, soggetto=sogg))
394        if st == 'scartata':
395            return (st, F('scartata', commit=corto, soggetto=sogg))
396        return ('da_firmare', F('da_firmare', commit=corto, soggetto=sogg, manca=_mancano(k), zone=', '.join((z['codice'] for z in k.get('zone') or []))))
397    fu = c['fuori']
398    lg = fu.get('legame')
399    zone = ', '.join((z['codice'] for z in fu.get('zone') or []))
400    if lg:
401        ramo = lg.get('ramo') or '?'
402        if lg.get('mancano'):
403            return ('zona', F('unita_mancano', commit=corto, soggetto=sogg, ramo=ramo, n=len(lg['mancano'])))
404        if lg.get('scoperte'):
405            return ('zona', F('unita_scoperta', commit=corto, soggetto=sogg, ramo=ramo, zone=', '.join((z['codice'] for z in lg['scoperte']))))
406        aperte = [x for x in lg.get('carte') or [] if x['stato'] not in ('firmata', 'libera')]
407        if lg.get('via') == 'ripreso':
408            return ('da_firmare', F('ripresa_da_firmare', commit=corto, soggetto=sogg, ramo=ramo)) if aperte else ('unita', F('ripresa', commit=corto, soggetto=sogg, ramo=ramo))
409        if aperte:
410            return ('da_firmare', F('unita_da_firmare', commit=corto, soggetto=sogg, ramo=ramo, n=len(aperte)))
411        return ('unita', F('unita', commit=corto, soggetto=sogg, ramo=ramo, n=len(lg.get('carte') or [])))
412    if zone:
413        return ('zona', F('senza_in_zona', commit=corto, soggetto=sogg, zone=zone))
414    return ('senza', F('senza', commit=corto, soggetto=sogg))
415
416def _dice_rotta(h: str, rid: str, perche: str) -> str:
417    return {'non_tornano': F('parole_non_tornano', commit=h[:10], id=rid), 'tolte': F('parole_tolte', commit=h[:10], id=rid)}.get(perche) or F('parole_ignote', commit=h[:10], id=rid)
418
419def controlla(a: list) -> int:
420    intervallo = intervallo_di(a)
421    commit = leggi(intervallo, promuovi=True)
422    if not commit:
423        print(F('nessun_commit', intervallo=intervallo))
424        return 0
425    conti = {'firmate': 0, 'da_firmare': 0, 'libere': 0, 'senza': 0, 'rotte': 0, 'urgenti': 0}
426    for c in commit:
427        for rid, perche in _parole_rotte(c['hash'], c['msg'], c['carta']):
428            print(_dice_rotta(c['hash'], rid, perche))
429            conti['rotte'] += 1
430        st, riga = esito(c)
431        print(riga)
432        if st in ('firmata', 'unita'):
433            conti['firmate'] += 1
434        elif st in ('libera', 'pulito'):
435            conti['libere'] += 1
436        elif st == 'urgente':
437            conti['urgenti'] += 1
438        elif st in ('senza', 'zona'):
439            conti['senza'] += 1
440        else:
441            conti['da_firmare'] += 1
442    print(F('esito', **conti))
443    return 1 if conti['da_firmare'] or conti['rotte'] or conti['senza'] else 0
444
445def _remoto() -> str:
446    remoto = os.environ.get('DELMINIO_FIRME_REPO', '').strip() or git('remote', 'get-url', 'origin')
447    return re.sub('^([A-Za-z][A-Za-z0-9+.-]*://)[^/]*@', '\\1', remoto)
448
449def _quando(iso: str) -> str:
450    return (iso or '')[:16].replace('T', ' ') + ' UTC' if iso else ''
451
452def _richieste(c: dict) -> list:
453    dette, testi = _parole_nel_messaggio(c['msg'])
454    return [(rid, testi.get(rid) or '', imp, impronta(testi.get(rid) or '') == imp) for rid, imp in dette.items()]
455
456def _nome_stato(st: str) -> str:
457    return {'firmata': F('stato_firmata'), 'unita': F('stato_unita'), 'libera': F('stato_libera'), 'pulito': F('stato_pulito'), 'senza': F('stato_senza'), 'da_firmare': F('stato_da_firmare'), 'respinta': F('stato_respinta'), 'zona': F('stato_zona')}.get(st, st)
458
459def _nome_firma(significato: str) -> str:
460    return {'autore': F('significato_autore'), 'revisione': F('significato_revisione'), 'respinta': F('significato_respinta')}.get(significato, significato)
461
462def descrizione(a: list) -> int:
463    intervallo = intervallo_di(a)
464    commit = [c for c in leggi(intervallo) if not c['pulito']]
465    if not commit:
466        print(F('nessun_commit', intervallo=intervallo))
467        return 0
468    out, viste = ([F('descr_parole'), ''], set())
469    for c in commit:
470        for rid, testo, imp, _torna in _richieste(c):
471            if imp in viste:
472                continue
473            viste.add(imp)
474            out += ['> ' + r if r else '>' for r in testo.split('\n')] + ['']
475    if not viste:
476        out += [F('descr_nessuna_parola'), '']
477    file, assistiti, zone, controlli, revisioni = (set(), set(), {}, {}, [])
478    for c in commit:
479        k = c['carta'] or {}
480        file |= set(k.get('file') or _file(c['hash']))
481        if k.get('assistito'):
482            assistiti.add(k['assistito'])
483        for z in k.get('zone') or c['fuori'].get('zone') or []:
484            zone[z['codice']] = z
485        for x in k.get('controlli') or []:
486            controlli[x['codice'], x['comando']] = x['uscita']
487        revisioni += k.get('revisioni') or []
488    stati = {}
489    for c in commit:
490        st, _ = esito(c)
491        stati[st] = stati.get(st, 0) + 1
492    out += [F('descr_fatti'), '', '- ' + F('descr_commit', n=len(commit), file=len(file))]
493    if assistiti:
494        out.append('- ' + F('descr_assistito', con=', '.join(sorted(assistiti))))
495    for z in zone.values():
496        chi = ', '.join(z['firme'].get('persone') or []) or F('descr_chiunque')
497        out.append('- ' + F('descr_zona', codice=z['codice'], cosa=z['cosa'], servono=z['firme']['servono'], chi=chi))
498    for (codice, comando), uscita in controlli.items():
499        out.append('- ' + F('descr_controllo', codice=codice, comando=comando, uscita=uscita))
500    for r in revisioni:
501        out.append('- ' + F('descr_revisione', chi=r.get('persona') or F('chi_non_detto'), revisore=r['revisore'], esito=r['esito'], rilievi=r['rilievi'], indipendente=_indipendente(r)))
502    out.append('- ' + F('descr_stati', stati=', '.join((f'{_nome_stato(k)} {v}' for k, v in sorted(stati.items())))))
503    print('\n'.join(out))
504    return 0
505
506def _ancore() -> list:
507    out = []
508    for riga in git('log', '--all', '-n', '20000', '--format=%H%x09%(trailers:key=Delminio-Chain,valueonly,separator=%x2C)%x2C%(trailers:key=Delminio-Catena,valueonly,separator=%x2C)').splitlines():
509        h, _, valori = riga.partition('\t')
510        for v in valori.split(','):
511            m = re.fullmatch('\\s*(\\d+) ([0-9a-f]{64})\\s*', v)
512            if m:
513                out.append((h, int(m.group(1)), m.group(2)))
514    return out
515
516def _ancore_rotte(anelli: list) -> tuple:
517    per_seq = {a.get('seq'): a.get('impronta') for a in anelli}
518    ancore = _ancore()
519    return (len(ancore), [(h, seq) for h, seq, imp in ancore if per_seq.get(seq) != imp])
520
521def _dalla_catena(anelli: list) -> dict:
522    d = {'carte': {}, 'firme': {}, 'revisioni': {}, 'zone_dopo': {}, 'scartate': {}, 'prove': {}, 'governo': [], 'chiavi': {}, 'revocate': {}, 'persone': {}, 'regola': None}
523    for a in anelli:
524        try:
525            x = json.loads(a.get('contenuto') or '{}')
526        except ValueError:
527            continue
528        tipo = a.get('tipo')
529        if tipo == 'carta':
530            d['carte'][x.get('id')] = x
531        elif tipo == 'firma':
532            d['firme'].setdefault(x.get('carta'), []).append({**x, '_seq': a.get('seq')})
533        elif tipo == 'revisione':
534            d['revisioni'].setdefault(x.get('carta'), []).append(x)
535        elif tipo == 'zona_dopo':
536            d['zone_dopo'].setdefault(x.get('carta'), []).append(x)
537        elif tipo == 'scartata':
538            d['scartate'][x.get('carta')] = x
539        elif tipo == 'prove':
540            fatte = d['prove'].setdefault(x.get('carta'), {})
541            for p in x.get('controlli') or []:
542                fatte[p.get('codice')] = p
543        elif tipo in ('funzione', 'repo', 'zona', 'lettore', 'urgenza'):
544            d['governo'].append({'tipo': tipo, **x})
545        elif tipo == 'chiave':
546            if x.get('creata'):
547                d['chiavi'][x.get('id')] = {**x, '_seq': a.get('seq')}
548            else:
549                d['revocate'].setdefault(x.get('id'), a.get('seq'))
550            d['governo'].append({'tipo': tipo, **x})
551        elif tipo == 'persona':
552            if x.get('gesto') == 'entrata':
553                d['persone'].setdefault(x.get('persona'), x)
554            d['governo'].append({'tipo': tipo, **x})
555        elif tipo == 'regola' and x.get('passkey') and (d['regola'] is None):
556            d['regola'] = a.get('seq')
557            d['governo'].append({'tipo': tipo, **x})
558    return d
559
560def _canonico(d: dict) -> str:
561    return json.dumps(d, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
562
563def _da_b64u(s: str) -> bytes:
564    s = str(s or '')
565    return base64.urlsafe_b64decode(s + '=' * (-len(s) % 4))
566
567def _sfida(cosa: dict, nonce: str) -> str:
568    h = hashlib.sha256((_canonico(cosa) + '\n' + nonce).encode('utf-8')).digest()
569    return base64.urlsafe_b64encode(h).rstrip(b'=').decode()
570
571def _firma_valida(alg: int, pem: str, firma: bytes, dati: bytes):
572    try:
573        from cryptography.exceptions import InvalidSignature
574        from cryptography.hazmat.primitives import hashes, serialization
575        from cryptography.hazmat.primitives.asymmetric import ec, ed25519, padding, rsa
576        k = serialization.load_pem_public_key(pem.encode())
577        try:
578            if isinstance(k, ec.EllipticCurvePublicKey):
579                k.verify(firma, dati, ec.ECDSA(hashes.SHA256()))
580            elif isinstance(k, rsa.RSAPublicKey):
581                k.verify(firma, dati, padding.PKCS1v15(), hashes.SHA256())
582            elif isinstance(k, ed25519.Ed25519PublicKey):
583                k.verify(firma, dati)
584            else:
585                return False
586            return True
587        except (InvalidSignature, ValueError):
588            return False
589    except ImportError:
590        pass
591    if not shutil.which('openssl'):
592        return None
593    with tempfile.TemporaryDirectory() as cartella:
594        percorsi = {}
595        for nome, contenuto in (('chiave.pem', pem.encode()), ('firma', firma), ('dati', dati)):
596            percorsi[nome] = os.path.join(cartella, nome)
597            with open(percorsi[nome], 'wb') as h:
598                h.write(contenuto)
599        if alg == -8:
600            cmd = ['openssl', 'pkeyutl', '-verify', '-pubin', '-inkey', percorsi['chiave.pem'], '-rawin', '-in', percorsi['dati'], '-sigfile', percorsi['firma']]
601        else:
602            cmd = ['openssl', 'dgst', '-sha256', '-verify', percorsi['chiave.pem'], '-signature', percorsi['firma'], percorsi['dati']]
603        return subprocess.run(cmd, capture_output=True).returncode == 0
604
605def _origine_sua(origine: str, rp: str) -> bool:
606    from urllib.parse import urlparse
607    if origine.startswith('android:apk-key-hash:'):
608        return origine[len('android:apk-key-hash:'):] in APP_ANDROID
609    return urlparse(origine).hostname == rp
610
611def _dispositivo(f: dict, k: dict, fatti: dict) -> tuple:
612    d = f.get('dispositivo')
613    if not d:
614        if fatti['regola'] is not None and (f.get('_seq') or 0) > fatti['regola']:
615            return (F('res_senza_passkey_dopo'), False)
616        return (F('res_senza_passkey_prima'), True)
617    persona = f.get('persona') or '?'
618    chiave = fatti['chiavi'].get(d.get('chiave'))
619    perche = ''
620    if chiave is None or chiave.get('persona') != persona or (chiave.get('_seq') or 0) > (f.get('_seq') or 0):
621        perche = F('perche_chiave')
622    elif (rev := fatti['revocate'].get(d.get('chiave'))) is not None and rev < (f.get('_seq') or 0):
623        perche = F('perche_revocata')
624    elif {'id': k.get('id'), 'hash': k.get('hash')} not in (d.get('carte') or []):
625        perche = F('perche_commit')
626    if not perche:
627        cosa = {'persona': persona, 'significato': f.get('significato'), 'parole': f.get('parole') or '', 'carte': d.get('carte') or []}
628        try:
629            cdj = _da_b64u(d.get('client'))
630            cd, ad = (json.loads(cdj), _da_b64u(d.get('autenticatore')))
631        except ValueError:
632            cd, ad, cdj = ({}, b'', b'')
633        rp = chiave.get('rp') or ''
634        if cd.get('type') != 'webauthn.get' or cd.get('challenge') != _sfida(cosa, d.get('nonce') or ''):
635            perche = F('perche_sfida')
636        elif not _origine_sua(cd.get('origin') or '', rp) or ad[:32] != hashlib.sha256(rp.encode()).digest():
637            perche = F('perche_origine')
638        elif len(ad) < 37 or ad[32] & 5 != 5:
639            perche = F('perche_persona')
640        else:
641            esito = _firma_valida(int(chiave.get('alg') or 0), chiave.get('pem') or '', _da_b64u(d.get('firma')), ad + hashlib.sha256(cdj).digest())
642            if esito is None:
643                return (F('res_passkey_cieca'), False)
644            if not esito:
645                perche = F('perche_firma')
646    if perche:
647        return (F('res_passkey_non_torna', perche=perche, persona=persona), False)
648    come = F('res_passkey_mail') if chiave.get('provata') == 'mail' else F('res_passkey_password')
649    return (F('res_passkey', nome=chiave.get('nome') or '—', persona=persona, quando=_quando(chiave.get('quando')), come=come), True)
650
651def _chi_e_entrato(persona: str, fatti: dict) -> str:
652    e = fatti['persone'].get(persona) or {}
653    k = next((x for x in fatti['chiavi'].values() if x.get('persona') == persona), {})
654    quando = e.get('quando') or k.get('entrata') or ''
655    da = e.get('invitata_da') or k.get('invitata_da') or ''
656    if not quando:
657        return ''
658    return F('res_persona', persona=persona, quando=_quando(quando), da=F('res_persona_invitata', chi=da) if da else F('res_persona_da_sempre'))
659
660def _verifica(anelli: list) -> tuple:
661    rotto = verifica_catena(anelli)
662    if rotto is not None:
663        return (F('catena_rotta', anello=rotto), False)
664    n, rotte = _ancore_rotte(anelli)
665    if rotte:
666        h, seq = rotte[0]
667        return (F('ancora_rotta', commit=h[:10], anello=seq, n=len(rotte)), False)
668    return (F('catena_ancorata', n=n) if n else F('catena_non_ancorata'), True)
669
670def _governo(g: dict) -> str:
671    quando, chi = (_quando(g.get('quando')), g.get('chi') or '?')
672    if g['tipo'] == 'funzione':
673        if g.get('accesa'):
674            return F('gov_accese', quando=quando, chi=chi)
675        return F('gov_spente', quando=quando, chi=chi)
676    if g['tipo'] == 'repo':
677        if g.get('firme'):
678            return F('gov_repo_si', quando=quando, chi=chi, repo=g.get('repo') or '?')
679        return F('gov_repo_no', quando=quando, chi=chi, repo=g.get('repo') or '?')
680    if g['tipo'] == 'regola':
681        return F('gov_passkey', quando=quando)
682    if g['tipo'] == 'persona':
683        if g.get('gesto') == 'entrata':
684            return F('gov_persona_entrata', quando=quando, persona=g.get('persona') or '?', ruolo=g.get('ruolo') or '?', chi=g.get('invitata_da') or '?')
685        if g.get('gesto') == 'spenta':
686            return F('gov_persona_spenta', quando=quando, persona=g.get('persona') or '?')
687        return F('gov_persona_riaccesa', quando=quando, persona=g.get('persona') or '?')
688    if g['tipo'] == 'chiave':
689        if g.get('creata'):
690            come = F('res_passkey_mail') if g.get('provata') == 'mail' else F('res_passkey_password')
691            return F('gov_passkey_nuova', quando=quando, persona=g.get('persona') or '?', nome=g.get('nome') or '—', rp=g.get('rp') or '?', come=come)
692        return F('gov_passkey_revocata', quando=quando, chi=chi, persona=g.get('persona') or '?', nome=g.get('nome') or '—')
693    if g['tipo'] == 'urgenza':
694        return F('gov_urgenza', quando=quando, chi=chi, commit=(g.get('hash') or '?')[:10], repo=g.get('remoto') or '?', perche=g.get('perche') or '')
695    if g['tipo'] == 'lettore':
696        if g.get('creata'):
697            return F('gov_chiave_si', quando=quando, chi=chi, etichetta=g.get('etichetta') or '?')
698        return F('gov_chiave_no', quando=quando, chi=chi, etichetta=g.get('etichetta') or '?')
699    prima, dopo = (g.get('prima'), g.get('dopo'))
700
701    def detta(z):
702        f = z['firme']
703        return F('gov_zona_detta', dove=', '.join(z.get('dove') or []), servono=f.get('servono'), chi=', '.join(f.get('persone') or []) or F('descr_chiunque'), comando=z.get('comando') or '-')
704    if not prima:
705        return F('gov_zona_nata', quando=quando, chi=chi, codice=g.get('codice') or '?', zona=detta(dopo))
706    if not dopo:
707        return F('gov_zona_ritirata', quando=quando, chi=chi, codice=g.get('codice') or '?')
708    return F('gov_zona_cambiata', quando=quando, chi=chi, codice=g.get('codice') or '?', prima=detta(prima), dopo=detta(dopo))
709
710def _parole_dal_git(k: dict) -> list:
711    if subprocess.run(['git', 'cat-file', '-e', k['hash'] + '^{commit}'], capture_output=True).returncode:
712        return None
713    registrate = {x['impronta'] for x in k.get('richieste') or []}
714    return [(rid, testo, imp, torna, imp in registrate) for rid, testo, imp, torna in _richieste({'msg': git('log', '-1', '--format=%B', k['hash'])})]
715
716def _scrivi_parole(out: list, righe, rientro: str) -> None:
717    for rid, testo, imp, torna, *registrata in righe:
718        ok = torna and (not registrata or registrata[0])
719        out.append(rientro + '- ' + F('res_richiesta', id=rid, impronta=imp[:16], torna=F('res_torna') if ok else F('res_non_torna')))
720        out += [rientro + '  > ' + r if r else rientro + '  >' for r in testo.split('\n')]
721
722def resoconto(a: list) -> int:
723    intervallo = intervallo_di(a[:1])
724    dove = a[1] if len(a) > 1 else ''
725    commit = leggi(intervallo)
726    anelli = chiedi('GET', '/api/carta/catena').get('anelli') or []
727    verdetto, ok = _verifica(anelli)
728    fatti = _dalla_catena(anelli)
729    out = [F('res_titolo', remoto=_remoto() or '?', intervallo=intervallo), '', F('res_generato', quando=datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%d %H:%M UTC'), anelli=len(anelli), esito=verdetto), '']
730    for c in commit:
731        st, riga = esito(c)
732        out += [f"## {c['hash'][:10]} — {c['soggetto']}", '', '- ' + F('res_stato', riga=riga.strip())]
733        if c['pulito']:
734            out.append('')
735            continue
736        carte = [c['carta']] if c['carta'] else (c['fuori'].get('legame') or {}).get('carte') or []
737        if not c['carta'] and carte:
738            out.append('- ' + F('res_unita', n=len(carte), ramo=c['fuori']['legame'].get('ramo') or '?'))
739            ct = git('log', '-1', '--format=%ct', c['hash'])
740            quando = datetime.datetime.fromtimestamp(int(ct), datetime.timezone.utc).strftime('%Y-%m-%d %H:%M UTC') if ct.isdigit() else ''
741            out.append('- ' + F('res_unito_da', chi=git('log', '-1', '--format=%cn', c['hash']), quando=quando))
742        if not carte:
743            out.append('- ' + F('res_git_dice', autore=git('log', '-1', '--format=%an <%ae>', c['hash'])))
744        for k in carte:
745            dentro = '  ' if not c['carta'] else ''
746            if not c['carta']:
747                out.append(f"- `{k['hash'][:10]}` {k.get('soggetto') or ''}")
748            dalla = fatti['carte'].get(k['id'])
749            if dalla is None:
750                out.append(dentro + '- ' + F('res_non_in_catena'))
751                ok = False
752            out.append(dentro + '- ' + F('res_autore', autore=(dalla or k)['autore'], con=(dalla or k).get('assistito') or F('res_a_mano'), quando=_quando((dalla or k).get('quando'))))
753            for z in (dalla or k).get('zone') or []:
754                out.append(dentro + '- ' + F('res_zona', codice=z['codice'], cosa=z['cosa'], servono=max(int(z['firme'].get('servono') or 0), 2)))
755            for zd in fatti['zone_dopo'].get(k['id']) or []:
756                out.append(dentro + '- ' + F('res_zona_dopo', quando=_quando(zd.get('quando')), zone=', '.join((z['codice'] for z in zd.get('zone') or []))))
757            dopo = fatti['prove'].get(k['id']) or {}
758            for p in (dalla or k).get('prove') or []:
759                fatta = next((x for x in [dopo.get(p['codice'])] + list((dalla or k).get('controlli') or []) if x and x['codice'] == p['codice'] and (x['comando'] == p['comando'])), None)
760                out.append(dentro + '- ' + (F('descr_controllo', codice=p['codice'], comando=p['comando'], uscita=fatta['uscita']) if fatta else F('res_prova_mancante', codice=p['codice'], comando=p['comando'])))
761            for r in fatti['revisioni'].get(k['id']) or []:
762                out.append(dentro + '- ' + F('descr_revisione', chi=r.get('persona') or F('chi_non_detto'), revisore=r['revisore'], esito=r['esito'], rilievi=r['rilievi'], indipendente=_indipendente(r, k.get('autore', ''))))
763            firme_catena = fatti['firme'].get(k['id']) or []
764            for f in firme_catena:
765                out.append(dentro + '- ' + F('res_firma', persona=f['persona'], significato=_nome_firma(f['significato']), quando=_quando(f['quando']), parole=' — «' + f['parole'] + '»' if f.get('parole') else ''))
766                riga, buona = _dispositivo(f, k, fatti)
767                out.append(dentro + '  - ' + riga)
768                if (chi_e := _chi_e_entrato(f['persona'], fatti)):
769                    out.append(dentro + '  - ' + chi_e)
770                ok = ok and buona
771            if {(f['persona'], f['significato']) for f in firme_catena} != {(f['persona'], f['significato']) for f in k.get('firme') or []}:
772                out.append(dentro + '- ' + F('res_firme_diverse', motore=', '.join((f"{f['persona']} ({_nome_firma(f['significato'])})" for f in k.get('firme') or [])) or '-'))
773                ok = False
774            if not firme_catena and (k.get('zone') or []):
775                out.append(dentro + '- ' + F('res_nessuna_firma'))
776            if (sc := fatti['scartate'].get(k['id'])):
777                out.append(dentro + '- ' + F('res_scartata', quando=_quando(sc.get('quando')), perche=sc.get('perche') or ''))
778            if not c['carta']:
779                parole = _parole_dal_git(k)
780                if parole is None:
781                    out.append(dentro + '- ' + F('res_parole_altrove', commit=k['hash'][:10], ramo=k.get('ramo') or '?'))
782                else:
783                    _scrivi_parole(out, parole, dentro)
784        if c['carta'] or not carte:
785            _scrivi_parole(out, _richieste(c), '')
786            for rid, perche in _parole_rotte(c['hash'], c['msg'], c['carta']):
787                if perche == 'tolte':
788                    out.append('- ' + _dice_rotta(c['hash'], rid, perche).strip())
789        file = (c['carta'] or {}).get('file') or _file(c['hash'])
790        out.append('- ' + F('res_file', n=len(file), elenco=', '.join((f'`{x}`' for x in file[:30])) + (f' (+{len(file) - 30})' if len(file) > 30 else '')))
791        out.append('')
792    if fatti['governo']:
793        out += [F('res_governo'), ''] + ['- ' + _governo(g) for g in fatti['governo']] + ['']
794    out += [F('res_come_verificare'), '']
795    testo = '\n'.join(out) + '\n'
796    if dove.lower().endswith(('.html', '.htm')):
797        conti = {'firmate': 0, 'da_firmare': 0, 'libere': 0, 'senza': 0, 'rotte': 0, 'urgenti': 0}
798        for c in commit:
799            st = esito(c)[0]
800            chiave = {'firmata': 'firmate', 'unita': 'firmate', 'libera': 'libere', 'pulito': 'libere', 'urgente': 'urgenti', 'senza': 'senza', 'zona': 'senza'}.get(st, 'da_firmare')
801            conti[chiave] += 1
802        testo = _html(testo, F('esito', **conti), ok)
803    elif dove.lower().endswith('.csv'):
804        testo = _csv(commit, fatti, ok)
805    if dove:
806        with open(dove, 'w', encoding='utf-8') as h:
807            h.write(testo)
808        print(F('res_scritto', file=dove, commit=len(commit)))
809    else:
810        sys.stdout.write(testo)
811    return 0 if ok else 1
812_STILE = '\n:root{--fondo:#f6f4ef;--carta:#fff;--testo:#1d1b18;--piano:#6b665c;--oro:#a77d1c;--verde:#2f7d4f;--rosso:#b3362c;--ambra:#b7791f}\n*{box-sizing:border-box}body{margin:0;background:var(--fondo);color:var(--testo);font:15px/1.55 system-ui,-apple-system,"Segoe UI",sans-serif}\nmain{max-width:980px;margin:0 auto;padding:32px 20px 60px}h1{font:600 26px/1.25 Georgia,serif;margin:0 0 6px}\n.sotto{color:var(--piano);margin:0 0 18px}.conto{background:var(--carta);border-radius:10px;padding:14px 18px;margin:0 0 22px;\nborder-left:5px solid var(--oro);font-weight:600}.catena-ok{border-left-color:var(--verde)}.catena-no{border-left-color:var(--rosso)}\nsection{background:var(--carta);border-radius:10px;padding:16px 20px;margin:0 0 14px;border-left:5px solid #ccc;box-shadow:0 1px 2px #0001}\nsection.ok{border-left-color:var(--verde)}section.no{border-left-color:var(--rosso)}section.urgente{border-left-color:var(--ambra)}\nh2{font:600 17px/1.3 Georgia,serif;margin:0 0 8px}ul{margin:4px 0;padding-left:20px}li{margin:2px 0}\ncode{font:13px ui-monospace,Menlo,Consolas,monospace;background:#efece4;padding:1px 5px;border-radius:4px}\nli.parole{list-style:none}blockquote{margin:2px 0 8px 0;padding:4px 12px;border-left:3px solid var(--oro);background:#faf7ef;font-style:italic}\n@media print{body{background:#fff}section,.conto{box-shadow:none;break-inside:avoid}main{padding:0}}\n'
813
814def _inline_html(t: str) -> str:
815    import html
816    pezzi = re.split('(`[^`]+`)', t)
817    out = []
818    for p in pezzi:
819        if len(p) > 1 and p.startswith('`') and p.endswith('`'):
820            out.append('<code>' + html.escape(p[1:-1]) + '</code>')
821        else:
822            out.append(re.sub('\\*\\*(.+?)\\*\\*', '<b>\\1</b>', html.escape(p)))
823    return ''.join(out)
824
825def _html(testo: str, conto: str, catena_ok: bool) -> str:
826    import html
827    righe, corpo, livello, sezione = (testo.splitlines(), [], 0, False)
828    titolo = next((r[2:] for r in righe if r.startswith('# ')), '')
829
830    def chiudi_liste(fino: int=0) -> None:
831        nonlocal livello
832        while livello > fino:
833            corpo.append('</ul>')
834            livello -= 1
835    for i, r in enumerate(righe):
836        if r.startswith('# '):
837            continue
838        if r.startswith('## '):
839            chiudi_liste()
840            if sezione:
841                corpo.append('</section>')
842            stato = next((x for x in righe[i + 1:i + 4] if x.startswith('- ')), '')
843            classe = 'ok' if '✅' in stato else 'urgente' if '⚡' in stato else 'no' if '❌' in stato else ''
844            corpo.append(f'<section class="{classe}"><h2>{_inline_html(r[3:])}</h2>')
845            sezione = True
846            continue
847        m = re.match('^( *)- (.*)$', r)
848        if m:
849            voluto = len(m.group(1)) // 2 + 1
850            if voluto > livello:
851                while livello < voluto:
852                    corpo.append('<ul>')
853                    livello += 1
854            else:
855                chiudi_liste(voluto)
856            corpo.append(f'<li>{_inline_html(m.group(2))}</li>')
857            continue
858        q = r.lstrip()
859        if q == '>' or q.startswith('> '):
860            corpo.append(f'<li class="parole"><blockquote>{_inline_html(q[2:])}</blockquote></li>' if livello else f'<blockquote>{_inline_html(q[2:])}</blockquote>')
861            continue
862        chiudi_liste()
863        if r.strip():
864            if sezione:
865                corpo.append('</section>')
866                sezione = False
867            corpo.append(f'<p class="sotto">{_inline_html(r)}</p>')
868    chiudi_liste()
869    if sezione:
870        corpo.append('</section>')
871    return f"""<!doctype html>\n<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>{html.escape(titolo)}</title><style>{_STILE}</style></head><body><main><h1>{_inline_html(titolo)}</h1><div class="conto {('catena-ok' if catena_ok else 'catena-no')}">{_inline_html(conto)}</div>""" + '\n'.join(corpo) + '</main></body></html>\n'
872COLONNE_CSV = ('commit', 'committed_at', 'subject', 'status', 'author', 'agent', 'zones', 'checks', 'reviews', 'signoffs', 'signoff_devices_verified', 'urgent_by', 'urgent_at', 'urgent_reason', 'chain_verified')
873
874def _cella(x) -> str:
875    x = '' if x is None else str(x)
876    return "'" + x if x[:1] in ('=', '+', '-', '@', '\t', '\r') else x
877
878def _csv(commit: list, fatti: dict, catena_ok: bool) -> str:
879    import csv
880    import io
881    buf = io.StringIO()
882    w = csv.writer(buf, lineterminator='\n')
883    w.writerow(COLONNE_CSV)
884    for c in commit:
885        st, _riga = esito(c)
886        carte = [c['carta']] if c['carta'] else (c['fuori'].get('legame') or {}).get('carte') or []
887        autori, agenti, zone, prove, rev, firme, buone = ([], [], [], [], [], [], [])
888        for k in carte:
889            dalla = fatti['carte'].get(k['id']) or k
890            autori.append(dalla['autore'])
891            agenti.append(dalla.get('assistito') or '')
892            zone += [z['codice'] for z in dalla.get('zone') or []]
893            fatte = {**{x['codice']: x for x in dalla.get('controlli') or []}, **(fatti['prove'].get(k['id']) or {})}
894            prove += [f"{p['codice']}:{(fatte[p['codice']]['uscita'] if p['codice'] in fatte else '?')}" for p in dalla.get('prove') or []]
895            rev += [f"{r.get('persona') or '?'}:{r['esito']}" for r in fatti['revisioni'].get(k['id']) or []]
896            for f in fatti['firme'].get(k['id']) or []:
897                firme.append(f"{f['persona']}:{f['significato']}@{(f.get('quando') or '')[:19]}")
898                buone.append(_dispositivo(f, k, fatti)[1])
899        ct = git('log', '-1', '--format=%cI', c['hash'])
900        u = c.get('urgenza') or {}
901        w.writerow([_cella(x) for x in (c['hash'], ct, c['soggetto'], st, ' '.join(dict.fromkeys(autori)) or git('log', '-1', '--format=%ae', c['hash']), ' '.join(dict.fromkeys((a for a in agenti if a))), ' '.join(dict.fromkeys(zone)), ' '.join(dict.fromkeys(prove)), ' '.join(dict.fromkeys(rev)), ' '.join(firme), ('yes' if all(buone) else 'no') if buone else '', u.get('da') or '', (u.get('quando') or '')[:19], u.get('perche') or '', 'yes' if catena_ok else 'no')])
902    return buf.getvalue()
903
904def esporta(a: list) -> int:
905    d = chiedi('GET', '/api/carta/catena')
906    dove = a[0] if a else 'delminio-signoff-' + datetime.date.today().isoformat() + '.json'
907    with open(dove, 'w', encoding='utf-8') as h:
908        json.dump({'anelli': d.get('anelli') or []}, h, ensure_ascii=False, indent=1)
909    verdetto, ok = _verifica(d.get('anelli') or [])
910    print(F('esportata', file=dove, anelli=len(d.get('anelli') or []), esito=verdetto))
911    return 0 if ok else 1
912
913def catena(a: list) -> int:
914    if not a:
915        raise Rifiuto(F('uso', cmd=CMD))
916    anelli = json.load(open(a[0], encoding='utf-8')).get('anelli') or []
917    verdetto, ok = _verifica(anelli)
918    print(F('esportata', file=a[0], anelli=len(anelli), esito=verdetto))
919    if len(a) > 1:
920        vecchi = json.load(open(a[1], encoding='utf-8')).get('anelli') or []
921        per_seq = {x.get('seq'): x.get('impronta') for x in anelli}
922        diverso = next((x.get('seq') for x in vecchi if per_seq.get(x.get('seq')) != x.get('impronta')), None)
923        if verifica_catena(vecchi) is not None or diverso is not None:
924            print(F('copia_diversa', file=a[1], anello=diverso if diverso is not None else verifica_catena(vecchi)))
925            ok = False
926        else:
927            print(F('copia_uguale', file=a[1], anelli=len(vecchi)))
928    return 0 if ok else 1
929
930def _indipendente(r: dict, autore: str='') -> str:
931    if not r.get('indipendente'):
932        return F('stessa_sessione')
933    if autore and r.get('persona') == autore:
934        return F('dell_autore')
935    return F('indipendente_stesso_modello') if r.get('stesso_modello') else F('indipendente')
936
937def revisione(a: list) -> int:
938    if len(a) > 1:
939        a[1] = {'clean': 'pulita', 'findings': 'rilievi'}.get(a[1], a[1])
940    sess = os.environ.get('DELMINIO_SESSIONE', '')
941    if len(a) < 2 or a[1] not in ('pulita', 'rilievi'):
942        raise Rifiuto(F('uso', cmd=CMD))
943    if not sess:
944        raise Rifiuto(F('revisione_senza_sessione', cmd=CMD))
945    rilievi = int(a[2]) if len(a) > 2 and a[2].isdigit() else 0
946    voluti = git('rev-list', '--no-merges', '--reverse', a[0]).split() if '..' in a[0] else [git('rev-parse', a[0]) or a[0]]
947    for h in voluti[-COMMIT_MAX:]:
948        try:
949            r = chiedi('POST', '/api/carta/revisione', {'hash': h, 'esito': a[1], 'rilievi': rilievi, 'sessione': sess})
950        except Rifiuto as e:
951            print(f'  {h[:10]} {e}', file=sys.stderr)
952            continue
953        ultima = (r.get('revisioni') or [{}])[-1]
954        print(F('revisione_dell_autore', commit=h[:10]) if ultima.get('persona') == r.get('autore') else F('revisione_registrata', commit=h[:10]))
955    return 0
956
957def _stato(nome: str) -> str:
958    return os.path.join(STATO, nome)
959
960def _richiesta(a: list) -> int:
961    sess = a[0] if a else ''
962    try:
963        testo = json.load(sys.stdin).get('prompt') or ''
964    except Exception:
965        return 0
966    if not sess or not isinstance(testo, str) or (not testo.strip()):
967        return 0
968    nascosto = F('nascosto')
969    for r in ('-----BEGIN [A-Z ]*PRIVATE KEY-----[\\s\\S]+?-----END [A-Z ]*PRIVATE KEY-----', 'eyJ[A-Za-z0-9_-]{8,}\\.eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{16,}', '\\bsk-[A-Za-z0-9_-]{20,}', '\\b(?:ghp|gho|ghu|ghs|github_pat)_[A-Za-z0-9_]{20,}', '\\bAKIA[0-9A-Z]{16}\\b', '\\bxox[abprs]-[A-Za-z0-9-]{10,}', '\\bAIza[0-9A-Za-z_-]{35}\\b', '\\bglpat-[A-Za-z0-9_-]{20,}'):
970        testo = re.sub(r, nascosto, testo)
971    testo = re.sub('(?i)\\b(password|passwd|pwd|secret|token|api[_-]?key)(\\s*[:=]\\s*)\\S+', '\\1\\2' + nascosto, testo)
972    testo = forma(testo)
973    if len(testo) > MASSIMO:
974        testo = forma(testo[:MASSIMO] + '\n' + F('troncata', n=len(testo) - MASSIMO))
975    voce = {'impronta': impronta(testo), 'testo': testo}
976    try:
977        r = chiedi('POST', '/api/carta/richiesta', {'sessione': sess, 'impronta': voce['impronta'], 'remoto': _remoto()}, attesa=3)
978        voce.update(id=r['id'], quando=r['quando'])
979        _segno(True)
980    except Rifiuto as e:
981        if e.codice == 409:
982            return 0
983        if e.codice in (403, 404):
984            _segno(False)
985            return 0
986        voce['quando'] = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='seconds')
987    except Exception:
988        voce['quando'] = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='seconds')
989    fd = os.open(_stato(f'carta-{sess}.jsonl'), os.O_WRONLY | os.O_CREAT | os.O_APPEND, 384)
990    with os.fdopen(fd, 'a', encoding='utf-8') as h:
991        h.write(json.dumps(voce, ensure_ascii=False) + '\n')
992    return 0
993
994def _segno(accese: bool) -> None:
995    si, no = (_stato('carta'), _stato('carta-no'))
996    try:
997        open(si if accese else no, 'a').close()
998        os.remove(no if accese else si)
999    except OSError:
1000        pass
1001
1002def _voci(sess: str) -> list:
1003    voci = []
1004    if not sess:
1005        return voci
1006    try:
1007        for riga in open(_stato(f'carta-{sess}.jsonl'), encoding='utf-8'):
1008            try:
1009                voci.append(json.loads(riga))
1010            except ValueError:
1011                pass
1012    except OSError:
1013        pass
1014    return voci
1015
1016def _messaggio(a: list) -> int:
1017    file, sess, controlli_f = (a + ['', '', ''])[:3]
1018    carta = json.loads(os.environ.get('DELMINIO_DURI') or '{}').get('carta') or {}
1019    try:
1020        controlli = json.load(open(controlli_f, encoding='utf-8'))
1021    except (OSError, ValueError):
1022        controlli = []
1023    voci = _voci(sess)
1024    blocco = []
1025    if voci:
1026        blocco.append(F('intestazione'))
1027        for v in voci:
1028            blocco.append(f"[{v.get('id') or '-'}] {_quando(v.get('quando'))}" + ('' if v.get('id') else ' · ' + F('non_registrata')))
1029            blocco += ['> ' + r if r else '>' for r in v['testo'].split('\n')]
1030            blocco.append('')
1031    if controlli:
1032        blocco.append(F('controlli'))
1033        blocco += [f"  {c['codice']} `{c['comando']}` → {c['uscita']}" for c in controlli]
1034        blocco.append('')
1035    testo = open(file, encoding='utf-8').read()
1036    if blocco:
1037        righe = testo.rstrip('\n').split('\n')
1038        fine = len(righe)
1039        while fine > 0 and righe[fine - 1].startswith('#'):
1040            fine -= 1
1041        inizio = fine
1042        while inizio > 0 and righe[inizio - 1].strip():
1043            inizio -= 1
1044        trailer = inizio > 0 and all((re.match('^[A-Za-z0-9-]+: ', r) for r in righe[inizio:fine]))
1045        punto = inizio if trailer else fine
1046        nuove = righe[:punto] + ([''] if punto and righe[punto - 1].strip() else []) + blocco + righe[punto:]
1047        with open(file, 'w', encoding='utf-8') as h:
1048            h.write('\n'.join(nuove).rstrip('\n') + '\n')
1049    aggiunti = ['Assisted-by: ' + carta['assistito']] if carta.get('assistito') else []
1050    aggiunti += [f"Delminio-Request: {v['id']} {v['impronta']}" for v in voci if v.get('id')]
1051    testa = carta.get('catena') or {}
1052    if isinstance(testa.get('seq'), int) and re.fullmatch('[0-9a-f]{64}', str(testa.get('impronta') or '')):
1053        aggiunti.append(f"Delminio-Chain: {testa['seq']} {testa['impronta']}")
1054    gia = open(file, encoding='utf-8').read()
1055    for t in aggiunti:
1056        if t.replace('Delminio-Request:', 'Delminio-Richiesta:').replace('Delminio-Chain:', 'Delminio-Catena:') in gia.splitlines():
1057            continue
1058        subprocess.run(['git', 'interpret-trailers', '--in-place', '--if-exists', 'addIfDifferent', '--trailer', t, file], check=False)
1059    with open(_stato(f"carta-incluse-{sess or 'mano'}.json"), 'w', encoding='utf-8') as h:
1060        json.dump({'impronte': [v['impronta'] for v in voci], 'richieste': [v['id'] for v in voci if v.get('id')], 'controlli': controlli}, h)
1061    zone = carta.get('zone') or []
1062    if zone:
1063        print(F('zona', zone=', '.join((f"{z['codice']} «{z['cosa']}»" for z in zone))), file=sys.stderr)
1064    return 0
1065
1066def _commit(a: list) -> int:
1067    sess = a[0] if a else ''
1068    incl = _stato(f"carta-incluse-{sess or 'mano'}.json")
1069    try:
1070        d = json.load(open(incl, encoding='utf-8'))
1071    except (OSError, ValueError):
1072        return 0
1073    try:
1074        os.remove(incl)
1075    except OSError:
1076        pass
1077    file = [f for f in git('show', '--name-only', '--format=', '-z', 'HEAD').split('\x00') if f.strip()]
1078    controlli = list(d.get('controlli') or [])
1079    fatte = _gira_prove(git('rev-parse', 'HEAD'), file)
1080    if fatte:
1081        gia = {x['codice'] for x in fatte}
1082        controlli = [x for x in controlli if x.get('codice') not in gia] + fatte
1083    dette = list(_parole_nel_messaggio(git('log', '-1', '--format=%B', 'HEAD'))[0])
1084    richieste = list(dict.fromkeys([str(x) for x in d.get('richieste') or []] + dette))
1085    print(json.dumps({'file': file[:400], 'richieste': [int(x) for x in richieste if x.isdigit()], 'controlli': controlli}))
1086    scritte = set(d.get('impronte') or [])
1087    if scritte and sess:
1088        p = _stato(f'carta-{sess}.jsonl')
1089        try:
1090            resta = [r for r in open(p, encoding='utf-8') if json.loads(r).get('impronta') not in scritte]
1091            with open(p, 'w', encoding='utf-8') as h:
1092                h.writelines(resta)
1093        except (OSError, ValueError):
1094            pass
1095    return 0
1096
1097def _segni(a: list) -> int:
1098    h = git('rev-parse', a[0] if a else 'HEAD')
1099    if not h:
1100        return 0
1101    sg = segni(h)
1102    nome = git('rev-parse', '--abbrev-ref', 'HEAD')
1103    print(json.dumps({'albero': sg['albero'], 'patch': sg['patch'], 'ramo': _ramo(h, '' if nome == 'HEAD' else nome)}))
1104    return 0
1105
1106def _prove_chieste(h: str, file: list) -> list:
1107    if not file or not URL or (not TOKEN):
1108        return []
1109    try:
1110        r = chiedi('POST', '/api/lock/commit', {'staged': file, 'sessione': '', 'remoto': os.environ.get('DELMINIO_REMOTO') or _remoto()}, attesa=8)
1111    except Rifiuto:
1112        return []
1113    return (r.get('carta') or {}).get('prove') or []
1114
1115def _gira_prove(h: str, file: list) -> list | None:
1116    prove = _prove_chieste(h, file)
1117    if not prove:
1118        return []
1119    uguale = git('rev-parse', 'HEAD') == h and subprocess.run(['git', 'diff', '--quiet', 'HEAD'], capture_output=True).returncode == 0 and (subprocess.run(['git', 'diff', '--cached', '--quiet', 'HEAD'], capture_output=True).returncode == 0)
1120    if not uguale:
1121        print(F('prove_albero_diverso', zone=', '.join((p['codice'] for p in prove)), commit=h[:10]), file=sys.stderr)
1122        return None
1123    try:
1124        accettate = set(open(os.environ.get('DELMINIO_ACCETTATE') or git('rev-parse', '--git-path', 'delminio-guardie-accettate'), encoding='utf-8').read().split())
1125    except OSError:
1126        accettate = set()
1127    radice = git('rev-parse', '--show-toplevel') or '.'
1128    fatte = []
1129    for p in prove:
1130        if hashlib.sha256((p['codice'] + '\x00' + p['comando']).encode()).hexdigest() not in accettate:
1131            print(F('prova_non_accettata', codice=p['codice'], comando=p['comando']), file=sys.stderr)
1132            continue
1133        try:
1134            e = subprocess.run(p['comando'], shell=True, cwd=radice, capture_output=True, text=True, timeout=PROVE_TEMPO)
1135            rc, uscita = (e.returncode, (e.stdout or '') + (e.stderr or ''))
1136        except subprocess.TimeoutExpired:
1137            rc, uscita = (124, '')
1138        fatte.append({'codice': p['codice'], 'comando': p['comando'], 'uscita': rc})
1139        if rc == 0:
1140            print(F('prova_passata', codice=p['codice']), file=sys.stderr)
1141        else:
1142            print(F('prova_fallita', codice=p['codice'], comando=p['comando'], uscita=rc), file=sys.stderr)
1143            for riga in uscita.strip().splitlines()[-15:]:
1144                print('     ' + riga, file=sys.stderr)
1145    return fatte
1146
1147def prove(a: list) -> int:
1148    h = git('rev-parse', 'HEAD')
1149    if a and git('rev-parse', a[0]) != h:
1150        print(F('prove_solo_testa'))
1151        return 2
1152    fatte = _gira_prove(h, _file(h))
1153    if fatte is None:
1154        return 1
1155    if not fatte:
1156        print(F('prove_nessuna', commit=h[:10]))
1157        return 0
1158    chiedi('POST', '/api/carta/prove', {'hash': h, 'controlli': fatte})
1159    esito = ', '.join((f"{x['codice']} → {x['uscita']}" for x in fatte))
1160    print(F('prove_registrate', commit=h[:10], esito=esito))
1161    return 0 if all((x['uscita'] == 0 for x in fatte)) else 1
1162
1163def _riscritti(a: list) -> int:
1164    coppie = [r.split()[:2] for r in sys.stdin.read().splitlines() if len(r.split()) >= 2 and r.split()[0] != r.split()[1]]
1165    sg = {}
1166    if a and a[0] == 'segni':
1167        for _vecchio, nuovo in coppie:
1168            s = segni(nuovo)
1169            sg[nuovo] = {'albero': s['albero'], 'patch': s['patch'], 'ramo': _ramo(nuovo)}
1170    print(json.dumps({'vecchi': [v for v, _ in coppie], 'coppie': coppie, 'segni': sg}))
1171    return 0
1172_CI_GITHUB = '# {commento}\nname: delminio-firme\non:\n  pull_request:\n  push:\n    branches: [{ramo}]\njobs:\n  controlla:\n    runs-on: {macchina}\n    steps:\n      - uses: actions/checkout@v7\n        with:\n          fetch-depth: 0\n      - name: delminio-firme\n        env:\n          DELMINIO_URL: {url}\n          DELMINIO_FIRME_REPO: {repo}\n          DELMINIO_TOKEN: ${{{{ secrets.DELMINIO_FIRME }}}}\n          BASE: ${{{{ github.base_ref }}}}\n          PRIMA: ${{{{ github.event.before }}}}\n        run: |\n          curl -fsS -H "Authorization: Bearer $DELMINIO_TOKEN" "$DELMINIO_URL/static/kit/signoff-client" -o "$RUNNER_TEMP/signoff.py"\n          if [ -n "$BASE" ]; then\n            python3 "$RUNNER_TEMP/signoff.py" controlla "origin/$BASE..HEAD"\n          else\n            case "$PRIMA" in ""|0000000000000000000000000000000000000000) PRIMA=HEAD~1 ;; esac\n            python3 "$RUNNER_TEMP/signoff.py" controlla "$PRIMA..HEAD"\n          fi\n'
1173_CI_GITLAB = 'delminio-firme:\n  image: python:3\n  variables:\n    GIT_DEPTH: "0"\n    DELMINIO_URL: {url}\n    DELMINIO_FIRME_REPO: {repo}\n  rules:\n    - if: $CI_PIPELINE_SOURCE == "merge_request_event"\n  script:\n    - git fetch -q origin "$CI_MERGE_REQUEST_TARGET_BRANCH_NAME"\n    - curl -fsS -H "Authorization: Bearer $DELMINIO_FIRME" "$DELMINIO_URL/static/kit/signoff-client" -o signoff.py\n    - DELMINIO_TOKEN="$DELMINIO_FIRME" python3 signoff.py controlla "origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME..HEAD"\n'
1174
1175def _servizio(a: list) -> str:
1176    if a and a[0] in ('github', 'forgejo', 'gitea', 'gitlab'):
1177        return 'forgejo' if a[0] == 'gitea' else a[0]
1178    host = re.sub('^[a-z][a-z0-9+.-]*://', '', _remoto().lower()).split('@')[-1].split('/')[0].split(':')[0]
1179    if host == 'github.com' or host.endswith('.github.com'):
1180        return 'github'
1181    if 'gitlab' in host:
1182        return 'gitlab'
1183    if os.path.isdir('.forgejo') or os.path.isdir('.gitea'):
1184        return 'forgejo'
1185    return ''
1186
1187def _da_fuori(url: str) -> bool:
1188    import ipaddress
1189    import urllib.parse
1190    host = (urllib.parse.urlparse(url).hostname or '').lower()
1191    if not host or host == 'localhost' or '.' not in host or host.endswith(('.local', '.lan', '.home.arpa', '.internal')):
1192        return False
1193    try:
1194        ip = ipaddress.ip_address(host)
1195        return not (ip.is_private or ip.is_loopback or ip.is_link_local)
1196    except ValueError:
1197        return True
1198
1199def ci(a: list) -> int:
1200    servizio = _servizio(a)
1201    if not servizio:
1202        print(F('ci_quale'))
1203        return 2
1204    url = os.environ.get('DELMINIO_URL', '').rstrip('/')
1205    radice = git('rev-parse', '--show-toplevel') or '.'
1206    repo = json.dumps(_remoto())
1207    ramo = (git('symbolic-ref', '--short', 'refs/remotes/origin/HEAD') or 'origin/main').split('/', 1)[-1]
1208    if not _da_fuori(url):
1209        print(F('ci_dentro_casa', url=url))
1210    if servizio == 'gitlab':
1211        print(F('ci_gitlab', file='.gitlab-ci.yml'))
1212        print(_CI_GITLAB.format(url=url, repo=repo))
1213        print(F('ci_gitlab_passi'))
1214        return 0
1215    cartella = '.github' if servizio == 'github' else '.forgejo'
1216    file = os.path.join(cartella, 'workflows', 'delminio-firme.yml')
1217    testo = _CI_GITHUB.format(commento=F('ci_commento'), ramo=ramo, url=url, repo=repo, macchina='ubuntu-latest' if servizio == 'github' else 'docker')
1218    dove = os.path.join(radice, file)
1219    if os.path.exists(dove):
1220        if open(dove, encoding='utf-8').read() == testo:
1221            print(F('ci_gia_pronto', file=file))
1222        else:
1223            print(F('ci_esiste_diverso', file=file))
1224    else:
1225        os.makedirs(os.path.dirname(dove), exist_ok=True)
1226        with open(dove, 'w', encoding='utf-8') as f:
1227            f.write(testo)
1228        print(F('ci_scritto', file=file))
1229    if servizio == 'github':
1230        return _github(ramo)
1231    print(F('ci_passi_forgejo', ramo=ramo))
1232    return 0
1233_CONTROLLO = 'controlla'
1234
1235def _gh(*a: str, entrata: str | None=None) -> tuple[int, str]:
1236    try:
1237        r = subprocess.run(['gh', *a], capture_output=True, text=True, input=entrata, timeout=60)
1238    except (OSError, subprocess.TimeoutExpired) as e:
1239        return (1, str(e))
1240    return (r.returncode, (r.stdout if r.returncode == 0 else r.stderr or r.stdout).strip())
1241
1242def _gh_errore(out: str) -> str:
1243    righe = [r for r in out.splitlines() if r.strip()]
1244    return righe[-1][:300] if righe else '?'
1245
1246def _github(ramo: str) -> int:
1247    if not shutil.which('gh'):
1248        print(F('ci_gh_manca'))
1249        print(F('ci_passi_github', ramo=ramo))
1250        return 0
1251    if _gh('auth', 'status')[0] != 0:
1252        print(F('ci_gh_non_collegato'))
1253        print(F('ci_passi_github', ramo=ramo))
1254        return 0
1255    rc, out = _gh('repo', 'view', '--json', 'nameWithOwner,viewerPermission')
1256    try:
1257        r = json.loads(out) if rc == 0 else {}
1258    except ValueError:
1259        r = {}
1260    nwo = r.get('nameWithOwner') or ''
1261    if not nwo:
1262        print(F('ci_gh_quale_repo', errore=_gh_errore(out)))
1263        print(F('ci_passi_github', ramo=ramo))
1264        return 0
1265    if r.get('viewerPermission') != 'ADMIN':
1266        print(F('ci_gh_permessi', repo=nwo))
1267        print(F('ci_passi_github', ramo=ramo))
1268        return 0
1269    regola = _gh_regola(nwo, ramo)
1270    segreto = _gh_segreto(nwo)
1271    return 0 if regola and segreto else 1
1272
1273def _gh_regola(nwo: str, ramo: str) -> bool:
1274    base = f'repos/{nwo}/branches/{ramo}/protection'
1275    rc, out = _gh('api', base)
1276    if rc != 0 and 'HTTP 404' not in out:
1277        print(F('ci_gh_privato', repo=nwo) if 'Upgrade to GitHub Pro' in out else F('ci_gh_regola_no', ramo=ramo, errore=_gh_errore(out)))
1278        return False
1279    if rc != 0:
1280        corpo = {'required_status_checks': {'strict': False, 'contexts': [_CONTROLLO]}, 'enforce_admins': True, 'required_pull_request_reviews': None, 'restrictions': None}
1281        rc, out = _gh('api', '-X', 'PUT', base, '--input', '-', entrata=json.dumps(corpo))
1282        if rc != 0:
1283            print(F('ci_gh_privato', repo=nwo) if 'Upgrade to GitHub Pro' in out else F('ci_gh_regola_no', ramo=ramo, errore=_gh_errore(out)))
1284            return False
1285    else:
1286        d = json.loads(out)
1287        rsc = d.get('required_status_checks') or {}
1288        if _CONTROLLO not in _gh_controlli(rsc):
1289            print(F('ci_gh_regole_altre', ramo=ramo))
1290            rc, out = _gh('api', '-X', 'POST', base + '/required_status_checks/contexts', '--input', '-', entrata=json.dumps([_CONTROLLO])) if rsc else _gh('api', '-X', 'PATCH', base + '/required_status_checks', '--input', '-', entrata=json.dumps({'strict': False, 'contexts': [_CONTROLLO]}))
1291            if rc != 0:
1292                print(F('ci_gh_regola_no', ramo=ramo, errore=_gh_errore(out)))
1293                return False
1294        if not (d.get('enforce_admins') or {}).get('enabled'):
1295            rc, out = _gh('api', '-X', 'POST', base + '/enforce_admins')
1296            if rc != 0:
1297                print(F('ci_gh_regola_no', ramo=ramo, errore=_gh_errore(out)))
1298                return False
1299    rc, out = _gh('api', base)
1300    d = json.loads(out) if rc == 0 else {}
1301    if _CONTROLLO in _gh_controlli(d.get('required_status_checks') or {}) and (d.get('enforce_admins') or {}).get('enabled'):
1302        print(F('ci_gh_regola_ok', ramo=ramo, repo=nwo))
1303        return True
1304    print(F('ci_gh_regola_no', ramo=ramo, errore=_gh_errore(out) if rc else '?'))
1305    return False
1306
1307def _gh_controlli(rsc: dict) -> set:
1308    return set(rsc.get('contexts') or []) | {c.get('context') for c in rsc.get('checks') or [] if isinstance(c, dict)}
1309
1310def _gh_segreto(nwo: str) -> bool:
1311    rc, out = _gh('secret', 'list', '--repo', nwo, '--json', 'name')
1312    try:
1313        nomi = {x.get('name') for x in json.loads(out)} if rc == 0 else set()
1314    except ValueError:
1315        nomi = set()
1316    if rc != 0:
1317        print(F('ci_gh_segreto_no', errore=_gh_errore(out)))
1318        return False
1319    if 'DELMINIO_FIRME' in nomi:
1320        print(F('ci_gh_segreto_c_e', repo=nwo))
1321        return True
1322    imposta = ['gh', 'secret', 'set', 'DELMINIO_FIRME', '--repo', nwo]
1323    cmd = ' '.join(imposta)
1324    if not (sys.stdin.isatty() and sys.stdout.isatty()):
1325        print(F('ci_gh_segreto_tu', cmd=cmd))
1326        return False
1327    print(F('ci_gh_segreto_incolla'))
1328    esito = subprocess.run(imposta).returncode
1329    if esito != 0:
1330        print(F('ci_gh_segreto_no', errore=esito))
1331        return False
1332    print(F('ci_gh_segreto_fatto', repo=nwo))
1333    return True
1334VERBI = {'controlla': controlla, 'descrizione': descrizione, 'resoconto': resoconto, 'esporta': esporta, 'catena': catena, 'revisione': revisione, 'prove': prove, 'ci': ci, '_richiesta': _richiesta, '_messaggio': _messaggio, '_commit': _commit, '_segni': _segni, '_riscritti': _riscritti}
1335
1336def main(argv: list) -> int:
1337    verbo = argv[0] if argv else 'controlla'
1338    verbo = COMANDI['carta'].get(verbo, verbo)
1339    fai = VERBI.get(verbo)
1340    if fai is None:
1341        print(F('uso', cmd=CMD), file=sys.stderr if verbo not in ('-h', '--help') else sys.stdout)
1342        return 0 if verbo in ('-h', '--help') else 2
1343    try:
1344        return fai(argv[1:])
1345    except SenzaFirme as e:
1346        if e.sconosciuto:
1347            print(F('repo_sconosciuto', remoto=_remoto()), file=sys.stderr)
1348            return 2
1349        print(F('repo_senza_firme'))
1350        return 0
1351    except Rifiuto as e:
1352        if verbo.startswith('_'):
1353            return 0
1354        print(str(e), file=sys.stderr)
1355        return 2
1356if __name__ == '__main__':
1357    sys.exit(main(sys.argv[1:]))