Compare commits

...

3 Commits

Author SHA1 Message Date
Sosthene
6cbce160f3 Fix pdf generation and parsing 2025-07-03 18:01:33 +02:00
Sosthene
2270051f1c Add merkle proof validation message bus 2025-07-03 18:01:02 +02:00
Sosthene
81b715a730 Add document verification page 2025-07-03 18:00:18 +02:00
10 changed files with 597 additions and 441 deletions

View File

@ -0,0 +1,171 @@
@import "@Themes/constants.scss";
.root {
display: flex;
flex-direction: column;
gap: var(--spacing-2xl, 40px);
max-width: 800px;
margin: 0 auto;
padding: var(--spacing-xl, 32px);
.header {
display: flex;
flex-direction: column;
gap: var(--spacing-md, 16px);
text-align: center;
}
.content {
display: flex;
flex-direction: column;
gap: var(--spacing-2xl, 40px);
.drag-drop-container {
display: flex;
flex-direction: column;
gap: var(--spacing-xl, 32px);
@media (min-width: $screen-m) {
flex-direction: row;
gap: var(--spacing-lg, 24px);
}
.drag-drop-box {
flex: 1;
min-height: 200px;
display: flex;
flex-direction: column;
gap: var(--spacing-sm, 8px);
// Force the DragAndDrop component to take full width and height
> div {
width: 100% !important;
height: 100% !important;
min-height: 200px !important;
display: flex !important;
flex-direction: column !important;
// Override the fit-content width from DragAndDrop
&.root {
width: 100% !important;
height: 100% !important;
min-height: 200px !important;
}
}
.file-info {
padding: var(--spacing-sm, 8px) var(--spacing-md, 16px);
background-color: var(--color-success-50, #f0f9ff);
border: 1px solid var(--color-success-200, #bae6fd);
border-radius: var(--radius-md, 8px);
margin-top: var(--spacing-sm, 8px);
}
}
}
.warning {
text-align: center;
padding: var(--spacing-md, 16px);
background-color: var(--color-warning-50, #fffbeb);
border: 1px solid var(--color-warning-200, #fde68a);
border-radius: var(--radius-md, 8px);
}
.verification-result {
text-align: center;
padding: var(--spacing-lg, 24px);
border-radius: var(--radius-md, 8px);
border: 2px solid;
display: flex;
flex-direction: column;
gap: var(--spacing-md, 16px);
&.success {
background-color: var(--color-success-50, #f0fdf4);
border-color: var(--color-success-200, #bbf7d0);
}
&.error {
background-color: var(--color-error-50, #fef2f2);
border-color: var(--color-error-200, #fecaca);
}
.verification-details {
background-color: rgba(0, 0, 0, 0.05);
padding: var(--spacing-md, 16px);
border-radius: var(--radius-sm, 4px);
font-family: monospace;
white-space: pre-line;
text-align: left;
max-width: 100%;
overflow-x: auto;
}
.merkle-proof-section {
display: flex;
flex-direction: column;
align-items: center;
gap: var(--spacing-md, 16px);
padding: var(--spacing-lg, 24px);
background-color: rgba(0, 0, 0, 0.02);
border-radius: var(--radius-md, 8px);
border: 1px solid rgba(0, 0, 0, 0.1);
}
}
.qr-container {
display: flex;
flex-direction: column;
align-items: center;
gap: var(--spacing-sm, 8px);
.qr-code {
width: 150px;
height: 150px;
border: 2px solid var(--color-neutral-200, #e5e7eb);
border-radius: var(--radius-sm, 4px);
padding: var(--spacing-sm, 8px);
background-color: white;
}
.qr-description {
text-align: center;
max-width: 200px;
}
}
.qr-loading {
display: flex;
justify-content: center;
align-items: center;
width: 150px;
height: 150px;
border: 2px dashed var(--color-neutral-300, #d1d5db);
border-radius: var(--radius-sm, 4px);
background-color: var(--color-neutral-50, #f9fafb);
}
.qr-error {
display: flex;
justify-content: center;
align-items: center;
width: 150px;
height: 150px;
border: 2px solid var(--color-error-200, #fecaca);
border-radius: var(--radius-sm, 4px);
background-color: var(--color-error-50, #fef2f2);
}
.actions {
display: flex;
justify-content: space-between;
align-items: center;
gap: var(--spacing-lg, 24px);
@media (max-width: $screen-s) {
flex-direction: column;
gap: var(--spacing-md, 16px);
}
}
}
}

View File

@ -0,0 +1,260 @@
import Button, { EButtonSize, EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button";
import DragAndDrop from "@Front/Components/DesignSystem/DragAndDrop";
import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography";
import Module from "@Front/Config/Module";
import PdfService from "@Front/Services/PdfService";
import { FileBlob } from "@Front/Api/Entities/types";
import { ShieldCheckIcon } from "@heroicons/react/24/outline";
import { useRouter } from "next/router";
import React, { useState } from "react";
import MessageBus from "src/sdk/MessageBus";
import classes from "./classes.module.scss";
import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
import FileService from "src/common/Api/LeCoffreApi/sdk/FileService";
type IProps = {
folderUid: string;
};
/**
* Convert a File object to FileBlob
* @param file - The File object to convert
* @returns Promise<FileBlob> - The converted FileBlob
*/
const convertFileToFileBlob = async (file: File): Promise<FileBlob> => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
const arrayBuffer = reader.result as ArrayBuffer;
const uint8Array = new Uint8Array(arrayBuffer);
resolve({
type: file.type,
data: uint8Array
});
};
reader.onerror = () => reject(new Error('Failed to read file'));
reader.readAsArrayBuffer(file);
});
};
export default function DocumentVerification(props: IProps) {
const { folderUid } = props;
const router = useRouter();
const [documentToVerify, setDocumentToVerify] = useState<File | null>(null);
const [validationCertificate, setValidationCertificate] = useState<File | null>(null);
const [isVerifying, setIsVerifying] = useState(false);
const [verificationResult, setVerificationResult] = useState<{
success: boolean;
message: string;
details?: string;
merkleProof?: string;
} | null>(null);
const handleDocumentToVerifyChange = (files: File[]) => {
if (files.length > 0 && files[0]) {
setDocumentToVerify(files[0]);
} else {
setDocumentToVerify(null);
}
};
const handleValidationCertificateChange = (files: File[]) => {
if (files.length > 0 && files[0]) {
setValidationCertificate(files[0]);
} else {
setValidationCertificate(null);
}
};
const handleVerifyDocuments = async () => {
if (!documentToVerify || !validationCertificate) {
console.error("Both documents are required for verification");
return;
}
setIsVerifying(true);
setVerificationResult(null);
const messageBus = MessageBus.getInstance();
try {
// Here the things we need to verify:
// - we can produce the same hash from the document provided than what is in the validation certificate
// - the merkle proof is valid with that hash
// - the root of the merkle tree is a state id from a commited state in the process
// - that process is a file process linked to the right folder
// Step 1: Parse the validation certificate
const validationData = await PdfService.getInstance().parseCertificate(validationCertificate);
// Step 2: Convert File to FileBlob and hash the document using MessageBus
const fileBlob = await convertFileToFileBlob(documentToVerify);
await messageBus.isReady();
const documentHash = await messageBus.hashDocument(fileBlob, validationData.commitmentId);
// Step 3: Compare hashes
const hashesMatch = documentHash.toLowerCase() === validationData.documentHash.toLowerCase();
if (!hashesMatch) {
throw new Error('Hash du document invalide, le document fourni n\'est pas celui qui a été certifié');
}
// Step 4: Verify the merkle proof
const merkleProof = validationData.merkleProof;
const merkleProofValid = await messageBus.verifyMerkleProof(merkleProof, documentHash);
if (!merkleProofValid) {
throw new Error('Preuve de Merkle invalide, le document n\'a pas été certifié là où le certificat le prétend');
}
// Step 5: Verify that this file process depends on the right folder process
// First pin all the validated documents related to the folder
const documentProcesses = await DocumentService.getDocuments();
const documents = documentProcesses.filter((process: any) =>
process.processData.document_status === "VALIDATED" &&
process.processData.folder.uid === folderUid
);
if (!documents || documents.length === 0) {
throw new Error(`Aucune demande de document trouvé pour le dossier ${folderUid}`);
}
// Step 6: verify that the merkle proof match the last commited state for the file process
const stateId = JSON.parse(validationData.merkleProof)['root'];
let stateIdExists = false;
for (const doc of documents) {
const processData = doc.processData;
for (const file of processData.files) {
const fileUid = file.uid;
const fileProcess = await FileService.getFileByUid(fileUid);
const lastUpdatedStateId = fileProcess.lastUpdatedFileState.state_id;
stateIdExists = lastUpdatedStateId === stateId; // we assume that last state is the validated document, that seems reasonable
if (stateIdExists) break;
}
if (stateIdExists) break;
}
if (!stateIdExists) {
throw new Error('La preuve fournie ne correspond à aucun document demandé pour ce dossier.');
}
setVerificationResult({
success: true,
message: "✅ Vérification réussie ! Le document est authentique et intègre.",
});
} catch (error) {
console.error("Verification failed:", error);
setVerificationResult({
success: false,
message: `❌ Erreur lors de la vérification: ${error}`,
});
} finally {
setIsVerifying(false);
}
};
const handleBackToFolder = () => {
const folderPath = Module.getInstance()
.get()
.modules.pages.Folder.pages.FolderInformation.props.path.replace("[folderUid]", folderUid);
router.push(folderPath);
};
const bothDocumentsPresent = documentToVerify && validationCertificate;
return (
<div className={classes["root"]}>
<div className={classes["header"]}>
<Typography typo={ETypo.TITLE_H2} color={ETypoColor.TEXT_PRIMARY}>
Vérification de Documents
</Typography>
<Typography typo={ETypo.TEXT_LG_REGULAR} color={ETypoColor.TEXT_SECONDARY}>
Vérifiez l'intégrité et l'authenticité de vos documents
</Typography>
</div>
<div className={classes["content"]}>
<div className={classes["drag-drop-container"]}>
<div className={classes["drag-drop-box"]}>
<DragAndDrop
title="Document à valider"
description="Glissez-déposez ou cliquez pour sélectionner le document que vous souhaitez vérifier"
onChange={handleDocumentToVerifyChange}
/>
{documentToVerify && (
<div className={classes["file-info"]}>
<Typography typo={ETypo.TEXT_SM_REGULAR} color={ETypoColor.COLOR_SUCCESS_500}>
{documentToVerify.name}
</Typography>
</div>
)}
</div>
<div className={classes["drag-drop-box"]}>
<DragAndDrop
title="Certificat de validation"
description="Glissez-déposez ou cliquez pour sélectionner le certificat de validation correspondant"
onChange={handleValidationCertificateChange}
/>
{validationCertificate && (
<div className={classes["file-info"]}>
<Typography typo={ETypo.TEXT_SM_REGULAR} color={ETypoColor.COLOR_SUCCESS_500}>
{validationCertificate.name}
</Typography>
</div>
)}
</div>
</div>
{!bothDocumentsPresent && (
<div className={classes["warning"]}>
<Typography typo={ETypo.TEXT_MD_REGULAR} color={ETypoColor.COLOR_WARNING_500}>
Veuillez sélectionner les deux documents pour procéder à la vérification
</Typography>
</div>
)}
{verificationResult && (
<div className={`${classes["verification-result"]} ${classes[verificationResult.success ? "success" : "error"]}`}>
<Typography typo={ETypo.TEXT_LG_REGULAR} color={verificationResult.success ? ETypoColor.COLOR_SUCCESS_500 : ETypoColor.COLOR_ERROR_500}>
{verificationResult.message}
</Typography>
</div>
)}
<div className={classes["actions"]}>
<Button
variant={EButtonVariant.SECONDARY}
styletype={EButtonstyletype.TEXT}
size={EButtonSize.LG}
onClick={handleBackToFolder}
disabled={isVerifying}
>
Retour au dossier
</Button>
<Button
variant={EButtonVariant.PRIMARY}
styletype={EButtonstyletype.CONTAINED}
size={EButtonSize.LG}
onClick={handleVerifyDocuments}
rightIcon={<ShieldCheckIcon />}
disabled={!bothDocumentsPresent || isVerifying}
isLoading={isVerifying}
>
{isVerifying ? "Vérification en cours..." : "Vérifier les documents"}
</Button>
</div>
</div>
</div>
);
}

View File

@ -5,11 +5,12 @@ import { IItem } from "@Front/Components/DesignSystem/Menu/MenuItem";
import Tag, { ETagColor } from "@Front/Components/DesignSystem/Tag";
import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography";
import Module from "@Front/Config/Module";
import { ArchiveBoxIcon, EllipsisHorizontalIcon, PaperAirplaneIcon, PencilSquareIcon, UsersIcon } from "@heroicons/react/24/outline";
import { ArchiveBoxIcon, EllipsisHorizontalIcon, PaperAirplaneIcon, PencilSquareIcon, ShieldCheckIcon, UsersIcon } from "@heroicons/react/24/outline";
import classNames from "classnames";
import { OfficeFolder } from "le-coffre-resources/dist/Notary";
import Link from "next/link";
import { useMemo } from "react";
import { useRouter } from "next/router";
import { AnchorStatus } from "..";
import classes from "./classes.module.scss";
@ -24,6 +25,7 @@ type IProps = {
export default function InformationSection(props: IProps) {
const { folder, progress, onArchive, anchorStatus, isArchived } = props;
const router = useRouter();
const menuItemsDekstop = useMemo(() => {
let elements: IItem[] = [];
@ -43,6 +45,17 @@ export default function InformationSection(props: IProps) {
link: Module.getInstance()
.get()
.modules.pages.Folder.pages.EditInformations.props.path.replace("[folderUid]", folder?.uid ?? ""),
hasSeparator: true,
};
const verifyDocumentElement = {
icon: <ShieldCheckIcon />,
text: "Vérifier le document",
onClick: () => {
const verifyPath = Module.getInstance()
.get()
.modules.pages.Folder.pages.VerifyDocuments.props.path.replace("[folderUid]", folder?.uid ?? "");
router.push(verifyPath);
},
hasSeparator: false,
};
@ -52,8 +65,11 @@ export default function InformationSection(props: IProps) {
elements.push(modifyInformationsElement);
}
// Add verify document option
elements.push(verifyDocumentElement);
return elements;
}, [anchorStatus, folder?.uid]);
}, [anchorStatus, folder?.uid, router]);
const menuItemsMobile = useMemo(() => {
let elements: IItem[] = [];
@ -75,6 +91,17 @@ export default function InformationSection(props: IProps) {
.modules.pages.Folder.pages.EditInformations.props.path.replace("[folderUid]", folder?.uid ?? ""),
hasSeparator: true,
};
const verifyDocumentElement = {
icon: <ShieldCheckIcon />,
text: "Vérifier le document",
onClick: () => {
const verifyPath = Module.getInstance()
.get()
.modules.pages.Folder.pages.VerifyDocuments.props.path.replace("[folderUid]", folder?.uid ?? "");
router.push(verifyPath);
},
hasSeparator: true,
};
// If the folder is not anchored, we can modify the collaborators and the informations
if (anchorStatus === AnchorStatus.NOT_ANCHORED) {
@ -82,6 +109,9 @@ export default function InformationSection(props: IProps) {
elements.push(modifyInformationsElement);
}
// Add verify document option
elements.push(verifyDocumentElement);
elements.push({
icon: <PaperAirplaneIcon />,
text: "Envoyer des documents",
@ -101,7 +131,7 @@ export default function InformationSection(props: IProps) {
}
return elements;
}, [anchorStatus, folder?.uid, isArchived, onArchive]);
}, [anchorStatus, folder?.uid, isArchived, onArchive, router]);
return (
<section className={classes["root"]}>
<div className={classes["info-box1"]}>

View File

@ -160,6 +160,13 @@
"path": "/folders/select",
"labelKey": "select_folder"
}
},
"VerifyDocuments": {
"enabled": true,
"props": {
"path": "/folders/[folderUid]/verify-documents",
"labelKey": "verify_documents"
}
}
}
},

View File

@ -160,6 +160,13 @@
"path": "/folders/select",
"labelKey": "select_folder"
}
},
"VerifyDocuments": {
"enabled": true,
"props": {
"path": "/folders/[folderUid]/verify-documents",
"labelKey": "verify_documents"
}
}
}
},

View File

@ -160,6 +160,13 @@
"path": "/folders/select",
"labelKey": "select_folder"
}
},
"VerifyDocuments": {
"enabled": true,
"props": {
"path": "/folders/[folderUid]/verify-documents",
"labelKey": "verify_documents"
}
}
}
},

