@astratra/ai 1.10.0 → 1.11.0

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/README.md CHANGED
@@ -39,7 +39,7 @@ const reply = await guards.output(modelAnswer, run); // démasqué, pui
39
39
 
40
40
  | Garde | Ce qu'elle fait |
41
41
  |---|---|
42
- | `input(text, run)` | masque les noms (détecteur d'entités + `names` du registre) et les données structurées (e-mail, IBAN, carte, téléphone) ; le texte revient démasqué dans `output`. Rend `text: null` si elle bloque. |
42
+ | `input(text, run)` | masque les noms (détecteur d'entités + `names` du registre) et les données structurées (e-mail, IBAN, carte, téléphone) ainsi que les secrets (clés d'API, jetons JWT, clés privées, adresses IP) ; le texte revient démasqué dans `output`. Rend `text: null` si elle bloque. |
43
43
  | `toolResult(result, run, { tool, external })` | pour un résultat **externe** (ou marqué `{ untrusted: true, content }`) : détection d'injection (texte long lu par fenêtres, jamais passé sans contrôle), contenu encadré par des marqueurs à nonce comme *données non fiables*. Injection suspectée : `run.requiresConfirmation = true` pour tout le reste de l'exécution. |
44
44
  | `output(text, run)` | démasque ; **ancrage** (chaque phrase contre les sources lues, NLI, via `verifySources` de rag) avec `groundingScore` et la liste `unsupported` ; **fuite** de données personnelles que la personne n'a pas données (`onLeak`: `block`, `redact`, `flag`) ; **modération**. |
45
45
  | `beforeAction(action, run, { humanConfirmed })` | refuse toute action tant qu'une injection est suspectée et qu'aucun humain n'a confirmé (`humanConfirmed: true` vient de votre interface, jamais du modèle). |
@@ -61,7 +61,12 @@ vraies gardes sur ce client, avec un enregistreur d'événements) et
61
61
  `createEventRecorder`.
62
62
 
63
63
  Limites : les gardes réduisent le risque, elles ne le suppriment pas. Les
64
- règles de fuite ne couvrent que les données structurées ; l'ancrage compte
64
+ règles de fuite ne couvrent que les données structurées et les secrets à forme
65
+ connue (`findPersonalData` : `email`, `iban`, `card`, `phone`, `apiKey` —
66
+ OpenAI, Anthropic, Google, GitHub, Stripe, AWS, Slack, Groq, Hugging Face —,
67
+ `jwt`, `privateKey`, `ip`) ; une clé sans préfixe reconnaissable passe. Une
68
+ clé ou une adresse IP n'est jamais lue à moitié comme un téléphone ou une
69
+ carte. L'ancrage compte
65
70
  aussi comme « non soutenues » des phrases de liaison ; la détection d'injection
66
71
  lit un texte isolé.
67
72
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astratra/ai",
3
- "version": "1.10.0",
3
+ "version": "1.11.0",
4
4
  "description": "Generic AI provider routing, tool registry, and agent loop utilities for Astratra, plus agent guards (@astratra/ai/guards): outbound masking, prompt-injection handling for untrusted tool results, reply checks.",
5
5
  "engines": {
6
6
  "node": ">=20"
@@ -72,7 +72,7 @@ export interface CreateGuardsOptions {
72
72
  moderation?: boolean;
73
73
  /** Share of supported claims under which the reply is `unsupported`. Default 0.5. */
74
74
  minSupport?: number;
75
- leakTypes?: Array<'email' | 'iban' | 'card' | 'phone'>;
75
+ leakTypes?: Array<PersonalDataType>;
76
76
  allowLeak?: (item: { type: string; key: string }, run: GuardRun) => boolean;
77
77
  };
78
78
  /** `verifySources` of @astratra/rag; default: the installed @astratra/rag. */
@@ -143,7 +143,9 @@ export function createGuards(options?: CreateGuardsOptions): Guards;
143
143
  /** Every check on, failClosed for actions, 0.3 injection threshold before an action, leaks and unsafe replies blocked. */
144
144
  export function recommendedGuards(options?: CreateGuardsOptions & { readOnly?: boolean }): Guards;
145
145
  export function frameUntrusted(content: string, options?: { source?: string; nonce?: string }): string;
146
- export function findPersonalData(text: string, types?: string[]): Array<{ type: string; value: string; key: string; start: number; end: number }>;
146
+ /** Personal data and secrets recognised without a model. */
147
+ export type PersonalDataType = 'email' | 'iban' | 'card' | 'phone' | 'apiKey' | 'jwt' | 'privateKey' | 'ip';
148
+ export function findPersonalData(text: string, types?: PersonalDataType[]): Array<{ type: PersonalDataType; value: string; key: string; start: number; end: number }>;
147
149
  export const UNTRUSTED_NOTICE: string;
148
150
  export const GUARD_DECISIONS: readonly GuardDecision[];
149
151
  export const FAIL_CLOSED: 'failClosed';
@@ -1,7 +1,9 @@
1
1
  'use strict';
2
2
 
3
- /* Personal data a reply must not carry unless the person gave it in this run.
4
- Small on purpose: structured data that can be recognised without a model. */
3
+ /* Personal data and secrets a reply must not carry unless the person gave it in this run.
4
+ Small on purpose: structured data that can be recognised without a model. Secrets
5
+ (API keys, tokens, private keys) and IP addresses are found first: a key or an address
6
+ is never half-read as a phone number or a card. */
5
7
 
6
8
  function luhnValid(digits) {
7
9
  if (digits.length < 13 || digits.length > 19) return false;
@@ -30,7 +32,31 @@ function ibanValid(value) {
30
32
 
31
33
  const DATE_LIKE = /^\d{4}-\d{2}-\d{2}/;
32
34
 
35
+ /* Keys whose shape is published by their provider. A prefix and a long random tail: no
36
+ ordinary word looks like this. */
37
+ const API_KEY = new RegExp([
38
+ 'sk-ant-[A-Za-z0-9_-]{20,}', // Anthropic
39
+ 'sk-(?:proj-|svcacct-)?[A-Za-z0-9_-]{20,}', // OpenAI
40
+ 'AIza[0-9A-Za-z_-]{35}', // Google
41
+ 'gh[pousr]_[A-Za-z0-9]{36,}', // GitHub
42
+ 'github_pat_[A-Za-z0-9_]{22,}', // GitHub, fine-grained
43
+ '(?:sk|rk|pk)_(?:live|test)_[A-Za-z0-9]{16,}', // Stripe
44
+ 'whsec_[A-Za-z0-9]{24,}', // Stripe webhooks
45
+ 'AKIA[0-9A-Z]{16}', // AWS
46
+ 'xox[baprs]-[A-Za-z0-9-]{10,}', // Slack
47
+ 'gsk_[A-Za-z0-9]{20,}', // Groq
48
+ 'hf_[A-Za-z0-9]{30,}' // Hugging Face
49
+ ].map((p) => `(?<![A-Za-z0-9_-])${p}`).join('|'), 'g');
50
+
51
+ function ipv4Valid(value) {
52
+ return value.split('.').every((part) => Number(part) <= 255 && !(part.length > 1 && part.startsWith('0')));
53
+ }
54
+
33
55
  const DETECTORS = [
56
+ { type: 'privateKey', pattern: () => /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, valid: () => true },
57
+ { type: 'jwt', pattern: () => /(?<![A-Za-z0-9_-])eyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g, valid: () => true },
58
+ { type: 'apiKey', pattern: () => new RegExp(API_KEY.source, 'g'), valid: () => true },
59
+ { type: 'ip', pattern: () => /(?<![\w.:])(?:\d{1,3}\.){3}\d{1,3}(?![\w.])|(?<![\w:])(?:[0-9a-f]{1,4}:){7}[0-9a-f]{1,4}(?![\w:])|(?<![\w:])(?:[0-9a-f]{1,4}:){1,6}:(?:[0-9a-f]{1,4}(?::[0-9a-f]{1,4}){0,5})?(?![\w:])/gi, valid: (value) => (value.includes('.') ? ipv4Valid(value) : (value.match(/:/g) || []).length >= 2) },
34
60
  { type: 'email', pattern: () => /[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}/g, valid: () => true },
35
61
  { type: 'iban', pattern: () => /\b[A-Z]{2}\d{2}(?: ?[A-Z0-9]{2,5}){3,8}\b/g, valid: ibanValid },
36
62
  { type: 'card', pattern: () => /\b(?:\d[ -]?){13,19}\b/g, valid: (value) => luhnValid(value.replace(/\D/g, '')) },
@@ -44,7 +70,12 @@ const DETECTORS = [
44
70
  }
45
71
  ];
46
72
 
47
- const normal = (type, value) => (type === 'email' ? value.toLowerCase() : value.replace(/[\s.()-]/g, '').toUpperCase());
73
+ const SECRET_TYPES = new Set(['privateKey', 'jwt', 'apiKey']);
74
+ const normal = (type, value) => {
75
+ if (type === 'email' || type === 'ip') return value.toLowerCase();
76
+ if (SECRET_TYPES.has(type)) return value.replace(/\s+/g, '');
77
+ return value.replace(/[\s.()-]/g, '').toUpperCase();
78
+ };
48
79
 
49
80
  /** Structured personal data in a text: [{ type, value, start, end }] (values stay in memory, never in events). */
50
81
  function findPersonalData(text, types) {