@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.
- package/CHANGELOG.md +170 -0
- package/README.md +58 -10
- package/README.zh-CN.md +52 -9
- package/dist/Codec.d.ts +3 -2
- package/dist/Codec.js +106 -10
- package/dist/abstracts/BaseHeader.d.ts +28 -2
- package/dist/abstracts/BaseHeader.js +132 -43
- package/dist/errors/CodecSchemaValidateError.d.ts +34 -1
- package/dist/errors/CodecSchemaValidateError.js +26 -3
- package/dist/headers/ADSAMS.js +2 -0
- package/dist/headers/AH.js +1 -0
- package/dist/headers/AMQP.js +2 -1
- package/dist/headers/ARP.js +16 -10
- package/dist/headers/BACnetIP.js +1 -0
- package/dist/headers/BGP.js +1 -0
- package/dist/headers/Babel.js +2 -1
- package/dist/headers/BitTorrent.d.ts +2 -0
- package/dist/headers/BitTorrent.js +4 -2
- package/dist/headers/C37118.js +1 -0
- package/dist/headers/CAPWAP.js +1 -0
- package/dist/headers/CDP.js +1 -1
- package/dist/headers/CMS.js +2 -2
- package/dist/headers/COTP.d.ts +2 -0
- package/dist/headers/COTP.js +6 -1
- package/dist/headers/CassandraCQL.js +1 -0
- package/dist/headers/Codesys.js +1 -0
- package/dist/headers/Collectd.js +1 -1
- package/dist/headers/DCCP.js +1 -0
- package/dist/headers/DHCPFailover.js +1 -0
- package/dist/headers/DNS.js +3 -3
- package/dist/headers/DTLS.js +1 -0
- package/dist/headers/Diameter.js +3 -2
- package/dist/headers/EAPOL.js +1 -1
- package/dist/headers/EIGRP.js +1 -1
- package/dist/headers/ENIP.js +1 -0
- package/dist/headers/Elasticsearch.js +1 -0
- package/dist/headers/EtherCAT.js +1 -0
- package/dist/headers/EthernetII.js +6 -0
- package/dist/headers/FTP.js +6 -6
- package/dist/headers/Finger.js +3 -3
- package/dist/headers/FoundationFieldbusHSE.js +1 -0
- package/dist/headers/GELF.js +7 -1
- package/dist/headers/GENEVE.js +1 -1
- package/dist/headers/GLBP.js +1 -1
- package/dist/headers/GTPU.js +1 -0
- package/dist/headers/GTPv2C.js +1 -0
- package/dist/headers/GitProtocol.js +2 -2
- package/dist/headers/Goose.d.ts +32 -2
- package/dist/headers/Goose.js +116 -89
- package/dist/headers/Gopher.js +6 -6
- package/dist/headers/HARTIP.js +1 -0
- package/dist/headers/HSR.js +2 -0
- package/dist/headers/HTTP.js +6 -6
- package/dist/headers/HTTP2.js +1 -0
- package/dist/headers/ICMP.js +1 -0
- package/dist/headers/ICMPv6.js +1 -0
- package/dist/headers/IEC104_I_Frame.js +26 -3
- package/dist/headers/IEC104_S_Frame.js +7 -2
- package/dist/headers/IEC104_U_Frame.js +14 -3
- package/dist/headers/IEC61850SampledValues.js +2 -1
- package/dist/headers/IGMP.js +1 -0
- package/dist/headers/IMAP.js +5 -5
- package/dist/headers/IPFIX.js +2 -1
- package/dist/headers/IPv4.js +18 -1
- package/dist/headers/IPv6.js +1 -0
- package/dist/headers/IPv6HopByHopOptions.js +12 -11
- package/dist/headers/IRC.js +4 -4
- package/dist/headers/ISAKMP.js +2 -1
- package/dist/headers/ISCSI.js +2 -0
- package/dist/headers/ISIS.js +2 -1
- package/dist/headers/ISOSession.d.ts +2 -0
- package/dist/headers/ISOSession.js +14 -10
- package/dist/headers/Ident.js +8 -8
- package/dist/headers/KNXnetIP.js +1 -0
- package/dist/headers/Kafka.js +1 -0
- package/dist/headers/Kerberos.js +1 -0
- package/dist/headers/L2TP.js +2 -2
- package/dist/headers/LACP.js +1 -1
- package/dist/headers/LDAP.js +2 -3
- package/dist/headers/LDP.js +1 -0
- package/dist/headers/LLC.d.ts +2 -0
- package/dist/headers/LLC.js +2 -0
- package/dist/headers/LPD.js +3 -3
- package/dist/headers/MGCP.js +7 -7
- package/dist/headers/MMS.d.ts +2 -0
- package/dist/headers/MMS.js +10 -6
- package/dist/headers/MQTT.js +1 -0
- package/dist/headers/MQTTSN.js +1 -0
- package/dist/headers/MarkerProtocol.js +1 -1
- package/dist/headers/Megaco.js +3 -3
- package/dist/headers/Memcached.js +3 -2
- package/dist/headers/ModbusTCP.js +1 -0
- package/dist/headers/ModbusUDP.js +1 -0
- package/dist/headers/MongoDB.js +1 -0
- package/dist/headers/MySQL.js +1 -0
- package/dist/headers/NATS.js +2 -2
- package/dist/headers/NBDS.js +1 -0
- package/dist/headers/NBSS.js +1 -0
- package/dist/headers/NFS.js +1 -0
- package/dist/headers/NHRP.js +1 -0
- package/dist/headers/NNTP.js +6 -6
- package/dist/headers/NetFlowV5.js +1 -0
- package/dist/headers/OLSR.js +2 -1
- package/dist/headers/OPCUA.js +1 -0
- package/dist/headers/OpenFlow.js +1 -0
- package/dist/headers/OpenVPN.js +1 -0
- package/dist/headers/PCWorx.js +1 -0
- package/dist/headers/POP3.js +5 -5
- package/dist/headers/PPPoEDiscovery.js +2 -1
- package/dist/headers/PPPoESession.js +1 -0
- package/dist/headers/PPTP.js +1 -0
- package/dist/headers/PTP.js +1 -0
- package/dist/headers/PostgreSQL.js +2 -0
- package/dist/headers/QUIC.js +2 -0
- package/dist/headers/RADIUS.js +1 -0
- package/dist/headers/RDP.d.ts +2 -0
- package/dist/headers/RDP.js +4 -1
- package/dist/headers/RFB.js +4 -4
- package/dist/headers/RGoose.js +6 -1
- package/dist/headers/RSVP.js +3 -2
- package/dist/headers/RTCP.js +1 -0
- package/dist/headers/RTP.js +2 -1
- package/dist/headers/RTPS.d.ts +2 -0
- package/dist/headers/RTPS.js +4 -1
- package/dist/headers/RTSP.js +7 -7
- package/dist/headers/RawData.js +1 -1
- package/dist/headers/Redis.js +4 -4
- package/dist/headers/Rlogin.js +5 -5
- package/dist/headers/Rsync.js +2 -2
- package/dist/headers/S7comm.d.ts +2 -0
- package/dist/headers/S7comm.js +5 -1
- package/dist/headers/SCTP.js +2 -2
- package/dist/headers/SFlow.js +2 -1
- package/dist/headers/SIP.js +6 -6
- package/dist/headers/SLMP.js +1 -0
- package/dist/headers/SLP.js +2 -0
- package/dist/headers/SLPv1.js +1 -0
- package/dist/headers/SMB1.js +1 -0
- package/dist/headers/SMB2.js +1 -0
- package/dist/headers/SMPP.js +1 -0
- package/dist/headers/SMTP.js +6 -6
- package/dist/headers/SNAP.js +18 -5
- package/dist/headers/SNMP.js +4 -4
- package/dist/headers/SOCKS4.js +11 -5
- package/dist/headers/SSDP.js +7 -7
- package/dist/headers/SSH.js +5 -4
- package/dist/headers/STOMP.js +5 -5
- package/dist/headers/STUN.js +2 -0
- package/dist/headers/Skinny.js +1 -0
- package/dist/headers/StatsD.js +4 -4
- package/dist/headers/SunRPC.js +1 -0
- package/dist/headers/Syslog.js +2 -2
- package/dist/headers/TCP.js +18 -6
- package/dist/headers/TLS_Alert.js +23 -11
- package/dist/headers/TLS_ApplicationData.js +9 -4
- package/dist/headers/TLS_ChangeCipherSpec.js +10 -5
- package/dist/headers/TLS_Handshake.js +41 -26
- package/dist/headers/TLS_Heartbeat.js +10 -1
- package/dist/headers/TPKT.js +3 -1
- package/dist/headers/TacacsPlus.js +1 -0
- package/dist/headers/Telnet.js +2 -1
- package/dist/headers/Teredo.js +2 -2
- package/dist/headers/UDP.js +8 -0
- package/dist/headers/VLAN_802dot1Q.js +7 -0
- package/dist/headers/WCCP.js +1 -0
- package/dist/headers/WHOIS.js +3 -3
- package/dist/headers/WSDiscovery.js +2 -2
- package/dist/headers/XMPP.js +3 -3
- package/dist/headers/Zabbix.js +1 -0
- package/dist/index.d.ts +3 -3
- package/dist/lib/SchemaValidator.d.ts +31 -0
- package/dist/lib/SchemaValidator.js +137 -0
- package/dist/schema/ProtocolFieldJSONSchema.d.ts +4 -1
- package/dist/schema/ProtocolJSONSchema.d.ts +1 -1
- package/dist/types/CodecErrorInfo.d.ts +11 -0
- package/dist/types/LayerGraph.d.ts +14 -1
- package/package.json +2 -2
- package/dist/lib/GetBERIntegerLengthFromBuffer.d.ts +0 -6
- package/dist/lib/GetBERIntegerLengthFromBuffer.js +0 -16
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,176 @@
|
|
|
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.0.0](https://github.com/myq1991/netkitty/compare/@netkitty/codec@1.2.1...@netkitty/codec@2.0.0) (2026-11-26)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
### Bug Fixes
|
|
10
|
+
|
|
11
|
+
* **codec:** do not write inferred discriminators back into encode input ([4a44c65](https://github.com/myq1991/netkitty/commit/4a44c65643b9e6b7be6d7da6a44f4f5de54f937b))
|
|
12
|
+
* **codec:** keep an IEC 104 U-frame controlField when apciType is left out ([6adde45](https://github.com/myq1991/netkitty/commit/6adde45e71250cc8f414c1049910211865d03b76))
|
|
13
|
+
* **codec:** keep bytes trailing a GOOSE PDU or a plain SOCKS4 request intact ([3c314f8](https://github.com/myq1991/netkitty/commit/3c314f80093e46adb6e71c0f158f951f010dc3c1))
|
|
14
|
+
* **codec:** make every decoded tree re-encodable ([26b298f](https://github.com/myq1991/netkitty/commit/26b298f9f3ab0a0882737356d64364db2fb68de8))
|
|
15
|
+
* **codec:** reject unknown control values instead of silently encoding nothing ([9b832f8](https://github.com/myq1991/netkitty/commit/9b832f8d23129349d46c61b9d37e120268f93c89))
|
|
16
|
+
* **codec:** treat missing optional encode data as empty and name the failing field ([0ce131a](https://github.com/myq1991/netkitty/commit/0ce131adaffc397d6cffb02678fa946e3da96122))
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
### Features
|
|
20
|
+
|
|
21
|
+
* **codec:** annotate read-only, auto-calculated and byte-aligned schema fields ([0aa78e3](https://github.com/myq1991/netkitty/commit/0aa78e3ae77c67fbc27b45a8d17d2173ce291e81))
|
|
22
|
+
* **codec:** compile schema validators lazily and locate validation errors ([7c0b81d](https://github.com/myq1991/netkitty/commit/7c0b81db006bafd2c9e745bca922cdef5e453509))
|
|
23
|
+
* **codec:** complete the editor layer graph and infer omitted discriminators ([fae632a](https://github.com/myq1991/netkitty/commit/fae632a36d4220776ecaae693cd8d6765c8f37aa))
|
|
24
|
+
* **codec:** grade recorded errors by severity ([843381a](https://github.com/myq1991/netkitty/commit/843381a5f454805c4e5abe296cbd4f99c2ea0ad2))
|
|
25
|
+
* **codec:** validate address and number-string fields by format ([f828f4d](https://github.com/myq1991/netkitty/commit/f828f4d57b3faa895b727447d4eb669372ce6a34))
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
### BREAKING CHANGES
|
|
29
|
+
|
|
30
|
+
* **codec:** encode() rejects ipv4/ipv6/mac fields that are not valid
|
|
31
|
+
addresses and bigint fields that are not integer strings
|
|
32
|
+
(CodecSchemaValidateError, keyword format / pattern).
|
|
33
|
+
|
|
34
|
+
### Behaviour changes (check before upgrading)
|
|
35
|
+
|
|
36
|
+
#### encode() input validation (throws `CodecSchemaValidateError`)
|
|
37
|
+
- Address and number-string fields are validated by what they are. Any string field whose
|
|
38
|
+
`contentEncoding` is `ipv4` / `ipv6` / `mac` now gets `format: 'ipv4' | 'ipv6' | 'mac'`, and a `bigint`
|
|
39
|
+
field gets `pattern: '^(-?[0-9]+|0[xX][0-9a-fA-F]+)$'`. Input that used to pass — `ipv4.sip = 'abcdefg'`,
|
|
40
|
+
`sv.seqASDU[].refrTm = 'test'` — now throws (keyword `format` / `pattern`). IPv4 octets with leading
|
|
41
|
+
zeros (`010.0.0.1`) are still accepted.
|
|
42
|
+
- `gelf.form` is an enum `['chunked', 'gzip', 'uncompressed']`; an unknown or empty form now throws
|
|
43
|
+
(it used to encode a 0-byte GELF layer). Leave it out to infer it.
|
|
44
|
+
- The record-level `version` of tls-alert / tls-appdata / tls-ccsp / tls-handshake / tls-heartbeat is an
|
|
45
|
+
enum (the version names, or `'0'`).
|
|
46
|
+
- Constraints were removed where decode could produce a value that encode then rejected (no value accepted
|
|
47
|
+
before is rejected now): `ipv4.hdrLen` minimum 20 → 0; `arp.opcode` enum `[1,2,3,4]` → integer 0..65535
|
|
48
|
+
(type `number` → `integer`); `socks4.command` / `socks4.status` / `eapol.packetType` enums removed;
|
|
49
|
+
`snmp.version` / `errorStatus` / `errorIndex` and `ldap.messageID` unbounded; `goose.goosePdu.gocbRef` /
|
|
50
|
+
`datSet` / `goID` maxLength removed (encode still reports over-long values); `sv.svPdu.noASDU` minimum
|
|
51
|
+
1 → 0; `rsvp.length` minimum 8 → 0; tls-alert `length` maximum 255 → 65535;
|
|
52
|
+
tls-handshake `handshakeLength` maximum → 16777215.
|
|
53
|
+
- IEC 104 Double Command (type 46) item variant required `SCS`; it now requires `DCS`.
|
|
54
|
+
|
|
55
|
+
#### `CodecSchemaValidateError`
|
|
56
|
+
- New properties: `layerId`, `layerIndex` (position in the `encode()` array), `path` (dotted field path,
|
|
57
|
+
same form as `errors[].path`, e.g. `options[0].kind`), `errors` (Ajv error objects plus `path`).
|
|
58
|
+
- `message` is still Ajv's message. Inside item variants (`anyOf`), it is now the message of the most
|
|
59
|
+
specific failure (e.g. `must be integer` at `goosePdu.allData[0].value[0].value`) instead of Ajv's first
|
|
60
|
+
one, which was usually a sibling variant's `must be equal to constant`.
|
|
61
|
+
|
|
62
|
+
#### `result.errors` / layer `errors`
|
|
63
|
+
- Every entry has `severity: 'error' | 'warning' | 'info'` (optional in the type). Decode errors are all
|
|
64
|
+
`error`. On encode: `'Not Found'` (field left out, default used) → `info`; adjusted/flagged but written
|
|
65
|
+
→ `warning`; could not be encoded as given → `error`.
|
|
66
|
+
- `'Not Found'` is no longer reported for an omitted `etherType` / `protocol` / `nxt` that encode now
|
|
67
|
+
infers (see below). It is still reported (as `info`) for other defaulted fields, and for `etherType` when
|
|
68
|
+
nothing follows that it could be inferred from.
|
|
69
|
+
- TLS headers reported `'Not found'`; now `'Not Found'` like every other header.
|
|
70
|
+
- Internal exceptions are recorded under the failing field's path instead of `''`
|
|
71
|
+
(`Encode error: …` / `Decode error: …`, severity `error`).
|
|
72
|
+
- Errors recorded by packet-level post handlers are now included in `result.errors` (they were dropped);
|
|
73
|
+
a post handler that throws no longer escapes `encode()` / `decode()`.
|
|
74
|
+
- New messages: `Unknown TLS version '…', encoded as 0`, `Unknown alert level '…'`, `Unknown alert
|
|
75
|
+
description '…'`, `Unknown handshake type '…'`, `Unknown heartbeat type '…'`, `Unknown APCI type '…'`
|
|
76
|
+
(IEC 104 I/S/U), `Unknown form '…'` (GELF), `Header length should be at least 20` (IPv4),
|
|
77
|
+
`Cannot compute UDP checksum: no IP layer beneath UDP`, `802.3 length … exceeds 1500`,
|
|
78
|
+
`Not Found, extension ignored` (TLS handshake extension without type), `Invalid Structure value, encoded
|
|
79
|
+
as empty` / `Invalid INT64 value` (GOOSE).
|
|
80
|
+
|
|
81
|
+
#### encode() output for omitted fields
|
|
82
|
+
- An omitted parent demux field is filled from the next input layer: EtherType (eth, vlan, hsr, gre,
|
|
83
|
+
geneve, snap), IPv4 `protocol`, IPv6 `nxt` — the value `childDiscriminator()` returns. eth/vlan followed
|
|
84
|
+
by `llc` get the IEEE 802.3 length. Explicit values (including `'0000'` / `0`) are always written as
|
|
85
|
+
given. Before: `0x0000` / `0` plus `'Not Found'`. The inferred value is used for the encoded
|
|
86
|
+
layer only; the input objects passed to `encode()` are not modified.
|
|
87
|
+
- Signature fields default to their protocol constants (new schema `default`, applied by Ajv):
|
|
88
|
+
`tpkt.version` 3, `cotp.pduType` 0xF0 and `cotp.eot` true, `s7comm.protocolId` 0x32,
|
|
89
|
+
`rdp.negotiationType` 1, `rtps.magic` `'52545053'`, `bittorrent.pstrlen` 19 / `pstr`
|
|
90
|
+
(`'BitTorrent protocol'`), `isis.irpDiscriminator` `'83'`, `iso-session.spdus` (Give Tokens + Data
|
|
91
|
+
Transfer), `mms.message` `'6100'`. `snap.oui` / `etherType` default from `snap.ouiProtocol`.
|
|
92
|
+
- IEC 104 S-frame without `apciType` gets the S-format bit (it got the I-format bit). U-frame: an omitted
|
|
93
|
+
`apciType` leaves `controlField` as given (its default used to overwrite the first control byte), an
|
|
94
|
+
omitted `controlField` is a 4-octet zero word (it was 1 byte), an unknown `apciType` writes a 4-octet
|
|
95
|
+
zero word. An unknown I-frame value no longer writes its format bit into octet 5.
|
|
96
|
+
- TCP generic option `{kind: 0 | 1}` is one octet (it was a kind+length pair); `{kind}` without `data` is
|
|
97
|
+
the bare kind+length pair (it threw internally). GOOSE `Structure` without `value` is an empty Structure.
|
|
98
|
+
- UDP encoded without an IP layer beneath records a checksum error instead of throwing out of `encode()`.
|
|
99
|
+
|
|
100
|
+
#### decode() output
|
|
101
|
+
- Bytes after a GOOSE PDU (padding, trailer) stay whole in the `raw` layer; the goose layer no longer
|
|
102
|
+
swallows part of them.
|
|
103
|
+
- SOCKS4 `domain` is only decoded for a SOCKS4a request (dstIp 0.0.0.x); bytes after a plain request
|
|
104
|
+
go to `raw`.
|
|
105
|
+
- A header the fields could not reproduce is left to `raw`: IPv4 with IHL 0 or fewer bytes than its
|
|
106
|
+
header, Ethernet < 14 bytes, 802.1Q tag < 4 bytes, ARP < 28 bytes. (IPv4 IHL 1–4 still decodes as ipv4.)
|
|
107
|
+
- IEC 104 types 46 / 47 / 59 / 60 items now include `QU` (it was dropped).
|
|
108
|
+
|
|
109
|
+
#### Schema representation (`CODEC_SCHEMAS`)
|
|
110
|
+
- `vlan.etherType`, `hsr.etherType`: `contentEncoding: 'hex'` added (value format unchanged: lowercase
|
|
111
|
+
4-hex string).
|
|
112
|
+
- `arp.sender.mac` / `arp.target.mac`: `contentEncoding` `utf8` → `mac`; `arp.sender.ipv4` /
|
|
113
|
+
`arp.target.ipv4`: `utf8` → `ipv4`. `socks4.dstIp`: `contentEncoding: 'ipv4'` added.
|
|
114
|
+
- tls-alert `length` label `'Legacy Version'` → `'Length'`.
|
|
115
|
+
- `format` / `pattern` / `enum` / `default` additions listed above.
|
|
116
|
+
- New optional annotation keywords (Ajv ignores them; nothing about validation changes):
|
|
117
|
+
- `readOnly: true` on 171 fields in 45 protocols — encode ignores the value (display-only projections
|
|
118
|
+
such as http/sip/ftp/smtp `method`/`statusCode`/…, CMS `serviceDataDecoded`/`serviceDataStrings`, MMS
|
|
119
|
+
and ISO-session metadata; values encode always derives, such as dns `rdlength`, geneve `optLen`).
|
|
120
|
+
- `autoCalculated: true` on 137 fields in 100 protocols — encode computes the value when it is left out
|
|
121
|
+
(or 0 where that is the convention); an explicit value is written as given (`ipv4.length` /
|
|
122
|
+
`checksum` / `hdrLen`, `tcp.hdrLen` / `checksum`, `udp.length` / `checksum`, …).
|
|
123
|
+
- `byteAlignment: 4` on `ipv4.options`, `tcp.options`, `stun.attributes[].value`, `iscsi.dataSegment`.
|
|
124
|
+
- `cms.serviceDataDecoded` gains `properties: {}` and `additionalProperties: true` (it was the only
|
|
125
|
+
object node without `properties`).
|
|
126
|
+
|
|
127
|
+
#### allowedNextLayers()
|
|
128
|
+
- `discriminator` keeps its `{field, value} | null` shape. New entries: `llc` after eth / vlan (null),
|
|
129
|
+
`cotp` after tpkt (null), `s7comm` / `iso-session` after cotp (`{field: 'pduType', value: 240}`), `rdp`
|
|
130
|
+
after cotp (`{field: 'pduType', value: 224}`), `mms` after iso-session (null), `rtps` after udp (null),
|
|
131
|
+
`bittorrent` after tcp (null). `null` now also means "recognized by content / derived by encode", not
|
|
132
|
+
only RawData. `childDiscriminator('cotp', 'rdp' | 's7comm' | 'iso-session')` is no longer null.
|
|
133
|
+
|
|
134
|
+
#### Performance
|
|
135
|
+
- `new Codec()` no longer compiles every schema (≈570 ms → ≈15 ms). Each protocol's validator is compiled
|
|
136
|
+
on its first `encode()` (a few ms each).
|
|
137
|
+
|
|
138
|
+
### Additions
|
|
139
|
+
- Types: `CodecErrorSeverity`, `CodecSchemaValidationIssue`, `HeuristicParent`.
|
|
140
|
+
- `BaseHeader`: `heuristicParents` (editor graph only), static `HEURISTIC_PARENTS`;
|
|
141
|
+
`recordError(path, message, severity?)`; protected `encodeOmittedEtherType(field, offset)`.
|
|
142
|
+
|
|
143
|
+
### Known limitations
|
|
144
|
+
|
|
145
|
+
Not fixed in this release:
|
|
146
|
+
- UDP (and probably other) checksums read the pseudo-header from the immediately previous layer only, so
|
|
147
|
+
UDP behind AH or another extension header gets checksum 0.
|
|
148
|
+
- IGMPv3 query: the source list is dropped on encode when `ipv4.length` is left to auto-calculate (it reads
|
|
149
|
+
the IP length before it is computed).
|
|
150
|
+
- Lengths / checksums that are written as given and never computed (so not marked autoCalculated): TLS
|
|
151
|
+
record and handshake lengths, IEC 104 apduLength, cms frameLength, dnp3 length / headerCrc, OSPF
|
|
152
|
+
packetLength / checksum, igmp / pim / eigrp / rsvp / nhrp / cdp / vrrp / sctp / dccp checksums,
|
|
153
|
+
bfd length, coap tokenLength, c37118 chk, sercos3 crc32.
|
|
154
|
+
|
|
155
|
+
Also known (tracked as todo tests):
|
|
156
|
+
- IPv4 does not bound its payload by Total Length (bytes after an empty payload decode as a next header).
|
|
157
|
+
- Many pre-existing editor-graph edges do not re-decode when built from defaults alone (e.g. tcp → http
|
|
158
|
+
with an empty message; ipv4 → ipv6-hopopt / icmpv6 listed via the shared ipproto namespace but rejected
|
|
159
|
+
by match()).
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
## [1.2.1](https://github.com/myq1991/netkitty/compare/@netkitty/codec@1.2.0...@netkitty/codec@1.2.1) (2026-09-28)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
### Bug Fixes
|
|
169
|
+
|
|
170
|
+
* **codec:** decode GOOSE allData INTEGER and BIT STRING items without data loss ([eeca0a5](https://github.com/myq1991/netkitty/commit/eeca0a54a942ed84917d37b5df10d77c83d5ad06))
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
|
|
6
176
|
# [1.2.0](https://github.com/myq1991/netkitty/compare/@netkitty/codec@1.1.0...@netkitty/codec@1.2.0) (2026-07-23)
|
|
7
177
|
|
|
8
178
|
|
package/README.md
CHANGED
|
@@ -60,12 +60,15 @@ rebuilt.equals(packet) // true for a well-formed packet — decode/encode roun
|
|
|
60
60
|
```
|
|
61
61
|
|
|
62
62
|
Build a packet from scratch by handing `encode` an array of `{id, data}` inputs in outer-to-inner
|
|
63
|
-
order; any field you omit is filled from the schema's defaults, and form-string values are coerced
|
|
63
|
+
order; any field you omit is filled from the schema's defaults, and form-string values are coerced.
|
|
64
|
+
A parent's demux field you leave out — an EtherType (`eth`/`vlan`/`hsr`/`gre`/`geneve`/`snap`), the
|
|
65
|
+
IPv4 `protocol`, the IPv6 `nxt` — is filled from the layer that follows (eth before LLC gets the IEEE
|
|
66
|
+
802.3 length instead); a value you do supply is always written as given:
|
|
64
67
|
|
|
65
68
|
```ts
|
|
66
69
|
const {packet} = await codec.encode([
|
|
67
|
-
{id: 'eth', data: {dmac: 'ff:ff:ff:ff:ff:ff', smac: '00:11:22:33:44:55', etherType
|
|
68
|
-
{id: 'ipv4', data: {sip: '192.168.0.1', dip: '192.168.0.2', protocol
|
|
70
|
+
{id: 'eth', data: {dmac: 'ff:ff:ff:ff:ff:ff', smac: '00:11:22:33:44:55'}}, // etherType → '0800'
|
|
71
|
+
{id: 'ipv4', data: {sip: '192.168.0.1', dip: '192.168.0.2'}}, // protocol → 17
|
|
69
72
|
{id: 'udp', data: {srcport: 12345, dstport: 53}}
|
|
70
73
|
])
|
|
71
74
|
```
|
|
@@ -84,12 +87,19 @@ type CodecDecodeResult = {
|
|
|
84
87
|
name: string // human-readable name, e.g. 'Ethernet II'
|
|
85
88
|
nickname: string // short tag, e.g. 'ETH'
|
|
86
89
|
protocol: boolean // whether this layer is a real protocol (false for raw payload)
|
|
87
|
-
errors: CodecErrorInfo[] // {id, path, message}[] — field-path-addressed decode errors
|
|
90
|
+
errors: CodecErrorInfo[] // {id, path, message, severity}[] — field-path-addressed decode errors
|
|
88
91
|
data: HeaderTreeNode // the decoded field tree
|
|
89
92
|
}
|
|
90
93
|
|
|
91
94
|
type CodecEncodeInput = Pick<CodecDecodeResult, 'id' | 'data'> & Partial<Omit<CodecDecodeResult, 'id' | 'data'>>
|
|
92
95
|
type CodecEncodeResult = {packet: Buffer, errors: CodecErrorInfo[]}
|
|
96
|
+
|
|
97
|
+
type CodecErrorInfo = {
|
|
98
|
+
id: string // layer id
|
|
99
|
+
path: string // dotted field path inside the layer, e.g. 'flags.df', 'options[0].kind'
|
|
100
|
+
message: string // e.g. 'Not Found', 'IPv4 version should be 4'
|
|
101
|
+
severity?: 'error' | 'warning' | 'info' // always set by the built-in codec, see below
|
|
102
|
+
}
|
|
93
103
|
```
|
|
94
104
|
|
|
95
105
|
## Key concepts
|
|
@@ -107,17 +117,48 @@ declaration plays four parts at once:
|
|
|
107
117
|
yields exact dotted field paths (`options[3].kind`) for binding errors to UI inputs.
|
|
108
118
|
3. **Input validation** — `encode` validates each input with Ajv against the schema. `useDefaults`
|
|
109
119
|
makes the schema double as a packet template (omitted fields are filled in); `coerceTypes` tolerates
|
|
110
|
-
form-string input.
|
|
120
|
+
form-string input. A string field's `contentEncoding` implies its format: `ipv4`/`ipv6`/`mac` fields
|
|
121
|
+
carry `format: 'ipv4'|'ipv6'|'mac'` and `bigint` fields a numeric `pattern`, in the published schema
|
|
122
|
+
and in the validator alike, so `'abcdefg'` is rejected as an IPv4 address.
|
|
111
123
|
4. **UI form metadata** — custom keywords (`label`, `hidden`, `contentEncoding`) plus `enum`/`min`/`max`
|
|
112
|
-
and `anyOf` + `const` discriminators describe how a form should render each field.
|
|
124
|
+
and `anyOf` + `const` discriminators describe how a form should render each field. Three optional
|
|
125
|
+
annotations tell an editor how `encode` treats a field (annotation only — Ajv ignores them):
|
|
126
|
+
- `readOnly: true` — encode ignores the value, so editing it never changes the bytes (display-only
|
|
127
|
+
projections such as HTTP `method`/`statusCode` or CMS `serviceDataDecoded`, decoded from a
|
|
128
|
+
verbatim field that is the real encode authority; also values encode always derives itself). On an
|
|
129
|
+
object/array it covers every descendant.
|
|
130
|
+
- `autoCalculated: true` — encode computes the value (length, checksum, count, offset…) from the
|
|
131
|
+
rest of the packet when it is left out (or 0 where that is the field's convention); an explicit
|
|
132
|
+
value is still written as given. E.g. `ipv4.length`, `ipv4.checksum`, `tcp.hdrLen`.
|
|
133
|
+
- `byteAlignment: N` — encode zero-pads the field to a multiple of N bytes, e.g. `ipv4.options`
|
|
134
|
+
(4) and `tcp.options` (4).
|
|
113
135
|
|
|
114
136
|
### Decode never fails; errors accumulate instead of throwing
|
|
115
137
|
|
|
116
138
|
Malformed packets are first-class input. A field whose bytes are truncated or invalid records an error
|
|
117
|
-
via `recordError()` (a `{id, path, message}` entry on the layer's `errors`) and clamps to a
|
|
118
|
-
value — it does not throw. Decode therefore always returns a full best-effort layer list plus
|
|
119
|
-
field-path-addressed error list you can use to highlight problems in a UI.
|
|
120
|
-
|
|
139
|
+
via `recordError()` (a `{id, path, message, severity}` entry on the layer's `errors`) and clamps to a
|
|
140
|
+
best-effort value — it does not throw. Decode therefore always returns a full best-effort layer list plus
|
|
141
|
+
a field-path-addressed error list you can use to highlight problems in a UI. Whatever decode returns is
|
|
142
|
+
accepted by `encode` (a header its fields could not reproduce — IPv4 with IHL 0, a header cut short — is
|
|
143
|
+
left to `raw` instead), so read → edit → re-emit never dead-ends.
|
|
144
|
+
|
|
145
|
+
`severity` grades each entry: every decode error is `error`; on encode, a field left out that fell back to
|
|
146
|
+
its default (`'Not Found'`) is `info`, a value encode adjusted or flagged but still wrote (clamped to its
|
|
147
|
+
range, IPv4 version ≠ 4, a checksum with no IP layer to compute it from) is `warning`, and a value that
|
|
148
|
+
could not be encoded as given (an internal failure, an unknown name such as a TLS alert level) is `error`.
|
|
149
|
+
|
|
150
|
+
The only deliberate fast-fail is the Ajv shape check at the `encode` entry point. It throws a
|
|
151
|
+
`CodecSchemaValidateError` that names the input: `layerId` and `layerIndex` (its position in the `encode`
|
|
152
|
+
array), `path` (same dotted form as `errors[].path`) and `errors` (Ajv's error objects); `message` is
|
|
153
|
+
Ajv's message for the most specific failure.
|
|
154
|
+
|
|
155
|
+
```ts
|
|
156
|
+
try {
|
|
157
|
+
await codec.encode([{id: 'eth', data: {}}, {id: 'ipv4', data: {sip: 'abc'}}])
|
|
158
|
+
} catch (e) {
|
|
159
|
+
if (e instanceof CodecSchemaValidateError) e.layerId + '.' + e.path // 'ipv4.sip'
|
|
160
|
+
}
|
|
161
|
+
```
|
|
121
162
|
|
|
122
163
|
### RawData is the catch-all
|
|
123
164
|
|
|
@@ -157,6 +198,13 @@ error/ok severity (a Wireshark-style hex-to-field view); `summary(decoded)` rend
|
|
|
157
198
|
description (Wireshark's Info column); `allowedNextLayers`, `childDiscriminator` and `checkConsistency`
|
|
158
199
|
describe and validate which layer may follow which.
|
|
159
200
|
|
|
201
|
+
`allowedNextLayers(parent)` lists each child with the `{field, value}` to set on the parent so decode
|
|
202
|
+
routes to it. Children decode recognizes by their own bytes (LLC after an 802.3 frame, COTP after TPKT,
|
|
203
|
+
S7comm / ISO-Session / RDP after COTP, MMS after ISO-Session, RTPS, BitTorrent) are listed too — a header
|
|
204
|
+
declares them with `heuristicParents` — usually with a `null` discriminator (nothing to set), or with the
|
|
205
|
+
parent value they need (RDP: COTP `pduType` 0xE0). Their signature fields default to the protocol
|
|
206
|
+
constants, so a layer added from scratch re-opens as that layer.
|
|
207
|
+
|
|
160
208
|
## Built-in headers
|
|
161
209
|
|
|
162
210
|
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.
|
package/README.zh-CN.md
CHANGED
|
@@ -58,12 +58,14 @@ rebuilt.equals(packet) // 对于结构完好的报文为 true —— 解码/
|
|
|
58
58
|
```
|
|
59
59
|
|
|
60
60
|
想从零构造一个报文,只要按从外到内的顺序给 `encode` 传一组 `{id, data}` 输入即可;没填的字段会用
|
|
61
|
-
schema
|
|
61
|
+
schema 里的默认值补齐,表单传来的字符串也会被自动转换成对应类型。上一层用来区分下一层的字段如果没填
|
|
62
|
+
(`eth`/`vlan`/`hsr`/`gre`/`geneve`/`snap` 的 EtherType、IPv4 的 `protocol`、IPv6 的 `nxt`),会按
|
|
63
|
+
后面那一层自动填写(eth 后面接 LLC 时填 IEEE 802.3 长度);显式填写的值总是原样写出:
|
|
62
64
|
|
|
63
65
|
```ts
|
|
64
66
|
const {packet} = await codec.encode([
|
|
65
|
-
{id: 'eth', data: {dmac: 'ff:ff:ff:ff:ff:ff', smac: '00:11:22:33:44:55', etherType
|
|
66
|
-
{id: 'ipv4', data: {sip: '192.168.0.1', dip: '192.168.0.2', protocol
|
|
67
|
+
{id: 'eth', data: {dmac: 'ff:ff:ff:ff:ff:ff', smac: '00:11:22:33:44:55'}}, // etherType → '0800'
|
|
68
|
+
{id: 'ipv4', data: {sip: '192.168.0.1', dip: '192.168.0.2'}}, // protocol → 17
|
|
67
69
|
{id: 'udp', data: {srcport: 12345, dstport: 53}}
|
|
68
70
|
])
|
|
69
71
|
```
|
|
@@ -82,12 +84,19 @@ type CodecDecodeResult = {
|
|
|
82
84
|
name: string // 可读名称,如 'Ethernet II'
|
|
83
85
|
nickname: string // 简称,如 'ETH'
|
|
84
86
|
protocol: boolean // 该层是否为真正的协议(原始载荷为 false)
|
|
85
|
-
errors: CodecErrorInfo[] // {id, path, message}[] —— 用字段路径定位的解码错误
|
|
87
|
+
errors: CodecErrorInfo[] // {id, path, message, severity}[] —— 用字段路径定位的解码错误
|
|
86
88
|
data: HeaderTreeNode // 解码出来的字段树
|
|
87
89
|
}
|
|
88
90
|
|
|
89
91
|
type CodecEncodeInput = Pick<CodecDecodeResult, 'id' | 'data'> & Partial<Omit<CodecDecodeResult, 'id' | 'data'>>
|
|
90
92
|
type CodecEncodeResult = {packet: Buffer, errors: CodecErrorInfo[]}
|
|
93
|
+
|
|
94
|
+
type CodecErrorInfo = {
|
|
95
|
+
id: string // 协议层 id
|
|
96
|
+
path: string // 层内的点分字段路径,如 'flags.df'、'options[0].kind'
|
|
97
|
+
message: string // 如 'Not Found'、'IPv4 version should be 4'
|
|
98
|
+
severity?: 'error' | 'warning' | 'info' // 内置编解码器总会填写,含义见下文
|
|
99
|
+
}
|
|
91
100
|
```
|
|
92
101
|
|
|
93
102
|
## 关键概念
|
|
@@ -104,16 +113,44 @@ type CodecEncodeResult = {packet: Buffer, errors: CodecErrorInfo[]}
|
|
|
104
113
|
路径的代理对象,深层访问永远不会抛异常,并能给出精确的点分字段路径(如 `options[3].kind`),用来把
|
|
105
114
|
错误绑定到界面上对应的输入框。
|
|
106
115
|
3. **输入校验**——`encode` 会用 Ajv 按 schema 校验每一份输入。`useDefaults` 让 schema 同时充当报文
|
|
107
|
-
模板(缺失字段自动补齐);`coerceTypes`
|
|
116
|
+
模板(缺失字段自动补齐);`coerceTypes` 则容忍来自表单的字符串输入。字符串字段的 `contentEncoding`
|
|
117
|
+
同时决定它的格式约束:`ipv4`/`ipv6`/`mac` 字段带 `format: 'ipv4'|'ipv6'|'mac'`,`bigint` 字段带数字
|
|
118
|
+
`pattern`,公开的 schema 和编码校验器里都一样,所以 `'abcdefg'` 不会再被当成 IPv4 地址接受。
|
|
108
119
|
4. **界面表单元数据**——自定义关键字(`label`、`hidden`、`contentEncoding`),加上 `enum`/`min`/`max`
|
|
109
|
-
以及 `anyOf` + `const`
|
|
120
|
+
以及 `anyOf` + `const` 判别式,共同描述表单该如何渲染每个字段。另有三个可选注解告诉编辑器 `encode`
|
|
121
|
+
如何对待某个字段(仅为注解,Ajv 不据此校验):
|
|
122
|
+
- `readOnly: true`——encode 忽略该值,修改它永远不会改变编码字节(例如 HTTP `method`/`statusCode`、
|
|
123
|
+
CMS `serviceDataDecoded` 这类从逐字节保留的字段解出、仅供展示的投影——真正的编码依据是那个逐字节
|
|
124
|
+
字段;以及 encode 总是自行推导的值)。标在对象/数组上时覆盖其全部子孙字段。
|
|
125
|
+
- `autoCalculated: true`——输入缺省该字段(或按该字段约定给 0)时,encode 会根据报文其余部分自动
|
|
126
|
+
计算(长度、校验和、计数、偏移等);显式给出的值仍按原样写入。例如 `ipv4.length`、`ipv4.checksum`、
|
|
127
|
+
`tcp.hdrLen`。
|
|
128
|
+
- `byteAlignment: N`——encode 会用 0 把该字段补齐到 N 字节的整数倍,例如 `ipv4.options`(4)、
|
|
129
|
+
`tcp.options`(4)。
|
|
110
130
|
|
|
111
131
|
### 解码永不失败,错误只累积不抛出
|
|
112
132
|
|
|
113
133
|
畸形报文本身就是合法输入。某个字段的字节被截断或取值非法时,会通过 `recordError()` 记录一条错误(即该
|
|
114
|
-
层 `errors` 上的一条 `{id, path, message}`)
|
|
115
|
-
|
|
116
|
-
|
|
134
|
+
层 `errors` 上的一条 `{id, path, message, severity}`),并把值收敛到一个尽力而为的结果——而不是抛异常。
|
|
135
|
+
因此解码总能返回一份完整的、尽力而为的分层结果,外加一份用字段路径定位的错误清单,供界面高亮问题。解码
|
|
136
|
+
返回的任何结果 `encode` 都能接受(字段无法复原的协议头,比如 IHL 为 0 的 IPv4、被截断的头部,会直接留给
|
|
137
|
+
`raw`),所以"读取 → 编辑 → 重新写出"不会卡住。
|
|
138
|
+
|
|
139
|
+
`severity` 给每条错误分级:解码错误一律是 `error`;编码时,没填而用了默认值的字段(`'Not Found'`)是
|
|
140
|
+
`info`,编码器调整或标记过、但仍然写出的值(超范围被钳位、IPv4 version 不是 4、没有 IP 层算不了校验和)
|
|
141
|
+
是 `warning`,无法按给定值编码的(内部异常、TLS 告警级别这类不认识的名称)是 `error`。
|
|
142
|
+
|
|
143
|
+
唯一刻意的快速失败,是 `encode` 入口处的 Ajv 形状校验。它抛出的 `CodecSchemaValidateError` 会指明是哪一项
|
|
144
|
+
输入:`layerId` 和 `layerIndex`(在 `encode` 数组里的位置)、`path`(与 `errors[].path` 同样的点分形式),
|
|
145
|
+
以及 `errors`(Ajv 的原始错误对象);`message` 是最具体那一条失败的 Ajv 信息。
|
|
146
|
+
|
|
147
|
+
```ts
|
|
148
|
+
try {
|
|
149
|
+
await codec.encode([{id: 'eth', data: {}}, {id: 'ipv4', data: {sip: 'abc'}}])
|
|
150
|
+
} catch (e) {
|
|
151
|
+
if (e instanceof CodecSchemaValidateError) e.layerId + '.' + e.path // 'ipv4.sip'
|
|
152
|
+
}
|
|
153
|
+
```
|
|
117
154
|
|
|
118
155
|
### RawData 兜底
|
|
119
156
|
|
|
@@ -147,6 +184,12 @@ decode 处理器按先进先出执行(内层语义依赖外层上下文,例如 T
|
|
|
147
184
|
(类似 Wireshark 的字节到字段视图);`summary(decoded)` 渲染出一行描述(相当于 Wireshark 的 Info 列);
|
|
148
185
|
`allowedNextLayers`、`childDiscriminator` 和 `checkConsistency` 则描述并校验哪一层可以接在哪一层之后。
|
|
149
186
|
|
|
187
|
+
`allowedNextLayers(parent)` 列出每个可接的下一层,以及要在上一层设置的 `{field, value}`,解码才会走到它。
|
|
188
|
+
靠自身内容识别的协议(802.3 帧后的 LLC、TPKT 后的 COTP、COTP 后的 S7comm / ISO-Session / RDP、
|
|
189
|
+
ISO-Session 后的 MMS、RTPS、BitTorrent)也会列出——协议头用 `heuristicParents` 声明——通常区分字段为
|
|
190
|
+
`null`(无需设置),或给出它需要的上一层取值(RDP 需要 COTP `pduType` 为 0xE0)。这些协议的签名字段默认就是
|
|
191
|
+
协议常量,所以从零添加的一层重新打开时仍是这一层。
|
|
192
|
+
|
|
150
193
|
## 内置协议头
|
|
151
194
|
|
|
152
195
|
默认注册了 189 个协议头(`raw` 是强制兜底)。向 `new Codec(customCodecs)` 传入自定义类可覆盖同 id 的内置头或新增协议头。
|
package/dist/Codec.d.ts
CHANGED
|
@@ -88,8 +88,9 @@ export declare class Codec {
|
|
|
88
88
|
/**
|
|
89
89
|
* Editor helper (read-only projection over the same demux graph decode uses): the layers that
|
|
90
90
|
* may follow `parentLayerId`, each tagged with the {field,value} to set on the parent so decode
|
|
91
|
-
* would route to it. Derived by reversing the dispatch table over the parent's producer fields
|
|
92
|
-
*
|
|
91
|
+
* would route to it. Derived by reversing the dispatch table over the parent's producer fields,
|
|
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
94
|
* @param parentLayerId
|
|
94
95
|
*/
|
|
95
96
|
allowedNextLayers(parentLayerId: string): NextLayer[];
|
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,84 @@ 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,
|
|
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 (
|
|
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
|
-
|
|
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
|
-
|
|
363
|
+
let validated;
|
|
364
|
+
try {
|
|
365
|
+
validated = codecModule.validate(input.data);
|
|
366
|
+
}
|
|
367
|
+
catch (e) {
|
|
368
|
+
//Name the input layer by position too, so a caller can bind the error to its form.
|
|
369
|
+
if (e instanceof CodecSchemaValidateError_1.CodecSchemaValidateError)
|
|
370
|
+
e.layerIndex = layerIndex;
|
|
371
|
+
throw e;
|
|
372
|
+
}
|
|
373
|
+
codecModule.instance = new FlexibleObject_1.FlexibleObject(this.#inferDiscriminator(codecModule, validated, inputs[layerIndex + 1]));
|
|
339
374
|
await codecModule.encode();
|
|
340
|
-
|
|
375
|
+
reports.push(codecModule);
|
|
341
376
|
codecData.startPos = codecModule.endPos;
|
|
342
377
|
codecModules.push(codecModule);
|
|
343
378
|
}
|
|
344
379
|
return codecData;
|
|
345
380
|
}
|
|
381
|
+
/**
|
|
382
|
+
* Demux namespaces whose producer field encode fills from the next input layer when it is left out:
|
|
383
|
+
* the EtherType (eth/vlan/hsr/gre/geneve…) and the IP protocol / IPv6 next header. Explicit values
|
|
384
|
+
* always win, so a deliberately inconsistent packet can still be crafted.
|
|
385
|
+
* @private
|
|
386
|
+
*/
|
|
387
|
+
static #INFERRED_NAMESPACES = ['ethertype', 'ipproto'];
|
|
388
|
+
/**
|
|
389
|
+
* When none of a layer's producer fields (in an inferred namespace) was supplied, set the one that
|
|
390
|
+
* routes decode to the next input layer, e.g. eth.etherType = '0800' before ipv4 — the value
|
|
391
|
+
* childDiscriminator() would suggest. A layer whose child is matched by content (LLC after eth)
|
|
392
|
+
* derives its own value instead (see EthernetII's 802.3 length). The value goes on a shallow copy:
|
|
393
|
+
* the caller's input object is left as given, so re-encoding it after the next layer changes infers
|
|
394
|
+
* again instead of replaying a stale "explicit" value.
|
|
395
|
+
* @private
|
|
396
|
+
*/
|
|
397
|
+
#inferDiscriminator(codecModule, data, next) {
|
|
398
|
+
if (!next || !data || typeof data !== 'object')
|
|
399
|
+
return data;
|
|
400
|
+
const fields = data;
|
|
401
|
+
const producers = codecModule.demuxProducers.filter((producer) => _a.#INFERRED_NAMESPACES.includes(producer.namespace));
|
|
402
|
+
if (!producers.length)
|
|
403
|
+
return data;
|
|
404
|
+
if (producers.some((producer) => fields[producer.field] !== undefined))
|
|
405
|
+
return data;
|
|
406
|
+
const discriminator = this.#childDiscriminatorCached(codecModule.id, next.id);
|
|
407
|
+
if (!discriminator || !producers.some((producer) => producer.field === discriminator.field))
|
|
408
|
+
return data;
|
|
409
|
+
return { ...data, [discriminator.field]: discriminator.value };
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* childDiscriminator() memoised per parent/child pair for the encode path: it reverses the whole
|
|
413
|
+
* dispatch table, which is too much work to repeat for every encoded layer. Cleared with the table.
|
|
414
|
+
* @private
|
|
415
|
+
*/
|
|
416
|
+
#childDiscriminatorCached(parentLayerId, childLayerId) {
|
|
417
|
+
const key = `${parentLayerId}\u0000${childLayerId}`;
|
|
418
|
+
if (!this.#discriminatorCache.has(key))
|
|
419
|
+
this.#discriminatorCache.set(key, this.childDiscriminator(parentLayerId, childLayerId));
|
|
420
|
+
return this.#discriminatorCache.get(key);
|
|
421
|
+
}
|
|
346
422
|
/**
|
|
347
423
|
* Internal decode packet
|
|
348
424
|
* @param codecData
|
|
@@ -397,14 +473,23 @@ class Codec {
|
|
|
397
473
|
* @param inputs
|
|
398
474
|
*/
|
|
399
475
|
async encode(inputs) {
|
|
400
|
-
const
|
|
401
|
-
const codecData = await this.#encode(inputs,
|
|
476
|
+
const reports = [];
|
|
477
|
+
const codecData = await this.#encode(inputs, reports);
|
|
402
478
|
const postEncodeHandlers = (0, ProcessPacketPostHandlers_1.ProcessPacketEncodePostHandlers)(codecData.postHandlers);
|
|
403
479
|
let postEncodeHandler = postEncodeHandlers.shift();
|
|
404
480
|
while (postEncodeHandler) {
|
|
405
481
|
await postEncodeHandler.handler();
|
|
406
482
|
postEncodeHandler = postEncodeHandlers.shift();
|
|
407
483
|
}
|
|
484
|
+
//Collect each layer's errors only now, so those recorded by packet-level post handlers (which
|
|
485
|
+
//run after every layer is encoded) are reported too; layer order is preserved.
|
|
486
|
+
const errors = [];
|
|
487
|
+
for (const report of reports) {
|
|
488
|
+
if (Array.isArray(report.errors))
|
|
489
|
+
report.errors.forEach((errorInfo) => errors.push(errorInfo));
|
|
490
|
+
else
|
|
491
|
+
errors.push(report);
|
|
492
|
+
}
|
|
408
493
|
return {
|
|
409
494
|
packet: codecData.packetLength === undefined ? codecData.packet : codecData.packet.subarray(0, codecData.packetLength),
|
|
410
495
|
errors: errors
|
|
@@ -423,8 +508,9 @@ class Codec {
|
|
|
423
508
|
/**
|
|
424
509
|
* Editor helper (read-only projection over the same demux graph decode uses): the layers that
|
|
425
510
|
* 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
|
-
*
|
|
511
|
+
* would route to it. Derived by reversing the dispatch table over the parent's producer fields,
|
|
512
|
+
* plus the content-heuristic children that declare this parent in `heuristicParents` (listed with a
|
|
513
|
+
* null discriminator). RawData is always appended as the custom/fallback layer that may follow anything.
|
|
428
514
|
* @param parentLayerId
|
|
429
515
|
*/
|
|
430
516
|
allowedNextLayers(parentLayerId) {
|
|
@@ -458,6 +544,15 @@ class Codec {
|
|
|
458
544
|
}
|
|
459
545
|
}
|
|
460
546
|
}
|
|
547
|
+
//Content-heuristic children (LLC after eth, COTP after TPKT, …): routed by their own bytes or by a
|
|
548
|
+
//value encode derives, so usually there is no parent field to set (discriminator null); a child
|
|
549
|
+
//may declare the parent value it needs (RDP: COTP pduType 0xE0).
|
|
550
|
+
for (const { codecModuleConstructor, discriminator } of this.#heuristicChildren.get(parentLayerId) || []) {
|
|
551
|
+
if (seen.has(codecModuleConstructor.PROTOCOL_ID))
|
|
552
|
+
continue;
|
|
553
|
+
seen.add(codecModuleConstructor.PROTOCOL_ID);
|
|
554
|
+
result.push({ id: codecModuleConstructor.PROTOCOL_ID, name: codecModuleConstructor.PROTOCOL_NAME, discriminator: discriminator });
|
|
555
|
+
}
|
|
461
556
|
result.push({ id: this.#rawDataCodec.PROTOCOL_ID, name: this.#rawDataCodec.PROTOCOL_NAME, discriminator: null });
|
|
462
557
|
return result;
|
|
463
558
|
}
|
|
@@ -630,3 +725,4 @@ class Codec {
|
|
|
630
725
|
}
|
|
631
726
|
}
|
|
632
727
|
exports.Codec = Codec;
|
|
728
|
+
_a = Codec;
|