import { createHash } from 'node:crypto'; import { readFile, readdir } from 'node:fs/promises'; import { join, relative, sep } from 'node:path'; const repositoryRoot = process.cwd(); const environment = requiredNacosEnvironment('NACOS_ENVIRONMENT'); const configRoot = join(repositoryRoot, 'nacos', 'namespaces', environment); const nacosUrls = requiredEnvironment(`NACOS_${environment.toUpperCase()}_URLS`).split(',').map((value) => value.trim()).filter(Boolean); const username = requiredEnvironment(`NACOS_${environment.toUpperCase()}_USERNAME`); const password = requiredEnvironment(`NACOS_${environment.toUpperCase()}_PASSWORD`); const group = 'DEFAULT_GROUP'; const verificationNodeCount = environment === 'prod' ? 2 : 1; if (nacosUrls.length < verificationNodeCount) { throw new Error(`${environment} 环境至少需要 ${verificationNodeCount} 个 Nacos 地址用于发布校验`); } const configFiles = await collectYamlFiles(configRoot); if (configFiles.length === 0) { throw new Error(`nacos/namespaces/${environment} 下没有可发布的 YAML 配置`); } const token = await login(nacosUrls[0], username, password); for (const filePath of configFiles) { const relativePath = relative(configRoot, filePath).split(sep); if (relativePath.length !== 3 || relativePath[1] !== group) { throw new Error(`配置路径必须是 /${group}/.yaml:${relativePath.join('/')}`); } const [namespace, , dataId] = relativePath; const content = await readFile(filePath, 'utf8'); await publish(nacosUrls[0], token, namespace, group, dataId, content); await verify(nacosUrls.slice(0, verificationNodeCount), token, namespace, group, dataId, content); console.log(`已发布并校验 ${environment}/${namespace}/${group}/${dataId}`); } function requiredEnvironment(name) { const value = process.env[name]; if (!value) { throw new Error(`缺少环境变量 ${name}`); } return value; } function requiredNacosEnvironment(name) { const environment = requiredEnvironment(name); if (environment !== 'prod' && environment !== 'sit') { throw new Error(`不支持的 Nacos 发布环境:${environment};只允许 prod 或 sit`); } return environment; } async function collectYamlFiles(directory) { const entries = await readdir(directory, { withFileTypes: true }); const files = []; for (const entry of entries) { const entryPath = join(directory, entry.name); if (entry.isDirectory()) { files.push(...await collectYamlFiles(entryPath)); } else if (entry.isFile() && entry.name.endsWith('.yaml')) { files.push(entryPath); } } return files.sort(); } async function login(baseUrl, user, secret) { const body = new URLSearchParams({ username: user, password: secret }); const response = await fetch(`${baseUrl}/nacos/v1/auth/login`, { method: 'POST', body }); if (!response.ok) { throw new Error(`Nacos 登录失败:${baseUrl} HTTP ${response.status}`); } const payload = await response.json(); if (!payload.accessToken) { throw new Error(`Nacos 登录响应缺少 accessToken:${baseUrl}`); } return payload.accessToken; } async function publish(baseUrl, token, namespace, configGroup, dataId, content) { const body = new URLSearchParams({ dataId, group: configGroup, tenant: namespace, type: 'yaml', content }); const response = await fetch(`${baseUrl}/nacos/v1/cs/configs?accessToken=${encodeURIComponent(token)}`, { method: 'POST', body }); const result = await response.text(); if (!response.ok || result.trim() !== 'true') { throw new Error(`Nacos 发布失败:${baseUrl}/${namespace}/${dataId} HTTP ${response.status} ${result}`); } } async function verify(baseUrls, token, namespace, configGroup, dataId, expectedContent) { const expectedHash = sha256(expectedContent); for (const baseUrl of baseUrls) { const query = new URLSearchParams({ dataId, group: configGroup, tenant: namespace }); const response = await fetch(`${baseUrl}/nacos/v1/cs/configs?${query}&accessToken=${encodeURIComponent(token)}`); const content = await response.text(); if (!response.ok || sha256(content) !== expectedHash) { throw new Error(`Nacos 配置校验失败:${baseUrl}/${namespace}/${dataId} HTTP ${response.status}`); } } } function sha256(value) { return createHash('sha256').update(value, 'utf8').digest('hex'); }