@laburen/delta-sdk 1.0.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/CHANGELOG.md +29 -0
- package/LICENSE +21 -0
- package/README.md +133 -0
- package/dist/core/config.d.ts +44 -0
- package/dist/core/config.d.ts.map +1 -0
- package/dist/core/config.js +163 -0
- package/dist/core/config.js.map +1 -0
- package/dist/core/constantes.d.ts +15 -0
- package/dist/core/constantes.d.ts.map +1 -0
- package/dist/core/constantes.js +15 -0
- package/dist/core/constantes.js.map +1 -0
- package/dist/core/contadores.d.ts +28 -0
- package/dist/core/contadores.d.ts.map +1 -0
- package/dist/core/contadores.js +53 -0
- package/dist/core/contadores.js.map +1 -0
- package/dist/core/scrubbing.d.ts +10 -0
- package/dist/core/scrubbing.d.ts.map +1 -0
- package/dist/core/scrubbing.js +92 -0
- package/dist/core/scrubbing.js.map +1 -0
- package/dist/core/sesion.d.ts +9 -0
- package/dist/core/sesion.d.ts.map +1 -0
- package/dist/core/sesion.js +20 -0
- package/dist/core/sesion.js.map +1 -0
- package/dist/core/sobre.d.ts +46 -0
- package/dist/core/sobre.d.ts.map +1 -0
- package/dist/core/sobre.js +200 -0
- package/dist/core/sobre.js.map +1 -0
- package/dist/core/tipos.d.ts +154 -0
- package/dist/core/tipos.d.ts.map +1 -0
- package/dist/core/tipos.js +6 -0
- package/dist/core/tipos.js.map +1 -0
- package/dist/core/transporte.d.ts +24 -0
- package/dist/core/transporte.d.ts.map +1 -0
- package/dist/core/transporte.js +70 -0
- package/dist/core/transporte.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -0
- package/dist/telemetry/captura.d.ts +8 -0
- package/dist/telemetry/captura.d.ts.map +1 -0
- package/dist/telemetry/captura.js +136 -0
- package/dist/telemetry/captura.js.map +1 -0
- package/dist/telemetry/index.d.ts +5 -0
- package/dist/telemetry/index.d.ts.map +1 -0
- package/dist/telemetry/index.js +3 -0
- package/dist/telemetry/index.js.map +1 -0
- package/dist/telemetry/tipos.d.ts +2 -0
- package/dist/telemetry/tipos.d.ts.map +1 -0
- package/dist/telemetry/tipos.js +2 -0
- package/dist/telemetry/tipos.js.map +1 -0
- package/dist/telemetry/with-telemetry.d.ts +18 -0
- package/dist/telemetry/with-telemetry.d.ts.map +1 -0
- package/dist/telemetry/with-telemetry.js +81 -0
- package/dist/telemetry/with-telemetry.js.map +1 -0
- package/dist/telemetry/with-tool.d.ts +9 -0
- package/dist/telemetry/with-tool.d.ts.map +1 -0
- package/dist/telemetry/with-tool.js +20 -0
- package/dist/telemetry/with-tool.js.map +1 -0
- package/docs/que-se-manda.md +133 -0
- package/docs/superficies.md +239 -0
- package/docs/telemetria.md +258 -0
- package/docs/troubleshooting.md +115 -0
- package/package.json +61 -0
- package/src/core/config.ts +178 -0
- package/src/core/constantes.ts +17 -0
- package/src/core/contadores.ts +71 -0
- package/src/core/scrubbing.ts +104 -0
- package/src/core/sesion.ts +22 -0
- package/src/core/sobre.ts +236 -0
- package/src/core/tipos.ts +131 -0
- package/src/core/transporte.ts +93 -0
- package/src/index.ts +7 -0
- package/src/telemetry/captura.ts +161 -0
- package/src/telemetry/index.ts +16 -0
- package/src/telemetry/tipos.ts +13 -0
- package/src/telemetry/with-telemetry.ts +128 -0
- package/src/telemetry/with-tool.ts +23 -0
package/package.json
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@laburen/delta-sdk",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Cliente de telemetría para los workers de Laburen en Cloudflare",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"sideEffects": false,
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
},
|
|
13
|
+
"./telemetry": {
|
|
14
|
+
"types": "./dist/telemetry/index.d.ts",
|
|
15
|
+
"import": "./dist/telemetry/index.js"
|
|
16
|
+
},
|
|
17
|
+
"./package.json": "./package.json"
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"dist",
|
|
21
|
+
"src",
|
|
22
|
+
"docs",
|
|
23
|
+
"README.md",
|
|
24
|
+
"CHANGELOG.md",
|
|
25
|
+
"LICENSE"
|
|
26
|
+
],
|
|
27
|
+
"scripts": {
|
|
28
|
+
"prepack": "npm run build",
|
|
29
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json",
|
|
30
|
+
"typecheck": "tsc --noEmit && tsc --noEmit -p test/tsconfig.json",
|
|
31
|
+
"lint": "biome check .",
|
|
32
|
+
"lint:fix": "biome check --write .",
|
|
33
|
+
"test": "vitest run",
|
|
34
|
+
"test:watch": "vitest",
|
|
35
|
+
"version:check": "node scripts/check-version.mjs",
|
|
36
|
+
"check:publicable": "node scripts/check-publicable.mjs",
|
|
37
|
+
"check": "npm run build && publint && attw --pack . && npm run check:publicable && npm run version:check",
|
|
38
|
+
"smoke": "node scripts/smoke.mjs"
|
|
39
|
+
},
|
|
40
|
+
"dependencies": {},
|
|
41
|
+
"devDependencies": {
|
|
42
|
+
"@arethetypeswrong/cli": "^0.18.5",
|
|
43
|
+
"@biomejs/biome": "^2.5.6",
|
|
44
|
+
"@cloudflare/vitest-pool-workers": "^0.12.21",
|
|
45
|
+
"publint": "^0.3.22",
|
|
46
|
+
"typescript": "^5.9.3",
|
|
47
|
+
"vitest": "~3.2.0",
|
|
48
|
+
"wrangler": "^4.118.0",
|
|
49
|
+
"zod": "^4.4.3"
|
|
50
|
+
},
|
|
51
|
+
"publishConfig": {
|
|
52
|
+
"access": "public"
|
|
53
|
+
},
|
|
54
|
+
"repository": {
|
|
55
|
+
"type": "git",
|
|
56
|
+
"url": "git+https://github.com/Laburen/laburen-delta-sdk.git"
|
|
57
|
+
},
|
|
58
|
+
"engines": {
|
|
59
|
+
"node": ">=20"
|
|
60
|
+
}
|
|
61
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import { INGEST_URL } from "./constantes.js";
|
|
2
|
+
import {
|
|
3
|
+
type Notify,
|
|
4
|
+
SURFACES,
|
|
5
|
+
type Surface,
|
|
6
|
+
type TelemetryConfig,
|
|
7
|
+
type TelemetryEvent,
|
|
8
|
+
} from "./tipos.js";
|
|
9
|
+
|
|
10
|
+
export interface ConfigValidada {
|
|
11
|
+
service: { name: string; version?: string; environment?: string };
|
|
12
|
+
surface: Surface;
|
|
13
|
+
organizationId: string;
|
|
14
|
+
agentId: string;
|
|
15
|
+
apiKey: string;
|
|
16
|
+
notify: Notify;
|
|
17
|
+
ingestUrl: string;
|
|
18
|
+
scrub: string[];
|
|
19
|
+
beforeSend?: (evento: TelemetryEvent) => TelemetryEvent | null;
|
|
20
|
+
debug: boolean;
|
|
21
|
+
queueMaxRetries?: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export type ResultadoConfig =
|
|
25
|
+
| { ok: true; config: ConfigValidada }
|
|
26
|
+
| { ok: false; faltan: string[] };
|
|
27
|
+
|
|
28
|
+
// Los `?.` no son paranoia: los valores salen del env del worker, y ahí TypeScript no manda.
|
|
29
|
+
function vacio(valor: unknown): boolean {
|
|
30
|
+
return typeof valor !== "string" || valor.trim() === "";
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Mismo criterio que `textoDe` en sobre.ts: un aviso no puede lanzar por describir el valor que
|
|
34
|
+
// está avisando. `JSON.stringify` no sabe serializar un `BigInt` (un `queueMaxRetries` armado con
|
|
35
|
+
// uno lo hace lanzar), así que cae a `String()` en vez de romper el aviso.
|
|
36
|
+
function describirValor(valor: unknown): string {
|
|
37
|
+
try {
|
|
38
|
+
return JSON.stringify(valor) ?? String(valor);
|
|
39
|
+
} catch {
|
|
40
|
+
return String(valor);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// El mismo regex que aplica la ingesta: el contrato ya está duplicado a propósito, así que
|
|
45
|
+
// copiarlo acá es coherente.
|
|
46
|
+
const SLACK_CHANNEL_ID = /^[CGD][A-Z0-9]{8,}$/;
|
|
47
|
+
|
|
48
|
+
type EstadoCanal = "sinDeclarar" | "incompleto" | "completo";
|
|
49
|
+
|
|
50
|
+
// Objetos sueltos porque vienen de un `unknown` en runtime (env, fila de D1): no se puede confiar
|
|
51
|
+
// en que respeten el tipo `Notify` solo porque TypeScript los tipó así en el archivo del cliente.
|
|
52
|
+
// "sinDeclarar" es un canal AUSENTE (la clave `slack`/`email` no está, o `enabled` es `false`); un
|
|
53
|
+
// canal PRESENTE cuyo `enabled` es truthy pero no un booleano estricto (un `1` de una columna
|
|
54
|
+
// INTEGER de D1 usada como boolean, el mismo patrón que ya cita `emailPlausible` más abajo) es
|
|
55
|
+
// "incompleto", no "sinDeclarar": la ingesta valida `enabled` con un union discriminado entre los
|
|
56
|
+
// literales `true`/`false`, y cualquier otro valor le rompe el discriminante — `notify` sale crudo
|
|
57
|
+
// al sobre si el OTRO canal es válido, y la ingesta lo rechaza con "Invalid discriminator value"
|
|
58
|
+
// mientras el SDK cree que la config está sana.
|
|
59
|
+
function estadoSlack(slack: unknown): EstadoCanal {
|
|
60
|
+
if (typeof slack !== "object" || slack === null) return "sinDeclarar";
|
|
61
|
+
const valor = slack as { enabled?: unknown; channel?: unknown };
|
|
62
|
+
if (typeof valor.enabled !== "boolean") return "incompleto";
|
|
63
|
+
if (valor.enabled === false) return "sinDeclarar";
|
|
64
|
+
return typeof valor.channel === "string" && SLACK_CHANNEL_ID.test(valor.channel)
|
|
65
|
+
? "completo"
|
|
66
|
+
: "incompleto";
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Deliberadamente MÁS PERMISIVO que el `z.email()` de la ingesta (verificado con un fuzz test en
|
|
70
|
+
* `test/config.test.ts` que compara contra el Zod real): atrapa la basura obvia —sin `@`, con
|
|
71
|
+
* espacios o comas, sin un dominio con punto— y nada más. Quedar más estricto que la ingesta es
|
|
72
|
+
* peor que el 400 mudo que este archivo cierra: una dirección real rechazada acá manda TODO el
|
|
73
|
+
* worker a inerte, no solo ese evento. */
|
|
74
|
+
function emailPlausible(valor: unknown): boolean {
|
|
75
|
+
if (typeof valor !== "string" || valor === "" || valor.trim() !== valor) return false;
|
|
76
|
+
if (/\s/.test(valor) || valor.includes(",")) return false;
|
|
77
|
+
const arroba = valor.indexOf("@");
|
|
78
|
+
if (arroba <= 0 || arroba !== valor.lastIndexOf("@")) return false;
|
|
79
|
+
const dominio = valor.slice(arroba + 1);
|
|
80
|
+
if (dominio === "" || !dominio.includes(".")) return false;
|
|
81
|
+
return !dominio.startsWith(".") && !dominio.endsWith(".");
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function estadoEmail(email: unknown): EstadoCanal {
|
|
85
|
+
if (typeof email !== "object" || email === null) return "sinDeclarar";
|
|
86
|
+
const valor = email as { enabled?: unknown; to?: unknown };
|
|
87
|
+
// Mismo criterio que `estadoSlack`: un `enabled` truthy pero no booleano estricto es
|
|
88
|
+
// "incompleto", no "sinDeclarar".
|
|
89
|
+
if (typeof valor.enabled !== "boolean") return "incompleto";
|
|
90
|
+
if (valor.enabled === false) return "sinDeclarar";
|
|
91
|
+
return Array.isArray(valor.to) && valor.to.length > 0 && valor.to.every(emailPlausible)
|
|
92
|
+
? "completo"
|
|
93
|
+
: "incompleto";
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** El motivo por el que `notify` no es usable, o `null` si lo es. Dos reglas, no una: (a) un canal
|
|
97
|
+
* DECLARADO (`enabled: true`) pero incompleto invalida TODA la config, aunque el otro canal esté
|
|
98
|
+
* bien — antes esto era un `||`, y un slack roto con un email bueno pasaba la validación porque el
|
|
99
|
+
* email "salvaba" el OR; la ingesta igual rechazaba el sobre por `slack.channel`, un 400 mudo que
|
|
100
|
+
* el SDK nunca llegaba a ver; (b) al menos un canal tiene que estar completo. Nunca lanza: un
|
|
101
|
+
* `notify` armado con un getter o un `Proxy` que lanza al leer sus propiedades cuenta como "no
|
|
102
|
+
* usable", no como una excepción que se escapa de `createTelemetry` — el SDK no lanza nunca, ni
|
|
103
|
+
* con el notify más raro. */
|
|
104
|
+
export function motivoNotifyInvalido(notify: unknown): string | null {
|
|
105
|
+
try {
|
|
106
|
+
if (typeof notify !== "object" || notify === null) {
|
|
107
|
+
return "notify (revisá slack.channel / email.to)";
|
|
108
|
+
}
|
|
109
|
+
const valor = notify as { slack?: unknown; email?: unknown };
|
|
110
|
+
const slack = estadoSlack(valor.slack);
|
|
111
|
+
const email = estadoEmail(valor.email);
|
|
112
|
+
if (slack === "incompleto") return "notify: slack.channel declarado pero vacío o mal formado";
|
|
113
|
+
if (email === "incompleto") return "notify: email.to declarado pero vacío o mal formado";
|
|
114
|
+
if (slack !== "completo" && email !== "completo") {
|
|
115
|
+
return "notify (revisá slack.channel / email.to)";
|
|
116
|
+
}
|
|
117
|
+
return null;
|
|
118
|
+
} catch {
|
|
119
|
+
return "notify (no se pudo leer: revisá slack.channel / email.to)";
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Wrapper booleano de `motivoNotifyInvalido`, para los callers que solo necesitan saber si el
|
|
124
|
+
* `notify` sirve (el override por evento de `captura.ts`) sin mostrar el motivo. */
|
|
125
|
+
export function notifyUsable(notify: unknown): boolean {
|
|
126
|
+
return motivoNotifyInvalido(notify) === null;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Un `queueMaxRetries` usable es un entero ≥ 0: sale del `max_retries` del `wrangler.jsonc` vía
|
|
130
|
+
* una `var` del env, que siempre es `string` — `"2" + 1` da `"21"`, no `3`. */
|
|
131
|
+
export function queueMaxRetriesUsable(valor: unknown): valor is number {
|
|
132
|
+
return typeof valor === "number" && Number.isInteger(valor) && valor >= 0;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Valida en runtime lo que el tipo no puede: un campo que llega vacío desde el env es un string
|
|
136
|
+
* válido para TypeScript, y significa que ese worker nunca va a reportar nada. */
|
|
137
|
+
export function validar(entrada: TelemetryConfig): ResultadoConfig {
|
|
138
|
+
const faltan: string[] = [];
|
|
139
|
+
if (vacio(entrada.service?.name)) faltan.push("service.name");
|
|
140
|
+
if (vacio(entrada.organizationId)) faltan.push("organizationId");
|
|
141
|
+
if (vacio(entrada.agentId)) faltan.push("agentId");
|
|
142
|
+
if (vacio(entrada.apiKey)) faltan.push("apiKey");
|
|
143
|
+
if (!(SURFACES as readonly string[]).includes(entrada.surface)) faltan.push("surface");
|
|
144
|
+
const motivoNotify = motivoNotifyInvalido(entrada.notify);
|
|
145
|
+
if (motivoNotify !== null) faltan.push(motivoNotify);
|
|
146
|
+
if (faltan.length > 0) return { ok: false, faltan };
|
|
147
|
+
|
|
148
|
+
const service: ConfigValidada["service"] = { name: entrada.service.name.trim() };
|
|
149
|
+
if (entrada.service.version !== undefined) service.version = entrada.service.version;
|
|
150
|
+
if (entrada.service.environment !== undefined) service.environment = entrada.service.environment;
|
|
151
|
+
|
|
152
|
+
const config: ConfigValidada = {
|
|
153
|
+
service,
|
|
154
|
+
surface: entrada.surface,
|
|
155
|
+
organizationId: entrada.organizationId.trim(),
|
|
156
|
+
agentId: entrada.agentId.trim(),
|
|
157
|
+
apiKey: entrada.apiKey.trim(),
|
|
158
|
+
notify: entrada.notify,
|
|
159
|
+
// La URL es constante del paquete; el override existe solo para desarrollo local.
|
|
160
|
+
ingestUrl: entrada.ingestUrl?.trim() || INGEST_URL,
|
|
161
|
+
scrub: entrada.scrub ?? [],
|
|
162
|
+
debug: entrada.debug ?? false,
|
|
163
|
+
};
|
|
164
|
+
if (entrada.beforeSend !== undefined) config.beforeSend = entrada.beforeSend;
|
|
165
|
+
if (entrada.queueMaxRetries !== undefined) {
|
|
166
|
+
if (queueMaxRetriesUsable(entrada.queueMaxRetries)) {
|
|
167
|
+
config.queueMaxRetries = entrada.queueMaxRetries;
|
|
168
|
+
} else {
|
|
169
|
+
// Se descarta y no se suma a `faltan`: a diferencia de los seis obligatorios, sin este
|
|
170
|
+
// dato el cliente sigue reportando — solo se omite `retry.limit` en surface "queue".
|
|
171
|
+
console.error(
|
|
172
|
+
`[delta-sdk] queueMaxRetries inválido (se esperaba un entero ≥ 0, llegó ${describirValor(entrada.queueMaxRetries)}): se ignora`,
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
return { ok: true, config };
|
|
178
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** La ingesta es infraestructura, no config del cliente: si viviera en cada worker, cambiarla
|
|
2
|
+
* obligaría a editar y redeployar cada worker que la use. */
|
|
3
|
+
export const INGEST_URL = "https://telemetry.laburen.com/events";
|
|
4
|
+
|
|
5
|
+
export const SDK_NAME = "@laburen/delta-sdk";
|
|
6
|
+
|
|
7
|
+
/** Tiene que coincidir con `version` del package.json; lo verifica `npm run version:check`. */
|
|
8
|
+
export const SDK_VERSION = "1.0.0";
|
|
9
|
+
|
|
10
|
+
/** Los mismos topes que aplica la ingesta. El cliente los aplica para no perder el sobre entero;
|
|
11
|
+
* la ingesta, para no confiar en el cliente. */
|
|
12
|
+
export const LIMITES = {
|
|
13
|
+
stacktraceChars: 8 * 1024,
|
|
14
|
+
messageChars: 2 * 1024,
|
|
15
|
+
attributeKeys: 64,
|
|
16
|
+
bodyBytes: 512 * 1024,
|
|
17
|
+
} as const;
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/** Lo que viaja en el campo `drops` del sobre. La ingesta lo acepta como
|
|
2
|
+
* `z.record(z.string(), z.number())`, así que las claves son libres; `before_send` conserva la
|
|
3
|
+
* grafía canónica de Sentry para las razones de drop. */
|
|
4
|
+
export interface Drops {
|
|
5
|
+
incompletos: number;
|
|
6
|
+
fallados: number;
|
|
7
|
+
before_send: number;
|
|
8
|
+
recortados: number;
|
|
9
|
+
internos: number;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const stats = {
|
|
13
|
+
disparados: 0,
|
|
14
|
+
completados: 0,
|
|
15
|
+
fallados: 0,
|
|
16
|
+
before_send: 0,
|
|
17
|
+
recortados: 0,
|
|
18
|
+
internos: 0,
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/** Veces que el código pidió enviar. */
|
|
22
|
+
export function contarDisparado(): void {
|
|
23
|
+
stats.disparados += 1;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Envíos que terminaron, con cualquier status: un 429 y un 503 salieron y los rechazaron. */
|
|
27
|
+
export function contarCompletado(): void {
|
|
28
|
+
stats.completados += 1;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Envíos que lanzaron: red, DNS. */
|
|
32
|
+
export function contarFallado(): void {
|
|
33
|
+
stats.fallados += 1;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function contarBeforeSend(): void {
|
|
37
|
+
stats.before_send += 1;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function contarRecortado(): void {
|
|
41
|
+
stats.recortados += 1;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** La quinta forma de perder un evento: algo entre `armarEvento` y `serializarAcotado` lanzó, y la
|
|
45
|
+
* red del `catch` de `capturar` lo atrapó. Sin este contador, ese evento desaparecía sin dejar
|
|
46
|
+
* rastro en ningún `drops` del sobre siguiente. */
|
|
47
|
+
export function contarInterno(): void {
|
|
48
|
+
stats.internos += 1;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** `incompletos` es la resta, y es el único contador que prueba pérdida por ciclo de vida: sin
|
|
52
|
+
* esta separación, un 429 por rate limit y "se perdió el evento" se ven idénticos. */
|
|
53
|
+
export function drops(): Drops {
|
|
54
|
+
return {
|
|
55
|
+
incompletos: stats.disparados - stats.completados - stats.fallados,
|
|
56
|
+
fallados: stats.fallados,
|
|
57
|
+
before_send: stats.before_send,
|
|
58
|
+
recortados: stats.recortados,
|
|
59
|
+
internos: stats.internos,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Solo para los tests. No sale por ninguna puerta del `exports` map. */
|
|
64
|
+
export function reiniciarContadores(): void {
|
|
65
|
+
stats.disparados = 0;
|
|
66
|
+
stats.completados = 0;
|
|
67
|
+
stats.fallados = 0;
|
|
68
|
+
stats.before_send = 0;
|
|
69
|
+
stats.recortados = 0;
|
|
70
|
+
stats.internos = 0;
|
|
71
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import type { TelemetryEvent } from "./tipos.js";
|
|
2
|
+
|
|
3
|
+
export const REDACTADO = "[redactado]";
|
|
4
|
+
|
|
5
|
+
/** Los términos habituales en credenciales: claves, tokens y headers de autorización. */
|
|
6
|
+
export const DENYLIST = [
|
|
7
|
+
"secret",
|
|
8
|
+
"token",
|
|
9
|
+
"apikey",
|
|
10
|
+
"api_key",
|
|
11
|
+
"password",
|
|
12
|
+
"authorization",
|
|
13
|
+
"bearer",
|
|
14
|
+
"cookie",
|
|
15
|
+
"credential",
|
|
16
|
+
"private_key",
|
|
17
|
+
] as const;
|
|
18
|
+
|
|
19
|
+
function escaparRegex(termino: string): string {
|
|
20
|
+
return termino.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function claveSospechosa(clave: string, terminos: string[]): boolean {
|
|
24
|
+
const bajo = clave.toLowerCase();
|
|
25
|
+
return terminos.some((termino) => bajo.includes(termino.toLowerCase()));
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Es una red para descuidos, no una garantía: un secreto en un campo llamado `config` no lo
|
|
29
|
+
* agarra. La defensa real es no meter secretos en el mensaje de error.
|
|
30
|
+
*
|
|
31
|
+
* Dos reglas con alcance distinto a propósito. `clave: valor` / `clave=valor` es inequívoca —el
|
|
32
|
+
* separador ya dice "lo que sigue es un valor"— y por eso corre para la denylist completa. La
|
|
33
|
+
* regla sin separador, `clave valor`, es una apuesta: no hay forma de distinguir un valor real de
|
|
34
|
+
* la palabra siguiente de una frase, y la denylist completa aparece todo el tiempo en prosa
|
|
35
|
+
* común ("Token no disponible", "Password reset required"); aplicarla ahí mutila mensajes que no
|
|
36
|
+
* tenían ningún secreto. Con `bearer` la apuesta vale la pena porque el 100% de sus apariciones
|
|
37
|
+
* reales son un header sin dos puntos (`Bearer eyJ…`); con los términos que el propio cliente
|
|
38
|
+
* pasa por `scrub` también, porque ahí la agresividad es la que pidió explícitamente. */
|
|
39
|
+
function redactarTexto(texto: string, completa: readonly string[], agresivos: string[]): string {
|
|
40
|
+
let salida = texto;
|
|
41
|
+
for (const termino of completa) {
|
|
42
|
+
const t = escaparRegex(termino);
|
|
43
|
+
// `clave: valor` y `clave=valor`: se borra el resto de la línea, porque el valor puede
|
|
44
|
+
// tener espacios (`Authorization: Bearer eyJ…`).
|
|
45
|
+
salida = salida.replace(new RegExp(`(${t})\\s*[:=]\\s*[^\\n]*`, "gi"), `$1: ${REDACTADO}`);
|
|
46
|
+
}
|
|
47
|
+
for (const termino of agresivos) {
|
|
48
|
+
const t = escaparRegex(termino);
|
|
49
|
+
// `clave valor`: solo el token que sigue, y solo para `bearer` y los términos del cliente
|
|
50
|
+
// (ver el comentario de arriba). No matchea una mención suelta al final de la frase, que
|
|
51
|
+
// no tiene nada detrás.
|
|
52
|
+
salida = salida.replace(new RegExp(`(${t})\\s+(\\S+)`, "gi"), `$1 ${REDACTADO}`);
|
|
53
|
+
}
|
|
54
|
+
return salida;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Devuelve una copia con la denylist y los términos del cliente aplicados. No muta la entrada:
|
|
58
|
+
* el evento original es el que ve el implementador si algo falla después. */
|
|
59
|
+
export function scrubEvento(evento: TelemetryEvent, extra: string[] = []): TelemetryEvent {
|
|
60
|
+
const terminos = [...DENYLIST, ...extra];
|
|
61
|
+
// La regla sin separador solo corre para `bearer` (headers reales sin dos puntos) y lo que el
|
|
62
|
+
// cliente mismo eligió redactar así: el resto de la denylist es prosa común, no un valor.
|
|
63
|
+
const agresivos = ["bearer", ...extra];
|
|
64
|
+
const salida: TelemetryEvent = { ...evento };
|
|
65
|
+
|
|
66
|
+
if (salida.message !== undefined) {
|
|
67
|
+
salida.message = redactarTexto(salida.message, terminos, agresivos);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
if (salida.exception !== undefined) {
|
|
71
|
+
const excepcion = { ...salida.exception };
|
|
72
|
+
if (excepcion.message !== undefined) {
|
|
73
|
+
excepcion.message = redactarTexto(excepcion.message, terminos, agresivos);
|
|
74
|
+
}
|
|
75
|
+
if (excepcion.stacktrace !== undefined) {
|
|
76
|
+
excepcion.stacktrace = redactarTexto(excepcion.stacktrace, terminos, agresivos);
|
|
77
|
+
}
|
|
78
|
+
salida.exception = excepcion;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
if (salida.attributes !== undefined) {
|
|
82
|
+
const atributos: Record<string, string | number | boolean> = {};
|
|
83
|
+
for (const [clave, valor] of Object.entries(salida.attributes)) {
|
|
84
|
+
atributos[clave] = claveSospechosa(clave, terminos) ? REDACTADO : valor;
|
|
85
|
+
}
|
|
86
|
+
salida.attributes = atributos;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return salida;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** El escape hatch. Un `null` descarta el evento; una excepción no puede hacerlo perder. */
|
|
93
|
+
export function aplicarBeforeSend(
|
|
94
|
+
evento: TelemetryEvent,
|
|
95
|
+
beforeSend: ((evento: TelemetryEvent) => TelemetryEvent | null) | undefined,
|
|
96
|
+
): TelemetryEvent | null {
|
|
97
|
+
if (beforeSend === undefined) return evento;
|
|
98
|
+
try {
|
|
99
|
+
return beforeSend(evento);
|
|
100
|
+
} catch (error) {
|
|
101
|
+
console.error("[delta-sdk] beforeSend lanzó; el evento se manda sin aplicarlo", error);
|
|
102
|
+
return evento;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
let _session: string | null = null;
|
|
2
|
+
let _seq = 0;
|
|
3
|
+
|
|
4
|
+
/** El id del isolate. Perezoso: generarlo al cargar el módulo hace fallar el deploy del worker
|
|
5
|
+
* del cliente, y `wrangler dev` local no lo detecta. */
|
|
6
|
+
export function session(): string {
|
|
7
|
+
// biome-ignore lint/suspicious/noAssignInExpressions: el `??=` perezoso es el punto del diseño.
|
|
8
|
+
return (_session ??= crypto.randomUUID().slice(0, 8));
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Arranca en 1 y no se reinicia: la ingesta detecta los huecos comparando los seq que le
|
|
12
|
+
* llegan. Detecta huecos en el medio, no una cola cortada. */
|
|
13
|
+
export function nextSeq(): number {
|
|
14
|
+
_seq += 1;
|
|
15
|
+
return _seq;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Solo para los tests. No sale por ninguna puerta del `exports` map. */
|
|
19
|
+
export function reiniciarSesion(): void {
|
|
20
|
+
_session = null;
|
|
21
|
+
_seq = 0;
|
|
22
|
+
}
|