shacl-vue/vite.config.app.mjs
Stephan Heunis bb69bd46d8 Add support for Content Security Policy configuration
Another security-heightening feature: content security policy.
This new feature depends on the existing build configuration support. Deployment-
specific CSP content can be configured via the CSP_CONTENT option, e.g.:

CSP_CONTENT:
  connect-src:
    - https://hub.psychoinformatics.de/
    - https://concepts.datalad.org/

This is parsed by a new addition to the vite config 'serializeCsp(csp)' which
serializes input CSP directives and associated values into strings that can be
included in the correct location in index.html meta tag:

content='%CSP_CONTENT'

Note that the 'self' specification in any directive, if provided via YAML, should
be enclosed in single AND double quotes, in order to retain the required single
quotes for the html tag.

There is no default CSP introduced by this featue, just an empty string. This means
shacl-vue's current CSP is unrestricted by default.
2026-10-22 14:40:05 +02:00

143 lines
4.9 KiB
JavaScript

// Plugins
import Components from 'unplugin-vue-components/vite';
import Vue from '@vitejs/plugin-vue';
import Vuetify, { transformAssetUrls } from 'vite-plugin-vuetify';
// Utilities
import { defineConfig } from 'vite';
import { fileURLToPath, URL } from 'node:url';
import fs from 'fs';
import path from 'path';
import YAML from 'yaml';
// Git repo version
import { execSync } from 'child_process';
const commitHash = execSync('git rev-parse HEAD').toString().trim();
const commitHashShort = execSync('git rev-parse --short HEAD')
.toString()
.trim();
const branch = execSync('git rev-parse --abbrev-ref HEAD').toString().trim();
const commitDate = execSync('git show -s --format=%cI HEAD').toString().trim().replace(/[+-][0-9]{2}:[0-9]{2}$/, '');
// Output directory of build process
const outDir = process.env.VITE_OUT_DIR || 'dist/app';
const variant = process.env.VITE_SHACLVUE_VARIANT || 'default';
console.log(`Building shacl-vue application variant: '${variant}'`)
// Build process inputs
const buildGitCommit = process.env.BUILD_GIT_COMMIT ?? null;
const buildGitCommitShort = process.env.BUILD_GIT_COMMIT_SHORT ?? null;
const buildGitBranch = process.env.BUILD_GIT_BRANCH ?? null;
let buildGitDate = process.env.BUILD_GIT_DATE ?? null;
if (buildGitDate) buildGitDate = buildGitDate.replace(/[+-][0-9]{2}:[0-9]{2}$/, '');
// Build date
let buildDate = new Date().toISOString();
buildDate = buildDate.substring(0, buildDate.length - 5);
// Build configuration
function loadBuildConfig() {
const configFile = process.env.BUILD_CONFIG || null;
if (configFile === null) {
return {}
}
const filePath = path.resolve(configFile);
if (!fs.existsSync(filePath)) {
throw new Error(`Build config file not found at: ${filePath}`);
}
const contents = fs.readFileSync(filePath, 'utf8');
const extension = path.extname(filePath).toLowerCase();
let config = {};
if (extension === '.json') {
config = JSON.parse(contents);
} else if (['.yaml', '.yml'].includes(extension)) {
config = YAML.parse(contents);
} else {
throw new Error(
`Unsupported config file extension: ${extension}. Use .json, .yaml, or .yml.`,
);
}
if ( config === null || typeof config !== 'object' || Array.isArray(config)) {
throw new Error('Build config must be a JSON/YAML object.');
}
console.log(`Using ENV-provided build config file: ${filePath}`);
return config
}
function serializeCsp(csp) {
return Object.entries(csp).map(([directive, sources]) => `${directive} ${sources.join(' ')};`).join(' ');
}
const buildConfig = loadBuildConfig();
buildConfig.CSP_CONTENT = buildConfig.CSP_CONTENT ? serializeCsp(buildConfig.CSP_CONTENT) : '';
const buildConfigDefines = Object.fromEntries(
Object.entries(buildConfig).map(([key, value]) => [
`import.meta.env.${key}`,
JSON.stringify(value),
]),
);
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
Vue({
template: { transformAssetUrls },
}),
// https://github.com/vuetifyjs/vuetify-loader/tree/master/packages/vite-plugin#readme
Vuetify(),
Components(),
{
name: 'no-spa-fallback-for-html',
configureServer(server) {
server.middlewares.use((req, res, next) => {
if (req.url && req.url.endsWith('.html')) {
const filePath = path.join(process.cwd(), 'public', req.url);
if (!fs.existsSync(filePath)) {
res.statusCode = 404;
res.end('Not Found');
return; // stop here
}
}
next();
});
},
},
],
define: {
...buildConfigDefines,
'process.env': {},
__SV_COMMIT_HASH__: JSON.stringify(commitHash),
__SV_COMMIT_HASH_SHORT__: JSON.stringify(commitHashShort),
__SV_BRANCH__: JSON.stringify(branch),
__SV_COMMIT_DATE__: JSON.stringify(commitDate),
__BUILD_COMMIT_HASH__: buildGitCommit ? JSON.stringify(buildGitCommit) : null,
__BUILD_COMMIT_HASH_SHORT__: buildGitCommitShort ? JSON.stringify(buildGitCommitShort) : null,
__BUILD_BRANCH__: buildGitBranch ? JSON.stringify(buildGitBranch) : null,
__BUILD_COMMIT_DATE__: buildGitDate ? JSON.stringify(buildGitDate) : null,
__BUILD_DATE__: JSON.stringify(buildDate),
},
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
},
extensions: ['.js', '.json', '.jsx', '.mjs', '.ts', '.tsx', '.vue'],
},
build: {
outDir,
emptyOutDir: true,
sourcemap: true,
rollupOptions: {
input: 'index.html',
},
},
server: {
port: 3000,
mimeTypes: {
'.vue': 'application/javascript',
},
},
base: './',
});