@netkitty/codec 2.1.0 → 2.3.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 (83) hide show
  1. package/CHANGELOG.md +249 -0
  2. package/README.md +30 -1
  3. package/README.zh-CN.md +26 -1
  4. package/dist/Codec.d.ts +25 -7
  5. package/dist/Codec.js +151 -18
  6. package/dist/PacketHeaders.d.ts +2 -0
  7. package/dist/PacketHeaders.js +8 -4
  8. package/dist/abstracts/BaseHeader.d.ts +34 -0
  9. package/dist/abstracts/BaseHeader.js +43 -0
  10. package/dist/headers/ARP.d.ts +3 -1
  11. package/dist/headers/ARP.js +8 -1
  12. package/dist/headers/BACnetIP.js +2 -1
  13. package/dist/headers/BGP.js +3 -2
  14. package/dist/headers/Babel.js +1 -1
  15. package/dist/headers/Codesys.js +3 -2
  16. package/dist/headers/DHCP.js +2 -1
  17. package/dist/headers/DNP3.d.ts +12 -7
  18. package/dist/headers/DNP3.js +98 -18
  19. package/dist/headers/DTLS.js +5 -3
  20. package/dist/headers/Diameter.js +2 -1
  21. package/dist/headers/Elasticsearch.js +3 -2
  22. package/dist/headers/EthernetII.d.ts +1 -0
  23. package/dist/headers/EthernetII.js +3 -0
  24. package/dist/headers/Goose.d.ts +31 -7
  25. package/dist/headers/Goose.js +409 -168
  26. package/dist/headers/HARTIP.js +2 -2
  27. package/dist/headers/ICMP.d.ts +1 -0
  28. package/dist/headers/ICMP.js +9 -1
  29. package/dist/headers/ICMPv6.d.ts +1 -0
  30. package/dist/headers/ICMPv6.js +1 -0
  31. package/dist/headers/IEC104_I_Frame.d.ts +28 -0
  32. package/dist/headers/IEC104_I_Frame.js +246 -160
  33. package/dist/headers/IEC104_S_Frame.js +3 -3
  34. package/dist/headers/IEC104_U_Frame.js +5 -3
  35. package/dist/headers/IEC61850SampledValues.d.ts +1 -0
  36. package/dist/headers/IEC61850SampledValues.js +16 -1
  37. package/dist/headers/IPFIX.js +2 -1
  38. package/dist/headers/IPv4.d.ts +1 -0
  39. package/dist/headers/IPv4.js +6 -0
  40. package/dist/headers/IPv6.d.ts +1 -0
  41. package/dist/headers/IPv6.js +6 -0
  42. package/dist/headers/IPv6HopByHopOptions.d.ts +2 -0
  43. package/dist/headers/IPv6HopByHopOptions.js +11 -0
  44. package/dist/headers/KNXnetIP.js +3 -2
  45. package/dist/headers/LACP.js +2 -1
  46. package/dist/headers/LDP.js +2 -2
  47. package/dist/headers/MQTT.js +3 -1
  48. package/dist/headers/MarkerProtocol.js +2 -1
  49. package/dist/headers/NHRP.js +7 -15
  50. package/dist/headers/NetFlowV5.js +2 -1
  51. package/dist/headers/OPCUA.js +4 -0
  52. package/dist/headers/OSPF.d.ts +2 -2
  53. package/dist/headers/OSPF.js +32 -20
  54. package/dist/headers/OSPFv3.d.ts +38 -0
  55. package/dist/headers/OSPFv3.js +316 -0
  56. package/dist/headers/PPTP.js +2 -2
  57. package/dist/headers/QUIC.js +8 -3
  58. package/dist/headers/RGoose.js +2 -1
  59. package/dist/headers/RIP.js +3 -2
  60. package/dist/headers/RIPng.js +3 -2
  61. package/dist/headers/RTCP.js +3 -2
  62. package/dist/headers/RTP.js +3 -2
  63. package/dist/headers/SFlow.js +4 -2
  64. package/dist/headers/SLMP.js +2 -1
  65. package/dist/headers/SLP.js +2 -1
  66. package/dist/headers/SLPv1.js +2 -1
  67. package/dist/headers/SMB1.js +3 -2
  68. package/dist/headers/SMB2.js +3 -2
  69. package/dist/headers/STUN.js +2 -1
  70. package/dist/headers/TLS_Handshake.d.ts +6 -0
  71. package/dist/headers/TLS_Handshake.js +28 -3
  72. package/dist/headers/TacacsPlus.js +3 -1
  73. package/dist/headers/Trailer.d.ts +30 -0
  74. package/dist/headers/Trailer.js +63 -0
  75. package/dist/headers/VLAN_802dot1Q.d.ts +1 -0
  76. package/dist/headers/VLAN_802dot1Q.js +3 -0
  77. package/dist/headers/WakeOnLAN.js +2 -1
  78. package/dist/headers/WireGuard.js +3 -2
  79. package/dist/headers/Zabbix.js +2 -2
  80. package/dist/lib/BERElement.d.ts +51 -0
  81. package/dist/lib/BERElement.js +125 -0
  82. package/dist/types/LayerGraph.d.ts +10 -5
  83. package/package.json +2 -2
