write_signed_twice.py

Die Python-Datei des Beispiels „Zwei Signaturen, einer empfangenen Datei hinzugefügt“. Eine fertige Datei ohne Formular und ohne Unterschriftsstelle erhält zwei und wird dann zweimal signiert. Jeder Schritt wird hinter dem letzten Byte der Datei angefügt, sodass die erste Signatur weiterhin genau abdeckt, was sie abgedeckt hat, und OpenSSL prüft beide ohne diese Bibliothek.

Python 610 Zeilen

Wofür dieses Beispiel da ist

Ein Vertrag kommt oft als fertige Datei an, die jemand anderes geschrieben hat, ohne Platz zum Unterschreiben. Zwei Personen müssen ihn trotzdem unterschreiben — eine genehmigt, eine prüft —, und die zweite Signatur darf die erste nicht brechen. Die Datei neu zu schreiben würde genau das tun: Eine Signatur wird aus den Bytes der Datei berechnet, und ein einziges verschobenes Byte bricht sie.

Was dieses Beispiel zeigt

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
"""Takes a finished file with no form and no place to sign, and signs it twice.

The Python twin of the `write_signed_twice` example in Rust: the same document, through
the binding rather than through the library directly. Two places to sign are added to
the file, and signed one after the other, each signature leaving the one before it
covering what it covered.

Five files, each the whole of the one before it followed by a section appended after
its last byte:

1. the file received: one page, written on its own, with no form;
2. the same file with the two framed signature fields APPROVAL and REVIEW added under
   the word its page sets over each, one section each, through
   `IncrementalUpdate.to_bytes_with_signature_field`;
3. that file with APPROVAL signed, through `IncrementalUpdate.to_signed_bytes`;
4. that file with REVIEW signed the same way, read afresh;
5. that file with the demonstration certificate kept in its document security store,
   filed under both signatures, through `IncrementalUpdate.to_bytes_with_store`, so
   that both stay checkable once the certificate has expired.

The approval certifies the document, allowing forms to be filled in and the fields left
empty to be signed after it, and states where it was made and how to reach its signer;
the review is an ordinary signature in the older PKCS #7 form. What each states of
itself is printed as it is made.

Both signatures are made with the demonstration signer `_signer.py` hands to `openssl`.
The approval covers the third file whole but for the room its own structure sits in,
and nothing of the section the review appends; the review covers the fourth. A
signature made with an RSA key is the same bytes every time it is made over the same
bytes, so the example writes the same file on every run.

The page is written in the language `HQF_PDF_LANG` names. The command, the signer's name
and the moments of signing are not.

Usage: python examples/write_signed_twice.py [out.pdf] [font.ttf]
       HQF_PDF_LANG=fr python examples/write_signed_twice.py
"""

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out
import _signer
from _signer import CHECK_COMMAND, SIGNER

import hqf_pdf

# The name of the field signed first.
APPROVAL = "approval"

# The name of the field signed second.
REVIEW = "review"

# When the approval is signed, as its signature states it.
APPROVED_AT = "2026-09-14T09:00:00+00:00"

# When the review is signed, as its signature states it.
REVIEWED_AT = "2026-09-15T14:30:00+00:00"

# When the validation data of both signatures is kept, as each entry of the security
# store states it.
KEPT_AT = "2026-09-16T08:00:00+00:00"

# The page the two fields are added to, counting from zero: the file's only one.
PAGE = 0

# How far in from the left edge of the sheet every line is set, in points.
LEFT = 72.0

# Where the baseline of the heading sits, in points up from the foot of the sheet.
HEADING_BASELINE = 770.0

# The size the heading is set at, in points.
HEADING_SIZE = 18.0

# The size the body and the text over the command are set at, in points.
BODY_SIZE = 10.5

# The size the section heading is set at, in points.
SECTION_SIZE = 13.0

# The size the command is set at, in points.
COMMAND_SIZE = 8.5

# The size the word over each box is set at, in points.
LABEL_SIZE = 9.0

# How far the baseline of the word over a box sits above the box's top, in points.
LABEL_RISE = 6.0

