Skip to content

TagSpaces is an offline, open source, document manager with tagging support

security replace execSync from main thread (#2348)

Stanimirf3763abcb8df
diff --git a/.erb/configs/webpack.config.base.ts b/.erb/configs/webpack.config.base.ts
index 8f5a3dcdd..169159d67 100644
--- a/.erb/configs/webpack.config.base.ts
+++ b/.erb/configs/webpack.config.base.ts
@@ -9,10 +9,7 @@ import webpackPaths from './webpack.paths';
import { dependencies as externals } from '../../release/app/package.json';
//import NodePolyfillPlugin from 'node-polyfill-webpack-plugin';
import path = require('path');
-import { checkThirdPartyTxt, checkVersionJson } from '../../src/main/util';
-
-checkVersionJson();
-checkThirdPartyTxt();
+import { TsMetaPlugin } from '../../plugins/TsMetaPlugin';
const configuration: webpack.Configuration = {
// packages that is not included in the bundle
@@ -94,6 +91,7 @@ const configuration: webpack.Configuration = {
),
}),
//new NodePolyfillPlugin(),
+ new TsMetaPlugin(),
],
};
diff --git a/.erb/configs/webpack.config.renderer.dev.dll.ts b/.erb/configs/webpack.config.renderer.dev.dll.ts
index 090f0e9fe..614b90f04 100644
--- a/.erb/configs/webpack.config.renderer.dev.dll.ts
+++ b/.erb/configs/webpack.config.renderer.dev.dll.ts
@@ -9,12 +9,10 @@ import baseConfig from './webpack.config.base';
import webpackPaths from './webpack.paths';
import { dependencies } from '../../package.json';
import checkNodeEnv from '../scripts/check-node-env';
-import { generateJWT } from '../../src/main/util';
checkNodeEnv('development');
const dist = webpackPaths.dllPath;
-generateJWT();
const configuration: webpack.Configuration = {
context: webpackPaths.rootPath,
diff --git a/.erb/configs/webpack.config.renderer.dev.ts b/.erb/configs/webpack.config.renderer.dev.ts
index d35c6c088..36ab8a1dc 100644
--- a/.erb/configs/webpack.config.renderer.dev.ts
+++ b/.erb/configs/webpack.config.renderer.dev.ts
@@ -11,7 +11,6 @@ import ReactRefreshWebpackPlugin from '@pmmmwh/react-refresh-webpack-plugin';
import baseConfig from './webpack.config.base';
import webpackPaths from './webpack.paths';
import checkNodeEnv from '../scripts/check-node-env';
-import { generateJWT } from '../../src/main/util';
// When an ESLint server is running, we can't set the NODE_ENV so we'll check if it's
// at the dev webpack config is not accidentally run in a production environment
@@ -25,7 +24,6 @@ const skipDLLs =
module.parent?.filename.includes('webpack.config.renderer.dev.dll') ||
module.parent?.filename.includes('webpack.config.eslint');
-generateJWT();
/**
* Warn if the DLL is not built
*/
diff --git a/.erb/configs/webpack.config.renderer.prod.ts b/.erb/configs/webpack.config.renderer.prod.ts
index 7d8f5027c..549541d71 100644
--- a/.erb/configs/webpack.config.renderer.prod.ts
+++ b/.erb/configs/webpack.config.renderer.prod.ts
@@ -14,11 +14,9 @@ import baseConfig from './webpack.config.base';
import webpackPaths from './webpack.paths';
import checkNodeEnv from '../scripts/check-node-env';
import deleteSourceMaps from '../scripts/delete-source-maps';
-import { generateJWT } from '../../src/main/util';
checkNodeEnv('production');
deleteSourceMaps();
-generateJWT();
const configuration: webpack.Configuration = {
devtool: 'source-map',
diff --git a/plugins/TsMetaPlugin.ts b/plugins/TsMetaPlugin.ts
new file mode 100644
index 000000000..f45672a25
--- /dev/null
+++ b/plugins/TsMetaPlugin.ts
@@ -0,0 +1,133 @@
+import webpack from 'webpack';
+import path from 'path';
+import webpackPaths from '../.erb/configs/webpack.paths';
+import fs from 'fs';
+import fsPromises from 'fs/promises';
+import chalk from 'chalk';
+import { execFile, spawn } from 'child_process';
+
+export class TsMetaPlugin {
+ apply(compiler: webpack.Compiler) {
+ /**
+ * Warn third-party.txt is missing
+ */
+ async function checkThirdPartyTxt(): Promise<void> {
+ const thirdParty = path.resolve(
+ webpackPaths.srcRendererPath,
+ 'third-party.txt',
+ );
+
+ try {
+ // Try to read the file metadata; if it doesn't exist, we'll catch below
+ await fsPromises.access(thirdParty);
+ // file exists — nothing to do
+ } catch {
+ // file is missing
+ console.log(
+ chalk.black.bgYellow.bold(
+ 'The third-party.txt file is missing. Sit back while we build it for you with "npm run third-party"',
+ ),
+ );
+
+ const root = path.resolve(webpackPaths.rootPath);
+ const entryPoint = path.join(
+ root,
+ 'node_modules',
+ 'generate-license-file',
+ 'bin',
+ 'generate-license-file',
+ );
+
+ if (!fs.existsSync(entryPoint)) {
+ throw new Error(
+ `Cannot find generate-license-file script at ${entryPoint}`,
+ );
+ }
+
+ await new Promise<void>((resolve, reject) => {
+ // On Windows, shell=false is fine because we're calling Node directly.
+ const child = spawn(process.execPath, [entryPoint], {
+ cwd: root,
+ stdio: 'inherit',
+ shell: false,
+ });
+
+ child.on('error', reject);
+ child.on('exit', (code, signal) => {
+ if (signal) return reject(new Error(`killed by signal ${signal}`));
+ if (code !== 0) return reject(new Error(`exit code ${code}`));
+ resolve();
+ });
+ });
+ }
+ }
+
+ /**
+ * Warn version.json is missing
+ */
+ async function checkVersionJson() {
+ const cwd = path.resolve(webpackPaths.rootPath);
+ const script = path.join(cwd, 'scripts', 'versionmeta.js');
+
+ // Spawn "npm run version-meta" asynchronously
+ await new Promise<void>((resolve, reject) => {
+ execFile(
+ 'node',
+ [script],
+ { cwd, stdio: 'inherit' },
+ (err, _stdout, _stderr) => {
+ if (err) return reject(err);
+ resolve();
+ },
+ );
+ });
+ }
+
+ /**
+ * generate JWT token
+ */
+ async function generateJWT() {
+ const envPath = path.resolve(webpackPaths.appPath, '.env');
+ try {
+ // Try to read the file metadata; if it doesn't exist, we'll catch below
+ await fsPromises.access(envPath);
+ // file exists — nothing to do
+ } catch {
+ console.log(
+ chalk.black.bgYellow.bold(
+ 'The env files are missing. Sit back while we generate them for you with "KEY=testDevKey"',
+ ),
+ );
+ console.log(
+ chalk.red.bgWhiteBright.bold("Don't forget to change this KEY!"),
+ );
+ // write the file atomically
+ fs.writeFileSync(envPath, 'KEY=testDevKey\n', {
+ encoding: 'utf8',
+ flag: 'wx',
+ });
+ }
+
+ const cwd = path.resolve(webpackPaths.rootPath);
+ const script = path.join(cwd, 'scripts', 'jwt_generate.js');
+
+ await new Promise((resolve, reject) => {
+ execFile(
+ 'node',
+ [script],
+ { cwd, stdio: 'inherit' },
+ (err, _stdout, _stderr) => {
+ if (err) return reject(err);
+ resolve();
+ },
+ );
+ });
+ }
+ // beforeRun fires once, before compiling begins
+ compiler.hooks.beforeRun.tapPromise('TsMetaPlugin', async () => {
+ await checkVersionJson();
+ await checkThirdPartyTxt();
+ await generateJWT();
+ });
+ }
+}
diff --git a/src/main/util.ts b/src/main/util.ts
index 39a6a9730..5e46f9cfd 100644
--- a/src/main/util.ts
+++ b/src/main/util.ts
@@ -2,10 +2,7 @@
import { URL } from 'url';
import path from 'path';
import { BrowserWindow } from 'electron';
-import webpackPaths from '../../.erb/configs/webpack.paths';
-import fs from 'fs';
-import chalk from 'chalk';
-import { execFile, execSync } from 'child_process';
+import { execFile } from 'child_process';
import http from 'http';
import settings from './settings';
@@ -19,52 +16,6 @@ export function resolveHtmlPath(htmlFileName: string) {
return `file://${path.resolve(__dirname, '../renderer/', htmlFileName)}`;
}
-/**
- * Warn version.json is missing
- */
-export function checkVersionJson() {
- const version = path.resolve(webpackPaths.srcRendererPath, 'version.json');
- execSync('npm run version-meta');
-}
-
-/**
- * Warn third-party.txt is missing
- */
-export function checkThirdPartyTxt() {
- const thirdParty = path.resolve(
- webpackPaths.srcRendererPath,
- 'third-party.txt',
- );
- if (!fs.existsSync(thirdParty)) {
- console.log(
- chalk.black.bgYellow.bold(
- 'The third-party.txt files are missing. Sit back while we build them for you with "npm run third-party"',
- ),
- );
- execSync('npm run third-party');
- }
-}
-
-/**
- * generate JWT token
- */
-export function generateJWT() {
- const env = path.resolve(webpackPaths.appPath, '.env');
- if (!fs.existsSync(env)) {
- console.log(
- chalk.black.bgYellow.bold(
- 'The env files are missing. Sit back while we generate them for you with "KEY=testDevKey"',
- ),
- );
- console.log(
- chalk.red.bgWhiteBright.bold("Don't forget to change this KEY!"),
- );
- execSync('echo KEY=testDevKey > ' + env);
- }
-
- execSync('npm run generate-jwt');
-}
-
/**
* @param payload: string
* @param endpoint: string