View File

@ -160,6 +160,13 @@
"path": "/folders/select",
"labelKey": "select_folder"
}
},
"VerifyDocuments": {
"enabled": true,
"props": {
"path": "/folders/[folderUid]/verify-documents",
"labelKey": "verify_documents"
}
}
}
},

View File

@ -1,6 +1,8 @@
import { saveAs } from 'file-saver';
import { PDFDocument, rgb, StandardFonts } from 'pdf-lib';
const separator = '\x1f';
export interface CustomerInfo {
firstName: string;
lastName: string;
@ -185,50 +187,17 @@ export default class PdfService {
});
y -= lineSpacing;
// Document Hash Section
page.drawText('Intégrité du Document', {
x: leftMargin,
y: y,
size: 12,
font: helveticaBoldFont,
color: rgb(0, 0, 0)
});
y -= lineSpacing;
// Add verification data as base64
const verificationData = {
documentHash: certificateData.documentHash,
commitmentId: certificateData.metadata.commitmentId,
merkleProof: certificateData.metadata.merkleProof || "N/A"
};
const verificationDataBase64 = btoa(JSON.stringify(verificationData));
// Calculate proper chunk size based on available width and font size
const availableWidth = width - (2 * leftMargin) - 20; // Full width minus margins and safety buffer
const fontSize = 12;
// Use a typical base64 character for width calculation
const avgCharWidth = helveticaFont.widthOfTextAtSize('A', fontSize);
const charsPerLine = Math.floor(availableWidth / avgCharWidth);
const chunkSize = Math.max(60, Math.min(100, charsPerLine)); // More conservative limits
const chunks = [];
for (let j = 0; j < verificationDataBase64.length; j += chunkSize) {
chunks.push(verificationDataBase64.slice(j, j + chunkSize));
}
chunks.forEach((chunk, index) => {
page.drawText(chunk, {
x: leftMargin,
y: y - (index * 12), // Increased line spacing
size: fontSize,
font: helveticaFont,
color: rgb(0, 0, 0)
});
});
const keywords = [
certificateData.documentHash,
certificateData.metadata.commitmentId,
JSON.stringify(certificateData.metadata.merkleProof)
];
pdfDoc.setKeywords([keywords.join(separator)]);
// Add explanatory text about certificate usage
y -= (chunks.length * 12) + 40; // Space after verification data
const explanatoryText = "Ce certificat doit être utilisé avec le document qu'il certifie pour être vérifié sur la page dédiée. Le document correspondant à ce certificat doit être téléchargé depuis LeCoffre et peut être conservé avec le certificat tant qu'il n'est pas modifié.";
const explanatoryLines = this.splitTextToFit(helveticaObliqueFont, explanatoryText, width - (2 * leftMargin), 11);
y -= (explanatoryLines.length * 12) + 40; // Space after verification data
explanatoryLines.forEach((line, index) => {
page.drawText(line, {
x: leftMargin,
@ -322,314 +291,47 @@ export default class PdfService {
}
}
/**
* Generate certificate for notary documents
* @param certificateData - Data needed for the certificate
* @returns Promise<Blob> - The generated PDF as a blob
*/
public async generateNotaryCertificate(certificateData: CertificateData): Promise<Blob> {
try {
// Create a new PDF document
const pdfDoc = await PDFDocument.create();
const page = pdfDoc.addPage([595, 842]); // A4 size
const { width, height } = page.getSize();
// Embed the standard font
const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica);
const helveticaBoldFont = await pdfDoc.embedFont(StandardFonts.HelveticaBold);
const helveticaObliqueFont = await pdfDoc.embedFont(StandardFonts.HelveticaOblique);
// Notary Information Section (Top Left)
page.drawText('Notaire Validateur:', {
x: 20,
y: height - 30,
size: 12,
font: helveticaBoldFont,
color: rgb(0, 0, 0)
});
page.drawText(certificateData.notary.name, {
x: 20,
y: height - 37,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
// Customer Information Section (Top Right)
page.drawText('Fournisseur de Document:', {
x: 120,
y: height - 30,
size: 12,
font: helveticaBoldFont,
color: rgb(0, 0, 0)
});
page.drawText(`${certificateData.customer.firstName} ${certificateData.customer.lastName}`, {
x: 120,
y: height - 37,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
page.drawText(certificateData.customer.email, {
x: 120,
y: height - 44,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
page.drawText(certificateData.customer.postalAddress, {
x: 120,
y: height - 51,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
// Centered Title
const titleText = 'Certificat Notarial de Validation de Document';
const titleWidth = helveticaBoldFont.widthOfTextAtSize(titleText, 20);
page.drawText(titleText, {
x: (width - titleWidth) / 2,
y: height - 80,
size: 20,
font: helveticaBoldFont,
color: rgb(0, 0, 0)
});
// Add a line separator
page.drawLine({
start: { x: 20, y: height - 90 },
end: { x: width - 20, y: height - 90 },
thickness: 0.5,
color: rgb(0, 0, 0)
});
let yPosition = height - 110;
// Document Information Section
page.drawText('Informations du Document', {
x: 20,
y: yPosition,
size: 12,
font: helveticaBoldFont,
color: rgb(0, 0, 0)
});
yPosition -= 10;
page.drawText(`Identifiant du Document: ${certificateData.metadata.documentUid}`, {
x: 20,
y: yPosition,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
yPosition -= 7;
page.drawText(`Type de Document: ${certificateData.metadata.documentType}`, {
x: 20,
y: yPosition,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
yPosition -= 7;
page.drawText(`Numéro de dossier: ${certificateData.folderUid}`, {
x: 20,
y: yPosition,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
yPosition -= 7;
page.drawText(`Créé le: ${certificateData.metadata.createdAt.toLocaleDateString('fr-FR')}`, {
x: 20,
y: yPosition,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
yPosition -= 7;
page.drawText(`Nom du fichier: ${certificateData.metadata.fileName}`, {
x: 20,
y: yPosition,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
yPosition -= 7;
page.drawText(`ID de transaction: ${certificateData.metadata.commitmentId}`, {
x: 20,
y: yPosition,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
yPosition -= 7;
page.drawText(`Dernière modification: ${certificateData.metadata.updatedAt.toLocaleDateString('fr-FR')}`, {
x: 20,
y: yPosition,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
yPosition -= 7;
page.drawText(`Statut: ${certificateData.metadata.isDeleted ? 'Supprimé' : 'Actif'}`, {
x: 20,
y: yPosition,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
yPosition -= 15;
// Document Hash Section
page.drawText('Intégrité du Document', {
x: 20,
y: yPosition,
size: 12,
font: helveticaBoldFont,
color: rgb(0, 0, 0)
});
yPosition -= 10;
page.drawText(`Hash SHA256 du Document:`, {
x: 20,
y: yPosition,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
yPosition -= 7;
// Split hash into multiple lines if needed
const hash = certificateData.documentHash;
const maxWidth = 170; // Available width for text
const hashLines = this.splitTextToFit(helveticaFont, hash, maxWidth, 12);
for (const line of hashLines) {
page.drawText(line, {
x: 25,
y: yPosition,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
yPosition -= 7;
}
yPosition -= 8; // Extra space after hash
yPosition -= 5;
// Footer
const footerText1 = `Page 1 sur 1`;
const footerText2 = `Certificat Notarial - Généré le ${new Date().toLocaleString('fr-FR')}`;
const footerWidth1 = helveticaObliqueFont.widthOfTextAtSize(footerText1, 10);
const footerWidth2 = helveticaObliqueFont.widthOfTextAtSize(footerText2, 10);
page.drawText(footerText1, {
x: (width - footerWidth1) / 2,
y: 30,
size: 10,
font: helveticaObliqueFont,
color: rgb(0, 0, 0)
});
page.drawText(footerText2, {
x: (width - footerWidth2) / 2,
y: 25,
size: 10,
font: helveticaObliqueFont,
color: rgb(0, 0, 0)
});
// Add verification data as base64 in small font
const verificationData = {
documentHash: certificateData.documentHash,
commitmentId: certificateData.metadata.commitmentId,
merkleProof: certificateData.metadata.merkleProof || "N/A"
};
const verificationDataBase64 = btoa(JSON.stringify(verificationData));
// Split into chunks if too long
const chunkSize = 80;
const chunks = [];
for (let j = 0; j < verificationDataBase64.length; j += chunkSize) {
chunks.push(verificationDataBase64.slice(j, j + chunkSize));
}
chunks.forEach((chunk, index) => {
page.drawText(chunk, {
x: 20,
y: 15 - (index * 3),
size: 6,
font: helveticaFont,
color: rgb(0, 0, 0)
});
});
// Save the PDF
const pdfBytes = await pdfDoc.save();
return new Blob([pdfBytes], { type: 'application/pdf' });
} catch (error) {
console.error('Error generating notary certificate:', error);
throw new Error('Failed to generate notary certificate');
}
}
/**
* Download a notary certificate PDF
* @param certificateData - Data needed for the certificate
* @param filename - Optional filename for the download
*/
public async downloadNotaryCertificate(certificateData: CertificateData, filename?: string): Promise<void> {
try {
const pdfBlob = await this.generateNotaryCertificate(certificateData);
const defaultFilename = `notary_certificate_${certificateData.metadata.documentUid}_${new Date().toISOString().split('T')[0]}.pdf`;
saveAs(pdfBlob, filename || defaultFilename);
} catch (error) {
console.error('Error downloading notary certificate:', error);
throw error;
}
}
/**
* Parse a PDF certificate and extract document information
* @param pdfBlob - The PDF file as a blob
* @returns Promise<{documentHash: string, documentUid: string, commitmentId: string, merkleProof?: string}> - Extracted information
*/
public async parseCertificate(pdfBlob: Blob): Promise<{documentHash: string, documentUid: string, commitmentId: string, merkleProof?: string}> {
public async parseCertificate(certificateFile: File): Promise<{documentHash: string, commitmentId: string, merkleProof: any}> {
return new Promise((resolve, reject) => {
const fileReader = new FileReader();
console.log("certificateFile", certificateFile);
fileReader.onload = async () => {
try {
// Convert PDF to text using browser's PDF capabilities
const arrayBuffer = fileReader.result as ArrayBuffer;
const pdfData = new Uint8Array(arrayBuffer);
console.log("PDF data:", pdfData);
// Read the metadata and get the validation data from the keywords
const pdfDoc = await PDFDocument.load(await certificateFile.arrayBuffer());
const keywords = pdfDoc.getKeywords()?.split(separator);
// Use a simple text extraction approach
// This is a basic implementation - for production, consider using pdfjs-dist
const text = await this.extractTextFromPdf(pdfData);
// Parse the extracted text to find our certificate data
const parsedData = this.parseCertificateText(text);
if (!parsedData.documentHash) {
throw new Error('Document hash not found in certificate');
if (!keywords) {
throw new Error("No keywords found in certificate");
}
resolve(parsedData);
console.log(keywords);
if (keywords.length !== 3) {
throw new Error("Invalid keywords found in certificate");
}
const documentHash = keywords[0];
const commitmentId = keywords[1];
const merkleProof = keywords[2];
if (!documentHash || !commitmentId || !merkleProof) {
throw new Error("Invalid keywords found in certificate");
}
console.log("documentHash", documentHash);
console.log("commitmentId", commitmentId);
console.log("merkleProof", merkleProof);
resolve({ documentHash, commitmentId, merkleProof });
} catch (error) {
reject(error);
}
@ -639,103 +341,7 @@ export default class PdfService {
reject(new Error('Failed to read PDF file'));
};
fileReader.readAsArrayBuffer(pdfBlob);
fileReader.readAsArrayBuffer(certificateFile);
});
}
/**
* Extract text from PDF using browser capabilities
* @param pdfData - PDF data as Uint8Array
* @returns Promise<string> - Extracted text
*/
private async extractTextFromPdf(pdfData: Uint8Array): Promise<string> {
console.log("extractTextFromPdf");
// Convert PDF data to string to search for base64 patterns
const pdfString = new TextDecoder('utf-8').decode(pdfData);
// Look for base64 patterns in the PDF content
// This is a simple approach that should work for our embedded data
const base64Matches = pdfString.match(/([A-Za-z0-9+/]{80,}={0,2})/g);
if (base64Matches && base64Matches.length > 0) {
console.log('Found base64 patterns in PDF:', base64Matches.length);
// Return the longest base64 string (most likely our verification data)
const longestBase64 = base64Matches.reduce((a, b) => a.length > b.length ? a : b);
return longestBase64;
}
// If no base64 found, return empty string
console.log('No base64 patterns found in PDF');
return '';
}
/**
* Parse certificate text to extract specific fields
* @param text - Extracted text from PDF (could be base64 or regular text)
* @returns Parsed certificate data
*/
private parseCertificateText(text: string): {documentHash: string, documentUid: string, commitmentId: string, merkleProof?: string} {
const result = {
documentHash: '',
documentUid: '',
commitmentId: '',
merkleProof: undefined as string | undefined
};
// Check if the text is a base64 string (our new format)
if (text.match(/^[A-Za-z0-9+/]+={0,2}$/)) {
try {
console.log('Attempting to decode base64 data:', text.substring(0, 50) + '...');
const decodedData = atob(text);
const verificationData = JSON.parse(decodedData);
console.log('Successfully decoded verification data:', verificationData);
if (verificationData.documentHash) {
result.documentHash = verificationData.documentHash;
}
if (verificationData.commitmentId) {
result.commitmentId = verificationData.commitmentId;
}
if (verificationData.merkleProof && verificationData.merkleProof !== "N/A") {
result.merkleProof = verificationData.merkleProof;
}
// If we successfully extracted data from base64, return early
if (result.documentHash) {
return result;
}
} catch (error) {
console.log('Failed to decode base64 data:', error);
}
}
// Fallback to text parsing for older certificates
// Extract document hash (64 character hex string)
const hashMatch = text.match(/Hash SHA256 du Document:\s*([a-fA-F0-9]{64})/);
if (hashMatch && hashMatch[1]) {
result.documentHash = hashMatch[1];
}
// Extract document UID
const uidMatch = text.match(/UID du Document:\s*([^\n\r]+)/);
if (uidMatch && uidMatch[1]) {
result.documentUid = uidMatch[1].trim();
}
// Extract commitment ID
const commitmentMatch = text.match(/ID de transaction:\s*([^\n\r]+)/);
if (commitmentMatch && commitmentMatch[1]) {
result.commitmentId = commitmentMatch[1].trim();
}
// Extract merkle proof
const merkleProofMatch = text.match(/Preuve Merkle \(Blockchain\):\s*([^\n\r]+)/);
if (merkleProofMatch && merkleProofMatch[1]) {
result.merkleProof = merkleProofMatch[1].trim();
}
return result;
}
}

View File

@ -0,0 +1,20 @@
import { useRouter } from "next/router";
import React from "react";
import DefaultNotaryDashboard from "@Front/Components/LayoutTemplates/DefaultNotaryDashboard";
import DocumentVerification from "@Front/Components/Layouts/Folder/DocumentVerification";
export default function VerifyDocuments() {
const router = useRouter();
const { folderUid } = router.query;
if (!folderUid || Array.isArray(folderUid)) {
return null;
}
return (
<DefaultNotaryDashboard>
<DocumentVerification folderUid={folderUid} />
</DefaultNotaryDashboard>
);
}

View File

@ -646,6 +646,41 @@ export default class MessageBus {
});
}
public verifyMerkleProof(merkleProof: string, documentHash: string): Promise<boolean> {
return new Promise<boolean>((resolve: (isValid: boolean) => void, reject: (error: string) => void) => {
this.checkToken().then(() => {
const messageId = `VALIDATE_MERKLE_PROOF_${uuidv4()}`;
const unsubscribe = EventBus.getInstance().on('MERKLE_PROOF_VALIDATED', (responseId: string, isValid: boolean) => {
if (responseId !== messageId) {
return;
}
unsubscribe();
resolve(isValid);
});
const unsubscribeError = EventBus.getInstance().on('ERROR_MERKLE_PROOF_VALIDATED', (responseId: string, error: string) => {
if (responseId !== messageId) {
return;
}
unsubscribeError();
reject(error);
});
const user = User.getInstance();
const accessToken = user.getAccessToken()!;
this.sendMessage({
type: 'VALIDATE_MERKLE_PROOF',
accessToken,
merkleProof,
documentHash,
messageId
});
}).catch(reject);
});
}
private validateToken(): Promise<boolean> {
return new Promise<boolean>((resolve: (isValid: boolean) => void, reject: (error: string) => void) => {
const messageId = `VALIDATE_TOKEN_${uuidv4()}`;
@ -736,7 +771,9 @@ export default class MessageBus {
console.error('[MessageBus] sendMessage: iframe not found');
return;
}
// console.log('[MessageBus] sendMessage:', message);
if (message.type === 'VALIDATE_MERKLE_PROOF') {
console.log('[MessageBus] sendMessage:', message);
}
iframe.contentWindow?.postMessage(message, targetOrigin);
}
@ -839,10 +876,14 @@ export default class MessageBus {
this.doHandleMessage(message.messageId, 'VALUE_HASHED', message, (message: any) => message.hash);
break;
case 'MERKLE_PROOF_RETRIEVED': // GENERATE_MERKLE_PROOF
case 'MERKLE_PROOF_RETRIEVED': // GET_MERKLE_PROOF
this.doHandleMessage(message.messageId, 'MERKLE_PROOF_RETRIEVED', message, (message: any) => message.proof);
break;
case 'MERKLE_PROOF_VALIDATED': // VALIDATE_MERKLE_PROOF
this.doHandleMessage(message.messageId, 'MERKLE_PROOF_VALIDATED', message, (message: any) => message.isValid);
break;
case 'ERROR':
console.error('Error:', message);
this.errors[message.messageId] = message.error;