package/CHANGELOG.md CHANGED
@@ -3,6 +3,255 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ # [2.3.0](https://github.com/myq1991/netkitty/compare/@netkitty/codec@2.2.0...@netkitty/codec@2.3.0) (2026-11-27)
7
+
8
+
9
+ ### Bug Fixes
10
+
11
+ * **codec:** decode ICMP, OSPF and NHRP behind AH or an IPv6 extension header ([18aaa37](https://github.com/myq1991/netkitty/commit/18aaa377cee8d83232bb8afb513a2d8024a66a57))
12
+
13
+
14
+ ### Features
15
+
16
+ * **codec:** list next layers by the IP version they run over ([2769a8a](https://github.com/myq1991/netkitty/commit/2769a8a962df83e36f5b19f1baf4efbd7d26911b))
17
+
18
+
19
+ ### Upgrade note
20
+
21
+ The editor graph no longer offers a header on an IP version it does not run over, and
22
+ `checkConsistency()` reports such a placement. ICMP, OSPF and NHRP behind AH or an IPv6 extension
23
+ header now decode as themselves instead of `raw`. Decoding the local captures gives the same trees as
24
+ 2.2.0, and encode output is unchanged.
25
+
26
+ ### Behaviour changes (check before upgrading)
27
+
28
+ #### allowedNextLayers() by IP version
29
+ - ICMP runs over IPv4; ICMPv6, OSPFv3 and the IPv6 Hop-by-Hop header run over IPv6, Hop-by-Hop directly
30
+ after the IPv6 header. They share the ipproto namespace, so they used to be listed under either
31
+ version, and a layer built there decoded back as `raw`. Entries removed from the menu: under `ipv4`
32
+ icmpv6, ipv6-hopopt and ospfv3; under `ipv6` icmp; under `ipv6-hopopt` icmp and ipv6-hopopt; under
33
+ `ah` ipv6-hopopt. `childDiscriminator()` returns `null` for those pairs.
34
+ - A parent that does not say which IP version it rides on (AH) still lists both versions' children,
35
+ unless the new `options.ancestors` gives the layers beneath it:
36
+ `allowedNextLayers('ah', {ancestors: ['eth', 'ipv4']})`. `childDiscriminator()` takes the same option.
37
+ - Encode still infers a left-out parent field from the full graph (`ipv4.protocol` is still 89 for
38
+ eth/ipv4/ospfv3), so a deliberately unusual stack can be crafted.
39
+ - OSPFv2 (`ospf`) stays listed under IPv6 and decodes there, although RFC 2328 runs it over IPv4 only.
40
+
41
+ #### checkConsistency()
42
+ - New issue `kind: 'carrier'` for a child on an IP version it does not run over (OSPFv3 over IPv4, with
43
+ or without AH between them; ICMP over IPv6; no IP layer at all) or a Hop-by-Hop header that does not
44
+ directly follow the IPv6 header. `field` / `actual` are the parent's demux field as given (`''` when it
45
+ has none) and `suggestion` is `null`. Existing issues now carry `kind: 'discriminator'`.
46
+ - The parameter type is `CodecEncodeInput[]`, so encode input type-checks as well as decode results
47
+ (only `id` and `data` are read). Issues come back sorted by layer index.
48
+
49
+ #### Decode behind AH or an IPv6 extension header
50
+ - ICMP accepts Next Header 1 from AH when the nearest IP layer is IPv4 (it read only the IPv4 protocol
51
+ field). OSPF and NHRP bound themselves by what the nearest IP layer's length leaves, instead of the
52
+ IPv4 Total Length / IPv6 Payload Length of the layer right below, which AH and Hop-by-Hop do not have.
53
+ All three decoded as `raw` there before.
54
+ - Side effect for OSPF / NHRP: under an IPv4 Total Length of 0 (segmentation offload) they now decode
55
+ as OSPF / NHRP; they used to be left to `raw`.
56
+
57
+ ### Additions
58
+ - `BaseHeader.ipVersions` / `directlyAfterIP` (static `IP_VERSIONS` / `DIRECTLY_AFTER_IP`) for custom
59
+ codecs, read by `allowedNextLayers()` and `checkConsistency()`.
60
+ - `allowedNextLayers(parent, {ancestors})`, `childDiscriminator(parent, child, {ancestors})`, and
61
+ `ConsistencyIssue.kind`.
62
+
63
+
64
+
65
+
66
+
67
+ # [2.2.0](https://github.com/myq1991/netkitty/compare/@netkitty/codec@2.1.0...@netkitty/codec@2.2.0) (2026-11-27)
68
+
69
+
70
+ ### Bug Fixes
71
+
72
+ * **codec:** compute DNP3 data-block CRCs from a new userData field ([fcbf954](https://github.com/myq1991/netkitty/commit/fcbf9546c7f854eb1139b4f7bb227ac400d0721a))
73
+ * **codec:** count the IEC 104 information objects from IOA when left out ([d89d78c](https://github.com/myq1991/netkitty/commit/d89d78c5129fc84bc40444354e6b295bae205416))
74
+ * **codec:** default the IEC 104 U-frame and S-frame control field to its format ([c768977](https://github.com/myq1991/netkitty/commit/c768977c0fb972916f728ae64aa0dcd2b32145d1))
75
+ * **codec:** default the signature fields match() checks ([cd44c7b](https://github.com/myq1991/netkitty/commit/cd44c7b6a75f0db58d4c7bbd4f9b46ee378d8a0b))
76
+ * **codec:** keep a GOOSE or SV PDU with malformed BER as raw ([9ae2cda](https://github.com/myq1991/netkitty/commit/9ae2cda5a44c59327f571addbe3b02275710e511))
77
+ * **codec:** keep a tls-handshake Hello cut short by the capture as raw ([2bc0671](https://github.com/myq1991/netkitty/commit/2bc0671f54fb20bb9f6d5b4272f2480ac3f9d363))
78
+ * **codec:** keep a wrong-size IPv6 Hop-by-Hop option as a Custom item ([1c57d2a](https://github.com/myq1991/netkitty/commit/1c57d2a65b7697532bb80cacc9a872fa8a48e603))
79
+ * **codec:** keep bytes past a GOOSE or SV Length as a trailer layer ([3aa7d81](https://github.com/myq1991/netkitty/commit/3aa7d814d9153e1399abf4a05a8463e0a68639bc))
80
+ * **codec:** keep bytes past an IP or 802.3 length as a trailer layer ([b6bc47d](https://github.com/myq1991/netkitty/commit/b6bc47d2e013df5eaab2867c9a8f4ac4292620bb))
81
+ * **codec:** keep the Ethernet padding after an ARP packet as a trailer ([fe4eca6](https://github.com/myq1991/netkitty/commit/fe4eca62305d7b54b211f25acb7e84ddf1f06468))
82
+ * **codec:** lay out IEC 104 elements as IEC 60870-5-101 defines them ([8eb7a5d](https://github.com/myq1991/netkitty/commit/8eb7a5dec85eeed824dd969eaec2cf4425c74534))
83
+ * **codec:** mark every node of the GOOSE encoding hints hidden ([935644e](https://github.com/myq1991/netkitty/commit/935644e7f07892c28dac9d4763822c84728886a3))
84
+ * **codec:** re-encode GOOSE with the BER lengths and INTEGER widths it was captured with ([2f6ac64](https://github.com/myq1991/netkitty/commit/2f6ac643556f8a781eaaf02ea3ff4d777b32e740))
85
+ * **codec:** report IOA items of an unknown IEC 104 type id instead of failing ([ff8d7c9](https://github.com/myq1991/netkitty/commit/ff8d7c920346b6943b7ca0d554a5d95a3a7c2228))
86
+ * **codec:** write a tls-handshake body that matches its handshake type ([0415333](https://github.com/myq1991/netkitty/commit/0415333215a85c3425838e5e4634c203b7db717b))
87
+
88
+
89
+ ### Features
90
+
91
+ * **codec:** add OSPFv3 (RFC 5340) as its own header ([fc9a756](https://github.com/myq1991/netkitty/commit/fc9a756dcb594b3cbbc4881b028f76a6ec2f7bef))
92
+
93
+
94
+ ### Upgrade note
95
+
96
+ Decoded trees change shape: bytes past a layer's own length (Ethernet padding) come back as a `trailer`
97
+ layer instead of inside the innermost layer or a trailing `raw`; DNP3 frames whose block CRCs check decode
98
+ as `userData` instead of `payload`; OSPF version 3 decodes as the new `ospfv3`; GOOSE trees carry hidden
99
+ `encoding` hints and malformed GOOSE / SV PDUs decode as `raw`; IEC 104 types 40, 107 and 120–127 read
100
+ their elements at the offsets IEC 60870-5-101 defines.
101
+
102
+ Encode output changes where fields are left out: signature fields that match() checks now have schema
103
+ defaults (a saved template without `rtp.version` now sends 2; a U-frame from `{}` is STARTDT act). Some
104
+ input no longer validates: IEC 104 `NOS` above 255 and the old type-127 `{NOF, SCQ}` shape. Subclasses of
105
+ `Goose` that override its protected BER helpers break. Read "Behaviour changes" below before upgrading.
106
+
107
+ ### Behaviour changes (check before upgrading)
108
+
109
+ #### Ethernet padding is a `trailer` layer
110
+ - IPv4 bounds its payload by Total Length, IPv6 by Payload Length, Ethernet / 802.1Q by the 802.3
111
+ length, GOOSE and Sampled Values by their Length, and an Ethernet/IPv4 ARP packet ends after its 28
112
+ octets. Bytes past that end become a new
113
+ `trailer` layer (`{data: '<hex>'}`, `protocol: false`) at the
114
+ end of the layer list. Before, they were part of the innermost layer (an ICMP echo padded to 60 octets
115
+ showed the padding in `icmp.message`, a UDP payload gained it) or a trailing `raw` layer (after
116
+ LLC / STP, ARP, GOOSE and SV). Across the local captures the trailer bytes equal tshark's
117
+ `eth.padding` + `eth.trailer` on every frame where both see one (15,366 frames).
118
+ - Padding after a TCP segment with no payload no longer decodes as an application layer: across the
119
+ local captures, padding used to decode as CMS, NBSS, COTP or a TLS record on their ports.
120
+ - A length of 0 (segmentation offload), one longer than the bytes captured, or one shorter than its own
121
+ header sets no bound: those frames decode as before. Nested IP layers each bound their own payload, so
122
+ IP in GRE can end with two trailers.
123
+ - Encode writes `trailer` bytes after every other layer and after every computed length and checksum, so
124
+ a left-out IPv4 Total Length, IPv6 Payload Length, 802.3 length or checksum no longer counts the
125
+ padding (before: Total Length 32 → 46 for a padded echo, 802.3 length 38 → 45). A layer given after a
126
+ `trailer` is written before it, with a warning.
127
+ - `allowedNextLayers()` lists `trailer` after every layer (after `raw`); `checkConsistency()` never flags
128
+ it; `summary()` skips it like `raw`.
129
+ - Custom codecs: `BaseHeader.payloadEnd()` (decode only) lets a header with its own length field set the
130
+ same bound.
131
+
132
+ #### DNP3 data blocks
133
+ - New field `userData`: the transport header + application data with the per-block CRCs removed. Left out
134
+ of nothing else, encode splits it into 16-octet blocks and appends each block's CRC-16/DNP.
135
+ - Decode emits exactly one of the two: `userData` when every block CRC checks (`userData: ''` for a frame
136
+ with no user data), otherwise the verbatim `payload` plus a `warning` per bad or truncated block.
137
+ Readers of `dnp3.payload` must read `userData` for well-formed frames.
138
+ - Encode: a non-empty `payload` is written verbatim and wins (to craft a bad CRC); `userData` given as
139
+ well is ignored with a warning. `payload: ''` counts as left out. A left-out `length` is 5 + the
140
+ user-data octets of whichever field is written.
141
+
142
+ #### OSPFv3 is its own header
143
+ - New header `ospfv3` (RFC 5340): 16-octet header with `instanceId`, Hello decoded field by field
144
+ (`interfaceId`, `routerPriority`, `options`, intervals, DR/BDR, `neighbors`), other types kept as
145
+ `rawBody`. `packetLength` and `checksum` (IPv6 pseudo-header, over Packet Length) are computed when left
146
+ out. It runs over IPv6 only; OSPFv3 over IPv4 (RFC 7949) is not supported and decodes as raw.
147
+ - `ospf` now matches version 2 only and has `version` default 2. Protocol 89 with version 3 over IPv6
148
+ decodes as `ospfv3` (it used to decode as `ospf` with the v2 layout); other versions decode as raw.
149
+ `ospf` given `version: 3` on encode still writes the v2 layout, with a warning pointing to `ospfv3`.
150
+
151
+ #### IEC 104
152
+ - `numberOfObject` is computed when left out: the number of IOA items (for SQ=1, the elements). The items
153
+ written always come from `IOA`: an explicit count that differs is written as given, every item is still
154
+ written, and a warning is recorded. Before, a left-out or 0 count dropped every item silently, and a
155
+ larger count failed with an encode error. More than 127 items: the count is clamped to 127 with a
156
+ warning.
157
+ - A U-frame built from empty data is STARTDT act (`controlField` default `07000000`, `680407000000`)
158
+ instead of `680400000000`, which re-decoded as an I-frame. An S-frame from empty data is
159
+ `680401000000` (6 octets) instead of `680101`.
160
+ - `apciType` (I / S / U) lost its numeric `minimum` / `maximum` (it is a string).
161
+
162
+ #### tls-handshake
163
+ - Only ClientHello and ServerHello build a body from fields. Every other type writes `messagedata.raw`, or
164
+ nothing when it is left out, so `{}` is an empty HelloRequest (`160303000400000000`) instead of a 6-byte
165
+ zero body. Hello fields given under another type are dropped with a warning.
166
+ - In a Hello, a left-out `random` is 32 zero octets and a left-out ServerHello `cipherSuite` /
167
+ `compressionMethod` is zeros of its size, so a Hello built from its type alone re-decodes as a Hello.
168
+ - A captured ServerHelloDone no longer gains 6 octets on re-encode.
169
+
170
+ #### GOOSE and Sampled Values
171
+ - GOOSE re-encodes with the BER length forms and INTEGER widths it was captured with. Before, a device
172
+ that writes long-form lengths or fixed 4-octet INTEGERs (timeAllowedtoLive, stNum, sqNum, confRev,
173
+ numDatSetEntries, INT32 items) got a shorter frame back: 798 of 8693 GOOSE frames in one substation
174
+ capture. Decode records only the forms that are not minimal, in a hidden `encoding` node on `goosePdu`
175
+ (`lengthOctets`, and `{lengthOctets?, width?}` per field) and on each `allData` item (`lengthOctets`,
176
+ `width` on INT items, `content` hex on FLOAT32). Encode uses a hint while the value still fits and
177
+ writes the minimal form otherwise; a tree without hints encodes exactly as before.
178
+ - FLOAT32 items decode the 4 octets after the exponent-width octet. Before, the goosePdu span was one
179
+ octet short after a long-form length, so the last item lost its final octet (0.0 decoded as
180
+ 3.85e-34, and the lost octet became a stray `raw` layer). FLOAT64 (width 11) decodes as its value with
181
+ a warning; other forms decode as 0 with an error; both, and NaN, re-emit their captured octets. -0.0
182
+ encodes as `80000000`.
183
+ - A goosePdu or savPdu whose BER cannot be walked strictly (an element that runs past its parent or
184
+ Length, octets left over, unknown, repeated or out-of-order goosePdu elements) decodes as `raw` with
185
+ the error `Malformed goosePdu, kept as raw: …` instead of partial fields that re-encoded to a different
186
+ PDU.
187
+ - GOOSE / SV `length` now bounds the PDU: a decoded tree edited to a different PDU size must leave
188
+ `length` out to have it recomputed (an explicit value is written as given).
189
+ - Subclasses of `Goose`: the protected `decodeDataTLVItem` takes `BERElement[]`, `encodeDataTLVItem`
190
+ returns `Buffer[]`, and `TLVInstance` / `TLVChild` are gone.
191
+
192
+ #### IEC 104 element layouts
193
+ - Type 32 (M_ST_TB_1) wrote the CP56Time2a minute IV flag into the high milliseconds octet, so a time
194
+ tag with milliseconds ≥ 32768 re-encoded wrong.
195
+ - Types 40, 107 and 120–126 read and write their elements as IEC 60870-5-101 defines them, so the same
196
+ bytes decode to different values (same field names): 40 M_EP_TF_1 has QDP in its own octet (11
197
+ octets, CP16Time2a at +5, CP56Time2a at +7); 107 C_TS_TA_1 has a 16-bit TSC (9 octets); file transfer
198
+ has NOF 2 octets, NOS 1 and LOF 3 (122 / 123 little-endian like the rest; 126's CP56Time2a at +9).
199
+ - Type 127 F_SC_NB_1 is QueryLog: `{address, NOF, RangeStartTime, RangeStopTime}` (two CP56Time2a). The
200
+ old `{NOF, SCQ}` input no longer validates.
201
+ - Schema: `NOS` maximum 65535 → 255 (larger input is now rejected), `LOF` maximum → 16777215, `TSC` →
202
+ 65535; type 126's `LOS` is `SOF` (Status Of File), as decode already produced.
203
+ - An unknown type id with IOA items records `Type id N has no element layout: the IOA items are not
204
+ written` (the unparsed ASDU in `raw` is still written) instead of an encode error.
205
+
206
+ #### tls-handshake cut short by the capture
207
+ - A Hello whose body runs past the captured bytes (a ClientHello split across TCP segments) decodes as
208
+ `messagedata.raw` with the error `… the body continues past the captured bytes`, so it re-encodes
209
+ byte-exact. Before, a segment that ended exactly at an extension boundary decoded as a structured Hello
210
+ and re-encode rewrote the extensions length. Cut-short Hellos that already decoded raw keep their shape;
211
+ their error text changes.
212
+
213
+ #### IPv6 Hop-by-Hop
214
+ - A fixed-size option with the wrong size decodes as a Custom item instead of a typed item that failed
215
+ encode validation.
216
+
217
+ #### Signature defaults
218
+ - Fields a header's match() checks now have schema defaults, so the header built from `{}` re-decodes as
219
+ itself: STUN / DHCP / PPTP / Zabbix magic cookies, BGP marker, Wake-on-LAN sync stream, version fields
220
+ (NetFlow 5, sFlow 5, IPFIX 10, Diameter 1, HART-IP 1, LDP 1, SLP 2 / 1, RTP 2, KNXnet/IP 06/10,
221
+ TACACS+ 0xc, RIP 2, RIPng 1, DTLS fefd, QUIC v1 with `headerForm` and `fixedBit` true — also filled
222
+ when `firstByte` is given without them), message types (R-GOOSE 0xA1, WireGuard 1, MQTT
223
+ PINGREQ, RTCP RR, OPC UA HEL, SLMP 0x5000, LACP 1, Marker 2) and Babel / Elasticsearch / CODESYS /
224
+ SMB / BACnet signatures. Only input that leaves these fields out changes; decoded trees carry them.
225
+
226
+ ### Additions
227
+ - Headers `trailer` and `ospfv3`.
228
+ - Fixtures from real captures for GOOSE (long-form lengths, fixed-width INTEGERs, a minimal device), SV
229
+ and GOOSE with trailers, IEC 104 type 32, a cut-short TLS ClientHello and a TLS ServerHelloDone.
230
+ - `BaseHeader.payloadEnd()` for custom codecs.
231
+ - Test gate: every header built from `{}` under its usual parent re-decodes as itself.
232
+
233
+ ### Known limitations
234
+ - Trailer layers are always written at the end of the packet, so a trailer that decode placed inside a
235
+ tunnel (between an inner and an outer IP datagram) moves to the end when the lengths are left out.
236
+ - An 802.3 length below 3 (shorter than an LLC header) sets no bound.
237
+ - OSPFv3 over IPv4 (RFC 7949) is not supported.
238
+ - IEC 104: C_RD_NA_1 (102) decodes and encodes a READ octet the standard does not have, so a captured read
239
+ command gains an octet on re-encode; VTI decodes unsigned (tshark reads it as signed 7-bit). Types 40,
240
+ 107 and 120–127 are checked against the standard's element sizes only (no capture has them).
241
+ - GOOSE: a goosePdu carrying an element the decoder does not know, such as the optional `security [12]`
242
+ element, or a repeated or out-of-order one, now decodes as `raw` as a whole (it still re-encodes
243
+ byte-exact, but its fields cannot be edited). Unknown allData item tags (array, binary-time, bcd, mMSString, …) are dropped; a boolean TRUE
244
+ other than `01` re-encodes as `01`; a constructed goosePdu tag other than `61` re-encodes as `61`;
245
+ GOOSE strings and SV svID / datSet decode as ASCII, so octets ≥ 0x80 lose bit 7. SV gets no encoding
246
+ hints, so a non-minimal SV length form is not kept.
247
+ - Where a given length positions what follows (QUIC connection IDs, S7comm parameter/data, Diameter AVPs,
248
+ AMQP frame end, …), an explicit length that disagrees with the data reshapes the packet the way decode
249
+ would read it.
250
+
251
+
252
+
253
+
254
+
6
255
  # [2.1.0](https://github.com/myq1991/netkitty/compare/@netkitty/codec@2.0.0...@netkitty/codec@2.1.0) (2026-11-26)
7
256
 
8
257
 
package/README.md CHANGED
@@ -171,6 +171,24 @@ heuristic matches at the current offset, then advances and recurses until the pa
171
171
  `RawData` is the forced final fallback and always matches, so unknown or malformed trailing bytes simply
172
172
  become a `raw` layer and decode can never dead-end.
173
173
 
174
+ ### Padding and trailers
175
+
176
+ IPv4 (Total Length), IPv6 (Payload Length), an Ethernet / 802.1Q 802.3 length and the GOOSE / Sampled
177
+ Values Length bound the payload they carry, and an Ethernet/IPv4 ARP packet ends after its 28 octets. Bytes past that end — Ethernet padding up to the 60-octet minimum frame, or a trailer a device
178
+ appended — are not given to the layers above; they become a `trailer` layer at the end of the list
179
+ (`{data: '<hex>'}`, `protocol: false`). A length of 0, one longer than the bytes captured, or one shorter
180
+ than its own header sets no bound. On encode, `trailer` bytes are written after every other layer and
181
+ after every computed length and checksum, so a left-out length or checksum never counts them; append
182
+ `{id: 'trailer', data: {data: '0000…'}}` to pad a frame you build.
183
+
184
+ ### Captured encodings
185
+
186
+ Where a protocol allows more than one byte form for the same value, decode keeps what the capture used
187
+ so re-encode reproduces it. GOOSE records BER length forms and INTEGER widths that are not minimal in a
188
+ hidden `encoding` node (on `goosePdu` and on each `allData` item); encode uses them while the value still
189
+ fits and falls back to the minimal form otherwise, and a tree without them encodes minimal. A GOOSE or SV
190
+ PDU whose BER cannot be walked strictly is kept as `raw` (with an error) instead of being decoded partway.
191
+
174
192
  ### The declarative shell vs. the imperative core
175
193
 
176
194
  `PROTOCOL_SCHEMA` is the schema with its closures stripped (via a `JSON.parse(JSON.stringify())`
@@ -209,9 +227,18 @@ declares them with `heuristicParents` — usually with a `null` discriminator (n
209
227
  parent value they need (RDP: COTP `pduType` 0xE0). Their signature fields default to the protocol
210
228
  constants, so a layer added from scratch re-opens as that layer.
211
229
 
230
+ Headers that run over one IP version only — ICMP over IPv4; ICMPv6, OSPFv3 and the IPv6 Hop-by-Hop header
231
+ over IPv6 — are listed only under that version (Hop-by-Hop only directly under `ipv6`). Under a layer that
232
+ does not say which version it rides on, such as AH, pass the layers beneath it:
233
+ `allowedNextLayers('ah', {ancestors: ['eth', 'ipv4']})` (`childDiscriminator` takes the same option);
234
+ without them both versions' children are listed. `checkConsistency(layers)` accepts decoded layers or
235
+ encode input and reports each problem with a `kind`: `'discriminator'` when a parent's demux field does
236
+ not route to the child that follows, `'carrier'` when a child sits on an IP version it does not run over
237
+ (OSPFv3 over IPv4) or Hop-by-Hop does not directly follow the IPv6 header.
238
+
212
239
  ## Built-in headers
213
240
 
214
- 189 protocol headers are registered by default; `raw` is the forced catch-all. Pass custom classes to `new Codec(customCodecs)` to override a built-in with the same id or add new ones.
241
+ 191 headers are registered by default: 189 protocols, `raw` (the forced catch-all) and `trailer` (bytes past a layer's own length). Pass custom classes to `new Codec(customCodecs)` to override a built-in with the same id or add new ones.
215
242
 
216
243
  | id | name |
217
244
  | ---------------- | --------------------------------------------------- |
@@ -328,6 +355,7 @@ constants, so a layer added from scratch re-opens as that layer.
328
355
  | `openflow` | OpenFlow |
329
356
  | `openvpn` | OpenVPN Protocol |
330
357
  | `ospf` | Open Shortest Path First |
358
+ | `ospfv3` | Open Shortest Path First version 3 |
331
359
  | `pcworx` | PCWorx |
332
360
  | `pgsql` | PostgreSQL Protocol |
333
361
  | `pim` | Protocol Independent Multicast |
@@ -393,6 +421,7 @@ constants, so a layer added from scratch re-opens as that layer.
393
421
  | `tls-handshake` | Transport Layer Security(Handshake Protocol) |
394
422
  | `tls-heartbeat` | Transport Layer Security(Heartbeat Protocol) |
395
423
  | `tpkt` | TPKT |
424
+ | `trailer` | Trailer |
396
425
  | `udp` | User Datagram Protocol |
397
426
  | `vlan` | 802.1Q Virtual LAN |
398
427
  | `vrrp` | Virtual Router Redundancy Protocol |
package/README.zh-CN.md CHANGED
@@ -161,6 +161,22 @@ try {
161
161
  递归,直到把报文消费完。`RawData` 是被强制放在最后的兜底项,且永远匹配成功,所以无法识别或畸形的尾部
162
162
  字节会直接变成一层 `raw`,解码绝不会走进死胡同。
163
163
 
164
+ ### 填充与尾部数据
165
+
166
+ IPv4(Total Length)、IPv6(Payload Length)、Ethernet / 802.1Q 的 802.3 长度以及 GOOSE / SV 的 Length
167
+ 会限定各自所承载载荷的范围,Ethernet/IPv4 的 ARP 报文在 28 字节处结束。超出这个范围的字节(补齐到 60 字节最小帧的以太网填充,或设备附加的尾部数据)不会交给上层,而是在层
168
+ 列表末尾单独成为一层 `trailer`(`{data: '<hex>'}`,`protocol: false`)。长度为 0、比实际抓到的字节还长、
169
+ 或者比自身头部还短时,不做限定。编码时 `trailer` 的字节在其他所有层、以及所有自动计算的长度和校验和之后
170
+ 才写入,所以不填的长度和校验和不会把它算进去;自己构造报文时追加 `{id: 'trailer', data: {data: '0000…'}}`
171
+ 即可补齐填充。
172
+
173
+ ### 保留抓包里的编码形式
174
+
175
+ 同一个值在协议里有多种字节写法时,解码会记下抓包实际用的那种,重新编码时照样写出。GOOSE 会把非最简的
176
+ BER 长度形式和 INTEGER 宽度记在隐藏的 `encoding` 节点里(`goosePdu` 和每个 `allData` 项上都有);编码时
177
+ 只要值还放得下就沿用,放不下就退回最简形式;不带这些节点的树按最简形式编码。BER 无法严格解析的 GOOSE / SV
178
+ PDU 整体保留为 `raw`(并记一条错误),不再解一半。
179
+
164
180
  ### 声明式外壳与命令式内核
165
181
 
166
182
  `PROTOCOL_SCHEMA` 是剥离了闭包之后的 schema(通过 `JSON.parse(JSON.stringify())` 往返——JSON 序列化
@@ -193,9 +209,16 @@ ISO-Session 后的 MMS、RTPS、BitTorrent)也会列出——协议头用 `heuri
193
209
  `null`(无需设置),或给出它需要的上一层取值(RDP 需要 COTP `pduType` 为 0xE0)。这些协议的签名字段默认就是
194
210
  协议常量,所以从零添加的一层重新打开时仍是这一层。
195
211
 
212
+ 只承载在一种 IP 版本上的协议——IPv4 上的 ICMP,IPv6 上的 ICMPv6、OSPFv3 和 IPv6 Hop-by-Hop 头——只在对应版本下
213
+ 列出(Hop-by-Hop 只在 `ipv6` 的正下方列出)。像 AH 这种本身看不出下面是哪个 IP 版本的层,可以把它下面的各层传进来:
214
+ `allowedNextLayers('ah', {ancestors: ['eth', 'ipv4']})`(`childDiscriminator` 也接受同样的参数);不传时两个
215
+ 版本的协议都会列出。`checkConsistency(layers)` 接受解码结果或编码输入,每个问题带 `kind`:`'discriminator'`
216
+ 表示上一层的分发字段指向的不是后面这一层,`'carrier'` 表示这一层放在了它不支持的 IP 版本上(例如 IPv4 上的
217
+ OSPFv3),或 Hop-by-Hop 没有紧跟在 IPv6 头后面。
218
+
196
219
  ## 内置协议头
197
220
 
198
- 默认注册了 189 个协议头(`raw` 是强制兜底)。向 `new Codec(customCodecs)` 传入自定义类可覆盖同 id 的内置头或新增协议头。
221
+ 默认注册了 191 个头:189 个协议,加上 `raw`(强制兜底)和 `trailer`(超出该层自身长度的字节)。向 `new Codec(customCodecs)` 传入自定义类可覆盖同 id 的内置头或新增协议头。
199
222
 
200
223
  | id | name |
201
224
  | ---------------- | --------------------------------------------------- |
@@ -312,6 +335,7 @@ ISO-Session 后的 MMS、RTPS、BitTorrent)也会列出——协议头用 `heuri
312
335
  | `openflow` | OpenFlow |
313
336
  | `openvpn` | OpenVPN Protocol |
314
337
  | `ospf` | Open Shortest Path First |
338
+ | `ospfv3` | Open Shortest Path First version 3 |
315
339
  | `pcworx` | PCWorx |
316
340
  | `pgsql` | PostgreSQL Protocol |
317
341
  | `pim` | Protocol Independent Multicast |
@@ -377,6 +401,7 @@ ISO-Session 后的 MMS、RTPS、BitTorrent)也会列出——协议头用 `heuri
377
401
  | `tls-handshake` | Transport Layer Security(Handshake Protocol) |
378
402
  | `tls-heartbeat` | Transport Layer Security(Heartbeat Protocol) |
379
403
  | `tpkt` | TPKT |
404
+ | `trailer` | Trailer |
380
405
  | `udp` | User Datagram Protocol |
381
406
  | `vlan` | 802.1Q Virtual LAN |
382
407
  | `vrrp` | Virtual Router Redundancy Protocol |
package/dist/Codec.d.ts CHANGED
@@ -90,19 +90,35 @@ export declare class Codec {
90
90
  * may follow `parentLayerId`, each tagged with the {field,value} to set on the parent so decode
91
91
  * would route to it. Derived by reversing the dispatch table over the parent's producer fields,
92
92
  * plus the content-heuristic children that declare this parent in `heuristicParents` (listed with a
93
- * null discriminator). RawData is always appended as the custom/fallback layer that may follow anything.
93
+ * null discriminator). RawData (the custom/fallback layer) and Trailer (padding written after every
94
+ * other layer) are always appended: either may follow anything.
95
+ *
96
+ * Headers that run over one IP version only (`ipVersions`: ICMP over IPv4; ICMPv6, OSPFv3 and the
97
+ * IPv6 Hop-by-Hop header over IPv6) are left out when the IP version beneath is known to be the
98
+ * other one, and a header that must directly follow its IP header (`directlyAfterIP`) is listed only
99
+ * under ipv4 / ipv6. The version is known when the parent is ipv4 / ipv6 or runs over one version
100
+ * itself (ipv6-hopopt), or from `options.ancestors`; under AH with no ancestors given, both
101
+ * versions' children are listed (checkConsistency() flags a wrong pick).
94
102
  * @param parentLayerId
103
+ * @param options `ancestors`: the ids of the layers beneath the parent, outermost first (e.g.
104
+ * ['eth', 'ipv4'] for parent 'ah'), so a parent such as AH can be placed over its IP version
95
105
  */
96
- allowedNextLayers(parentLayerId: string): NextLayer[];
106
+ allowedNextLayers(parentLayerId: string, options?: {
107
+ ancestors?: string[];
108
+ }): NextLayer[];
97
109
  /**
98
110
  * The {field,value} to set on `parentLayerId` so `childLayerId` follows it — used to auto-fill
99
111
  * the parent discriminator when a child is added, and to suggest a fix for a consistency issue.
100
112
  * Null when the child is not reachable from that parent via the demux graph (RawData, or a
101
- * content-heuristic child such as TLS/IEC104 whose match is port/content based).
113
+ * content-heuristic child such as TLS/IEC104 whose match is port/content based), or when
114
+ * allowedNextLayers() leaves it out on that carrier (OSPFv3 under ipv4).
102
115
  * @param parentLayerId
103
116
  * @param childLayerId
117
+ * @param options as for allowedNextLayers()
104
118
  */
105
- childDiscriminator(parentLayerId: string, childLayerId: string): {
119
+ childDiscriminator(parentLayerId: string, childLayerId: string, options?: {
120
+ ancestors?: string[];
121
+ }): {
106
122
  field: string;
107
123
  value: string | number;
108
124
  } | null;
@@ -111,10 +127,12 @@ export declare class Codec {
111
127
  * actually follows (e.g. eth.etherType says IPv6 but the next layer is IPv4). This is advisory
112
128
  * only — encode never blocks on it, since a deliberately-inconsistent packet is a valid crafted
113
129
  * packet. Only demux-based relationships are checked; content-heuristic children (TLS/IEC104) are
114
- * not flagged. RawData may follow anything and is never flagged.
130
+ * not flagged. RawData and Trailer may follow anything and are never flagged. Also reports a header
131
+ * placed on a carrier it does not run over (`kind: 'carrier'`, see ConsistencyIssue). Accepts decode
132
+ * results or encode input (only `id` and `data` are read).
115
133
  * @param decoded
116
134
  */
117
- checkConsistency(decoded: CodecDecodeResult[]): ConsistencyIssue[];
135
+ checkConsistency(decoded: CodecEncodeInput[]): ConsistencyIssue[];
118
136
  /**
119
137
  * Wireshark-style dissection: decode the packet with byte-range tracking on, then project each
120
138
  * layer into a field tree carrying the value, the schema label, the exact packet bytes the field
@@ -127,7 +145,7 @@ export declare class Codec {
127
145
  * One-line human summary of a decoded packet (Wireshark's Info column). The innermost layer that
128
146
  * declares a `summary` template in its schema wins (the most specific layer describes the packet);
129
147
  * the template's ${dotted.field} placeholders are filled from that layer's decoded data. Falls back
130
- * to the innermost non-raw layer's name when no template is declared. Read-only projection.
148
+ * to the innermost layer that is neither raw nor a trailer when no template is declared. Read-only projection.
131
149
  * @param decoded
132
150
  */
133
151
  summary(decoded: CodecDecodeResult[]): string;