# The two boxes, side by side under the body, each with its field's name: the lower-left
# corner, the width and the height, in points.
BOXES = (
    (APPROVAL, LEFT, 528.0, 200.0, 44.0),
    (REVIEW, 323.0, 528.0, 200.0, 44.0),
)

# How far the section heading sits below the last line of the body, the boxes standing
# between the two, in points.
PAST_THE_BOXES = 110.0

# The grey of the frame around each box, and its width in points.
BORDER = hqf_pdf.Rgb.gray(0.55)
BORDER_WIDTH = 0.75

# What a line of the page is, which sets its size and how far it sits below the line
# before it.
HEADING = "heading"
BODY = "body"
PARAGRAPH = "paragraph"
SECTION = "section"
STEP = "step"
STEP_CARRIED_ON = "step carried on"
COMMAND = "command"


@dataclass(frozen=True)
class Words:
    """Every word the page is written in, in one language.

    The command, the signer's name and the moments of signing are not among them.
    """

    # What the document is called, at the head of the page and in what the file says of
    # itself.
    title: str
    # Where the file came from, and what was added to it.
    received: tuple[str, ...]
    # What the demonstration key proves, and what it does not.
    proves: tuple[str, ...]
    # How the two signatures went in, and what each covers.
    added: tuple[str, ...]
    # The word over the box signed first.
    approval_label: str
    # The word over the box signed second.
    review_label: str
    # Why the approval was signed, as its signature states it.
    approval_reason: str
    # Why the review was signed, as its signature states it.
    review_reason: str
    # What stands over the way to check the file.
    check_heading: str
    # What to hand the check.
    check: tuple[str, ...]
    # What the last section keeps for checking the signatures later.
    kept: tuple[str, ...]


# The page in English.
ENGLISH = Words(
    title="A file received, then signed twice",
    received=(
        "This page stands for a file somebody else sent. It was written first,",
        "on its own, with no form and no place to sign; the two framed boxes below",
        "were added to it afterwards, and not one of its bytes has moved.",
    ),
    proves=(
        "Both signatures are made with the demonstration key committed in keys/:",
        "they prove the bytes unchanged, and nothing about who signed them.",
    ),
    added=(
        "Each box went in as a section appended after the file's last byte. Then",
        "the approval was signed, and the review after it, each in a section of",
        "its own again. The review covers the whole file; the approval still covers",
        "exactly the bytes it covered when it was made, and still verifies.",
    ),
    approval_label="Approval",
    review_label="Review",
    approval_reason="Approves the file received",
    review_reason="Reviews the approved file",
    check_heading="Checking both without this library",
    check=(
        "The file holds one /ByteRange per signature. For each, join its two runs",
        "into covered.bin, decode the structure between them into signature.der,",
        "and run:",
    ),
    kept=(
        "Last, a fifth section keeps the demonstration certificate in the file's",
        "security store, filed under both signatures, so both stay checkable later.",
    ),
)

# The page in French.
FRENCH = Words(
    title="Un fichier reçu, puis signé deux fois",
    received=(
        "Cette page tient lieu d’un fichier envoyé par quelqu’un d’autre. Il a",
        "d’abord été écrit seul, sans formulaire ni place pour signer ; les deux",
        "cadres ci-dessous y ont été ajoutés ensuite, sans déplacer un seul octet.",
    ),
    proves=(
        ("Les deux signatures sont faites avec la clé de démonstration du dossier "
         "keys/ :"),
        "elles prouvent que les octets n’ont pas changé, et rien sur le signataire.",
    ),
    added=(
        "Chaque cadre est entré dans une section ajoutée après le dernier octet.",
        "Puis l’approbation a été signée, et la relecture après elle, chacune dans",
        ("sa propre section, elle aussi. La relecture couvre tout le fichier ; "
         "l’approbation"),
        "couvre exactement les octets couverts à sa création, et se vérifie toujours.",
    ),
    approval_label="Approbation",
    review_label="Relecture",
    approval_reason="Approuve le fichier reçu",
    review_reason="Relit le fichier approuvé",
    check_heading="Les vérifier toutes deux sans cette bibliothèque",
    check=(
        "Le fichier contient un /ByteRange par signature. Pour chacun, concaténez ses",
        "deux plages dans covered.bin, décodez la structure entre elles dans",
        "signature.der, puis lancez :",
    ),
    kept=(
        "Enfin, une cinquième section conserve le certificat de démonstration, pour les deux",
        "signatures, dans le magasin de sécurité du fichier : elles resteront vérifiables.",
    ),
)

