@netkitty/codec 1.2.1 → 2.1.0

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 (205) hide show
  1. package/CHANGELOG.md +295 -0
  2. package/README.md +62 -10
  3. package/README.zh-CN.md +55 -9
  4. package/dist/Codec.d.ts +3 -2
  5. package/dist/Codec.js +109 -10
  6. package/dist/abstracts/BaseHeader.d.ts +54 -2
  7. package/dist/abstracts/BaseHeader.js +185 -43
  8. package/dist/errors/CodecSchemaValidateError.d.ts +34 -1
  9. package/dist/errors/CodecSchemaValidateError.js +26 -3
  10. package/dist/headers/ADSAMS.js +2 -0
  11. package/dist/headers/AH.js +4 -2
  12. package/dist/headers/AMQP.js +2 -1
  13. package/dist/headers/ARP.js +16 -10
  14. package/dist/headers/BACnetIP.js +1 -0
  15. package/dist/headers/BFD.d.ts +2 -1
  16. package/dist/headers/BFD.js +30 -4
  17. package/dist/headers/BGP.js +6 -1
  18. package/dist/headers/Babel.js +2 -1
  19. package/dist/headers/BitTorrent.d.ts +2 -0
  20. package/dist/headers/BitTorrent.js +4 -2
  21. package/dist/headers/C37118.d.ts +3 -2
  22. package/dist/headers/C37118.js +35 -15
  23. package/dist/headers/CAPWAP.js +1 -0
  24. package/dist/headers/CDP.d.ts +3 -3
  25. package/dist/headers/CDP.js +47 -11
  26. package/dist/headers/CMS.js +27 -12
  27. package/dist/headers/COTP.d.ts +2 -0
  28. package/dist/headers/COTP.js +8 -4
  29. package/dist/headers/CassandraCQL.js +1 -0
  30. package/dist/headers/CoAP.js +20 -2
  31. package/dist/headers/Codesys.js +1 -0
  32. package/dist/headers/Collectd.js +1 -1
  33. package/dist/headers/DCCP.d.ts +3 -2
  34. package/dist/headers/DCCP.js +61 -8
  35. package/dist/headers/DHCPFailover.js +1 -0
  36. package/dist/headers/DNP3.d.ts +5 -3
  37. package/dist/headers/DNP3.js +62 -7
  38. package/dist/headers/DNS.js +3 -3
  39. package/dist/headers/DTLS.js +1 -0
  40. package/dist/headers/Diameter.js +3 -2
  41. package/dist/headers/EAPOL.js +1 -1
  42. package/dist/headers/EIGRP.d.ts +3 -2
  43. package/dist/headers/EIGRP.js +32 -6
  44. package/dist/headers/ENIP.js +1 -0
  45. package/dist/headers/Elasticsearch.js +1 -0
  46. package/dist/headers/EtherCAT.js +1 -0
  47. package/dist/headers/EthernetII.js +7 -0
  48. package/dist/headers/FTP.js +6 -6
  49. package/dist/headers/Finger.js +3 -3
  50. package/dist/headers/FoundationFieldbusHSE.js +1 -0
  51. package/dist/headers/GELF.js +8 -1
  52. package/dist/headers/GENEVE.js +2 -1
  53. package/dist/headers/GLBP.js +1 -1
  54. package/dist/headers/GRE.js +1 -0
  55. package/dist/headers/GTPU.js +1 -0
  56. package/dist/headers/GTPv2C.js +2 -0
  57. package/dist/headers/GitProtocol.js +2 -2
  58. package/dist/headers/Goose.js +24 -12
  59. package/dist/headers/Gopher.js +6 -6
  60. package/dist/headers/HARTIP.js +1 -0
  61. package/dist/headers/HSR.js +3 -0
  62. package/dist/headers/HTTP.js +6 -6
  63. package/dist/headers/HTTP2.js +2 -0
  64. package/dist/headers/ICMP.js +3 -1
  65. package/dist/headers/ICMPv6.js +11 -16
  66. package/dist/headers/IEC104_I_Frame.js +215 -163
  67. package/dist/headers/IEC104_S_Frame.js +26 -3
  68. package/dist/headers/IEC104_U_Frame.js +33 -4
  69. package/dist/headers/IEC61850SampledValues.js +6 -5
  70. package/dist/headers/IGMP.d.ts +8 -7
  71. package/dist/headers/IGMP.js +58 -19
  72. package/dist/headers/IMAP.js +5 -5
  73. package/dist/headers/IPFIX.js +3 -2
  74. package/dist/headers/IPv4.js +41 -21
  75. package/dist/headers/IPv6.js +5 -1
  76. package/dist/headers/IPv6HopByHopOptions.js +15 -12
  77. package/dist/headers/IRC.js +4 -4
  78. package/dist/headers/ISAKMP.js +3 -1
  79. package/dist/headers/ISCSI.js +2 -0
  80. package/dist/headers/ISIS.js +2 -1
  81. package/dist/headers/ISOSession.d.ts +2 -0
  82. package/dist/headers/ISOSession.js +14 -10
  83. package/dist/headers/Ident.js +8 -8
  84. package/dist/headers/KNXnetIP.js +1 -0
  85. package/dist/headers/Kafka.js +1 -0
  86. package/dist/headers/Kerberos.js +2 -0
  87. package/dist/headers/L2TP.js +3 -2
  88. package/dist/headers/LACP.js +1 -1
  89. package/dist/headers/LDAP.js +3 -4
  90. package/dist/headers/LDP.js +1 -0
  91. package/dist/headers/LLC.d.ts +2 -0
  92. package/dist/headers/LLC.js +3 -0
  93. package/dist/headers/LPD.js +3 -3
  94. package/dist/headers/MGCP.js +7 -7
  95. package/dist/headers/MMS.d.ts +2 -0
  96. package/dist/headers/MMS.js +10 -6
  97. package/dist/headers/MQTT.js +1 -0
  98. package/dist/headers/MQTTSN.js +1 -0
  99. package/dist/headers/MarkerProtocol.js +1 -1
  100. package/dist/headers/Megaco.js +3 -3
  101. package/dist/headers/Memcached.js +3 -2
  102. package/dist/headers/ModbusTCP.js +1 -0
  103. package/dist/headers/ModbusUDP.js +1 -0
  104. package/dist/headers/MongoDB.js +1 -0
  105. package/dist/headers/MySQL.js +1 -0
  106. package/dist/headers/NATS.js +2 -2
  107. package/dist/headers/NBDS.js +1 -0
  108. package/dist/headers/NBSS.js +1 -0
  109. package/dist/headers/NFS.js +1 -0
  110. package/dist/headers/NHRP.d.ts +1 -1
  111. package/dist/headers/NHRP.js +30 -4
  112. package/dist/headers/NNTP.js +6 -6
  113. package/dist/headers/NetFlowV5.js +1 -0
  114. package/dist/headers/OLSR.js +2 -1
  115. package/dist/headers/OPCUA.js +1 -0
  116. package/dist/headers/OSPF.d.ts +3 -3
  117. package/dist/headers/OSPF.js +72 -7
  118. package/dist/headers/OpenFlow.js +1 -0
  119. package/dist/headers/OpenVPN.js +1 -0
  120. package/dist/headers/PCWorx.js +1 -0
  121. package/dist/headers/PIM.d.ts +3 -3
  122. package/dist/headers/PIM.js +55 -6
  123. package/dist/headers/POP3.js +5 -5
  124. package/dist/headers/PPPoEDiscovery.js +4 -1
  125. package/dist/headers/PPPoESession.js +1 -0
  126. package/dist/headers/PPTP.js +1 -0
  127. package/dist/headers/PTP.js +6 -1
  128. package/dist/headers/PostgreSQL.js +2 -0
  129. package/dist/headers/QUIC.js +2 -0
  130. package/dist/headers/RADIUS.js +1 -0
  131. package/dist/headers/RDP.d.ts +2 -0
  132. package/dist/headers/RDP.js +6 -1
  133. package/dist/headers/RFB.js +4 -4
  134. package/dist/headers/RGoose.js +8 -1
  135. package/dist/headers/RSVP.d.ts +3 -3
  136. package/dist/headers/RSVP.js +59 -44
  137. package/dist/headers/RTCP.js +2 -0
  138. package/dist/headers/RTP.js +2 -1
  139. package/dist/headers/RTPS.d.ts +2 -0
  140. package/dist/headers/RTPS.js +4 -1
  141. package/dist/headers/RTSP.js +7 -7
  142. package/dist/headers/RawData.js +1 -1
  143. package/dist/headers/Redis.js +4 -4
  144. package/dist/headers/Rlogin.js +5 -5
  145. package/dist/headers/Rsync.js +2 -2
  146. package/dist/headers/S7comm.d.ts +2 -0
  147. package/dist/headers/S7comm.js +5 -1
  148. package/dist/headers/SCTP.d.ts +2 -2
  149. package/dist/headers/SCTP.js +31 -7
  150. package/dist/headers/SFlow.js +2 -1
  151. package/dist/headers/SIP.js +6 -6
  152. package/dist/headers/SLMP.js +1 -0
  153. package/dist/headers/SLP.js +2 -0
  154. package/dist/headers/SLPv1.js +1 -0
  155. package/dist/headers/SMB1.js +1 -0
  156. package/dist/headers/SMB2.js +1 -0
  157. package/dist/headers/SMPP.js +1 -0
  158. package/dist/headers/SMTP.js +6 -6
  159. package/dist/headers/SNAP.js +18 -5
  160. package/dist/headers/SNMP.js +6 -6
  161. package/dist/headers/SOCKS4.js +11 -5
  162. package/dist/headers/SSDP.js +7 -7
  163. package/dist/headers/SSH.js +5 -4
  164. package/dist/headers/STOMP.js +5 -5
  165. package/dist/headers/STUN.js +3 -1
  166. package/dist/headers/SercosIII.d.ts +3 -2
  167. package/dist/headers/SercosIII.js +41 -5
  168. package/dist/headers/Skinny.js +1 -0
  169. package/dist/headers/StatsD.js +4 -4
  170. package/dist/headers/SunRPC.js +1 -0
  171. package/dist/headers/Syslog.js +2 -2
  172. package/dist/headers/TCP.js +31 -64
  173. package/dist/headers/TLS_Alert.js +42 -12
  174. package/dist/headers/TLS_ApplicationData.d.ts +3 -3
  175. package/dist/headers/TLS_ApplicationData.js +32 -8
  176. package/dist/headers/TLS_ChangeCipherSpec.d.ts +2 -2
  177. package/dist/headers/TLS_ChangeCipherSpec.js +33 -8
  178. package/dist/headers/TLS_Handshake.js +78 -30
  179. package/dist/headers/TLS_Heartbeat.d.ts +4 -3
  180. package/dist/headers/TLS_Heartbeat.js +50 -8
  181. package/dist/headers/TPKT.js +4 -2
  182. package/dist/headers/TacacsPlus.js +1 -0
  183. package/dist/headers/Telnet.js +2 -1
  184. package/dist/headers/Teredo.js +2 -2
  185. package/dist/headers/UDP.js +20 -56
  186. package/dist/headers/VLAN_802dot1Q.js +8 -0
  187. package/dist/headers/VRRP.d.ts +2 -1
  188. package/dist/headers/VRRP.js +45 -9
  189. package/dist/headers/WCCP.js +1 -0
  190. package/dist/headers/WHOIS.js +3 -3
  191. package/dist/headers/WSDiscovery.js +2 -2
  192. package/dist/headers/XMPP.js +3 -3
  193. package/dist/headers/Zabbix.js +1 -0
  194. package/dist/helper/Checksum.d.ts +15 -0
  195. package/dist/helper/Checksum.js +56 -0
  196. package/dist/helper/Crc.d.ts +18 -0
  197. package/dist/helper/Crc.js +58 -0
  198. package/dist/index.d.ts +3 -3
  199. package/dist/lib/SchemaValidator.d.ts +31 -0
  200. package/dist/lib/SchemaValidator.js +137 -0
  201. package/dist/schema/ProtocolFieldJSONSchema.d.ts +4 -1
  202. package/dist/schema/ProtocolJSONSchema.d.ts +1 -1
  203. package/dist/types/CodecErrorInfo.d.ts +11 -0
  204. package/dist/types/LayerGraph.d.ts +14 -1
  205. package/package.json +2 -2
