@ai-pip/core 0.1.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.
Files changed (43) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +165 -0
  3. package/package.json +79 -0
  4. package/src/cpe/envelope.ts +115 -0
  5. package/src/cpe/exceptions/EnvelopeError.ts +11 -0
  6. package/src/cpe/exceptions/index.ts +6 -0
  7. package/src/cpe/index.ts +35 -0
  8. package/src/cpe/types.ts +68 -0
  9. package/src/cpe/utils.ts +65 -0
  10. package/src/cpe/value-objects/Metadata.ts +78 -0
  11. package/src/cpe/value-objects/Nonce.ts +57 -0
  12. package/src/cpe/value-objects/Signature.ts +83 -0
  13. package/src/cpe/value-objects/index.ts +8 -0
  14. package/src/csl/classify.ts +77 -0
  15. package/src/csl/exceptions/ClassificationError.ts +16 -0
  16. package/src/csl/exceptions/SegmentationError.ts +19 -0
  17. package/src/csl/exceptions/index.ts +3 -0
  18. package/src/csl/index.ts +34 -0
  19. package/src/csl/lineage.ts +40 -0
  20. package/src/csl/segment.ts +100 -0
  21. package/src/csl/types.ts +113 -0
  22. package/src/csl/utils.ts +30 -0
  23. package/src/csl/value-objects/ContentHash.ts +48 -0
  24. package/src/csl/value-objects/LineageEntry.ts +33 -0
  25. package/src/csl/value-objects/Origin-map.ts +51 -0
  26. package/src/csl/value-objects/Origin.ts +52 -0
  27. package/src/csl/value-objects/TrustLevel.ts +33 -0
  28. package/src/csl/value-objects/index.ts +14 -0
  29. package/src/index.ts +18 -0
  30. package/src/isl/exceptions/SanitizationError.ts +14 -0
  31. package/src/isl/exceptions/index.ts +2 -0
  32. package/src/isl/index.ts +20 -0
  33. package/src/isl/sanitize.ts +93 -0
  34. package/src/isl/types.ts +87 -0
  35. package/src/isl/value-objects/AnomalyScore.ts +40 -0
  36. package/src/isl/value-objects/Pattern.ts +158 -0
  37. package/src/isl/value-objects/PiDetection.ts +92 -0
  38. package/src/isl/value-objects/PiDetectionResult.ts +129 -0
  39. package/src/isl/value-objects/PolicyRule.ts +117 -0
  40. package/src/isl/value-objects/index.ts +41 -0
  41. package/src/shared/index.ts +13 -0
  42. package/src/shared/lineage.ts +53 -0
  43. package/tsconfig.json +27 -0
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Utility functions for CSL - funciones puras
3
+ */
4
+
5
+ /**
6
+ * Generates a unique ID for a segment
7
+ */
8
+ export function generateId(): string {
9
+ return `seg-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`
10
+ }
11
+
12
+ /**
13
+ * Splits content by context rules - función pura de segmentación
14
+ *
15
+ * @remarks
16
+ * Segmentación básica por líneas. Sin normalización agresiva
17
+ * (la normalización va a ISL).
18
+ */
19
+ export function splitByContextRules(content: string): string[] {
20
+ if (content.length === 0) {
21
+ return []
22
+ }
23
+
24
+ // Segmentación básica por líneas
25
+ return content
26
+ .split(/\n+/)
27
+ .map(line => line.trim())
28
+ .filter(line => line.length > 0)
29
+ }
30
+
@@ -0,0 +1,48 @@
1
+ import type { HashAlgorithm } from '../types'
2
+
3
+ /**
4
+ * ContentHash - tipo puro
5
+ */
6
+ export type ContentHash = {
7
+ readonly value: string
8
+ readonly algorithm: HashAlgorithm
9
+ }
10
+
11
+ /**
12
+ * Crea un ContentHash - función pura
13
+ */
14
+ export function createContentHash(value: string, algorithm: HashAlgorithm = 'sha256'): ContentHash {
15
+ if (!value || typeof value !== 'string') {
16
+ throw new Error('ContentHash value must be a non-empty string')
17
+ }
18
+
19
+ if (!['sha256', 'sha512'].includes(algorithm)) {
20
+ throw new Error(`Invalid HashAlgorithm: ${algorithm}. Must be 'sha256' or 'sha512'`)
21
+ }
22
+
23
+ const hexPattern = /^[a-f0-9]+$/i
24
+ if (!hexPattern.test(value)) {
25
+ throw new Error('ContentHash value must be a valid hexadecimal string')
26
+ }
27
+
28
+ const expectedLength = algorithm === 'sha256' ? 64 : 128
29
+ if (value.length !== expectedLength) {
30
+ throw new Error(`ContentHash value length must be ${expectedLength} characters for ${algorithm}`)
31
+ }
32
+
33
+ return {
34
+ value: value.toLowerCase(),
35
+ algorithm
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Funciones puras para ContentHash
41
+ */
42
+ export function isSha256(hash: ContentHash): boolean {
43
+ return hash.algorithm === 'sha256'
44
+ }
45
+
46
+ export function isSha512(hash: ContentHash): boolean {
47
+ return hash.algorithm === 'sha512'
48
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * LineageEntry - tipo puro
3
+ *
4
+ * @remarks
5
+ * El core semántico solo preserva linaje estructural.
6
+ * Notes libres son para observabilidad (SDK), no core.
7
+ */
8
+ export type LineageEntry = {
9
+ readonly step: string
10
+ readonly timestamp: number
11
+ }
12
+
13
+ /**
14
+ * Crea un LineageEntry - función pura
15
+ *
16
+ * @remarks
17
+ * El core solo registra step y timestamp.
18
+ * Notes y metadata van en el SDK para observabilidad.
19
+ */
20
+ export function createLineageEntry(step: string, timestamp: number): LineageEntry {
21
+ if (!step || typeof step !== 'string' || step.trim().length === 0) {
22
+ throw new Error('LineageEntry step must be a non-empty string')
23
+ }
24
+
25
+ if (typeof timestamp !== 'number' || timestamp < 0 || !Number.isFinite(timestamp)) {
26
+ throw new Error('LineageEntry timestamp must be a valid positive number')
27
+ }
28
+
29
+ return {
30
+ step: step.trim(),
31
+ timestamp
32
+ }
33
+ }
@@ -0,0 +1,51 @@
1
+ import { OriginType, TrustLevelType } from '../types'
2
+
3
+ /**
4
+ * originMap is the deterministic mapping from OriginType to TrustLevelType.
5
+ *
6
+ * @remarks
7
+ * This map defines the **deterministic classification rules** for content segments.
8
+ * The mapping is based solely on the origin type, not on content analysis.
9
+ *
10
+ * **Key Principles:**
11
+ * - 100% deterministic: same origin → same trust level, always
12
+ * - No heuristics or content analysis
13
+ * - All OriginType values must be present in this map
14
+ */
15
+ export const originMap = new Map<OriginType, TrustLevelType>([
16
+ // User origins - always untrusted (security by default)
17
+ [OriginType.USER, TrustLevelType.UC],
18
+
19
+ // DOM origins - trust based on visibility
20
+ [OriginType.DOM_VISIBLE, TrustLevelType.STC],
21
+ [OriginType.DOM_HIDDEN, TrustLevelType.UC],
22
+ [OriginType.DOM_ATTRIBUTE, TrustLevelType.STC],
23
+
24
+ // External origins - always untrusted
25
+ [OriginType.SCRIPT_INJECTED, TrustLevelType.UC],
26
+ [OriginType.NETWORK_FETCHED, TrustLevelType.UC],
27
+
28
+ // System origins - trusted (system controls)
29
+ [OriginType.SYSTEM_GENERATED, TrustLevelType.TC],
30
+
31
+ // Unknown - untrusted by default (fail-secure)
32
+ [OriginType.UNKNOWN, TrustLevelType.UC],
33
+ ])
34
+
35
+ /**
36
+ * Validates that all OriginType values are mapped in originMap.
37
+ *
38
+ * @throws {Error} If any OriginType is not present in originMap
39
+ */
40
+ export function validateOriginMap(): void {
41
+ const allOriginTypes = Object.values(OriginType)
42
+ const missingTypes = allOriginTypes.filter(type => !originMap.has(type))
43
+
44
+ if (missingTypes.length > 0) {
45
+ throw new Error(
46
+ `Missing origin mappings: ${missingTypes.join(', ')}. ` +
47
+ `All OriginType values must be mapped in originMap.`
48
+ )
49
+ }
50
+ }
51
+
@@ -0,0 +1,52 @@
1
+ import { OriginType } from '../types'
2
+
3
+ /**
4
+ * Origin - tipo puro
5
+ */
6
+ export type Origin = {
7
+ readonly type: OriginType
8
+ }
9
+
10
+ /**
11
+ * Crea un Origin - función pura
12
+ */
13
+ export function createOrigin(type: OriginType): Origin {
14
+ if (!Object.values(OriginType).includes(type)) {
15
+ throw new Error(`Invalid Origin type: ${type}`)
16
+ }
17
+ return { type }
18
+ }
19
+
20
+ /**
21
+ * Funciones puras para Origin
22
+ */
23
+ export function isDom(origin: Origin): boolean {
24
+ return origin.type === OriginType.DOM_HIDDEN ||
25
+ origin.type === OriginType.DOM_VISIBLE ||
26
+ origin.type === OriginType.DOM_ATTRIBUTE
27
+ }
28
+
29
+ export function isUser(origin: Origin): boolean {
30
+ return origin.type === OriginType.USER
31
+ }
32
+
33
+ export function isSystem(origin: Origin): boolean {
34
+ return origin.type === OriginType.SYSTEM_GENERATED
35
+ }
36
+
37
+ export function isInjected(origin: Origin): boolean {
38
+ return origin.type === OriginType.SCRIPT_INJECTED
39
+ }
40
+
41
+ export function isUnknown(origin: Origin): boolean {
42
+ return origin.type === OriginType.UNKNOWN
43
+ }
44
+
45
+ export function isNetworkFetched(origin: Origin): boolean {
46
+ return origin.type === OriginType.NETWORK_FETCHED
47
+ }
48
+
49
+ export function isExternal(origin: Origin): boolean {
50
+ return origin.type === OriginType.NETWORK_FETCHED ||
51
+ origin.type === OriginType.SCRIPT_INJECTED
52
+ }
@@ -0,0 +1,33 @@
1
+ import { TrustLevelType } from '../types'
2
+
3
+ /**
4
+ * TrustLevel - tipo puro
5
+ */
6
+ export type TrustLevel = {
7
+ readonly value: TrustLevelType
8
+ }
9
+
10
+ /**
11
+ * Crea un TrustLevel - función pura
12
+ */
13
+ export function createTrustLevel(value: TrustLevelType): TrustLevel {
14
+ if (!Object.values(TrustLevelType).includes(value)) {
15
+ throw new Error(`Invalid TrustLevel: ${value}`)
16
+ }
17
+ return { value }
18
+ }
19
+
20
+ /**
21
+ * Funciones puras para TrustLevel
22
+ */
23
+ export function isTrusted(trust: TrustLevel): boolean {
24
+ return trust.value === TrustLevelType.TC
25
+ }
26
+
27
+ export function isSemiTrusted(trust: TrustLevel): boolean {
28
+ return trust.value === TrustLevelType.STC
29
+ }
30
+
31
+ export function isUntrusted(trust: TrustLevel): boolean {
32
+ return trust.value === TrustLevelType.UC
33
+ }
@@ -0,0 +1,14 @@
1
+ // Tipos
2
+ export type { TrustLevel } from './TrustLevel'
3
+ export type { Origin } from './Origin'
4
+ export type { LineageEntry } from './LineageEntry'
5
+ export type { ContentHash } from './ContentHash'
6
+
7
+ // Funciones de creación
8
+ export { createTrustLevel, isTrusted, isSemiTrusted, isUntrusted } from './TrustLevel'
9
+ export { createOrigin, isDom, isUser, isSystem, isInjected, isUnknown, isNetworkFetched, isExternal } from './Origin'
10
+ export { createLineageEntry } from './LineageEntry'
11
+ export { createContentHash, isSha256, isSha512 } from './ContentHash'
12
+
13
+ // Origin-map
14
+ export { originMap, validateOriginMap } from './Origin-map'
package/src/index.ts ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * @ai-pip/core - Core implementation of the AI-PIP protocol
3
+ *
4
+ * @remarks
5
+ * Main entry point that re-exports all layers (CSL, ISL, Shared)
6
+ *
7
+ * You can also import specific layers:
8
+ * - import { segment } from '@ai-pip/core/csl'
9
+ * - import { sanitize } from '@ai-pip/core/isl'
10
+ * - import { addLineageEntry } from '@ai-pip/core/shared'
11
+ * - import { envelope } from '@ai-pip/core/cpe'
12
+ */
13
+
14
+ // Re-export all layers
15
+ export * from './csl'
16
+ export * from './isl'
17
+ export * from './shared'
18
+ export * from './cpe'
@@ -0,0 +1,14 @@
1
+ /**
2
+ * SanitizationError is thrown when sanitization fails.
3
+ */
4
+ export class SanitizationError extends Error {
5
+ constructor(
6
+ message: string,
7
+ public readonly cause?: unknown
8
+ ) {
9
+ super(message)
10
+ this.name = 'SanitizationError'
11
+ Object.setPrototypeOf(this, SanitizationError.prototype)
12
+ }
13
+ }
14
+
@@ -0,0 +1,2 @@
1
+ export * from './SanitizationError'
2
+
@@ -0,0 +1,20 @@
1
+ /**
2
+ * ISL (Instruction Sanitization Layer) - Core Semántico
3
+ *
4
+ * @remarks
5
+ * ISL sanitiza instrucciones maliciosas recibidas de CSL,
6
+ * aplicando diferentes niveles de sanitización según el nivel de confianza.
7
+ */
8
+
9
+ // Funciones puras principales
10
+ export { sanitize } from './sanitize'
11
+
12
+ // Value objects
13
+ export * from './value-objects'
14
+
15
+ // Exceptions
16
+ export * from './exceptions'
17
+
18
+ // Types
19
+ export * from './types'
20
+
@@ -0,0 +1,93 @@
1
+ import type { CSLResult } from '@/csl/types'
2
+ import type { ISLResult, ISLSegment, RemovedInstruction } from './types'
3
+ import { createLineageEntry } from '@/csl/value-objects'
4
+ import { addLineageEntry } from '@/shared/lineage'
5
+ import type { TrustLevel } from '@/csl/value-objects'
6
+ import { TrustLevelType } from '@/csl/types'
7
+
8
+ /**
9
+ * Sanitiza contenido según nivel de confianza - función pura
10
+ *
11
+ * @remarks
12
+ * ISL aplica sanitización diferenciada según el trust level:
13
+ * - TC: Sanitización mínima
14
+ * - STC: Sanitización moderada
15
+ * - UC: Sanitización agresiva
16
+ */
17
+ export function sanitize(cslResult: CSLResult): ISLResult {
18
+ const segments: ISLSegment[] = []
19
+ let allLineage: typeof cslResult.lineage = [...cslResult.lineage]
20
+ const blockedCount = 0
21
+ let instructionsRemovedCount = 0
22
+
23
+ for (const cslSegment of cslResult.segments) {
24
+ // Determinar nivel de sanitización según trust level
25
+ const sanitizationLevel = getSanitizationLevel(cslSegment.trust)
26
+
27
+ // Sanitizar contenido según nivel
28
+ const sanitized = sanitizeContent(
29
+ cslSegment.content,
30
+ sanitizationLevel
31
+ )
32
+
33
+ // Detectar instrucciones removidas (esto se implementará con detección de PI)
34
+ const removedInstructions: RemovedInstruction[] = []
35
+
36
+ // Crear segmento sanitizado
37
+ const islSegment: ISLSegment = {
38
+ id: cslSegment.id,
39
+ originalContent: cslSegment.content, // ✅ Preservar original
40
+ sanitizedContent: sanitized.content,
41
+ trust: cslSegment.trust,
42
+ lineage: addLineageEntry(
43
+ cslSegment.lineage,
44
+ createLineageEntry('ISL', Date.now())
45
+ ),
46
+ instructionsRemoved: removedInstructions,
47
+ sanitizationLevel
48
+ }
49
+
50
+ segments.push(islSegment)
51
+ const lastLineageEntry = islSegment.lineage.at(-1)
52
+ if (lastLineageEntry) {
53
+ allLineage = addLineageEntry(allLineage, lastLineageEntry)
54
+ }
55
+ instructionsRemovedCount += removedInstructions.length
56
+ }
57
+
58
+ return {
59
+ segments: Object.freeze(segments),
60
+ lineage: Object.freeze(allLineage),
61
+ metadata: {
62
+ totalSegments: segments.length,
63
+ sanitizedSegments: segments.length,
64
+ blockedSegments: blockedCount,
65
+ instructionsRemoved: instructionsRemovedCount
66
+ }
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Determina nivel de sanitización según trust level - función pura
72
+ */
73
+ function getSanitizationLevel(trust: TrustLevel): 'minimal' | 'moderate' | 'aggressive' {
74
+ if (trust.value === TrustLevelType.TC) return 'minimal'
75
+ if (trust.value === TrustLevelType.STC) return 'moderate'
76
+ return 'aggressive' // UC
77
+ }
78
+
79
+ /**
80
+ * Sanitiza contenido según nivel - función pura
81
+ */
82
+ function sanitizeContent(
83
+ content: string,
84
+ _level: 'minimal' | 'moderate' | 'aggressive'
85
+ ): { content: string; removed: RemovedInstruction[] } {
86
+ // Por ahora retorna el contenido sin cambios
87
+ // La lógica de sanitización real se implementará después
88
+ return {
89
+ content,
90
+ removed: []
91
+ }
92
+ }
93
+
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Types for ISL (Instruction Sanitization Layer) - Core Semántico
3
+ */
4
+
5
+ // Importar tipos de CSL y value objects
6
+ import type { LineageEntry, TrustLevel } from '@/csl/value-objects'
7
+ import type { PiDetectionResult } from './value-objects/PiDetectionResult'
8
+ import type { AnomalyScore } from './value-objects/AnomalyScore'
9
+
10
+ /**
11
+ * RiskScore - Score de riesgo (0-1)
12
+ */
13
+ export type RiskScore = number
14
+
15
+ /**
16
+ * AnomalyAction - Acción recomendada basada en análisis
17
+ */
18
+ export type AnomalyAction = 'ALLOW' | 'WARN' | 'BLOCK'
19
+
20
+ /**
21
+ * Position - Posición de un patrón detectado en el contenido
22
+ */
23
+ export type Position = {
24
+ readonly start: number
25
+ readonly end: number
26
+ }
27
+
28
+ /**
29
+ * BlockedIntent - Intent que está explícitamente bloqueado por política
30
+ */
31
+ export type BlockedIntent = string
32
+
33
+ /**
34
+ * SensitiveScope - Tema sensible que requiere validación adicional
35
+ */
36
+ export type SensitiveScope = string
37
+
38
+ /**
39
+ * ProtectedRole - Rol que no puede ser sobrescrito
40
+ */
41
+ export type ProtectedRole = string
42
+
43
+ /**
44
+ * ImmutableInstruction - Instrucción que no puede ser modificada
45
+ */
46
+ export type ImmutableInstruction = string
47
+
48
+ /**
49
+ * RemovedInstruction - Instrucción removida durante sanitización
50
+ */
51
+ export interface RemovedInstruction {
52
+ readonly type: 'system_command' | 'role_swapping' | 'jailbreak' | 'override' | 'manipulation'
53
+ readonly pattern: string
54
+ readonly position: Position
55
+ readonly description: string
56
+ }
57
+
58
+ /**
59
+ * ISLSegment - Segmento sanitizado por ISL
60
+ */
61
+ export interface ISLSegment {
62
+ readonly id: string
63
+ readonly originalContent: string // Contenido original de CSL
64
+ readonly sanitizedContent: string // Contenido sanitizado
65
+ readonly trust: TrustLevel // Trust level del segmento original
66
+ readonly lineage: LineageEntry[] // Linaje actualizado con ISL
67
+ readonly piDetection?: PiDetectionResult // Detección de prompt injection
68
+ readonly anomalyScore?: AnomalyScore // Score de anomalía
69
+ readonly instructionsRemoved: RemovedInstruction[] // Instrucciones removidas
70
+ readonly sanitizationLevel: 'minimal' | 'moderate' | 'aggressive'
71
+ }
72
+
73
+ /**
74
+ * ISLResult - Resultado de la sanitización
75
+ */
76
+ export interface ISLResult {
77
+ readonly segments: readonly ISLSegment[]
78
+ readonly lineage: readonly LineageEntry[]
79
+ readonly metadata: {
80
+ readonly totalSegments: number
81
+ readonly sanitizedSegments: number
82
+ readonly blockedSegments: number
83
+ readonly instructionsRemoved: number
84
+ readonly processingTimeMs?: number
85
+ }
86
+ }
87
+
@@ -0,0 +1,40 @@
1
+ import type { AnomalyAction, RiskScore } from '../types'
2
+
3
+ /**
4
+ * AnomalyScore - tipo puro
5
+ */
6
+ export type AnomalyScore = {
7
+ readonly score: RiskScore
8
+ readonly action: AnomalyAction
9
+ }
10
+
11
+ /**
12
+ * Crea un AnomalyScore - función pura
13
+ */
14
+ export function createAnomalyScore(score: RiskScore, action: AnomalyAction): AnomalyScore {
15
+ if (score < 0 || score > 1) {
16
+ throw new Error('Anomaly score must be a value between 0 and 1')
17
+ }
18
+
19
+ if (!['ALLOW', 'WARN', 'BLOCK'].includes(action)) {
20
+ throw new Error(`Invalid AnomalyAction: ${action}. Must be one of: ALLOW, WARN, BLOCK`)
21
+ }
22
+
23
+ return { score, action }
24
+ }
25
+
26
+ /**
27
+ * Funciones puras para AnomalyScore
28
+ */
29
+ export function isHighRisk(anomaly: AnomalyScore): boolean {
30
+ return anomaly.action === 'BLOCK'
31
+ }
32
+
33
+ export function isWarnRisk(anomaly: AnomalyScore): boolean {
34
+ return anomaly.action === 'WARN'
35
+ }
36
+
37
+ export function isLowRisk(anomaly: AnomalyScore): boolean {
38
+ return anomaly.action === 'ALLOW'
39
+ }
40
+