harnery 0.41.0 → 0.43.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/dist/commander.d.ts +16 -0
- package/dist/commander.d.ts.map +1 -1
- package/dist/commander.js +21 -0
- package/dist/commands/agents.d.ts.map +1 -1
- package/dist/commands/agents.js +63 -5
- package/dist/commands/artifacts.d.ts.map +1 -1
- package/dist/commands/artifacts.js +113 -12
- package/dist/commands/browse.d.ts +164 -0
- package/dist/commands/browse.d.ts.map +1 -1
- package/dist/commands/browse.js +263 -51
- package/dist/commands/claude-desktop.d.ts.map +1 -1
- package/dist/commands/claude-desktop.js +52 -0
- package/dist/commands/disk.d.ts +6 -0
- package/dist/commands/disk.d.ts.map +1 -0
- package/dist/commands/disk.js +80 -0
- package/dist/commands/doctor.d.ts +8 -0
- package/dist/commands/doctor.d.ts.map +1 -1
- package/dist/commands/doctor.js +48 -1
- package/dist/commands/files.d.ts +16 -0
- package/dist/commands/files.d.ts.map +1 -1
- package/dist/commands/files.js +54 -2
- package/dist/commands/init.d.ts +2 -2
- package/dist/commands/init.d.ts.map +1 -1
- package/dist/commands/init.js +43 -9
- package/dist/commands/rm.d.ts +4 -0
- package/dist/commands/rm.d.ts.map +1 -0
- package/dist/commands/rm.js +87 -0
- package/dist/commands/servers.d.ts +7 -0
- package/dist/commands/servers.d.ts.map +1 -0
- package/dist/commands/servers.js +394 -0
- package/dist/commands/tunnel.d.ts +65 -0
- package/dist/commands/tunnel.d.ts.map +1 -1
- package/dist/commands/tunnel.js +372 -103
- package/dist/commands/web-fetch.d.ts +3 -2
- package/dist/commands/web-fetch.d.ts.map +1 -1
- package/dist/commands/web-fetch.js +25 -19
- package/dist/commands/web.d.ts +7 -1
- package/dist/commands/web.d.ts.map +1 -1
- package/dist/commands/web.js +9 -3
- package/dist/core/adapters/profiles.d.ts +9 -0
- package/dist/core/adapters/profiles.d.ts.map +1 -1
- package/dist/core/adapters/profiles.js +22 -1
- package/dist/core/adapters/types.d.ts +9 -0
- package/dist/core/adapters/types.d.ts.map +1 -1
- package/dist/core/agents/cli.js +13 -6
- package/dist/core/agents/render/prompt-context.d.ts.map +1 -1
- package/dist/core/agents/render/prompt-context.js +11 -5
- package/dist/core/agents/render/session-context.d.ts.map +1 -1
- package/dist/core/agents/render/session-context.js +59 -13
- package/dist/core/agents/state/live-coordination-view.d.ts +20 -0
- package/dist/core/agents/state/live-coordination-view.d.ts.map +1 -1
- package/dist/core/agents/state/live-coordination-view.js +60 -0
- package/dist/core/agents/state/names.d.ts +43 -3
- package/dist/core/agents/state/names.d.ts.map +1 -1
- package/dist/core/agents/state/names.js +87 -3
- package/dist/core/artifacts/delivery-card.js +9 -2
- package/dist/core/artifacts/index.d.ts +140 -4
- package/dist/core/artifacts/index.d.ts.map +1 -1
- package/dist/core/artifacts/index.js +522 -49
- package/dist/core/config.d.ts +68 -11
- package/dist/core/config.d.ts.map +1 -1
- package/dist/core/config.js +128 -3
- package/dist/core/diagnostics/bundle.d.ts.map +1 -1
- package/dist/core/diagnostics/bundle.js +2 -2
- package/dist/core/events/v3/producers/recorder.d.ts.map +1 -1
- package/dist/core/events/v3/producers/recorder.js +16 -0
- package/dist/core/events/v3/projection.js +9 -1
- package/dist/core/events/v3/support-storage/pack-reader.d.ts.map +1 -1
- package/dist/core/events/v3/support-storage/pack-reader.js +42 -16
- package/dist/core/hooks/adapter/events.d.ts +17 -0
- package/dist/core/hooks/adapter/events.d.ts.map +1 -1
- package/dist/core/hooks/adapter/events.js +5 -0
- package/dist/core/hooks/adapter/runtime-telemetry.js +3 -1
- package/dist/core/hooks/adapter/wiring.d.ts +37 -7
- package/dist/core/hooks/adapter/wiring.d.ts.map +1 -1
- package/dist/core/hooks/adapter/wiring.js +62 -4
- package/dist/core/hooks/cli.js +131 -23
- package/dist/core/hooks/fork-lineage.d.ts +40 -0
- package/dist/core/hooks/fork-lineage.d.ts.map +1 -0
- package/dist/core/hooks/fork-lineage.js +62 -0
- package/dist/core/hooks/resolve/transcript.d.ts +16 -0
- package/dist/core/hooks/resolve/transcript.d.ts.map +1 -1
- package/dist/core/hooks/resolve/transcript.js +84 -0
- package/dist/core/hooks/run-markers.d.ts +37 -0
- package/dist/core/hooks/run-markers.d.ts.map +1 -0
- package/dist/core/hooks/run-markers.js +109 -0
- package/dist/core/hooks/shell-rm.d.ts +2 -0
- package/dist/core/hooks/shell-rm.d.ts.map +1 -0
- package/dist/core/hooks/shell-rm.js +105 -0
- package/dist/core/hooks/shell-tokens.d.ts +12 -0
- package/dist/core/hooks/shell-tokens.d.ts.map +1 -0
- package/dist/core/hooks/shell-tokens.js +97 -0
- package/dist/core/hooks/shell-waiter.d.ts.map +1 -1
- package/dist/core/hooks/shell-waiter.js +3 -93
- package/dist/core/semantic/contract.d.ts +5 -5
- package/dist/core/servers/index.d.ts +211 -0
- package/dist/core/servers/index.d.ts.map +1 -0
- package/dist/core/servers/index.js +560 -0
- package/dist/core/servers/net.d.ts +58 -0
- package/dist/core/servers/net.d.ts.map +1 -0
- package/dist/core/servers/net.js +270 -0
- package/dist/core/servers/tunnels.d.ts +14 -0
- package/dist/core/servers/tunnels.d.ts.map +1 -0
- package/dist/core/servers/tunnels.js +33 -0
- package/dist/core/storage/builtins.js +1 -0
- package/dist/core/storage/process-log.d.ts +12 -0
- package/dist/core/storage/process-log.d.ts.map +1 -1
- package/dist/core/storage/process-log.js +10 -2
- package/dist/core/workflow/engine.d.ts.map +1 -1
- package/dist/core/workflow/engine.js +30 -1
- package/dist/core/workflow/sandbox-projection.d.ts +13 -2
- package/dist/core/workflow/sandbox-projection.d.ts.map +1 -1
- package/dist/core/workflow/sandbox-projection.js +23 -0
- package/dist/core/workflow/spawn-claude.d.ts.map +1 -1
- package/dist/core/workflow/spawn-claude.js +6 -1
- package/dist/core/workflow/spawn-codex.d.ts +2 -0
- package/dist/core/workflow/spawn-codex.d.ts.map +1 -1
- package/dist/core/workflow/spawn-codex.js +20 -1
- package/dist/core/workflow/spawn-cursor.d.ts.map +1 -1
- package/dist/core/workflow/spawn-cursor.js +6 -1
- package/dist/core/workflow/spawn-opencode.d.ts.map +1 -1
- package/dist/core/workflow/spawn-opencode.js +4 -1
- package/dist/core/workflow/types.d.ts +47 -2
- package/dist/core/workflow/types.d.ts.map +1 -1
- package/dist/core/workflow/worker-access.d.ts +92 -0
- package/dist/core/workflow/worker-access.d.ts.map +1 -0
- package/dist/core/workflow/worker-access.js +450 -0
- package/dist/lib/browser/batch-steps.d.ts +18 -0
- package/dist/lib/browser/batch-steps.d.ts.map +1 -0
- package/dist/lib/browser/batch-steps.js +82 -0
- package/dist/lib/browser/collect/collector.d.ts +99 -0
- package/dist/lib/browser/collect/collector.d.ts.map +1 -0
- package/dist/lib/browser/collect/collector.js +202 -0
- package/dist/lib/browser/collect/fields.d.ts +31 -0
- package/dist/lib/browser/collect/fields.d.ts.map +1 -0
- package/dist/lib/browser/collect/fields.js +75 -0
- package/dist/lib/browser/collect/index.d.ts +6 -0
- package/dist/lib/browser/collect/index.d.ts.map +1 -0
- package/dist/lib/browser/collect/index.js +5 -0
- package/dist/lib/browser/collect/page-driver.d.ts +14 -0
- package/dist/lib/browser/collect/page-driver.d.ts.map +1 -0
- package/dist/lib/browser/collect/page-driver.js +306 -0
- package/dist/lib/browser/collect/presets.d.ts +52 -0
- package/dist/lib/browser/collect/presets.d.ts.map +1 -0
- package/dist/lib/browser/collect/presets.js +176 -0
- package/dist/lib/browser/collect/scroll-plan.d.ts +85 -0
- package/dist/lib/browser/collect/scroll-plan.d.ts.map +1 -0
- package/dist/lib/browser/collect/scroll-plan.js +118 -0
- package/dist/lib/browser/index.d.ts +1 -1
- package/dist/lib/browser/index.d.ts.map +1 -1
- package/dist/lib/browser/page-review-judge.d.ts +2 -0
- package/dist/lib/browser/page-review-judge.d.ts.map +1 -1
- package/dist/lib/browser/page-review-judge.js +13 -0
- package/dist/lib/browser/qa-run-contracts.d.ts +10 -0
- package/dist/lib/browser/qa-run-contracts.d.ts.map +1 -1
- package/dist/lib/browser/qa-run.d.ts.map +1 -1
- package/dist/lib/browser/qa-run.js +1 -0
- package/dist/lib/browser/windows-chrome.d.ts +59 -0
- package/dist/lib/browser/windows-chrome.d.ts.map +1 -0
- package/dist/lib/browser/windows-chrome.js +179 -0
- package/dist/lib/claude-desktop-share.d.ts +136 -0
- package/dist/lib/claude-desktop-share.d.ts.map +1 -0
- package/dist/lib/claude-desktop-share.js +394 -0
- package/dist/lib/disk-usage.d.ts +50 -0
- package/dist/lib/disk-usage.d.ts.map +1 -0
- package/dist/lib/disk-usage.js +303 -0
- package/dist/lib/docs-lint.d.ts +6 -0
- package/dist/lib/docs-lint.d.ts.map +1 -1
- package/dist/lib/docs-lint.js +8 -3
- package/dist/lib/guarded-remove.d.ts +34 -0
- package/dist/lib/guarded-remove.d.ts.map +1 -0
- package/dist/lib/guarded-remove.js +310 -0
- package/dist/lib/instructions/templates.js +8 -8
- package/dist/lib/tunnel/allowlist.d.ts +44 -0
- package/dist/lib/tunnel/allowlist.d.ts.map +1 -0
- package/dist/lib/tunnel/allowlist.js +204 -0
- package/dist/lib/tunnel/current-address.d.ts +41 -0
- package/dist/lib/tunnel/current-address.d.ts.map +1 -0
- package/dist/lib/tunnel/current-address.js +123 -0
- package/dist/lib/tunnel/error-page.d.ts +1 -1
- package/dist/lib/tunnel/error-page.d.ts.map +1 -1
- package/dist/lib/tunnel/error-page.js +19 -8
- package/dist/lib/tunnel/gate.js +33 -7
- package/dist/lib/tunnel/path-scope.d.ts +22 -0
- package/dist/lib/tunnel/path-scope.d.ts.map +1 -0
- package/dist/lib/tunnel/path-scope.js +62 -0
- package/dist/lib/tunnel/processes.d.ts +39 -0
- package/dist/lib/tunnel/processes.d.ts.map +1 -0
- package/dist/lib/tunnel/processes.js +121 -0
- package/dist/lib/tunnel/state.d.ts +33 -3
- package/dist/lib/tunnel/state.d.ts.map +1 -1
- package/dist/lib/tunnel/state.js +115 -30
- package/package.json +7 -1
- package/schemas/config.schema.json +91 -0
- package/src/commander.ts +51 -0
- package/src/commands/agents.ts +111 -11
- package/src/commands/artifacts.ts +171 -19
- package/src/commands/browse.ts +400 -57
- package/src/commands/claude-desktop.ts +61 -0
- package/src/commands/disk.ts +114 -0
- package/src/commands/doctor.ts +52 -1
- package/src/commands/files.ts +93 -2
- package/src/commands/init.ts +55 -5
- package/src/commands/rm.ts +115 -0
- package/src/commands/servers.ts +506 -0
- package/src/commands/tunnel.ts +494 -116
- package/src/commands/web-fetch.ts +30 -19
- package/src/commands/web.ts +9 -3
- package/src/core/adapters/profiles.ts +22 -1
- package/src/core/adapters/types.ts +10 -0
- package/src/core/agents/cli.ts +14 -6
- package/src/core/agents/render/prompt-context.ts +25 -8
- package/src/core/agents/render/session-context.ts +84 -16
- package/src/core/agents/state/live-coordination-view.ts +73 -0
- package/src/core/agents/state/names.ts +117 -6
- package/src/core/artifacts/delivery-card.ts +10 -2
- package/src/core/artifacts/index.ts +697 -44
- package/src/core/config.ts +183 -4
- package/src/core/diagnostics/bundle.ts +2 -1
- package/src/core/events/v3/producers/recorder.ts +16 -0
- package/src/core/events/v3/projection.ts +11 -1
- package/src/core/events/v3/support-storage/pack-reader.ts +45 -19
- package/src/core/hooks/adapter/events.ts +19 -0
- package/src/core/hooks/adapter/runtime-telemetry.ts +3 -1
- package/src/core/hooks/adapter/wiring.ts +116 -8
- package/src/core/hooks/cli.ts +152 -22
- package/src/core/hooks/fork-lineage.ts +82 -0
- package/src/core/hooks/resolve/transcript.ts +88 -0
- package/src/core/hooks/run-markers.ts +132 -0
- package/src/core/hooks/shell-rm.ts +103 -0
- package/src/core/hooks/shell-tokens.ts +96 -0
- package/src/core/hooks/shell-waiter.ts +4 -91
- package/src/core/servers/index.ts +712 -0
- package/src/core/servers/net.ts +283 -0
- package/src/core/servers/tunnels.ts +39 -0
- package/src/core/storage/builtins.ts +1 -0
- package/src/core/storage/process-log.ts +17 -2
- package/src/core/workflow/engine.ts +38 -1
- package/src/core/workflow/sandbox-projection.ts +38 -2
- package/src/core/workflow/spawn-claude.ts +5 -1
- package/src/core/workflow/spawn-codex.ts +18 -1
- package/src/core/workflow/spawn-cursor.ts +5 -1
- package/src/core/workflow/spawn-opencode.ts +4 -1
- package/src/core/workflow/types.ts +62 -2
- package/src/core/workflow/worker-access.ts +525 -0
- package/src/lib/browser/batch-steps.ts +79 -0
- package/src/lib/browser/collect/collector.ts +306 -0
- package/src/lib/browser/collect/fields.ts +87 -0
- package/src/lib/browser/collect/index.ts +47 -0
- package/src/lib/browser/collect/page-driver.ts +327 -0
- package/src/lib/browser/collect/presets.ts +237 -0
- package/src/lib/browser/collect/scroll-plan.ts +179 -0
- package/src/lib/browser/index.ts +1 -0
- package/src/lib/browser/page-review-judge.ts +16 -0
- package/src/lib/browser/qa-run-contracts.ts +11 -0
- package/src/lib/browser/qa-run.ts +1 -0
- package/src/lib/browser/windows-chrome.ts +227 -0
- package/src/lib/claude-desktop-share.ts +511 -0
- package/src/lib/disk-usage.ts +347 -0
- package/src/lib/docs-lint.ts +8 -3
- package/src/lib/guarded-remove.ts +376 -0
- package/src/lib/instructions/templates.ts +8 -8
- package/src/lib/tunnel/allowlist.ts +208 -0
- package/src/lib/tunnel/current-address.ts +158 -0
- package/src/lib/tunnel/error-page.ts +25 -9
- package/src/lib/tunnel/gate.ts +38 -9
- package/src/lib/tunnel/path-scope.ts +73 -0
- package/src/lib/tunnel/processes.ts +149 -0
- package/src/lib/tunnel/state.ts +143 -30
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { lstatSync, readdirSync, readlinkSync, realpathSync, rmSync, type Stats } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { basename, dirname, isAbsolute, parse, relative, resolve, sep } from "node:path";
|
|
5
|
+
|
|
6
|
+
export interface RemoveOptions {
|
|
7
|
+
root: string;
|
|
8
|
+
recursive?: boolean;
|
|
9
|
+
yes?: boolean;
|
|
10
|
+
dryRun?: boolean;
|
|
11
|
+
/**
|
|
12
|
+
* Protected paths (Git metadata, credentials, Harnery state, SSH or GnuPG
|
|
13
|
+
* keys, a bare repository) the caller names for removal, one exact path
|
|
14
|
+
* each. A protected path that is not named is still refused.
|
|
15
|
+
*/
|
|
16
|
+
allowProtected?: string[];
|
|
17
|
+
/** Directories whose own Git metadata and Harnery state may never be allowed (the live workspace). */
|
|
18
|
+
liveRoots?: string[];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface RemovalLink {
|
|
22
|
+
path: string;
|
|
23
|
+
/** What the link points to. It is removed as a link and never followed. */
|
|
24
|
+
target: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface RemovalReport {
|
|
28
|
+
schema: "harnery.removal/v1";
|
|
29
|
+
applied: boolean;
|
|
30
|
+
root: string;
|
|
31
|
+
targets: string[];
|
|
32
|
+
entries: number;
|
|
33
|
+
bytes: number;
|
|
34
|
+
/** Protected paths removed because the caller named them with allowProtected. */
|
|
35
|
+
protected: string[];
|
|
36
|
+
/** Symbolic links inside recursive targets, removed as links. */
|
|
37
|
+
links: RemovalLink[];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const protectedNames = new Set([".git", ".harnery", ".credentials", ".ssh", ".gnupg"]);
|
|
41
|
+
const MAX_ENTRIES = 10_000;
|
|
42
|
+
|
|
43
|
+
/** Permanent removal is deliberately limited to inspected, untracked local outputs. */
|
|
44
|
+
export function guardedRemove(
|
|
45
|
+
paths: string[],
|
|
46
|
+
options: RemoveOptions,
|
|
47
|
+
checkClaims: (targets: string[]) => void = () => {},
|
|
48
|
+
): RemovalReport {
|
|
49
|
+
const cwd = realpathSync(process.cwd());
|
|
50
|
+
const root = checkedPath(options.root, new Set(), true);
|
|
51
|
+
const allowed = allowedProtected(options.allowProtected ?? [], root, options.liveRoots ?? []);
|
|
52
|
+
const rootStat = lstatSync(root);
|
|
53
|
+
const rootFingerprint = fingerprint(rootStat);
|
|
54
|
+
if (!rootStat.isDirectory()) throw new Error("--root must be a directory");
|
|
55
|
+
if (root === parse(root).root || root === realpathSync(homedir()))
|
|
56
|
+
throw new Error("--root cannot be a filesystem root or home directory");
|
|
57
|
+
if (paths.length === 0 || paths.length > 100) throw new Error("Supply 1-100 explicit targets");
|
|
58
|
+
const targets = paths.map((path) => checkedPath(path, allowed));
|
|
59
|
+
const snapshots = new Map<string, string>();
|
|
60
|
+
const removedProtected = new Set<string>();
|
|
61
|
+
const links: RemovalLink[] = [];
|
|
62
|
+
const gitDirs = new Set<string>();
|
|
63
|
+
let bytes = 0;
|
|
64
|
+
const devices = new Set<number>();
|
|
65
|
+
|
|
66
|
+
for (const target of targets) {
|
|
67
|
+
const home = realpathSync(homedir());
|
|
68
|
+
if (target === home || strictlyInside(target, home))
|
|
69
|
+
throw new Error(`Cannot remove the home directory or its ancestor: ${target}`);
|
|
70
|
+
const systemRoots =
|
|
71
|
+
process.platform === "win32"
|
|
72
|
+
? [
|
|
73
|
+
process.env.SystemRoot,
|
|
74
|
+
process.env.ProgramFiles,
|
|
75
|
+
process.env["ProgramFiles(x86)"],
|
|
76
|
+
].filter((value): value is string => Boolean(value))
|
|
77
|
+
: [
|
|
78
|
+
"/etc",
|
|
79
|
+
"/usr",
|
|
80
|
+
"/boot",
|
|
81
|
+
"/dev",
|
|
82
|
+
"/proc",
|
|
83
|
+
"/sys",
|
|
84
|
+
"/bin",
|
|
85
|
+
"/sbin",
|
|
86
|
+
"/lib",
|
|
87
|
+
"/lib64",
|
|
88
|
+
"/run",
|
|
89
|
+
];
|
|
90
|
+
if (
|
|
91
|
+
systemRoots.some(
|
|
92
|
+
(system) =>
|
|
93
|
+
target === resolve(system) ||
|
|
94
|
+
strictlyInside(resolve(system), target) ||
|
|
95
|
+
strictlyInside(target, resolve(system)),
|
|
96
|
+
)
|
|
97
|
+
)
|
|
98
|
+
throw new Error(`System files are protected: ${target}`);
|
|
99
|
+
if (!strictlyInside(root, target))
|
|
100
|
+
throw new Error(`Target must be strictly inside --root: ${target}`);
|
|
101
|
+
if (target === cwd || strictlyInside(target, cwd))
|
|
102
|
+
throw new Error(`Cannot remove the working directory or its ancestor: ${target}`);
|
|
103
|
+
if (
|
|
104
|
+
targets.some((other) => other !== target && strictlyInside(other, target)) ||
|
|
105
|
+
targets.filter((other) => other === target).length > 1
|
|
106
|
+
)
|
|
107
|
+
throw new Error("Targets must not duplicate or contain one another");
|
|
108
|
+
const stat = lstatSync(target);
|
|
109
|
+
if (stat.dev !== rootStat.dev) throw new Error(`Target crosses a mount boundary: ${target}`);
|
|
110
|
+
if (stat.isDirectory() && !options.recursive)
|
|
111
|
+
throw new Error(`Directory removal requires --recursive: ${target}`);
|
|
112
|
+
const device = stat.dev;
|
|
113
|
+
devices.add(device);
|
|
114
|
+
const pending = [target];
|
|
115
|
+
while (pending.length) {
|
|
116
|
+
const path = pending.pop()!;
|
|
117
|
+
const info = lstatSync(path);
|
|
118
|
+
if (basename(path) === ARTIFACT_RECORD && insideArtifactWorkspace(path, null))
|
|
119
|
+
throw new Error(`An artifact's record is managed by the artifact commands: ${path}`);
|
|
120
|
+
if (protectedNames.has(basename(path).toLowerCase())) {
|
|
121
|
+
if (!allowed.has(path)) throw new Error(protectedMessage(path));
|
|
122
|
+
removedProtected.add(path);
|
|
123
|
+
}
|
|
124
|
+
if (info.isSymbolicLink()) {
|
|
125
|
+
// A link inside the tree is removed as a link; its target is never
|
|
126
|
+
// read, followed, or counted. (The target itself and its ancestors
|
|
127
|
+
// were already refused if they were links, in checkedPath.)
|
|
128
|
+
if (path === target) throw new Error(`Path contains a symlink: ${path}`);
|
|
129
|
+
if (snapshots.size >= MAX_ENTRIES)
|
|
130
|
+
throw new Error(
|
|
131
|
+
`Removal exceeds the ${MAX_ENTRIES}-entry limit; use the owning cleanup command`,
|
|
132
|
+
);
|
|
133
|
+
snapshots.set(path, fingerprint(info));
|
|
134
|
+
links.push({ path, target: readlinkSync(path) });
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
if (info.dev !== device || (!info.isDirectory() && !info.isFile()))
|
|
138
|
+
throw new Error(`Mount boundary or special file cannot be removed: ${path}`);
|
|
139
|
+
if (snapshots.size >= MAX_ENTRIES)
|
|
140
|
+
throw new Error(
|
|
141
|
+
`Removal exceeds the ${MAX_ENTRIES}-entry limit; use the owning cleanup command`,
|
|
142
|
+
);
|
|
143
|
+
snapshots.set(path, fingerprint(info));
|
|
144
|
+
if (info.isFile()) bytes += info.size;
|
|
145
|
+
else {
|
|
146
|
+
const names = readdirSync(path);
|
|
147
|
+
if (
|
|
148
|
+
names.includes("HEAD") &&
|
|
149
|
+
names.includes("objects") &&
|
|
150
|
+
names.includes("config") &&
|
|
151
|
+
!insideAllowed(path, allowed)
|
|
152
|
+
)
|
|
153
|
+
throw new Error(
|
|
154
|
+
`Repository metadata cannot be removed: ${path}. To remove it on purpose, name it with --allow-protected ${path}`,
|
|
155
|
+
);
|
|
156
|
+
if (allowed.has(path)) removedProtected.add(path);
|
|
157
|
+
if (isRepositoryMetadata(path)) gitDirs.add(path);
|
|
158
|
+
for (const name of names) pending.push(resolve(path, name));
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
assertUntracked(target);
|
|
162
|
+
}
|
|
163
|
+
if (devices.size > 1) throw new Error("Targets must be on one filesystem");
|
|
164
|
+
for (const path of allowed)
|
|
165
|
+
if (!removedProtected.has(path))
|
|
166
|
+
throw new Error(`--allow-protected names a path no target removes: ${path}`);
|
|
167
|
+
for (const dir of gitDirs) assertNoUnpushedHistory(dir);
|
|
168
|
+
checkClaims(targets);
|
|
169
|
+
const report: RemovalReport = {
|
|
170
|
+
schema: "harnery.removal/v1",
|
|
171
|
+
applied: false,
|
|
172
|
+
root,
|
|
173
|
+
targets,
|
|
174
|
+
entries: snapshots.size,
|
|
175
|
+
bytes,
|
|
176
|
+
protected: [...removedProtected].sort(),
|
|
177
|
+
links,
|
|
178
|
+
};
|
|
179
|
+
if (!options.yes || options.dryRun) return report;
|
|
180
|
+
|
|
181
|
+
// Recheck the entire batch before its first mutation. Filesystem changes after
|
|
182
|
+
// these checks remain possible; this is a guard, not a transactional filesystem.
|
|
183
|
+
if (
|
|
184
|
+
checkedPath(options.root, new Set(), true) !== root ||
|
|
185
|
+
fingerprint(lstatSync(root)) !== rootFingerprint
|
|
186
|
+
)
|
|
187
|
+
throw new Error("Allowed root changed during inspection");
|
|
188
|
+
for (const target of targets) {
|
|
189
|
+
checkedPath(target, allowed);
|
|
190
|
+
assertUntracked(target);
|
|
191
|
+
}
|
|
192
|
+
for (const dir of gitDirs) assertNoUnpushedHistory(dir);
|
|
193
|
+
checkClaims(targets);
|
|
194
|
+
for (const [path, previous] of snapshots) {
|
|
195
|
+
if (fingerprint(lstatSync(path)) !== previous)
|
|
196
|
+
throw new Error(`Target changed during inspection: ${path}`);
|
|
197
|
+
}
|
|
198
|
+
for (const target of targets)
|
|
199
|
+
rmSync(target, { recursive: Boolean(options.recursive), force: false });
|
|
200
|
+
return { ...report, applied: true };
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** The metadata file the artifact commands keep in each artifact workspace. */
|
|
204
|
+
const ARTIFACT_RECORD = ".harnery-artifact.json";
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* True when `path` lies strictly inside one artifact workspace,
|
|
208
|
+
* <dir>/.harnery/artifacts/<id>/..., under the `.harnery` component `state`
|
|
209
|
+
* (any `.harnery` when null). Artifact workspaces hold local outputs, so their
|
|
210
|
+
* contents may be removed; the workspace itself, its record file, and the rest
|
|
211
|
+
* of Harnery state stay protected and follow the artifact commands. `orSelf`
|
|
212
|
+
* accepts the workspace directory itself (used for --root, which is never removed).
|
|
213
|
+
*/
|
|
214
|
+
function insideArtifactWorkspace(path: string, state: string | null, orSelf = false): boolean {
|
|
215
|
+
const parts = path.split(sep);
|
|
216
|
+
for (let i = 0; i < parts.length; i++) {
|
|
217
|
+
if (parts[i]!.toLowerCase() !== ".harnery") continue;
|
|
218
|
+
if (state !== null && parts.slice(0, i + 1).join(sep) !== state) continue;
|
|
219
|
+
// .harnery / artifacts / <id> / <something>
|
|
220
|
+
return (
|
|
221
|
+
parts[i + 1] === "artifacts" && Boolean(parts[i + 2]) && parts.length >= i + (orSelf ? 3 : 4)
|
|
222
|
+
);
|
|
223
|
+
}
|
|
224
|
+
return false;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function protectedMessage(path: string): string {
|
|
228
|
+
return `Protected state cannot be removed: ${path}. To remove it on purpose, name it with --allow-protected ${path}`;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function insideAllowed(path: string, allowed: ReadonlySet<string>): boolean {
|
|
232
|
+
for (const entry of allowed) if (path === entry || strictlyInside(entry, path)) return true;
|
|
233
|
+
return false;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Resolves the caller's --allow-protected paths. Each must be one exact
|
|
238
|
+
* protected path strictly inside the root, reached without symlinks, and
|
|
239
|
+
* never the Git metadata or Harnery state of a live workspace root.
|
|
240
|
+
*/
|
|
241
|
+
function allowedProtected(paths: string[], root: string, liveRoots: string[]): Set<string> {
|
|
242
|
+
const allowed = new Set<string>();
|
|
243
|
+
const live = liveRoots.map((dir) => resolve(dir));
|
|
244
|
+
for (const input of paths) {
|
|
245
|
+
if (!input?.trim() || /[\0\r\n*?[\]$]/.test(input))
|
|
246
|
+
throw new Error("Use a nonempty explicit --allow-protected path without wildcards");
|
|
247
|
+
const path = resolve(input);
|
|
248
|
+
let cursor = dirname(path);
|
|
249
|
+
while (true) {
|
|
250
|
+
if (lstatSync(cursor).isSymbolicLink())
|
|
251
|
+
throw new Error(`--allow-protected path contains a symlink: ${cursor}`);
|
|
252
|
+
const parent = dirname(cursor);
|
|
253
|
+
if (parent === cursor) break;
|
|
254
|
+
cursor = parent;
|
|
255
|
+
}
|
|
256
|
+
const info = lstatSync(path);
|
|
257
|
+
if (info.isSymbolicLink()) throw new Error(`--allow-protected path is a symlink: ${path}`);
|
|
258
|
+
if (!strictlyInside(root, path))
|
|
259
|
+
throw new Error(`--allow-protected path must be strictly inside --root: ${path}`);
|
|
260
|
+
const named = protectedNames.has(basename(path).toLowerCase());
|
|
261
|
+
if (!named && !(info.isDirectory() && isRepositoryMetadata(path)))
|
|
262
|
+
throw new Error(`--allow-protected must name a protected path itself: ${path}`);
|
|
263
|
+
for (const dir of live) {
|
|
264
|
+
const own = [".git", ".harnery"].map((name) => resolve(dir, name));
|
|
265
|
+
if (
|
|
266
|
+
path === dir ||
|
|
267
|
+
strictlyInside(path, dir) ||
|
|
268
|
+
own.some((state) => path === state || strictlyInside(state, path))
|
|
269
|
+
)
|
|
270
|
+
throw new Error(`The live workspace's own state cannot be allowed: ${path}`);
|
|
271
|
+
}
|
|
272
|
+
allowed.add(realpathSync(path));
|
|
273
|
+
}
|
|
274
|
+
return allowed;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function isRepositoryMetadata(dir: string): boolean {
|
|
278
|
+
const names = readdirSync(dir);
|
|
279
|
+
return names.includes("HEAD") && names.includes("objects") && names.includes("config");
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Removing a repository's metadata loses any commit that exists nowhere
|
|
284
|
+
* else. An allowed Git directory must have no branch or tag commit missing
|
|
285
|
+
* from its remotes; anything that cannot be checked is refused.
|
|
286
|
+
*/
|
|
287
|
+
function assertNoUnpushedHistory(gitDir: string): void {
|
|
288
|
+
const result = spawnSync(
|
|
289
|
+
"git",
|
|
290
|
+
[
|
|
291
|
+
"--git-dir",
|
|
292
|
+
gitDir,
|
|
293
|
+
"rev-list",
|
|
294
|
+
"--max-count=1",
|
|
295
|
+
"--branches",
|
|
296
|
+
"--tags",
|
|
297
|
+
"--not",
|
|
298
|
+
"--remotes",
|
|
299
|
+
],
|
|
300
|
+
{
|
|
301
|
+
encoding: "utf8",
|
|
302
|
+
timeout: 10_000,
|
|
303
|
+
env: { ...process.env, LC_ALL: "C", GIT_DIR: undefined, GIT_WORK_TREE: undefined },
|
|
304
|
+
},
|
|
305
|
+
);
|
|
306
|
+
if (result.error || result.status !== 0)
|
|
307
|
+
throw new Error(`Cannot confirm ${gitDir} holds no unpushed history`);
|
|
308
|
+
if (result.stdout.trim()) throw new Error(`Repository has commits not on any remote: ${gitDir}`);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function strictlyInside(parent: string, child: string): boolean {
|
|
312
|
+
const rel = relative(parent, child);
|
|
313
|
+
return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function checkedPath(
|
|
317
|
+
input: string,
|
|
318
|
+
allowed: ReadonlySet<string> = new Set(),
|
|
319
|
+
isRoot = false,
|
|
320
|
+
): string {
|
|
321
|
+
if (!input?.trim() || /[\0\r\n*?[\]$]/.test(input))
|
|
322
|
+
throw new Error("Use a nonempty explicit path without wildcards or unresolved variables");
|
|
323
|
+
const path = resolve(input);
|
|
324
|
+
let cursor = path;
|
|
325
|
+
while (true) {
|
|
326
|
+
if (
|
|
327
|
+
protectedNames.has(basename(cursor).toLowerCase()) &&
|
|
328
|
+
!allowed.has(cursor) &&
|
|
329
|
+
!insideArtifactWorkspace(path, cursor, isRoot)
|
|
330
|
+
)
|
|
331
|
+
throw new Error(
|
|
332
|
+
cursor === path ? protectedMessage(path) : `Protected state contains this path: ${cursor}`,
|
|
333
|
+
);
|
|
334
|
+
const info = lstatSync(cursor);
|
|
335
|
+
if (info.isSymbolicLink()) throw new Error(`Path contains a symlink: ${cursor}`);
|
|
336
|
+
const parent = dirname(cursor);
|
|
337
|
+
if (parent === cursor) break;
|
|
338
|
+
cursor = parent;
|
|
339
|
+
}
|
|
340
|
+
return realpathSync(path);
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
function fingerprint(stat: Stats): string {
|
|
344
|
+
return [stat.dev, stat.ino, stat.mode, stat.size, stat.mtimeMs, stat.ctimeMs].join(":");
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function assertUntracked(target: string): void {
|
|
348
|
+
const git = (args: string[]) =>
|
|
349
|
+
spawnSync("git", ["-C", dirname(target), ...args], {
|
|
350
|
+
encoding: "utf8",
|
|
351
|
+
timeout: 10_000,
|
|
352
|
+
maxBuffer: 4 * 1024 * 1024,
|
|
353
|
+
env: {
|
|
354
|
+
...process.env,
|
|
355
|
+
LC_ALL: "C",
|
|
356
|
+
GIT_LITERAL_PATHSPECS: "1",
|
|
357
|
+
GIT_DIR: undefined,
|
|
358
|
+
GIT_WORK_TREE: undefined,
|
|
359
|
+
GIT_INDEX_FILE: undefined,
|
|
360
|
+
},
|
|
361
|
+
});
|
|
362
|
+
const detected = git(["rev-parse", "--show-toplevel"]);
|
|
363
|
+
if (detected.error) throw new Error(`Cannot check Git ownership: ${detected.error.message}`);
|
|
364
|
+
if (detected.status !== 0) {
|
|
365
|
+
if (detected.status === 128 && detected.stderr.startsWith("fatal: not a git repository"))
|
|
366
|
+
return;
|
|
367
|
+
throw new Error(`Cannot check Git ownership: ${detected.stderr.trim()}`);
|
|
368
|
+
}
|
|
369
|
+
const repo = detected.stdout.trim();
|
|
370
|
+
const tracked = git(["ls-files", "--cached", "-z", "--full-name", "--", target]);
|
|
371
|
+
if (tracked.error || tracked.status !== 0) throw new Error(`Cannot inspect Git index in ${repo}`);
|
|
372
|
+
if (tracked.stdout.length)
|
|
373
|
+
throw new Error(
|
|
374
|
+
`Tracked files are protected; use git rm for intentional source removal: ${target}`,
|
|
375
|
+
);
|
|
376
|
+
}
|
|
@@ -89,8 +89,7 @@ export function renderInstructionsBlock(
|
|
|
89
89
|
return `## harnery coordination
|
|
90
90
|
|
|
91
91
|
This project runs [harnery](https://harnery.com) for multi-agent coordination.
|
|
92
|
-
You share this checkout with other agents; the surfaces below keep you oriented
|
|
93
|
-
and out of each other's way, and let you dispatch a team of your own when a job
|
|
92
|
+
You share this checkout with other agents; the surfaces below keep you oriented and out of each other's way, and let you dispatch a team of your own when a job
|
|
94
93
|
is bigger than one session. Run \`${b} <command> --help\` for any command's full
|
|
95
94
|
surface. ${deeper}
|
|
96
95
|
|
|
@@ -103,8 +102,7 @@ widely-shared files.
|
|
|
103
102
|
**Task lifecycle.** Beside the activity peers already see, declare whether your
|
|
104
103
|
objective is still open: \`${b} agents lifecycle blocked --reason "<why>"\` when
|
|
105
104
|
it cannot proceed, \`${b} agents lifecycle done\` when it is complete, and
|
|
106
|
-
\`${b} agents lifecycle active\` to reopen. \`done\` requires a current task and
|
|
107
|
-
a passing Git finalization check (dirty or unpushed work refuses, and nothing is
|
|
105
|
+
\`${b} agents lifecycle active\` to reopen. \`done\` requires a current task and a passing Git finalization check (dirty or unpushed work refuses, and nothing is
|
|
108
106
|
written). Ordinary \`set-task\` calls never change lifecycle, and a transition
|
|
109
107
|
that re-mints the session title tells you the new name to copy. ${endPointer}
|
|
110
108
|
|
|
@@ -129,8 +127,7 @@ It reclaims an abandoned namesake (no live process) and refuses only when anothe
|
|
|
129
127
|
live process still holds the name; never hand-edit Harnery's history, heartbeat,
|
|
130
128
|
or derived identity cache.
|
|
131
129
|
|
|
132
|
-
**Declare intent on shell commands.** Every command you run is captured to the
|
|
133
|
-
coordination ledger (\`.harnery/ledgers/v3/\`). Lead a shell command with a
|
|
130
|
+
**Declare intent on shell commands.** Every command you run is captured to the coordination ledger (\`.harnery/ledgers/v3/\`). Lead a shell command with a
|
|
134
131
|
\`# intent: <why>\` comment (or set the tool's description) so the recorded event
|
|
135
132
|
carries a reason instead of \`(no intent)\`; the [tool-intent
|
|
136
133
|
guide](https://harnery.com/guides/tool-intent/) owns the details.
|
|
@@ -154,6 +151,10 @@ After review, use \`${b} artifacts discard <id> --reason "<why no longer needed>
|
|
|
154
151
|
Do not create a repo-root temp directory; \`${b} artifacts clean\` previews
|
|
155
152
|
expired cleanup and requires \`--yes\` to delete anything.
|
|
156
153
|
|
|
154
|
+
**Removing local outputs.** Use \`${b} rm --root <directory> <paths...>\` instead of shell \`rm\`, which skips resolved-path, Git ownership, and peer-claim checks. Preview
|
|
155
|
+
is the default; \`--yes\` deletes permanently and \`--recursive\` permits directories.
|
|
156
|
+
Use \`git rm\` for tracked source and the artifact commands for managed evidence.
|
|
157
|
+
|
|
157
158
|
**Local file links.** When the operator should open a local repo file, mint the
|
|
158
159
|
URL with \`${b} files url <repo-relative-path>\` instead of guessing it. HTML opens
|
|
159
160
|
as a real page with working scripts and relative assets; other files open in the
|
|
@@ -164,8 +165,7 @@ can't resolve from the repo, file it instead. \`${b} decision file "<question>"\
|
|
|
164
165
|
records it and lets you proceed on a stated default; \`${b} decision search "<terms>"\`
|
|
165
166
|
surfaces prior decisions, so check for precedent before re-deciding. ${decidePointer}
|
|
166
167
|
|
|
167
|
-
**Councils.** For a hard or contested decision, convene a council of agents.
|
|
168
|
-
\`${b} council create "<objective>"\` runs structured rounds toward a decision. ${councilPointer}`;
|
|
168
|
+
**Councils.** For a hard or contested decision, convene a council of agents. \`${b} council create "<objective>"\` runs structured rounds toward a decision. ${councilPointer}`;
|
|
169
169
|
}
|
|
170
170
|
|
|
171
171
|
// ── Skills ──────────────────────────────────────────────────────────────────
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
// Address allowlist for the tunnel gate: exact addresses and CIDR ranges, IPv4
|
|
2
|
+
// and IPv6. Pure functions with no I/O, shared by the gate worker (matching)
|
|
3
|
+
// and the `tunnel allow` commands (validation + canonical spelling).
|
|
4
|
+
//
|
|
5
|
+
// An IPv6 phone and laptop on one Wi-Fi network have different addresses but
|
|
6
|
+
// share a /64 prefix, so a range entry such as `2601:db8:1:2::/64` admits both.
|
|
7
|
+
// An entry without a prefix length is a single address (/32 or /128).
|
|
8
|
+
//
|
|
9
|
+
// IPv4-mapped IPv6 addresses (`::ffff:203.0.113.8`) are IPv4 addresses reached
|
|
10
|
+
// through a dual-stack socket, so they parse and match as IPv4.
|
|
11
|
+
|
|
12
|
+
import { isIPv4, isIPv6 } from "node:net";
|
|
13
|
+
|
|
14
|
+
export type IpFamily = 4 | 6;
|
|
15
|
+
|
|
16
|
+
export interface ParsedIp {
|
|
17
|
+
family: IpFamily;
|
|
18
|
+
value: bigint;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface AllowEntry extends ParsedIp {
|
|
22
|
+
/** Prefix length in bits (32 or 128 for a single address). */
|
|
23
|
+
prefix: number;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const FULL_BITS: Record<IpFamily, number> = { 4: 32, 6: 128 };
|
|
27
|
+
|
|
28
|
+
function parseIpv4(text: string): bigint | null {
|
|
29
|
+
if (!isIPv4(text)) return null;
|
|
30
|
+
let value = 0n;
|
|
31
|
+
for (const part of text.split(".")) value = (value << 8n) | BigInt(Number(part));
|
|
32
|
+
return value;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function parseIpv6(text: string): bigint | null {
|
|
36
|
+
if (!isIPv6(text)) return null;
|
|
37
|
+
let rest = text;
|
|
38
|
+
// A trailing dotted quad (`::ffff:1.2.3.4`, `64:ff9b::1.2.3.4`) is two groups.
|
|
39
|
+
const dotted = rest.match(/^(.*:)(\d+\.\d+\.\d+\.\d+)$/);
|
|
40
|
+
if (dotted) {
|
|
41
|
+
const v4 = parseIpv4(dotted[2] as string);
|
|
42
|
+
if (v4 === null) return null;
|
|
43
|
+
rest = `${dotted[1]}${(v4 >> 16n).toString(16)}:${(v4 & 0xffffn).toString(16)}`;
|
|
44
|
+
}
|
|
45
|
+
const halves = rest.split("::");
|
|
46
|
+
if (halves.length > 2) return null;
|
|
47
|
+
const head = halves[0] ? (halves[0] as string).split(":") : [];
|
|
48
|
+
const tail = halves.length === 2 && halves[1] ? (halves[1] as string).split(":") : [];
|
|
49
|
+
const missing = 8 - head.length - tail.length;
|
|
50
|
+
if (halves.length === 1 ? missing !== 0 : missing < 1) return null;
|
|
51
|
+
const groups = [
|
|
52
|
+
...head,
|
|
53
|
+
...Array.from({ length: halves.length === 2 ? missing : 0 }, () => "0"),
|
|
54
|
+
...tail,
|
|
55
|
+
];
|
|
56
|
+
if (groups.length !== 8) return null;
|
|
57
|
+
let value = 0n;
|
|
58
|
+
for (const group of groups) {
|
|
59
|
+
if (!/^[0-9a-f]{1,4}$/i.test(group)) return null;
|
|
60
|
+
value = (value << 16n) | BigInt(Number.parseInt(group, 16));
|
|
61
|
+
}
|
|
62
|
+
return value;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Parse one address. Returns null for anything that is not an IP literal. A
|
|
67
|
+
* zone id (`fe80::1%en0`) is dropped, and an IPv4-mapped IPv6 address is
|
|
68
|
+
* reported as the IPv4 address it carries.
|
|
69
|
+
*/
|
|
70
|
+
export function parseIp(raw: string): ParsedIp | null {
|
|
71
|
+
let text = raw.trim();
|
|
72
|
+
if (text.startsWith("[") && text.endsWith("]")) text = text.slice(1, -1);
|
|
73
|
+
const zone = text.indexOf("%");
|
|
74
|
+
if (zone !== -1) text = text.slice(0, zone);
|
|
75
|
+
if (!text) return null;
|
|
76
|
+
const v4 = parseIpv4(text);
|
|
77
|
+
if (v4 !== null) return { family: 4, value: v4 };
|
|
78
|
+
const v6 = parseIpv6(text);
|
|
79
|
+
if (v6 === null) return null;
|
|
80
|
+
if (v6 >> 32n === 0xffffn) return { family: 4, value: v6 & 0xffffffffn };
|
|
81
|
+
return { family: 6, value: v6 };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function maskFor(family: IpFamily, prefix: number): bigint {
|
|
85
|
+
const bits = BigInt(FULL_BITS[family]);
|
|
86
|
+
const host = bits - BigInt(prefix);
|
|
87
|
+
return ((1n << bits) - 1n) ^ ((1n << host) - 1n);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Parse an allowlist entry: `203.0.113.8`, `203.0.113.0/24`, `2601:db8::1`, or
|
|
92
|
+
* `2601:db8:1:2::/64`. Host bits below the prefix are cleared, so
|
|
93
|
+
* `203.0.113.77/24` means the network `203.0.113.0/24`. Returns null when the
|
|
94
|
+
* entry is not a valid address or its prefix length is out of range.
|
|
95
|
+
*/
|
|
96
|
+
export function parseAllowEntry(raw: string): AllowEntry | null {
|
|
97
|
+
const text = raw.trim();
|
|
98
|
+
const slash = text.indexOf("/");
|
|
99
|
+
const address = parseIp(slash === -1 ? text : text.slice(0, slash));
|
|
100
|
+
if (!address) return null;
|
|
101
|
+
let prefix = FULL_BITS[address.family];
|
|
102
|
+
if (slash !== -1) {
|
|
103
|
+
const lengthText = text.slice(slash + 1);
|
|
104
|
+
if (!/^\d{1,3}$/.test(lengthText)) return null;
|
|
105
|
+
prefix = Number(lengthText);
|
|
106
|
+
// A prefix on an IPv4-mapped IPv6 entry counts from the IPv6 start, so
|
|
107
|
+
// `::ffff:1.2.3.0/120` is the IPv4 /24. Anything shorter is not an IPv4 range.
|
|
108
|
+
if (address.family === 4 && /:/.test(text.slice(0, slash))) {
|
|
109
|
+
if (prefix < 96 || prefix > 128) return null;
|
|
110
|
+
prefix -= 96;
|
|
111
|
+
}
|
|
112
|
+
if (prefix > FULL_BITS[address.family]) return null;
|
|
113
|
+
}
|
|
114
|
+
return { ...address, prefix, value: address.value & maskFor(address.family, prefix) };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function compress(groups: number[]): string {
|
|
118
|
+
// RFC 5952: collapse the longest run of two or more zero groups (first wins).
|
|
119
|
+
let bestStart = -1;
|
|
120
|
+
let bestLen = 0;
|
|
121
|
+
for (let i = 0; i < 8; ) {
|
|
122
|
+
if (groups[i] !== 0) {
|
|
123
|
+
i++;
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
let j = i;
|
|
127
|
+
while (j < 8 && groups[j] === 0) j++;
|
|
128
|
+
if (j - i > bestLen) {
|
|
129
|
+
bestStart = i;
|
|
130
|
+
bestLen = j - i;
|
|
131
|
+
}
|
|
132
|
+
i = j;
|
|
133
|
+
}
|
|
134
|
+
if (bestLen < 2) return groups.map((g) => g.toString(16)).join(":");
|
|
135
|
+
const left = groups.slice(0, bestStart).map((g) => g.toString(16));
|
|
136
|
+
const right = groups.slice(bestStart + bestLen).map((g) => g.toString(16));
|
|
137
|
+
return `${left.join(":")}::${right.join(":")}`;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Canonical text of an address (dotted quad, or compressed lowercase IPv6). */
|
|
141
|
+
export function formatIp(ip: ParsedIp): string {
|
|
142
|
+
if (ip.family === 4) {
|
|
143
|
+
return [24n, 16n, 8n, 0n].map((shift) => Number((ip.value >> shift) & 0xffn)).join(".");
|
|
144
|
+
}
|
|
145
|
+
const groups: number[] = [];
|
|
146
|
+
for (let i = 7; i >= 0; i--) groups.push(Number((ip.value >> BigInt(i * 16)) & 0xffffn));
|
|
147
|
+
return compress(groups);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Canonical text of an entry; a single address carries no `/len` suffix. */
|
|
151
|
+
export function formatAllowEntry(entry: AllowEntry): string {
|
|
152
|
+
const address = formatIp(entry);
|
|
153
|
+
return entry.prefix === FULL_BITS[entry.family] ? address : `${address}/${entry.prefix}`;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Canonical spelling of an allowlist entry, or null when invalid. Two spellings
|
|
158
|
+
* of one address or range (`2601:DB8:0:0::1`, `2601:db8::1`) normalize equal.
|
|
159
|
+
*/
|
|
160
|
+
export function normalizeAllowEntry(raw: string): string | null {
|
|
161
|
+
const entry = parseAllowEntry(raw);
|
|
162
|
+
return entry ? formatAllowEntry(entry) : null;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export interface Allowlist {
|
|
166
|
+
entries: AllowEntry[];
|
|
167
|
+
/** Entries that could not be parsed; they never match anything. */
|
|
168
|
+
invalid: string[];
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export function compileAllowlist(rawEntries: readonly string[]): Allowlist {
|
|
172
|
+
const entries: AllowEntry[] = [];
|
|
173
|
+
const invalid: string[] = [];
|
|
174
|
+
for (const raw of rawEntries) {
|
|
175
|
+
const text = raw.trim();
|
|
176
|
+
if (!text) continue;
|
|
177
|
+
const entry = parseAllowEntry(text);
|
|
178
|
+
if (entry) entries.push(entry);
|
|
179
|
+
else invalid.push(text);
|
|
180
|
+
}
|
|
181
|
+
return { entries, invalid };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** True when `ip` lies inside any entry. A missing or malformed address never matches. */
|
|
185
|
+
export function allowlistMatches(list: Allowlist, ip: string): boolean {
|
|
186
|
+
const address = parseIp(ip);
|
|
187
|
+
if (!address) return false;
|
|
188
|
+
for (const entry of list.entries) {
|
|
189
|
+
if (entry.family !== address.family) continue;
|
|
190
|
+
const mask = maskFor(entry.family, entry.prefix);
|
|
191
|
+
if ((address.value & mask) === entry.value) return true;
|
|
192
|
+
}
|
|
193
|
+
return false;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** The IPv6 /64 network prefix of an address, as a canonical `…/64` entry. */
|
|
197
|
+
export function ipv6Slash64(address: string): string | null {
|
|
198
|
+
const ip = parseIp(address);
|
|
199
|
+
if (!ip || ip.family !== 6) return null;
|
|
200
|
+
return formatAllowEntry({ ...ip, prefix: 64, value: ip.value & maskFor(6, 64) });
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** A single IPv4 address as a `/32` entry. */
|
|
204
|
+
export function ipv4Slash32(address: string): string | null {
|
|
205
|
+
const ip = parseIp(address);
|
|
206
|
+
if (!ip || ip.family !== 4) return null;
|
|
207
|
+
return `${formatIp(ip)}/32`;
|
|
208
|
+
}
|