# The page in Dutch.
DUTCH = Words(
    title="Een ontvangen bestand, tweemaal ondertekend",
    received=(
        "Deze pagina staat voor een bestand van iemand anders. Het is eerst geschreven, op",
        "zichzelf, zonder formulier of tekenplek; de twee omkaderde vakken hieronder",
        "zijn er later aan toegevoegd, en geen enkele byte ervan is verschoven.",
    ),
    proves=(
        "Beide handtekeningen zijn gemaakt met de demonstratiesleutel in keys/:",
        "ze bewijzen dat de bytes niet veranderd zijn, en niets over wie tekende.",
    ),
    added=(
        "Elk vak kwam erin als een sectie na de laatste byte van het bestand. Daarna",
        "werd de goedkeuring ondertekend, en de beoordeling erna, elk weer in een eigen",
        "sectie. De beoordeling dekt het hele bestand; de goedkeuring dekt nog steeds",
        "precies de bytes die ze dekte toen ze gezet werd, en klopt nog steeds.",
    ),
    approval_label="Goedkeuring",
    review_label="Beoordeling",
    approval_reason="Keurt het ontvangen bestand goed",
    review_reason="Beoordeelt het goedgekeurde bestand",
    check_heading="Beide controleren zonder deze bibliotheek",
    check=(
        "Per handtekening is er één /ByteRange. Voeg voor elk de twee reeksen samen",
        "tot covered.bin, decodeer de structuur ertussen naar signature.der,",
        "en voer uit:",
    ),
    kept=(
        "Ten slotte bewaart een vijfde sectie het demonstratiecertificaat in de",
        "beveiligingsopslag, zodat beide handtekeningen later te controleren blijven.",
    ),
)

# The page in Portuguese.
PORTUGUESE = Words(
    title="Um ficheiro recebido, depois assinado duas vezes",
    received=(
        "Esta página faz as vezes de um ficheiro que alguém enviou. Foi escrito primeiro,",
        "sozinho, sem formulário nem lugar para assinar; as duas caixas emolduradas abaixo",
        "foram-lhe acrescentadas depois, e nem um dos seus bytes se mexeu.",
    ),
    proves=(
        "As duas assinaturas são feitas com a chave de demonstração guardada em keys/:",
        "provam que os bytes não mudaram, e nada sobre quem os assinou.",
    ),
    added=(
        "Cada caixa entrou numa secção acrescentada após o último byte do ficheiro. Depois",
        "foi assinada a aprovação, e a revisão a seguir, cada uma de novo numa secção",
        "própria. A revisão cobre o ficheiro inteiro; a aprovação continua a cobrir",
        "exatamente os bytes que cobria quando foi feita, e continua a verificar-se.",
    ),
    approval_label="Aprovação",
    review_label="Revisão",
    approval_reason="Aprova o ficheiro recebido",
    review_reason="Revê o ficheiro aprovado",
    check_heading="Verificar as duas sem esta biblioteca",
    check=(
        "O ficheiro tem um /ByteRange por assinatura. Para cada uma, junte os dois troços",
        "em covered.bin, descodifique a estrutura entre eles em signature.der,",
        "e execute:",
    ),
    kept=(
        "Por fim, uma quinta secção guarda o certificado de demonstração no",
        "arquivo de segurança, para as duas assinaturas continuarem verificáveis.",
    ),
)

