@netkitty/codec 1.2.0 → 2.0.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 (179) hide show
  1. package/CHANGELOG.md +170 -0
  2. package/README.md +58 -10
  3. package/README.zh-CN.md +52 -9
  4. package/dist/Codec.d.ts +3 -2
  5. package/dist/Codec.js +106 -10
  6. package/dist/abstracts/BaseHeader.d.ts +28 -2
  7. package/dist/abstracts/BaseHeader.js +132 -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 +1 -0
  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/BGP.js +1 -0
  16. package/dist/headers/Babel.js +2 -1
  17. package/dist/headers/BitTorrent.d.ts +2 -0
  18. package/dist/headers/BitTorrent.js +4 -2
  19. package/dist/headers/C37118.js +1 -0
  20. package/dist/headers/CAPWAP.js +1 -0
  21. package/dist/headers/CDP.js +1 -1
  22. package/dist/headers/CMS.js +2 -2
  23. package/dist/headers/COTP.d.ts +2 -0
  24. package/dist/headers/COTP.js +6 -1
  25. package/dist/headers/CassandraCQL.js +1 -0
  26. package/dist/headers/Codesys.js +1 -0
  27. package/dist/headers/Collectd.js +1 -1
  28. package/dist/headers/DCCP.js +1 -0
  29. package/dist/headers/DHCPFailover.js +1 -0
  30. package/dist/headers/DNS.js +3 -3
  31. package/dist/headers/DTLS.js +1 -0
  32. package/dist/headers/Diameter.js +3 -2
  33. package/dist/headers/EAPOL.js +1 -1
  34. package/dist/headers/EIGRP.js +1 -1
  35. package/dist/headers/ENIP.js +1 -0
  36. package/dist/headers/Elasticsearch.js +1 -0
  37. package/dist/headers/EtherCAT.js +1 -0
  38. package/dist/headers/EthernetII.js +6 -0
  39. package/dist/headers/FTP.js +6 -6
  40. package/dist/headers/Finger.js +3 -3
  41. package/dist/headers/FoundationFieldbusHSE.js +1 -0
  42. package/dist/headers/GELF.js +7 -1
  43. package/dist/headers/GENEVE.js +1 -1
  44. package/dist/headers/GLBP.js +1 -1
  45. package/dist/headers/GTPU.js +1 -0
  46. package/dist/headers/GTPv2C.js +1 -0
  47. package/dist/headers/GitProtocol.js +2 -2
  48. package/dist/headers/Goose.d.ts +32 -2
  49. package/dist/headers/Goose.js +116 -89
  50. package/dist/headers/Gopher.js +6 -6
  51. package/dist/headers/HARTIP.js +1 -0
  52. package/dist/headers/HSR.js +2 -0
  53. package/dist/headers/HTTP.js +6 -6
  54. package/dist/headers/HTTP2.js +1 -0
  55. package/dist/headers/ICMP.js +1 -0
  56. package/dist/headers/ICMPv6.js +1 -0
  57. package/dist/headers/IEC104_I_Frame.js +26 -3
  58. package/dist/headers/IEC104_S_Frame.js +7 -2
  59. package/dist/headers/IEC104_U_Frame.js +14 -3
  60. package/dist/headers/IEC61850SampledValues.js +2 -1
  61. package/dist/headers/IGMP.js +1 -0
  62. package/dist/headers/IMAP.js +5 -5
  63. package/dist/headers/IPFIX.js +2 -1
  64. package/dist/headers/IPv4.js +18 -1
  65. package/dist/headers/IPv6.js +1 -0
  66. package/dist/headers/IPv6HopByHopOptions.js +12 -11
  67. package/dist/headers/IRC.js +4 -4
  68. package/dist/headers/ISAKMP.js +2 -1
  69. package/dist/headers/ISCSI.js +2 -0
  70. package/dist/headers/ISIS.js +2 -1
  71. package/dist/headers/ISOSession.d.ts +2 -0
  72. package/dist/headers/ISOSession.js +14 -10
  73. package/dist/headers/Ident.js +8 -8
  74. package/dist/headers/KNXnetIP.js +1 -0
  75. package/dist/headers/Kafka.js +1 -0
  76. package/dist/headers/Kerberos.js +1 -0
  77. package/dist/headers/L2TP.js +2 -2
  78. package/dist/headers/LACP.js +1 -1
  79. package/dist/headers/LDAP.js +2 -3
  80. package/dist/headers/LDP.js +1 -0
  81. package/dist/headers/LLC.d.ts +2 -0
  82. package/dist/headers/LLC.js +2 -0
  83. package/dist/headers/LPD.js +3 -3
  84. package/dist/headers/MGCP.js +7 -7
  85. package/dist/headers/MMS.d.ts +2 -0
  86. package/dist/headers/MMS.js +10 -6
  87. package/dist/headers/MQTT.js +1 -0
  88. package/dist/headers/MQTTSN.js +1 -0
  89. package/dist/headers/MarkerProtocol.js +1 -1
  90. package/dist/headers/Megaco.js +3 -3
  91. package/dist/headers/Memcached.js +3 -2
  92. package/dist/headers/ModbusTCP.js +1 -0
  93. package/dist/headers/ModbusUDP.js +1 -0
  94. package/dist/headers/MongoDB.js +1 -0
  95. package/dist/headers/MySQL.js +1 -0
  96. package/dist/headers/NATS.js +2 -2
  97. package/dist/headers/NBDS.js +1 -0
  98. package/dist/headers/NBSS.js +1 -0
  99. package/dist/headers/NFS.js +1 -0
  100. package/dist/headers/NHRP.js +1 -0
  101. package/dist/headers/NNTP.js +6 -6
  102. package/dist/headers/NetFlowV5.js +1 -0
  103. package/dist/headers/OLSR.js +2 -1
  104. package/dist/headers/OPCUA.js +1 -0
  105. package/dist/headers/OpenFlow.js +1 -0
  106. package/dist/headers/OpenVPN.js +1 -0
  107. package/dist/headers/PCWorx.js +1 -0
  108. package/dist/headers/POP3.js +5 -5
  109. package/dist/headers/PPPoEDiscovery.js +2 -1
  110. package/dist/headers/PPPoESession.js +1 -0
  111. package/dist/headers/PPTP.js +1 -0
  112. package/dist/headers/PTP.js +1 -0
  113. package/dist/headers/PostgreSQL.js +2 -0
  114. package/dist/headers/QUIC.js +2 -0
  115. package/dist/headers/RADIUS.js +1 -0
  116. package/dist/headers/RDP.d.ts +2 -0
  117. package/dist/headers/RDP.js +4 -1
  118. package/dist/headers/RFB.js +4 -4
  119. package/dist/headers/RGoose.js +6 -1
  120. package/dist/headers/RSVP.js +3 -2
  121. package/dist/headers/RTCP.js +1 -0
  122. package/dist/headers/RTP.js +2 -1
  123. package/dist/headers/RTPS.d.ts +2 -0
  124. package/dist/headers/RTPS.js +4 -1
  125. package/dist/headers/RTSP.js +7 -7
  126. package/dist/headers/RawData.js +1 -1
  127. package/dist/headers/Redis.js +4 -4
  128. package/dist/headers/Rlogin.js +5 -5
  129. package/dist/headers/Rsync.js +2 -2
  130. package/dist/headers/S7comm.d.ts +2 -0
  131. package/dist/headers/S7comm.js +5 -1
  132. package/dist/headers/SCTP.js +2 -2
  133. package/dist/headers/SFlow.js +2 -1
  134. package/dist/headers/SIP.js +6 -6
  135. package/dist/headers/SLMP.js +1 -0
  136. package/dist/headers/SLP.js +2 -0
  137. package/dist/headers/SLPv1.js +1 -0
  138. package/dist/headers/SMB1.js +1 -0
  139. package/dist/headers/SMB2.js +1 -0
  140. package/dist/headers/SMPP.js +1 -0
  141. package/dist/headers/SMTP.js +6 -6
  142. package/dist/headers/SNAP.js +18 -5
  143. package/dist/headers/SNMP.js +4 -4
  144. package/dist/headers/SOCKS4.js +11 -5
  145. package/dist/headers/SSDP.js +7 -7
  146. package/dist/headers/SSH.js +5 -4
  147. package/dist/headers/STOMP.js +5 -5
  148. package/dist/headers/STUN.js +2 -0
  149. package/dist/headers/Skinny.js +1 -0
  150. package/dist/headers/StatsD.js +4 -4
  151. package/dist/headers/SunRPC.js +1 -0
  152. package/dist/headers/Syslog.js +2 -2
  153. package/dist/headers/TCP.js +18 -6
  154. package/dist/headers/TLS_Alert.js +23 -11
  155. package/dist/headers/TLS_ApplicationData.js +9 -4
  156. package/dist/headers/TLS_ChangeCipherSpec.js +10 -5
  157. package/dist/headers/TLS_Handshake.js +41 -26
  158. package/dist/headers/TLS_Heartbeat.js +10 -1
  159. package/dist/headers/TPKT.js +3 -1
  160. package/dist/headers/TacacsPlus.js +1 -0
  161. package/dist/headers/Telnet.js +2 -1
  162. package/dist/headers/Teredo.js +2 -2
  163. package/dist/headers/UDP.js +8 -0
  164. package/dist/headers/VLAN_802dot1Q.js +7 -0
  165. package/dist/headers/WCCP.js +1 -0
  166. package/dist/headers/WHOIS.js +3 -3
  167. package/dist/headers/WSDiscovery.js +2 -2
  168. package/dist/headers/XMPP.js +3 -3
  169. package/dist/headers/Zabbix.js +1 -0
  170. package/dist/index.d.ts +3 -3
  171. package/dist/lib/SchemaValidator.d.ts +31 -0
  172. package/dist/lib/SchemaValidator.js +137 -0
  173. package/dist/schema/ProtocolFieldJSONSchema.d.ts +4 -1
  174. package/dist/schema/ProtocolJSONSchema.d.ts +1 -1
  175. package/dist/types/CodecErrorInfo.d.ts +11 -0
  176. package/dist/types/LayerGraph.d.ts +14 -1
  177. package/package.json +2 -2
  178. package/dist/lib/GetBERIntegerLengthFromBuffer.d.ts +0 -6
  179. package/dist/lib/GetBERIntegerLengthFromBuffer.js +0 -16
