cmvr-wms/scripts/deploy/InitializeEmptyProduction.java
lixiaolong 5bdeceafd7 feat(auth): 添加认证cookie名称配置并优化表单布局
- 在 .env.production 中新增 VITE_AUTH_COOKIE_NAME 配置项用于设置认证cookie名称
- 将 AcceptanceException.vue 中的表单标签宽度从固定90px改为自动适配
- 在 ActionDialog.vue 中将多个表单项标记为必填项并调整标签宽度为自动适配
- 重构 ActionHistory.vue 中的按钮布局结构并添加表格列样式类名
- 更新 api-contract-audit.cjs 添加生产任务和BOM相关接口的契约测试
- 修改 auth.js 使用动态认证cookie键名替换硬编码的Admin-Token
- 调整系统角色授权用户页面的表单布局和表格样式类名
- 优化 ReceiptDialog Batch 组件的对话框尺寸、表单验证和分页功能
2026-10-15 11:30:55 +08:00

58 lines
6.8 KiB
Java

import com.fasterxml.jackson.databind.ObjectMapper;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.sql.*;
import java.util.*;
import java.util.regex.*;
/** Explicit, one-time full copy into the named EMPTY production database only. */
public class InitializeEmptyProduction {
static final String TARGET="cmvr-project-prod", SOURCE="cmvr-project-dev";
public static void main(String[] args)throws Exception{
if(args.length!=2||!"--initialize-empty-cmvr-project-prod".equals(args[0]))throw new IllegalArgumentException("Explicit empty-production initialization required");
Path directory=Path.of(args[1]).toAbsolutePath().normalize(),allowed=Path.of(".codex-tmp/database-backups").toAbsolutePath().normalize();
if(!directory.startsWith(allowed))throw new IllegalArgumentException("Backup directory outside workspace backup root");
var json=new ObjectMapper();var manifest=json.readTree(directory.resolve("manifest.json").toFile());
if(!SOURCE.equals(manifest.path("database").asText())||!manifest.path("complete").asBoolean()||!manifest.path("readOnly").asBoolean())throw new IllegalArgumentException("Incomplete source backup");
for(String kind:List.of("views","triggers","routines","events"))if(!manifest.path(kind).isEmpty())throw new IllegalStateException("Manual review required for stored programs: "+kind);
Path sql=directory.resolve(SOURCE+".sql");byte[] bytes=Files.readAllBytes(sql);
if(!BackupReplayTarget.hash(bytes).equals(manifest.path("sha256").asText()))throw new IllegalStateException("Backup checksum mismatch");
String content=new String(bytes,StandardCharsets.UTF_8);if(!content.endsWith("-- BACKUP COMPLETE\n"))throw new IllegalStateException("Backup not finalized");
Map<String,String> config=new HashMap<>();boolean master=false;
for(String line:Files.readAllLines(Path.of("ruoyi-admin/src/main/resources/application-druid.yml"))){if(line.trim().equals("master:")){master=true;continue;}if(line.trim().equals("slave:"))break;if(master&&line.indexOf(':')>0){int colon=line.indexOf(':');config.put(line.substring(0,colon).trim(),DatabaseTool.value(line.substring(colon+1).trim()));}}
String configured=config.get("url");if(configured==null||!configured.matches("^jdbc:mysql://192\\.168\\.28\\.10:3306/cmvr-project-dev(?:\\?.*)?$"))throw new IllegalStateException("Unexpected datasource");
var properties=new Properties();properties.setProperty("user",config.get("username"));properties.setProperty("password",config.get("password"));properties.setProperty("socketTimeout","60000");properties.setProperty("connectTimeout","5000");properties.setProperty("tinyInt1isBit","false");
Set<String> names=new HashSet<>();manifest.path("tables").fieldNames().forEachRemaining(names::add);
var statements=new ArrayList<String>();var tablePattern=Pattern.compile("(?is)^(?:CREATE TABLE|INSERT INTO) `([A-Za-z0-9_]+)`.*");
for(String statement:DatabaseTool.split(content)){
if(statement.equals("USE `cmvr-project-dev`")||statement.matches("(?is)^DROP TABLE IF EXISTS `[A-Za-z0-9_]+`$")||statement.startsWith("SET "))continue;
var match=tablePattern.matcher(statement);if(!match.matches()||!names.contains(match.group(1)))throw new IllegalStateException("Unexpected backup statement");
if(Pattern.compile("`[^`]+`\\s*\\.\\s*`[^`]+`").matcher(statement).find())throw new IllegalStateException("Qualified database reference forbidden");
statements.add(statement);
}
Path output=Path.of(".codex-tmp/deploy-production");Files.createDirectories(output);
try(var c=DriverManager.getConnection(configured.replace("/"+SOURCE,"/"+TARGET),properties)){
if(!TARGET.equals(BackupReplayTarget.scalar(c,"select database()")))throw new IllegalStateException("Target mismatch");
try(var s=c.prepareStatement("select count(*) from information_schema.tables where table_schema=?")){s.setString(1,TARGET);try(var r=s.executeQuery()){r.next();if(r.getLong(1)!=0)throw new IllegalStateException("Production is not empty; refusing overwrite");}}
Files.writeString(output.resolve("production-before-initialize.json"),json.writerWithDefaultPrettyPrinter().writeValueAsString(Map.of("database",TARGET,"tables",0,"sourceBackup",directory.toString(),"sourceSha256",manifest.path("sha256").asText())),StandardOpenOption.CREATE_NEW);
try(var s=c.createStatement()){
s.execute("SET NAMES utf8mb4");s.execute("SET FOREIGN_KEY_CHECKS=0");
try{int count=0;for(String statement:statements){s.execute(statement);if(++count%1000==0)System.out.println("Production initialization statements="+count);}}finally{s.execute("SET FOREIGN_KEY_CHECKS=1");}
}
var changed=new ArrayList<String>();long rows=0;
for(String name:new TreeSet<>(names)){var definition=manifest.path("tables").path(name);long actual=Long.parseLong(BackupReplayTarget.scalar(c,"select count(*) from "+BackupReplayTarget.id(name)));rows+=actual;if(actual!=definition.path("rows").asLong()||!ReadOnlyReplayAudit.fingerprint(c,name,definition).equals(definition.path("rowFingerprint").asText()))changed.add(name);}
var result=Map.of("database",TARGET,"source",SOURCE,"tables",names.size(),"rows",rows,"fingerprintDifferences",changed,"sourceBackup",directory.toString(),"sourceUnmodified",true);
Files.writeString(output.resolve("production-initialization-result.json"),json.writerWithDefaultPrettyPrinter().writeValueAsString(result));
if(!changed.isEmpty())throw new IllegalStateException("Production copy verification failed: "+changed);
System.out.println("Production initialized and fingerprint verified: tables="+names.size()+", rows="+rows);
}
String redisPassword=null;
for(String line:Files.readAllLines(Path.of("ruoyi-admin/src/main/resources/application-druid.yml")))if(line.matches("^ {12}password:.*"))redisPassword=DatabaseTool.value(line.substring(line.indexOf(':')+1).trim());
if(redisPassword==null)throw new IllegalStateException("Redis credentials not found; environment not generated");
byte[] random=new byte[64];new java.security.SecureRandom().nextBytes(random);
String env="PROD_DB_USERNAME="+config.get("username")+"\nPROD_DB_PASSWORD="+config.get("password")+"\nPROD_REDIS_PASSWORD="+redisPassword+"\nPROD_TOKEN_SECRET="+Base64.getEncoder().encodeToString(random)+"\nPROD_REDIS_HOST=192.168.28.10\nPROD_REDIS_PORT=6379\nPROD_REDIS_DATABASE=13\nPROD_BIND_ADDRESS=127.0.0.1\nPROD_BACKEND_PORT=28183\nPROD_UPLOAD_PATH=/app/uploads\nRUOYI_LOG_PATH=/app/logs\n";
Files.writeString(output.resolve("production.env"),env,StandardOpenOption.CREATE_NEW);
System.out.println("Server environment generated in ignored release staging; no secret values printed.");
}
}