# The page in Italian.
ITALIAN = Words(
    title="Un file ricevuto, poi firmato due volte",
    received=(
        "Questa pagina rappresenta un file inviato da qualcun altro. È stato scritto prima,",
        "da solo, senza modulo né posto per firmare; i due riquadri incorniciati qui sotto",
        "gli sono stati aggiunti dopo, e nemmeno uno dei suoi byte si è mosso.",
    ),
    proves=(
        "Entrambe le firme sono fatte con la chiave di dimostrazione registrata in keys/:",
        "provano che i byte non sono cambiati, e nulla su chi li ha firmati.",
    ),
    added=(
        "Ogni riquadro è entrato come una sezione aggiunta dopo l’ultimo byte del file. Poi",
        "è stata firmata l’approvazione, poi la revisione, ciascuna di nuovo in una sezione",
        "propria. La revisione copre l’intero file; l’approvazione copre ancora",
        "esattamente i byte che copriva quando è stata fatta, e si verifica ancora.",
    ),
    approval_label="Approvazione",
    review_label="Revisione",
    approval_reason="Approva il file ricevuto",
    review_reason="Rivede il file approvato",
    check_heading="Verificarle entrambe senza questa libreria",
    check=(
        "Il file ha un /ByteRange per firma. Per ciascuna, unite i suoi due tratti",
        "in covered.bin, decodificate la struttura tra di essi in signature.der,",
        "ed eseguite:",
    ),
    kept=(
        "Infine, una quinta sezione conserva il certificato di dimostrazione",
        "nell’archivio di sicurezza, perché entrambe le firme restino verificabili.",
    ),
)

# The page in Spanish.
SPANISH = Words(
    title="Un archivo recibido, y luego firmado dos veces",
    received=(
        "Esta página representa un archivo que envió otra persona. Se escribió primero,",
        "solo, sin formulario ni lugar para firmar; las dos cajas enmarcadas de abajo",
        "se le añadieron después, y ni uno de sus bytes se ha movido.",
    ),
    proves=(
        "Las dos firmas se hacen con la clave de demostración guardada en keys/:",
        "prueban que los bytes no cambiaron, y no prueban nada de quién las firmó.",
    ),
    added=(
        "Cada caja entró como una sección añadida tras el último byte del archivo. Luego",
        "se firmó la aprobación, y la revisión después, cada una otra vez en una sección",
        "propia. La revisión cubre el archivo entero; la aprobación sigue cubriendo",
        "exactamente los bytes que cubría al hacerse, y sigue verificándose.",
    ),
    approval_label="Aprobación",
    review_label="Revisión",
    approval_reason="Aprueba el archivo recibido",
    review_reason="Revisa el archivo aprobado",
    check_heading="Comprobar las dos sin esta biblioteca",
    check=(
        "El archivo tiene un /ByteRange por firma. Para cada una, concatene sus dos tramos",
        "en covered.bin, decodifique la estructura entre ellos en signature.der,",
        "y ejecute:",
    ),
    kept=(
        "Por último, una quinta sección guarda el certificado de demostración en",
        "el almacén de seguridad, para que ambas firmas sigan siendo verificables.",
    ),
)

# The page in German.
GERMAN = Words(
    title="Eine erhaltene Datei, dann zweimal signiert",
    received=(
        "Diese Seite steht für eine Datei, die jemand anderes schickte. Sie entstand zuerst",
        "für sich, ohne Formular und ohne Unterschriftsfeld; die beiden Kästen unten kamen",
        "danach hinzu, und kein einziges ihrer Bytes hat sich verändert.",
    ),
    proves=(
        "Beide Signaturen stammen vom Vorführschlüssel aus keys/: Sie beweisen,",
        "dass die Bytes unverändert sind, und nichts über die Unterzeichner.",
    ),
    added=(
        "Jeder Kasten kam als Abschnitt hinter das letzte Byte der Datei. Dann",
        "wurde die Freigabe signiert, danach die Prüfung, jede wieder in einem",
        "eigenen Abschnitt. Die Prüfung deckt die ganze Datei ab; die Freigabe deckt noch",
        "genau die Bytes von damals und lässt sich weiterhin verifizieren.",
    ),
    approval_label="Freigabe",
    review_label="Prüfung",
    approval_reason="Gibt die erhaltene Datei frei",
    review_reason="Prüft die freigegebene Datei",
    check_heading="Beide ohne diese Bibliothek prüfen",
    check=(
        "Die Datei enthält je Signatur ein /ByteRange. Für jede die zwei Folgen",
        "zu covered.bin zusammenfügen, die Struktur dazwischen zu signature.der",
        "dekodieren und ausführen:",
    ),
    kept=(
        "Zuletzt legt ein fünfter Abschnitt das Vorführzertifikat im",
        "Sicherheitsspeicher der Datei ab, damit beide Signaturen prüfbar bleiben.",
    ),
)

