@amaster.ai/pi-shared 0.1.2-beta.10 → 0.1.2-beta.100
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/__tests__/models.test.d.ts +2 -0
- package/dist/__tests__/models.test.d.ts.map +1 -0
- package/dist/__tests__/models.test.js +68 -0
- package/dist/__tests__/models.test.js.map +1 -0
- package/dist/__tests__/network-transport.test.d.ts +2 -0
- package/dist/__tests__/network-transport.test.d.ts.map +1 -0
- package/dist/__tests__/network-transport.test.js +68 -0
- package/dist/__tests__/network-transport.test.js.map +1 -0
- package/dist/__tests__/network.test.d.ts +2 -0
- package/dist/__tests__/network.test.d.ts.map +1 -0
- package/dist/__tests__/network.test.js +174 -0
- package/dist/__tests__/network.test.js.map +1 -0
- package/dist/__tests__/office-cli.test.d.ts +2 -0
- package/dist/__tests__/office-cli.test.d.ts.map +1 -0
- package/dist/__tests__/office-cli.test.js +473 -0
- package/dist/__tests__/office-cli.test.js.map +1 -0
- package/dist/__tests__/policy-profiles-async.test.d.ts +2 -0
- package/dist/__tests__/policy-profiles-async.test.d.ts.map +1 -0
- package/dist/__tests__/policy-profiles-async.test.js +79 -0
- package/dist/__tests__/policy-profiles-async.test.js.map +1 -0
- package/dist/__tests__/settings-async.test.d.ts +2 -0
- package/dist/__tests__/settings-async.test.d.ts.map +1 -0
- package/dist/__tests__/settings-async.test.js +52 -0
- package/dist/__tests__/settings-async.test.js.map +1 -0
- package/dist/__tests__/settings.test.js +139 -31
- package/dist/__tests__/settings.test.js.map +1 -1
- package/dist/__tests__/tool-errors.test.d.ts +2 -0
- package/dist/__tests__/tool-errors.test.d.ts.map +1 -0
- package/dist/__tests__/tool-errors.test.js +250 -0
- package/dist/__tests__/tool-errors.test.js.map +1 -0
- package/dist/__tests__/tool-output.test.d.ts +2 -0
- package/dist/__tests__/tool-output.test.d.ts.map +1 -0
- package/dist/__tests__/tool-output.test.js +37 -0
- package/dist/__tests__/tool-output.test.js.map +1 -0
- package/dist/index.d.ts +29 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/models.d.ts +18 -0
- package/dist/models.d.ts.map +1 -0
- package/dist/models.js +23 -0
- package/dist/models.js.map +1 -0
- package/dist/network.d.ts +40 -0
- package/dist/network.d.ts.map +1 -0
- package/dist/network.js +322 -0
- package/dist/network.js.map +1 -0
- package/dist/office-cli.d.ts +13 -0
- package/dist/office-cli.d.ts.map +1 -0
- package/dist/office-cli.js +475 -0
- package/dist/office-cli.js.map +1 -0
- package/dist/settings.d.ts +31 -2
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js +182 -25
- package/dist/settings.js.map +1 -1
- package/dist/threat-patterns.d.ts +34 -0
- package/dist/threat-patterns.d.ts.map +1 -0
- package/dist/threat-patterns.js +211 -0
- package/dist/threat-patterns.js.map +1 -0
- package/dist/tool-errors.d.ts +130 -0
- package/dist/tool-errors.d.ts.map +1 -0
- package/dist/tool-errors.js +351 -0
- package/dist/tool-errors.js.map +1 -0
- package/dist/tool-output.d.ts +10 -0
- package/dist/tool-output.d.ts.map +1 -0
- package/dist/tool-output.js +45 -0
- package/dist/tool-output.js.map +1 -0
- package/package.json +23 -2
package/dist/settings.js
CHANGED
|
@@ -1,9 +1,16 @@
|
|
|
1
|
-
import { readdirSync, readFileSync } from 'node:fs';
|
|
1
|
+
import { constants, readdirSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { open, opendir } from 'node:fs/promises';
|
|
2
3
|
import { homedir } from 'node:os';
|
|
3
4
|
import { basename, join, resolve } from 'node:path';
|
|
4
|
-
|
|
5
|
+
import { ValidationError } from './tool-errors.js';
|
|
6
|
+
export function isProjectTrusted(context) {
|
|
7
|
+
return context?.isProjectTrusted?.() === true;
|
|
8
|
+
}
|
|
9
|
+
function resolveEnvVars(value, expandBareEnvVars) {
|
|
5
10
|
if (typeof value === 'string') {
|
|
6
|
-
|
|
11
|
+
const pattern = expandBareEnvVars ? /\$\{([^}]+)\}|\$([A-Z_][A-Z0-9_]*)/g : /\$\{([^}]+)\}/g;
|
|
12
|
+
return value.replace(pattern, (_match, braced, bare) => {
|
|
13
|
+
const expr = braced ?? bare ?? '';
|
|
7
14
|
const [name, ...rest] = expr.split(':-');
|
|
8
15
|
const fallback = rest.join(':-');
|
|
9
16
|
const envVal = process.env[name];
|
|
@@ -13,48 +20,88 @@ function resolveEnvVars(value) {
|
|
|
13
20
|
});
|
|
14
21
|
}
|
|
15
22
|
if (Array.isArray(value)) {
|
|
16
|
-
return value.map(resolveEnvVars);
|
|
23
|
+
return value.map((item) => resolveEnvVars(item, expandBareEnvVars));
|
|
17
24
|
}
|
|
18
25
|
if (value && typeof value === 'object') {
|
|
19
26
|
const result = {};
|
|
20
27
|
for (const [k, v] of Object.entries(value)) {
|
|
21
|
-
result[k] = resolveEnvVars(v);
|
|
28
|
+
result[k] = resolveEnvVars(v, expandBareEnvVars);
|
|
22
29
|
}
|
|
23
30
|
return result;
|
|
24
31
|
}
|
|
25
32
|
return value;
|
|
26
33
|
}
|
|
27
|
-
function readSettingsSection(filePath, key) {
|
|
34
|
+
function readSettingsSection(filePath, key, options) {
|
|
28
35
|
try {
|
|
29
36
|
const raw = readFileSync(filePath, 'utf-8');
|
|
30
37
|
const parsed = JSON.parse(raw);
|
|
31
38
|
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
32
|
-
|
|
39
|
+
const section = parsed[key] === undefined ? {} : parsed[key];
|
|
40
|
+
if (!section || typeof section !== 'object' || Array.isArray(section)) {
|
|
41
|
+
throw new Error('Settings section must be an object');
|
|
42
|
+
}
|
|
43
|
+
return (options.expandEnv ? resolveEnvVars(section, options.expandBareEnvVars) : section);
|
|
33
44
|
}
|
|
34
|
-
|
|
45
|
+
throw new Error('Settings root must be an object');
|
|
35
46
|
}
|
|
36
|
-
catch {
|
|
37
|
-
|
|
47
|
+
catch (error) {
|
|
48
|
+
if (error.code === 'ENOENT')
|
|
49
|
+
return {};
|
|
50
|
+
throw new ValidationError(options.strict
|
|
51
|
+
? 'Trusted project settings are unreadable or malformed. Fix settings.json before retrying.'
|
|
52
|
+
: 'Settings are unreadable or malformed. Fix settings.json before retrying; defaults were not substituted.', 'configuration_error');
|
|
38
53
|
}
|
|
39
54
|
}
|
|
40
|
-
|
|
55
|
+
/**
|
|
56
|
+
* Resolve the user data / runtime home directory.
|
|
57
|
+
* Used for: memories, data, skills, logs.
|
|
58
|
+
*/
|
|
59
|
+
export function resolveHome(override) {
|
|
41
60
|
return resolve(override ?? process.env.PI_AGENT_HOME ?? join(homedir(), '.pi', 'agent'));
|
|
42
61
|
}
|
|
62
|
+
/**
|
|
63
|
+
* Resolve the system config directory.
|
|
64
|
+
* Used for: settings.json, policy, auth, models.
|
|
65
|
+
*/
|
|
66
|
+
export function resolveConfigDir(override) {
|
|
67
|
+
return resolve(override ??
|
|
68
|
+
process.env.PI_CODING_AGENT_DIR ??
|
|
69
|
+
process.env.PI_AGENT_HOME ??
|
|
70
|
+
join(homedir(), '.pi', 'agent'));
|
|
71
|
+
}
|
|
72
|
+
/** @deprecated Use resolveHome() or resolveConfigDir() instead. */
|
|
73
|
+
export function resolveAgentDir(override) {
|
|
74
|
+
return resolveHome(override);
|
|
75
|
+
}
|
|
43
76
|
/**
|
|
44
77
|
* Load extension config from pi-agent settings files.
|
|
45
|
-
* Reads from global (~/.pi/agent/settings.json), agentDir (env/param), and project
|
|
78
|
+
* Reads from global (~/.pi/agent/settings.json), agentDir (env/param), and trusted project
|
|
79
|
+
* (<cwd>/.pi/settings.json) settings.
|
|
46
80
|
* Priority from low to high: global < agentDir < project.
|
|
81
|
+
* Environment variables are expanded only in the global and agentDir layers.
|
|
47
82
|
*/
|
|
48
83
|
export function loadPiSettings(key, options) {
|
|
49
84
|
const globalDir = resolve(join(homedir(), '.pi', 'agent'));
|
|
50
|
-
const
|
|
85
|
+
const configDir = resolveConfigDir(options?.configDir);
|
|
51
86
|
const cwd = options?.cwd ?? process.cwd();
|
|
52
|
-
const globalSettings = readSettingsSection(join(globalDir, 'settings.json'), key
|
|
53
|
-
|
|
87
|
+
const globalSettings = readSettingsSection(join(globalDir, 'settings.json'), key, {
|
|
88
|
+
expandEnv: true,
|
|
89
|
+
expandBareEnvVars: options?.expandBareEnvVars !== false,
|
|
90
|
+
});
|
|
91
|
+
const configSettings = configDir === globalDir
|
|
54
92
|
? {}
|
|
55
|
-
: readSettingsSection(join(
|
|
56
|
-
|
|
57
|
-
|
|
93
|
+
: readSettingsSection(join(configDir, 'settings.json'), key, {
|
|
94
|
+
expandEnv: true,
|
|
95
|
+
expandBareEnvVars: options?.expandBareEnvVars !== false,
|
|
96
|
+
});
|
|
97
|
+
const projectSettings = options?.projectTrusted === true
|
|
98
|
+
? readSettingsSection(join(cwd, '.pi', 'settings.json'), key, {
|
|
99
|
+
expandEnv: false,
|
|
100
|
+
expandBareEnvVars: false,
|
|
101
|
+
strict: options?.strictProjectSettings === true,
|
|
102
|
+
})
|
|
103
|
+
: {};
|
|
104
|
+
return { ...globalSettings, ...configSettings, ...projectSettings };
|
|
58
105
|
}
|
|
59
106
|
export function loadJsonProfileDir(dir) {
|
|
60
107
|
const result = {};
|
|
@@ -82,13 +129,123 @@ export function loadJsonProfileDir(dir) {
|
|
|
82
129
|
}
|
|
83
130
|
return result;
|
|
84
131
|
}
|
|
132
|
+
function configurationLayers(options) {
|
|
133
|
+
const global = resolve(join(homedir(), '.pi', 'agent'));
|
|
134
|
+
const config = resolveConfigDir(options?.configDir);
|
|
135
|
+
return [
|
|
136
|
+
{ dir: global, project: false },
|
|
137
|
+
...(config === global ? [] : [{ dir: config, project: false }]),
|
|
138
|
+
...(options?.projectTrusted === true
|
|
139
|
+
? [{ dir: resolve(join(options.cwd ?? process.cwd(), '.pi')), project: true }]
|
|
140
|
+
: []),
|
|
141
|
+
];
|
|
142
|
+
}
|
|
85
143
|
export function loadPiPolicyProfiles(options) {
|
|
86
|
-
|
|
87
|
-
const
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
144
|
+
let result = {};
|
|
145
|
+
for (const { dir } of configurationLayers(options))
|
|
146
|
+
result = { ...result, ...loadJsonProfileDir(join(dir, 'policy')) };
|
|
147
|
+
return result;
|
|
148
|
+
}
|
|
149
|
+
const MAX_CONFIG_FILE_BYTES = 128 * 1024;
|
|
150
|
+
const MAX_SETTINGS_FILE_BYTES = 1024 * 1024;
|
|
151
|
+
const MAX_POLICY_BYTES = 2 * 1024 * 1024;
|
|
152
|
+
const MAX_POLICY_FILES = 128;
|
|
153
|
+
const MAX_POLICY_ENTRIES = 1024;
|
|
154
|
+
async function readBoundedConfig(path, maxBytes, signal) {
|
|
155
|
+
signal?.throwIfAborted();
|
|
156
|
+
const handle = await open(path, constants.O_RDONLY | constants.O_NONBLOCK);
|
|
157
|
+
try {
|
|
158
|
+
signal?.throwIfAborted();
|
|
159
|
+
const metadata = await handle.stat();
|
|
160
|
+
signal?.throwIfAborted();
|
|
161
|
+
if (!metadata.isFile() || metadata.size > maxBytes)
|
|
162
|
+
throw new Error('Configuration file size limit exceeded.');
|
|
163
|
+
const buffer = Buffer.alloc(metadata.size + 1);
|
|
164
|
+
let bytes = 0;
|
|
165
|
+
while (bytes < buffer.length) {
|
|
166
|
+
signal?.throwIfAborted();
|
|
167
|
+
const result = await handle.read(buffer, bytes, buffer.length - bytes, null);
|
|
168
|
+
signal?.throwIfAborted();
|
|
169
|
+
if (!result.bytesRead)
|
|
170
|
+
break;
|
|
171
|
+
bytes += result.bytesRead;
|
|
172
|
+
}
|
|
173
|
+
if (bytes > metadata.size)
|
|
174
|
+
throw new Error('Configuration file changed while reading; size limit cannot be verified.');
|
|
175
|
+
return { parsed: JSON.parse(buffer.subarray(0, bytes).toString('utf8')), bytes };
|
|
176
|
+
}
|
|
177
|
+
finally {
|
|
178
|
+
await handle.close();
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
/** Fresh, bounded settings for authorization; malformed configuration rejects the decision. */
|
|
182
|
+
export async function loadPiSettingsAsync(key, options) {
|
|
183
|
+
let result = {};
|
|
184
|
+
for (const { dir, project } of configurationLayers(options)) {
|
|
185
|
+
options?.signal?.throwIfAborted();
|
|
186
|
+
try {
|
|
187
|
+
const { parsed } = await readBoundedConfig(join(dir, 'settings.json'), MAX_SETTINGS_FILE_BYTES, options?.signal);
|
|
188
|
+
options?.signal?.throwIfAborted();
|
|
189
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
190
|
+
throw new Error('Settings root must be an object.');
|
|
191
|
+
const section = parsed[key] === undefined ? {} : parsed[key];
|
|
192
|
+
if (!section || typeof section !== 'object' || Array.isArray(section))
|
|
193
|
+
throw new Error('Settings section must be an object.');
|
|
194
|
+
result = {
|
|
195
|
+
...result,
|
|
196
|
+
...(project
|
|
197
|
+
? section
|
|
198
|
+
: resolveEnvVars(section, options?.expandBareEnvVars !== false)),
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
catch (error) {
|
|
202
|
+
options?.signal?.throwIfAborted();
|
|
203
|
+
if (error.code !== 'ENOENT')
|
|
204
|
+
throw error;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
options?.signal?.throwIfAborted();
|
|
208
|
+
return result;
|
|
209
|
+
}
|
|
210
|
+
/** Read fresh policies with bounded directory traversal and allocation; failures must block authorization. */
|
|
211
|
+
export async function loadPiPolicyProfilesAsync(options) {
|
|
212
|
+
const result = {};
|
|
213
|
+
let entries = 0;
|
|
214
|
+
let files = 0;
|
|
215
|
+
let bytes = 0;
|
|
216
|
+
for (const { dir } of configurationLayers(options)) {
|
|
217
|
+
options?.signal?.throwIfAborted();
|
|
218
|
+
let directory;
|
|
219
|
+
try {
|
|
220
|
+
directory = await opendir(join(dir, 'policy'));
|
|
221
|
+
}
|
|
222
|
+
catch (error) {
|
|
223
|
+
options?.signal?.throwIfAborted();
|
|
224
|
+
if (error.code === 'ENOENT')
|
|
225
|
+
continue;
|
|
226
|
+
throw error;
|
|
227
|
+
}
|
|
228
|
+
if (options?.signal?.aborted) {
|
|
229
|
+
await directory.close();
|
|
230
|
+
options.signal.throwIfAborted();
|
|
231
|
+
}
|
|
232
|
+
for await (const entry of directory) {
|
|
233
|
+
options?.signal?.throwIfAborted();
|
|
234
|
+
if (++entries > MAX_POLICY_ENTRIES)
|
|
235
|
+
throw new Error('Policy directory entry limit exceeded.');
|
|
236
|
+
if (!entry.name.endsWith('.json'))
|
|
237
|
+
continue;
|
|
238
|
+
if (++files > MAX_POLICY_FILES)
|
|
239
|
+
throw new Error('Policy file count limit exceeded.');
|
|
240
|
+
const value = await readBoundedConfig(join(dir, 'policy', entry.name), Math.min(MAX_CONFIG_FILE_BYTES, MAX_POLICY_BYTES - bytes), options?.signal);
|
|
241
|
+
options?.signal?.throwIfAborted();
|
|
242
|
+
bytes += value.bytes;
|
|
243
|
+
if (!value.parsed || typeof value.parsed !== 'object' || Array.isArray(value.parsed))
|
|
244
|
+
throw new Error('Policy profile must be an object.');
|
|
245
|
+
result[basename(entry.name, '.json')] = value.parsed;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
options?.signal?.throwIfAborted();
|
|
249
|
+
return result;
|
|
93
250
|
}
|
|
94
251
|
//# sourceMappingURL=settings.js.map
|
package/dist/settings.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"settings.js","sourceRoot":"","sources":["../src/settings.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;
|
|
1
|
+
{"version":3,"file":"settings.js","sourceRoot":"","sources":["../src/settings.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAC/D,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;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, C2 framework names, exfiltration,
|
|
5
|
+
* persistence (SSH backdoor, agent-config edits), and invisible unicode.
|
|
6
|
+
*
|
|
7
|
+
* Pattern philosophy: anchor on attack-specific vocabulary or unambiguous
|
|
8
|
+
* attack behavior, NOT on bossy English. Multi-word filler is allowed via
|
|
9
|
+
* `(?:\w+\s+)*` between key tokens so attackers can't bypass with
|
|
10
|
+
* synonyms ("ignore all prior instructions").
|
|
11
|
+
*/
|
|
12
|
+
type Scope = 'all' | 'context' | 'strict';
|
|
13
|
+
/**
|
|
14
|
+
* Invisible / bidirectional unicode characters used in injection attacks.
|
|
15
|
+
*/
|
|
16
|
+
export declare const INVISIBLE_CHARS: ReadonlySet<string>;
|
|
17
|
+
/**
|
|
18
|
+
* Return matched pattern IDs in `content` at the given scope.
|
|
19
|
+
*
|
|
20
|
+
* - `all`: classic injection + exfil only (lowest false-positive set).
|
|
21
|
+
* - `context`: adds promptware / C2 / role-play patterns.
|
|
22
|
+
* - `strict`: adds persistence / SSH backdoor / exfil-URL patterns.
|
|
23
|
+
*
|
|
24
|
+
* Invisible-unicode hits are reported as `invisible_unicode_U+XXXX`.
|
|
25
|
+
*/
|
|
26
|
+
export declare function scanForThreats(content: string, scope?: Scope): string[];
|
|
27
|
+
/**
|
|
28
|
+
* Return a human-readable error string for the first threat in `content`,
|
|
29
|
+
* or `null` when clean. Convenience wrapper for paths that block on first
|
|
30
|
+
* hit (memory writes).
|
|
31
|
+
*/
|
|
32
|
+
export declare function firstThreatMessage(content: string, scope?: Scope): string | null;
|
|
33
|
+
export {};
|
|
34
|
+
//# sourceMappingURL=threat-patterns.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"threat-patterns.d.ts","sourceRoot":"","sources":["../src/threat-patterns.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,KAAK,KAAK,GAAG,KAAK,GAAG,SAAS,GAAG,QAAQ,CAAC;AAmH1C;;GAEG;AACH,eAAO,MAAM,eAAe,EAAE,WAAW,CAAC,MAAM,CAkB9C,CAAC;AA0BH;;;;;;;;GAQG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,GAAE,KAAiB,GAAG,MAAM,EAAE,CA0BlF;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,GAAE,KAAgB,GAAG,MAAM,GAAG,IAAI,CAW1F"}
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared threat-pattern library for memory content scanning.
|
|
3
|
+
*
|
|
4
|
+
* Covers prompt injection, role hijack, C2 framework names, exfiltration,
|
|
5
|
+
* persistence (SSH backdoor, agent-config edits), and invisible unicode.
|
|
6
|
+
*
|
|
7
|
+
* Pattern philosophy: anchor on attack-specific vocabulary or unambiguous
|
|
8
|
+
* attack behavior, NOT on bossy English. Multi-word filler is allowed via
|
|
9
|
+
* `(?:\w+\s+)*` between key tokens so attackers can't bypass with
|
|
10
|
+
* synonyms ("ignore all prior instructions").
|
|
11
|
+
*/
|
|
12
|
+
const RAW_PATTERNS = [
|
|
13
|
+
// Classic prompt injection (applies everywhere)
|
|
14
|
+
[
|
|
15
|
+
String.raw `ignore\s+(?:\w+\s+)*(previous|all|above|prior)\s+(?:\w+\s+)*instructions`,
|
|
16
|
+
'prompt_injection',
|
|
17
|
+
'all',
|
|
18
|
+
],
|
|
19
|
+
[String.raw `system\s+prompt\s+override`, 'sys_prompt_override', 'all'],
|
|
20
|
+
[
|
|
21
|
+
String.raw `disregard\s+(?:\w+\s+)*(your|all|any)\s+(?:\w+\s+)*(instructions|rules|guidelines)`,
|
|
22
|
+
'disregard_rules',
|
|
23
|
+
'all',
|
|
24
|
+
],
|
|
25
|
+
[
|
|
26
|
+
String.raw `act\s+as\s+(if|though)\s+(?:\w+\s+)*you\s+(?:\w+\s+)*(have\s+no|don't\s+have)\s+(?:\w+\s+)*(restrictions|limits|rules)`,
|
|
27
|
+
'bypass_restrictions',
|
|
28
|
+
'all',
|
|
29
|
+
],
|
|
30
|
+
['<!--[^>]*(?:ignore|override|system|secret|hidden)[^>]*-->', 'html_comment_injection', 'all'],
|
|
31
|
+
[String.raw `<\s*div\s+style\s*=\s*["'][\s\S]*?display\s*:\s*none`, 'hidden_div', 'all'],
|
|
32
|
+
[String.raw `translate\s+.*\s+into\s+.*\s+and\s+(execute|run|eval)`, 'translate_execute', 'all'],
|
|
33
|
+
[String.raw `do\s+not\s+(?:\w+\s+)*tell\s+(?:\w+\s+)*the\s+user`, 'deception_hide', 'all'],
|
|
34
|
+
// Role-play / identity hijack (context + strict)
|
|
35
|
+
[String.raw `you\s+are\s+(?:\w+\s+)*now\s+(?:a|an|the)\s+`, 'role_hijack', 'context'],
|
|
36
|
+
[String.raw `pretend\s+(?:\w+\s+)*(you\s+are|to\s+be)\s+`, 'role_pretend', 'context'],
|
|
37
|
+
[String.raw `output\s+(?:\w+\s+)*(system|initial)\s+prompt`, 'leak_system_prompt', 'context'],
|
|
38
|
+
[
|
|
39
|
+
String.raw `(respond|answer|reply)\s+without\s+(?:\w+\s+)*(restrictions|limitations|filters|safety)`,
|
|
40
|
+
'remove_filters',
|
|
41
|
+
'context',
|
|
42
|
+
],
|
|
43
|
+
[
|
|
44
|
+
String.raw `you\s+have\s+been\s+(?:\w+\s+)*(updated|upgraded|patched)\s+to`,
|
|
45
|
+
'fake_update',
|
|
46
|
+
'context',
|
|
47
|
+
],
|
|
48
|
+
[String.raw `\bname\s+yourself\s+\w+`, 'identity_override', 'context'],
|
|
49
|
+
// C2 / Brainworm-style promptware
|
|
50
|
+
[String.raw `register\s+(as\s+)?a?\s*node`, 'c2_node_registration', 'context'],
|
|
51
|
+
[String.raw `(heartbeat|beacon|check[\s\-]?in)\s+(to|with)\s+`, 'c2_heartbeat', 'context'],
|
|
52
|
+
[String.raw `pull\s+(down\s+)?(?:new\s+)?task(?:ing|s)?\b`, 'c2_task_pull', 'context'],
|
|
53
|
+
[String.raw `connect\s+to\s+the\s+network\b`, 'c2_network_connect', 'context'],
|
|
54
|
+
[
|
|
55
|
+
String.raw `you\s+must\s+(?:\w+\s+){0,3}(register|connect|report|beacon)\b`,
|
|
56
|
+
'forced_action',
|
|
57
|
+
'context',
|
|
58
|
+
],
|
|
59
|
+
[String.raw `only\s+use\s+one[\s\-]?liners?\b`, 'anti_forensic_oneliner', 'context'],
|
|
60
|
+
[
|
|
61
|
+
String.raw `never\s+(?:\w+\s+)*(?:create|write)\s+(?:\w+\s+)*(?:script|file)\s+(?:\w+\s+)*disk`,
|
|
62
|
+
'anti_forensic_disk',
|
|
63
|
+
'context',
|
|
64
|
+
],
|
|
65
|
+
[
|
|
66
|
+
String.raw `unset\s+\w*(?:CLAUDE|CODEX|HERMES|AGENT|OPENAI|ANTHROPIC|PI)\w*`,
|
|
67
|
+
'env_var_unset_agent',
|
|
68
|
+
'context',
|
|
69
|
+
],
|
|
70
|
+
// Known C2 framework names
|
|
71
|
+
[
|
|
72
|
+
String.raw `\b(?:praxis|cobalt\s*strike|sliver|havoc|mythic|metasploit|brainworm)\b`,
|
|
73
|
+
'known_c2_framework',
|
|
74
|
+
'context',
|
|
75
|
+
],
|
|
76
|
+
[String.raw `\bc2\s+(?:server|channel|infrastructure|beacon)\b`, 'c2_explicit', 'context'],
|
|
77
|
+
[String.raw `\bcommand\s+and\s+control\b`, 'c2_explicit_long', 'context'],
|
|
78
|
+
// Exfiltration via curl/wget/cat with secrets
|
|
79
|
+
[
|
|
80
|
+
String.raw `curl\s+[^\n]*\$\{?\w*(KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|API)`,
|
|
81
|
+
'exfil_curl',
|
|
82
|
+
'all',
|
|
83
|
+
],
|
|
84
|
+
[
|
|
85
|
+
String.raw `wget\s+[^\n]*\$\{?\w*(KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|API)`,
|
|
86
|
+
'exfil_wget',
|
|
87
|
+
'all',
|
|
88
|
+
],
|
|
89
|
+
[
|
|
90
|
+
String.raw `cat\s+[^\n]*(\.env|credentials|\.netrc|\.pgpass|\.npmrc|\.pypirc)`,
|
|
91
|
+
'read_secrets',
|
|
92
|
+
'all',
|
|
93
|
+
],
|
|
94
|
+
[String.raw `(send|post|upload|transmit)\s+.*\s+(to|at)\s+https?://`, 'send_to_url', 'strict'],
|
|
95
|
+
[
|
|
96
|
+
String.raw `(include|output|print|share)\s+(?:\w+\s+)*(conversation|chat\s+history|previous\s+messages|full\s+context|entire\s+context)`,
|
|
97
|
+
'context_exfil',
|
|
98
|
+
'strict',
|
|
99
|
+
],
|
|
100
|
+
// Persistence / SSH backdoor (strict scope)
|
|
101
|
+
['authorized_keys', 'ssh_backdoor', 'strict'],
|
|
102
|
+
[String.raw `\$HOME/\.ssh|~/\.ssh`, 'ssh_access', 'strict'],
|
|
103
|
+
[String.raw `\$HOME/\.pi/\.env|~/\.pi/\.env`, 'pi_env', 'strict'],
|
|
104
|
+
[
|
|
105
|
+
String.raw `(update|modify|edit|write|change|append|add\s+to)\s+.*(?:AGENTS\.md|CLAUDE\.md|\.cursorrules|\.clinerules)`,
|
|
106
|
+
'agent_config_mod',
|
|
107
|
+
'strict',
|
|
108
|
+
],
|
|
109
|
+
// Hardcoded secrets
|
|
110
|
+
[
|
|
111
|
+
String.raw `(?:api[_-]?key|token|secret|password)\s*[=:]\s*["'][A-Za-z0-9+/=_-]{20,}`,
|
|
112
|
+
'hardcoded_secret',
|
|
113
|
+
'strict',
|
|
114
|
+
],
|
|
115
|
+
];
|
|
116
|
+
/**
|
|
117
|
+
* Invisible / bidirectional unicode characters used in injection attacks.
|
|
118
|
+
*/
|
|
119
|
+
export const INVISIBLE_CHARS = new Set([
|
|
120
|
+
'', // zero-width space
|
|
121
|
+
'', // zero-width non-joiner
|
|
122
|
+
'', // zero-width joiner
|
|
123
|
+
'', // word joiner
|
|
124
|
+
'', // invisible times
|
|
125
|
+
'', // invisible separator
|
|
126
|
+
'', // invisible plus
|
|
127
|
+
'', // zero-width no-break space (BOM)
|
|
128
|
+
'', // left-to-right embedding
|
|
129
|
+
'', // right-to-left embedding
|
|
130
|
+
'', // pop directional formatting
|
|
131
|
+
'', // left-to-right override
|
|
132
|
+
'', // right-to-left override
|
|
133
|
+
'', // left-to-right isolate
|
|
134
|
+
'', // right-to-left isolate
|
|
135
|
+
'', // first strong isolate
|
|
136
|
+
'', // pop directional isolate
|
|
137
|
+
]);
|
|
138
|
+
function buildScopeSets() {
|
|
139
|
+
const all = [];
|
|
140
|
+
const context = [];
|
|
141
|
+
const strict = [];
|
|
142
|
+
for (const [pattern, id, scope] of RAW_PATTERNS) {
|
|
143
|
+
const compiled = [new RegExp(pattern, 'i'), id];
|
|
144
|
+
if (scope === 'all') {
|
|
145
|
+
all.push(compiled);
|
|
146
|
+
context.push(compiled);
|
|
147
|
+
strict.push(compiled);
|
|
148
|
+
}
|
|
149
|
+
else if (scope === 'context') {
|
|
150
|
+
context.push(compiled);
|
|
151
|
+
strict.push(compiled);
|
|
152
|
+
}
|
|
153
|
+
else {
|
|
154
|
+
strict.push(compiled);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
return { all, context, strict };
|
|
158
|
+
}
|
|
159
|
+
const COMPILED = buildScopeSets();
|
|
160
|
+
/**
|
|
161
|
+
* Return matched pattern IDs in `content` at the given scope.
|
|
162
|
+
*
|
|
163
|
+
* - `all`: classic injection + exfil only (lowest false-positive set).
|
|
164
|
+
* - `context`: adds promptware / C2 / role-play patterns.
|
|
165
|
+
* - `strict`: adds persistence / SSH backdoor / exfil-URL patterns.
|
|
166
|
+
*
|
|
167
|
+
* Invisible-unicode hits are reported as `invisible_unicode_U+XXXX`.
|
|
168
|
+
*/
|
|
169
|
+
export function scanForThreats(content, scope = 'context') {
|
|
170
|
+
if (!content) {
|
|
171
|
+
return [];
|
|
172
|
+
}
|
|
173
|
+
const findings = [];
|
|
174
|
+
for (const ch of content) {
|
|
175
|
+
if (INVISIBLE_CHARS.has(ch)) {
|
|
176
|
+
const code = ch.codePointAt(0).toString(16).toUpperCase().padStart(4, '0');
|
|
177
|
+
const finding = `invisible_unicode_U+${code}`;
|
|
178
|
+
if (!findings.includes(finding)) {
|
|
179
|
+
findings.push(finding);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
const patterns = COMPILED[scope];
|
|
184
|
+
if (!patterns) {
|
|
185
|
+
throw new Error(`scanForThreats: unknown scope '${scope}'`);
|
|
186
|
+
}
|
|
187
|
+
for (const [regex, id] of patterns) {
|
|
188
|
+
if (regex.test(content)) {
|
|
189
|
+
findings.push(id);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return findings;
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Return a human-readable error string for the first threat in `content`,
|
|
196
|
+
* or `null` when clean. Convenience wrapper for paths that block on first
|
|
197
|
+
* hit (memory writes).
|
|
198
|
+
*/
|
|
199
|
+
export function firstThreatMessage(content, scope = 'strict') {
|
|
200
|
+
const findings = scanForThreats(content, scope);
|
|
201
|
+
if (findings.length === 0) {
|
|
202
|
+
return null;
|
|
203
|
+
}
|
|
204
|
+
const id = findings[0];
|
|
205
|
+
if (id.startsWith('invisible_unicode_')) {
|
|
206
|
+
const codepoint = id.replace('invisible_unicode_', '');
|
|
207
|
+
return `Blocked: content contains invisible unicode character ${codepoint} (possible injection).`;
|
|
208
|
+
}
|
|
209
|
+
return `Blocked: content matches threat pattern '${id}'. Content is injected into the system prompt and must not contain injection or exfiltration payloads.`;
|
|
210
|
+
}
|
|
211
|
+
//# sourceMappingURL=threat-patterns.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"threat-patterns.js","sourceRoot":"","sources":["../src/threat-patterns.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAMH,MAAM,YAAY,GAA0B;IAC1C,gDAAgD;IAChD;QACE,MAAM,CAAC,GAAG,CAAA,0EAA0E;QACpF,kBAAkB;QAClB,KAAK;KACN;IACD,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