i更新
This commit is contained in:
@@ -0,0 +1,329 @@
|
||||
const assert = require('node:assert/strict')
|
||||
const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
const test = require('node:test')
|
||||
const { createHash, webcrypto } = require('node:crypto')
|
||||
const ts = require('typescript')
|
||||
const vue = require('vue')
|
||||
const { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc')
|
||||
|
||||
globalThis.crypto ??= webcrypto
|
||||
|
||||
function loadModule(filename, imports) {
|
||||
const code = ts.transpileModule(fs.readFileSync(path.join(__dirname, '../src', filename), 'utf8'), {
|
||||
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }
|
||||
}).outputText
|
||||
const exports = {}
|
||||
new Function('require', 'exports', code)((id) => {
|
||||
assert.ok(Object.hasOwn(imports, id), `Unexpected import ${id}`)
|
||||
return imports[id]
|
||||
}, exports)
|
||||
return exports
|
||||
}
|
||||
|
||||
const pdfBytes = Buffer.from('%PDF-1.7\nSigned test bytes\n%%EOF')
|
||||
const file = {
|
||||
filename: 'signed.pdf',
|
||||
content_base64: pdfBytes.toString('base64'),
|
||||
sha256: createHash('sha256').update(pdfBytes).digest('hex')
|
||||
}
|
||||
const status = (changes = {}) => ({
|
||||
enabled: true, required: true, environment: 'sandbox', status: 'pending',
|
||||
status_label: '待签署', can_sign: true, can_download: false, message: '', ...changes
|
||||
})
|
||||
|
||||
test('signing mutations allow 180 seconds and explicitly disable transport replay', async () => {
|
||||
const calls = []
|
||||
const api = loadModule('api/tcm.ts', {
|
||||
'@/utils/request': { default: {
|
||||
post: async (config, options) => { calls.push({ config, options }); return status() }
|
||||
} }
|
||||
})
|
||||
await api.prescriptionEsignStart({ id: 17 })
|
||||
await api.prescriptionEsignComplete({ id: 17 })
|
||||
assert.equal(calls.length, 2)
|
||||
for (const { config, options } of calls) {
|
||||
assert.equal(config.timeout, 180000)
|
||||
assert.equal(options.isOpenRetry, false)
|
||||
assert.equal(options.retryCount, 0)
|
||||
}
|
||||
})
|
||||
|
||||
test('authentication links accept only absolute HTTPS URLs without credentials', () => {
|
||||
const utils = loadModule('utils/prescription-esign.ts', { '@/api/tcm': {} })
|
||||
for (const value of ['javascript:alert(1)', 'http://example.test', '//example.test', 'https://user:secret@example.test', '', null]) {
|
||||
assert.equal(utils.safeEsignAuthUrl(value), '')
|
||||
}
|
||||
for (const host of ['smlt.esign.cn', 'smlfront.esign.cn', 't.esign.cn', 'idverify.esign.cn']) {
|
||||
assert.equal(utils.safeEsignAuthUrl(`https://${host}/verify?token=test`), `https://${host}/verify?token=test`)
|
||||
}
|
||||
assert.equal(utils.safeEsignAuthUrl('https://auth.example.test/session'), '')
|
||||
assert.equal(utils.safeEsignAuthUrl('https://smlfront.esign.cn:8890/identity/login'), 'https://smlfront.esign.cn:8890/identity/login')
|
||||
assert.equal(utils.safeEsignAuthUrl('https://smlfront.esign.cn:444/x'), '')
|
||||
assert.equal(utils.safeEsignAuthUrl('https://smlt.esign.cn:8890/x'), '')
|
||||
})
|
||||
|
||||
test('signed PDF preserves original bytes and requires SHA-256 to match', async () => {
|
||||
const { verifyEsignPdf } = loadModule('utils/prescription-esign.ts', { '@/api/tcm': {} })
|
||||
assert.deepEqual(Buffer.from(await verifyEsignPdf(file)), pdfBytes)
|
||||
await assert.rejects(verifyEsignPdf({ ...file, sha256: '0'.repeat(64) }), /校验失败/)
|
||||
await assert.rejects(verifyEsignPdf({ ...file, sha256: '' }), /校验信息/)
|
||||
await assert.rejects(verifyEsignPdf({ ...file, content_base64: Buffer.from('<html>Error</html>').toString('base64') }), /PDF/)
|
||||
})
|
||||
|
||||
test('successful download writes the verified server bytes into the PDF Blob unchanged', async () => {
|
||||
let downloaded
|
||||
let clicked = false
|
||||
let requestedId
|
||||
const previousDocument = globalThis.document
|
||||
const previousCreate = URL.createObjectURL
|
||||
const previousRevoke = URL.revokeObjectURL
|
||||
URL.createObjectURL = (blob) => { downloaded = blob; return 'blob:verified-pdf' }
|
||||
URL.revokeObjectURL = () => {}
|
||||
const link = { click: () => { clicked = true }, remove() {} }
|
||||
globalThis.document = { createElement: () => link, body: { appendChild() {} } }
|
||||
try {
|
||||
const { downloadOriginalEsignPdf } = loadModule('utils/prescription-esign.ts', {
|
||||
'@/api/tcm': { prescriptionEsignDownload: async ({ id }) => { requestedId = id; return file } }
|
||||
})
|
||||
await downloadOriginalEsignPdf(17)
|
||||
assert.equal(requestedId, 17)
|
||||
assert.equal(clicked, true)
|
||||
assert.equal(link.download, 'signed.pdf')
|
||||
assert.equal(downloaded.type, 'application/pdf')
|
||||
assert.deepEqual(Buffer.from(await downloaded.arrayBuffer()), pdfBytes)
|
||||
} finally {
|
||||
globalThis.document = previousDocument
|
||||
URL.createObjectURL = previousCreate
|
||||
URL.revokeObjectURL = previousRevoke
|
||||
}
|
||||
})
|
||||
|
||||
test('download rechecks the server, blocks pending/unknown states and permits legacy rendering only', async () => {
|
||||
let response = status()
|
||||
let fileRequests = 0
|
||||
const { downloadPrescriptionPdfIfRequired } = loadModule('utils/prescription-esign.ts', {
|
||||
'@/api/tcm': {
|
||||
prescriptionEsignStatus: async ({ id }) => { assert.equal(id, 17); return response },
|
||||
prescriptionEsignDownload: async () => { fileRequests++; return { ...file, sha256: '0'.repeat(64) } }
|
||||
}
|
||||
})
|
||||
for (const state of ['pending', 'authenticating', 'signing', 'uncertain', 'failed', 'voided']) {
|
||||
response = status({ status: state })
|
||||
await assert.rejects(downloadPrescriptionPdfIfRequired(17), /签署/)
|
||||
}
|
||||
assert.equal(fileRequests, 0)
|
||||
response = null
|
||||
await assert.rejects(downloadPrescriptionPdfIfRequired(17), /状态/)
|
||||
response = { status: 'legacy', can_download: false }
|
||||
await assert.rejects(downloadPrescriptionPdfIfRequired(17), /状态/)
|
||||
response = status({ enabled: false, required: false, status: 'legacy' })
|
||||
assert.equal(await downloadPrescriptionPdfIfRequired(17), false)
|
||||
response = status({ status: 'signed', can_download: true })
|
||||
await assert.rejects(downloadPrescriptionPdfIfRequired(17), /校验失败/)
|
||||
assert.equal(fileRequests, 1)
|
||||
await assert.rejects(downloadPrescriptionPdfIfRequired(0), /编号/)
|
||||
})
|
||||
|
||||
test('configuration failures do not downgrade to handwritten mode; retry can restore explicit disabled mode', async () => {
|
||||
let fail = true
|
||||
let calls = 0
|
||||
const { usePrescriptionEsignConfig } = loadModule('hooks/usePrescriptionEsignConfig.ts', {
|
||||
vue,
|
||||
'@/api/tcm': { prescriptionEsignConfig: async () => {
|
||||
calls++
|
||||
if (fail) throw new Error('offline')
|
||||
return { enabled: false, environment: 'sandbox' }
|
||||
} }
|
||||
})
|
||||
const config = usePrescriptionEsignConfig()
|
||||
assert.equal(config.ready.value, false)
|
||||
assert.deepEqual(await Promise.all([config.load(), config.load()]), [false, false])
|
||||
assert.equal(calls, 1)
|
||||
assert.equal(config.ready.value, false)
|
||||
assert.ok(config.error.value)
|
||||
fail = false
|
||||
assert.equal(await config.load(), true)
|
||||
assert.equal(config.ready.value, true)
|
||||
assert.equal(config.enabled.value, false)
|
||||
})
|
||||
|
||||
const panelPath = path.join(__dirname, '../src/components/EsignPrescriptionPanel.vue')
|
||||
const panelSource = parse(fs.readFileSync(panelPath, 'utf8'), { filename: panelPath }).descriptor.scriptSetup.content
|
||||
const ast = ts.createSourceFile('panel.ts', panelSource, ts.ScriptTarget.Latest, true)
|
||||
const panelCode = ast.statements.filter((node) => {
|
||||
if (ts.isImportDeclaration(node)) return false
|
||||
if (ts.isVariableStatement(node)) return !node.declarationList.declarations.some((d) => ['props', 'emit'].includes(d.name.getText(ast)))
|
||||
return true
|
||||
}).map((node) => node.getText(ast)).join('\n')
|
||||
const compiledPanel = ts.transpileModule(panelCode, {
|
||||
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }
|
||||
}).outputText
|
||||
|
||||
function panel(initial = status(), api = {}) {
|
||||
const calls = []
|
||||
const events = []
|
||||
const watchers = []
|
||||
const props = { prescriptionId: 17, initialState: initial }
|
||||
const globals = {
|
||||
ref: vue.ref, computed: vue.computed,
|
||||
watch: (getter, callback) => watchers.push(callback),
|
||||
props, emit: (_, value) => events.push(value),
|
||||
safeEsignAuthUrl: (value) => typeof value === 'string' && value.startsWith('https://') ? value : '',
|
||||
validateEsignStatus: loadModule('utils/prescription-esign.ts', { '@/api/tcm': {} }).validateEsignStatus,
|
||||
downloadPrescriptionPdfIfRequired: async () => {},
|
||||
prescriptionEsignStatus: async (p) => { calls.push(['status', p]); return api.refresh ? api.refresh() : initial },
|
||||
prescriptionEsignStart: async (p) => { calls.push(['start', p]); return api.start ? api.start() : status({ status: 'authenticating', auth_url: 'https://auth.example.test/session' }) },
|
||||
prescriptionEsignComplete: async (p) => { calls.push(['complete', p]); return api.complete ? api.complete() : status({ status: 'signed', can_sign: false, can_download: true }) }
|
||||
}
|
||||
const value = new Function(...Object.keys(globals), `${compiledPanel}\nreturn { state, busy, confirmed, error, authUrl, start, complete, refresh }`)(...Object.values(globals))
|
||||
value.confirmed.value = true // The existing-state tests begin after a successful initial query.
|
||||
return { ...value, props, calls, events, watchers }
|
||||
}
|
||||
|
||||
test('opening an authentication URL does not mark signed; complete uses the server result', async () => {
|
||||
const p = panel()
|
||||
await p.start()
|
||||
assert.equal(p.state.value.status, 'authenticating')
|
||||
assert.equal(p.state.value.can_download, false)
|
||||
assert.ok(p.authUrl.value)
|
||||
assert.deepEqual(p.calls, [['start', { id: 17 }]])
|
||||
await p.complete()
|
||||
assert.equal(p.state.value.status, 'signed')
|
||||
assert.equal(p.events.at(-1).can_download, true)
|
||||
await p.start()
|
||||
assert.equal(p.calls.length, 2, 'server can_sign=false prevents a new signing request')
|
||||
})
|
||||
|
||||
test('failed or cancelled authentication stays pending and remains recoverable', async () => {
|
||||
const p = panel(status({ status: 'authenticating' }), {
|
||||
complete: async () => status({ status: 'authenticating', message: '尚未完成核身' })
|
||||
})
|
||||
await p.complete()
|
||||
assert.equal(p.state.value.status, 'authenticating')
|
||||
assert.equal(p.state.value.can_download, false)
|
||||
const offline = panel(status(), { start: async () => { throw new Error('offline') } })
|
||||
await offline.start()
|
||||
assert.equal(offline.state.value.status, 'pending')
|
||||
assert.match(offline.error.value, /offline/)
|
||||
assert.equal(offline.busy.value, false)
|
||||
await offline.refresh()
|
||||
assert.equal(offline.error.value, '')
|
||||
})
|
||||
|
||||
test('double clicks share one active operation and late results cannot replace another prescription', async () => {
|
||||
let resolve
|
||||
const deferred = new Promise((done) => { resolve = done })
|
||||
const p = panel(status(), { start: () => deferred })
|
||||
const first = p.start()
|
||||
await p.start()
|
||||
assert.equal(p.calls.length, 1)
|
||||
p.props.prescriptionId = 18
|
||||
p.props.initialState = status({ status_label: 'Another prescription' })
|
||||
p.watchers[0]()
|
||||
resolve(status({ status: 'signed', can_download: true }))
|
||||
await first
|
||||
await Promise.resolve()
|
||||
assert.notEqual(p.state.value.status, 'signed')
|
||||
assert.equal(p.events.some((e) => e.status === 'signed'), false)
|
||||
})
|
||||
|
||||
test('preparing capability and malformed responses disable signing until a validated refresh', async () => {
|
||||
const preparing = panel(status({ status: 'authenticating', can_sign: false }))
|
||||
await preparing.start()
|
||||
await preparing.complete()
|
||||
assert.deepEqual(preparing.calls, [])
|
||||
const malformed = panel(status(), { start: async () => ({ status: 'signed', can_download: true }) })
|
||||
await malformed.start()
|
||||
assert.equal(malformed.confirmed.value, false)
|
||||
assert.equal(malformed.state.value.status, 'pending')
|
||||
await malformed.start()
|
||||
assert.equal(malformed.calls.length, 1)
|
||||
await malformed.refresh()
|
||||
assert.equal(malformed.confirmed.value, true)
|
||||
})
|
||||
|
||||
function pageDeclarations(filename, selected, globals) {
|
||||
const fullPath = path.join(__dirname, '../src', filename)
|
||||
const source = parse(fs.readFileSync(fullPath, 'utf8'), { filename: fullPath }).descriptor.scriptSetup.content
|
||||
const ast = ts.createSourceFile('page.ts', source, ts.ScriptTarget.Latest, true)
|
||||
const declarations = new Map()
|
||||
for (const node of ast.statements) {
|
||||
if (ts.isFunctionDeclaration(node) && node.name) declarations.set(node.name.text, node.getText(ast))
|
||||
if (ts.isVariableStatement(node)) {
|
||||
for (const d of node.declarationList.declarations) declarations.set(d.name.getText(ast), `const ${d.getText(ast)}`)
|
||||
}
|
||||
}
|
||||
const compiled = ts.transpileModule(selected.map((key) => {
|
||||
assert.ok(declarations.has(key), `${filename}: missing ${key}`)
|
||||
return declarations.get(key)
|
||||
}).join('\n'), { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText
|
||||
return new Function(...Object.keys(globals), `${compiled}\nreturn { ${selected.join(', ')} }`)(...Object.values(globals))
|
||||
}
|
||||
|
||||
test('shared editor permits an unsigned save only in enabled mode and retains the saved id after detail failure', async () => {
|
||||
for (const enabled of [false, true]) {
|
||||
const requests = []
|
||||
const messages = []
|
||||
const savedPrescription = vue.ref(null)
|
||||
const globals = {
|
||||
saving: vue.ref(false), esignReady: vue.ref(true), esignEnabled: vue.ref(enabled),
|
||||
loadEsignConfig: async () => true,
|
||||
formData: { clinical_diagnosis: 'test diagnosis', herbs: [{ name: 'test herb', dosage: 1 }], doctor_signature: '' },
|
||||
findDuplicateHerbNames: () => [], normalizeHerbRow: (herb) => herb,
|
||||
auxHerbRows: vue.ref([]), savedPrescription,
|
||||
prescriptionAdd: async (payload) => { requests.push(payload); return { id: 17, esign: status() } },
|
||||
prescriptionDetail: async () => { throw new Error('offline') },
|
||||
emit: () => {},
|
||||
feedback: { msgWarning: (m) => messages.push(m), msgSuccess: (m) => messages.push(m), msgError: (m) => messages.push(m) }
|
||||
}
|
||||
const { handleSave } = pageDeclarations('components/tcm-prescription/index.vue', ['handleSave'], globals)
|
||||
await handleSave()
|
||||
assert.equal(requests.length, enabled ? 1 : 0)
|
||||
if (enabled) {
|
||||
assert.equal(savedPrescription.value.id, 17)
|
||||
assert.equal(savedPrescription.value.esign.status, 'pending')
|
||||
assert.equal(requests[0].doctor_signature, '')
|
||||
} else {
|
||||
assert.match(messages[0], /手写/)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test('consumer editor keeps the saved prescription open for signing instead of reporting audit completion', async () => {
|
||||
const messages = []
|
||||
const viewed = []
|
||||
const globals = {
|
||||
formRef: vue.ref({ validate: async () => {} }), submitLoading: vue.ref(false),
|
||||
esignReady: vue.ref(true), esignEnabled: vue.ref(true), loadEsignConfig: async () => true,
|
||||
editForm: { herbs: [{ name: 'test herb', dosage: 1 }], doctor_signature: '' },
|
||||
editMode: vue.ref('add'), showEdit: vue.ref(true), herbValidationLabel: () => 'test herb',
|
||||
prescriptionAdd: async () => ({ id: 17, esign: status() }),
|
||||
prescriptionEdit: async () => { throw new Error('wrong API') },
|
||||
handleView: async (row) => viewed.push(row), getLists: () => {},
|
||||
feedback: { msgSuccess: (m) => messages.push(m), msgError: (m) => messages.push(m) }
|
||||
}
|
||||
const { handleSubmit } = pageDeclarations('views/consumer/prescription/index.vue', ['handleSubmit'], globals)
|
||||
await handleSubmit()
|
||||
assert.equal(viewed[0].id, 17)
|
||||
assert.equal(viewed[0].esign.status, 'pending')
|
||||
assert.equal(globals.showEdit.value, true)
|
||||
assert.match(messages[0], /核身签署/)
|
||||
})
|
||||
|
||||
for (const filename of [
|
||||
'components/EsignPrescriptionPanel.vue',
|
||||
'components/tcm-prescription/index.vue',
|
||||
'views/consumer/prescription/index.vue',
|
||||
'views/consumer/prescription/order_list.vue',
|
||||
'views/consumer/prescription/order_list_h5.vue'
|
||||
]) {
|
||||
test(`${filename}: compiles the integrated signing controls`, () => {
|
||||
const fullPath = path.join(__dirname, '../src', filename)
|
||||
const { descriptor, errors } = parse(fs.readFileSync(fullPath, 'utf8'), { filename: fullPath })
|
||||
assert.deepEqual(errors, [])
|
||||
const script = compileScript(descriptor, { id: filename })
|
||||
const template = compileTemplate({ source: descriptor.template.content, filename: fullPath, id: filename, compilerOptions: { bindingMetadata: script.bindings } })
|
||||
assert.deepEqual(template.errors, [])
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user