@first-ch/tools-mcp 0.4.1 → 0.24.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 +52 -4
- package/aspect-ratio.mjs +706 -0
- package/base64.mjs +356 -0
- package/color.mjs +629 -0
- package/cron.mjs +633 -0
- package/diff.mjs +322 -0
- package/hash.mjs +234 -0
- package/html-escape.mjs +308 -0
- package/json-yaml.mjs +1693 -0
- package/jwt.mjs +639 -0
- package/lib.mjs +103 -0
- package/markdown-table.mjs +641 -0
- package/marp-theme.css +51 -0
- package/marp.mjs +219 -0
- package/package.json +130 -3
- package/px-rem.mjs +488 -0
- package/qr.mjs +744 -0
- package/server.mjs +942 -2
- package/sql-format.mjs +694 -0
- package/testdata.mjs +608 -0
- package/unixtime.mjs +505 -0
- package/url.mjs +415 -0
- package/user-agent.mjs +633 -0
- package/uuid.mjs +238 -0
package/diff.mjs
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
// テキスト・コード差分(diff_check)
|
|
2
|
+
// アルゴリズムは tools.first-ch.com/diff/ の site/diff/app.js と同一(site側が正本)。
|
|
3
|
+
//
|
|
4
|
+
// 行差分は patience diff(両方に1回だけ現れる行をアンカーにして分割)+
|
|
5
|
+
// アンカーが取れない区間だけ Myers O(ND)。Myers は編集距離が MAX_D を超えたら
|
|
6
|
+
// その区間を丸ごと「削除+追加」に落とす(巨大な無関係ファイル同士で固まらないため)。
|
|
7
|
+
// 変更行の対応付けができたペアだけ、さらにトークン単位の差分を取って
|
|
8
|
+
// 語(和文は1文字)単位の変更点を返す。
|
|
9
|
+
|
|
10
|
+
const MAX_D = 1200; // Myers の編集距離の上限
|
|
11
|
+
export const MAX_LINES = 50000; // 1入力あたりの行数上限
|
|
12
|
+
|
|
13
|
+
/** 比較用のキーへ正規化する(表示は常に元の行を使う) */
|
|
14
|
+
function normalize(line, opt) {
|
|
15
|
+
let s = line;
|
|
16
|
+
if (opt.ignoreWhitespace) s = s.replace(/\s+/g, ' ').trim();
|
|
17
|
+
else if (opt.ignoreTrailing) s = s.replace(/[ \t]+$/, '');
|
|
18
|
+
if (opt.ignoreCase) s = s.toLowerCase();
|
|
19
|
+
return s;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** 両方にちょうど1回だけ現れる行を拾い、b側の位置の最長増加部分列を返す(patience diff) */
|
|
23
|
+
function uniqueAnchors(a, b, a0, a1, b0, b1) {
|
|
24
|
+
const ca = new Map();
|
|
25
|
+
const cb = new Map();
|
|
26
|
+
for (let i = a0; i < a1; i++) ca.set(a[i], (ca.get(a[i]) || 0) + 1);
|
|
27
|
+
for (let j = b0; j < b1; j++) cb.set(b[j], (cb.get(b[j]) || 0) + 1);
|
|
28
|
+
const posB = new Map();
|
|
29
|
+
for (let j = b0; j < b1; j++) if (cb.get(b[j]) === 1) posB.set(b[j], j);
|
|
30
|
+
const pairs = [];
|
|
31
|
+
for (let i = a0; i < a1; i++) {
|
|
32
|
+
if (ca.get(a[i]) !== 1) continue;
|
|
33
|
+
const j = posB.get(a[i]);
|
|
34
|
+
if (j !== undefined) pairs.push([i, j]);
|
|
35
|
+
}
|
|
36
|
+
if (!pairs.length) return [];
|
|
37
|
+
// pairs は i の昇順。j の最長増加部分列(O(k log k))
|
|
38
|
+
const tail = [];
|
|
39
|
+
const prev = new Int32Array(pairs.length).fill(-1);
|
|
40
|
+
for (let k = 0; k < pairs.length; k++) {
|
|
41
|
+
const j = pairs[k][1];
|
|
42
|
+
let lo = 0;
|
|
43
|
+
let hi = tail.length;
|
|
44
|
+
while (lo < hi) {
|
|
45
|
+
const mid = (lo + hi) >> 1;
|
|
46
|
+
if (pairs[tail[mid]][1] < j) lo = mid + 1;
|
|
47
|
+
else hi = mid;
|
|
48
|
+
}
|
|
49
|
+
if (lo > 0) prev[k] = tail[lo - 1];
|
|
50
|
+
tail[lo] = k;
|
|
51
|
+
}
|
|
52
|
+
const out = [];
|
|
53
|
+
let k = tail[tail.length - 1];
|
|
54
|
+
while (k >= 0) {
|
|
55
|
+
out.push(pairs[k]);
|
|
56
|
+
k = prev[k];
|
|
57
|
+
}
|
|
58
|
+
return out.reverse();
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* 行(またはトークン)の配列2本の差分を取る。
|
|
63
|
+
* @returns {Array<{t:'='|'-'|'+', a:number, b:number}>} a/b は元配列の添字(無い側は -1)
|
|
64
|
+
*/
|
|
65
|
+
export function diffSeq(a, b) {
|
|
66
|
+
const out = [];
|
|
67
|
+
const push = (t, i, j) => out.push({ t, a: i, b: j });
|
|
68
|
+
|
|
69
|
+
function myers(a0, a1, b0, b1) {
|
|
70
|
+
const n = a1 - a0;
|
|
71
|
+
const m = b1 - b0;
|
|
72
|
+
const maxD = Math.min(n + m, MAX_D);
|
|
73
|
+
const off = maxD;
|
|
74
|
+
const v = new Int32Array(2 * maxD + 1);
|
|
75
|
+
const trace = [];
|
|
76
|
+
let found = -1;
|
|
77
|
+
for (let d = 0; d <= maxD && found < 0; d++) {
|
|
78
|
+
trace.push(v.slice());
|
|
79
|
+
for (let k = -d; k <= d; k += 2) {
|
|
80
|
+
let x;
|
|
81
|
+
if (k === -d || (k !== d && v[off + k - 1] < v[off + k + 1])) x = v[off + k + 1];
|
|
82
|
+
else x = v[off + k - 1] + 1;
|
|
83
|
+
let y = x - k;
|
|
84
|
+
while (x < n && y < m && a[a0 + x] === b[b0 + y]) { x++; y++; }
|
|
85
|
+
v[off + k] = x;
|
|
86
|
+
if (x >= n && y >= m) { found = d; break; }
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
if (found < 0) {
|
|
90
|
+
// 上限超過。この区間は「まるごと置き換え」として出す
|
|
91
|
+
for (let i = a0; i < a1; i++) push('-', i, -1);
|
|
92
|
+
for (let j = b0; j < b1; j++) push('+', -1, j);
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
const rev = [];
|
|
96
|
+
let x = n;
|
|
97
|
+
let y = m;
|
|
98
|
+
for (let d = found; d > 0; d--) {
|
|
99
|
+
const vp = trace[d];
|
|
100
|
+
const k = x - y;
|
|
101
|
+
const prevK = (k === -d || (k !== d && vp[off + k - 1] < vp[off + k + 1])) ? k + 1 : k - 1;
|
|
102
|
+
const px = vp[off + prevK];
|
|
103
|
+
const py = px - prevK;
|
|
104
|
+
while (x > px && y > py) { x--; y--; rev.push(['=', a0 + x, b0 + y]); }
|
|
105
|
+
if (x > px) { x--; rev.push(['-', a0 + x, -1]); }
|
|
106
|
+
else if (y > py) { y--; rev.push(['+', -1, b0 + y]); }
|
|
107
|
+
}
|
|
108
|
+
while (x > 0 && y > 0) { x--; y--; rev.push(['=', a0 + x, b0 + y]); }
|
|
109
|
+
for (let t = rev.length - 1; t >= 0; t--) push(rev[t][0], rev[t][1], rev[t][2]);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function middle(a0, a1, b0, b1) {
|
|
113
|
+
if (a0 >= a1 && b0 >= b1) return;
|
|
114
|
+
if (a0 >= a1) { for (let j = b0; j < b1; j++) push('+', -1, j); return; }
|
|
115
|
+
if (b0 >= b1) { for (let i = a0; i < a1; i++) push('-', i, -1); return; }
|
|
116
|
+
const anchors = uniqueAnchors(a, b, a0, a1, b0, b1);
|
|
117
|
+
if (!anchors.length) { myers(a0, a1, b0, b1); return; }
|
|
118
|
+
let ai = a0;
|
|
119
|
+
let bi = b0;
|
|
120
|
+
for (const [i, j] of anchors) {
|
|
121
|
+
walk(ai, i, bi, j);
|
|
122
|
+
push('=', i, j);
|
|
123
|
+
ai = i + 1;
|
|
124
|
+
bi = j + 1;
|
|
125
|
+
}
|
|
126
|
+
walk(ai, a1, bi, b1);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function walk(a0, a1, b0, b1) {
|
|
130
|
+
while (a0 < a1 && b0 < b1 && a[a0] === b[b0]) { push('=', a0, b0); a0++; b0++; }
|
|
131
|
+
let tail = 0;
|
|
132
|
+
while (a1 - tail > a0 && b1 - tail > b0 && a[a1 - 1 - tail] === b[b1 - 1 - tail]) tail++;
|
|
133
|
+
middle(a0, a1 - tail, b0, b1 - tail);
|
|
134
|
+
for (let t = 0; t < tail; t++) push('=', a1 - tail + t, b1 - tail + t);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
walk(0, a.length, 0, b.length);
|
|
138
|
+
return out;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// 語(英数字の連なり)は1トークン、和文・記号は1文字ずつ。和文は分かち書きが無いため
|
|
142
|
+
// まとめると行全体が1トークンになり、単語ハイライトが機能しない
|
|
143
|
+
const TOKEN_RE = /[A-Za-z0-9_]+|\s+|[\s\S]/gu;
|
|
144
|
+
const tokenize = (s) => s.match(TOKEN_RE) || [];
|
|
145
|
+
|
|
146
|
+
/** 行を配列にする。末尾の改行だけの空行は落とす(差分に無意味な1行が出るため) */
|
|
147
|
+
export function splitLines(text) {
|
|
148
|
+
const t = String(text).replace(/\r\n?/g, '\n');
|
|
149
|
+
if (t === '') return [];
|
|
150
|
+
const lines = t.split('\n');
|
|
151
|
+
if (lines.length > 1 && lines[lines.length - 1] === '') lines.pop();
|
|
152
|
+
return lines;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** 隣り合う同種の断片をつなぐ(<del>,</del><del> </del>… と分かれると読みにくいため) */
|
|
156
|
+
function mergeParts(parts) {
|
|
157
|
+
const out = [];
|
|
158
|
+
for (const p of parts) {
|
|
159
|
+
const last = out[out.length - 1];
|
|
160
|
+
if (last && last.c === p.c) last.s += p.s;
|
|
161
|
+
else out.push({ c: p.c, s: p.s });
|
|
162
|
+
}
|
|
163
|
+
return out;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** 削除行と追加行を上から順に対応づけ、似ている組だけトークン差分を持たせる */
|
|
167
|
+
function pairWords(del, ins, opt) {
|
|
168
|
+
const n = Math.min(del.length, ins.length);
|
|
169
|
+
for (let k = 0; k < n; k++) {
|
|
170
|
+
const ta = tokenize(del[k].text);
|
|
171
|
+
const tb = tokenize(ins[k].text);
|
|
172
|
+
if (ta.length + tb.length > 4000) continue; // 極端に長い行は語差分を諦める(行単位で見せる)
|
|
173
|
+
const ka = ta.map((s) => normalize(s, { ignoreWhitespace: false, ignoreCase: opt.ignoreCase }));
|
|
174
|
+
const kb = tb.map((s) => normalize(s, { ignoreWhitespace: false, ignoreCase: opt.ignoreCase }));
|
|
175
|
+
const ops = diffSeq(ka, kb);
|
|
176
|
+
let same = 0;
|
|
177
|
+
for (const o of ops) if (o.t === '=') same += ta[o.a].length;
|
|
178
|
+
const len = Math.max(del[k].text.length, ins[k].text.length, 1);
|
|
179
|
+
// 共通部分が少なすぎる組は「別の行」。無理に語ハイライトすると読めなくなる
|
|
180
|
+
if (same / len < 0.3) continue;
|
|
181
|
+
del[k].parts = mergeParts(ops.filter((o) => o.t !== '+').map((o) => ({ c: o.t === '=', s: ta[o.a] })));
|
|
182
|
+
ins[k].parts = mergeParts(ops.filter((o) => o.t !== '-').map((o) => ({ c: o.t === '=', s: tb[o.b] })));
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* 差分を「ブロック」の列にまとめる。
|
|
188
|
+
* blocks: {t:'equal', rows:[{a,b,text}]} | {t:'change', del:[{a,text,parts?}], ins:[{b,text,parts?}]}
|
|
189
|
+
*/
|
|
190
|
+
export function buildDiff(textA, textB, options) {
|
|
191
|
+
const opt = Object.assign(
|
|
192
|
+
{ ignoreWhitespace: false, ignoreCase: false, ignoreTrailing: true, words: true },
|
|
193
|
+
options,
|
|
194
|
+
);
|
|
195
|
+
const A = splitLines(textA);
|
|
196
|
+
const B = splitLines(textB);
|
|
197
|
+
const truncated = A.length > MAX_LINES || B.length > MAX_LINES;
|
|
198
|
+
if (truncated) { A.length = Math.min(A.length, MAX_LINES); B.length = Math.min(B.length, MAX_LINES); }
|
|
199
|
+
const ka = A.map((l) => normalize(l, opt));
|
|
200
|
+
const kb = B.map((l) => normalize(l, opt));
|
|
201
|
+
const ops = diffSeq(ka, kb);
|
|
202
|
+
|
|
203
|
+
const blocks = [];
|
|
204
|
+
const stats = { added: 0, removed: 0, changed: 0, same: 0 };
|
|
205
|
+
let i = 0;
|
|
206
|
+
while (i < ops.length) {
|
|
207
|
+
if (ops[i].t === '=') {
|
|
208
|
+
const rows = [];
|
|
209
|
+
while (i < ops.length && ops[i].t === '=') { rows.push({ a: ops[i].a, b: ops[i].b, text: A[ops[i].a] }); i++; }
|
|
210
|
+
stats.same += rows.length;
|
|
211
|
+
blocks.push({ t: 'equal', rows });
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
// 連続する非一致をひとまとめにする('+' が '-' より先に来ることもあるため分けて集める)
|
|
215
|
+
const del = [];
|
|
216
|
+
const ins = [];
|
|
217
|
+
while (i < ops.length && ops[i].t !== '=') {
|
|
218
|
+
if (ops[i].t === '-') del.push({ a: ops[i].a, text: A[ops[i].a] });
|
|
219
|
+
else ins.push({ b: ops[i].b, text: B[ops[i].b] });
|
|
220
|
+
i++;
|
|
221
|
+
}
|
|
222
|
+
const paired = Math.min(del.length, ins.length);
|
|
223
|
+
stats.changed += paired;
|
|
224
|
+
stats.removed += del.length - paired;
|
|
225
|
+
stats.added += ins.length - paired;
|
|
226
|
+
if (opt.words) pairWords(del, ins, opt);
|
|
227
|
+
blocks.push({ t: 'change', del, ins });
|
|
228
|
+
}
|
|
229
|
+
return { blocks, stats, truncated, linesA: A.length, linesB: B.length };
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** unified diff(.patch)を組み立てる。context は前後に残す同一行の数 */
|
|
233
|
+
export function toUnified(textA, textB, options, nameA, nameB, context) {
|
|
234
|
+
const ctx = context == null ? 3 : context;
|
|
235
|
+
const A = splitLines(textA);
|
|
236
|
+
const B = splitLines(textB);
|
|
237
|
+
const opt = Object.assign({ ignoreTrailing: true }, options);
|
|
238
|
+
const ops = diffSeq(A.map((l) => normalize(l, opt)), B.map((l) => normalize(l, opt)));
|
|
239
|
+
const changed = ops.map((o) => o.t !== '=');
|
|
240
|
+
if (!changed.some(Boolean)) return '';
|
|
241
|
+
// 変更点の前後 ctx 行を含む範囲をまとめてハンクにする
|
|
242
|
+
const keep = new Array(ops.length).fill(false);
|
|
243
|
+
for (let i = 0; i < ops.length; i++) {
|
|
244
|
+
if (!changed[i]) continue;
|
|
245
|
+
for (let j = Math.max(0, i - ctx); j <= Math.min(ops.length - 1, i + ctx); j++) keep[j] = true;
|
|
246
|
+
}
|
|
247
|
+
const out = [`--- ${nameA || 'a'}`, `+++ ${nameB || 'b'}`];
|
|
248
|
+
let i = 0;
|
|
249
|
+
while (i < ops.length) {
|
|
250
|
+
if (!keep[i]) { i++; continue; }
|
|
251
|
+
let end = i;
|
|
252
|
+
while (end < ops.length && keep[end]) end++;
|
|
253
|
+
let aStart = -1;
|
|
254
|
+
let bStart = -1;
|
|
255
|
+
let aCount = 0;
|
|
256
|
+
let bCount = 0;
|
|
257
|
+
const body = [];
|
|
258
|
+
for (let k = i; k < end; k++) {
|
|
259
|
+
const o = ops[k];
|
|
260
|
+
if (o.a >= 0) { if (aStart < 0) aStart = o.a; aCount++; }
|
|
261
|
+
if (o.b >= 0) { if (bStart < 0) bStart = o.b; bCount++; }
|
|
262
|
+
body.push((o.t === '=' ? ' ' : o.t) + (o.t === '+' ? B[o.b] : A[o.a]));
|
|
263
|
+
}
|
|
264
|
+
out.push(`@@ -${aCount ? aStart + 1 : 0},${aCount} +${bCount ? bStart + 1 : 0},${bCount} @@`);
|
|
265
|
+
out.push(...body);
|
|
266
|
+
i = end;
|
|
267
|
+
}
|
|
268
|
+
return out.join('\n') + '\n';
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* MCP `diff_check` の本体。2つのテキストを比較して統計・unified diff・変更ハンクを返す。
|
|
273
|
+
* @param {string} a 変更前テキスト
|
|
274
|
+
* @param {string} b 変更後テキスト
|
|
275
|
+
* @param {object} opts { ignoreWhitespace, ignoreCase, words, context, format, nameA, nameB }
|
|
276
|
+
*/
|
|
277
|
+
export function diffCheck(a, b, opts = {}) {
|
|
278
|
+
const options = {
|
|
279
|
+
ignoreWhitespace: !!opts.ignoreWhitespace,
|
|
280
|
+
ignoreCase: !!opts.ignoreCase,
|
|
281
|
+
ignoreTrailing: true,
|
|
282
|
+
words: opts.words !== false,
|
|
283
|
+
};
|
|
284
|
+
const format = opts.format || 'unified';
|
|
285
|
+
const { blocks, stats, truncated, linesA, linesB } = buildDiff(a, b, options);
|
|
286
|
+
const identical = blocks.every((blk) => blk.t === 'equal');
|
|
287
|
+
const result = {
|
|
288
|
+
identical,
|
|
289
|
+
lines_a: linesA,
|
|
290
|
+
lines_b: linesB,
|
|
291
|
+
added: stats.added,
|
|
292
|
+
removed: stats.removed,
|
|
293
|
+
changed: stats.changed,
|
|
294
|
+
unchanged: stats.same,
|
|
295
|
+
ignore_whitespace: options.ignoreWhitespace,
|
|
296
|
+
ignore_case: options.ignoreCase,
|
|
297
|
+
};
|
|
298
|
+
if (truncated) result.note = `各テキストの先頭 ${MAX_LINES} 行までを比較しました。`;
|
|
299
|
+
if (identical) return result;
|
|
300
|
+
|
|
301
|
+
if (format === 'unified' || format === 'both') {
|
|
302
|
+
result.unified = toUnified(a, b, options, opts.nameA || 'a', opts.nameB || 'b', opts.context);
|
|
303
|
+
}
|
|
304
|
+
if (format === 'blocks' || format === 'both') {
|
|
305
|
+
// 変更のあったブロックだけを、行番号(1始まり)と語単位の変更点つきで返す
|
|
306
|
+
result.changes = blocks
|
|
307
|
+
.filter((blk) => blk.t === 'change')
|
|
308
|
+
.map((blk) => ({
|
|
309
|
+
removed: blk.del.map((r) => ({
|
|
310
|
+
line: r.a + 1,
|
|
311
|
+
text: r.text,
|
|
312
|
+
...(r.parts ? { changed_parts: r.parts.filter((p) => !p.c).map((p) => p.s) } : {}),
|
|
313
|
+
})),
|
|
314
|
+
added: blk.ins.map((r) => ({
|
|
315
|
+
line: r.b + 1,
|
|
316
|
+
text: r.text,
|
|
317
|
+
...(r.parts ? { changed_parts: r.parts.filter((p) => !p.c).map((p) => p.s) } : {}),
|
|
318
|
+
})),
|
|
319
|
+
}));
|
|
320
|
+
}
|
|
321
|
+
return result;
|
|
322
|
+
}
|
package/hash.mjs
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
// MD5 / SHA-1 / SHA-256 / SHA-384 / SHA-512 のハッシュ生成と照合
|
|
2
|
+
// (tools.first-ch.com/hash/ と同一の仕様)
|
|
3
|
+
//
|
|
4
|
+
// site 側(site/hash/app.js)はブラウザの Web Crypto でSHA系を計算し、Web Cryptoに無い
|
|
5
|
+
// MD5 だけを RFC 1321 のJavaScript実装で持っている。Nodeでは node:crypto が5種類すべてを
|
|
6
|
+
// 持っているのでそちらを使う(=実装は別物)。
|
|
7
|
+
// 2箇所ルール: 出力の書式・期待値の読み取り・入力の正規化(改行コード / BOM)は
|
|
8
|
+
// site 側と同じ挙動にする。片方を直したらもう片方も直す(site側が正本)。
|
|
9
|
+
// どちらの実装も test.mjs / ブラウザ側の検証で RFC の既知テストベクタと突き合わせている。
|
|
10
|
+
import { createHash } from 'node:crypto';
|
|
11
|
+
import { readFile, stat } from 'node:fs/promises';
|
|
12
|
+
import { createReadStream } from 'node:fs';
|
|
13
|
+
import { basename } from 'node:path';
|
|
14
|
+
|
|
15
|
+
export class HashError extends Error {}
|
|
16
|
+
|
|
17
|
+
export const HASH_ALGOS = ['md5', 'sha1', 'sha256', 'sha384', 'sha512'];
|
|
18
|
+
// 既定は site 側の表示と同じ4種(SHA-384 は指定したときだけ)
|
|
19
|
+
export const DEFAULT_ALGOS = ['md5', 'sha1', 'sha256', 'sha512'];
|
|
20
|
+
const ALGO_LABEL = { md5: 'MD5', sha1: 'SHA-1', sha256: 'SHA-256', sha384: 'SHA-384', sha512: 'SHA-512' };
|
|
21
|
+
// node:crypto の名前。site 側の Web Crypto 名(SHA-1 / SHA-256 …)とは綴りが違う
|
|
22
|
+
const NODE_NAME = { md5: 'md5', sha1: 'sha1', sha256: 'sha256', sha384: 'sha384', sha512: 'sha512' };
|
|
23
|
+
const HEX_LEN = { md5: 32, sha1: 40, sha256: 64, sha384: 96, sha512: 128 };
|
|
24
|
+
const FORMATS = ['hex', 'HEX', 'base64', 'base64url'];
|
|
25
|
+
|
|
26
|
+
// これ以上のファイルは一度にメモリへ載せず、ストリームで流し込む
|
|
27
|
+
const STREAM_THRESHOLD = 64 * 1024 * 1024;
|
|
28
|
+
|
|
29
|
+
/* ==================== 書式・正規化(site/hash/app.js と同じ挙動) ==================== */
|
|
30
|
+
|
|
31
|
+
/** ダイジェスト(Buffer)を指定の書式の文字列にする */
|
|
32
|
+
export function encodeDigest(buf, format) {
|
|
33
|
+
if (format === 'HEX') return buf.toString('hex').toUpperCase();
|
|
34
|
+
if (format === 'base64') return buf.toString('base64');
|
|
35
|
+
// base64url は + / を - _ にし、パディングの = を落とした形(Node 15+ の 'base64url')
|
|
36
|
+
if (format === 'base64url') return buf.toString('base64url');
|
|
37
|
+
return buf.toString('hex');
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* テキストをハッシュ対象のバイト列にする。改行コードとBOMで結果が変わるため明示的に決める。
|
|
42
|
+
* @param {string} text
|
|
43
|
+
* @param {'lf'|'crlf'} [newline='lf']
|
|
44
|
+
* @param {boolean} [bom=false]
|
|
45
|
+
*/
|
|
46
|
+
export function normalizeText(text, newline = 'lf', bom = false) {
|
|
47
|
+
let s = String(text).replace(/\r\n/g, '\n').replace(/\r/g, '\n');
|
|
48
|
+
if (newline === 'crlf') s = s.replace(/\n/g, '\r\n');
|
|
49
|
+
const body = Buffer.from(s, 'utf8');
|
|
50
|
+
return bom ? Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), body]) : body;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 照合用に渡された文字列から、ハッシュ値らしい部分だけを取り出す。
|
|
55
|
+
* `sha256sum` の出力(`<hash> <ファイル名>`)・`SHA256 (file) = <hash>`・
|
|
56
|
+
* `sha256:<hash>`・コロン区切りの16進・Base64 をそのまま渡せる。
|
|
57
|
+
* @returns {{value: string, kind: 'hex'|'base64'|'', bits: number}}
|
|
58
|
+
*/
|
|
59
|
+
export function parseExpected(input) {
|
|
60
|
+
const raw = String(input == null ? '' : input).trim();
|
|
61
|
+
if (!raw) return { value: '', kind: '', bits: 0 };
|
|
62
|
+
let s = raw.split('\n')[0].trim();
|
|
63
|
+
const bsd = s.match(/^[A-Za-z0-9-]+\s*\([^)]*\)\s*=\s*(\S+)\s*$/);
|
|
64
|
+
if (bsd) s = bsd[1];
|
|
65
|
+
s = s.replace(/^(?:md5|sha-?1|sha-?256|sha-?384|sha-?512)\s*[:=]\s*/i, '').trim();
|
|
66
|
+
const compact = s.replace(/[\s:-]/g, '');
|
|
67
|
+
if (/^[0-9a-fA-F]+$/.test(compact) && compact.length % 2 === 0 && compact.length >= 16) {
|
|
68
|
+
return { value: compact.toLowerCase(), kind: 'hex', bits: compact.length * 4 };
|
|
69
|
+
}
|
|
70
|
+
const head = s.split(/[\s*]+/)[0] || '';
|
|
71
|
+
if (/^[0-9a-fA-F]+$/.test(head) && head.length % 2 === 0 && head.length >= 16) {
|
|
72
|
+
return { value: head.toLowerCase(), kind: 'hex', bits: head.length * 4 };
|
|
73
|
+
}
|
|
74
|
+
if (/^[A-Za-z0-9+/_-]+={0,2}$/.test(head) && head.length >= 16) {
|
|
75
|
+
const norm = head.replace(/-/g, '+').replace(/_/g, '/').replace(/=+$/, '');
|
|
76
|
+
return { value: norm, kind: 'base64', bits: Math.floor((norm.length * 6) / 8) * 8 };
|
|
77
|
+
}
|
|
78
|
+
return { value: head || s, kind: '', bits: 0 };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** 期待値とダイジェストが一致するか。書式(16進・大文字・base64・base64url)は問わない */
|
|
82
|
+
export function digestMatches(buf, expected) {
|
|
83
|
+
if (!expected.value) return false;
|
|
84
|
+
if (expected.kind === 'hex') return buf.toString('hex') === expected.value;
|
|
85
|
+
if (expected.kind === 'base64') return buf.toString('base64').replace(/=+$/, '') === expected.value;
|
|
86
|
+
return false;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/* ==================== 計算 ==================== */
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* バイト列(Buffer)のハッシュを計算する。
|
|
93
|
+
* @param {Buffer} buf
|
|
94
|
+
* @param {string[]} algos
|
|
95
|
+
* @returns {Object<string, Buffer>}
|
|
96
|
+
*/
|
|
97
|
+
export function hashBuffer(buf, algos = DEFAULT_ALGOS) {
|
|
98
|
+
const out = {};
|
|
99
|
+
for (const algo of algos) out[algo] = createHash(NODE_NAME[algo]).update(buf).digest();
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* ファイルをストリームで読みながら、複数のハッシュを1パスで同時に計算する。
|
|
105
|
+
* 大きなファイルをメモリへ載せないため。
|
|
106
|
+
* @param {string} path
|
|
107
|
+
* @param {string[]} algos
|
|
108
|
+
* @returns {Promise<Object<string, Buffer>>}
|
|
109
|
+
*/
|
|
110
|
+
export function hashFileStream(path, algos = DEFAULT_ALGOS) {
|
|
111
|
+
return new Promise((resolve, reject) => {
|
|
112
|
+
const hashes = algos.map((algo) => [algo, createHash(NODE_NAME[algo])]);
|
|
113
|
+
const stream = createReadStream(path);
|
|
114
|
+
stream.on('error', reject);
|
|
115
|
+
stream.on('data', (chunk) => {
|
|
116
|
+
for (const [, h] of hashes) h.update(chunk);
|
|
117
|
+
});
|
|
118
|
+
stream.on('end', () => {
|
|
119
|
+
const out = {};
|
|
120
|
+
for (const [algo, h] of hashes) out[algo] = h.digest();
|
|
121
|
+
resolve(out);
|
|
122
|
+
});
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* テキストまたはファイルのハッシュ値を算出し、期待値との照合結果を返す。
|
|
128
|
+
*
|
|
129
|
+
* @param {object} opts
|
|
130
|
+
* @param {string} [opts.text] 対象テキスト(path と排他)
|
|
131
|
+
* @param {string} [opts.path] 対象ファイルの絶対パス(text と排他)
|
|
132
|
+
* @param {string[]} [opts.algorithms] md5 / sha1 / sha256 / sha384 / sha512(既定は sha384 以外の4種)
|
|
133
|
+
* @param {'hex'|'HEX'|'base64'|'base64url'} [opts.format='hex'] 出力の書式
|
|
134
|
+
* @param {'lf'|'crlf'} [opts.newline='lf'] text の改行コード(ファイルには影響しない)
|
|
135
|
+
* @param {boolean} [opts.bom=false] text の先頭にUTF-8のBOMを付ける(ファイルには影響しない)
|
|
136
|
+
* @param {string} [opts.expected] 照合するハッシュ値(コマンドの出力をそのまま渡せる)
|
|
137
|
+
*/
|
|
138
|
+
export async function hashGenerate(opts = {}) {
|
|
139
|
+
const hasText = typeof opts.text === 'string';
|
|
140
|
+
if (hasText === Boolean(opts.path)) throw new HashError('text か path のどちらか一方を渡してください');
|
|
141
|
+
|
|
142
|
+
const algos = opts.algorithms && opts.algorithms.length ? opts.algorithms : DEFAULT_ALGOS;
|
|
143
|
+
for (const algo of algos) {
|
|
144
|
+
if (HASH_ALGOS.indexOf(algo) === -1) {
|
|
145
|
+
throw new HashError(`algorithms は ${HASH_ALGOS.join(' / ')} のいずれか: ${algo}`);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
const format = opts.format || 'hex';
|
|
149
|
+
if (FORMATS.indexOf(format) === -1) throw new HashError(`format は ${FORMATS.join(' / ')}: ${opts.format}`);
|
|
150
|
+
const newline = opts.newline || 'lf';
|
|
151
|
+
if (newline !== 'lf' && newline !== 'crlf') throw new HashError(`newline は lf か crlf: ${opts.newline}`);
|
|
152
|
+
|
|
153
|
+
// 重複は落としつつ、指定された順序は保つ
|
|
154
|
+
const list = algos.filter((a, i) => algos.indexOf(a) === i);
|
|
155
|
+
|
|
156
|
+
let digests;
|
|
157
|
+
let source;
|
|
158
|
+
let size;
|
|
159
|
+
if (hasText) {
|
|
160
|
+
const buf = normalizeText(opts.text, newline, Boolean(opts.bom));
|
|
161
|
+
size = buf.length;
|
|
162
|
+
digests = hashBuffer(buf, list);
|
|
163
|
+
source = { type: 'text', bytes: size, newline, bom: Boolean(opts.bom), encoding: 'utf-8' };
|
|
164
|
+
} else {
|
|
165
|
+
const info = await stat(opts.path);
|
|
166
|
+
if (!info.isFile()) throw new HashError(`ファイルではありません: ${opts.path}`);
|
|
167
|
+
size = info.size;
|
|
168
|
+
// 大きなファイルは1パスのストリームで流す(全体をメモリへ載せない)
|
|
169
|
+
digests = size > STREAM_THRESHOLD
|
|
170
|
+
? await hashFileStream(opts.path, list)
|
|
171
|
+
: hashBuffer(await readFile(opts.path), list);
|
|
172
|
+
source = { type: 'file', path: opts.path, name: basename(opts.path), bytes: size };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const expected = parseExpected(opts.expected);
|
|
176
|
+
const hashes = {};
|
|
177
|
+
let matched = null;
|
|
178
|
+
for (const algo of list) {
|
|
179
|
+
hashes[algo] = encodeDigest(digests[algo], format);
|
|
180
|
+
if (digestMatches(digests[algo], expected)) matched = algo;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const notes = [];
|
|
184
|
+
if (list.indexOf('md5') !== -1 || list.indexOf('sha1') !== -1) {
|
|
185
|
+
notes.push(
|
|
186
|
+
'MD5 と SHA-1 は衝突耐性が破られており、異なる2つの入力から同じ値を作れます。'
|
|
187
|
+
+ '偶発的な破損の検出には使えますが、署名・改ざん検知には使わないでください(新規は SHA-256 以上)。',
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
notes.push(
|
|
191
|
+
'ハッシュ値そのものはパスワードの保存方法ではありません。'
|
|
192
|
+
+ 'パスワードにはソルト付きで意図的に遅いアルゴリズム(bcrypt / scrypt / Argon2)を使います。',
|
|
193
|
+
);
|
|
194
|
+
if (hasText && newline === 'crlf') {
|
|
195
|
+
notes.push('改行を CRLF として計算しています。LF の同じ文章とは全く違う値になります。');
|
|
196
|
+
}
|
|
197
|
+
if (hasText && opts.bom) {
|
|
198
|
+
notes.push('先頭に UTF-8 の BOM(EF BB BF)を付けて計算しています。BOM無しの同じ文章とは値が変わります。');
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const result = {
|
|
202
|
+
source,
|
|
203
|
+
format,
|
|
204
|
+
algorithms: list,
|
|
205
|
+
hashes,
|
|
206
|
+
notes,
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
if (expected.value) {
|
|
210
|
+
// 桁数が同じアルゴリズムだけを「照合の対象」とみなす(違う長さの値は無関係)
|
|
211
|
+
const target = list.find((algo) => (expected.kind === 'hex'
|
|
212
|
+
? expected.value.length === HEX_LEN[algo]
|
|
213
|
+
: expected.kind === 'base64' && expected.bits === digests[algo].length * 8));
|
|
214
|
+
result.verification = {
|
|
215
|
+
expected: expected.value,
|
|
216
|
+
expected_format: expected.kind || 'unrecognized',
|
|
217
|
+
matched: Boolean(matched),
|
|
218
|
+
algorithm: matched || target || null,
|
|
219
|
+
};
|
|
220
|
+
if (matched) {
|
|
221
|
+
result.verification.message = `貼り付けた値は ${ALGO_LABEL[matched]} のハッシュ値と一致しました(データは同一です)。`;
|
|
222
|
+
} else if (target) {
|
|
223
|
+
result.verification.message = `期待値は ${ALGO_LABEL[target]} の桁数ですが一致しません。`
|
|
224
|
+
+ 'データが異なるか、改行コード・BOM・末尾の改行など入力の作り方が違います。';
|
|
225
|
+
} else if (!expected.kind) {
|
|
226
|
+
result.verification.message = '期待値を16進・Base64のハッシュ値として読み取れませんでした。';
|
|
227
|
+
} else {
|
|
228
|
+
result.verification.message = '算出したどのハッシュ値とも桁数が一致しませんでした'
|
|
229
|
+
+ '(algorithms に対象のアルゴリズムを含めているか確認してください)。';
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
return result;
|
|
234
|
+
}
|