@griddo/ax 12.18.1 → 12.18.3
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/config/env.js +25 -34
- package/config/lib/bundleSecrets.js +159 -0
- package/config/lib/publicEnv.js +44 -0
- package/package.json +4 -4
- package/scripts/build.js +5 -0
- package/scripts/check-bundle-secrets.js +109 -0
- package/src/__tests__/helpers/bundleSecrets.test.ts +261 -0
- package/src/__tests__/helpers/bundleSecretsLiterals.test.ts +35 -0
- package/src/__tests__/helpers/checkBundleSecrets.test.ts +253 -0
- package/src/__tests__/helpers/clientEnvironment.test.ts +135 -0
- package/src/__tests__/helpers/publicEnv.test.ts +96 -0
- package/src/__tests__/helpers/publicEnvUsage.test.ts +105 -0
- package/src/components/Fields/Wysiwyg/config.tsx +1 -1
- package/src/modules/Login/index.tsx +1 -1
package/config/env.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
const fs = require("fs");
|
|
2
2
|
const path = require("path");
|
|
3
3
|
const paths = require("./paths");
|
|
4
|
+
const { PUBLIC_ENV_KEYS, pickPublicEnv } = require("./lib/publicEnv");
|
|
4
5
|
|
|
5
6
|
// Make sure that including paths.js after env.js will read .env variables.
|
|
6
7
|
delete require.cache[require.resolve("./paths")];
|
|
@@ -52,41 +53,31 @@ process.env.NODE_PATH = (process.env.NODE_PATH || "")
|
|
|
52
53
|
.map((folder) => path.resolve(appDirectory, folder))
|
|
53
54
|
.join(path.delimiter);
|
|
54
55
|
|
|
55
|
-
// Grab NODE_ENV and
|
|
56
|
-
// injected into the application via DefinePlugin in webpack configuration.
|
|
57
|
-
|
|
58
|
-
const GRIDDO = /^GRIDDO_/i;
|
|
59
|
-
|
|
56
|
+
// Grab NODE_ENV and the public environment variables (closed list `PUBLIC_ENV_KEYS`) and prepare them to be
|
|
57
|
+
// injected into the application via DefinePlugin in webpack configuration. The bundle is public, so nothing
|
|
58
|
+
// outside that list may reach it (sc-125775).
|
|
60
59
|
function getClientEnvironment(publicUrl) {
|
|
61
|
-
const raw = Object.
|
|
62
|
-
|
|
63
|
-
.
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
WDS_SOCKET_HOST: process.env.WDS_SOCKET_HOST,
|
|
83
|
-
WDS_SOCKET_PATH: process.env.WDS_SOCKET_PATH,
|
|
84
|
-
WDS_SOCKET_PORT: process.env.WDS_SOCKET_PORT,
|
|
85
|
-
// Whether or not react-refresh is enabled.
|
|
86
|
-
// It is defined here so it is available in the webpackHotDevClient.
|
|
87
|
-
FAST_REFRESH: process.env.FAST_REFRESH !== "false",
|
|
88
|
-
},
|
|
89
|
-
);
|
|
60
|
+
const raw = Object.assign(pickPublicEnv(process.env, PUBLIC_ENV_KEYS), {
|
|
61
|
+
// Useful for determining whether we’re running in production mode.
|
|
62
|
+
// Most importantly, it switches React into the correct mode.
|
|
63
|
+
NODE_ENV: process.env.NODE_ENV || "development",
|
|
64
|
+
// Useful for resolving the correct path to static assets in `public`.
|
|
65
|
+
// For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />.
|
|
66
|
+
// This should only be used as an escape hatch. Normally you would put
|
|
67
|
+
// images into the `src` and `import` them in code to get their paths.
|
|
68
|
+
PUBLIC_URL: publicUrl,
|
|
69
|
+
// We support configuring the sockjs pathname during development.
|
|
70
|
+
// These settings let a developer run multiple simultaneous projects.
|
|
71
|
+
// They are used as the connection `hostname`, `pathname` and `port`
|
|
72
|
+
// in webpackHotDevClient. They are used as the `sockHost`, `sockPath`
|
|
73
|
+
// and `sockPort` options in webpack-dev-server.
|
|
74
|
+
WDS_SOCKET_HOST: process.env.WDS_SOCKET_HOST,
|
|
75
|
+
WDS_SOCKET_PATH: process.env.WDS_SOCKET_PATH,
|
|
76
|
+
WDS_SOCKET_PORT: process.env.WDS_SOCKET_PORT,
|
|
77
|
+
// Whether or not react-refresh is enabled.
|
|
78
|
+
// It is defined here so it is available in the webpackHotDevClient.
|
|
79
|
+
FAST_REFRESH: process.env.FAST_REFRESH !== "false",
|
|
80
|
+
});
|
|
90
81
|
// Stringify all values so we can feed into webpack DefinePlugin
|
|
91
82
|
const stringified = {
|
|
92
83
|
"process.env": Object.keys(raw).reduce((env, key) => {
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Detección de secretos en el bundle de AX (lógica pura, sin E/S ni dependencias).
|
|
3
|
+
*
|
|
4
|
+
* Es la segunda barrera de sc-125775: la primera es la lista cerrada `PUBLIC_ENV_KEYS` (`publicEnv.js`) y esta
|
|
5
|
+
* comprueba, ya compilado, que nada sensible haya llegado al directorio de salida. Los hallazgos llevan el
|
|
6
|
+
* nombre de la variable o clave y el fichero, **nunca el valor**.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Claves literales con prefijo de Griddo o `REACT_APP_` que acaban en el bundle y no son variables de entorno:
|
|
11
|
+
* el id del iframe y los de los contextos de `@griddo/core` (`src/`), y las que traen las dependencias
|
|
12
|
+
* (`styled-components` lee `REACT_APP_SC_*`). Salieron de un build real con el guard activo; si una dependencia
|
|
13
|
+
* nueva añade otra, el build falla y se añade aquí tras comprobar que no es un secreto.
|
|
14
|
+
*/
|
|
15
|
+
const KNOWN_LITERAL_KEYS = Object.freeze([
|
|
16
|
+
"GRIDDO_ID",
|
|
17
|
+
"GRIDDO_ID_ENABLED",
|
|
18
|
+
"GRIDDO_I18N_CONTEXT__",
|
|
19
|
+
"GRIDDO_MODULE_PREVIEW_CONTEXT__",
|
|
20
|
+
"GRIDDO_NAVIGATION_CONTEXT__",
|
|
21
|
+
"GRIDDO_PAGE_CONTEXT__",
|
|
22
|
+
"GRIDDO_SESSION_CONTEXT__",
|
|
23
|
+
"GRIDDO_SITE_CONTEXT__",
|
|
24
|
+
"REACT_APP_SC_ATTR",
|
|
25
|
+
"REACT_APP_SC_DISABLE_SPEEDY",
|
|
26
|
+
"griddo_config",
|
|
27
|
+
]);
|
|
28
|
+
|
|
29
|
+
/** Segmentos de un nombre de variable (partido por `_`, sin distinguir mayúsculas) que delatan un secreto. */
|
|
30
|
+
const SECRET_SEGMENTS = Object.freeze(["token", "secret", "password", "passw", "key", "webhook", "credential"]);
|
|
31
|
+
|
|
32
|
+
/** Nombres sin guion bajo que también son secretos (los que pasan los workflows de CI), en minúsculas. */
|
|
33
|
+
const SECRET_NAMES = Object.freeze(["botpassword", "developerkey"]);
|
|
34
|
+
|
|
35
|
+
/** Longitud mínima del valor para buscarlo en el bundle: por debajo habría demasiadas coincidencias casuales. */
|
|
36
|
+
const MIN_SECRET_VALUE_LENGTH = 16;
|
|
37
|
+
|
|
38
|
+
const KEY_PATTERN = /(?:GRIDDO|REACT_APP)_[A-Za-z0-9_]+/gi;
|
|
39
|
+
const NPM_TOKEN_PATTERN = /npm_[A-Za-z0-9]{36}/;
|
|
40
|
+
/**
|
|
41
|
+
* Webpack deriva identificadores de la ruta del módulo (`griddo_node_modules_…__WEBPACK_IMPORTED_MODULE_0__`
|
|
42
|
+
* cuando el checkout se llama `griddo`): no son claves de entorno y su nombre depende de dónde se compile.
|
|
43
|
+
*/
|
|
44
|
+
const WEBPACK_GENERATED = "__WEBPACK_";
|
|
45
|
+
const PREFIXED_NAME = /^(?:GRIDDO|REACT_APP)_/i;
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Palabras de un nombre de variable en minúsculas: se parte por `_` y por los cambios de minúscula a mayúscula
|
|
49
|
+
* (`QodanaToken` → `qodana`, `token`; `MONKEY` sigue siendo una sola palabra).
|
|
50
|
+
*
|
|
51
|
+
* @param {string} name
|
|
52
|
+
* @returns {string[]}
|
|
53
|
+
*/
|
|
54
|
+
function wordsOf(name) {
|
|
55
|
+
return name
|
|
56
|
+
.replace(/([a-z0-9])([A-Z])/g, "$1_$2")
|
|
57
|
+
.toLowerCase()
|
|
58
|
+
.split("_");
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Formas en las que un valor puede aparecer en un fichero: literal, escapado como JSON y, para ambas, con los
|
|
63
|
+
* caracteres no ASCII escritos como `\uXXXX` (Terser lo hace con `ascii_only`), en minúsculas y mayúsculas.
|
|
64
|
+
*
|
|
65
|
+
* @param {string} value
|
|
66
|
+
* @returns {Set<string>}
|
|
67
|
+
*/
|
|
68
|
+
function formsOf(value) {
|
|
69
|
+
const forms = new Set([value, JSON.stringify(value).slice(1, -1)]);
|
|
70
|
+
for (const form of [...forms]) {
|
|
71
|
+
const withUnicodeEscapes = (hex) =>
|
|
72
|
+
form.replace(/[\u0080-\uffff]/g, (c) => `\\u${hex(c.charCodeAt(0).toString(16).padStart(4, "0"))}`);
|
|
73
|
+
forms.add(withUnicodeEscapes((h) => h));
|
|
74
|
+
forms.add(withUnicodeEscapes((h) => h.toUpperCase()));
|
|
75
|
+
}
|
|
76
|
+
return forms;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Indica si una variable de entorno debe tratarse como secreta: por su nombre (segmento sensible o nombre
|
|
81
|
+
* conocido) o por llevar el prefijo `GRIDDO_`/`REACT_APP_` sin estar en la lista pública.
|
|
82
|
+
*
|
|
83
|
+
* @param {string} name Nombre de la variable.
|
|
84
|
+
* @returns {boolean}
|
|
85
|
+
*/
|
|
86
|
+
function isSecretName(name) {
|
|
87
|
+
const lower = name.toLowerCase();
|
|
88
|
+
return (
|
|
89
|
+
PREFIXED_NAME.test(name) ||
|
|
90
|
+
SECRET_NAMES.includes(lower) ||
|
|
91
|
+
wordsOf(name).some((word) => SECRET_SEGMENTS.includes(word))
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Busca secretos en el contenido de los ficheros del bundle.
|
|
97
|
+
*
|
|
98
|
+
* Reglas:
|
|
99
|
+
* - **key**: una clave `(GRIDDO|REACT_APP)_…` (sin distinguir mayúsculas al detectarla, comparación exacta al
|
|
100
|
+
* permitirla) que no esté en `allowedKeys` ni en `knownLiterals`. Se ignoran los identificadores generados por
|
|
101
|
+
* webpack (contienen `__WEBPACK_`).
|
|
102
|
+
* - **npm-token**: un token `npm_` + 36 alfanuméricos.
|
|
103
|
+
* - **env-value**: el valor (≥16 caracteres, buscado literal, escapado como JSON y con los no ASCII como
|
|
104
|
+
* `\uXXXX`) de una variable de `env` fuera de `allowedKeys` con nombre de secreto (véase {@link isSecretName}),
|
|
105
|
+
* salvo que su valor sea el de una variable de `allowedKeys` (ya es público).
|
|
106
|
+
*
|
|
107
|
+
* @param {object} input
|
|
108
|
+
* @param {{ name: string, content: string }[]} input.files Ficheros a revisar (`name` es lo que se informa).
|
|
109
|
+
* @param {Record<string, string | undefined>} input.env Entorno del builder (`process.env` ya con los `.env`).
|
|
110
|
+
* @param {readonly string[]} input.allowedKeys Lista pública (`PUBLIC_ENV_KEYS`).
|
|
111
|
+
* @param {readonly string[]} input.knownLiterals Claves literales permitidas que no son variables.
|
|
112
|
+
* @returns {{ kind: "key" | "npm-token" | "env-value", name: string, file: string }[]} Hallazgos sin duplicados.
|
|
113
|
+
*/
|
|
114
|
+
function findSecretLeaks({ files, env, allowedKeys, knownLiterals }) {
|
|
115
|
+
const allowed = new Set([...allowedKeys, ...knownLiterals]);
|
|
116
|
+
const publicKeys = new Set(allowedKeys);
|
|
117
|
+
|
|
118
|
+
// Un valor que ya es público (el de una variable de la lista) no es una fuga aunque otra variable lo repita.
|
|
119
|
+
const publicValues = new Set(allowedKeys.map((key) => env[key]).filter((val) => typeof val === "string"));
|
|
120
|
+
|
|
121
|
+
const candidates = Object.entries(env)
|
|
122
|
+
.filter(
|
|
123
|
+
([name, val]) =>
|
|
124
|
+
typeof val === "string" &&
|
|
125
|
+
val.length >= MIN_SECRET_VALUE_LENGTH &&
|
|
126
|
+
!publicKeys.has(name) &&
|
|
127
|
+
!publicValues.has(val) &&
|
|
128
|
+
!knownLiterals.includes(name) &&
|
|
129
|
+
isSecretName(name),
|
|
130
|
+
)
|
|
131
|
+
.map(([name, val]) => ({ name, forms: formsOf(val) }));
|
|
132
|
+
|
|
133
|
+
const leaks = [];
|
|
134
|
+
for (const { name: file, content } of files) {
|
|
135
|
+
const seen = new Set();
|
|
136
|
+
const report = (kind, name) => {
|
|
137
|
+
const id = `${kind}\0${name}`;
|
|
138
|
+
if (seen.has(id)) return;
|
|
139
|
+
seen.add(id);
|
|
140
|
+
leaks.push({ kind, name, file });
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
for (const [key] of content.matchAll(KEY_PATTERN)) {
|
|
144
|
+
if (!allowed.has(key) && !key.includes(WEBPACK_GENERATED)) report("key", key);
|
|
145
|
+
}
|
|
146
|
+
if (NPM_TOKEN_PATTERN.test(content)) report("npm-token", "npm_token");
|
|
147
|
+
for (const { name, forms } of candidates) {
|
|
148
|
+
for (const form of forms) {
|
|
149
|
+
if (content.includes(form)) {
|
|
150
|
+
report("env-value", name);
|
|
151
|
+
break;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return leaks;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
module.exports = { findSecretLeaks, KNOWN_LITERAL_KEYS };
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lista cerrada de variables de entorno que `config/env.js` incrusta en el bundle de AX.
|
|
3
|
+
*
|
|
4
|
+
* El bundle es público: todo lo que entra en él lo puede leer cualquiera que cargue la página. Por eso la
|
|
5
|
+
* selección es por nombre exacto y no por prefijo (sc-125775). Para exponer una variable nueva al navegador hay
|
|
6
|
+
* que añadirla aquí; el test de consistencia de `src/__tests__/helpers/publicEnvUsage.test.ts` falla si el código
|
|
7
|
+
* de `src/` lee una variable que no esté en la lista.
|
|
8
|
+
*
|
|
9
|
+
* @type {readonly string[]}
|
|
10
|
+
*/
|
|
11
|
+
const PUBLIC_ENV_KEYS = Object.freeze([
|
|
12
|
+
"GRIDDO_API_URL",
|
|
13
|
+
"GRIDDO_PUBLIC_API_URL",
|
|
14
|
+
"GRIDDO_REACT_APP_INSTANCE",
|
|
15
|
+
"GRIDDO_FROALA_KEY",
|
|
16
|
+
"GRIDDO_SITE_TITLE",
|
|
17
|
+
"REACT_APP_API_ENDPOINT",
|
|
18
|
+
"REACT_APP_PUBLIC_API_ENDPOINT",
|
|
19
|
+
"REACT_APP_INSTANCE",
|
|
20
|
+
]);
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Devuelve solo las claves de `keys` que son propiedades propias de `env` y están definidas.
|
|
24
|
+
*
|
|
25
|
+
* - Comparación exacta, sensible a mayúsculas y minúsculas.
|
|
26
|
+
* - Un valor vacío (`""`) cuenta como definido; `undefined` no.
|
|
27
|
+
* - Las propiedades heredadas del prototipo no cuentan.
|
|
28
|
+
* - No muta `env`.
|
|
29
|
+
*
|
|
30
|
+
* @param {Record<string, string | undefined>} env Entorno de origen (normalmente `process.env`).
|
|
31
|
+
* @param {readonly string[]} keys Claves permitidas.
|
|
32
|
+
* @returns {Record<string, string>} Objeto nuevo con las claves permitidas y definidas.
|
|
33
|
+
*/
|
|
34
|
+
function pickPublicEnv(env, keys) {
|
|
35
|
+
const picked = {};
|
|
36
|
+
for (const key of keys) {
|
|
37
|
+
if (Object.hasOwn(env, key) && env[key] !== undefined) {
|
|
38
|
+
picked[key] = env[key];
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return picked;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
module.exports = { PUBLIC_ENV_KEYS, pickPublicEnv };
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@griddo/ax",
|
|
3
3
|
"description": "Griddo Author Experience",
|
|
4
|
-
"version": "12.18.
|
|
4
|
+
"version": "12.18.3",
|
|
5
5
|
"homepage": "https://griddo.io",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|
|
@@ -128,7 +128,7 @@
|
|
|
128
128
|
},
|
|
129
129
|
"devDependencies": {
|
|
130
130
|
"@biomejs/biome": "2.5.15",
|
|
131
|
-
"@griddo/core": "12.18.
|
|
131
|
+
"@griddo/core": "12.18.3",
|
|
132
132
|
"@stryker-mutator/core": "^10.0.0",
|
|
133
133
|
"@stryker-mutator/vitest-runner": "^10.0.0",
|
|
134
134
|
"@types/redux-mock-store": "1.5.0",
|
|
@@ -141,7 +141,7 @@
|
|
|
141
141
|
"vitest-styled-components": "1.0.0"
|
|
142
142
|
},
|
|
143
143
|
"peerDependencies": {
|
|
144
|
-
"@griddo/core": "12.18.
|
|
144
|
+
"@griddo/core": "12.18.3"
|
|
145
145
|
},
|
|
146
146
|
"babel": {
|
|
147
147
|
"presets": [
|
|
@@ -174,5 +174,5 @@
|
|
|
174
174
|
"publishConfig": {
|
|
175
175
|
"access": "public"
|
|
176
176
|
},
|
|
177
|
-
"gitHead": "
|
|
177
|
+
"gitHead": "2a2a235e969c21c50cb7532a85aa5106129b4fbf"
|
|
178
178
|
}
|
package/scripts/build.js
CHANGED
|
@@ -26,6 +26,7 @@ const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild;
|
|
|
26
26
|
|
|
27
27
|
const configFactory = require("../config/webpack.config");
|
|
28
28
|
const paths = require("../config/paths");
|
|
29
|
+
const { guardBuildOutput } = require("./check-bundle-secrets");
|
|
29
30
|
|
|
30
31
|
const useYarn = fs.existsSync(paths.yarnLockFile);
|
|
31
32
|
|
|
@@ -66,6 +67,8 @@ checkBrowsers(paths.appPath, isInteractive)
|
|
|
66
67
|
})
|
|
67
68
|
.then(
|
|
68
69
|
({ stats, previousFileSizes, warnings }) => {
|
|
70
|
+
// Webpack ya ha emitido: ningún secreto puede quedar en la salida (sc-125775). Sale con 1 si lo hay.
|
|
71
|
+
guardBuildOutput();
|
|
69
72
|
console.log(chalk.green("Compiled successfully.\n"));
|
|
70
73
|
|
|
71
74
|
console.log("File sizes after gzip:\n");
|
|
@@ -87,6 +90,8 @@ checkBrowsers(paths.appPath, isInteractive)
|
|
|
87
90
|
(err) => {
|
|
88
91
|
const tscCompileOnError = process.env.TSC_COMPILE_ON_ERROR === "true";
|
|
89
92
|
if (tscCompileOnError) {
|
|
93
|
+
// Tolerar errores de tipos no exime de la comprobación de secretos: la salida sí se ha emitido.
|
|
94
|
+
guardBuildOutput();
|
|
90
95
|
console.log(
|
|
91
96
|
chalk.yellow(
|
|
92
97
|
"Compiled with the following type errors (you may want to check these before deploying your app):\n",
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Guard post-build de AX (sc-125775): escanea la salida de la compilación y falla si contiene secretos.
|
|
3
|
+
*
|
|
4
|
+
* Revisa con `findSecretLeaks` todos los ficheros de `paths.appBuild` (`BUILD_PATH` o `exports/ax`) salvo
|
|
5
|
+
* los binarios (imágenes, fuentes, vídeo…). Si encuentra alguno imprime la variable y el fichero (nunca el valor), vacía el
|
|
6
|
+
* directorio de salida (que sigue existiendo) y sale con 1. Falla cerrado: un directorio inexistente o un
|
|
7
|
+
* fichero ilegible también es un error. Un build sin `.map` no lo es.
|
|
8
|
+
*
|
|
9
|
+
* `scripts/build.js` lo invoca al terminar webpack (`guardBuildOutput`); también se puede lanzar a mano con
|
|
10
|
+
* `node scripts/check-bundle-secrets.js`.
|
|
11
|
+
*
|
|
12
|
+
* Falso positivo: si una clave o valor legítimo salta, añade la variable a `PUBLIC_ENV_KEYS`
|
|
13
|
+
* (`config/lib/publicEnv.js`) o, si es un literal de `src/` que no es una variable, a `KNOWN_LITERAL_KEYS`
|
|
14
|
+
* (`config/lib/bundleSecrets.js`). Nunca desactives el guard.
|
|
15
|
+
*/
|
|
16
|
+
const fs = require("node:fs");
|
|
17
|
+
const path = require("node:path");
|
|
18
|
+
|
|
19
|
+
const { findSecretLeaks, KNOWN_LITERAL_KEYS } = require("../config/lib/bundleSecrets");
|
|
20
|
+
const { PUBLIC_ENV_KEYS } = require("../config/lib/publicEnv");
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Se escanea todo lo que acaba en la salida (también lo que `copyPublicFolder` copia de `static/`) salvo los
|
|
24
|
+
* binarios, donde un secreto en texto no tiene sentido y el escaneo solo daría ruido.
|
|
25
|
+
*/
|
|
26
|
+
const BINARY_EXTENSIONS = /\.(?:png|jpe?g|gif|webp|avif|bmp|ico|woff2?|ttf|otf|eot|pdf|zip|gz|mp[34]|webm|mov|wasm)$/i;
|
|
27
|
+
const isScannable = (fileName) => !BINARY_EXTENSIONS.test(fileName);
|
|
28
|
+
|
|
29
|
+
/** Lista, recursivamente, los ficheros escaneables de `dir` (rutas relativas a `dir`). */
|
|
30
|
+
function listScannable(dir, base = dir) {
|
|
31
|
+
return fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
|
|
32
|
+
const full = path.join(dir, entry.name);
|
|
33
|
+
if (entry.isDirectory()) return listScannable(full, base);
|
|
34
|
+
return isScannable(entry.name) ? [path.relative(base, full)] : [];
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Vacía `dir` sin borrarlo. */
|
|
39
|
+
function emptyDir(dir) {
|
|
40
|
+
for (const entry of fs.readdirSync(dir)) {
|
|
41
|
+
fs.rmSync(path.join(dir, entry), { recursive: true, force: true });
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Comprueba el directorio de salida y devuelve el código de salida del guard.
|
|
47
|
+
*
|
|
48
|
+
* @param {object} opts
|
|
49
|
+
* @param {string} opts.buildDir Directorio de salida de la compilación.
|
|
50
|
+
* @param {Record<string, string | undefined>} [opts.env] Entorno del builder (por defecto `process.env`).
|
|
51
|
+
* @param {(line: string) => void} [opts.out] Salida informativa (por defecto `console.log`).
|
|
52
|
+
* @param {(line: string) => void} [opts.err] Salida de error (por defecto `console.error`).
|
|
53
|
+
* @returns {number} 0 si el bundle está limpio; 1 si hay secretos o no se pudo comprobar.
|
|
54
|
+
*/
|
|
55
|
+
function runBundleGuard({ buildDir, env = process.env, out = console.log, err = console.error }) {
|
|
56
|
+
let files;
|
|
57
|
+
try {
|
|
58
|
+
files = listScannable(buildDir).map((name) => {
|
|
59
|
+
try {
|
|
60
|
+
return { name, content: fs.readFileSync(path.join(buildDir, name), "utf8") };
|
|
61
|
+
} catch (error) {
|
|
62
|
+
throw new Error(`no se puede leer el fichero ${name} (${error.code ?? "error"})`);
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
} catch (error) {
|
|
66
|
+
const reason = error.message.startsWith("no se puede leer")
|
|
67
|
+
? error.message
|
|
68
|
+
: `no se puede leer el directorio de salida ${buildDir} (${error.code ?? "error"})`;
|
|
69
|
+
err(`Guard de secretos: ${reason}. El bundle no se ha podido comprobar, el build falla.`);
|
|
70
|
+
return 1;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const leaks = findSecretLeaks({ files, env, allowedKeys: PUBLIC_ENV_KEYS, knownLiterals: KNOWN_LITERAL_KEYS });
|
|
74
|
+
if (leaks.length === 0) {
|
|
75
|
+
out(`Guard de secretos: ${files.length} ficheros revisados, sin secretos.`);
|
|
76
|
+
return 0;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
err("Guard de secretos: el bundle contiene secretos y se ha vaciado el directorio de salida:");
|
|
80
|
+
for (const { kind, name, file } of leaks) {
|
|
81
|
+
err(` - [${kind}] ${name} en ${file}`);
|
|
82
|
+
}
|
|
83
|
+
emptyDir(buildDir);
|
|
84
|
+
return 1;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Ejecuta el guard sobre `paths.appBuild` y termina el proceso con su código si falla.
|
|
89
|
+
*
|
|
90
|
+
* @param {object} [opts] Todo opcional; existe para poder probarlo.
|
|
91
|
+
* @param {string} [opts.buildDir] Por defecto `paths.appBuild`.
|
|
92
|
+
* @param {Record<string, string | undefined>} [opts.env]
|
|
93
|
+
* @param {(code: number) => void} [opts.exit] Por defecto `process.exit`.
|
|
94
|
+
* @param {(line: string) => void} [opts.out]
|
|
95
|
+
* @param {(line: string) => void} [opts.err]
|
|
96
|
+
*/
|
|
97
|
+
function guardBuildOutput({ buildDir, env, exit = process.exit, out, err } = {}) {
|
|
98
|
+
const code = runBundleGuard({ buildDir: buildDir ?? require("../config/paths").appBuild, env, out, err });
|
|
99
|
+
if (code !== 0) exit(code);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
module.exports = { runBundleGuard, guardBuildOutput };
|
|
103
|
+
|
|
104
|
+
if (require.main === module) {
|
|
105
|
+
process.env.NODE_ENV = process.env.NODE_ENV || "production";
|
|
106
|
+
// Carga los `.env`: el guard comprueba contra el mismo entorno que vio la compilación.
|
|
107
|
+
require("../config/env");
|
|
108
|
+
guardBuildOutput();
|
|
109
|
+
}
|