package/dist/Codec.js CHANGED
@@ -32,11 +32,13 @@ var __importStar = (this && this.__importStar) || (function () {
32
32
  return result;
33
33
  };
34
34
  })();
35
+ var _a;
35
36
  Object.defineProperty(exports, "__esModule", { value: true });
36
37
  exports.Codec = void 0;
37
38
  const FlexibleObject_1 = require("./lib/FlexibleObject");
38
39
  const ProcessPacketPostHandlers_1 = require("./lib/ProcessPacketPostHandlers");
39
40
  const RawData_1 = require("./headers/RawData");
41
+ const CodecSchemaValidateError_1 = require("./errors/CodecSchemaValidateError");
40
42
  const packetHeaders = __importStar(require("./PacketHeaders"));
41
43
  /**
42
44
  * The schema-driven packet codec: the entry point a consumer uses to turn bytes into a
@@ -81,6 +83,13 @@ class Codec {
81
83
  * encoded layer. First registration wins, preserving the previous `.find` first-match semantics.
82
84
  */
83
85
  #codecConstructorById = new Map();
86
+ /**
87
+ * Editor graph: parent layer id → content-heuristic children that declare it in heuristicParents.
88
+ * Read only by allowedNextLayers(); decode never consults it.
89
+ */
90
+ #heuristicChildren = new Map();
91
+ /** Memoised childDiscriminator() for encode-time inference (parent\0child → discriminator). */
92
+ #discriminatorCache = new Map();
84
93
  /**
85
94
  * The RawData catch-all. Not part of the dispatch table or heuristic list;
86
95
  * used explicitly as the final fallback so decode never fails.
@@ -147,6 +156,8 @@ class Codec {
147
156
  this.#heuristicCodecs.length = 0;
148
157
  this.#rangeTable.clear();
149
158
  this.#codecConstructorById.clear();
159
+ this.#heuristicChildren.clear();
160
+ this.#discriminatorCache.clear();
150
161
  for (const codecModuleConstructor of this.HEADER_CODECS) {
151
162
  //Read PROTOCOL_ID once (the getter builds a throwaway instance) and register it for O(1)
152
163
  //encode lookup; keep the first registration so this matches the old `.find` first-match.
@@ -157,6 +168,18 @@ class Codec {
157
168
  this.#rawDataCodec = codecModuleConstructor;
158
169
  continue;
159
170
  }
171
+ for (const heuristicParent of codecModuleConstructor.HEURISTIC_PARENTS || []) {
172
+ const parentId = typeof heuristicParent === 'string' ? heuristicParent : heuristicParent.parent;
173
+ const entry = {
174
+ codecModuleConstructor: codecModuleConstructor,
175
+ discriminator: typeof heuristicParent === 'string' ? null : heuristicParent.discriminator
176
+ };
177
+ const children = this.#heuristicChildren.get(parentId);
178
+ if (children)
179
+ children.push(entry);
180
+ else
181
+ this.#heuristicChildren.set(parentId, [entry]);
182
+ }
160
183
  const matchKeys = codecModuleConstructor.MATCH_KEYS;
161
184
  const keyed = !!(matchKeys && matchKeys.length);
162
185
  if (keyed) {
@@ -318,31 +341,87 @@ class Codec {
318
341
  /**
319
342
  * Internal encode headers to packet
320
343
  * @param inputs
321
- * @param errors
344
+ * @param reports per input, in order: the encoded module (its errors are read later, once
345
+ * packet-level post handlers have also had a chance to record) or a codec-level error
322
346
  * @private
323
347
  */
