kimi-plugin-cc 2.7.2 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +3 -5
- package/CHANGELOG.md +78 -1
- package/README.md +505 -448
- package/agents/kimi-pursue.md +6 -6
- package/agents/kimi-review.md +22 -22
- package/agents/kimi-swarm.md +25 -23
- package/agents/{kimi-ask.md → kimi-task.md} +34 -30
- package/commands/README.md +4 -6
- package/commands/pursue.md +1 -1
- package/commands/review.md +8 -3
- package/commands/setup.md +4 -2
- package/commands/swarm.md +6 -5
- package/commands/{rescue.md → task.md} +13 -11
- package/dist/background-spawn.js +10 -17
- package/dist/cli-client.js +65 -46
- package/dist/commands/ask.js +22 -89
- package/dist/commands/cancel.js +7 -46
- package/dist/commands/cli-helpers.js +102 -1
- package/dist/commands/models.js +2 -3
- package/dist/commands/pursue.js +5 -19
- package/dist/commands/repair-sessions.js +118 -12
- package/dist/commands/rescue.js +12 -82
- package/dist/commands/result.js +7 -1
- package/dist/commands/review-gate.js +1 -0
- package/dist/commands/review.js +12 -15
- package/dist/commands/setup.js +606 -270
- package/dist/commands/status.js +2 -2
- package/dist/commands/swarm.js +93 -119
- package/dist/commands/worker.js +1 -2
- package/dist/companion.js +3 -1
- package/dist/dsh/index.js +15 -17
- package/dist/git.js +1 -9
- package/dist/help.js +3 -3
- package/dist/hooks/approval-hook.js +41 -0
- package/dist/hooks/approval-policy.js +72 -10
- package/dist/hooks/config-safety.js +19 -42
- package/dist/hooks/hook-timing.js +48 -0
- package/dist/hooks/install.js +206 -11
- package/dist/hooks/managed-block.js +78 -33
- package/dist/job-store.js +100 -128
- package/dist/jobs.js +14 -19
- package/dist/kimi-command.js +74 -1
- package/dist/kimi-engine.js +170 -74
- package/dist/kimi-errors.js +14 -69
- package/dist/kimi-home.js +6 -0
- package/dist/kimi-journal.js +41 -0
- package/dist/kimi-releases.js +144 -0
- package/dist/kimi-timeouts.js +1 -1
- package/dist/kimi-version-probe.js +12 -48
- package/dist/mcp/job-control.js +4 -6
- package/dist/mcp/launcher.js +12 -6
- package/dist/mcp/operations.js +50 -18
- package/dist/mcp/protocol.js +16 -14
- package/dist/mcp/stdio.js +3 -2
- package/dist/model-command.js +5 -3
- package/dist/native-v2-preflight.js +139 -68
- package/dist/parsing.js +171 -237
- package/dist/paths.js +8 -0
- package/dist/process-tree.js +35 -24
- package/dist/read-scope.js +435 -0
- package/dist/render.js +46 -9
- package/dist/rescue-approval.js +461 -84
- package/dist/schemas/review-gate-output.js +3 -5
- package/dist/session-title.js +25 -5
- package/dist/stream-json.js +1 -3
- package/dist/surface-routing.js +21 -0
- package/dist/swarm-activation.js +74 -77
- package/dist/swarm-policy.js +2 -1
- package/dist/swarm-recovery.js +2 -1
- package/dist/util.js +28 -0
- package/dist/version.js +1 -1
- package/docs/migration.md +27 -6
- package/docs/models.md +2 -2
- package/docs/registry-releases.md +3 -1
- package/docs/safety.md +131 -81
- package/docs/session-visibility.md +5 -3
- package/docs/swarm-recovery.md +4 -4
- package/docs/upstream-2.7.2-certification.md +16 -2
- package/docs/upstream-2.7.3-certification.md +95 -0
- package/package.json +2 -1
- package/plugins/kimi-codex/.codex-plugin/plugin.json +3 -3
- package/plugins/kimi-codex/.mcp.json +1 -0
- package/plugins/kimi-codex/dist/background-spawn.js +10 -17
- package/plugins/kimi-codex/dist/cli-client.js +65 -46
- package/plugins/kimi-codex/dist/commands/ask.js +22 -89
- package/plugins/kimi-codex/dist/commands/cancel.js +7 -46
- package/plugins/kimi-codex/dist/commands/cli-helpers.js +102 -1
- package/plugins/kimi-codex/dist/commands/models.js +2 -3
- package/plugins/kimi-codex/dist/commands/pursue.js +5 -19
- package/plugins/kimi-codex/dist/commands/repair-sessions.js +118 -12
- package/plugins/kimi-codex/dist/commands/rescue.js +12 -82
- package/plugins/kimi-codex/dist/commands/result.js +7 -1
- package/plugins/kimi-codex/dist/commands/review-gate.js +1 -0
- package/plugins/kimi-codex/dist/commands/review.js +12 -15
- package/plugins/kimi-codex/dist/commands/setup.js +606 -270
- package/plugins/kimi-codex/dist/commands/status.js +2 -2
- package/plugins/kimi-codex/dist/commands/swarm.js +93 -119
- package/plugins/kimi-codex/dist/commands/worker.js +1 -2
- package/plugins/kimi-codex/dist/companion.js +3 -1
- package/plugins/kimi-codex/dist/dsh/index.js +15 -17
- package/plugins/kimi-codex/dist/git.js +1 -9
- package/plugins/kimi-codex/dist/help.js +3 -3
- package/plugins/kimi-codex/dist/hooks/approval-hook.js +41 -0
- package/plugins/kimi-codex/dist/hooks/approval-policy.js +72 -10
- package/plugins/kimi-codex/dist/hooks/config-safety.js +19 -42
- package/plugins/kimi-codex/dist/hooks/hook-timing.js +48 -0
- package/plugins/kimi-codex/dist/hooks/install.js +206 -11
- package/plugins/kimi-codex/dist/hooks/managed-block.js +78 -33
- package/plugins/kimi-codex/dist/job-store.js +100 -128
- package/plugins/kimi-codex/dist/jobs.js +14 -19
- package/plugins/kimi-codex/dist/kimi-command.js +74 -1
- package/plugins/kimi-codex/dist/kimi-engine.js +170 -74
- package/plugins/kimi-codex/dist/kimi-errors.js +14 -69
- package/plugins/kimi-codex/dist/kimi-home.js +6 -0
- package/plugins/kimi-codex/dist/kimi-journal.js +41 -0
- package/plugins/kimi-codex/dist/kimi-releases.js +144 -0
- package/plugins/kimi-codex/dist/kimi-timeouts.js +1 -1
- package/plugins/kimi-codex/dist/kimi-version-probe.js +12 -48
- package/plugins/kimi-codex/dist/mcp/job-control.js +4 -6
- package/plugins/kimi-codex/dist/mcp/launcher.js +12 -6
- package/plugins/kimi-codex/dist/mcp/operations.js +50 -18
- package/plugins/kimi-codex/dist/mcp/protocol.js +16 -14
- package/plugins/kimi-codex/dist/mcp/stdio.js +3 -2
- package/plugins/kimi-codex/dist/model-command.js +5 -3
- package/plugins/kimi-codex/dist/native-v2-preflight.js +139 -68
- package/plugins/kimi-codex/dist/parsing.js +171 -237
- package/plugins/kimi-codex/dist/paths.js +8 -0
- package/plugins/kimi-codex/dist/process-tree.js +35 -24
- package/plugins/kimi-codex/dist/read-scope.js +435 -0
- package/plugins/kimi-codex/dist/render.js +46 -9
- package/plugins/kimi-codex/dist/rescue-approval.js +461 -84
- package/plugins/kimi-codex/dist/schemas/review-gate-output.js +3 -5
- package/plugins/kimi-codex/dist/session-title.js +25 -5
- package/plugins/kimi-codex/dist/stream-json.js +1 -3
- package/plugins/kimi-codex/dist/surface-routing.js +21 -0
- package/plugins/kimi-codex/dist/swarm-activation.js +74 -77
- package/plugins/kimi-codex/dist/swarm-policy.js +2 -1
- package/plugins/kimi-codex/dist/swarm-recovery.js +2 -1
- package/plugins/kimi-codex/dist/util.js +28 -0
- package/plugins/kimi-codex/dist/version.js +1 -1
- package/plugins/kimi-codex/skills/kimi-pursue/SKILL.md +1 -1
- package/plugins/kimi-codex/skills/kimi-review/SKILL.md +8 -7
- package/plugins/kimi-codex/skills/kimi-review/agents/openai.yaml +1 -1
- package/plugins/kimi-codex/skills/kimi-setup/SKILL.md +2 -1
- package/plugins/kimi-codex/skills/kimi-swarm/SKILL.md +8 -6
- package/plugins/kimi-codex/skills/kimi-swarm/agents/openai.yaml +1 -1
- package/plugins/kimi-codex/skills/{kimi-ask → kimi-task}/SKILL.md +11 -9
- package/plugins/kimi-codex/skills/kimi-task/agents/openai.yaml +6 -0
- package/plugins/kimi-dsh/README.md +3 -2
- package/plugins/kimi-dsh/dist/background-spawn.js +10 -17
- package/plugins/kimi-dsh/dist/cli-client.js +65 -46
- package/plugins/kimi-dsh/dist/commands/ask.js +22 -89
- package/plugins/kimi-dsh/dist/commands/cancel.js +7 -46
- package/plugins/kimi-dsh/dist/commands/cli-helpers.js +102 -1
- package/plugins/kimi-dsh/dist/commands/models.js +2 -3
- package/plugins/kimi-dsh/dist/commands/pursue.js +5 -19
- package/plugins/kimi-dsh/dist/commands/repair-sessions.js +118 -12
- package/plugins/kimi-dsh/dist/commands/rescue.js +12 -82
- package/plugins/kimi-dsh/dist/commands/result.js +7 -1
- package/plugins/kimi-dsh/dist/commands/review-gate.js +1 -0
- package/plugins/kimi-dsh/dist/commands/review.js +12 -15
- package/plugins/kimi-dsh/dist/commands/setup.js +606 -270
- package/plugins/kimi-dsh/dist/commands/status.js +2 -2
- package/plugins/kimi-dsh/dist/commands/swarm.js +93 -119
- package/plugins/kimi-dsh/dist/commands/worker.js +1 -2
- package/plugins/kimi-dsh/dist/companion.js +3 -1
- package/plugins/kimi-dsh/dist/dsh/index.js +15 -17
- package/plugins/kimi-dsh/dist/git.js +1 -9
- package/plugins/kimi-dsh/dist/help.js +3 -3
- package/plugins/kimi-dsh/dist/hooks/approval-hook.js +41 -0
- package/plugins/kimi-dsh/dist/hooks/approval-policy.js +72 -10
- package/plugins/kimi-dsh/dist/hooks/config-safety.js +19 -42
- package/plugins/kimi-dsh/dist/hooks/hook-timing.js +48 -0
- package/plugins/kimi-dsh/dist/hooks/install.js +206 -11
- package/plugins/kimi-dsh/dist/hooks/managed-block.js +78 -33
- package/plugins/kimi-dsh/dist/job-store.js +100 -128
- package/plugins/kimi-dsh/dist/jobs.js +14 -19
- package/plugins/kimi-dsh/dist/kimi-command.js +74 -1
- package/plugins/kimi-dsh/dist/kimi-engine.js +170 -74
- package/plugins/kimi-dsh/dist/kimi-errors.js +14 -69
- package/plugins/kimi-dsh/dist/kimi-home.js +6 -0
- package/plugins/kimi-dsh/dist/kimi-journal.js +41 -0
- package/plugins/kimi-dsh/dist/kimi-releases.js +144 -0
- package/plugins/kimi-dsh/dist/kimi-timeouts.js +1 -1
- package/plugins/kimi-dsh/dist/kimi-version-probe.js +12 -48
- package/plugins/kimi-dsh/dist/mcp/job-control.js +4 -6
- package/plugins/kimi-dsh/dist/mcp/launcher.js +12 -6
- package/plugins/kimi-dsh/dist/mcp/operations.js +50 -18
- package/plugins/kimi-dsh/dist/mcp/protocol.js +16 -14
- package/plugins/kimi-dsh/dist/mcp/stdio.js +3 -2
- package/plugins/kimi-dsh/dist/model-command.js +5 -3
- package/plugins/kimi-dsh/dist/native-v2-preflight.js +139 -68
- package/plugins/kimi-dsh/dist/parsing.js +171 -237
- package/plugins/kimi-dsh/dist/paths.js +8 -0
- package/plugins/kimi-dsh/dist/process-tree.js +35 -24
- package/plugins/kimi-dsh/dist/read-scope.js +435 -0
- package/plugins/kimi-dsh/dist/render.js +46 -9
- package/plugins/kimi-dsh/dist/rescue-approval.js +461 -84
- package/plugins/kimi-dsh/dist/schemas/review-gate-output.js +3 -5
- package/plugins/kimi-dsh/dist/session-title.js +25 -5
- package/plugins/kimi-dsh/dist/stream-json.js +1 -3
- package/plugins/kimi-dsh/dist/surface-routing.js +21 -0
- package/plugins/kimi-dsh/dist/swarm-activation.js +74 -77
- package/plugins/kimi-dsh/dist/swarm-policy.js +2 -1
- package/plugins/kimi-dsh/dist/swarm-recovery.js +2 -1
- package/plugins/kimi-dsh/dist/util.js +28 -0
- package/plugins/kimi-dsh/dist/version.js +1 -1
- package/plugins/kimi-dsh/package.json +1 -1
- package/agents/kimi-challenge.md +0 -86
- package/agents/kimi-rescue.md +0 -92
- package/agents/kimi-swarm-write.md +0 -96
- package/commands/ask.md +0 -38
- package/commands/challenge.md +0 -35
- package/dist/commands/not-implemented.js +0 -4
- package/plugins/kimi-codex/dist/commands/not-implemented.js +0 -4
- package/plugins/kimi-codex/skills/kimi-ask/agents/openai.yaml +0 -6
- package/plugins/kimi-codex/skills/kimi-challenge/SKILL.md +0 -34
- package/plugins/kimi-codex/skills/kimi-challenge/agents/openai.yaml +0 -6
- package/plugins/kimi-codex/skills/kimi-rescue/SKILL.md +0 -34
- package/plugins/kimi-codex/skills/kimi-rescue/agents/openai.yaml +0 -6
- package/plugins/kimi-codex/skills/kimi-swarm-write/SKILL.md +0 -36
- package/plugins/kimi-codex/skills/kimi-swarm-write/agents/openai.yaml +0 -6
- package/plugins/kimi-dsh/dist/commands/not-implemented.js +0 -4
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { execFile } from "node:child_process";
|
|
2
2
|
import { readdir, readFile } from "node:fs/promises";
|
|
3
3
|
import { promisify } from "node:util";
|
|
4
|
+
import { sleep } from "./util.js";
|
|
4
5
|
const execFileAsync = promisify(execFile);
|
|
5
6
|
const MAX_DESCENDANT_DEPTH = 8;
|
|
6
7
|
const MAX_DESCENDANT_PIDS = 512;
|
|
@@ -18,22 +19,39 @@ const PROBE_TIMEOUT = Symbol("process-probe-timeout");
|
|
|
18
19
|
export async function collectDescendantIdentities(rootPid, expectedRoot) {
|
|
19
20
|
if (!Number.isInteger(rootPid) || rootPid <= 0 || process.platform === "win32")
|
|
20
21
|
return [];
|
|
21
|
-
|
|
22
|
-
if (snapshot === PROBE_TIMEOUT) {
|
|
23
|
-
throw new Error(`process snapshot exceeded ${PROCESS_SNAPSHOT_TIMEOUT_MS}ms`);
|
|
24
|
-
}
|
|
25
|
-
return snapshot;
|
|
22
|
+
return snapshotWithinTimeout(collectVerifiedDescendantIdentities(rootPid, expectedRoot));
|
|
26
23
|
}
|
|
27
24
|
/** Collect owned roots and descendants with one shared table and targeted verification. */
|
|
28
25
|
export async function collectDescendantIdentitiesForRoots(expectedRoots) {
|
|
29
26
|
if (expectedRoots.length === 0 || process.platform === "win32")
|
|
30
27
|
return [];
|
|
31
|
-
|
|
28
|
+
return snapshotWithinTimeout(collectVerifiedDescendantIdentitiesForRoots(expectedRoots));
|
|
29
|
+
}
|
|
30
|
+
async function snapshotWithinTimeout(collect) {
|
|
31
|
+
const snapshot = await raceValueWithTimeout(collect, PROCESS_SNAPSHOT_TIMEOUT_MS, PROBE_TIMEOUT);
|
|
32
32
|
if (snapshot === PROBE_TIMEOUT) {
|
|
33
33
|
throw new Error(`process snapshot exceeded ${PROCESS_SNAPSHOT_TIMEOUT_MS}ms`);
|
|
34
34
|
}
|
|
35
35
|
return snapshot;
|
|
36
36
|
}
|
|
37
|
+
const INCOMPLETE_CAPTURE_RETRY_DELAYS_MS = [5, 20];
|
|
38
|
+
/**
|
|
39
|
+
* A capture that overlaps a process exit can read a row in mid-release and
|
|
40
|
+
* come back incomplete, and one incomplete capture makes a whole teardown
|
|
41
|
+
* unverifiable. Look again at once: a root that has gone then reads as absent,
|
|
42
|
+
* which is a complete observation, while a table that stays unreadable still
|
|
43
|
+
* fails. A capture that timed out is not retried.
|
|
44
|
+
*/
|
|
45
|
+
export async function retryIncompleteCapture(capture, retryDelaysMs = INCOMPLETE_CAPTURE_RETRY_DELAYS_MS) {
|
|
46
|
+
let snapshot = await capture();
|
|
47
|
+
for (const delayMs of retryDelaysMs) {
|
|
48
|
+
if (snapshot.complete || snapshot.timedOut === true)
|
|
49
|
+
break;
|
|
50
|
+
await sleep(delayMs);
|
|
51
|
+
snapshot = await capture();
|
|
52
|
+
}
|
|
53
|
+
return snapshot;
|
|
54
|
+
}
|
|
37
55
|
/** Return current members of the selected process groups, or undefined when unreadable. */
|
|
38
56
|
export async function collectProcessGroupsIdentities(processGroupIds) {
|
|
39
57
|
if (process.platform === "win32")
|
|
@@ -41,7 +59,7 @@ export async function collectProcessGroupsIdentities(processGroupIds) {
|
|
|
41
59
|
const groups = new Set(processGroupIds.filter((id) => Number.isInteger(id) && id > 0));
|
|
42
60
|
if (groups.size === 0)
|
|
43
61
|
return [];
|
|
44
|
-
const rows = await raceValueWithTimeout(collectProcessSnapshotRows(), PROCESS_SNAPSHOT_TIMEOUT_MS);
|
|
62
|
+
const rows = await raceValueWithTimeout(collectProcessSnapshotRows(), PROCESS_SNAPSHOT_TIMEOUT_MS, PROBE_TIMEOUT);
|
|
45
63
|
if (rows === PROBE_TIMEOUT || rows === undefined)
|
|
46
64
|
return undefined;
|
|
47
65
|
return rows.filter((row) => groups.has(row.processGroupId)).map(toProcessIdentity);
|
|
@@ -66,7 +84,7 @@ export async function probeProcessIdentity(pid) {
|
|
|
66
84
|
const read = process.platform === "linux"
|
|
67
85
|
? readProcessIdentityBatchFromProc([pid])
|
|
68
86
|
: readProcessIdentityBatchWithPs([pid]);
|
|
69
|
-
const batch = await raceValueWithTimeout(read, PROCESS_IDENTITY_PROBE_TIMEOUT_MS);
|
|
87
|
+
const batch = await raceValueWithTimeout(read, PROCESS_IDENTITY_PROBE_TIMEOUT_MS, PROBE_TIMEOUT);
|
|
70
88
|
if (batch === PROBE_TIMEOUT)
|
|
71
89
|
return { complete: false };
|
|
72
90
|
return { identity: batch.identities.get(pid), complete: batch.complete };
|
|
@@ -88,7 +106,7 @@ export async function revalidateProcessIdentities(expectedIdentities, options =
|
|
|
88
106
|
const read = options.identityReader === undefined
|
|
89
107
|
? readCurrentIdentityBatch(expected)
|
|
90
108
|
: readIdentityBatchWithReader(expected, options.identityReader);
|
|
91
|
-
const batch = await raceValueWithTimeout(read, timeoutMs);
|
|
109
|
+
const batch = await raceValueWithTimeout(read, timeoutMs, PROBE_TIMEOUT);
|
|
92
110
|
if (batch === PROBE_TIMEOUT)
|
|
93
111
|
return { identities: [], complete: false };
|
|
94
112
|
const identities = [];
|
|
@@ -323,9 +341,7 @@ async function collectProcessSnapshotRowsFromProc() {
|
|
|
323
341
|
try {
|
|
324
342
|
entries = await readdir("/proc");
|
|
325
343
|
}
|
|
326
|
-
catch
|
|
327
|
-
if (isErrnoException(err, "ENOENT") || isErrnoException(err, "EPERM"))
|
|
328
|
-
return undefined;
|
|
344
|
+
catch {
|
|
329
345
|
return undefined;
|
|
330
346
|
}
|
|
331
347
|
const outcomes = await Promise.all(entries
|
|
@@ -354,7 +370,7 @@ async function collectProcessSnapshotRowsFromPs(pids) {
|
|
|
354
370
|
stdout = result.stdout;
|
|
355
371
|
}
|
|
356
372
|
catch (err) {
|
|
357
|
-
if (uniquePids !== undefined &&
|
|
373
|
+
if (uniquePids !== undefined && hasErrorCode(err, 1))
|
|
358
374
|
return [];
|
|
359
375
|
return undefined;
|
|
360
376
|
}
|
|
@@ -404,7 +420,7 @@ async function readProcessIdentityBatchWithPs(pids) {
|
|
|
404
420
|
stdout = result.stdout;
|
|
405
421
|
}
|
|
406
422
|
catch (err) {
|
|
407
|
-
if (
|
|
423
|
+
if (hasErrorCode(err, 1))
|
|
408
424
|
return { identities: new Map(), complete: true };
|
|
409
425
|
return { identities: new Map(), complete: false };
|
|
410
426
|
}
|
|
@@ -452,7 +468,7 @@ async function readProcRow(pid) {
|
|
|
452
468
|
stat = await readFile(`/proc/${pid}/stat`, "utf8");
|
|
453
469
|
}
|
|
454
470
|
catch (err) {
|
|
455
|
-
if (
|
|
471
|
+
if (hasErrorCode(err, "ENOENT") || hasErrorCode(err, "ESRCH")) {
|
|
456
472
|
return { status: "missing" };
|
|
457
473
|
}
|
|
458
474
|
return { status: "error" };
|
|
@@ -560,16 +576,13 @@ function isQuiescentState(state) {
|
|
|
560
576
|
const normalized = state.trim().toUpperCase();
|
|
561
577
|
return normalized.startsWith("Z") || normalized.startsWith("X");
|
|
562
578
|
}
|
|
563
|
-
function
|
|
564
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
565
|
-
}
|
|
566
|
-
async function raceValueWithTimeout(promise, timeoutMs) {
|
|
579
|
+
export async function raceValueWithTimeout(promise, timeoutMs, timeoutValue) {
|
|
567
580
|
let timer;
|
|
568
581
|
try {
|
|
569
582
|
return await Promise.race([
|
|
570
583
|
promise,
|
|
571
584
|
new Promise((resolve) => {
|
|
572
|
-
timer = setTimeout(() => resolve(
|
|
585
|
+
timer = setTimeout(() => resolve(timeoutValue), Math.max(0, timeoutMs));
|
|
573
586
|
}),
|
|
574
587
|
]);
|
|
575
588
|
}
|
|
@@ -578,9 +591,7 @@ async function raceValueWithTimeout(promise, timeoutMs) {
|
|
|
578
591
|
clearTimeout(timer);
|
|
579
592
|
}
|
|
580
593
|
}
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
}
|
|
584
|
-
function isExitCode(err, code) {
|
|
594
|
+
/** Matches an errno string (ENOENT) or a numeric child exit code on a thrown value. */
|
|
595
|
+
function hasErrorCode(err, code) {
|
|
585
596
|
return typeof err === "object" && err !== null && "code" in err && err.code === code;
|
|
586
597
|
}
|
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
import { realpathSync } from "node:fs";
|
|
2
|
+
import { lstat, realpath, stat } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { RuntimeError } from "./errors.js";
|
|
5
|
+
/**
|
|
6
|
+
* Per-call scope for the read-only operations (ask, review, challenge,
|
|
7
|
+
* read-only swarm). kimi-code approves Read, Grep, Glob, ReadMediaFile,
|
|
8
|
+
* WebSearch and FetchURL itself, so the PreToolUse hook is the only place
|
|
9
|
+
* these can be scoped. Web access is coupled to read confinement: a job that
|
|
10
|
+
* can send data out may read only the workspace and the caller's read roots.
|
|
11
|
+
*
|
|
12
|
+
* The plugin sets or deletes both variables on every spawn; the hook reads
|
|
13
|
+
* only these, never the hook payload's cwd.
|
|
14
|
+
*/
|
|
15
|
+
export const READ_ROOTS_ENV = "KIMI_PLUGIN_CC_READ_ROOTS";
|
|
16
|
+
export const NETWORK_ENV = "KIMI_PLUGIN_CC_NETWORK";
|
|
17
|
+
/** Hook labels that may carry a non-default scope. */
|
|
18
|
+
export const READ_SCOPE_LABELS = new Set(["ask", "review", "challenge", "swarm"]);
|
|
19
|
+
export const SCOPE_FLAGS_WRITE_MESSAGE = "--read-root and --network apply only to read-only operations (ask, review, challenge, read-only swarm). " +
|
|
20
|
+
"Write-capable operations can read through allowlisted shell commands, so read confinement could not be honoured there.";
|
|
21
|
+
/** Validate --read-root values and build the scope; undefined means the default scope. */
|
|
22
|
+
export async function resolveReadScope(readRoots, network, stage) {
|
|
23
|
+
const requested = readRoots ?? [];
|
|
24
|
+
if (requested.length === 0 && network !== true)
|
|
25
|
+
return undefined;
|
|
26
|
+
const resolved = [];
|
|
27
|
+
for (const root of requested) {
|
|
28
|
+
if (!path.isAbsolute(root)) {
|
|
29
|
+
throw new RuntimeError("INVALID_ARGS", `--read-root must be an absolute directory path; got "${root}".`, stage);
|
|
30
|
+
}
|
|
31
|
+
let real;
|
|
32
|
+
if (root.includes("\\")) {
|
|
33
|
+
throw new RuntimeError("INVALID_ARGS", `--read-root ${root} contains a backslash, which kimi-code reads as a path separator.`, stage);
|
|
34
|
+
}
|
|
35
|
+
try {
|
|
36
|
+
real = await realpath(root);
|
|
37
|
+
if (!(await stat(real)).isDirectory())
|
|
38
|
+
throw new Error("not a directory");
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
throw new RuntimeError("INVALID_ARGS", `--read-root ${root} is not an existing directory.`, stage);
|
|
42
|
+
}
|
|
43
|
+
if (real.includes("\\")) {
|
|
44
|
+
throw new RuntimeError("INVALID_ARGS", `--read-root ${root} contains a backslash, which kimi-code reads as a path separator.`, stage);
|
|
45
|
+
}
|
|
46
|
+
if (!resolved.includes(real))
|
|
47
|
+
resolved.push(real);
|
|
48
|
+
}
|
|
49
|
+
return Object.freeze({ readRoots: Object.freeze(resolved), network: network === true });
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Read confinement rests on tool schemas verified at certified releases only.
|
|
53
|
+
* --read-root can only narrow, so it runs anywhere; --network is the
|
|
54
|
+
* relaxation and is refused on an uncertified release.
|
|
55
|
+
*/
|
|
56
|
+
export function assertScopeSupported(scope, certification, code, stage) {
|
|
57
|
+
if (scope?.network === true && certification === "uncertified") {
|
|
58
|
+
throw new RuntimeError(code, "--network is refused on an uncertified kimi-code release: read confinement is verified only against certified releases. Run without --network, or install a certified kimi-code release.", stage);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/** The roots the hook confines reads to: the run directory first, then the read roots. */
|
|
62
|
+
export function effectiveReadRoots(scope, cwd) {
|
|
63
|
+
// Root 1 is the directory kimi runs in, so relative and defaulted tool
|
|
64
|
+
// paths resolve inside it exactly as upstream resolves them.
|
|
65
|
+
if (cwd.includes("\\")) {
|
|
66
|
+
throw new RuntimeError("READ_SCOPE_INVALID", `Read confinement cannot use ${cwd}: it contains a backslash, which kimi-code reads as a path separator.`, "read-scope.roots");
|
|
67
|
+
}
|
|
68
|
+
const roots = [realpathSync.native(cwd)];
|
|
69
|
+
for (const root of scope.readRoots)
|
|
70
|
+
if (!roots.includes(root))
|
|
71
|
+
roots.push(root);
|
|
72
|
+
// kimi-code resolves with pathe, which reads "\\" as a separator, so such a
|
|
73
|
+
// root would name a different directory to kimi than to the hook.
|
|
74
|
+
const slashed = roots.find((root) => root.includes("\\"));
|
|
75
|
+
if (slashed !== undefined) {
|
|
76
|
+
throw new RuntimeError("READ_SCOPE_INVALID", `Read confinement cannot use ${slashed}: it contains a backslash, which kimi-code reads as a path separator.`, "read-scope.roots");
|
|
77
|
+
}
|
|
78
|
+
return roots;
|
|
79
|
+
}
|
|
80
|
+
/** True when every root in `inner` lies within some root in `outer`. */
|
|
81
|
+
export function rootsWithin(inner, outer) {
|
|
82
|
+
return inner.every((root) => outer.some((candidate) => isWithin(candidate, root)));
|
|
83
|
+
}
|
|
84
|
+
/** Child-environment values for one spawn; both absent for the default scope. */
|
|
85
|
+
export function readScopeEnvironment(scope, cwd) {
|
|
86
|
+
if (scope === undefined || (scope.readRoots.length === 0 && !scope.network))
|
|
87
|
+
return {};
|
|
88
|
+
return {
|
|
89
|
+
[READ_ROOTS_ENV]: JSON.stringify(effectiveReadRoots(scope, cwd)),
|
|
90
|
+
...(scope.network ? { [NETWORK_ENV]: "1" } : {}),
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
const FAIL_CLOSED = Object.freeze({ confined: true, roots: Object.freeze([]), network: false });
|
|
94
|
+
/**
|
|
95
|
+
* Hook-side parse of the plugin-set variables. Both absent is the default
|
|
96
|
+
* scope. Anything malformed (bad JSON, empty array, relative or unnormalized
|
|
97
|
+
* entries, a network value other than "1", network without roots) confines
|
|
98
|
+
* reads to NO roots with network off.
|
|
99
|
+
*/
|
|
100
|
+
export function parseScopeEnvironment(rawRoots, rawNetwork) {
|
|
101
|
+
if (rawRoots === undefined && rawNetwork === undefined)
|
|
102
|
+
return { confined: false, network: false };
|
|
103
|
+
if (rawRoots === undefined)
|
|
104
|
+
return FAIL_CLOSED;
|
|
105
|
+
if (rawNetwork !== undefined && rawNetwork !== "1")
|
|
106
|
+
return FAIL_CLOSED;
|
|
107
|
+
let parsed;
|
|
108
|
+
try {
|
|
109
|
+
parsed = JSON.parse(rawRoots);
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
return FAIL_CLOSED;
|
|
113
|
+
}
|
|
114
|
+
if (!Array.isArray(parsed) || parsed.length === 0)
|
|
115
|
+
return FAIL_CLOSED;
|
|
116
|
+
for (const entry of parsed) {
|
|
117
|
+
if (typeof entry !== "string" || entry.includes("\0") || entry.includes("\\") || !path.isAbsolute(entry) || path.resolve(entry) !== entry) {
|
|
118
|
+
return FAIL_CLOSED;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return Object.freeze({ confined: true, roots: Object.freeze([...parsed]), network: rawNetwork === "1" });
|
|
122
|
+
}
|
|
123
|
+
/** Persisted job-row form; NULL for the default scope so old rows keep their shape. */
|
|
124
|
+
export function serializeReadScope(scope) {
|
|
125
|
+
if (scope === undefined || (scope.readRoots.length === 0 && !scope.network))
|
|
126
|
+
return null;
|
|
127
|
+
return JSON.stringify({ read_roots: scope.readRoots, network: scope.network });
|
|
128
|
+
}
|
|
129
|
+
/** Inverse of serializeReadScope. A corrupt row refuses rather than run unconfined. */
|
|
130
|
+
export function parseJobReadScope(raw) {
|
|
131
|
+
if (raw === null || raw === undefined)
|
|
132
|
+
return undefined;
|
|
133
|
+
let parsed;
|
|
134
|
+
try {
|
|
135
|
+
parsed = JSON.parse(raw);
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
parsed = undefined;
|
|
139
|
+
}
|
|
140
|
+
const record = parsed;
|
|
141
|
+
if (typeof record !== "object" || record === null ||
|
|
142
|
+
!Array.isArray(record.read_roots) || typeof record.network !== "boolean" ||
|
|
143
|
+
!record.read_roots.every((root) => typeof root === "string" && path.isAbsolute(root))) {
|
|
144
|
+
throw new RuntimeError("READ_SCOPE_INVALID", "The job's stored read scope is unreadable; refusing to run it unconfined.", "read-scope.load");
|
|
145
|
+
}
|
|
146
|
+
return Object.freeze({ readRoots: Object.freeze([...record.read_roots]), network: record.network });
|
|
147
|
+
}
|
|
148
|
+
/** Header line for a non-default scope; undefined for the default. */
|
|
149
|
+
export function describeReadScope(scope) {
|
|
150
|
+
if (scope === undefined || (scope.readRoots.length === 0 && !scope.network))
|
|
151
|
+
return undefined;
|
|
152
|
+
const roots = scope.readRoots.length === 0
|
|
153
|
+
? "the workspace"
|
|
154
|
+
: `the workspace and ${scope.readRoots.length} read root${scope.readRoots.length === 1 ? "" : "s"} (${scope.readRoots.join(", ")})`;
|
|
155
|
+
return `Scope: reads confined to ${roots}; network ${scope.network ? "on" : "off"}`;
|
|
156
|
+
}
|
|
157
|
+
// ---------------------------------------------------------------------------
|
|
158
|
+
// Hook enforcement of confined reads.
|
|
159
|
+
//
|
|
160
|
+
// Input schemas are those of kimi-code 0.41.0 (legacy agent-core), 2.0.0 and
|
|
161
|
+
// 2.7.3 (agent-core-v2): Read/ReadMediaFile resolve `path`; Glob and Grep
|
|
162
|
+
// search `path` or, when omitted, the session cwd; Glob's `pattern` and Grep's
|
|
163
|
+
// `glob` are ripgrep --glob filters inside that search root. Upstream expands
|
|
164
|
+
// `~`, resolves relative paths against the cwd and normalizes `..` lexically
|
|
165
|
+
// before access. ripgrep runs without --follow, so links met while walking are
|
|
166
|
+
// skipped; links named directly are followed, hence realpath below.
|
|
167
|
+
// ---------------------------------------------------------------------------
|
|
168
|
+
const SCOPED_READ_KEYS = {
|
|
169
|
+
Read: new Set(["path", "line_offset", "column_offset", "n_lines", "max_chars"]),
|
|
170
|
+
ReadMediaFile: new Set(["path", "region", "full_resolution"]),
|
|
171
|
+
Glob: new Set(["pattern", "path", "head_limit", "offset", "include_ignored", "include_dirs"]),
|
|
172
|
+
Grep: new Set([
|
|
173
|
+
"pattern", "path", "glob", "type", "output_mode", "-i", "-n", "-A", "-B", "-C",
|
|
174
|
+
"head_limit", "offset", "multiline", "include_ignored",
|
|
175
|
+
]),
|
|
176
|
+
};
|
|
177
|
+
export const SCOPED_READ_TOOLS = new Set(Object.keys(SCOPED_READ_KEYS));
|
|
178
|
+
class ScopeDenial extends Error {
|
|
179
|
+
}
|
|
180
|
+
export async function evaluateScopedRead(toolName, toolInput, roots) {
|
|
181
|
+
const deny = (why) => ({
|
|
182
|
+
decision: "deny",
|
|
183
|
+
reason: `kimi-plugin-cc safety hook: reads are confined to ${roots.length === 0 ? "no readable roots (the scope variables are malformed)" : roots.join(", ")}; tool "${toolName}" denied: ${why}`,
|
|
184
|
+
});
|
|
185
|
+
if (roots.length === 0)
|
|
186
|
+
return deny("no path can be read.");
|
|
187
|
+
const allowedKeys = SCOPED_READ_KEYS[toolName];
|
|
188
|
+
if (allowedKeys === undefined)
|
|
189
|
+
return deny("the tool has no confinement rule.");
|
|
190
|
+
if (typeof toolInput !== "object" || toolInput === null || Array.isArray(toolInput)) {
|
|
191
|
+
return deny("its arguments are not an object.");
|
|
192
|
+
}
|
|
193
|
+
const args = toolInput;
|
|
194
|
+
for (const key of Object.keys(args)) {
|
|
195
|
+
if (!allowedKeys.has(key))
|
|
196
|
+
return deny(`argument "${key}" cannot be checked.`);
|
|
197
|
+
}
|
|
198
|
+
try {
|
|
199
|
+
const targets = [];
|
|
200
|
+
if (toolName === "Read" || toolName === "ReadMediaFile") {
|
|
201
|
+
targets.push(requirePath(args.path, "path"));
|
|
202
|
+
}
|
|
203
|
+
else {
|
|
204
|
+
targets.push(args.path === undefined ? roots[0] : requirePath(args.path, "path"));
|
|
205
|
+
const patternKey = toolName === "Glob" ? "pattern" : "glob";
|
|
206
|
+
const pattern = args[patternKey];
|
|
207
|
+
if (toolName === "Glob" || pattern !== undefined) {
|
|
208
|
+
const anchor = patternAnchor(pattern, patternKey);
|
|
209
|
+
if (anchor !== undefined)
|
|
210
|
+
targets.push(anchor);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
for (const target of targets) {
|
|
214
|
+
const absolute = path.isAbsolute(target) ? path.resolve(target) : path.resolve(roots[0], target);
|
|
215
|
+
const real = await realTarget(absolute);
|
|
216
|
+
if (!roots.some((root) => isWithin(root, real))) {
|
|
217
|
+
return deny(`"${target}" resolves outside the read roots.`);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
catch (error) {
|
|
222
|
+
return deny(error instanceof ScopeDenial ? error.message : "its target could not be resolved.");
|
|
223
|
+
}
|
|
224
|
+
return { decision: "allow" };
|
|
225
|
+
}
|
|
226
|
+
function requirePath(value, key) {
|
|
227
|
+
if (typeof value !== "string" || value.length === 0 || value.includes("\0")) {
|
|
228
|
+
throw new ScopeDenial(`argument "${key}" is not a usable path.`);
|
|
229
|
+
}
|
|
230
|
+
// Upstream expands ~ against the home directory and treats kimi-file://
|
|
231
|
+
// as a session attachment; neither target is a workspace path.
|
|
232
|
+
if (value.startsWith("~"))
|
|
233
|
+
throw new ScopeDenial(`"${value}" uses home-directory expansion.`);
|
|
234
|
+
if (/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(value))
|
|
235
|
+
throw new ScopeDenial(`"${value}" is not a filesystem path.`);
|
|
236
|
+
denyAmbiguousSpelling(value, "path");
|
|
237
|
+
return value;
|
|
238
|
+
}
|
|
239
|
+
// Upstream resolves with pathe, which reads "\\" as a separator and a drive
|
|
240
|
+
// prefix as absolute; node:path on POSIX reads neither. Deny those spellings
|
|
241
|
+
// instead of imitating pathe.
|
|
242
|
+
function denyAmbiguousSpelling(value, noun) {
|
|
243
|
+
if (value.includes("\\"))
|
|
244
|
+
throw new ScopeDenial(`${noun} "${value}" contains a backslash.`);
|
|
245
|
+
if (/^[A-Za-z]:/.test(value))
|
|
246
|
+
throw new ScopeDenial(`${noun} "${value}" starts with a drive letter.`);
|
|
247
|
+
}
|
|
248
|
+
/** Literal directory an absolute glob names; undefined for a relative glob. */
|
|
249
|
+
function patternAnchor(value, key) {
|
|
250
|
+
if (typeof value !== "string" || value.includes("\0")) {
|
|
251
|
+
throw new ScopeDenial(`argument "${key}" is not a usable glob.`);
|
|
252
|
+
}
|
|
253
|
+
const body = value.startsWith("!") ? value.slice(1) : value;
|
|
254
|
+
if (body.startsWith("~"))
|
|
255
|
+
throw new ScopeDenial(`glob "${value}" uses home-directory expansion.`);
|
|
256
|
+
denyAmbiguousSpelling(body, "glob");
|
|
257
|
+
const segments = body.split("/");
|
|
258
|
+
if (segments.includes(".."))
|
|
259
|
+
throw new ScopeDenial(`glob "${value}" climbs with "..".`);
|
|
260
|
+
if (!path.isAbsolute(body))
|
|
261
|
+
return undefined;
|
|
262
|
+
const literal = [];
|
|
263
|
+
for (const segment of segments) {
|
|
264
|
+
if (/[*?[\]{}!]/.test(segment))
|
|
265
|
+
break;
|
|
266
|
+
literal.push(segment);
|
|
267
|
+
}
|
|
268
|
+
return literal.join("/") || "/";
|
|
269
|
+
}
|
|
270
|
+
/** Physical location of `absolute`: realpath when it exists, else the nearest existing ancestor's. */
|
|
271
|
+
async function realTarget(absolute) {
|
|
272
|
+
try {
|
|
273
|
+
return await realpath(absolute);
|
|
274
|
+
}
|
|
275
|
+
catch (error) {
|
|
276
|
+
const code = error.code;
|
|
277
|
+
if (code !== "ENOENT" && code !== "ENOTDIR")
|
|
278
|
+
throw error;
|
|
279
|
+
}
|
|
280
|
+
// A dangling link may later point anywhere; only a truly absent path falls back.
|
|
281
|
+
try {
|
|
282
|
+
await lstat(absolute);
|
|
283
|
+
throw new ScopeDenial(`"${absolute}" is a link whose target cannot be resolved.`);
|
|
284
|
+
}
|
|
285
|
+
catch (error) {
|
|
286
|
+
if (error instanceof ScopeDenial)
|
|
287
|
+
throw error;
|
|
288
|
+
}
|
|
289
|
+
let ancestor = path.dirname(absolute);
|
|
290
|
+
while (true) {
|
|
291
|
+
try {
|
|
292
|
+
const real = await realpath(ancestor);
|
|
293
|
+
return path.resolve(real, path.relative(ancestor, absolute));
|
|
294
|
+
}
|
|
295
|
+
catch (error) {
|
|
296
|
+
const code = error.code;
|
|
297
|
+
if (code !== "ENOENT" && code !== "ENOTDIR")
|
|
298
|
+
throw error;
|
|
299
|
+
const parent = path.dirname(ancestor);
|
|
300
|
+
if (parent === ancestor)
|
|
301
|
+
throw error;
|
|
302
|
+
ancestor = parent;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
function isWithin(root, candidate) {
|
|
307
|
+
const relative = path.relative(root, candidate);
|
|
308
|
+
return relative === "" || (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
|
|
309
|
+
}
|
|
310
|
+
// ---------------------------------------------------------------------------
|
|
311
|
+
// FetchURL targets under --network: http(s) without credentials, and never a
|
|
312
|
+
// local name or an IP literal that is not global unicast. The WHATWG parser
|
|
313
|
+
// canonicalizes the hostname; the raw authority is compared so that integer,
|
|
314
|
+
// hex, octal or percent-encoded IPv4 spellings are refused rather than decoded.
|
|
315
|
+
// ---------------------------------------------------------------------------
|
|
316
|
+
const NON_GLOBAL_IPV4 = [
|
|
317
|
+
[0x00000000, 8], // this network
|
|
318
|
+
[0x0a000000, 8], // private
|
|
319
|
+
[0x64400000, 10], // shared address space
|
|
320
|
+
[0x7f000000, 8], // loopback
|
|
321
|
+
[0xa9fe0000, 16], // link-local
|
|
322
|
+
[0xac100000, 12], // private
|
|
323
|
+
[0xc0000000, 24], // IETF protocol assignments
|
|
324
|
+
[0xc0000200, 24], // documentation
|
|
325
|
+
[0xc0586300, 24], // deprecated 6to4 relay anycast
|
|
326
|
+
[0xc0a80000, 16], // private
|
|
327
|
+
[0xc6120000, 15], // benchmarking
|
|
328
|
+
[0xc6336400, 24], // documentation
|
|
329
|
+
[0xcb007100, 24], // documentation
|
|
330
|
+
[0xe0000000, 4], // multicast
|
|
331
|
+
[0xf0000000, 4], // reserved, including broadcast
|
|
332
|
+
];
|
|
333
|
+
/** True when `url` is an allowed FetchURL target. */
|
|
334
|
+
export function isAllowedFetchUrl(url) {
|
|
335
|
+
if (typeof url !== "string" || !/^https?:\/\//i.test(url))
|
|
336
|
+
return false;
|
|
337
|
+
let parsed;
|
|
338
|
+
try {
|
|
339
|
+
parsed = new URL(url);
|
|
340
|
+
}
|
|
341
|
+
catch {
|
|
342
|
+
return false;
|
|
343
|
+
}
|
|
344
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
|
|
345
|
+
return false;
|
|
346
|
+
if (parsed.username !== "" || parsed.password !== "")
|
|
347
|
+
return false;
|
|
348
|
+
const host = parsed.hostname;
|
|
349
|
+
if (host.startsWith("[")) {
|
|
350
|
+
const hextets = ipv6Hextets(host.slice(1, -1));
|
|
351
|
+
return hextets !== undefined && isGlobalIpv6(hextets);
|
|
352
|
+
}
|
|
353
|
+
const ipv4 = ipv4Value(host);
|
|
354
|
+
if (ipv4 !== undefined) {
|
|
355
|
+
// The parser accepts many IPv4 spellings; only the canonical one is allowed.
|
|
356
|
+
if (rawHost(url) !== host)
|
|
357
|
+
return false;
|
|
358
|
+
return isGlobalIpv4(ipv4);
|
|
359
|
+
}
|
|
360
|
+
const name = host.replace(/\.+$/, "");
|
|
361
|
+
if (name.length === 0 || /^[0-9]+$/.test(name))
|
|
362
|
+
return false;
|
|
363
|
+
return !(name === "localhost" || name.endsWith(".localhost") || name.endsWith(".local") || name.endsWith(".internal"));
|
|
364
|
+
}
|
|
365
|
+
function rawHost(url) {
|
|
366
|
+
const authority = url.replace(/^https?:\/\//i, "").split(/[/\\?#]/, 1)[0];
|
|
367
|
+
const hostPort = authority.slice(authority.lastIndexOf("@") + 1);
|
|
368
|
+
return hostPort.replace(/:[0-9]*$/, "").toLowerCase();
|
|
369
|
+
}
|
|
370
|
+
function ipv4Value(host) {
|
|
371
|
+
const match = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
|
|
372
|
+
if (!match)
|
|
373
|
+
return undefined;
|
|
374
|
+
const octets = match.slice(1).map(Number);
|
|
375
|
+
if (octets.some((octet) => octet > 255))
|
|
376
|
+
return undefined;
|
|
377
|
+
return ((octets[0] << 24) >>> 0) + (octets[1] << 16) + (octets[2] << 8) + octets[3];
|
|
378
|
+
}
|
|
379
|
+
function inRange(value, base, bits) {
|
|
380
|
+
const mask = bits === 0 ? 0 : (0xffffffff << (32 - bits)) >>> 0;
|
|
381
|
+
return ((value & mask) >>> 0) === base;
|
|
382
|
+
}
|
|
383
|
+
function ipv6Hextets(text) {
|
|
384
|
+
const halves = text.split("::");
|
|
385
|
+
if (halves.length > 2)
|
|
386
|
+
return undefined;
|
|
387
|
+
const parse = (part) => {
|
|
388
|
+
if (part === "")
|
|
389
|
+
return [];
|
|
390
|
+
const out = [];
|
|
391
|
+
for (const piece of part.split(":")) {
|
|
392
|
+
if (piece.includes(".")) {
|
|
393
|
+
const v4 = ipv4Value(piece);
|
|
394
|
+
if (v4 === undefined)
|
|
395
|
+
return undefined;
|
|
396
|
+
out.push(v4 >>> 16, v4 & 0xffff);
|
|
397
|
+
}
|
|
398
|
+
else if (/^[0-9a-f]{1,4}$/i.test(piece)) {
|
|
399
|
+
out.push(parseInt(piece, 16));
|
|
400
|
+
}
|
|
401
|
+
else {
|
|
402
|
+
return undefined;
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
return out;
|
|
406
|
+
};
|
|
407
|
+
const head = parse(halves[0]);
|
|
408
|
+
const tail = halves.length === 2 ? parse(halves[1]) : [];
|
|
409
|
+
if (head === undefined || tail === undefined)
|
|
410
|
+
return undefined;
|
|
411
|
+
const fill = 8 - head.length - tail.length;
|
|
412
|
+
if (halves.length === 2 ? fill < 0 : fill !== 0)
|
|
413
|
+
return undefined;
|
|
414
|
+
return [...head, ...new Array(halves.length === 2 ? fill : 0).fill(0), ...tail];
|
|
415
|
+
}
|
|
416
|
+
function isGlobalIpv4(value) {
|
|
417
|
+
return !NON_GLOBAL_IPV4.some(([base, bits]) => inRange(value, base, bits));
|
|
418
|
+
}
|
|
419
|
+
/** Only global unicast 2000::/3, less its special-purpose blocks; NAT64 by its IPv4. */
|
|
420
|
+
function isGlobalIpv6(h) {
|
|
421
|
+
if (h[0] === 0x64 && h[1] === 0xff9b && h.slice(2, 6).every((part) => part === 0)) {
|
|
422
|
+
return isGlobalIpv4(((h[6] << 16) >>> 0) + h[7]);
|
|
423
|
+
}
|
|
424
|
+
if ((h[0] & 0xe000) !== 0x2000)
|
|
425
|
+
return false;
|
|
426
|
+
if (h[0] === 0x2001 && h[1] < 0x0200)
|
|
427
|
+
return false; // 2001::/23 IETF assignments, Teredo 2001::/32
|
|
428
|
+
if (h[0] === 0x2001 && h[1] === 0x0db8)
|
|
429
|
+
return false; // documentation
|
|
430
|
+
if (h[0] === 0x2002)
|
|
431
|
+
return false; // 6to4 embeds an IPv4 address
|
|
432
|
+
if (h[0] === 0x3fff && h[1] < 0x1000)
|
|
433
|
+
return false; // documentation 3fff::/20
|
|
434
|
+
return true;
|
|
435
|
+
}
|