@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
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ /** Read the secret values out of the secret files in the workspace. */
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k;
5
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k]; } };
8
+ }
9
+ Object.defineProperty(o, k2, desc);
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ o[k2] = m[k];
13
+ }));
14
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
16
+ }) : function(o, v) {
17
+ o["default"] = v;
18
+ });
19
+ var __importStar = (this && this.__importStar) || (function () {
20
+ var ownKeys = function(o) {
21
+ ownKeys = Object.getOwnPropertyNames || function (o) {
22
+ var ar = [];
23
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
24
+ return ar;
25
+ };
26
+ return ownKeys(o);
27
+ };
28
+ return function (mod) {
29
+ if (mod && mod.__esModule) return mod;
30
+ var result = {};
31
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
32
+ __setModuleDefault(result, mod);
33
+ return result;
34
+ };
35
+ })();
36
+ Object.defineProperty(exports, "__esModule", { value: true });
37
+ exports.collectWorkspaceSecrets = collectWorkspaceSecrets;
38
+ const path = __importStar(require("node:path"));
39
+ const secret_files_1 = require("../secret-files");
40
+ const parse_1 = require("./parse");
41
+ /** Dirs never walked: dependencies, VCS data, and build output. */
42
+ const SKIP_DIRS = new Set(['node_modules', '.git', '.next', '.turbo', 'dist', 'build', 'coverage']);
43
+ const MAX_DEPTH = 4;
44
+ const MAX_FILE_BYTES = 256 * 1024;
45
+ const MAX_DIRS = 5000;
46
+ /**
47
+ * Read the secret files in the workspace dirs (the root and nested, to depth 4,
48
+ * skipping dependencies and build output, files up to 256 KB). Sibling dirs are
49
+ * walked in parallel, since a refresh runs after every tool that can write.
50
+ */
51
+ async function collectWorkspaceSecrets(dirs, fs) {
52
+ const result = { values: [], errors: [] };
53
+ const files = [];
54
+ let visited = 0;
55
+ const walk = async (dir, depth) => {
56
+ if (visited++ >= MAX_DIRS)
57
+ return;
58
+ let entries;
59
+ try {
60
+ entries = await fs.readDir(dir);
61
+ }
62
+ catch (error) {
63
+ if (depth === 0)
64
+ result.errors.push({ file: dir, error });
65
+ return;
66
+ }
67
+ const subdirs = [];
68
+ for (const entry of entries) {
69
+ const full = path.join(dir, entry.name);
70
+ if (entry.kind === 'dir') {
71
+ if (!SKIP_DIRS.has(entry.name) && depth + 1 < MAX_DEPTH)
72
+ subdirs.push(full);
73
+ }
74
+ else if ((entry.kind === 'file' || entry.kind === 'symlink') && (0, secret_files_1.isSecretFileName)(entry.name)) {
75
+ files.push(full);
76
+ }
77
+ }
78
+ await Promise.all(subdirs.map((sub) => walk(sub, depth + 1)));
79
+ };
80
+ await Promise.all(dirs.map((dir) => walk(dir, 0)));
81
+ await Promise.all(files.map(async (file) => {
82
+ try {
83
+ if ((await fs.size(file)) > MAX_FILE_BYTES)
84
+ return;
85
+ const text = await fs.readFile(file);
86
+ if (text.includes('\u0000'))
87
+ return;
88
+ for (const v of (0, parse_1.secretValuesOf)((0, parse_1.parseSecretFile)(path.basename(file), text)))
89
+ result.values.push({ ...v, file });
90
+ }
91
+ catch (error) {
92
+ result.errors.push({ file, error });
93
+ }
94
+ }));
95
+ return result;
96
+ }
@@ -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,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.UNNAMED_TOKEN = exports.SecretVault = exports.PLACEHOLDER_PATTERN = exports.findPlaceholders = exports.TOKEN_SHAPE_RES = exports.SECRET_KEY_PATTERN = exports.MIN_SECRET_LENGTH = exports.isSecretEntry = exports.redactToolResult = exports.secretValuesOf = exports.parseSecretFile = exports.parseDotenv = exports.collectWorkspaceSecrets = void 0;
4
+ var collect_1 = require("./collect");
5
+ Object.defineProperty(exports, "collectWorkspaceSecrets", { enumerable: true, get: function () { return collect_1.collectWorkspaceSecrets; } });
6
+ var parse_1 = require("./parse");
7
+ Object.defineProperty(exports, "parseDotenv", { enumerable: true, get: function () { return parse_1.parseDotenv; } });
8
+ Object.defineProperty(exports, "parseSecretFile", { enumerable: true, get: function () { return parse_1.parseSecretFile; } });
9
+ Object.defineProperty(exports, "secretValuesOf", { enumerable: true, get: function () { return parse_1.secretValuesOf; } });
10
+ var redact_result_1 = require("./redact-result");
11
+ Object.defineProperty(exports, "redactToolResult", { enumerable: true, get: function () { return redact_result_1.redactToolResult; } });
12
+ var rules_1 = require("./rules");
13
+ Object.defineProperty(exports, "isSecretEntry", { enumerable: true, get: function () { return rules_1.isSecretEntry; } });
14
+ Object.defineProperty(exports, "MIN_SECRET_LENGTH", { enumerable: true, get: function () { return rules_1.MIN_SECRET_LENGTH; } });
15
+ Object.defineProperty(exports, "SECRET_KEY_PATTERN", { enumerable: true, get: function () { return rules_1.SECRET_KEY_PATTERN; } });
16
+ Object.defineProperty(exports, "TOKEN_SHAPE_RES", { enumerable: true, get: function () { return rules_1.TOKEN_SHAPE_RES; } });
17
+ var vault_1 = require("./vault");
18
+ Object.defineProperty(exports, "findPlaceholders", { enumerable: true, get: function () { return vault_1.findPlaceholders; } });
19
+ Object.defineProperty(exports, "PLACEHOLDER_PATTERN", { enumerable: true, get: function () { return vault_1.PLACEHOLDER_PATTERN; } });
20
+ Object.defineProperty(exports, "SecretVault", { enumerable: true, get: function () { return vault_1.SecretVault; } });
21
+ Object.defineProperty(exports, "UNNAMED_TOKEN", { enumerable: true, get: function () { return vault_1.UNNAMED_TOKEN; } });
@@ -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,145 @@
1
+ "use strict";
2
+ /** The `KEY → value` pairs in a secret file, by its format (dotenv, ini, JSON, netrc, …). */
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.parseDotenv = parseDotenv;
5
+ exports.parseSecretFile = parseSecretFile;
6
+ exports.secretValuesOf = secretValuesOf;
7
+ const secret_files_1 = require("../secret-files");
8
+ const rules_1 = require("./rules");
9
+ function unescapeDouble(s) {
10
+ return s.replace(/\\([nrt"\\$`])/g, (_m, c) => ({ n: '\n', r: '\r', t: '\t' })[c] ?? c);
11
+ }
12
+ /** Parse dotenv text (`KEY=value`, `export KEY=…`, quoted and multi-line quoted values). */
13
+ function parseDotenv(text) {
14
+ const out = [];
15
+ const lines = text.split(/\r?\n/);
16
+ for (let i = 0; i < lines.length; i++) {
17
+ const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s?(.*)$/.exec(lines[i]);
18
+ if (!m)
19
+ continue;
20
+ const key = m[1];
21
+ let rest = m[2].trimStart();
22
+ const quote = rest[0];
23
+ if (quote === '"' || quote === "'" || quote === '`') {
24
+ rest = rest.slice(1);
25
+ let body = '';
26
+ let closed = false;
27
+ for (;;) {
28
+ let end = -1;
29
+ for (let k = 0; k < rest.length; k++) {
30
+ if (quote === '"' && rest[k] === '\\')
31
+ k++;
32
+ else if (rest[k] === quote) {
33
+ end = k;
34
+ break;
35
+ }
36
+ }
37
+ if (end >= 0) {
38
+ body += rest.slice(0, end);
39
+ closed = true;
40
+ break;
41
+ }
42
+ body += rest;
43
+ if (i + 1 >= lines.length)
44
+ break;
45
+ body += '\n';
46
+ rest = lines[++i];
47
+ }
48
+ if (!closed)
49
+ continue;
50
+ const value = quote === '"' ? unescapeDouble(body) : body;
51
+ out.push(value === body ? { key, value } : { key, value, raw: body });
52
+ continue;
53
+ }
54
+ const value = rest.replace(/\s+#.*$/, '').trim();
55
+ out.push({ key, value });
56
+ }
57
+ return out;
58
+ }
59
+ /** `key=value`, `key = value` and `key: value` lines (npmrc, pypirc, boto, aws credentials). */
60
+ function parseIni(text) {
61
+ const out = [];
62
+ for (const line of text.split(/\r?\n/)) {
63
+ if (/^\s*[#;[]/.test(line))
64
+ continue;
65
+ const m = /^\s*([^=:#\s][^=]*?)\s*[=:]\s*(.*?)\s*$/.exec(line);
66
+ if (!m)
67
+ continue;
68
+ out.push({ key: m[1], value: m[2].replace(/^(['"])(.*)\1$/, '$2') });
69
+ }
70
+ return out;
71
+ }
72
+ function walkJson(node, key, out, depth = 0) {
73
+ if (depth > 32)
74
+ return;
75
+ if (typeof node === 'string')
76
+ out.push({ key, value: node });
77
+ else if (Array.isArray(node))
78
+ node.forEach((item) => walkJson(item, key, out, depth + 1));
79
+ else if (node && typeof node === 'object') {
80
+ for (const [k, v] of Object.entries(node))
81
+ walkJson(v, k, out, depth + 1);
82
+ }
83
+ }
84
+ /** The `KEY → value` pairs in one secret file, by its name. Unknown formats give `[]`. */
85
+ function parseSecretFile(fileName, text) {
86
+ const name = fileName.toLowerCase();
87
+ if ((0, secret_files_1.isEnvFileName)(name))
88
+ return parseDotenv(text);
89
+ if (name.endsWith('.json') || name === '.dockercfg' || name.endsWith('.tfstate') || name.endsWith('.tfstate.backup')) {
90
+ try {
91
+ const out = [];
92
+ walkJson(JSON.parse(text), 'SECRET', out);
93
+ return out;
94
+ }
95
+ catch {
96
+ return [];
97
+ }
98
+ }
99
+ if (name === '.netrc') {
100
+ return [...text.matchAll(/\bpassword\s+(\S+)/g)].map((m) => ({ key: 'NETRC_PASSWORD', value: m[1], secret: true }));
101
+ }
102
+ if (name === '.pgpass') {
103
+ return text
104
+ .split(/\r?\n/)
105
+ .filter((l) => l && !l.startsWith('#'))
106
+ .map((l) => ({ key: 'PGPASSWORD', value: l.split(/(?<!\\):/).pop() ?? '', secret: true }));
107
+ }
108
+ if (name === '.htpasswd') {
109
+ return text
110
+ .split(/\r?\n/)
111
+ .filter((l) => l.includes(':'))
112
+ .map((l) => ({ key: 'HTPASSWD', value: l.slice(l.indexOf(':') + 1), secret: true }));
113
+ }
114
+ if (name === '.git-credentials') {
115
+ return [...text.matchAll(/:\/\/[^\s/:@]*:([^\s/@]+)@/g)].map((m) => ({ key: 'GIT_PASSWORD', value: m[1], secret: true }));
116
+ }
117
+ if (['.npmrc', '.pypirc', '.boto', '.s3cfg', 'credentials'].includes(name) || name.endsWith('.tfvars')) {
118
+ return parseIni(text);
119
+ }
120
+ return [];
121
+ }
122
+ /** The secret values among parsed pairs, named after their keys. URL passwords count on their own. */
123
+ function secretValuesOf(pairs) {
124
+ const out = [];
125
+ for (const pair of pairs) {
126
+ if (pair.secret ? !(0, rules_1.isTrivial)(pair.value) : (0, rules_1.isSecretEntry)(pair.key, pair.value)) {
127
+ out.push({ name: pair.key, value: pair.value });
128
+ if (pair.raw)
129
+ out.push({ name: pair.key, value: pair.raw });
130
+ }
131
+ const pw = (0, rules_1.urlPasswordOf)(pair.value);
132
+ if (pw && !(0, rules_1.isTrivial)(pw)) {
133
+ out.push({ name: pair.key, value: pw });
134
+ try {
135
+ const decoded = decodeURIComponent(pw);
136
+ if (decoded !== pw && !(0, rules_1.isTrivial)(decoded))
137
+ out.push({ name: pair.key, value: decoded });
138
+ }
139
+ catch {
140
+ // malformed percent-encoding: the raw form is already in
141
+ }
142
+ }
143
+ }
144
+ return out;
145
+ }
@@ -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
+ };
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ /** Redaction of a whole tool result: its content blocks and its details. */
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.redactToolResult = redactToolResult;
5
+ function isTextBlock(block) {
6
+ const b = block;
7
+ return Boolean(b) && typeof b === 'object' && b.type === 'text' && typeof b.text === 'string';
8
+ }
9
+ /**
10
+ * Join a run of adjacent text blocks into one when a secret value runs across
11
+ * the boundary between two of them, so it is redacted whole.
12
+ */
13
+ function joinSplitSecrets(content, vault) {
14
+ const out = [];
15
+ let run = [];
16
+ const flush = () => {
17
+ const texts = run.map((b) => b.text);
18
+ if (run.length > 1 && vault.crossesBoundary(texts))
19
+ out.push({ ...run[0], text: texts.join('') });
20
+ else
21
+ out.push(...run);
22
+ run = [];
23
+ };
24
+ for (const block of content) {
25
+ if (isTextBlock(block)) {
26
+ run.push(block);
27
+ }
28
+ else {
29
+ flush();
30
+ out.push(block);
31
+ }
32
+ }
33
+ flush();
34
+ return out;
35
+ }
36
+ /** Redact every string inside a value, copying containers. Cycles keep their shape. */
37
+ function redactDeep(value, text, seen = new WeakMap()) {
38
+ if (typeof value === 'string')
39
+ return text(value);
40
+ if (!value || typeof value !== 'object')
41
+ return value;
42
+ if (seen.has(value))
43
+ return seen.get(value);
44
+ if (Array.isArray(value)) {
45
+ const out = [];
46
+ seen.set(value, out);
47
+ for (const item of value)
48
+ out.push(redactDeep(item, text, seen));
49
+ return out;
50
+ }
51
+ if (value instanceof Uint8Array || value instanceof Date)
52
+ return value;
53
+ const out = {};
54
+ seen.set(value, out);
55
+ for (const [k, v] of Object.entries(value))
56
+ out[k] = redactDeep(v, text, seen);
57
+ return out;
58
+ }
59
+ /** Replace every known secret value in the text blocks and in every string of `details`. */
60
+ function redactToolResult(vault, content, details) {
61
+ let changed = false;
62
+ const text = (s) => {
63
+ const out = vault.redact(s);
64
+ if (out.changed)
65
+ changed = true;
66
+ return out.text;
67
+ };
68
+ const redacted = joinSplitSecrets(content, vault).map((block) => (isTextBlock(block) ? { ...block, text: text(block.text) } : block));
69
+ return { content: redacted, details: details === undefined ? undefined : redactDeep(details, text), changed };
70
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Which values are secret: the key-name rule, the vendor token shapes, and the
3
+ * local-dev defaults that are not worth hiding.
4
+ */
5
+ export declare const MIN_SECRET_LENGTH = 8;
6
+ /** Env keys whose values are secret. `DATABASE_ID`, `OWNER_ID` do not match. */
7
+ export declare const SECRET_KEY_PATTERN: RegExp;
8
+ /**
9
+ * Vendor token shapes (oh-my-pi `secrets/patterns.ts`). Group 1, when present,
10
+ * is the secret part. `hints`: lowercase text one of which every match holds,
11
+ * so a scan skips a shape whose hints are not in the text.
12
+ */
13
+ export declare const TOKEN_SHAPES: readonly {
14
+ name: string;
15
+ source: string;
16
+ flags?: string;
17
+ hints: readonly string[];
18
+ }[];
19
+ /** The shapes compiled once, to test a whole value. */
20
+ export declare const TOKEN_SHAPE_RES: readonly {
21
+ name: string;
22
+ re: RegExp;
23
+ }[];
24
+ /** The shapes compiled once to scan a text. `matchAll` copies a global regex, so no `lastIndex` state leaks. */
25
+ export declare const TOKEN_SHAPE_SCANNERS: readonly {
26
+ name: string;
27
+ re: RegExp;
28
+ hints: readonly string[];
29
+ }[];
30
+ /** The password of a URL value, if it has one. */
31
+ export declare function urlPasswordOf(value: string): string | undefined;
32
+ export declare function isTrivial(value: string): boolean;
33
+ /** The vault rule for one `KEY=value` pair. */
34
+ export declare function isSecretEntry(key: string, value: string): boolean;
@@ -0,0 +1,107 @@
1
+ "use strict";
2
+ /**
3
+ * Which values are secret: the key-name rule, the vendor token shapes, and the
4
+ * local-dev defaults that are not worth hiding.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.TOKEN_SHAPE_SCANNERS = exports.TOKEN_SHAPE_RES = exports.TOKEN_SHAPES = exports.SECRET_KEY_PATTERN = exports.MIN_SECRET_LENGTH = void 0;
8
+ exports.urlPasswordOf = urlPasswordOf;
9
+ exports.isTrivial = isTrivial;
10
+ exports.isSecretEntry = isSecretEntry;
11
+ exports.MIN_SECRET_LENGTH = 8;
12
+ /** Env keys whose values are secret. `DATABASE_ID`, `OWNER_ID` do not match. */
13
+ exports.SECRET_KEY_PATTERN = /(KEY|SECRET|TOKEN|PASSWORD|PASS|AUTH|CREDENTIAL|PRIVATE|DSN|DATABASE_URL)(_|$)/i;
14
+ const B = '(?<![A-Za-z0-9_-])';
15
+ const E = '(?![A-Za-z0-9_-])';
16
+ /**
17
+ * Vendor token shapes (oh-my-pi `secrets/patterns.ts`). Group 1, when present,
18
+ * is the secret part. `hints`: lowercase text one of which every match holds,
19
+ * so a scan skips a shape whose hints are not in the text.
20
+ */
21
+ exports.TOKEN_SHAPES = [
22
+ {
23
+ name: 'Credential',
24
+ source: '(?<![a-zA-Z0-9_*-])(gh[opusr]_[a-zA-Z0-9_]{36,}|github_pat_[a-zA-Z0-9_]{36,}|glpat-[a-zA-Z0-9_-]{20,}|sk-proj-[a-zA-Z0-9_-]{36,}|sk-ant-[a-zA-Z0-9_-]{36,}|sk-[a-zA-Z0-9_-]{48,})(?![a-zA-Z0-9_*-])',
25
+ hints: ['gh', 'glpat-', 'sk-']
26
+ },
27
+ { name: 'AWSAccessKey', source: `${B}(?:AKIA|ASIA)[A-Z0-9]{16}${E}`, hints: ['akia', 'asia'] },
28
+ { name: 'GoogleAPIKey', source: `${B}AIza[A-Za-z0-9_-]{30,}${E}`, hints: ['aiza'] },
29
+ { name: 'SlackToken', source: `${B}xox[abprs]-[A-Za-z0-9-]{10,}${E}`, hints: ['xox'] },
30
+ { name: 'NpmToken', source: `${B}npm_[A-Za-z0-9]{30,}${E}`, hints: ['npm_'] },
31
+ { name: 'StripeKey', source: `${B}(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{20,}${E}`, hints: ['_live_', '_test_'] },
32
+ { name: 'StripeWebhookSecret', source: `${B}whsec_[A-Za-z0-9]{20,}${E}`, hints: ['whsec_'] },
33
+ { name: 'HuggingFaceToken', source: `${B}hf_[A-Za-z0-9]{30,}${E}`, hints: ['hf_'] },
34
+ { name: 'SendGridKey', source: `${B}SG\\.[A-Za-z0-9_-]{22}\\.[A-Za-z0-9_-]{43}${E}`, hints: ['sg.'] },
35
+ { name: 'JWT', source: `${B}eyJ[A-Za-z0-9_-]{10,}\\.eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}${E}`, hints: ['eyj'] },
36
+ { name: 'BearerToken', source: '\\bBearer ([A-Za-z0-9._~+/=-]{20,})(?![A-Za-z0-9_-])', flags: 'i', hints: ['bearer '] },
37
+ {
38
+ name: 'PrivateKey',
39
+ source: '-----BEGIN [A-Z ]*PRIVATE KEY-----[\\s\\S]*?-----END [A-Z ]*PRIVATE KEY-----',
40
+ hints: ['-----begin']
41
+ },
42
+ { name: 'UrlPassword', source: '\\b[a-z][a-z0-9+.-]*://[^\\s/:@?#]*:([^\\s/@?#]+)@', flags: 'i', hints: ['://'] }
43
+ ];
44
+ /** The shapes compiled once, to test a whole value. */
45
+ exports.TOKEN_SHAPE_RES = exports.TOKEN_SHAPES.map((shape) => ({
46
+ name: shape.name,
47
+ re: new RegExp(shape.source, shape.flags)
48
+ }));
49
+ /** The shapes compiled once to scan a text. `matchAll` copies a global regex, so no `lastIndex` state leaks. */
50
+ exports.TOKEN_SHAPE_SCANNERS = exports.TOKEN_SHAPES.map((shape) => ({ name: shape.name, re: new RegExp(shape.source, `${shape.flags ?? ''}g`), hints: shape.hints }));
51
+ /** A value that is a URL with a password (`postgres://app:pw@host`); group 1 is the password. */
52
+ const URL_WITH_PASSWORD = /^[a-z][a-z0-9+.-]*:\/\/[^\s/:@?#]*:([^\s/@?#]+)@/i;
53
+ /** The password of a URL value, if it has one. */
54
+ function urlPasswordOf(value) {
55
+ return URL_WITH_PASSWORD.exec(value)?.[1];
56
+ }
57
+ /** Common local-dev defaults: redacting them would garble ordinary source text. */
58
+ const TRIVIAL_VALUES = new Set([
59
+ 'password',
60
+ 'postgres',
61
+ 'changeme',
62
+ 'change_me',
63
+ 'change-me',
64
+ 'development',
65
+ 'production',
66
+ 'localhost',
67
+ 'undefined',
68
+ 'placeholder',
69
+ 'username',
70
+ 'example',
71
+ 'testtest',
72
+ 'password1',
73
+ 'secret123',
74
+ 'mysecret',
75
+ 'supersecret'
76
+ ]);
77
+ function isTrivial(value) {
78
+ const v = value.trim();
79
+ if (v.length < exports.MIN_SECRET_LENGTH)
80
+ return true;
81
+ if (TRIVIAL_VALUES.has(v.toLowerCase()))
82
+ return true;
83
+ if (/^(.)\1*$/.test(v))
84
+ return true;
85
+ if (/^\$\{[^}]*\}$|^<[^>]*>$|^your[-_]/i.test(v))
86
+ return true;
87
+ if (/^(true|false|\d+)$/i.test(v))
88
+ return true;
89
+ return false;
90
+ }
91
+ function matchesTokenShape(value) {
92
+ return exports.TOKEN_SHAPE_RES.some(({ name, re }) => name !== 'UrlPassword' && re.test(value));
93
+ }
94
+ /** A URL with no password in it is an address, not a secret. */
95
+ function isPlainUrl(value) {
96
+ return /^[a-z][a-z0-9+.-]*:\/\//i.test(value) && urlPasswordOf(value) === undefined;
97
+ }
98
+ /** The vault rule for one `KEY=value` pair. */
99
+ function isSecretEntry(key, value) {
100
+ if (value.trim().length < exports.MIN_SECRET_LENGTH)
101
+ return false;
102
+ if (matchesTokenShape(value))
103
+ return true;
104
+ if (!exports.SECRET_KEY_PATTERN.test(key))
105
+ return false;
106
+ return !isTrivial(value) && !isPlainUrl(value);
107
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * The secret vault: the values the model must never see, and the placeholders
3
+ * it sees instead.
4
+ *
5
+ * A value is replaced by `«secret:NAME#h4»`, where `h4` is the first 4 hex
6
+ * chars of HMAC-SHA256(key, value). The key is per install (or per engine), so
7
+ * a placeholder says which secret it stands for without revealing anything
8
+ * about the value. Restoring maps a placeholder back to its value; the engine
9
+ * only does that where it is safe (writes to secret files, approved commands).
10
+ */
11
+ export declare const PLACEHOLDER_PATTERN: RegExp;
12
+ /** The name used for a token-shaped value found in text with no name of its own. */
13
+ export declare const UNNAMED_TOKEN = "TOKEN";
14
+ export type SecretOrigin = 'file' | 'host' | 'token';
15
+ export declare class SecretVault {
16
+ private readonly key;
17
+ private readonly byValue;
18
+ private readonly byPlaceholder;
19
+ private readonly origin;
20
+ private sorted;
21
+ constructor(key: string);
22
+ get size(): number;
23
+ /** Register a value. The first name a value gets is the one it keeps. */
24
+ add(name: string, value: string, origin?: SecretOrigin): string;
25
+ /** Drop the values from one origin (before re-reading the files). */
26
+ clear(origin: SecretOrigin): void;
27
+ private entries;
28
+ /** Learn token-shaped values in `text` that no source named. */
29
+ private discover;
30
+ /** Replace every known value, longest first, with its placeholder. */
31
+ redact(text: string): {
32
+ text: string;
33
+ changed: boolean;
34
+ };
35
+ /**
36
+ * A known value runs across the boundary between two of `parts` (adjacent
37
+ * text blocks), so redacting each part alone would leave both halves.
38
+ */
39
+ crossesBoundary(parts: readonly string[]): boolean;
40
+ /** Put real values back for known placeholders. Unknown placeholders stay. */
41
+ restore(text: string): string;
42
+ /** The secret a text carries: a known value or a placeholder. */
43
+ findSecret(text: string): {
44
+ name: string;
45
+ kind: 'value' | 'placeholder';
46
+ } | null;
47
+ }
48
+ export declare function findPlaceholders(text: string): string[];