@first-ch/tools-mcp 0.28.0 → 0.29.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/README.md +3 -1
- package/cidr.mjs +826 -0
- package/package.json +13 -3
- package/server.mjs +38 -0
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @first-ch/tools-mcp
|
|
2
2
|
|
|
3
|
-
MCP server exposing [First CH Tools](https://tools.first-ch.com)' free web-tool logic — WCAG contrast, JP character/X-weight counting, WebP conversion, JSON-LD generation, llms.txt generation, encoding/line-ending conversion, Marp Markdown→slide rendering, Japanese/English test-data generation, text/code diffing, cron-expression explanation, Base64/data-URI encoding, URL query-parameter editing, HTML entity escaping/unescaping, JSON⇄YAML conversion, px ⇄ rem/em unit conversion, colour-code conversion with alpha compositing, MD5/SHA-1/SHA-256/SHA-384/SHA-512 hashing, JWT decoding with expiry and signature checks, User-Agent parsing with device/bot detection, bulk UUID v4 / ULID generation, aspect-ratio calculation with responsive sizing, case conversion between camelCase, snake_case and kebab-case,
|
|
3
|
+
MCP server exposing [First CH Tools](https://tools.first-ch.com)' free web-tool logic — WCAG contrast, JP character/X-weight counting, WebP conversion, JSON-LD generation, llms.txt generation, encoding/line-ending conversion, Marp Markdown→slide rendering, Japanese/English test-data generation, text/code diffing, cron-expression explanation, Base64/data-URI encoding, URL query-parameter editing, HTML entity escaping/unescaping, JSON⇄YAML conversion, px ⇄ rem/em unit conversion, colour-code conversion with alpha compositing, MD5/SHA-1/SHA-256/SHA-384/SHA-512 hashing, JWT decoding with expiry and signature checks, User-Agent parsing with device/bot detection, bulk UUID v4 / ULID generation, aspect-ratio calculation with responsive sizing, case conversion between camelCase, snake_case and kebab-case, CSV/TSV ⇄ JSON conversion, and IP/CIDR calculation with subnet splitting and IP-range reduction — to AI agents such as Claude Code.
|
|
4
4
|
|
|
5
5
|
日本語版は [後半セクション](#日本語) を参照してください。
|
|
6
6
|
|
|
@@ -74,6 +74,7 @@ This server is also registered in the [MCP Registry](https://registry.modelconte
|
|
|
74
74
|
| `case_convert` | Converts identifiers between eleven cases — camelCase, PascalCase, snake_case, CONSTANT_CASE, kebab-case, Train-Case, dot.case, Title Case, Sentence case, lower case and UPPER CASE — the same logic as the browser tool at tools.first-ch.com/case/. Built for the mechanical jobs at the boundary between layers: renaming variables in bulk, moving between `snake_case` database columns and `camelCase` JSON keys, tidying CSV headers. `scope` sets the unit of work: `lines` (the default, one item per line), `items` (every comma or tab separated field of a line, for CSV header rows) or `whole`. **Leading and trailing spaces, indentation, line endings (LF/CRLF) and the separators are preserved**, so only the names change. A run of capitals is broken only before a capital followed by a lower-case letter (`XMLHttpRequest` → `XML` / `Http` / `Request`), and digits stay attached to the word before them (`sha256Hash` → `sha256` / `Hash`; `splitDigits` splits them). Acronyms fold to `parseXmlData` by default and stay capitalised with `keepAcronyms`, except the first word of a camelCase name, which is always lower-cased (`URLParser` → `urlParser`). Characters with no letter case (Japanese, for example) pass through rather than being transliterated. `notes` reports **names that collide after conversion** (`first name` and `first_name` both become `first_name`, which is how a column silently disappears on import), results starting with a digit that cannot be identifiers, and items containing acronyms; `items[].detected` names the case each input was written in. `allFormats` expands every item into all eleven cases, `listFormats` returns just the list of cases with what each is used for | `text?` or `path?`, `outputPath?`, `format?` (`camel` default), `scope?` (`lines` default / `items` / `whole`), `splitDigits?`, `keepAcronyms?`, `allFormats?`, `listFormats?`, `lang?` (`ja` default / `en`) |
|
|
75
75
|
| `csv_convert` | Converts CSV/TSV into a JSON array and back — the same logic as the browser tool at tools.first-ch.com/csv-json/. For moving data you already have between a spreadsheet and an API: turning an exported table into JSON a request body can carry, or an API response into something Excel opens. With `direction` omitted it guesses `json2csv` when the input starts with `[` or `{` and `csv2json` otherwise. The delimiter is detected by looking at the first 20 lines for the character that appears the same number of times on every line, and can be pinned with `delimiter`. **Column names such as `stock.qty` are read and written as nested objects, and `tags.0` / `tags.1` (`tags[0]` means the same) become an array** — the reverse direction flattens by the same rule, so a round trip through CSV restores the original structure (`nest: false` writes nested values into a single cell as JSON text). **Type inference is decided by round trip — a value becomes a number only when converting it back to text is character-for-character identical** — so `0123`, `+1`, `1.50` and integers beyond 2^53 (`12345678901234567890`) stay strings and postcodes, phone numbers, invoice numbers and version strings survive. Reading follows RFC 4180: quoted cells, `""` escapes, line breaks inside cells, CRLF and a BOM are all handled, and the output side offers `bom` and `newline` for Excel. On the JSON side it accepts an array, a single object, an object wrapping an array such as `{"data":[…]}`, and JSON Lines. **A JSON syntax error comes back as an `ok: false` result with a line, a column and an excerpt rather than an exception**, so the reply itself says where to fix it. `notes` also reports rows whose column count does not match the header, duplicate header names (kept as `name_2`), empty headers (named `column4`), values that would lose digits, cells starting with `=`, `+`, `-` or `@` that a spreadsheet may execute as a formula (CSV injection), and objects with a different set of keys | `text?` or `path?`, `outputPath?`, `direction?` (`auto` default / `csv2json` / `json2csv`), `delimiter?` (`auto` default / `comma` / `tab` / `semicolon` / `pipe`), `header?`, `nest?`, `types?`, `trim?`, `emptyNull?`, `indent?` (`2` default / 0–8 / `tab`), `newline?` (`lf` default / `crlf`), `quoteAll?`, `bom?`, `lang?` (`ja` default / `en`) |
|
|
76
76
|
| `zenkaku_convert` | Converts letters and digits, katakana, symbols and spaces between their full-width and half-width forms **with a direction chosen per kind**, and cleans up the whitespace in the same pass — the same logic as the browser tool at tools.first-ch.com/zenkaku/. For normalising Japanese copy supplied by a client, cleaning a file before an import, and tidying form input. Each of `alnum` / `kana` / `symbol` / `space` takes `keep`, `han` (half-width) or `zen` (full-width); the defaults are the form most Japanese copy is set in — letters, digits, symbols and spaces half-width, katakana full-width (the same as `preset: 'ja'`). `preset` offers `ja`, `csv` (`ja` plus the whitespace and invisible-character cleanup), `han` and `zen`, and any per-kind option overrides it. **Half-width katakana is not one character per glyph**, so converting to full-width composes a following voiced mark (`ガ` → `ガ`, `パ` → `パ`, `ヴ` → `ヴ`) and converting the other way splits it into two. Japanese punctuation, brackets, the middle dot and the prolonged sound mark (`。 、 「 」 ・ ー`) live inside the half-width katakana block (U+FF61–U+FF9F) and are **treated as katakana** (`kana: 'han'` turns `「テスト」。` into `「テスト」。`; use `keep` to leave the punctuation full-width). Spaces cover U+3000 ⇄ U+0020 and fold NBSP and the Latin space family to the half-width side. The cleanup is `collapseSpaces` (a run of spaces becomes its first character), `trimLines`, `blankLines` (`keep` / `collapse` / `remove`), `removeInvisible` (zero-width, BOM, control codes) and `composeMarks` (NFC, for copy that writes `ガ` as `カ` plus a combining U+3099). **Line endings (LF/CRLF), tabs, hiragana and kanji are never rewritten.** `notes` reports what is left — half-width katakana, ideographic spaces, invisible characters, combining marks — plus the wave dash `〜` (U+301C) versus the fullwidth tilde `~` (U+FF5E) and platform-dependent characters (`① ㈱ Ⅲ`), which are **reported and never rewritten** because which way they should go depends on the destination. **This is deliberately not NFKC**: `①` never becomes `1`, and only the kinds you selected are touched. `inspect: true` converts nothing and returns just the audit | `text?` or `path?`, `outputPath?`, `preset?` (`ja` / `csv` / `han` / `zen`), `alnum?`, `kana?`, `symbol?`, `space?` (each `keep` / `han` / `zen`), `collapseSpaces?`, `trimLines?`, `blankLines?` (`keep` default / `collapse` / `remove`), `removeInvisible?`, `composeMarks?`, `inspect?`, `lang?` (`ja` default / `en`) |
|
|
77
|
+
| `cidr_calc` | Turns CIDR notation, a subnet mask, an ACL wildcard mask or a bare address into the network address, broadcast address, usable host range, address and host counts, reverse DNS zone and a binary breakdown — the same logic as the browser tool at tools.first-ch.com/cidr/. For subnet maths while writing server configs, firewall rules and Basic-auth allow lists. **IPv4 and IPv6 both work**: `::` compression, a trailing IPv4 form (`::ffff:192.168.0.1`), `[...]` brackets and a `%zone` suffix are parsed, and output follows RFC 5952. `192.168.1.5 255.255.255.0` and `192.168.1.5/0.0.0.255` (the ACL convention) are accepted in the same field. **The exceptions in host counting are built in**: a `/31` has two usable addresses for point-to-point links (RFC 3021), a `/32` is one host, and IPv6 has no broadcast address. When host bits are set in the address you pass, `notes` returns the block it actually belongs to — the form that belongs in a config file. **Octets with a leading zero (`192.168.001.1`) are refused**, because some libraries read them as octal and the same text then means a different address. The address type is matched against the main IANA special-purpose blocks (private, CGNAT, loopback, link-local, documentation, multicast, ULA and more) and a network that extends beyond its reserved range is flagged. `split` lists the equal subnets of a new prefix length, `contains` tests addresses for membership, and `range` reduces ranges such as `10.0.0.5 - 10.0.0.200` (mixed with CIDR blocks and single addresses, one per line or `;`-separated) to **the fewest blocks that cover them exactly**, merging overlaps and adjacencies first. All arithmetic is BigInt | `cidr?` and/or `range?`, `split?` (prefix length), `contains?` (string[]), `limit?` (1-4096, default 256), `lang?` (`ja` default / `en`) |
|
|
77
78
|
|
|
78
79
|
See [`server.mjs`](./server.mjs) for the exact Zod input schemas.
|
|
79
80
|
|
|
@@ -190,6 +191,7 @@ claude mcp add firstch-tools -- npx -y @first-ch/tools-mcp
|
|
|
190
191
|
| `case_convert` | 識別子を camelCase / PascalCase / snake_case / CONSTANT_CASE / kebab-case・Train-Case・dot.case・Title Case・Sentence case・lower case・UPPER CASE の11形式へ相互変換する。tools.first-ch.com/case/ と同一ロジック。変数名の一括リネーム、`snake_case` のDB列名と `camelCase` のJSONキーの読み替え、CSVヘッダーの整形といった、層の境目で発生する定型処理のための道具。`scope` で処理の単位を選ぶ: `lines`(既定=1行1件)/ `items`(行内のカンマ・タブ区切りで1件ずつ=CSVヘッダー)/ `whole`(全体で1件)。**前後の空白・インデント・改行コード(LF/CRLF)・区切り記号はそのまま残す**ので、名前だけが置き換わる。大文字の連なりは直後に「大文字+小文字」が続くときだけ手前で切り(`XMLHttpRequest` → `XML` / `Http` / `Request`)、数字は既定で直前の語へ付く(`sha256Hash` → `sha256` / `Hash`。`splitDigits` で分けられる)。頭字語は既定で `parseXmlData` へ畳み、`keepAcronyms` で `parseXMLData` のまま残す(camelCase の先頭語はどちらでも小文字=`URLParser` → `urlParser`)。大文字小文字を持たない文字(日本語など)はそのまま出力し、ローマ字化はしない。`notes` では**変換後に同じ名前へ衝突する項目**(`first name` と `first_name` はどちらも `first_name`=インポート時に片方が黙って消える事故の元)・数字で始まって識別子にできない結果・頭字語を含む項目を指摘し、`items[].detected` では各入力がどの形式で書かれていたかを返す。`allFormats` で各項目を11形式すべてへ展開、`listFormats` で形式の一覧と使いどころだけを返す | `text?` または `path?`、`outputPath?`、`format?`(既定 `camel`)、`scope?`(既定 `lines` / `items` / `whole`)、`splitDigits?`、`keepAcronyms?`、`allFormats?`、`listFormats?`、`lang?`(既定 `ja` / `en`) |
|
|
191
192
|
| `csv_convert` | CSV/TSVとJSON配列を相互変換する。tools.first-ch.com/csv-json/ と同一ロジック。表計算ソフトから書き出した表をAPIに渡せるJSONにする、逆にAPIの応答をExcelで開ける表にする、という**手持ちのデータを形式だけ移し替える**ための道具。`direction` を省くと、入力の先頭が `[` か `{` なら `json2csv`、そうでなければ `csv2json` と推定する。区切り文字は先頭20行で「どの記号が各行に同じ個数だけ現れるか」を見て自動判定し、`delimiter` で固定もできる。**`stock.qty` のような列名は入れ子のオブジェクトとして読み書きし、`tags.0` / `tags.1`(`tags[0]` も同義)は配列になる**。逆向きも同じ規則で平らにするので、CSVへ出してJSONへ戻すと元の構造に復元される(`nest: false` なら入れ子はJSONの文字列としてセル1つに入る)。**型の読み替えは「一度数値にして文字列へ戻したとき元の表記と1文字も違わないか」で決める**ため、`0123`・`+1`・`1.50`・2の53乗を超えるID(`12345678901234567890`)は文字列のまま残り、郵便番号・電話番号・伝票番号・バージョン番号が壊れない。読み取りは RFC 4180 準拠で、引用符・`""` エスケープ・セル内改行・CRLF・BOM に対応する(書き出し側は Excel 向けに `bom` と `newline` を選べる)。JSONは配列・単体のオブジェクト・`{"data":[…]}` のように配列を包んだもの・1行1件のJSON Lines を受け取れる。**JSONの構文エラーは例外にせず、行・桁と前後の抜粋を持つ `ok: false` の結果として返す**ので、応答そのものが直しどころになる。`notes` では、列数が見出しと合わない行・重複した列名(`name_2` として残す)・空の見出し(`column4` を割り当てる)・桁落ちする数値・`=` `+` `-` `@` で始まり表計算ソフトが数式として実行しうるセル(CSVインジェクション)・キーの並びが揃わないオブジェクトを指摘する | `text?` または `path?`、`outputPath?`、`direction?`(既定 `auto` / `csv2json` / `json2csv`)、`delimiter?`(既定 `auto` / `comma` / `tab` / `semicolon` / `pipe`)、`header?`、`nest?`、`types?`、`trim?`、`emptyNull?`、`indent?`(既定 `2` / 0〜8 / `tab`)、`newline?`(既定 `lf` / `crlf`)、`quoteAll?`、`bom?`、`lang?`(既定 `ja` / `en`) |
|
|
192
193
|
| `zenkaku_convert` | 英数字・カタカナ・記号・スペースを**文字種ごとに向きを選んで**全角⇄半角へ変換し、あわせて空白まわりを掃除する。tools.first-ch.com/zenkaku/ と同一ロジック。顧客支給原稿の表記統一、CSV取り込み前の正規化、フォーム入力値の掃除のための道具。`alnum` / `kana` / `symbol` / `space` にそれぞれ `keep`(そのまま)/ `han`(半角へ)/ `zen`(全角へ)を渡す。既定は日本語の原稿で最も多い「英数字・記号・スペースは半角、カタカナは全角」(`preset: 'ja'` と同じ)。`preset` は `ja` / `csv`(`ja` に空白の掃除と見えない文字の除去を足したもの)/ `han` / `zen` で、個別指定が優先される。**半角カタカナは1文字ではない**ため、半角→全角では次が濁点なら1文字へ合成し(`ガ`→`ガ`・`パ`→`パ`・`ヴ`→`ヴ`)、全角→半角では2文字へ分解する。句読点・カギ括弧・中黒・長音(`。 、 「 」 ・ ー`)は半角カタカナのブロック(U+FF61〜U+FF9F)に同居しているので**カタカナと同じ文字種**として扱う(`kana: 'han'` は `「テスト」。` を `「テスト」。` にする。句読点を全角で残すなら `keep`)。スペースは U+3000 ⇄ U+0020 に加え、NBSP や欧文の各種スペースも半角側へ寄せる。掃除は `collapseSpaces`(連続する空白を先頭の1文字へ)・`trimLines`・`blankLines`(`keep` / `collapse` / `remove`)・`removeInvisible`(ゼロ幅・BOM・制御文字)・`composeMarks`(NFC。`ガ` が `カ`+結合文字 U+3099 で書かれた原稿向け)。**改行コード(LF/CRLF)とタブ、ひらがな・漢字は書き換えない。** `notes` では出力に残った半角カナ・全角スペース・見えない文字・結合文字の濁点に加え、波ダッシュ `〜`(U+301C)/全角チルダ `~`(U+FF5E)と環境依存文字(`① ㈱ Ⅲ`)を指摘する(後の2つはどちらへ寄せるべきかが届け先で変わるため**指摘のみで自動変換しない**)。**NFKC正規化とは別物**で、`①` が `1` になることはなく、選んだ文字種しか触らない。`inspect: true` なら変換せず点検結果だけを返す | `text?` または `path?`、`outputPath?`、`preset?`(`ja` / `csv` / `han` / `zen`)、`alnum?`、`kana?`、`symbol?`、`space?`(いずれも `keep` / `han` / `zen`)、`collapseSpaces?`、`trimLines?`、`blankLines?`(既定 `keep` / `collapse` / `remove`)、`removeInvisible?`、`composeMarks?`、`inspect?`、`lang?`(既定 `ja` / `en`) |
|
|
194
|
+
| `cidr_calc` | CIDR表記・サブネットマスク・ACLのワイルドカードマスク・単体のIPから、ネットワークアドレス・ブロードキャスト・使えるホストの範囲・アドレス数とホスト数・逆引きゾーン・2進表記を返す。tools.first-ch.com/cidr/ と同一ロジック。サーバー設定・ファイアウォール・Basic認証の許可リストを書くときのサブネット計算のための道具。**IPv4とIPv6の両対応**で、`::` の省略・末尾のIPv4表記(`::ffff:192.168.0.1`)・`[...]` 囲み・`%zone` を読み、出力は RFC 5952 に従う。`192.168.1.5 255.255.255.0` や `192.168.1.5/0.0.0.255`(ACLの書き方)も同じ入力欄で受け取る。**ホスト数の例外も織り込む**: `/31` は点対点リンクとして2アドレスとも使え(RFC 3021)、`/32` は1台、IPv6にブロードキャストは無い。渡したアドレスのホスト部にビットが立っていれば、`notes` で**設定ファイルに書くべき本来のCIDR**を返す。**先頭に0の付いたオクテット(`192.168.001.1`)は受け取らない**(8進数として読む実装があり、同じ表記が別のアドレスになるため)。アドレス帯は IANA の主要な予約ブロック(プライベート・CGNAT・ループバック・リンクローカル・文書用・マルチキャスト・ULA ほか)と照合して種別を返し、ネットワークがその帯からはみ出す場合も指摘する。`split` はそのプレフィックス長で均等に割った一覧、`contains` は各アドレスがそのネットワークに入るかの判定、`range` は `10.0.0.5 - 10.0.0.200` のような範囲(CIDR・単体IPと混ぜて1行1件か `;` 区切り)を**重なりと隣接をまとめたうえで過不足なく覆う最小個数のCIDR**へ逆算する。計算はすべてBigInt | `cidr?` と/または `range?`、`split?`(プレフィックス長)、`contains?`(文字列の配列)、`limit?`(1〜4096・既定 256)、`lang?`(既定 `ja` / `en`) |
|
|
193
195
|
|
|
194
196
|
正確な入力スキーマ(Zod定義)は [`server.mjs`](./server.mjs) を参照してください。
|
|
195
197
|
|
package/cidr.mjs
ADDED
|
@@ -0,0 +1,826 @@
|
|
|
1
|
+
/* IPアドレス・CIDR計算(cidr_calc)
|
|
2
|
+
* 計算コア(cidrParse / cidrCalc / cidrSplit / cidrSummarize ほか)は
|
|
3
|
+
* FirstCHTools の site/cidr/app.js と同一
|
|
4
|
+
* (2箇所ルール: site側が正本・片方を直したらもう片方も同じ内容で反映する)。
|
|
5
|
+
* 両ファイルからコアの開始/終了コメントに挟まれた範囲を sed で切り出し
|
|
6
|
+
* (site側は字下げ2文字を落とす・こちらは行頭の export を落とす)、
|
|
7
|
+
* diff が空になることで同期を機械的に確認できる。
|
|
8
|
+
*
|
|
9
|
+
* 使っているのは BigInt と String だけなので、ブラウザ版のコードをそのまま持ってこられる。
|
|
10
|
+
* 完全ローカル処理・ネットワーク送信なし。 */
|
|
11
|
+
|
|
12
|
+
/* ==================== ここから計算コア(site / MCP で同一) ==================== */
|
|
13
|
+
|
|
14
|
+
export class CidrError extends Error {
|
|
15
|
+
constructor(code, info) {
|
|
16
|
+
super(code);
|
|
17
|
+
this.name = 'CidrError';
|
|
18
|
+
this.code = code;
|
|
19
|
+
this.info = info || {};
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export const CIDR_BITS = { 4: 32, 6: 128 };
|
|
24
|
+
|
|
25
|
+
/** そのバージョンの全ビットが1の値(IPv4なら255.255.255.255) */
|
|
26
|
+
export function cidrFull(version) {
|
|
27
|
+
return (1n << BigInt(CIDR_BITS[version])) - 1n;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** プレフィックス長 → ネットマスクの数値 */
|
|
31
|
+
export function cidrMask(prefix, version) {
|
|
32
|
+
const bits = CIDR_BITS[version];
|
|
33
|
+
if (prefix <= 0) return 0n;
|
|
34
|
+
return ((1n << BigInt(prefix)) - 1n) << BigInt(bits - prefix);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** 左から1が連続しているか(ネットマスクとして成立するか)。成立すればプレフィックス長・しなければ -1 */
|
|
38
|
+
export function cidrMaskPrefix(value, version) {
|
|
39
|
+
const bits = CIDR_BITS[version];
|
|
40
|
+
let seenZero = false;
|
|
41
|
+
let prefix = 0;
|
|
42
|
+
for (let i = bits - 1; i >= 0; i--) {
|
|
43
|
+
if (((value >> BigInt(i)) & 1n) === 1n) {
|
|
44
|
+
if (seenZero) return -1;
|
|
45
|
+
prefix++;
|
|
46
|
+
} else {
|
|
47
|
+
seenZero = true;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return prefix;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** ドット10進のIPv4を数値へ。IPv4の形をしていなければ null(形は合っていて値が不正なら例外) */
|
|
54
|
+
export function cidrParseIpv4(str) {
|
|
55
|
+
const s = String(str).trim();
|
|
56
|
+
if (!/^\d{1,3}(\.\d{1,3}){3}$/.test(s)) return null;
|
|
57
|
+
let v = 0n;
|
|
58
|
+
for (const part of s.split('.')) {
|
|
59
|
+
// 先頭の0は 8進数と解釈する実装(inet_aton 系)があり、同じ表記で別のアドレスになるため受け取らない
|
|
60
|
+
if (part.length > 1 && part.charAt(0) === '0') throw new CidrError('LEADING_ZERO', { text: s });
|
|
61
|
+
const n = Number(part);
|
|
62
|
+
if (n > 255) throw new CidrError('OCTET_RANGE', { text: s, octet: part });
|
|
63
|
+
v = (v << 8n) | BigInt(n);
|
|
64
|
+
}
|
|
65
|
+
return v;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** IPv6(:: の省略・末尾のIPv4表記・[] 囲み・%zone 付き)を数値へ。形が違えば null */
|
|
69
|
+
export function cidrParseIpv6(str) {
|
|
70
|
+
let s = String(str).trim();
|
|
71
|
+
if (s.charAt(0) === '[' && s.charAt(s.length - 1) === ']') s = s.slice(1, -1);
|
|
72
|
+
let zone = '';
|
|
73
|
+
const zi = s.indexOf('%');
|
|
74
|
+
if (zi !== -1) {
|
|
75
|
+
zone = s.slice(zi + 1);
|
|
76
|
+
s = s.slice(0, zi);
|
|
77
|
+
}
|
|
78
|
+
if (s.indexOf(':') === -1) return null;
|
|
79
|
+
if (!/^[0-9a-fA-F:.]+$/.test(s)) return null;
|
|
80
|
+
// ::ffff:192.168.0.1 のように末尾がIPv4表記なら、16進の2グループへ置き換えてから読む
|
|
81
|
+
if (s.indexOf('.') !== -1) {
|
|
82
|
+
const di = s.lastIndexOf(':');
|
|
83
|
+
const v4 = cidrParseIpv4(s.slice(di + 1));
|
|
84
|
+
if (v4 === null) return null;
|
|
85
|
+
s = s.slice(0, di + 1) + (v4 >> 16n).toString(16) + ':' + (v4 & 0xffffn).toString(16);
|
|
86
|
+
}
|
|
87
|
+
const halves = s.split('::');
|
|
88
|
+
if (halves.length > 2) return null;
|
|
89
|
+
const head = halves[0] === '' ? [] : halves[0].split(':');
|
|
90
|
+
const tail = halves.length === 2 ? (halves[1] === '' ? [] : halves[1].split(':')) : [];
|
|
91
|
+
let groups;
|
|
92
|
+
if (halves.length === 1) {
|
|
93
|
+
if (head.length !== 8) return null;
|
|
94
|
+
groups = head;
|
|
95
|
+
} else {
|
|
96
|
+
// :: は最低1グループを表すので、前後を足して7グループまで
|
|
97
|
+
if (head.length + tail.length > 7) return null;
|
|
98
|
+
groups = head.concat(new Array(8 - head.length - tail.length).fill('0'), tail);
|
|
99
|
+
}
|
|
100
|
+
let v = 0n;
|
|
101
|
+
for (const g of groups) {
|
|
102
|
+
if (!/^[0-9a-fA-F]{1,4}$/.test(g)) return null;
|
|
103
|
+
v = (v << 16n) | BigInt(parseInt(g, 16));
|
|
104
|
+
}
|
|
105
|
+
return { value: v, zone: zone };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** IPアドレス1つを読む。{ version, value, zone } */
|
|
109
|
+
export function cidrParseIp(str) {
|
|
110
|
+
const s = String(str == null ? '' : str).trim();
|
|
111
|
+
if (s === '') throw new CidrError('EMPTY', {});
|
|
112
|
+
if (s.indexOf(':') !== -1) {
|
|
113
|
+
const r = cidrParseIpv6(s);
|
|
114
|
+
if (!r) throw new CidrError('BAD_IP', { text: s });
|
|
115
|
+
return { version: 6, value: r.value, zone: r.zone };
|
|
116
|
+
}
|
|
117
|
+
const v4 = cidrParseIpv4(s);
|
|
118
|
+
if (v4 === null) throw new CidrError('BAD_IP', { text: s });
|
|
119
|
+
return { version: 4, value: v4, zone: '' };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** 数値 → 表記。IPv6は RFC 5952(小文字・最長の0連続だけを :: に畳む) */
|
|
123
|
+
export function cidrFormatIp(value, version) {
|
|
124
|
+
if (version === 4) {
|
|
125
|
+
return [24n, 16n, 8n, 0n].map((sh) => ((value >> sh) & 255n).toString()).join('.');
|
|
126
|
+
}
|
|
127
|
+
const groups = [];
|
|
128
|
+
for (let i = 7; i >= 0; i--) groups.push(Number((value >> BigInt(i * 16)) & 0xffffn));
|
|
129
|
+
let bestStart = -1;
|
|
130
|
+
let bestLen = 0;
|
|
131
|
+
let curStart = -1;
|
|
132
|
+
let curLen = 0;
|
|
133
|
+
for (let i = 0; i < 8; i++) {
|
|
134
|
+
if (groups[i] === 0) {
|
|
135
|
+
if (curStart === -1) {
|
|
136
|
+
curStart = i;
|
|
137
|
+
curLen = 0;
|
|
138
|
+
}
|
|
139
|
+
curLen++;
|
|
140
|
+
// 同じ長さなら左を採る(> で比較しているので最初の並びが残る)
|
|
141
|
+
if (curLen > bestLen) {
|
|
142
|
+
bestLen = curLen;
|
|
143
|
+
bestStart = curStart;
|
|
144
|
+
}
|
|
145
|
+
} else {
|
|
146
|
+
curStart = -1;
|
|
147
|
+
curLen = 0;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
const hex = groups.map((g) => g.toString(16));
|
|
151
|
+
if (bestLen < 2) return hex.join(':');
|
|
152
|
+
return hex.slice(0, bestStart).join(':') + '::' + hex.slice(bestStart + bestLen).join(':');
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** 省略しない表記(IPv6は 4桁×8グループ) */
|
|
156
|
+
export function cidrExpandIp(value, version) {
|
|
157
|
+
if (version === 4) return cidrFormatIp(value, version);
|
|
158
|
+
const groups = [];
|
|
159
|
+
for (let i = 7; i >= 0; i--) {
|
|
160
|
+
groups.push(('000' + Number((value >> BigInt(i * 16)) & 0xffffn).toString(16)).slice(-4));
|
|
161
|
+
}
|
|
162
|
+
return groups.join(':');
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** 「192.168.1.0/24」「10.0.0.1 255.0.0.0」「192.168.1.5」などを読む */
|
|
166
|
+
export function cidrParse(input) {
|
|
167
|
+
const raw = String(input == null ? '' : input).trim();
|
|
168
|
+
if (raw === '') throw new CidrError('EMPTY', {});
|
|
169
|
+
const s = raw.replace(/\s*\/\s*/, '/');
|
|
170
|
+
let addrPart = s;
|
|
171
|
+
let maskPart = '';
|
|
172
|
+
const slash = s.indexOf('/');
|
|
173
|
+
if (slash !== -1) {
|
|
174
|
+
addrPart = s.slice(0, slash).trim();
|
|
175
|
+
maskPart = s.slice(slash + 1).trim();
|
|
176
|
+
if (maskPart === '') throw new CidrError('NO_PREFIX', { text: raw });
|
|
177
|
+
} else {
|
|
178
|
+
const two = s.match(/^(\S+)\s+(\S+)$/);
|
|
179
|
+
if (two) {
|
|
180
|
+
addrPart = two[1];
|
|
181
|
+
maskPart = two[2];
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
const ip = cidrParseIp(addrPart);
|
|
185
|
+
const bits = CIDR_BITS[ip.version];
|
|
186
|
+
let prefix = bits;
|
|
187
|
+
let hadPrefix = false;
|
|
188
|
+
let maskKind = 'prefix';
|
|
189
|
+
if (maskPart !== '') {
|
|
190
|
+
hadPrefix = true;
|
|
191
|
+
if (/^\d+$/.test(maskPart)) {
|
|
192
|
+
prefix = Number(maskPart);
|
|
193
|
+
if (prefix > bits) throw new CidrError('BAD_PREFIX', { text: maskPart, max: bits, version: ip.version });
|
|
194
|
+
} else {
|
|
195
|
+
const mv = cidrParseIp(maskPart);
|
|
196
|
+
if (mv.version !== ip.version) throw new CidrError('MASK_VERSION', { text: maskPart });
|
|
197
|
+
const asMask = cidrMaskPrefix(mv.value, ip.version);
|
|
198
|
+
if (asMask >= 0) {
|
|
199
|
+
prefix = asMask;
|
|
200
|
+
maskKind = 'netmask';
|
|
201
|
+
} else {
|
|
202
|
+
// 0.0.0.255 のようなワイルドカードマスク(ACLでよく使う)も受け取る
|
|
203
|
+
const asWild = cidrMaskPrefix(~mv.value & cidrFull(ip.version), ip.version);
|
|
204
|
+
if (asWild < 0) throw new CidrError('BAD_MASK', { text: maskPart });
|
|
205
|
+
prefix = asWild;
|
|
206
|
+
maskKind = 'wildcard';
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
return {
|
|
211
|
+
version: ip.version,
|
|
212
|
+
address: ip.value,
|
|
213
|
+
prefix: prefix,
|
|
214
|
+
hadPrefix: hadPrefix,
|
|
215
|
+
maskKind: maskKind,
|
|
216
|
+
zone: ip.zone,
|
|
217
|
+
input: raw,
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/* 特別な用途に予約されたアドレス帯(IANA の Special-Purpose Address Registry から主要なものだけ)。
|
|
222
|
+
表示用の文言は site / MCP がそれぞれ持ち、ここではキーだけを返す。 */
|
|
223
|
+
export const CIDR_SPECIAL_SRC = [
|
|
224
|
+
['0.0.0.0/8', 'thisnet'],
|
|
225
|
+
['10.0.0.0/8', 'private'],
|
|
226
|
+
['100.64.0.0/10', 'cgnat'],
|
|
227
|
+
['127.0.0.0/8', 'loopback'],
|
|
228
|
+
['169.254.0.0/16', 'linklocal'],
|
|
229
|
+
['172.16.0.0/12', 'private'],
|
|
230
|
+
['192.0.0.0/24', 'ietf'],
|
|
231
|
+
['192.0.2.0/24', 'doc'],
|
|
232
|
+
['192.88.99.0/24', 'relay6to4'],
|
|
233
|
+
['192.168.0.0/16', 'private'],
|
|
234
|
+
['198.18.0.0/15', 'benchmark'],
|
|
235
|
+
['198.51.100.0/24', 'doc'],
|
|
236
|
+
['203.0.113.0/24', 'doc'],
|
|
237
|
+
['224.0.0.0/4', 'multicast'],
|
|
238
|
+
['240.0.0.0/4', 'future'],
|
|
239
|
+
['255.255.255.255/32', 'broadcast'],
|
|
240
|
+
['::/128', 'unspecified'],
|
|
241
|
+
['::1/128', 'loopback'],
|
|
242
|
+
['::ffff:0:0/96', 'mapped'],
|
|
243
|
+
['64:ff9b::/96', 'nat64'],
|
|
244
|
+
['100::/64', 'discard'],
|
|
245
|
+
['2001::/32', 'teredo'],
|
|
246
|
+
['2001:db8::/32', 'doc'],
|
|
247
|
+
['2002::/16', 'relay6to4'],
|
|
248
|
+
['2000::/3', 'global'],
|
|
249
|
+
['fc00::/7', 'ula'],
|
|
250
|
+
['fe80::/10', 'linklocal'],
|
|
251
|
+
['ff00::/8', 'multicast'],
|
|
252
|
+
];
|
|
253
|
+
export let CIDR_SPECIAL_CACHE = null;
|
|
254
|
+
|
|
255
|
+
export function cidrSpecialList() {
|
|
256
|
+
if (!CIDR_SPECIAL_CACHE) {
|
|
257
|
+
CIDR_SPECIAL_CACHE = CIDR_SPECIAL_SRC.map((e) => {
|
|
258
|
+
const p = cidrParse(e[0]);
|
|
259
|
+
return { cidr: e[0], key: e[1], version: p.version, value: p.address & cidrMask(p.prefix, p.version), prefix: p.prefix };
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
return CIDR_SPECIAL_CACHE;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** そのアドレスがどの予約帯に入るか(いちばん細かい一致を採る) */
|
|
266
|
+
export function cidrScope(value, prefix, version) {
|
|
267
|
+
let hit = null;
|
|
268
|
+
for (const e of cidrSpecialList()) {
|
|
269
|
+
if (e.version !== version) continue;
|
|
270
|
+
if ((value & cidrMask(e.prefix, version)) === e.value) {
|
|
271
|
+
if (!hit || e.prefix > hit.prefix) hit = e;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
if (!hit) return { key: version === 4 ? 'global' : 'reserved', cidr: null, coversAll: true };
|
|
275
|
+
// prefix が予約帯より短い=ネットワークが予約帯からはみ出している
|
|
276
|
+
return { key: hit.key, cidr: hit.cidr, coversAll: prefix >= hit.prefix };
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** IPv4の歴史的なクラス(A/B/C/D/E) */
|
|
280
|
+
export function cidrClassOf(value) {
|
|
281
|
+
const first = Number((value >> 24n) & 255n);
|
|
282
|
+
if (first < 128) return 'A';
|
|
283
|
+
if (first < 192) return 'B';
|
|
284
|
+
if (first < 224) return 'C';
|
|
285
|
+
if (first < 240) return 'D';
|
|
286
|
+
return 'E';
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** 2進表記をグループ(IPv4は8bit×4・IPv6は16bit×8)の配列で返す */
|
|
290
|
+
export function cidrBinary(value, version) {
|
|
291
|
+
const size = version === 4 ? 8 : 16;
|
|
292
|
+
const count = version === 4 ? 4 : 8;
|
|
293
|
+
const out = [];
|
|
294
|
+
for (let i = count - 1; i >= 0; i--) {
|
|
295
|
+
let s = '';
|
|
296
|
+
for (let b = size - 1; b >= 0; b--) s += ((value >> BigInt(i * size + b)) & 1n).toString();
|
|
297
|
+
out.push(s);
|
|
298
|
+
}
|
|
299
|
+
return out;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** 逆引き(PTR)の名前 */
|
|
303
|
+
export function cidrPtr(value, version) {
|
|
304
|
+
if (version === 4) {
|
|
305
|
+
return [0n, 8n, 16n, 24n].map((sh) => ((value >> sh) & 255n).toString()).join('.') + '.in-addr.arpa';
|
|
306
|
+
}
|
|
307
|
+
return cidrExpandIp(value, 6).replace(/:/g, '').split('').reverse().join('.') + '.ip6.arpa';
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** 逆引きゾーン名。区切りに合わないプレフィックス(IPv4は8の倍数・IPv6は4の倍数以外)は null */
|
|
311
|
+
export function cidrPtrZone(value, prefix, version) {
|
|
312
|
+
if (version === 4) {
|
|
313
|
+
if (prefix % 8 !== 0) return null;
|
|
314
|
+
if (prefix === 0) return 'in-addr.arpa';
|
|
315
|
+
const o = [0n, 8n, 16n, 24n].map((sh) => ((value >> sh) & 255n).toString());
|
|
316
|
+
return o.slice(4 - prefix / 8).join('.') + '.in-addr.arpa';
|
|
317
|
+
}
|
|
318
|
+
if (prefix % 4 !== 0) return null;
|
|
319
|
+
const hex = cidrExpandIp(value, 6).replace(/:/g, '');
|
|
320
|
+
const keep = hex.slice(0, prefix / 4).split('').reverse().join('.');
|
|
321
|
+
return (keep ? keep + '.' : '') + 'ip6.arpa';
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/** 2のべき乗ならその指数を返す(アドレス数の短い表示に使う)。違えば -1 */
|
|
325
|
+
export function cidrPowerOfTwo(n) {
|
|
326
|
+
if (n <= 0n) return -1;
|
|
327
|
+
let e = 0;
|
|
328
|
+
let v = n;
|
|
329
|
+
while (v > 1n) {
|
|
330
|
+
if (v & 1n) return -1;
|
|
331
|
+
v >>= 1n;
|
|
332
|
+
e++;
|
|
333
|
+
}
|
|
334
|
+
return e;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/** CIDR 1件の計算。文字列でも cidrParse の結果でも受け取る */
|
|
338
|
+
export function cidrCalc(input) {
|
|
339
|
+
const p = input && typeof input === 'object' && input.version ? input : cidrParse(input);
|
|
340
|
+
const version = p.version;
|
|
341
|
+
const bits = CIDR_BITS[version];
|
|
342
|
+
const prefix = p.prefix;
|
|
343
|
+
const mask = cidrMask(prefix, version);
|
|
344
|
+
const network = p.address & mask;
|
|
345
|
+
const last = network | (cidrFull(version) & ~mask);
|
|
346
|
+
const total = 1n << BigInt(bits - prefix);
|
|
347
|
+
let broadcast = null;
|
|
348
|
+
let hostMin;
|
|
349
|
+
let hostMax;
|
|
350
|
+
let usable;
|
|
351
|
+
if (version === 4) {
|
|
352
|
+
if (prefix <= 30) {
|
|
353
|
+
broadcast = last;
|
|
354
|
+
hostMin = network + 1n;
|
|
355
|
+
hostMax = last - 1n;
|
|
356
|
+
usable = total - 2n;
|
|
357
|
+
} else if (prefix === 31) {
|
|
358
|
+
// RFC 3021: 2アドレスとも点対点リンクのホストに使える(ネットワーク/ブロードキャストを取らない)
|
|
359
|
+
hostMin = network;
|
|
360
|
+
hostMax = last;
|
|
361
|
+
usable = 2n;
|
|
362
|
+
} else {
|
|
363
|
+
hostMin = network;
|
|
364
|
+
hostMax = network;
|
|
365
|
+
usable = 1n;
|
|
366
|
+
}
|
|
367
|
+
} else {
|
|
368
|
+
// IPv6にブロードキャストは無い。先頭はサブネットルータ anycast だが範囲としては含める
|
|
369
|
+
hostMin = network;
|
|
370
|
+
hostMax = last;
|
|
371
|
+
usable = total;
|
|
372
|
+
}
|
|
373
|
+
return {
|
|
374
|
+
version: version,
|
|
375
|
+
input: p.input,
|
|
376
|
+
address: cidrFormatIp(p.address, version),
|
|
377
|
+
addressExpanded: cidrExpandIp(p.address, version),
|
|
378
|
+
prefix: prefix,
|
|
379
|
+
hadPrefix: p.hadPrefix,
|
|
380
|
+
maskKind: p.maskKind,
|
|
381
|
+
zone: p.zone,
|
|
382
|
+
cidr: cidrFormatIp(network, version) + '/' + prefix,
|
|
383
|
+
inputCidr: cidrFormatIp(p.address, version) + '/' + prefix,
|
|
384
|
+
isNetworkAddress: p.address === network,
|
|
385
|
+
network: cidrFormatIp(network, version),
|
|
386
|
+
broadcast: broadcast === null ? null : cidrFormatIp(broadcast, version),
|
|
387
|
+
last: cidrFormatIp(last, version),
|
|
388
|
+
netmask: cidrFormatIp(mask, version),
|
|
389
|
+
wildcard: version === 4 ? cidrFormatIp(cidrFull(4) & ~mask, 4) : null,
|
|
390
|
+
hostMin: cidrFormatIp(hostMin, version),
|
|
391
|
+
hostMax: cidrFormatIp(hostMax, version),
|
|
392
|
+
hasHosts: usable > 0n,
|
|
393
|
+
networkBits: prefix,
|
|
394
|
+
hostBits: bits - prefix,
|
|
395
|
+
total: total.toString(),
|
|
396
|
+
totalPow2: cidrPowerOfTwo(total),
|
|
397
|
+
usable: usable.toString(),
|
|
398
|
+
usablePow2: cidrPowerOfTwo(usable),
|
|
399
|
+
scope: cidrScope(network, prefix, version),
|
|
400
|
+
class: version === 4 ? cidrClassOf(network) : null,
|
|
401
|
+
integer: network.toString(),
|
|
402
|
+
hex: (version === 4 ? '0x' : '0x') + ('0'.repeat(version === 4 ? 8 : 32) + network.toString(16).toUpperCase()).slice(-(version === 4 ? 8 : 32)),
|
|
403
|
+
ptr: cidrPtr(network, version),
|
|
404
|
+
ptrZone: cidrPtrZone(network, prefix, version),
|
|
405
|
+
binary: cidrBinary(network, version),
|
|
406
|
+
binaryAddress: cidrBinary(p.address, version),
|
|
407
|
+
values: { network: network, last: last, mask: mask, address: p.address },
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/** ネットワークを細かいプレフィックスへ分割する。limit 件で打ち切り、総数は count で返す */
|
|
412
|
+
export function cidrSplit(network, prefix, newPrefix, version, limit) {
|
|
413
|
+
const bits = CIDR_BITS[version];
|
|
414
|
+
if (!Number.isInteger(newPrefix) || newPrefix < 0 || newPrefix > bits) {
|
|
415
|
+
throw new CidrError('BAD_PREFIX', { text: String(newPrefix), max: bits, version: version });
|
|
416
|
+
}
|
|
417
|
+
if (newPrefix < prefix) throw new CidrError('SPLIT_WIDER', { prefix: prefix, newPrefix: newPrefix });
|
|
418
|
+
const count = 1n << BigInt(newPrefix - prefix);
|
|
419
|
+
const step = 1n << BigInt(bits - newPrefix);
|
|
420
|
+
const max = BigInt(limit == null ? 256 : limit);
|
|
421
|
+
const subnets = [];
|
|
422
|
+
let addr = network & cidrMask(prefix, version);
|
|
423
|
+
for (let i = 0n; i < count && i < max; i++) {
|
|
424
|
+
subnets.push({ network: addr, prefix: newPrefix, cidr: cidrFormatIp(addr, version) + '/' + newPrefix });
|
|
425
|
+
addr += step;
|
|
426
|
+
}
|
|
427
|
+
return { count: count.toString(), step: step.toString(), subnets: subnets, truncated: count > max };
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/** 開始〜終了のアドレス範囲を、過不足のない最小のCIDR集合へ分解する */
|
|
431
|
+
export function cidrFromRange(start, end, version) {
|
|
432
|
+
if (start > end) throw new CidrError('RANGE_ORDER', { start: cidrFormatIp(start, version), end: cidrFormatIp(end, version) });
|
|
433
|
+
const bits = BigInt(CIDR_BITS[version]);
|
|
434
|
+
const out = [];
|
|
435
|
+
let cur = start;
|
|
436
|
+
while (cur <= end) {
|
|
437
|
+
let size = 0n; // このアドレスから取れるブロックのホストビット数
|
|
438
|
+
while (size < bits) {
|
|
439
|
+
const next = size + 1n;
|
|
440
|
+
const blockMask = (1n << next) - 1n;
|
|
441
|
+
if ((cur & blockMask) !== 0n) break; // そろっていない
|
|
442
|
+
if (cur + blockMask > end) break; // はみ出す
|
|
443
|
+
size = next;
|
|
444
|
+
}
|
|
445
|
+
const prefix = Number(bits - size);
|
|
446
|
+
out.push({ network: cur, prefix: prefix, cidr: cidrFormatIp(cur, version) + '/' + prefix });
|
|
447
|
+
cur += 1n << size;
|
|
448
|
+
}
|
|
449
|
+
return out;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/** 重なり・隣接した範囲をまとめる */
|
|
453
|
+
export function cidrMergeRanges(ranges) {
|
|
454
|
+
const sorted = ranges.slice().sort((a, b) => {
|
|
455
|
+
if (a.start < b.start) return -1;
|
|
456
|
+
if (a.start > b.start) return 1;
|
|
457
|
+
if (a.end < b.end) return -1;
|
|
458
|
+
if (a.end > b.end) return 1;
|
|
459
|
+
return 0;
|
|
460
|
+
});
|
|
461
|
+
const out = [];
|
|
462
|
+
for (const r of sorted) {
|
|
463
|
+
const prev = out[out.length - 1];
|
|
464
|
+
if (prev && r.start <= prev.end + 1n) {
|
|
465
|
+
if (r.end > prev.end) prev.end = r.end;
|
|
466
|
+
} else {
|
|
467
|
+
out.push({ start: r.start, end: r.end });
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
return out;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
export function cidrRangeFromPair(a, b, source) {
|
|
474
|
+
const s = cidrParseIp(a);
|
|
475
|
+
const e = cidrParseIp(b);
|
|
476
|
+
if (s.version !== e.version) throw new CidrError('MIXED_VERSION', { text: source });
|
|
477
|
+
if (s.value > e.value) throw new CidrError('RANGE_ORDER', { start: a, end: b });
|
|
478
|
+
return { start: s.value, end: e.value, version: s.version, source: source, kind: 'range' };
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/** 1行を範囲として読む。CIDR・単体のIP・「a - b」「a ~ b」「a b」のいずれも受ける */
|
|
482
|
+
export function cidrParseRangeLine(line) {
|
|
483
|
+
const s = String(line).trim();
|
|
484
|
+
if (s === '' || s.charAt(0) === '#') return null;
|
|
485
|
+
const dash = s.match(/^(\S+)\s*(?:\.\.|[-–—~,])\s*(\S+)$/);
|
|
486
|
+
if (dash) return cidrRangeFromPair(dash[1], dash[2], s);
|
|
487
|
+
try {
|
|
488
|
+
const p = cidrParse(s);
|
|
489
|
+
const mask = cidrMask(p.prefix, p.version);
|
|
490
|
+
const network = p.address & mask;
|
|
491
|
+
return {
|
|
492
|
+
start: network,
|
|
493
|
+
end: network | (cidrFull(p.version) & ~mask),
|
|
494
|
+
version: p.version,
|
|
495
|
+
source: s,
|
|
496
|
+
kind: p.hadPrefix ? 'cidr' : 'ip',
|
|
497
|
+
prefix: p.prefix,
|
|
498
|
+
};
|
|
499
|
+
} catch (err) {
|
|
500
|
+
const two = s.match(/^(\S+)\s+(\S+)$/);
|
|
501
|
+
if (two) return cidrRangeFromPair(two[1], two[2], s);
|
|
502
|
+
throw err;
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/** 複数行(範囲・CIDR・単体IPの混在)をまとめて最小のCIDR集合にする */
|
|
507
|
+
export function cidrSummarize(text) {
|
|
508
|
+
const lines = String(text == null ? '' : text).split(/\r\n|\n|\r/);
|
|
509
|
+
const ranges = [];
|
|
510
|
+
const errors = [];
|
|
511
|
+
let version = null;
|
|
512
|
+
for (let i = 0; i < lines.length; i++) {
|
|
513
|
+
let r;
|
|
514
|
+
try {
|
|
515
|
+
r = cidrParseRangeLine(lines[i]);
|
|
516
|
+
} catch (err) {
|
|
517
|
+
if (!(err instanceof CidrError)) throw err;
|
|
518
|
+
errors.push({ line: i + 1, text: lines[i].trim(), code: err.code, info: err.info });
|
|
519
|
+
continue;
|
|
520
|
+
}
|
|
521
|
+
if (!r) continue;
|
|
522
|
+
if (version === null) version = r.version;
|
|
523
|
+
else if (version !== r.version) {
|
|
524
|
+
errors.push({ line: i + 1, text: lines[i].trim(), code: 'MIXED_VERSION', info: {} });
|
|
525
|
+
continue;
|
|
526
|
+
}
|
|
527
|
+
ranges.push(r);
|
|
528
|
+
}
|
|
529
|
+
const merged = cidrMergeRanges(ranges);
|
|
530
|
+
const cidrs = [];
|
|
531
|
+
for (const r of merged) {
|
|
532
|
+
for (const c of cidrFromRange(r.start, r.end, version)) cidrs.push(c);
|
|
533
|
+
}
|
|
534
|
+
let total = 0n;
|
|
535
|
+
for (const r of merged) total += r.end - r.start + 1n;
|
|
536
|
+
return {
|
|
537
|
+
version: version,
|
|
538
|
+
inputCount: ranges.length,
|
|
539
|
+
ranges: ranges,
|
|
540
|
+
merged: merged.map((r) => ({
|
|
541
|
+
start: cidrFormatIp(r.start, version),
|
|
542
|
+
end: cidrFormatIp(r.end, version),
|
|
543
|
+
count: (r.end - r.start + 1n).toString(),
|
|
544
|
+
})),
|
|
545
|
+
cidrs: cidrs.map((c) => c.cidr),
|
|
546
|
+
total: total.toString(),
|
|
547
|
+
errors: errors,
|
|
548
|
+
};
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/** そのアドレスがネットワークに含まれるか */
|
|
552
|
+
export function cidrContains(network, prefix, version, value) {
|
|
553
|
+
const mask = cidrMask(prefix, version);
|
|
554
|
+
return (value & mask) === (network & mask);
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/* ==================== ここまで計算コア ==================== */
|
|
558
|
+
|
|
559
|
+
/* ---- ここから下はMCP側だけの層(入出力・文言)。site側の app.js には UI 用の同じ文言表がある ---- */
|
|
560
|
+
|
|
561
|
+
export class CidrCalcError extends Error {}
|
|
562
|
+
|
|
563
|
+
const SCOPE_JA = {
|
|
564
|
+
private: 'プライベート(RFC 1918)',
|
|
565
|
+
cgnat: 'キャリアグレードNAT(RFC 6598)',
|
|
566
|
+
loopback: 'ループバック',
|
|
567
|
+
linklocal: 'リンクローカル',
|
|
568
|
+
thisnet: '「このネットワーク」',
|
|
569
|
+
ietf: 'IETFプロトコル用',
|
|
570
|
+
doc: '文書・例示用',
|
|
571
|
+
relay6to4: '6to4 リレー',
|
|
572
|
+
benchmark: '性能試験用',
|
|
573
|
+
multicast: 'マルチキャスト',
|
|
574
|
+
future: '将来用に予約',
|
|
575
|
+
broadcast: '限定ブロードキャスト',
|
|
576
|
+
global: 'グローバル(インターネット側)',
|
|
577
|
+
unspecified: '未指定アドレス',
|
|
578
|
+
mapped: 'IPv4射影アドレス',
|
|
579
|
+
nat64: 'NAT64 用',
|
|
580
|
+
discard: '破棄専用',
|
|
581
|
+
teredo: 'Teredo',
|
|
582
|
+
ula: 'ユニークローカル(IPv6の私設用)',
|
|
583
|
+
reserved: '未割り当て・予約',
|
|
584
|
+
};
|
|
585
|
+
|
|
586
|
+
const SCOPE_EN = {
|
|
587
|
+
private: 'Private (RFC 1918)',
|
|
588
|
+
cgnat: 'Carrier-grade NAT (RFC 6598)',
|
|
589
|
+
loopback: 'Loopback',
|
|
590
|
+
linklocal: 'Link-local',
|
|
591
|
+
thisnet: '"This network"',
|
|
592
|
+
ietf: 'IETF protocol assignments',
|
|
593
|
+
doc: 'Documentation / examples',
|
|
594
|
+
relay6to4: '6to4 relay',
|
|
595
|
+
benchmark: 'Benchmarking',
|
|
596
|
+
multicast: 'Multicast',
|
|
597
|
+
future: 'Reserved for future use',
|
|
598
|
+
broadcast: 'Limited broadcast',
|
|
599
|
+
global: 'Global unicast (routable)',
|
|
600
|
+
unspecified: 'Unspecified address',
|
|
601
|
+
mapped: 'IPv4-mapped',
|
|
602
|
+
nat64: 'NAT64 prefix',
|
|
603
|
+
discard: 'Discard-only',
|
|
604
|
+
teredo: 'Teredo',
|
|
605
|
+
ula: 'Unique local (private)',
|
|
606
|
+
reserved: 'Reserved / unassigned',
|
|
607
|
+
};
|
|
608
|
+
|
|
609
|
+
const ERR_JA = {
|
|
610
|
+
EMPTY: () => '入力が空です。',
|
|
611
|
+
BAD_IP: (i) => `IPアドレスとして読めません: ${i.text} — IPv4は 192.168.1.10、IPv6は 2001:db8::1 のように書きます。`,
|
|
612
|
+
LEADING_ZERO: (i) =>
|
|
613
|
+
`先頭に0の付いた数字があります: ${i.text} — 8進数として読む実装があり別のアドレスになるため、0を外して書いてください(010 → 10)。`,
|
|
614
|
+
OCTET_RANGE: (i) => `IPv4の各数字は0〜255までです: ${i.text}(${i.octet} が範囲外)。`,
|
|
615
|
+
BAD_PREFIX: (i) => `プレフィックス長が範囲外です: /${i.text} — IPv${i.version} は 0〜${i.max} です。`,
|
|
616
|
+
NO_PREFIX: () => '/ の後ろにプレフィックス長がありません(例: /24)。',
|
|
617
|
+
BAD_MASK: (i) => `サブネットマスクとして成立しません: ${i.text} — 1が左から連続している必要があります(255.255.255.0 など)。`,
|
|
618
|
+
MASK_VERSION: (i) => `アドレスとマスクのIPバージョンが違います: ${i.text}`,
|
|
619
|
+
MIXED_VERSION: () => 'IPv4とIPv6が混ざっています。どちらかに揃えてください。',
|
|
620
|
+
RANGE_ORDER: (i) => `開始が終了より後ろになっています: ${i.start} → ${i.end}`,
|
|
621
|
+
SPLIT_WIDER: (i) => `/${i.newPrefix} は元の /${i.prefix} より大きい範囲です。分割するには元より長いプレフィックスを選びます。`,
|
|
622
|
+
};
|
|
623
|
+
|
|
624
|
+
const ERR_EN = {
|
|
625
|
+
EMPTY: () => 'The input is empty.',
|
|
626
|
+
BAD_IP: (i) => `Not a valid IP address: ${i.text} — write IPv4 as 192.168.1.10 or IPv6 as 2001:db8::1.`,
|
|
627
|
+
LEADING_ZERO: (i) =>
|
|
628
|
+
`An octet has a leading zero: ${i.text} — some libraries read that as octal, which is a different address. Drop the zero (010 → 10).`,
|
|
629
|
+
OCTET_RANGE: (i) => `Each IPv4 octet must be 0–255: ${i.text} (${i.octet} is out of range).`,
|
|
630
|
+
BAD_PREFIX: (i) => `Prefix length out of range: /${i.text} — IPv${i.version} allows 0–${i.max}.`,
|
|
631
|
+
NO_PREFIX: () => 'Nothing after the slash — write a prefix length such as /24.',
|
|
632
|
+
BAD_MASK: (i) => `Not a valid subnet mask: ${i.text} — the 1 bits must be contiguous from the left (255.255.255.0 and so on).`,
|
|
633
|
+
MASK_VERSION: (i) => `Address and mask are different IP versions: ${i.text}`,
|
|
634
|
+
MIXED_VERSION: () => 'IPv4 and IPv6 are mixed. Use one family at a time.',
|
|
635
|
+
RANGE_ORDER: (i) => `The start address comes after the end: ${i.start} → ${i.end}`,
|
|
636
|
+
SPLIT_WIDER: (i) => `/${i.newPrefix} is larger than the original /${i.prefix}. Pick a longer prefix to split into.`,
|
|
637
|
+
};
|
|
638
|
+
|
|
639
|
+
const NOTE_JA = {
|
|
640
|
+
NO_PREFIX: (n) => `プレフィックスが無いので /${n.prefix}(1アドレスだけ)として計算しました。範囲を見るなら ${n.address}/24 のように書きます。`,
|
|
641
|
+
HOST_BITS: (n) => `${n.address} はホスト部にビットが立っています。この /${n.prefix} のネットワークは ${n.cidr} です(設定ファイルに書くときはこちら)。`,
|
|
642
|
+
MASK_GIVEN: (n) => `サブネットマスク ${n.mask} を /${n.prefix} として読みました。`,
|
|
643
|
+
WILDCARD_GIVEN: (n) => `ワイルドカードマスク ${n.mask} を /${n.prefix} として読みました(ACLの書き方)。`,
|
|
644
|
+
P2P: () => '/31 は点対点リンク用で、2つのアドレスをどちらもホストに使えます(RFC 3021)。ネットワーク/ブロードキャストは取りません。',
|
|
645
|
+
SINGLE: () => '/32 は1台だけを指す書き方です(許可リストではこの形を使います)。',
|
|
646
|
+
V6_NO_BROADCAST: () => 'IPv6にブロードキャストはありません。先頭のアドレスはサブネットルータanycastとして予約されています。',
|
|
647
|
+
V6_SLAAC: () => 'IPv6のLANセグメントは /64 が基本です。これより細かく切るとSLAAC(ホストが自分でアドレスを作る仕組み)が動きません。',
|
|
648
|
+
SCOPE_PARTIAL: (n) => `このネットワークは ${n.cidr}(${n.label})からはみ出しています。一部だけが重なっています。`,
|
|
649
|
+
SPLIT_TRUNCATED: (n) => `全 ${n.count} 個のうち先頭 ${n.shown} 個だけを返しました。limit を上げると増やせます。`,
|
|
650
|
+
RANGE_MERGED: (n) => `${n.input} 行を ${n.merged} つの連続した範囲にまとめ、${n.cidrs} 個のCIDRで過不足なく表せました。`,
|
|
651
|
+
};
|
|
652
|
+
|
|
653
|
+
const NOTE_EN = {
|
|
654
|
+
NO_PREFIX: (n) => `No prefix was given, so this was read as /${n.prefix} (a single address). Write it as ${n.address}/24 to see a range.`,
|
|
655
|
+
HOST_BITS: (n) => `${n.address} has bits set in the host part. The network it belongs to is ${n.cidr} — use that form in config files.`,
|
|
656
|
+
MASK_GIVEN: (n) => `The subnet mask ${n.mask} was read as /${n.prefix}.`,
|
|
657
|
+
WILDCARD_GIVEN: (n) => `The wildcard mask ${n.mask} was read as /${n.prefix} (the ACL convention).`,
|
|
658
|
+
P2P: () => 'A /31 is for point-to-point links: both addresses are usable hosts (RFC 3021), with no network or broadcast address.',
|
|
659
|
+
SINGLE: () => 'A /32 names a single host — the form used in allow lists.',
|
|
660
|
+
V6_NO_BROADCAST: () => 'IPv6 has no broadcast address. The first address of a subnet is reserved for the subnet-router anycast.',
|
|
661
|
+
V6_SLAAC: () => 'IPv6 LAN segments are /64 by convention. Splitting below that stops SLAAC (hosts building their own addresses) from working.',
|
|
662
|
+
SCOPE_PARTIAL: (n) => `This network extends beyond ${n.cidr} (${n.label}); only part of it overlaps that reserved range.`,
|
|
663
|
+
SPLIT_TRUNCATED: (n) => `Returned the first ${n.shown} of ${n.count} subnets. Raise limit to get more.`,
|
|
664
|
+
RANGE_MERGED: (n) => `Merged ${n.input} lines into ${n.merged} contiguous range(s), covered exactly by ${n.cidrs} CIDR block(s).`,
|
|
665
|
+
};
|
|
666
|
+
|
|
667
|
+
const errText = (lang, code, info) => {
|
|
668
|
+
const table = lang === 'en' ? ERR_EN : ERR_JA;
|
|
669
|
+
return table[code] ? table[code](info || {}) : code;
|
|
670
|
+
};
|
|
671
|
+
|
|
672
|
+
const noteText = (lang, code, info) => {
|
|
673
|
+
const table = lang === 'en' ? NOTE_EN : NOTE_JA;
|
|
674
|
+
return { code: code, message: table[code] ? table[code](info || {}) : code };
|
|
675
|
+
};
|
|
676
|
+
|
|
677
|
+
const scopeLabel = (lang, key) => (lang === 'en' ? SCOPE_EN : SCOPE_JA)[key] || key;
|
|
678
|
+
|
|
679
|
+
/** 計算結果1件をMCPの戻り値の形へ(BigIntは残さず文字列にする) */
|
|
680
|
+
function shapeCalc(r, lang) {
|
|
681
|
+
const notes = [];
|
|
682
|
+
if (!r.hadPrefix) notes.push(noteText(lang, 'NO_PREFIX', { prefix: r.prefix, address: r.address }));
|
|
683
|
+
else if (!r.isNetworkAddress) notes.push(noteText(lang, 'HOST_BITS', { address: r.address, prefix: r.prefix, cidr: r.cidr }));
|
|
684
|
+
if (r.maskKind === 'netmask') notes.push(noteText(lang, 'MASK_GIVEN', { mask: r.netmask, prefix: r.prefix }));
|
|
685
|
+
if (r.maskKind === 'wildcard') notes.push(noteText(lang, 'WILDCARD_GIVEN', { mask: r.wildcard, prefix: r.prefix }));
|
|
686
|
+
if (r.version === 4 && r.prefix === 31) notes.push(noteText(lang, 'P2P', {}));
|
|
687
|
+
if (r.version === 4 && r.prefix === 32) notes.push(noteText(lang, 'SINGLE', {}));
|
|
688
|
+
if (r.version === 6) notes.push(noteText(lang, 'V6_NO_BROADCAST', {}));
|
|
689
|
+
if (r.version === 6 && r.prefix > 64) notes.push(noteText(lang, 'V6_SLAAC', {}));
|
|
690
|
+
if (!r.scope.coversAll) notes.push(noteText(lang, 'SCOPE_PARTIAL', { cidr: r.scope.cidr, label: scopeLabel(lang, r.scope.key) }));
|
|
691
|
+
|
|
692
|
+
const out = {
|
|
693
|
+
version: r.version,
|
|
694
|
+
input: r.input,
|
|
695
|
+
address: r.address,
|
|
696
|
+
prefix: r.prefix,
|
|
697
|
+
cidr: r.cidr,
|
|
698
|
+
is_network_address: r.isNetworkAddress,
|
|
699
|
+
network: r.network,
|
|
700
|
+
netmask: r.netmask,
|
|
701
|
+
host_min: r.hostMin,
|
|
702
|
+
host_max: r.hostMax,
|
|
703
|
+
total_addresses: r.total,
|
|
704
|
+
usable_hosts: r.usable,
|
|
705
|
+
network_bits: r.networkBits,
|
|
706
|
+
host_bits: r.hostBits,
|
|
707
|
+
type: { key: r.scope.key, label: scopeLabel(lang, r.scope.key), block: r.scope.cidr, covers_all: r.scope.coversAll },
|
|
708
|
+
integer: r.integer,
|
|
709
|
+
hex: r.hex,
|
|
710
|
+
reverse_dns: r.ptr,
|
|
711
|
+
reverse_zone: r.ptrZone,
|
|
712
|
+
binary: r.binary.join(r.version === 4 ? '.' : ':'),
|
|
713
|
+
notes: notes,
|
|
714
|
+
};
|
|
715
|
+
if (r.version === 4) {
|
|
716
|
+
out.broadcast = r.broadcast;
|
|
717
|
+
out.wildcard = r.wildcard;
|
|
718
|
+
out.class = r.class;
|
|
719
|
+
} else {
|
|
720
|
+
out.last_address = r.last;
|
|
721
|
+
out.expanded = r.addressExpanded;
|
|
722
|
+
if (r.zone) out.zone = r.zone;
|
|
723
|
+
}
|
|
724
|
+
return out;
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
/**
|
|
728
|
+
* MCPツール cidr_calc の本体。CIDRの計算・サブネット分割・包含判定・範囲の逆算を1つで受ける。
|
|
729
|
+
* 計算そのものは計算コア(site版と同一)に任せ、ここは入出力と文言だけを持つ。
|
|
730
|
+
*/
|
|
731
|
+
export async function cidrCalcTool(opts = {}) {
|
|
732
|
+
const o = opts || {};
|
|
733
|
+
const lang = o.lang === undefined ? 'ja' : o.lang;
|
|
734
|
+
if (lang !== 'ja' && lang !== 'en') throw new CidrCalcError(`lang は ja か en: ${o.lang}`);
|
|
735
|
+
|
|
736
|
+
const hasCidr = typeof o.cidr === 'string' && o.cidr.trim() !== '';
|
|
737
|
+
const hasRange = typeof o.range === 'string' && o.range.trim() !== '';
|
|
738
|
+
// 「split だけ渡した」のように狙いが分かるものは、先に具体的な言い方で返す
|
|
739
|
+
if (o.split !== undefined && !hasCidr) throw new CidrCalcError('split は cidr と一緒に渡してください');
|
|
740
|
+
if (o.contains !== undefined && !hasCidr) throw new CidrCalcError('contains は cidr と一緒に渡してください');
|
|
741
|
+
if (!hasCidr && !hasRange) throw new CidrCalcError('cidr か range のどちらかを渡してください');
|
|
742
|
+
if (o.contains !== undefined && !Array.isArray(o.contains)) throw new CidrCalcError('contains は文字列の配列です');
|
|
743
|
+
if (o.split !== undefined && !Number.isInteger(o.split)) throw new CidrCalcError(`split は整数のプレフィックス長です: ${o.split}`);
|
|
744
|
+
if (o.limit !== undefined && !(Number.isInteger(o.limit) && o.limit >= 1 && o.limit <= 4096)) {
|
|
745
|
+
throw new CidrCalcError(`limit は 1〜4096 の整数です: ${o.limit}`);
|
|
746
|
+
}
|
|
747
|
+
const limit = o.limit === undefined ? 256 : o.limit;
|
|
748
|
+
|
|
749
|
+
const result = { ok: true };
|
|
750
|
+
|
|
751
|
+
let calc = null;
|
|
752
|
+
if (hasCidr) {
|
|
753
|
+
try {
|
|
754
|
+
calc = cidrCalc(o.cidr);
|
|
755
|
+
} catch (err) {
|
|
756
|
+
if (!(err instanceof CidrError)) throw err;
|
|
757
|
+
// 入力が壊れているのは「呼び出し方の誤り」ではないので、例外ではなく結果として返す
|
|
758
|
+
return { ok: false, input: o.cidr, error: { code: err.code, message: errText(lang, err.code, err.info) } };
|
|
759
|
+
}
|
|
760
|
+
Object.assign(result, shapeCalc(calc, lang));
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
if (o.split !== undefined) {
|
|
764
|
+
let sp;
|
|
765
|
+
try {
|
|
766
|
+
sp = cidrSplit(calc.values.network, calc.prefix, o.split, calc.version, limit);
|
|
767
|
+
} catch (err) {
|
|
768
|
+
if (!(err instanceof CidrError)) throw err;
|
|
769
|
+
return { ok: false, input: o.cidr, error: { code: err.code, message: errText(lang, err.code, err.info) } };
|
|
770
|
+
}
|
|
771
|
+
result.subnets = {
|
|
772
|
+
prefix: o.split,
|
|
773
|
+
count: sp.count,
|
|
774
|
+
addresses_each: sp.step,
|
|
775
|
+
truncated: sp.truncated,
|
|
776
|
+
list: sp.subnets.map((s) => {
|
|
777
|
+
const c = cidrCalc(s.cidr);
|
|
778
|
+
const row = { cidr: c.cidr, network: c.network, host_min: c.hostMin, host_max: c.hostMax };
|
|
779
|
+
if (c.version === 4) row.broadcast = c.broadcast;
|
|
780
|
+
else row.last_address = c.last;
|
|
781
|
+
return row;
|
|
782
|
+
}),
|
|
783
|
+
};
|
|
784
|
+
if (sp.truncated) {
|
|
785
|
+
result.notes = (result.notes || []).concat([
|
|
786
|
+
noteText(lang, 'SPLIT_TRUNCATED', { count: sp.count, shown: sp.subnets.length }),
|
|
787
|
+
]);
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
if (o.contains !== undefined) {
|
|
792
|
+
result.contains = o.contains.map((raw) => {
|
|
793
|
+
let ip;
|
|
794
|
+
try {
|
|
795
|
+
ip = cidrParseIp(raw);
|
|
796
|
+
} catch (err) {
|
|
797
|
+
if (!(err instanceof CidrError)) throw err;
|
|
798
|
+
return { address: String(raw), inside: null, error: { code: err.code, message: errText(lang, err.code, err.info) } };
|
|
799
|
+
}
|
|
800
|
+
if (ip.version !== calc.version) {
|
|
801
|
+
return { address: cidrFormatIp(ip.value, ip.version), inside: null, error: { code: 'MIXED_VERSION', message: errText(lang, 'MIXED_VERSION', {}) } };
|
|
802
|
+
}
|
|
803
|
+
return {
|
|
804
|
+
address: cidrFormatIp(ip.value, ip.version),
|
|
805
|
+
inside: cidrContains(calc.values.network, calc.prefix, calc.version, ip.value),
|
|
806
|
+
};
|
|
807
|
+
});
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
if (hasRange) {
|
|
811
|
+
const s = cidrSummarize(o.range.split(';').join('\n'));
|
|
812
|
+
result.range = {
|
|
813
|
+
version: s.version,
|
|
814
|
+
input_count: s.inputCount,
|
|
815
|
+
merged: s.merged,
|
|
816
|
+
cidrs: s.cidrs,
|
|
817
|
+
total_addresses: s.total,
|
|
818
|
+
errors: s.errors.map((e) => ({ line: e.line, text: e.text, code: e.code, message: errText(lang, e.code, e.info) })),
|
|
819
|
+
};
|
|
820
|
+
if (s.merged.length && s.inputCount > s.merged.length) {
|
|
821
|
+
result.range.notes = [noteText(lang, 'RANGE_MERGED', { input: s.inputCount, merged: s.merged.length, cidrs: s.cidrs.length })];
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
return result;
|
|
826
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@first-ch/tools-mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "First CH Tools の計算ロジック(WCAGコントラスト比・文字数/Xウェイト・WebP変換・JSON-LD生成・llms.txt生成・文字コード/改行コード変換・Marp Markdown→スライド レンダリング・テストデータ生成・テキスト/コード差分・Cron式の解説・Base64/Data URI変換・URLパラメータの分解/再構築・HTML特殊文字のエスケープ/エンティティのデコード・JSON⇄YAMLの相互変換・px⇄rem/emの単位換算とCSSの一括変換・カラーコードの相互変換とアルファ透過の合成・MD5/SHA-1/SHA-256/SHA-384/SHA-512のハッシュ生成と照合・JWTのデコードと有効期限/署名の検証・User-Agent文字列の解析とデバイス判定・UUID v4/ULIDの一括生成・アスペクト比の計算とレスポンシブサイズの算出・TSV/CSVからMarkdownテーブルへの整形と相互変換・SQLクエリの整形と予約語の大文字化・URL/テキストからのQRコード生成・UNIXタイムスタンプと日時表記の相互変換・robots.txtの生成(AIクローラーの許可プリセット付き)・文字列のケース変換(camelCase/snake_case/kebab-case など11形式)・CSV/TSVとJSON配列の相互変換(区切りの自動判定・a.b
|
|
3
|
+
"version": "0.29.0",
|
|
4
|
+
"description": "First CH Tools の計算ロジック(WCAGコントラスト比・文字数/Xウェイト・WebP変換・JSON-LD生成・llms.txt生成・文字コード/改行コード変換・Marp Markdown→スライド レンダリング・テストデータ生成・テキスト/コード差分・Cron式の解説・Base64/Data URI変換・URLパラメータの分解/再構築・HTML特殊文字のエスケープ/エンティティのデコード・JSON⇄YAMLの相互変換・px⇄rem/emの単位換算とCSSの一括変換・カラーコードの相互変換とアルファ透過の合成・MD5/SHA-1/SHA-256/SHA-384/SHA-512のハッシュ生成と照合・JWTのデコードと有効期限/署名の検証・User-Agent文字列の解析とデバイス判定・UUID v4/ULIDの一括生成・アスペクト比の計算とレスポンシブサイズの算出・TSV/CSVからMarkdownテーブルへの整形と相互変換・SQLクエリの整形と予約語の大文字化・URL/テキストからのQRコード生成・UNIXタイムスタンプと日時表記の相互変換・robots.txtの生成(AIクローラーの許可プリセット付き)・文字列のケース変換(camelCase/snake_case/kebab-case など11形式)・CSV/TSVとJSON配列の相互変換(区切りの自動判定・a.b 列と入れ子の相互展開)・全角⇄半角の変換とテキストの掃除(文字種ごとの向き指定・半角カナの合成/分解・空白と空行の整理)・IPアドレス/CIDRの計算(ネットワーク・ブロードキャスト・ホスト範囲とホスト数・IPv4/IPv6・サブネット分割・包含判定・IP範囲→最小CIDR集合の逆算))をMCPツールとして提供するサーバー",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
7
7
|
"firstch-tools-mcp": "server.mjs"
|
|
@@ -155,7 +155,16 @@
|
|
|
155
155
|
"half-width",
|
|
156
156
|
"japanese",
|
|
157
157
|
"normalize",
|
|
158
|
-
"text-cleaner"
|
|
158
|
+
"text-cleaner",
|
|
159
|
+
"cidr",
|
|
160
|
+
"subnet",
|
|
161
|
+
"subnet-calculator",
|
|
162
|
+
"ip",
|
|
163
|
+
"ipv4",
|
|
164
|
+
"ipv6",
|
|
165
|
+
"netmask",
|
|
166
|
+
"network",
|
|
167
|
+
"ip-range"
|
|
159
168
|
],
|
|
160
169
|
"author": "First CH LLC (https://first-ch.com)",
|
|
161
170
|
"homepage": "https://tools.first-ch.com",
|
|
@@ -200,6 +209,7 @@
|
|
|
200
209
|
"case-convert.mjs",
|
|
201
210
|
"csv-json.mjs",
|
|
202
211
|
"zenkaku.mjs",
|
|
212
|
+
"cidr.mjs",
|
|
203
213
|
"vendor/",
|
|
204
214
|
"README.md",
|
|
205
215
|
"LICENSE"
|
package/server.mjs
CHANGED
|
@@ -31,6 +31,7 @@ import { robotsTxtGenerate } from './robots-txt.mjs';
|
|
|
31
31
|
import { caseConvertTool } from './case-convert.mjs';
|
|
32
32
|
import { zenkakuConvertTool } from './zenkaku.mjs';
|
|
33
33
|
import { csvConvertTool } from './csv-json.mjs';
|
|
34
|
+
import { cidrCalcTool } from './cidr.mjs';
|
|
34
35
|
|
|
35
36
|
const { version } = createRequire(import.meta.url)('./package.json');
|
|
36
37
|
const server = new McpServer({ name: 'firstch-tools', version });
|
|
@@ -1344,4 +1345,41 @@ server.registerTool(
|
|
|
1344
1345
|
},
|
|
1345
1346
|
);
|
|
1346
1347
|
|
|
1348
|
+
server.registerTool(
|
|
1349
|
+
'cidr_calc',
|
|
1350
|
+
{
|
|
1351
|
+
title: 'IPアドレス・CIDRの計算',
|
|
1352
|
+
description:
|
|
1353
|
+
'CIDR表記・サブネットマスク・ワイルドカードマスク・単体のIPから、ネットワークアドレス・ブロードキャスト・' +
|
|
1354
|
+
'使えるホストの範囲・アドレス数・逆引きゾーン・2進表記までを計算する(tools.first-ch.com/cidr/ と同一ロジック)。' +
|
|
1355
|
+
'サーバー設定・ファイアウォール・許可リストの作成時のサブネット計算に使う。**IPv4とIPv6の両対応**' +
|
|
1356
|
+
'(IPv6は `::` の省略・末尾のIPv4表記・`[...]`・`%zone` を読み、出力は RFC 5952 に従う)。' +
|
|
1357
|
+
'`192.168.1.5 255.255.255.0`(マスク併記)や `192.168.1.5/0.0.0.255`(ACLのワイルドカード)も同じ入力欄で受け取る。' +
|
|
1358
|
+
'**ホスト数の例外も織り込む**: `/31` は点対点リンクとして2アドレスとも使え(RFC 3021)、`/32` は1台、IPv6にブロードキャストは無い。' +
|
|
1359
|
+
'入力がネットワークアドレスでない(ホスト部にビットが立っている)ときは、設定に書くべき本来のCIDRを notes で返す。' +
|
|
1360
|
+
'**先頭に0の付いたオクテット(192.168.001.1)は受け取らない**(8進数として読む実装があり、同じ表記が別のアドレスになるため)。' +
|
|
1361
|
+
'アドレス帯は IANA の Special-Purpose Address Registry の主要ブロック(プライベート・CGNAT・ループバック・リンクローカル・' +
|
|
1362
|
+
'文書用・マルチキャスト・ULA ほか)と照合して種別を返し、ネットワークがその帯からはみ出す場合も指摘する。' +
|
|
1363
|
+
'`split` を渡すとそのプレフィックス長で均等に分割した一覧を、`contains` を渡すと各アドレスがそのネットワークに入るかを返す。' +
|
|
1364
|
+
'`range` に「10.0.0.5 - 10.0.0.200」のような範囲・CIDR・単体IPを(`;` か改行で区切って)渡すと、' +
|
|
1365
|
+
'**重なりと隣接をまとめたうえで過不足なく覆う最小個数のCIDR集合**へ逆算する。' +
|
|
1366
|
+
'計算はすべてBigIntで行い、完全ローカル処理・ネットワーク送信なし。',
|
|
1367
|
+
inputSchema: {
|
|
1368
|
+
cidr: z.string().optional().describe('計算するブロック(例: 192.168.1.0/24 / 10.0.0.1 255.0.0.0 / 2001:db8::1/48。range と併用可)'),
|
|
1369
|
+
split: z.number().int().optional().describe('分割後のプレフィックス長(cidr と一緒に渡す。元より長い値)'),
|
|
1370
|
+
contains: z.array(z.string()).optional().describe('そのネットワークに含まれるかを確かめるIPアドレスの配列(cidr と一緒に渡す)'),
|
|
1371
|
+
range: z
|
|
1372
|
+
.string()
|
|
1373
|
+
.optional()
|
|
1374
|
+
.describe('最小のCIDR集合へ逆算する範囲。1行1件(`;` 区切りも可)で「a - b」「a ~ b」「a..b」やCIDR・単体IPを混ぜられる'),
|
|
1375
|
+
limit: z.number().int().min(1).max(4096).optional().describe('split で返すサブネットの最大件数(既定 256)'),
|
|
1376
|
+
lang: z.enum(['ja', 'en']).optional().describe("指摘事項とエラーの言語(既定 'ja')"),
|
|
1377
|
+
},
|
|
1378
|
+
},
|
|
1379
|
+
async (opts) => {
|
|
1380
|
+
await logUsage('cidr_calc');
|
|
1381
|
+
return asText(await cidrCalcTool(opts));
|
|
1382
|
+
},
|
|
1383
|
+
);
|
|
1384
|
+
|
|
1347
1385
|
await server.connect(new StdioServerTransport());
|