# Every language the example is written in. A language is added by writing its own set
# of words and naming it here.
WORDS = {_language.ENGLISH: ENGLISH, _language.FRENCH: FRENCH, _language.GERMAN: GERMAN, _language.SPANISH: SPANISH, _language.ITALIAN: ITALIAN, _language.PORTUGUESE: PORTUGUESE, _language.DUTCH: DUTCH}


def size_of(kind: str) -> float:
    """The size a line of `kind` is set at, in points."""
    if kind == HEADING:
        return HEADING_SIZE
    if kind == SECTION:
        return SECTION_SIZE
    if kind == COMMAND:
        return COMMAND_SIZE
    return BODY_SIZE


def drop_after(kind: str, before: str) -> float:
    """How far a line of `kind` sits below the line before it, of kind `before`."""
    if before == HEADING:
        return 32.0
    if before == BODY and kind == SECTION:
        return PAST_THE_BOXES
    if kind == PARAGRAPH or before == SECTION:
        return 22.0
    if before == COMMAND and kind == COMMAND:
        return 12.0
    if kind == COMMAND:
        return 14.0
    return 15.0


def block(lines: tuple[str, ...], first: str, rest: str) -> list[tuple[str, str]]:
    """The lines of one block, the first of kind `first` and the others of kind `rest`."""
    return [(line, first if index == 0 else rest) for index, line in enumerate(lines)]


def lines(words: Words) -> list[tuple[str, str]]:
    """Every line the page draws down its left margin, in order, with its kind."""
    return [
        (words.title, HEADING),
        *block(words.received, BODY, BODY),
        *block(words.proves, PARAGRAPH, BODY),
        *block(words.added, PARAGRAPH, BODY),
        (words.check_heading, SECTION),
        *block(words.check, STEP, STEP_CARRIED_ON),
        *block(CHECK_COMMAND, COMMAND, COMMAND),
        *block(words.kept, PARAGRAPH, BODY),
    ]


def drawing(words: Words) -> list[tuple[str, float, float]]:
    """Every line the page draws down its left margin, in the order they are drawn.

    Each is what it says, the size it is set at, and where its baseline sits in points
    up from the foot of the sheet.
    """
    drawn = []
    baseline = HEADING_BASELINE
    before = None
    for line, kind in lines(words):
        if before is not None:
            baseline -= drop_after(kind, before)
        drawn.append((line, size_of(kind), baseline))
        before = kind
    return drawn


def labels(words: Words) -> list[tuple[str, float, float]]:
    """The word over each box, in the order of BOXES, and where its baseline starts."""
    (_, ax, ay, _, ah), (_, rx, ry, _, rh) = BOXES
    return [
        (words.approval_label, ax, ay + ah + LABEL_RISE),
        (words.review_label, rx, ry + rh + LABEL_RISE),
    ]


def received(words: Words, face: Path) -> bytes:
    """The file received: one page, no form, no place to sign."""
    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    document.set_info("Title", words.title)
    handle = document.add_font(hqf_pdf.Font.from_path(face))

    content = hqf_pdf.Content()
    for line, size, baseline in drawing(words):
        content.draw_text(handle, size, LEFT, baseline, line)
    for line, x, baseline in labels(words):
        content.draw_text(handle, LABEL_SIZE, x, baseline, line)
    page = hqf_pdf.Page.a4()
    page.set_content(content)
    document.add_page(page)
    return document.to_bytes()


def update(pdf: bytes) -> hqf_pdf.IncrementalUpdate:
    """An update over `pdf`, under the examples' licence."""
    result = hqf_pdf.IncrementalUpdate(pdf)
    result.set_license(_licence.licensed())
    return result


