fix(deploy): preserve live runtime for the bounded material image update

This commit is contained in:
WuYongJie 2026-10-29 18:36:29 +08:00
parent 4de34cd352
commit 72674fdc5b
6 changed files with 332 additions and 0 deletions

View File

@ -0,0 +1,15 @@
# 素材图片更新的限定发布
正常发布仍使用完整 Git 源码构建及现有生产门禁。本次用户明确授权本机构建。
现场运行版本为 7e230efd998b20be3e4a05ea423d3aa514b9d1d0,对应完整源码未在权威仓库找到;现场还包含正式分支没有的薪酬、岗位接口和 Prisma 结构。直接发布完整 4de34cd3 镜像会回退这些能力,因此该镜像仅作为修复源码的构建验证,不用于切流。
限定镜像以当前生产镜像为不可变基底,只增加本次修复的三个编译文件、四个对应源码文件,以及发布身份和非敏感溯源清单。基底文件系统层、启动配置、Prisma 结构、前端静态资源和其他业务模块均须保持。scripts/material-image-hotfix-base.json 锁定当前基底和全部输入哈希;基底、文件、AST 结构、补丁次数发生变化均停止。只按 AST 的已验证字符区间修改,不重新生成其他代码。
Docker 从旧式 image store 导出至 containerd store 时会移除仅为空字符串、false 或 null 的旧默认配置项,因此导入 ID 可能变化。必须逐项验证这类默认项、全部 69 个文件系统层及剩余完整运行配置;非默认项丢失或任何业务配置改变均拒绝,不以标签相同代替身份验证。
生成器使用既有锁定的 Next.js 内 Acorn 解析器,只输出一份新的构建目录,不接触账户、工程、上传目录或生产数据库。镜像构建先校验基底七个目标文件、原版本和当前 Prisma 哈希,再覆盖,最后校验全部结果并记录独立的发布配方提交及原修复提交。
镜像经本机验证后通过 SSH 传输;仍执行既有生产部署脚本内相同的生产阶段,包括发布锁、上传排空、存储、桌面连接、worker、预览基线、代理切流、回滚和公网验收。不得使用未核验的镜像、跳过门禁或直接覆盖运行容器中的文件。
此配方仅适用于锁定的这一个线上基底,不能成为通用字符串替换工具。恢复完整现场源码并合入权威分支之前,不得使用旧的正式分支全量镜像覆盖这些现场功能。保留旧镜像及审计证据。

View File

@ -0,0 +1,21 @@
{
"version": 1,
"baseImageId": "sha256:b28607f43d14609ec21ac8979a53889f002d6661b4ab80c69b8b67acdf9cc02b",
"baseCommit": "7e230efd998b20be3e4a05ea423d3aa514b9d1d0",
"sourceCommit": "4de34cd3520999e127a6fc5fc7e3e88ac6f12780",
"schemaHash": "68224c3a12318452878b03ed843eab3752ca4ab8402d71cf60a4c14f881230d9",
"compiled": {
"app/api/external/download/route.js": "6724bf2fdb5f7c70606ed3ac542b5973a56308ba0d45d93ba324322315d33d98",
"app/api/external/product-assets/route.js": "d649789ba6d7a8e24653ba538ac1291e7d86eb52dd395c3c6129d693c4867c96",
"chunks/29.js": "8295cc4dc7a91da38eab6c340c63ff6b81c902a4c1cad54f6c498e90051bdc5b"
},
"sources": {
"app/api/external/download/route.ts": "989e6dff7d4a13d517e598dbf32c1cca8fda894687a2c53796d5b02f34e2c61a",
"app/api/external/product-assets/route.ts": "16602244f793db7c51820cd9bb22d414eb735c215a9d68ed4dc36e008eab5265",
"lib/task-detail-asset-edit.ts": "fdf480af9360334aa6881f3f9ae7f4a7224563ddee6d024806dc2644322b1d02",
"lib/task-detail-change-approval.ts": "0e494bb26dd4ab1c0bfec96156ec93899d6f900de7d37ba8b088b96cea231884"
},
"importedBaseImageId": "sha256:6e70431cffa3b31c98199fc18ad870891c74a2c3607f4f566e6b9298df0f4e72",
"runtimeFingerprint": "7a384a4dfad373975fb3d7b27292506705454a21bea6e9d9ee716393e4c0d481",
"filesystemLayers": 69
}

