86 lines
6.8 KiB
TypeScript
86 lines
6.8 KiB
TypeScript
/** Explicit, versioned configuration repair. Bundle from the exact release commit; never runs on GET. */
|
|
import fs from 'node:fs'
|
|
import path from 'node:path'
|
|
import { pathToFileURL } from 'node:url'
|
|
import { createHash } from 'node:crypto'
|
|
import { Prisma } from '@prisma/client'
|
|
import { prisma } from '../lib/prisma'
|
|
import { requireSalaryAccess } from '../lib/personnel-salary'
|
|
import { connectManagementVisualSurvey } from '../lib/connect-salary-management-survey'
|
|
import { INITIAL_SALARY_POSITIONS } from '../lib/salary-position-seeds'
|
|
import { positionFields } from '../lib/salary-position-contract'
|
|
import { serializePosition, updateSalaryPosition } from '../lib/salary-positions'
|
|
|
|
type Fields = ReturnType<typeof positionFields>
|
|
type Manifest = { format: 1; target: string; actorUserId: string; positionId: string; beforeRevision: number; before: Fields; after: Fields; snapshot: unknown }
|
|
const mode = process.argv[2], actor = process.env.SALARY_SURVEY_ACTOR_ID || '', file = path.resolve(process.env.SALARY_SURVEY_MANIFEST || '')
|
|
const hash = (value: Buffer) => createHash('sha256').update(value).digest('hex')
|
|
const canonical = (value: unknown): string => JSON.stringify(value, (_k, v) => v && typeof v === 'object' && !Array.isArray(v) ? Object.fromEntries(Object.keys(v).sort().map(k => [k, v[k]])) : v)
|
|
async function main() {
|
|
if (!['audit', 'apply', 'restore'].includes(mode) || !actor || !path.isAbsolute(process.env.SALARY_SURVEY_MANIFEST || '')) throw new Error('Explicit mode, actor and absolute manifest required')
|
|
const url = new URL(process.env.DATABASE_URL!)
|
|
let target: string
|
|
if (process.env.SALARY_SURVEY_TARGET === 'production') {
|
|
const guard = await import(pathToFileURL(path.join(process.cwd(), 'scripts/safe-production-migrate.mjs')).href)
|
|
const commit = guard.requireExactCommit(process.env.EXPECTED_COMMIT_SHA, 'EXPECTED_COMMIT_SHA')
|
|
if (fs.readFileSync('/app/DEPLOYMENT_COMMIT', 'utf8').trim() !== commit) throw new Error('IMAGE_COMMIT_MISMATCH')
|
|
const [identity] = await prisma.$queryRawUnsafe<Array<Record<string, unknown>>>('SELECT current_database() AS database,current_user AS "user",inet_server_addr()::text AS server_address,inet_server_port()::text AS server_port')
|
|
const database = guard.assertExpectedDatabaseIdentity(url, identity)
|
|
target = JSON.stringify({ commit, database })
|
|
if (mode !== 'audit') await guard.assertBackupReceipt({ expectedCommit: commit, database })
|
|
} else {
|
|
if (process.env.SALARY_SURVEY_TARGET !== 'local' || url.hostname !== '127.0.0.1' || url.port !== '55439' || !url.pathname.startsWith('/salary_isolated_')) throw new Error('ISOLATED_DATABASE_REQUIRED')
|
|
target = 'local:' + url.pathname
|
|
}
|
|
const directory = fs.lstatSync(path.dirname(file))
|
|
if (!directory.isDirectory() || directory.isSymbolicLink() || (directory.mode & 0o077)) throw new Error('PRIVATE_DIRECTORY_REQUIRED')
|
|
if (mode === 'audit') {
|
|
const manifest = await prisma.$transaction(async db => {
|
|
await db.$executeRawUnsafe('SET TRANSACTION READ ONLY')
|
|
await requireSalaryAccess(actor, true, db)
|
|
const seed = INITIAL_SALARY_POSITIONS[0]
|
|
const row = await db.salaryPositionConfig.findUniqueOrThrow({ where: { id: seed.id } })
|
|
if (row.deletedAt) throw new Error('POSITION_DELETED')
|
|
const templates = await db.performanceSurveyTemplate.findMany({ where: { name: '品牌调性视觉评分(品牌创意主管)', isActive: true, archivedAt: null }, select: { code: true } })
|
|
if (templates.length !== 1) throw new Error('SOURCE_NOT_UNIQUE')
|
|
const before = positionFields(serializePosition(row)), after = structuredClone(before)
|
|
const metric = after.dimensions.flatMap(d => d.metrics).find(m => m.id === seed.value.dimensions[0].metrics[0].id)
|
|
if (!metric || metric.source.kind !== 'survey' || !['visual_brand_tone', templates[0].code].includes(metric.source.templateCode)) throw new Error('SOURCE_CHANGED_MANUALLY')
|
|
metric.source = { kind: 'survey', templateCode: templates[0].code }
|
|
return { format: 1 as const, target, actorUserId: actor, positionId: row.id, beforeRevision: row.revision, before, after,
|
|
snapshot: { position: row, audits: await db.salaryPositionConfigAudit.findMany({ where: { positionId: row.id }, orderBy: { createdAt: 'asc' } }) } }
|
|
}, { isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead })
|
|
const bytes = Buffer.from(JSON.stringify(manifest, null, 2) + '\n')
|
|
fs.writeFileSync(file, bytes, { mode: 0o600, flag: 'wx' })
|
|
console.log(JSON.stringify({ mode, revision: manifest.beforeRevision, changes: canonical(manifest.before) === canonical(manifest.after) ? 0 : 1, manifestSha256: hash(bytes) }))
|
|
return
|
|
}
|
|
if (process.env.SALARY_SURVEY_CONFIRM !== 'UPDATE_MANAGEMENT_VISUAL_SOURCE_ONLY') throw new Error('EXPLICIT_WRITE_FLAG_REQUIRED')
|
|
const stat = fs.lstatSync(file), bytes = fs.readFileSync(file)
|
|
if (!stat.isFile() || stat.isSymbolicLink() || (stat.mode & 0o077) || hash(bytes) !== process.env.EXPECTED_SURVEY_MANIFEST_SHA256) throw new Error('PRIVATE_MANIFEST_HASH_REQUIRED')
|
|
const manifest: Manifest = JSON.parse(bytes.toString('utf8'))
|
|
if (manifest.format !== 1 || manifest.target !== target || manifest.actorUserId !== actor || manifest.positionId !== INITIAL_SALARY_POSITIONS[0].id) throw new Error('MANIFEST_TARGET_MISMATCH')
|
|
await requireSalaryAccess(actor, true)
|
|
const row = await prisma.salaryPositionConfig.findUniqueOrThrow({ where: { id: manifest.positionId } })
|
|
if (row.deletedAt) throw new Error('POSITION_DELETED')
|
|
const fields = positionFields(serializePosition(row)), same = (value: Fields) => canonical(fields) === canonical(value)
|
|
let result: { changed: boolean; revision: number }
|
|
if (mode === 'apply') {
|
|
if (same(manifest.after) && [manifest.beforeRevision, manifest.beforeRevision + 1].includes(row.revision)) result = { changed: false, revision: row.revision }
|
|
else {
|
|
if (!same(manifest.before) || row.revision !== manifest.beforeRevision) throw new Error('REVISION_CONFLICT')
|
|
result = await connectManagementVisualSurvey(actor, manifest.beforeRevision)
|
|
}
|
|
} else {
|
|
if (same(manifest.before) && [manifest.beforeRevision, manifest.beforeRevision + 2].includes(row.revision)) result = { changed: false, revision: row.revision }
|
|
else {
|
|
if (!same(manifest.after) || row.revision !== manifest.beforeRevision + 1) throw new Error('REVISION_CONFLICT')
|
|
const updated = await updateSalaryPosition(row.id, { ...manifest.before, revision: row.revision }, actor)
|
|
result = { changed: true, revision: updated.revision }
|
|
}
|
|
}
|
|
fs.writeFileSync(file + '.' + mode + '.json', JSON.stringify({ mode, ...result, positionId: row.id, actorUserId: actor, at: new Date() }, null, 2), { mode: 0o600 })
|
|
console.log(JSON.stringify({ mode, ...result }))
|
|
}
|
|
main().catch(error => { console.error(error.message); process.exitCode = 1 }).finally(() => prisma.$disconnect())
|