324
- async #encode(inputs, errors = []) {
348
+ async #encode(inputs, reports = []) {
325
349
  const codecData = {
326
350
  packet: Buffer.from([]),
327
351
  startPos: 0,
328
352
  postHandlers: []
329
353
  };
330
354
  const codecModules = [];
331
- for (const input of inputs) {
355
+ for (let layerIndex = 0; layerIndex < inputs.length; layerIndex++) {
356
+ const input = inputs[layerIndex];
332
357
  const codecModuleConstructor = this.#codecConstructorById.get(input.id);
333
358
  if (!codecModuleConstructor) {
334
- errors.push({ id: input.id, path: '', message: `Unknown protocol id: ${input.id}` });
359
+ reports.push({ id: input.id, path: '', message: `Unknown protocol id: ${input.id}`, severity: 'error' });
335
360
  continue;
336
361
  }
337
362
  const codecModule = codecModuleConstructor.CREATE_INSTANCE(codecData, codecModules);
338
- codecModule.instance = new FlexibleObject_1.FlexibleObject(codecModule.validate(input.data));
363
+ let validated;
364
+ try {
365
+ //Ajv fills schema defaults into, and coerces types in, the object it validates. Work on
366
+ //a deep copy so the caller's input is never changed (re-encoding it later must not
367
+ //replay those defaults as explicit values).
368
+ validated = codecModule.validate(structuredClone(input.data));
369
+ }
370
+ catch (e) {
371
+ //Name the input layer by position too, so a caller can bind the error to its form.
372
+ if (e instanceof CodecSchemaValidateError_1.CodecSchemaValidateError)
373
+ e.layerIndex = layerIndex;
374
+ throw e;
375
+ }
376
+ codecModule.instance = new FlexibleObject_1.FlexibleObject(this.#inferDiscriminator(codecModule, validated, inputs[layerIndex + 1]));
339
377
  await codecModule.encode();
340
- codecModule.errors.forEach((errorInfo) => errors.push(errorInfo));
378
+ reports.push(codecModule);
341
379
  codecData.startPos = codecModule.endPos;
342
380
  codecModules.push(codecModule);
343
381
  }
344
382
  return codecData;
345
383
  }
384
+ /**
385
+ * Demux namespaces whose producer field encode fills from the next input layer when it is left out:
386
+ * the EtherType (eth/vlan/hsr/gre/geneve…) and the IP protocol / IPv6 next header. Explicit values
387
+ * always win, so a deliberately inconsistent packet can still be crafted.
388
+ * @private
389
+ */
390
+ static #INFERRED_NAMESPACES = ['ethertype', 'ipproto'];
391
+ /**
392
+ * When none of a layer's producer fields (in an inferred namespace) was supplied, set the one that
393
+ * routes decode to the next input layer, e.g. eth.etherType = '0800' before ipv4 — the value
394
+ * childDiscriminator() would suggest. A layer whose child is matched by content (LLC after eth)
395
+ * derives its own value instead (see EthernetII's 802.3 length). The value goes on a shallow copy:
396
+ * the caller's input object is left as given, so re-encoding it after the next layer changes infers
397
+ * again instead of replaying a stale "explicit" value.
398
+ * @private
399
+ */
400
+ #inferDiscriminator(codecModule, data, next) {
401
+ if (!next || !data || typeof data !== 'object')
402
+ return data;
403
+ const fields = data;
404
+ const producers = codecModule.demuxProducers.filter((producer) => _a.#INFERRED_NAMESPACES.includes(producer.namespace));
405
+ if (!producers.length)
406
+ return data;
407
+ if (producers.some((producer) => fields[producer.field] !== undefined))
408
+ return data;
409
+ const discriminator = this.#childDiscriminatorCached(codecModule.id, next.id);
410
+ if (!discriminator || !producers.some((producer) => producer.field === discriminator.field))
411
+ return data;
412
+ return { ...data, [discriminator.field]: discriminator.value };
413
+ }
414
+ /**
415
+ * childDiscriminator() memoised per parent/child pair for the encode path: it reverses the whole
416
+ * dispatch table, which is too much work to repeat for every encoded layer. Cleared with the table.
417
+ * @private
418
+ */
419
+ #childDiscriminatorCached(parentLayerId, childLayerId) {
420
+ const key = `${parentLayerId}\u0000${childLayerId}`;
421
+ if (!this.#discriminatorCache.has(key))
422
+ this.#discriminatorCache.set(key, this.childDiscriminator(parentLayerId, childLayerId));
423
+ return this.#discriminatorCache.get(key);
424
+ }
346
425
  /**
347
426
  * Internal decode packet
348
427
  * @param codecData
@@ -397,14 +476,23 @@ class Codec {
397
476
  * @param inputs
398
477
  */
399
478
  async encode(inputs) {
400
- const errors = [];
401
- const codecData = await this.#encode(inputs, errors);
479
+ const reports = [];
480
+ const codecData = await this.#encode(inputs, reports);
402
481
  const postEncodeHandlers = (0, ProcessPacketPostHandlers_1.ProcessPacketEncodePostHandlers)(codecData.postHandlers);
403
482
  let postEncodeHandler = postEncodeHandlers.shift();
404
483
  while (postEncodeHandler) {
405
484
  await postEncodeHandler.handler();
406
485
  postEncodeHandler = postEncodeHandlers.shift();
407
486
  }
487
+ //Collect each layer's errors only now, so those recorded by packet-level post handlers (which
488
+ //run after every layer is encoded) are reported too; layer order is preserved.
489
+ const errors = [];
490
+ for (const report of reports) {
491
+ if (Array.isArray(report.errors))
492
+ report.errors.forEach((errorInfo) => errors.push(errorInfo));
493
+ else
494
+ errors.push(report);
495
+ }
408
496
  return {
409
497
  packet: codecData.packetLength === undefined ? codecData.packet : codecData.packet.subarray(0, codecData.packetLength),
410
498
  errors: errors
@@ -423,8 +511,9 @@ class Codec {
423
511
  /**
424
512
  * Editor helper (read-only projection over the same demux graph decode uses): the layers that
425
513
  * may follow `parentLayerId`, each tagged with the {field,value} to set on the parent so decode
426
- * would route to it. Derived by reversing the dispatch table over the parent's producer fields.
427
- * RawData is always appended as the custom/fallback layer that may follow anything.
514
+ * would route to it. Derived by reversing the dispatch table over the parent's producer fields,
515
+ * plus the content-heuristic children that declare this parent in `heuristicParents` (listed with a
516
+ * null discriminator). RawData is always appended as the custom/fallback layer that may follow anything.
428
517
  * @param parentLayerId
429
518
  */
430
519
  allowedNextLayers(parentLayerId) {
@@ -458,6 +547,15 @@ class Codec {
458
547
  }
459
548
  }
460
549
  }
550
+ //Content-heuristic children (LLC after eth, COTP after TPKT, …): routed by their own bytes or by a
551
+ //value encode derives, so usually there is no parent field to set (discriminator null); a child
552
+ //may declare the parent value it needs (RDP: COTP pduType 0xE0).
553
+ for (const { codecModuleConstructor, discriminator } of this.#heuristicChildren.get(parentLayerId) || []) {
554
+ if (seen.has(codecModuleConstructor.PROTOCOL_ID))
555
+ continue;
556
+ seen.add(codecModuleConstructor.PROTOCOL_ID);
557
+ result.push({ id: codecModuleConstructor.PROTOCOL_ID, name: codecModuleConstructor.PROTOCOL_NAME, discriminator: discriminator });
558
+ }
461
559
  result.push({ id: this.#rawDataCodec.PROTOCOL_ID, name: this.#rawDataCodec.PROTOCOL_NAME, discriminator: null });
462
560
  return result;
463
561
  }
@@ -630,3 +728,4 @@ class Codec {
630
728
  }
631
729
  }
632
730
  exports.Codec = Codec;
731
+ _a = Codec;
@@ -1,10 +1,11 @@
1
1
  import { ProtocolJSONSchema } from '../schema/ProtocolJSONSchema';
2
2
  import { CodecModule } from '../types/CodecModule';
3
3
  import { ProtocolFieldJSONSchema } from '../schema/ProtocolFieldJSONSchema';
4
- import { CodecErrorInfo } from '../types/CodecErrorInfo';
4
+ import { CodecErrorInfo, CodecErrorSeverity } from '../types/CodecErrorInfo';
5
5
  import { PostHandlerItem } from '../types/PostHandlerItem';
6
6
  import { CodecData } from '../types/CodecData';
7
7
  import { DemuxProducer } from '../types/DemuxProducer';
8
+ import { HeuristicParent } from '../types/LayerGraph';
8
9
  import { FlexibleObject } from '../lib/FlexibleObject';
9
10
  import { HeaderTreeNode } from '../types/HeaderTreeNode';
10
11
  /** Absolute byte span a field occupies in the packet, collected during a dissect pass. */
@@ -54,6 +55,8 @@ export declare abstract class BaseHeader {
54
55
  * false: matchKeys → bucket only; no matchKeys → heuristic only.
55
56
  */
56
57
  static get HEURISTIC_FALLBACK(): boolean;
58
+ /** Parent layer ids a content-heuristic header can follow (see the instance field heuristicParents). */
59
+ static get HEURISTIC_PARENTS(): HeuristicParent[];
57
60
  /** Higher is tried first within a demux bucket and within the heuristic chain; ties keep registration order. */
58
61
  static get MATCH_PRIORITY(): number;
59
62
  static get PROTOCOL_SCHEMA(): ProtocolJSONSchema;
@@ -101,6 +104,15 @@ export declare abstract class BaseHeader {
101
104
  readonly heuristicFallback: boolean;
102
105
  /** Selection priority within a bucket / the heuristic chain (higher first; ties keep registration order). */
103
106
  readonly matchPriority: number;
107
+ /**
108
+ * Editor graph only (never used to select a codec on decode): the parent layer ids this header can
109
+ * follow when it is matched by content rather than by a demux key (no matchKeys, or reachable off its
110
+ * parent only via heuristicFallback) — e.g. LLC after eth/vlan (802.3 length), COTP after TPKT.
111
+ * allowedNextLayers(parent) lists such a child with a null discriminator — there is no parent field
112
+ * to set, the child's own bytes (or a value encode derives, like the 802.3 length) route it — or,
113
+ * for an entry {parent, discriminator}, with that parent field value the child needs.
114
+ */
115
+ readonly heuristicParents: HeuristicParent[];
104
116
  /**
105
117
  * Encode/Decode error info objects
106
118
  */
@@ -272,13 +284,53 @@ export declare abstract class BaseHeader {
272
284
  * @protected
273
285
  */
274
286
  protected getFieldCodecs(schema: ProtocolFieldJSONSchema, codecName: string, execBeforeSubCodecs: boolean, codecs?: (() => void | Promise<void>)[], paths?: string[] | null, pathPrefix?: string): (() => void | Promise<void>)[];
287
+ /**
288
+ * Encode an EtherType field the input left out (eth/vlan). The codec has already filled it from the
289
+ * next layer when that layer is routed by EtherType, so reaching here means it is not: when the next
290
+ * encoded layer is LLC the field carries the IEEE 802.3 length (byte count of everything after this
291
+ * header), otherwise it stays 0x0000 and is reported as 'Not Found'. Decided once every layer is
292
+ * encoded, since the length is only known then.
293
+ * @param field the EtherType field node
294
+ * @param offset its header-relative byte offset
295
+ * @protected
296
+ */
297
+ protected encodeOmittedEtherType(field: FlexibleObject, offset: number): void;
298
+ /**
299
+ * True when `field` was left out of the encode input, which is what asks encode to calculate an
300
+ * autoCalculated length, count or checksum. Any value given, 0 included, is written as given, so a
301
+ * deliberately wrong value can still be crafted. An empty string counts as left out (a hex field
302
+ * has no bytes to write then). Read it at the top of the field's encode closure, before the closure
303
+ * writes a placeholder into the same node.
304
+ * @param field
305
+ * @protected
306
+ */
307
+ protected isLeftOut(field: FlexibleObject): boolean;
308
+ /**
309
+ * The nearest IPv4 or IPv6 layer beneath this one, skipping whatever sits in between (AH, IPv6
310
+ * extension headers, …); undefined when there is none.
311
+ * @protected
312
+ */
313
+ protected nearestIPModule(): CodecModule | undefined;
314
+ /**
315
+ * The pseudo-header an upper-layer checksum covers, built from the nearest IP layer beneath: for
316
+ * IPv4 source, destination, zero, protocol and the 16-bit upper-layer length (RFC 768 / 793); for
317
+ * IPv6 source, destination, the 32-bit length, three zero octets and the next header (RFC 8200
318
+ * section 8.1). undefined when no IP layer is beneath or its addresses are unusable.
319
+ * @param protocol the upper-layer protocol number (6 TCP, 17 UDP, …)
320
+ * @param upperLayerLength byte count the checksum covers above the pseudo-header
321
+ * @protected
322
+ */
323
+ protected ipPseudoHeader(protocol: number, upperLayerLength: number): Buffer | undefined;
275
324
  /**
276
325
  * Record encode/decode error
277
326
  * @param path
278
327
  * @param message
328
+ * @param severity defaults by phase: every decode error is 'error'; on encode, a missing field that
329
+ * fell back to its default ('Not Found') is 'info', an internal exception is 'error', and anything
330
+ * else recorded while still writing the layer (clamped values, odd-but-encodable values) is 'warning'
279
331
  * @protected
280
332
  */
281
- protected recordError(path: string, message: string): void;
333
+ protected recordError(path: string, message: string, severity?: CodecErrorSeverity): void;
282
334
  /**
283
335
  * Register post encode handler for current codec
284
336
  * @param handler
@@ -3,8 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.BaseHeader = void 0;
4
4
  const SortPostHandlers_1 = require("../lib/SortPostHandlers");
5
5
  const FlexibleObject_1 = require("../lib/FlexibleObject");
6
- const ajv_1 = require("ajv");
7
- const CodecSchemaValidateError_1 = require("../errors/CodecSchemaValidateError");
6
+ const SchemaValidator_1 = require("../lib/SchemaValidator");
8
7
  const BufferToNumber_1 = require("../helper/BufferToNumber");
9
8
  const NumberToBuffer_1 = require("../helper/NumberToBuffer");
10
9
  const BufferToHex_1 = require("../helper/BufferToHex");
@@ -12,7 +11,7 @@ const HexToBuffer_1 = require("../helper/HexToBuffer");
12
11
  const BufferToIP_1 = require("../helper/BufferToIP");
13
12
  const IPToBuffer_1 = require("../helper/IPToBuffer");
14
13
  const StringContentEncodingEnum_1 = require("../lib/StringContentEncodingEnum");
15
- const CONSTRUCTOR_VALIDATE_KEY = '__validate';
14
+ const NumberToHex_1 = require("../helper/NumberToHex");
16
15
  //Per-codec-class cached MATCH probe. Content-heuristic selection calls MATCH() on many candidates
17
16
  //per layer; each used to build a whole fresh instance (rebuilding the SCHEMA) just to run match().
18
17
  //Since match() only inspects the previous layer and the raw buffer, one reusable probe per class
@@ -73,25 +72,20 @@ class BaseHeader {
73
72
  static get HEURISTIC_FALLBACK() {
74
73
  return this.CODEC_INSTANCE.heuristicFallback;
75
74
  }
75
+ /** Parent layer ids a content-heuristic header can follow (see the instance field heuristicParents). */
76
+ static get HEURISTIC_PARENTS() {
77
+ return this.CODEC_INSTANCE.heuristicParents;
78
+ }
76
79
  /** Higher is tried first within a demux bucket and within the heuristic chain; ties keep registration order. */
77
80
  static get MATCH_PRIORITY() {
78
81
  return this.CODEC_INSTANCE.matchPriority;
79
82
  }
83
+ //The JSON round-trip strips the decode/encode closures, leaving the declarative shell (plus the
84
+ //format/pattern each contentEncoding implies, see DeriveContentConstraints). The Ajv
85
+ //validator is no longer compiled here (it was, for every protocol, at `new Codec()`); validate()
86
+ //compiles it on first encode of that protocol.
80
87
  static get PROTOCOL_SCHEMA() {
81
- const schema = JSON.parse(JSON.stringify(this.CODEC_INSTANCE.SCHEMA));
82
- if (!Object.hasOwn(this, CONSTRUCTOR_VALIDATE_KEY)) {
83
- const validate = new ajv_1.Ajv({
84
- strict: false,
85
- useDefaults: true,
86
- coerceTypes: true
87
- }).compile(schema);
88
- Object.defineProperty(this, CONSTRUCTOR_VALIDATE_KEY, {
89
- enumerable: false,
90
- configurable: false,
91
- value: validate
92
- });
93
- }
94
- return schema;
88
+ return (0, SchemaValidator_1.DeriveContentConstraints)(JSON.parse(JSON.stringify(this.CODEC_INSTANCE.SCHEMA)));
95
89
  }
96
90
  static MATCH(codecData, codecModules) {
97
91
  //Reuse one cached probe instance per codec class instead of rebuilding a full instance (and its
@@ -114,6 +108,14 @@ class BaseHeader {
114
108
  //the hot path is untouched. See enableByteRangeTracking() / getByteRanges().
115
109
  #byteRanges;
116
110
  #currentFieldPath;
111
+ //Index (in getFieldCodecs walk order) of the field closure currently running, and its phase. A
112
+ //post handler registered from inside that closure captures them, so an exception it throws later
113
+ //is attributed to the field that registered it. -1 outside the field loop.
114
+ #activeFieldIndex;
115
+ #activeFieldPhase;
116
+ //Whether this instance is decoding or encoding; picks the default severity of recorded errors.
117
+ //Stays set after encode()/decode() return, so packet-level post handlers (which run later) inherit it.
118
+ #phase;
117
119
  /**
118
120
  * Turn on byte-range collection for a dissect pass (call before decode()). Additive and
119
121
  * read-only: it changes nothing about the decoded values, only records where each field lives.
@@ -191,6 +193,15 @@ class BaseHeader {
191
193
  this.heuristicFallback = false;
192
194
  /** Selection priority within a bucket / the heuristic chain (higher first; ties keep registration order). */
193
195
  this.matchPriority = 0;
196
+ /**
197
+ * Editor graph only (never used to select a codec on decode): the parent layer ids this header can
198
+ * follow when it is matched by content rather than by a demux key (no matchKeys, or reachable off its
199
+ * parent only via heuristicFallback) — e.g. LLC after eth/vlan (802.3 length), COTP after TPKT.
200
+ * allowedNextLayers(parent) lists such a child with a null discriminator — there is no parent field
201
+ * to set, the child's own bytes (or a value encode derives, like the 802.3 length) route it — or,
202
+ * for an entry {parent, discriminator}, with that parent field value the child needs.
203
+ */
204
+ this.heuristicParents = [];
194
205
  /**
195
206
  * Encode/Decode error info objects
196
207
  */
@@ -204,6 +215,14 @@ class BaseHeader {
204
215
  //the hot path is untouched. See enableByteRangeTracking() / getByteRanges().
205
216
  this.#byteRanges = null;
206
217
  this.#currentFieldPath = '';
218
+ //Index (in getFieldCodecs walk order) of the field closure currently running, and its phase. A
219
+ //post handler registered from inside that closure captures them, so an exception it throws later
220
+ //is attributed to the field that registered it. -1 outside the field loop.
221
+ this.#activeFieldIndex = -1;
222
+ this.#activeFieldPhase = 'decode';
223
+ //Whether this instance is decoding or encoding; picks the default severity of recorded errors.
224
+ //Stays set after encode()/decode() return, so packet-level post handlers (which run later) inherit it.
225
+ this.#phase = 'decode';
207
226
  /**
208
227
  * The start position of this header in the entire packet's buffer
209
228
  */
@@ -559,19 +578,123 @@ class BaseHeader {
559
578
  }
560
579
  return codecs;
561
580
  }
581
+ /**
582
+ * Encode an EtherType field the input left out (eth/vlan). The codec has already filled it from the
583
+ * next layer when that layer is routed by EtherType, so reaching here means it is not: when the next
584
+ * encoded layer is LLC the field carries the IEEE 802.3 length (byte count of everything after this
585
+ * header), otherwise it stays 0x0000 and is reported as 'Not Found'. Decided once every layer is
586
+ * encoded, since the length is only known then.
587
+ * @param field the EtherType field node
588
+ * @param offset its header-relative byte offset
589
+ * @protected
590
+ */
591
+ encodeOmittedEtherType(field, offset) {
592
+ this.writeBytes(offset, Buffer.alloc(2, 0));
593
+ this.addPostPacketEncodeHandler(() => {
594
+ const index = this.codecModules.indexOf(this);
595
+ const next = index >= 0 ? this.codecModules[index + 1] : undefined;
596
+ if (!next || next.id !== 'llc') {
597
+ this.recordError(field.getPath(), 'Not Found');
598
+ return;
599
+ }
600
+ let length = 0;
601
+ for (let i = index + 1; i < this.codecModules.length; i++)
602
+ length += this.codecModules[i].length;
603
+ if (length > 0x05dc)
604
+ this.recordError(field.getPath(), `802.3 length ${length} exceeds 1500, the frame will not decode as LLC`);
605
+ field.setValue((0, NumberToHex_1.UInt16ToHex)(Math.min(length, 0xffff)));
606
+ this.writeBytes(offset, (0, NumberToBuffer_1.UInt16ToBuffer)(Math.min(length, 0xffff)));
607
+ });
608
+ }
609
+ /**
610
+ * True when `field` was left out of the encode input, which is what asks encode to calculate an
611
+ * autoCalculated length, count or checksum. Any value given, 0 included, is written as given, so a
612
+ * deliberately wrong value can still be crafted. An empty string counts as left out (a hex field
613
+ * has no bytes to write then). Read it at the top of the field's encode closure, before the closure
614
+ * writes a placeholder into the same node.
615
+ * @param field
616
+ * @protected
617
+ */
618
+ isLeftOut(field) {
619
+ const value = field.getValue();
620
+ return value === undefined || value === null || value === '';
621
+ }
622
+ /**
623
+ * The nearest IPv4 or IPv6 layer beneath this one, skipping whatever sits in between (AH, IPv6
624
+ * extension headers, …); undefined when there is none.
625
+ * @protected
626
+ */
627
+ nearestIPModule() {
628
+ for (let i = this.prevCodecModules.length - 1; i >= 0; i--) {
629
+ const id = this.prevCodecModules[i].id;
630
+ if (id === 'ipv4' || id === 'ipv6')
631
+ return this.prevCodecModules[i];
632
+ }
633
+ return undefined;
634
+ }
635
+ /**
636
+ * The pseudo-header an upper-layer checksum covers, built from the nearest IP layer beneath: for
637
+ * IPv4 source, destination, zero, protocol and the 16-bit upper-layer length (RFC 768 / 793); for
638
+ * IPv6 source, destination, the 32-bit length, three zero octets and the next header (RFC 8200
639
+ * section 8.1). undefined when no IP layer is beneath or its addresses are unusable.
640
+ * @param protocol the upper-layer protocol number (6 TCP, 17 UDP, …)
641
+ * @param upperLayerLength byte count the checksum covers above the pseudo-header
642
+ * @protected
643
+ */
644
+ ipPseudoHeader(protocol, upperLayerLength) {
645
+ const ip = this.nearestIPModule();
646
+ if (!ip)
647
+ return undefined;
648
+ const sourceIp = ip.instance.sip.getValue();
649
+ const destinationIp = ip.instance.dip.getValue();
650
+ if (typeof sourceIp !== 'string' || typeof destinationIp !== 'string')
651
+ return undefined;
652
+ try {
653
+ if (ip.id === 'ipv4') {
654
+ return Buffer.concat([(0, IPToBuffer_1.IPv4ToBuffer)(sourceIp), (0, IPToBuffer_1.IPv4ToBuffer)(destinationIp), (0, NumberToBuffer_1.UInt8ToBuffer)(0), (0, NumberToBuffer_1.UInt8ToBuffer)(protocol), (0, NumberToBuffer_1.UInt16ToBuffer)(upperLayerLength)]);
655
+ }
656
+ return Buffer.concat([(0, IPToBuffer_1.IPv6ToBuffer)(sourceIp), (0, IPToBuffer_1.IPv6ToBuffer)(destinationIp), (0, NumberToBuffer_1.UInt32ToBuffer)(upperLayerLength), Buffer.alloc(3, 0), (0, NumberToBuffer_1.UInt8ToBuffer)(protocol)]);
657
+ }
658
+ catch (e) {
659
+ return undefined;
660
+ }
661
+ }
662
+ /**
663
+ * Dotted path of the index-th field codec in the same walk order getFieldCodecs uses. Cold path only
664
+ * (a field closure threw): rebuilds the path list on demand so the hot loop carries no per-field
665
+ * path bookkeeping, yet the recorded error still names the field that failed instead of ''.
666
+ */
667
+ #fieldPathAt(codecName, execBeforeSubCodecs, index) {
668
+ const paths = [];
669
+ this.getFieldCodecs(this.SCHEMA, codecName, execBeforeSubCodecs, [], paths);
670
+ return paths[index] ?? '';
671
+ }
562
672
  /**
563
673
  * Record encode/decode error
564
674
  * @param path
565
675
  * @param message
676
+ * @param severity defaults by phase: every decode error is 'error'; on encode, a missing field that
677
+ * fell back to its default ('Not Found') is 'info', an internal exception is 'error', and anything
678
+ * else recorded while still writing the layer (clamped values, odd-but-encodable values) is 'warning'
566
679
  * @protected
567
680
  */
568
- recordError(path, message) {
681
+ recordError(path, message, severity) {
569
682
  this.errors.push({
570
683
  id: this.id,
571
684
  path: path,
572
- message: message
685
+ message: message,
686
+ severity: severity ? severity : this.#defaultSeverity(message)
573
687
  });
574
688
  }
689
+ #defaultSeverity(message) {
690
+ if (this.#phase === 'decode')
691
+ return 'error';
692
+ if (message === 'Not Found')
693
+ return 'info';
694
+ if (message.startsWith('Encode error:'))
695
+ return 'error';
696
+ return 'warning';
697
+ }
575
698
  /**
576
699
  * Register post encode handler for current codec
577
700
  * @param handler
@@ -581,7 +704,7 @@ class BaseHeader {
581
704
  addPostSelfEncodeHandler(handler, priority = 0) {
582
705
  this.postSelfEncodeHandlers.push({
583
706
  priority: priority,
584
- handler: handler
707
+ handler: this.#guardPostHandler(handler)
585
708
  });
586
709
  }
587
710
  /**
@@ -593,7 +716,7 @@ class BaseHeader {
593
716
  addPostSelfDecodeHandler(handler, priority = 0) {
594
717
  this.postSelfDecodeHandlers.push({
595
718
  priority: priority,
596
- handler: handler
719
+ handler: this.#guardPostHandler(handler)
597
720
  });
598
721
  }
599
722
  /**
@@ -606,7 +729,7 @@ class BaseHeader {
606
729
  addPostPacketEncodeHandler(handler, priority = 0) {
607
730
  this.postPacketHandlers.push({
608
731
  priority: priority,
609
- handler: handler
732
+ handler: this.#guardPostHandler(handler)
610
733
  });
611
734
  }
612
735
  /**
@@ -619,37 +742,48 @@ class BaseHeader {
619
742
  addPostPacketDecodeHandler(handler, priority = 0) {
620
743
  this.postPacketHandlers.push({
621
744
  priority: priority,
622
- handler: handler
745
+ handler: this.#guardPostHandler(handler)
623
746
  });
624
747
  }
748
+ /**
749
+ * Wrap a post handler so an exception it throws (sync or async) is contained as a recorded error,
750
+ * the same contract as a field closure: encode/decode never crash on an edge-case input (e.g. a
751
+ * UDP layer encoded without an IP parent for its checksum pseudo-header). The error is attributed
752
+ * to the field whose closure registered the handler, when there is one.
753
+ */
754
+ #guardPostHandler(handler) {
755
+ const fieldIndex = this.#activeFieldIndex;
756
+ const phase = this.#activeFieldPhase;
757
+ const record = (e) => {
758
+ const path = fieldIndex >= 0 ? this.#fieldPathAt(phase, phase === 'decode', fieldIndex) : '';
759
+ this.recordError(path, `${phase === 'encode' ? 'Encode' : 'Decode'} error: ${e.message}`);
760
+ };
761
+ return () => {
762
+ try {
763
+ const result = handler();
764
+ if (result && typeof result.then === 'function')
765
+ return result.catch(record);
766
+ }
767
+ catch (e) {
768
+ record(e);
769
+ }
770
+ };
771
+ }
625
772
  /**
626
773
  * Validate input json node is valid
627
774
  * @param headerTreeNode
628
775
  */
629
776
  validate(headerTreeNode) {
630
- let validate = this.constructor[CONSTRUCTOR_VALIDATE_KEY];
631
- if (!validate) {
632
- validate = new ajv_1.Ajv({
633
- strict: false,
634
- useDefaults: true,
635
- coerceTypes: true
636
- }).compile(this.SCHEMA);
637
- this.constructor[CONSTRUCTOR_VALIDATE_KEY] = validate;
638
- }
639
- const isValid = validate(headerTreeNode);
640
- if (!isValid) {
641
- let errorObject;
642
- if (validate.errors)
643
- errorObject = validate.errors[0];
644
- const errorMessage = errorObject?.message ? errorObject.message : 'Unknown Error';
645
- throw new CodecSchemaValidateError_1.CodecSchemaValidateError(errorMessage);
646
- }
777
+ const validate = (0, SchemaValidator_1.SchemaValidatorOf)(this.constructor, this.SCHEMA);
778
+ if (!validate(headerTreeNode))
779
+ throw (0, SchemaValidator_1.SchemaValidateErrorOf)(this.id, validate.errors);
647
780
  return headerTreeNode;
648
781
  }
649
782
  /**
650
783
  * Decode packet header field by field
651
784
  */
652
785
  async decode() {
786
+ this.#phase = 'decode';
653
787
  const paths = this.#byteRanges ? [] : null;
654
788
  const decodes = this.getFieldCodecs(this.SCHEMA, 'decode', true, [], paths);
655
789
  for (let i = 0; i < decodes.length; i++) {
@@ -660,6 +794,8 @@ class BaseHeader {
660
794
  //closures are synchronous, so this avoids a promise allocation + scheduler turn per field.
661
795
  if (paths)
662
796
  this.#currentFieldPath = paths[i];
797
+ this.#activeFieldIndex = i;
798
+ this.#activeFieldPhase = 'decode';
663
799
  try {
664
800
  //Invoke with the current instance as `this`. Arrow closures (headers not yet migrated)
665
801
  //ignore the binding and use their captured lexical this — the same instance — so this is
@@ -670,12 +806,13 @@ class BaseHeader {
670
806
  await result;
671
807
  }
672
808
  catch (e) {
673
- this.recordError('', `Decode error: ${e.message}`);
809
+ this.recordError(paths ? paths[i] : this.#fieldPathAt('decode', true, i), `Decode error: ${e.message}`);
674
810
  }
675
811
  }
676
812
  //Post-handler reads (cross-field/cross-layer fixups) are not a single field's bytes — clear
677
813
  //the tracked path so they are not attributed to whichever field decoded last.
678
814
  this.#currentFieldPath = '';
815
+ this.#activeFieldIndex = -1;
679
816
  const postSelfDecodeHandlers = (0, SortPostHandlers_1.SortPostHandlers)(this.postSelfDecodeHandlers);
680
817
  let postDecodeHandler = postSelfDecodeHandlers.shift();
681
818
  while (postDecodeHandler) {
@@ -692,8 +829,12 @@ class BaseHeader {
692
829
  * Encode packet header field by field
693
830
  */
694
831
  async encode() {
832
+ this.#phase = 'encode';
695
833
  const encodes = this.getFieldCodecs(this.SCHEMA, 'encode', false);
696
- for (const encode of encodes) {
834
+ for (let i = 0; i < encodes.length; i++) {
835
+ const encode = encodes[i];
836
+ this.#activeFieldIndex = i;
837
+ this.#activeFieldPhase = 'encode';
697
838
  //Shape validation is the deliberate fast-fail at the encode entry point (Ajv, in
698
839
  //Codec.#encode); it runs before we get here. Past that, a field's encode closure must
699
840
  //not crash the whole encode on an edge-case value — contain it to a recorded error so
@@ -706,9 +847,10 @@ class BaseHeader {
706
847
  await result;
707
848
  }
708
849
  catch (e) {
709
- this.recordError('', `Encode error: ${e.message}`);
850
+ this.recordError(this.#fieldPathAt('encode', false, i), `Encode error: ${e.message}`);
710
851
  }
711
852
  }
853
+ this.#activeFieldIndex = -1;
712
854
  const postSelfEncodeHandlers = (0, SortPostHandlers_1.SortPostHandlers)(this.postSelfEncodeHandlers);
713
855
  let postEncodeHandler = postSelfEncodeHandlers.shift();
714
856
  while (postEncodeHandler) {