def placed(pdf: bytes) -> bytes:
    """The file with a framed, empty signature field over each box, one section each."""
    for name, x, y, width, height in BOXES:
        field = hqf_pdf.SignatureField(
            name, x, y, width, height, border_color=BORDER, border_width=BORDER_WIDTH
        )
        pdf = update(pdf).to_bytes_with_signature_field(PAGE, field)
    return pdf


# Where the approval says it was signed.
LOCATION = "Paris"

# How the approval says its signer is reached.
CONTACT = "contact@hqf-pdf.com"


def signature(
    field: str,
    reason: str,
    at: str,
    sub_filter: hqf_pdf.SubFilter = hqf_pdf.SubFilter.EtsiCadesDetached,
    **stated,
) -> hqf_pdf.Signature:
    """What a signature states about itself: the field it fills, why, and when, and
    whatever else `stated` names."""
    return hqf_pdf.Signature(
        field,
        name=SIGNER,
        reason=reason,
        signed_at=at,
        sub_filter=sub_filter,
        **stated,
    )


def allowed(certification) -> str:
    """What `certification` allows after it, as the terminal says it."""
    if certification is None:
        return "an ordinary signature, certifying nothing"
    if certification == hqf_pdf.Certification.NoChanges:
        return "certifies the document, allowing no change"
    if certification == hqf_pdf.Certification.FormFilling:
        return "certifies the document, allowing forms filled in and empty fields signed"
    if certification == hqf_pdf.Certification.Annotating:
        return "certifies the document, allowing forms, signatures and annotations"
    return "certifies the document"


def approved(pdf: bytes, words: Words) -> bytes:
    """The file with the approval signed: a certifying signature that allows the review
    to be signed after it, and says where it was made and how to reach its signer."""
    signed = signature(
        APPROVAL,
        words.approval_reason,
        APPROVED_AT,
        location=LOCATION,
        contact=CONTACT,
        certifies=hqf_pdf.Certification.FormFilling,
    )
    print(f"{signed.field}: {allowed(signed.certification)}")
    return update(pdf).to_signed_bytes(signed, _signer.demonstration())


def reviewed(pdf: bytes, words: Words) -> bytes:
    """The approved file with the review signed, in the older PKCS #7 form."""
    signed = signature(
        REVIEW,
        words.review_reason,
        REVIEWED_AT,
        sub_filter=hqf_pdf.SubFilter.AdbePkcs7Detached,
    )
    print(f"{signed.field}: {allowed(signed.certification)}")
    return update(pdf).to_signed_bytes(signed, _signer.demonstration())


def kept(pdf: bytes) -> bytes:
    """The reviewed file with the demonstration certificate kept in its document
    security store, filed under each of the two signatures."""
    certificate = _signer.run(_signer.CERTIFICATE_COMMAND, b"")
    store = hqf_pdf.SecurityStore(
        certificates=[certificate],
        signatures=[
            hqf_pdf.SignatureValidation(field, certificates=[certificate], created_at=KEPT_AT)
            for field in (APPROVAL, REVIEW)
        ],
    )
    print(
        f"security store: {len(store.certificates)} certificate, "
        f"filed under {len(store.signatures)} signatures"
    )
    return update(pdf).to_bytes_with_store(store)


def signed_twice(words: Words, face: Path) -> bytes:
    """The file received, its two places added, both signed in turn, and the
    certificate they were signed with kept in it."""
    return kept(reviewed(approved(placed(received(words, face)), words), words))


def main() -> None:
    language = _language.from_environment()
    words = _language.words_of(WORDS, language)

    # A named file is written as named; the default one carries the language, so the two
    # languages do not overwrite each other in `tmp/`.
    name = Path(_language.file_name("signed_twice.pdf", language)).stem
    out = Path(_out.output_path(name))

    pdf = signed_twice(words, _out.font_path())
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_bytes(pdf)
    print(f"wrote {out} ({len(pdf)} bytes)")


if __name__ == "__main__":
    main()