@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
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,165 @@
1
+ # @ai-pip/core
2
+
3
+ > Core implementation of the AI-PIP protocol. Provides layered, zero-trust context processing (CSL, ISL, CPE) to protect AI systems from prompt injection and malicious context manipulation.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@ai-pip/core)](https://www.npmjs.com/package/@ai-pip/core)
6
+ [![License](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE)
7
+
8
+ ## 📋 Descripción
9
+
10
+ **AI-PIP (AI Prompt Integrity Protocol)** es un protocolo de seguridad de múltiples capas diseñado para proteger sistemas de IA contra prompt injection y manipulación maliciosa de contexto.
11
+
12
+ Este paquete contiene la implementación **core** del protocolo, que incluye funciones puras, value objects inmutables y contratos semánticos entre capas.
13
+
14
+ ## 🏗️ Arquitectura
15
+
16
+ El protocolo AI-PIP está compuesto por las siguientes capas:
17
+
18
+ ### ✅ Capas Implementadas
19
+
20
+ - **CSL (Context Segmentation Layer)**: Segmenta y clasifica contenido según su origen
21
+ - **ISL (Instruction Sanitization Layer)**: Sanitiza instrucciones según nivel de confianza
22
+ - **CPE (Cryptographic Prompt Envelope)**: Genera envoltorio criptográfico con firma HMAC-SHA256
23
+
24
+ ### ⏳ Capas Pendientes
25
+
26
+ - **AAL (Agent Action Lock)**: Bloqueo de acciones de agentes
27
+ - **Model Gateway**: Interfaz con modelos de IA
28
+
29
+ ## 📦 Instalación
30
+
31
+ ```bash
32
+ pnpm add @ai-pip/core
33
+ # o
34
+ npm install @ai-pip/core
35
+ # o
36
+ yarn add @ai-pip/core
37
+ ```
38
+
39
+ ## 🚀 Uso Básico
40
+
41
+ ### Importar capas completas
42
+
43
+ ```typescript
44
+ 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'
61
+ ```
62
+
63
+ ### Ejemplo Completo
64
+
65
+ ```typescript
66
+ import { segment } from '@ai-pip/core/csl'
67
+ import { sanitize } from '@ai-pip/core/isl'
68
+ import { envelope } from '@ai-pip/core/cpe'
69
+
70
+ // 1. Segmentar contenido (CSL)
71
+ const cslResult = segment({
72
+ content: 'User input here',
73
+ source: 'UI',
74
+ metadata: {}
75
+ })
76
+
77
+ // 2. Sanitizar contenido (ISL)
78
+ const islResult = sanitize(cslResult)
79
+
80
+ // 3. Generar envelope criptográfico (CPE)
81
+ const secretKey = 'your-secret-key'
82
+ const cpeResult = envelope(islResult, secretKey)
83
+
84
+ // cpeResult.envelope contiene el prompt protegido
85
+ ```
86
+
87
+ ## 📚 Documentación
88
+
89
+ ### Documentación de Capas
90
+
91
+ - **[CSL - Context Segmentation Layer](docs/layer/csl.md)**: Documentación completa de la capa de segmentación
92
+ - **[ISL - Instruction Sanitization Layer](docs/layer/isl.md)**: Documentación completa de la capa de sanitización
93
+ - **[CPE - Cryptographic Prompt Envelope](docs/layer/cpe.md)**: Documentación completa del envoltorio criptográfico
94
+
95
+ ### Documentación General
96
+
97
+ - **[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
+ - **[SDK Reference](docs/SDK.md)**: Referencia para desarrollo de SDKs
101
+
102
+ ## 🧪 Testing
103
+
104
+ ```bash
105
+ # Ejecutar tests
106
+ pnpm test
107
+
108
+ # Tests en modo watch
109
+ pnpm test:watch
110
+
111
+ # Tests con cobertura
112
+ pnpm test:coverage
113
+
114
+ # UI de tests
115
+ pnpm test:ui
116
+ ```
117
+
118
+ **Cobertura actual**: 87%
119
+
120
+ ## 🔧 Desarrollo
121
+
122
+ ```bash
123
+ # Instalar dependencias
124
+ pnpm install
125
+
126
+ # Type checking
127
+ pnpm type-check
128
+
129
+ # Linting
130
+ pnpm lint
131
+
132
+ # Desarrollo
133
+ pnpm dev
134
+ ```
135
+
136
+ ## 📋 Requisitos
137
+
138
+ - **Node.js**: >= 18.0.0
139
+ - **pnpm**: >= 8.0.0
140
+
141
+ ## 📄 Licencia
142
+
143
+ Apache-2.0 - Ver [LICENSE](LICENSE) para más detalles.
144
+
145
+ ## 🤝 Contribuir
146
+
147
+ Las contribuciones son bienvenidas. Por favor:
148
+
149
+ 1. Revisa el [Roadmap](docs/roadmap.md) para ver qué está pendiente
150
+ 2. Abre un issue para discutir cambios mayores
151
+ 3. Envía un pull request con tus mejoras
152
+
153
+ **Repositorio**: https://github.com/AI-PIP/ai-pip-core
154
+ **Issues**: https://github.com/AI-PIP/ai-pip-core/issues
155
+
156
+ ## 🔗 Enlaces
157
+
158
+ - **Documentación**: [docs/](docs/)
159
+ - **NPM Package**: https://www.npmjs.com/package/@ai-pip/core
160
+ - **GitHub**: https://github.com/AI-PIP/ai-pip-core
161
+
162
+ ---
163
+
164
+ **Versión**: 0.1.0
165
+ **Estado**: Fase 1 - Capas Core (60% completado)
package/package.json ADDED
@@ -0,0 +1,79 @@
1
+ {
2
+ "name": "@ai-pip/core",
3
+ "version": "0.1.0",
4
+ "description": "Core implementation of the AI-PIP protocol. Provides layered, zero-trust context processing (CSL, ISL, CPE, ALL, ModelGateway)",
5
+ "type": "module",
6
+ "main": "./src/index.ts",
7
+ "types": "./src/index.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./src/index.ts",
11
+ "import": "./src/index.ts"
12
+ },
13
+ "./csl": {
14
+ "types": "./src/csl/index.ts",
15
+ "import": "./src/csl/index.ts"
16
+ },
17
+ "./isl": {
18
+ "types": "./src/isl/index.ts",
19
+ "import": "./src/isl/index.ts"
20
+ },
21
+ "./cpe": {
22
+ "types": "./src/cpe/index.ts",
23
+ "import": "./src/cpe/index.ts"
24
+ },
25
+ "./shared": {
26
+ "types": "./src/shared/index.ts",
27
+ "import": "./src/shared/index.ts"
28
+ }
29
+ },
30
+ "files": [
31
+ "src",
32
+ "tsconfig.json",
33
+ "README.md",
34
+ "LICENSE"
35
+ ],
36
+ "engines": {
37
+ "node": ">= 18.0.0"
38
+ },
39
+ "keywords": [
40
+ "ai",
41
+ "security",
42
+ "prompt-injection",
43
+ "context-processing",
44
+ "zero-trust"
45
+ ],
46
+ "author": "MasliahDev d3vTek-mv@outlook.com",
47
+ "repository": {
48
+ "type": "git",
49
+ "url": "https://github.com/AI-PIP/ai-pip-core"
50
+ },
51
+ "bugs": {
52
+ "url": "https://github.com/AI-PIP/ai-pip-core/issues"
53
+ },
54
+ "homepage": "https://github.com/AI-PIP/ai-pip-core#readme",
55
+ "license": "Apache-2.0",
56
+ "devDependencies": {
57
+ "@eslint/js": "^9.39.2",
58
+ "@types/node": "^22.19.3",
59
+ "@vitest/coverage-v8": "^2.1.9",
60
+ "eslint": "^9.39.2",
61
+ "tsx": "^4.21.0",
62
+ "typescript": "^5.9.3",
63
+ "typescript-eslint": "^8.50.1",
64
+ "vitest": "^2.1.9"
65
+ },
66
+ "publishConfig": {
67
+ "access": "public"
68
+ },
69
+ "scripts": {
70
+ "dev": "tsx src/index.ts",
71
+ "type-check": "tsc --noEmit",
72
+ "build": "tsc",
73
+ "lint": "eslint src --max-warnings=0",
74
+ "test": "vitest",
75
+ "test:watch": "vitest --watch",
76
+ "test:ui": "vitest --ui",
77
+ "test:coverage": "vitest --coverage"
78
+ }
79
+ }
@@ -0,0 +1,115 @@
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
+
@@ -0,0 +1,11 @@
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
+
@@ -0,0 +1,6 @@
1
+ /**
2
+ * CPE Exceptions - Exports
3
+ */
4
+
5
+ export { EnvelopeError } from './EnvelopeError'
6
+
@@ -0,0 +1,35 @@
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 * from './exceptions'
29
+
30
+ // Types
31
+ export * from './types'
32
+
33
+ // Serialización y verificación NO son core - van al SDK
34
+ // El core solo define la estructura del envelope, no implementa serialización
35
+
@@ -0,0 +1,68 @@
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
+