@nyx5/nyx5 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.
@@ -0,0 +1,38 @@
1
+ # Cómo contribuir a Chasqui
2
+
3
+ Chasqui es la implementación de referencia de un protocolo. La prioridad no es agregar
4
+ funciones: es que el estándar (`docs/SPEC.md`) y el código digan exactamente lo mismo.
5
+
6
+ ## Reglas duras
7
+
8
+ 1. **Cero dependencias.** No se agregan paquetes npm. Todo se resuelve con `node:` builtins.
9
+ Si algo parece necesitar una dependencia, casi siempre la respuesta es que no se necesita.
10
+ 2. **Un cambio de comportamiento sin test es un cambio a medias.** El test se escribe contra el
11
+ defecto real, no contra un ejemplo inventado. `npm test` corre en verde antes de cualquier PR.
12
+ 3. **Los invariantes no se rompen.** Están en `CLAUDE.md` y en `docs/SPEC.md §12`. El primero manda
13
+ sobre todos: *sin firma verificable no hay entrega*. Si tu cambio los toca, ábrelo como discusión
14
+ antes de escribir código.
15
+ 4. **El SPEC y el código se mueven juntos.** Un cambio en el formato del sobre, en un código de
16
+ error o en una operación del Libro cambia `docs/SPEC.md` en el mismo PR.
17
+
18
+ ## Antes de abrir un PR
19
+
20
+ ```
21
+ npm test # todas las pruebas verdes
22
+ npm run demo # correo: tarea cifrada, respuesta, acuse
23
+ npm run demo:contratos # libro: escrow, fianza, mandato en cadena
24
+ ```
25
+
26
+ ## Cómo se extiende (sin tocar el kernel)
27
+
28
+ - **Nuevo contrato**: una entrada en `src/libro/contratos.js` (`ops.<nombre>` y, si se cotiza,
29
+ `CONTRATOS.<kind>`). No se toca `src/libro/libro.js`.
30
+ - **Nueva política de buzón**: `src/correo/politica.js` (`applyInboxPolicy`).
31
+ - **Nueva extensión**: un URI `urn:chasqui:ext:*` declarado en la tarjeta; los datos viajan en
32
+ `extensions[uri]` del sobre. Los campos desconocidos se conservan y se firman, pero se ignoran.
33
+
34
+ ## Estilo
35
+
36
+ Sustantivos del dominio en español (sobre, estafeta, tarjeta, libro, asiento, casa, mandato,
37
+ fianza, estampilla); nombres de métodos y campos JSON en inglés cuando ya son convención
38
+ (`send`, `accept`, `release`). Sin abreviaturas crípticas. El código se lee como el que lo rodea.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,133 @@
1
+ # Nyx5/1
2
+
3
+ **Correo y Libro para agentes de IA, en una sola pieza.** Un agente tiene tres cosas que no
4
+ tiene de otra forma: una **dirección** propia (`agente@dominio`), un **buzón** que guarda aunque
5
+ esté apagado, y un **libro contable** donde un acuerdo pesa —el pago se retiene hasta cumplir, y
6
+ una afirmación falsa cuesta dinero—. Cada mensaje va firmado; cada movimiento de dinero deja un
7
+ recibo que nadie puede negar. Sin dependencias, sobre Node y Cloudflare Workers.
8
+
9
+ ```bash
10
+ node examples/hola-mundo.mjs # una casa, dos agentes, un sobre firmado y cifrado (~20 líneas)
11
+ ```
12
+
13
+ - **Correo**: direcciones `agente@dominio`, buzón que guarda aunque estés apagado, firma verificable, cifrado extremo a extremo, compatible con MCP y A2A.
14
+ - **Libro**: el ledger de cada casa. Cotizaciones firmadas, contratos (spot, escrow, fianza, medido), mandatos en cadena, estampillas, recibos que nadie puede negar. Sin login: se opera escribiéndole a `libro@<casa>` con la misma identidad del Correo.
15
+
16
+ **Enlaces**: la casa → [nyx5.com](https://nyx5.com) · la especificación en una página → [nyx5.com/spec](https://nyx5.com/spec) ·
17
+ `docs/SPEC.md` (el estándar) · `docs/ARQUITECTURA.md` (operación y producción) ·
18
+ `CONTRIBUTING.md` · `SECURITY.md` · licencia [Apache-2.0](LICENSE) ·
19
+ implementación de referencia en `src/` (Node 20+, cero dependencias).
20
+
21
+ ## Probar en 1 minuto
22
+
23
+ ```bash
24
+ npm run demo # correo: dos dominios, tarea cifrada, respuesta, acuse de entrega
25
+ npm run demo:offline # correo: el destino está apagado: cola, reintento, entrega al volver
26
+ npm run demo:spam # correo: firma falsa, remitente inexistente, allowlist, proof-of-work, duplicados
27
+ npm run demo:contratos # libro: spot, escrow, fianza, mandato en cadena, agente delegado, estampilla
28
+ npm run demo:piloto # libro: una flota con presupuesto, escrow + verificación medida, costo por entrega
29
+ npm test # 70 pruebas automatizadas
30
+ ```
31
+
32
+ ## Probar por partes (dos terminales)
33
+
34
+ `hosts.local.json` ya mapea `alfa.local` y `beta.local` a los puertos 4001 y 4002 (en producción esto lo hace el DNS).
35
+
36
+ Terminal 1 y 2, una estafeta por dominio:
37
+ ```bash
38
+ node bin/nyx5.js estafeta --domain alfa.local --port 4001 --data ./data/alfa --admin-token secreto-alfa
39
+ node bin/nyx5.js estafeta --domain beta.local --port 4002 --data ./data/beta --admin-token secreto-beta
40
+ ```
41
+
42
+ Terminal 3, los agentes:
43
+ ```bash
44
+ node bin/nyx5.js keygen --address nicolas@alfa.local --estafeta http://127.0.0.1:4001
45
+ node bin/nyx5.js keygen --address asistente@beta.local --estafeta http://127.0.0.1:4002
46
+ node bin/nyx5.js register --agent keys/nicolas.json --admin-token secreto-alfa
47
+ node bin/nyx5.js register --agent keys/asistente.json --admin-token secreto-beta --mcp http://127.0.0.1:4010/mcp
48
+
49
+ node bin/nyx5.js card --address asistente@beta.local
50
+ node bin/nyx5.js send --agent keys/nicolas.json --to asistente@beta.local --type task --json --body '{"skill":"resumir","input":"hola"}'
51
+ node bin/nyx5.js inbox --agent keys/asistente.json --ack
52
+ node bin/nyx5.js outbox --agent keys/nicolas.json
53
+ ```
54
+
55
+ Apaga la terminal 2, envía otro sobre, mira `outbox` (queda en `retrying`), vuelve a levantar beta y mira cómo llega.
56
+
57
+ Registro como servicio: levanta la estafeta con `--registration invite` (o `open`), emite códigos con `node bin/nyx5.js invite --estafeta http://127.0.0.1:4001 --admin-token secreto-alfa --uses 5 --welcome 100`, y cada agente entra con `register --agent keys/x.json --invite CODIGO` sin tocar el token de la casa. `node bin/nyx5.js directory --house alfa.local --capability mcp` lista quién ofrece qué.
58
+
59
+ Políticas de buzón al registrar: `--policy allowlist --allow socio@gamma.local`, `--policy pow --pow-bits 16`, o `--policy stamp` (cobra por recibir; el precio se fija en la tarjeta).
60
+
61
+ ## El Libro por terminal
62
+
63
+ ```bash
64
+ node bin/nyx5.js topup --estafeta http://127.0.0.1:4001 --admin-token secreto-alfa --account nicolas@alfa.local --amount 1000
65
+ node bin/nyx5.js keygen --address verifica@alfa.local --estafeta http://127.0.0.1:4001
66
+ node bin/nyx5.js register --agent keys/verifica.json --admin-token secreto-alfa
67
+ node bin/nyx5.js quote --agent keys/verifica.json --to nicolas@alfa.local --price 40 --concept "verificación" --contract escrow
68
+ node bin/nyx5.js inbox --agent keys/nicolas.json # copia el content.body de la cotización a un archivo
69
+ node bin/nyx5.js accept --agent keys/nicolas.json --quote cotizacion.json
70
+ node bin/nyx5.js inbox --agent keys/nicolas.json # llega el recibo de libro@ con el contrato y el asiento
71
+ node bin/nyx5.js libro --agent keys/verifica.json --op deliver --json --body '{"contract":"<id>","evidence_sha256":"..."}'
72
+ node bin/nyx5.js libro --agent keys/nicolas.json --op release --json --body '{"contract":"<id>"}'
73
+ node bin/nyx5.js balance --agent keys/nicolas.json
74
+ node bin/nyx5.js delegate --agent keys/nicolas.json --name bot --scope '{"types":["message","result"],"cap":100}'
75
+ ```
76
+
77
+ Fianza: `--op bond --body '{"amount":50,"claim":"desplegado y verificado","verifier":"verifica@alfa.local"}'`. Mandato: `--op mandate --body '{"grantee":"bot.nicolas@alfa.local","cap":200}'`; luego el mandatario cobra con `--op charge --body '{"mandate":"<id>","amount":30,"concept":"tokens de modelo"}'`.
78
+
79
+ ## Usarlo desde Claude Desktop / Claude Code (puente MCP)
80
+
81
+ Cualquier cliente MCP puede leer y escribir sobres como herramientas. En `claude_desktop_config.json`:
82
+
83
+ ```json
84
+ {
85
+ "mcpServers": {
86
+ "chasqui": {
87
+ "command": "node",
88
+ "args": ["/ruta/a/chasqui/bin/nyx5.js", "mcp", "--agent", "/ruta/a/chasqui/keys/nicolas.json"],
89
+ "env": { "CHASQUI_HOSTS": "/ruta/a/chasqui/hosts.local.json" }
90
+ }
91
+ }
92
+ }
93
+ ```
94
+
95
+ Herramientas expuestas: correo `nyx5_send`, `nyx5_inbox`, `nyx5_ack`, `nyx5_resolve`, `nyx5_outbox`, `nyx5_directory`; libro `nyx5_quote`, `nyx5_accept`, `nyx5_libro`, `nyx5_balance`, `nyx5_contract`. Con eso, Claude puede decir "revisa mi buzón, acepta la cotización de verifica si es menor a 50 y libera el escrow del constructor".
96
+
97
+ ## Pasar a un dominio real (ej. sigo.uk)
98
+
99
+ 1. Levanta la estafeta en un servidor con TLS: `--domain sigo.uk --public-url https://mail.sigo.uk`.
100
+ 2. Copia `keys[0].sig` de `data/sigo.uk/domain.json` y publica en DNS: `_nyx5.sigo.uk TXT "v=nyx51; url=https://mail.sigo.uk; sig=<esa clave>"`.
101
+ 3. Registra tus agentes (`nicolas@sigo.uk`, `asistente@sigo.uk`).
102
+ 4. Cualquier estafeta del mundo ya puede resolverte y escribirte, sin `hosts.json`.
103
+
104
+ Detalles, esquema de base de datos, seguridad operativa y hoja de ruta en `docs/ARQUITECTURA.md`.
105
+
106
+ ## Estructura
107
+
108
+ ```
109
+ CLAUDE.md guía para Claude Code
110
+ bin/nyx5.js CLI (correo: estafeta, keygen, register, invite, directory, card, send, inbox, ack, outbox, mcp · libro: topup, balance, quote, accept, libro, contract, delegate)
111
+ src/nucleo/crypto.js Ed25519, X25519+AES-GCM, JSON canónico, sha256, proof-of-work
112
+ src/nucleo/almacen.js persistencia en archivos de ambos componentes (interfaz para Postgres/D1)
113
+ src/correo/resolver.js DNS / well-known / override, cadena de confianza y de delegación, caché, rotación
114
+ src/correo/politica.js validación de sobres, allowlist / pow / stamp / rate limit
115
+ src/correo/estafeta.js servidor de dominio: registro (admin/invite/open), directorio, cola, reintentos, verificación, buzones, webhooks, libro@
116
+ src/correo/agente.js cliente: correo (send, inbox, open, reply, receipt, delegate) + libro (quote, accept, deliver, release, refund, bond, forfeit, mandate, charge, revoke, balance)
117
+ src/libro/libro.js kernel del ledger: asientos firmados, primitivas, verificación de cotizaciones, estampillas
118
+ src/libro/contratos.js contratos: spot, escrow, fianza, medido, mandatos en cadena
119
+ src/puentes/mcp.js puente MCP por stdio
120
+ demo/ e2e, offline, spam, contratos, piloto-d4 (economía de una flota)
121
+ examples/ hola-mundo.mjs (el ejemplo mínimo, ~20 líneas)
122
+ test/ correo, libro, registro, invariantes+D1, índice, concurrencia, altos, diferidos (70)
123
+ ```
124
+
125
+ ## Para seguir construyendo con Claude Code
126
+
127
+ Abre el repo en Claude Code; `CLAUDE.md` le da el mapa y los invariantes. Prompts útiles, en orden:
128
+
129
+ 1. "Piloto en casa: crea un script `demo/piloto.js` que registre mis sesiones como agentes, cargue el presupuesto mensual por frente como topup, y modele una cajita como escrow con prueba de aceptación." (Fase 1 de la hoja de ruta.)
130
+ 2. "Implementa `D1Store` (Cloudflare D1) con la misma interfaz que `FileStore`, incluidos los métodos `libro*`, usando el esquema de `docs/ARQUITECTURA.md` sección 4.2, y haz que `Estafeta` acepte `store` como opción."
131
+ 3. "Agrega un `Dockerfile` y un `fly.toml` para correr la estafeta de sigo.uk con volumen persistente."
132
+ 4. "Implementa la extensión `urn:nyx5:ext:email`: un receptor SMTP mínimo que deposite correos en el buzón con `from_verified: false`."
133
+ 5. "Agrega el contrato `bounty` en `contratos.js` (fondos retenidos; cobra el primero que pase el criterio) con su test."
package/SECURITY.md ADDED
@@ -0,0 +1,28 @@
1
+ # Política de seguridad
2
+
3
+ Chasqui mueve identidad, mensajes cifrados y un ledger. Una vulnerabilidad aquí no es un bug
4
+ cualquiera. Agradecemos el reporte responsable.
5
+
6
+ ## Cómo reportar
7
+
8
+ Reporta en privado a **security@chsq.uk**. No abras un issue público para una vulnerabilidad.
9
+ Incluye: qué invariante se rompe, cómo reproducirlo, y el impacto. Respondemos el recibo del
10
+ reporte lo antes posible y coordinamos una divulgación una vez que haya un arreglo.
11
+
12
+ ## Qué es una vulnerabilidad aquí
13
+
14
+ El modelo de amenazas está en `docs/SPEC.md §12`. En corto, es un reporte de seguridad si permite:
15
+
16
+ - **Entregar un sobre sin firma verificable** (rompe el invariante 1) o hacer pasar por verificado
17
+ algo que no lo es.
18
+ - **Leer contenido cifrado** desde la estafeta o un relay (el invariante 8: la estafeta no lo lee).
19
+ - **Mover tokens sin un sobre firmado** a `libro@`, dejar un asiento que no cuadra, o hacer que
20
+ alguien salvo `casa@` quede en negativo (invariante 3).
21
+ - **Registrar una clave que no se controla**, pisar un nombre ajeno, o exceder el ámbito de un
22
+ mandato o de una tarjeta delegada (invariantes 6 y 9).
23
+ - **Filtrar una clave privada** (de dominio o de agente) por cualquier endpoint.
24
+
25
+ ## Alcance
26
+
27
+ Esta es una implementación de referencia. Un despliegue en producción (Cloudflare Workers + D1)
28
+ suma su propia superficie: la configuración del despliegue es responsabilidad de quien lo opera.
package/bin/nyx5.js ADDED
@@ -0,0 +1,184 @@
1
+ #!/usr/bin/env node
2
+ // Nyx5/1 — CLI
3
+ //
4
+ // nyx5 estafeta --domain alfa.local --port 4001 --data ./data/alfa --admin-token secreto [--registration admin|invite|open] [--welcome 100] [--fee 0.10]
5
+ // nyx5 keygen --address nicolas@alfa.local --estafeta http://127.0.0.1:4001 --out ./keys/nicolas.json
6
+ // nyx5 register --agent ./keys/nicolas.json --admin-token secreto [--policy open|allowlist|pow|stamp] [--allow a@b,c@d] [--pow-bits 16] [--webhook URL] [--mcp URL] [--a2a URL]
7
+ // nyx5 register --agent ./keys/nicolas.json --invite CODIGO (o sin nada, si la casa tiene registration=open)
8
+ // nyx5 invite --estafeta http://127.0.0.1:4001 --admin-token secreto [--uses 1] [--expires ISO] [--note "para Marta"]
9
+ // nyx5 directory [--house alfa.local | --estafeta URL] [--capability mcp] [--accepts media] [--q texto]
10
+ // nyx5 search --index indice.local [--q texto] [--capability mcp] [--accepts media] [--house uno.local]
11
+ // nyx5 card --address asistente@beta.local
12
+ // nyx5 send --agent ./keys/nicolas.json --to asistente@beta.local --body "hola" [--json] [--type task] [--plain]
13
+ // nyx5 inbox --agent ./keys/nicolas.json [--ack]
14
+ // nyx5 ack --agent ./keys/nicolas.json --id <id>[,<id>]
15
+ // nyx5 outbox --agent ./keys/nicolas.json
16
+ // nyx5 mcp --agent ./keys/nicolas.json (servidor MCP por stdio)
17
+ // --- Libro ---
18
+ // nyx5 topup --estafeta http://127.0.0.1:4001 --admin-token secreto --account nicolas@alfa.local --amount 1000
19
+ // nyx5 balance --agent ./keys/nicolas.json [--house alfa.local]
20
+ // nyx5 quote --agent ./keys/verifica.json --to nicolas@alfa.local --price 40 --concept "verificación" [--contract spot|escrow|metered] [--terms '{...}'] [--arbiter a@casa] [--expires ISO]
21
+ // nyx5 accept --agent ./keys/nicolas.json --quote <archivo.json o JSON> (o `inbox` te muestra la cotización; cópiala)
22
+ // nyx5 libro --agent ./keys/nicolas.json --op release --args '{"contract":"..."}' [--house alfa.local]
23
+ // nyx5 contract --agent ./keys/nicolas.json --id <contrato>
24
+ // nyx5 delegate --agent ./keys/constructor.json --name tester --scope '{"types":["message","result"],"cap":100}' --out ./keys/tester.json
25
+ //
26
+ // Resolución local: --hosts hosts.json, o CHASQUI_HOSTS, o ./hosts.local.json si existe.
27
+
28
+ import fs from 'node:fs';
29
+ import path from 'node:path';
30
+ import { parseArgs } from 'node:util';
31
+ import { Estafeta } from '../src/correo/estafeta.js';
32
+ import { Agent } from '../src/correo/agente.js';
33
+ import { Resolver } from '../src/correo/resolver.js';
34
+ import { runMcpServer } from '../src/puentes/mcp.js';
35
+
36
+ const [cmd, ...rest] = process.argv.slice(2);
37
+ const { values: o } = parseArgs({ args: rest, allowPositionals: true, options: {
38
+ domain: { type: 'string' }, port: { type: 'string' }, data: { type: 'string' }, 'admin-token': { type: 'string' }, 'public-url': { type: 'string' },
39
+ 'require-relay': { type: 'boolean' }, hosts: { type: 'string' }, registration: { type: 'string' }, welcome: { type: 'string' }, fee: { type: 'string' },
40
+ invite: { type: 'string' }, uses: { type: 'string' }, expires: { type: 'string' }, note: { type: 'string' }, capability: { type: 'string' }, accepts: { type: 'string' }, q: { type: 'string' },
41
+ address: { type: 'string' }, estafeta: { type: 'string' }, out: { type: 'string' }, agent: { type: 'string' },
42
+ policy: { type: 'string' }, allow: { type: 'string' }, 'pow-bits': { type: 'string' }, webhook: { type: 'string' }, mcp: { type: 'string' }, a2a: { type: 'string' },
43
+ to: { type: 'string' }, body: { type: 'string' }, type: { type: 'string' }, json: { type: 'boolean' }, plain: { type: 'boolean' }, thread: { type: 'string' }, 'reply-to': { type: 'string' },
44
+ ack: { type: 'boolean' }, id: { type: 'string' },
45
+ account: { type: 'string' }, amount: { type: 'string' }, house: { type: 'string' }, price: { type: 'string' }, concept: { type: 'string' }, contract: { type: 'string' }, terms: { type: 'string' },
46
+ quote: { type: 'string' }, op: { type: 'string' }, name: { type: 'string' }, scope: { type: 'string' },
47
+ args: { type: 'string' }, index: { type: 'string' }, arbiter: { type: 'string' }, receipt: { type: 'string' }, limit: { type: 'string' },
48
+ } });
49
+
50
+ const need = (k) => { if (!o[k]) { console.error(`falta --${k}`); process.exit(2); } return o[k]; };
51
+ const loadHosts = () => {
52
+ const file = o.hosts || process.env.CHASQUI_HOSTS || (fs.existsSync('hosts.local.json') ? 'hosts.local.json' : null);
53
+ if (!file && ['send', 'inbox', 'card', 'directory'].includes(cmd)) console.error('aviso: sin hosts.local.json en este cwd; la resolución irá por DNS/well-known');
54
+ return file ? JSON.parse(fs.readFileSync(file, 'utf8')) : {};
55
+ };
56
+ const loadAgent = () => Agent.load(need('agent'), { hosts: loadHosts() });
57
+ const warnHosts = (h) => { if (!Object.keys(h).length && !process.env.CHASQUI_HOSTS) console.error('aviso: sin hosts.local.json en este directorio; la resolución irá por DNS/well-known'); return h; };
58
+ const print = (v) => console.log(JSON.stringify(v, null, 2));
59
+
60
+ try {
61
+ switch (cmd) {
62
+ case 'estafeta': {
63
+ const e = new Estafeta({
64
+ domain: need('domain'), port: Number(o.port || 4000), dataDir: need('data'),
65
+ adminToken: o['admin-token'] || process.env.CHASQUI_ADMIN_TOKEN || need('admin-token'),
66
+ publicUrl: o['public-url'], hosts: loadHosts(),
67
+ policy: { require_relay: !!o['require-relay'], registration: o.registration || 'admin' },
68
+ libro: { welcome: Number(o.welcome || 0), feePct: o.fee != null ? Number(o.fee) : null },
69
+ });
70
+ await e.start();
71
+ process.on('SIGINT', async () => { await e.stop(); process.exit(0); });
72
+ break;
73
+ }
74
+ case 'keygen': {
75
+ const a = Agent.create(need('address'), need('estafeta'));
76
+ const out = o.out || `./keys/${a.local}.json`;
77
+ fs.mkdirSync(path.dirname(out), { recursive: true });
78
+ fs.writeFileSync(out, JSON.stringify({ address: a.address, estafeta: a.estafeta, keys: a.keys }, null, 2), { mode: 0o600 });
79
+ console.log(`claves de ${a.address} guardadas en ${out} (guárdalo como una contraseña)`);
80
+ console.log(`clave pública de firma: ${a.keys.sig}`);
81
+ break;
82
+ }
83
+ case 'register': {
84
+ const a = await loadAgent();
85
+ const inbox = { policy: o.policy || 'open' };
86
+ if (o.allow) inbox.allowlist = o.allow.split(',').map((s) => s.trim());
87
+ if (o['pow-bits']) inbox.pow_bits = Number(o['pow-bits']);
88
+ const capabilities = {};
89
+ if (o.mcp) capabilities.mcp = o.mcp;
90
+ if (o.a2a) capabilities.a2a = o.a2a;
91
+ print(await a.register({ adminToken: o['admin-token'] || process.env.CHASQUI_ADMIN_TOKEN, invite: o.invite, inbox, capabilities, webhook: o.webhook }));
92
+ break;
93
+ }
94
+ case 'invite': {
95
+ const res = await fetch(`${need('estafeta')}/invitations`, { method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${o['admin-token'] || process.env.CHASQUI_ADMIN_TOKEN}` }, body: JSON.stringify({ uses: Number(o.uses || 1), expires: o.expires || null, note: o.note || null, welcome: o.welcome != null ? Number(o.welcome) : null }) });
96
+ print(await res.json()); break;
97
+ }
98
+ case 'directory': {
99
+ const params = new URLSearchParams(Object.entries({ capability: o.capability, accepts: o.accepts, q: o.q }).filter(([, v]) => v));
100
+ let base = o.estafeta;
101
+ if (!base) { const r = new Resolver({ hosts: loadHosts() }); base = (await r.domainCard(need('house')))._estafeta; }
102
+ const d = await (await fetch(`${base}/agents?${params}`)).json();
103
+ console.log(`${d.total} agente(s)`);
104
+ for (const a of d.agents) console.log(` ${a.address.padEnd(36)} ${Object.keys(a.capabilities || {}).filter((k) => k !== 'accepts').join(',') || '-'} buzón=${a.inbox?.policy}${a.delegated_by ? ' delegado por ' + a.delegated_by : ''}`);
105
+ break;
106
+ }
107
+ case 'search': {
108
+ const r = new Resolver({ hosts: loadHosts() });
109
+ const idx = need('index');
110
+ const base = idx.startsWith('http') ? idx.replace(/\/$/, '') : (await r.domainCard(idx))._estafeta;
111
+ const params = new URLSearchParams(Object.entries({ q: o.q, capability: o.capability, accepts: o.accepts, house: o.house, limit: o.limit }).filter(([, v]) => v));
112
+ const d = await (await fetch(`${base}/index/agents?${params}`)).json();
113
+ console.log(`${d.total} agente(s) en el índice ${d.index || idx}`);
114
+ for (const a of d.agents || []) console.log(` ${a.address.padEnd(40)} casa=${a._house || '-'} ${Object.keys(a.capabilities || {}).filter((k) => k !== 'accepts').join(',') || '-'}`);
115
+ break;
116
+ }
117
+ case 'card': {
118
+ const r = new Resolver({ hosts: loadHosts() });
119
+ const { _domain, ...card } = await r.agentCard(need('address'));
120
+ print(card);
121
+ break;
122
+ }
123
+ case 'send': {
124
+ const a = await loadAgent();
125
+ const body = o.json ? JSON.parse(need('body')) : need('body');
126
+ const r = await a.send({ to: need('to').split(',').map((s) => s.trim()), body, type: o.type || 'message', encrypt: !o.plain, thread: o.thread, inReplyTo: o['reply-to'], receipt: o.receipt });
127
+ print({ id: r.id, jobs: r.jobs, encrypted: !!r.envelope.encrypted });
128
+ break;
129
+ }
130
+ case 'inbox': {
131
+ const a = await loadAgent();
132
+ const msgs = await a.inbox({ limit: Number(o.limit || 50) });
133
+ if (!msgs.length) { console.log('buzón vacío'); break; }
134
+ const abiertos = [];
135
+ for (const m of msgs) {
136
+ try { const op = await a.open(m.envelope); const { sender, ...rest } = op; abiertos.push(m.envelope.id); print({ ...rest, received: m.received, relay_verified: m.relay_verified }); }
137
+ catch (e) { print({ id: m.envelope.id, from: m.envelope.from, error: e.message }); }
138
+ }
139
+ // --ack confirma SOLO lo abierto con éxito: un sobre que no descifra se queda en el buzón.
140
+ if (o.ack && abiertos.length) console.log('ack:', await a.ack(abiertos));
141
+ break;
142
+ }
143
+ case 'ack': print({ acked: await (await loadAgent()).ack(need('id').split(',')) }); break;
144
+ case 'outbox': print(await (await loadAgent()).outbox()); break;
145
+ case 'mcp': await runMcpServer({ agentFile: need('agent'), hosts: loadHosts() }); break;
146
+
147
+ // ----- Libro -----
148
+ case 'topup': {
149
+ const res = await fetch(`${need('estafeta')}/libro/topup`, { method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${o['admin-token'] || process.env.CHASQUI_ADMIN_TOKEN}` }, body: JSON.stringify({ account: need('account'), amount: Number(need('amount')), concept: o.concept }) });
150
+ print(await res.json()); break;
151
+ }
152
+ case 'balance': print(await (await loadAgent()).balance(o.house)); break;
153
+ case 'quote': {
154
+ const a = await loadAgent();
155
+ const r = await a.quote({ to: need('to'), contract: o.contract || 'spot', price: Number(need('price')), concept: need('concept'), terms: o.terms ? JSON.parse(o.terms) : undefined, arbiter: o.arbiter, expires: o.expires, house: o.house });
156
+ print({ sent: r.id, quote: r.quote }); break;
157
+ }
158
+ case 'accept': {
159
+ const raw = need('quote');
160
+ const q = fs.existsSync(raw) ? JSON.parse(fs.readFileSync(raw, 'utf8')) : JSON.parse(raw);
161
+ print(await (await loadAgent()).accept(q.content?.body || q)); break;
162
+ }
163
+ case 'libro': {
164
+ const a = await loadAgent();
165
+ const extra = o.args ? JSON.parse(o.args) : (o.json ? JSON.parse(o.body || '{}') : {});
166
+ print(await a.libroOp(o.house || a.domain, { op: need('op'), ...extra })); break;
167
+ }
168
+ case 'contract': { const a = await loadAgent(); print(await a.contract(o.house || a.domain, need('id'))); break; }
169
+ case 'delegate': {
170
+ const a = await loadAgent();
171
+ const sub = await a.delegate(need('name'), { scope: o.scope ? JSON.parse(o.scope) : {} });
172
+ const out = o.out || `./keys/${sub.local}.json`;
173
+ fs.mkdirSync(path.dirname(out), { recursive: true });
174
+ fs.writeFileSync(out, JSON.stringify({ address: sub.address, estafeta: sub.estafeta, keys: sub.keys }, null, 2), { mode: 0o600 });
175
+ console.log(`agente delegado ${sub.address} creado; claves en ${out}`); break;
176
+ }
177
+ default:
178
+ console.log(fs.readFileSync(new URL(import.meta.url)).toString().split('\n').slice(1, 27).map((l) => l.replace(/^\/\/ ?/, '')).join('\n'));
179
+ process.exit(cmd ? 1 : 0);
180
+ }
181
+ } catch (e) {
182
+ console.error('error:', e.message);
183
+ process.exit(1);
184
+ }