dataspace-client-sdk-node 0.1.1

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 (56) hide show
  1. package/README.md +310 -0
  2. package/SDK_PARITY_MAP.md +120 -0
  3. package/TODO_PROMPT_NEXT_STEPS.md +185 -0
  4. package/artifacts/update-smart-wallet.js +1016 -0
  5. package/dist/builders.d.ts +12 -0
  6. package/dist/builders.js +17 -0
  7. package/dist/client.d.ts +333 -0
  8. package/dist/client.js +1229 -0
  9. package/dist/consent/pdfSignatureVerification.d.ts +18 -0
  10. package/dist/consent/pdfSignatureVerification.js +23 -0
  11. package/dist/index.d.ts +4 -0
  12. package/dist/index.js +8 -0
  13. package/dist/sdk/dataspace-wallet-sdk-node/MultiWalletClient.d.ts +9 -0
  14. package/dist/sdk/dataspace-wallet-sdk-node/MultiWalletClient.js +21 -0
  15. package/dist/sdk/dataspace-wallet-sdk-node/WalletClient.d.ts +26 -0
  16. package/dist/sdk/dataspace-wallet-sdk-node/WalletClient.js +36 -0
  17. package/dist/sdk/dataspace-wallet-sdk-node/index.d.ts +6 -0
  18. package/dist/sdk/dataspace-wallet-sdk-node/index.js +6 -0
  19. package/dist/sdk/dataspace-wallet-sdk-node/provider.d.ts +24 -0
  20. package/dist/sdk/dataspace-wallet-sdk-node/provider.js +1 -0
  21. package/dist/sdk/dataspace-wallet-sdk-node/providers/memory-provider.d.ts +41 -0
  22. package/dist/sdk/dataspace-wallet-sdk-node/providers/memory-provider.js +216 -0
  23. package/dist/sdk/dataspace-wallet-sdk-node/providers/seed-provider.d.ts +22 -0
  24. package/dist/sdk/dataspace-wallet-sdk-node/providers/seed-provider.js +28 -0
  25. package/dist/sdk/dataspace-wallet-sdk-node/types.d.ts +51 -0
  26. package/dist/sdk/dataspace-wallet-sdk-node/types.js +1 -0
  27. package/dist/types.d.ts +445 -0
  28. package/dist/types.js +1 -0
  29. package/docs/API.md +745 -0
  30. package/docs/DATA_MODEL_ALIGNMENT.md +31 -0
  31. package/docs/DATA_PLANES_SCOPE_MATRIX.md +51 -0
  32. package/docs/DEVELOPER_USE_CASES.md +253 -0
  33. package/docs/E2E_BOOTSTRAP.md +54 -0
  34. package/docs/TODO_SMART_EHR_COMPAT.md +58 -0
  35. package/examples/backend-pkce-auth.mjs +119 -0
  36. package/examples/conversion-upload.mjs +52 -0
  37. package/examples/e2e-bootstrap-tenant.mjs +126 -0
  38. package/examples/e2e-individual-flow.mjs +43 -0
  39. package/examples/host-activate-and-employee.mjs +75 -0
  40. package/package.json +26 -0
  41. package/src/builders.ts +28 -0
  42. package/src/client.ts +1626 -0
  43. package/src/consent/pdfSignatureVerification.ts +41 -0
  44. package/src/index.ts +8 -0
  45. package/src/sdk/dataspace-wallet-sdk-node/MultiWalletClient.ts +25 -0
  46. package/src/sdk/dataspace-wallet-sdk-node/WalletClient.ts +63 -0
  47. package/src/sdk/dataspace-wallet-sdk-node/index.ts +6 -0
  48. package/src/sdk/dataspace-wallet-sdk-node/provider.ts +44 -0
  49. package/src/sdk/dataspace-wallet-sdk-node/providers/memory-provider.ts +310 -0
  50. package/src/sdk/dataspace-wallet-sdk-node/providers/seed-provider.ts +31 -0
  51. package/src/sdk/dataspace-wallet-sdk-node/types.ts +61 -0
  52. package/src/types.ts +497 -0
  53. package/tests/client.test.mjs +892 -0
  54. package/tests/uc5-org-onboarding.flow.test.mjs +145 -0
  55. package/tests/uc5-subject-data.flow.test.mjs +198 -0
  56. package/tsconfig.json +13 -0
