parser.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.AsnParser = void 0;
  4. const tslib_1 = require("tslib");
  5. const asn1js = tslib_1.__importStar(require("asn1js"));
  6. const utils_1 = require("@peculiar/utils");
  7. const enums_1 = require("./enums");
  8. const converters = tslib_1.__importStar(require("./converters"));
  9. const errors_1 = require("./errors");
  10. const helper_1 = require("./helper");
  11. const storage_1 = require("./storage");
  12. class AsnParser {
  13. static parse(data, target, options) {
  14. const asn1Parsed = asn1js.fromBER((0, utils_1.toArrayBuffer)(data), options?.berOptions);
  15. if (asn1Parsed.result.error) {
  16. throw new Error(asn1Parsed.result.error);
  17. }
  18. const res = this.fromASN(asn1Parsed.result, target, options);
  19. return res;
  20. }
  21. static fromASN(asn1Schema, target, options) {
  22. try {
  23. if ((0, helper_1.isConvertible)(target)) {
  24. const value = new target();
  25. return value.fromASN(asn1Schema);
  26. }
  27. const schema = storage_1.schemaStorage.get(target);
  28. storage_1.schemaStorage.cache(target);
  29. let targetSchema = schema.schema;
  30. const choiceResult = this.handleChoiceTypes(asn1Schema, schema, target, targetSchema, options);
  31. if (choiceResult?.result) {
  32. return choiceResult.result;
  33. }
  34. if (choiceResult?.targetSchema) {
  35. targetSchema = choiceResult.targetSchema;
  36. }
  37. const sequenceResult = this.handleSequenceTypes(asn1Schema, schema, target, targetSchema);
  38. const res = new target();
  39. if ((0, helper_1.isTypeOfArray)(target)) {
  40. return this.handleArrayTypes(asn1Schema, schema, target, options);
  41. }
  42. this.processSchemaItems(schema, sequenceResult, res, options);
  43. return res;
  44. }
  45. catch (error) {
  46. if (error instanceof errors_1.AsnSchemaValidationError) {
  47. error.schemas.push(target.name);
  48. }
  49. throw error;
  50. }
  51. }
  52. static handleChoiceTypes(asn1Schema, schema, target, targetSchema, options) {
  53. if (asn1Schema.constructor === asn1js.Constructed && schema.type === enums_1.AsnTypeTypes.Choice && asn1Schema.idBlock.tagClass === 3) {
  54. for (const key in schema.items) {
  55. const schemaItem = schema.items[key];
  56. if (schemaItem.context === asn1Schema.idBlock.tagNumber && schemaItem.implicit) {
  57. if (typeof schemaItem.type === "function" && storage_1.schemaStorage.has(schemaItem.type)) {
  58. const fieldSchema = storage_1.schemaStorage.get(schemaItem.type);
  59. if (fieldSchema && fieldSchema.type === enums_1.AsnTypeTypes.Sequence) {
  60. const newSeq = new asn1js.Sequence();
  61. if ("value" in asn1Schema.valueBlock && Array.isArray(asn1Schema.valueBlock.value) && "value" in newSeq.valueBlock) {
  62. newSeq.valueBlock.value = asn1Schema.valueBlock.value;
  63. const fieldValue = this.fromASN(newSeq, schemaItem.type, options);
  64. const res = new target();
  65. res[key] = fieldValue;
  66. return { result: res };
  67. }
  68. }
  69. }
  70. }
  71. }
  72. }
  73. else if (asn1Schema.constructor === asn1js.Constructed && schema.type !== enums_1.AsnTypeTypes.Choice) {
  74. const newTargetSchema = new asn1js.Constructed({
  75. idBlock: {
  76. tagClass: 3,
  77. tagNumber: asn1Schema.idBlock.tagNumber,
  78. },
  79. value: schema.schema.valueBlock.value,
  80. });
  81. for (const key in schema.items) {
  82. delete asn1Schema[key];
  83. }
  84. return { targetSchema: newTargetSchema };
  85. }
  86. return null;
  87. }
  88. static handleSequenceTypes(asn1Schema, schema, target, targetSchema) {
  89. if (schema.type === enums_1.AsnTypeTypes.Sequence) {
  90. const asn1ComparedSchema = asn1js.compareSchema({}, asn1Schema, targetSchema);
  91. if (!asn1ComparedSchema.verified) {
  92. throw new errors_1.AsnSchemaValidationError(`Data does not match to ${target.name} ASN1 schema.${asn1ComparedSchema.result.error ? ` ${asn1ComparedSchema.result.error}` : ""}`);
  93. }
  94. return asn1ComparedSchema;
  95. }
  96. else {
  97. const asn1ComparedSchema = asn1js.compareSchema({}, asn1Schema, targetSchema);
  98. if (!asn1ComparedSchema.verified) {
  99. throw new errors_1.AsnSchemaValidationError(`Data does not match to ${target.name} ASN1 schema.${asn1ComparedSchema.result.error ? ` ${asn1ComparedSchema.result.error}` : ""}`);
  100. }
  101. return asn1ComparedSchema;
  102. }
  103. }
  104. static processRepeatedField(asn1Elements, asn1Index, schemaItem) {
  105. let elementsToProcess = asn1Elements.slice(asn1Index);
  106. if (elementsToProcess.length === 1 && elementsToProcess[0].constructor.name === "Sequence") {
  107. const seq = elementsToProcess[0];
  108. if (seq.valueBlock && seq.valueBlock.value && Array.isArray(seq.valueBlock.value)) {
  109. elementsToProcess = seq.valueBlock.value;
  110. }
  111. }
  112. if (typeof schemaItem.type === "number") {
  113. const converter = converters.defaultConverter(schemaItem.type);
  114. if (!converter)
  115. throw new Error(`No converter for ASN.1 type ${schemaItem.type}`);
  116. return elementsToProcess
  117. .filter((el) => el && el.valueBlock)
  118. .map((el) => {
  119. try {
  120. return converter.fromASN(el);
  121. }
  122. catch {
  123. return undefined;
  124. }
  125. })
  126. .filter((v) => v !== undefined);
  127. }
  128. else {
  129. return elementsToProcess
  130. .filter((el) => el && el.valueBlock)
  131. .map((el) => {
  132. try {
  133. return this.fromASN(el, schemaItem.type);
  134. }
  135. catch {
  136. return undefined;
  137. }
  138. })
  139. .filter((v) => v !== undefined);
  140. }
  141. }
  142. static processPrimitiveField(asn1Element, schemaItem) {
  143. const converter = converters.defaultConverter(schemaItem.type);
  144. if (!converter)
  145. throw new Error(`No converter for ASN.1 type ${schemaItem.type}`);
  146. return converter.fromASN(asn1Element);
  147. }
  148. static isOptionalChoiceField(schemaItem) {
  149. return (schemaItem.optional &&
  150. typeof schemaItem.type === "function" &&
  151. storage_1.schemaStorage.has(schemaItem.type) &&
  152. storage_1.schemaStorage.get(schemaItem.type).type === enums_1.AsnTypeTypes.Choice);
  153. }
  154. static processOptionalChoiceField(asn1Element, schemaItem) {
  155. try {
  156. const value = this.fromASN(asn1Element, schemaItem.type);
  157. return {
  158. processed: true,
  159. value,
  160. };
  161. }
  162. catch (err) {
  163. if (err instanceof errors_1.AsnSchemaValidationError && /Wrong values for Choice type/.test(err.message)) {
  164. return { processed: false };
  165. }
  166. throw err;
  167. }
  168. }
  169. static handleArrayTypes(asn1Schema, schema, target, options) {
  170. if (!("value" in asn1Schema.valueBlock && Array.isArray(asn1Schema.valueBlock.value))) {
  171. throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");
  172. }
  173. const itemType = schema.itemType;
  174. if (typeof itemType === "number") {
  175. const converter = converters.defaultConverter(itemType);
  176. if (!converter) {
  177. throw new Error(`Cannot get default converter for array item of ${target.name} ASN1 schema`);
  178. }
  179. return target.from(asn1Schema.valueBlock.value, (element) => converter.fromASN(element));
  180. }
  181. else {
  182. return target.from(asn1Schema.valueBlock.value, (element) => this.fromASN(element, itemType, options));
  183. }
  184. }
  185. static processSchemaItems(schema, asn1ComparedSchema, res, options) {
  186. for (const key in schema.items) {
  187. const asn1SchemaValue = asn1ComparedSchema.result[key];
  188. if (!asn1SchemaValue) {
  189. continue;
  190. }
  191. const schemaItem = schema.items[key];
  192. const schemaItemType = schemaItem.type;
  193. let parsedValue;
  194. if (typeof schemaItemType === "number" || (0, helper_1.isConvertible)(schemaItemType)) {
  195. parsedValue = this.processPrimitiveSchemaItem(asn1SchemaValue, schemaItem, schemaItemType, options);
  196. }
  197. else {
  198. parsedValue = this.processComplexSchemaItem(asn1SchemaValue, schemaItem, schemaItemType, options);
  199. }
  200. if (parsedValue && typeof parsedValue === "object" && "value" in parsedValue && "raw" in parsedValue) {
  201. res[key] = parsedValue.value;
  202. res[`${key}Raw`] = parsedValue.raw;
  203. }
  204. else {
  205. res[key] = parsedValue;
  206. }
  207. }
  208. }
  209. static processPrimitiveSchemaItem(asn1SchemaValue, schemaItem, schemaItemType, options) {
  210. const converter = schemaItem.converter ?? ((0, helper_1.isConvertible)(schemaItemType) ? new schemaItemType() : null);
  211. if (!converter) {
  212. throw new Error("Converter is empty");
  213. }
  214. if (schemaItem.repeated) {
  215. return this.processRepeatedPrimitiveItem(asn1SchemaValue, schemaItem, converter, options);
  216. }
  217. else {
  218. return this.processSinglePrimitiveItem(asn1SchemaValue, schemaItem, schemaItemType, converter, options);
  219. }
  220. }
  221. static processRepeatedPrimitiveItem(asn1SchemaValue, schemaItem, converter, options) {
  222. if (schemaItem.implicit) {
  223. const Container = schemaItem.repeated === "sequence" ? asn1js.Sequence : asn1js.Set;
  224. const newItem = new Container();
  225. newItem.valueBlock = asn1SchemaValue.valueBlock;
  226. const newItemAsn = asn1js.fromBER(newItem.toBER(false), options?.berOptions);
  227. if (newItemAsn.offset === -1) {
  228. throw new Error(`Cannot parse the child item. ${newItemAsn.result.error}`);
  229. }
  230. if (!("value" in newItemAsn.result.valueBlock && Array.isArray(newItemAsn.result.valueBlock.value))) {
  231. throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");
  232. }
  233. const value = newItemAsn.result.valueBlock.value;
  234. return Array.from(value, (element) => converter.fromASN(element));
  235. }
  236. else {
  237. return Array.from(asn1SchemaValue, (element) => converter.fromASN(element));
  238. }
  239. }
  240. static processSinglePrimitiveItem(asn1SchemaValue, schemaItem, schemaItemType, converter, options) {
  241. let value = asn1SchemaValue;
  242. if (schemaItem.implicit) {
  243. let newItem;
  244. if ((0, helper_1.isConvertible)(schemaItemType)) {
  245. newItem = new schemaItemType().toSchema("");
  246. }
  247. else {
  248. const Asn1TypeName = enums_1.AsnPropTypes[schemaItemType];
  249. const Asn1Type = asn1js[Asn1TypeName];
  250. if (!Asn1Type) {
  251. throw new Error(`Cannot get '${Asn1TypeName}' class from asn1js module`);
  252. }
  253. newItem = new Asn1Type();
  254. }
  255. newItem.valueBlock = value.valueBlock;
  256. value = asn1js.fromBER(newItem.toBER(false), options?.berOptions).result;
  257. }
  258. return converter.fromASN(value);
  259. }
  260. static processComplexSchemaItem(asn1SchemaValue, schemaItem, schemaItemType, options) {
  261. if (schemaItem.repeated) {
  262. if (!Array.isArray(asn1SchemaValue)) {
  263. throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");
  264. }
  265. return Array.from(asn1SchemaValue, (element) => this.fromASN(element, schemaItemType, options));
  266. }
  267. else {
  268. const valueToProcess = this.handleImplicitTagging(asn1SchemaValue, schemaItem, schemaItemType);
  269. if (this.isOptionalChoiceField(schemaItem)) {
  270. try {
  271. return this.fromASN(valueToProcess, schemaItemType, options);
  272. }
  273. catch (err) {
  274. if (err instanceof errors_1.AsnSchemaValidationError && /Wrong values for Choice type/.test(err.message)) {
  275. return undefined;
  276. }
  277. throw err;
  278. }
  279. }
  280. else {
  281. const parsedValue = this.fromASN(valueToProcess, schemaItemType, options);
  282. if (schemaItem.raw) {
  283. return {
  284. value: parsedValue,
  285. raw: asn1SchemaValue.valueBeforeDecodeView,
  286. };
  287. }
  288. return parsedValue;
  289. }
  290. }
  291. }
  292. static handleImplicitTagging(asn1SchemaValue, schemaItem, schemaItemType) {
  293. if (schemaItem.implicit && typeof schemaItem.context === "number") {
  294. const schema = storage_1.schemaStorage.get(schemaItemType);
  295. if (schema.type === enums_1.AsnTypeTypes.Sequence) {
  296. const newSeq = new asn1js.Sequence();
  297. if ("value" in asn1SchemaValue.valueBlock && Array.isArray(asn1SchemaValue.valueBlock.value) && "value" in newSeq.valueBlock) {
  298. newSeq.valueBlock.value = asn1SchemaValue.valueBlock.value;
  299. return newSeq;
  300. }
  301. }
  302. else if (schema.type === enums_1.AsnTypeTypes.Set) {
  303. const newSet = new asn1js.Set();
  304. if ("value" in asn1SchemaValue.valueBlock && Array.isArray(asn1SchemaValue.valueBlock.value) && "value" in newSet.valueBlock) {
  305. newSet.valueBlock.value = asn1SchemaValue.valueBlock.value;
  306. return newSet;
  307. }
  308. }
  309. }
  310. return asn1SchemaValue;
  311. }
  312. }
  313. exports.AsnParser = AsnParser;