@koneeric/onetool 0.0.0-stage → 0.1.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.
@@ -0,0 +1,136 @@
1
+ // The adapter of Claude Code: what its own permission rules (`deny`, `ask`, `allow` of its settings files)
2
+ // say of one call. A close copy of the host's matching, wider where a difference can only tighten.
3
+ import { join, resolve } from "node:path";
4
+
5
+ export const names = ["claude-code"];
6
+
7
+ export function files(home, roots) {
8
+ const out = [{ file: join(home, ".claude", "settings.json"), anchors: [...roots] }];
9
+ for (const root of roots) {
10
+ out.push({ file: join(root, ".claude", "settings.json"), anchors: [root] });
11
+ out.push({ file: join(root, ".claude", "settings.local.json"), anchors: [root] });
12
+ }
13
+ return out;
14
+ }
15
+
16
+ function list(value) {
17
+ if (value === undefined) return [];
18
+ if (!Array.isArray(value)) throw new TypeError("a permission list is not a list");
19
+ return value.filter((item) => typeof item === "string");
20
+ }
21
+
22
+ export function parse(text) {
23
+ const data = JSON.parse(text);
24
+ if (typeof data !== "object" || data === null || Array.isArray(data)) throw new TypeError("not a settings file");
25
+ const permissions = data.permissions;
26
+ if (permissions === undefined) return { deny: [], ask: [], allow: [] };
27
+ if (typeof permissions !== "object" || permissions === null || Array.isArray(permissions)) {
28
+ throw new TypeError("permissions is not an object");
29
+ }
30
+ return { deny: list(permissions.deny), ask: list(permissions.ask), allow: list(permissions.allow) };
31
+ }
32
+
33
+ // The actions each tool name of a rule speaks of.
34
+ const ACTIONS = { Bash: ["run"], Read: ["read"], Edit: ["edit", "write"], Write: ["write"] };
35
+
36
+ // -> { name, spec } with spec null when the rule has no parentheses, or null when it is not a rule that is read.
37
+ function readRule(rule) {
38
+ const text = rule.trim();
39
+ const open = text.indexOf("(");
40
+ let name = text;
41
+ let spec = null;
42
+ if (open !== -1) {
43
+ if (!text.endsWith(")")) return null;
44
+ name = text.slice(0, open);
45
+ spec = text.slice(open + 1, -1);
46
+ }
47
+ return Object.hasOwn(ACTIONS, name) ? { name, spec } : null;
48
+ }
49
+
50
+ // `*` stands for any run of characters; with `single`, `?` stands for one character. Everything else stands for itself.
51
+ function wild(pattern, text, single) {
52
+ const p = Array.from(pattern);
53
+ const s = Array.from(text);
54
+ let pi = 0;
55
+ let si = 0;
56
+ let star = -1;
57
+ let mark = 0;
58
+ while (si < s.length) {
59
+ if (p[pi] === "*") {
60
+ star = pi++;
61
+ mark = si;
62
+ } else if (pi < p.length && (p[pi] === s[si] || (single && p[pi] === "?"))) {
63
+ pi++;
64
+ si++;
65
+ } else if (star >= 0) {
66
+ pi = star + 1;
67
+ si = ++mark;
68
+ } else {
69
+ return false;
70
+ }
71
+ }
72
+ while (p[pi] === "*") pi++;
73
+ return pi === p.length;
74
+ }
75
+
76
+ function candidates(command) {
77
+ const whole = command.trim();
78
+ const pieces = whole.split(/[;&|\r\n]/).map((piece) => piece.trim()).filter((piece) => piece !== "");
79
+ return [whole, ...pieces];
80
+ }
81
+
82
+ function matchesCommand(spec, command) {
83
+ return candidates(command).some((candidate) => {
84
+ if (spec.endsWith(":*")) return candidate.startsWith(spec.slice(0, -2));
85
+ if (wild(spec, candidate, false)) return true;
86
+ return spec.endsWith(" *") && wild(spec.slice(0, -2), candidate, false);
87
+ });
88
+ }
89
+
90
+ const noSlashEnd = (text) => text.replace(/\/+$/, "");
91
+
92
+ function patternsOf(spec, home, anchors) {
93
+ let out;
94
+ if (spec.startsWith("//")) out = [spec.slice(1)];
95
+ else if (spec.startsWith("~/")) out = [noSlashEnd(home) + spec.slice(1)];
96
+ else if (spec.startsWith("/")) out = anchors.map((anchor) => noSlashEnd(anchor) + spec);
97
+ else if (spec.startsWith("./")) out = anchors.map((anchor) => noSlashEnd(anchor) + spec.slice(1));
98
+ else if (spec.slice(0, -1).includes("/")) out = anchors.map((anchor) => `${noSlashEnd(anchor)}/${spec}`);
99
+ else out = anchors.map((anchor) => `${noSlashEnd(anchor)}/**/${spec}`);
100
+ return out.map((pattern) => (pattern.endsWith("/") ? pattern.slice(0, -1) : pattern));
101
+ }
102
+
103
+ // The pattern is used up: what is left of the path is a folder's content, which the rule on the folder covers.
104
+ function matchPieces(pattern, pi, path, si) {
105
+ if (pi === pattern.length) return true;
106
+ if (pattern[pi] === "**") {
107
+ for (let k = si; k <= path.length; k++) if (matchPieces(pattern, pi + 1, path, k)) return true;
108
+ return false;
109
+ }
110
+ return si < path.length && wild(pattern[pi], path[si], true) && matchPieces(pattern, pi + 1, path, si + 1);
111
+ }
112
+
113
+ function matchesPath(spec, paths, home, anchors) {
114
+ const patterns = patternsOf(spec, home, anchors).map((pattern) => pattern.split("/"));
115
+ return patterns.some((pattern) => paths.some((path) => matchPieces(pattern, 0, path.split("/"), 0)));
116
+ }
117
+
118
+ export function matches(rule, call, { home, anchors }) {
119
+ const read = readRule(rule);
120
+ if (read === null || !ACTIONS[read.name].includes(call.action)) return false;
121
+ if (read.spec === null || read.spec === "") return true;
122
+ if (call.action === "run") return matchesCommand(read.spec, call.command);
123
+ return matchesPath(read.spec, call.paths, home, anchors);
124
+ }
125
+
126
+ const isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
127
+
128
+ export function ownCall(tool, args, cwd) {
129
+ if (!isPlainObject(args)) return null;
130
+ if (tool === "Bash") return typeof args.command === "string" ? { action: "run", command: args.command } : null;
131
+ if (tool === "Read" || tool === "Edit" || tool === "Write") {
132
+ if (typeof args.file_path !== "string" || args.file_path === "") return null;
133
+ return { action: tool.toLowerCase(), paths: [resolve(cwd, args.file_path)] };
134
+ }
135
+ return null;
136
+ }
@@ -0,0 +1,107 @@
1
+ import os from "node:os";
2
+ import { readdir, readFile, realpath, stat } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { fileURLToPath, pathToFileURL } from "node:url";
5
+
6
+ const DEFAULT_ADAPTERS = fileURLToPath(new URL("./adapters", import.meta.url));
7
+ const EXPORTS = ["names", "files", "parse", "matches", "ownCall"];
8
+
9
+ // The adapter modules of the folder, in the order of the file names; one that cannot be loaded is left out.
10
+ async function* adapters(folder) {
11
+ let entries;
12
+ try {
13
+ entries = (await readdir(folder)).filter((name) => name.endsWith(".js")).sort();
14
+ } catch {
15
+ return;
16
+ }
17
+ for (const name of entries) {
18
+ const path = join(folder, name);
19
+ try {
20
+ const info = await stat(path);
21
+ if (!info.isFile()) continue;
22
+ // the stamp makes a file that changed be loaded again
23
+ const url = `${pathToFileURL(path).href}?m=${info.mtimeMs}-${info.size}`;
24
+ const mod = await import(url);
25
+ if (EXPORTS.every((key) => key in mod) && Array.isArray(mod.names)) yield mod;
26
+ } catch {
27
+ // not loadable: left out
28
+ }
29
+ }
30
+ }
31
+
32
+ async function realOf(path) {
33
+ try {
34
+ return await realpath(path);
35
+ } catch {
36
+ return path;
37
+ }
38
+ }
39
+
40
+ export async function hostRules(hostName, { home = os.homedir(), adaptersFolder = DEFAULT_ADAPTERS } = {}) {
41
+ if (typeof home !== "string" || home === "") throw new TypeError("home must be a non-empty string");
42
+ if (typeof hostName !== "string") return null;
43
+ const wanted = hostName.trim().toLowerCase();
44
+ if (wanted === "") return null;
45
+ let adapter = null;
46
+ for await (const mod of adapters(adaptersFolder)) {
47
+ if (mod.names.includes(wanted)) {
48
+ adapter = mod;
49
+ break;
50
+ }
51
+ }
52
+ if (adapter === null) return null;
53
+
54
+ // one entry per file that gave rules: { file, anchors, homes, deny, ask }
55
+ let rules = [];
56
+
57
+ async function refresh(roots) {
58
+ const next = [];
59
+ const faults = [];
60
+ const realHome = await realOf(home);
61
+ const homes = realHome === home ? [home] : [home, realHome];
62
+ for (const { file, anchors } of adapter.files(home, roots)) {
63
+ let text;
64
+ try {
65
+ text = await readFile(file, "utf8");
66
+ } catch (error) {
67
+ if (error?.code !== "ENOENT" && error?.code !== "ENOTDIR") faults.push(file);
68
+ continue;
69
+ }
70
+ let parsed;
71
+ try {
72
+ parsed = adapter.parse(text);
73
+ if (!Array.isArray(parsed.deny) || !Array.isArray(parsed.ask)) throw new TypeError("bad lists");
74
+ } catch {
75
+ faults.push(file);
76
+ continue;
77
+ }
78
+ const reals = await Promise.all(anchors.map(realOf));
79
+ const all = [...anchors, ...reals.filter((real, i) => real !== anchors[i])];
80
+ next.push({ file, anchors: all, deny: parsed.deny, ask: parsed.ask });
81
+ }
82
+ rules = next.map((entry) => ({ ...entry, homes }));
83
+ return faults;
84
+ }
85
+
86
+ function hit(entry, rule, call) {
87
+ return entry.homes.some((h) => adapter.matches(rule, call, { home: h, anchors: entry.anchors }));
88
+ }
89
+
90
+ function decide(call) {
91
+ for (const effect of ["deny", "ask"]) {
92
+ for (const entry of rules) {
93
+ for (const rule of entry[effect]) {
94
+ if (hit(entry, rule, call)) return { effect, file: entry.file, rule };
95
+ }
96
+ }
97
+ }
98
+ return { effect: "none" };
99
+ }
100
+
101
+ return {
102
+ host: adapter.names[0],
103
+ refresh,
104
+ decide,
105
+ ownCall: (tool, args, cwd) => adapter.ownCall(tool, args, cwd),
106
+ };
107
+ }