@traffic-twin/sdk 0.0.0-stage → 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 (133) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +171 -2
  3. package/dist/cjs/agent.d.ts +143 -0
  4. package/dist/cjs/agent.js +927 -0
  5. package/dist/cjs/capture/body.d.ts +11 -0
  6. package/dist/cjs/capture/body.js +73 -0
  7. package/dist/cjs/capture/common.d.ts +75 -0
  8. package/dist/cjs/capture/common.js +180 -0
  9. package/dist/cjs/capture/context.d.ts +28 -0
  10. package/dist/cjs/capture/context.js +92 -0
  11. package/dist/cjs/capture/inbound.d.ts +12 -0
  12. package/dist/cjs/capture/inbound.js +195 -0
  13. package/dist/cjs/capture/outbound-http.d.ts +4 -0
  14. package/dist/cjs/capture/outbound-http.js +200 -0
  15. package/dist/cjs/capture/outbound-undici.d.ts +2 -0
  16. package/dist/cjs/capture/outbound-undici.js +242 -0
  17. package/dist/cjs/capture/wire.d.ts +27 -0
  18. package/dist/cjs/capture/wire.js +68 -0
  19. package/dist/cjs/export/event.d.ts +46 -0
  20. package/dist/cjs/export/event.js +91 -0
  21. package/dist/cjs/export/exporter.d.ts +50 -0
  22. package/dist/cjs/export/exporter.js +192 -0
  23. package/dist/cjs/export/pipeline.d.ts +20 -0
  24. package/dist/cjs/export/pipeline.js +40 -0
  25. package/dist/cjs/fleet/asn1.d.ts +44 -0
  26. package/dist/cjs/fleet/asn1.js +150 -0
  27. package/dist/cjs/fleet/client.d.ts +84 -0
  28. package/dist/cjs/fleet/client.js +216 -0
  29. package/dist/cjs/fleet/http.d.ts +17 -0
  30. package/dist/cjs/fleet/http.js +80 -0
  31. package/dist/cjs/fleet/store.d.ts +18 -0
  32. package/dist/cjs/fleet/store.js +115 -0
  33. package/dist/cjs/index.d.ts +14 -0
  34. package/dist/cjs/index.js +69 -0
  35. package/dist/cjs/log.d.ts +4 -0
  36. package/dist/cjs/log.js +30 -0
  37. package/dist/cjs/package.json +1 -0
  38. package/dist/cjs/register.d.ts +1 -0
  39. package/dist/cjs/register.js +18 -0
  40. package/dist/cjs/sanitizer/bodies.d.ts +55 -0
  41. package/dist/cjs/sanitizer/bodies.js +710 -0
  42. package/dist/cjs/sanitizer/formats.d.ts +26 -0
  43. package/dist/cjs/sanitizer/formats.js +110 -0
  44. package/dist/cjs/sanitizer/graphql.d.ts +23 -0
  45. package/dist/cjs/sanitizer/graphql.js +478 -0
  46. package/dist/cjs/sanitizer/hostpat.d.ts +15 -0
  47. package/dist/cjs/sanitizer/hostpat.js +129 -0
  48. package/dist/cjs/sanitizer/json.d.ts +60 -0
  49. package/dist/cjs/sanitizer/json.js +460 -0
  50. package/dist/cjs/sanitizer/policy.d.ts +224 -0
  51. package/dist/cjs/sanitizer/policy.js +820 -0
  52. package/dist/cjs/sanitizer/sanitizer.d.ts +149 -0
  53. package/dist/cjs/sanitizer/sanitizer.js +1473 -0
  54. package/dist/cjs/sanitizer/utf8.d.ts +22 -0
  55. package/dist/cjs/sanitizer/utf8.js +180 -0
  56. package/dist/cjs/sanitizer/vectors.d.ts +22 -0
  57. package/dist/cjs/sanitizer/vectors.js +130 -0
  58. package/dist/cjs/version.d.ts +2 -0
  59. package/dist/cjs/version.js +5 -0
  60. package/dist/cjs/worker/dir.d.ts +1 -0
  61. package/dist/cjs/worker/dir.js +8 -0
  62. package/dist/cjs/worker/pool.d.ts +47 -0
  63. package/dist/cjs/worker/pool.js +179 -0
  64. package/dist/cjs/worker/protocol.d.ts +37 -0
  65. package/dist/cjs/worker/protocol.js +3 -0
  66. package/dist/cjs/worker/sanitizer-worker.d.ts +1 -0
  67. package/dist/cjs/worker/sanitizer-worker.js +53 -0
  68. package/dist/esm/agent.d.ts +143 -0
  69. package/dist/esm/agent.js +921 -0
  70. package/dist/esm/capture/body.d.ts +11 -0
  71. package/dist/esm/capture/body.js +69 -0
  72. package/dist/esm/capture/common.d.ts +75 -0
  73. package/dist/esm/capture/common.js +166 -0
  74. package/dist/esm/capture/context.d.ts +28 -0
  75. package/dist/esm/capture/context.js +84 -0
  76. package/dist/esm/capture/inbound.d.ts +12 -0
  77. package/dist/esm/capture/inbound.js +187 -0
  78. package/dist/esm/capture/outbound-http.d.ts +4 -0
  79. package/dist/esm/capture/outbound-http.js +193 -0
  80. package/dist/esm/capture/outbound-undici.d.ts +2 -0
  81. package/dist/esm/capture/outbound-undici.js +236 -0
  82. package/dist/esm/capture/wire.d.ts +27 -0
  83. package/dist/esm/capture/wire.js +65 -0
  84. package/dist/esm/export/event.d.ts +46 -0
  85. package/dist/esm/export/event.js +85 -0
  86. package/dist/esm/export/exporter.d.ts +50 -0
  87. package/dist/esm/export/exporter.js +188 -0
  88. package/dist/esm/export/pipeline.d.ts +20 -0
  89. package/dist/esm/export/pipeline.js +37 -0
  90. package/dist/esm/fleet/asn1.d.ts +44 -0
  91. package/dist/esm/fleet/asn1.js +128 -0
  92. package/dist/esm/fleet/client.d.ts +84 -0
  93. package/dist/esm/fleet/client.js +204 -0
  94. package/dist/esm/fleet/http.d.ts +17 -0
  95. package/dist/esm/fleet/http.js +73 -0
  96. package/dist/esm/fleet/store.d.ts +18 -0
  97. package/dist/esm/fleet/store.js +110 -0
  98. package/dist/esm/index.d.ts +14 -0
  99. package/dist/esm/index.js +48 -0
  100. package/dist/esm/log.d.ts +4 -0
  101. package/dist/esm/log.js +25 -0
  102. package/dist/esm/package.json +1 -0
  103. package/dist/esm/register.d.ts +1 -0
  104. package/dist/esm/register.js +16 -0
  105. package/dist/esm/sanitizer/bodies.d.ts +55 -0
  106. package/dist/esm/sanitizer/bodies.js +694 -0
  107. package/dist/esm/sanitizer/formats.d.ts +26 -0
  108. package/dist/esm/sanitizer/formats.js +101 -0
  109. package/dist/esm/sanitizer/graphql.d.ts +23 -0
  110. package/dist/esm/sanitizer/graphql.js +472 -0
  111. package/dist/esm/sanitizer/hostpat.d.ts +15 -0
  112. package/dist/esm/sanitizer/hostpat.js +122 -0
  113. package/dist/esm/sanitizer/json.d.ts +60 -0
  114. package/dist/esm/sanitizer/json.js +447 -0
  115. package/dist/esm/sanitizer/policy.d.ts +224 -0
  116. package/dist/esm/sanitizer/policy.js +800 -0
  117. package/dist/esm/sanitizer/sanitizer.d.ts +149 -0
  118. package/dist/esm/sanitizer/sanitizer.js +1459 -0
  119. package/dist/esm/sanitizer/utf8.d.ts +22 -0
  120. package/dist/esm/sanitizer/utf8.js +166 -0
  121. package/dist/esm/sanitizer/vectors.d.ts +22 -0
  122. package/dist/esm/sanitizer/vectors.js +125 -0
  123. package/dist/esm/version.d.ts +2 -0
  124. package/dist/esm/version.js +2 -0
  125. package/dist/esm/worker/dir.d.ts +1 -0
  126. package/dist/esm/worker/dir.js +5 -0
  127. package/dist/esm/worker/pool.d.ts +47 -0
  128. package/dist/esm/worker/pool.js +175 -0
  129. package/dist/esm/worker/protocol.d.ts +37 -0
  130. package/dist/esm/worker/protocol.js +2 -0
  131. package/dist/esm/worker/sanitizer-worker.d.ts +1 -0
  132. package/dist/esm/worker/sanitizer-worker.js +51 -0
  133. package/package.json +75 -4
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 CHANGED
@@ -1,3 +1,172 @@
1
- # Temporary Holding Version
1
+ # @traffic-twin/sdk (Node.js)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ SDK di cattura di traffic-twin per Node.js ≥ 20. Osserva le chiamate HTTP in ingresso e in
4
+ uscita del processo, le **sanifica nel processo** secondo la policy firmata (specifica
5
+ `docs/spec/sanitizer.md` v1.1.1) e invia a `tt-core` solo forme, token HMAC e valori
6
+ ammessi dalla policy, come log OTLP/HTTP JSON su mTLS.
7
+
8
+ - **Zero dipendenze a runtime**: solo la libreria standard di Node. Nessun pacchetto
9
+ `@opentelemetry/*` tra le dipendenze.
10
+ - **Non modifica il traffico dell'app**: nessun `traceparent` iniettato; l'unica eccezione,
11
+ opzionale e decisa dalla policy, è il membro di baggage `tt.s` verso gli host di
12
+ `sampling.propagate_to` (mai verso un host esterno della policy).
13
+ - **Fail-closed**: senza policy valida, chiave HMAC o primo heartbeat non cattura nulla;
14
+ l'app continua a funzionare normalmente. Senza chiave HMAC lo stato è `key_missing` (mai
15
+ `no_policy`) e l'SDK lo scrive sempre su stderr, anche senza `TT_DEBUG`, con la causa. La
16
+ chiave è un file dell'installazione distribuito dal team piattaforma (stesso kid di
17
+ `hmac.kid` della policy, stessa chiave di keyguard): vedi [docs/USER_GUIDE.md](https://github.com/ivseb/traffic-twin/blob/main/docs/USER_GUIDE.md) §4.
18
+ - ESM e CommonJS (`dist/esm`, `dist/cjs`).
19
+
20
+ ## Avvio senza codice
21
+
22
+ ```bash
23
+ npm install @traffic-twin/sdk # o, finché non è nel registro: npm install ./traffic-twin-sdk-x.y.z.tgz
24
+ TT_ENROLL_URL=https://tt-core.internal:4318 \
25
+ TT_ENROLL_TOKEN=tte_… \
26
+ TT_HMAC_KEY_FILE=/run/secrets/tt-hmac-key \
27
+ TT_SERVICE_NAME=shop-api \
28
+ node --import @traffic-twin/sdk/register app.js
29
+ ```
30
+
31
+ Per le app CommonJS si può usare anche `node --require @traffic-twin/sdk/register app.js`.
32
+ Gli hook si installano subito; iscrizione, heartbeat e download della policy avvengono in
33
+ background e non ritardano l'avvio dell'app.
34
+
35
+ | Variabile | Significato |
36
+ |---|---|
37
+ | `TT_ENROLL_URL` | URL del listener Fleet/intake di `tt-core` (sempre `https`) |
38
+ | `TT_ENROLL_TOKEN` | Token di iscrizione `tte_<segreto>.<impronta CA>`, monouso o di gruppo |
39
+ | `TT_HMAC_KEY` / `TT_HMAC_KEY_FILE` | Chiave HMAC locale, una o più righe `<kid>:<base64url>` (§7.1). Non viaggia mai verso `tt-core` |
40
+ | `TT_SERVICE_NAME` | Nome di servizio richiesto all'iscrizione (altrimenti `OTEL_SERVICE_NAME` in minuscolo). Il nome usato negli eventi è quello **assegnato** da `tt-core` |
41
+ | `TT_STATE_DIR` | Cartella dello stato locale (default `~/.traffic-twin/<id>`): certificato, chiave privata, CA, policy firmata, interruttore. Cartella `0700`, file `0600` |
42
+ | `TT_ENROLL_CSR` | `0` per chiedere la chiave a `tt-core` invece di generare una CSR (default: CSR ECDSA P-256, la chiave privata non esce dal processo) |
43
+ | `TT_SANITIZER_THREADS` | Thread di sanificazione (`worker_threads`). Default: `min(2, core − 1)`, usati solo quando il campionamento della policy è ≥ 2 % (sotto, si sanifica nel thread principale: costa meno che svegliare un thread). `0` = sempre nel thread principale |
44
+ | `TT_DISABLED` | `1` disattiva completamente l'SDK |
45
+ | `TT_DEBUG` | `1` scrive su stderr solo codici di stato ed errore (mai valori) |
46
+ | `TT_HEARTBEAT_INTERVAL_MS`, `TT_POLICY_POLL_INTERVAL_MS`, `TT_EXPORT_FLUSH_MS` | Solo per test: sostituiscono gli intervalli ricevuti da `tt-core` |
47
+
48
+ ## API programmatica
49
+
50
+ ```js
51
+ import { start, stop, current } from '@traffic-twin/sdk';
52
+
53
+ const agent = await start({
54
+ enrollUrl: 'https://tt-core.internal:4318',
55
+ enrollToken: process.env.TT_ENROLL_TOKEN,
56
+ hmacKeyFile: '/run/secrets/tt-hmac-key',
57
+ serviceName: 'shop-api',
58
+ });
59
+ console.log(agent.status()); // { state: 'capturing', counters: {...}, queue: {...} }
60
+ ```
61
+
62
+ `start()` non lancia mai eccezioni ed è idempotente (un solo agente per processo, anche se
63
+ l'app carica sia la build ESM sia quella CommonJS). La funzione di test dei vettori
64
+ (`runVector`, `parseVector`) e il sanitizer (`Sanitizer`, `Policy`) sono esportati.
65
+
66
+ ## Cosa viene catturato
67
+
68
+ | Direzione | Punto di aggancio | Corpo |
69
+ |---|---|---|
70
+ | Ingresso | `diagnostics_channel` `http.server.request.start` / `http.server.response.finish` (node:http, node:https, Express e framework basati su node:http) | richiesta: copia dei byte già de-chunkati dal parser; risposta: copia di `write`/`end` |
71
+ | Uscita, node:http(s) | `http.client.request.created` (o `start` su Node meno recenti), `http.client.response.finish`, `http.client.request.error` | come sopra |
72
+ | Uscita, `fetch`/undici | canali `undici:request:*` | `bodyChunkSent` / `bodyChunkReceived` (byte ancora codificati: la decodifica gzip/deflate la fa il sanitizer) |
73
+
74
+ Gli unici "wrapper" sono installati sugli **oggetti** richiesta/risposta degli scambi
75
+ campionati (`push`, `write`, `end`): sono sincroni, non cambiano argomenti, valori di
76
+ ritorno né tempi, e non aggiungono listener `error` (che cambierebbero la gestione degli
77
+ errori dell'app). Il resto (normalizzazione, sanificazione, serializzazione, invio) avviene
78
+ dopo la risposta, a blocchi di pochi millisecondi con `setImmediate`.
79
+
80
+ Contesto: un `AsyncLocalStorage` lega le chiamate in uscita allo scambio in ingresso (stesso
81
+ `trace_id`, campionamento ereditato). Il `traceparent` in ingresso viene letto; se l'app usa
82
+ OpenTelemetry, l'SDK carica `@opentelemetry/api` **dall'albero dell'app** e ne legge solo il
83
+ contesto attivo, senza mai registrare provider, propagatori o context manager.
84
+
85
+ Sanificazione fuori dal thread delle richieste: con campionamento ≥ 2 % gli scambi
86
+ catturati vengono raggruppati (≈ 8 ms) e inviati a uno o due thread di lavoro, che producono
87
+ direttamente i `logRecord` OTLP già pronti; il thread principale esegue solo la copia dei
88
+ byte, il `postMessage` e l'invio. Il risultato è identico byte per byte a quello
89
+ dell'esecuzione nel thread principale (`test/unit/worker.test.mjs`); se un thread muore si
90
+ torna alla sanificazione in linea e gli scambi in volo vengono contati come scartati. Misure
91
+ e metodo: `BENCHMARKS.md`.
92
+
93
+ Pressione: code limitate (2 000 scambi da sanificare, 10 000 eventi / 16 MiB da inviare);
94
+ quando sono piene si scartano gli eventi più vecchi e si contano, l'app non aspetta mai.
95
+ Invio a lotti (≤ 512 eventi, ≤ 4 MiB), ripetizioni con attesa esponenziale e `Retry-After`
96
+ su 429/502/503/504 ed errori di rete.
97
+
98
+ ### Host non dichiarati e scoperta automatica (spec v1.5)
99
+
100
+ Un host esterno che nessuna `base` della policy né `segments.hosts_allow` elenca non esce
101
+ più come `host:unlisted`: con `hosts.discovery: auto` (default, anche quando il campo
102
+ `hosts` manca) il `service` dell'evento è `host:` + **pattern** (sanitizer.md §3.5). Il
103
+ pattern è l'host in minuscolo, senza porta di default e senza un punto finale, in cui ogni
104
+ etichetta resta letterale solo se è `^[a-z][a-z0-9-]{0,62}$`, non ha sei cifre consecutive
105
+ né dodici esadecimali consecutivi, altrimenti diventa `{*}` (`t-3912345678.tenant.example` →
106
+ `host:{*}.tenant.example`). I letterali IP escono solo come `ip:private` / `ip:public`
107
+ (tabella chiusa di §3.6, con parser IPv6 proprio: nessuna funzione di libreria), con la porta
108
+ se non di default; un'etichetta vuota dà `host:invalid`. L'host è passato al sanitizer così
109
+ come lo vede il client (IPv6 tra parentesi, nessun IDN, nessun punto tolto).
110
+
111
+ `hosts.discovery: off` è la **modalità stretta**: gli host non dichiarati escono come
112
+ `host:unlisted`, byte per byte come prima della v1.5. Lo imposta la policy (`tt-core`, la
113
+ chiusura `auto` → `off` e l'apertura `off` → `auto` sono approvate come per ogni policy);
114
+ l'SDK non ha opzioni locali. Il dominio registrabile e la cardinalità delle etichette sono
115
+ controlli di `tt-core` (zona B): l'SDK non li implementa.
116
+
117
+ ### Codici alfanumerici, XML/SOAP, multipart, documenti e corpi grandi (spec v1.19)
118
+
119
+ L'SDK implementa la v1.19 del sanitizer (sanitizer.md §5.6 e §22; vettori 2200–2453):
120
+
121
+ - `{"action":"code","shape":"alnum"}`: codici con cifre e punti, `^[A-Za-z0-9_.-]{1,16}$`
122
+ entro `keep_max_bytes`; le guardie H1/H2 la trattano come `code`.
123
+ - L'oggetto `bodies` della policy (assente = tutto spento, uscita identica alle versioni precedenti):
124
+ `xml` analizza i corpi XML e SOAP con un lettore scritto a mano, sottoinsieme rigoroso di
125
+ XML 1.0 (`src/sanitizer/bodies.ts`: nessuna libreria XML, nessuna DTD né entità oltre le
126
+ cinque predefinite, al massimo 256 elementi annidati) e aggiunge `fmt`, `xmlns` e
127
+ `soap_action`; `multipart` analizza `multipart/form-data` (le parti file escono solo come
128
+ `drop:file:<tipo>:<classe>`); `docs` dà la forma `drop:doc:<tipo>:<classe>` alle stringhe
129
+ che sono il base64 di un documento; `max_large_body_bytes`, `large_array` e
130
+ `large_nested_array` attivano la modalità «corpo grande».
131
+ - Con `max_large_body_bytes` > 0 la cattura (ingresso, `http`/`https` e `fetch`/undici in
132
+ uscita) conserva `max(max_body_bytes, max_large_body_bytes) + 1` byte di ogni corpo
133
+ campionato invece di `max_body_bytes + 1`.
134
+
135
+ ## Fleet
136
+
137
+ - Iscrizione con token: prima connessione TLS senza fiducia, verifica che la radice della
138
+ catena presentata da `tt-core` abbia l'impronta SHA-256 contenuta nel token, poi richiesta
139
+ di iscrizione con quella radice come unica CA. Certificato e chiave restano nello stato
140
+ locale e si riusano ai riavvii.
141
+ - Heartbeat **prima** di qualsiasi cattura; interruttore di emergenza, revoca e
142
+ `min_issued_seq` sono salvati e restano validi dopo un riavvio.
143
+ - Policy: firma Ed25519 su `"tt.policy.body/v1" || 0x00 || corpo` con chiavi fissate e non
144
+ revocate, schema completo del corpo, coerenza busta/corpo, gruppo, `not_after`,
145
+ `issued_seq` crescente e ≥ `min_issued_seq`. Una policy rifiutata non sostituisce mai la
146
+ precedente valida. Nuove chiavi di firma solo se approvate da una chiave già fissata.
147
+
148
+ ## Limiti noti
149
+
150
+ - Versioni: Node ≥ 20; il corpo completo delle risposte di `fetch` solo da Node ≥ 24.
151
+ Node 20 e 22: il corpo delle risposte di `fetch` non è visibile (i canali `bodyChunk*` di
152
+ undici mancano) e l'evento riporta `trunc:size`; per le richieste node:http create e
153
+ chiuse prima dell'assegnazione del socket il corpo risulta di lunghezza ignota.
154
+ - `framework_route` si passa solo per Express e solo per le route definite direttamente
155
+ sull'app (senza router montati, il cui prefisso non è ricostruibile come template);
156
+ altrimenti valgono i template della policy (§3.3 punto 2).
157
+ - HTTP/2 (`node:http2`) non è ancora agganciato.
158
+
159
+ - **SDK oppure tt-egress per ogni chiamata in uscita.** Se l'app chiama un servizio esterno attraverso [tt-egress](https://github.com/ivseb/traffic-twin/blob/main/internal/egress/README.md), l'SDK registra anche il salto verso il proxy (servizio `host:…`) e la chiamata è catturata due volte. Non mettere l'indirizzo del proxy in `hosts_allow`; la Fleet segnala `double_capture` quando lo vede.
160
+
161
+ ## Sviluppo
162
+
163
+ ```bash
164
+ npm ci
165
+ npm run vectors # vettori di conformità (conformance/vectors), confronto byte per byte
166
+ npm test # unit test + integrazione (app, carrier finto, tt-core finto con mTLS)
167
+ node bench/hooks.mjs # costo del solo percorso degli hook (opz. --subject none|cookie|jwt, --out 1)
168
+ npm run bench # overhead con SDK spento/acceso (opzioni: --rate-bp, --steady-rps, --seconds, --rounds, --threads, --endpoint orders|health, --io-ms)
169
+ ```
170
+
171
+ Le dipendenze di sviluppo (TypeScript, `@types/node`, OpenTelemetry per il test di
172
+ convivenza) sono fissate a versioni esatte.
@@ -0,0 +1,143 @@
1
+ import type { CaptureHost, RawExchange } from './capture/common.js';
2
+ import { Sanitizer } from './sanitizer/sanitizer.js';
3
+ export type SourceState = 'starting' | 'capturing' | 'no_policy' | 'policy_rejected' | 'expired_policy' | 'key_missing' | 'key_mismatch' | 'killed';
4
+ export interface AgentOptions {
5
+ /** Fleet base URL used for enrollment (TT_ENROLL_URL). */
6
+ enrollUrl?: string;
7
+ /** Enrollment token `tte_<secret>.<pin>` (TT_ENROLL_TOKEN). */
8
+ enrollToken?: string;
9
+ /** Content of the HMAC key (TT_HMAC_KEY). */
10
+ hmacKey?: string;
11
+ /** File holding the HMAC key (TT_HMAC_KEY_FILE). */
12
+ hmacKeyFile?: string;
13
+ /** Service name requested at enrollment (TT_SERVICE_NAME, else OTEL_SERVICE_NAME). */
14
+ serviceName?: string;
15
+ /** Where certificates, keys and the policy cache are kept (TT_STATE_DIR). */
16
+ stateDir?: string;
17
+ /** Informational instance name (TT_INSTANCE, default hostname). */
18
+ instance?: string;
19
+ /** Send a CSR at enrollment so the private key never leaves the process (default true). */
20
+ useCsr?: boolean;
21
+ debug?: boolean;
22
+ /** Overrides for tests and benchmarks. */
23
+ heartbeatIntervalMs?: number;
24
+ policyPollIntervalMs?: number;
25
+ exportFlushMs?: number;
26
+ /** Sanitizer worker threads: 0 = always inline, default min(2, cores - 1) (TT_SANITIZER_THREADS). */
27
+ sanitizerThreads?: number;
28
+ /** Sampling rate (basis points) from which sanitization moves to the workers (default 200 = 2%). */
29
+ workerMinBp?: number;
30
+ }
31
+ export declare function serviceNameFromEnv(env: NodeJS.ProcessEnv): string | undefined;
32
+ export declare function optionsFromEnv(env?: NodeJS.ProcessEnv): AgentOptions;
33
+ export declare class Agent implements CaptureHost {
34
+ readonly opts: AgentOptions;
35
+ readonly counters: {
36
+ exchanges_seen: number;
37
+ exchanges_sampled: number;
38
+ events_sent: number;
39
+ events_dropped_queue: number;
40
+ events_rejected: number;
41
+ send_errors: number;
42
+ sanitizer_errors: number;
43
+ };
44
+ state: SourceState;
45
+ private san;
46
+ private policy;
47
+ private policyKid;
48
+ private rejected;
49
+ private ring;
50
+ private keyState;
51
+ private heartbeatOk;
52
+ private lastContact;
53
+ private persisted;
54
+ private overrideBp;
55
+ private decisionNames;
56
+ private readonly overhead;
57
+ private overheadN;
58
+ private lastErrors;
59
+ private pending;
60
+ private pendingBytes;
61
+ private drainScheduled;
62
+ private pool;
63
+ /** The last drain handed its work to the workers: the next one is batched on a timer. */
64
+ private workerMode;
65
+ private inflight;
66
+ private inflightBytes;
67
+ private uninstall;
68
+ private timers;
69
+ private stopped;
70
+ private store;
71
+ private enrollment;
72
+ private keyPem;
73
+ private httpsAgent;
74
+ private fleet;
75
+ private exporter;
76
+ private etag;
77
+ private switching;
78
+ private acceptedHashes;
79
+ private polling;
80
+ private pollAgain;
81
+ constructor(opts: AgentOptions);
82
+ active(): Sanitizer | null;
83
+ serviceName(): string;
84
+ decisionHeaders(): ReadonlySet<string>;
85
+ propagates(): boolean;
86
+ mayPropagate(urlBase: string): boolean;
87
+ private propMemoFor;
88
+ private readonly propMemo;
89
+ private mayPropagateUncached;
90
+ noteSeen(): void;
91
+ noteSampled(): void;
92
+ noteOverhead(ns: number): void;
93
+ noteError(code: string): void;
94
+ submit(raw: RawExchange): void;
95
+ private threads;
96
+ /** Worker threads pay off only when many exchanges are sampled (high rate). */
97
+ private wantWorkers;
98
+ private onWorkerOut;
99
+ /**
100
+ * Inline sanitization runs right after the response (setImmediate). With worker threads
101
+ * the exchanges are collected for a few milliseconds and posted as one batch: one message
102
+ * and one thread wake-up for many exchanges instead of one each.
103
+ */
104
+ private scheduleDrain;
105
+ private drain;
106
+ /** Posts up to WORKER_BATCH pending exchanges to a worker. False when none could be posted. */
107
+ private drainToWorkers;
108
+ private process;
109
+ /** Installs the hooks and runs the first Fleet cycle. Never throws. */
110
+ start(): Promise<void>;
111
+ stop(): Promise<void>;
112
+ /** Sanitizes what is pending and sends everything queued (tests, graceful shutdown). */
113
+ flush(): Promise<void>;
114
+ status(): {
115
+ state: SourceState;
116
+ counters: Agent['counters'];
117
+ queue: {
118
+ events: number;
119
+ bytes: number;
120
+ };
121
+ };
122
+ private enrollWithRetry;
123
+ private connect;
124
+ private schedule;
125
+ private loadKeys;
126
+ /** Said once per cause, whatever TT_DEBUG: without the key nothing is captured. Never prints key material or paths. */
127
+ private keyWarned;
128
+ private warnKeyMissing;
129
+ private signingKeys;
130
+ private persist;
131
+ private tryAccept;
132
+ private pollPolicy;
133
+ private pollOnce;
134
+ private overheadUs;
135
+ private heartbeat;
136
+ private applyHeartbeat;
137
+ private addSigningKeys;
138
+ private renew;
139
+ private revoke;
140
+ private dropQueues;
141
+ /** Recomputes the state and the capture gate. */
142
+ private recompute;
143
+ }