firma-web 0.0.0-stage → 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 +176 -2
- package/dist/components/firma-cert-validator.d.ts +15 -0
- package/dist/components/firma-pdf-validator.d.ts +14 -0
- package/dist/components/firma-sign-modal.d.ts +53 -0
- package/dist/components/firma-studio.d.ts +9 -0
- package/dist/components/styles.d.ts +1 -0
- package/dist/core/p12-signer.d.ts +23 -0
- package/dist/core/pdf-signer.d.ts +2 -0
- package/dist/core/pdf-validator.d.ts +2 -0
- package/dist/firma-web.js +25821 -0
- package/dist/firma-web.umd.cjs +631 -0
- package/dist/index.d.ts +13 -0
- package/dist/types/index.d.ts +90 -0
- package/package.json +38 -4
package/README.md
CHANGED
|
@@ -1,3 +1,177 @@
|
|
|
1
|
-
#
|
|
1
|
+
# firma-web
|
|
2
2
|
|
|
3
|
-
|
|
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
|
+
```
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { CertificateInfo } from '../types/index.ts';
|
|
2
|
+
export declare function renderCertSummaryHtml(cert: CertificateInfo): string;
|
|
3
|
+
declare const BaseElement: typeof HTMLElement;
|
|
4
|
+
export declare class FirmaCertValidatorElement extends BaseElement {
|
|
5
|
+
private fileBytes;
|
|
6
|
+
private fileName;
|
|
7
|
+
private lastResult;
|
|
8
|
+
constructor();
|
|
9
|
+
connectedCallback(): void;
|
|
10
|
+
private handleValidate;
|
|
11
|
+
private renderResult;
|
|
12
|
+
private render;
|
|
13
|
+
}
|
|
14
|
+
export declare function registerCertValidator(): void;
|
|
15
|
+
export {};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { PdfSignatureValidationResult } from '../types/index.ts';
|
|
2
|
+
declare const BaseElement: typeof HTMLElement;
|
|
3
|
+
export declare class FirmaPdfValidatorElement extends BaseElement {
|
|
4
|
+
private results;
|
|
5
|
+
private fileName;
|
|
6
|
+
private errorMsg;
|
|
7
|
+
constructor();
|
|
8
|
+
connectedCallback(): void;
|
|
9
|
+
inspectPdf(bytes: Uint8Array, fileName?: string): Promise<PdfSignatureValidationResult[]>;
|
|
10
|
+
private renderResults;
|
|
11
|
+
private render;
|
|
12
|
+
}
|
|
13
|
+
export declare function registerPdfValidator(): void;
|
|
14
|
+
export {};
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { SignerAdapter } from '../types/index.ts';
|
|
2
|
+
declare const BaseElement: typeof HTMLElement;
|
|
3
|
+
export declare class FirmaSignModalElement extends BaseElement {
|
|
4
|
+
static get observedAttributes(): string[];
|
|
5
|
+
private p12Bytes;
|
|
6
|
+
private externalAdapter;
|
|
7
|
+
private activeAdapter;
|
|
8
|
+
private certInfo;
|
|
9
|
+
private pdfBytes;
|
|
10
|
+
private pdfFileName;
|
|
11
|
+
private pdfDocProxy;
|
|
12
|
+
private currentPage;
|
|
13
|
+
private totalPages;
|
|
14
|
+
private xRatio;
|
|
15
|
+
private yRatio;
|
|
16
|
+
private stampWidth;
|
|
17
|
+
private stampHeight;
|
|
18
|
+
private pagePdfWidth;
|
|
19
|
+
private pagePdfHeight;
|
|
20
|
+
private lastSignedPdf;
|
|
21
|
+
private isSigning;
|
|
22
|
+
private dragging;
|
|
23
|
+
private dragOffsetX;
|
|
24
|
+
private dragOffsetY;
|
|
25
|
+
constructor();
|
|
26
|
+
connectedCallback(): void;
|
|
27
|
+
attributeChangedCallback(name: string): void;
|
|
28
|
+
get open(): boolean;
|
|
29
|
+
set open(val: boolean);
|
|
30
|
+
openModal(): void;
|
|
31
|
+
closeModal(): void;
|
|
32
|
+
/**
|
|
33
|
+
* Permite inyectar un adaptador personalizado (por ejemplo, un Token USB PKCS#11)
|
|
34
|
+
* en lugar de cargar un archivo .p12/.pfx.
|
|
35
|
+
*/
|
|
36
|
+
setSignerAdapter(adapter: SignerAdapter): Promise<void>;
|
|
37
|
+
loadPdfBytes(bytes: Uint8Array, fileName?: string): Promise<void>;
|
|
38
|
+
private syncVisibility;
|
|
39
|
+
private handleValidateCert;
|
|
40
|
+
private updateCertStatus;
|
|
41
|
+
private updateSignStatus;
|
|
42
|
+
private updateSignButtonState;
|
|
43
|
+
private updateDownloadButton;
|
|
44
|
+
private renderPdfPage;
|
|
45
|
+
private positionStampOverlay;
|
|
46
|
+
private updateStampPreviewText;
|
|
47
|
+
private handleSign;
|
|
48
|
+
private downloadSignedPdf;
|
|
49
|
+
private render;
|
|
50
|
+
private bindEvents;
|
|
51
|
+
}
|
|
52
|
+
export declare function registerSignModal(): void;
|
|
53
|
+
export {};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
declare const BaseElement: typeof HTMLElement;
|
|
2
|
+
export declare class FirmaStudioElement extends BaseElement {
|
|
3
|
+
constructor();
|
|
4
|
+
connectedCallback(): void;
|
|
5
|
+
private switchTab;
|
|
6
|
+
private render;
|
|
7
|
+
}
|
|
8
|
+
export declare function registerFirmaStudio(): void;
|
|
9
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const BASE_STYLES = "\n :host {\n --firma-primary: #1d4ed8;\n --firma-primary-hover: #1e40af;\n --firma-bg: #ffffff;\n --firma-surface: #f8fafc;\n --firma-border: #cbd5e1;\n --firma-text: #0f172a;\n --firma-muted: #475569;\n --firma-success: #15803d;\n --firma-success-bg: #dcfce7;\n --firma-error: #b91c1c;\n --firma-error-bg: #fee2e2;\n --firma-warn: #a16207;\n --firma-warn-bg: #fef9c3;\n --firma-radius: 10px;\n font-family: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;\n color: var(--firma-text);\n box-sizing: border-box;\n }\n\n *, *::before, *::after {\n box-sizing: border-box;\n }\n\n .card {\n background: var(--firma-bg);\n border: 1px solid var(--firma-border);\n border-radius: var(--firma-radius);\n padding: 18px;\n box-shadow: 0 2px 10px rgba(15, 23, 42, 0.05);\n }\n\n .title {\n margin: 0 0 6px 0;\n font-size: 1.1rem;\n font-weight: 700;\n color: var(--firma-text);\n }\n\n .subtitle {\n margin: 0 0 16px 0;\n font-size: 0.875rem;\n color: var(--firma-muted);\n }\n\n .field {\n display: flex;\n flex-direction: column;\n gap: 6px;\n margin-bottom: 12px;\n }\n\n .field label {\n font-size: 0.82rem;\n font-weight: 600;\n color: var(--firma-text);\n }\n\n input[type=\"text\"],\n input[type=\"password\"],\n input[type=\"file\"] {\n width: 100%;\n padding: 8px 10px;\n border: 1px solid var(--firma-border);\n border-radius: 7px;\n font-size: 0.875rem;\n background: #fff;\n color: var(--firma-text);\n }\n\n input:focus {\n outline: 2px solid rgba(29, 78, 216, 0.25);\n border-color: var(--firma-primary);\n }\n\n .row {\n display: flex;\n gap: 10px;\n flex-wrap: wrap;\n align-items: center;\n }\n\n .btn {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n gap: 6px;\n padding: 8px 14px;\n border-radius: 7px;\n font-size: 0.875rem;\n font-weight: 600;\n cursor: pointer;\n border: 1px solid transparent;\n transition: background 0.15s, opacity 0.15s;\n }\n\n .btn:disabled {\n opacity: 0.55;\n cursor: not-allowed;\n }\n\n .btn-primary {\n background: var(--firma-primary);\n color: #fff;\n }\n\n .btn-primary:hover:not(:disabled) {\n background: var(--firma-primary-hover);\n }\n\n .btn-secondary {\n background: var(--firma-surface);\n color: var(--firma-text);\n border-color: var(--firma-border);\n }\n\n .btn-secondary:hover:not(:disabled) {\n background: #e2e8f0;\n }\n\n .alert {\n padding: 10px 12px;\n border-radius: 7px;\n font-size: 0.85rem;\n margin-top: 10px;\n }\n\n .alert-success {\n background: var(--firma-success-bg);\n color: var(--firma-success);\n border: 1px solid #86efac;\n }\n\n .alert-error {\n background: var(--firma-error-bg);\n color: var(--firma-error);\n border: 1px solid #fca5a5;\n }\n\n .alert-warn {\n background: var(--firma-warn-bg);\n color: var(--firma-warn);\n border: 1px solid #fde047;\n }\n\n .kv-grid {\n display: grid;\n grid-template-columns: repeat(auto-fit, minmax(190px, 1fr));\n gap: 8px 14px;\n margin-top: 10px;\n padding: 10px;\n background: var(--firma-surface);\n border-radius: 7px;\n border: 1px solid #e2e8f0;\n font-size: 0.82rem;\n }\n\n .kv-item span {\n display: block;\n font-size: 0.72rem;\n color: var(--firma-muted);\n text-transform: uppercase;\n letter-spacing: 0.03em;\n }\n\n .kv-item strong {\n word-break: break-word;\n }\n\n .badge {\n display: inline-block;\n padding: 2px 8px;\n border-radius: 999px;\n font-size: 0.75rem;\n font-weight: 700;\n }\n\n .badge-ok {\n background: var(--firma-success-bg);\n color: var(--firma-success);\n }\n\n .badge-bad {\n background: var(--firma-error-bg);\n color: var(--firma-error);\n }\n";
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { default as forge } from 'node-forge';
|
|
2
|
+
import { CertificateInfo, CertificateSubject, SignerAdapter, ValidationResult } from '../types/index.ts';
|
|
3
|
+
export declare function uint8ToBinaryString(bytes: Uint8Array): string;
|
|
4
|
+
export declare function binaryStringToUint8(str: string): Uint8Array;
|
|
5
|
+
export declare function extractSubject(attrs: forge.pki.CertificateField[]): CertificateSubject;
|
|
6
|
+
export declare function buildCertificateInfo(cert: forge.pki.Certificate, referenceDate?: Date): CertificateInfo;
|
|
7
|
+
export interface ParsedP12 {
|
|
8
|
+
privateKey: forge.pki.rsa.PrivateKey;
|
|
9
|
+
certificate: forge.pki.Certificate;
|
|
10
|
+
caChain: forge.pki.Certificate[];
|
|
11
|
+
certificateInfo: CertificateInfo;
|
|
12
|
+
}
|
|
13
|
+
export declare function parseP12(p12Bytes: ArrayBuffer | Uint8Array, password: string): ParsedP12;
|
|
14
|
+
export declare function validateP12(p12Bytes: ArrayBuffer | Uint8Array, password: string): ValidationResult;
|
|
15
|
+
export declare class P12SignerAdapter implements SignerAdapter {
|
|
16
|
+
readonly kind: "p12";
|
|
17
|
+
private readonly parsed;
|
|
18
|
+
private constructor();
|
|
19
|
+
static fromBytes(p12Bytes: ArrayBuffer | Uint8Array, password: string): P12SignerAdapter;
|
|
20
|
+
static fromFile(file: Blob, password: string): Promise<P12SignerAdapter>;
|
|
21
|
+
getCertificateInfo(): Promise<CertificateInfo>;
|
|
22
|
+
signPkcs7Detached(contentBytes: Uint8Array, signingTime?: Date): Promise<Uint8Array>;
|
|
23
|
+
}
|