@@ -0,0 +1,137 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DeriveContentConstraints = DeriveContentConstraints;
4
+ exports.CompileSchemaValidator = CompileSchemaValidator;
5
+ exports.SchemaValidatorOf = SchemaValidatorOf;
6
+ exports.AjvErrorFieldPath = AjvErrorFieldPath;
7
+ exports.SchemaValidateErrorOf = SchemaValidateErrorOf;
8
+ const ajv_1 = require("ajv");
9
+ const ip_address_1 = require("ip-address");
10
+ const CodecSchemaValidateError_1 = require("../errors/CodecSchemaValidateError");
11
+ const StringContentEncodingEnum_1 = require("./StringContentEncodingEnum");
12
+ /**
13
+ * Dotted-quad IPv4: four 0–255 decimal octets. Leading zeros ('010') are accepted because encode
14
+ * parses each octet as decimal (IPv4ToBuffer), so such input already encoded deterministically.
15
+ */
16
+ const IPV4_PATTERN = /^((25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(25[0-5]|2[0-4]\d|[01]?\d?\d)$/;
17
+ /** Colon-separated 6-octet MAC (what decode emits and encode parses). */
18
+ const MAC_PATTERN = /^[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}$/;
19
+ /** A BigInt-convertible integer string: decimal (optionally negative) or 0x-hex. */
20
+ const BIGINT_PATTERN = '^(-?[0-9]+|0[xX][0-9a-fA-F]+)$';
21
+ /** Ajv `format` name each address content encoding validates against. */
22
+ const CONTENT_ENCODING_FORMATS = {
23
+ [StringContentEncodingEnum_1.StringContentEncodingEnum.IPv4]: 'ipv4',
24
+ [StringContentEncodingEnum_1.StringContentEncodingEnum.IPv6]: 'ipv6',
25
+ [StringContentEncodingEnum_1.StringContentEncodingEnum.MAC]: 'mac'
26
+ };
27
+ /**
28
+ * Derive the validation keywords a string field's `contentEncoding` implies, in place: an ipv4/ipv6/mac
29
+ * field gets `format: 'ipv4'|'ipv6'|'mac'`, a bigint field gets a numeric `pattern`. An explicit
30
+ * `format`/`pattern` on the field is left alone. Applied to every published schema (PROTOCOL_SCHEMA)
31
+ * and to every compiled validator, so the shape a UI sees and the shape encode enforces are the same,
32
+ * and every address field is constrained consistently without repeating the keyword per field.
33
+ */
34
+ function DeriveContentConstraints(node) {
35
+ if (!node || typeof node !== 'object')
36
+ return node;
37
+ if (Array.isArray(node)) {
38
+ node.forEach((item) => DeriveContentConstraints(item));
39
+ return node;
40
+ }
41
+ const schemaNode = node;
42
+ const encoding = schemaNode.contentEncoding;
43
+ if (typeof encoding === 'string') {
44
+ if (CONTENT_ENCODING_FORMATS[encoding] && schemaNode.format === undefined)
45
+ schemaNode.format = CONTENT_ENCODING_FORMATS[encoding];
46
+ if (encoding === StringContentEncodingEnum_1.StringContentEncodingEnum.BIGINT && schemaNode.pattern === undefined)
47
+ schemaNode.pattern = BIGINT_PATTERN;
48
+ }
49
+ for (const key of ['properties', 'items', 'anyOf', 'oneOf', 'allOf', 'definitions', '$defs']) {
50
+ const child = schemaNode[key];
51
+ if (!child || typeof child !== 'object')
52
+ continue;
53
+ if (key === 'properties' || key === 'definitions' || key === '$defs')
54
+ Object.values(child).forEach((value) => DeriveContentConstraints(value));
55
+ else
56
+ DeriveContentConstraints(child);
57
+ }
58
+ return node;
59
+ }
60
+ //Own-property slot on each header class holding its compiled validator. Own (not inherited) so a
61
+ //custom codec extending a built-in compiles its own schema instead of reusing the base class's.
62
+ const VALIDATOR_KEY = '__validate';
63
+ /**
64
+ * Compile the Ajv shape validator for a protocol schema. The schema's decode/encode closures are
65
+ * stripped first (the same JSON round-trip that produces PROTOCOL_SCHEMA), so only the declarative
66
+ * shell is compiled. One place for the Ajv options keeps every validator identical.
67
+ */
68
+ function CompileSchemaValidator(schema) {
69
+ const ajv = new ajv_1.Ajv({
70
+ strict: false,
71
+ useDefaults: true,
72
+ coerceTypes: true
73
+ });
74
+ ajv.addFormat('ipv4', IPV4_PATTERN);
75
+ ajv.addFormat('ipv6', (value) => ip_address_1.Address6.isValid(value));
76
+ ajv.addFormat('mac', MAC_PATTERN);
77
+ return ajv.compile(DeriveContentConstraints(JSON.parse(JSON.stringify(schema))));
78
+ }
79
+ /**
80
+ * The validator for a header class, compiled on first use and cached on that class. Compiling all
81
+ * ~190 schemas eagerly cost ~0.5 s at `new Codec()`; lazily, a codec only pays for the protocols it
82
+ * actually encodes.
83
+ */
84
+ function SchemaValidatorOf(headerClass, schema) {
85
+ if (Object.hasOwn(headerClass, VALIDATOR_KEY))
86
+ return headerClass[VALIDATOR_KEY];
87
+ const validate = CompileSchemaValidator(schema);
88
+ Object.defineProperty(headerClass, VALIDATOR_KEY, { enumerable: false, configurable: false, writable: false, value: validate });
89
+ return validate;
90
+ }
91
+ /**
92
+ * Ajv instancePath (JSON Pointer, '/goosePdu/allData/0/dataType') → the dotted field path the codec
93
+ * uses everywhere else for errors ('goosePdu.allData[0].dataType'). A 'required' /
94
+ * 'additionalProperties' error points at the parent object, so the named property is appended.
95
+ */
96
+ function AjvErrorFieldPath(error) {
97
+ const segments = error.instancePath
98
+ .split('/')
99
+ .slice(1)
100
+ .map((segment) => segment.replace(/~1/g, '/').replace(/~0/g, '~'));
101
+ const params = error.params;
102
+ if (error.keyword === 'required' && typeof params.missingProperty === 'string')
103
+ segments.push(params.missingProperty);
104
+ if (error.keyword === 'additionalProperties' && typeof params.additionalProperty === 'string')
105
+ segments.push(params.additionalProperty);
106
+ let path = '';
107
+ for (const segment of segments) {
108
+ if (/^\d+$/.test(segment))
109
+ path += `[${segment}]`;
110
+ else
111
+ path += path ? `.${segment}` : segment;
112
+ }
113
+ return path;
114
+ }
115
+ /** Build the thrown error for a failed validation, carrying the layer, the field path and Ajv's errors. */
116
+ function SchemaValidateErrorOf(layerId, ajvErrors) {
117
+ const errors = (ajvErrors ? ajvErrors : []).map((error) => ({
118
+ instancePath: error.instancePath,
119
+ schemaPath: error.schemaPath,
120
+ keyword: error.keyword,
121
+ params: error.params,
122
+ message: error.message ? error.message : '',
123
+ path: AjvErrorFieldPath(error)
124
+ }));
125
+ //Report the most specific failure. Inside an anyOf (option/item variants) Ajv lists every failed
126
+ //branch, and the first is usually just "must be equal to constant" on the variant discriminator
127
+ //of a branch that was never meant to match; the deepest instancePath is the real offending field.
128
+ //At equal depth a non-`const` failure wins over a sibling variant's discriminator mismatch. Ties
129
+ //otherwise keep Ajv's order, so a plain (non-anyOf) failure reports exactly Ajv's first error.
130
+ const score = (issue) => issue.instancePath.split('/').length * 2 + (issue.keyword === 'const' ? 0 : 1);
131
+ const primary = errors.reduce((best, issue) => (!best || score(issue) > score(best) ? issue : best), undefined);
132
+ return new CodecSchemaValidateError_1.CodecSchemaValidateError(primary && primary.message ? primary.message : 'Unknown Error', {
133
+ layerId: layerId,
134
+ path: primary ? primary.path : '',
135
+ errors: errors
136
+ });
137
+ }
@@ -5,6 +5,9 @@ export interface ProtocolFieldJSONSchema extends JSONSchema7 {
5
5
  decode?: () => void | Promise<void>;
6
6
  label?: string;
7
7
  hidden?: boolean;
8
+ readOnly?: boolean;
9
+ autoCalculated?: boolean;
10
+ byteAlignment?: number;
8
11
  $defs?: {
9
12
  [key: string]: ProtocolFieldJSONSchemaDefinition;
10
13
  } | undefined;
@@ -17,7 +20,7 @@ export interface ProtocolFieldJSONSchema extends JSONSchema7 {
17
20
  patternProperties?: {
18
21
  [key: string]: ProtocolFieldJSONSchemaDefinition;
19
22
  } | undefined;
20
- additionalProperties?: ProtocolFieldJSONSchemaDefinition | undefined;
23
+ additionalProperties?: ProtocolFieldJSONSchemaDefinition | boolean | undefined;
21
24
  dependencies?: {
22
25
  [key: string]: ProtocolFieldJSONSchemaDefinition | string[];
23
26
  } | undefined;
@@ -14,7 +14,7 @@ export interface ProtocolJSONSchema extends JSONSchema7 {
14
14
  patternProperties?: {
15
15
  [key: string]: ProtocolFieldJSONSchemaDefinition;
16
16
  } | undefined;
17
- additionalProperties?: ProtocolFieldJSONSchemaDefinition | undefined;
17
+ additionalProperties?: ProtocolFieldJSONSchemaDefinition | boolean | undefined;
18
18
  dependencies?: {
19
19
  [key: string]: ProtocolFieldJSONSchemaDefinition | string[];
20
20
  } | undefined;
@@ -1,5 +1,16 @@
1
+ /**
2
+ * How serious a recorded codec error is:
3
+ * - `error`: the field could not be decoded/encoded as given (malformed bytes on decode; an internal
4
+ * failure or an unencodable value on encode, so the emitted layer may be incomplete).
5
+ * - `warning`: encode wrote the layer but had to adjust or flag the input (value clamped to its
6
+ * range, a semantically odd value such as IPv4 version != 4, a checksum that could not be computed).
7
+ * - `info`: encode used a field's default because the input left it out ("Not Found").
8
+ */
9
+ export type CodecErrorSeverity = 'error' | 'warning' | 'info';
1
10
  export type CodecErrorInfo = {
2
11
  id: string;
3
12
  path: string;
4
13
  message: string;
14
+ /** Always set by the built-in codec; optional in the type so hand-built entries stay valid. */
15
+ severity?: CodecErrorSeverity;
5
16
  };
@@ -1,7 +1,20 @@
1
+ /**
2
+ * A parent a content-heuristic header can follow (BaseHeader.heuristicParents): the parent layer id,
3
+ * optionally with the parent field value the child needs (e.g. RDP needs COTP pduType 0xE0, a
4
+ * Connection Request) — reported by allowedNextLayers() as that child's discriminator.
5
+ */
6
+ export type HeuristicParent = string | {
7
+ parent: string;
8
+ discriminator: {
9
+ field: string;
10
+ value: string | number;
11
+ };
12
+ };
1
13
  /**
2
14
  * A layer that may follow a given parent layer in the editor's "add next layer" menu. `discriminator`
3
15
  * tells the caller which parent field to set (and to what) so decode would route to this layer;
4
- * it is null for RawData, which may always follow any layer.
16
+ * it is null when there is no parent field to set: RawData (which may follow any layer), and children
17
+ * recognized by their own content or by a value encode derives (LLC after eth, COTP after TPKT, …).
5
18
  */
6
19
  export type NextLayer = {
7
20
  id: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@netkitty/codec",
3
- "version": "1.2.0",
3
+ "version": "2.0.0",
4
4
  "description": "Schema-driven packet codec: encode/decode 180+ network and industrial (OT/ICS/SCADA) protocol headers — TCP/IP, TLS, HTTP/2, DNS, MQTT, plus Modbus, DNP3, IEC 61850 (GOOSE/SV/MMS), IEC 104, S7comm, OPC UA, PROFINET, EtherCAT, BACnet and more.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -138,5 +138,5 @@
138
138
  },
139
139
  "homepage": "https://github.com/myq1991/netkitty/tree/main/packages/codec#readme",
140
140
  "bugs": "https://github.com/myq1991/netkitty/issues",
141
- "gitHead": "52958b705354ac379a1a6d90a3955773c190d65a"
141
+ "gitHead": "a0b16ffec11eb830dd5846bd942dd9a63ae04d5e"
142
142
  }
@@ -1,6 +0,0 @@
1
- /**
2
- * Get BER encoded integer real length from buffer
3
- * @param buffer
4
- * @constructor
5
- */
6
- export declare function GetBERIntegerLengthFromBuffer(buffer: Buffer): number;
@@ -1,16 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.GetBERIntegerLengthFromBuffer = GetBERIntegerLengthFromBuffer;
4
- /**
5
- * Get BER encoded integer real length from buffer
6
- * @param buffer
7
- * @constructor
8
- */
9
- function GetBERIntegerLengthFromBuffer(buffer) {
10
- if (buffer[0] === 0) {
11
- return buffer.length - 1;
12
- }
13
- else {
14
- return buffer.length;
15
- }
16
- }