@erseco/autofirma-client 1.9.3-canary.20260802075844.ee23ef2
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/LICENSE +255 -0
- package/README.md +303 -0
- package/dist/autoscript-adapter.d.ts +30 -0
- package/dist/base64.d.ts +6 -0
- package/dist/client.d.ts +80 -0
- package/dist/errors.d.ts +26 -0
- package/dist/index.cjs +380 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +348 -0
- package/dist/index.js.map +1 -0
- package/dist/loader.d.ts +33 -0
- package/dist/parameters.d.ts +27 -0
- package/dist/testing/index.cjs +62 -0
- package/dist/testing/index.cjs.map +1 -0
- package/dist/testing/index.d.ts +16 -0
- package/dist/testing/index.js +37 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/types.d.ts +100 -0
- package/package.json +78 -0
- package/vendor/autoscript.js +5441 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
GNU GENERAL PUBLIC LICENSE
|
|
2
|
+
Version 2, June 1991
|
|
3
|
+
|
|
4
|
+
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
|
|
5
|
+
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
|
6
|
+
|
|
7
|
+
Everyone is permitted to copy and distribute verbatim copies of this license
|
|
8
|
+
document, but changing it is not allowed.
|
|
9
|
+
|
|
10
|
+
Preamble
|
|
11
|
+
|
|
12
|
+
The licenses for most software are designed to take away your freedom to share
|
|
13
|
+
and change it. By contrast, the GNU General Public License is intended to
|
|
14
|
+
guarantee your freedom to share and change free software--to make sure the
|
|
15
|
+
software is free for all its users. This General Public License applies to most
|
|
16
|
+
of the Free Software Foundation's software and to any other program whose
|
|
17
|
+
authors commit to using it. (Some other Free Software Foundation software is
|
|
18
|
+
covered by the GNU Lesser General Public License instead.) You can apply it to
|
|
19
|
+
your programs, too.
|
|
20
|
+
|
|
21
|
+
When we speak of free software, we are referring to freedom, not price. Our
|
|
22
|
+
General Public Licenses are designed to make sure that you have the freedom to
|
|
23
|
+
distribute copies of free software (and charge for this service if you wish),
|
|
24
|
+
that you receive source code or can get it if you want it, that you can change
|
|
25
|
+
the software or use pieces of it in new free programs; and that you know you can
|
|
26
|
+
do these things.
|
|
27
|
+
|
|
28
|
+
To protect your rights, we need to make restrictions that forbid anyone to deny
|
|
29
|
+
you these rights or to ask you to surrender the rights. These restrictions
|
|
30
|
+
translate to certain responsibilities for you if you distribute copies of the
|
|
31
|
+
software, or if you modify it.
|
|
32
|
+
|
|
33
|
+
For example, if you distribute copies of such a program, whether gratis or for
|
|
34
|
+
a fee, you must give the recipients all the rights that you have. You must make
|
|
35
|
+
sure that they, too, receive or can get the source code. And you must show them
|
|
36
|
+
these terms so they know their rights.
|
|
37
|
+
|
|
38
|
+
We protect your rights with two steps: (1) copyright the software, and (2) offer
|
|
39
|
+
you this license which gives you legal permission to copy, distribute and/or
|
|
40
|
+
modify the software.
|
|
41
|
+
|
|
42
|
+
Also, for each author's protection and ours, we want to make certain that
|
|
43
|
+
everyone understands that there is no warranty for this free software. If the
|
|
44
|
+
software is modified by someone else and passed on, we want its recipients to
|
|
45
|
+
know that what they have is not the original, so that any problems introduced by
|
|
46
|
+
others will not reflect on the original authors' reputations.
|
|
47
|
+
|
|
48
|
+
Finally, any free program is threatened constantly by software patents. We wish
|
|
49
|
+
to avoid the danger that redistributors of a free program will individually
|
|
50
|
+
obtain patent licenses, in effect making the program proprietary. To prevent
|
|
51
|
+
this, we have made it clear that any patent must be licensed for everyone's free
|
|
52
|
+
use or not licensed at all.
|
|
53
|
+
|
|
54
|
+
The precise terms and conditions for copying, distribution and modification
|
|
55
|
+
follow.
|
|
56
|
+
|
|
57
|
+
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
|
58
|
+
|
|
59
|
+
0. This License applies to any program or other work which contains a notice
|
|
60
|
+
placed by the copyright holder saying it may be distributed under the terms of
|
|
61
|
+
this General Public License. The "Program", below, refers to any such program or
|
|
62
|
+
work, and a "work based on the Program" means either the Program or any
|
|
63
|
+
derivative work under copyright law: that is to say, a work containing the
|
|
64
|
+
Program or a portion of it, either verbatim or with modifications and/or
|
|
65
|
+
translated into another language. (Hereinafter, translation is included without
|
|
66
|
+
limitation in the term "modification".) Each licensee is addressed as "you".
|
|
67
|
+
|
|
68
|
+
Activities other than copying, distribution and modification are not covered by
|
|
69
|
+
this License; they are outside its scope. The act of running the Program is not
|
|
70
|
+
restricted, and the output from the Program is covered only if its contents
|
|
71
|
+
constitute a work based on the Program (independent of having been made by
|
|
72
|
+
running the Program). Whether that is true depends on what the Program does.
|
|
73
|
+
|
|
74
|
+
1. You may copy and distribute verbatim copies of the Program's source code as
|
|
75
|
+
you receive it, in any medium, provided that you conspicuously and appropriately
|
|
76
|
+
publish on each copy an appropriate copyright notice and disclaimer of warranty;
|
|
77
|
+
keep intact all the notices that refer to this License and to the absence of any
|
|
78
|
+
warranty; and give any other recipients of the Program a copy of this License
|
|
79
|
+
along with the Program.
|
|
80
|
+
|
|
81
|
+
You may charge a fee for the physical act of transferring a copy, and you may at
|
|
82
|
+
your option offer warranty protection in exchange for a fee.
|
|
83
|
+
|
|
84
|
+
2. You may modify your copy or copies of the Program or any portion of it, thus
|
|
85
|
+
forming a work based on the Program, and copy and distribute such modifications
|
|
86
|
+
or work under the terms of Section 1 above, provided that you also meet all of
|
|
87
|
+
these conditions:
|
|
88
|
+
|
|
89
|
+
a) You must cause the modified files to carry prominent notices stating that
|
|
90
|
+
you changed the files and the date of any change.
|
|
91
|
+
|
|
92
|
+
b) You must cause any work that you distribute or publish, that in whole or in
|
|
93
|
+
part contains or is derived from the Program or any part thereof, to be licensed
|
|
94
|
+
as a whole at no charge to all third parties under the terms of this License.
|
|
95
|
+
|
|
96
|
+
c) If the modified program normally reads commands interactively when run, you
|
|
97
|
+
must cause it, when started running for such interactive use in the most ordinary
|
|
98
|
+
way, to print or display an announcement including an appropriate copyright
|
|
99
|
+
notice and a notice that there is no warranty (or else, saying that you provide a
|
|
100
|
+
warranty) and that users may redistribute the program under these conditions,
|
|
101
|
+
and telling the user how to view a copy of this License. (Exception: if the
|
|
102
|
+
Program itself is interactive but does not normally print such an announcement,
|
|
103
|
+
your work based on the Program is not required to print an announcement.)
|
|
104
|
+
|
|
105
|
+
These requirements apply to the modified work as a whole. If identifiable
|
|
106
|
+
sections of that work are not derived from the Program, and can be reasonably
|
|
107
|
+
considered independent and separate works in themselves, then this License, and
|
|
108
|
+
its terms, do not apply to those sections when you distribute them as separate
|
|
109
|
+
works. But when you distribute the same sections as part of a whole which is a
|
|
110
|
+
work based on the Program, the distribution of the whole must be on the terms of
|
|
111
|
+
this License, whose permissions for other licensees extend to the entire whole,
|
|
112
|
+
and thus to each and every part regardless of who wrote it.
|
|
113
|
+
|
|
114
|
+
Thus, it is not the intent of this section to claim rights or contest your rights
|
|
115
|
+
to work written entirely by you; rather, the intent is to exercise the right to
|
|
116
|
+
control the distribution of derivative or collective works based on the Program.
|
|
117
|
+
|
|
118
|
+
In addition, mere aggregation of another work not based on the Program with the
|
|
119
|
+
Program (or with a work based on the Program) on a volume of a storage or
|
|
120
|
+
distribution medium does not bring the other work under the scope of this
|
|
121
|
+
License.
|
|
122
|
+
|
|
123
|
+
3. You may copy and distribute the Program (or a work based on it, under Section
|
|
124
|
+
2) in object code or executable form under the terms of Sections 1 and 2 above
|
|
125
|
+
provided that you also do one of the following:
|
|
126
|
+
|
|
127
|
+
a) Accompany it with the complete corresponding machine-readable source code,
|
|
128
|
+
which must be distributed under the terms of Sections 1 and 2 above on a medium
|
|
129
|
+
customarily used for software interchange; or,
|
|
130
|
+
|
|
131
|
+
b) Accompany it with a written offer, valid for at least three years, to give any
|
|
132
|
+
third party, for a charge no more than your cost of physically performing source
|
|
133
|
+
distribution, a complete machine-readable copy of the corresponding source code,
|
|
134
|
+
to be distributed under the terms of Sections 1 and 2 above on a medium
|
|
135
|
+
customarily used for software interchange; or,
|
|
136
|
+
|
|
137
|
+
c) Accompany it with the information you received as to the offer to distribute
|
|
138
|
+
corresponding source code. (This alternative is allowed only for noncommercial
|
|
139
|
+
distribution and only if you received the program in object code or executable
|
|
140
|
+
form with such an offer, in accord with Subsection b above.)
|
|
141
|
+
|
|
142
|
+
The source code for a work means the preferred form of the work for making
|
|
143
|
+
modifications to it. For an executable work, complete source code means all the
|
|
144
|
+
source code for all modules it contains, plus any associated interface
|
|
145
|
+
definition files, plus the scripts used to control compilation and installation
|
|
146
|
+
of the executable. However, as a special exception, the source code distributed
|
|
147
|
+
need not include anything that is normally distributed (in either source or
|
|
148
|
+
binary form) with the major components (compiler, kernel, and so on) of the
|
|
149
|
+
operating system on which the executable runs, unless that component itself
|
|
150
|
+
accompanies the executable.
|
|
151
|
+
|
|
152
|
+
If distribution of executable or object code is made by offering access to copy
|
|
153
|
+
from a designated place, then offering equivalent access to copy the source code
|
|
154
|
+
from the same place counts as distribution of the source code, even though third
|
|
155
|
+
parties are not compelled to copy the source along with the object code.
|
|
156
|
+
|
|
157
|
+
4. You may not copy, modify, sublicense, or distribute the Program except as
|
|
158
|
+
expressly provided under this License. Any attempt otherwise to copy, modify,
|
|
159
|
+
sublicense or distribute the Program is void, and will automatically terminate
|
|
160
|
+
your rights under this License. However, parties who have received copies, or
|
|
161
|
+
rights, from you under this License will not have their licenses terminated so
|
|
162
|
+
long as such parties remain in full compliance.
|
|
163
|
+
|
|
164
|
+
5. You are not required to accept this License, since you have not signed it.
|
|
165
|
+
However, nothing else grants you permission to modify or distribute the Program
|
|
166
|
+
or its derivative works. These actions are prohibited by law if you do not accept
|
|
167
|
+
this License. Therefore, by modifying or distributing the Program (or any work
|
|
168
|
+
based on the Program), you indicate your acceptance of this License to do so, and
|
|
169
|
+
all its terms and conditions for copying, distributing or modifying the Program
|
|
170
|
+
or works based on it.
|
|
171
|
+
|
|
172
|
+
6. Each time you redistribute the Program (or any work based on the Program),
|
|
173
|
+
the recipient automatically receives a license from the original licensor to
|
|
174
|
+
copy, distribute or modify the Program subject to these terms and conditions.
|
|
175
|
+
You may not impose any further restrictions on the recipients' exercise of the
|
|
176
|
+
rights granted herein. You are not responsible for enforcing compliance by third
|
|
177
|
+
parties to this License.
|
|
178
|
+
|
|
179
|
+
7. If, as a consequence of a court judgment or allegation of patent infringement
|
|
180
|
+
or for any other reason (not limited to patent issues), conditions are imposed on
|
|
181
|
+
you (whether by court order, agreement or otherwise) that contradict the
|
|
182
|
+
conditions of this License, they do not excuse you from the conditions of this
|
|
183
|
+
License. If you cannot distribute so as to satisfy simultaneously your
|
|
184
|
+
obligations under this License and any other pertinent obligations, then as a
|
|
185
|
+
consequence you may not distribute the Program at all. For example, if a patent
|
|
186
|
+
license would not permit royalty-free redistribution of the Program by all those
|
|
187
|
+
who receive copies directly or indirectly through you, then the only way you
|
|
188
|
+
could satisfy both it and this License would be to refrain entirely from
|
|
189
|
+
distribution of the Program.
|
|
190
|
+
|
|
191
|
+
If any portion of this section is held invalid or unenforceable under any
|
|
192
|
+
particular circumstance, the balance of the section is intended to apply and the
|
|
193
|
+
section as a whole is intended to apply in other circumstances.
|
|
194
|
+
|
|
195
|
+
It is not the purpose of this section to induce you to infringe any patents or
|
|
196
|
+
other property right claims or to contest validity of any such claims; this
|
|
197
|
+
section has the sole purpose of protecting the integrity of the free software
|
|
198
|
+
distribution system, which is implemented by public license practices. Many
|
|
199
|
+
people have made generous contributions to the wide range of software
|
|
200
|
+
distributed through that system in reliance on consistent application of that
|
|
201
|
+
system; it is up to the author/donor to decide if he or she is willing to
|
|
202
|
+
distribute software through any other system and a licensee cannot impose that
|
|
203
|
+
choice.
|
|
204
|
+
|
|
205
|
+
This section is intended to make thoroughly clear what is believed to be a
|
|
206
|
+
consequence of the rest of this License.
|
|
207
|
+
|
|
208
|
+
8. If the distribution and/or use of the Program is restricted in certain
|
|
209
|
+
countries either by patents or by copyrighted interfaces, the original copyright
|
|
210
|
+
holder who places the Program under this License may add an explicit geographical
|
|
211
|
+
distribution limitation excluding those countries, so that distribution is
|
|
212
|
+
permitted only in or among countries not thus excluded. In such case, this
|
|
213
|
+
License incorporates the limitation as if written in the body of this License.
|
|
214
|
+
|
|
215
|
+
9. The Free Software Foundation may publish revised and/or new versions of the
|
|
216
|
+
General Public License from time to time. Such new versions will be similar in
|
|
217
|
+
spirit to the present version, but may differ in detail to address new problems
|
|
218
|
+
or concerns.
|
|
219
|
+
|
|
220
|
+
Each version is given a distinguishing version number. If the Program specifies
|
|
221
|
+
a version number of this License which applies to it and "any later version", you
|
|
222
|
+
have the option of following the terms and conditions either of that version or
|
|
223
|
+
of any later version published by the Free Software Foundation. If the Program
|
|
224
|
+
does not specify a version number of this License, you may choose any version
|
|
225
|
+
ever published by the Free Software Foundation.
|
|
226
|
+
|
|
227
|
+
10. If you wish to incorporate parts of the Program into other free programs
|
|
228
|
+
whose distribution conditions are different, write to the author to ask for
|
|
229
|
+
permission. For software which is copyrighted by the Free Software Foundation,
|
|
230
|
+
write to the Free Software Foundation; we sometimes make exceptions for this.
|
|
231
|
+
Our decision will be guided by the two goals of preserving the free status of all
|
|
232
|
+
derivatives of our free software and of promoting the sharing and reuse of
|
|
233
|
+
software generally.
|
|
234
|
+
|
|
235
|
+
NO WARRANTY
|
|
236
|
+
|
|
237
|
+
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE
|
|
238
|
+
PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED
|
|
239
|
+
IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS"
|
|
240
|
+
WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT
|
|
241
|
+
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
|
|
242
|
+
PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
|
|
243
|
+
PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
|
244
|
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
|
245
|
+
|
|
246
|
+
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL
|
|
247
|
+
ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE
|
|
248
|
+
PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL,
|
|
249
|
+
SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY
|
|
250
|
+
TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
|
|
251
|
+
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF
|
|
252
|
+
THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER
|
|
253
|
+
PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
|
254
|
+
|
|
255
|
+
END OF TERMS AND CONDITIONS
|
package/README.md
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
# AutoFirma Client
|
|
2
|
+
|
|
3
|
+
Cliente TypeScript para usar la API oficial **AutoScript** con promesas,
|
|
4
|
+
tipado estricto, conversión de datos, errores normalizados y dobles de prueba.
|
|
5
|
+
|
|
6
|
+
> [!IMPORTANT]
|
|
7
|
+
> Este proyecto no pertenece al Gobierno de España, no incluye AutoFirma y no
|
|
8
|
+
> sustituye la validación criptográfica en servidor.
|
|
9
|
+
|
|
10
|
+
## Estado
|
|
11
|
+
|
|
12
|
+
El proyecto está en una fase inicial. La versión del paquete refleja el tag
|
|
13
|
+
del repositorio oficial `ctt-gob-es/clienteafirma`, no una línea propia de
|
|
14
|
+
AutoScript (ver [ADR-0004](docs/arquitectura/adr/ADR-0004-versionado-en-espejo.md)).
|
|
15
|
+
La versión de AutoScript realmente empaquetada, y sus constantes, son las que
|
|
16
|
+
registra `autoscript.lock.json`, la única fuente de verdad al respecto: hoy
|
|
17
|
+
fija el tag `v1.9.2`, que corresponde a AutoScript `1.9.0`. Consulta la
|
|
18
|
+
política de compatibilidad en
|
|
19
|
+
[AGENTS.md](AGENTS.md#compatibilidad-y-versiones) antes de actualizar.
|
|
20
|
+
|
|
21
|
+
## Instalación
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
npm install @erseco/autofirma-client
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
El paquete incluye una copia fijada y verificada por hash de `autoscript.js`
|
|
28
|
+
en `vendor/autoscript.js`; no hace falta descargarla aparte. Ese fichero no es
|
|
29
|
+
un módulo: es un script clásico que no declara UMD ni exporta nada, sino que
|
|
30
|
+
confía en que su `var` de nivel superior se convierta en global. Por eso no
|
|
31
|
+
puede importarse con un empaquetador y hay que insertarlo como etiqueta
|
|
32
|
+
`<script>`. `loadAutoScript(url)` hace justo eso: sirve `vendor/autoscript.js`
|
|
33
|
+
desde tu propia infraestructura estática y pásale esa URL.
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
import { AutoFirmaClient, loadAutoScript } from "@erseco/autofirma-client";
|
|
37
|
+
|
|
38
|
+
const autoScript = await loadAutoScript("/vendor/autoscript.js");
|
|
39
|
+
const client = new AutoFirmaClient({ autoScript });
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
### Si lo sirves desde otro origen
|
|
43
|
+
|
|
44
|
+
El paquete fija `autoscript.js` por sha256 (ver
|
|
45
|
+
[ADR-0005](docs/arquitectura/adr/ADR-0005-empaquetar-autoscript.md)), pero esa
|
|
46
|
+
garantía termina donde empieza la red: si lo sirves desde un CDN o un dominio de
|
|
47
|
+
estáticos, quien controle ese origen controla el fichero. `loadAutoScript`
|
|
48
|
+
acepta los atributos de Subresource Integrity para recuperarla.
|
|
49
|
+
|
|
50
|
+
```ts
|
|
51
|
+
const autoScript = await loadAutoScript(
|
|
52
|
+
"https://cdn.example.org/autoscript.js",
|
|
53
|
+
{
|
|
54
|
+
integrity: "sha256-…",
|
|
55
|
+
crossOrigin: "anonymous",
|
|
56
|
+
},
|
|
57
|
+
);
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
`autoscript.lock.json` guarda la huella en hexadecimal y SRI la quiere en base64
|
|
61
|
+
con prefijo `sha256-`:
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
printf 'sha256-%s\n' "$(node -p "require('./autoscript.lock.json').sha256" \
|
|
65
|
+
| xxd -r -p | base64)"
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Uso
|
|
69
|
+
|
|
70
|
+
```ts
|
|
71
|
+
import { AutoFirmaClient } from "@erseco/autofirma-client";
|
|
72
|
+
|
|
73
|
+
const client = new AutoFirmaClient();
|
|
74
|
+
client.initialize();
|
|
75
|
+
|
|
76
|
+
const file = document.querySelector<HTMLInputElement>("#document")?.files?.[0];
|
|
77
|
+
|
|
78
|
+
if (!file) {
|
|
79
|
+
throw new Error("Selecciona un documento.");
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const result = await client.sign({
|
|
83
|
+
data: file,
|
|
84
|
+
format: "PAdES",
|
|
85
|
+
parameters: {
|
|
86
|
+
mode: "implicit",
|
|
87
|
+
signingReason: "Aprobación del documento",
|
|
88
|
+
},
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
console.log(result.signature);
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Las cadenas se interpretan como Base64. Para datos sin codificar usa `File`,
|
|
95
|
+
`Blob`, `ArrayBuffer` o `Uint8Array`.
|
|
96
|
+
|
|
97
|
+
### Servicios intermedios
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
const client = new AutoFirmaClient({
|
|
101
|
+
storageUrl: "https://example.org/storage",
|
|
102
|
+
retrieveUrl: "https://example.org/retrieve",
|
|
103
|
+
});
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
Estos servicios pertenecen al protocolo de transporte de AutoFirma. No son un
|
|
107
|
+
repositorio documental.
|
|
108
|
+
|
|
109
|
+
### Guardar ficheros y comprobar el reloj
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
await client.saveDataToFile({
|
|
113
|
+
data: base64Data,
|
|
114
|
+
title: "Guardar firma",
|
|
115
|
+
filename: "firma",
|
|
116
|
+
extension: "csig",
|
|
117
|
+
description: "Firma electrónica (*.csig)",
|
|
118
|
+
});
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
`saveDataToFile` pide a AutoFirma que guarde datos en un fichero elegido por
|
|
122
|
+
la persona usuaria; rechaza si la versión fijada de AutoScript no expone la
|
|
123
|
+
operación.
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
await client.checkTime({ checkType: "CT_RECOMMENDED" });
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
`checkTime` no informa del resultado a través de la promesa que devuelve:
|
|
130
|
+
AutoScript hace una petición **síncrona** que bloquea la página mientras
|
|
131
|
+
espera respuesta y solo avisa de un desfase con un `alert()` nativo;
|
|
132
|
+
cualquier error (incluido uno de red) se silencia. Con
|
|
133
|
+
`checkType: "CT_OBLIGATORY"` puede además impedir en silencio que una llamada
|
|
134
|
+
posterior a `initialize()` cargue AutoFirma, así que el orden de las llamadas
|
|
135
|
+
importa. El docblock de `checkTime` en [`src/client.ts`](src/client.ts)
|
|
136
|
+
documenta el detalle completo.
|
|
137
|
+
|
|
138
|
+
### Ficheros de ejemplo
|
|
139
|
+
|
|
140
|
+
Para probar una integración local sin usar documentos reales:
|
|
141
|
+
|
|
142
|
+
- [Texto para CAdES](docs/ejemplos/files/ejemplo.txt)
|
|
143
|
+
- [XML para XAdES](docs/ejemplos/files/ejemplo.xml)
|
|
144
|
+
- [PDF para PAdES](docs/ejemplos/files/ejemplo.pdf)
|
|
145
|
+
|
|
146
|
+
Contienen datos ficticios. Una firma generada con ellos no demuestra que la
|
|
147
|
+
integración valide certificados, cadenas de confianza o revocación.
|
|
148
|
+
|
|
149
|
+
## Errores
|
|
150
|
+
|
|
151
|
+
Todo fallo llega como `AutoFirmaError`, que conserva intactos `nativeType` y
|
|
152
|
+
`nativeMessage` tal y como los devolvió AutoFirma. El campo `code` clasifica los
|
|
153
|
+
casos sobre los que se puede actuar:
|
|
154
|
+
|
|
155
|
+
| `code` | Cuándo |
|
|
156
|
+
| ------------------------ | ---------------------------------------------------------------------- |
|
|
157
|
+
| `USER_CANCELLED` | La persona usuaria canceló la operación o la selección de certificado. |
|
|
158
|
+
| `DATA_TOO_LARGE` | El fichero excede la memoria disponible de AutoFirma. |
|
|
159
|
+
| `NATIVE_TIMEOUT` | AutoFirma no respondió: no está instalada o no llegó a abrirse. |
|
|
160
|
+
| `NATIVE_ERROR` | Cualquier otro fallo de AutoFirma, incluidos sus códigos `SAF_xx`. |
|
|
161
|
+
| `UNSUPPORTED_OPERATION` | La versión fijada de AutoScript no expone esa operación. |
|
|
162
|
+
| `AUTOSCRIPT_UNAVAILABLE` | `window.AutoScript` no existe o no es la API de AutoScript. |
|
|
163
|
+
|
|
164
|
+
No existe un tamaño máximo declarado en ninguna parte. El fichero viaja entero
|
|
165
|
+
en una sola pieza codificado en Base64, que lo agranda un tercio, y el límite
|
|
166
|
+
real es la memoria de la aplicación nativa: al superarla responde `MEMORY_ERROR`
|
|
167
|
+
y el cliente lo entrega como `DATA_TOO_LARGE`.
|
|
168
|
+
|
|
169
|
+
## Qué aporta
|
|
170
|
+
|
|
171
|
+
- API basada en `Promise`.
|
|
172
|
+
- Tipos para PAdES, CAdES, XAdES y FacturaE.
|
|
173
|
+
- Entradas `Blob`, `File`, `ArrayBuffer`, `Uint8Array` y Base64.
|
|
174
|
+
- Serialización segura de parámetros en el formato de AutoScript.
|
|
175
|
+
- Errores normalizados sin perder el tipo y mensaje nativos.
|
|
176
|
+
- `MockAutoFirmaClient` para pruebas de aplicaciones consumidoras.
|
|
177
|
+
- Acceso a `client.raw` para funciones oficiales no cubiertas todavía.
|
|
178
|
+
|
|
179
|
+
## Seguridad y privacidad
|
|
180
|
+
|
|
181
|
+
La librería transforma los datos en memoria y los entrega al objeto AutoScript
|
|
182
|
+
de la página. **No incluye telemetría, backend, cookies ni almacenamiento**. Que
|
|
183
|
+
un documento salga o no del equipo depende de la configuración de AutoScript,
|
|
184
|
+
de los servicios intermedios configurados por la aplicación y del código de la
|
|
185
|
+
aplicación consumidora.
|
|
186
|
+
|
|
187
|
+
No confíes en los datos devueltos por el navegador para decisiones jurídicas o
|
|
188
|
+
de autorización. Valida en servidor la firma, la integridad del documento, el
|
|
189
|
+
certificado, la cadena de confianza y, cuando proceda, la revocación.
|
|
190
|
+
|
|
191
|
+
## Desarrollo
|
|
192
|
+
|
|
193
|
+
```bash
|
|
194
|
+
make install
|
|
195
|
+
make check
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
La CI ejecuta formato, TypeScript, tests con cobertura y construcción en Node
|
|
199
|
+
20, 22 y 24.
|
|
200
|
+
|
|
201
|
+
### Symlinks en Windows
|
|
202
|
+
|
|
203
|
+
Los procedimientos recurrentes del proyecto viven como skills en
|
|
204
|
+
`.agents/skills/`, la ruta que leen Codex y Grok. Como Claude Code y GitHub
|
|
205
|
+
Copilot buscan en `.claude/skills/` y `.github/skills/`, esos dos directorios
|
|
206
|
+
contienen enlaces simbólicos a los mismos ficheros en vez de copias.
|
|
207
|
+
|
|
208
|
+
Git guarda esos enlaces como tales, pero **en Windows solo los recrea al clonar
|
|
209
|
+
si el soporte está activado**; de lo contrario aparecen como ficheros de texto
|
|
210
|
+
que contienen la ruta de destino, y ni Claude Code ni Copilot encontrarán las
|
|
211
|
+
skills. La copia real de `.agents/skills/` sigue funcionando en cualquier caso.
|
|
212
|
+
|
|
213
|
+
```bash
|
|
214
|
+
git config --global core.symlinks true
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
Hay que fijarlo **antes de clonar**: en un clon ya hecho no basta con activarlo,
|
|
218
|
+
hay que volver a clonar o restaurar esas rutas. Además, Windows exige modo de
|
|
219
|
+
desarrollador o privilegios de administrador para crear enlaces simbólicos.
|
|
220
|
+
|
|
221
|
+
> [!NOTE]
|
|
222
|
+
> `prepack` (y por tanto `npm pack` y `npm publish`) ejecuta
|
|
223
|
+
> `scripts/vendor-autoscript.ts` directamente con `node`, que necesita el
|
|
224
|
+
> soporte nativo de tipos activado por defecto (Node ≥22.18 o ≥23.6; en
|
|
225
|
+
> versiones anteriores de la línea 22 existe solo tras la flag
|
|
226
|
+
> `--experimental-strip-types`). Es intencional: la librería en sí es
|
|
227
|
+
> compatible con Node 20 (`engines.node`), pero los scripts de mantenimiento
|
|
228
|
+
> no. Empaquetar con una versión de Node anterior a esa falla con un error de
|
|
229
|
+
> sintaxis poco claro; usa Node 22.18 o superior para generar el tarball o
|
|
230
|
+
> publicar.
|
|
231
|
+
|
|
232
|
+
Los objetivos rápidos son:
|
|
233
|
+
|
|
234
|
+
- `make lint`: comprueba Prettier y TypeScript.
|
|
235
|
+
- `make fix`: aplica Prettier.
|
|
236
|
+
- `make test`: ejecuta Vitest con cobertura.
|
|
237
|
+
- `make build`: genera ESM, CommonJS y tipos.
|
|
238
|
+
- `make check`: ejecuta lint, tests y build.
|
|
239
|
+
|
|
240
|
+
## Publicación
|
|
241
|
+
|
|
242
|
+
Cada tag `v*` ejecuta `.github/workflows/release.yml`: comprueba que el tag
|
|
243
|
+
coincide con la versión de `package.json` y con el tag fijado en
|
|
244
|
+
`autoscript.lock.json`, repite todos los controles, verifica que el tarball
|
|
245
|
+
generado contiene `vendor/autoscript.js` con el `sha256` que registra el
|
|
246
|
+
lock y publica ese mismo tarball ya verificado (`npm publish artifacts/*.tgz`,
|
|
247
|
+
sin volver a empaquetar) en tres sitios: el registro público de npm, el gestor
|
|
248
|
+
de paquetes de GitHub y GitHub Releases.
|
|
249
|
+
|
|
250
|
+
La publicación en npm usa **npm Trusted Publishing con OIDC**, sin tokens. Antes
|
|
251
|
+
de la primera publicación hay que registrar en npm el repositorio
|
|
252
|
+
`erseco/autofirma-client` y los workflows `release.yml` y `canary.yml` como
|
|
253
|
+
publicadores de confianza.
|
|
254
|
+
|
|
255
|
+
### Canal canary
|
|
256
|
+
|
|
257
|
+
Cada push a `main` que pueda cambiar el paquete ejecuta
|
|
258
|
+
`.github/workflows/canary.yml`, que repite los mismos controles y la misma
|
|
259
|
+
verificación del tarball y publica bajo el dist-tag **`canary`**:
|
|
260
|
+
|
|
261
|
+
```bash
|
|
262
|
+
npm install @erseco/autofirma-client@canary
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
La versión se calcula sobre el **patch siguiente** al de `package.json`, no
|
|
266
|
+
sobre el actual: una preversión ordena por debajo de su versión, así que
|
|
267
|
+
`1.9.2-canary.x` quedaría por detrás de la `1.9.2` ya publicada pese a contener
|
|
268
|
+
más código. Con `1.9.3-canary.<sello>.<sha>` ordena por encima de `1.9.2`, por
|
|
269
|
+
debajo de un futuro `1.9.3`, y no ocupa ese número.
|
|
270
|
+
|
|
271
|
+
`latest` queda reservado a los tags de release, y un rango como `^1.9.2` no
|
|
272
|
+
acepta preversiones, así que quien instale de la forma habitual nunca recibirá
|
|
273
|
+
un canary sin pedirlo. Este canal es además la única vía para publicar
|
|
274
|
+
correcciones del wrapper entre dos tags de AutoFirma, que ADR-0004 registró como
|
|
275
|
+
la contrapartida del versionado en espejo.
|
|
276
|
+
|
|
277
|
+
Mientras no exista ninguna versión estable publicada, `npm install
|
|
278
|
+
@erseco/autofirma-client` sin sufijo no resuelve, porque no hay dist-tag
|
|
279
|
+
`latest`: hasta el primer tag hay que instalar con `@canary`.
|
|
280
|
+
|
|
281
|
+
GitHub Packages no admite Trusted Publishing, así que ese paso se autentica con
|
|
282
|
+
el `GITHUB_TOKEN` efímero del propio workflow y necesita el permiso
|
|
283
|
+
`packages: write`. Para instalar desde ahí hay que apuntar el ámbito `@erseco`
|
|
284
|
+
a ese registro y autenticarse, porque incluso los paquetes públicos de GitHub
|
|
285
|
+
Packages exigen credenciales para descargarse:
|
|
286
|
+
|
|
287
|
+
```
|
|
288
|
+
@erseco:registry=https://npm.pkg.github.com
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
Quien no quiera ese paso adicional tiene el paquete en npm sin autenticación.
|
|
292
|
+
|
|
293
|
+
## Documentación
|
|
294
|
+
|
|
295
|
+
Una página con una demo ejecutable se publica en
|
|
296
|
+
<https://erseco.github.io/autofirma-client/>, generada con
|
|
297
|
+
`npm run build:web` a partir de `web/`. Las decisiones de arquitectura (ADR y
|
|
298
|
+
SDD) están en [`docs/arquitectura/`](docs/arquitectura/).
|
|
299
|
+
|
|
300
|
+
## Licencia
|
|
301
|
+
|
|
302
|
+
GPL-2.0-or-later. AutoFirma y AutoScript conservan sus propias licencias y
|
|
303
|
+
marcas.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { AutoScriptApi, SignatureOperation, SignResult } from "./types.js";
|
|
2
|
+
declare global {
|
|
3
|
+
interface Window {
|
|
4
|
+
AutoScript?: AutoScriptApi;
|
|
5
|
+
}
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Comprueba que un candidato sea la API de AutoScript y no cualquier otra cosa
|
|
9
|
+
* que ocupe el mismo nombre global.
|
|
10
|
+
*
|
|
11
|
+
* `window.AutoScript` no requiere ejecutar JavaScript para existir: un elemento
|
|
12
|
+
* con `id="AutoScript"` o `name="AutoScript"` lo define solo (DOM clobbering),
|
|
13
|
+
* y los saneadores de HTML habituales permiten `id`. Comprobar únicamente que
|
|
14
|
+
* el global sea *truthy* aceptaba ese elemento como si fuera la API: la firma
|
|
15
|
+
* no fallaba al construir el cliente sino mucho después, con un `TypeError`
|
|
16
|
+
* sin `code` al invocar una operación inexistente.
|
|
17
|
+
*
|
|
18
|
+
* `sign` es la única operación que AutoScript garantiza en todas sus versiones
|
|
19
|
+
* —el resto son opcionales en `AutoScriptApi`—, así que es lo mínimo que puede
|
|
20
|
+
* exigirse sin rechazar versiones legítimas.
|
|
21
|
+
*/
|
|
22
|
+
export declare function isAutoScriptApi(candidate: unknown): candidate is AutoScriptApi;
|
|
23
|
+
/**
|
|
24
|
+
* Resuelve la API inyectada o el objeto global oficial.
|
|
25
|
+
*/
|
|
26
|
+
export declare function resolveAutoScript(injected?: AutoScriptApi): AutoScriptApi;
|
|
27
|
+
/**
|
|
28
|
+
* Adapta una operación nativa basada en callbacks a una promesa.
|
|
29
|
+
*/
|
|
30
|
+
export declare function invokeSignatureOperation(operation: SignatureOperation, data: string, algorithm: string, format: string, parameters: string): Promise<SignResult>;
|
package/dist/base64.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { SignableData } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Convierte datos binarios o texto Base64 en el formato esperado por
|
|
4
|
+
* AutoScript. Las cadenas se consideran ya codificadas en Base64.
|
|
5
|
+
*/
|
|
6
|
+
export declare function toBase64(data: SignableData): Promise<string>;
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import type { AutoFirmaClientOptions, AutoScriptApi, CertificateResult, CheckTimeOptions, ExtraParameters, SaveOptions, SignatureClient, SignOptions, SignResult } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Cliente moderno y fino sobre la API oficial AutoScript.
|
|
4
|
+
*/
|
|
5
|
+
export declare class AutoFirmaClient implements SignatureClient {
|
|
6
|
+
private readonly autoScript;
|
|
7
|
+
constructor(options?: AutoFirmaClientOptions);
|
|
8
|
+
/**
|
|
9
|
+
* Solicita a AutoScript que prepare o abra AutoFirma.
|
|
10
|
+
*/
|
|
11
|
+
initialize(): void;
|
|
12
|
+
/**
|
|
13
|
+
* Firma los datos proporcionados.
|
|
14
|
+
*/
|
|
15
|
+
sign(options: SignOptions): Promise<SignResult>;
|
|
16
|
+
/**
|
|
17
|
+
* Añade una firma al mismo nivel cuando AutoScript expone la operación.
|
|
18
|
+
*/
|
|
19
|
+
coSign(options: SignOptions): Promise<SignResult>;
|
|
20
|
+
/**
|
|
21
|
+
* Contrafirma cuando AutoScript expone la operación.
|
|
22
|
+
*/
|
|
23
|
+
counterSign(options: SignOptions): Promise<SignResult>;
|
|
24
|
+
/**
|
|
25
|
+
* Abre la selección de certificado sin iniciar una firma.
|
|
26
|
+
*/
|
|
27
|
+
selectCertificate(parameters?: ExtraParameters): Promise<CertificateResult>;
|
|
28
|
+
/**
|
|
29
|
+
* Pide a AutoFirma que guarde datos en un fichero elegido por la persona
|
|
30
|
+
* usuaria.
|
|
31
|
+
*/
|
|
32
|
+
saveDataToFile(options: SaveOptions): Promise<void>;
|
|
33
|
+
/**
|
|
34
|
+
* Comprueba la sincronía del reloj del equipo contra un servidor.
|
|
35
|
+
*
|
|
36
|
+
* AutoScript lo implementa con una petición XHR **síncrona** que bloquea el
|
|
37
|
+
* hilo principal (`xhr.open('GET', url, false)`) hasta obtener respuesta.
|
|
38
|
+
* Si no se indica `checkUrl`, la petición se envía contra
|
|
39
|
+
* `document.URL + '/' + Math.random()`: una URL inventada contra el propio
|
|
40
|
+
* origen de la página, un acceso de red no documentado en ningún otro sitio
|
|
41
|
+
* y que este método no evita ni controla, pese a que esta librería no hace
|
|
42
|
+
* ningún acceso de red propio.
|
|
43
|
+
*
|
|
44
|
+
* El único efecto observable de un desfase es un `alert()` nativo; AutoScript
|
|
45
|
+
* captura y silencia cualquier error (por ejemplo, que la petición falle).
|
|
46
|
+
* Por eso la promesa devuelta nunca informa del resultado de la
|
|
47
|
+
* comprobación: se resuelve siempre que la operación exista, haya o no
|
|
48
|
+
* desfase y haya o no error de red.
|
|
49
|
+
*
|
|
50
|
+
* Con `checkType: "CT_OBLIGATORY"` y un desfase detectado, AutoScript marca
|
|
51
|
+
* un estado interno (`severeTimeDelay`) que hace que su función de carga
|
|
52
|
+
* (`cargarAppAfirma`, a la que invoca `initialize()`) registre un aviso y
|
|
53
|
+
* retorne sin hacer nada la siguiente vez que se ejecute. El orden de
|
|
54
|
+
* llamadas importa y no está documentado: invocar
|
|
55
|
+
* `checkTime({ checkType: "CT_OBLIGATORY" })` antes de `initialize()` puede
|
|
56
|
+
* convertir `initialize()` en un no-op silencioso; invocarlo después de
|
|
57
|
+
* `initialize()` no afecta a una carga que ya se ha iniciado.
|
|
58
|
+
*
|
|
59
|
+
* Si no se indica `maxMillis`, se reenvía tal cual: AutoScript aplica
|
|
60
|
+
* entonces su propio valor por defecto (300000 ms, 5 minutos) en vez de uno
|
|
61
|
+
* impuesto aquí.
|
|
62
|
+
*/
|
|
63
|
+
checkTime(options?: CheckTimeOptions): Promise<void>;
|
|
64
|
+
/**
|
|
65
|
+
* Devuelve el objeto oficial para casos que el wrapper todavía no cubra.
|
|
66
|
+
*/
|
|
67
|
+
get raw(): AutoScriptApi;
|
|
68
|
+
/**
|
|
69
|
+
* Valida que exista la operación opcional antes de ejecutarla.
|
|
70
|
+
*/
|
|
71
|
+
private executeRequired;
|
|
72
|
+
/**
|
|
73
|
+
* Rechazo homogéneo para operaciones ausentes en la versión fijada.
|
|
74
|
+
*/
|
|
75
|
+
private unsupported;
|
|
76
|
+
/**
|
|
77
|
+
* Normaliza datos y parámetros antes de delegar en AutoScript.
|
|
78
|
+
*/
|
|
79
|
+
private execute;
|
|
80
|
+
}
|