@agentic-kit/permissions 0.0.0-stage → 0.2.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 (143) hide show
  1. package/LICENSE +23 -0
  2. package/README.md +279 -2
  3. package/bash/analyze.d.ts +133 -0
  4. package/bash/analyze.js +442 -0
  5. package/bash/args.d.ts +45 -0
  6. package/bash/args.js +145 -0
  7. package/bash/braces.d.ts +6 -0
  8. package/bash/braces.js +72 -0
  9. package/bash/commands.d.ts +14 -0
  10. package/bash/commands.js +361 -0
  11. package/bash/file-commands.d.ts +22 -0
  12. package/bash/file-commands.js +278 -0
  13. package/bash/flows.d.ts +67 -0
  14. package/bash/flows.js +208 -0
  15. package/bash/git.d.ts +7 -0
  16. package/bash/git.js +163 -0
  17. package/bash/network.d.ts +24 -0
  18. package/bash/network.js +295 -0
  19. package/bash/quoting.d.ts +16 -0
  20. package/bash/quoting.js +164 -0
  21. package/bash/system.d.ts +16 -0
  22. package/bash/system.js +122 -0
  23. package/bash/tokenize.d.ts +67 -0
  24. package/bash/tokenize.js +440 -0
  25. package/bash/words.d.ts +9 -0
  26. package/bash/words.js +30 -0
  27. package/bash/wrappers.d.ts +32 -0
  28. package/bash/wrappers.js +237 -0
  29. package/classify.d.ts +22 -0
  30. package/classify.js +259 -0
  31. package/engine.d.ts +109 -0
  32. package/engine.js +144 -0
  33. package/env.d.ts +13 -0
  34. package/env.js +37 -0
  35. package/esm/bash/analyze.d.ts +133 -0
  36. package/esm/bash/analyze.js +405 -0
  37. package/esm/bash/args.d.ts +45 -0
  38. package/esm/bash/args.js +135 -0
  39. package/esm/bash/braces.d.ts +6 -0
  40. package/esm/bash/braces.js +69 -0
  41. package/esm/bash/commands.d.ts +14 -0
  42. package/esm/bash/commands.js +324 -0
  43. package/esm/bash/file-commands.d.ts +22 -0
  44. package/esm/bash/file-commands.js +233 -0
  45. package/esm/bash/flows.d.ts +67 -0
  46. package/esm/bash/flows.js +203 -0
  47. package/esm/bash/git.d.ts +7 -0
  48. package/esm/bash/git.js +127 -0
  49. package/esm/bash/network.d.ts +24 -0
  50. package/esm/bash/network.js +282 -0
  51. package/esm/bash/quoting.d.ts +16 -0
  52. package/esm/bash/quoting.js +153 -0
  53. package/esm/bash/system.d.ts +16 -0
  54. package/esm/bash/system.js +82 -0
  55. package/esm/bash/tokenize.d.ts +67 -0
  56. package/esm/bash/tokenize.js +437 -0
  57. package/esm/bash/words.d.ts +9 -0
  58. package/esm/bash/words.js +24 -0
  59. package/esm/bash/wrappers.d.ts +32 -0
  60. package/esm/bash/wrappers.js +200 -0
  61. package/esm/classify.d.ts +22 -0
  62. package/esm/classify.js +223 -0
  63. package/esm/engine.d.ts +109 -0
  64. package/esm/engine.js +108 -0
  65. package/esm/env.d.ts +13 -0
  66. package/esm/env.js +34 -0
  67. package/esm/findings.d.ts +7 -0
  68. package/esm/findings.js +9 -0
  69. package/esm/glob.d.ts +15 -0
  70. package/esm/glob.js +69 -0
  71. package/esm/grants.d.ts +36 -0
  72. package/esm/grants.js +99 -0
  73. package/esm/index.d.ts +19 -0
  74. package/esm/index.js +18 -0
  75. package/esm/node-fs.d.ts +6 -0
  76. package/esm/node-fs.js +34 -0
  77. package/esm/paths.d.ts +43 -0
  78. package/esm/paths.js +121 -0
  79. package/esm/policy.d.ts +21 -0
  80. package/esm/policy.js +85 -0
  81. package/esm/prompt.d.ts +14 -0
  82. package/esm/prompt.js +79 -0
  83. package/esm/roots.d.ts +75 -0
  84. package/esm/roots.js +148 -0
  85. package/esm/secret-files.d.ts +16 -0
  86. package/esm/secret-files.js +84 -0
  87. package/esm/secrets/collect.d.ts +19 -0
  88. package/esm/secrets/collect.js +60 -0
  89. package/esm/secrets/index.d.ts +5 -0
  90. package/esm/secrets/index.js +5 -0
  91. package/esm/secrets/parse.d.ts +19 -0
  92. package/esm/secrets/parse.js +140 -0
  93. package/esm/secrets/redact-result.d.ts +8 -0
  94. package/esm/secrets/redact-result.js +67 -0
  95. package/esm/secrets/rules.d.ts +34 -0
  96. package/esm/secrets/rules.js +101 -0
  97. package/esm/secrets/vault.d.ts +48 -0
  98. package/esm/secrets/vault.js +158 -0
  99. package/esm/signals.d.ts +14 -0
  100. package/esm/signals.js +26 -0
  101. package/esm/tool-input.d.ts +13 -0
  102. package/esm/tool-input.js +40 -0
  103. package/esm/types.d.ts +146 -0
  104. package/esm/types.js +20 -0
  105. package/findings.d.ts +7 -0
  106. package/findings.js +13 -0
  107. package/glob.d.ts +15 -0
  108. package/glob.js +73 -0
  109. package/grants.d.ts +36 -0
  110. package/grants.js +110 -0
  111. package/index.d.ts +19 -0
  112. package/index.js +52 -0
  113. package/node-fs.d.ts +6 -0
  114. package/node-fs.js +37 -0
  115. package/package.json +35 -3
  116. package/paths.d.ts +43 -0
  117. package/paths.js +164 -0
  118. package/policy.d.ts +21 -0
  119. package/policy.js +88 -0
  120. package/prompt.d.ts +14 -0
  121. package/prompt.js +83 -0
  122. package/roots.d.ts +75 -0
  123. package/roots.js +192 -0
  124. package/secret-files.d.ts +16 -0
  125. package/secret-files.js +124 -0
  126. package/secrets/collect.d.ts +19 -0
  127. package/secrets/collect.js +96 -0
  128. package/secrets/index.d.ts +5 -0
  129. package/secrets/index.js +21 -0
  130. package/secrets/parse.d.ts +19 -0
  131. package/secrets/parse.js +145 -0
  132. package/secrets/redact-result.d.ts +8 -0
  133. package/secrets/redact-result.js +70 -0
  134. package/secrets/rules.d.ts +34 -0
  135. package/secrets/rules.js +107 -0
  136. package/secrets/vault.d.ts +48 -0
  137. package/secrets/vault.js +163 -0
  138. package/signals.d.ts +14 -0
  139. package/signals.js +29 -0
  140. package/tool-input.d.ts +13 -0
  141. package/tool-input.js +46 -0
  142. package/types.d.ts +146 -0
  143. package/types.js +24 -0
