#!/usr/bin/env python3 # © 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. """Le firme delle modifiche da un terminale, dai ganci git e da una CI (B923).""" from __future__ import annotations import base64 import datetime import hashlib import json import os import re import shutil import subprocess import sys import tempfile import urllib.error import urllib.request CMD = 'delminio firme' URL = os.environ.get('DELMINIO_URL', '').rstrip('/') TOKEN = os.environ.get('DELMINIO_TOKEN', '') STATO = os.environ.get('DELMINIO_STATO', '') MASSIMO = 20000 COMMIT_MAX = 500 RAMO_MAX = 200 APP_ANDROID = ('jG9UXQXhlWwgZvpNwGNDmhcDbR_94LnCQOAcyOOgJqg',) PROVE_TEMPO = 900 COMANDI = { "carta": { "catena": "catena", "chain": "catena", "check": "controlla", "checks": "prove", "ci": "ci", "controlla": "controlla", "description": "descrizione", "descrizione": "descrizione", "esporta": "esporta", "export": "esporta", "prove": "prove", "report": "resoconto", "resoconto": "resoconto", "review": "revisione", "revisione": "revisione" } } FRASI = { "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.", "ci_gitlab": "With GitLab there is a single file for the whole repo ({file}), and I won't touch it: add this job.", "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.", "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.", "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.", "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.", "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.", "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.", "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.", "ci_gh_regole_altre": "The {ramo} branch already has its own rules: I leave them as they are and only add what is missing.", "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.", "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.", "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.", "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.", "ci_gh_segreto_fatto": "\u2705 The DELMINIO_FIRME secret is on {repo}.", "ci_gh_segreto_no": "\u274c The secret was not set ({errore}): in the repository, Settings \u2192 Secrets and variables \u2192 Actions, name DELMINIO_FIRME.", "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.", "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.", "ci_gia_pronto": "\u2705 {file} is already there, and it's the right one.", "ci_scritto": "\u2705 Wrote {file}: commit it and push it like any other file.", "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.", "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.", "ci_quale": "I can't tell this repo's git service. Tell me which: delminio signoffs ci github, forgejo (Gitea too) or gitlab.", "dell_autore": "by the author: it does not count", "chi_non_detto": "another session", "revisione_dell_autore": "The review of {commit} is recorded, but you are the author: what counts is the reviewer's, with their agent.", "uso": "usage: {cmd} check [] \xb7 {cmd} description [] \xb7 {cmd} report [] [] \xb7 {cmd} export [] \xb7 {cmd} chain [] \xb7 {cmd} review clean|findings [N] \xb7 {cmd} checks \xb7 {cmd} ci [github|forgejo|gitlab]", "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).", "non_risponde": "\u274c Delminio does not answer ({url}): {errore}", "assenti": "Change sign-off is not available in this space: the licence does not include it.", "intestazione": "The person's words to the agent, recorded by Delminio (change sign-off):", "non_registrata": "not recorded in Delminio", "controlli": "The checks before the commit:", "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.", "nascosto": "[hidden]", "troncata": "[\u2026 {n} more characters not copied here]", "nessun_commit": "No commits in {intervallo}.", "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.", "firmata": " \u2705 {commit} signed \u2014 {soggetto}", "da_firmare": " \u274c {commit} to sign ({zone}): still missing {manca} \u2014 {soggetto}", "respinta": " \u274c {commit} rejected \u2014 {soggetto}", "libera": " \xb7 {commit} outside the sign-off zones \u2014 {soggetto}", "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}", "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}", "merge_pulito": " \xb7 {commit} merge with no changes of its own \u2014 {soggetto}", "unita": " \u2705 {commit} comes from branch {ramo}: its {n} changes are signed \u2014 {soggetto}", "unita_da_firmare": " \u274c {commit} comes from branch {ramo}: {n} of its changes still need signing \u2014 {soggetto}", "unita_mancano": " \u274c {commit} comes from branch {ramo}, but {n} of its commits have no recorded sign-off \u2014 {soggetto}", "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}", "parole_non_tornano": " \u274c {commit}: the words of request {id} do not match its fingerprint \u2014 the message was changed", "parole_ignote": " \u274c {commit}: request {id} is not the one Delminio recorded", "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.", "urgente": " \u26a1 {commit} let in as urgent \u2014 {soggetto} (let through by {da} on {quando}: \u201c{perche}\u201d; sign-offs are given afterwards)", "gov_urgenza": "{quando} \u2014 {chi} lets commit {commit} into {repo} as urgent: \u201c{perche}\u201d", "esportata": "The chain is in {file}: {anelli} links, {esito}.", "catena_rotta": "broken at link {anello}", "revisione_registrata": "Your review of {commit} is recorded: you can now sign it from the app, under Sign-offs.", "revisione_senza_sessione": "Your agent records the review, from its session: ask it to review the commit and to run \u201c{cmd} review 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.", "descr_parole": "### What the person asked for", "descr_nessuna_parola": "_No recorded request: changes made by hand._", "descr_fatti": "### The facts", "descr_commit": "{n} commits, {file} files", "descr_assistito": "With the agent: {con}", "descr_zona": "Sign-off zone {codice} \u201c{cosa}\u201d: {servono} signatures, reviewed by {chi}", "descr_chiunque": "anyone in the space", "descr_controllo": "Check {codice} `{comando}` \u2192 exit {uscita}", "descr_revisione": "Review by {chi}, with {revisore}: {esito}, {rilievi} findings ({indipendente})", "indipendente": "independent", "stessa_sessione": "from the session that wrote it: does not count", "indipendente_stesso_modello": "independent, same model as the author", "descr_stati": "Sign-off: {stati}", "stato_firmata": "signed", "stato_unita": "signed on the branch", "stato_libera": "outside the zones", "stato_pulito": "merges", "stato_senza": "with no recorded sign-off", "stato_da_firmare": "to sign", "stato_respinta": "rejected", "stato_zona": "in a zone with no recorded sign-off", "res_titolo": "# Change sign-off \u2014 {remoto} \u2014 {intervallo}", "res_generato": "Written on {quando} by Delminio. The sign-off chain: {anelli} links, {esito}.", "res_stato": "Status: {riga}", "res_unita": "Merged into the main branch from branch {ramo}: the signatures are on its {n} commits.", "res_autore": "Accountable: {autore} \xb7 with {con} \xb7 {quando}", "res_a_mano": "no agent (by hand)", "res_zona": "Sign-off zone {codice} \u201c{cosa}\u201d: {servono} signatures", "res_firma": "Signed by {persona}, {significato}, {quando}{parole}", "significato_autore": "as author", "significato_revisione": "as reviewer", "significato_respinta": "rejected", "res_nessuna_firma": "No signatures yet.", "res_richiesta": "Request {id} (fingerprint {impronta}\u2026): {torna}", "res_torna": "the words match the recorded fingerprint", "res_non_torna": "the words do NOT match the fingerprint: the message was changed", "res_file": "{n} files: {elenco}", "res_come_verificare": "The chain can be checked without Delminio: \u201cdelminio signoffs export\u201d, then, inside the repository, \u201cdelminio signoffs chain []\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.", "res_scritto": "The report is in {file}: {commit} commits.", "ripresa": " \u2705 {commit} is a change from branch {ramo}, redone (rebase or cherry-pick), with its signatures \u2014 {soggetto}", "ripresa_da_firmare": " \u274c {commit} is a change from branch {ramo}, redone (rebase or cherry-pick), still to sign \u2014 {soggetto}", "repo_senza_firme": "This repository has no change sign-off: nothing to check. The administrator turns it on per repository, from Sign-offs.", "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.", "scartata": " \u274c {commit} discarded: it is no longer signed \u2014 {soggetto}", "manca_prove": "the zone's checks on this commit", "manca_autore": "the author's signature", "manca_persone": "the reviewer's review, with their agent, and their signature", "parole_tolte": " \u274c {commit}: request {id}, which Delminio linked to this commit, is not in the message \u2014 the words were removed", "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", "catena_ancorata": "intact, and anchored in {n} commits of this repository", "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", "gov_accese": "{quando} \u2014 {chi} switches sign-off on in the space", "gov_spente": "{quando} \u2014 {chi} switches sign-off off in the space: nothing is recorded until it is switched back on", "gov_repo_si": "{quando} \u2014 {chi} switches sign-off on in repository {repo}", "gov_repo_no": "{quando} \u2014 {chi} switches sign-off off in repository {repo}: nothing is recorded there until it is switched back on", "gov_chiave_si": "{quando} \u2014 {chi} creates the read key \u201c{etichetta}\u201d", "gov_chiave_no": "{quando} \u2014 {chi} revokes the read key \u201c{etichetta}\u201d", "gov_zona_nata": "{quando} \u2014 {chi} creates zone {codice}: {zona}", "gov_zona_ritirata": "{quando} \u2014 {chi} withdraws zone {codice}", "gov_zona_cambiata": "{quando} \u2014 {chi} changes zone {codice}: from {prima} to {dopo}", "gov_zona_detta": "{dove}, {servono} signatures, reviewed by {chi}, checks `{comando}`", "res_governo": "## Who governed sign-off", "res_unito_da": "Into the main branch by {chi}, on {quando} (git says so: the person who merges doesn't go through Delminio)", "res_git_dice": "Git says the author is {autore}: not verified, Delminio did not see this commit being made", "res_non_in_catena": "\u274c this change is not in the chain: Delminio's database says things the chain does not", "res_zona_dopo": "{quando}: zone {zone} was created after the commit, and applies to it too", "res_prova_mancante": "Check {codice} `{comando}` \u2192 not run on this commit", "res_firme_diverse": "\u274c Delminio's database shows different signatures ({motore}): the chain is what counts, and the database has been changed", "res_scartata": "Discarded on {quando}: {perche}", "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)", "copia_diversa": "\u274c {file} is not the beginning of this chain: link {anello} is different. The chain was rewritten after that copy", "copia_uguale": "{file}: its {anelli} links are the beginning of this chain, unchanged", "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.", "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}", "prova_passata": "\u2705 the check for sign-off zone {codice} passed on this commit.", "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", "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\" ", "prove_registrate": "The checks of {commit} are recorded: {esito}.", "prove_nessuna": "No sign-off zone asks for checks on {commit}.", "res_passkey": "with {persona}'s passkey \u201c{nome}\u201d, added on {quando} (confirmed with {come}): the device signature matches", "res_passkey_non_torna": "\u274c the device signature does NOT match ({perche}): this sign-off wasn't given by {persona}'s passkey", "res_passkey_cieca": "\u26a0\ufe0f the device signature can't be checked here: it needs Python's cryptography module or the openssl command", "res_senza_passkey_prima": "signed in the app before sign-offs required a passkey", "res_senza_passkey_dopo": "\u274c signed without a passkey after sign-offs require one: no device gave this sign-off", "res_persona": "{persona} has been in the space since {quando}, {da}", "res_persona_invitata": "invited by {chi}", "res_persona_da_sempre": "from before who invites was recorded", "res_passkey_mail": "email", "res_passkey_password": "password", "gov_passkey": "{quando} \u2014 from here every sign-off requires the passkey of the signer's device", "gov_persona_entrata": "{quando} \u2014 {persona} joins the space as {ruolo}, invited by {chi}", "gov_persona_spenta": "{quando} \u2014 {persona} leaves the space (account turned off)", "gov_persona_riaccesa": "{quando} \u2014 {persona} is back in the space (account turned on)", "gov_passkey_nuova": "{quando} \u2014 {persona} adds the passkey \u201c{nome}\u201d for {rp}, confirmed with {come}", "gov_passkey_revocata": "{quando} \u2014 {chi} revokes {persona}'s passkey \u201c{nome}\u201d", "perche_chiave": "the passkey isn't in the chain, or isn't the signer's", "perche_revocata": "the passkey was revoked", "perche_commit": "the device signed other commits", "perche_sfida": "the device signed other words, another meaning or another person", "perche_origine": "signed from another address", "perche_persona": "without the person's fingerprint or PIN", "perche_firma": "the cryptographic signature doesn't match the public key" } def F(chiave: str, **sost) -> str: t = FRASI.get(chiave, chiave) for k, v in sost.items(): t = t.replace('{' + k + '}', str(v)) return t class Rifiuto(Exception): def __init__(self, messaggio: str, codice: int=0): super().__init__(messaggio) self.codice = codice def forma(testo: str) -> str: return '\n'.join((r.rstrip() for r in (testo or '').strip().splitlines())).strip() def impronta(testo: str) -> str: return hashlib.sha256(forma(testo).encode('utf-8')).hexdigest() def verifica_catena(anelli: list) -> object: prima = '' for i, a in enumerate(anelli): atteso = hashlib.sha256((prima + '\n' + a.get('tipo', '') + '\n' + a.get('contenuto', '')).encode('utf-8')).hexdigest() if a.get('prima', '') != prima or a.get('impronta') != atteso: return a.get('seq', i + 1) prima = atteso return None def git(*a: str) -> str: r = subprocess.run(['git', *a], capture_output=True, text=True, encoding='utf-8', errors='replace') return r.stdout.strip() if r.returncode == 0 else '' def chiedi(metodo: str, percorso: str, corpo=None, attesa: int=30) -> dict: if not URL or not TOKEN: raise Rifiuto(F('senza_motore')) 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'}) try: return json.loads(urllib.request.urlopen(req, timeout=attesa).read()) except urllib.error.HTTPError as e: try: perche = json.loads(e.read()).get('error') or str(e) except Exception: perche = str(e) raise Rifiuto(F('assenti') if e.code == 404 and perche == 'Not Found' else '❌ ' + perche, e.code) from None except Exception as e: raise Rifiuto(F('non_risponde', url=URL, errore=e)) from None _VUOTO = [] def _albero_vuoto() -> str: if not _VUOTO: r = subprocess.run(['git', 'hash-object', '-t', 'tree', '--stdin'], input=b'', capture_output=True) _VUOTO.append(r.stdout.decode().strip()) return _VUOTO[0] def _patch(da: str, a: str) -> str: d = subprocess.run(['git', '-c', 'diff.noprefix=false', '-c', 'diff.mnemonicPrefix=false', 'diff', '--no-color', '--no-ext-diff', '--binary', da, a], capture_output=True) if d.returncode or not d.stdout.strip(): return '' p = subprocess.run(['git', 'patch-id', '--stable'], input=d.stdout, capture_output=True) return (p.stdout.split() or [b''])[0].decode() def _genitori(h: str) -> list: return git('rev-list', '--parents', '-n', '1', h).split()[1:] def _principale() -> str: r = git('symbolic-ref', '-q', 'refs/remotes/origin/HEAD') if r: return r for n in ('refs/remotes/origin/main', 'refs/remotes/origin/master'): if git('rev-parse', '-q', '--verify', n): return n return '' def _ramo(h: str, nome: str='') -> dict | None: principale = _principale() base = git('merge-base', principale, h) if principale else '' if not base: return None commit = git('rev-list', '--no-merges', '--reverse', f'{base}..{h}').split()[-RAMO_MAX:] return {'nome': nome, 'patch': _patch(base, h) if commit else '', 'commit': commit} def _file(h: str) -> list: file = git('diff-tree', '--no-commit-id', '--name-only', '-r', '-z', '--root', h).split('\x00') return [f for f in file if f.strip()][:400] def segni(h: str) -> dict: gen = _genitori(h) return {'albero': git('rev-parse', h + '^{tree}'), 'patch': _patch(gen[0] if gen else _albero_vuoto(), h), 'file': _file(h)} def _parole_nel_messaggio(msg: str) -> tuple[dict, dict]: dette = dict(re.findall('^Delminio-(?:Request|Richiesta): (\\d+) ([0-9a-f]{64})\\s*$', msg, re.M)) testi, corrente = ({}, None) for r in msg.splitlines(): m = re.match('^\\[(\\d+)\\] ', r) if m: corrente = m.group(1) testi[corrente] = [] elif corrente and (r == '>' or r.startswith('> ')): testi[corrente].append(r[2:] if r.startswith('> ') else '') else: corrente = None return (dette, {k: '\n'.join(v) for k, v in testi.items()}) def _parole_rotte(h: str, msg: str, carta: dict | None) -> list: dette, testi = _parole_nel_messaggio(msg) registrate = {x['impronta']: x for x in (carta or {}).get('richieste') or []} rotte = [] for rid, imp in dette.items(): if impronta(testi.get(rid) or '') != imp: rotte.append((rid, 'non_tornano')) elif carta is not None and imp not in registrate: rotte.append((rid, 'ignote')) scritte = set(dette.values()) for imp, x in registrate.items(): if imp not in scritte: rotte.append((str(x.get('id') or '?'), 'tolte')) return rotte def intervallo_di(a: list) -> str: if a: return a[0] if git('rev-parse', '-q', '--verify', '@{upstream}'): return '@{upstream}..HEAD' p = _principale() return f'{p}..HEAD' if p else 'HEAD~1..HEAD' def _merge_pulito(h: str) -> bool: return len(_genitori(h)) > 1 and (not git('diff-tree', '--cc', '--no-commit-id', '--name-only', '-r', h)) class SenzaFirme(Exception): def __init__(self, sconosciuto: bool=False): super().__init__() self.sconosciuto = sconosciuto def leggi(intervallo: str, promuovi: bool=False) -> list: r = subprocess.run(['git', 'rev-list', '--reverse', intervallo], capture_output=True, text=True, encoding='utf-8', errors='replace') if r.returncode != 0: raise Rifiuto(F('intervallo_illeggibile', intervallo=intervallo, errore=(r.stderr.strip().splitlines() or ['?'])[0][:200])) voluti = r.stdout.split()[-COMMIT_MAX:] if not voluti: return [] remoto = _remoto() puliti = {h for h in voluti if _merge_pulito(h)} da_chiedere = [h for h in voluti if h not in puliti] 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 {}}) if d.get('repo_senza_firme'): raise SenzaFirme(bool(d.get('repo_sconosciuto'))) carte = d.get('carte') or {} if da_chiedere else {} urgenze = dict(d.get('urgenze') or {}) if da_chiedere else {} senza = [h for h in da_chiedere if carte.get(h) is None] fuori = {} if senza: d2 = chiedi('POST', '/api/carta/commit', {'hash': senza, 'segni': {h: segni(h) for h in senza}, 'remoto': remoto, 'promuovi': promuovi}) fuori = d2.get('fuori') or {} urgenze.update(d2.get('urgenze') or {}) out = [] for h in voluti: msg = git('log', '-1', '--format=%B', h) 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)}) return out PASSANO = ('firmata', 'libera', 'unita', 'pulito', 'urgente') def _mancano(k: dict) -> str: nomi = {'prove': F('manca_prove'), 'autore': F('manca_autore'), 'persone': F('manca_persone')} return ', '.join((nomi.get(m, m) for m in k.get('mancano') or [])) def esito(c: dict) -> tuple[str, str]: st, riga = _esito(c) u = c.get('urgenza') if u and st in ('da_firmare', 'zona', 'senza'): 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 '')) return (st, riga) def _esito(c: dict) -> tuple[str, str]: corto, sogg = (c['hash'][:10], c['soggetto']) if c['pulito']: return ('pulito', F('merge_pulito', commit=corto, soggetto=sogg)) k = c['carta'] if k is not None: st = k['stato'] if st == 'firmata': return (st, F('firmata', commit=corto, soggetto=sogg)) if st == 'libera': return (st, F('libera', commit=corto, soggetto=sogg)) if st == 'respinta': return (st, F('respinta', commit=corto, soggetto=sogg)) if st == 'scartata': return (st, F('scartata', commit=corto, soggetto=sogg)) return ('da_firmare', F('da_firmare', commit=corto, soggetto=sogg, manca=_mancano(k), zone=', '.join((z['codice'] for z in k.get('zone') or [])))) fu = c['fuori'] lg = fu.get('legame') zone = ', '.join((z['codice'] for z in fu.get('zone') or [])) if lg: ramo = lg.get('ramo') or '?' if lg.get('mancano'): return ('zona', F('unita_mancano', commit=corto, soggetto=sogg, ramo=ramo, n=len(lg['mancano']))) if lg.get('scoperte'): return ('zona', F('unita_scoperta', commit=corto, soggetto=sogg, ramo=ramo, zone=', '.join((z['codice'] for z in lg['scoperte'])))) aperte = [x for x in lg.get('carte') or [] if x['stato'] not in ('firmata', 'libera')] if lg.get('via') == 'ripreso': 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)) if aperte: return ('da_firmare', F('unita_da_firmare', commit=corto, soggetto=sogg, ramo=ramo, n=len(aperte))) return ('unita', F('unita', commit=corto, soggetto=sogg, ramo=ramo, n=len(lg.get('carte') or []))) if zone: return ('zona', F('senza_in_zona', commit=corto, soggetto=sogg, zone=zone)) return ('senza', F('senza', commit=corto, soggetto=sogg)) def _dice_rotta(h: str, rid: str, perche: str) -> str: 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) def controlla(a: list) -> int: intervallo = intervallo_di(a) commit = leggi(intervallo, promuovi=True) if not commit: print(F('nessun_commit', intervallo=intervallo)) return 0 conti = {'firmate': 0, 'da_firmare': 0, 'libere': 0, 'senza': 0, 'rotte': 0, 'urgenti': 0} for c in commit: for rid, perche in _parole_rotte(c['hash'], c['msg'], c['carta']): print(_dice_rotta(c['hash'], rid, perche)) conti['rotte'] += 1 st, riga = esito(c) print(riga) if st in ('firmata', 'unita'): conti['firmate'] += 1 elif st in ('libera', 'pulito'): conti['libere'] += 1 elif st == 'urgente': conti['urgenti'] += 1 elif st in ('senza', 'zona'): conti['senza'] += 1 else: conti['da_firmare'] += 1 print(F('esito', **conti)) return 1 if conti['da_firmare'] or conti['rotte'] or conti['senza'] else 0 def _remoto() -> str: remoto = os.environ.get('DELMINIO_FIRME_REPO', '').strip() or git('remote', 'get-url', 'origin') return re.sub('^([A-Za-z][A-Za-z0-9+.-]*://)[^/]*@', '\\1', remoto) def _quando(iso: str) -> str: return (iso or '')[:16].replace('T', ' ') + ' UTC' if iso else '' def _richieste(c: dict) -> list: dette, testi = _parole_nel_messaggio(c['msg']) return [(rid, testi.get(rid) or '', imp, impronta(testi.get(rid) or '') == imp) for rid, imp in dette.items()] def _nome_stato(st: str) -> str: 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) def _nome_firma(significato: str) -> str: return {'autore': F('significato_autore'), 'revisione': F('significato_revisione'), 'respinta': F('significato_respinta')}.get(significato, significato) def descrizione(a: list) -> int: intervallo = intervallo_di(a) commit = [c for c in leggi(intervallo) if not c['pulito']] if not commit: print(F('nessun_commit', intervallo=intervallo)) return 0 out, viste = ([F('descr_parole'), ''], set()) for c in commit: for rid, testo, imp, _torna in _richieste(c): if imp in viste: continue viste.add(imp) out += ['> ' + r if r else '>' for r in testo.split('\n')] + [''] if not viste: out += [F('descr_nessuna_parola'), ''] file, assistiti, zone, controlli, revisioni = (set(), set(), {}, {}, []) for c in commit: k = c['carta'] or {} file |= set(k.get('file') or _file(c['hash'])) if k.get('assistito'): assistiti.add(k['assistito']) for z in k.get('zone') or c['fuori'].get('zone') or []: zone[z['codice']] = z for x in k.get('controlli') or []: controlli[x['codice'], x['comando']] = x['uscita'] revisioni += k.get('revisioni') or [] stati = {} for c in commit: st, _ = esito(c) stati[st] = stati.get(st, 0) + 1 out += [F('descr_fatti'), '', '- ' + F('descr_commit', n=len(commit), file=len(file))] if assistiti: out.append('- ' + F('descr_assistito', con=', '.join(sorted(assistiti)))) for z in zone.values(): chi = ', '.join(z['firme'].get('persone') or []) or F('descr_chiunque') out.append('- ' + F('descr_zona', codice=z['codice'], cosa=z['cosa'], servono=z['firme']['servono'], chi=chi)) for (codice, comando), uscita in controlli.items(): out.append('- ' + F('descr_controllo', codice=codice, comando=comando, uscita=uscita)) for r in revisioni: 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))) out.append('- ' + F('descr_stati', stati=', '.join((f'{_nome_stato(k)} {v}' for k, v in sorted(stati.items()))))) print('\n'.join(out)) return 0 def _ancore() -> list: out = [] 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(): h, _, valori = riga.partition('\t') for v in valori.split(','): m = re.fullmatch('\\s*(\\d+) ([0-9a-f]{64})\\s*', v) if m: out.append((h, int(m.group(1)), m.group(2))) return out def _ancore_rotte(anelli: list) -> tuple: per_seq = {a.get('seq'): a.get('impronta') for a in anelli} ancore = _ancore() return (len(ancore), [(h, seq) for h, seq, imp in ancore if per_seq.get(seq) != imp]) def _dalla_catena(anelli: list) -> dict: d = {'carte': {}, 'firme': {}, 'revisioni': {}, 'zone_dopo': {}, 'scartate': {}, 'prove': {}, 'governo': [], 'chiavi': {}, 'revocate': {}, 'persone': {}, 'regola': None} for a in anelli: try: x = json.loads(a.get('contenuto') or '{}') except ValueError: continue tipo = a.get('tipo') if tipo == 'carta': d['carte'][x.get('id')] = x elif tipo == 'firma': d['firme'].setdefault(x.get('carta'), []).append({**x, '_seq': a.get('seq')}) elif tipo == 'revisione': d['revisioni'].setdefault(x.get('carta'), []).append(x) elif tipo == 'zona_dopo': d['zone_dopo'].setdefault(x.get('carta'), []).append(x) elif tipo == 'scartata': d['scartate'][x.get('carta')] = x elif tipo == 'prove': fatte = d['prove'].setdefault(x.get('carta'), {}) for p in x.get('controlli') or []: fatte[p.get('codice')] = p elif tipo in ('funzione', 'repo', 'zona', 'lettore', 'urgenza'): d['governo'].append({'tipo': tipo, **x}) elif tipo == 'chiave': if x.get('creata'): d['chiavi'][x.get('id')] = {**x, '_seq': a.get('seq')} else: d['revocate'].setdefault(x.get('id'), a.get('seq')) d['governo'].append({'tipo': tipo, **x}) elif tipo == 'persona': if x.get('gesto') == 'entrata': d['persone'].setdefault(x.get('persona'), x) d['governo'].append({'tipo': tipo, **x}) elif tipo == 'regola' and x.get('passkey') and (d['regola'] is None): d['regola'] = a.get('seq') d['governo'].append({'tipo': tipo, **x}) return d def _canonico(d: dict) -> str: return json.dumps(d, ensure_ascii=False, sort_keys=True, separators=(',', ':')) def _da_b64u(s: str) -> bytes: s = str(s or '') return base64.urlsafe_b64decode(s + '=' * (-len(s) % 4)) def _sfida(cosa: dict, nonce: str) -> str: h = hashlib.sha256((_canonico(cosa) + '\n' + nonce).encode('utf-8')).digest() return base64.urlsafe_b64encode(h).rstrip(b'=').decode() def _firma_valida(alg: int, pem: str, firma: bytes, dati: bytes): try: from cryptography.exceptions import InvalidSignature from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import ec, ed25519, padding, rsa k = serialization.load_pem_public_key(pem.encode()) try: if isinstance(k, ec.EllipticCurvePublicKey): k.verify(firma, dati, ec.ECDSA(hashes.SHA256())) elif isinstance(k, rsa.RSAPublicKey): k.verify(firma, dati, padding.PKCS1v15(), hashes.SHA256()) elif isinstance(k, ed25519.Ed25519PublicKey): k.verify(firma, dati) else: return False return True except (InvalidSignature, ValueError): return False except ImportError: pass if not shutil.which('openssl'): return None with tempfile.TemporaryDirectory() as cartella: percorsi = {} for nome, contenuto in (('chiave.pem', pem.encode()), ('firma', firma), ('dati', dati)): percorsi[nome] = os.path.join(cartella, nome) with open(percorsi[nome], 'wb') as h: h.write(contenuto) if alg == -8: cmd = ['openssl', 'pkeyutl', '-verify', '-pubin', '-inkey', percorsi['chiave.pem'], '-rawin', '-in', percorsi['dati'], '-sigfile', percorsi['firma']] else: cmd = ['openssl', 'dgst', '-sha256', '-verify', percorsi['chiave.pem'], '-signature', percorsi['firma'], percorsi['dati']] return subprocess.run(cmd, capture_output=True).returncode == 0 def _origine_sua(origine: str, rp: str) -> bool: from urllib.parse import urlparse if origine.startswith('android:apk-key-hash:'): return origine[len('android:apk-key-hash:'):] in APP_ANDROID return urlparse(origine).hostname == rp def _dispositivo(f: dict, k: dict, fatti: dict) -> tuple: d = f.get('dispositivo') if not d: if fatti['regola'] is not None and (f.get('_seq') or 0) > fatti['regola']: return (F('res_senza_passkey_dopo'), False) return (F('res_senza_passkey_prima'), True) persona = f.get('persona') or '?' chiave = fatti['chiavi'].get(d.get('chiave')) perche = '' if chiave is None or chiave.get('persona') != persona or (chiave.get('_seq') or 0) > (f.get('_seq') or 0): perche = F('perche_chiave') elif (rev := fatti['revocate'].get(d.get('chiave'))) is not None and rev < (f.get('_seq') or 0): perche = F('perche_revocata') elif {'id': k.get('id'), 'hash': k.get('hash')} not in (d.get('carte') or []): perche = F('perche_commit') if not perche: cosa = {'persona': persona, 'significato': f.get('significato'), 'parole': f.get('parole') or '', 'carte': d.get('carte') or []} try: cdj = _da_b64u(d.get('client')) cd, ad = (json.loads(cdj), _da_b64u(d.get('autenticatore'))) except ValueError: cd, ad, cdj = ({}, b'', b'') rp = chiave.get('rp') or '' if cd.get('type') != 'webauthn.get' or cd.get('challenge') != _sfida(cosa, d.get('nonce') or ''): perche = F('perche_sfida') elif not _origine_sua(cd.get('origin') or '', rp) or ad[:32] != hashlib.sha256(rp.encode()).digest(): perche = F('perche_origine') elif len(ad) < 37 or ad[32] & 5 != 5: perche = F('perche_persona') else: esito = _firma_valida(int(chiave.get('alg') or 0), chiave.get('pem') or '', _da_b64u(d.get('firma')), ad + hashlib.sha256(cdj).digest()) if esito is None: return (F('res_passkey_cieca'), False) if not esito: perche = F('perche_firma') if perche: return (F('res_passkey_non_torna', perche=perche, persona=persona), False) come = F('res_passkey_mail') if chiave.get('provata') == 'mail' else F('res_passkey_password') return (F('res_passkey', nome=chiave.get('nome') or '—', persona=persona, quando=_quando(chiave.get('quando')), come=come), True) def _chi_e_entrato(persona: str, fatti: dict) -> str: e = fatti['persone'].get(persona) or {} k = next((x for x in fatti['chiavi'].values() if x.get('persona') == persona), {}) quando = e.get('quando') or k.get('entrata') or '' da = e.get('invitata_da') or k.get('invitata_da') or '' if not quando: return '' return F('res_persona', persona=persona, quando=_quando(quando), da=F('res_persona_invitata', chi=da) if da else F('res_persona_da_sempre')) def _verifica(anelli: list) -> tuple: rotto = verifica_catena(anelli) if rotto is not None: return (F('catena_rotta', anello=rotto), False) n, rotte = _ancore_rotte(anelli) if rotte: h, seq = rotte[0] return (F('ancora_rotta', commit=h[:10], anello=seq, n=len(rotte)), False) return (F('catena_ancorata', n=n) if n else F('catena_non_ancorata'), True) def _governo(g: dict) -> str: quando, chi = (_quando(g.get('quando')), g.get('chi') or '?') if g['tipo'] == 'funzione': if g.get('accesa'): return F('gov_accese', quando=quando, chi=chi) return F('gov_spente', quando=quando, chi=chi) if g['tipo'] == 'repo': if g.get('firme'): return F('gov_repo_si', quando=quando, chi=chi, repo=g.get('repo') or '?') return F('gov_repo_no', quando=quando, chi=chi, repo=g.get('repo') or '?') if g['tipo'] == 'regola': return F('gov_passkey', quando=quando) if g['tipo'] == 'persona': if g.get('gesto') == 'entrata': return F('gov_persona_entrata', quando=quando, persona=g.get('persona') or '?', ruolo=g.get('ruolo') or '?', chi=g.get('invitata_da') or '?') if g.get('gesto') == 'spenta': return F('gov_persona_spenta', quando=quando, persona=g.get('persona') or '?') return F('gov_persona_riaccesa', quando=quando, persona=g.get('persona') or '?') if g['tipo'] == 'chiave': if g.get('creata'): come = F('res_passkey_mail') if g.get('provata') == 'mail' else F('res_passkey_password') return F('gov_passkey_nuova', quando=quando, persona=g.get('persona') or '?', nome=g.get('nome') or '—', rp=g.get('rp') or '?', come=come) return F('gov_passkey_revocata', quando=quando, chi=chi, persona=g.get('persona') or '?', nome=g.get('nome') or '—') if g['tipo'] == 'urgenza': return F('gov_urgenza', quando=quando, chi=chi, commit=(g.get('hash') or '?')[:10], repo=g.get('remoto') or '?', perche=g.get('perche') or '') if g['tipo'] == 'lettore': if g.get('creata'): return F('gov_chiave_si', quando=quando, chi=chi, etichetta=g.get('etichetta') or '?') return F('gov_chiave_no', quando=quando, chi=chi, etichetta=g.get('etichetta') or '?') prima, dopo = (g.get('prima'), g.get('dopo')) def detta(z): f = z['firme'] 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 '-') if not prima: return F('gov_zona_nata', quando=quando, chi=chi, codice=g.get('codice') or '?', zona=detta(dopo)) if not dopo: return F('gov_zona_ritirata', quando=quando, chi=chi, codice=g.get('codice') or '?') return F('gov_zona_cambiata', quando=quando, chi=chi, codice=g.get('codice') or '?', prima=detta(prima), dopo=detta(dopo)) def _parole_dal_git(k: dict) -> list: if subprocess.run(['git', 'cat-file', '-e', k['hash'] + '^{commit}'], capture_output=True).returncode: return None registrate = {x['impronta'] for x in k.get('richieste') or []} return [(rid, testo, imp, torna, imp in registrate) for rid, testo, imp, torna in _richieste({'msg': git('log', '-1', '--format=%B', k['hash'])})] def _scrivi_parole(out: list, righe, rientro: str) -> None: for rid, testo, imp, torna, *registrata in righe: ok = torna and (not registrata or registrata[0]) out.append(rientro + '- ' + F('res_richiesta', id=rid, impronta=imp[:16], torna=F('res_torna') if ok else F('res_non_torna'))) out += [rientro + ' > ' + r if r else rientro + ' >' for r in testo.split('\n')] def resoconto(a: list) -> int: intervallo = intervallo_di(a[:1]) dove = a[1] if len(a) > 1 else '' commit = leggi(intervallo) anelli = chiedi('GET', '/api/carta/catena').get('anelli') or [] verdetto, ok = _verifica(anelli) fatti = _dalla_catena(anelli) 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), ''] for c in commit: st, riga = esito(c) out += [f"## {c['hash'][:10]} — {c['soggetto']}", '', '- ' + F('res_stato', riga=riga.strip())] if c['pulito']: out.append('') continue carte = [c['carta']] if c['carta'] else (c['fuori'].get('legame') or {}).get('carte') or [] if not c['carta'] and carte: out.append('- ' + F('res_unita', n=len(carte), ramo=c['fuori']['legame'].get('ramo') or '?')) ct = git('log', '-1', '--format=%ct', c['hash']) quando = datetime.datetime.fromtimestamp(int(ct), datetime.timezone.utc).strftime('%Y-%m-%d %H:%M UTC') if ct.isdigit() else '' out.append('- ' + F('res_unito_da', chi=git('log', '-1', '--format=%cn', c['hash']), quando=quando)) if not carte: out.append('- ' + F('res_git_dice', autore=git('log', '-1', '--format=%an <%ae>', c['hash']))) for k in carte: dentro = ' ' if not c['carta'] else '' if not c['carta']: out.append(f"- `{k['hash'][:10]}` {k.get('soggetto') or ''}") dalla = fatti['carte'].get(k['id']) if dalla is None: out.append(dentro + '- ' + F('res_non_in_catena')) ok = False 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')))) for z in (dalla or k).get('zone') or []: out.append(dentro + '- ' + F('res_zona', codice=z['codice'], cosa=z['cosa'], servono=max(int(z['firme'].get('servono') or 0), 2))) for zd in fatti['zone_dopo'].get(k['id']) or []: out.append(dentro + '- ' + F('res_zona_dopo', quando=_quando(zd.get('quando')), zone=', '.join((z['codice'] for z in zd.get('zone') or [])))) dopo = fatti['prove'].get(k['id']) or {} for p in (dalla or k).get('prove') or []: 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) 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']))) for r in fatti['revisioni'].get(k['id']) or []: 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', '')))) firme_catena = fatti['firme'].get(k['id']) or [] for f in firme_catena: 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 '')) riga, buona = _dispositivo(f, k, fatti) out.append(dentro + ' - ' + riga) if (chi_e := _chi_e_entrato(f['persona'], fatti)): out.append(dentro + ' - ' + chi_e) ok = ok and buona if {(f['persona'], f['significato']) for f in firme_catena} != {(f['persona'], f['significato']) for f in k.get('firme') or []}: out.append(dentro + '- ' + F('res_firme_diverse', motore=', '.join((f"{f['persona']} ({_nome_firma(f['significato'])})" for f in k.get('firme') or [])) or '-')) ok = False if not firme_catena and (k.get('zone') or []): out.append(dentro + '- ' + F('res_nessuna_firma')) if (sc := fatti['scartate'].get(k['id'])): out.append(dentro + '- ' + F('res_scartata', quando=_quando(sc.get('quando')), perche=sc.get('perche') or '')) if not c['carta']: parole = _parole_dal_git(k) if parole is None: out.append(dentro + '- ' + F('res_parole_altrove', commit=k['hash'][:10], ramo=k.get('ramo') or '?')) else: _scrivi_parole(out, parole, dentro) if c['carta'] or not carte: _scrivi_parole(out, _richieste(c), '') for rid, perche in _parole_rotte(c['hash'], c['msg'], c['carta']): if perche == 'tolte': out.append('- ' + _dice_rotta(c['hash'], rid, perche).strip()) file = (c['carta'] or {}).get('file') or _file(c['hash']) 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 ''))) out.append('') if fatti['governo']: out += [F('res_governo'), ''] + ['- ' + _governo(g) for g in fatti['governo']] + [''] out += [F('res_come_verificare'), ''] testo = '\n'.join(out) + '\n' if dove.lower().endswith(('.html', '.htm')): conti = {'firmate': 0, 'da_firmare': 0, 'libere': 0, 'senza': 0, 'rotte': 0, 'urgenti': 0} for c in commit: st = esito(c)[0] chiave = {'firmata': 'firmate', 'unita': 'firmate', 'libera': 'libere', 'pulito': 'libere', 'urgente': 'urgenti', 'senza': 'senza', 'zona': 'senza'}.get(st, 'da_firmare') conti[chiave] += 1 testo = _html(testo, F('esito', **conti), ok) elif dove.lower().endswith('.csv'): testo = _csv(commit, fatti, ok) if dove: with open(dove, 'w', encoding='utf-8') as h: h.write(testo) print(F('res_scritto', file=dove, commit=len(commit))) else: sys.stdout.write(testo) return 0 if ok else 1 _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' def _inline_html(t: str) -> str: import html pezzi = re.split('(`[^`]+`)', t) out = [] for p in pezzi: if len(p) > 1 and p.startswith('`') and p.endswith('`'): out.append('' + html.escape(p[1:-1]) + '') else: out.append(re.sub('\\*\\*(.+?)\\*\\*', '\\1', html.escape(p))) return ''.join(out) def _html(testo: str, conto: str, catena_ok: bool) -> str: import html righe, corpo, livello, sezione = (testo.splitlines(), [], 0, False) titolo = next((r[2:] for r in righe if r.startswith('# ')), '') def chiudi_liste(fino: int=0) -> None: nonlocal livello while livello > fino: corpo.append('') livello -= 1 for i, r in enumerate(righe): if r.startswith('# '): continue if r.startswith('## '): chiudi_liste() if sezione: corpo.append('') stato = next((x for x in righe[i + 1:i + 4] if x.startswith('- ')), '') classe = 'ok' if '✅' in stato else 'urgente' if '⚡' in stato else 'no' if '❌' in stato else '' corpo.append(f'

