firma-web 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +177 -0
- package/package.json +1 -1
package/README.md
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
# firma-web
|
|
2
|
+
|
|
3
|
+
Librería agnóstica (**Angular**, **React**, **HTML/JS**) para firma electrónica de archivos PDF en navegador mediante certificados `.p12` / `.pfx`, estampa visual con código QR, validación de certificados y verificación de firmas incrustadas en documentos PDF.
|
|
4
|
+
|
|
5
|
+
## Características
|
|
6
|
+
|
|
7
|
+
- **100% client-side en navegador**: lectura de `.p12`/`.pfx`, validación de contraseña, firma criptográfica `PKCS#7` detached (SHA-256 + RSA) y verificación de integridad (`/ByteRange` + `/Contents`).
|
|
8
|
+
- **Estampa visual interactiva**: modal (o modo `inline`) con vista previa de páginas PDF y recuadro arrastrable para ubicar la estampa con código QR.
|
|
9
|
+
- **Web Components nativos**: funciona en Angular, React y cualquier proyecto web sin dependencias de framework.
|
|
10
|
+
- **Interfaz extensible (`SignerAdapter`)**: permite conectar adaptadores externos (por ejemplo, un agente local para tokens USB PKCS#11) sin cambiar la UI ni el flujo de firmado.
|
|
11
|
+
|
|
12
|
+
## Instalación
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npm install firma-web
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
> **Nota sobre `pdfjs-dist`**: `pdfjs-dist` se declara como dependencia externa en el bundle. Si usas el visor de PDF en `<firma-sign-modal>` o `<firma-studio>` dentro de un bundler moderno (Angular/Vite/Webpack), puedes indicar la ruta del worker mediante el atributo `worker-src`:
|
|
19
|
+
>
|
|
20
|
+
> ```html
|
|
21
|
+
> <firma-studio worker-src="/assets/pdf.worker.min.mjs"></firma-studio>
|
|
22
|
+
> ```
|
|
23
|
+
|
|
24
|
+
## Uso en Angular
|
|
25
|
+
|
|
26
|
+
1. Registra los Web Components una vez (por ejemplo en `main.ts` o en el componente):
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
import { registerFirmaComponents } from 'firma-web';
|
|
30
|
+
|
|
31
|
+
registerFirmaComponents();
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
2. Habilita `CUSTOM_ELEMENTS_SCHEMA` en tu componente o módulo:
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
import { Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
|
|
38
|
+
import type { FirmaSignedEventDetail } from 'firma-web';
|
|
39
|
+
|
|
40
|
+
@Component({
|
|
41
|
+
selector: 'app-firma',
|
|
42
|
+
standalone: true,
|
|
43
|
+
schemas: [CUSTOM_ELEMENTS_SCHEMA],
|
|
44
|
+
template: `
|
|
45
|
+
<!-- Interfaz completa con pestañas -->
|
|
46
|
+
<firma-studio></firma-studio>
|
|
47
|
+
|
|
48
|
+
<!-- O usar únicamente el modal de firma -->
|
|
49
|
+
<button (click)="modalOpen = true">Firmar PDF</button>
|
|
50
|
+
<firma-sign-modal
|
|
51
|
+
[attr.open]="modalOpen ? '' : null"
|
|
52
|
+
(firma-signed)="onSigned($event)"
|
|
53
|
+
(firma-close)="modalOpen = false">
|
|
54
|
+
</firma-sign-modal>
|
|
55
|
+
`
|
|
56
|
+
})
|
|
57
|
+
export class FirmaComponent {
|
|
58
|
+
modalOpen = false;
|
|
59
|
+
|
|
60
|
+
onSigned(event: Event): void {
|
|
61
|
+
const { signedPdf, fileName, certificate } =
|
|
62
|
+
(event as CustomEvent<FirmaSignedEventDetail>).detail;
|
|
63
|
+
console.log('PDF firmado:', fileName, 'Titular:', certificate.subject.commonName);
|
|
64
|
+
// signedPdf es un Uint8Array listo para descargar o enviar al servidor
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Uso en React
|
|
70
|
+
|
|
71
|
+
```tsx
|
|
72
|
+
import { useEffect, useRef, useState } from 'react';
|
|
73
|
+
import {
|
|
74
|
+
registerFirmaComponents,
|
|
75
|
+
type FirmaSignedEventDetail,
|
|
76
|
+
type FirmaSignModalElement
|
|
77
|
+
} from 'firma-web';
|
|
78
|
+
|
|
79
|
+
registerFirmaComponents();
|
|
80
|
+
|
|
81
|
+
export function FirmaPage() {
|
|
82
|
+
const [open, setOpen] = useState(false);
|
|
83
|
+
const modalRef = useRef<FirmaSignModalElement | null>(null);
|
|
84
|
+
|
|
85
|
+
useEffect(() => {
|
|
86
|
+
const el = modalRef.current;
|
|
87
|
+
if (!el) return;
|
|
88
|
+
|
|
89
|
+
const handleSigned = (e: Event) => {
|
|
90
|
+
const { signedPdf, fileName, certificate } =
|
|
91
|
+
(e as CustomEvent<FirmaSignedEventDetail>).detail;
|
|
92
|
+
console.log('Firmado:', fileName, certificate.subject.commonName, signedPdf);
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
const handleClose = () => setOpen(false);
|
|
96
|
+
|
|
97
|
+
el.addEventListener('firma-signed', handleSigned);
|
|
98
|
+
el.addEventListener('firma-close', handleClose);
|
|
99
|
+
return () => {
|
|
100
|
+
el.removeEventListener('firma-signed', handleSigned);
|
|
101
|
+
el.removeEventListener('firma-close', handleClose);
|
|
102
|
+
};
|
|
103
|
+
}, []);
|
|
104
|
+
|
|
105
|
+
return (
|
|
106
|
+
<div>
|
|
107
|
+
<button onClick={() => setOpen(true)}>Abrir modal de firma</button>
|
|
108
|
+
<firma-sign-modal ref={modalRef} open={open ? '' : undefined} />
|
|
109
|
+
|
|
110
|
+
{/* O el panel unificado con pestañas */}
|
|
111
|
+
<firma-studio />
|
|
112
|
+
</div>
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
## Web Components disponibles
|
|
118
|
+
|
|
119
|
+
| Etiqueta | Descripción | Eventos |
|
|
120
|
+
| --- | --- | --- |
|
|
121
|
+
| `<firma-studio>` | Panel con pestañas: Firmar Documento, Validar Certificado y Validar Firmas en PDF | Propaga los eventos de cada módulo |
|
|
122
|
+
| `<firma-sign-modal>` | Modal (o `inline`) para validar `.p12`/`.pfx`, previsualizar PDF, ubicar estampa y firmar | `firma-signed` (`FirmaSignedEventDetail`), `firma-close` |
|
|
123
|
+
| `<firma-cert-validator>` | Valida `.p12`/`.pfx` + contraseña y muestra titular, emisor, serial y vigencia | `firma-cert-validated` (`ValidationResult`) |
|
|
124
|
+
| `<firma-pdf-validator>` | Inspecciona un PDF y valida todas las firmas encontradas e integridad | `firma-pdf-validated` (`{ fileName, signatures }`) |
|
|
125
|
+
|
|
126
|
+
## Uso programático (sin UI)
|
|
127
|
+
|
|
128
|
+
```ts
|
|
129
|
+
import {
|
|
130
|
+
P12SignerAdapter,
|
|
131
|
+
signPdf,
|
|
132
|
+
validateP12,
|
|
133
|
+
validatePdfSignatures
|
|
134
|
+
} from 'firma-web';
|
|
135
|
+
|
|
136
|
+
// 1. Validar certificado .p12/.pfx
|
|
137
|
+
const certValidation = validateP12(p12Bytes, 'mi-password');
|
|
138
|
+
|
|
139
|
+
// 2. Firmar y estampar un PDF
|
|
140
|
+
const signer = P12SignerAdapter.fromBytes(p12Bytes, 'mi-password');
|
|
141
|
+
const signedPdf = await signPdf(pdfBytes, signer, {
|
|
142
|
+
stamp: {
|
|
143
|
+
page: 1,
|
|
144
|
+
xRatio: 0.58,
|
|
145
|
+
yRatio: 0.78,
|
|
146
|
+
reason: 'Aprobación de documento',
|
|
147
|
+
location: 'Quito, Ecuador',
|
|
148
|
+
showQr: true
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
// 3. Validar las firmas encontradas en un PDF
|
|
153
|
+
const signatures = await validatePdfSignatures(signedPdf);
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
## Adaptador personalizado (Token USB / PKCS#11)
|
|
157
|
+
|
|
158
|
+
Puedes implementar la interfaz `SignerAdapter` e inyectarla en `<firma-sign-modal>` o en `signPdf(...)`:
|
|
159
|
+
|
|
160
|
+
```ts
|
|
161
|
+
import type { SignerAdapter } from 'firma-web';
|
|
162
|
+
|
|
163
|
+
const tokenAdapter: SignerAdapter = {
|
|
164
|
+
kind: 'token',
|
|
165
|
+
async getCertificateInfo() {
|
|
166
|
+
// Retornar CertificateInfo obtenido desde tu agente local
|
|
167
|
+
throw new Error('No implementado');
|
|
168
|
+
},
|
|
169
|
+
async signPkcs7Detached(contentBytes, signingTime) {
|
|
170
|
+
// Retornar firma DER PKCS#7 detached generada por el token
|
|
171
|
+
throw new Error('No implementado');
|
|
172
|
+
}
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
// Inyectar en el modal:
|
|
176
|
+
// await modalElement.setSignerAdapter(tokenAdapter);
|
|
177
|
+
```
|
package/package.json
CHANGED