View File

@ -0,0 +1,34 @@
const fs = require('node:fs')
const crypto = require('node:crypto')
const plan = JSON.parse(fs.readFileSync('/tmp/material-hotfix-plan.json', 'utf8'))
const stage = process.argv[2]
if (!['before', 'after'].includes(stage) || plan.version !== 1 || plan.files.length !== 7) throw Error('Invalid hotfix plan')
const digest = bytes => crypto.createHash('sha256').update(bytes).digest('hex')
const normalized = bytes => Buffer.from(bytes.toString('utf8').replace(/\r\n/g, '\n'))
const allowed = new Set([
'.next/server/chunks/29.js',
'.next/server/app/api/external/download/route.js',
'.next/server/app/api/external/product-assets/route.js',
'app/api/external/download/route.ts', 'app/api/external/product-assets/route.ts',
'lib/task-detail-asset-edit.ts', 'lib/task-detail-change-approval.ts',
])
for (const file of plan.files) {
if (!allowed.delete(file.path)) throw Error('Duplicate or unapproved hotfix path')
const bytes = fs.readFileSync('/app/' + file.path)
if (digest(file.normalizeLf ? normalized(bytes) : bytes) !== file[stage]) throw Error('Image file hash mismatch: ' + file.path)
}
if (allowed.size || digest(normalized(fs.readFileSync('/app/prisma/schema.prisma'))) !== plan.schemaHash) {
throw Error('Existing production schema changed')
}
if (stage === 'before') {
if (fs.readFileSync('/app/DEPLOYMENT_COMMIT', 'utf8').trim() !== plan.baseCommit) throw Error('Production base commit mismatch')
} else {
const commit = process.env.VCS_REF
if (!/^[0-9a-f]{40}$/.test(commit || '') || /^0+$/.test(commit)) throw Error('Exact release recipe commit required')
fs.writeFileSync('/app/DEPLOYMENT_COMMIT', commit + '\n')
fs.chmodSync('/app/DEPLOYMENT_COMMIT', 0o444)
fs.writeFileSync('/app/MATERIAL_IMAGE_HOTFIX.json', JSON.stringify({ ...plan, releaseRecipeCommit: commit }) + '\n')
fs.chmodSync('/app/MATERIAL_IMAGE_HOTFIX.json', 0o444)
for (const file of plan.files) fs.chmodSync('/app/' + file.path, 0o444)
}
console.log('Verified bounded material image hotfix: ' + stage)

View File

@ -0,0 +1,15 @@
# Incident-only. Caller checks this local tag's immutable image ID against the
# adjacent base lock before and after build, and checks unchanged base layers.
FROM youyidian-3d-material:material-base-b28607f43d14
USER root
COPY --chown=root:root verified-plan.json /tmp/material-hotfix-plan.json
COPY --chown=root:root verify.cjs /tmp/material-hotfix-verify.cjs
RUN node /tmp/material-hotfix-verify.cjs before
COPY --chown=root:root overlay/ /app/
ARG VCS_REF
LABEL org.opencontainers.image.revision=$VCS_REF
LABEL com.youyidian.material-hotfix.source-commit=4de34cd3520999e127a6fc5fc7e3e88ac6f12780
LABEL com.youyidian.material-hotfix.base-image=sha256:b28607f43d14609ec21ac8979a53889f002d6661b4ab80c69b8b67acdf9cc02b
RUN VCS_REF="$VCS_REF" node /tmp/material-hotfix-verify.cjs after && \
rm /tmp/material-hotfix-plan.json /tmp/material-hotfix-verify.cjs
USER nextjs

View File