{_inline_html(r[3:])}

') sezione = True continue m = re.match('^( *)- (.*)$', r) if m: voluto = len(m.group(1)) // 2 + 1 if voluto > livello: while livello < voluto: corpo.append('
    ') livello += 1 else: chiudi_liste(voluto) corpo.append(f'
  • {_inline_html(m.group(2))}
  • ') continue q = r.lstrip() if q == '>' or q.startswith('> '): corpo.append(f'
  • {_inline_html(q[2:])}
  • ' if livello else f'
    {_inline_html(q[2:])}
    ') continue chiudi_liste() if r.strip(): if sezione: corpo.append('
') sezione = False corpo.append(f'

{_inline_html(r)}

') chiudi_liste() if sezione: corpo.append('') return f"""\n{html.escape(titolo)}

{_inline_html(titolo)}

{_inline_html(conto)}
""" + '\n'.join(corpo) + '
\n' COLONNE_CSV = ('commit', 'committed_at', 'subject', 'status', 'author', 'agent', 'zones', 'checks', 'reviews', 'signoffs', 'signoff_devices_verified', 'urgent_by', 'urgent_at', 'urgent_reason', 'chain_verified') def _cella(x) -> str: x = '' if x is None else str(x) return "'" + x if x[:1] in ('=', '+', '-', '@', '\t', '\r') else x def _csv(commit: list, fatti: dict, catena_ok: bool) -> str: import csv import io buf = io.StringIO() w = csv.writer(buf, lineterminator='\n') w.writerow(COLONNE_CSV) for c in commit: st, _riga = esito(c) carte = [c['carta']] if c['carta'] else (c['fuori'].get('legame') or {}).get('carte') or [] autori, agenti, zone, prove, rev, firme, buone = ([], [], [], [], [], [], []) for k in carte: dalla = fatti['carte'].get(k['id']) or k autori.append(dalla['autore']) agenti.append(dalla.get('assistito') or '') zone += [z['codice'] for z in dalla.get('zone') or []] fatte = {**{x['codice']: x for x in dalla.get('controlli') or []}, **(fatti['prove'].get(k['id']) or {})} prove += [f"{p['codice']}:{(fatte[p['codice']]['uscita'] if p['codice'] in fatte else '?')}" for p in dalla.get('prove') or []] rev += [f"{r.get('persona') or '?'}:{r['esito']}" for r in fatti['revisioni'].get(k['id']) or []] for f in fatti['firme'].get(k['id']) or []: firme.append(f"{f['persona']}:{f['significato']}@{(f.get('quando') or '')[:19]}") buone.append(_dispositivo(f, k, fatti)[1]) ct = git('log', '-1', '--format=%cI', c['hash']) u = c.get('urgenza') or {} 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')]) return buf.getvalue() def esporta(a: list) -> int: d = chiedi('GET', '/api/carta/catena') dove = a[0] if a else 'delminio-signoff-' + datetime.date.today().isoformat() + '.json' with open(dove, 'w', encoding='utf-8') as h: json.dump({'anelli': d.get('anelli') or []}, h, ensure_ascii=False, indent=1) verdetto, ok = _verifica(d.get('anelli') or []) print(F('esportata', file=dove, anelli=len(d.get('anelli') or []), esito=verdetto)) return 0 if ok else 1 def catena(a: list) -> int: if not a: raise Rifiuto(F('uso', cmd=CMD)) anelli = json.load(open(a[0], encoding='utf-8')).get('anelli') or [] verdetto, ok = _verifica(anelli) print(F('esportata', file=a[0], anelli=len(anelli), esito=verdetto)) if len(a) > 1: vecchi = json.load(open(a[1], encoding='utf-8')).get('anelli') or [] per_seq = {x.get('seq'): x.get('impronta') for x in anelli} diverso = next((x.get('seq') for x in vecchi if per_seq.get(x.get('seq')) != x.get('impronta')), None) if verifica_catena(vecchi) is not None or diverso is not None: print(F('copia_diversa', file=a[1], anello=diverso if diverso is not None else verifica_catena(vecchi))) ok = False else: print(F('copia_uguale', file=a[1], anelli=len(vecchi))) return 0 if ok else 1 def _indipendente(r: dict, autore: str='') -> str: if not r.get('indipendente'): return F('stessa_sessione') if autore and r.get('persona') == autore: return F('dell_autore') return F('indipendente_stesso_modello') if r.get('stesso_modello') else F('indipendente') def revisione(a: list) -> int: if len(a) > 1: a[1] = {'clean': 'pulita', 'findings': 'rilievi'}.get(a[1], a[1]) sess = os.environ.get('DELMINIO_SESSIONE', '') if len(a) < 2 or a[1] not in ('pulita', 'rilievi'): raise Rifiuto(F('uso', cmd=CMD)) if not sess: raise Rifiuto(F('revisione_senza_sessione', cmd=CMD)) rilievi = int(a[2]) if len(a) > 2 and a[2].isdigit() else 0 voluti = git('rev-list', '--no-merges', '--reverse', a[0]).split() if '..' in a[0] else [git('rev-parse', a[0]) or a[0]] for h in voluti[-COMMIT_MAX:]: try: r = chiedi('POST', '/api/carta/revisione', {'hash': h, 'esito': a[1], 'rilievi': rilievi, 'sessione': sess}) except Rifiuto as e: print(f' {h[:10]} {e}', file=sys.stderr) continue ultima = (r.get('revisioni') or [{}])[-1] print(F('revisione_dell_autore', commit=h[:10]) if ultima.get('persona') == r.get('autore') else F('revisione_registrata', commit=h[:10])) return 0 def _stato(nome: str) -> str: return os.path.join(STATO, nome) def _richiesta(a: list) -> int: sess = a[0] if a else '' try: testo = json.load(sys.stdin).get('prompt') or '' except Exception: return 0 if not sess or not isinstance(testo, str) or (not testo.strip()): return 0 nascosto = F('nascosto') 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,}'): testo = re.sub(r, nascosto, testo) testo = re.sub('(?i)\\b(password|passwd|pwd|secret|token|api[_-]?key)(\\s*[:=]\\s*)\\S+', '\\1\\2' + nascosto, testo) testo = forma(testo) if len(testo) > MASSIMO: testo = forma(testo[:MASSIMO] + '\n' + F('troncata', n=len(testo) - MASSIMO)) voce = {'impronta': impronta(testo), 'testo': testo} try: r = chiedi('POST', '/api/carta/richiesta', {'sessione': sess, 'impronta': voce['impronta'], 'remoto': _remoto()}, attesa=3) voce.update(id=r['id'], quando=r['quando']) _segno(True) except Rifiuto as e: if e.codice == 409: return 0 if e.codice in (403, 404): _segno(False) return 0 voce['quando'] = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='seconds') except Exception: voce['quando'] = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='seconds') fd = os.open(_stato(f'carta-{sess}.jsonl'), os.O_WRONLY | os.O_CREAT | os.O_APPEND, 384) with os.fdopen(fd, 'a', encoding='utf-8') as h: h.write(json.dumps(voce, ensure_ascii=False) + '\n') return 0 def _segno(accese: bool) -> None: si, no = (_stato('carta'), _stato('carta-no')) try: open(si if accese else no, 'a').close() os.remove(no if accese else si) except OSError: pass def _voci(sess: str) -> list: voci = [] if not sess: return voci try: for riga in open(_stato(f'carta-{sess}.jsonl'), encoding='utf-8'): try: voci.append(json.loads(riga)) except ValueError: pass except OSError: pass return voci def _messaggio(a: list) -> int: file, sess, controlli_f = (a + ['', '', ''])[:3] carta = json.loads(os.environ.get('DELMINIO_DURI') or '{}').get('carta') or {} try: controlli = json.load(open(controlli_f, encoding='utf-8')) except (OSError, ValueError): controlli = [] voci = _voci(sess) blocco = [] if voci: blocco.append(F('intestazione')) for v in voci: blocco.append(f"[{v.get('id') or '-'}] {_quando(v.get('quando'))}" + ('' if v.get('id') else ' · ' + F('non_registrata'))) blocco += ['> ' + r if r else '>' for r in v['testo'].split('\n')] blocco.append('') if controlli: blocco.append(F('controlli')) blocco += [f" {c['codice']} `{c['comando']}` → {c['uscita']}" for c in controlli] blocco.append('') testo = open(file, encoding='utf-8').read() if blocco: righe = testo.rstrip('\n').split('\n') fine = len(righe) while fine > 0 and righe[fine - 1].startswith('#'): fine -= 1 inizio = fine while inizio > 0 and righe[inizio - 1].strip(): inizio -= 1 trailer = inizio > 0 and all((re.match('^[A-Za-z0-9-]+: ', r) for r in righe[inizio:fine])) punto = inizio if trailer else fine nuove = righe[:punto] + ([''] if punto and righe[punto - 1].strip() else []) + blocco + righe[punto:] with open(file, 'w', encoding='utf-8') as h: h.write('\n'.join(nuove).rstrip('\n') + '\n') aggiunti = ['Assisted-by: ' + carta['assistito']] if carta.get('assistito') else [] aggiunti += [f"Delminio-Request: {v['id']} {v['impronta']}" for v in voci if v.get('id')] testa = carta.get('catena') or {} if isinstance(testa.get('seq'), int) and re.fullmatch('[0-9a-f]{64}', str(testa.get('impronta') or '')): aggiunti.append(f"Delminio-Chain: {testa['seq']} {testa['impronta']}") gia = open(file, encoding='utf-8').read() for t in aggiunti: if t.replace('Delminio-Request:', 'Delminio-Richiesta:').replace('Delminio-Chain:', 'Delminio-Catena:') in gia.splitlines(): continue subprocess.run(['git', 'interpret-trailers', '--in-place', '--if-exists', 'addIfDifferent', '--trailer', t, file], check=False) with open(_stato(f"carta-incluse-{sess or 'mano'}.json"), 'w', encoding='utf-8') as h: json.dump({'impronte': [v['impronta'] for v in voci], 'richieste': [v['id'] for v in voci if v.get('id')], 'controlli': controlli}, h) zone = carta.get('zone') or [] if zone: print(F('zona', zone=', '.join((f"{z['codice']} «{z['cosa']}»" for z in zone))), file=sys.stderr) return 0 def _commit(a: list) -> int: sess = a[0] if a else '' incl = _stato(f"carta-incluse-{sess or 'mano'}.json") try: d = json.load(open(incl, encoding='utf-8')) except (OSError, ValueError): return 0 try: os.remove(incl) except OSError: pass file = [f for f in git('show', '--name-only', '--format=', '-z', 'HEAD').split('\x00') if f.strip()] controlli = list(d.get('controlli') or []) fatte = _gira_prove(git('rev-parse', 'HEAD'), file) if fatte: gia = {x['codice'] for x in fatte} controlli = [x for x in controlli if x.get('codice') not in gia] + fatte dette = list(_parole_nel_messaggio(git('log', '-1', '--format=%B', 'HEAD'))[0]) richieste = list(dict.fromkeys([str(x) for x in d.get('richieste') or []] + dette)) print(json.dumps({'file': file[:400], 'richieste': [int(x) for x in richieste if x.isdigit()], 'controlli': controlli})) scritte = set(d.get('impronte') or []) if scritte and sess: p = _stato(f'carta-{sess}.jsonl') try: resta = [r for r in open(p, encoding='utf-8') if json.loads(r).get('impronta') not in scritte] with open(p, 'w', encoding='utf-8') as h: h.writelines(resta) except (OSError, ValueError): pass return 0 def _segni(a: list) -> int: h = git('rev-parse', a[0] if a else 'HEAD') if not h: return 0 sg = segni(h) nome = git('rev-parse', '--abbrev-ref', 'HEAD') print(json.dumps({'albero': sg['albero'], 'patch': sg['patch'], 'ramo': _ramo(h, '' if nome == 'HEAD' else nome)})) return 0 def _prove_chieste(h: str, file: list) -> list: if not file or not URL or (not TOKEN): return [] try: r = chiedi('POST', '/api/lock/commit', {'staged': file, 'sessione': '', 'remoto': os.environ.get('DELMINIO_REMOTO') or _remoto()}, attesa=8) except Rifiuto: return [] return (r.get('carta') or {}).get('prove') or [] def _gira_prove(h: str, file: list) -> list | None: prove = _prove_chieste(h, file) if not prove: return [] 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) if not uguale: print(F('prove_albero_diverso', zone=', '.join((p['codice'] for p in prove)), commit=h[:10]), file=sys.stderr) return None try: accettate = set(open(os.environ.get('DELMINIO_ACCETTATE') or git('rev-parse', '--git-path', 'delminio-guardie-accettate'), encoding='utf-8').read().split()) except OSError: accettate = set() radice = git('rev-parse', '--show-toplevel') or '.' fatte = [] for p in prove: if hashlib.sha256((p['codice'] + '\x00' + p['comando']).encode()).hexdigest() not in accettate: print(F('prova_non_accettata', codice=p['codice'], comando=p['comando']), file=sys.stderr) continue try: e = subprocess.run(p['comando'], shell=True, cwd=radice, capture_output=True, text=True, timeout=PROVE_TEMPO) rc, uscita = (e.returncode, (e.stdout or '') + (e.stderr or '')) except subprocess.TimeoutExpired: rc, uscita = (124, '') fatte.append({'codice': p['codice'], 'comando': p['comando'], 'uscita': rc}) if rc == 0: print(F('prova_passata', codice=p['codice']), file=sys.stderr) else: print(F('prova_fallita', codice=p['codice'], comando=p['comando'], uscita=rc), file=sys.stderr) for riga in uscita.strip().splitlines()[-15:]: print(' ' + riga, file=sys.stderr) return fatte def prove(a: list) -> int: h = git('rev-parse', 'HEAD') if a and git('rev-parse', a[0]) != h: print(F('prove_solo_testa')) return 2 fatte = _gira_prove(h, _file(h)) if fatte is None: return 1 if not fatte: print(F('prove_nessuna', commit=h[:10])) return 0 chiedi('POST', '/api/carta/prove', {'hash': h, 'controlli': fatte}) esito = ', '.join((f"{x['codice']} → {x['uscita']}" for x in fatte)) print(F('prove_registrate', commit=h[:10], esito=esito)) return 0 if all((x['uscita'] == 0 for x in fatte)) else 1 def _riscritti(a: list) -> int: coppie = [r.split()[:2] for r in sys.stdin.read().splitlines() if len(r.split()) >= 2 and r.split()[0] != r.split()[1]] sg = {} if a and a[0] == 'segni': for _vecchio, nuovo in coppie: s = segni(nuovo) sg[nuovo] = {'albero': s['albero'], 'patch': s['patch'], 'ramo': _ramo(nuovo)} print(json.dumps({'vecchi': [v for v, _ in coppie], 'coppie': coppie, 'segni': sg})) return 0 _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' _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' def _servizio(a: list) -> str: if a and a[0] in ('github', 'forgejo', 'gitea', 'gitlab'): return 'forgejo' if a[0] == 'gitea' else a[0] host = re.sub('^[a-z][a-z0-9+.-]*://', '', _remoto().lower()).split('@')[-1].split('/')[0].split(':')[0] if host == 'github.com' or host.endswith('.github.com'): return 'github' if 'gitlab' in host: return 'gitlab' if os.path.isdir('.forgejo') or os.path.isdir('.gitea'): return 'forgejo' return '' def _da_fuori(url: str) -> bool: import ipaddress import urllib.parse host = (urllib.parse.urlparse(url).hostname or '').lower() if not host or host == 'localhost' or '.' not in host or host.endswith(('.local', '.lan', '.home.arpa', '.internal')): return False try: ip = ipaddress.ip_address(host) return not (ip.is_private or ip.is_loopback or ip.is_link_local) except ValueError: return True def ci(a: list) -> int: servizio = _servizio(a) if not servizio: print(F('ci_quale')) return 2 url = os.environ.get('DELMINIO_URL', '').rstrip('/') radice = git('rev-parse', '--show-toplevel') or '.' repo = json.dumps(_remoto()) ramo = (git('symbolic-ref', '--short', 'refs/remotes/origin/HEAD') or 'origin/main').split('/', 1)[-1] if not _da_fuori(url): print(F('ci_dentro_casa', url=url)) if servizio == 'gitlab': print(F('ci_gitlab', file='.gitlab-ci.yml')) print(_CI_GITLAB.format(url=url, repo=repo)) print(F('ci_gitlab_passi')) return 0 cartella = '.github' if servizio == 'github' else '.forgejo' file = os.path.join(cartella, 'workflows', 'delminio-firme.yml') testo = _CI_GITHUB.format(commento=F('ci_commento'), ramo=ramo, url=url, repo=repo, macchina='ubuntu-latest' if servizio == 'github' else 'docker') dove = os.path.join(radice, file) if os.path.exists(dove): if open(dove, encoding='utf-8').read() == testo: print(F('ci_gia_pronto', file=file)) else: print(F('ci_esiste_diverso', file=file)) else: os.makedirs(os.path.dirname(dove), exist_ok=True) with open(dove, 'w', encoding='utf-8') as f: f.write(testo) print(F('ci_scritto', file=file)) if servizio == 'github': return _github(ramo) print(F('ci_passi_forgejo', ramo=ramo)) return 0 _CONTROLLO = 'controlla' def _gh(*a: str, entrata: str | None=None) -> tuple[int, str]: try: r = subprocess.run(['gh', *a], capture_output=True, text=True, input=entrata, timeout=60) except (OSError, subprocess.TimeoutExpired) as e: return (1, str(e)) return (r.returncode, (r.stdout if r.returncode == 0 else r.stderr or r.stdout).strip()) def _gh_errore(out: str) -> str: righe = [r for r in out.splitlines() if r.strip()] return righe[-1][:300] if righe else '?' def _github(ramo: str) -> int: if not shutil.which('gh'): print(F('ci_gh_manca')) print(F('ci_passi_github', ramo=ramo)) return 0 if _gh('auth', 'status')[0] != 0: print(F('ci_gh_non_collegato')) print(F('ci_passi_github', ramo=ramo)) return 0 rc, out = _gh('repo', 'view', '--json', 'nameWithOwner,viewerPermission') try: r = json.loads(out) if rc == 0 else {} except ValueError: r = {} nwo = r.get('nameWithOwner') or '' if not nwo: print(F('ci_gh_quale_repo', errore=_gh_errore(out))) print(F('ci_passi_github', ramo=ramo)) return 0 if r.get('viewerPermission') != 'ADMIN': print(F('ci_gh_permessi', repo=nwo)) print(F('ci_passi_github', ramo=ramo)) return 0 regola = _gh_regola(nwo, ramo) segreto = _gh_segreto(nwo) return 0 if regola and segreto else 1 def _gh_regola(nwo: str, ramo: str) -> bool: base = f'repos/{nwo}/branches/{ramo}/protection' rc, out = _gh('api', base) if rc != 0 and 'HTTP 404' not in out: 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))) return False if rc != 0: corpo = {'required_status_checks': {'strict': False, 'contexts': [_CONTROLLO]}, 'enforce_admins': True, 'required_pull_request_reviews': None, 'restrictions': None} rc, out = _gh('api', '-X', 'PUT', base, '--input', '-', entrata=json.dumps(corpo)) if rc != 0: 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))) return False else: d = json.loads(out) rsc = d.get('required_status_checks') or {} if _CONTROLLO not in _gh_controlli(rsc): print(F('ci_gh_regole_altre', ramo=ramo)) 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]})) if rc != 0: print(F('ci_gh_regola_no', ramo=ramo, errore=_gh_errore(out))) return False if not (d.get('enforce_admins') or {}).get('enabled'): rc, out = _gh('api', '-X', 'POST', base + '/enforce_admins') if rc != 0: print(F('ci_gh_regola_no', ramo=ramo, errore=_gh_errore(out))) return False rc, out = _gh('api', base) d = json.loads(out) if rc == 0 else {} if _CONTROLLO in _gh_controlli(d.get('required_status_checks') or {}) and (d.get('enforce_admins') or {}).get('enabled'): print(F('ci_gh_regola_ok', ramo=ramo, repo=nwo)) return True print(F('ci_gh_regola_no', ramo=ramo, errore=_gh_errore(out) if rc else '?')) return False def _gh_controlli(rsc: dict) -> set: return set(rsc.get('contexts') or []) | {c.get('context') for c in rsc.get('checks') or [] if isinstance(c, dict)} def _gh_segreto(nwo: str) -> bool: rc, out = _gh('secret', 'list', '--repo', nwo, '--json', 'name') try: nomi = {x.get('name') for x in json.loads(out)} if rc == 0 else set() except ValueError: nomi = set() if rc != 0: print(F('ci_gh_segreto_no', errore=_gh_errore(out))) return False if 'DELMINIO_FIRME' in nomi: print(F('ci_gh_segreto_c_e', repo=nwo)) return True imposta = ['gh', 'secret', 'set', 'DELMINIO_FIRME', '--repo', nwo] cmd = ' '.join(imposta) if not (sys.stdin.isatty() and sys.stdout.isatty()): print(F('ci_gh_segreto_tu', cmd=cmd)) return False print(F('ci_gh_segreto_incolla')) esito = subprocess.run(imposta).returncode if esito != 0: print(F('ci_gh_segreto_no', errore=esito)) return False print(F('ci_gh_segreto_fatto', repo=nwo)) return True VERBI = {'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} def main(argv: list) -> int: verbo = argv[0] if argv else 'controlla' verbo = COMANDI['carta'].get(verbo, verbo) fai = VERBI.get(verbo) if fai is None: print(F('uso', cmd=CMD), file=sys.stderr if verbo not in ('-h', '--help') else sys.stdout) return 0 if verbo in ('-h', '--help') else 2 try: return fai(argv[1:]) except SenzaFirme as e: if e.sconosciuto: print(F('repo_sconosciuto', remoto=_remoto()), file=sys.stderr) return 2 print(F('repo_senza_firme')) return 0 except Rifiuto as e: if verbo.startswith('_'): return 0 print(str(e), file=sys.stderr) return 2 if __name__ == '__main__': sys.exit(main(sys.argv[1:]))