@precisa-saude/fhir-rnds-sandbox 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.
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,477 @@
1
+ # @precisa-saude/fhir-rnds-sandbox
2
+
3
+ > Mock local da RNDS (Rede Nacional de Dados em Saúde) — endpoints FHIR R4
4
+ > com cenários sintéticos para desenvolvimento, ensino e demos.
5
+
6
+ [![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://www.apache.org/licenses/LICENSE-2.0)
7
+
8
+ Sem certificado ICP-Brasil. Sem credenciamento DATASUS. Roda em segundos.
9
+
10
+ ## Por que existe
11
+
12
+ Testar uma integração com a RNDS em produção exige certificado ICP-Brasil
13
+ (SERPRO/AC) e homologação no DATASUS — meses de papelada. Esse atrito trava
14
+ hackathons, aulas, PoCs e a adoção de qualquer cliente RNDS, inclusive o
15
+ nosso (`@precisa-saude/fhir-rnds`).
16
+
17
+ `rnds-sandbox` é um servidor HTTP leve que implementa o subset de endpoints
18
+ FHIR R4 que clientes RNDS usam de fato — busca de paciente por CPF/CNS,
19
+ consulta de organização (CNES) e profissional (CNS), e submissão de Bundle.
20
+ Os dados são sintéticos, claramente falsos e versionados em cenários
21
+ nomeados.
22
+
23
+ ## Instalação
24
+
25
+ ```bash
26
+ npx @precisa-saude/fhir-rnds-sandbox start
27
+ ```
28
+
29
+ Ou como dependência:
30
+
31
+ ```bash
32
+ pnpm add -D @precisa-saude/fhir-rnds-sandbox
33
+ ```
34
+
35
+ ## Uso — CLI
36
+
37
+ ```bash
38
+ # sobe na porta padrão 8080 com cenário "paciente-com-exames"
39
+ rnds-sandbox start
40
+
41
+ # escolhe cenário e porta
42
+ rnds-sandbox start --port 9000 --scenario internacao
43
+
44
+ # habilita mTLS (cliente precisa apresentar certificado)
45
+ rnds-sandbox start --mtls --pfx ./dev-cert.pfx --pfx-password senha
46
+
47
+ # lista cenários disponíveis
48
+ rnds-sandbox scenarios
49
+ ```
50
+
51
+ ## Uso — programático
52
+
53
+ ```ts
54
+ import { createSandboxServer } from '@precisa-saude/fhir-rnds-sandbox';
55
+
56
+ const sandbox = createSandboxServer({
57
+ scenario: 'paciente-com-exames',
58
+ port: 0, // porta efêmera — útil em testes
59
+ });
60
+
61
+ const { host, port } = await sandbox.start();
62
+ console.log(`sandbox em http://${host}:${port}`);
63
+
64
+ // ... rode seus testes ...
65
+
66
+ await sandbox.stop();
67
+ ```
68
+
69
+ ## Cenários
70
+
71
+ | Nome | Descrição |
72
+ | --------------------- | ---------------------------------------------------------------------------------------------- |
73
+ | `paciente-com-exames` | Joana da Silva, 42 anos, com lipidograma + glicemia codificados em LOINC. (padrão) |
74
+ | `internacao` | Carlos Souza, 67, internado por insuficiência cardíaca (CID I50.0), com NT-proBNP e troponina. |
75
+ | `vacina` | Pedro Almeida, 8 anos, com calendário vacinal aplicado (BCG, hepatite B, tríplice viral). |
76
+ | `vazio` | Estado limpo. Útil para testar fluxos do zero. |
77
+
78
+ Identificadores sintéticos usados nos cenários:
79
+
80
+ | CPF | CNS | Cenário |
81
+ | ------------- | ----------------- | ------------------- |
82
+ | `12345678901` | `700000000000001` | paciente-com-exames |
83
+ | `98765432100` | `700000000000020` | internacao |
84
+ | _(sem CPF)_ | `700000000000040` | vacina |
85
+
86
+ CNES dos estabelecimentos: `2345678` (lab), `3456789` (hospital), `4567890` (UBS).
87
+
88
+ ### Exemplos por cenário
89
+
90
+ Todos os exemplos assumem o sandbox rodando em `http://127.0.0.1:8080`. Os
91
+ campos `submittedBundles` listados em cada cenário ficam disponíveis via
92
+ `sandbox.store.getSubmittedBundles()` na API programática (ou seja, são
93
+ "histórico" do paciente — o cliente os consome via outras consultas, não
94
+ por um endpoint dedicado).
95
+
96
+ #### `paciente-com-exames` (padrão)
97
+
98
+ ```bash
99
+ rnds-sandbox start
100
+ ```
101
+
102
+ Buscar paciente por CPF:
103
+
104
+ ```bash
105
+ $ curl -s "http://127.0.0.1:8080/api/fhir/r4/Patient?identifier=$(printf 'http://rnds.saude.gov.br/fhir/r4/NamingSystem/cpf|12345678901' | jq -sRr @uri)"
106
+ ```
107
+
108
+ ```json
109
+ {
110
+ "resourceType": "Patient",
111
+ "id": "700000000000001",
112
+ "identifier": [
113
+ { "system": "http://rnds.saude.gov.br/fhir/r4/NamingSystem/cpf", "value": "12345678901" },
114
+ { "system": "http://rnds.saude.gov.br/fhir/r4/NamingSystem/cns", "value": "700000000000001" }
115
+ ],
116
+ "name": [{ "family": "Silva", "given": ["Joana", "Maria", "da"] }],
117
+ "gender": "female",
118
+ "birthDate": "1983-08-12"
119
+ }
120
+ ```
121
+
122
+ Histórico pré-carregado (Bundle de lipidograma + glicemia, todas as
123
+ Observations codificadas em LOINC):
124
+
125
+ | LOINC | Biomarcador | Valor |
126
+ | -------- | ---------------- | --------- |
127
+ | `2093-3` | Colesterol total | 198 mg/dL |
128
+ | `2089-1` | LDL-Colesterol | 124 mg/dL |
129
+ | `2085-9` | HDL-Colesterol | 56 mg/dL |
130
+ | `2345-7` | Glicose | 96 mg/dL |
131
+
132
+ Submeter um novo Bundle (resposta abaixo):
133
+
134
+ ```bash
135
+ $ curl -s -X POST http://127.0.0.1:8080/api/fhir/r4/Bundle \
136
+ -H "Content-Type: application/fhir+json" \
137
+ -d '{"resourceType":"Bundle","type":"transaction","entry":[{"request":{"method":"POST","url":"Observation"},"resource":{"resourceType":"Observation","status":"final","code":{"coding":[{"system":"http://loinc.org","code":"2345-7","display":"Glicose"}]},"valueQuantity":{"value":102,"unit":"mg/dL","system":"http://unitsofmeasure.org","code":"mg/dL"}}}]}'
138
+ ```
139
+
140
+ ```json
141
+ {
142
+ "resourceType": "Bundle",
143
+ "type": "transaction-response",
144
+ "entry": [{ "response": { "status": "201 Created", "location": "Resource/sandbox-1" } }]
145
+ }
146
+ ```
147
+
148
+ #### `internacao`
149
+
150
+ ```bash
151
+ rnds-sandbox start --scenario internacao
152
+ ```
153
+
154
+ Buscar paciente por CNS:
155
+
156
+ ```bash
157
+ $ curl -s http://127.0.0.1:8080/api/fhir/r4/Patient/700000000000020
158
+ ```
159
+
160
+ ```json
161
+ {
162
+ "resourceType": "Patient",
163
+ "id": "700000000000020",
164
+ "identifier": [
165
+ { "system": "http://rnds.saude.gov.br/fhir/r4/NamingSystem/cpf", "value": "98765432100" },
166
+ { "system": "http://rnds.saude.gov.br/fhir/r4/NamingSystem/cns", "value": "700000000000020" }
167
+ ],
168
+ "name": [{ "family": "Souza", "given": ["Carlos", "Henrique"] }],
169
+ "gender": "male",
170
+ "birthDate": "1958-02-28"
171
+ }
172
+ ```
173
+
174
+ Buscar o hospital (Organization) pelo CNES:
175
+
176
+ ```bash
177
+ $ curl -s http://127.0.0.1:8080/api/fhir/r4/Organization/3456789
178
+ ```
179
+
180
+ ```json
181
+ {
182
+ "resourceType": "Organization",
183
+ "id": "3456789",
184
+ "active": true,
185
+ "identifier": [
186
+ { "system": "http://rnds.saude.gov.br/fhir/r4/NamingSystem/cnes", "value": "3456789" }
187
+ ],
188
+ "name": "Hospital Sintético do Coração (sandbox)"
189
+ }
190
+ ```
191
+
192
+ Histórico pré-carregado:
193
+
194
+ | Recurso | Detalhe |
195
+ | ----------------------------- | -------------------------------------------------- |
196
+ | `Encounter` | classe `IMP` (inpatient), iniciado em 2026-04-15 |
197
+ | `Condition` | CID-10 `I50.0` (Insuficiência cardíaca congestiva) |
198
+ | `Observation` LOINC `33762-6` | NT-proBNP — 4820 pg/mL |
199
+ | `Observation` LOINC `49563-0` | Troponina I — 0.08 ng/mL |
200
+
201
+ #### `vacina`
202
+
203
+ ```bash
204
+ rnds-sandbox start --scenario vacina
205
+ ```
206
+
207
+ Buscar o paciente pediátrico:
208
+
209
+ ```bash
210
+ $ curl -s http://127.0.0.1:8080/api/fhir/r4/Patient/700000000000040
211
+ ```
212
+
213
+ ```json
214
+ {
215
+ "resourceType": "Patient",
216
+ "id": "700000000000040",
217
+ "identifier": [
218
+ { "system": "http://rnds.saude.gov.br/fhir/r4/NamingSystem/cns", "value": "700000000000040" }
219
+ ],
220
+ "name": [{ "family": "Almeida", "given": ["Pedro", "Lima"] }],
221
+ "gender": "male",
222
+ "birthDate": "2017-11-04"
223
+ }
224
+ ```
225
+
226
+ Histórico pré-carregado (3 `Immunization`, sistema PNI/CVP
227
+ `urn:oid:2.16.840.1.113883.6.59`):
228
+
229
+ | Vacina | Código | Data |
230
+ | -------------------- | ------ | ---------- |
231
+ | BCG | `BCG` | 2017-11-05 |
232
+ | Hepatite B (RN) | `HBV` | 2017-11-05 |
233
+ | Tríplice viral (SCR) | `MMR` | 2018-12-12 |
234
+
235
+ #### `vazio`
236
+
237
+ ```bash
238
+ rnds-sandbox start --scenario vazio
239
+ ```
240
+
241
+ Toda consulta de leitura retorna `404 OperationOutcome`. Útil para
242
+ exercitar o caminho de erro do cliente:
243
+
244
+ ```bash
245
+ $ curl -s -i http://127.0.0.1:8080/api/fhir/r4/Patient/700000000000001 | head -1
246
+ HTTP/1.1 404 Not Found
247
+ ```
248
+
249
+ ```json
250
+ {
251
+ "resourceType": "OperationOutcome",
252
+ "issue": [
253
+ {
254
+ "severity": "error",
255
+ "code": "not-found",
256
+ "diagnostics": "Paciente CNS 700000000000001 não encontrado"
257
+ }
258
+ ]
259
+ }
260
+ ```
261
+
262
+ ## Endpoints
263
+
264
+ Compatível com o subset usado por `@precisa-saude/fhir-rnds`:
265
+
266
+ | Método | Path | Auth (modo strict) | Descrição |
267
+ | ------ | -------------------------------------------------------------------------------------------------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------ |
268
+ | `POST` | `/api/token` | mTLS (cert do cliente) | Emite token JWT assinado em RS256. |
269
+ | `GET` | `/.well-known/jwks.json` | público | Chave pública (JWK) usada para verificar a assinatura do token. |
270
+ | `GET` | `/api/fhir/r4/Patient?identifier={system}\|{value}` | bearer + CNS | Busca por CPF (`.../cpf`) ou CNS (`.../cns`). |
271
+ | `GET` | `/api/fhir/r4/Patient/{cns}` | bearer + CNS | Lê paciente por CNS. |
272
+ | `GET` | `/api/fhir/r4/Organization/{cnes}` | bearer + CNS | Lê estabelecimento por CNES. |
273
+ | `GET` | `/api/fhir/r4/Practitioner/{cns}` | bearer + CNS | Lê profissional por CNS. |
274
+ | `POST` | `/api/fhir/r4/Bundle` | bearer + CNS | Aceita Bundle transaction/batch e retorna transaction-response. |
275
+ | `GET` | `/api/fhir/r4/{Observation\|DiagnosticReport\|Immunization\|Condition\|Encounter}?subject=Patient/{cns}` | bearer + CNS | Retorna searchset Bundle com recursos pré-carregados + submetidos. Aceita também `?patient=...` ou só o CNS sem prefixo. |
276
+
277
+ Em modo **permissivo** (padrão sem flags) nenhum auth é exigido — qualquer
278
+ curl entra. Recursos não encontrados retornam `404` com `OperationOutcome`.
279
+ Endpoints FHIR exigem dois headers em modo strict (igual à API real):
280
+
281
+ - `X-Authorization-Server: Bearer <jwt>` — token RS256 emitido pelo sandbox
282
+ - `Authorization: <CNS>` — CNS de 15 dígitos do profissional requisitante
283
+
284
+ ## Modos de fidelidade
285
+
286
+ O sandbox tem três modos. Escolha o que combina com o que você quer
287
+ demonstrar/testar:
288
+
289
+ | Modo | Como ativar | Comportamento |
290
+ | -------------- | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
291
+ | **Permissivo** | (sem flags) | HTTP puro, qualquer chamada aceita. Útil para curl, aulas e iteração rápida. |
292
+ | **Strict** | `--strict` | HTTP, mas /api/fhir/r4/\* exige bearer + CNS, e /api/token exige cert mTLS apresentado (rejeita sem). Útil para validar a lógica de auth do cliente sem precisar configurar TLS. |
293
+ | **mTLS** | `--mtls` (implica strict) | HTTPS com handshake mTLS opcional do cliente. Réplica fiel da RNDS: cert exigido em /api/token; FHIR API exige bearer. |
294
+
295
+ ### JWT — RS256 com JWKS
296
+
297
+ O token é um JWT RS256 real, assinado com uma chave RSA-2048. Por padrão
298
+ a chave é gerada **efêmera** no boot — bom para devs que rodam o sandbox
299
+ em sessões curtas. Em CI/demos onde você quer reusar o mesmo token entre
300
+ restarts, passe `--jwt-private-key`:
301
+
302
+ ```bash
303
+ # gere uma chave estável (uma vez)
304
+ openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out jwt.pem
305
+
306
+ rnds-sandbox start --strict --jwt-private-key ./jwt.pem
307
+ ```
308
+
309
+ A chave pública é exposta via `/.well-known/jwks.json`. Bibliotecas de JWT
310
+ (`jose`, `jsonwebtoken`, `jwt.io` com a URL do JWKS) podem verificar a
311
+ assinatura sem configuração fora-de-banda:
312
+
313
+ ```bash
314
+ $ curl -s http://127.0.0.1:8080/.well-known/jwks.json | jq
315
+ {
316
+ "keys": [
317
+ {
318
+ "alg": "RS256",
319
+ "e": "AQAB",
320
+ "kid": "rnds-sandbox-1",
321
+ "kty": "RSA",
322
+ "n": "qdg8rAyVCT0s7UA4YM_j6fjjLt_-0huK7sQyLT...",
323
+ "use": "sig"
324
+ }
325
+ ]
326
+ }
327
+ ```
328
+
329
+ ### Validação contra perfis do IG
330
+
331
+ Por padrão o sandbox valida cada `Bundle.entry[i].resource` enviado em
332
+ `POST /api/fhir/r4/Bundle` contra os perfis `BR*` do IG `fhir-brasil`
333
+ (`BRPatient`, `BRLabObservation`, `BRDiagnosticReport`). Bundles que
334
+ violam restrições são rejeitados com `422 OperationOutcome` listando
335
+ todas as issues — formato e códigos espelham o que a RNDS real
336
+ retorna.
337
+
338
+ ```bash
339
+ # Patient sem campos obrigatórios — o sandbox responde 422 com a lista
340
+ $ curl -s -X POST http://127.0.0.1:8080/api/fhir/r4/Bundle \
341
+ -H 'Content-Type: application/fhir+json' \
342
+ -d '{"resourceType":"Bundle","type":"transaction","entry":[
343
+ {"request":{"method":"POST","url":"Patient"},
344
+ "resource":{"resourceType":"Patient"}}
345
+ ]}'
346
+ ```
347
+
348
+ ```json
349
+ {
350
+ "resourceType": "OperationOutcome",
351
+ "issue": [
352
+ {
353
+ "severity": "error",
354
+ "code": "required",
355
+ "diagnostics": "Patient.identifier requer pelo menos 1 elemento(s); recebido 0",
356
+ "location": ["Bundle.entry[0].resource.identifier"]
357
+ },
358
+ {
359
+ "severity": "error",
360
+ "code": "required",
361
+ "diagnostics": "Patient.name requer pelo menos 1 elemento(s); recebido 0",
362
+ "location": ["Bundle.entry[0].resource.name"]
363
+ },
364
+ {
365
+ "severity": "error",
366
+ "code": "required",
367
+ "diagnostics": "Patient.birthDate é obrigatório",
368
+ "location": ["Bundle.entry[0].resource.birthDate"]
369
+ },
370
+ {
371
+ "severity": "error",
372
+ "code": "required",
373
+ "diagnostics": "Patient.gender é obrigatório",
374
+ "location": ["Bundle.entry[0].resource.gender"]
375
+ }
376
+ ]
377
+ }
378
+ ```
379
+
380
+ O resolver de perfil usa `meta.profile` quando presente; caso contrário
381
+ seleciona pelo `resourceType` (`Patient` → BRPatient, `Observation` →
382
+ BRLabObservation, `DiagnosticReport` → BRDiagnosticReport). Outros
383
+ tipos passam sem checagem de perfil — declare `meta.profile` se quiser
384
+ conformidade estrita para tipos fora desse conjunto.
385
+
386
+ Para desligar (e voltar ao comportamento "aceita qualquer Bundle
387
+ estruturalmente válido", útil em aulas):
388
+
389
+ ```bash
390
+ rnds-sandbox start --no-validate
391
+ # ou programaticamente:
392
+ createSandboxServer({ validateSubmissions: false });
393
+ ```
394
+
395
+ As regras espelham as restrições FSH em `ig/input/fsh/profiles/`. São
396
+ implementadas em pure TS (zero deps novas) e cobrem o subset que a
397
+ RNDS real rejeita na prática (cardinalidade, identifiers brasileiros,
398
+ coding LOINC/UCUM, value sets de status). Não pretendem ser FHIR
399
+ validation completa — slicing complexo, value-set binding contra
400
+ terminologias externas e algumas invariantes FHIRPath ficam de fora.
401
+
402
+ ### mTLS na prática
403
+
404
+ Você precisa de um cert para o **servidor**. Qualquer cert auto-assinado
405
+ serve, ou use o que já tiver (cert ICP-Brasil de homologação, por
406
+ exemplo). O sandbox aceita certs de cliente sem validar a CA
407
+ (`rejectUnauthorized: false`) — propósito: dev, não produção.
408
+
409
+ ```bash
410
+ # 1. Gere cert auto-assinado para o servidor (uma vez)
411
+ openssl req -newkey rsa:2048 -nodes -keyout srv.key -x509 \
412
+ -days 365 -out srv.crt -subj "/CN=rnds-sandbox.local"
413
+
414
+ # 2. Suba com mTLS — aceita PFX OU key+cert PEM
415
+ rnds-sandbox start --mtls --server-key ./srv.key --server-cert ./srv.crt
416
+
417
+ # (alternativa) PFX:
418
+ openssl pkcs12 -export -out srv.pfx -inkey srv.key -in srv.crt -password pass:dev
419
+ rnds-sandbox start --mtls --pfx ./srv.pfx --pfx-password dev
420
+ ```
421
+
422
+ Para apresentar um cert de cliente no curl (e receber CN/CNES embutidos
423
+ no token):
424
+
425
+ ```bash
426
+ # Gere um cert de cliente que embute CNES "1234567" no CN
427
+ openssl req -newkey rsa:2048 -nodes -keyout client.key -x509 \
428
+ -days 365 -out client.crt \
429
+ -subj "/CN=PRECISA SAUDE LTDA:1234567"
430
+
431
+ # Pega token via mTLS — note --cacert + --cert
432
+ TOKEN=$(curl -sk \
433
+ --cert client.crt --key client.key \
434
+ -X POST https://127.0.0.1:8443/api/token | jq -r .access_token)
435
+
436
+ # Decodifique para conferir cn/cnes nas claims (jwt.io ou jq):
437
+ echo "$TOKEN" | cut -d. -f2 | base64 -d 2>/dev/null | jq
438
+ # → { "iss": "...", "sub": "PRECISA SAUDE LTDA:1234567",
439
+ # "cnes": "1234567", "cn": "PRECISA SAUDE LTDA:1234567", ... }
440
+
441
+ # Use o token + CNS do profissional na chamada FHIR:
442
+ curl -sk https://127.0.0.1:8443/api/fhir/r4/Patient/700000000000001 \
443
+ -H "X-Authorization-Server: Bearer $TOKEN" \
444
+ -H "Authorization: 700000000000010"
445
+ ```
446
+
447
+ ## Docker
448
+
449
+ ```bash
450
+ docker run --rm -p 8080:8080 ghcr.io/precisa-saude/fhir-rnds-sandbox:latest
451
+ ```
452
+
453
+ Escolha cenário e porta:
454
+
455
+ ```bash
456
+ docker run --rm -p 9000:9000 ghcr.io/precisa-saude/fhir-rnds-sandbox:latest \
457
+ start --port 9000 --scenario internacao
458
+ ```
459
+
460
+ ## Aviso de produção
461
+
462
+ Este pacote é estritamente para **desenvolvimento, testes e ensino**.
463
+ Tokens são RS256-assinados, mas com chave gerada localmente (não da RNDS)
464
+ — a assinatura é cryptograficamente válida no escopo do sandbox e nada
465
+ mais. Dados são sintéticos. Não submeta dados de pacientes reais a este
466
+ servidor — ele apenas armazena em memória e perde o estado quando
467
+ reinicia.
468
+
469
+ ## Aviso médico
470
+
471
+ Os recursos FHIR retornados pelo sandbox **não constituem** registros de
472
+ saúde reais. Cenários são fictícios e ilustrativos. Não use para tomar
473
+ decisões clínicas.
474
+
475
+ ## Licença
476
+
477
+ Apache-2.0 © Precisa Saúde