@hop-top/kit 0.4.0-alpha.1

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.
Files changed (174) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/LICENSE +25 -0
  3. package/README.md +189 -0
  4. package/dist/aim.d.ts +116 -0
  5. package/dist/aim.js +417 -0
  6. package/dist/alias.d.ts +73 -0
  7. package/dist/alias.js +207 -0
  8. package/dist/api.d.ts +62 -0
  9. package/dist/api.js +165 -0
  10. package/dist/auth.d.ts +26 -0
  11. package/dist/auth.js +41 -0
  12. package/dist/cli.d.ts +309 -0
  13. package/dist/cli.js +885 -0
  14. package/dist/config.d.ts +97 -0
  15. package/dist/config.js +79 -0
  16. package/dist/errcorrect.d.ts +37 -0
  17. package/dist/errcorrect.js +69 -0
  18. package/dist/llm.d.ts +188 -0
  19. package/dist/llm.js +356 -0
  20. package/dist/output.d.ts +213 -0
  21. package/dist/output.js +447 -0
  22. package/dist/progress.d.ts +30 -0
  23. package/dist/progress.js +56 -0
  24. package/dist/provenance.d.ts +24 -0
  25. package/dist/provenance.js +32 -0
  26. package/dist/routellm.d.ts +64 -0
  27. package/dist/routellm.js +258 -0
  28. package/dist/rpc.d.ts +25 -0
  29. package/dist/rpc.js +101 -0
  30. package/dist/safety.d.ts +24 -0
  31. package/dist/safety.js +44 -0
  32. package/dist/scope.d.ts +121 -0
  33. package/dist/scope.js +380 -0
  34. package/dist/sqlstore.d.ts +84 -0
  35. package/dist/sqlstore.js +85 -0
  36. package/dist/stream.d.ts +35 -0
  37. package/dist/stream.js +52 -0
  38. package/dist/tui/index.d.ts +300 -0
  39. package/dist/tui/index.js +332 -0
  40. package/dist/upgrade.d.ts +95 -0
  41. package/dist/upgrade.js +115 -0
  42. package/dist/xdg.d.ts +169 -0
  43. package/dist/xdg.js +129 -0
  44. package/eslint.config.mjs +17 -0
  45. package/package.json +133 -0
  46. package/src/README.md +3 -0
  47. package/src/aim.test.ts +331 -0
  48. package/src/aim.ts +388 -0
  49. package/src/alias.test.ts +423 -0
  50. package/src/alias.ts +256 -0
  51. package/src/api.test.ts +190 -0
  52. package/src/api.ts +214 -0
  53. package/src/auth.test.ts +24 -0
  54. package/src/auth.ts +37 -0
  55. package/src/bus.test.ts +178 -0
  56. package/src/bus.ts +114 -0
  57. package/src/cli.test.ts +690 -0
  58. package/src/cli.ts +741 -0
  59. package/src/completion-values.test.ts +202 -0
  60. package/src/completion-values.ts +173 -0
  61. package/src/completion.test.ts +212 -0
  62. package/src/completion.ts +158 -0
  63. package/src/compliance.test.ts +134 -0
  64. package/src/compliance.ts +669 -0
  65. package/src/config.test.ts +110 -0
  66. package/src/config.ts +164 -0
  67. package/src/errcorrect.test.ts +134 -0
  68. package/src/errcorrect.ts +84 -0
  69. package/src/flagregister.test.ts +103 -0
  70. package/src/flagregister.ts +78 -0
  71. package/src/gen/crud_connect.ts +76 -0
  72. package/src/gen/crud_pb.ts +269 -0
  73. package/src/hint.test.ts +315 -0
  74. package/src/hint.ts +178 -0
  75. package/src/llm.test.ts +612 -0
  76. package/src/llm.ts +577 -0
  77. package/src/log.test.ts +145 -0
  78. package/src/log.ts +155 -0
  79. package/src/output/builtins.ts +34 -0
  80. package/src/output/dispatch.ts +195 -0
  81. package/src/output/flags.ts +151 -0
  82. package/src/output/format_help.ts +80 -0
  83. package/src/output/formatter.ts +167 -0
  84. package/src/output/formatters/csv.ts +72 -0
  85. package/src/output/formatters/json.ts +44 -0
  86. package/src/output/formatters/table.ts +44 -0
  87. package/src/output/formatters/text.ts +109 -0
  88. package/src/output/formatters/yaml.ts +47 -0
  89. package/src/output/projection.ts +126 -0
  90. package/src/output/registry.ts +88 -0
  91. package/src/output/template.ts +63 -0
  92. package/src/output.test.ts +117 -0
  93. package/src/output.ts +90 -0
  94. package/src/progress.test.ts +93 -0
  95. package/src/progress.ts +58 -0
  96. package/src/provenance.test.ts +59 -0
  97. package/src/provenance.ts +26 -0
  98. package/src/routellm.test.ts +179 -0
  99. package/src/routellm.ts +365 -0
  100. package/src/router/bert.test.ts +180 -0
  101. package/src/router/bert.ts +145 -0
  102. package/src/router/controller.test.ts +183 -0
  103. package/src/router/controller.ts +165 -0
  104. package/src/router/integration.test.ts +309 -0
  105. package/src/router/intent.test.ts +187 -0
  106. package/src/router/intent.ts +208 -0
  107. package/src/router/mf.test.ts +66 -0
  108. package/src/router/mf.ts +52 -0
  109. package/src/router/random.test.ts +23 -0
  110. package/src/router/random.ts +13 -0
  111. package/src/router/router.test.ts +31 -0
  112. package/src/router/router.ts +62 -0
  113. package/src/router/server.test.ts +193 -0
  114. package/src/router/server.ts +134 -0
  115. package/src/router/sw.test.ts +199 -0
  116. package/src/router/sw.ts +232 -0
  117. package/src/rpc.test.ts +47 -0
  118. package/src/rpc.ts +91 -0
  119. package/src/safety.test.ts +53 -0
  120. package/src/safety.ts +42 -0
  121. package/src/scope-defaults.json +72 -0
  122. package/src/scope.test.ts +177 -0
  123. package/src/scope.ts +382 -0
  124. package/src/setflag.test.ts +110 -0
  125. package/src/setflag.ts +102 -0
  126. package/src/sqlstore.test.ts +110 -0
  127. package/src/sqlstore.ts +144 -0
  128. package/src/stream.test.ts +69 -0
  129. package/src/stream.ts +47 -0
  130. package/src/textflag.test.ts +105 -0
  131. package/src/textflag.ts +68 -0
  132. package/src/toolspec.test.ts +187 -0
  133. package/src/toolspec.ts +279 -0
  134. package/src/triton/client.test.ts +205 -0
  135. package/src/triton/client.ts +261 -0
  136. package/src/tui/anim.test.ts +146 -0
  137. package/src/tui/anim.ts +134 -0
  138. package/src/tui/badge.test.ts +41 -0
  139. package/src/tui/badge.ts +55 -0
  140. package/src/tui/confirm.test.ts +68 -0
  141. package/src/tui/confirm.ts +49 -0
  142. package/src/tui/index.ts +29 -0
  143. package/src/tui/list.test.ts +84 -0
  144. package/src/tui/list.ts +72 -0
  145. package/src/tui/parity.ts +41 -0
  146. package/src/tui/pills.test.ts +40 -0
  147. package/src/tui/pills.ts +43 -0
  148. package/src/tui/progress.test.ts +164 -0
  149. package/src/tui/progress.ts +120 -0
  150. package/src/tui/spinner.test.ts +111 -0
  151. package/src/tui/spinner.ts +96 -0
  152. package/src/tui/status.test.ts +68 -0
  153. package/src/tui/status.ts +66 -0
  154. package/src/upgrade.test.ts +298 -0
  155. package/src/upgrade.ts +205 -0
  156. package/src/uri.ts +199 -0
  157. package/src/wizard.test.ts +441 -0
  158. package/src/wizard.ts +662 -0
  159. package/src/xdg.test.ts +202 -0
  160. package/src/xdg.ts +280 -0
  161. package/test/output/cols.test.ts +148 -0
  162. package/test/output/csv.test.ts +129 -0
  163. package/test/output/dispatch.test.ts +194 -0
  164. package/test/output/format_help.test.ts +131 -0
  165. package/test/output/formatter.test.ts +137 -0
  166. package/test/output/output_flag.test.ts +124 -0
  167. package/test/output/registry.test.ts +127 -0
  168. package/test/output/smoke-capture.ts +83 -0
  169. package/test/output/smoke.test.ts +142 -0
  170. package/test/output/template.test.ts +95 -0
  171. package/test/output/text.test.ts +75 -0
  172. package/test/testdata/api-fixture.json +115 -0
  173. package/test/testdata/query-vectors.json +187 -0
  174. package/tsconfig.json +12 -0
