edockit 0.4.0-dev.0 → 0.4.0-dev.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.
Files changed (49) hide show
  1. package/dist/{certificate-c46e14a0.js → certificate-3c9dcdac.js} +16 -27
  2. package/dist/certificate-3c9dcdac.js.map +1 -0
  3. package/dist/{certificate-fc0e06f7.js → certificate-c7123a37.js} +37 -27
  4. package/dist/certificate-c7123a37.js.map +1 -0
  5. package/dist/identity-c9e5052e.js +410 -0
  6. package/dist/identity-c9e5052e.js.map +1 -0
  7. package/dist/identity-fca881b1.js +406 -0
  8. package/dist/identity-fca881b1.js.map +1 -0
  9. package/dist/index.cjs.js +40 -1244
  10. package/dist/index.cjs.js.map +1 -1
  11. package/dist/index.esm.js +36 -1240
  12. package/dist/index.esm.js.map +1 -1
  13. package/dist/index.umd.js +23 -17
  14. package/dist/index.umd.js.map +1 -1
  15. package/dist/{loader-43d8e17a.js → loader-7a0f771f.js} +2 -2
  16. package/dist/{loader-43d8e17a.js.map → loader-7a0f771f.js.map} +1 -1
  17. package/dist/{loader-1ac52e12.js → loader-ad1a5051.js} +2 -2
  18. package/dist/{loader-1ac52e12.js.map → loader-ad1a5051.js.map} +1 -1
  19. package/dist/normalize-50862581.js +456 -0
  20. package/dist/normalize-50862581.js.map +1 -0
  21. package/dist/normalize-9626be7c.js +479 -0
  22. package/dist/normalize-9626be7c.js.map +1 -0
  23. package/dist/{reference-provider-1cd85b7b.js → reference-provider-3838ebfb.js} +4 -4
  24. package/dist/{reference-provider-1cd85b7b.js.map → reference-provider-3838ebfb.js.map} +1 -1
  25. package/dist/{reference-provider-53240217.js → reference-provider-9bbbaab8.js} +4 -4
  26. package/dist/{reference-provider-53240217.js.map → reference-provider-9bbbaab8.js.map} +1 -1
  27. package/dist/trusted-list-build.cjs.js +8 -3
  28. package/dist/trusted-list-build.cjs.js.map +1 -1
  29. package/dist/trusted-list-build.esm.js +8 -3
  30. package/dist/trusted-list-build.esm.js.map +1 -1
  31. package/dist/trusted-list-bundled.cjs.js +7 -4
  32. package/dist/trusted-list-bundled.cjs.js.map +1 -1
  33. package/dist/trusted-list-bundled.esm.js +7 -4
  34. package/dist/trusted-list-bundled.esm.js.map +1 -1
  35. package/dist/trusted-list.cjs.js +7 -4
  36. package/dist/trusted-list.cjs.js.map +1 -1
  37. package/dist/trusted-list.esm.js +7 -4
  38. package/dist/trusted-list.esm.js.map +1 -1
  39. package/package.json +1 -1
  40. package/dist/certificate-c46e14a0.js.map +0 -1
  41. package/dist/certificate-fc0e06f7.js.map +0 -1
  42. package/dist/identity-1a3dddc3.js +0 -902
  43. package/dist/identity-1a3dddc3.js.map +0 -1
  44. package/dist/identity-b3a70fc1.js +0 -897
  45. package/dist/identity-b3a70fc1.js.map +0 -1
  46. package/dist/normalize-60f2d7e6.js +0 -6270
  47. package/dist/normalize-60f2d7e6.js.map +0 -1
  48. package/dist/normalize-70da6516.js +0 -6214
  49. package/dist/normalize-70da6516.js.map +0 -1
