@intflows/genkit-guard 0.0.5 → 0.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,18 @@
1
+ export interface IntentGuardConfig {
2
+ allowedIntent: string;
3
+ intents: Record<string, string>;
4
+ threshold?: number;
5
+ fallbackMessage?: string;
6
+ }
7
+ export interface IntentResult {
8
+ allowed: boolean;
9
+ score: number;
10
+ }
11
+ export interface PiiRule {
12
+ name: string;
13
+ pattern: RegExp;
14
+ }
15
+ export interface PiiConfig {
16
+ rules?: PiiRule[];
17
+ maskCharacter?: string;
18
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,6 @@
1
+ export { guard } from './middleware/middleware.js';
2
+ export * from './core/types.js';
3
+ /**
4
+ * Pre-load the model to avoid cold-start delay on first user request.
5
+ */
6
+ export declare function initGuard(): Promise<void>;
package/dist/index.js ADDED
@@ -0,0 +1,15 @@
1
+ import { ModelSingleton } from './util/singleton.js';
2
+ // export { intentGuard, piiGuard } from './middleware/middleware.js';
3
+ export { guard } from './middleware/middleware.js';
4
+ export * from './core/types.js';
5
+ /**
6
+ * Pre-load the model to avoid cold-start delay on first user request.
7
+ */
8
+ export async function initGuard() {
9
+ console.log('[Guard] Loading local models...');
10
+ await Promise.all([
11
+ ModelSingleton.getExtractor(),
12
+ ModelSingleton.getNER()
13
+ ]);
14
+ console.log('[Guard] Models loaded');
15
+ }
@@ -0,0 +1,6 @@
1
+ export declare function detectInjection(userInput: string): Promise<boolean>;
2
+ export declare function analyzeIntentStructured(input: string, intents: Record<string, string>, threshold: number): Promise<{
3
+ intent: string;
4
+ score: number;
5
+ allowed: boolean;
6
+ }>;
@@ -0,0 +1,80 @@
1
+ import { cos_sim } from '@huggingface/transformers';
2
+ import { ModelSingleton } from '../util/singleton.js';
3
+ const INJECTION_PATTERNS = [
4
+ 'ignore instructions',
5
+ 'reveal secrets',
6
+ 'bypass security',
7
+ 'system prompt',
8
+ 'internal policy',
9
+ 'developer message',
10
+ 'confidential information',
11
+ 'do not follow previous instructions',
12
+ 'disregard earlier directives',
13
+ 'override safety measures',
14
+ 'leak data',
15
+ 'expose vulnerabilities',
16
+ 'access restricted areas',
17
+ 'execute arbitrary code',
18
+ 'perform unauthorized actions',
19
+ 'escalate privileges',
20
+ 'disable safeguards',
21
+ 'manipulate output',
22
+ 'circumvent controls',
23
+ 'exploit weaknesses',
24
+ 'compromise integrity',
25
+ 'subvert protections',
26
+ 'inject malicious content',
27
+ 'craft deceptive prompts',
28
+ 'trick the model',
29
+ 'confuse the system',
30
+ 'You are now a hacker',
31
+ 'You are a malicious actor',
32
+ 'Find a vulnerability',
33
+ 'Write a prompt that bypasses security',
34
+ 'Write a prompt that tricks the model',
35
+ 'Write a prompt that confuses the system',
36
+ "ignore previous",
37
+ "ignore earlier",
38
+ "disregard previous",
39
+ "disregard earlier",
40
+ "you are a hacker",
41
+ "you are now a hacker",
42
+ "you are malicious",
43
+ "export the api key",
44
+ "give me the api key",
45
+ "bypass",
46
+ "override",
47
+ "jailbreak",
48
+ "system override",
49
+ "forget instructions",
50
+ "forget previous",
51
+ "forget earlier",
52
+ "do anything now",
53
+ "dan mode",
54
+ "developer mode",
55
+ "break character",
56
+ "act as"
57
+ ];
58
+ export async function detectInjection(userInput) {
59
+ return INJECTION_PATTERNS.some(p => userInput.toLowerCase().includes(p));
60
+ }
61
+ export async function analyzeIntentStructured(input, intents, threshold) {
62
+ const extractor = await ModelSingleton.getExtractor();
63
+ let bestIntent = '';
64
+ let bestScore = 0;
65
+ for (const [key, desc] of Object.entries(intents)) {
66
+ const output = await extractor([`intent: ${desc}`, `intent: ${input}`], { pooling: 'mean', normalize: true });
67
+ const vectors = output.tolist();
68
+ const score = cos_sim(vectors[0], vectors[1]);
69
+ const finalScore = typeof score === 'number' ? score : score.data[0];
70
+ if (finalScore > bestScore) {
71
+ bestScore = finalScore;
72
+ bestIntent = key;
73
+ }
74
+ }
75
+ return {
76
+ intent: bestIntent,
77
+ score: bestScore,
78
+ allowed: bestScore >= threshold
79
+ };
80
+ }
@@ -0,0 +1 @@
1
+ export declare function guard(config: any): (req: any, next: any) => Promise<any>;
@@ -0,0 +1,113 @@
1
+ import { analyzeIntentStructured, detectInjection } from '../intent/intentAnalyzer.js';
2
+ import { detectPII } from '../pii/detector.js';
3
+ import { PiiTokenizer } from '../pii/tokenizer.js';
4
+ export function guard(config) {
5
+ return async (req, next) => {
6
+ const input = req.prompt ||
7
+ req.messages?.[req.messages.length - 1]?.content?.[0]?.text ||
8
+ "";
9
+ // -------------------------
10
+ // 1. INTENT ANALYSIS
11
+ // -------------------------
12
+ const isInjection = await detectInjection(input);
13
+ if (isInjection) {
14
+ console.warn(`[Intent Guard] Prompt injection pattern detected in input`);
15
+ return block("Prompt injection detected", {
16
+ reason: "pattern_match"
17
+ });
18
+ }
19
+ console.log(`[Intent Guard] Analyzing intent for user's input`);
20
+ const intentResult = await analyzeIntentStructured(input, config.intent.semantic.intents, config.intent.semantic.threshold);
21
+ console.log(`[Intent Guard] Detected intent: ${intentResult.intent} (score: ${intentResult.score.toFixed(2)})`);
22
+ if (!intentResult.allowed) {
23
+ console.warn(`[Intent Guard] Intent "${intentResult.intent}" not allowed ${intentResult.allowed}`);
24
+ return block("Intent not allowed", {
25
+ intent: intentResult.intent,
26
+ score: intentResult.score
27
+ });
28
+ }
29
+ // -------------------------
30
+ // 2. PII DETECTION + MASKING
31
+ // -------------------------
32
+ const piiMatches = await detectPII(input);
33
+ console.log(`[PII Guard] Detected PII: ${piiMatches.length} matches found`);
34
+ const tokenizer = new PiiTokenizer(); // <-- SINGLE INSTANCE
35
+ const piiResult = tokenizer.mask(input, piiMatches);
36
+ console.log(`[PII Guard] Masked PII: ${piiResult.piiTypes.length} types found`);
37
+ // Attach tokenizer so response can unmask
38
+ req.metadata = {
39
+ ...req.metadata,
40
+ piiTokenizer: tokenizer,
41
+ intent: intentResult.intent,
42
+ score: intentResult.score,
43
+ piiDetected: piiMatches.length > 0,
44
+ piiTypes: piiResult.piiTypes,
45
+ maskedInput: piiResult.maskedText
46
+ };
47
+ // Replace input
48
+ req.prompt = piiResult.maskedText;
49
+ req.messages = [
50
+ {
51
+ role: 'user',
52
+ content: [{ text: piiResult.maskedText }],
53
+ },
54
+ ];
55
+ // -------------------------
56
+ // 3. LLM CALL
57
+ // -------------------------
58
+ const res = await next(req);
59
+ // -------------------------
60
+ // 4. RESPONSE UNMASK
61
+ // -------------------------
62
+ console.log(`[PII Guard] Unmasking response if needed`);
63
+ if (tokenizer) {
64
+ /**
65
+ * RECURSIVE TRANSFORMER
66
+ * This will find every string in the Genkit response (no matter if it's in
67
+ * candidates, message, custom, or output) and unmask it.
68
+ */
69
+ const transform = (obj) => {
70
+ // 1. If it's a string, unmask it
71
+ if (typeof obj === 'string') {
72
+ return tokenizer.unmask(obj);
73
+ }
74
+ // 2. If it's an array, transform each element
75
+ if (Array.isArray(obj)) {
76
+ return obj.map(transform);
77
+ }
78
+ // 3. If it's an object, transform each value
79
+ if (obj !== null && typeof obj === 'object') {
80
+ // Note: We iterate keys and mutate the object directly
81
+ // to ensure Genkit's internal references are updated.
82
+ for (const key of Object.keys(obj)) {
83
+ obj[key] = transform(obj[key]);
84
+ }
85
+ return obj;
86
+ }
87
+ // 4. Return as-is for numbers/booleans/null
88
+ return obj;
89
+ };
90
+ // ----------------------------------------------------------------------
91
+ // 5. Transform the entire response object in-place to unmask all strings
92
+ // ----------------------------------------------------------------------
93
+ transform(res);
94
+ console.log("[PII Guard] Deep unmasking complete across all candidates and custom fields.");
95
+ }
96
+ // ---------------------------------------------------------
97
+ // 6. Return the modified response with unmasked content
98
+ // ---------------------------------------------------------
99
+ return res;
100
+ };
101
+ }
102
+ // Helper to create a blocked response
103
+ function block(message, metadata) {
104
+ return {
105
+ finishReason: 'blocked',
106
+ output: {
107
+ type: "error",
108
+ status: "BLOCKED",
109
+ message
110
+ },
111
+ metadata
112
+ };
113
+ }
@@ -0,0 +1,4 @@
1
+ export declare function detectPII(text: string): Promise<{
2
+ type: string;
3
+ value: string;
4
+ }[]>;
@@ -0,0 +1,34 @@
1
+ import { ModelSingleton } from '../util/singleton.js';
2
+ const REGEX_RULES = [
3
+ // EMAIL (keep your existing one)
4
+ { type: 'EMAIL', pattern: /\b[\w\.-]+@[\w\.-]+\.\w{2,}\b/gi },
5
+ // AU MOBILE (04xx xxx xxx or +61 4xx xxx xxx)
6
+ { type: 'AU_MOBILE', pattern: /\b(?:\+?61|0)4\d{2}[-\s]?\d{3}[-\s]?\d{3}\b/g },
7
+ // AU LANDLINE (02, 03, 07, 08)
8
+ { type: 'AU_LANDLINE', pattern: /\b(?:\+?61[-\s]?)?(?:2|3|7|8)\d{1}[-\s]?\d{4}[-\s]?\d{4}\b/g },
9
+ // MEDICARE NUMBER (10 digits, often grouped 4-5-1)
10
+ { type: 'MEDICARE', pattern: /\b\d{4}[-\s]?\d{5}[-\s]?\d\b/g },
11
+ // TFN (9 digits)
12
+ { type: 'TFN', pattern: /\b\d{3}[-\s]?\d{3}[-\s]?\d{3}\b/g },
13
+ // ABN (11 digits)
14
+ { type: 'ABN', pattern: /\b\d{2}[-\s]?\d{3}[-\s]?\d{3}[-\s]?\d{3}\b/g },
15
+ // CREDIT CARD (keep your existing one if needed)
16
+ { type: 'CREDIT_CARD', pattern: /\b(?:\d[ -]*?){13,16}\b/g }
17
+ ];
18
+ export async function detectPII(text) {
19
+ const ner = await ModelSingleton.getNER();
20
+ const results = [];
21
+ // ---- NER ----
22
+ const entities = await ner(text);
23
+ for (const e of entities) {
24
+ if (e.entity.includes('PER')) {
25
+ results.push({ type: 'NAME', value: e.word.replace('##', '') });
26
+ }
27
+ }
28
+ // ---- REGEX ----
29
+ for (const rule of REGEX_RULES) {
30
+ const matches = text.match(rule.pattern) || [];
31
+ matches.forEach(m => results.push({ type: rule.type, value: m }));
32
+ }
33
+ return results;
34
+ }
@@ -0,0 +1,19 @@
1
+ export type PiiResult = {
2
+ maskedText: string;
3
+ pii: Record<string, string>;
4
+ piiTypes: string[];
5
+ };
6
+ export declare class PiiTokenizer {
7
+ private vault;
8
+ private counter;
9
+ private piiTypes;
10
+ private createToken;
11
+ mask(text: string, matches: {
12
+ type: string;
13
+ value: string;
14
+ }[]): PiiResult;
15
+ unmask(text: string): string;
16
+ getVault(): {
17
+ [k: string]: string;
18
+ };
19
+ }
@@ -0,0 +1,32 @@
1
+ export class PiiTokenizer {
2
+ vault = new Map();
3
+ counter = 0;
4
+ piiTypes = new Set();
5
+ createToken(type) {
6
+ return `[[${type}_${this.counter++}]]`;
7
+ }
8
+ mask(text, matches) {
9
+ let masked = text;
10
+ for (const match of matches) {
11
+ const token = this.createToken(match.type);
12
+ this.vault.set(token, match.value);
13
+ this.piiTypes.add(match.type.toLowerCase());
14
+ masked = masked.split(match.value).join(token);
15
+ }
16
+ return {
17
+ maskedText: masked,
18
+ pii: Object.fromEntries(this.vault),
19
+ piiTypes: Array.from(this.piiTypes)
20
+ };
21
+ }
22
+ unmask(text) {
23
+ let result = text;
24
+ this.vault.forEach((value, token) => {
25
+ result = result.split(token).join(value); // Global replacement
26
+ });
27
+ return result;
28
+ }
29
+ getVault() {
30
+ return Object.fromEntries(this.vault);
31
+ }
32
+ }
@@ -0,0 +1,7 @@
1
+ export declare class ModelSingleton {
2
+ private static extractor;
3
+ private static classifier;
4
+ static init(): void;
5
+ static getExtractor(): Promise<any>;
6
+ static getNER(): Promise<any>;
7
+ }
@@ -0,0 +1,40 @@
1
+ import { pipeline, env } from '@huggingface/transformers';
2
+ import path from 'path';
3
+ import fs from 'fs';
4
+ import { fileURLToPath } from 'url';
5
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
6
+ env.allowRemoteModels = false;
7
+ env.localModelPath = path.join(__dirname, '../../models');
8
+ export class ModelSingleton {
9
+ static extractor = null;
10
+ static classifier = null;
11
+ static init() {
12
+ // Always resolve model path relative to the client app, not the library
13
+ const projectRoot = process.cwd();
14
+ const modelPath = path.join(projectRoot, "models");
15
+ // Ensure directory exists
16
+ if (!fs.existsSync(modelPath)) {
17
+ fs.mkdirSync(modelPath, { recursive: true });
18
+ }
19
+ env.cacheDir = modelPath;
20
+ env.localModelPath = modelPath;
21
+ // Allow remote download if missing
22
+ env.allowRemoteModels = true;
23
+ console.log("[Guard] Using model directory:", modelPath);
24
+ }
25
+ static async getExtractor() {
26
+ if (!this.extractor) {
27
+ this.init();
28
+ this.extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2');
29
+ }
30
+ return this.extractor;
31
+ }
32
+ static async getNER() {
33
+ if (!this.classifier) {
34
+ this.init();
35
+ // Token classification model for identifying sensitive entities
36
+ this.classifier = await pipeline('token-classification', 'Xenova/bert-base-NER');
37
+ }
38
+ return this.classifier;
39
+ }
40
+ }
package/package.json CHANGED
@@ -5,7 +5,7 @@
5
5
  "Hemant Kohli"
6
6
  ],
7
7
  "license": "Apache-2.0",
8
- "version": "0.0.5",
8
+ "version": "0.0.6",
9
9
  "type": "module",
10
10
  "exports": "./dist/index.js",
11
11
  "types": "./dist/index.d.ts",
@@ -13,7 +13,8 @@
13
13
  "src/",
14
14
  "README.md",
15
15
  "package.json",
16
- "scripts/"
16
+ "scripts/",
17
+ "dist/"
17
18
  ],
18
19
  "scripts": {
19
20
  "prepare-models": "node scripts/download-model.js",