opencode-apex 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,385 @@
1
+ /**
2
+ * Apex Redact — patrones de detección de secretos.
3
+ *
4
+ * Fuentes (patrones por defecto copiados íntegramente):
5
+ * - opencode-secret-redactor@0.5.1 (casonadams)
6
+ * - opencode-warden@latest (toreuyar)
7
+ * - más los patrones propios de apex
8
+ *
9
+ * Cada patrón declara:
10
+ * - `name` identificador único (se usa como etiqueta legible del marcador)
11
+ * - `regex` expresión regular con flag `g`
12
+ * - `confidence` low | medium | high — filtra vía `redact.minConfidence`
13
+ * - `validate?` comprobación extra sobre el match (Luhn, IPs privadas…)
14
+ *
15
+ * NOTA IMPORTANTE: apex redacta el CONTEXTO COMPLETO (system prompt + historial
16
+ * + tools), no solo la salida de una tool. Por eso los patrones ruidosos o de
17
+ * baja confianza NO se activan por defecto (`minConfidence: "medium"`), y los
18
+ * de PII viven en bundles propios que hay que activar explícitamente.
19
+ */
20
+
21
+ export type PatternConfidence = "low" | "medium" | "high"
22
+
23
+ export interface PatternDefinition {
24
+ readonly name: string
25
+ readonly regex: RegExp
26
+ readonly confidence: PatternConfidence
27
+ /** Comprobación adicional; si devuelve false el match se ignora. */
28
+ readonly validate?: (match: string) => boolean
29
+ /** Origen del patrón, para trazabilidad. */
30
+ readonly source?: "apex" | "secret-redactor" | "warden"
31
+ }
32
+
33
+ // ---------------------------------------------------------------------------
34
+ // Validadores compartidos
35
+ // ---------------------------------------------------------------------------
36
+
37
+ /** Algoritmo de Luhn (tarjetas de crédito). */
38
+ export function luhnCheck(value: string): boolean {
39
+ const digits = value.replace(/\D/g, "")
40
+ if (digits.length < 12) return false
41
+ let sum = 0
42
+ let alternate = false
43
+ for (let i = digits.length - 1; i >= 0; i--) {
44
+ let n = Number.parseInt(digits[i]!, 10)
45
+ if (alternate) {
46
+ n *= 2
47
+ if (n > 9) n -= 9
48
+ }
49
+ sum += n
50
+ alternate = !alternate
51
+ }
52
+ return sum % 10 === 0
53
+ }
54
+
55
+ const PRIVATE_IP = /^(?:127\.|0\.0\.0\.0|192\.168\.|10\.|172\.(?:1[6-9]|2\d|3[01])\.|255\.255\.255\.)/
56
+ const isPublicIp = (value: string): boolean => !PRIVATE_IP.test(value)
57
+
58
+ // ---------------------------------------------------------------------------
59
+ // Bundles
60
+ // ---------------------------------------------------------------------------
61
+
62
+ const BUNDLES: Record<string, PatternDefinition[]> = {
63
+ // ------------------------------------------------------------------ AWS
64
+ aws: [
65
+ { name: "aws-access-key-id", regex: /\b(?:AKIA|ASIA|AIDA|AROA|AIPA|ANPA|ANVA)[0-9A-Z]{16}\b/g, confidence: "high", source: "warden" },
66
+ {
67
+ name: "aws-secret-access-key",
68
+ regex: /(?<=(?:aws_secret_access_key|AWS_SECRET_ACCESS_KEY|SecretAccessKey|secret_access_key)\s*[=:\s"']+)[A-Za-z0-9/+=]{40}/g,
69
+ confidence: "high",
70
+ source: "warden",
71
+ },
72
+ ],
73
+
74
+ // --------------------------------------------------------------- GitHub
75
+ github: [
76
+ { name: "github-pat", regex: /\bgh[pousr]_[A-Za-z0-9]{36,255}\b/g, confidence: "high", source: "warden" },
77
+ { name: "github-fine-grained-pat", regex: /\bgithub_pat_[A-Za-z0-9_]{22,255}\b/g, confidence: "high", source: "warden" },
78
+ { name: "github-app-token", regex: /\bghu_[A-Za-z0-9]{36,}/g, confidence: "high", source: "secret-redactor" },
79
+ { name: "github-app-install", regex: /\bghs_[A-Za-z0-9]{36,}/g, confidence: "high", source: "secret-redactor" },
80
+ ],
81
+
82
+ // --------------------------------------------------------------- GitLab
83
+ gitlab: [
84
+ { name: "gitlab-pat", regex: /\bglpat-[A-Za-z0-9_-]{20,}/g, confidence: "high", source: "secret-redactor" },
85
+ { name: "gitlab-pipeline-trigger", regex: /\bglptt-[A-Za-z0-9_-]{20,}/g, confidence: "high", source: "secret-redactor" },
86
+ { name: "gitlab-deploy-token", regex: /\bgldt-[A-Za-z0-9_-]{20,}/g, confidence: "high", source: "secret-redactor" },
87
+ { name: "gitlab-ci-job-token", regex: /\bglcbt-[A-Za-z0-9_-]{20,}/g, confidence: "high", source: "secret-redactor" },
88
+ { name: "gitlab-runner-token", regex: /\bglrt-[A-Za-z0-9_-]{20,}/g, confidence: "high", source: "secret-redactor" },
89
+ { name: "gitlab-service-account", regex: /\bglsoat-[A-Za-z0-9_-]{20,}/g, confidence: "high", source: "secret-redactor" },
90
+ { name: "gitlab-feed-token", regex: /\bglft-[A-Za-z0-9_-]{20,}/g, confidence: "high", source: "secret-redactor" },
91
+ { name: "gitlab-incoming-mail", regex: /\bglimt-[A-Za-z0-9_-]{20,}/g, confidence: "high", source: "secret-redactor" },
92
+ { name: "gitlab-oauth-secret", regex: /\bgloas-[A-Za-z0-9_-]{20,}/g, confidence: "high", source: "secret-redactor" },
93
+ { name: "gitlab-agent-token", regex: /\bglagent-[A-Za-z0-9_-]{20,}/g, confidence: "high", source: "secret-redactor" },
94
+ ],
95
+
96
+ // -------------------------------------------------------- Proveedores IA
97
+ openai: [
98
+ { name: "openai-project-key", regex: /\bsk-proj-[A-Za-z0-9_-]{20,}/g, confidence: "high", source: "warden" },
99
+ { name: "openai-legacy-key", regex: /\bsk-(?!ant-)(?!proj-)[A-Za-z0-9]{20,}/g, confidence: "medium", source: "secret-redactor" },
100
+ ],
101
+ anthropic: [
102
+ { name: "anthropic-api-key", regex: /\bsk-ant-[A-Za-z0-9_-]{20,}/g, confidence: "high", source: "warden" },
103
+ ],
104
+ cohere: [{ name: "cohere-key", regex: /\bco-[A-Za-z0-9]{30,}/g, confidence: "low", source: "secret-redactor" }],
105
+ huggingface: [{ name: "huggingface-token", regex: /\bhf_[A-Za-z0-9]{30,}/g, confidence: "high", source: "secret-redactor" }],
106
+
107
+ // ------------------------------------------------------------ Google Cloud
108
+ google: [
109
+ { name: "gcp-api-key", regex: /\bAIza[0-9A-Za-z_-]{35}/g, confidence: "high", source: "warden" },
110
+ { name: "google-oauth-secret", regex: /\bGOCSPX-[A-Za-z0-9_-]{28}/g, confidence: "high", source: "secret-redactor" },
111
+ { name: "gcloud-access-token", regex: /\bya29\.[A-Za-z0-9_-]{50,}/g, confidence: "high", source: "secret-redactor" },
112
+ { name: "google-refresh-token", regex: /\b1\/\/[A-Za-z0-9_-]{40,}/g, confidence: "medium", source: "secret-redactor" },
113
+ ],
114
+
115
+ // ------------------------------------------------------------- Plataformas
116
+ slack: [
117
+ { name: "slack-token", regex: /\bxox[baprs]-[A-Za-z0-9-]{10,}/g, confidence: "high", source: "warden" },
118
+ { name: "slack-webhook", regex: /\bhooks\.slack\.com\/services\/T[A-Z0-9]+\/B[A-Z0-9]+\/[A-Za-z0-9]+/g, confidence: "high", source: "secret-redactor" },
119
+ ],
120
+ stripe: [
121
+ { name: "stripe-secret-key", regex: /\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{20,}/g, confidence: "high", source: "warden" },
122
+ { name: "stripe-webhook-secret", regex: /\bwhsec_[A-Za-z0-9]{32,}/g, confidence: "high", source: "secret-redactor" },
123
+ ],
124
+ twilio: [{ name: "twilio-api-key", regex: /\bSK[0-9a-fA-F]{32}\b/g, confidence: "medium", source: "warden" }],
125
+ sendgrid: [{ name: "sendgrid-api-key", regex: /\bSG\.[A-Za-z0-9_-]{22,}\.[A-Za-z0-9_-]{22,}/g, confidence: "high", source: "warden" }],
126
+ postman: [{ name: "postman-api-key", regex: /\bPMAK-[A-Za-z0-9-]{50,}/g, confidence: "high", source: "secret-redactor" }],
127
+ datadog: [{ name: "datadog-api-key", regex: /\bdd[a-z]{1,2}_[A-Za-z0-9]{32,40}/g, confidence: "low", source: "secret-redactor" }],
128
+ discord: [{ name: "discord-bot-token", regex: /\b[MN][A-Za-z\d]{23,}\.[\w-]{6}\.[\w-]{27,}/g, confidence: "medium", source: "warden" }],
129
+ mailgun: [{ name: "mailgun-api-key", regex: /\bkey-[0-9a-zA-Z]{32}/g, confidence: "high", source: "warden" }],
130
+ mailchimp: [{ name: "mailchimp-api-key", regex: /\b[a-f0-9]{32}-us\d{1,2}\b/g, confidence: "medium", source: "secret-redactor" }],
131
+ linear: [{ name: "linear-api-key", regex: /\blin_api_[A-Za-z0-9]{40,}/g, confidence: "high", source: "secret-redactor" }],
132
+ shopify: [
133
+ { name: "shopify-access-token", regex: /\bshpat_[a-fA-F0-9]{20,}/g, confidence: "high", source: "secret-redactor" },
134
+ { name: "shopify-custom-app", regex: /\bshpca_[a-fA-F0-9]{20,}/g, confidence: "high", source: "secret-redactor" },
135
+ { name: "shopify-private-app", regex: /\bshppa_[a-fA-F0-9]{20,}/g, confidence: "high", source: "secret-redactor" },
136
+ { name: "shopify-shared-secret", regex: /\bshpss_[a-fA-F0-9]{20,}/g, confidence: "high", source: "secret-redactor" },
137
+ ],
138
+ square: [
139
+ { name: "square-access-token", regex: /\bsq0atp-[A-Za-z0-9_-]{22,}/g, confidence: "high", source: "secret-redactor" },
140
+ { name: "square-oauth-secret", regex: /\bsq0csp-[A-Za-z0-9_-]{43}/g, confidence: "high", source: "secret-redactor" },
141
+ ],
142
+ docker: [
143
+ { name: "docker-swarm-token", regex: /\bSWMTKN-1-[a-z0-9]{49,}-[a-z0-9]{25,}/g, confidence: "high", source: "warden" },
144
+ { name: "docker-registry-auth", regex: /(?<="auth"\s*:\s*")[A-Za-z0-9+/=]{20,}(?=")/g, confidence: "high", source: "warden" },
145
+ { name: "docker-pat", regex: /\bdckr_pat_[A-Za-z0-9_-]{24,}/g, confidence: "high", source: "secret-redactor" },
146
+ {
147
+ name: "docker-run-env-secret",
148
+ regex: /(?<=docker\s+(?:run|exec|create)\s+.*(?:-e|--env)\s+(?:[A-Z_]*(?:SECRET|TOKEN|PASSWORD|KEY|CREDENTIAL|AUTH)[A-Z_]*)=)[^\s]+/gi,
149
+ confidence: "high",
150
+ source: "warden",
151
+ },
152
+ {
153
+ name: "docker-build-arg-secret",
154
+ regex: /(?<=--build-arg\s+(?:[A-Z_]*(?:SECRET|TOKEN|PASSWORD|KEY|CREDENTIAL|AUTH)[A-Z_]*)=)[^\s]+/gi,
155
+ confidence: "high",
156
+ source: "warden",
157
+ },
158
+ ],
159
+
160
+ // ------------------------------------------------------------- Registries
161
+ npm: [{ name: "npm-token", regex: /\bnpm_[A-Za-z0-9]{36,}/g, confidence: "high", source: "warden" }],
162
+ pypi: [{ name: "pypi-token", regex: /\bpypi-[A-Za-z0-9_-]{50,}/g, confidence: "high", source: "warden" }],
163
+ rubygems: [{ name: "rubygems-key", regex: /\brubygems_[A-Za-z0-9]{48}/g, confidence: "high", source: "secret-redactor" }],
164
+
165
+ // ------------------------------------------------------------------ Cloud
166
+ azure: [
167
+ {
168
+ name: "azure-connection-string",
169
+ regex: /DefaultEndpointsProtocol=https?;AccountName=[^;\s]+;AccountKey=[A-Za-z0-9+/=]{40,};/g,
170
+ confidence: "high",
171
+ source: "warden",
172
+ },
173
+ { name: "azure-storage-key", regex: /\bAccountKey=[A-Za-z0-9+/]{86}==/g, confidence: "high", source: "secret-redactor" },
174
+ { name: "azure-sas-token", regex: /[?&](?:sig|sv)=[^&\s'"]{10,}(?:&[a-z]{2,3}=[^&\s'"]+){2,}/g, confidence: "high", source: "warden" },
175
+ {
176
+ name: "azure-ad-client-secret",
177
+ regex: /(?<=(?:AZURE_CLIENT_SECRET|client_secret|clientSecret)\s*[=:]\s*['"]?)[A-Za-z0-9~._-]{30,}/g,
178
+ confidence: "medium",
179
+ source: "warden",
180
+ },
181
+ ],
182
+ terraform: [
183
+ { name: "terraform-state-sensitive", regex: /(?<="sensitive":\s*true,\s*"value":\s*")[^"]+/g, confidence: "high", source: "warden" },
184
+ { name: "terraform-var-secret", regex: /(?<=TF_VAR_[a-z_]*(?:secret|password|token|key)[a-z_]*=)[^\s]+/gi, confidence: "high", source: "warden" },
185
+ { name: "terraform-cloud-token", regex: /\b[A-Za-z0-9]{14}\.atlasv1\.[A-Za-z0-9_-]{60,}/g, confidence: "high", source: "secret-redactor" },
186
+ { name: "pulumi-token", regex: /\bpul-[a-f0-9]{40}/g, confidence: "high", source: "secret-redactor" },
187
+ { name: "pulumi-passphrase", regex: /(?<=PULUMI_CONFIG_PASSPHRASE\s*[=:]\s*['"]?)[^\s'"]+/g, confidence: "high", source: "warden" },
188
+ ],
189
+ vault: [
190
+ { name: "vault-token-hvs", regex: /\bhvs\.[A-Za-z0-9_-]{24,}/g, confidence: "high", source: "warden" },
191
+ { name: "vault-token-s", regex: /(?<=(?:VAULT_TOKEN|X-Vault-Token)\s*[=:]\s*['"]?)s\.[A-Za-z0-9]{24,}/g, confidence: "high", source: "warden" },
192
+ ],
193
+ heroku: [
194
+ {
195
+ name: "heroku-api-key",
196
+ regex: /(?<=(?:HEROKU_API_KEY|heroku_api_key)\s*[=:\s"']+)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g,
197
+ confidence: "high",
198
+ source: "warden",
199
+ },
200
+ ],
201
+ vercel: [
202
+ { name: "vercel-token", regex: /\bvercel_[A-Za-z0-9]{24,}/g, confidence: "high", source: "secret-redactor" },
203
+ {
204
+ name: "vercel-token-env",
205
+ regex: /(?<=(?:VERCEL_TOKEN|vercel_token)\s*[=:]\s*['"]?)[A-Za-z0-9]{24,}/g,
206
+ confidence: "medium",
207
+ source: "warden",
208
+ },
209
+ ],
210
+ supabase: [
211
+ {
212
+ name: "supabase-service-role-key",
213
+ regex: /(?<=(?:SUPABASE_SERVICE_ROLE_KEY|supabase_service_role_key|service_role)\s*[=:]\s*['"]?)eyJ[A-Za-z0-9_-]{100,}/g,
214
+ confidence: "high",
215
+ source: "warden",
216
+ },
217
+ ],
218
+ digitalocean: [
219
+ { name: "digitalocean-pat", regex: /\bdop_v1_[a-f0-9]{64}/g, confidence: "high", source: "warden" },
220
+ { name: "digitalocean-oauth", regex: /\bdoo_v1_[a-f0-9]{64}/g, confidence: "high", source: "secret-redactor" },
221
+ ],
222
+ cloudflare: [
223
+ {
224
+ name: "cloudflare-api-token",
225
+ regex: /(?<=(?:CF_API_TOKEN|CLOUDFLARE_API_TOKEN)\s*[=:]\s*['"]?)[A-Za-z0-9_-]{40,}/g,
226
+ confidence: "high",
227
+ source: "warden",
228
+ },
229
+ {
230
+ name: "cloudflare-global-api-key",
231
+ regex: /(?<=(?:CF_API_KEY|CLOUDFLARE_API_KEY)\s*[=:]\s*['"]?)[0-9a-f]{37}/g,
232
+ confidence: "high",
233
+ source: "warden",
234
+ },
235
+ ],
236
+
237
+ // -------------------------------------------------------- Observabilidad
238
+ observability: [
239
+ {
240
+ name: "sentry-dsn",
241
+ regex: /https:\/\/[a-f0-9]{32}@[^\s/]+\.ingest\.sentry\.io\/[0-9]+/g,
242
+ confidence: "high",
243
+ source: "secret-redactor",
244
+ },
245
+ { name: "grafana-api-key", regex: /\bglc_[A-Za-z0-9_-]{32,}/g, confidence: "high", source: "secret-redactor" },
246
+ { name: "doppler-token", regex: /\bdp\.st\.[A-Za-z0-9_-]{40,}/g, confidence: "high", source: "secret-redactor" },
247
+ ],
248
+
249
+ // --------------------------------------------------------- Claves privadas
250
+ pem: [
251
+ { name: "rsa-private-key", regex: /-----BEGIN RSA PRIVATE KEY-----[\s\S]*?-----END RSA PRIVATE KEY-----/g, confidence: "high", source: "warden" },
252
+ { name: "openssh-private-key", regex: /-----BEGIN OPENSSH PRIVATE KEY-----[\s\S]*?-----END OPENSSH PRIVATE KEY-----/g, confidence: "high", source: "warden" },
253
+ { name: "dsa-private-key", regex: /-----BEGIN DSA PRIVATE KEY-----[\s\S]*?-----END DSA PRIVATE KEY-----/g, confidence: "high", source: "warden" },
254
+ { name: "ec-private-key", regex: /-----BEGIN EC PRIVATE KEY-----[\s\S]*?-----END EC PRIVATE KEY-----/g, confidence: "high", source: "warden" },
255
+ { name: "encrypted-private-key", regex: /-----BEGIN ENCRYPTED PRIVATE KEY-----[\s\S]*?-----END ENCRYPTED PRIVATE KEY-----/g, confidence: "high", source: "warden" },
256
+ { name: "pkcs8-private-key", regex: /-----BEGIN PRIVATE KEY-----[\s\S]*?-----END PRIVATE KEY-----/g, confidence: "high", source: "warden" },
257
+ { name: "pgp-private-key", regex: /-----BEGIN PGP PRIVATE KEY BLOCK-----[\s\S]*?-----END PGP PRIVATE KEY BLOCK-----/g, confidence: "high", source: "warden" },
258
+ { name: "age-secret-key", regex: /\bAGE-SECRET-KEY-1[A-Za-z0-9]{58}/g, confidence: "high", source: "secret-redactor" },
259
+ { name: "ssh-public-key", regex: /\bssh-(?:rsa|ed25519|dss)\s+[A-Za-z0-9+/]{60,}={0,2}/g, confidence: "medium", source: "secret-redactor" },
260
+ { name: "ssh-ecdsa-key", regex: /\becdsa-sha2-nistp(?:256|384|521)\s+[A-Za-z0-9+/]{60,}={0,2}/g, confidence: "medium", source: "secret-redactor" },
261
+ ],
262
+
263
+ // ------------------------------------------------------------------ Auth
264
+ jwt: [
265
+ { name: "jwt", regex: /\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g, confidence: "high", source: "warden" },
266
+ ],
267
+ bearer: [
268
+ { name: "bearer-token", regex: /(?<=Bearer\s+)[A-Za-z0-9\-._~+/]{20,}=*/g, confidence: "medium", source: "warden" },
269
+ { name: "basic-auth", regex: /(?<=Basic\s+)[A-Za-z0-9+/]{10,}={0,2}/g, confidence: "medium", source: "secret-redactor" },
270
+ ],
271
+
272
+ // -------------------------------------------------------------- Databases
273
+ database: [
274
+ {
275
+ name: "db-uri-credentials",
276
+ regex: /\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqp):\/\/[^:\s/]+:([^@\s/]{6,})@/gi,
277
+ confidence: "high",
278
+ source: "apex",
279
+ },
280
+ { name: "mongodb-connection-string", regex: /\bmongodb(?:\+srv)?:\/\/[^\s'"]+/g, confidence: "medium", source: "warden" },
281
+ { name: "postgres-connection-string", regex: /\bpostgres(?:ql)?:\/\/[^\s'"]+/g, confidence: "medium", source: "warden" },
282
+ { name: "mysql-connection-string", regex: /\bmysql:\/\/[^\s'"]+/g, confidence: "medium", source: "warden" },
283
+ { name: "redis-connection-string", regex: /\bredis(?:s)?:\/\/[^\s'"]+/g, confidence: "low", source: "warden" },
284
+ { name: "generic-connection-string", regex: /(?:Server|Data Source|Host)=[^;]+;.*(?:Password|Pwd)=[^;]+/gi, confidence: "medium", source: "warden" },
285
+ ],
286
+
287
+ // -------------------------------- Asignaciones genéricas de env (ruidoso)
288
+ env: [
289
+ {
290
+ name: "env-assignment",
291
+ regex: /\b(?:[A-Z0-9_]{0,30}(?:SECRET|TOKEN|PASSWORD|PASSWD|APIKEY|API_KEY|PRIVATE_KEY|ACCESS_KEY|ENCRYPTION_KEY|SIGNING_KEY)[A-Z0-9_]{0,30})\s*[=:]\s*['"]?([^\s'"#]{8,})['"]?/g,
292
+ confidence: "medium",
293
+ source: "secret-redactor",
294
+ },
295
+ ],
296
+
297
+ // ------------------------------------------------------------ Kubernetes
298
+ kubernetes: [
299
+ { name: "k8s-secret-data-value", regex: /(?<=data:\s*\n(?:\s+\w+:\s*[^\n]*\n)*\s+\w+:\s*)[A-Za-z0-9+/=]{20,}/g, confidence: "medium", source: "warden" },
300
+ { name: "kubeconfig-token", regex: /(?<=token:\s*)[A-Za-z0-9_.-]{20,}/g, confidence: "medium", source: "warden" },
301
+ { name: "kubeconfig-client-key-data", regex: /(?<=client-key-data:\s*)[A-Za-z0-9+/=\n]{50,}/g, confidence: "high", source: "warden" },
302
+ { name: "kubeconfig-client-cert-data", regex: /(?<=client-certificate-data:\s*)[A-Za-z0-9+/=\n]{50,}/g, confidence: "high", source: "warden" },
303
+ { name: "helm-set-secret", regex: /(?<=helm\s+.*--set\s+[a-zA-Z._]*(?:secret|password|token|key|credential|auth)[a-zA-Z._]*=)[^\s,]+/gi, confidence: "high", source: "warden" },
304
+ { name: "k8s-service-account-token", regex: /(?<=serviceAccountToken:\s*['"]?)[A-Za-z0-9_.-]{50,}/g, confidence: "high", source: "warden" },
305
+ ],
306
+
307
+ // -------------------------------------------------------------------- PII
308
+ // Desactivado por defecto: redactar emails/teléfonos del contexto completo
309
+ // es muy agresivo. Actívalo explícitamente si lo necesitas.
310
+ pii: [
311
+ { name: "pii-email", regex: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z]{2,}\b/gi, confidence: "medium", source: "warden" },
312
+ { name: "pii-us-phone", regex: /(?<!\d)(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}(?!\d)/g, confidence: "low", source: "warden" },
313
+ { name: "pii-us-ssn", regex: /(?<!\d)\d{3}-\d{2}-\d{4}(?!\d)/g, confidence: "medium", source: "warden" },
314
+ {
315
+ name: "pii-credit-card",
316
+ regex: /(?<!\d)(?:\d{4}[-\s]?){3}\d{3,4}(?!\d)/g,
317
+ confidence: "high",
318
+ source: "warden",
319
+ validate: luhnCheck,
320
+ },
321
+ ],
322
+ network: [
323
+ {
324
+ name: "pii-ipv4",
325
+ regex: /(?<!\d)(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)(?!\d)/g,
326
+ confidence: "low",
327
+ source: "warden",
328
+ validate: isPublicIp,
329
+ },
330
+ ],
331
+ }
332
+
333
+ /** Bundles ACTIVOS por defecto (el resto hay que activarlos explícitamente). */
334
+ export const DEFAULT_BUNDLES: readonly string[] = [
335
+ "aws", "github", "gitlab", "slack", "jwt", "pem", "bearer", "env",
336
+ "openai", "anthropic", "google", "stripe", "npm", "database",
337
+ "azure", "terraform", "vault", "heroku", "vercel", "supabase", "digitalocean",
338
+ "cloudflare", "observability", "pypi", "rubygems", "twilio", "sendgrid",
339
+ "postman", "mailgun", "mailchimp", "linear", "shopify", "square", "docker",
340
+ "kubernetes", "cohere", "huggingface", "discord",
341
+ ]
342
+
343
+ /** Bundles opt-in (ruidosos o de PII): no se activan por defecto. */
344
+ export const OPT_IN_BUNDLES: readonly string[] = ["pii", "network", "datadog"]
345
+
346
+ /** Nombres de bundle disponibles. */
347
+ export function availableBundles(): string[] {
348
+ return Object.keys(BUNDLES)
349
+ }
350
+
351
+ /**
352
+ * Compila la lista de patrones activos: bundles por nombre + patrones propios.
353
+ * Filtra por confianza mínima. Los patrones inválidos se ignoran con un aviso.
354
+ */
355
+ export function compilePatterns(
356
+ bundleNames: string[],
357
+ customSources: string[],
358
+ minConfidence: PatternConfidence = "medium",
359
+ ): PatternDefinition[] {
360
+ const rank: Record<PatternConfidence, number> = { low: 0, medium: 1, high: 2 }
361
+ const threshold = rank[minConfidence]
362
+
363
+ const patterns: PatternDefinition[] = []
364
+
365
+ for (const name of bundleNames) {
366
+ const bundle = BUNDLES[name]
367
+ if (!bundle) {
368
+ console.warn(`[apex.redact] Bundle desconocido: "${name}" (disponibles: ${availableBundles().join(", ")})`)
369
+ continue
370
+ }
371
+ for (const pattern of bundle) {
372
+ if (rank[pattern.confidence] >= threshold) patterns.push(pattern)
373
+ }
374
+ }
375
+
376
+ customSources.forEach((source, index) => {
377
+ try {
378
+ patterns.push({ name: `custom-${index}`, regex: new RegExp(source, "g"), confidence: "high", source: "apex" })
379
+ } catch (error) {
380
+ console.warn(`[apex.redact] Patrón inválido #${index} (${source}): ${String(error)}`)
381
+ }
382
+ })
383
+
384
+ return patterns
385
+ }
package/core/redact.ts ADDED
@@ -0,0 +1,256 @@
1
+ /**
2
+ * Apex Redact — motor de redacción/restauración.
3
+ *
4
+ * Marcador (autocontenido y legible):
5
+ * `${prefix}${patternName}:${base64url(iv||tag||ciphertext)}${suffix}`
6
+ * p. ej. `[SECRET:github-pat:AbC123...]`
7
+ *
8
+ * - `patternName` es el nombre del patrón que detectó el secreto → el usuario
9
+ * ve una referencia legible aunque no pueda ver el secreto.
10
+ * - El payload se descifra con la clave: no hay mapping en memoria.
11
+ *
12
+ * Redacción: hook `context` (entrada al modelo).
13
+ * Restauración: hook `execute.before` (salida hacia la herramienta).
14
+ */
15
+
16
+ import { decryptSecret, encryptSecret, escapeRegExp } from "./crypto.js"
17
+ import type { PatternDefinition } from "./patterns.js"
18
+
19
+ export type RedactMode = "strict" | "warn"
20
+
21
+ export interface RedactEngineOptions {
22
+ readonly patterns: readonly PatternDefinition[]
23
+ readonly allowlist: readonly RegExp[]
24
+ readonly prefix: string
25
+ readonly suffix: string
26
+ readonly key: Buffer
27
+ readonly mode: RedactMode
28
+ /** Callback opcional de observabilidad (secreto nunca incluido). */
29
+ readonly onFinding?: (finding: { pattern: string; stage?: string }) => void
30
+ }
31
+
32
+ export interface RedactEngine {
33
+ readonly redactText: (text: string, stage?: string) => string
34
+ readonly restoreText: (text: string) => string
35
+ readonly redactValue: (value: unknown, stage?: string) => unknown
36
+ readonly restoreValue: (value: unknown) => unknown
37
+ /** Regex que reconoce los marcadores generados (con prefix/suffix actuales). */
38
+ readonly markerRegex: RegExp
39
+ }
40
+
41
+ const MAX_DEPTH = 32
42
+
43
+ /** Caracteres admitidos en el nombre de patrón dentro del marcador. */
44
+ function sanitizeLabel(name: string): string {
45
+ const safe = name.replace(/[^A-Za-z0-9_.-]/g, "-")
46
+ return safe.length > 0 ? safe : "secret"
47
+ }
48
+
49
+ /**
50
+ * Crea el motor. Compila la regex de marcador a partir de prefix/suffix.
51
+ */
52
+ export function createRedactEngine(options: RedactEngineOptions): RedactEngine {
53
+ const { patterns, allowlist, prefix, suffix, key, mode, onFinding } = options
54
+
55
+ // `prefix`/`suffix` pueden contener metacaracteres regex → se escapan.
56
+ // Grupo 1: nombre del patrón · Grupo 2: payload cifrado.
57
+ const markerRegex = new RegExp(
58
+ `${escapeRegExp(prefix)}([A-Za-z0-9_.-]+):([A-Za-z0-9_-]+)${escapeRegExp(suffix)}`,
59
+ "g",
60
+ )
61
+
62
+ const isAllowed = (match: string): boolean => allowlist.some((re) => re.test(match))
63
+
64
+ /**
65
+ * Redacta un texto en UNA sola pasada sobre el original:
66
+ * 1. se recogen todas las coincidencias de todos los patrones,
67
+ * 2. se descartan solapes (gana la más larga / más temprana),
68
+ * 3. se construye la salida insertando un marcador por coincidencia.
69
+ *
70
+ * Pasada única ⇒ un patrón nunca puede volver a coincidir con un marcador
71
+ * ya generado (evita el doble cifrado en cascada).
72
+ */
73
+ const redactText = (text: string, stage?: string): string => {
74
+ if (!text) return text
75
+
76
+ interface Hit {
77
+ start: number
78
+ end: number
79
+ value: string
80
+ pattern: string
81
+ }
82
+
83
+ const hits: Hit[] = []
84
+
85
+ // Los marcadores ya presentes son regiones protegidas: ninguna coincidencia
86
+ // puede solaparlos. Esto hace la redacción IDEMPOTENTE: el hook `context`
87
+ // re-redacta el histórico completo en cada petición sin doble cifrado.
88
+ const protectedSpans: Array<{ start: number; end: number }> = []
89
+ markerRegex.lastIndex = 0
90
+ for (;;) {
91
+ const marker = markerRegex.exec(text)
92
+ if (marker === null) break
93
+ const markerText = marker[0]
94
+ if (markerText.length === 0) {
95
+ markerRegex.lastIndex++
96
+ continue
97
+ }
98
+ protectedSpans.push({ start: marker.index, end: marker.index + markerText.length })
99
+ }
100
+ const overlapsProtected = (start: number, end: number): boolean =>
101
+ protectedSpans.some((span) => start < span.end && end > span.start)
102
+
103
+ for (const pattern of patterns) {
104
+ // Copia con flag global para no mutar el estado compartido entre llamadas.
105
+ const flags = pattern.regex.flags.includes("g")
106
+ ? pattern.regex.flags
107
+ : `${pattern.regex.flags}g`
108
+ const regex = new RegExp(pattern.regex.source, flags)
109
+ for (;;) {
110
+ const match = regex.exec(text)
111
+ if (match === null) break
112
+ const value = match[0]
113
+ if (value.length === 0) {
114
+ regex.lastIndex++
115
+ continue
116
+ }
117
+ if (overlapsProtected(match.index, match.index + value.length)) continue
118
+ // Validación extra por patrón (p. ej. Luhn para tarjetas, IPs privadas)
119
+ if (pattern.validate && !pattern.validate(value)) continue
120
+ hits.push({
121
+ start: match.index,
122
+ end: match.index + value.length,
123
+ value,
124
+ pattern: pattern.name,
125
+ })
126
+ }
127
+ }
128
+
129
+ if (hits.length === 0) return text
130
+
131
+ // Orden por posición; a igual inicio, la coincidencia más larga primero.
132
+ hits.sort((a, b) => a.start - b.start || b.end - b.start - (a.end - a.start))
133
+
134
+ // Resolución de solapes: se conserva la primera (más larga) y se salta el resto.
135
+ const chosen: Hit[] = []
136
+ let lastEnd = -1
137
+ for (const hit of hits) {
138
+ if (hit.start >= lastEnd) {
139
+ chosen.push(hit)
140
+ lastEnd = hit.end
141
+ }
142
+ }
143
+
144
+ let out = ""
145
+ let cursor = 0
146
+ for (const hit of chosen) {
147
+ out += text.slice(cursor, hit.start)
148
+ if (isAllowed(hit.value)) {
149
+ out += hit.value
150
+ } else {
151
+ onFinding?.({ pattern: hit.pattern, stage })
152
+ out +=
153
+ mode === "warn"
154
+ ? hit.value
155
+ : `${prefix}${sanitizeLabel(hit.pattern)}:${encryptSecret(hit.value, key)}${suffix}`
156
+ }
157
+ cursor = hit.end
158
+ }
159
+ out += text.slice(cursor)
160
+
161
+ return out
162
+ }
163
+
164
+ /**
165
+ * Restaura un texto: descifra cada marcador. Si un marcador no se puede
166
+ * descifrar (forma coincidente pero no generado por nosotros) se deja intacto.
167
+ */
168
+ const restoreText = (text: string): string => {
169
+ if (!text) return text
170
+ markerRegex.lastIndex = 0
171
+ return text.replace(markerRegex, (marker, _label: string, payload: string) => {
172
+ const secret = decryptSecret(payload, key)
173
+ return secret === null ? marker : secret
174
+ })
175
+ }
176
+
177
+ /**
178
+ * ¿Es un objeto que NO debemos transformar? (estructuras especiales)
179
+ * Todo lo demás —incluidas instancias de clase— SÍ se recorre: un
180
+ * `Schema.Class` o cualquier objeto con datos debe redactarse igualmente.
181
+ */
182
+ const shouldSkipObject = (value: object): boolean => {
183
+ const candidate = value as Record<string | symbol, unknown>
184
+ // Streams
185
+ if (typeof candidate.getReader === "function") return true
186
+ if (typeof candidate.pipeThrough === "function") return true
187
+ if (typeof candidate.pipeTo === "function") return true
188
+ // Request / Response / Blob
189
+ if (typeof candidate.arrayBuffer === "function") return true
190
+ // Thenables / promesas
191
+ if (typeof candidate.then === "function") return true
192
+ // Iterables: Map, Set, Buffer/TypedArray, Headers…
193
+ if (Symbol.iterator in value || Symbol.asyncIterator in value) return true
194
+
195
+ const ctor = candidate.constructor
196
+ if (typeof ctor === "function") {
197
+ const skip: ReadonlyArray<unknown> = [
198
+ Date, RegExp, Error, Promise, URL, URLSearchParams, AbortController, AbortSignal,
199
+ ArrayBuffer, SharedArrayBuffer, DataView, WeakMap, WeakSet,
200
+ ]
201
+ if (skip.includes(ctor)) return true
202
+ const name = ctor.name
203
+ if (name === "Date" || name === "RegExp" || name === "Error" || name === "Buffer") return true
204
+ }
205
+ return false
206
+ }
207
+
208
+ /** Recorre recursivamente strings dentro de objetos/arrays. */
209
+ const transformValue = (
210
+ value: unknown,
211
+ transform: (text: string) => string,
212
+ depth: number,
213
+ ): unknown => {
214
+ if (depth > MAX_DEPTH) return value
215
+
216
+ if (typeof value === "string") return transform(value)
217
+
218
+ if (Array.isArray(value)) {
219
+ let changed = false
220
+ const next = value.map((item) => {
221
+ const out = transformValue(item, transform, depth + 1)
222
+ if (out !== item) changed = true
223
+ return out
224
+ })
225
+ return changed ? next : value
226
+ }
227
+
228
+ if (value !== null && typeof value === "object") {
229
+ // Estructuras especiales (streams, Request/Response, Date, Map…) intactas.
230
+ if (shouldSkipObject(value)) return value
231
+
232
+ let changed = false
233
+ const next: Record<string, unknown> = {}
234
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
235
+ const out = transformValue(v, transform, depth + 1)
236
+ if (out !== v) changed = true
237
+ next[k] = out
238
+ }
239
+ if (!changed) return value
240
+
241
+ // Preservar el prototipo: una instancia de clase sigue siéndolo
242
+ // (no rompemos métodos/getters) pero con los strings ya transformados.
243
+ const proto = Object.getPrototypeOf(value)
244
+ return Object.assign(Object.create(proto ?? Object.prototype), next)
245
+ }
246
+
247
+ return value
248
+ }
249
+
250
+ const redactValue = (value: unknown, stage?: string): unknown =>
251
+ transformValue(value, (text) => redactText(text, stage), 0)
252
+
253
+ const restoreValue = (value: unknown): unknown => transformValue(value, restoreText, 0)
254
+
255
+ return { redactText, restoreText, redactValue, restoreValue, markerRegex }
256
+ }