@@ -0,0 +1,177 @@
1
+ /**
2
+ * Tests for scope.ts — TS port parity with hop.top/kit/go/core/scope.
3
+ *
4
+ * Parity strategy:
5
+ *
6
+ * - Load the canonical contracts/parity/scope-defaults.json directly and
7
+ * compare it byte-for-byte (post JSON parse) with the local copy at
8
+ * sdk/ts/src/scope-defaults.json. If they drift, the test fails — keeping
9
+ * ports honest about syncing the contract.
10
+ * - SecretPaths() is verified to be (common ∪ platform-specific) on the
11
+ * current host, with `~` left unexpanded (the Go port also leaves it for
12
+ * late expansion at match time).
13
+ */
14
+
15
+ import * as fs from 'fs';
16
+ import * as path from 'path';
17
+ import { describe, expect, it, afterEach } from 'vitest';
18
+
19
+ import {
20
+ Decision,
21
+ Default,
22
+ ErrDenied,
23
+ Mode,
24
+ New,
25
+ Op,
26
+ Policy,
27
+ SecretPaths,
28
+ setDefault,
29
+ } from './scope';
30
+
31
+ // ─── Contract sync ───────────────────────────────────────────────────────────
32
+
33
+ describe('scope contract parity', () => {
34
+ it('local scope-defaults.json matches contracts/parity/scope-defaults.json', () => {
35
+ const local = JSON.parse(
36
+ fs.readFileSync(path.join(__dirname, 'scope-defaults.json'), 'utf8'),
37
+ );
38
+ const canonical = JSON.parse(
39
+ fs.readFileSync(
40
+ path.join(__dirname, '..', '..', '..', 'contracts', 'parity', 'scope-defaults.json'),
41
+ 'utf8',
42
+ ),
43
+ );
44
+ expect(local).toEqual(canonical);
45
+ });
46
+ });
47
+
48
+ // ─── SecretPaths ────────────────────────────────────────────────────────────
49
+
50
+ describe('SecretPaths', () => {
51
+ it('returns a non-empty pattern set', () => {
52
+ const sp = SecretPaths();
53
+ expect(sp.length).toBeGreaterThan(0);
54
+ });
55
+
56
+ it('includes common patterns (~/.ssh/**)', () => {
57
+ expect(SecretPaths()).toContain('~/.ssh/**');
58
+ });
59
+
60
+ it('includes platform-specific patterns', () => {
61
+ const sp = SecretPaths();
62
+ if (process.platform === 'darwin') {
63
+ expect(sp).toContain('~/Library/Keychains/**');
64
+ } else if (process.platform === 'linux') {
65
+ expect(sp).toContain('~/.mozilla/firefox/**/cookies.sqlite');
66
+ }
67
+ });
68
+ });
69
+
70
+ // ─── Policy: Allow / Deny / Check ───────────────────────────────────────────
71
+
72
+ describe('Policy.check', () => {
73
+ it('returns Unknown for an empty policy', () => {
74
+ const p = New();
75
+ expect(p.check('/tmp/anything', Op.Read)).toBe(Decision.Unknown);
76
+ });
77
+
78
+ it('Allow + matching path → Allowed', () => {
79
+ const p = New().allow('/tmp/**');
80
+ expect(p.check('/tmp/foo.txt', Op.Read)).toBe(Decision.Allowed);
81
+ });
82
+
83
+ it('Deny + matching path → Denied (deny wins)', () => {
84
+ const p = New().allow('/tmp/**').deny('/tmp/sensitive/**');
85
+ expect(p.check('/tmp/sensitive/x', Op.Read)).toBe(Decision.Denied);
86
+ });
87
+
88
+ it('Op bitset: Read-only rule does not match Write', () => {
89
+ const p = New().allowOp(Op.Read, '/tmp/**');
90
+ expect(p.check('/tmp/x', Op.Read)).toBe(Decision.Allowed);
91
+ expect(p.check('/tmp/x', Op.Write)).toBe(Decision.Unknown);
92
+ });
93
+ });
94
+
95
+ // ─── Policy.enforce ─────────────────────────────────────────────────────────
96
+
97
+ describe('Policy.enforce', () => {
98
+ it('Strict + Unknown → throws ErrDenied', () => {
99
+ const p = New();
100
+ expect(() => p.enforce('/tmp/x', Op.Read)).toThrow(ErrDenied);
101
+ });
102
+
103
+ it('Strict + Allowed → no throw', () => {
104
+ const p = New().allow('/tmp/**');
105
+ expect(() => p.enforce('/tmp/x', Op.Read)).not.toThrow();
106
+ });
107
+
108
+ it('Warn + Denied → logs, no throw', () => {
109
+ const p = New().setMode(Mode.Warn).deny('/tmp/x');
110
+ expect(() => p.enforce('/tmp/x', Op.Read)).not.toThrow();
111
+ });
112
+
113
+ it('Prompt + Denied + cb=true → no throw', () => {
114
+ const p = New()
115
+ .setMode(Mode.Prompt)
116
+ .deny('/tmp/x')
117
+ .setPromptFunc(() => true);
118
+ expect(() => p.enforce('/tmp/x', Op.Read)).not.toThrow();
119
+ });
120
+
121
+ it('Prompt + Denied + cb=false → throws', () => {
122
+ const p = New()
123
+ .setMode(Mode.Prompt)
124
+ .deny('/tmp/x')
125
+ .setPromptFunc(() => false);
126
+ expect(() => p.enforce('/tmp/x', Op.Read)).toThrow(ErrDenied);
127
+ });
128
+ });
129
+
130
+ // ─── Snapshot / SetDefault ───────────────────────────────────────────────────
131
+
132
+ describe('Policy.snapshot + setDefault', () => {
133
+ let restore: (() => void) | null = null;
134
+ afterEach(() => {
135
+ if (restore) {
136
+ restore();
137
+ restore = null;
138
+ }
139
+ });
140
+
141
+ it('snapshot is independent of original', () => {
142
+ const orig = New().allow('/tmp/**');
143
+ const cp = orig.snapshot();
144
+ cp.deny('/tmp/x');
145
+ expect(orig.check('/tmp/x', Op.Read)).toBe(Decision.Allowed);
146
+ expect(cp.check('/tmp/x', Op.Read)).toBe(Decision.Denied);
147
+ });
148
+
149
+ it('setDefault swaps singleton and restore puts it back', () => {
150
+ const before = Default();
151
+ const swap = New().allow('/tmp/swap/**');
152
+ restore = setDefault(swap);
153
+ expect(Default()).toBe(swap);
154
+ restore();
155
+ restore = null;
156
+ expect(Default()).toBe(before);
157
+ });
158
+ });
159
+
160
+ // ─── Default singleton seeded with SecretPaths ──────────────────────────────
161
+
162
+ describe('Default()', () => {
163
+ let restore: (() => void) | null = null;
164
+ afterEach(() => {
165
+ if (restore) {
166
+ restore();
167
+ restore = null;
168
+ }
169
+ });
170
+
171
+ it('denies a known secret path on the current platform', () => {
172
+ // ~ expands to homedir at match time; pick a path that matches **/.env
173
+ // (in the common deny set on every platform).
174
+ const policy: Policy = Default();
175
+ expect(policy.check('/tmp/whatever/.env', Op.Read)).toBe(Decision.Denied);
176
+ });
177
+ });
package/src/scope.ts ADDED
@@ -0,0 +1,382 @@
1
+ /**
2
+ * @packageDocumentation
3
+ *
4
+ * Filesystem path policy guardrails — TypeScript port of `hop.top/kit/go/core/scope`.
5
+ *
6
+ * Mirrors the Go API surface (`New`, `Default`, `Allow`, `Deny`, `Check`,
7
+ * `Enforce`, `SetMode`, `SetDefault`, `Snapshot`, `SecretPaths`). The default
8
+ * deny list is loaded from `contracts/parity/scope-defaults.json` (the
9
+ * cross-language source of truth).
10
+ *
11
+ * Glob matching uses [`picomatch`](https://github.com/micromatch/picomatch)
12
+ * which supports the subset of bash-style globs (including `**`) that the Go
13
+ * port relies on via `bmatcuk/doublestar/v4`.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * import { Default, Op, Strict } from '@hop-top/kit/scope';
18
+ *
19
+ * const dec = Default().check('/Users/me/.ssh/id_rsa', Op.Read);
20
+ * // -> Decision.Denied
21
+ * ```
22
+ */
23
+
24
+ import * as fs from 'fs';
25
+ import * as os from 'os';
26
+ import * as path from 'path';
27
+ import picomatch from 'picomatch';
28
+
29
+ import scopeDefaultsRaw from './scope-defaults.json';
30
+
31
+ // ─── Types ───────────────────────────────────────────────────────────────────
32
+
33
+ /** Mode controls how `Enforce` reacts to a `Denied` decision. */
34
+ export enum Mode {
35
+ /** Strict denies → throws `ErrDenied`. The default. */
36
+ Strict = 'strict',
37
+ /** Warn denies → logs to stderr and returns. */
38
+ Warn = 'warn',
39
+ /** Prompt denies → invokes the prompt callback. */
40
+ Prompt = 'prompt',
41
+ }
42
+
43
+ /** Op is a bitset of filesystem operations. */
44
+ export enum Op {
45
+ Read = 1 << 0,
46
+ Write = 1 << 1,
47
+ Exec = 1 << 2,
48
+ }
49
+
50
+ /** Decision is the outcome of `Check`. */
51
+ export enum Decision {
52
+ Unknown = 'unknown',
53
+ Allowed = 'allowed',
54
+ Denied = 'denied',
55
+ }
56
+
57
+ /** A single rule: glob patterns + ops bitset + allow/deny verdict. */
58
+ export interface Rule {
59
+ patterns: string[];
60
+ ops: Op;
61
+ allow: boolean;
62
+ }
63
+
64
+ /** Prompt callback used in `Mode.Prompt`. Return `true` to allow this call. */
65
+ export type PromptFunc = (path: string, op: Op) => boolean;
66
+
67
+ /** Error thrown by `Enforce` when a path is denied. */
68
+ export class ErrDenied extends Error {
69
+ constructor(p: string, op: Op) {
70
+ super(`scope: path denied: ${p} (op=${opString(op)})`);
71
+ this.name = 'ErrDenied';
72
+ }
73
+ }
74
+
75
+ // ─── Defaults JSON shape ─────────────────────────────────────────────────────
76
+
77
+ interface ScopeDefaults {
78
+ version: number;
79
+ deny: Record<string, string[]>;
80
+ }
81
+
82
+ const defaults: ScopeDefaults = scopeDefaultsRaw as unknown as ScopeDefaults;
83
+
84
+ // ─── Policy ──────────────────────────────────────────────────────────────────
85
+
86
+ /**
87
+ * Policy holds an ordered list of rules, a Mode, and an optional prompt
88
+ * callback. Construct via `New()` or `Default()`.
89
+ */
90
+ export class Policy {
91
+ private rules: Rule[] = [];
92
+ private mode: Mode = Mode.Strict;
93
+ private prompt?: PromptFunc;
94
+
95
+ /** Register an allow rule covering Read|Write|Exec. */
96
+ allow(...patterns: string[]): this {
97
+ return this.allowOp(Op.Read | Op.Write | Op.Exec, ...patterns);
98
+ }
99
+
100
+ /** Register an allow rule for the given operations. */
101
+ allowOp(op: Op, ...patterns: string[]): this {
102
+ if (patterns.length === 0) return this;
103
+ this.rules.push({ patterns: [...patterns], ops: op, allow: true });
104
+ return this;
105
+ }
106
+
107
+ /** Register a deny rule covering Read|Write|Exec. */
108
+ deny(...patterns: string[]): this {
109
+ return this.denyOp(Op.Read | Op.Write | Op.Exec, ...patterns);
110
+ }
111
+
112
+ /** Register a deny rule for the given operations. */
113
+ denyOp(op: Op, ...patterns: string[]): this {
114
+ if (patterns.length === 0) return this;
115
+ this.rules.push({ patterns: [...patterns], ops: op, allow: false });
116
+ return this;
117
+ }
118
+
119
+ /** Set the enforcement mode. */
120
+ setMode(m: Mode): this {
121
+ this.mode = m;
122
+ return this;
123
+ }
124
+
125
+ /** Get the current enforcement mode. */
126
+ getMode(): Mode {
127
+ return this.mode;
128
+ }
129
+
130
+ /** Set the prompt callback used in `Mode.Prompt`. */
131
+ setPromptFunc(fn: PromptFunc): this {
132
+ this.prompt = fn;
133
+ return this;
134
+ }
135
+
136
+ /** Defensive copy of the policy's rules in registration order. */
137
+ getRules(): Rule[] {
138
+ return this.rules.map((r) => ({ patterns: [...r.patterns], ops: r.ops, allow: r.allow }));
139
+ }
140
+
141
+ /**
142
+ * Evaluate `(p, op)` against the policy. Pure — no prompt, no mutation.
143
+ * Resolves symlinks before matching to defeat symlink escapes; on ENOENT
144
+ * the cleaned path is used so "intent to write" still matches deny rules.
145
+ */
146
+ check(p: string, op: Op): Decision {
147
+ const resolved = resolvePath(p);
148
+ let sawAllow = false;
149
+ for (const r of this.rules) {
150
+ if ((r.ops & op) === 0) continue;
151
+ if (!matchAny(r.patterns, resolved)) continue;
152
+ if (!r.allow) return Decision.Denied;
153
+ sawAllow = true;
154
+ }
155
+ return sawAllow ? Decision.Allowed : Decision.Unknown;
156
+ }
157
+
158
+ /**
159
+ * Enforce calls `check` and translates the decision according to mode:
160
+ * Strict + (Denied|Unknown) throws; Warn + Denied logs; Prompt + Denied
161
+ * invokes the prompt callback.
162
+ */
163
+ enforce(p: string, op: Op): void {
164
+ const dec = this.check(p, op);
165
+ if (dec === Decision.Allowed) return;
166
+ if (dec === Decision.Unknown && this.mode !== Mode.Strict) return;
167
+ this.handleDeny(p, op);
168
+ }
169
+
170
+ private handleDeny(p: string, op: Op): void {
171
+ switch (this.mode) {
172
+ case Mode.Warn:
173
+ console.warn(`scope: path denied (warn mode, allowing): ${p} op=${opString(op)}`);
174
+ return;
175
+ case Mode.Prompt:
176
+ if (this.prompt && this.prompt(p, op)) return;
177
+ throw new ErrDenied(p, op);
178
+ default: // Strict
179
+ throw new ErrDenied(p, op);
180
+ }
181
+ }
182
+
183
+ /** Deep copy. Useful for per-test isolation paired with `setDefault`. */
184
+ snapshot(): Policy {
185
+ const cp = new Policy();
186
+ cp.mode = this.mode;
187
+ cp.prompt = this.prompt;
188
+ cp.rules = this.rules.map((r) => ({ patterns: [...r.patterns], ops: r.ops, allow: r.allow }));
189
+ return cp;
190
+ }
191
+ }
192
+
193
+ // ─── Singleton + factory ─────────────────────────────────────────────────────
194
+
195
+ let defaultP: Policy | null = null;
196
+
197
+ /** Create an empty `Policy` in `Mode.Strict`. */
198
+ export function New(): Policy {
199
+ return new Policy();
200
+ }
201
+
202
+ /**
203
+ * Returns the package-level singleton policy used by primitives that don't
204
+ * accept an explicit policy. Lazy-initialised on first call. The singleton is
205
+ * pre-seeded with `SecretPaths()` as a deny-all-ops rule.
206
+ */
207
+ export function Default(): Policy {
208
+ if (!defaultP) {
209
+ defaultP = New().deny(...SecretPaths());
210
+ }
211
+ return defaultP;
212
+ }
213
+
214
+ /**
215
+ * Swap the package-level singleton with `p`. Returns a restore function that
216
+ * puts the previous policy back. Intended for tests:
217
+ *
218
+ * ```ts
219
+ * const restore = setDefault(New().allow('~/tmp/**'));
220
+ * try { ... } finally { restore(); }
221
+ * ```
222
+ */
223
+ export function setDefault(p: Policy): () => void {
224
+ const prev = Default();
225
+ defaultP = p;
226
+ return () => {
227
+ defaultP = prev;
228
+ };
229
+ }
230
+
231
+ // ─── Default deny list ───────────────────────────────────────────────────────
232
+
233
+ /**
234
+ * Returns the default deny pattern set: common patterns plus the patterns
235
+ * specific to the current platform. Patterns are ready to feed into
236
+ * `Policy.deny`. `~` and Windows env macros are resolved at match time.
237
+ */
238
+ export function SecretPaths(): string[] {
239
+ const common = defaults.deny['common'] ?? [];
240
+ const platName = platformKey();
241
+ const platSpecific = defaults.deny[platName] ?? [];
242
+ return [...common, ...platSpecific].map(expandWindowsEnv);
243
+ }
244
+
245
+ /** Map Node.js `process.platform` to the keys used in scope-defaults.json. */
246
+ function platformKey(): string {
247
+ switch (process.platform) {
248
+ case 'darwin':
249
+ return 'darwin';
250
+ case 'win32':
251
+ return 'windows';
252
+ default:
253
+ return 'linux';
254
+ }
255
+ }
256
+
257
+ /**
258
+ * Expand `%APPDATA%`, `%LOCALAPPDATA%`, `%USERPROFILE%` in `p` using the
259
+ * matching env vars when present. On non-Windows hosts the expansion is
260
+ * best-effort: when the env var is empty the macro is left in place and the
261
+ * pattern simply won't match anything.
262
+ */
263
+ function expandWindowsEnv(p: string): string {
264
+ for (const key of ['APPDATA', 'LOCALAPPDATA', 'USERPROFILE']) {
265
+ const token = `%${key}%`;
266
+ if (!p.includes(token)) continue;
267
+ const v = process.env[key];
268
+ if (!v) continue;
269
+ p = p.split(token).join(v);
270
+ }
271
+ return p;
272
+ }
273
+
274
+ // ─── Path resolution + match ─────────────────────────────────────────────────
275
+
276
+ /** Expand a leading `~` to the user's home dir, then `path.normalize`. */
277
+ function expandHome(s: string): string {
278
+ if (s === '~' || s.startsWith('~/')) {
279
+ let home = os.homedir();
280
+ try {
281
+ home = fs.realpathSync(home);
282
+ } catch {
283
+ // best effort; keep raw home
284
+ }
285
+ return s === '~' ? home : path.join(home, s.slice(2));
286
+ }
287
+ return s;
288
+ }
289
+
290
+ /**
291
+ * Resolve `s`: expand `~`, normalize, and follow symlinks. On ENOENT walks
292
+ * up to the deepest existing ancestor and re-attaches the missing tail.
293
+ */
294
+ function resolvePath(s: string): string {
295
+ const expanded = expandHome(s);
296
+ const cleaned = path.normalize(expanded);
297
+ try {
298
+ return fs.realpathSync(cleaned);
299
+ } catch (err: unknown) {
300
+ if (!isENOENT(err)) return cleaned;
301
+ }
302
+ // Walk up to the deepest existing ancestor.
303
+ let dir = path.dirname(cleaned);
304
+ let tail = path.basename(cleaned);
305
+ while (dir && dir !== path.parse(dir).root) {
306
+ try {
307
+ const resolved = fs.realpathSync(dir);
308
+ return path.join(resolved, tail);
309
+ } catch (err: unknown) {
310
+ if (!isENOENT(err)) return cleaned;
311
+ }
312
+ tail = path.join(path.basename(dir), tail);
313
+ dir = path.dirname(dir);
314
+ }
315
+ return cleaned;
316
+ }
317
+
318
+ function isENOENT(err: unknown): boolean {
319
+ return typeof err === 'object' && err !== null && (err as { code?: string }).code === 'ENOENT';
320
+ }
321
+
322
+ /** Returns true if any of the patterns matches `abs` (already resolved). */
323
+ function matchAny(patterns: string[], abs: string): boolean {
324
+ for (const p of patterns) {
325
+ const expanded = expandHome(p);
326
+ const canon = canonicalisePattern(path.normalize(expanded));
327
+ if (picomatch.isMatch(abs, canon, { dot: true })) return true;
328
+ }
329
+ return false;
330
+ }
331
+
332
+ /**
333
+ * Resolve the longest leading literal directory prefix of `pat` through
334
+ * realpath so the pattern keeps matching after the input path is canonicalised.
335
+ */
336
+ function canonicalisePattern(pat: string): string {
337
+ const sep = path.sep;
338
+ const parts = pat.split(sep);
339
+ let cut = 0;
340
+ for (let i = 0; i < parts.length; i++) {
341
+ if (containsGlobMeta(parts[i] ?? '')) break;
342
+ cut = i + 1;
343
+ }
344
+ if (cut === 0) return pat;
345
+ const literalParts = parts.slice(0, cut);
346
+ const prefix = literalParts.join(sep);
347
+ if (!prefix) return pat;
348
+ try {
349
+ const resolved = fs.realpathSync(prefix);
350
+ return joinPattern(resolved, parts.slice(cut));
351
+ } catch {
352
+ // Walk up to the deepest existing ancestor.
353
+ for (let i = literalParts.length - 1; i >= 1; i--) {
354
+ const ancestor = literalParts.slice(0, i).join(sep);
355
+ if (!ancestor) continue;
356
+ try {
357
+ const resolved = fs.realpathSync(ancestor);
358
+ const tail = [...literalParts.slice(i), ...parts.slice(cut)];
359
+ return joinPattern(resolved, tail);
360
+ } catch {
361
+ // continue
362
+ }
363
+ }
364
+ }
365
+ return pat;
366
+ }
367
+
368
+ function joinPattern(resolved: string, rest: string[]): string {
369
+ return rest.length === 0 ? resolved : resolved + path.sep + rest.join(path.sep);
370
+ }
371
+
372
+ function containsGlobMeta(s: string): boolean {
373
+ return /[*?[\]{}]/.test(s);
374
+ }
375
+
376
+ function opString(op: Op): string {
377
+ const parts: string[] = [];
378
+ if (op & Op.Read) parts.push('read');
379
+ if (op & Op.Write) parts.push('write');
380
+ if (op & Op.Exec) parts.push('exec');
381
+ return parts.length === 0 ? 'none' : parts.join('|');
382
+ }
@@ -0,0 +1,110 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { SetFlag } from './setflag';
3
+
4
+ describe('SetFlag', () => {
5
+ it('appends by default', () => {
6
+ const sf = new SetFlag();
7
+ sf.set('feat');
8
+ sf.set('docs');
9
+ expect(sf.values()).toEqual(['feat', 'docs']);
10
+ });
11
+
12
+ it('appends with + prefix', () => {
13
+ const sf = new SetFlag();
14
+ sf.set('+feat');
15
+ sf.set('+docs');
16
+ expect(sf.values()).toEqual(['feat', 'docs']);
17
+ });
18
+
19
+ it('removes with - prefix', () => {
20
+ const sf = new SetFlag(['feat', 'bug', 'docs']);
21
+ sf.set('-bug');
22
+ expect(sf.values()).toEqual(['feat', 'docs']);
23
+ });
24
+
25
+ it('remove nonexistent is no-op', () => {
26
+ const sf = new SetFlag(['feat']);
27
+ sf.set('-nope');
28
+ expect(sf.values()).toEqual(['feat']);
29
+ });
30
+
31
+ it('replaces all with = prefix', () => {
32
+ const sf = new SetFlag(['old1', 'old2']);
33
+ sf.set('=new1,new2');
34
+ expect(sf.values()).toEqual(['new1', 'new2']);
35
+ });
36
+
37
+ it('clears all with bare =', () => {
38
+ const sf = new SetFlag(['a', 'b', 'c']);
39
+ sf.set('=');
40
+ expect(sf.values()).toEqual([]);
41
+ });
42
+
43
+ it('toString returns comma-joined', () => {
44
+ const sf = new SetFlag(['a', 'b']);
45
+ expect(sf.toString()).toBe('a,b');
46
+ });
47
+
48
+ it('toString empty returns empty string', () => {
49
+ const sf = new SetFlag();
50
+ expect(sf.toString()).toBe('');
51
+ });
52
+
53
+ it('deduplicates', () => {
54
+ const sf = new SetFlag();
55
+ sf.set('feat');
56
+ sf.set('feat');
57
+ expect(sf.values()).toEqual(['feat']);
58
+ });
59
+
60
+ it('mixed operations', () => {
61
+ const sf = new SetFlag();
62
+ sf.set('a');
63
+ sf.set('b');
64
+ sf.set('c');
65
+ sf.set('-b');
66
+ sf.set('+d');
67
+ expect(sf.values()).toEqual(['a', 'c', 'd']);
68
+ });
69
+
70
+ it('replace after append', () => {
71
+ const sf = new SetFlag();
72
+ sf.set('a');
73
+ sf.set('b');
74
+ sf.set('=x');
75
+ expect(sf.values()).toEqual(['x']);
76
+ });
77
+
78
+ it('comma in append splits', () => {
79
+ const sf = new SetFlag();
80
+ sf.set('a,b');
81
+ expect(sf.values()).toEqual(['a', 'b']);
82
+ });
83
+
84
+ it('= escapes literal + prefix', () => {
85
+ const sf = new SetFlag();
86
+ sf.set('=+ppl');
87
+ expect(sf.values()).toEqual(['+ppl']);
88
+ });
89
+
90
+ it('= escapes literal - prefix', () => {
91
+ const sf = new SetFlag();
92
+ sf.set('=-negative');
93
+ expect(sf.values()).toEqual(['-negative']);
94
+ });
95
+
96
+ it('= escapes literal = prefix', () => {
97
+ const sf = new SetFlag();
98
+ sf.set('==equals');
99
+ expect(sf.values()).toEqual(['=equals']);
100
+ });
101
+
102
+ it('parseArg works as Commander option parser', () => {
103
+ const sf = new SetFlag();
104
+ // Commander calls parseArg(value, previous)
105
+ let result = sf.parseArg('feat', []);
106
+ result = sf.parseArg('+docs', result);
107
+ result = sf.parseArg('-feat', result);
108
+ expect(result).toEqual(['docs']);
109
+ });
110
+ });