package/esm/prompt.js ADDED
@@ -0,0 +1,79 @@
1
+ /** The approval card for an ASK: a title, what it touches, and why it asks. */
2
+ import { showPath } from './paths';
3
+ /** The title of a write to a file that runs code later, by the label of its root. */
4
+ const ASK_WRITE_TITLES = {
5
+ 'git hook': 'Write to a git hook',
6
+ 'git config': 'Change the git config',
7
+ 'direnv script': 'Change the direnv script',
8
+ 'editor task config': 'Change the editor task config'
9
+ };
10
+ /** The most specific title, by signal priority. */
11
+ export function promptTitle(request) {
12
+ const has = (s) => request.signals.includes(s);
13
+ const bash = request.toolName === 'bash';
14
+ if (has('placeholder-in-command'))
15
+ return 'Run a command that uses a secret';
16
+ if (has('upload'))
17
+ return 'Run a command that uploads data';
18
+ if (has('destructive'))
19
+ return 'Run a destructive command';
20
+ if (has('sudo'))
21
+ return 'Run a command as root';
22
+ if (has('persistence'))
23
+ return 'Make a change that outlasts this session';
24
+ if (has('network-exposure'))
25
+ return 'Expose this machine to the network';
26
+ if (has('secret-env-expansion'))
27
+ return 'Run a command that uses a secret variable';
28
+ if (has('secret-transform'))
29
+ return 'Run a command that transforms a secret file';
30
+ if (has('shell-dynamic'))
31
+ return 'Run a command with dynamic shell code';
32
+ if (has('secret-into-plain-file'))
33
+ return 'Write a secret into a regular file';
34
+ if (has('clipboard'))
35
+ return 'Use the clipboard';
36
+ if (has('stdin-operands'))
37
+ return 'Run a command on file names from its input';
38
+ if (has('ask-write')) {
39
+ const label = request.targets.find((t) => t.zone === 'ask-write')?.label ?? '';
40
+ return ASK_WRITE_TITLES[label] ?? 'Write to a file that runs code';
41
+ }
42
+ if (has('unresolvable-path'))
43
+ return 'Use a path that cannot be resolved';
44
+ if (has('outside-workspace')) {
45
+ if (bash)
46
+ return 'Run a command that touches files outside the project';
47
+ if (request.kind === 'write')
48
+ return 'Write a file outside the project';
49
+ return 'Read a file outside the project';
50
+ }
51
+ if (bash)
52
+ return 'Run a command';
53
+ if (request.toolName === 'edit')
54
+ return 'Edit a file';
55
+ if (request.kind === 'write')
56
+ return 'Write a file';
57
+ return 'Read a file';
58
+ }
59
+ /**
60
+ * The card for an ASK. `reasons` are the sentences the policy asked for, in
61
+ * order. With one target and no command, the card shows the path in its own
62
+ * row, so a reason that opens with that path says "it" instead.
63
+ */
64
+ export function buildPrompt(request, reasons, grantOptions, display) {
65
+ const shown = request.targets.map((t) => showPath(t.path, display.workspace, display.homeDir));
66
+ const only = request.command === undefined && shown.length === 1 ? `${shown[0]} ` : null;
67
+ const cardReasons = reasons.map((r) => (only && r.startsWith(only) ? `it ${r.slice(only.length)}` : r));
68
+ return {
69
+ title: promptTitle(request),
70
+ summary: request.command ?? shown.join('\n'),
71
+ toolName: request.toolName,
72
+ kind: request.kind,
73
+ ...(request.command === undefined ? {} : { command: request.command }),
74
+ targets: request.targets.map((t, i) => ({ path: shown[i], access: t.access, zone: t.zone })),
75
+ signals: request.signals,
76
+ reasons: cardReasons,
77
+ grantOptions: grantOptions.map(({ scope, label, pattern }) => ({ scope, label, pattern }))
78
+ };
79
+ }
package/esm/roots.d.ts ADDED
@@ -0,0 +1,75 @@
1
+ /**
2
+ * The fixed places the engine knows about, and the zone a path falls in.
3
+ *
4
+ * Roots are canonicalized once per engine, so `/tmp/x` and `/private/tmp/x`
5
+ * (macOS) compare equal. Each root keeps its lexical spelling too, so a list
6
+ * entry still matches when the root itself is a symlink or does not exist yet.
7
+ */
8
+ import type { Access, FsProbe, Zone } from './types';
9
+ /** One fixed place, relative to the home dir or a workspace, and what it is in words. */
10
+ export interface KnownPath {
11
+ rel: string;
12
+ label: string;
13
+ }
14
+ /** The macOS keychain dir. The bash analyzer counts a `security` read as a read of it. */
15
+ export declare const KEYCHAIN_DIR = "Library/Keychains";
16
+ /** Credential stores under the home dir. Read, write and run there are DENY in every mode. */
17
+ export declare const HOME_HARD_DENY: readonly KnownPath[];
18
+ export declare function defaultHardDeny(homeDir: string): string[];
19
+ /** Scratch dirs the agent may read and write without a prompt. */
20
+ export declare function defaultTempDirs(): string[];
21
+ /** Inside each workspace: writes are DENY in every mode (pi loads extensions from here). */
22
+ export declare const WORKSPACE_PROTECTED_WRITE: readonly KnownPath[];
23
+ /** Inside each workspace: writes run code later, so they ask outside Full mode. */
24
+ export declare const WORKSPACE_ASK_WRITE: readonly KnownPath[];
25
+ /** One root: the canonical path plus the lexical spelling, and what it is for. */
26
+ export interface Root {
27
+ path: string;
28
+ lexical: string;
29
+ label: string;
30
+ }
31
+ export interface Roots {
32
+ workspace: Root[];
33
+ trustedRead: Root[];
34
+ trustedExec: Root[];
35
+ temp: Root[];
36
+ hardDeny: Root[];
37
+ /** Writes are DENY: the trusted roots, `<ws>/.pi`, and host entries. */
38
+ protectedWrite: Root[];
39
+ /** Writes ask outside Full mode. */
40
+ askWrite: Root[];
41
+ }
42
+ export interface RootsSpec {
43
+ cwd: string;
44
+ homeDir: string;
45
+ workspace?: string[];
46
+ trustedRead?: string[];
47
+ trustedExec?: string[];
48
+ temp?: string[];
49
+ hardDeny?: string[];
50
+ protectedWrite?: string[];
51
+ askWrite?: string[];
52
+ }
53
+ /** Host hard-deny paths listed at decision time (a folder made during the session). */
54
+ export declare function buildHostHardDeny(paths: readonly string[], fs: FsProbe): Promise<Root[]>;
55
+ /** Canonicalize every root once. */
56
+ export declare function buildRoots(spec: RootsSpec, fs: FsProbe): Promise<Roots>;
57
+ /** The first root that holds `p`, matching either spelling. */
58
+ export declare function findRoot(roots: readonly Root[], p: string, caseInsensitive?: boolean): Root | undefined;
59
+ export interface ZoneHit {
60
+ zone: Zone;
61
+ root?: Root;
62
+ }
63
+ /**
64
+ * Where a canonical path sits for one access, most specific first:
65
+ * hard-deny > protected (writes) > ask-write (writes) > trusted > workspace > temp > outside.
66
+ * The restrictive lists match case-insensitively on macOS and Windows.
67
+ */
68
+ export declare function zoneOf(p: string, access: Access, roots: Roots): ZoneHit;
69
+ /**
70
+ * The strictest restrictive zone a glob path could expand into: hard-deny,
71
+ * then (writes) protected and ask-write. `undefined` when it reaches none.
72
+ */
73
+ export declare function globZoneOf(pattern: string, access: Access, roots: Roots, dot: boolean): ZoneHit | undefined;
74
+ /** `p` is exactly one of the roots (a workspace or temp root itself). */
75
+ export declare function isRootItself(roots: readonly Root[], p: string): boolean;
package/esm/roots.js ADDED
@@ -0,0 +1,148 @@
1
+ /**
2
+ * The fixed places the engine knows about, and the zone a path falls in.
3
+ *
4
+ * Roots are canonicalized once per engine, so `/tmp/x` and `/private/tmp/x`
5
+ * (macOS) compare equal. Each root keeps its lexical spelling too, so a list
6
+ * entry still matches when the root itself is a symlink or does not exist yet.
7
+ */
8
+ import * as os from 'node:os';
9
+ import * as path from 'node:path';
10
+ import { globReaches } from './glob';
11
+ import { canonicalize, CASE_INSENSITIVE_FS, contains } from './paths';
12
+ /** The macOS keychain dir. The bash analyzer counts a `security` read as a read of it. */
13
+ export const KEYCHAIN_DIR = 'Library/Keychains';
14
+ /** Credential stores under the home dir. Read, write and run there are DENY in every mode. */
15
+ export const HOME_HARD_DENY = [
16
+ { rel: '.ssh', label: 'SSH keys' },
17
+ { rel: '.aws', label: 'AWS credentials' },
18
+ { rel: '.gnupg', label: 'GPG keys' },
19
+ { rel: '.config/gh', label: 'GitHub CLI credentials' },
20
+ { rel: '.config/gcloud', label: 'Google Cloud credentials' },
21
+ { rel: '.azure', label: 'Azure credentials' },
22
+ { rel: '.kube', label: 'Kubernetes credentials' },
23
+ { rel: '.docker/config.json', label: 'Docker credentials' },
24
+ { rel: '.netrc', label: 'network credentials' },
25
+ { rel: '.npmrc', label: 'npm credentials' },
26
+ { rel: '.pypirc', label: 'PyPI credentials' },
27
+ { rel: '.git-credentials', label: 'git credentials' },
28
+ { rel: '.pgpass', label: 'Postgres passwords' },
29
+ { rel: KEYCHAIN_DIR, label: 'macOS keychain' },
30
+ { rel: 'Library/Application Support/Google/Chrome', label: 'browser profile' },
31
+ { rel: 'Library/Application Support/Firefox', label: 'browser profile' },
32
+ { rel: 'Library/Application Support/BraveSoftware', label: 'browser profile' },
33
+ { rel: 'Library/Application Support/Arc', label: 'browser profile' }
34
+ ];
35
+ export function defaultHardDeny(homeDir) {
36
+ return HOME_HARD_DENY.map(({ rel }) => path.join(path.resolve(homeDir), rel));
37
+ }
38
+ /** Scratch dirs the agent may read and write without a prompt. */
39
+ export function defaultTempDirs() {
40
+ const dirs = [os.tmpdir(), '/tmp', '/private/tmp'];
41
+ if (process.platform === 'darwin')
42
+ dirs.push('/private/var/folders');
43
+ return [...new Set(dirs.map((d) => path.resolve(d)))];
44
+ }
45
+ /** Inside each workspace: writes are DENY in every mode (pi loads extensions from here). */
46
+ export const WORKSPACE_PROTECTED_WRITE = [{ rel: '.pi', label: 'agent extension dir' }];
47
+ /** Inside each workspace: writes run code later, so they ask outside Full mode. */
48
+ export const WORKSPACE_ASK_WRITE = [
49
+ { rel: '.git/hooks', label: 'git hook' },
50
+ { rel: '.git/config', label: 'git config' },
51
+ { rel: '.husky', label: 'git hook' },
52
+ { rel: '.envrc', label: 'direnv script' },
53
+ { rel: '.vscode/tasks.json', label: 'editor task config' }
54
+ ];
55
+ async function makeRoot(p, label, fs) {
56
+ const lexical = path.resolve(p);
57
+ const canonical = await canonicalize(lexical, fs);
58
+ return { path: canonical ?? lexical, lexical, label };
59
+ }
60
+ const HOST_HARD_DENY_LABEL = 'app data the agent may not touch';
61
+ /** Host hard-deny paths listed at decision time (a folder made during the session). */
62
+ export function buildHostHardDeny(paths, fs) {
63
+ return Promise.all(paths.map((p) => makeRoot(p, HOST_HARD_DENY_LABEL, fs)));
64
+ }
65
+ /** Canonicalize every root once. */
66
+ export async function buildRoots(spec, fs) {
67
+ const labelled = (list, label) => (list ?? []).map((p) => ({ p, label }));
68
+ const known = (base, list) => list.map(({ rel, label }) => ({ p: path.join(base, rel), label }));
69
+ const build = (entries) => Promise.all(entries.map(({ p, label }) => makeRoot(p, label, fs)));
70
+ const workspaceDirs = spec.workspace?.length ? spec.workspace : [spec.cwd];
71
+ const trustedRead = labelled(spec.trustedRead, 'trusted harness files');
72
+ const trustedExec = labelled(spec.trustedExec, 'trusted harness scripts');
73
+ const [workspace, tRead, tExec, temp, hardDeny, protectedWrite, askWrite] = await Promise.all([
74
+ build(labelled(workspaceDirs, 'project')),
75
+ build(trustedRead),
76
+ build(trustedExec),
77
+ build(labelled(spec.temp ?? defaultTempDirs(), 'temp dir')),
78
+ build([...known(path.resolve(spec.homeDir), HOME_HARD_DENY), ...labelled(spec.hardDeny, HOST_HARD_DENY_LABEL)]),
79
+ build([
80
+ ...trustedRead,
81
+ ...trustedExec,
82
+ ...workspaceDirs.flatMap((ws) => known(ws, WORKSPACE_PROTECTED_WRITE)),
83
+ ...labelled(spec.protectedWrite, 'protected by the host')
84
+ ]),
85
+ build([...workspaceDirs.flatMap((ws) => known(ws, WORKSPACE_ASK_WRITE)), ...labelled(spec.askWrite, 'file that can run code')])
86
+ ]);
87
+ return { workspace, trustedRead: tRead, trustedExec: tExec, temp, hardDeny, protectedWrite, askWrite };
88
+ }
89
+ /** The first root that holds `p`, matching either spelling. */
90
+ export function findRoot(roots, p, caseInsensitive = false) {
91
+ return roots.find((r) => contains(r.path, p, caseInsensitive) || contains(r.lexical, p, caseInsensitive));
92
+ }
93
+ /**
94
+ * Where a canonical path sits for one access, most specific first:
95
+ * hard-deny > protected (writes) > ask-write (writes) > trusted > workspace > temp > outside.
96
+ * The restrictive lists match case-insensitively on macOS and Windows.
97
+ */
98
+ export function zoneOf(p, access, roots) {
99
+ const ci = CASE_INSENSITIVE_FS;
100
+ let root = findRoot(roots.hardDeny, p, ci);
101
+ if (root)
102
+ return { zone: 'hard-deny', root };
103
+ if (access === 'write') {
104
+ root = findRoot(roots.protectedWrite, p, ci);
105
+ if (root)
106
+ return { zone: 'protected', root };
107
+ root = findRoot(roots.askWrite, p, ci);
108
+ if (root)
109
+ return { zone: 'ask-write', root };
110
+ }
111
+ if (access !== 'exec') {
112
+ root = findRoot(roots.trustedRead, p);
113
+ if (root)
114
+ return { zone: 'trusted', root };
115
+ }
116
+ root = findRoot(roots.trustedExec, p);
117
+ if (root)
118
+ return { zone: 'trusted', root };
119
+ root = findRoot(roots.workspace, p);
120
+ if (root)
121
+ return { zone: 'workspace', root };
122
+ root = findRoot(roots.temp, p);
123
+ if (root)
124
+ return { zone: 'temp', root };
125
+ return { zone: 'outside' };
126
+ }
127
+ /**
128
+ * The strictest restrictive zone a glob path could expand into: hard-deny,
129
+ * then (writes) protected and ask-write. `undefined` when it reaches none.
130
+ */
131
+ export function globZoneOf(pattern, access, roots, dot) {
132
+ const opts = { dot, caseInsensitive: CASE_INSENSITIVE_FS };
133
+ const reached = (list) => list.find((r) => globReaches(pattern, r.path, opts) || globReaches(pattern, r.lexical, opts));
134
+ let root = reached(roots.hardDeny);
135
+ if (root)
136
+ return { zone: 'hard-deny', root };
137
+ if (access !== 'write')
138
+ return undefined;
139
+ root = reached(roots.protectedWrite);
140
+ if (root)
141
+ return { zone: 'protected', root };
142
+ root = reached(roots.askWrite);
143
+ return root ? { zone: 'ask-write', root } : undefined;
144
+ }
145
+ /** `p` is exactly one of the roots (a workspace or temp root itself). */
146
+ export function isRootItself(roots, p) {
147
+ return roots.some((r) => r.path === p || r.lexical === p);
148
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Files that hold credentials, by name (from the oh-my-pi jfind list). Reading
3
+ * one is allowed, because the output is redacted; writing one gets the real
4
+ * values restored; and their values feed the secret vault.
5
+ */
6
+ export declare const SECRET_FILE_NAMES: readonly string[];
7
+ /** Committed `.env` templates: not secret. */
8
+ export declare const ENV_TEMPLATE_NAMES: readonly string[];
9
+ export declare const SECRET_FILE_EXTENSIONS: readonly string[];
10
+ /** The base name is a secret file. Case-insensitive (`.ENV` opens `.env` on macOS). */
11
+ export declare function isSecretFileName(name: string): boolean;
12
+ export declare function isSecretFile(p: string): boolean;
13
+ /** `.env`, `.env.*` (not a template) or `.envrc`: parsed as dotenv for the vault. */
14
+ export declare function isEnvFileName(name: string): boolean;
15
+ /** A glob (grep `glob`, find `pattern`) that names secret files: `.env*`, `*.pem`. */
16
+ export declare function globNamesSecretFiles(glob: string): boolean;
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Files that hold credentials, by name (from the oh-my-pi jfind list). Reading
3
+ * one is allowed, because the output is redacted; writing one gets the real
4
+ * values restored; and their values feed the secret vault.
5
+ */
6
+ import * as path from 'node:path';
7
+ export const SECRET_FILE_NAMES = [
8
+ '.env',
9
+ '.envrc',
10
+ '.netrc',
11
+ '.npmrc',
12
+ '.pypirc',
13
+ '.pgpass',
14
+ '.boto',
15
+ '.s3cfg',
16
+ '.dockercfg',
17
+ '.git-credentials',
18
+ '.htpasswd',
19
+ 'credentials',
20
+ 'credentials.json',
21
+ 'client_secret.json',
22
+ 'service-account.json',
23
+ 'id_rsa',
24
+ 'id_dsa',
25
+ 'id_ecdsa',
26
+ 'id_ed25519'
27
+ ];
28
+ /** Committed `.env` templates: not secret. */
29
+ export const ENV_TEMPLATE_NAMES = ['.env.example', '.env.sample', '.env.template', '.env.dist'];
30
+ export const SECRET_FILE_EXTENSIONS = [
31
+ 'pem',
32
+ 'key',
33
+ 'p12',
34
+ 'pfx',
35
+ 'jks',
36
+ 'keystore',
37
+ 'bks',
38
+ 'ppk',
39
+ 'kdbx',
40
+ 'gpg',
41
+ 'pgp',
42
+ 'asc',
43
+ 'tfvars',
44
+ 'tfvars.json',
45
+ 'tfstate',
46
+ 'tfstate.backup'
47
+ ];
48
+ const NAMES = new Set(SECRET_FILE_NAMES);
49
+ const TEMPLATES = new Set(ENV_TEMPLATE_NAMES);
50
+ /** The base name is a secret file. Case-insensitive (`.ENV` opens `.env` on macOS). */
51
+ export function isSecretFileName(name) {
52
+ const lower = name.toLowerCase();
53
+ if (NAMES.has(lower))
54
+ return true;
55
+ if (lower.startsWith('.env.'))
56
+ return !TEMPLATES.has(lower);
57
+ return SECRET_FILE_EXTENSIONS.some((ext) => lower.length > ext.length + 1 && lower.endsWith(`.${ext}`));
58
+ }
59
+ export function isSecretFile(p) {
60
+ return isSecretFileName(path.basename(p));
61
+ }
62
+ /** `.env`, `.env.*` (not a template) or `.envrc`: parsed as dotenv for the vault. */
63
+ export function isEnvFileName(name) {
64
+ const lower = name.toLowerCase();
65
+ if (lower === '.env' || lower === '.envrc')
66
+ return true;
67
+ return lower.startsWith('.env.') && !TEMPLATES.has(lower);
68
+ }
69
+ /** A glob (grep `glob`, find `pattern`) that names secret files: `.env*`, `*.pem`. */
70
+ export function globNamesSecretFiles(glob) {
71
+ const names = glob
72
+ .split(/[{},/]/)
73
+ .map((part) => part.trim())
74
+ .filter(Boolean);
75
+ return names.some((name) => {
76
+ const lower = name.toLowerCase();
77
+ if (lower === '*' || lower === '**')
78
+ return false;
79
+ if (/^\.env(\*|\..*)?$/.test(lower) && !TEMPLATES.has(lower))
80
+ return true;
81
+ const literal = lower.replace(/\*/g, 'x');
82
+ return isSecretFileName(literal);
83
+ });
84
+ }
@@ -0,0 +1,19 @@
1
+ /** Read the secret values out of the secret files in the workspace. */
2
+ import type { FsProbe } from '../types';
3
+ export interface CollectedSecrets {
4
+ values: {
5
+ name: string;
6
+ value: string;
7
+ file: string;
8
+ }[];
9
+ errors: {
10
+ file: string;
11
+ error: unknown;
12
+ }[];
13
+ }
14
+ /**
15
+ * Read the secret files in the workspace dirs (the root and nested, to depth 4,
16
+ * skipping dependencies and build output, files up to 256 KB). Sibling dirs are
17
+ * walked in parallel, since a refresh runs after every tool that can write.
18
+ */
19
+ export declare function collectWorkspaceSecrets(dirs: readonly string[], fs: FsProbe): Promise<CollectedSecrets>;
@@ -0,0 +1,60 @@
1
+ /** Read the secret values out of the secret files in the workspace. */
2
+ import * as path from 'node:path';
3
+ import { isSecretFileName } from '../secret-files';
4
+ import { parseSecretFile, secretValuesOf } from './parse';
5
+ /** Dirs never walked: dependencies, VCS data, and build output. */
6
+ const SKIP_DIRS = new Set(['node_modules', '.git', '.next', '.turbo', 'dist', 'build', 'coverage']);
7
+ const MAX_DEPTH = 4;
8
+ const MAX_FILE_BYTES = 256 * 1024;
9
+ const MAX_DIRS = 5000;
10
+ /**
11
+ * Read the secret files in the workspace dirs (the root and nested, to depth 4,
12
+ * skipping dependencies and build output, files up to 256 KB). Sibling dirs are
13
+ * walked in parallel, since a refresh runs after every tool that can write.
14
+ */
15
+ export async function collectWorkspaceSecrets(dirs, fs) {
16
+ const result = { values: [], errors: [] };
17
+ const files = [];
18
+ let visited = 0;
19
+ const walk = async (dir, depth) => {
20
+ if (visited++ >= MAX_DIRS)
21
+ return;
22
+ let entries;
23
+ try {
24
+ entries = await fs.readDir(dir);
25
+ }
26
+ catch (error) {
27
+ if (depth === 0)
28
+ result.errors.push({ file: dir, error });
29
+ return;
30
+ }
31
+ const subdirs = [];
32
+ for (const entry of entries) {
33
+ const full = path.join(dir, entry.name);
34
+ if (entry.kind === 'dir') {
35
+ if (!SKIP_DIRS.has(entry.name) && depth + 1 < MAX_DEPTH)
36
+ subdirs.push(full);
37
+ }
38
+ else if ((entry.kind === 'file' || entry.kind === 'symlink') && isSecretFileName(entry.name)) {
39
+ files.push(full);
40
+ }
41
+ }
42
+ await Promise.all(subdirs.map((sub) => walk(sub, depth + 1)));
43
+ };
44
+ await Promise.all(dirs.map((dir) => walk(dir, 0)));
45
+ await Promise.all(files.map(async (file) => {
46
+ try {
47
+ if ((await fs.size(file)) > MAX_FILE_BYTES)
48
+ return;
49
+ const text = await fs.readFile(file);
50
+ if (text.includes('\u0000'))
51
+ return;
52
+ for (const v of secretValuesOf(parseSecretFile(path.basename(file), text)))
53
+ result.values.push({ ...v, file });
54
+ }
55
+ catch (error) {
56
+ result.errors.push({ file, error });
57
+ }
58
+ }));
59
+ return result;
60
+ }
@@ -0,0 +1,5 @@
1
+ export { type CollectedSecrets, collectWorkspaceSecrets } from './collect';
2
+ export { parseDotenv, type ParsedValue, parseSecretFile, secretValuesOf } from './parse';
3
+ export { redactToolResult } from './redact-result';
4
+ export { isSecretEntry, MIN_SECRET_LENGTH, SECRET_KEY_PATTERN, TOKEN_SHAPE_RES } from './rules';
5
+ export { findPlaceholders, PLACEHOLDER_PATTERN, type SecretOrigin, SecretVault, UNNAMED_TOKEN } from './vault';
@@ -0,0 +1,5 @@
1
+ export { collectWorkspaceSecrets } from './collect';
2
+ export { parseDotenv, parseSecretFile, secretValuesOf } from './parse';
3
+ export { redactToolResult } from './redact-result';
4
+ export { isSecretEntry, MIN_SECRET_LENGTH, SECRET_KEY_PATTERN, TOKEN_SHAPE_RES } from './rules';
5
+ export { findPlaceholders, PLACEHOLDER_PATTERN, SecretVault, UNNAMED_TOKEN } from './vault';
@@ -0,0 +1,19 @@
1
+ /** The `KEY → value` pairs in a secret file, by its format (dotenv, ini, JSON, netrc, …). */
2
+ export interface ParsedValue {
3
+ key: string;
4
+ /** The value as a program sees it. */
5
+ value: string;
6
+ /** The value as written in the file, when it differs (escapes inside double quotes). */
7
+ raw?: string;
8
+ /** The file format says the value is a secret (a `.netrc` password, a `.htpasswd` hash), whatever its key. */
9
+ secret?: true;
10
+ }
11
+ /** Parse dotenv text (`KEY=value`, `export KEY=…`, quoted and multi-line quoted values). */
12
+ export declare function parseDotenv(text: string): ParsedValue[];
13
+ /** The `KEY → value` pairs in one secret file, by its name. Unknown formats give `[]`. */
14
+ export declare function parseSecretFile(fileName: string, text: string): ParsedValue[];
15
+ /** The secret values among parsed pairs, named after their keys. URL passwords count on their own. */
16
+ export declare function secretValuesOf(pairs: readonly ParsedValue[]): {
17
+ name: string;
18
+ value: string;
19
+ }[];
@@ -0,0 +1,140 @@
1
+ /** The `KEY → value` pairs in a secret file, by its format (dotenv, ini, JSON, netrc, …). */
2
+ import { isEnvFileName } from '../secret-files';
3
+ import { isSecretEntry, isTrivial, urlPasswordOf } from './rules';
4
+ function unescapeDouble(s) {
5
+ return s.replace(/\\([nrt"\\$`])/g, (_m, c) => ({ n: '\n', r: '\r', t: '\t' })[c] ?? c);
6
+ }
7
+ /** Parse dotenv text (`KEY=value`, `export KEY=…`, quoted and multi-line quoted values). */
8
+ export function parseDotenv(text) {
9
+ const out = [];
10
+ const lines = text.split(/\r?\n/);
11
+ for (let i = 0; i < lines.length; i++) {
12
+ const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s?(.*)$/.exec(lines[i]);
13
+ if (!m)
14
+ continue;
15
+ const key = m[1];
16
+ let rest = m[2].trimStart();
17
+ const quote = rest[0];
18
+ if (quote === '"' || quote === "'" || quote === '`') {
19
+ rest = rest.slice(1);
20
+ let body = '';
21
+ let closed = false;
22
+ for (;;) {
23
+ let end = -1;
24
+ for (let k = 0; k < rest.length; k++) {
25
+ if (quote === '"' && rest[k] === '\\')
26
+ k++;
27
+ else if (rest[k] === quote) {
28
+ end = k;
29
+ break;
30
+ }
31
+ }
32
+ if (end >= 0) {
33
+ body += rest.slice(0, end);
34
+ closed = true;
35
+ break;
36
+ }
37
+ body += rest;
38
+ if (i + 1 >= lines.length)
39
+ break;
40
+ body += '\n';
41
+ rest = lines[++i];
42
+ }
43
+ if (!closed)
44
+ continue;
45
+ const value = quote === '"' ? unescapeDouble(body) : body;
46
+ out.push(value === body ? { key, value } : { key, value, raw: body });
47
+ continue;
48
+ }
49
+ const value = rest.replace(/\s+#.*$/, '').trim();
50
+ out.push({ key, value });
51
+ }
52
+ return out;
53
+ }
54
+ /** `key=value`, `key = value` and `key: value` lines (npmrc, pypirc, boto, aws credentials). */
55
+ function parseIni(text) {
56
+ const out = [];
57
+ for (const line of text.split(/\r?\n/)) {
58
+ if (/^\s*[#;[]/.test(line))
59
+ continue;
60
+ const m = /^\s*([^=:#\s][^=]*?)\s*[=:]\s*(.*?)\s*$/.exec(line);
61
+ if (!m)
62
+ continue;
63
+ out.push({ key: m[1], value: m[2].replace(/^(['"])(.*)\1$/, '$2') });
64
+ }
65
+ return out;
66
+ }
67
+ function walkJson(node, key, out, depth = 0) {
68
+ if (depth > 32)
69
+ return;
70
+ if (typeof node === 'string')
71
+ out.push({ key, value: node });
72
+ else if (Array.isArray(node))
73
+ node.forEach((item) => walkJson(item, key, out, depth + 1));
74
+ else if (node && typeof node === 'object') {
75
+ for (const [k, v] of Object.entries(node))
76
+ walkJson(v, k, out, depth + 1);
77
+ }
78
+ }
79
+ /** The `KEY → value` pairs in one secret file, by its name. Unknown formats give `[]`. */
80
+ export function parseSecretFile(fileName, text) {
81
+ const name = fileName.toLowerCase();
82
+ if (isEnvFileName(name))
83
+ return parseDotenv(text);
84
+ if (name.endsWith('.json') || name === '.dockercfg' || name.endsWith('.tfstate') || name.endsWith('.tfstate.backup')) {
85
+ try {
86
+ const out = [];
87
+ walkJson(JSON.parse(text), 'SECRET', out);
88
+ return out;
89
+ }
90
+ catch {
91
+ return [];
92
+ }
93
+ }
94
+ if (name === '.netrc') {
95
+ return [...text.matchAll(/\bpassword\s+(\S+)/g)].map((m) => ({ key: 'NETRC_PASSWORD', value: m[1], secret: true }));
96
+ }
97
+ if (name === '.pgpass') {
98
+ return text
99
+ .split(/\r?\n/)
100
+ .filter((l) => l && !l.startsWith('#'))
101
+ .map((l) => ({ key: 'PGPASSWORD', value: l.split(/(?<!\\):/).pop() ?? '', secret: true }));
102
+ }
103
+ if (name === '.htpasswd') {
104
+ return text
105
+ .split(/\r?\n/)
106
+ .filter((l) => l.includes(':'))
107
+ .map((l) => ({ key: 'HTPASSWD', value: l.slice(l.indexOf(':') + 1), secret: true }));
108
+ }
109
+ if (name === '.git-credentials') {
110
+ return [...text.matchAll(/:\/\/[^\s/:@]*:([^\s/@]+)@/g)].map((m) => ({ key: 'GIT_PASSWORD', value: m[1], secret: true }));
111
+ }
112
+ if (['.npmrc', '.pypirc', '.boto', '.s3cfg', 'credentials'].includes(name) || name.endsWith('.tfvars')) {
113
+ return parseIni(text);
114
+ }
115
+ return [];
116
+ }
117
+ /** The secret values among parsed pairs, named after their keys. URL passwords count on their own. */
118
+ export function secretValuesOf(pairs) {
119
+ const out = [];
120
+ for (const pair of pairs) {
121
+ if (pair.secret ? !isTrivial(pair.value) : isSecretEntry(pair.key, pair.value)) {
122
+ out.push({ name: pair.key, value: pair.value });
123
+ if (pair.raw)
124
+ out.push({ name: pair.key, value: pair.raw });
125
+ }
126
+ const pw = urlPasswordOf(pair.value);
127
+ if (pw && !isTrivial(pw)) {
128
+ out.push({ name: pair.key, value: pw });
129
+ try {
130
+ const decoded = decodeURIComponent(pw);
131
+ if (decoded !== pw && !isTrivial(decoded))
132
+ out.push({ name: pair.key, value: decoded });
133
+ }
134
+ catch {
135
+ // malformed percent-encoding: the raw form is already in
136
+ }
137
+ }
138
+ }
139
+ return out;
140
+ }
@@ -0,0 +1,8 @@
1
+ /** Redaction of a whole tool result: its content blocks and its details. */
2
+ import type { SecretVault } from './vault';
3
+ /** Replace every known secret value in the text blocks and in every string of `details`. */
4
+ export declare function redactToolResult(vault: SecretVault, content: readonly unknown[], details: unknown): {
5
+ content: unknown[];
6
+ details: unknown;
7
+ changed: boolean;
8
+ };