@first-ch/tools-mcp 0.47.1 → 0.49.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 +4 -0
- package/comfy-png-leak.mjs +575 -0
- package/package.json +4 -2
- package/reply-check.mjs +497 -0
- package/server.mjs +56 -0
package/README.md
CHANGED
|
@@ -91,6 +91,8 @@ This server is also registered in the [MCP Registry](https://registry.modelconte
|
|
|
91
91
|
| `wiki_doc_lint` | Audits an exported internal wiki — Markdown, HTML or text exported from Notion, Backlog Wiki, Confluence and the like (same logic as tools.first-ch.com/wiki-doc-lint/). Returns **near-duplicate page pairs** (`duplicates`: Jaccard index of four-character fragments of the text with symbols and spaces removed, at or above `threshold`, with the lines only one side has and a fix that keeps the page with more incoming links, or the longer one on a tie), **orphan pages that no other page links to** (`orphans`, with `addLine` — the link line to add to a Notion-style parent or a contents page; index/README/home pages are not counted unless `entryPages=false`), **inconsistent and outdated terms** (`terms`: a "preferred ← variant" dictionary — your `dictionary` is added to the default one — plus Japanese katakana words found both with and without a final long-vowel mark, suggesting the majority form; every hit has its line and the line before/after the fix), **broken links** (`broken`: relative links with a document extension and `[[Page name]]` links whose target is not among the files) and a Markdown `report` of suggested fixes. Links are read from `[text](path)`, `[[Page name]]` and `<a href>`, matched by relative path, title, Notion file names with their IDs and the page name at the end of Notion/Confluence URLs. Code blocks, inline code, URLs and tags are skipped for terms, and matches inside a longer word (ユーザ in ユーザビリティ, Javascript in Javascripts) are ignored. Pass `paths` (absolute files or folders, read recursively; hidden folders and node_modules are skipped) or `files`. UTF-8, Shift_JIS and UTF-16 (BOM) are detected; up to 3,000 files / 60 MB. Read-only — it never edits the files | `paths?` or `files?` (`[{ path, text }]`), `threshold?` (0.5–1, default 0.8), `dictionary?`, `useDefaultDictionary?`, `autoChoon?`, `entryPages?`, `format?` (`both` default / `json` / `markdown`), `lang?` (`ja` default / `en`) |
|
|
92
92
|
| `fit_to_box` | Character size and line breaks for writing a string by hand into a printed box — e.g. the address, amount and name boxes on the inner envelope (nakabukuro) of a Japanese wedding or condolence money envelope (same logic as tools.first-ch.com/en/nakabukuro-ran/). From the box width and height (mm) and direction, returns the character size that fits (mm, rounded down to 0.1 mm), the line count and each line. Size uses a 1.5 mm margin inside each side and a 0.3× line gap, limited by both line length and line count (half-width letters/digits count as 0.6 in horizontal boxes; caps of 9 mm for addresses, 14 mm for amount/name). `kind: "address"` breaks between the street number and the building/room first, and only when that cannot reach 4 mm also after the prefecture/city or before the street number (runs like 12番地の18 or 1203号室 are never split; a line break in `text` marks the building; up to 4 lines); `postalCode` adds a 〒 line; vertical boxes get kanji street numbers (`numerals`: `digits` = 一〇, `tens` = 十). Below 4 mm, `alternatives` gives the size and lines with the prefecture dropped and with the building on two lines (it does not decide what may be dropped); `asIs` is how many characters spill out when written unbroken at 5 mm. `kind: "amount"` writes 30000 / 3万 / 30,000円 in formal numerals (daiji) as 金参萬円 (1–99,999,999; 圓, 也 and pre-printed 金/円 supported); `name` breaks only at spaces; `plain` takes any text | `text`, `width`, `height` (mm), `orientation?` (`vertical` default / `horizontal`), `kind?` (`address` default / `name` / `amount` / `plain`), `postalCode?`, `numerals?`, `thousandChar?` (阡 default / 千 / 仟), `yenChar?` (円 / 圓), `nari?`, `kinEnPrinted?`, `lang?` |
|
|
93
93
|
| `invoice_nebiki_check` | For a freelancer in Japan who is **not a registered invoice issuer** and is asked for a price cut (same logic as tools.first-ch.com/invoice-nebiki/). From three answers — the client's consumption tax `method` (`general` / `simplified` / `niwari` 20% rule / `sanwari` 30% rule / `exempt` / `unknown`), `party` (`individual` / `corporation`, required for the special rules) and `small` (is one invoice under ¥10,000 incl. tax) — returns `rows` per period from `today`: `diff` (monthly difference = amount × 10/110 × 20/30/50/70/100%, rounded down), `none` or `check`. The 20% rule gives no difference to 2026 for sole proprietors and to the tax period including Sep 30, 2026 for corporations; the 30% rule covers sole proprietors' 2027–2028 only; after that `recheck: true` (no assumption of simplified taxation). Purchases that may fall under the small-amount rule (to Sep 30, 2029) are `check`. Optional `monthly`, `cutRate` / `cutAmount` add a comparison; `message` asks only the open points (`format: "md"` for Markdown) and always carries the four assumptions; `showAmount: false` hides yen amounts. |
|
|
94
|
+
| `reply_check` | Checks an AI-drafted reply against the email it answers before you send it (same logic as tools.first-ch.com/okurumae/). From `reply` it picks up **dates, weekdays, times, amounts, quantities (guests, nights, %), phone numbers, emails, URLs, names** (〇〇様, Dear Ms. …) and other numbers; those found in neither `received` nor your optional `facts` (hours, prices, dates) are `red` (`missing`), matches are `green` with the matching spots in `hits`, and leftover placeholders (`[Customer 1]`, 〇〇, XX, 【】, `{name}`) are `yellow`. A weekday that does not fit the date (e.g. Friday, November 8 in 2026) or a date that does not exist is `red` too (`weekday` / `nodate`, with the actual weekday). Dates without a year are checked in the year that falls between 60 days before and 305 days after `today`. Full-/half-width forms, commas, 18時30分 vs 18:30 and 3千円 vs 3,000円 are aligned for matching only — the text is never rewritten, and `start`/`end`/`line`/`column` point into `reply` as written. `count` covers every item; `items` stops at 500 (`truncated`). A `note` always says that 0 red does not mean the reply is correct. No auto-fix, no tone editing. Up to 20,000 characters per field | `reply`, `received?`, `facts?`, `today?` (YYYY-MM-DD), `includeGreen?` (default true), `lang?` (`ja` default / `en`) |
|
|
95
|
+
| `comfy_png_leak_scan` | Checks a ComfyUI PNG you received or posted for **API key formats** (Google `AIza`, OpenAI-style `sk-`, Anthropic `sk-ant-`, Hugging Face `hf_`, Replicate `r8_`) in its embedded data (same logic as tools.first-ch.com/en/comfy-key-leak/). Chunks are read in order with CRC checks; tEXt and uncompressed iTXt are searched. `status` is `found`, `none` (not a claim that the image is safe), `unchecked` (zTXt, compressed iTXt, eXIf, caBX, unknown chunks, data after IEND, over 30 MB) or `failed` (CRC mismatch, truncated, not a PNG). Each finding gives the place — node ID, `classType` and `input` from prompt, or node ID and `widgetIndex` when only a workflow exists (`fieldUnknown`) — plus flags for duplicate JSON keys, items outside inputs and bypassed/muted nodes. Node titles are not used. **Values are never returned**: only `masked` (first 4 characters) and `length`. `notice` is a heads-up message for the key owner (no values or file name; states that validity and cause were not checked) and `revoke` lists the official pages to disable each key type. With `outPath` it writes a copy without tEXt/iTXt/zTXt after re-reading it (0 text chunks, kept chunks byte-identical); the original is never changed, caBX (C2PA) PNGs are not rewritten. It does not test keys or fetch URLs, and sends nothing itself. Prefer `path`: with `base64` the image bytes (including any raw key) go into the AI conversation and to the model provider, and the result carries an `inputNote` saying so | `path` (absolute) or `base64`, `outPath?`, `overwrite?`, `includeUrl?`, `lang?` |
|
|
94
96
|
|
|
95
97
|
### App tools (`app_*`, sent to apps.first-ch.com)
|
|
96
98
|
|
|
@@ -280,6 +282,8 @@ claude mcp add firstch-tools -- npx -y @first-ch/tools-mcp
|
|
|
280
282
|
| `wiki_doc_lint` | Notion・Backlog Wiki・Confluence などから書き出した社内文書(Markdown / HTML / テキスト)を点検する(tools.first-ch.com/wiki-doc-lint/ と同一ロジック)。**内容がほぼ同じページの組**(`duplicates`: 記号と空白を除いた本文の4文字単位の断片の Jaccard 係数が `threshold` 以上の組・それぞれにしかない行・被リンクの多い方〔同数なら本文が長い方〕を残す修正案)、**ほかのどのページからもリンクされていない孤立ページ**(`orphans`: Notion 型の親ページか目次ページに足すリンクの1行 `addLine` つき。index・README・home などの目次ページは `entryPages=false` にしない限り数えない)、**表記ゆれ・旧称**(`terms`: 「揃える表記 ← ゆれ」の辞書〔`dictionary` は既定の辞書に足す〕と、辞書に無いカタカナ語の語末の長音ゆれ〔多い方に揃える案〕。各箇所の行番号と修正前後の文)、**リンク切れ**(`broken`: 文書の拡張子を持つ相対リンクと `[[ページ名]]` のうち行き先が無いもの)、修正案をまとめた Markdown の `report` を返す。リンクは `[文字](パス)`・`[[ページ名]]`・a タグを読み、相対パス・ページ名・Notion のIDつきファイル名・Notion/Confluence のURL末尾のページ名で照合する。コードブロック・インラインコード・URL・タグは表記ゆれの対象外で、語の途中(ユーザビリティの中のユーザ)は拾わない。`paths`(ファイル・フォルダーの絶対パス。サブフォルダーまで読み、隠しフォルダーと node_modules は飛ばす)か `files` を渡す。UTF-8・Shift_JIS・UTF-16(BOM)を自動判別し、3,000ファイル・合計60MBまで。ファイルは読むだけで書き換えない | `paths?` または `files?`(`[{ path, text }]`)、`threshold?`(0.5〜1・既定 0.8)、`dictionary?`、`useDefaultDictionary?`、`autoChoon?`、`entryPages?`、`format?`(既定 `both` / `json` / `markdown`)、`lang?`(既定 `ja` / `en`) |
|
|
281
283
|
| `fit_to_box` | 印刷済みの記入欄(市販の中袋〔ご祝儀袋・香典袋〕の「住所」「金額」「氏名」の欄など)に手で書くとき、欄の幅・高さ(mm)と向きから、収まる1字の大きさ(mm・0.1mm単位で切り捨て)・行数・改行した後の各行を返す(tools.first-ch.com/nakabukuro-ran/ と同一ロジック)。欄の線から内側へ1.5mmずつ余白を取り、行間を字の0.3倍として、行の長さと行数の両方から決める(横書きの半角英数は0.6字分・上限は住所9mm・金額と氏名14mm)。`kind: "address"` は「〜番地」と「建物名・部屋番号」の境目で改行し、そこで4mmに届かないときだけ都道府県・市区町村の後や番地の前でも区切る(「12番地の18」「1203号室」など数字の並びの途中では切らない・`text` の改行は建物名の前として扱う・最大4行)。`postalCode` で「〒」の行を先頭に足し、縦書きの欄では番地を漢数字にする(`numerals`: `digits`=一〇型 / `tens`=十型)。1字が4mm未満なら `alternatives` に「都道府県を省いた場合」「建物名を2行にした場合」の大きさと行を返す(省いてよいかは判断しない)。`asIs` は改行せずに1字5mmで書いたときにはみ出す字数。`kind: "amount"` は 30000・3万・30,000円 を大字の「金参萬円」にして欄に合わせる(1〜99,999,999円・圓/也/「金」「円」が印刷済みに対応)。`name` は空白でだけ改行し、`plain` は任意の文字列 | `text`、`width`・`height`(mm)、`orientation?`(既定 `vertical` / `horizontal`)、`kind?`(既定 `address` / `name` / `amount` / `plain`)、`postalCode?`、`numerals?`、`thousandChar?`(既定 阡 / 千 / 仟)、`yenChar?`(円 / 圓)、`nari?`、`kinEnPrinted?`、`lang?` |
|
|
282
284
|
| `invoice_nebiki_check` | インボイス未登録のまま取引先から値下げを求められた個人の制作者向け(tools.first-ch.com/invoice-nebiki/ と同一ロジック)。取引先の申告方式 `method`(`general` 一般課税・`simplified` 簡易課税・`niwari` 2割特例・`sanwari` 3割特例・`exempt` 免税・`unknown`)、`party`(個人・法人。特例では必須)、`small`(1回の請求が税込1万円未満か)の3問から、`today` を含む時期以降を `diff`(差あり・月額=税込×10/110×20/30/50/70/100% の1円未満切り捨て)・`none`(差なし)・`check`(要確認)で返す。2割特例は個人2026年分・法人は2026年9月30日を含む課税期間まで、3割特例は個人の2027・2028年分だけで、期限後は `recheck: true`(簡易課税へ移ったとは仮定しない)。少額特例(2029年9月30日まで)が効きうる取引は要確認。任意の `monthly`・`cutRate`/`cutAmount` で値下げと比べ、`message` は要確認の点だけを尋ねる確認文(前提4点つき・`format: "md"` で Markdown)。`showAmount: false` で金額を出さない。 |
|
|
285
|
+
| `reply_check` | 届いたメール(`received`)と任意の「自分で決めた事実」(`facts`:営業時間・料金・日程など)を、AI が書いた返信案(`reply`)と照らし合わせる(tools.first-ch.com/okurumae/ と同一ロジック)。返信案の**日付・曜日・時刻・金額・数量(〇名・〇泊・%)・電話番号・メールアドレス・URL・宛名(〇〇様・Dear Ms. …)・番号**のうち、原文のどちらにも無いものを `red`(`missing`)、あるものを `green`(一致した箇所は `hits`)、`[お客様1]`・〇〇・XX・【】・`{name}` などの消し忘れを `yellow` で返す。日付と曜日の食い違い(例: 2026年の11月8日(金))と存在しない日付も `red`(`weekday` / `nodate`・実際の曜日つき)。年の無い日付は `today` の60日前〜305日後に入る年で確かめる。全角/半角・カンマ・「18時30分」と「18:30」・「3千円」と「3,000円」は照合のときだけそろえ、本文は書き換えない(`start`/`end`/`line`/`column` は元の返信案の位置)。`count` は全件、`items` は500件まで(`truncated`)。「赤が0件でも内容の正しさは保証しない」注意(`note`)を常に付ける。自動修正・文体の添削はしない。各欄2万字まで | `reply`、`received?`、`facts?`、`today?`(YYYY-MM-DD)、`includeGreen?`(既定 true)、`lang?`(既定 `ja` / `en`) |
|
|
286
|
+
| `comfy_png_leak_scan` | 受け取った・投稿した ComfyUI の PNG の埋め込みデータから **APIキーの形**(Google の `AIza`・OpenAI などの `sk-`・Anthropic の `sk-ant-`・Hugging Face の `hf_`・Replicate の `r8_`)を探す(tools.first-ch.com/comfy-key-leak/ と同一ロジック)。チャンクを順に読んで CRC を確かめ、tEXt と非圧縮の iTXt を調べる。`status` は `found`・`none`(安全という意味ではない)・`unchecked`(zTXt・圧縮 iTXt・eXIf・caBX・不明なチャンク・IEND の後ろ・30MB超)・`failed`(CRC 不一致・途中で切れた・PNG でない)。場所は prompt ならノードID・`classType`・`input`、workflow だけならノードIDと `widgetIndex`(`fieldUnknown`)で、JSON の重複キー・inputs の外の項目・迂回/無効のノードの印つき。ノードの表示名は使わない。**値は返さない**(`masked`=先頭4字と `length` だけ)。`notice` はキーの持ち主へのお知らせ文(値・ファイル名なし、有効性と原因は確認していないと書く)、`revoke` は種類ごとの公式の無効化画面。`outPath` で tEXt・iTXt・zTXt を抜いたコピーを、読み直して確かめてから書く(元は変えない・caBX 付きは書き換えない)。キーの有効性の確認・URL の取得はしない(ツール自体は何も送らない)。入力は `path` を優先する: `base64` だと画像のバイト列(生のキーを含む)が AI との会話に載りモデルの提供元へ渡るため、返り値の `inputNote` でそれを伝える | `path`(絶対パス)か `base64`、`outPath?`、`overwrite?`、`includeUrl?`、`lang?` |
|
|
283
287
|
|
|
284
288
|
#### apps のツール(`app_*`・apps.first-ch.com へ送信)
|
|
285
289
|
|
|
@@ -0,0 +1,575 @@
|
|
|
1
|
+
/* 受け取ったComfyUI画像のキー点検(comfy_png_leak_scan)
|
|
2
|
+
* 解析のコアは FirstCHTools の site/comfy-key-leak/lib.mjs と同一
|
|
3
|
+
* (2箇所ルール: site側が正本・片方を直したらもう片方も同じ内容で反映する)。
|
|
4
|
+
* 両ファイルの「ここからコア」〜「ここまでコア」はバイト一致する(どちらも ES module):
|
|
5
|
+
* diff <(sed -n '/^\/\/ ===== ここから/,/^\/\/ ===== ここまで/p' site/comfy-key-leak/lib.mjs) <(sed -n '/^\/\/ ===== ここから/,/^\/\/ ===== ここまで/p' comfy-png-leak.mjs)
|
|
6
|
+
*
|
|
7
|
+
* ComfyUI の PNG のチャンクを順に読み、CRC を確かめ、tEXt と非圧縮の iTXt の文字列から APIキーの形(AIza・sk-・sk-ant-・hf_・r8_)を探す。
|
|
8
|
+
* prompt ならノードID・class_type・inputs の名前、workflow だけならノードIDと widgets_values の何番目かを返す。値は先頭4字だけを残して伏せ、元の値は返さない。
|
|
9
|
+
* キーが有効かどうかは確かめない。完全ローカル処理・ネットワーク送信なし。 */
|
|
10
|
+
|
|
11
|
+
import { readFile, stat } from 'node:fs/promises';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import { writeOutput } from './fs-safe.mjs';
|
|
14
|
+
|
|
15
|
+
// ===== ここからコア =====
|
|
16
|
+
export const MAX_BYTES = 30 * 1024 * 1024; // これを超える PNG は読まずに「未検査」
|
|
17
|
+
const SIG = [137, 80, 78, 71, 13, 10, 26, 10];
|
|
18
|
+
const TEXT_TYPES = ['tEXt', 'iTXt', 'zTXt'];
|
|
19
|
+
// 中身に文字列を持たない(キーが入りようのない)既知のチャンク。これ以外の補助チャンクは形だけ探して「未検査」に数える
|
|
20
|
+
const BINARY_TYPES = ['IHDR', 'PLTE', 'IDAT', 'IEND', 'tRNS', 'cHRM', 'gAMA', 'iCCP', 'sBIT', 'sRGB', 'cICP', 'mDCV', 'cLLI', 'bKGD', 'hIST', 'pHYs', 'sPLT', 'tIME', 'acTL', 'fcTL', 'fdAT', 'oFFs', 'pCAL', 'sCAL', 'sTER', 'dSIG', 'gIFg', 'gIFx', 'vpAg', 'iDOT', 'orNT'];
|
|
21
|
+
|
|
22
|
+
// キーの形。sk-ant- は sk- より先に見る。前に英数字・_・- が続く場合(task- など)は拾わない
|
|
23
|
+
export const KINDS = {
|
|
24
|
+
anthropic: { prefix: 'sk-ant-', re: 'sk-ant-[A-Za-z0-9_-]{20,}' },
|
|
25
|
+
openai: { prefix: 'sk-', re: 'sk-[A-Za-z0-9_-]{20,}' },
|
|
26
|
+
google: { prefix: 'AIza', re: 'AIza[A-Za-z0-9_-]{35}' },
|
|
27
|
+
huggingface: { prefix: 'hf_', re: 'hf_[A-Za-z0-9]{30,}' },
|
|
28
|
+
replicate: { prefix: 'r8_', re: 'r8_[A-Za-z0-9]{30,}' },
|
|
29
|
+
};
|
|
30
|
+
const KIND_ORDER = ['anthropic', 'openai', 'google', 'huggingface', 'replicate'];
|
|
31
|
+
function keyRe() {
|
|
32
|
+
return new RegExp('(?<![A-Za-z0-9_-])(?:' + KIND_ORDER.map((k) => '(' + KINDS[k].re + ')').join('|') + ')', 'g');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// 各サービスの公式の無効化(削除・作り直し)画面
|
|
36
|
+
export const REVOKE = {
|
|
37
|
+
google: [
|
|
38
|
+
{ ja: 'Google Cloud コンソールの「認証情報」', en: 'Google Cloud console – Credentials', url: 'https://console.cloud.google.com/apis/credentials' },
|
|
39
|
+
{ ja: 'Google AI Studio の API キー', en: 'Google AI Studio – API keys', url: 'https://aistudio.google.com/app/apikey' },
|
|
40
|
+
],
|
|
41
|
+
openai: [{ ja: 'OpenAI の API keys', en: 'OpenAI – API keys', url: 'https://platform.openai.com/api-keys' }],
|
|
42
|
+
anthropic: [{ ja: 'Anthropic Console の API Keys', en: 'Anthropic Console – API keys', url: 'https://console.anthropic.com/settings/keys' }],
|
|
43
|
+
huggingface: [{ ja: 'Hugging Face の Access Tokens', en: 'Hugging Face – Access tokens', url: 'https://huggingface.co/settings/tokens' }],
|
|
44
|
+
replicate: [{ ja: 'Replicate の API tokens', en: 'Replicate – API tokens', url: 'https://replicate.com/account/api-tokens' }],
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
export const KIND_LABEL = {
|
|
48
|
+
ja: { google: 'Google の API キーの形', openai: 'OpenAI などの API キーの形', anthropic: 'Anthropic の API キーの形', huggingface: 'Hugging Face のトークンの形', replicate: 'Replicate のトークンの形' },
|
|
49
|
+
en: { google: 'Google API key format', openai: 'OpenAI-style API key format', anthropic: 'Anthropic API key format', huggingface: 'Hugging Face token format', replicate: 'Replicate token format' },
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
// ---- CRC-32(PNG の各チャンクの検査値) ----
|
|
53
|
+
let CRC_TABLE = null;
|
|
54
|
+
export function crc32(bytes, start = 0, end = bytes.length) {
|
|
55
|
+
if (!CRC_TABLE) {
|
|
56
|
+
CRC_TABLE = new Uint32Array(256);
|
|
57
|
+
for (let n = 0; n < 256; n++) {
|
|
58
|
+
let c = n;
|
|
59
|
+
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
|
60
|
+
CRC_TABLE[n] = c >>> 0;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
let c = 0xffffffff;
|
|
64
|
+
for (let i = start; i < end; i++) c = CRC_TABLE[(c ^ bytes[i]) & 0xff] ^ (c >>> 8);
|
|
65
|
+
return (c ^ 0xffffffff) >>> 0;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function u32(b, i) { return ((b[i] << 24) | (b[i + 1] << 16) | (b[i + 2] << 8) | b[i + 3]) >>> 0; }
|
|
69
|
+
function typeOf(b, i) { return String.fromCharCode(b[i], b[i + 1], b[i + 2], b[i + 3]); }
|
|
70
|
+
function latin1(b, s, e) { let o = ''; for (let i = s; i < e; i++) o += String.fromCharCode(b[i]); return o; }
|
|
71
|
+
function utf8(b, s, e, fallback) {
|
|
72
|
+
try { return new TextDecoder('utf-8', { fatal: true }).decode(b.subarray(s, e)); } catch (_) { return fallback ? latin1(b, s, e) : null; }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// 先頭の数バイトで形式を見分ける(PNG でないときの案内に使う)
|
|
76
|
+
export function sniff(b) {
|
|
77
|
+
if (b.length >= 8 && SIG.every((v, i) => b[i] === v)) return 'png';
|
|
78
|
+
if (b.length >= 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return 'jpeg';
|
|
79
|
+
if (b.length >= 12 && latin1(b, 0, 4) === 'RIFF' && latin1(b, 8, 12) === 'WEBP') return 'webp';
|
|
80
|
+
if (b.length >= 6 && /^GIF8[79]a$/.test(latin1(b, 0, 6))) return 'gif';
|
|
81
|
+
if (b.length >= 12 && latin1(b, 4, 8) === 'ftyp') return 'heif';
|
|
82
|
+
return 'other';
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// チャンクを順に読む。壊れていれば { error } を返す(どこまで読めたかは chunks に残す)
|
|
86
|
+
export function readChunks(b) {
|
|
87
|
+
const chunks = [];
|
|
88
|
+
if (sniff(b) !== 'png') return { chunks, error: 'NOT_PNG' };
|
|
89
|
+
let i = 8, sawEnd = false;
|
|
90
|
+
while (i < b.length) {
|
|
91
|
+
if (i + 12 > b.length) return { chunks, error: 'TRUNCATED', at: i };
|
|
92
|
+
const len = u32(b, i), type = typeOf(b, i + 4);
|
|
93
|
+
if (!/^[A-Za-z]{4}$/.test(type)) return { chunks, error: 'BAD_TYPE', at: i };
|
|
94
|
+
if (len > 0x7fffffff || i + 12 + len > b.length) return { chunks, error: 'TRUNCATED', at: i };
|
|
95
|
+
const crc = u32(b, i + 8 + len);
|
|
96
|
+
if (crc32(b, i + 4, i + 8 + len) !== crc) return { chunks, error: 'CRC', at: i, type };
|
|
97
|
+
chunks.push({ type, offset: i, length: len, dataStart: i + 8, dataEnd: i + 8 + len, end: i + 12 + len });
|
|
98
|
+
i += 12 + len;
|
|
99
|
+
if (type === 'IEND') { sawEnd = true; break; }
|
|
100
|
+
}
|
|
101
|
+
if (!chunks.length || chunks[0].type !== 'IHDR') return { chunks, error: 'NO_IHDR' };
|
|
102
|
+
if (!sawEnd) return { chunks, error: 'NO_IEND' };
|
|
103
|
+
return { chunks, error: null, trailing: b.length - i, trailingStart: i };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// ---- JSON を、同じ名前の項目も捨てずに読む(値ごとに元の文字列の中の位置を持つ) ----
|
|
107
|
+
function parseJsonAst(s) {
|
|
108
|
+
let i = 0, depth = 0;
|
|
109
|
+
const ws = () => { while (i < s.length && (s[i] === ' ' || s[i] === '\t' || s[i] === '\n' || s[i] === '\r')) i++; };
|
|
110
|
+
const fail = () => { throw new Error('json'); };
|
|
111
|
+
function str() {
|
|
112
|
+
const start = i; i++;
|
|
113
|
+
let out = '';
|
|
114
|
+
for (;;) {
|
|
115
|
+
if (i >= s.length) fail();
|
|
116
|
+
const c = s[i];
|
|
117
|
+
if (c === '"') { i++; break; }
|
|
118
|
+
if (c === '\\') {
|
|
119
|
+
const e = s[i + 1];
|
|
120
|
+
if (e === 'u') { const h = s.slice(i + 2, i + 6); if (!/^[0-9a-fA-F]{4}$/.test(h)) fail(); out += String.fromCharCode(parseInt(h, 16)); i += 6; continue; }
|
|
121
|
+
const m = { '"': '"', '\\': '\\', '/': '/', b: '\b', f: '\f', n: '\n', r: '\r', t: '\t' }[e];
|
|
122
|
+
if (m === undefined) fail();
|
|
123
|
+
out += m; i += 2; continue;
|
|
124
|
+
}
|
|
125
|
+
out += c; i++;
|
|
126
|
+
}
|
|
127
|
+
return { t: 'str', v: out, start, end: i };
|
|
128
|
+
}
|
|
129
|
+
function val() {
|
|
130
|
+
ws();
|
|
131
|
+
const c = s[i];
|
|
132
|
+
if (c === '{') {
|
|
133
|
+
if (++depth > 400) fail();
|
|
134
|
+
const node = { t: 'obj', entries: [], start: i }; i++; ws();
|
|
135
|
+
if (s[i] === '}') { i++; depth--; node.end = i; return node; }
|
|
136
|
+
for (;;) {
|
|
137
|
+
ws(); if (s[i] !== '"') fail();
|
|
138
|
+
const k = str(); ws(); if (s[i] !== ':') fail(); i++;
|
|
139
|
+
node.entries.push([k, val()]); ws();
|
|
140
|
+
if (s[i] === ',') { i++; continue; }
|
|
141
|
+
if (s[i] === '}') { i++; break; }
|
|
142
|
+
fail();
|
|
143
|
+
}
|
|
144
|
+
depth--; node.end = i; return node;
|
|
145
|
+
}
|
|
146
|
+
if (c === '[') {
|
|
147
|
+
if (++depth > 400) fail();
|
|
148
|
+
const node = { t: 'arr', items: [], start: i }; i++; ws();
|
|
149
|
+
if (s[i] === ']') { i++; depth--; node.end = i; return node; }
|
|
150
|
+
for (;;) {
|
|
151
|
+
node.items.push(val()); ws();
|
|
152
|
+
if (s[i] === ',') { i++; continue; }
|
|
153
|
+
if (s[i] === ']') { i++; break; }
|
|
154
|
+
fail();
|
|
155
|
+
}
|
|
156
|
+
depth--; node.end = i; return node;
|
|
157
|
+
}
|
|
158
|
+
if (c === '"') return str();
|
|
159
|
+
const m = /^(?:-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null)/.exec(s.slice(i, i + 400));
|
|
160
|
+
if (!m) fail();
|
|
161
|
+
const start = i; i += m[0].length;
|
|
162
|
+
return { t: 'lit', v: m[0], start, end: i };
|
|
163
|
+
}
|
|
164
|
+
const root = val(); ws();
|
|
165
|
+
if (i !== s.length) fail();
|
|
166
|
+
return root;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function scalarOf(node) {
|
|
170
|
+
if (!node) return null;
|
|
171
|
+
if (node.t === 'str') return node.v;
|
|
172
|
+
if (node.t === 'lit') return node.v;
|
|
173
|
+
return null;
|
|
174
|
+
}
|
|
175
|
+
function entriesNamed(obj, name) { return obj && obj.t === 'obj' ? obj.entries.filter(([k]) => k.v === name).map(([, v]) => v) : []; }
|
|
176
|
+
|
|
177
|
+
// JSON の形から ComfyUI のどちらの形式かを見分ける(チャンクの名前は書き換えられるので形で見る)
|
|
178
|
+
function shapeOf(root) {
|
|
179
|
+
if (!root || root.t !== 'obj') return 'json';
|
|
180
|
+
if (entriesNamed(root, 'nodes').some((v) => v.t === 'arr')) return 'workflow';
|
|
181
|
+
const objs = root.entries.filter(([, v]) => v.t === 'obj');
|
|
182
|
+
if (objs.length && objs.some(([, v]) => entriesNamed(v, 'class_type').length)) return 'prompt';
|
|
183
|
+
return 'json';
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function maskText(s) { return String(s).replace(keyRe(), (v) => maskValue(v)); }
|
|
187
|
+
function seg(s) { s = maskText(s); return s.length > 40 ? s.slice(0, 39) + '…' : s; }
|
|
188
|
+
|
|
189
|
+
export function maskValue(v) {
|
|
190
|
+
v = String(v);
|
|
191
|
+
return v.slice(0, 4) + '•'.repeat(Math.max(0, Math.min(v.length - 4, 12)));
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// 文字列の値(と項目名)を辿り、キーの形が見つかったら場所をつけて返す
|
|
195
|
+
function walk(root, shape, push) {
|
|
196
|
+
const stack = []; // { node, key }(key は親の中での名前か番号)
|
|
197
|
+
function visit(node, key, isKey) {
|
|
198
|
+
if (node.t === 'str') { push(node.v, locate(shape, stack, key, isKey), node); return; }
|
|
199
|
+
stack.push({ node, key });
|
|
200
|
+
if (node.t === 'obj') for (const [k, v] of node.entries) { visit(k, k.v, true); visit(v, k.v, false); }
|
|
201
|
+
else if (node.t === 'arr') node.items.forEach((v, n) => visit(v, n, false));
|
|
202
|
+
stack.pop();
|
|
203
|
+
}
|
|
204
|
+
visit(root, null, false);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function locate(shape, stack, key, isKey) {
|
|
208
|
+
// stack[0] が根。path は根から見た名前・番号の並び(最後が値の位置)
|
|
209
|
+
const path = stack.slice(1).map((f) => f.key).concat([key]);
|
|
210
|
+
const dupKey = stack.some((f, n) => {
|
|
211
|
+
if (f.node.t !== 'obj') return false;
|
|
212
|
+
const name = n + 1 < stack.length ? stack[n + 1].key : key;
|
|
213
|
+
return typeof name === 'string' && f.node.entries.filter(([k]) => k.v === name).length > 1;
|
|
214
|
+
});
|
|
215
|
+
const loc = { shape, path: path.map((p) => typeof p === 'number' ? p : seg(p)), isKey: !!isKey, dupKey };
|
|
216
|
+
if (shape === 'prompt' && stack.length >= 2 && stack[1].node.t === 'obj') {
|
|
217
|
+
const node = stack[1].node;
|
|
218
|
+
loc.nodeId = seg(path[0]);
|
|
219
|
+
loc.classType = [...new Set(entriesNamed(node, 'class_type').map(scalarOf).filter((v) => v != null).map(seg))];
|
|
220
|
+
if (path[1] === 'inputs' && path.length >= 3 && !(path.length === 3 && isKey)) {
|
|
221
|
+
loc.input = seg(path[2]);
|
|
222
|
+
if (path.length > 3) loc.inputPath = path.slice(3).map((p) => typeof p === 'number' ? p : seg(p));
|
|
223
|
+
} else loc.extra = true;
|
|
224
|
+
return loc;
|
|
225
|
+
}
|
|
226
|
+
if (shape === 'workflow') {
|
|
227
|
+
// いちばん内側の「nodes 配列の要素」をノードとみなす(サブグラフの定義の中のノードも同じ)
|
|
228
|
+
for (let n = stack.length - 1; n >= 2; n--) {
|
|
229
|
+
const arr = stack[n - 1], el = stack[n];
|
|
230
|
+
if (arr.node.t === 'arr' && el.node.t === 'obj' && typeof arr.key === 'string' && arr.key === 'nodes' && n - 1 >= 1 && stack[n - 2].node.t === 'obj') {
|
|
231
|
+
const node = el.node;
|
|
232
|
+
const id = entriesNamed(node, 'id').map(scalarOf).find((v) => v != null);
|
|
233
|
+
loc.nodeId = id == null ? null : seg(id);
|
|
234
|
+
const mode = entriesNamed(node, 'mode').map(scalarOf).find((v) => v != null);
|
|
235
|
+
if (mode === '4') loc.bypassed = true;
|
|
236
|
+
if (mode === '2') loc.muted = true;
|
|
237
|
+
const rest = stack.slice(n + 1).map((f) => f.key).concat([key]);
|
|
238
|
+
if (n >= 3) loc.inSubgraph = stack.slice(1, n - 1).some((f) => f.key === 'subgraphs' || f.key === 'definitions');
|
|
239
|
+
if (rest[0] === 'widgets_values' && rest.length >= 2 && !(rest.length === 2 && isKey)) {
|
|
240
|
+
if (typeof rest[1] === 'number') loc.widgetIndex = rest[1];
|
|
241
|
+
else loc.widgetKey = seg(rest[1]);
|
|
242
|
+
loc.fieldUnknown = true;
|
|
243
|
+
} else { loc.extra = true; loc.rest = rest.map((p) => typeof p === 'number' ? p : seg(p)); }
|
|
244
|
+
return loc;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
loc.extra = true;
|
|
248
|
+
return loc;
|
|
249
|
+
}
|
|
250
|
+
return loc;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function scanText(text, chunkInfo, findings) {
|
|
254
|
+
let root = null;
|
|
255
|
+
const t = text.trim();
|
|
256
|
+
if (t[0] === '{' || t[0] === '[') { try { root = parseJsonAst(text); } catch (_) { root = null; } }
|
|
257
|
+
const covered = [];
|
|
258
|
+
const add = (value, kind, loc) => {
|
|
259
|
+
findings.push({ kind, prefix: KINDS[kind].prefix, masked: maskValue(value), length: value.length, chunk: chunkInfo, ...loc });
|
|
260
|
+
};
|
|
261
|
+
const matchAll = (s, cb) => {
|
|
262
|
+
const re = keyRe(); let m;
|
|
263
|
+
while ((m = re.exec(s))) {
|
|
264
|
+
const n = m.slice(1).findIndex((x) => x !== undefined);
|
|
265
|
+
cb(m[0], KIND_ORDER[n], m.index);
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
if (root) {
|
|
269
|
+
const shape = shapeOf(root);
|
|
270
|
+
walk(root, shape, (s, loc, node) => {
|
|
271
|
+
covered.push([node.start, node.end]);
|
|
272
|
+
matchAll(s, (v, kind) => add(v, kind, loc));
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
// JSON として読めない文字列・文字列の外(書き損じた JSON など)は、文字列全体で探す
|
|
276
|
+
matchAll(text, (v, kind, at) => {
|
|
277
|
+
if (covered.some(([a, b]) => at >= a && at < b)) return;
|
|
278
|
+
add(v, kind, { shape: root ? 'json-outside' : 'text', path: [] });
|
|
279
|
+
});
|
|
280
|
+
return root ? shapeOf(root) : 'text';
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** PNG のバイト列を点検する。返り値に元の値は入らない(先頭4字と長さだけ) */
|
|
284
|
+
export function scanPng(bytes) {
|
|
285
|
+
const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
|
|
286
|
+
const res = { status: 'none', reason: null, format: sniff(b), size: b.length, chunks: [], findings: [], unchecked: [], hasCaBX: false, hasExif: false, canStrip: false, kinds: [], textChunks: 0, trailing: 0 };
|
|
287
|
+
if (b.length > MAX_BYTES) { res.status = 'unchecked'; res.reason = 'TOO_LARGE'; res.unchecked.push({ type: '*', why: 'TOO_LARGE' }); return res; }
|
|
288
|
+
const rc = readChunks(b);
|
|
289
|
+
if (rc.error) {
|
|
290
|
+
res.status = 'failed'; res.reason = rc.error;
|
|
291
|
+
if (rc.type) res.badChunk = rc.type;
|
|
292
|
+
return res;
|
|
293
|
+
}
|
|
294
|
+
for (const c of rc.chunks) {
|
|
295
|
+
const info = { type: c.type, length: c.length, offset: c.offset, checked: true };
|
|
296
|
+
if (c.type === 'tEXt' || c.type === 'iTXt' || c.type === 'zTXt') {
|
|
297
|
+
res.textChunks++;
|
|
298
|
+
const d = b.subarray(c.dataStart, c.dataEnd);
|
|
299
|
+
const z = d.indexOf(0);
|
|
300
|
+
info.keyword = seg(latin1(d, 0, z < 0 ? Math.min(d.length, 79) : z));
|
|
301
|
+
if (z < 0) { info.checked = false; info.why = 'MALFORMED'; }
|
|
302
|
+
else if (c.type === 'zTXt') { info.checked = false; info.why = 'COMPRESSED'; }
|
|
303
|
+
else if (c.type === 'tEXt') {
|
|
304
|
+
const text = utf8(d, z + 1, d.length, true);
|
|
305
|
+
info.shape = scanText(text, { type: c.type, keyword: info.keyword }, res.findings);
|
|
306
|
+
} else {
|
|
307
|
+
// iTXt: keyword \0 圧縮フラグ 圧縮方式 言語タグ \0 翻訳キーワード \0 本文(UTF-8)
|
|
308
|
+
const flag = d[z + 1];
|
|
309
|
+
const l1 = d.indexOf(0, z + 3), l2 = l1 < 0 ? -1 : d.indexOf(0, l1 + 1);
|
|
310
|
+
if (flag === 1) { info.checked = false; info.why = 'COMPRESSED'; }
|
|
311
|
+
else if (flag !== 0 || l2 < 0) { info.checked = false; info.why = 'MALFORMED'; }
|
|
312
|
+
else {
|
|
313
|
+
const text = utf8(d, l2 + 1, d.length, true);
|
|
314
|
+
info.shape = scanText(text, { type: c.type, keyword: info.keyword }, res.findings);
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
} else if (!BINARY_TYPES.includes(c.type)) {
|
|
318
|
+
// eXIf・caBX(C2PA)・名前の分からないチャンクは構造を読まない。形だけは探すが、検査したとは言わない
|
|
319
|
+
if (c.type === 'eXIf') res.hasExif = true;
|
|
320
|
+
if (c.type === 'caBX') res.hasCaBX = true;
|
|
321
|
+
info.checked = false; info.why = c.type === 'eXIf' ? 'EXIF' : c.type === 'caBX' ? 'C2PA' : 'UNKNOWN_CHUNK';
|
|
322
|
+
scanText(latin1(b, c.dataStart, c.dataEnd), { type: c.type, keyword: null }, res.findings);
|
|
323
|
+
}
|
|
324
|
+
if (!info.checked) res.unchecked.push({ type: c.type, keyword: info.keyword || null, why: info.why });
|
|
325
|
+
res.chunks.push(info);
|
|
326
|
+
}
|
|
327
|
+
if (rc.trailing > 0) {
|
|
328
|
+
res.trailing = rc.trailing;
|
|
329
|
+
res.unchecked.push({ type: 'IEND+', why: 'TRAILING' });
|
|
330
|
+
scanText(latin1(b, rc.trailingStart, b.length), { type: 'IEND+', keyword: null }, res.findings);
|
|
331
|
+
}
|
|
332
|
+
res.kinds = KIND_ORDER.filter((k) => res.findings.some((f) => f.kind === k));
|
|
333
|
+
res.status = res.findings.length ? 'found' : res.unchecked.length ? 'unchecked' : 'none';
|
|
334
|
+
res.canStrip = !res.hasCaBX && res.textChunks > 0;
|
|
335
|
+
return res;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** 場所を1行の文にする(お知らせ文と画面で同じ言い方を使う) */
|
|
339
|
+
export function placeText(f, lang = 'ja') {
|
|
340
|
+
const ja = lang !== 'en';
|
|
341
|
+
const ct = f.classType && f.classType.length ? f.classType.join(' / ') : null;
|
|
342
|
+
const node = f.nodeId != null ? (ja ? 'ノードID ' + f.nodeId : 'node ID ' + f.nodeId) : null;
|
|
343
|
+
const p = (arr) => arr.map((x) => typeof x === 'number' ? '[' + x + ']' : x).join(' › ');
|
|
344
|
+
if (f.shape === 'prompt' && node) {
|
|
345
|
+
const head = node + (ct ? (ja ? '(' + ct + ')' : ' (' + ct + ')') : '');
|
|
346
|
+
if (f.input) return head + (ja ? 'の入力欄「' + f.input + '」' : ', input "' + f.input + '"') + (f.inputPath ? ' ' + p(f.inputPath) : '');
|
|
347
|
+
return head + (ja ? 'の inputs の外の項目「' : ', item outside inputs "') + p(f.path.slice(1)) + (ja ? '」' : '"');
|
|
348
|
+
}
|
|
349
|
+
if (f.shape === 'workflow' && node) {
|
|
350
|
+
if (f.widgetIndex != null) return node + (ja ? ' の widgets_values の ' + (f.widgetIndex + 1) + ' 番目' : ', widgets_values item ' + (f.widgetIndex + 1));
|
|
351
|
+
if (f.widgetKey != null) return node + (ja ? ' の widgets_values の「' + f.widgetKey + '」' : ', widgets_values "' + f.widgetKey + '"');
|
|
352
|
+
return node + (ja ? ' の項目「' : ', item "') + p(f.rest || []) + (ja ? '」' : '"');
|
|
353
|
+
}
|
|
354
|
+
const where = f.chunk.keyword ? (ja ? '埋め込みテキスト「' + f.chunk.keyword + '」' : 'embedded text "' + f.chunk.keyword + '"') : (f.chunk.type === 'IEND+' ? (ja ? '画像の終わりの後ろに付いたデータ' : 'data after the end of the image') : (ja ? f.chunk.type + ' チャンク' : f.chunk.type + ' chunk'));
|
|
355
|
+
if (f.path && f.path.length) return where + (ja ? 'の項目「' : ', item "') + p(f.path) + (ja ? '」' : '"');
|
|
356
|
+
return where + (ja ? 'の中' : '');
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/** キーの持ち主へのお知らせ文。値・ファイル名は入れない。欠陥や責任を言い切らない */
|
|
360
|
+
export function buildNotice(res, lang = 'ja', opts = {}) {
|
|
361
|
+
const ja = lang !== 'en';
|
|
362
|
+
if (!res || res.status !== 'found') return '';
|
|
363
|
+
const lines = [], seen = new Set();
|
|
364
|
+
for (const f of res.findings) {
|
|
365
|
+
const src = f.shape === 'prompt' ? 'prompt' : f.shape === 'workflow' ? 'workflow' + (f.bypassed ? (ja ? '・迂回中のノード' : ', bypassed node') : f.muted ? (ja ? '・無効のノード' : ', muted node') : '') : null;
|
|
366
|
+
const l = '・' + placeText(f, lang) + (src ? (ja ? '(' + src + ')' : ' (' + src + ')') : '') + (ja ? ': ' : ': ') + KIND_LABEL[ja ? 'ja' : 'en'][f.kind] + (ja ? '(' + f.prefix + ' で始まる)' : ' (starts with ' + f.prefix + ')');
|
|
367
|
+
const line = ja ? l : l.replace(/^・/, '- ');
|
|
368
|
+
if (!seen.has(line)) { seen.add(line); lines.push(line); }
|
|
369
|
+
}
|
|
370
|
+
const url = opts.url === false ? null : (opts.url || (ja ? 'https://tools.first-ch.com/comfy-key-leak/' : 'https://tools.first-ch.com/en/comfy-key-leak/'));
|
|
371
|
+
if (ja) {
|
|
372
|
+
return ['お知らせです。受け取った画像(PNG)の埋め込みデータに、APIキー形式の文字列がありました。', ...lines,
|
|
373
|
+
'値そのものはこの連絡には書いていません。有効かどうかと、書き込まれた原因は確認していません。',
|
|
374
|
+
'心当たりのあるキーでしたら、発行元の管理画面で状態をご確認ください。']
|
|
375
|
+
.concat(url ? ['(確認には ' + url + ' を使いました。画像はブラウザの外へ送っていません)'] : []).join('\n');
|
|
376
|
+
}
|
|
377
|
+
return ['A quick heads-up: the embedded data of an image (PNG) I received contains strings in an API key format.', ...lines,
|
|
378
|
+
'I have not included the values here. I have not checked whether they are valid, or how they got written into the image.',
|
|
379
|
+
'If you recognise the key, you may want to check its status in the provider’s dashboard.']
|
|
380
|
+
.concat(url ? ['(Checked with ' + url + ' — the image was not sent anywhere.)'] : []).join('\n');
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/** tEXt・iTXt・zTXt を抜いたコピー。caBX 付き・壊れた PNG は書き換えない */
|
|
384
|
+
export function stripTextChunks(bytes) {
|
|
385
|
+
const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
|
|
386
|
+
if (b.length > MAX_BYTES) throw Object.assign(new Error('too large'), { code: 'TOO_LARGE' });
|
|
387
|
+
const rc = readChunks(b);
|
|
388
|
+
if (rc.error) throw Object.assign(new Error('broken png'), { code: 'BROKEN' });
|
|
389
|
+
if (rc.chunks.some((c) => c.type === 'caBX')) throw Object.assign(new Error('has caBX (C2PA)'), { code: 'HAS_CABX' });
|
|
390
|
+
const keep = rc.chunks.filter((c) => !TEXT_TYPES.includes(c.type));
|
|
391
|
+
const removed = rc.chunks.filter((c) => TEXT_TYPES.includes(c.type)).map((c) => c.type);
|
|
392
|
+
let n = 8; for (const c of keep) n += c.end - c.offset;
|
|
393
|
+
const out = new Uint8Array(n);
|
|
394
|
+
out.set(b.subarray(0, 8), 0);
|
|
395
|
+
let o = 8; for (const c of keep) { out.set(b.subarray(c.offset, c.end), o); o += c.end - c.offset; }
|
|
396
|
+
return { bytes: out, removed, kept: keep.length, droppedTrailing: rc.trailing || 0 };
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/** 書き出したコピーを読み直し、文字のチャンクが無いことと、残したチャンクが元とバイト単位で同じことを確かめる */
|
|
400
|
+
export function verifyStripped(orig, out) {
|
|
401
|
+
const a = readChunks(orig instanceof Uint8Array ? orig : new Uint8Array(orig));
|
|
402
|
+
const b = readChunks(out instanceof Uint8Array ? out : new Uint8Array(out));
|
|
403
|
+
const r = { ok: false, readable: !b.error, textLeft: 0, kept: 0, sameBytes: false };
|
|
404
|
+
if (a.error || b.error) return r;
|
|
405
|
+
r.textLeft = b.chunks.filter((c) => TEXT_TYPES.includes(c.type)).length;
|
|
406
|
+
const ka = a.chunks.filter((c) => !TEXT_TYPES.includes(c.type));
|
|
407
|
+
const A = orig instanceof Uint8Array ? orig : new Uint8Array(orig), B = out instanceof Uint8Array ? out : new Uint8Array(out);
|
|
408
|
+
r.kept = b.chunks.length;
|
|
409
|
+
r.sameBytes = ka.length === b.chunks.length && ka.every((c, n) => {
|
|
410
|
+
const d = b.chunks[n], len = c.end - c.offset;
|
|
411
|
+
if (d.end - d.offset !== len) return false;
|
|
412
|
+
for (let k = 0; k < len; k++) if (A[c.offset + k] !== B[d.offset + k]) return false;
|
|
413
|
+
return true;
|
|
414
|
+
});
|
|
415
|
+
r.ok = r.textLeft === 0 && r.sameBytes;
|
|
416
|
+
return r;
|
|
417
|
+
}
|
|
418
|
+
// ===== ここまでコア =====
|
|
419
|
+
|
|
420
|
+
// ---- MCP の入口 ----
|
|
421
|
+
export class ComfyPngLeakError extends Error {
|
|
422
|
+
constructor(code, message) { super(message); this.code = code; }
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// お知らせ文。コアの「確認には〜を使いました・送っていません」はページで確かめたときの文なので使わず、MCP ではページを同じ点検ができる場所として添える
|
|
426
|
+
function mcpNotice(res, lang, withUrl) {
|
|
427
|
+
const base = buildNotice(res, lang, { url: false });
|
|
428
|
+
if (!base || !withUrl) return base;
|
|
429
|
+
return base + '\n' + (lang === 'en'
|
|
430
|
+
? '(You can run the same check at https://tools.first-ch.com/en/comfy-key-leak/ — the page does not send the image anywhere.)'
|
|
431
|
+
: '(同じ点検は https://tools.first-ch.com/comfy-key-leak/ でもできます。ページは画像をブラウザの外へ送りません)');
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
export async function comfyPngLeakTool(opts = {}) {
|
|
435
|
+
const lang = opts.lang === 'en' ? 'en' : 'ja';
|
|
436
|
+
let bytes = null, size = 0, source;
|
|
437
|
+
if (opts.path) {
|
|
438
|
+
if (!path.isAbsolute(opts.path)) throw new ComfyPngLeakError('PATH_NOT_ABSOLUTE', 'path must be an absolute path');
|
|
439
|
+
const st = await stat(opts.path).catch(() => null);
|
|
440
|
+
if (!st || !st.isFile()) throw new ComfyPngLeakError('NOT_FOUND', 'file not found: ' + opts.path);
|
|
441
|
+
size = st.size; source = 'path';
|
|
442
|
+
if (size <= MAX_BYTES) bytes = new Uint8Array(await readFile(opts.path));
|
|
443
|
+
} else if (opts.base64) {
|
|
444
|
+
const b64 = String(opts.base64).replace(/^data:[^,]*,/, '').replace(/\s+/g, '');
|
|
445
|
+
if (!/^[A-Za-z0-9+/_-]*={0,2}$/.test(b64)) throw new ComfyPngLeakError('INVALID_BASE64', 'base64 is not valid');
|
|
446
|
+
bytes = new Uint8Array(Buffer.from(b64, 'base64'));
|
|
447
|
+
size = bytes.length; source = 'base64';
|
|
448
|
+
} else throw new ComfyPngLeakError('NO_INPUT', 'pass path (absolute) or base64');
|
|
449
|
+
|
|
450
|
+
// 大きいファイルは読まずに「未検査」(ページと同じ)
|
|
451
|
+
const res = bytes ? scanPng(bytes) : { status: 'unchecked', reason: 'TOO_LARGE', format: null, size, chunks: [], findings: [], unchecked: [{ type: '*', why: 'TOO_LARGE' }], hasCaBX: false, hasExif: false, canStrip: false, kinds: [], textChunks: 0, trailing: 0 };
|
|
452
|
+
const out = {
|
|
453
|
+
ok: true, source, status: res.status, reason: res.reason, format: res.format, size,
|
|
454
|
+
findings: res.findings.map((f) => ({ ...f, place: placeText(f, lang), kindLabel: KIND_LABEL[lang][f.kind] })),
|
|
455
|
+
kinds: res.kinds,
|
|
456
|
+
revoke: res.kinds.map((k) => ({ kind: k, links: REVOKE[k].map((r) => ({ label: r[lang], url: r.url })) })),
|
|
457
|
+
unchecked: res.unchecked, chunks: res.chunks, hasCaBX: res.hasCaBX, hasExif: res.hasExif, canStrip: res.canStrip,
|
|
458
|
+
notice: mcpNotice(res, lang, opts.includeUrl !== false),
|
|
459
|
+
caution: res.status === 'found'
|
|
460
|
+
? (lang === 'en' ? 'If the image has already been posted or delivered and the key is in use, deleting the image is not enough; disable the key in the provider dashboard. Validity was not checked.'
|
|
461
|
+
: '投稿・納品済みで、実際に使っているキーなら、画像を消すだけでは対処できません。発行元の画面でキーを無効にしてください。キーが有効かどうかは確かめていません。')
|
|
462
|
+
: null,
|
|
463
|
+
};
|
|
464
|
+
if (source === 'base64') {
|
|
465
|
+
out.inputNote = lang === 'en'
|
|
466
|
+
? 'This image was passed as base64, so its bytes (including any embedded key) are already in this AI conversation and were sent to the model provider. This tool itself sends nothing, but treat a found key as exposed. Pass path next time.'
|
|
467
|
+
: 'base64 で渡した画像は、埋め込まれたキーを含めて既にこの AI との会話に載り、モデルの提供元へ送られています。このツール自体は何も送りませんが、見つかったキーは外へ出たものとして扱ってください。次からは path で渡してください。';
|
|
468
|
+
}
|
|
469
|
+
if (opts.outPath) {
|
|
470
|
+
if (!path.isAbsolute(opts.outPath)) throw new ComfyPngLeakError('PATH_NOT_ABSOLUTE', 'outPath must be an absolute path');
|
|
471
|
+
if (opts.path && path.resolve(opts.outPath) === path.resolve(opts.path)) throw new ComfyPngLeakError('SAME_FILE', 'outPath must differ from path (the original is never overwritten)');
|
|
472
|
+
if (!bytes) throw new ComfyPngLeakError('TOO_LARGE', 'files over 30 MB are not rewritten');
|
|
473
|
+
if (res.status === 'failed') throw new ComfyPngLeakError('BROKEN', 'damaged or non-PNG files are not rewritten');
|
|
474
|
+
if (res.hasCaBX) throw new ComfyPngLeakError('HAS_CABX', 'PNGs with caBX (C2PA) are not rewritten');
|
|
475
|
+
const s = stripTextChunks(bytes);
|
|
476
|
+
const v = verifyStripped(bytes, s.bytes);
|
|
477
|
+
if (!v.ok) throw new ComfyPngLeakError('VERIFY_FAILED', 'the stripped copy did not pass the re-check; nothing was written');
|
|
478
|
+
await writeOutput(opts.outPath, s.bytes, { overwrite: opts.overwrite === true });
|
|
479
|
+
const again = scanPng(s.bytes);
|
|
480
|
+
out.stripped = { outPath: opts.outPath, removed: s.removed, kept: s.kept, droppedTrailingBytes: s.droppedTrailing, verify: v, remainingFindings: again.findings.length, exifKept: again.hasExif };
|
|
481
|
+
}
|
|
482
|
+
return out;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
// ---- 見本(架空のキー)とテスト用の PNG を作る。キーの形の文字列はソースに直接書かない(実在のキーと見分けにくい並びを残さない) ----
|
|
486
|
+
export function fakeKey(kind, tag = 'EXAMPLE') {
|
|
487
|
+
const pre = { google: ['AI', 'za'], openai: ['s', 'k-', 'proj-'], anthropic: ['s', 'k-ant-', 'api03-'], huggingface: ['h', 'f_'], replicate: ['r', '8_'] }[kind].join('');
|
|
488
|
+
const body = ('FAKE0' + tag + '0NOT0A0REAL0KEY').replace(/[^A-Za-z0-9]/g, '0');
|
|
489
|
+
const n = { google: 35, openai: 40, anthropic: 40, huggingface: 34, replicate: 37 }[kind];
|
|
490
|
+
return pre + (body + '0'.repeat(n)).slice(0, n);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
function chunk(type, data) {
|
|
494
|
+
const out = new Uint8Array(12 + data.length);
|
|
495
|
+
const len = data.length;
|
|
496
|
+
out[0] = len >>> 24; out[1] = (len >>> 16) & 255; out[2] = (len >>> 8) & 255; out[3] = len & 255;
|
|
497
|
+
for (let i = 0; i < 4; i++) out[4 + i] = type.charCodeAt(i);
|
|
498
|
+
out.set(data, 8);
|
|
499
|
+
const c = crc32(out, 4, 8 + len);
|
|
500
|
+
out[8 + len] = c >>> 24; out[9 + len] = (c >>> 16) & 255; out[10 + len] = (c >>> 8) & 255; out[11 + len] = c & 255;
|
|
501
|
+
return out;
|
|
502
|
+
}
|
|
503
|
+
export function textChunk(keyword, text, type = 'tEXt') {
|
|
504
|
+
const enc = new TextEncoder();
|
|
505
|
+
const k = enc.encode(keyword), t = type === 'tEXt' ? Uint8Array.from(String(text), (ch) => ch.charCodeAt(0) & 255) : enc.encode(text);
|
|
506
|
+
if (type === 'tEXt') return chunk('tEXt', concat([k, [0], t]));
|
|
507
|
+
return chunk('iTXt', concat([k, [0, 0, 0, 0, 0], t])); // 非圧縮・言語タグと翻訳キーワードは空
|
|
508
|
+
}
|
|
509
|
+
export function rawChunk(type, data) { return chunk(type, data instanceof Uint8Array ? data : Uint8Array.from(data)); }
|
|
510
|
+
function concat(parts) {
|
|
511
|
+
let n = 0; for (const p of parts) n += p.length;
|
|
512
|
+
const out = new Uint8Array(n); let o = 0;
|
|
513
|
+
for (const p of parts) { out.set(p, o); o += p.length; }
|
|
514
|
+
return out;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
// 無圧縮の deflate(stored ブロック)で RGB の画像を PNG にする。extra は IDAT の前に入れるチャンク
|
|
518
|
+
export function makePng(w, h, pixel, extra = []) {
|
|
519
|
+
const raw = new Uint8Array((w * 3 + 1) * h);
|
|
520
|
+
for (let y = 0; y < h; y++) {
|
|
521
|
+
raw[y * (w * 3 + 1)] = 0;
|
|
522
|
+
for (let x = 0; x < w; x++) { const [r, g, bl] = pixel(x, y); const o = y * (w * 3 + 1) + 1 + x * 3; raw[o] = r; raw[o + 1] = g; raw[o + 2] = bl; }
|
|
523
|
+
}
|
|
524
|
+
const blocks = [];
|
|
525
|
+
for (let i = 0; i < raw.length; i += 65535) {
|
|
526
|
+
const part = raw.subarray(i, Math.min(raw.length, i + 65535)), last = i + 65535 >= raw.length ? 1 : 0;
|
|
527
|
+
blocks.push(Uint8Array.of(last, part.length & 255, part.length >>> 8, ~part.length & 255, (~part.length >>> 8) & 255), part);
|
|
528
|
+
}
|
|
529
|
+
let a = 1, b2 = 0;
|
|
530
|
+
for (let i = 0; i < raw.length; i++) { a = (a + raw[i]) % 65521; b2 = (b2 + a) % 65521; }
|
|
531
|
+
const adler = ((b2 << 16) | a) >>> 0;
|
|
532
|
+
const z = concat([[0x78, 0x01], ...blocks, [adler >>> 24, (adler >>> 16) & 255, (adler >>> 8) & 255, adler & 255]]);
|
|
533
|
+
const ihdr = Uint8Array.of(w >>> 24, (w >>> 16) & 255, (w >>> 8) & 255, w & 255, h >>> 24, (h >>> 16) & 255, (h >>> 8) & 255, h & 255, 8, 2, 0, 0, 0);
|
|
534
|
+
return concat([Uint8Array.from(SIG), chunk('IHDR', ihdr), ...extra, chunk('IDAT', z), chunk('IEND', new Uint8Array(0))]);
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
// 見本の画像: 夕方の空と山(ComfyUI の出力を想定した架空の1枚)。prompt と workflow に架空のキーを入れる
|
|
538
|
+
export function samplePrompt() {
|
|
539
|
+
return {
|
|
540
|
+
'3': { inputs: { seed: 42, steps: 20, cfg: 7, sampler_name: 'euler', scheduler: 'normal', denoise: 1, model: ['4', 0], positive: ['6', 0], negative: ['7', 0], latent_image: ['5', 0] }, class_type: 'KSampler', _meta: { title: 'KSampler' } },
|
|
541
|
+
'4': { inputs: { ckpt_name: 'example_model.safetensors' }, class_type: 'CheckpointLoaderSimple', _meta: { title: 'Load Checkpoint' } },
|
|
542
|
+
'6': { inputs: { text: 'sunset over mountains, soft light', clip: ['4', 1] }, class_type: 'CLIPTextEncode', _meta: { title: 'Prompt' } },
|
|
543
|
+
'12': { inputs: { prompt: 'refine the sky', model: 'example-pro', api_key: fakeKey('google', 'SAMPLE') }, class_type: 'ExampleGeminiPrompt', _meta: { title: '空の仕上げ' } },
|
|
544
|
+
'9': { inputs: { filename_prefix: 'ComfyUI', images: ['8', 0] }, class_type: 'SaveImage', _meta: { title: 'Save Image' } },
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
export function sampleWorkflow() {
|
|
548
|
+
return {
|
|
549
|
+
last_node_id: 15, last_link_id: 9,
|
|
550
|
+
nodes: [
|
|
551
|
+
{ id: 3, type: 'KSampler', mode: 0, widgets_values: [42, 'fixed', 20, 7, 'euler', 'normal', 1] },
|
|
552
|
+
{ id: 4, type: 'CheckpointLoaderSimple', mode: 0, widgets_values: ['example_model.safetensors'] },
|
|
553
|
+
{ id: 12, type: 'ExampleGeminiPrompt', title: '空の仕上げ', mode: 0, widgets_values: ['refine the sky', 'example-pro', fakeKey('google', 'SAMPLE')] },
|
|
554
|
+
{ id: 15, type: 'ExampleUpscaleAPI', title: 'アップスケール(今回は使わない)', mode: 4, widgets_values: [2, fakeKey('replicate', 'SAMPLE')] },
|
|
555
|
+
{ id: 9, type: 'SaveImage', mode: 0, widgets_values: ['ComfyUI'] },
|
|
556
|
+
],
|
|
557
|
+
links: [], groups: [], config: {}, extra: {}, version: 0.4,
|
|
558
|
+
};
|
|
559
|
+
}
|
|
560
|
+
// ComfyUI(Python の json.dumps)と同じく ASCII の外の文字は \uXXXX にする(tEXt は Latin-1)
|
|
561
|
+
export function asciiJson(v) { return JSON.stringify(v).replace(/[\u007f-\uffff]/g, (c) => '\\u' + c.charCodeAt(0).toString(16).padStart(4, '0')); }
|
|
562
|
+
export function makeSamplePng(w = 360, h = 240) {
|
|
563
|
+
const px = (x, y) => {
|
|
564
|
+
const t = y / h;
|
|
565
|
+
let r = 250 - 70 * t, g = 170 - 90 * t, b = 120 + 40 * t;
|
|
566
|
+
const sx = x - w * 0.68, sy = y - h * 0.5, d = Math.sqrt(sx * sx + sy * sy);
|
|
567
|
+
if (d < h * 0.14) { r = 255; g = 226; b = 170; }
|
|
568
|
+
const m1 = h * 0.62 + Math.sin(x / w * 7) * h * 0.08 + Math.sin(x / w * 17) * h * 0.03;
|
|
569
|
+
const m2 = h * 0.78 + Math.sin(x / w * 5 + 1) * h * 0.06;
|
|
570
|
+
if (y > m1) { r = 92; g = 70; b = 96; }
|
|
571
|
+
if (y > m2) { r = 52; g = 44; b = 66; }
|
|
572
|
+
return [Math.round(r), Math.round(g), Math.round(b)];
|
|
573
|
+
};
|
|
574
|
+
return makePng(w, h, px, [textChunk('prompt', asciiJson(samplePrompt())), textChunk('workflow', asciiJson(sampleWorkflow()))]);
|
|
575
|
+
}
|
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 列と入れ子の相互展開)・全角⇄半角の変換とテキストの掃除(文字種ごとの向き指定・半角カナの合成/分解・空白と空行の整理)・IPアドレス/CIDRの計算(ネットワーク・ブロードキャスト・ホスト範囲とホスト数・IPv4/IPv6・サブネット分割・包含判定・IP範囲→最小CIDR集合の逆算)・日数/営業日の計算(2日付間の日数と営業日数・起点日+N日/N営業日の期日・締め日と支払サイトからの支払日・土日と日本の祝日を内蔵)・HTML→Markdownの変換(見出し/リスト/表/リンク/画像/コード・script/styleや装飾タグの除去・本文だけの抽出・相対URLの絶対化)・和暦⇄西暦の変換(令和〜明治・自動判定・曜日と干支・存在しない和暦の指摘・満年齢と入学/卒業の年・元号一覧と早見表)・日本語タイトルからのURLスラッグ生成(かな→ヘボン式ローマ字・記号除去・ハイフン/アンダースコア連結・小文字化・長音の省略/表記)・Basic認証用 htpasswd の生成と照合(bcrypt / apr1-md5・パスワードの自動生成・Apache / nginx の設定スニペット)・OpenAPI/Swagger仕様書から日本語のMarkdownドキュメントとTypeScript型定義の生成(OpenAPI 3.x / Swagger 2.0・YAML/JSON・$ref/allOf/oneOf 対応・エンドポイントごとの引数/レスポンス型・外部 $ref は読みに行かない)・FAQ構造化データ(FAQPage の JSON-LD・Markdown・details/summary の HTML を同時生成・回答のリンク/箇条書きを HTML 化・「Q: / A:」形式の一括貼り付けの解析)・テキストの行操作(重複行の削除・数値を認識する並べ替え・シード付きシャッフル・行番号・空行除去・前後トリム・接頭辞/接尾辞)・印刷サイズとDPIの計算(用紙×解像度×塗り足しから必要なピクセル数・手持ちの画像の実効dpiと判定・早見表・mm/inch/px/pt/級の換算)・SERPのメタタグ文字数チェック(title / description が検索結果に収まるかをピクセル幅で判定・切り詰め位置と表示行・パンくず表示・https や階層の指摘)・Flexbox / CSS GridのCSS生成(既定値を省いた宣言・repeat()への畳み込み・grid-template-areasの検証・効かない組み合わせの指摘・定番プリセット)・社内文書の点検(Notion・Confluence などから書き出した Markdown/HTML の重複ページ・孤立ページ・表記ゆれや旧称・リンク切れの検出と修正案)・記入欄に収める字の大きさと改行位置(中袋〔ご祝儀袋・香典袋〕の住所欄などの幅・高さmmから1
|
|
3
|
+
"version": "0.49.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集合の逆算)・日数/営業日の計算(2日付間の日数と営業日数・起点日+N日/N営業日の期日・締め日と支払サイトからの支払日・土日と日本の祝日を内蔵)・HTML→Markdownの変換(見出し/リスト/表/リンク/画像/コード・script/styleや装飾タグの除去・本文だけの抽出・相対URLの絶対化)・和暦⇄西暦の変換(令和〜明治・自動判定・曜日と干支・存在しない和暦の指摘・満年齢と入学/卒業の年・元号一覧と早見表)・日本語タイトルからのURLスラッグ生成(かな→ヘボン式ローマ字・記号除去・ハイフン/アンダースコア連結・小文字化・長音の省略/表記)・Basic認証用 htpasswd の生成と照合(bcrypt / apr1-md5・パスワードの自動生成・Apache / nginx の設定スニペット)・OpenAPI/Swagger仕様書から日本語のMarkdownドキュメントとTypeScript型定義の生成(OpenAPI 3.x / Swagger 2.0・YAML/JSON・$ref/allOf/oneOf 対応・エンドポイントごとの引数/レスポンス型・外部 $ref は読みに行かない)・FAQ構造化データ(FAQPage の JSON-LD・Markdown・details/summary の HTML を同時生成・回答のリンク/箇条書きを HTML 化・「Q: / A:」形式の一括貼り付けの解析)・テキストの行操作(重複行の削除・数値を認識する並べ替え・シード付きシャッフル・行番号・空行除去・前後トリム・接頭辞/接尾辞)・印刷サイズとDPIの計算(用紙×解像度×塗り足しから必要なピクセル数・手持ちの画像の実効dpiと判定・早見表・mm/inch/px/pt/級の換算)・SERPのメタタグ文字数チェック(title / description が検索結果に収まるかをピクセル幅で判定・切り詰め位置と表示行・パンくず表示・https や階層の指摘)・Flexbox / CSS GridのCSS生成(既定値を省いた宣言・repeat()への畳み込み・grid-template-areasの検証・効かない組み合わせの指摘・定番プリセット)・社内文書の点検(Notion・Confluence などから書き出した Markdown/HTML の重複ページ・孤立ページ・表記ゆれや旧称・リンク切れの検出と修正案)・記入欄に収める字の大きさと改行位置(中袋〔ご祝儀袋・香典袋〕の住所欄などの幅・高さmmから1字の大きさ・行数・改行位置・縦書きの漢数字・金額の大字)・AIが書いた返信案と届いたメールの照合(原文に無い日付・曜日・時刻・金額・数量・電話・宛名を赤、消し忘れの仮の文字を黄)・ComfyUI画像(PNG)の埋め込みデータに残ったAPIキーの形の点検(ノードIDと入力欄で場所を示し値は伏せる・持ち主へのお知らせ文・文字のチャンクを抜いたコピー))をMCPツールとして提供するサーバー。あわせて apps.first-ch.com のWebアプリ38本(GEO・メタタグ・セキュリティヘッダー・SSL・DNS・リダイレクト・リンク切れ・構造化データ・AIクローラー許可・和文可読性・ビジネス文面チェック等)の JSON API を呼ぶ app_* ツールも提供する(こちらは入力を apps.first-ch.com へ送るため既定では無効・FIRSTCH_ENABLE_APPS=1 で有効)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
7
7
|
"firstch-tools-mcp": "server.mjs"
|
|
@@ -281,6 +281,8 @@
|
|
|
281
281
|
"fs-safe.mjs",
|
|
282
282
|
"fit-to-box.mjs",
|
|
283
283
|
"invoice-nebiki.mjs",
|
|
284
|
+
"comfy-png-leak.mjs",
|
|
285
|
+
"reply-check.mjs",
|
|
284
286
|
"webp.mjs",
|
|
285
287
|
"marp.mjs",
|
|
286
288
|
"marp-theme.css",
|
package/reply-check.mjs
ADDED
|
@@ -0,0 +1,497 @@
|
|
|
1
|
+
/* AI の返信案の送る前チェック(reply_check)
|
|
2
|
+
* 照合のコア(normalize / extract / checkReply ほか)は FirstCHTools の site/okurumae/app.js と同一
|
|
3
|
+
* (2箇所ルール: site側が正本・片方を直したらもう片方も同じ内容で反映する)。
|
|
4
|
+
* 両ファイルからコアの開始/終了コメントに挟まれた範囲を切り出し(site側は字下げ2文字を落とす。
|
|
5
|
+
* こちらはコアの中に export を書かず、末尾でまとめて export する)、diff が空になることで同期を確かめる:
|
|
6
|
+
* diff <(sed -n '/^ \/\/ ===== ここからコア/,/^ \/\/ ===== ここまでコア/p' site/okurumae/app.js | sed 's/^ //') \
|
|
7
|
+
* <(sed -n '/^\/\/ ===== ここからコア/,/^\/\/ ===== ここまでコア/p' reply-check.mjs | sed 's/^export //')
|
|
8
|
+
*
|
|
9
|
+
* 届いたメール(+自分で決めた事実)と AI が書いた返信案を照らし合わせ、返信案の日付・曜日・時刻・金額・数量・電話・
|
|
10
|
+
* メール・URL・宛名・番号のうち、原文のどちらにも無いものを赤、あるものを緑、[お客様1]・〇〇・XX などの消し忘れを黄で返す。
|
|
11
|
+
* 本文は書き換えず、照合のときだけ全角/半角などをそろえる。完全ローカル処理・ネットワーク送信なし。 */
|
|
12
|
+
|
|
13
|
+
// ===== ここからコア(DOM に触らない。document の無いときは globalThis.__okurumae で公開し、tests/okurumae.test.mjs が確かめる。MCP の reply-check.mjs と同じ) =====
|
|
14
|
+
var WD_JA = '日月火水木金土';
|
|
15
|
+
var WD_EN = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
|
|
16
|
+
var MONTHS_EN = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
|
|
17
|
+
var KANJI_NUM = '〇一二三四五六七八九';
|
|
18
|
+
// 宛名の前に来ても名前ではない語(お客様・皆様・ご担当者様など)
|
|
19
|
+
var NOT_NAMES = ['客', '皆', '各位', '会員', '利用者', '担当者', '担当', '担当者各位', '保護者', '関係者', '奥', '旦那', '生徒', '参加者', '出席者', '応募者',
|
|
20
|
+
'購入者', '一同', '子', '家族', '親御', '両親', '主人', '先方', '相手', '神', '王', '仏', '仕', '模', '同', '異', '多', '有', '左', '一', '皆々', 'みな', 'みなさ',
|
|
21
|
+
'店長', '部長', '課長', '社長', '先生', '院長', '会長', '係', '幹事', '代表', '業者', '来店者', 'ゲスト', 'メンバー', 'スタッフ', 'オーナー', '運営', '事務局',
|
|
22
|
+
'予約係', 'ご予約係', '受付', '窓口', '貴社', '御社', '貴店', '利用', '入会者', '新入会員', '児童', '園児', '父兄', 'お父', 'お母', 'じい', 'ばあ', 'お兄', 'お姉',
|
|
23
|
+
'兄', '姉', '弟', '妹', '娘', '息子', '奥方', 'お連れ', '連れ', '患者', '契約者', '依頼者', '世帯主', 'ご本人', '本人', '母', '父', '孫', '嬢', '主',
|
|
24
|
+
'苦労', '世話', '馳走', '愁傷', '気の毒', 'おかげ', 'たく', '注文者', '予約者', '依頼主', '得意', '取引先', '店舗', '施主', '入居者', '宿泊者', '利用者各位'];
|
|
25
|
+
var NOT_NAMES_EN = ['customer', 'customers', 'sir', 'madam', 'sir or madam', 'guest', 'guests', 'team', 'all', 'valued', 'friend', 'friends', 'member', 'members', 'client', 'parent', 'parents'];
|
|
26
|
+
var TITLE_TAIL = /(?:部長|課長|係長|社長|店長|先生|院長|会長|代表|さん|様)$/;
|
|
27
|
+
|
|
28
|
+
// 照合用にそろえる(本文は書き換えない)。NFKC で全角英数・記号を半角に、数字の間の長音・ダッシュを「-」に。
|
|
29
|
+
// map[i] は、そろえた文字列の i 文字目が元の文字列の何文字目から来たか(最後に元の長さを足す)
|
|
30
|
+
function normalize(s) {
|
|
31
|
+
s = String(s == null ? '' : s);
|
|
32
|
+
var out = '', map = [];
|
|
33
|
+
for (var i = 0; i < s.length;) {
|
|
34
|
+
var cp = s.codePointAt(i), ch = String.fromCodePoint(cp), n = ch.normalize('NFKC');
|
|
35
|
+
if (ch === '〜' || ch === '~') n = '~';
|
|
36
|
+
for (var k = 0; k < n.length; k++) { out += n[k]; map.push(i); }
|
|
37
|
+
i += ch.length;
|
|
38
|
+
}
|
|
39
|
+
map.push(s.length);
|
|
40
|
+
out = out.replace(/(\d)(\s*)[ー‐‑‒–—―−](?=\s*\d)/g, '$1$2-'); // 長さを変えない(map がそのまま使える)
|
|
41
|
+
return { t: out, map: map, src: s };
|
|
42
|
+
}
|
|
43
|
+
function toOrig(N, s, e) {
|
|
44
|
+
var a = N.map[s], j = e;
|
|
45
|
+
while (j < N.t.length && N.map[j] === N.map[e - 1]) j++;
|
|
46
|
+
return [a, j >= N.t.length ? N.src.length : N.map[j]];
|
|
47
|
+
}
|
|
48
|
+
function kanjiNum(s) {
|
|
49
|
+
if (/^\d+(?:\.\d+)?$/.test(s)) return parseFloat(s);
|
|
50
|
+
if (s === '十') return 10;
|
|
51
|
+
var m = /^([一二三四五六七八九])?十([一二三四五六七八九])?$/.exec(s);
|
|
52
|
+
if (m) return (m[1] ? KANJI_NUM.indexOf(m[1]) : 1) * 10 + (m[2] ? KANJI_NUM.indexOf(m[2]) : 0);
|
|
53
|
+
if (/^[〇一二三四五六七八九]$/.test(s)) return KANJI_NUM.indexOf(s);
|
|
54
|
+
return NaN;
|
|
55
|
+
}
|
|
56
|
+
function num(s) { return parseFloat(String(s).replace(/,/g, '')); }
|
|
57
|
+
function digits(s) { return String(s).replace(/\D/g, ''); }
|
|
58
|
+
|
|
59
|
+
// 月日から年を決める(年が書かれていなければ、今日の60日前〜305日後に入る年)
|
|
60
|
+
function inferYear(m, d, today) {
|
|
61
|
+
var t0 = Date.UTC(today.getFullYear(), today.getMonth(), today.getDate());
|
|
62
|
+
for (var dy = -1; dy <= 1; dy++) {
|
|
63
|
+
var y = today.getFullYear() + dy, t = Date.UTC(y, m - 1, d), diff = (t - t0) / 864e5;
|
|
64
|
+
if (diff >= -60 && diff <= 305) return y;
|
|
65
|
+
}
|
|
66
|
+
return today.getFullYear();
|
|
67
|
+
}
|
|
68
|
+
function weekdayOf(y, m, d) {
|
|
69
|
+
var dt = new Date(Date.UTC(y, m - 1, d));
|
|
70
|
+
if (dt.getUTCMonth() !== m - 1) return -1; // 11月31日など存在しない日
|
|
71
|
+
return dt.getUTCDay();
|
|
72
|
+
}
|
|
73
|
+
function wdIndex(w) {
|
|
74
|
+
if (!w) return -1;
|
|
75
|
+
var i = WD_JA.indexOf(w);
|
|
76
|
+
if (i >= 0 && w.length === 1) return i;
|
|
77
|
+
var k = w.toLowerCase().slice(0, 3);
|
|
78
|
+
return WD_EN.indexOf(k);
|
|
79
|
+
}
|
|
80
|
+
function monthIndex(w) { return MONTHS_EN.indexOf(w.toLowerCase().slice(0, 3)) + 1; }
|
|
81
|
+
|
|
82
|
+
// 1つの文章から照合の対象を拾う。種類ごとに順に探し、先に拾った範囲とは重ねない
|
|
83
|
+
function extract(text) {
|
|
84
|
+
var N = normalize(text), t = N.t, used = new Uint8Array(t.length + 1), toks = [];
|
|
85
|
+
function free(s, e) { for (var i = s; i < e; i++) if (used[i]) return false; return true; }
|
|
86
|
+
function add(tok, s, e) {
|
|
87
|
+
if (e <= s || !free(s, e)) return null;
|
|
88
|
+
for (var i = s; i < e; i++) used[i] = 1;
|
|
89
|
+
var o = toOrig(N, s, e);
|
|
90
|
+
tok.ns = s; tok.ne = e; tok.start = o[0]; tok.end = o[1]; tok.text = N.src.slice(o[0], o[1]);
|
|
91
|
+
toks.push(tok);
|
|
92
|
+
return tok;
|
|
93
|
+
}
|
|
94
|
+
function each(re, fn) {
|
|
95
|
+
re.lastIndex = 0;
|
|
96
|
+
var m;
|
|
97
|
+
while ((m = re.exec(t))) {
|
|
98
|
+
var s = m.index, e = s + m[0].length;
|
|
99
|
+
if (!free(s, e)) { re.lastIndex = s + 1; continue; } // 先に拾った範囲にかかるなら、1字ずらして探し直す
|
|
100
|
+
fn(m, s, e);
|
|
101
|
+
if (m[0].length === 0) re.lastIndex++;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// URL・メール
|
|
106
|
+
each(/\bhttps?:\/\/[^\s<>"'()\[\]{}「」『』【】、。]+|\bwww\.[A-Za-z0-9-]+\.[^\s<>"'()\[\]{}「」『』【】、。]+/gi, function (m, s, e) {
|
|
107
|
+
var v = m[0].replace(/[.,!?;:]+$/, ''); e = s + v.length;
|
|
108
|
+
// 大小文字をそろえるのはスキームとホストだけ(パス・クエリの /Reserve と /reserve は別のリンク。RFC 3986 6.2.2.1)
|
|
109
|
+
// スキーム・wwwの有無・末尾の「/」は別の接続先になり得るのでそろえない。空のパスだけ「/」と同じに扱う(RFC 3986 6.2.3)
|
|
110
|
+
var sc = (v.match(/^https?:\/\//i) || [''])[0], u = v.slice(sc.length), cut = u.search(/[\/?#]/), host = cut < 0 ? u : u.slice(0, cut), rest = cut < 0 ? '' : u.slice(cut);
|
|
111
|
+
if (rest.charAt(0) !== '/') rest = '/' + rest;
|
|
112
|
+
add({ type: 'url', key: sc.toLowerCase() + host.toLowerCase() + rest }, s, e);
|
|
113
|
+
});
|
|
114
|
+
each(/[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}/g, function (m, s, e) { add({ type: 'email', key: m[0].toLowerCase() }, s, e); });
|
|
115
|
+
|
|
116
|
+
// 消し忘れ(黄)。宛名・数字より先に拾う
|
|
117
|
+
var PH_WORDS = '名前|氏名|名|日付|日時|時間|時刻|金額|料金|会社|店名|住所|電話|番号|担当|お客様|宛名|URL|メール|ここ|入力|記入|挿入|要確認|未定|〇|○|◯|X|x';
|
|
118
|
+
each(new RegExp('\\[[^\\[\\]\\n]{1,30}\\](?!\\()|【\\s*】|【[^【】\\n]{0,20}?(?:' + PH_WORDS + ')[^【】\\n]{0,10}】|\\{\\{?[^{}\\n]{1,30}\\}\\}?|<[^<>\\n]*[^\\x00-\\x7f<>\\n][^<>\\n]*>|_{3,}', 'g'), function (m, s, e) {
|
|
119
|
+
add({ type: 'placeholder', key: m[0] }, s, e);
|
|
120
|
+
});
|
|
121
|
+
each(/(?<![一二三四五六七八九十〇])[〇○◯●△□■◇×]{2,}(?![一二三四五六七八九十〇])|[〇○◯●△□×](?=[月日時分円様名人号年])/g, function (m, s, e) { add({ type: 'placeholder', key: m[0] }, s, e); });
|
|
122
|
+
each(/(?<![A-Za-z0-9])[Xx]{2,}(?:[-:\/][Xx]{2,})*(?![A-Za-z0-9])/g, function (m, s, e) { add({ type: 'placeholder', key: m[0] }, s, e); });
|
|
123
|
+
|
|
124
|
+
// 日付(年月日・月/日・年-月-日・英語の月名)。直後(英語は直前も)の曜日を含める
|
|
125
|
+
function attachWeekday(tok, s, e) {
|
|
126
|
+
var rest = t.slice(e, e + 16), m;
|
|
127
|
+
if ((m = /^\s*\(\s*([月火水木金土日])(?:曜日?)?\s*(?:[・,、]\s*祝日?\s*)?\)/.exec(rest)) || (m = /^\s*([月火水木金土日])曜日?/.exec(rest))) {
|
|
128
|
+
tok.wd = wdIndex(m[1]); e += m[0].length;
|
|
129
|
+
} else if ((m = /^\s*\(\s*(Sun|Mon|Tue|Wed|Thu|Fri|Sat)[a-z]*\.?\s*\)/i.exec(rest))) {
|
|
130
|
+
tok.wd = wdIndex(m[1]); e += m[0].length;
|
|
131
|
+
} else {
|
|
132
|
+
var before = t.slice(Math.max(0, s - 14), s);
|
|
133
|
+
if ((m = /\b(Sun|Mon|Tue|Wed|Thu|Fri|Sat)[a-z]*\.?,?\s*(?:the\s+)?$/i.exec(before))) { tok.wd = wdIndex(m[1]); s -= m[0].length; }
|
|
134
|
+
}
|
|
135
|
+
return [s, e];
|
|
136
|
+
}
|
|
137
|
+
function addDate(y, mo, d, s, e) {
|
|
138
|
+
mo = mo ? +mo : 0; d = +d;
|
|
139
|
+
if ((mo && (mo < 1 || mo > 12)) || d < 1 || d > 31) return;
|
|
140
|
+
var tok = { type: 'date', y: y ? +y : 0, m: mo, d: d, wd: -1 }, r = attachWeekday(tok, s, e);
|
|
141
|
+
tok.key = (tok.y || '') + '-' + (mo || '*') + '-' + d;
|
|
142
|
+
add(tok, r[0], r[1]);
|
|
143
|
+
}
|
|
144
|
+
each(/(?:(\d{4})\s*年\s*)?(\d{1,2})\s*月\s*(\d{1,2})\s*日/g, function (m, s, e) { addDate(m[1], m[2], m[3], s, e); });
|
|
145
|
+
each(/(?<![\d\/.:-])(\d{4})[\/.-](\d{1,2})[\/.-](\d{1,2})(?![\d\/.-])/g, function (m, s, e) { addDate(m[1], m[2], m[3], s, e); });
|
|
146
|
+
each(/(?<![\d\/.:-])(\d{1,2})\/(\d{1,2})(?![\d\/])/g, function (m, s, e) { addDate(0, m[1], m[2], s, e); });
|
|
147
|
+
each(/\b(Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|June?|July?|Aug(?:ust)?|Sep(?:t(?:ember)?)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)\.?\s+(\d{1,2})(?:st|nd|rd|th)?\b(?:,?\s+(\d{4})\b)?/gi, function (m, s, e) { addDate(m[3], monthIndex(m[1]), m[2], s, e); });
|
|
148
|
+
each(/\b(\d{1,2})(?:st|nd|rd|th)?\s+(Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|June?|July?|Aug(?:ust)?|Sep(?:t(?:ember)?)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)\b(?:,?\s+(\d{4})\b)?/gi, function (m, s, e) { addDate(m[3], monthIndex(m[2]), m[1], s, e); });
|
|
149
|
+
// 日だけ(「8日(日)」「〜10日」)。月は前の日付から引き継ぐ
|
|
150
|
+
each(/(?<![\d月\/.,泊])(\d{1,2})\s*日(?!間|本|後|前|目|分|以|中|ぶり|おき|毎|ごと|当日|程度|ほど|くらい|ぐらい|まで以内)/g, function (m, s, e) { addDate(0, 0, m[1], s, e); });
|
|
151
|
+
|
|
152
|
+
// 時刻(18:30・18時30分・18時半・午後6時・6:30 pm・6 pm)。「18:00」「06:00」のようなコロンの形は24時間表記として読み、
|
|
153
|
+
// 午前・午後の無い「〇時」だけを両方に読む(06:00 を 18時 と一致させない)
|
|
154
|
+
function addTime(ap1, h, mi, half, ap2, s, e, colon) {
|
|
155
|
+
h = +h; mi = half ? 30 : (mi ? +mi : 0);
|
|
156
|
+
if (h > 30 || mi > 59) return;
|
|
157
|
+
var ap = (ap1 || ap2 || '').toLowerCase().replace(/\./g, ''), keys = [];
|
|
158
|
+
if (ap === '午後' || ap === 'pm') keys.push((h % 12 + 12) * 60 + mi);
|
|
159
|
+
else if (ap === '午前' || ap === 'am') keys.push((h % 12) * 60 + mi);
|
|
160
|
+
else { keys.push(h * 60 + mi); if (!colon && h >= 1 && h <= 11) keys.push((h + 12) * 60 + mi); if (!colon && h === 12) keys.push(mi); }
|
|
161
|
+
add({ type: 'time', keys: keys, key: keys.join('|') }, s, e);
|
|
162
|
+
}
|
|
163
|
+
var AP = '(午前|午後|AM|PM|am|pm|a\\.m\\.|p\\.m\\.)';
|
|
164
|
+
each(new RegExp('(?:' + AP + '\\s*)?(?<![\\d:.])(\\d{1,2})\\s*(?::(\\d{2})(?!\\d)|時(?!間)(?:\\s*(\\d{1,2})\\s*分(?!間)|(半))?)(?:\\s*' + AP + '(?![A-Za-z]))?', 'g'), function (m, s, e) { addTime(m[1], m[2], m[3] || m[4], m[5], m[6], s, e, m[3] != null); });
|
|
165
|
+
each(new RegExp('(?<![\\d:.])(\\d{1,2})\\s*' + AP + '(?![A-Za-z])', 'g'), function (m, s, e) { addTime('', m[1], 0, '', m[2], s, e); });
|
|
166
|
+
|
|
167
|
+
// 電話(数字が10〜11桁。+81 は 0 に読み替える。「+81 (0)90」の (0) は国内の0なので重ねない)
|
|
168
|
+
each(/(?<![\w.\/-])(?:\+81[-\s]?\(?0?\)?|\(?0)\d{1,4}\)?[-\s]?\d{1,4}[-\s]?\d{3,4}(?![\w-])/g, function (m, s, e) {
|
|
169
|
+
var dg = digits(m[0]);
|
|
170
|
+
if (m[0].charAt(0) === '+') dg = dg.slice(2);
|
|
171
|
+
if (dg[0] !== '0') dg = '0' + dg;
|
|
172
|
+
if (dg.length >= 10 && dg.length <= 11) add({ type: 'phone', key: dg }, s, e);
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
// 金額(円・万・千・¥・$・yen)
|
|
176
|
+
each(/(?:[¥\\]\s?)?(\d[\d,]*(?:\.\d+)?)(?:\s*(万|千)(?:(\d[\d,]*)(千)?)?)?\s*円/g, function (m, s, e) {
|
|
177
|
+
var v = num(m[1]) * (m[2] === '万' ? 10000 : m[2] === '千' ? 1000 : 1);
|
|
178
|
+
if (m[3]) v += num(m[3]) * (m[4] ? 1000 : 1);
|
|
179
|
+
add({ type: 'money', key: 'JPY:' + Math.round(v) }, s, e);
|
|
180
|
+
});
|
|
181
|
+
each(/[¥\\]\s?(\d[\d,]*(?:\.\d+)?)(?:\s*(万))?/g, function (m, s, e) { add({ type: 'money', key: 'JPY:' + Math.round(num(m[1]) * (m[2] ? 10000 : 1)) }, s, e); });
|
|
182
|
+
each(/\b(\d[\d,]*(?:\.\d+)?)\s*(?:yen|JPY)\b/gi, function (m, s, e) { add({ type: 'money', key: 'JPY:' + Math.round(num(m[1])) }, s, e); });
|
|
183
|
+
each(/(?:US)?\$\s?(\d[\d,]*(?:\.\d{1,2})?)|\b(\d[\d,]*(?:\.\d{1,2})?)\s*(?:dollars?|USD)\b/gi, function (m, s, e) { add({ type: 'money', key: 'USD:' + num(m[1] || m[2]) }, s, e); });
|
|
184
|
+
|
|
185
|
+
// 数量(2名・3泊・50%・4 adults)。「お一人様」「1人あたり」は単価の言い方なので数えない
|
|
186
|
+
// 桁区切り(1,100)は1つの数として読み、数の途中(「1,100」の「100」)からは読み始めない。
|
|
187
|
+
// 止めるのは直前が数字のときと、「数字,」「数字.」の後ろがちょうど3桁のとき(桁区切りの続き)だけ。「2泊,3名」「2,3人」の後ろの数は読む
|
|
188
|
+
// 直前に大人・子どもの語があれば区分(adult・child)を組にして持つ(「大人2名・子ども1名」と「大人1名・子ども2名」を取り違えない)。
|
|
189
|
+
// 区分は2つだけにし、男性・女性・学生などの言い換えには付けない(数と単位だけで照合する)
|
|
190
|
+
var QTY_LABEL = { '大人': 'adult', 'おとな': 'adult', '成人': 'adult', '子ども': 'child', '子供': 'child', 'こども': 'child', 'お子様': 'child', 'お子さま': 'child', '子様': 'child',
|
|
191
|
+
'小人': 'child', '児童': 'child', '小学生': 'child', '幼児': 'child', '乳児': 'child', '未就学児': 'child', '赤ちゃん': 'child' };
|
|
192
|
+
var QTY_LABEL_RE = new RegExp('(' + Object.keys(QTY_LABEL).sort(function (a, b) { return b.length - a.length; }).join('|') + ')\\s*(?::|は|が)?\\s*$');
|
|
193
|
+
function qtyLabel(s) { var m = QTY_LABEL_RE.exec(t.slice(Math.max(0, s - 10), s)); return m ? QTY_LABEL[m[1]] : ''; }
|
|
194
|
+
var UNIT = { '名': '人', '名様': '人', '人': '人', '人様': '人', 'つ': '個', 'ヶ月': 'か月', 'ケ月': 'か月', 'カ月': 'か月', 'ヵ月': 'か月', 'か月': 'か月', '才': '歳', 'パーセント': '%', '%': '%' };
|
|
195
|
+
var UNIT_EN = { people: '人', persons: '人', person: '人', guests: '人', guest: '人', adults: '人', adult: '人', children: '人', child: '人', kids: '人', pax: '人',
|
|
196
|
+
nights: '泊', night: '泊', pieces: '個', pcs: '個', items: '個', item: '個', tickets: '枚', ticket: '枚', seats: '席', seat: '席', rooms: '室', room: '室',
|
|
197
|
+
hours: '時間', hour: '時間', hrs: '時間', minutes: '分', minute: '分', mins: '分', days: '日間', day: '日間', weeks: '週間', week: '週間', months: 'か月', month: 'か月', percent: '%' };
|
|
198
|
+
each(/(お|ご)?(?<!\d)(?<!\d[,.](?=\d{3}(?!\d)))(\d{1,3}(?:,\d{3})+(?![\d,])|\d+(?:\.\d+)?|[一二三四五六七八九十]{1,3})\s*(名様|人様|名|人|個|つ|枚|本|台|件|部|冊|泊|回|杯|皿|席|組|箱|セット|点|日間|時間|分間|分|秒|週間|か月|カ月|ヶ月|ケ月|ヵ月|年間|年|歳|才|%|パーセント|割|cm|mm|km|kg|ml|mL|m|g|L|坪|畳|階|番|号室|号|室)(?![A-Za-z])(あたり|当たり|につき|ずつ)?/g, function (m, s, e) {
|
|
199
|
+
var isK = !/^\d/.test(m[2]);
|
|
200
|
+
if (isK && !/^(名様?|人様?|泊|組)$/.test(m[3])) return; // 漢数字は「一杯」「もう一つ」などの言い回しが多いので人数・泊・組だけ
|
|
201
|
+
var v = isK ? kanjiNum(m[2]) : num(m[2]);
|
|
202
|
+
if (isNaN(v)) return;
|
|
203
|
+
if (m[4] || (m[1] && v === 1 && /^(名|人)/.test(m[3]))) return; // 単価の言い方
|
|
204
|
+
var u = UNIT[m[3]] || m[3];
|
|
205
|
+
add({ type: 'qty', key: v + u, label: qtyLabel(s) }, s + (m[1] ? m[1].length : 0), e - (m[4] ? m[4].length : 0));
|
|
206
|
+
});
|
|
207
|
+
var LABEL_EN = { adults: 'adult', adult: 'adult', children: 'child', child: 'child', kids: 'child' };
|
|
208
|
+
each(/(?<!\d)(?<!\d[,.](?=\d{3}(?!\d)))(\d{1,3}(?:,\d{3})+(?![\d,])|\d+(?:\.\d+)?)\s*(people|persons?|guests?|adults?|children|child|kids|pax|nights?|pieces|pcs|items?|tickets?|seats?|rooms?|hours?|hrs|minutes?|mins|days?|weeks?|months?|percent)\b/gi, function (m, s, e) {
|
|
209
|
+
var w = m[2].toLowerCase();
|
|
210
|
+
add({ type: 'qty', key: num(m[1]) + UNIT_EN[w], label: LABEL_EN[w] || qtyLabel(s) }, s, e);
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
// 曜日だけ(「土曜日」「Saturday」「土日」)
|
|
214
|
+
each(/([月火水木金土日])曜日?/g, function (m, s, e) { add({ type: 'weekday', wds: [wdIndex(m[1])], key: m[1] }, s, e); });
|
|
215
|
+
each(/土日(?!曜)/g, function (m, s, e) { add({ type: 'weekday', wds: [6, 0], key: '土日' }, s, e); });
|
|
216
|
+
each(/\b(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sun|Mon|Tues?|Wed|Thur?s?|Fri|Sat)s?\b\.?/g, function (m, s, e) { add({ type: 'weekday', wds: [wdIndex(m[1])], key: m[1] }, s, e); });
|
|
217
|
+
|
|
218
|
+
// 宛名(〇〇様・さま・さん・殿・御中、Dear / Mr. / Ms.)
|
|
219
|
+
each(/(様|さま|さん|殿|御中)/g, function (m, s, e) {
|
|
220
|
+
if (used[s]) return;
|
|
221
|
+
if (m[1] === '様' && /^[々子式相]/.test(t.slice(e, e + 1))) return;
|
|
222
|
+
var s0 = s;
|
|
223
|
+
while (s0 > 0 && t[s0 - 1] === ' ' && !used[s0 - 1]) s0--; // 「田中 様」
|
|
224
|
+
var i = s0, sp = 0;
|
|
225
|
+
while (i > 0 && s0 - i < 14) {
|
|
226
|
+
var c = t[i - 1];
|
|
227
|
+
if (used[i - 1]) break;
|
|
228
|
+
if (/[\p{Script=Han}々〆ヵヶ\p{Script=Katakana}ー・A-Za-z]/u.test(c)) { i--; continue; }
|
|
229
|
+
if (c === ' ' && !sp && i < s0 && i > 1 && /[\p{Script=Han}々\p{Script=Katakana}A-Za-z]/u.test(t[i - 2])) { sp = 1; i--; continue; }
|
|
230
|
+
break;
|
|
231
|
+
}
|
|
232
|
+
if (i === s0) { // ひらがなの名前(行頭・空白・句読点の直後から)
|
|
233
|
+
var j = s0;
|
|
234
|
+
while (j > 0 && s0 - j < 8 && /[ぁ-ゟ]/.test(t[j - 1]) && !used[j - 1]) j--;
|
|
235
|
+
if (j < s0 && (j === 0 || /[\s、。「『(,]/.test(t[j - 1]))) i = j;
|
|
236
|
+
}
|
|
237
|
+
var name = t.slice(i, s0).replace(/^ +/, '');
|
|
238
|
+
i = s0 - name.length;
|
|
239
|
+
var bare = name.replace(/^[おご]/, '').replace(/ /g, '');
|
|
240
|
+
if (!bare || NOT_NAMES.indexOf(bare) >= 0 || NOT_NAMES.indexOf(name.replace(/ /g, '')) >= 0) return;
|
|
241
|
+
if (m[1] === '様' && /[同仕模異多有左]$/.test(bare)) return; // 同様・仕様・模様など
|
|
242
|
+
if (/^[一二三四五六七八九十]+[人名]$/.test(bare)) return; // お一人様・二名様
|
|
243
|
+
var nm = name.replace(/ +$/, '').replace(/^[おご](?=.)/, '');
|
|
244
|
+
add({ type: 'name', key: bare.replace(TITLE_TAIL, '') || bare, parts: nm.replace(TITLE_TAIL, '').split(/ +/).filter(Boolean) }, i, e);
|
|
245
|
+
});
|
|
246
|
+
each(/\b(?:Dear\s+(?:(?:Mr|Ms|Mrs|Mx|Dr|Miss)\.?\s+)?|(?:Mr|Ms|Mrs|Mx|Dr)\.?\s+|Miss\s+)([A-Z][A-Za-z'’-]+(?:\s+[A-Z][A-Za-z'’-]+)?)/g, function (m, s, e) {
|
|
247
|
+
var nm = m[1];
|
|
248
|
+
if (NOT_NAMES_EN.indexOf(nm.toLowerCase()) >= 0 || NOT_NAMES_EN.indexOf(nm.split(/\s+/)[0].toLowerCase()) >= 0) return;
|
|
249
|
+
add({ type: 'name', key: nm.replace(/\s+/g, ''), parts: nm.split(/\s+/) }, e - nm.length, e);
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
// そのほかの番号(3桁以上・123-4567 など)
|
|
253
|
+
each(/(?<![\d,.])\d{1,3}(?:,\d{3})+(?![\d,])|(?<![\d-])\d[\d-]{1,}\d(?![\d-])/g, function (m, s, e) {
|
|
254
|
+
var dg = digits(m[0]);
|
|
255
|
+
if (dg.length >= 3) add({ type: 'number', key: /,/.test(m[0]) ? String(num(m[0])) : dg }, s, e);
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
// 日だけの日付に、同じ文章の前の日付の月を入れる
|
|
259
|
+
toks.sort(function (a, b) { return a.start - b.start; });
|
|
260
|
+
var lastM = 0, lastY = 0;
|
|
261
|
+
toks.forEach(function (k) {
|
|
262
|
+
if (k.type !== 'date') return;
|
|
263
|
+
if (k.m) { lastM = k.m; lastY = k.y; } else if (lastM) { k.m = lastM; k.y = k.y || lastY; k.inherited = true; }
|
|
264
|
+
});
|
|
265
|
+
return { tokens: toks, norm: N };
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
var NAME_CH = '\\p{Script=Han}々〆ヵヶ\\p{Script=Katakana}ーA-Za-z\'’';
|
|
269
|
+
function nameRe(key) {
|
|
270
|
+
var body = Array.from(key).map(function (c) { return c.replace(/[.*+?^${}()|[\]\\\/]/g, '\\$&'); }).join(' ?');
|
|
271
|
+
return new RegExp('(?<![' + NAME_CH + '])' + body + '(?![' + NAME_CH + '])', 'gu');
|
|
272
|
+
}
|
|
273
|
+
function dateMatch(a, b) {
|
|
274
|
+
if (a.d !== b.d) return false;
|
|
275
|
+
if (a.m && b.m && a.m !== b.m) return false;
|
|
276
|
+
if (a.y && b.y && a.y !== b.y) return false;
|
|
277
|
+
return true;
|
|
278
|
+
}
|
|
279
|
+
function matches(r, s) {
|
|
280
|
+
if (r.type === 'date') return s.type === 'date' && dateMatch(r, s);
|
|
281
|
+
if (r.type === 'time') return s.type === 'time' && r.keys.some(function (k) { return s.keys.indexOf(k) >= 0; });
|
|
282
|
+
if (r.type === 'weekday') return (s.type === 'weekday' && r.wds.every(function (w) { return s.wds.indexOf(w) >= 0; })) || (s.type === 'date' && r.wds.length === 1 && s.wd === r.wds[0]);
|
|
283
|
+
if (r.type === 'phone' || r.type === 'number') return (s.type === 'phone' || s.type === 'number') && s.key === r.key;
|
|
284
|
+
// 宛名は敬称・空白を除いた名前が一致すること。姓だけ・名だけは、相手が空白で区切って書いた部分と一致するときだけ(「林」と「小林」は別人)
|
|
285
|
+
// 逆向き(原文が「田中様」・返信案が「田中 次郎様」)は緑にしない。原文に無い「次郎」を足しているため
|
|
286
|
+
// 数量は数と単位が同じこと。両方に区分(adult・child)があり、それが食い違うときだけ一致にしない
|
|
287
|
+
if (r.type === 'qty') return s.type === 'qty' && s.key === r.key && (!r.label || !s.label || r.label === s.label);
|
|
288
|
+
if (r.type === 'name') return s.type === 'name' && (s.key === r.key || (s.parts || []).indexOf(r.key) >= 0);
|
|
289
|
+
return s.type === r.type && s.key === r.key;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// 照らし合わせる。received・facts のどちらかに同じものがあれば緑、無ければ赤、消し忘れは黄
|
|
293
|
+
function checkReply(received, reply, facts, opts) {
|
|
294
|
+
opts = opts || {};
|
|
295
|
+
var today = opts.today instanceof Date ? opts.today : new Date();
|
|
296
|
+
var R = extract(reply), S = [{ id: 'received', x: extract(received) }, { id: 'facts', x: extract(facts || '') }];
|
|
297
|
+
var items = [], MAX_HITS = 20, nameHits = {};
|
|
298
|
+
R.tokens.forEach(function (tok) {
|
|
299
|
+
var it = { type: tok.type, text: tok.text, start: tok.start, end: tok.end, status: 'green', reasons: [], hits: [] };
|
|
300
|
+
if (tok.type === 'placeholder') { it.status = 'yellow'; it.reasons.push('placeholder'); items.push(it); return; }
|
|
301
|
+
// 一致の記録は1件あたり MAX_HITS 箇所まで(同じ語が大量にある文章でメモリを使い切らない)
|
|
302
|
+
for (var si = 0; si < S.length && it.hits.length < MAX_HITS; si++) {
|
|
303
|
+
var sts = S[si].x.tokens;
|
|
304
|
+
for (var ti = 0; ti < sts.length && it.hits.length < MAX_HITS; ti++) {
|
|
305
|
+
var st = sts[ti];
|
|
306
|
+
if (matches(tok, st)) it.hits.push({ src: S[si].id, start: st.start, end: st.end, y: st.y || 0, m: st.m || 0 });
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
// 署名・名乗り(「森川 結衣」「井上です」)は原文の中を探す。前後が名前の文字に続いていないこと(「小林」の中の「林」は数えない)
|
|
310
|
+
// 同じ名前は1回だけ探す
|
|
311
|
+
if (tok.type === 'name' && !it.hits.length) {
|
|
312
|
+
if (!Object.prototype.hasOwnProperty.call(nameHits, tok.key)) {
|
|
313
|
+
var found = [];
|
|
314
|
+
S.forEach(function (src) {
|
|
315
|
+
var N = src.x.norm, re = nameRe(tok.key), m;
|
|
316
|
+
while (found.length < MAX_HITS && (m = re.exec(N.t))) { var o = toOrig(N, m.index, m.index + m[0].length); found.push({ src: src.id, start: o[0], end: o[1] }); }
|
|
317
|
+
});
|
|
318
|
+
nameHits[tok.key] = found;
|
|
319
|
+
}
|
|
320
|
+
it.hits = nameHits[tok.key].slice();
|
|
321
|
+
}
|
|
322
|
+
if (!it.hits.length) { it.status = 'red'; it.reasons.push('missing'); }
|
|
323
|
+
if (tok.type === 'date' && tok.wd >= 0) {
|
|
324
|
+
var m = tok.m, y = tok.y;
|
|
325
|
+
if (!m) { var h0 = it.hits.filter(function (h) { return h.m; })[0]; if (h0) { m = h0.m; y = y || h0.y; } }
|
|
326
|
+
if (!y) { var hy = it.hits.filter(function (h) { return h.y; })[0]; if (hy) y = hy.y; }
|
|
327
|
+
if (m) {
|
|
328
|
+
y = y || inferYear(m, tok.d, today);
|
|
329
|
+
var real = weekdayOf(y, m, tok.d);
|
|
330
|
+
it.date = { y: y, m: m, d: tok.d, written: tok.wd, actual: real };
|
|
331
|
+
if (real !== tok.wd) { it.status = 'red'; it.reasons.push(real < 0 ? 'nodate' : 'weekday'); }
|
|
332
|
+
}
|
|
333
|
+
} else if (tok.type === 'date' && tok.m) {
|
|
334
|
+
var yy = tok.y || inferYear(tok.m, tok.d, today);
|
|
335
|
+
if (weekdayOf(yy, tok.m, tok.d) < 0) { it.status = 'red'; it.reasons.push('nodate'); it.date = { y: yy, m: tok.m, d: tok.d, written: -1, actual: -1 }; }
|
|
336
|
+
}
|
|
337
|
+
items.push(it);
|
|
338
|
+
});
|
|
339
|
+
var count = { red: 0, yellow: 0, green: 0 };
|
|
340
|
+
items.forEach(function (it) { count[it.status]++; });
|
|
341
|
+
return { items: items, count: count };
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
// 見本(架空のメール)。日付は今日から数えて作る(年が変わっても曜日が合う)
|
|
345
|
+
function addDays(d, n) { return new Date(d.getFullYear(), d.getMonth(), d.getDate() + n); }
|
|
346
|
+
function nextWeekday(today, wd, minAhead) { var d = addDays(today, minAhead); while (d.getDay() !== wd) d = addDays(d, 1); return d; }
|
|
347
|
+
function md(d) { return (d.getMonth() + 1) + '月' + d.getDate() + '日'; }
|
|
348
|
+
function wj(d) { return WD_JA[d.getDay()]; }
|
|
349
|
+
function mdEn(d) { return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][d.getMonth()] + ' ' + d.getDate(); }
|
|
350
|
+
function samples(today) {
|
|
351
|
+
var sat = nextWeekday(today, 6, 8), sun = addDays(sat, 1), thu = nextWeekday(today, 4, 8), fri = addDays(thu, 1), sun2 = nextWeekday(today, 0, 10);
|
|
352
|
+
return {
|
|
353
|
+
main: {
|
|
354
|
+
received: '見本亭 ご予約係様\n\nはじめまして。森川と申します。\n' + md(sat) + '(' + wj(sat) + ')の18時30分から、大人4名で夕食の予約をお願いできますか。\nコースはお一人5,500円のものを希望します。\n当日の連絡先は 090-0000-1234 です。\n\n森川 結衣',
|
|
355
|
+
facts: '営業時間 17:00〜23:00(月曜定休)\nコース 5,500円/7,700円\n電話 03-0000-5678',
|
|
356
|
+
reply: '森田様\n\nこのたびは見本亭へご予約のご連絡をいただき、ありがとうございます。\n' + md(sun) + '(' + wj(sat) + ')18:30より、大人4名様でご予約を承りました。\nコースはお一人様6,600円のものをご用意いたします。\n当日は17時より営業しております。お気をつけてお越しください。\nご不明な点は 03-0000-5678 までお電話ください。\n\n見本亭',
|
|
357
|
+
expectRed: ['森田様', md(sun) + '(' + wj(sat) + ')', '6,600円']
|
|
358
|
+
},
|
|
359
|
+
weekday: {
|
|
360
|
+
received: 'こんにちは。PTA広報係の佐々木です。\n次回の打ち合わせは ' + md(fri) + '(' + wj(fri) + ')の10時からでいかがでしょうか。\n場所は図書室を予定しています。',
|
|
361
|
+
facts: '',
|
|
362
|
+
reply: '佐々木様\n\nご連絡ありがとうございます。\n' + md(fri) + '(' + wj(thu) + ')の10時から、図書室で承知しました。\n当日はよろしくお願いいたします。',
|
|
363
|
+
expectRed: [md(fri) + '(' + wj(thu) + ')']
|
|
364
|
+
},
|
|
365
|
+
price: {
|
|
366
|
+
received: 'はじめまして、山本と申します。\n来月の子ども向けクッキー教室に、親子2人で参加したいのですが、料金はおいくらでしょうか。',
|
|
367
|
+
facts: '参加費 1人1,500円(材料費込み)\n時間 10:00〜12:00\n定員 8組',
|
|
368
|
+
reply: '山本様\n\nお問い合わせありがとうございます。\n参加費はお一人1,500円です。親子2人でのご参加をお待ちしております。\n別途、材料費として500円をいただきます。\n時間は10:00〜12:00、定員は8組です。\nキャンセルは前日まで無料、当日は50%を頂戴します。',
|
|
369
|
+
expectRed: ['500円', '50%']
|
|
370
|
+
},
|
|
371
|
+
name: {
|
|
372
|
+
received: '町内会の中村です。\n' + md(sun2) + '(' + wj(sun2) + ')の清掃活動ですが、雨の場合は延期でしょうか。',
|
|
373
|
+
facts: '',
|
|
374
|
+
reply: '中川様\n\nお問い合わせありがとうございます。\n' + md(sun2) + '(' + wj(sun2) + ')の清掃活動は、雨天の場合は翌週に延期します。\n決まり次第、回覧板でお知らせします。',
|
|
375
|
+
expectRed: ['中川様']
|
|
376
|
+
},
|
|
377
|
+
placeholder: {
|
|
378
|
+
received: 'お世話になっております。見本工務店の小林です。\n先日お送りした見積書について、ご確認いただけましたでしょうか。',
|
|
379
|
+
facts: '',
|
|
380
|
+
reply: '[お客様名]様\n\nいつもお世話になっております。〇〇でございます。\nお見積書を拝見しました。XX日までにお返事いたします。\n\n【担当者名】',
|
|
381
|
+
expectRed: [], expectYellow: ['[お客様名]', '〇〇', 'XX', '【担当者名】']
|
|
382
|
+
},
|
|
383
|
+
phone: {
|
|
384
|
+
received: 'はじめまして。ネイルの予約をしたい井上です。\n折り返しのお電話は 080-0000-2468 にお願いします。',
|
|
385
|
+
facts: '',
|
|
386
|
+
reply: '井上様\n\nご連絡ありがとうございます。\n080-0000-2468 に本日中にお電話いたします。',
|
|
387
|
+
expectRed: []
|
|
388
|
+
},
|
|
389
|
+
ok: {
|
|
390
|
+
received: '見本ヨガ教室様\n' + md(thu) + '(' + wj(thu) + ')19時のクラスに、友人と2名で参加できますか。\nメールは yoga-taro@example.com です。\n田村',
|
|
391
|
+
facts: '料金 1回2,000円\nヨガマットの貸出 300円\nhttps://example.com/yoga',
|
|
392
|
+
reply: '田村様\n\nお問い合わせありがとうございます。\n' + md(thu) + '(' + wj(thu) + ')19:00のクラス、2名様で承りました。\n料金はお一人1回2,000円です。ヨガマットの貸出は300円です。\n詳しくは https://example.com/yoga をご覧ください。\n確認のメールを yoga-taro@example.com にお送りします。',
|
|
393
|
+
expectRed: []
|
|
394
|
+
},
|
|
395
|
+
en: {
|
|
396
|
+
received: 'Hi, this is Yui Morikawa.\nCould I book a table for 4 adults on ' + WD_EN_FULL[sat.getDay()] + ', ' + mdEn(sat) + ' at 6:30 pm?\nI would like the $55 course. My number is 090-0000-1234.',
|
|
397
|
+
facts: 'Open 5:00 pm – 11:00 pm, closed on Mondays\nCourses: $55 / $77\nPhone: 03-0000-5678',
|
|
398
|
+
reply: 'Dear Ms. Morita,\n\nThank you for your reservation request.\nWe have booked a table for 4 adults on ' + WD_EN_FULL[sat.getDay()] + ', ' + mdEn(sun) + ' at 6:30 pm.\nWe will prepare the $66 course for you.\nWe open at 5 pm. If you have any questions, please call 03-0000-5678.\n\nMihon-tei',
|
|
399
|
+
expectRed: ['Morita', WD_EN_FULL[sat.getDay()] + ', ' + mdEn(sun), '$66']
|
|
400
|
+
}
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
var WD_EN_FULL = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
|
|
404
|
+
// ===== ここまでコア =====
|
|
405
|
+
|
|
406
|
+
// ---- MCP の入口 ----
|
|
407
|
+
export { normalize, extract, checkReply, inferYear, weekdayOf, samples };
|
|
408
|
+
|
|
409
|
+
export class ReplyCheckError extends Error {
|
|
410
|
+
constructor(code, message) { super(message); this.code = code; }
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
// 1欄あたりの上限(文字数)。拾い出しの正規表現と照合の総当たりは長さの2乗で重くなるため、メール1通に十分な長さで止める
|
|
414
|
+
export const REPLY_CHECK_MAX_CHARS = 20000;
|
|
415
|
+
// 返す項目と、1項目あたりの一致箇所の上限(件数 count は上限で切る前の全件)。応答が数MBにならないようにする
|
|
416
|
+
export const REPLY_CHECK_MAX_ITEMS = 500;
|
|
417
|
+
export const REPLY_CHECK_MAX_HITS = 5;
|
|
418
|
+
|
|
419
|
+
const RC_MSG = {
|
|
420
|
+
ja: {
|
|
421
|
+
missing: '届いたメールにも事実欄にも無い',
|
|
422
|
+
weekday: (d) => d.y + '年' + d.m + '月' + d.d + '日は' + WD_JA[d.actual] + '曜日(' + WD_JA[d.written] + 'ではない)',
|
|
423
|
+
nodate: (d) => d.m + '月' + d.d + '日は存在しない日付',
|
|
424
|
+
placeholder: '記号・仮の文字が残っている',
|
|
425
|
+
note: '赤が0件でも内容の正しさは保証しません。拾うのは日付・曜日・時刻・金額・数量・電話・メール・URL・宛名・番号だけで、文の意味や言い回しは見ていません。',
|
|
426
|
+
},
|
|
427
|
+
en: {
|
|
428
|
+
missing: 'Not in the email or your facts',
|
|
429
|
+
weekday: (d) => d.m + '/' + d.d + '/' + d.y + ' is a ' + WD_EN_FULL[d.actual] + ', not ' + WD_EN_FULL[d.written],
|
|
430
|
+
nodate: (d) => d.m + '/' + d.d + ' does not exist',
|
|
431
|
+
placeholder: 'Placeholder left in the reply',
|
|
432
|
+
note: 'A score of 0 red does not mean the reply is correct. Only dates, weekdays, times, amounts, quantities, phone numbers, emails, URLs, names and numbers are checked — not meaning or tone.',
|
|
433
|
+
},
|
|
434
|
+
};
|
|
435
|
+
|
|
436
|
+
function rcText(v, name) {
|
|
437
|
+
if (v == null) return '';
|
|
438
|
+
if (typeof v !== 'string') throw new ReplyCheckError('INVALID_INPUT', name + ' must be a string');
|
|
439
|
+
if (v.length > REPLY_CHECK_MAX_CHARS) throw new ReplyCheckError('TOO_LONG', name + ' is longer than ' + REPLY_CHECK_MAX_CHARS + ' characters');
|
|
440
|
+
return v;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
function rcToday(s) {
|
|
444
|
+
if (s == null || s === '') return new Date();
|
|
445
|
+
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(s));
|
|
446
|
+
const dt = m ? new Date(+m[1], +m[2] - 1, +m[3]) : null;
|
|
447
|
+
if (!dt || dt.getFullYear() !== +m[1] || dt.getMonth() !== +m[2] - 1 || dt.getDate() !== +m[3]) {
|
|
448
|
+
throw new ReplyCheckError('INVALID_TODAY', 'today must be a real date in YYYY-MM-DD');
|
|
449
|
+
}
|
|
450
|
+
return dt;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
const pad2 = (n) => String(n).padStart(2, '0');
|
|
454
|
+
|
|
455
|
+
export function replyCheckTool(opts = {}) {
|
|
456
|
+
const lang = opts.lang === 'en' ? 'en' : 'ja';
|
|
457
|
+
const L = RC_MSG[lang];
|
|
458
|
+
const reply = rcText(opts.reply, 'reply');
|
|
459
|
+
if (!reply.trim()) throw new ReplyCheckError('REPLY_REQUIRED', 'reply (the AI-drafted reply to check) is required');
|
|
460
|
+
const received = rcText(opts.received, 'received');
|
|
461
|
+
const facts = rcText(opts.facts, 'facts');
|
|
462
|
+
const today = rcToday(opts.today);
|
|
463
|
+
const includeGreen = opts.includeGreen !== false;
|
|
464
|
+
const sources = { received, facts };
|
|
465
|
+
|
|
466
|
+
const r = checkReply(received, reply, facts, { today });
|
|
467
|
+
const lineStarts = [0];
|
|
468
|
+
for (let i = 0; i < reply.length; i++) if (reply[i] === '\n') lineStarts.push(i + 1);
|
|
469
|
+
const lineOf = (pos) => {
|
|
470
|
+
let lo = 0, hi = lineStarts.length - 1;
|
|
471
|
+
while (lo < hi) { const mid = (lo + hi + 1) >> 1; if (lineStarts[mid] <= pos) lo = mid; else hi = mid - 1; }
|
|
472
|
+
return { line: lo + 1, column: pos - lineStarts[lo] + 1 };
|
|
473
|
+
};
|
|
474
|
+
|
|
475
|
+
const picked = r.items.filter((it) => includeGreen || it.status !== 'green');
|
|
476
|
+
const items = picked.slice(0, REPLY_CHECK_MAX_ITEMS).map((it) => {
|
|
477
|
+
const out = { status: it.status, type: it.type, text: it.text, start: it.start, end: it.end, ...lineOf(it.start), reasons: it.reasons.slice() };
|
|
478
|
+
const msgs = it.reasons.map((k) => (k === 'weekday' || k === 'nodate' ? L[k](it.date) : L[k])).filter(Boolean);
|
|
479
|
+
if (msgs.length) out.message = msgs.join(' / ');
|
|
480
|
+
if (it.date) {
|
|
481
|
+
out.date = { date: it.date.y + '-' + pad2(it.date.m) + '-' + pad2(it.date.d) };
|
|
482
|
+
if (it.date.written >= 0) out.date.writtenWeekday = WD_EN_FULL[it.date.written];
|
|
483
|
+
if (it.date.actual >= 0) out.date.actualWeekday = WD_EN_FULL[it.date.actual];
|
|
484
|
+
}
|
|
485
|
+
out.hitCount = it.hits.length;
|
|
486
|
+
out.hits = it.hits.slice(0, REPLY_CHECK_MAX_HITS).map((h) => ({ source: h.src, start: h.start, end: h.end, text: sources[h.src].slice(h.start, h.end) }));
|
|
487
|
+
return out;
|
|
488
|
+
});
|
|
489
|
+
|
|
490
|
+
return {
|
|
491
|
+
count: { ...r.count },
|
|
492
|
+
items,
|
|
493
|
+
truncated: picked.length > items.length,
|
|
494
|
+
note: L.note,
|
|
495
|
+
today: today.getFullYear() + '-' + pad2(today.getMonth() + 1) + '-' + pad2(today.getDate()),
|
|
496
|
+
};
|
|
497
|
+
}
|
package/server.mjs
CHANGED
|
@@ -48,6 +48,8 @@ import { cssLayoutGenerateTool } from './css-layout.mjs';
|
|
|
48
48
|
import { wikiDocLintTool } from './wiki-doc-lint.mjs';
|
|
49
49
|
import { fitToBoxTool } from './fit-to-box.mjs';
|
|
50
50
|
import { invoiceNebikiTool } from './invoice-nebiki.mjs';
|
|
51
|
+
import { comfyPngLeakTool } from './comfy-png-leak.mjs';
|
|
52
|
+
import { replyCheckTool } from './reply-check.mjs';
|
|
51
53
|
|
|
52
54
|
const { version } = createRequire(import.meta.url)('./package.json');
|
|
53
55
|
// SDK v2 の serveStdio は接続ごとに factory から McpServer を1つ作る(旧仕様の initialize と
|
|
@@ -2036,4 +2038,58 @@ registerTool(
|
|
|
2036
2038
|
},
|
|
2037
2039
|
);
|
|
2038
2040
|
|
|
2041
|
+
registerTool(
|
|
2042
|
+
'reply_check',
|
|
2043
|
+
{
|
|
2044
|
+
title: 'AIの返信案の送る前チェック(日付・金額・宛名などの照合)',
|
|
2045
|
+
description:
|
|
2046
|
+
'届いたメール(received)と、任意の「自分で決めた事実」(facts:営業時間・料金・日程など)を、AI が書いた返信案(reply)と照らし合わせる(tools.first-ch.com/okurumae/ と同一ロジック)。' +
|
|
2047
|
+
'返信案から日付・曜日・時刻・金額・数量(〇名・〇泊・%)・電話番号・メールアドレス・URL・宛名(〇〇様・Dear Ms. …)・番号を拾い、received と facts のどちらにも無いものを status=red(reasons に missing)、あるものを green、' +
|
|
2048
|
+
'[お客様1]・〇〇・XX・【】・{name} などの消し忘れを yellow(placeholder)で返す。日付と曜日の食い違い(例: 2026年11月8日(金))と存在しない日付も red(weekday / nodate・date に実際の曜日)。' +
|
|
2049
|
+
'年の書かれていない日付は today の60日前〜305日後に入る年で曜日を確かめる。全角/半角・カンマ・「18時30分」と「18:30」・「3千円」と「3,000円」は照合のときだけそろえ、本文は書き換えない。' +
|
|
2050
|
+
'items の start / end は reply の中の位置(JavaScript の文字列の添字=UTF-16)、line / column は1始まり。hits は一致した原文の箇所(1項目5件まで・hitCount は全数)。' +
|
|
2051
|
+
'count は全項目の件数で、items は500件まで(超えたら truncated:true)。赤が0件でも内容の正しさは保証しない(note)。自動修正・文体の添削・伏せ字はしない。' +
|
|
2052
|
+
'各欄2万字まで。入力の誤りは ReplyCheckError(code 付き)。完全ローカル処理・ネットワーク送信なし。',
|
|
2053
|
+
inputSchema: {
|
|
2054
|
+
received: z.string().optional().describe('届いたメール(返信の元になった原文)'),
|
|
2055
|
+
reply: z.string().describe('AI が書いた返信案(照合する文章)'),
|
|
2056
|
+
facts: z.string().optional().describe('自分で決めた事実(営業時間・料金・日程・電話番号など。任意)'),
|
|
2057
|
+
today: z.string().optional().describe('基準日 YYYY-MM-DD(年の無い日付の年を決めるのに使う。省略時はサーバーの今日)'),
|
|
2058
|
+
includeGreen: z.boolean().optional().describe('緑(一致した項目)も items に入れるか(既定 true)'),
|
|
2059
|
+
lang: z.enum(['ja', 'en']).optional().describe("message・note の言語(既定 'ja')"),
|
|
2060
|
+
},
|
|
2061
|
+
},
|
|
2062
|
+
async (opts) => {
|
|
2063
|
+
await logUsage('reply_check');
|
|
2064
|
+
return asText(replyCheckTool(opts));
|
|
2065
|
+
},
|
|
2066
|
+
);
|
|
2067
|
+
|
|
2068
|
+
registerTool(
|
|
2069
|
+
'comfy_png_leak_scan',
|
|
2070
|
+
{
|
|
2071
|
+
title: '受け取ったComfyUI画像のキー点検とお知らせ文',
|
|
2072
|
+
description:
|
|
2073
|
+
'ComfyUI の PNG の埋め込みデータ(tEXt・非圧縮 iTXt の prompt・workflow など)から APIキーの形(AIza・sk-・sk-ant-・hf_・r8_)を探す(tools.first-ch.com/comfy-key-leak/ と同一ロジック)。' +
|
|
2074
|
+
'status は found(キーの形あり)/ none(見つからず。安全という意味ではない)/ unchecked(zTXt・圧縮 iTXt・eXIf・caBX・不明なチャンク・IEND の後ろ・30MB超で読めない部分がある)/ failed(CRC 不一致・途中で切れた・PNG でない)。' +
|
|
2075
|
+
'findings の場所は prompt なら nodeId・classType・input、workflow だけなら nodeId と widgetIndex(入力欄名は特定できない・fieldUnknown)。JSON は重複キーの前の値も捨てずに読み、inputs の外(extra)・迂回ノード(bypassed)・JSON の外の文字も拾う。ノードの表示名(title)は使わない。' +
|
|
2076
|
+
'値は返さない(masked=先頭4字+伏せ字と length だけ)。notice はキーの持ち主へのお知らせ文(値・ファイル名なし、有効性と原因は確認していないと書く)。revoke は見つかった種類の公式の無効化画面。' +
|
|
2077
|
+
'outPath を渡すと tEXt・iTXt・zTXt を抜いたコピーを書き、書く前に読み直して文字のチャンク0個・残したチャンクのバイト一致を確かめる(元のファイルは変えない・caBX 付きと壊れた PNG は書き換えない・既存ファイルは overwrite:true が無いと上書きしない)。' +
|
|
2078
|
+
'キーが有効かどうかの確認・URL からの取得・JPEG/WebP の書き換えはしない。このツールはネットワークへ何も送らない。' +
|
|
2079
|
+
'入力は path を優先する: base64 で渡すと画像のバイト列(埋め込まれた生のキーを含む)が会話に載り、モデルの提供元へ渡る(そのとき返り値に inputNote が付く)。',
|
|
2080
|
+
inputSchema: {
|
|
2081
|
+
path: z.string().optional().describe('PNG の絶対パス(path か base64 のどちらか。こちらを優先)'),
|
|
2082
|
+
base64: z.string().optional().describe('PNG の Base64(data URI 可)。画像と埋め込まれたキーが会話に載りモデルの提供元へ渡るので、path が使えないときだけ'),
|
|
2083
|
+
outPath: z.string().optional().describe('文字のチャンクを抜いたコピーの書き出し先(絶対パス・任意)'),
|
|
2084
|
+
overwrite: z.boolean().optional().describe('outPath に既存ファイルがあるとき上書きするか(既定 false)'),
|
|
2085
|
+
includeUrl: z.boolean().optional().describe('お知らせ文に、同じ点検ができるページ(tools.first-ch.com)の URL を添えるか(既定 true)'),
|
|
2086
|
+
lang: z.enum(['ja', 'en']).optional().describe("文言の言語(既定 'ja')"),
|
|
2087
|
+
},
|
|
2088
|
+
},
|
|
2089
|
+
async (opts) => {
|
|
2090
|
+
await logUsage('comfy_png_leak_scan');
|
|
2091
|
+
return asText(await comfyPngLeakTool(opts));
|
|
2092
|
+
},
|
|
2093
|
+
);
|
|
2094
|
+
|
|
2039
2095
|
serveStdio(buildServer);
|