@netkitty/codec 2.2.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.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,67 @@
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
+
6
67
  # [2.2.0](https://github.com/myq1991/netkitty/compare/@netkitty/codec@2.1.0...@netkitty/codec@2.2.0) (2026-11-27)
7
68
 
8
69
 
package/README.md CHANGED
@@ -227,6 +227,15 @@ declares them with `heuristicParents` — usually with a `null` discriminator (n
227
227
  parent value they need (RDP: COTP `pduType` 0xE0). Their signature fields default to the protocol
228
228
  constants, so a layer added from scratch re-opens as that layer.
229
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
+
230
239
  ## Built-in headers
231
240
 
232
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.
package/README.zh-CN.md CHANGED
@@ -209,6 +209,13 @@ ISO-Session 后的 MMS、RTPS、BitTorrent)也会列出——协议头用 `heuri
209
209
  `null`(无需设置),或给出它需要的上一层取值(RDP 需要 COTP `pduType` 为 0xE0)。这些协议的签名字段默认就是
210
210
  协议常量,所以从零添加的一层重新打开时仍是这一层。
211
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
+
212
219
  ## 内置协议头
213
220
 
214
221
  默认注册了 191 个头:189 个协议,加上 `raw`(强制兜底)和 `trailer`(超出该层自身长度的字节)。向 `new Codec(customCodecs)` 传入自定义类可覆盖同 id 的内置头或新增协议头。
package/dist/Codec.d.ts CHANGED
@@ -92,18 +92,33 @@ export declare class Codec {
92
92
  * plus the content-heuristic children that declare this parent in `heuristicParents` (listed with a
93
93
  * null discriminator). RawData (the custom/fallback layer) and Trailer (padding written after every
94
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).
95
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
96
105
  */
97
- allowedNextLayers(parentLayerId: string): NextLayer[];
106
+ allowedNextLayers(parentLayerId: string, options?: {
107
+ ancestors?: string[];
108
+ }): NextLayer[];
98
109
  /**
99
110
  * The {field,value} to set on `parentLayerId` so `childLayerId` follows it — used to auto-fill
100
111
  * the parent discriminator when a child is added, and to suggest a fix for a consistency issue.
101
112
  * Null when the child is not reachable from that parent via the demux graph (RawData, or a
102
- * 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).
103
115
  * @param parentLayerId
104
116
  * @param childLayerId
117
+ * @param options as for allowedNextLayers()
105
118
  */
106
- childDiscriminator(parentLayerId: string, childLayerId: string): {
119
+ childDiscriminator(parentLayerId: string, childLayerId: string, options?: {
120
+ ancestors?: string[];
121
+ }): {
107
122
  field: string;
108
123
  value: string | number;
109
124
  } | null;
@@ -112,10 +127,12 @@ export declare class Codec {
112
127
  * actually follows (e.g. eth.etherType says IPv6 but the next layer is IPv4). This is advisory
113
128
  * only — encode never blocks on it, since a deliberately-inconsistent packet is a valid crafted
114
129
  * packet. Only demux-based relationships are checked; content-heuristic children (TLS/IEC104) are
115
- * not flagged. RawData and Trailer may follow anything and are 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).
116
133
  * @param decoded
117
134
  */
118
- checkConsistency(decoded: CodecDecodeResult[]): ConsistencyIssue[];
135
+ checkConsistency(decoded: CodecEncodeInput[]): ConsistencyIssue[];
119
136
  /**
120
137
  * Wireshark-style dissection: decode the packet with byte-range tracking on, then project each
121
138
  * layer into a field tree carrying the value, the schema label, the exact packet bytes the field
package/dist/Codec.js CHANGED
@@ -423,16 +423,26 @@ class Codec {
423
423
  return { ...data, [discriminator.field]: discriminator.value };
424
424
  }
425
425
  /**
426
- * childDiscriminator() memoised per parent/child pair for the encode path: it reverses the whole
427
- * dispatch table, which is too much work to repeat for every encoded layer. Cleared with the table.
426
+ * The parent field value that routes decode to the child, memoised per parent/child pair for the
427
+ * encode path: it reverses the whole dispatch table, which is too much work to repeat for every
428
+ * encoded layer. Cleared with the table. Read from the unfiltered graph, not from childDiscriminator():
429
+ * a child the editor menu leaves out on this carrier (OSPFv3 over IPv4) still gets its parent field
430
+ * filled, so a deliberately unusual stack can be crafted.
428
431
  * @private
429
432
  */
430
433
  #childDiscriminatorCached(parentLayerId, childLayerId) {
431
434
  const key = `${parentLayerId}\u0000${childLayerId}`;
432
435
  if (!this.#discriminatorCache.has(key))
433
- this.#discriminatorCache.set(key, this.childDiscriminator(parentLayerId, childLayerId));
436
+ this.#discriminatorCache.set(key, _a.#discriminatorIn(this.#nextLayers(parentLayerId), childLayerId));
434
437
  return this.#discriminatorCache.get(key);
435
438
  }
439
+ static #discriminatorIn(nextLayers, childLayerId) {
440
+ for (const next of nextLayers) {
441
+ if (next.id === childLayerId && next.discriminator)
442
+ return next.discriminator;
443
+ }
444
+ return null;
445
+ }
436
446
  /**
437
447
  * Internal decode packet
438
448
  * @param codecData
@@ -552,9 +562,53 @@ class Codec {
552
562
  * plus the content-heuristic children that declare this parent in `heuristicParents` (listed with a
553
563
  * null discriminator). RawData (the custom/fallback layer) and Trailer (padding written after every
554
564
  * other layer) are always appended: either may follow anything.
565
+ *
566
+ * Headers that run over one IP version only (`ipVersions`: ICMP over IPv4; ICMPv6, OSPFv3 and the
567
+ * IPv6 Hop-by-Hop header over IPv6) are left out when the IP version beneath is known to be the
568
+ * other one, and a header that must directly follow its IP header (`directlyAfterIP`) is listed only
569
+ * under ipv4 / ipv6. The version is known when the parent is ipv4 / ipv6 or runs over one version
570
+ * itself (ipv6-hopopt), or from `options.ancestors`; under AH with no ancestors given, both
571
+ * versions' children are listed (checkConsistency() flags a wrong pick).
555
572
  * @param parentLayerId
573
+ * @param options `ancestors`: the ids of the layers beneath the parent, outermost first (e.g.
574
+ * ['eth', 'ipv4'] for parent 'ah'), so a parent such as AH can be placed over its IP version
575
+ */
576
+ allowedNextLayers(parentLayerId, options = {}) {
577
+ const ipVersion = this.#ipVersionAt([...(options.ancestors || []), parentLayerId]);
578
+ const parentIsIP = parentLayerId === 'ipv4' || parentLayerId === 'ipv6';
579
+ return this.#nextLayers(parentLayerId).filter((next) => {
580
+ const codecModuleConstructor = this.#codecConstructorById.get(next.id);
581
+ if (!codecModuleConstructor)
582
+ return true;
583
+ if (codecModuleConstructor.DIRECTLY_AFTER_IP && !parentIsIP)
584
+ return false;
585
+ const ipVersions = codecModuleConstructor.IP_VERSIONS;
586
+ return !ipVersions.length || ipVersion === undefined || ipVersions.includes(ipVersion);
587
+ });
588
+ }
589
+ /**
590
+ * The IP version of the nearest IP layer in a stack of layer ids (outermost first): 4 or 6 for
591
+ * ipv4 / ipv6, or the single version a layer runs over (ipv6-hopopt); undefined when none says.
592
+ * @private
556
593
  */
557
- allowedNextLayers(parentLayerId) {
594
+ #ipVersionAt(stack) {
595
+ for (let i = stack.length - 1; i >= 0; i--) {
596
+ if (stack[i] === 'ipv4')
597
+ return 4;
598
+ if (stack[i] === 'ipv6')
599
+ return 6;
600
+ const ipVersions = this.#codecConstructorById.get(stack[i])?.IP_VERSIONS || [];
601
+ if (ipVersions.length === 1)
602
+ return ipVersions[0];
603
+ }
604
+ return undefined;
605
+ }
606
+ /**
607
+ * The unfiltered parent→child graph allowedNextLayers() projects (see there).
608
+ * @param parentLayerId
609
+ * @private
610
+ */
611
+ #nextLayers(parentLayerId) {
558
612
  const result = [];
559
613
  const seen = new Set();
560
614
  for (const producer of this.#producersOf(parentLayerId)) {
@@ -602,23 +656,23 @@ class Codec {
602
656
  * The {field,value} to set on `parentLayerId` so `childLayerId` follows it — used to auto-fill
603
657
  * the parent discriminator when a child is added, and to suggest a fix for a consistency issue.
604
658
  * Null when the child is not reachable from that parent via the demux graph (RawData, or a
605
- * content-heuristic child such as TLS/IEC104 whose match is port/content based).
659
+ * content-heuristic child such as TLS/IEC104 whose match is port/content based), or when
660
+ * allowedNextLayers() leaves it out on that carrier (OSPFv3 under ipv4).
606
661
  * @param parentLayerId
607
662
  * @param childLayerId
663
+ * @param options as for allowedNextLayers()
608
664
  */
609
- childDiscriminator(parentLayerId, childLayerId) {
610
- for (const next of this.allowedNextLayers(parentLayerId)) {
611
- if (next.id === childLayerId && next.discriminator)
612
- return next.discriminator;
613
- }
614
- return null;
665
+ childDiscriminator(parentLayerId, childLayerId, options = {}) {
666
+ return _a.#discriminatorIn(this.allowedNextLayers(parentLayerId, options), childLayerId);
615
667
  }
616
668
  /**
617
669
  * Editor helper: report parent layers whose discriminator field does not point at the child that
618
670
  * actually follows (e.g. eth.etherType says IPv6 but the next layer is IPv4). This is advisory
619
671
  * only — encode never blocks on it, since a deliberately-inconsistent packet is a valid crafted
620
672
  * packet. Only demux-based relationships are checked; content-heuristic children (TLS/IEC104) are
621
- * not flagged. RawData and Trailer may follow anything and are never flagged.
673
+ * not flagged. RawData and Trailer may follow anything and are never flagged. Also reports a header
674
+ * placed on a carrier it does not run over (`kind: 'carrier'`, see ConsistencyIssue). Accepts decode
675
+ * results or encode input (only `id` and `data` are read).
622
676
  * @param decoded
623
677
  */
624
678
  checkConsistency(decoded) {
@@ -665,10 +719,50 @@ class Codec {
665
719
  field: representative.producer.field,
666
720
  actual: representative.actual,
667
721
  suggestion: this.childDiscriminator(parent.id, child.id),
668
- message: `${parent.id}.${representative.producer.field}=${representative.actual} 与下一层 '${child.id}' 不符`
722
+ message: `${parent.id}.${representative.producer.field}=${representative.actual} 与下一层 '${child.id}' 不符`,
723
+ kind: 'discriminator'
724
+ });
725
+ }
726
+ //Carrier: a header that runs over one IP version only, or that must directly follow its IP
727
+ //header, placed elsewhere. Decode never yields such a stack (match() rejects it and the bytes
728
+ //become raw), so this is for encode input an editor is about to save.
729
+ for (let i = 1; i < decoded.length; i++) {
730
+ const parent = decoded[i - 1];
731
+ const child = decoded[i];
732
+ const codecModuleConstructor = this.#codecConstructorById.get(child.id);
733
+ if (!codecModuleConstructor)
734
+ continue;
735
+ let message = undefined;
736
+ const ipVersions = codecModuleConstructor.IP_VERSIONS;
737
+ if (ipVersions.length) {
738
+ const ipVersion = this.#ipVersionAt(decoded.slice(0, i).map((layer) => layer.id));
739
+ const carriers = ipVersions.map((version) => `IPv${version}`).join(' / ');
740
+ if (ipVersion === undefined)
741
+ message = `'${child.id}' 只能承载在 ${carriers} 上,但下面没有 IP 层`;
742
+ else if (!ipVersions.includes(ipVersion))
743
+ message = `'${child.id}' 只能承载在 ${carriers} 上,但下面最近的 IP 层是 IPv${ipVersion}`;
744
+ }
745
+ if (!message && codecModuleConstructor.DIRECTLY_AFTER_IP && parent.id !== 'ipv4' && parent.id !== 'ipv6') {
746
+ message = `'${child.id}' 必须紧跟在 IP 头后面,但前一层是 '${parent.id}'`;
747
+ }
748
+ if (!message)
749
+ continue;
750
+ const producer = this.#producersOf(parent.id).find((demuxProducer) => {
751
+ const value = parent.data ? parent.data[demuxProducer.field] : undefined;
752
+ return value !== undefined && value !== null;
753
+ });
754
+ issues.push({
755
+ index: i - 1,
756
+ parentId: parent.id,
757
+ childId: child.id,
758
+ field: producer ? producer.field : '',
759
+ actual: producer ? parent.data[producer.field] : '',
760
+ suggestion: null,
761
+ message: message,
762
+ kind: 'carrier'
669
763
  });
670
764
  }
671
- return issues;
765
+ return issues.sort((a, b) => a.index - b.index);
672
766
  }
673
767
  /**
674
768
  * Wireshark-style dissection: decode the packet with byte-range tracking on, then project each
@@ -57,6 +57,10 @@ export declare abstract class BaseHeader {
57
57
  static get HEURISTIC_FALLBACK(): boolean;
58
58
  /** Parent layer ids a content-heuristic header can follow (see the instance field heuristicParents). */
59
59
  static get HEURISTIC_PARENTS(): HeuristicParent[];
60
+ /** The IP versions this header runs over (see the instance field ipVersions). */
61
+ static get IP_VERSIONS(): number[];
62
+ /** Whether this header must directly follow an IP header (see the instance field directlyAfterIP). */
63
+ static get DIRECTLY_AFTER_IP(): boolean;
60
64
  /** Higher is tried first within a demux bucket and within the heuristic chain; ties keep registration order. */
61
65
  static get MATCH_PRIORITY(): number;
62
66
  static get PROTOCOL_SCHEMA(): ProtocolJSONSchema;
@@ -113,6 +117,19 @@ export declare abstract class BaseHeader {
113
117
  * for an entry {parent, discriminator}, with that parent field value the child needs.
114
118
  */
115
119
  readonly heuristicParents: HeuristicParent[];
120
+ /**
121
+ * Editor graph and checkConsistency() only (decode still routes by match()): the IP versions this
122
+ * header runs over, i.e. what the nearest IPv4 / IPv6 layer beneath it must be — 4 for ICMP, 6 for
123
+ * ICMPv6, OSPFv3 and the IPv6 Hop-by-Hop header. Several headers share one IP protocol number
124
+ * namespace (ipproto), so without this the menu would offer them under either IP version.
125
+ * Empty (the default): either version, or a header IP does not carry.
126
+ */
127
+ readonly ipVersions: number[];
128
+ /**
129
+ * Editor graph and checkConsistency() only: true for a header that must directly follow its IP
130
+ * header, not AH or an extension header (IPv6 Hop-by-Hop Options, RFC 8200 4.3).
131
+ */
132
+ readonly directlyAfterIP: boolean;
116
133
  /**
117
134
  * Encode/Decode error info objects
118
135
  */
@@ -76,6 +76,14 @@ class BaseHeader {
76
76
  static get HEURISTIC_PARENTS() {
77
77
  return this.CODEC_INSTANCE.heuristicParents;
78
78
  }
79
+ /** The IP versions this header runs over (see the instance field ipVersions). */
80
+ static get IP_VERSIONS() {
81
+ return this.CODEC_INSTANCE.ipVersions;
82
+ }
83
+ /** Whether this header must directly follow an IP header (see the instance field directlyAfterIP). */
84
+ static get DIRECTLY_AFTER_IP() {
85
+ return this.CODEC_INSTANCE.directlyAfterIP;
86
+ }
79
87
  /** Higher is tried first within a demux bucket and within the heuristic chain; ties keep registration order. */
80
88
  static get MATCH_PRIORITY() {
81
89
  return this.CODEC_INSTANCE.matchPriority;
@@ -213,6 +221,19 @@ class BaseHeader {
213
221
  * for an entry {parent, discriminator}, with that parent field value the child needs.
214
222
  */
215
223
  this.heuristicParents = [];
224
+ /**
225
+ * Editor graph and checkConsistency() only (decode still routes by match()): the IP versions this
226
+ * header runs over, i.e. what the nearest IPv4 / IPv6 layer beneath it must be — 4 for ICMP, 6 for
227
+ * ICMPv6, OSPFv3 and the IPv6 Hop-by-Hop header. Several headers share one IP protocol number
228
+ * namespace (ipproto), so without this the menu would offer them under either IP version.
229
+ * Empty (the default): either version, or a header IP does not carry.
230
+ */
231
+ this.ipVersions = [];
232
+ /**
233
+ * Editor graph and checkConsistency() only: true for a header that must directly follow its IP
234
+ * header, not AH or an extension header (IPv6 Hop-by-Hop Options, RFC 8200 4.3).
235
+ */
236
+ this.directlyAfterIP = false;
216
237
  /**
217
238
  * Encode/Decode error info objects
218
239
  */
@@ -9,6 +9,7 @@ export declare class ICMP extends BaseHeader {
9
9
  SCHEMA: ProtocolJSONSchema;
10
10
  id: string;
11
11
  readonly matchKeys: string[];
12
+ readonly ipVersions: number[];
12
13
  name: string;
13
14
  nickname: string;
14
15
  match(): boolean;
@@ -107,6 +107,8 @@ class ICMP extends BaseHeader_1.BaseHeader {
107
107
  };
108
108
  this.id = 'icmp';
109
109
  this.matchKeys = ['ipproto:1'];
110
+ //ICMP is for IPv4 (ICMPv6 is a separate protocol, 58).
111
+ this.ipVersions = [4];
110
112
  this.name = 'Internet Control Message Protocol';
111
113
  this.nickname = 'ICMP';
112
114
  }
@@ -144,7 +146,13 @@ class ICMP extends BaseHeader_1.BaseHeader {
144
146
  match() {
145
147
  if (!this.prevCodecModule)
146
148
  return false;
147
- return this.prevCodecModule.instance.protocol.getValue() === 0x01;
149
+ //Protocol 1 from the IPv4 header itself, or Next Header 1 from AH after an IPv4 header.
150
+ if (this.prevCodecModule.instance.protocol.getValue() === 0x01)
151
+ return true;
152
+ if (this.prevCodecModule.instance.nxt.getValue() !== 0x01)
153
+ return false;
154
+ const ip = this.nearestIPModule();
155
+ return !!ip && ip.id === 'ipv4';
148
156
  }
149
157
  }
150
158
  exports.ICMP = ICMP;
@@ -9,6 +9,7 @@ export declare class ICMPv6 extends BaseHeader {
9
9
  SCHEMA: ProtocolJSONSchema;
10
10
  id: string;
11
11
  readonly matchKeys: string[];
12
+ readonly ipVersions: number[];
12
13
  name: string;
13
14
  nickname: string;
14
15
  match(): boolean;
@@ -79,6 +79,7 @@ class ICMPv6 extends BaseHeader_1.BaseHeader {
79
79
  };
80
80
  this.id = 'icmpv6';
81
81
  this.matchKeys = ['ipproto:58'];
82
+ this.ipVersions = [6];
82
83
  this.name = 'Internet Control Message Protocol v6';
83
84
  this.nickname = 'ICMPv6';
84
85
  }
@@ -72,6 +72,8 @@ export declare class IPv6HopByHopOptions extends BaseHeader {
72
72
  SCHEMA: ProtocolJSONSchema;
73
73
  id: string;
74
74
  readonly matchKeys: string[];
75
+ readonly ipVersions: number[];
76
+ readonly directlyAfterIP: boolean;
75
77
  readonly demuxProducers: DemuxProducer[];
76
78
  name: string;
77
79
  nickname: string;
@@ -466,6 +466,9 @@ class IPv6HopByHopOptions extends BaseHeader_1.BaseHeader {
466
466
  };
467
467
  this.id = 'ipv6-hopopt';
468
468
  this.matchKeys = ['ipproto:0'];
469
+ //RFC 8200 4.3: the Hop-by-Hop Options header, when present, immediately follows the IPv6 header.
470
+ this.ipVersions = [6];
471
+ this.directlyAfterIP = true;
469
472
  //Extension header: it both consumes ipproto:0 and produces the next-header key for the layer after it.
470
473
  this.demuxProducers = [{ field: 'nxt', namespace: 'ipproto', kind: 'uint' }];
471
474
  this.name = 'IPv6 Hop-by-Hop Option';
@@ -42,24 +42,16 @@ class NHRP extends BaseHeader_1.BaseHeader {
42
42
  return (NHRP.#schemaCache ??= NHRP.#buildSchema());
43
43
  }
44
44
  /**
45
- * Bytes of NHRP the IP layer below says are available. IPv4 carries a total-length field, so the
46
- * NHRP payload is (total length - IP header length); IPv6 carries the payload length directly (plen).
47
- * Mirrors the OSPF/GRE pattern so the body decode and the match gate are bounded by the real on-wire
48
- * length rather than trusting the NHRP Packet Length field alone (which a malformed packet may
49
- * overstate). Returns 0 when neither is present.
45
+ * Bytes of NHRP the IP layer below carries. Decode cuts the packet view at the end the nearest IP
46
+ * layer's own length gives (BaseHeader.payloadEnd), so this is what remains of it — also behind AH
47
+ * or an IPv6 extension header, where the layer right below has no length of its own. The body decode
48
+ * and the match gate are bounded by it rather than by the NHRP Packet Length field alone (which a
49
+ * malformed packet may overstate).
50
50
  * @private
51
51
  */
52
52
  #available() {
53
- const prev = this.prevCodecModule;
54
- if (!prev)
55
- return 0;
56
- const ipv4TotalLength = prev.instance.length.getValue(0);
57
- if (ipv4TotalLength)
58
- return ipv4TotalLength - prev.length;
59
- const ipv6PayloadLength = prev.instance.plen.getValue(0);
60
- if (ipv6PayloadLength)
61
- return ipv6PayloadLength;
62
- return 0;
53
+ const available = this.packet.length - this.startPos;
54
+ return available < 0 ? 0 : available;
63
55
  }
64
56
  /**
65
57
  * Header-relative end offset of the NHRP body: the Packet Length field, clamped down to the bytes the
@@ -38,24 +38,15 @@ class OSPF extends BaseHeader_1.BaseHeader {
38
38
  this.demuxProducers = [];
39
39
  }
40
40
  /**
41
- * Bytes of OSPF the IP layer below says are available.
42
- * IPv4 carries a total-length field, so the OSPF payload is (total length - IP header length);
43
- * IPv6 carries the payload length directly (plen). Mirrors the GRE #available() pattern so the
44
- * body decode can be bounded by the real on-wire length rather than trusting the OSPF length
45
- * field alone (which a malformed packet may overstate). Returns 0 when neither is present.
41
+ * Bytes of OSPF the IP layer below carries. Decode cuts the packet view at the end the nearest IP
42
+ * layer's own length gives (BaseHeader.payloadEnd), so this is what remains of it — also behind AH
43
+ * or an IPv6 extension header, where the layer right below has no length of its own. The body decode
44
+ * is bounded by it rather than by the OSPF length field alone (which a malformed packet may overstate).
46
45
  * @private
47
46
  */
48
47
  #available() {
49
- const prev = this.prevCodecModule;
50
- if (!prev)
51
- return 0;
52
- const ipv4TotalLength = prev.instance.length.getValue(0);
53
- if (ipv4TotalLength)
54
- return ipv4TotalLength - prev.length;
55
- const ipv6PayloadLength = prev.instance.plen.getValue(0);
56
- if (ipv6PayloadLength)
57
- return ipv6PayloadLength;
58
- return 0;
48
+ const available = this.packet.length - this.startPos;
49
+ return available < 0 ? 0 : available;
59
50
  }
60
51
  /**
61
52
  * Header-relative end offset of the OSPF packet body: the OSPF length field, clamped down to the
@@ -30,6 +30,7 @@ export declare class OSPFv3 extends BaseHeader {
30
30
  get SCHEMA(): ProtocolJSONSchema;
31
31
  readonly id: string;
32
32
  readonly matchKeys: string[];
33
+ readonly ipVersions: number[];
33
34
  readonly name: string;
34
35
  readonly nickname: string;
35
36
  readonly demuxProducers: DemuxProducer[];
@@ -38,6 +38,8 @@ class OSPFv3 extends BaseHeader_1.BaseHeader {
38
38
  super(...arguments);
39
39
  this.id = 'ospfv3';
40
40
  this.matchKeys = ['ipproto:89'];
41
+ //RFC 5340 runs over IPv6; OSPFv3 over IPv4 (RFC 7949) is not supported.
42
+ this.ipVersions = [6];
41
43
  this.name = 'Open Shortest Path First version 3';
42
44
  this.nickname = 'OSPFv3';
43
45
  //A leaf header (LSA bodies are kept as rawBody).
@@ -25,11 +25,15 @@ export type NextLayer = {
25
25
  } | null;
26
26
  };
27
27
  /**
28
- * A parent layer whose discriminator field does not point at the child that actually follows it
29
- * (e.g. eth.etherType=0x86dd "IPv6" but the next layer is IPv4). Surfaced by the editor as a warning;
30
- * `suggestion` is the {field,value} that would align the parent with the actual child, or null when
31
- * the child is not reachable from that parent at all. Never blocks encoding — a lying packet is a
32
- * valid crafted packet.
28
+ * A parent / child pair that will not decode back as given. Surfaced by the editor as a warning; never
29
+ * blocks encoding — a lying packet is a valid crafted packet. `kind` says why:
30
+ * - 'discriminator': the parent's discriminator field does not point at the child that follows it (e.g.
31
+ * eth.etherType=0x86dd "IPv6" but the next layer is IPv4). `suggestion` is the {field,value} that would
32
+ * align the parent with the child, or null when the child is not reachable from that parent at all.
33
+ * - 'carrier': the child runs over one IP version only and the nearest IP layer beneath is the other one
34
+ * or missing (OSPFv3 over IPv4), or it must directly follow its IP header and does not (IPv6 Hop-by-Hop
35
+ * after AH). `field` / `actual` are the parent's discriminator as given ('' when it has none) and
36
+ * `suggestion` is null: no parent value fixes it.
33
37
  */
34
38
  export type ConsistencyIssue = {
35
39
  index: number;
@@ -42,4 +46,5 @@ export type ConsistencyIssue = {
42
46
  value: string | number;
43
47
  } | null;
44
48
  message: string;
49
+ kind?: 'discriminator' | 'carrier';
45
50
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@netkitty/codec",
3
- "version": "2.2.0",
3
+ "version": "2.3.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": "698bce9a3e8414a2a7ef2af687c4feff0aa1a25c"
141
+ "gitHead": "92e27a6ef8134f4b8437adbcc17c8705ead3b5d7"
142
142
  }