@ -0,0 +1,158 @@
// Incident-only bounded release; normal releases build the complete Git tree.
import fs from 'node:fs'
import path from 'node:path'
import crypto from 'node:crypto'
import { createRequire } from 'node:module'
import { execFileSync } from 'node:child_process'
import { fileURLToPath } from 'node:url'
const require = createRequire(import.meta.url)
const { parse } = require('next/dist/compiled/acorn')
export const sha256 = value => crypto.createHash('sha256').update(value).digest('hex')
const key = node => node?.key?.name ?? node?.key?.value ?? node?.property?.name ?? node?.property?.value
const isFunction = node => ['FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression'].includes(node.type)
const messages = ['素材尚未完成上传,暂不能编辑图片', '素材尚未完成上传,暂不能修改图片']
const ownSources = ['app/api/external/download/route.ts', 'app/api/external/product-assets/route.ts',
'lib/task-detail-asset-edit.ts', 'lib/task-detail-change-approval.ts']
export function walk(node, visit, ancestors = []) {
if (!node || typeof node.type !== 'string') return
visit(node, ancestors)
for (const value of Object.values(node)) {
if (Array.isArray(value)) for (const child of value) walk(child, visit, [...ancestors, node])
else if (value && typeof value === 'object' && value.type) walk(value, visit, [...ancestors, node])
}
}
function insist(value, message) { if (!value) throw new Error(message) }
export function patchCompiled(name, source) {
const ast = parse(source, { ecmaVersion: 'latest' }), edits = []
let guards = 0, selectors = 0, getters = 0, fetches = 0
const insert = (start, text) => edits.push({ start, end: start, text })
if (name === 'chunks/29.js') {
walk(ast, (node, ancestors) => {
if (node.type !== 'Literal' || !messages.includes(node.value)) return
const condition = ancestors.findLast(item => item.type === 'IfStatement')
const owner = ancestors.findLast(isFunction), test = condition?.test
insist(test?.type === 'BinaryExpression' && test.operator === '!==', 'Unexpected upload guard')
const member = test.left.type === 'MemberExpression' ? test.left : test.right
const literal = member === test.left ? test.right : test.left
insist(key(member) === 'taskStatus' && member.object.type === 'Identifier'
&& literal.type === 'Literal' && literal.value === 'completed', 'Unexpected guard operands')
const object = member.object.name
edits.push({ start: test.start, end: test.end,
text: '(' + object + '.isIncompleteShell||(' + source.slice(test.start, test.end)
+ '&&' + object + '.taskStatus!=="fetched"))' })
guards++
let queries = 0
walk(owner, call => {
if (call.type !== 'CallExpression' || call.callee.type !== 'MemberExpression'
|| key(call.callee) !== 'findFirst' || key(call.callee.object) !== 'material') return
const select = call.arguments[0]?.properties?.find(item => key(item) === 'select')?.value
const status = select?.properties?.find(item => key(item) === 'taskStatus')
if (!status) return
insist(!select.properties.some(item => key(item) === 'isIncompleteShell'), 'Selector already patched')
const value = source.slice(status.value.start, status.value.end)
insist(value === '!0' || value === 'true', 'Unexpected selector value')
insert(status.start, 'isIncompleteShell:!0,')
queries++
})
insist(queries === 1, 'Material selector missing or ambiguous')
selectors += queries
})
insist(guards === 2 && selectors === 2, 'Both upload gates must be patched exactly once')
} else {
insist(['app/api/external/download/route.js', 'app/api/external/product-assets/route.js'].includes(name),
'Unapproved compiled target')
walk(ast, (node, ancestors) => {
if (node.type !== 'Property' || key(node) !== 'GET') return
insist(node.value.type === 'ArrowFunctionExpression' && node.value.body.type === 'Identifier',
'Unexpected GET export')
const factory = ancestors.findLast(isFunction), exportedName = node.value.body.name
const functions = []
walk(factory, (item, parents) => {
if (item.type === 'FunctionDeclaration' && item.id.name === exportedName
&& parents.findLast(isFunction) === factory) functions.push(item)
})
insist(functions.length === 1 && functions[0].async, 'GET implementation missing or ambiguous')
const body = functions[0].body
insist(!source.includes('__materialLatestResponse'), 'GET already patched')
insert(body.start + 1, 'const __materialLatestResponse=await(async()=>{')
insert(body.end - 1, '})();__materialLatestResponse.headers.set("Cache-Control","private, no-store");return __materialLatestResponse;')
getters++
})
insist(getters === 1, 'Exactly one GET export is required')
if (name === 'app/api/external/download/route.js') {
walk(ast, (node, ancestors) => {
const owner = ancestors.findLast(isFunction)
if (node.type !== 'CallExpression' || node.callee.type !== 'Identifier'
|| node.callee.name !== 'fetch' || owner?.id?.name !== 'z') return
const options = node.arguments[1]
insist(options?.type === 'ObjectExpression'
&& options.properties.some(item => key(item) === 'headers')
&& !options.properties.some(item => key(item) === 'cache'), 'Unexpected download fetch')
insert(options.start + 1, 'cache:"no-store",')
fetches++
})
insist(fetches === 1, 'Exactly one original single-file fetch is required')
}
}
edits.sort((a, b) => b.start - a.start)
let boundary = source.length, output = source
for (const edit of edits) {
insist(edit.end <= boundary, 'Overlapping source edits')
output = output.slice(0, edit.start) + edit.text + output.slice(edit.end)
boundary = edit.start
}
parse(output, { ecmaVersion: 'latest' })
return { output, counts: { guards, selectors, getters, fetches }, edits }
}
export function createOverlay(input, lock, outputDirectory, sourceRoot) {
insist(lock.version === 1 && /^[0-9a-f]{40}$/.test(lock.sourceCommit)
&& /^[0-9a-f]{40}$/.test(lock.baseCommit), 'Invalid versioned source lock')
insist(JSON.stringify(Object.keys(lock.compiled).sort()) === JSON.stringify([
'app/api/external/download/route.js', 'app/api/external/product-assets/route.js', 'chunks/29.js',
]), 'Unapproved compiled lock set')
insist(input.baseImageId === lock.baseImageId, 'Production image identity changed')
insist(JSON.stringify(Object.keys(input.files).sort()) === JSON.stringify(Object.keys(lock.compiled).sort()),
'Compiled input set changed')
insist(!fs.existsSync(outputDirectory), 'Output directory already exists')
const files = [], results = {}
for (const [name, expected] of Object.entries(lock.compiled)) {
const bytes = Buffer.from(input.files[name].base64, 'base64')
insist(sha256(bytes) === expected, 'Compiled source hash changed: ' + name)
const patched = patchCompiled(name, bytes.toString('utf8'))
results['.next/server/' + name] = Buffer.from(patched.output)
files.push({ path: '.next/server/' + name, before: expected, after: sha256(patched.output),
normalizeLf: false, counts: patched.counts })
}
for (const name of ownSources) {
const bytes = execFileSync('git', ['show', lock.sourceCommit + ':' + name], { cwd: sourceRoot })
const normalized = bytes.toString('utf8').replace(/\r\n/g, '\n')
results[name] = bytes
files.push({ path: name, before: lock.sources[name], after: sha256(normalized), normalizeLf: true })
}
const plan = { version: 1, baseImageId: lock.baseImageId, baseCommit: lock.baseCommit,
sourceCommit: lock.sourceCommit, schemaHash: lock.schemaHash, files }
fs.mkdirSync(outputDirectory)
for (const [name, bytes] of Object.entries(results)) {
const destination = path.join(outputDirectory, 'overlay', name)
fs.mkdirSync(path.dirname(destination), { recursive: true })
fs.writeFileSync(destination, bytes, { flag: 'wx' })
}
fs.writeFileSync(path.join(outputDirectory, 'verified-plan.json'), JSON.stringify(plan, null, 2) + '\n', { flag: 'wx' })
const scripts = path.dirname(fileURLToPath(import.meta.url))
fs.copyFileSync(path.join(scripts, 'material-image-hotfix.Dockerfile'), path.join(outputDirectory, 'Dockerfile'), fs.constants.COPYFILE_EXCL)
fs.copyFileSync(path.join(scripts, 'material-image-hotfix-verify.cjs'), path.join(outputDirectory, 'verify.cjs'), fs.constants.COPYFILE_EXCL)
return plan
}
if (process.argv[1] && fileURLToPath(import.meta.url) === path.resolve(process.argv[1])) {
const [input, output] = process.argv.slice(2)
insist(input && output, 'Usage: node scripts/material-image-hotfix.mjs <observed-input.json> <new-output-directory>')
const lock = JSON.parse(fs.readFileSync(new URL('./material-image-hotfix-base.json', import.meta.url), 'utf8'))
const plan = createOverlay(JSON.parse(fs.readFileSync(input, 'utf8')), lock, path.resolve(output),
path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'))
console.log(JSON.stringify(plan, null, 2))
}

View File

@ -0,0 +1,89 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import vm from 'node:vm'
import { createRequire } from 'node:module'
import { patchCompiled, walk } from './material-image-hotfix.mjs'
const { parse } = createRequire(import.meta.url)('next/dist/compiled/acorn')
const errors = ['素材尚未完成上传,暂不能编辑图片', '素材尚未完成上传,暂不能修改图片']
const fixture = reverse => errors.map((message, index) =>
'async function guard' + index + '(prisma){const r=await prisma.material.findFirst({select:{taskStatus:true,materialType:true}});'
+ 'if(' + (reverse ? '"completed"!==r.taskStatus' : 'r.taskStatus!=="completed"')
+ ')throw new Error("' + message + '");return r;}').join('\n')
for (const reversed of [false, true]) {
test('both compiled gates preserve an explicit allowlist and incomplete shell gate: reversed=' + reversed, async () => {
const patched = patchCompiled('chunks/29.js', fixture(reversed))
assert.deepEqual(patched.counts, { guards: 2, selectors: 2, getters: 0, fetches: 0 })
const context = vm.createContext({})
vm.runInContext(patched.output, context)
for (const status of ['completed', 'fetched', 'pending', 'processing', 'failed', null, 'unknown']) {
for (const isIncompleteShell of [false, true]) {
for (const index of [0, 1]) {
const calls = []
const prisma = { material: { findFirst: async options => {
calls.push(options)
return { taskStatus: status, isIncompleteShell }
} } }
const action = context['guard' + index](prisma)
if (!isIncompleteShell && ['completed', 'fetched'].includes(status)) {
assert.equal((await action).taskStatus, status)
} else await assert.rejects(action, /素材尚未完成上传/)
assert.equal(calls[0].select.isIncompleteShell, true)
}
}
}
assert.throws(() => patchCompiled('chunks/29.js', patched.output))
})
}
test('missing or changed guard, material selector and duplicate guard fail closed', () => {
const valid = fixture(false)
for (const broken of [
valid.replace(errors[0], 'other error'),
valid.replace('taskStatus:true', 'taskStatus:false'),
valid.replace('material.findFirst', 'material.findUnique'),
valid.replace('r.taskStatus!=="completed"', 'r.taskStatus==="completed"'),
valid + valid.replaceAll('guard', 'duplicate'),
]) assert.throws(() => patchCompiled('chunks/29.js', broken))
})
const route = 'const exports={};(function(){function d(a,b){for(const k of Object.keys(b))Object.defineProperty(a,k,{get:b[k]});};'
+ 'd(exports,{GET:()=>handler});async function handler(request){if(request.fail)throw Error("original");'
+ 'if(request.denied)return request.denied;return request.response;}'
+ 'async function z(url,range){return fetch(url,{headers:range?{Range:range}:void 0});}'
+ 'async function unrelated(url,range){return fetch(url,{headers:range?{Range:range}:void 0});}})();'
test('GET wrapper preserves response identity, body, early return and original failures', async () => {
const result = patchCompiled('app/api/external/product-assets/route.js', route)
const context = vm.createContext({})
vm.runInContext(result.output, context)
const get = vm.runInContext('exports.GET', context)
for (const denied of [false, true]) {
const headers = new Map(), response = { headers, body: 'unchanged original bytes' }
assert.equal(await get(denied ? { denied: response } : { response }), response)
assert.equal(headers.get('Cache-Control'), 'private, no-store')
assert.equal(response.body, 'unchanged original bytes')
}
await assert.rejects(get({ fail: true }), /original/)
})
test('only the pinned original single-file fetch gains no-store; Range and other helpers are unchanged', () => {
const result = patchCompiled('app/api/external/download/route.js', route)
assert.deepEqual(result.counts, { guards: 0, selectors: 0, getters: 1, fetches: 1 })
const calls = []
walk(parse(result.output, { ecmaVersion: 'latest' }), (node, ancestors) => {
if (node.type === 'CallExpression' && node.callee.name === 'fetch') {
calls.push({ owner: ancestors.findLast(item => item.type === 'FunctionDeclaration').id.name,
keys: node.arguments[1].properties.map(item => item.key.name) })
}
})
assert.deepEqual(calls, [{ owner: 'z', keys: ['cache', 'headers'] }, { owner: 'unrelated', keys: ['headers'] }])
assert.throws(() => patchCompiled('app/api/external/download/route.js', route.replace('function z(', 'function changed(')))
assert.throws(() => patchCompiled('app/api/external/download/route.js', result.output))
})
test('unknown files and ambiguous GET exports are never patched', () => {
assert.throws(() => patchCompiled('app/other.js', route))
assert.throws(() => patchCompiled('app/api/external/product-assets/route.js', route + route.replaceAll('exports', 'otherExports')))
})