@ai-pip/core 0.1.4 → 0.1.5
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 +91 -30
- package/dist/index.d.ts +7 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -3
- package/dist/index.js.map +1 -1
- package/package.json +1 -2
- package/src/cpe/envelope.ts +0 -115
- package/src/cpe/exceptions/EnvelopeError.ts +0 -11
- package/src/cpe/exceptions/index.ts +0 -6
- package/src/cpe/index.ts +0 -44
- package/src/cpe/types.ts +0 -68
- package/src/cpe/utils.ts +0 -65
- package/src/cpe/value-objects/Metadata.ts +0 -78
- package/src/cpe/value-objects/Nonce.ts +0 -57
- package/src/cpe/value-objects/Signature.ts +0 -83
- package/src/cpe/value-objects/index.ts +0 -10
- package/src/csl/classify.ts +0 -77
- package/src/csl/exceptions/ClassificationError.ts +0 -16
- package/src/csl/exceptions/SegmentationError.ts +0 -19
- package/src/csl/exceptions/index.ts +0 -3
- package/src/csl/index.ts +0 -55
- package/src/csl/lineage.ts +0 -40
- package/src/csl/segment.ts +0 -100
- package/src/csl/types.ts +0 -113
- package/src/csl/utils.ts +0 -30
- package/src/csl/value-objects/ContentHash.ts +0 -48
- package/src/csl/value-objects/LineageEntry.ts +0 -33
- package/src/csl/value-objects/Origin-map.ts +0 -51
- package/src/csl/value-objects/Origin.ts +0 -52
- package/src/csl/value-objects/TrustLevel.ts +0 -33
- package/src/csl/value-objects/index.ts +0 -14
- package/src/index.ts +0 -94
- package/src/isl/exceptions/SanitizationError.ts +0 -14
- package/src/isl/exceptions/index.ts +0 -2
- package/src/isl/index.ts +0 -53
- package/src/isl/sanitize.ts +0 -93
- package/src/isl/types.ts +0 -87
- package/src/isl/value-objects/AnomalyScore.ts +0 -40
- package/src/isl/value-objects/Pattern.ts +0 -158
- package/src/isl/value-objects/PiDetection.ts +0 -92
- package/src/isl/value-objects/PiDetectionResult.ts +0 -129
- package/src/isl/value-objects/PolicyRule.ts +0 -117
- package/src/isl/value-objects/index.ts +0 -41
- package/src/shared/index.ts +0 -18
- package/src/shared/lineage.ts +0 -53
package/README.md
CHANGED
|
@@ -21,10 +21,13 @@ El protocolo AI-PIP está compuesto por las siguientes capas:
|
|
|
21
21
|
- **ISL (Instruction Sanitization Layer)**: Sanitiza instrucciones según nivel de confianza
|
|
22
22
|
- **CPE (Cryptographic Prompt Envelope)**: Genera envoltorio criptográfico con firma HMAC-SHA256
|
|
23
23
|
|
|
24
|
-
###
|
|
24
|
+
### 🔧 Features Compartidas
|
|
25
25
|
|
|
26
|
-
- **
|
|
27
|
-
|
|
26
|
+
- **Shared**: Funciones compartidas y linaje global e incremental (no es una capa, son features compartidas entre capas)
|
|
27
|
+
|
|
28
|
+
### 📝 Nota sobre AAL y Model Gateway
|
|
29
|
+
|
|
30
|
+
**AAL (Agent Action Lock)** y **Model Gateway** son componentes del SDK, no del core semántico. El core semántico se enfoca en funciones puras y señales, mientras que estas capas requieren decisiones operativas y efectos secundarios que pertenecen a la implementación (SDK).
|
|
28
31
|
|
|
29
32
|
## 📦 Instalación
|
|
30
33
|
|
|
@@ -38,50 +41,67 @@ yarn add @ai-pip/core
|
|
|
38
41
|
|
|
39
42
|
## 🚀 Uso Básico
|
|
40
43
|
|
|
41
|
-
### Importar
|
|
44
|
+
### Importar desde el paquete principal
|
|
42
45
|
|
|
43
46
|
```typescript
|
|
44
47
|
import { segment, sanitize, envelope } from '@ai-pip/core'
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
### Importar capas específicas
|
|
48
|
-
|
|
49
|
-
```typescript
|
|
50
|
-
// CSL - Context Segmentation Layer
|
|
51
|
-
import { segment, classifySource } from '@ai-pip/core/csl'
|
|
52
|
-
|
|
53
|
-
// ISL - Instruction Sanitization Layer
|
|
54
|
-
import { sanitize, createPolicyRule } from '@ai-pip/core/isl'
|
|
55
|
-
|
|
56
|
-
// CPE - Cryptographic Prompt Envelope
|
|
57
|
-
import { envelope, createNonce } from '@ai-pip/core/cpe'
|
|
58
|
-
|
|
59
|
-
// Shared utilities
|
|
60
|
-
import { addLineageEntry } from '@ai-pip/core/shared'
|
|
48
|
+
import type { CSLResult, ISLResult, CPEResult } from '@ai-pip/core'
|
|
61
49
|
```
|
|
62
50
|
|
|
63
51
|
### Ejemplo Completo
|
|
64
52
|
|
|
65
53
|
```typescript
|
|
66
|
-
import { segment } from '@ai-pip/core
|
|
67
|
-
import {
|
|
68
|
-
import { envelope } from '@ai-pip/core/cpe'
|
|
54
|
+
import { segment, sanitize, envelope } from '@ai-pip/core'
|
|
55
|
+
import type { CSLResult, ISLResult, CPEResult } from '@ai-pip/core'
|
|
69
56
|
|
|
70
57
|
// 1. Segmentar contenido (CSL)
|
|
71
|
-
const cslResult = segment({
|
|
58
|
+
const cslResult: CSLResult = segment({
|
|
72
59
|
content: 'User input here',
|
|
73
60
|
source: 'UI',
|
|
74
61
|
metadata: {}
|
|
75
62
|
})
|
|
76
63
|
|
|
77
64
|
// 2. Sanitizar contenido (ISL)
|
|
78
|
-
const islResult = sanitize(cslResult)
|
|
65
|
+
const islResult: ISLResult = sanitize(cslResult)
|
|
79
66
|
|
|
80
67
|
// 3. Generar envelope criptográfico (CPE)
|
|
81
68
|
const secretKey = 'your-secret-key'
|
|
82
|
-
const cpeResult = envelope(islResult, secretKey)
|
|
69
|
+
const cpeResult: CPEResult = envelope(islResult, secretKey)
|
|
83
70
|
|
|
84
71
|
// cpeResult.envelope contiene el prompt protegido
|
|
72
|
+
console.log(JSON.stringify(cpeResult, null, 2))
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### Ejemplo con funciones adicionales
|
|
76
|
+
|
|
77
|
+
```typescript
|
|
78
|
+
import {
|
|
79
|
+
segment,
|
|
80
|
+
sanitize,
|
|
81
|
+
envelope,
|
|
82
|
+
classifySource,
|
|
83
|
+
addLineageEntry,
|
|
84
|
+
createNonce
|
|
85
|
+
} from '@ai-pip/core'
|
|
86
|
+
import type {
|
|
87
|
+
CSLResult,
|
|
88
|
+
ISLResult,
|
|
89
|
+
CPEResult,
|
|
90
|
+
Source,
|
|
91
|
+
TrustLevel
|
|
92
|
+
} from '@ai-pip/core'
|
|
93
|
+
|
|
94
|
+
// Clasificar un source
|
|
95
|
+
const trust = classifySource('UI' as Source)
|
|
96
|
+
|
|
97
|
+
// Agregar entrada de linaje
|
|
98
|
+
const updatedLineage = addLineageEntry(cslResult.lineage, {
|
|
99
|
+
step: 'CUSTOM',
|
|
100
|
+
timestamp: Date.now()
|
|
101
|
+
})
|
|
102
|
+
|
|
103
|
+
// Generar nonce
|
|
104
|
+
const nonce = createNonce()
|
|
85
105
|
```
|
|
86
106
|
|
|
87
107
|
## 📚 Documentación
|
|
@@ -92,11 +112,14 @@ const cpeResult = envelope(islResult, secretKey)
|
|
|
92
112
|
- **[ISL - Instruction Sanitization Layer](docs/layer/isl.md)**: Documentación completa de la capa de sanitización
|
|
93
113
|
- **[CPE - Cryptographic Prompt Envelope](docs/layer/cpe.md)**: Documentación completa del envoltorio criptográfico
|
|
94
114
|
|
|
115
|
+
|
|
116
|
+
- **[Shared - Features Compartidas](docs/layer/shared.md)**: Funciones compartidas y linaje global
|
|
117
|
+
|
|
95
118
|
### Documentación General
|
|
96
119
|
|
|
120
|
+
- **[Whitepaper](docs/whitepaper.md)**: Especificación técnica completa del protocolo AI-PIP
|
|
121
|
+
- **[Roadmap](docs/roadmap.md)**: Plan de desarrollo y evolución del protocolo
|
|
97
122
|
- **[Arquitectura](docs/architecture.md)**: Arquitectura semántica del protocolo
|
|
98
|
-
- **[Roadmap](docs/roadmap.md)**: Plan de desarrollo y evolución
|
|
99
|
-
- **[Whitepaper](docs/whitepaper.md)**: Especificación técnica completa
|
|
100
123
|
- **[SDK Reference](docs/SDK.md)**: Referencia para desarrollo de SDKs
|
|
101
124
|
|
|
102
125
|
## 🧪 Testing
|
|
@@ -204,10 +227,48 @@ Las contribuciones son bienvenidas. Por favor:
|
|
|
204
227
|
- **NPM Package**: https://www.npmjs.com/package/@ai-pip/core
|
|
205
228
|
- **GitHub**: https://github.com/AI-PIP/ai-pip-core
|
|
206
229
|
|
|
230
|
+
## 🔮 Mejoras Futuras
|
|
231
|
+
|
|
232
|
+
### Imports por Capa Específica
|
|
233
|
+
|
|
234
|
+
Actualmente, se recomienda importar desde el paquete principal (`@ai-pip/core`) para evitar confusiones con nombres similares entre capas. En futuras versiones, se mejorará el soporte para imports directos desde capas específicas:
|
|
235
|
+
|
|
236
|
+
```typescript
|
|
237
|
+
// Futuro (en desarrollo)
|
|
238
|
+
import { segment } from '@ai-pip/core/csl'
|
|
239
|
+
import { sanitize } from '@ai-pip/core/isl'
|
|
240
|
+
import { envelope } from '@ai-pip/core/cpe'
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
Esto permitirá:
|
|
244
|
+
- **Mejor organización**: Importar solo lo necesario de cada capa
|
|
245
|
+
- **Evitar conflictos**: Prevenir confusiones con funciones de nombres similares
|
|
246
|
+
- **Tree-shaking mejorado**: Los bundlers podrán eliminar código no usado más eficientemente
|
|
247
|
+
|
|
248
|
+
**Nota**: Los exports por capa están técnicamente disponibles, pero se recomienda usar el paquete principal hasta que se complete la optimización de resolución de módulos.
|
|
249
|
+
|
|
207
250
|
---
|
|
208
251
|
|
|
209
252
|
## 📝 CHANGELOG
|
|
210
253
|
|
|
254
|
+
### [0.1.5] - 2025-12-28
|
|
255
|
+
|
|
256
|
+
#### 📚 Mejoras de Documentación
|
|
257
|
+
- **README actualizado**: Agregados links a whitepaper, roadmap y documentación completa de capas
|
|
258
|
+
- **Roadmap actualizado**: Agregado SDK-browser en Fase 4, actualizado estado de Fase 1 a 100% completado
|
|
259
|
+
- **Clarificación de arquitectura**: Corregida documentación sobre Shared (no es una capa, son features compartidas)
|
|
260
|
+
- **Nota sobre SDK**: Actualizada explicación sobre AAL y Model Gateway (son componentes del SDK, no del core)
|
|
261
|
+
|
|
262
|
+
#### 🔧 Optimizaciones
|
|
263
|
+
- **Reducción de tamaño del paquete**: Removido `src/` del campo `files` en `package.json` para hacer el paquete más liviano
|
|
264
|
+
- **Paquete optimizado**: Solo se incluyen archivos necesarios (`dist/`, `tsconfig.json`, `README.md`, `LICENSE`)
|
|
265
|
+
|
|
266
|
+
#### ✨ Mejoras
|
|
267
|
+
- **Documentación de capas**: Agregado link a documentación de Shared (features compartidas)
|
|
268
|
+
- **Organización de documentación**: Reorganizada sección de documentación con prioridad en whitepaper y roadmap
|
|
269
|
+
|
|
270
|
+
---
|
|
271
|
+
|
|
211
272
|
### [0.1.3] - 2025-12-28
|
|
212
273
|
|
|
213
274
|
#### ✨ Nuevas características
|
|
@@ -293,5 +354,5 @@ Las contribuciones son bienvenidas. Por favor:
|
|
|
293
354
|
|
|
294
355
|
---
|
|
295
356
|
|
|
296
|
-
**Versión actual**: 0.1.
|
|
297
|
-
**Estado**: Fase 1 - Capas Core (
|
|
357
|
+
**Versión actual**: 0.1.5
|
|
358
|
+
**Estado**: Fase 1 - Capas Core (100% completado)
|
package/dist/index.d.ts
CHANGED
|
@@ -2,13 +2,17 @@
|
|
|
2
2
|
* @ai-pip/core - Core implementation of the AI-PIP protocol
|
|
3
3
|
*
|
|
4
4
|
* @remarks
|
|
5
|
-
* Main entry point that re-exports all layers (CSL, ISL, Shared)
|
|
5
|
+
* Main entry point that re-exports all layers (CSL, ISL, CPE, Shared)
|
|
6
6
|
*
|
|
7
|
-
* You can
|
|
7
|
+
* You can import from specific layers:
|
|
8
8
|
* - import { segment } from '@ai-pip/core/csl'
|
|
9
9
|
* - import { sanitize } from '@ai-pip/core/isl'
|
|
10
|
-
* - import { addLineageEntry } from '@ai-pip/core/shared'
|
|
11
10
|
* - import { envelope } from '@ai-pip/core/cpe'
|
|
11
|
+
*
|
|
12
|
+
* Or import everything from the main entry point:
|
|
13
|
+
* - import { addLineageEntry, segment, sanitize, envelope } from '@ai-pip/core'
|
|
14
|
+
*
|
|
15
|
+
* Note: Shared functions are only available from the main entry point, not as a subpath.
|
|
12
16
|
*/
|
|
13
17
|
export { segment, classifySource, classifyOrigin, initLineage, createLineageEntry, generateId, splitByContextRules, OriginType, TrustLevelType, ClassificationError, SegmentationError } from './csl';
|
|
14
18
|
export type { HashAlgorithm, Source, CSLInput, CSLSegment, CSLResult, TrustLevel, Origin, LineageEntry, ContentHash } from './csl';
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAGH,OAAO,EACL,OAAO,EACP,cAAc,EACd,cAAc,EACd,WAAW,EACX,kBAAkB,EAClB,UAAU,EACV,mBAAmB,EACnB,UAAU,EACV,cAAc,EACd,mBAAmB,EACnB,iBAAiB,EAClB,MAAM,OAAO,CAAA;AACd,YAAY,EACV,aAAa,EACb,MAAM,EACN,QAAQ,EACR,UAAU,EACV,SAAS,EACT,UAAU,EACV,MAAM,EACN,YAAY,EACZ,WAAW,EACZ,MAAM,OAAO,CAAA;AAGd,OAAO,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAA;AAChC,YAAY,EACV,SAAS,EACT,aAAa,EACb,QAAQ,EACR,aAAa,EACb,cAAc,EACd,aAAa,EACb,oBAAoB,EACpB,kBAAkB,EAClB,UAAU,EACV,SAAS,EACT,WAAW,EACX,iBAAiB,EACjB,YAAY,EACZ,OAAO,EACR,MAAM,OAAO,CAAA;AACd,OAAO,EACL,iBAAiB,EACjB,kBAAkB,EAClB,gBAAgB,EAChB,kBAAkB,EAClB,eAAe,EACf,uBAAuB,EACvB,aAAa,EACb,iBAAiB,EACjB,mBAAmB,EACnB,6BAA6B,EAC7B,kBAAkB,EAClB,UAAU,EACV,UAAU,EACV,SAAS,EACT,aAAa,EACb,cAAc,EACd,SAAS,EACT,kBAAkB,EAClB,kBAAkB,EAClB,WAAW,EACX,iBAAiB,EAClB,MAAM,OAAO,CAAA;AAGd,OAAO,EACL,eAAe,EACf,iBAAiB,EACjB,mBAAmB,EACnB,mBAAmB,EACpB,MAAM,UAAU,CAAA;AAGjB,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,YAAY,EAAE,WAAW,EAAE,cAAc,EAAE,eAAe,EAAE,wBAAwB,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,OAAO,CAAA;AACnK,YAAY,EAAE,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,SAAS,EAAE,UAAU,EAAE,kBAAkB,EAAE,SAAS,EAAE,WAAW,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,OAAO,CAAA"}
|
package/dist/index.js
CHANGED
|
@@ -2,13 +2,17 @@
|
|
|
2
2
|
* @ai-pip/core - Core implementation of the AI-PIP protocol
|
|
3
3
|
*
|
|
4
4
|
* @remarks
|
|
5
|
-
* Main entry point that re-exports all layers (CSL, ISL, Shared)
|
|
5
|
+
* Main entry point that re-exports all layers (CSL, ISL, CPE, Shared)
|
|
6
6
|
*
|
|
7
|
-
* You can
|
|
7
|
+
* You can import from specific layers:
|
|
8
8
|
* - import { segment } from '@ai-pip/core/csl'
|
|
9
9
|
* - import { sanitize } from '@ai-pip/core/isl'
|
|
10
|
-
* - import { addLineageEntry } from '@ai-pip/core/shared'
|
|
11
10
|
* - import { envelope } from '@ai-pip/core/cpe'
|
|
11
|
+
*
|
|
12
|
+
* Or import everything from the main entry point:
|
|
13
|
+
* - import { addLineageEntry, segment, sanitize, envelope } from '@ai-pip/core'
|
|
14
|
+
*
|
|
15
|
+
* Note: Shared functions are only available from the main entry point, not as a subpath.
|
|
12
16
|
*/
|
|
13
17
|
// Re-export CSL
|
|
14
18
|
export { segment, classifySource, classifyOrigin, initLineage, createLineageEntry, generateId, splitByContextRules, OriginType, TrustLevelType, ClassificationError, SegmentationError } from './csl';
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,gBAAgB;AAChB,OAAO,EACL,OAAO,EACP,cAAc,EACd,cAAc,EACd,WAAW,EACX,kBAAkB,EAClB,UAAU,EACV,mBAAmB,EACnB,UAAU,EACV,cAAc,EACd,mBAAmB,EACnB,iBAAiB,EAClB,MAAM,OAAO,CAAA;AAad,gBAAgB;AAChB,OAAO,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAA;AAiBhC,OAAO,EACL,iBAAiB,EACjB,kBAAkB,EAClB,gBAAgB,EAChB,kBAAkB,EAClB,eAAe,EACf,uBAAuB,EACvB,aAAa,EACb,iBAAiB,EACjB,mBAAmB,EACnB,6BAA6B,EAC7B,kBAAkB,EAClB,UAAU,EACV,UAAU,EACV,SAAS,EACT,aAAa,EACb,cAAc,EACd,SAAS,EACT,kBAAkB,EAClB,kBAAkB,EAClB,WAAW,EACX,iBAAiB,EAClB,MAAM,OAAO,CAAA;AAEd,mBAAmB;AACnB,OAAO,EACL,eAAe,EACf,iBAAiB,EACjB,mBAAmB,EACnB,mBAAmB,EACpB,MAAM,UAAU,CAAA;AAEjB,gBAAgB;AAChB,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,YAAY,EAAE,WAAW,EAAE,cAAc,EAAE,eAAe,EAAE,wBAAwB,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,OAAO,CAAA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ai-pip/core",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.5",
|
|
4
4
|
"description": "Core implementation of the AI-PIP protocol. Provides layered, zero-trust context processing (CSL, ISL, CPE, ALL, ModelGateway)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -34,7 +34,6 @@
|
|
|
34
34
|
},
|
|
35
35
|
"files": [
|
|
36
36
|
"dist",
|
|
37
|
-
"src",
|
|
38
37
|
"tsconfig.json",
|
|
39
38
|
"README.md",
|
|
40
39
|
"LICENSE"
|
package/src/cpe/envelope.ts
DELETED
|
@@ -1,115 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Genera el envoltorio criptográfico (CPEEvelope) - función pura principal de CPE
|
|
3
|
-
*
|
|
4
|
-
* @remarks
|
|
5
|
-
* Esta es la función principal de CPE. Genera un envoltorio criptográfico
|
|
6
|
-
* que garantiza la integridad y autenticidad del prompt procesado.
|
|
7
|
-
*
|
|
8
|
-
* **Funciones:**
|
|
9
|
-
* - Genera metadata de seguridad (timestamp, nonce, versión)
|
|
10
|
-
* - Firma criptográficamente el contenido con HMAC-SHA256
|
|
11
|
-
* - Encapsula el contenido sanitizado con metadata
|
|
12
|
-
* - Preserva el linaje completo para auditoría
|
|
13
|
-
*
|
|
14
|
-
* @param islResult - Resultado de ISL con contenido sanitizado
|
|
15
|
-
* @param secretKey - Clave secreta para HMAC (debe ser proporcionada por el SDK)
|
|
16
|
-
* @returns CPEResult con el envelope criptográfico
|
|
17
|
-
*
|
|
18
|
-
* @throws {EnvelopeError} Si la generación del envelope falla
|
|
19
|
-
*
|
|
20
|
-
* @example
|
|
21
|
-
* ```typescript
|
|
22
|
-
* const cpeResult = envelope(islResult, secretKey)
|
|
23
|
-
*
|
|
24
|
-
* // cpeResult.envelope contiene:
|
|
25
|
-
* // - content: contenido sanitizado serializado
|
|
26
|
-
* // - signature: firma HMAC-SHA256
|
|
27
|
-
* // - metadata: timestamp, nonce, versión
|
|
28
|
-
* // - lineage: linaje completo
|
|
29
|
-
* ```
|
|
30
|
-
*/
|
|
31
|
-
import type { ISLResult } from '../isl/types'
|
|
32
|
-
import type { CPEEvelope, CPEResult } from './types'
|
|
33
|
-
import { createNonce } from './value-objects/Nonce'
|
|
34
|
-
import { createMetadata } from './value-objects/Metadata'
|
|
35
|
-
import { createSignature } from './value-objects/Signature'
|
|
36
|
-
import { EnvelopeError } from './exceptions'
|
|
37
|
-
// Serialización NO es core - va al SDK
|
|
38
|
-
// El core solo define la estructura del envelope
|
|
39
|
-
import { addLineageEntries } from '../shared/lineage'
|
|
40
|
-
import { createLineageEntry } from '../csl/value-objects/LineageEntry'
|
|
41
|
-
|
|
42
|
-
export function envelope(islResult: ISLResult, secretKey: string): CPEResult {
|
|
43
|
-
const startTime = Date.now()
|
|
44
|
-
|
|
45
|
-
try {
|
|
46
|
-
// 1. Validar input
|
|
47
|
-
if (!islResult?.segments?.length) {
|
|
48
|
-
throw new EnvelopeError('ISLResult must contain at least one segment')
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
if (!secretKey || secretKey.length === 0) {
|
|
52
|
-
throw new EnvelopeError('Secret key is required for envelope generation')
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
// 2. Generar metadata de seguridad
|
|
56
|
-
const timestamp = Date.now()
|
|
57
|
-
const nonce = createNonce()
|
|
58
|
-
const metadata = createMetadata(timestamp, nonce)
|
|
59
|
-
|
|
60
|
-
// 3. Preparar payload semántico (contenido procesado por ISL)
|
|
61
|
-
// El payload puede ser cualquier estructura que represente el contenido procesado
|
|
62
|
-
const payload: unknown = {
|
|
63
|
-
segments: islResult.segments.map((segment) => ({
|
|
64
|
-
id: segment.id,
|
|
65
|
-
content: segment.sanitizedContent,
|
|
66
|
-
trust: segment.trust.value,
|
|
67
|
-
sanitizationLevel: segment.sanitizationLevel,
|
|
68
|
-
})),
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
// 4. Generar firma criptográfica HMAC-SHA256
|
|
72
|
-
// Nota: La serialización del contenido para firma debe hacerse en el SDK
|
|
73
|
-
// El core solo define que se debe firmar el payload + metadata
|
|
74
|
-
// Por ahora, serializamos de forma básica para mantener funcionalidad
|
|
75
|
-
|
|
76
|
-
const algorithm = 'HMAC-SHA256'
|
|
77
|
-
const signableContent = JSON.stringify({
|
|
78
|
-
payload,
|
|
79
|
-
metadata,
|
|
80
|
-
algorithm
|
|
81
|
-
})
|
|
82
|
-
const signatureVO = createSignature(signableContent, secretKey)
|
|
83
|
-
|
|
84
|
-
// 5. Actualizar linaje con entrada CPE
|
|
85
|
-
const cpeLineageEntry = createLineageEntry('CPE', timestamp)
|
|
86
|
-
const updatedLineage = addLineageEntries(islResult.lineage, [cpeLineageEntry])
|
|
87
|
-
|
|
88
|
-
// 9. Construir envelope según especificación
|
|
89
|
-
const envelope: CPEEvelope = {
|
|
90
|
-
payload,
|
|
91
|
-
metadata,
|
|
92
|
-
signature: {
|
|
93
|
-
value: signatureVO.value,
|
|
94
|
-
algorithm: signatureVO.algorithm,
|
|
95
|
-
},
|
|
96
|
-
lineage: updatedLineage,
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
const processingTime = Date.now() - startTime
|
|
100
|
-
|
|
101
|
-
return {
|
|
102
|
-
envelope,
|
|
103
|
-
processingTimeMs: processingTime,
|
|
104
|
-
}
|
|
105
|
-
} catch (error) {
|
|
106
|
-
if (error instanceof EnvelopeError) {
|
|
107
|
-
throw error
|
|
108
|
-
}
|
|
109
|
-
throw new EnvelopeError(
|
|
110
|
-
`Failed to generate envelope: ${error instanceof Error ? error.message : 'Unknown error'}`,
|
|
111
|
-
error instanceof Error ? error : undefined
|
|
112
|
-
)
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* EnvelopeError - Error al generar el envelope criptográfico
|
|
3
|
-
*/
|
|
4
|
-
export class EnvelopeError extends Error {
|
|
5
|
-
constructor(message: string, public readonly cause?: Error) {
|
|
6
|
-
super(message)
|
|
7
|
-
this.name = 'EnvelopeError'
|
|
8
|
-
Object.setPrototypeOf(this, EnvelopeError.prototype)
|
|
9
|
-
}
|
|
10
|
-
}
|
|
11
|
-
|
package/src/cpe/index.ts
DELETED
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* CPE (Cryptographic Prompt Envelope) - Core Semántico
|
|
3
|
-
*
|
|
4
|
-
* @remarks
|
|
5
|
-
* Este es el core semántico de CPE. Solo contiene:
|
|
6
|
-
* - Funciones puras (sin estado)
|
|
7
|
-
* - Value objects inmutables
|
|
8
|
-
* - Tipos y excepciones
|
|
9
|
-
*
|
|
10
|
-
* **Funciones principales:**
|
|
11
|
-
* - Generación de metadata de seguridad (timestamp, nonce, versión)
|
|
12
|
-
* - Firma criptográfica HMAC-SHA256
|
|
13
|
-
* - Construcción del envelope criptográfico
|
|
14
|
-
* - Preservación del linaje completo
|
|
15
|
-
*/
|
|
16
|
-
|
|
17
|
-
// Funciones puras principales
|
|
18
|
-
export { envelope } from './envelope'
|
|
19
|
-
|
|
20
|
-
// Value objects
|
|
21
|
-
export { createNonce, isValidNonce, equalsNonce } from './value-objects/Nonce'
|
|
22
|
-
export type { Nonce } from './value-objects/Nonce'
|
|
23
|
-
export { createMetadata, isValidMetadata, CURRENT_PROTOCOL_VERSION } from './value-objects/Metadata'
|
|
24
|
-
export { createSignature } from './value-objects/Signature'
|
|
25
|
-
export type { SignatureVO } from './value-objects/Signature'
|
|
26
|
-
|
|
27
|
-
// Exceptions
|
|
28
|
-
export { EnvelopeError } from './exceptions/EnvelopeError'
|
|
29
|
-
|
|
30
|
-
// Types
|
|
31
|
-
export type {
|
|
32
|
-
ProtocolVersion,
|
|
33
|
-
Timestamp,
|
|
34
|
-
NonceValue,
|
|
35
|
-
SignatureAlgorithm,
|
|
36
|
-
Signature,
|
|
37
|
-
CPEMetadata,
|
|
38
|
-
CPEEvelope,
|
|
39
|
-
CPEResult
|
|
40
|
-
} from './types'
|
|
41
|
-
|
|
42
|
-
// Serialización y verificación NO son core - van al SDK
|
|
43
|
-
// El core solo define la estructura del envelope, no implementa serialización
|
|
44
|
-
|
package/src/cpe/types.ts
DELETED
|
@@ -1,68 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Types for CPE (Cryptographic Prompt Envelope) - Core Semántico
|
|
3
|
-
*/
|
|
4
|
-
|
|
5
|
-
// Importar tipos de CSL
|
|
6
|
-
import type { LineageEntry } from '../csl/value-objects'
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* ProtocolVersion - Versión del protocolo AI-PIP
|
|
10
|
-
*/
|
|
11
|
-
export type ProtocolVersion = string
|
|
12
|
-
|
|
13
|
-
/**
|
|
14
|
-
* Timestamp - Timestamp Unix en milisegundos
|
|
15
|
-
*/
|
|
16
|
-
export type Timestamp = number
|
|
17
|
-
|
|
18
|
-
/**
|
|
19
|
-
* NonceValue - Valor único para prevenir ataques de replay (string)
|
|
20
|
-
*/
|
|
21
|
-
export type NonceValue = string
|
|
22
|
-
|
|
23
|
-
/**
|
|
24
|
-
* SignatureAlgorithm - Algoritmo de firma criptográfica
|
|
25
|
-
*/
|
|
26
|
-
export type SignatureAlgorithm = 'HMAC-SHA256'
|
|
27
|
-
|
|
28
|
-
/**
|
|
29
|
-
* Signature - Firma criptográfica del envelope
|
|
30
|
-
*/
|
|
31
|
-
export type Signature = string
|
|
32
|
-
|
|
33
|
-
/**
|
|
34
|
-
* CPEMetadata - Metadata de seguridad del envelope
|
|
35
|
-
* Según especificación: timestamp, nonce, protocolVersion, previousSignatures opcionales
|
|
36
|
-
*/
|
|
37
|
-
export interface CPEMetadata {
|
|
38
|
-
readonly timestamp: Timestamp
|
|
39
|
-
readonly nonce: NonceValue
|
|
40
|
-
readonly protocolVersion: ProtocolVersion
|
|
41
|
-
readonly previousSignatures?: {
|
|
42
|
-
readonly csl?: string | undefined
|
|
43
|
-
readonly isl?: string | undefined
|
|
44
|
-
} | undefined
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/**
|
|
48
|
-
* CPEEvelope - Envoltorio criptográfico completo
|
|
49
|
-
* Según especificación: payload, metadata, signature (value + algorithm), lineage
|
|
50
|
-
*/
|
|
51
|
-
export interface CPEEvelope {
|
|
52
|
-
readonly payload: unknown // Payload semántico (contenido procesado)
|
|
53
|
-
readonly metadata: CPEMetadata
|
|
54
|
-
readonly signature: {
|
|
55
|
-
readonly value: string
|
|
56
|
-
readonly algorithm: string
|
|
57
|
-
}
|
|
58
|
-
readonly lineage: readonly LineageEntry[]
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
/**
|
|
62
|
-
* CPEResult - Resultado de la generación del envelope
|
|
63
|
-
*/
|
|
64
|
-
export interface CPEResult {
|
|
65
|
-
readonly envelope: CPEEvelope
|
|
66
|
-
readonly processingTimeMs?: number
|
|
67
|
-
}
|
|
68
|
-
|
package/src/cpe/utils.ts
DELETED
|
@@ -1,65 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Utilidades puras para CPE
|
|
3
|
-
*/
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* Serializa el contenido sanitizado de ISL para firma
|
|
7
|
-
*
|
|
8
|
-
* @param segments - Segmentos sanitizados
|
|
9
|
-
* @returns Contenido serializado
|
|
10
|
-
*/
|
|
11
|
-
export function serializeContent(segments: readonly { readonly sanitizedContent: string }[]): string {
|
|
12
|
-
return segments
|
|
13
|
-
.map((segment, index) => `[${index}]:${segment.sanitizedContent}`)
|
|
14
|
-
.join('\n')
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
/**
|
|
18
|
-
* Serializa metadata para firma
|
|
19
|
-
*
|
|
20
|
-
* @param metadata - Metadata a serializar
|
|
21
|
-
* @returns Metadata serializada
|
|
22
|
-
*/
|
|
23
|
-
export function serializeMetadata(metadata: {
|
|
24
|
-
readonly timestamp: number
|
|
25
|
-
readonly nonce: string
|
|
26
|
-
readonly protocolVersion: string
|
|
27
|
-
readonly previousSignatures?: {
|
|
28
|
-
readonly csl?: string | undefined
|
|
29
|
-
readonly isl?: string | undefined
|
|
30
|
-
} | undefined
|
|
31
|
-
}): string {
|
|
32
|
-
const parts = [
|
|
33
|
-
`timestamp:${metadata.timestamp}`,
|
|
34
|
-
`nonce:${metadata.nonce}`,
|
|
35
|
-
`version:${metadata.protocolVersion}`,
|
|
36
|
-
]
|
|
37
|
-
|
|
38
|
-
if (metadata.previousSignatures?.csl) {
|
|
39
|
-
parts.push(`csl:${metadata.previousSignatures.csl}`)
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
if (metadata.previousSignatures?.isl) {
|
|
43
|
-
parts.push(`isl:${metadata.previousSignatures.isl}`)
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
return parts.join('|')
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/**
|
|
50
|
-
* Genera el contenido completo para firma
|
|
51
|
-
* Según spec: contenido procesado + metadata + identificador del algoritmo
|
|
52
|
-
*
|
|
53
|
-
* @param content - Contenido serializado (payload semántico)
|
|
54
|
-
* @param metadata - Metadata serializada
|
|
55
|
-
* @param algorithm - Identificador del algoritmo de firma
|
|
56
|
-
* @returns Contenido completo para firma
|
|
57
|
-
*/
|
|
58
|
-
export function generateSignableContent(
|
|
59
|
-
content: string,
|
|
60
|
-
metadata: string,
|
|
61
|
-
algorithm: string
|
|
62
|
-
): string {
|
|
63
|
-
return `${metadata}\n---\n${content}\n---\nalgorithm:${algorithm}`
|
|
64
|
-
}
|
|
65
|
-
|
|
@@ -1,78 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* CPEMetadata - Metadata de seguridad del envelope
|
|
3
|
-
* Value Object puro e inmutable
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
import type { CPEMetadata, ProtocolVersion, Timestamp } from '../types'
|
|
7
|
-
import type { Nonce as NonceVO } from './Nonce'
|
|
8
|
-
|
|
9
|
-
/**
|
|
10
|
-
* Versión actual del protocolo
|
|
11
|
-
*/
|
|
12
|
-
export const CURRENT_PROTOCOL_VERSION: ProtocolVersion = '0.1.4'
|
|
13
|
-
|
|
14
|
-
/**
|
|
15
|
-
* Crea metadata de seguridad para el envelope
|
|
16
|
-
* Según especificación: timestamp, nonce, protocolVersion, previousSignatures opcionales
|
|
17
|
-
*
|
|
18
|
-
* @param timestamp - Timestamp Unix en milisegundos
|
|
19
|
-
* @param nonce - Nonce único
|
|
20
|
-
* @param protocolVersion - Versión del protocolo (default: CURRENT_PROTOCOL_VERSION)
|
|
21
|
-
* @param previousSignatures - Firmas opcionales de capas anteriores (csl, isl)
|
|
22
|
-
* @returns CPEMetadata inmutable
|
|
23
|
-
*/
|
|
24
|
-
export function createMetadata(
|
|
25
|
-
timestamp: Timestamp,
|
|
26
|
-
nonce: NonceVO,
|
|
27
|
-
protocolVersion: ProtocolVersion = CURRENT_PROTOCOL_VERSION,
|
|
28
|
-
previousSignatures?: {
|
|
29
|
-
csl?: string
|
|
30
|
-
isl?: string
|
|
31
|
-
}
|
|
32
|
-
): CPEMetadata {
|
|
33
|
-
// Validar timestamp
|
|
34
|
-
if (timestamp <= 0) {
|
|
35
|
-
throw new Error('Timestamp must be a positive number')
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
// Validar que no sea del futuro (con margen de 5 minutos para sincronización)
|
|
39
|
-
const maxFutureTimestamp = Date.now() + 5 * 60 * 1000
|
|
40
|
-
if (timestamp > maxFutureTimestamp) {
|
|
41
|
-
throw new Error('Timestamp cannot be in the future')
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
// Validar version del protocolo
|
|
45
|
-
if (!protocolVersion || typeof protocolVersion !== 'string') {
|
|
46
|
-
throw new Error('Protocol version must be a non-empty string')
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
return Object.freeze({
|
|
50
|
-
timestamp,
|
|
51
|
-
nonce: nonce.value,
|
|
52
|
-
protocolVersion,
|
|
53
|
-
previousSignatures: previousSignatures
|
|
54
|
-
? Object.freeze({
|
|
55
|
-
csl: previousSignatures.csl ?? undefined,
|
|
56
|
-
isl: previousSignatures.isl ?? undefined,
|
|
57
|
-
})
|
|
58
|
-
: undefined,
|
|
59
|
-
})
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
/**
|
|
63
|
-
* Valida que la metadata sea válida
|
|
64
|
-
*
|
|
65
|
-
* @param metadata - Metadata a validar
|
|
66
|
-
* @returns true si es válida
|
|
67
|
-
*/
|
|
68
|
-
export function isValidMetadata(metadata: CPEMetadata): boolean {
|
|
69
|
-
try {
|
|
70
|
-
if (metadata.timestamp <= 0) return false
|
|
71
|
-
if (!metadata.nonce || metadata.nonce.length < 16) return false
|
|
72
|
-
if (!metadata.protocolVersion) return false
|
|
73
|
-
return true
|
|
74
|
-
} catch {
|
|
75
|
-
return false
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
|