package/README.md ADDED
@@ -0,0 +1,310 @@
1
+ # dataspace-client-sdk-node
2
+
3
+ Node.js SDK to consume GW/UNID async DIDComm plain endpoints.
4
+
5
+ **[→ Full API Reference](docs/API.md)**
6
+ **[→ Data Model Alignment (GW + Chat + SDK)](docs/DATA_MODEL_ALIGNMENT.md)**
7
+ **[→ Frontend/Backend SDK Ownership Matrix](../docs/SDK_AUTH_OWNERSHIP.md)**
8
+ **[→ Developer Use-Case Cookbook (UC5 + additional patterns)](docs/DEVELOPER_USE_CASES.md)**
9
+
10
+ ## Scope
11
+ - Generic async batch client (`_batch` + `_batch-response`) and JSON POST helper.
12
+ - Route builders that cover Swagger v1 route families:
13
+ - `host/registry`: `Organization _batch/_activate`, `Order`,
14
+ - `entity`: `Employee`,
15
+ - `identity`: `Device/_dcr`, `Token/_exchange`, `License/_issue`, SMART token, Firebase custom token,
16
+ - `individual`: `Organization`, `Order`, `Person (legacy)`, `Consent`, `Composition`, `Communication`, `RelatedPerson`, `Observation`, `Task`,
17
+ - `digitaltwin`: `Composition` (`org.hl7.fhir.api` and `org.hl7.fhir.r4`),
18
+ - debug UHC task endpoints: `_call-start`, `_logs`.
19
+
20
+ ## Claims Placement Contract
21
+ - Canonical batch-entry claims location: `entry.resource.meta.claims`.
22
+ - Legacy compatibility location: `entry.meta.claims`.
23
+ - This SDK now emits both during migration; new consumers should read/write `resource.meta.claims`.
24
+
25
+ ## Install (local workspace)
26
+
27
+ ```bash
28
+ cd tools/dataspace-client-sdk-node
29
+ npm install
30
+ npm run type-check
31
+ npm run build
32
+ ```
33
+
34
+ ## Tests (mocked, no network)
35
+
36
+ The SDK includes mocked tests (Python-SDK style) for:
37
+ - route/path building,
38
+ - async `submit + poll`,
39
+ - multipart conversion upload.
40
+
41
+ Run:
42
+ ```bash
43
+ cd sdk/dataspace-client-sdk-node
44
+
45
+ npm test
46
+
47
+ ```
48
+
49
+
50
+ ```ts
51
+ import { DataspaceNodeClient, createDidcommPlainMessage } from './dist/index.js';
52
+ const client = new DataspaceNodeClient({
53
+ baseUrl: 'http://localhost:3000',
54
+ bearerToken: 'demo-token',
55
+ });
56
+
57
+ const ctx = { tenantId: 'acme', jurisdiction: 'ES', sector: 'health-care' };
58
+ iss: 'adult1@example.com',
59
+ aud: 'did:web:api.acme.org',
60
+ body: {
61
+ data: [
62
+ {
63
+ type: 'Family-registration-form-v1.0',
64
+ meta: {
65
+ claims: {
66
+ '@context': 'org.schema',
67
+ '@type': 'template',
68
+ 'org.schema.Organization.address.addressCountry': 'ES',
69
+ 'org.schema.Organization.identifier.additionalType': 'UUID',
70
+ 'org.schema.Organization.identifier.value': 'f0d4b66d-7e28-4fa2-91b7-7041e57f4f90',
71
+ 'org.schema.Person.email': 'adult1@example.com',
72
+ 'org.schema.Service.category': 'health-care',
73
+ 'org.schema.Service.identifier': 'did:web:api-provider.example.com',
74
+ 'org.schema.Service.serviceType': 'http://terminology.hl7.org/CodeSystem/v3-ActReason|SRVC',
75
+ 'org.schema.Service.termsOfService': 'https://provider.example.com/terms',
76
+ },
77
+ },
78
+ },
79
+ ],
80
+ },
81
+ });
82
+
83
+ const submitPath = client.individualFamilyOrganizationBatchPath(ctx);
84
+ const pollPath = client.individualFamilyOrganizationPollPath(ctx);
85
+ const result = await client.submitAndPoll(submitPath, pollPath, payload);
86
+ console.log(result.poll.status, result.poll.body);
87
+ ```
88
+
89
+ ## Backend auth: identity-exchange.v1 (B2B PKCE flow)
90
+
91
+ For server-to-server integration (e.g. `uhc-unid-chat-node` calling the GW), the SDK implements the
92
+ full `identity-exchange.v1` flow: DCR binding → PKCE code → token → SMART bearer exchange.
93
+
94
+ This is the Node equivalent of Python's `authenticate_backend_pkce_and_exchange` in `connector-sdk-py`.
95
+
96
+ **Prerequisites:**
97
+ 1. Your tenant org is activated in the GW (`registry/org.schema/Organization/_activate` with ICA VC).
98
+ 2. An API key with the required scopes has been issued by ICA (`identity/api-key/_create`).
99
+ 3. You have your service's public JWK (EC P-384 recommended).
100
+
101
+ **Usage:**
102
+
103
+ ```ts
104
+ import { DataspaceNodeClient } from './dist/index.js';
105
+
106
+ const client = new DataspaceNodeClient({ baseUrl: 'https://gw.example.com' });
107
+
108
+ const ctx = { tenantId: 'acme', jurisdiction: 'ES', sector: 'health-care' };
109
+
110
+ // Run once per key pair; result is cached automatically.
111
+ const auth = await client.authenticateBackendPkceAndExchange({
112
+ ctx,
113
+ apiKey: process.env.GW_API_KEY!,
114
+ controllerPublicJwk: JSON.parse(process.env.GW_PUBLIC_JWK!),
115
+ scopes: ['onboarding', 'family-registration', 'license-order'],
116
+ endpointId: 'chatbot-main', // cache key; re-auth on expiry is automatic
117
+ });
118
+
119
+ if (auth.status === 'failed') {
120
+ throw new Error(`Backend auth failed at step: ${auth.step}`);
121
+ }
122
+
123
+ // Use the bearer for subsequent requests:
124
+ const authedClient = new DataspaceNodeClient({
125
+ baseUrl: 'https://gw.example.com',
126
+ bearerToken: auth.accessToken,
127
+ });
128
+ ```
129
+
130
+ **Demo / local bypass (never for production):**
131
+
132
+ ```ts
133
+ // .env: SECURITY_MODE=demo GW_AUTH_BEARER=static-demo-token
134
+ const client = new DataspaceNodeClient({
135
+ baseUrl: process.env.BASE_URL!,
136
+ bearerToken: process.env.GW_AUTH_BEARER, // skip identity-exchange.v1 entirely
137
+ });
138
+ ```
139
+
140
+ ## Backend auth: smart-backend.v1 (client_credentials + private_key_jwt)
141
+
142
+ For direct OAuth2 machine-to-machine flows (bypassing the PKCE device flow), use the
143
+ `smart-backend.v1` profile. The SDK signs the `client_assertion` JWT locally using an
144
+ in-memory ES384 wallet.
145
+
146
+ This is the Node equivalent of Python's `authenticate_backend_smart_standard` in
147
+ `connector-sdk-py`.
148
+
149
+ **Usage:**
150
+
151
+ ```ts
152
+ import { DataspaceNodeClient, MemoryWalletProvider } from './dist/index.js';
153
+
154
+ const wallet = new MemoryWalletProvider();
155
+
156
+ // walletContext scopes the key pair. Use the service's logical identity.
157
+ const walletContext = { tenantId: 'service-a', jurisdiction: 'ES', sector: 'health-care' };
158
+
159
+ const client = new DataspaceNodeClient({
160
+ baseUrl: 'https://gw.example.com',
161
+ wallet,
162
+ });
163
+
164
+ // On first call, authenticates. On subsequent calls within token TTL, returns cached.
165
+ const result = await client.authenticateBackendSmartStandard({
166
+ clientId: 'service-a',
167
+ scopes: ['system/*.read', 'system/*.write'],
168
+ walletContext,
169
+ // tokenUrl: optional absolute URL; defaults to `${baseUrl}/token`
170
+ // audience: optional; defaults to the resolved tokenUrl
171
+ // assertionTtlSeconds: optional; defaults to 300
172
+ });
173
+
174
+ if (result.status === 'failed') {
175
+ throw new Error(`smart-backend.v1 auth failed: HTTP ${result.statusCode}`);
176
+ }
177
+
178
+ const authedClient = new DataspaceNodeClient({
179
+ baseUrl: 'https://gw.example.com',
180
+ bearerToken: result.accessToken,
181
+ });
182
+ ```
183
+
184
+ **How it works internally:**
185
+ 1. `MemoryWalletProvider` generates a dedicated EC P-384 key (`use: sig`, `alg: ES384`).
186
+ 2. `signCompactJws(...)` produces the `client_assertion` JWT signed with that key.
187
+ 3. A single `client_credentials` POST to the token endpoint returns the bearer.
188
+ 4. The token is cached until 30s before expiry; subsequent calls return `status: 'cached'`.
189
+
190
+ ## DIDComm encrypted (nested JWS-in-JWE)
191
+
192
+ For GW endpoints that require `application/didcomm-encrypted+json`, use `submitBatchEncrypted`.
193
+ This implements the nested JOSE pattern expected by the backend: sign first (ES384 compact JWS),
194
+ then encrypt (ML-KEM-768 + A256GCM compact JWE with `cty: JWS`).
195
+
196
+ Requires a wallet provider and the recipient's ML-KEM-768 encryption JWK (from GW
197
+ `.well-known/jwks.json`, `use: enc`). The `MemoryWalletProvider` generates ML-KEM-768 keys
198
+ automatically — no RSA setup required.
199
+
200
+ ### ML-KEM-768 JWK format
201
+
202
+ Encryption keys use the OKP JWK type with `crv: "ML-KEM-768"`:
203
+
204
+ ```json
205
+ {
206
+ "kty": "OKP",
207
+ "crv": "ML-KEM-768",
208
+ "use": "enc",
209
+ "alg": "ML-KEM-768",
210
+ "x": "<base64url-encoded 1184-byte public key>",
211
+ "kid": "wallet:acme:ES:health-care:abc123"
212
+ }
213
+ ```
214
+
215
+ The `encrypted_key` slot in the compact JWE is the 1088-byte ML-KEM ciphertext (base64url).
216
+ The 32-byte shared secret derived by KEM encapsulation is used directly as the AES-256-GCM CEK.
217
+
218
+ ```ts
219
+ import { DataspaceNodeClient, MemoryWalletProvider } from './dist/index.js';
220
+
221
+ const wallet = new MemoryWalletProvider();
222
+ const walletContext = { tenantId: 'acme', jurisdiction: 'ES', sector: 'health-care' };
223
+ const client = new DataspaceNodeClient({ baseUrl: 'https://gw.example.com', wallet });
224
+
225
+ // Wallet's own ML-KEM enc JWK (share with backend so it can encrypt to you):
226
+ const [, encJwk] = await wallet.getPublicJwks(walletContext);
227
+
228
+ // Fetch GW encryption JWK from well-known endpoint for outbound encryption:
229
+ // const { keys } = await (await fetch('https://gw.example.com/.well-known/jwks.json')).json();
230
+ // const recipientEncJwk = keys.find(k => k.use === 'enc' && k.crv === 'ML-KEM-768');
231
+
232
+ // For local roundtrip test, use wallet's own enc key as recipient:
233
+ const recipientEncJwk = encJwk;
234
+
235
+ const payload = { thid: 'my-thid', body: { data: [] } };
236
+ const result = await client.submitBatchEncrypted(
237
+ client.individualFamilyOrganizationBatchPath(ctx),
238
+ payload,
239
+ recipientEncJwk,
240
+ walletContext,
241
+ );
242
+ ```
243
+
244
+ **Cache helper** — if you need the current bearer without re-running the flow:
245
+
246
+ ```ts
247
+ const bearer = client.getCachedBearerToken('chatbot-main');
248
+ // Returns undefined if not cached or expired (>30s remaining).
249
+ ```
250
+
251
+ Full runnable example: `examples/backend-pkce-auth.mjs`
252
+
253
+ ## Swagger parity strategy
254
+ - For any v1 route exposed in Swagger, use:
255
+ - `client.v1Path(ctx, section, format, resourceType, action)` for tenant routes.
256
+ - `client.hostRegistryPath(ctx, resourceType, action)` for host registry routes.
257
+ - Then call one of:
258
+ - `submitBatch(path, didcommPayload)` for DIDComm plain submit routes,
259
+ - `pollBatchResponse(path, { thid })` / `pollUntilComplete(...)`,
260
+ - `postJson(path, payload)` for non-batch JSON routes.
261
+
262
+ This avoids hardcoding curl scripts per endpoint.
263
+
264
+ ## Notes for telephony tests
265
+ - Keep GW/UHC unit/integration tests direct (service/router level).
266
+ - Use this SDK for consumer-style E2E tests and external Node.js service integrations.
267
+ - If individual onboarding moves to a separate service, telephony tests should consume that service and only use GW/UHC for reminders/calls.
268
+
269
+ ## DataConversion / Excel
270
+
271
+ This SDK now includes conversion helpers:
272
+ - `conversionUploadPath(ctx, softwareId, sourceFormat)`
273
+ - `conversionUploadPollPath(ctx, softwareId, sourceFormat)`
274
+ - `uploadConversionFile({ path, fileName, fileContent, fields })`
275
+
276
+ Example:
277
+ - `examples/conversion-upload.mjs`
278
+
279
+ Run:
280
+ ```bash
281
+ cd sdk/dataspace-client-sdk-node
282
+ npm run build
283
+ BASE_URL="http://localhost:3000" \
284
+ AUTH_BEARER="demo-token" \
285
+ TENANT_ID="acme" \
286
+ JURISDICTION="ES" \
287
+ SECTOR="animal-care" \
288
+ SOFTWARE_ID="excel-adapter" \
289
+ SOURCE_FORMAT="xlsx" \
290
+ SOURCE_FILE="/absolute/path/to/input.xlsx" \
291
+ node examples/conversion-upload.mjs
292
+ ```
293
+
294
+ Notes:
295
+ - Exact multipart field names may vary by DataConversion deployment.
296
+ - If your conversion API is synchronous, polling is optional.
297
+ - If it is async, provide/resolve `thid` and poll `.../_upload-response`.
298
+
299
+ ## Next planned additions
300
+ - Typed payload builders per flow (`family`, `relatedPerson`, `observation`, `task`).
301
+ - Claims mappers (`ClaimName` <-> SQL internal name with `_`).
302
+ - Retry/backoff + richer error mapping.
303
+
304
+ ## Planning and Parity Docs
305
+
306
+ - TODO / execution prompt: `TODO_PROMPT_NEXT_STEPS.md`
307
+ - Node/Python API parity map: `SDK_PARITY_MAP.md`
308
+
309
+ ## Pending Compatibility TODO
310
+ - See [SMART EHR compatibility TODO](docs/TODO_SMART_EHR_COMPAT.md).
@@ -0,0 +1,120 @@
1
+ # SDK Parity Map (Node vs Python)
2
+
3
+ Estado: guía de referencia para alinear `dataspace-client-sdk-node` con `connector-sdk-py`.
4
+
5
+ Convención:
6
+ - Node SDK: `dataspace-client-sdk-node`
7
+ - Python SDK: `connector-sdk-py`
8
+ - Wallet interno temporal en Node: `src/sdk/dataspace-wallet-sdk-node/`
9
+
10
+ ## 0) Repos fuente del ecosistema (contexto obligatorio)
11
+
12
+ | Repo | Rol |
13
+ |---|---|
14
+ | `dataspace-client-sdk-node` | SDK backend Node (este repo) |
15
+ | `connector-sdk-py` | referencia de paridad backend Python |
16
+ | `gdc-sdk-client-ts` | SDK/frontend wallet UX-side |
17
+ | `gwtemplate-node-ts` | base backend GW + `gdc-backend-utils-node` |
18
+ | `gdc-unid-node-ts` | fork operativo de GW para UNID |
19
+ | `uhc-unid-chat-node` | consumidor de alto nivel (voice/chat orchestration) |
20
+
21
+ ## 1) Perímetro de paridad
22
+
23
+ La paridad se mide por capacidades, no por nombres internos exactos:
24
+
25
+ 1. Auth backend (PKCE + exchange / SMART backend)
26
+ 2. Submit + poll de operaciones de dominio
27
+ 3. Lifecycle de API keys
28
+ 4. Wallet/KMS cliente (firma, verificación, cifrado, descifrado)
29
+
30
+ ## 2) Identity Routes (canónicas)
31
+
32
+ Patrón objetivo para rutas de identidad:
33
+
34
+ `/{prefix}/cds-{jurisdiction}/v1/{sector}/{tenantId}/identity/auth/{action}`
35
+
36
+ Donde `prefix` depende del servicio:
37
+ - `host` (GW)
38
+ - `publisher` (DataConv)
39
+ - `ica` (ICA)
40
+
41
+ Nota de compatibilidad:
42
+ - Consumidores que usan métodos de alto nivel (`authenticateBackendPkceAndExchange`) no deberían depender de este detalle.
43
+ - Consumidores que montaban rutas manuales sí deben migrar.
44
+
45
+ ## 3) Paridad de Auth
46
+
47
+ | Capability | Node SDK | Python SDK | Estado objetivo |
48
+ |---|---|---|---|
49
+ | Identity DCR submit/poll | path builder + submit/poll | operación equivalente | ✅ |
50
+ | Identity code submit/poll | path builder + submit/poll | operación equivalente | ✅ |
51
+ | Identity token submit/poll | path builder + submit/poll | operación equivalente | ✅ |
52
+ | Identity exchange submit/poll | path builder + submit/poll | operación equivalente | ✅ |
53
+ | PKCE orchestration | `authenticateBackendPkceAndExchange(...)` | `authenticate_backend_pkce_and_exchange(...)` | ✅ |
54
+ | SMART backend orchestration | método Node equivalente (pendiente según contrato) | `authenticate_backend_smart_standard(...)` | ⏳ |
55
+
56
+ ## 4) Paridad de Wallet/KMS cliente
57
+
58
+ Arquitectura temporal Node:
59
+ - módulo interno `src/sdk/dataspace-wallet-sdk-node/`
60
+ - evolución futura: extraer a paquete/repo independiente
61
+
62
+ Baseline funcional backend/KMS que debe respetarse:
63
+ - en GW (`gdc-unid-node-ts`/`gwtemplate-node-ts`) existen servicios KMS runtime (`KmsService`, `DemoKmsService`) y utilidades KEK en backend utils,
64
+ - el SDK cliente no replica managers de GW,
65
+ - pero sí debe exponer wallet/KMS reutilizable para servicios backend cliente.
66
+
67
+ | Capability | Node target (`dataspace-wallet-sdk-node` interno) | Python target | Estado |
68
+ |---|---|---|---|
69
+ | Key material provider abstraction | `WalletProvider` | provider equivalente | ⏳ |
70
+ | In-memory provider | `memory-provider` | provider equivalente | ⏳ |
71
+ | Deterministic seed provider (demo/dev) | `seed-provider` | provider equivalente | ⏳ |
72
+ | Public JWK export | `getPublicJwks(...)` | equivalente | ⏳ |
73
+ | Sign/verify | `sign(...)`, `verify(...)` | equivalente | ⏳ |
74
+ | Encrypt/decrypt | `encrypt(...)`, `decrypt(...)` | equivalente | ⏳ |
75
+ | Single-tenant facade | `WalletClient` | equivalente | ⏳ |
76
+ | Multi-tenant facade | `MultiWalletClient` | equivalente | ⏳ |
77
+
78
+ ## 5) Paridad de dominios (baseline)
79
+
80
+ | Domain capability | Node SDK | Python SDK | Estado |
81
+ |---|---|---|---|
82
+ | Family/Organization onboarding | métodos batch + poll | equivalente | ✅/⏳ según endpoint |
83
+ | RelatedPerson | métodos batch + poll | equivalente | ✅ |
84
+ | Observation | métodos batch + poll | equivalente | ✅ |
85
+ | Communication | métodos batch + poll | equivalente | ✅ |
86
+ | Composition | métodos batch + poll | equivalente | ✅ |
87
+ | Task | métodos batch + poll | equivalente | ✅ |
88
+ | Conversion upload | upload + poll | equivalente | ✅ |
89
+
90
+ ## 6) Surface nuevo (onboarding/licensing/payment)
91
+
92
+ | Capability | Node SDK | Python SDK | Contract endpoint | Estado |
93
+ |---|---|---|---|---|
94
+ | Family Organization search | pendiente | pendiente | `individual/org.schema/Organization/_search` (+ `_batch-response`) | ⏳ |
95
+ | Family Organization create/resume | pendiente | pendiente | `individual/org.schema/Organization/_batch` (+ `_batch-response`) | ⏳ |
96
+ | Family Order create | pendiente | pendiente | `individual/org.schema/Order/_batch` (+ `_batch-response`) | ⏳ |
97
+ | Host registry order (host flow) | pendiente | pendiente | `host/.../registry/org.schema/Order/_batch` (+ `_batch-response`) | ⏳ |
98
+ | Offer consumption for family flow | pendiente | pendiente | offer returned by Organization `_batch-response` | ⏳ |
99
+ | Stripe intent | pendiente | pendiente | `payment/stripe/_intent` | ⏳ |
100
+ | Stripe status | pendiente | pendiente | `payment/stripe/_status` | ⏳ |
101
+ | API key create | pendiente | disponible en Python | `identity/api-key/_create` | ⏳ |
102
+ | API key disable | pendiente | disponible en Python | `identity/api-key/_disable` | ⏳ |
103
+ | API key search | pendiente | disponible en Python | `identity/api-key/_search` | ⏳ |
104
+
105
+ ## 7) Reglas de cambio
106
+
107
+ Cada PR que cambie superficie pública en Node o Python debe incluir:
108
+
109
+ 1. actualización de esta tabla,
110
+ 2. tests de paridad/compatibilidad,
111
+ 3. nota de migración si hay breaking changes.
112
+
113
+ ## 8) Check de salida para release
114
+
115
+ Antes de publicar nueva versión Node:
116
+
117
+ 1. `README` actualizado con auth + wallet.
118
+ 2. ejemplos funcionales en `examples/`.
119
+ 3. tests de paridad en verde.
120
+ 4. changelog con sección de migración (si aplica).
@@ -0,0 +1,185 @@
1
+ # TODO / Prompt - Next Steps (dataspace-client-sdk-node)
2
+
3
+ Objetivo de este backlog:
4
+ - Mantener `dataspace-client-sdk-node` como SDK backend oficial para Node.
5
+ - Añadir una capa wallet/KMS reutilizable para clientes backend Node (paridad conceptual con Python).
6
+ - Evitar que servicios consumidores implementen crypto/auth ad-hoc fuera del SDK.
7
+
8
+ Importante (decisión de arquitectura actual):
9
+ - El wallet/KMS se implementa temporalmente dentro de este repo en:
10
+ - `src/sdk/dataspace-wallet-sdk-node/`
11
+ - Más adelante se extraerá a repo/npm independiente (`dataspace-wallet-sdk-node`) sin romper API.
12
+
13
+ ## Repositorio fuente y referencias obligatorias
14
+
15
+ Estas son las fuentes que el agente debe tomar como referencia técnica antes de implementar:
16
+
17
+ 1. Frontend / cliente app:
18
+ - `gdc-sdk-client-ts`
19
+ - Papel: SDK frontend/wallet UX-side (no backend custodial KMS).
20
+
21
+ 2. Backend gateway template:
22
+ - `gwtemplate-node-ts`
23
+ - Ruta clave: `src/gdc-backend-utils-node`
24
+ - Papel: utilidades backend de crypto/KMS y contratos base.
25
+
26
+ 3. Backend UNID (fork operativo):
27
+ - `gdc-unid-node-ts`
28
+ - Papel: integración real de GW + managers + KMS runtime + flujos de negocio.
29
+
30
+ 4. SDK Python de referencia de paridad:
31
+ - `connector-sdk-py`
32
+ - Papel: referencia 1:1 de casos de uso backend.
33
+
34
+ 5. Orquestador de canal (consumidor actual):
35
+ - `uhc-unid-chat-node`
36
+ - Papel: usa SDK de alto nivel; no debe contener crypto/KMS de backend.
37
+
38
+ Regla: si hay contradicción entre implementación Node actual y Python, documentar la divergencia y dejar TODO de convergencia.
39
+
40
+ ## Contexto que el agente debe respetar
41
+
42
+ 1. `uhc-unid-chat-node` y otros consumidores deben seguir usando métodos de alto nivel del SDK.
43
+ 2. Los cambios internos de path builders de identidad son breaking solo para consumidores que montan rutas a mano.
44
+ 3. Si el consumidor usa `authenticateBackendPkceAndExchange(...)`, no debe cambiar nada en su código por la migración de rutas identity.
45
+
46
+ ## Funcionamiento actual de backend tools + KMS (baseline)
47
+
48
+ Resumen operativo esperado por el ecosistema backend:
49
+
50
+ 1. Capa SDK cliente (`dataspace-client-sdk-node`):
51
+ - construye paths canónicos,
52
+ - hace submit/poll,
53
+ - orquesta auth backend (`_dcr -> _code -> _token -> _exchange`).
54
+
55
+ 2. Capa backend utils / KMS (hoy en GW/template repos):
56
+ - `KmsService` / `DemoKmsService`,
57
+ - interfaces de crypto (`IKmsService`, tipos JWK/JWS/JWE),
58
+ - utilidades KEK/envelope para protección de claves y datos.
59
+
60
+ 3. Capa GW backend (`gdc-unid-node-ts` / `gwtemplate-node-ts`):
61
+ - runtime multitenant,
62
+ - provisión y resolución de claves por tenant,
63
+ - operaciones de firma/verificación/cifrado en contexto servidor.
64
+
65
+ Límite de responsabilidad:
66
+ - `dataspace-client-sdk-node` no debe replicar managers de GW.
67
+ - Sí debe poder exponer wallet/KMS cliente reutilizable para backends no-GW.
68
+
69
+ ## Definición de Hecho (DoD)
70
+
71
+ 1. Existe módulo wallet interno funcional con interfaz pública estable.
72
+ 2. El flujo `identity-exchange.v1` está soportado por métodos de alto nivel en Node (sin construir rutas manuales fuera del SDK).
73
+ 3. Se documenta paridad Node/Python por capability (no solo por endpoint).
74
+ 4. Hay tests que fallen si se rompe la paridad mínima acordada.
75
+ 5. README y ejemplos permiten a otro equipo integrar sin leer código interno.
76
+
77
+ ## Alcance técnico a implementar
78
+
79
+ ### A) Wallet/KMS interno (nuevo)
80
+
81
+ Crear módulo en `src/sdk/dataspace-wallet-sdk-node/`:
82
+
83
+ - `types.ts`
84
+ - `WalletContext` (`tenantId`, `jurisdiction`, `sector`, opcional `walletId`)
85
+ - `PublicJwk`, `PrivateKeyRef`, `SignOptions`, `EncryptOptions`, `DecryptOptions`
86
+ - `WalletProviderKind = 'mem' | 'seed' | 'external'`
87
+
88
+ - `provider.ts`
89
+ - `WalletProvider` interface:
90
+ - `init(...)`
91
+ - `getPublicJwks(context)`
92
+ - `sign(payload, context, options)`
93
+ - `verify(payload, signature, jwk)`
94
+ - `encrypt(plaintext, recipientJwk, options)`
95
+ - `decrypt(ciphertext, context, options)`
96
+
97
+ - `providers/memory-provider.ts`
98
+ - provider mínimo productivo para pruebas.
99
+
100
+ - `providers/seed-provider.ts`
101
+ - solo para `demo/dev` (determinístico).
102
+ - prohibido recomendarlo para staging/prod.
103
+
104
+ - `WalletClient.ts`
105
+ - fachada single-tenant.
106
+
107
+ - `MultiWalletClient.ts`
108
+ - resolución por `tenantId/jurisdiction/sector`.
109
+
110
+ ### B) Integración en `DataspaceNodeClient`
111
+
112
+ - Aceptar opcionalmente `wallet` en constructor/options.
113
+ - Mantener compatibilidad de los métodos actuales de negocio/auth.
114
+ - No mover lógica de dominios al wallet: wallet solo crypto/key operations.
115
+
116
+ ### C) Auth de alto nivel (paridad Python)
117
+
118
+ Asegurar métodos de alto nivel para:
119
+ - `authenticateBackendPkceAndExchange(...)`
120
+ - base para `authenticateBackendSmartStandard(...)` (si el contrato backend ya está listo)
121
+
122
+ Notas:
123
+ - Internamente usar path builders canónicos nuevos.
124
+ - Evitar exponer helpers de rutas como API pública “recomendada” para auth.
125
+
126
+ ## Plan de ejecución (orden obligatorio)
127
+
128
+ 1. Fase 1 - Contratos y estructura
129
+ - Crear árbol `src/sdk/dataspace-wallet-sdk-node/*`.
130
+ - Definir interfaces y tipos.
131
+ - Añadir tests unitarios de contrato (sin integración GW todavía).
132
+
133
+ 2. Fase 2 - Provider mem/seed
134
+ - Implementar `memory-provider` y `seed-provider`.
135
+ - Añadir tests de firma/verificación y cifrado/descifrado.
136
+
137
+ 3. Fase 3 - Integración client
138
+ - Conectar wallet opcional en `src/client.ts`.
139
+ - Mantener sin breaking en usos actuales.
140
+
141
+ 4. Fase 4 - Paridad y documentación
142
+ - Actualizar `SDK_PARITY_MAP.md` con estado real.
143
+ - Actualizar `README.md` con sección “Wallet/KMS for backend clients”.
144
+ - Añadir ejemplo runnable en `examples/`.
145
+
146
+ 5. Fase 5 - Puerta de extracción futura
147
+ - Definir imports internos de forma que luego sea fácil reemplazar:
148
+ - `src/sdk/dataspace-wallet-sdk-node/*` -> paquete npm externo.
149
+
150
+ ## Tests mínimos obligatorios
151
+
152
+ 1. Unit tests wallet:
153
+ - sign/verify roundtrip
154
+ - encrypt/decrypt roundtrip
155
+ - error handling de context faltante
156
+
157
+ 2. Unit tests auth orchestration:
158
+ - secuencia `_dcr -> _code -> _token -> _exchange`
159
+ - gestión de token cacheado vs refresh
160
+
161
+ 3. Regression tests identity routes:
162
+ - verificar que internamente se usa patrón canónico
163
+ - `/{prefix}/cds-{j}/v1/{sector}/{tenantId}/identity/auth/{action}`
164
+
165
+ 4. Public API smoke:
166
+ - import del SDK no rompe para consumidores actuales.
167
+
168
+ ## Criterios de seguridad
169
+
170
+ - Ninguna private key en logs.
171
+ - `seed-provider` marcado explícitamente como no apto para staging/prod.
172
+ - Errores crypto sin volcar material sensible.
173
+
174
+ ## Entregables esperados del agente
175
+
176
+ 1. PR con código + tests + docs.
177
+ 2. Resumen de decisiones (tradeoffs) en la descripción.
178
+ 3. Tabla de estado actualizada en `SDK_PARITY_MAP.md`.
179
+ 4. Lista de pendientes para extracción a repo independiente.
180
+
181
+ ## Plantilla de commit sugerida
182
+
183
+ - `feat(wallet): add internal dataspace-wallet-sdk-node module (mem/seed providers)`
184
+ - `feat(auth): keep pkce high-level orchestration aligned with canonical identity routes`
185
+ - `docs(parity): update SDK parity map and wallet roadmap`