官方纰漏bug修复和安全能力提升
This commit is contained in:
1 parent
459339719d
commit
ce00640ea4
148 files changed
+9524
-1701
No files matched your search
@@ -0,0 +1,250 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import {
|
||||
existsSync,
|
||||
lstatSync,
|
||||
readFileSync,
|
||||
readdirSync,
|
||||
realpathSync,
|
||||
statSync,
|
||||
writeFileSync,
|
||||
} from 'node:fs'
|
||||
import path from 'node:path'
|
||||
|
||||
export const ARTIFACT_MANIFEST_FILENAME = 'artifact-manifest.json'
|
||||
export const SOURCE_INPUTS = [
|
||||
'src',
|
||||
'scripts',
|
||||
'public',
|
||||
'index.html',
|
||||
'package.json',
|
||||
'package-lock.json',
|
||||
'vite.config.ts',
|
||||
'tsconfig.json',
|
||||
'tsconfig.node.json',
|
||||
'postcss.config.js',
|
||||
'tailwind.config.js',
|
||||
]
|
||||
|
||||
function isWithin(root, candidate) {
|
||||
const relative = path.relative(root, candidate)
|
||||
return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative))
|
||||
}
|
||||
|
||||
function canonicalizeCandidate(candidate) {
|
||||
let existingAncestor = path.resolve(candidate)
|
||||
const missingSegments = []
|
||||
|
||||
while (!existsSync(existingAncestor)) {
|
||||
const parent = path.dirname(existingAncestor)
|
||||
if (parent === existingAncestor) {
|
||||
break
|
||||
}
|
||||
missingSegments.unshift(path.basename(existingAncestor))
|
||||
existingAncestor = parent
|
||||
}
|
||||
|
||||
const canonicalAncestor = existsSync(existingAncestor)
|
||||
? realpathSync.native(existingAncestor)
|
||||
: existingAncestor
|
||||
return path.resolve(canonicalAncestor, ...missingSegments)
|
||||
}
|
||||
|
||||
export function parseArtifactOutDir(argv) {
|
||||
let outDir
|
||||
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
const argument = argv[index]
|
||||
if (argument === '--outDir') {
|
||||
if (outDir !== undefined || index + 1 >= argv.length || argv[index + 1].startsWith('--')) {
|
||||
throw new Error('Exactly one non-empty --outDir value is required')
|
||||
}
|
||||
outDir = argv[index + 1]
|
||||
index += 1
|
||||
continue
|
||||
}
|
||||
if (argument.startsWith('--outDir=')) {
|
||||
if (outDir !== undefined) {
|
||||
throw new Error('Exactly one non-empty --outDir value is required')
|
||||
}
|
||||
outDir = argument.slice('--outDir='.length)
|
||||
continue
|
||||
}
|
||||
throw new Error(`Unsupported build:artifact argument: ${argument}`)
|
||||
}
|
||||
|
||||
if (!outDir || outDir.trim() === '') {
|
||||
throw new Error('A non-empty --outDir is required; release artifacts must not use financial_system_frontend/dist')
|
||||
}
|
||||
return outDir
|
||||
}
|
||||
|
||||
export function resolveArtifactOutDir(rawOutDir, {
|
||||
cwd,
|
||||
frontendRoot,
|
||||
repoRoot,
|
||||
ciArtifactRoot,
|
||||
}) {
|
||||
const resolvedFrontendRoot = canonicalizeCandidate(frontendRoot)
|
||||
const resolvedRepoRoot = canonicalizeCandidate(repoRoot)
|
||||
const target = canonicalizeCandidate(path.resolve(cwd, rawOutDir))
|
||||
const filesystemRoot = path.parse(target).root
|
||||
|
||||
if (target === filesystemRoot) {
|
||||
throw new Error('Artifact output cannot be a filesystem root')
|
||||
}
|
||||
|
||||
const frontendDist = canonicalizeCandidate(path.join(resolvedFrontendRoot, 'dist'))
|
||||
if (isWithin(frontendDist, target)) {
|
||||
throw new Error('Artifact output cannot be financial_system_frontend/dist or any path below it')
|
||||
}
|
||||
|
||||
if (!isWithin(resolvedRepoRoot, target)) {
|
||||
return target
|
||||
}
|
||||
|
||||
if (!ciArtifactRoot || ciArtifactRoot.trim() === '') {
|
||||
throw new Error('Artifact output inside the repository requires an explicit CI_ARTIFACT_DIR')
|
||||
}
|
||||
|
||||
const resolvedCiRoot = canonicalizeCandidate(path.resolve(cwd, ciArtifactRoot))
|
||||
const protectedRoots = [
|
||||
path.join(resolvedRepoRoot, '.git'),
|
||||
path.join(resolvedFrontendRoot, 'src'),
|
||||
path.join(resolvedFrontendRoot, 'scripts'),
|
||||
path.join(resolvedFrontendRoot, 'public'),
|
||||
path.join(resolvedFrontendRoot, 'dist'),
|
||||
].map(canonicalizeCandidate)
|
||||
|
||||
if (!isWithin(resolvedRepoRoot, resolvedCiRoot)
|
||||
|| protectedRoots.some((protectedRoot) => isWithin(protectedRoot, resolvedCiRoot))) {
|
||||
throw new Error('CI_ARTIFACT_DIR must be a dedicated, unprotected directory inside the repository')
|
||||
}
|
||||
if (!isWithin(resolvedCiRoot, target)) {
|
||||
throw new Error('Artifact output must stay within CI_ARTIFACT_DIR')
|
||||
}
|
||||
return target
|
||||
}
|
||||
|
||||
export function assertArtifactDirectoryReady(outDir) {
|
||||
if (!existsSync(outDir)) {
|
||||
return
|
||||
}
|
||||
if (!statSync(outDir).isDirectory()) {
|
||||
throw new Error(`Artifact output already exists and is not a directory: ${outDir}`)
|
||||
}
|
||||
if (readdirSync(outDir).length > 0) {
|
||||
throw new Error(`Artifact output directory must be empty: ${outDir}`)
|
||||
}
|
||||
}
|
||||
|
||||
export function sha256File(filePath) {
|
||||
return createHash('sha256').update(readFileSync(filePath)).digest('hex')
|
||||
}
|
||||
|
||||
function collectFiles(directory, relativeDirectory = '') {
|
||||
const files = []
|
||||
const absoluteDirectory = path.join(directory, relativeDirectory)
|
||||
for (const entry of readdirSync(absoluteDirectory, { withFileTypes: true })) {
|
||||
const relativePath = path.join(relativeDirectory, entry.name)
|
||||
const absolutePath = path.join(directory, relativePath)
|
||||
const fileInfo = lstatSync(absolutePath)
|
||||
|
||||
if (fileInfo.isSymbolicLink()) {
|
||||
throw new Error(`Artifact output must not contain symbolic links: ${relativePath}`)
|
||||
}
|
||||
if (fileInfo.isDirectory()) {
|
||||
files.push(...collectFiles(directory, relativePath))
|
||||
continue
|
||||
}
|
||||
if (!fileInfo.isFile()) {
|
||||
throw new Error(`Artifact output contains an unsupported entry: ${relativePath}`)
|
||||
}
|
||||
if (relativeDirectory === '' && entry.name === ARTIFACT_MANIFEST_FILENAME) {
|
||||
continue
|
||||
}
|
||||
files.push({
|
||||
path: relativePath.split(path.sep).join('/'),
|
||||
sha256: sha256File(absolutePath),
|
||||
size: fileInfo.size,
|
||||
})
|
||||
}
|
||||
return files
|
||||
}
|
||||
|
||||
function collectSourcePath(frontendRoot, relativePath) {
|
||||
const absolutePath = path.join(frontendRoot, relativePath)
|
||||
if (!existsSync(absolutePath)) return []
|
||||
const info = lstatSync(absolutePath)
|
||||
if (info.isSymbolicLink()) throw new Error(`Source input must not be a symbolic link: ${relativePath}`)
|
||||
if (info.isDirectory()) {
|
||||
return readdirSync(absolutePath, { withFileTypes: true })
|
||||
.flatMap(entry => collectSourcePath(frontendRoot, path.join(relativePath, entry.name)))
|
||||
}
|
||||
if (!info.isFile()) throw new Error(`Source input is not a regular file: ${relativePath}`)
|
||||
return [{
|
||||
path: `financial_system_frontend/${relativePath.split(path.sep).join('/')}`,
|
||||
sha256: sha256File(absolutePath),
|
||||
size: info.size,
|
||||
}]
|
||||
}
|
||||
|
||||
export function collectSourceInputs(frontendRoot, inputs = SOURCE_INPUTS) {
|
||||
return inputs.flatMap(relativePath => collectSourcePath(frontendRoot, relativePath))
|
||||
.sort((left, right) => left.path === right.path ? 0 : left.path < right.path ? -1 : 1)
|
||||
}
|
||||
|
||||
export function sourceTreeSha256(files) {
|
||||
const canonical = files.map(file => `${file.path}\0${file.size}\0${file.sha256}\n`).join('')
|
||||
return createHash('sha256').update(canonical, 'utf8').digest('hex')
|
||||
}
|
||||
|
||||
export const gitStatusIsDirty = (porcelainOutput) => porcelainOutput.trim().length > 0
|
||||
|
||||
export function createArtifactManifest({
|
||||
outDir,
|
||||
packageLockPath,
|
||||
sourceRevision,
|
||||
buildUtc,
|
||||
nodeVersion,
|
||||
npmVersion,
|
||||
sourceDirty,
|
||||
sourceFiles,
|
||||
}) {
|
||||
const normalizedRevision = sourceRevision?.trim()
|
||||
if (!normalizedRevision) {
|
||||
throw new Error('A source revision is required for a release artifact')
|
||||
}
|
||||
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
sourceRevision: normalizedRevision,
|
||||
source: {
|
||||
dirty: sourceDirty === true,
|
||||
treeSha256: sourceTreeSha256(sourceFiles),
|
||||
files: sourceFiles,
|
||||
},
|
||||
packageLock: {
|
||||
path: 'financial_system_frontend/package-lock.json',
|
||||
sha256: sha256File(packageLockPath),
|
||||
},
|
||||
build: {
|
||||
utc: buildUtc,
|
||||
nodeVersion,
|
||||
npmVersion,
|
||||
},
|
||||
files: collectFiles(outDir).sort((left, right) => {
|
||||
if (left.path === right.path) return 0
|
||||
return left.path < right.path ? -1 : 1
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
export function serializeArtifactManifest(manifest) {
|
||||
return `${JSON.stringify(manifest, null, 2)}\n`
|
||||
}
|
||||
|
||||
export function writeArtifactManifest(outDir, manifest) {
|
||||
const manifestPath = path.join(outDir, ARTIFACT_MANIFEST_FILENAME)
|
||||
writeFileSync(manifestPath, serializeArtifactManifest(manifest), { encoding: 'utf8', flag: 'wx' })
|
||||
return manifestPath
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { existsSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import {
|
||||
assertArtifactDirectoryReady,
|
||||
collectSourceInputs,
|
||||
createArtifactManifest,
|
||||
gitStatusIsDirty,
|
||||
parseArtifactOutDir,
|
||||
resolveArtifactOutDir,
|
||||
writeArtifactManifest,
|
||||
} from './artifact-manifest.mjs'
|
||||
|
||||
const scriptPath = fileURLToPath(import.meta.url)
|
||||
const frontendRoot = path.resolve(path.dirname(scriptPath), '..')
|
||||
// The frontend is an independent Git repository after the workspace split.
|
||||
const repoRoot = frontendRoot
|
||||
|
||||
function commandOutput(command, args, cwd) {
|
||||
const result = spawnSync(command, args, {
|
||||
cwd,
|
||||
encoding: 'utf8',
|
||||
windowsHide: true,
|
||||
})
|
||||
if (result.status !== 0) {
|
||||
const detail = result.stderr?.trim() || result.error?.message || `${command} exited with status ${result.status}`
|
||||
throw new Error(detail)
|
||||
}
|
||||
return result.stdout.trim()
|
||||
}
|
||||
|
||||
function resolveSourceRevision() {
|
||||
const configuredRevision = process.env.RELEASE_SOURCE_REVISION?.trim()
|
||||
return configuredRevision || commandOutput('git', ['rev-parse', 'HEAD'], repoRoot)
|
||||
}
|
||||
|
||||
function resolveNpmVersion() {
|
||||
const userAgentMatch = process.env.npm_config_user_agent?.match(/(?:^|\s)npm\/([^\s]+)/)
|
||||
if (userAgentMatch) {
|
||||
return userAgentMatch[1]
|
||||
}
|
||||
const npmCommand = process.platform === 'win32' ? 'npm.cmd' : 'npm'
|
||||
return commandOutput(npmCommand, ['--version'], frontendRoot)
|
||||
}
|
||||
|
||||
function runViteBuild(outDir) {
|
||||
const viteEntry = path.join(frontendRoot, 'node_modules', 'vite', 'bin', 'vite.js')
|
||||
if (!existsSync(viteEntry)) {
|
||||
throw new Error('Vite is not installed; run npm ci before build:artifact')
|
||||
}
|
||||
|
||||
const result = spawnSync(
|
||||
process.execPath,
|
||||
[viteEntry, 'build', '--outDir', outDir],
|
||||
{
|
||||
cwd: frontendRoot,
|
||||
env: { ...process.env, NODE_ENV: 'production' },
|
||||
stdio: 'inherit',
|
||||
windowsHide: true,
|
||||
},
|
||||
)
|
||||
if (result.status !== 0) {
|
||||
throw new Error(result.error?.message || `Vite build exited with status ${result.status}`)
|
||||
}
|
||||
}
|
||||
|
||||
export function buildArtifact(argv = process.argv.slice(2)) {
|
||||
const rawOutDir = parseArtifactOutDir(argv)
|
||||
const outDir = resolveArtifactOutDir(rawOutDir, {
|
||||
cwd: process.cwd(),
|
||||
frontendRoot,
|
||||
repoRoot,
|
||||
ciArtifactRoot: process.env.CI_ARTIFACT_DIR,
|
||||
})
|
||||
assertArtifactDirectoryReady(outDir)
|
||||
|
||||
const sourceRevision = resolveSourceRevision()
|
||||
const sourceDirty = gitStatusIsDirty(commandOutput('git', ['status', '--porcelain=v1', '--untracked-files=all'], repoRoot))
|
||||
const sourceFiles = collectSourceInputs(frontendRoot)
|
||||
const npmVersion = resolveNpmVersion()
|
||||
runViteBuild(outDir)
|
||||
|
||||
const manifest = createArtifactManifest({
|
||||
outDir,
|
||||
packageLockPath: path.join(frontendRoot, 'package-lock.json'),
|
||||
sourceRevision,
|
||||
buildUtc: new Date().toISOString(),
|
||||
nodeVersion: process.version,
|
||||
npmVersion,
|
||||
sourceDirty,
|
||||
sourceFiles,
|
||||
})
|
||||
const manifestPath = writeArtifactManifest(outDir, manifest)
|
||||
process.stdout.write(`[build:artifact] artifact: ${outDir}\n`)
|
||||
process.stdout.write(`[build:artifact] manifest: ${manifestPath}\n`)
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === scriptPath) {
|
||||
try {
|
||||
buildArtifact()
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
process.stderr.write(`[build:artifact] ${message}\n`)
|
||||
process.exitCode = 1
|
||||
}
|
||||
}
|
||||