@@ -1,897 +0,0 @@
1
- /*!
2
- * MIT License
3
- * Copyright (c) 2025 Edgars Jēkabsons, ZenomyTech SIA
4
- */
5
- import { X509Certificate } from '@peculiar/x509';
6
- import { p as fromBER, q as isConvertible, s as schemaStorage, r as isTypeOfArray, t as Constructed, e as AsnTypeTypes, S as Sequence, u as compareSchema, v as defaultConverter, w as Set, b as AsnPropTypes, x as asn1js, y as BaseBlock, z as isArrayEqual, D as Null, P as Primitive, F as BufferSourceConverter, H as fetchIssuerCertificate, m as arrayBufferToPEM, I as fetchOCSP, C as Certificate, J as hexToArrayBuffer, L as CertID, g as AlgorithmIdentifier, O as OctetString, R as Request, M as TBSRequest, Q as OCSPRequest, U as OCSPResponse, V as OCSPResponseStatus, W as BasicOCSPResponse, X as normalizeDistinguishedName, n as arrayBufferToHex, Y as normalizeKeyIdentifier } from './normalize-70da6516.js';
7
-
8
- class AsnSchemaValidationError extends Error {
9
- constructor() {
10
- super(...arguments);
11
- this.schemas = [];
12
- }
13
- }
14
-
15
- class AsnParser {
16
- static parse(data, target) {
17
- const asn1Parsed = fromBER(data);
18
- if (asn1Parsed.result.error) {
19
- throw new Error(asn1Parsed.result.error);
20
- }
21
- const res = this.fromASN(asn1Parsed.result, target);
22
- return res;
23
- }
24
- static fromASN(asn1Schema, target) {
25
- try {
26
- if (isConvertible(target)) {
27
- const value = new target();
28
- return value.fromASN(asn1Schema);
29
- }
30
- const schema = schemaStorage.get(target);
31
- schemaStorage.cache(target);
32
- let targetSchema = schema.schema;
33
- const choiceResult = this.handleChoiceTypes(asn1Schema, schema, target, targetSchema);
34
- if (choiceResult === null || choiceResult === void 0 ? void 0 : choiceResult.result) {
35
- return choiceResult.result;
36
- }
37
- if (choiceResult === null || choiceResult === void 0 ? void 0 : choiceResult.targetSchema) {
38
- targetSchema = choiceResult.targetSchema;
39
- }
40
- const sequenceResult = this.handleSequenceTypes(asn1Schema, schema, target, targetSchema);
41
- const res = new target();
42
- if (isTypeOfArray(target)) {
43
- return this.handleArrayTypes(asn1Schema, schema, target);
44
- }
45
- this.processSchemaItems(schema, sequenceResult, res);
46
- return res;
47
- }
48
- catch (error) {
49
- if (error instanceof AsnSchemaValidationError) {
50
- error.schemas.push(target.name);
51
- }
52
- throw error;
53
- }
54
- }
55
- static handleChoiceTypes(asn1Schema, schema, target, targetSchema) {
56
- if (asn1Schema.constructor === Constructed &&
57
- schema.type === AsnTypeTypes.Choice &&
58
- asn1Schema.idBlock.tagClass === 3) {
59
- for (const key in schema.items) {
60
- const schemaItem = schema.items[key];
61
- if (schemaItem.context === asn1Schema.idBlock.tagNumber && schemaItem.implicit) {
62
- if (typeof schemaItem.type === "function" &&
63
- schemaStorage.has(schemaItem.type)) {
64
- const fieldSchema = schemaStorage.get(schemaItem.type);
65
- if (fieldSchema && fieldSchema.type === AsnTypeTypes.Sequence) {
66
- const newSeq = new Sequence();
67
- if ("value" in asn1Schema.valueBlock &&
68
- Array.isArray(asn1Schema.valueBlock.value) &&
69
- "value" in newSeq.valueBlock) {
70
- newSeq.valueBlock.value = asn1Schema.valueBlock.value;
71
- const fieldValue = this.fromASN(newSeq, schemaItem.type);
72
- const res = new target();
73
- res[key] = fieldValue;
74
- return { result: res };
75
- }
76
- }
77
- }
78
- }
79
- }
80
- }
81
- else if (asn1Schema.constructor === Constructed &&
82
- schema.type !== AsnTypeTypes.Choice) {
83
- const newTargetSchema = new Constructed({
84
- idBlock: {
85
- tagClass: 3,
86
- tagNumber: asn1Schema.idBlock.tagNumber,
87
- },
88
- value: schema.schema.valueBlock.value,
89
- });
90
- for (const key in schema.items) {
91
- delete asn1Schema[key];
92
- }
93
- return { targetSchema: newTargetSchema };
94
- }
95
- return null;
96
- }
97
- static handleSequenceTypes(asn1Schema, schema, target, targetSchema) {
98
- if (schema.type === AsnTypeTypes.Sequence) {
99
- const asn1ComparedSchema = compareSchema({}, asn1Schema, targetSchema);
100
- if (!asn1ComparedSchema.verified) {
101
- throw new AsnSchemaValidationError(`Data does not match to ${target.name} ASN1 schema.${asn1ComparedSchema.result.error ? ` ${asn1ComparedSchema.result.error}` : ""}`);
102
- }
103
- return asn1ComparedSchema;
104
- }
105
- else {
106
- const asn1ComparedSchema = compareSchema({}, asn1Schema, targetSchema);
107
- if (!asn1ComparedSchema.verified) {
108
- throw new AsnSchemaValidationError(`Data does not match to ${target.name} ASN1 schema.${asn1ComparedSchema.result.error ? ` ${asn1ComparedSchema.result.error}` : ""}`);
109
- }
110
- return asn1ComparedSchema;
111
- }
112
- }
113
- static processRepeatedField(asn1Elements, asn1Index, schemaItem) {
114
- let elementsToProcess = asn1Elements.slice(asn1Index);
115
- if (elementsToProcess.length === 1 && elementsToProcess[0].constructor.name === "Sequence") {
116
- const seq = elementsToProcess[0];
117
- if (seq.valueBlock && seq.valueBlock.value && Array.isArray(seq.valueBlock.value)) {
118
- elementsToProcess = seq.valueBlock.value;
119
- }
120
- }
121
- if (typeof schemaItem.type === "number") {
122
- const converter = defaultConverter(schemaItem.type);
123
- if (!converter)
124
- throw new Error(`No converter for ASN.1 type ${schemaItem.type}`);
125
- return elementsToProcess
126
- .filter((el) => el && el.valueBlock)
127
- .map((el) => {
128
- try {
129
- return converter.fromASN(el);
130
- }
131
- catch {
132
- return undefined;
133
- }
134
- })
135
- .filter((v) => v !== undefined);
136
- }
137
- else {
138
- return elementsToProcess
139
- .filter((el) => el && el.valueBlock)
140
- .map((el) => {
141
- try {
142
- return this.fromASN(el, schemaItem.type);
143
- }
144
- catch {
145
- return undefined;
146
- }
147
- })
148
- .filter((v) => v !== undefined);
149
- }
150
- }
151
- static processPrimitiveField(asn1Element, schemaItem) {
152
- const converter = defaultConverter(schemaItem.type);
153
- if (!converter)
154
- throw new Error(`No converter for ASN.1 type ${schemaItem.type}`);
155
- return converter.fromASN(asn1Element);
156
- }
157
- static isOptionalChoiceField(schemaItem) {
158
- return (schemaItem.optional &&
159
- typeof schemaItem.type === "function" &&
160
- schemaStorage.has(schemaItem.type) &&
161
- schemaStorage.get(schemaItem.type).type === AsnTypeTypes.Choice);
162
- }
163
- static processOptionalChoiceField(asn1Element, schemaItem) {
164
- try {
165
- const value = this.fromASN(asn1Element, schemaItem.type);
166
- return { processed: true, value };
167
- }
168
- catch (err) {
169
- if (err instanceof AsnSchemaValidationError &&
170
- /Wrong values for Choice type/.test(err.message)) {
171
- return { processed: false };
172
- }
173
- throw err;
174
- }
175
- }
176
- static handleArrayTypes(asn1Schema, schema, target) {
177
- if (!("value" in asn1Schema.valueBlock && Array.isArray(asn1Schema.valueBlock.value))) {
178
- throw new Error(`Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.`);
179
- }
180
- const itemType = schema.itemType;
181
- if (typeof itemType === "number") {
182
- const converter = defaultConverter(itemType);
183
- if (!converter) {
184
- throw new Error(`Cannot get default converter for array item of ${target.name} ASN1 schema`);
185
- }
186
- return target.from(asn1Schema.valueBlock.value, (element) => converter.fromASN(element));
187
- }
188
- else {
189
- return target.from(asn1Schema.valueBlock.value, (element) => this.fromASN(element, itemType));
190
- }
191
- }
192
- static processSchemaItems(schema, asn1ComparedSchema, res) {
193
- for (const key in schema.items) {
194
- const asn1SchemaValue = asn1ComparedSchema.result[key];
195
- if (!asn1SchemaValue) {
196
- continue;
197
- }
198
- const schemaItem = schema.items[key];
199
- const schemaItemType = schemaItem.type;
200
- let parsedValue;
201
- if (typeof schemaItemType === "number" || isConvertible(schemaItemType)) {
202
- parsedValue = this.processPrimitiveSchemaItem(asn1SchemaValue, schemaItem, schemaItemType);
203
- }
204
- else {
205
- parsedValue = this.processComplexSchemaItem(asn1SchemaValue, schemaItem, schemaItemType);
206
- }
207
- if (parsedValue &&
208
- typeof parsedValue === "object" &&
209
- "value" in parsedValue &&
210
- "raw" in parsedValue) {
211
- res[key] = parsedValue.value;
212
- res[`${key}Raw`] = parsedValue.raw;
213
- }
214
- else {
215
- res[key] = parsedValue;
216
- }
217
- }
218
- }
219
- static processPrimitiveSchemaItem(asn1SchemaValue, schemaItem, schemaItemType) {
220
- var _a;
221
- const converter = (_a = schemaItem.converter) !== null && _a !== void 0 ? _a : (isConvertible(schemaItemType)
222
- ? new schemaItemType()
223
- : null);
224
- if (!converter) {
225
- throw new Error("Converter is empty");
226
- }
227
- if (schemaItem.repeated) {
228
- return this.processRepeatedPrimitiveItem(asn1SchemaValue, schemaItem, converter);
229
- }
230
- else {
231
- return this.processSinglePrimitiveItem(asn1SchemaValue, schemaItem, schemaItemType, converter);
232
- }
233
- }
234
- static processRepeatedPrimitiveItem(asn1SchemaValue, schemaItem, converter) {
235
- if (schemaItem.implicit) {
236
- const Container = schemaItem.repeated === "sequence" ? Sequence : Set;
237
- const newItem = new Container();
238
- newItem.valueBlock = asn1SchemaValue.valueBlock;
239
- const newItemAsn = fromBER(newItem.toBER(false));
240
- if (newItemAsn.offset === -1) {
241
- throw new Error(`Cannot parse the child item. ${newItemAsn.result.error}`);
242
- }
243
- if (!("value" in newItemAsn.result.valueBlock &&
244
- Array.isArray(newItemAsn.result.valueBlock.value))) {
245
- throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");
246
- }
247
- const value = newItemAsn.result.valueBlock.value;
248
- return Array.from(value, (element) => converter.fromASN(element));
249
- }
250
- else {
251
- return Array.from(asn1SchemaValue, (element) => converter.fromASN(element));
252
- }
253
- }
254
- static processSinglePrimitiveItem(asn1SchemaValue, schemaItem, schemaItemType, converter) {
255
- let value = asn1SchemaValue;
256
- if (schemaItem.implicit) {
257
- let newItem;
258
- if (isConvertible(schemaItemType)) {
259
- newItem = new schemaItemType().toSchema("");
260
- }
261
- else {
262
- const Asn1TypeName = AsnPropTypes[schemaItemType];
263
- const Asn1Type = asn1js[Asn1TypeName];
264
- if (!Asn1Type) {
265
- throw new Error(`Cannot get '${Asn1TypeName}' class from asn1js module`);
266
- }
267
- newItem = new Asn1Type();
268
- }
269
- newItem.valueBlock = value.valueBlock;
270
- value = fromBER(newItem.toBER(false)).result;
271
- }
272
- return converter.fromASN(value);
273
- }
274
- static processComplexSchemaItem(asn1SchemaValue, schemaItem, schemaItemType) {
275
- if (schemaItem.repeated) {
276
- if (!Array.isArray(asn1SchemaValue)) {
277
- throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");
278
- }
279
- return Array.from(asn1SchemaValue, (element) => this.fromASN(element, schemaItemType));
280
- }
281
- else {
282
- const valueToProcess = this.handleImplicitTagging(asn1SchemaValue, schemaItem, schemaItemType);
283
- if (this.isOptionalChoiceField(schemaItem)) {
284
- try {
285
- return this.fromASN(valueToProcess, schemaItemType);
286
- }
287
- catch (err) {
288
- if (err instanceof AsnSchemaValidationError &&
289
- /Wrong values for Choice type/.test(err.message)) {
290
- return undefined;
291
- }
292
- throw err;
293
- }
294
- }
295
- else {
296
- const parsedValue = this.fromASN(valueToProcess, schemaItemType);
297
- if (schemaItem.raw) {
298
- return {
299
- value: parsedValue,
300
- raw: asn1SchemaValue.valueBeforeDecodeView,
301
- };
302
- }
303
- return parsedValue;
304
- }
305
- }
306
- }
307
- static handleImplicitTagging(asn1SchemaValue, schemaItem, schemaItemType) {
308
- if (schemaItem.implicit && typeof schemaItem.context === "number") {
309
- const schema = schemaStorage.get(schemaItemType);
310
- if (schema.type === AsnTypeTypes.Sequence) {
311
- const newSeq = new Sequence();
312
- if ("value" in asn1SchemaValue.valueBlock &&
313
- Array.isArray(asn1SchemaValue.valueBlock.value) &&
314
- "value" in newSeq.valueBlock) {
315
- newSeq.valueBlock.value = asn1SchemaValue.valueBlock.value;
316
- return newSeq;
317
- }
318
- }
319
- else if (schema.type === AsnTypeTypes.Set) {
320
- const newSet = new Set();
321
- if ("value" in asn1SchemaValue.valueBlock &&
322
- Array.isArray(asn1SchemaValue.valueBlock.value) &&
323
- "value" in newSet.valueBlock) {
324
- newSet.valueBlock.value = asn1SchemaValue.valueBlock.value;
325
- return newSet;
326
- }
327
- }
328
- }
329
- return asn1SchemaValue;
330
- }
331
- }
332
-
333
- class AsnSerializer {
334
- static serialize(obj) {
335
- if (obj instanceof BaseBlock) {
336
- return obj.toBER(false);
337
- }
338
- return this.toASN(obj).toBER(false);
339
- }
340
- static toASN(obj) {
341
- if (obj && typeof obj === "object" && isConvertible(obj)) {
342
- return obj.toASN();
343
- }
344
- if (!(obj && typeof obj === "object")) {
345
- throw new TypeError("Parameter 1 should be type of Object.");
346
- }
347
- const target = obj.constructor;
348
- const schema = schemaStorage.get(target);
349
- schemaStorage.cache(target);
350
- let asn1Value = [];
351
- if (schema.itemType) {
352
- if (!Array.isArray(obj)) {
353
- throw new TypeError("Parameter 1 should be type of Array.");
354
- }
355
- if (typeof schema.itemType === "number") {
356
- const converter = defaultConverter(schema.itemType);
357
- if (!converter) {
358
- throw new Error(`Cannot get default converter for array item of ${target.name} ASN1 schema`);
359
- }
360
- asn1Value = obj.map((o) => converter.toASN(o));
361
- }
362
- else {
363
- asn1Value = obj.map((o) => this.toAsnItem({ type: schema.itemType }, "[]", target, o));
364
- }
365
- }
366
- else {
367
- for (const key in schema.items) {
368
- const schemaItem = schema.items[key];
369
- const objProp = obj[key];
370
- if (objProp === undefined ||
371
- schemaItem.defaultValue === objProp ||
372
- (typeof schemaItem.defaultValue === "object" &&
373
- typeof objProp === "object" &&
374
- isArrayEqual(this.serialize(schemaItem.defaultValue), this.serialize(objProp)))) {
375
- continue;
376
- }
377
- const asn1Item = AsnSerializer.toAsnItem(schemaItem, key, target, objProp);
378
- if (typeof schemaItem.context === "number") {
379
- if (schemaItem.implicit) {
380
- if (!schemaItem.repeated &&
381
- (typeof schemaItem.type === "number" || isConvertible(schemaItem.type))) {
382
- const value = {};
383
- value.valueHex =
384
- asn1Item instanceof Null
385
- ? asn1Item.valueBeforeDecodeView
386
- : asn1Item.valueBlock.toBER();
387
- asn1Value.push(new Primitive({
388
- optional: schemaItem.optional,
389
- idBlock: {
390
- tagClass: 3,
391
- tagNumber: schemaItem.context,
392
- },
393
- ...value,
394
- }));
395
- }
396
- else {
397
- asn1Value.push(new Constructed({
398
- optional: schemaItem.optional,
399
- idBlock: {
400
- tagClass: 3,
401
- tagNumber: schemaItem.context,
402
- },
403
- value: asn1Item.valueBlock.value,
404
- }));
405
- }
406
- }
407
- else {
408
- asn1Value.push(new Constructed({
409
- optional: schemaItem.optional,
410
- idBlock: {
411
- tagClass: 3,
412
- tagNumber: schemaItem.context,
413
- },
414
- value: [asn1Item],
415
- }));
416
- }
417
- }
418
- else if (schemaItem.repeated) {
419
- asn1Value = asn1Value.concat(asn1Item);
420
- }
421
- else {
422
- asn1Value.push(asn1Item);
423
- }
424
- }
425
- }
426
- let asnSchema;
427
- switch (schema.type) {
428
- case AsnTypeTypes.Sequence:
429
- asnSchema = new Sequence({ value: asn1Value });
430
- break;
431
- case AsnTypeTypes.Set:
432
- asnSchema = new Set({ value: asn1Value });
433
- break;
434
- case AsnTypeTypes.Choice:
435
- if (!asn1Value[0]) {
436
- throw new Error(`Schema '${target.name}' has wrong data. Choice cannot be empty.`);
437
- }
438
- asnSchema = asn1Value[0];
439
- break;
440
- }
441
- return asnSchema;
442
- }
443
- static toAsnItem(schemaItem, key, target, objProp) {
444
- let asn1Item;
445
- if (typeof schemaItem.type === "number") {
446
- const converter = schemaItem.converter;
447
- if (!converter) {
448
- throw new Error(`Property '${key}' doesn't have converter for type ${AsnPropTypes[schemaItem.type]} in schema '${target.name}'`);
449
- }
450
- if (schemaItem.repeated) {
451
- if (!Array.isArray(objProp)) {
452
- throw new TypeError("Parameter 'objProp' should be type of Array.");
453
- }
454
- const items = Array.from(objProp, (element) => converter.toASN(element));
455
- const Container = schemaItem.repeated === "sequence" ? Sequence : Set;
456
- asn1Item = new Container({
457
- value: items,
458
- });
459
- }
460
- else {
461
- asn1Item = converter.toASN(objProp);
462
- }
463
- }
464
- else {
465
- if (schemaItem.repeated) {
466
- if (!Array.isArray(objProp)) {
467
- throw new TypeError("Parameter 'objProp' should be type of Array.");
468
- }
469
- const items = Array.from(objProp, (element) => this.toASN(element));
470
- const Container = schemaItem.repeated === "sequence" ? Sequence : Set;
471
- asn1Item = new Container({
472
- value: items,
473
- });
474
- }
475
- else {
476
- asn1Item = this.toASN(objProp);
477
- }
478
- }
479
- return asn1Item;
480
- }
481
- }
482
-
483
- class AsnConvert {
484
- static serialize(obj) {
485
- return AsnSerializer.serialize(obj);
486
- }
487
- static parse(data, target) {
488
- return AsnParser.parse(data, target);
489
- }
490
- static toString(data) {
491
- const buf = BufferSourceConverter.isBufferSource(data)
492
- ? BufferSourceConverter.toArrayBuffer(data)
493
- : AsnConvert.serialize(data);
494
- const asn = fromBER(buf);
495
- if (asn.offset === -1) {
496
- throw new Error(`Cannot decode ASN.1 data. ${asn.result.error}`);
497
- }
498
- return asn.result.toString();
499
- }
500
- }
501
-
502
- // src/core/revocation/ocsp.ts
503
- /**
504
- * OID for Authority Information Access extension
505
- */
506
- const id_pe_authorityInfoAccess = "1.3.6.1.5.5.7.1.1";
507
- /**
508
- * SHA-1 algorithm identifier for OCSP
509
- */
510
- const SHA1_OID = "1.3.14.3.2.26";
511
- /**
512
- * Compute SHA-1 hash of data (cross-platform)
513
- */
514
- async function computeSHA1(data) {
515
- if (typeof crypto !== "undefined" && crypto.subtle) {
516
- return crypto.subtle.digest("SHA-1", data);
517
- }
518
- // Node.js fallback
519
- const nodeCrypto = require("crypto");
520
- const hash = nodeCrypto.createHash("sha1");
521
- hash.update(Buffer.from(data));
522
- return hash.digest().buffer;
523
- }
524
- /**
525
- * Extract OCSP responder URLs from certificate
526
- * @param cert X509Certificate to extract OCSP URLs from
527
- * @returns Array of OCSP responder URLs
528
- */
529
- function extractOCSPUrls(cert) {
530
- try {
531
- const aiaExt = cert.getExtension(id_pe_authorityInfoAccess);
532
- if (!aiaExt) {
533
- return [];
534
- }
535
- // Get OCSP URLs from the extension
536
- return aiaExt.ocsp.filter((gn) => gn.type === "url").map((gn) => gn.value);
537
- }
538
- catch {
539
- return [];
540
- }
541
- }
542
- /**
543
- * Extract CA Issuers URLs from certificate (for fetching issuer cert)
544
- * @param cert X509Certificate to extract URLs from
545
- * @returns Array of CA Issuers URLs
546
- */
547
- function extractCAIssuersUrls(cert) {
548
- try {
549
- const aiaExt = cert.getExtension(id_pe_authorityInfoAccess);
550
- if (!aiaExt) {
551
- return [];
552
- }
553
- return aiaExt.caIssuers.filter((gn) => gn.type === "url").map((gn) => gn.value);
554
- }
555
- catch {
556
- return [];
557
- }
558
- }
559
- /**
560
- * Find issuer certificate from certificate chain
561
- * @param cert Certificate to find issuer for
562
- * @param chain Array of PEM-formatted certificates
563
- * @returns Issuer certificate or null if not found
564
- */
565
- function findIssuerInChain(cert, chain) {
566
- const issuerName = cert.issuer;
567
- for (const pemCert of chain) {
568
- try {
569
- const chainCert = new X509Certificate(pemCert);
570
- // Check if this cert's subject matches our cert's issuer
571
- if (chainCert.subject === issuerName) {
572
- return chainCert;
573
- }
574
- }
575
- catch {
576
- // Skip invalid certificates
577
- }
578
- }
579
- return null;
580
- }
581
- /**
582
- * Fetch issuer certificate from AIA extension
583
- * @param cert Certificate to fetch issuer for
584
- * @param timeout Timeout in ms
585
- * @param proxyUrl Optional CORS proxy URL
586
- * @returns Issuer certificate or null
587
- */
588
- async function fetchIssuerFromAIA(cert, timeout = 5000, proxyUrl) {
589
- const urls = extractCAIssuersUrls(cert);
590
- for (const url of urls) {
591
- try {
592
- const result = await fetchIssuerCertificate(url, timeout, proxyUrl);
593
- if (result.ok && result.data) {
594
- // Try to parse as DER first, then PEM
595
- try {
596
- return new X509Certificate(result.data);
597
- }
598
- catch {
599
- // Try converting to PEM
600
- const pem = arrayBufferToPEM(result.data);
601
- return new X509Certificate(pem);
602
- }
603
- }
604
- }
605
- catch {
606
- // Try next URL
607
- }
608
- }
609
- return null;
610
- }
611
- /**
612
- * Build OCSP request for a certificate
613
- * @param cert Certificate to check
614
- * @param issuerCert Issuer certificate
615
- * @returns DER-encoded OCSP request
616
- */
617
- async function buildOCSPRequest(cert, issuerCert) {
618
- // Get issuer name hash (SHA-1 of issuer's DN in DER)
619
- // Parse the raw certificate to get the proper ASN.1 structures for serialization
620
- const issuerCertAsn = AsnParser.parse(issuerCert.rawData, Certificate);
621
- const issuerNameDer = AsnConvert.serialize(issuerCertAsn.tbsCertificate.subject);
622
- const issuerNameHash = await computeSHA1(issuerNameDer);
623
- // Get issuer key hash (SHA-1 of issuer's public key BIT STRING value, not the full SPKI)
624
- const issuerKeyHash = await computeSHA1(issuerCertAsn.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey);
625
- // Get certificate serial number
626
- const serialNumber = hexToArrayBuffer(cert.serialNumber);
627
- // Build CertID
628
- const certId = new CertID({
629
- hashAlgorithm: new AlgorithmIdentifier({ algorithm: SHA1_OID }),
630
- issuerNameHash: new OctetString(issuerNameHash),
631
- issuerKeyHash: new OctetString(issuerKeyHash),
632
- serialNumber: serialNumber,
633
- });
634
- // Build request
635
- const request = new Request({ reqCert: certId });
636
- // Build TBS request
637
- const tbsRequest = new TBSRequest({
638
- requestList: [request],
639
- });
640
- // Build OCSP request
641
- const ocspRequest = new OCSPRequest({ tbsRequest });
642
- return AsnConvert.serialize(ocspRequest);
643
- }
644
- /**
645
- * Parse OCSP response and extract revocation status
646
- * @param responseData DER-encoded OCSP response
647
- * @returns Revocation result
648
- */
649
- function parseOCSPResponse(responseData) {
650
- const now = new Date();
651
- try {
652
- const response = AsnConvert.parse(responseData, OCSPResponse);
653
- // Check response status
654
- switch (response.responseStatus) {
655
- case OCSPResponseStatus.successful:
656
- break;
657
- case OCSPResponseStatus.malformedRequest:
658
- return {
659
- isValid: false,
660
- status: "error",
661
- method: "ocsp",
662
- reason: "OCSP responder returned: malformed request",
663
- checkedAt: now,
664
- };
665
- case OCSPResponseStatus.internalError:
666
- return {
667
- isValid: false,
668
- status: "error",
669
- method: "ocsp",
670
- reason: "OCSP responder returned: internal error",
671
- checkedAt: now,
672
- };
673
- case OCSPResponseStatus.tryLater:
674
- return {
675
- isValid: false,
676
- status: "unknown",
677
- method: "ocsp",
678
- reason: "OCSP responder returned: try later",
679
- checkedAt: now,
680
- };
681
- case OCSPResponseStatus.sigRequired:
682
- return {
683
- isValid: false,
684
- status: "error",
685
- method: "ocsp",
686
- reason: "OCSP responder requires signature",
687
- checkedAt: now,
688
- };
689
- case OCSPResponseStatus.unauthorized:
690
- return {
691
- isValid: false,
692
- status: "error",
693
- method: "ocsp",
694
- reason: "OCSP responder returned: unauthorized",
695
- checkedAt: now,
696
- };
697
- default:
698
- return {
699
- isValid: false,
700
- status: "error",
701
- method: "ocsp",
702
- reason: `OCSP responder returned unknown status: ${response.responseStatus}`,
703
- checkedAt: now,
704
- };
705
- }
706
- // Parse response bytes
707
- if (!response.responseBytes) {
708
- return {
709
- isValid: false,
710
- status: "error",
711
- method: "ocsp",
712
- reason: "OCSP response has no response bytes",
713
- checkedAt: now,
714
- };
715
- }
716
- // Parse BasicOCSPResponse
717
- const basicResponse = AsnConvert.parse(response.responseBytes.response.buffer, BasicOCSPResponse);
718
- // Get the first single response
719
- const responses = basicResponse.tbsResponseData.responses;
720
- if (!responses || responses.length === 0) {
721
- return {
722
- isValid: false,
723
- status: "error",
724
- method: "ocsp",
725
- reason: "OCSP response contains no certificate status",
726
- checkedAt: now,
727
- };
728
- }
729
- const singleResponse = responses[0];
730
- const certStatus = singleResponse.certStatus;
731
- // Check certificate status
732
- if (certStatus.good !== undefined) {
733
- return {
734
- isValid: true,
735
- status: "good",
736
- method: "ocsp",
737
- checkedAt: now,
738
- };
739
- }
740
- else if (certStatus.revoked) {
741
- return {
742
- isValid: false,
743
- status: "revoked",
744
- method: "ocsp",
745
- reason: certStatus.revoked.revocationReason !== undefined
746
- ? `Certificate revoked (reason: ${certStatus.revoked.revocationReason})`
747
- : "Certificate revoked",
748
- revokedAt: certStatus.revoked.revocationTime,
749
- checkedAt: now,
750
- };
751
- }
752
- else if (certStatus.unknown !== undefined) {
753
- return {
754
- isValid: false,
755
- status: "unknown",
756
- method: "ocsp",
757
- reason: "OCSP responder does not know about this certificate",
758
- checkedAt: now,
759
- };
760
- }
761
- return {
762
- isValid: false,
763
- status: "error",
764
- method: "ocsp",
765
- reason: "Unexpected certificate status in OCSP response",
766
- checkedAt: now,
767
- };
768
- }
769
- catch (error) {
770
- return {
771
- isValid: false,
772
- status: "error",
773
- method: "ocsp",
774
- reason: `Failed to parse OCSP response: ${error instanceof Error ? error.message : String(error)}`,
775
- checkedAt: now,
776
- };
777
- }
778
- }
779
- /**
780
- * Check certificate revocation via OCSP
781
- * @param cert Certificate to check
782
- * @param issuerCert Issuer certificate (optional, will try to find/fetch)
783
- * @param options OCSP check options
784
- * @returns Revocation result
785
- */
786
- async function checkOCSP(cert, issuerCert, options = {}) {
787
- const { timeout = 5000, certificateChain = [], proxyUrl } = options;
788
- const now = new Date();
789
- // Get OCSP URLs
790
- const ocspUrls = extractOCSPUrls(cert);
791
- if (ocspUrls.length === 0) {
792
- return {
793
- isValid: false,
794
- status: "unknown",
795
- method: "ocsp",
796
- reason: "Certificate has no OCSP responder URL",
797
- checkedAt: now,
798
- };
799
- }
800
- // Try to find issuer certificate
801
- let issuer = issuerCert;
802
- if (!issuer) {
803
- // Try certificate chain first
804
- issuer = findIssuerInChain(cert, certificateChain);
805
- }
806
- if (!issuer) {
807
- // Try AIA extension
808
- issuer = await fetchIssuerFromAIA(cert, timeout, proxyUrl);
809
- }
810
- if (!issuer) {
811
- return {
812
- isValid: false,
813
- status: "unknown",
814
- method: "ocsp",
815
- reason: "Could not find or fetch issuer certificate for OCSP",
816
- checkedAt: now,
817
- };
818
- }
819
- // Build OCSP request
820
- let request;
821
- try {
822
- request = await buildOCSPRequest(cert, issuer);
823
- }
824
- catch (error) {
825
- return {
826
- isValid: false,
827
- status: "error",
828
- method: "ocsp",
829
- reason: `Failed to build OCSP request: ${error instanceof Error ? error.message : String(error)}`,
830
- checkedAt: now,
831
- };
832
- }
833
- // Try each OCSP URL
834
- for (const url of ocspUrls) {
835
- try {
836
- const result = await fetchOCSP(url, request, timeout, proxyUrl);
837
- if (result.ok && result.data) {
838
- return parseOCSPResponse(result.data);
839
- }
840
- }
841
- catch {
842
- // Try next URL
843
- }
844
- }
845
- return {
846
- isValid: false,
847
- status: "error",
848
- method: "ocsp",
849
- reason: "All OCSP requests failed",
850
- checkedAt: now,
851
- };
852
- }
853
-
854
- const AUTHORITY_KEY_IDENTIFIER_OID = "2.5.29.35";
855
- const SUBJECT_KEY_IDENTIFIER_OID = "2.5.29.14";
856
- async function computeSha256Hex(input) {
857
- const digest = await crypto.subtle.digest("SHA-256", input);
858
- return arrayBufferToHex(digest);
859
- }
860
- function getAuthorityKeyIdentifierHex(certificate) {
861
- const authorityKeyIdentifier = certificate.getExtension(AUTHORITY_KEY_IDENTIFIER_OID);
862
- return normalizeKeyIdentifier(authorityKeyIdentifier?.keyId);
863
- }
864
- function getSubjectKeyIdentifierHex(certificate) {
865
- const subjectKeyIdentifier = certificate.getExtension(SUBJECT_KEY_IDENTIFIER_OID);
866
- return normalizeKeyIdentifier(subjectKeyIdentifier?.keyId);
867
- }
868
- async function extractIssuerIdentityFromCertificate(certificatePem, options = {}) {
869
- const signerCertificate = new X509Certificate(certificatePem);
870
- let issuerCertificate = options.certificateChain && options.certificateChain.length > 0
871
- ? findIssuerInChain(signerCertificate, options.certificateChain)
872
- : null;
873
- if (!issuerCertificate && options.fetchOptions) {
874
- issuerCertificate = await fetchIssuerFromAIA(signerCertificate, options.fetchOptions.timeout, options.fetchOptions.proxyUrl);
875
- }
876
- return {
877
- issuerSubjectDn: normalizeDistinguishedName(signerCertificate.issuer),
878
- authorityKeyIdentifierHex: getAuthorityKeyIdentifierHex(signerCertificate),
879
- issuerCertificate: issuerCertificate
880
- ? {
881
- subjectDn: normalizeDistinguishedName(issuerCertificate.subject),
882
- spkiSha256Hex: await computeSha256Hex(issuerCertificate.publicKey.rawData),
883
- }
884
- : null,
885
- };
886
- }
887
- async function extractCertificateIdentityFromCertificate(certificatePem) {
888
- const certificate = new X509Certificate(certificatePem);
889
- return {
890
- subjectDn: normalizeDistinguishedName(certificate.subject),
891
- subjectKeyIdentifierHex: getSubjectKeyIdentifierHex(certificate),
892
- spkiSha256Hex: await computeSha256Hex(certificate.publicKey.rawData),
893
- };
894
- }
895
-
896
- export { AsnConvert as A, extractCertificateIdentityFromCertificate as a, checkOCSP as c, extractIssuerIdentityFromCertificate as e };
897
- //# sourceMappingURL=identity-b3a70fc1.js.map