支持自部署需求管理、交付流程与飞书集成
This commit is contained in:
1 parent
2149aeb6ed
commit
51a2e548f2
152 files changed
+8652
-6394
No files matched your search
@@ -0,0 +1,110 @@
|
||||
"""Administrator demand visibility without ownership or draft leakage."""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
from playwright.sync_api import sync_playwright, expect
|
||||
|
||||
origin=os.environ['APP_URL']
|
||||
assert urlparse(origin).hostname=='127.0.0.1'
|
||||
assert Path(os.environ['DATA_DIR']).name.startswith('demand-scope-browser-db-')
|
||||
output=Path('/private/tmp/demand-admin-visibility-qa');output.mkdir(exist_ok=True)
|
||||
fields={'title':'','project':'订单平台','module':'订单查询','type':'新增功能','proposer':'业务成员','department':'业务部','source':'本地回归','owner':'业务成员','background':'当前需要人工查询订单','impact':'日常运营人员','goal':'按状态筛选订单','expectedDate':'','noFixedDate':True,'dateReason':'','scope':'','outOfScope':'','criteria':'筛选后仅显示符合状态的订单','priority':'P2','priorityReason':'减少重复操作','dataSource':'','dataContact':'','noData':True,'risk':'无','pending':'无','references':'','version':'v1.0'}
|
||||
checks=[]
|
||||
with sync_playwright() as p:
|
||||
browser=p.chromium.launch(headless=True,channel='chrome')
|
||||
admin=browser.new_context(viewport={'width':1440,'height':1000},accept_downloads=True)
|
||||
def post(context,path,data):
|
||||
response=context.request.post(origin+path,data=data,headers={'Origin':origin})
|
||||
assert response.ok,(response.status,response.text())
|
||||
return response.json()
|
||||
post(admin,'/api/auth/login',{'username':'scope_qa','password':os.environ['INITIAL_ADMIN_PASSWORD']})
|
||||
post(admin,'/api/auth/password',{'currentPassword':os.environ['INITIAL_ADMIN_PASSWORD'],'newPassword':os.environ['QA_PASSWORD']})
|
||||
temporary=secrets.token_urlsafe(24);current=secrets.token_urlsafe(24)
|
||||
post(admin,'/api/admin/users',{'username':'business_qa','displayName':'业务成员','password':temporary,'role':'user'})
|
||||
business=browser.new_context(viewport={'width':1440,'height':1000})
|
||||
post(business,'/api/auth/login',{'username':'business_qa','password':temporary})
|
||||
post(business,'/api/auth/password',{'currentPassword':temporary,'newPassword':current})
|
||||
upload=business.request.post(origin+'/api/attachments',headers={'Origin':origin},multipart={'file':{'name':'业务说明.txt','mimeType':'text/plain','buffer':'管理员可核对的正式附件'.encode()}})
|
||||
assert upload.ok
|
||||
attachment=upload.json()['attachment']
|
||||
def create(context,title,mode='review',attachment_ids=None):
|
||||
return post(context,'/api/demands',{'action':'create','mode':mode,'fields':{**fields,'title':title},'attachmentIds':attachment_ids or []})['demand']
|
||||
observed=create(business,'其他同事的正式需求',attachment_ids=[attachment['id']])
|
||||
post(admin,'/api/admin/users',{'username':'legacy_dev','displayName':'历史开发','password':secrets.token_urlsafe(24),'role':'user'})
|
||||
post(business,'/api/demands',{'action':'assign-developer','id':observed['id'],'revision':observed['revision'],'username':'legacy_dev'})
|
||||
create(business,'业务成员的私有草稿','draft')
|
||||
assigned=create(business,'管理员负责开发的需求')
|
||||
assert assigned['review']['developer']['username']=='scope_qa'
|
||||
create(admin,'管理员自己的正式需求')
|
||||
create(admin,'管理员自己的草稿','draft')
|
||||
page=admin.new_page();errors=[]
|
||||
page.on('pageerror',lambda error:errors.append(str(error)))
|
||||
page.goto(origin);page.wait_for_load_state('networkidle')
|
||||
nav=page.get_by_role('navigation',name='主导航')
|
||||
expect(nav.get_by_role('button',name='全部需求',exact=True)).to_be_visible()
|
||||
expect(page.locator('.stats').get_by_role('button',name='我的需求 2',exact=True)).to_be_visible()
|
||||
expect(page.locator('.stats').get_by_role('button',name='待我处理 2',exact=True)).to_be_visible()
|
||||
expect(page.get_by_role('button',name='其他同事的正式需求',exact=True)).not_to_be_attached()
|
||||
checks.append('personal dashboard totals and tasks exclude administrator-only observations')
|
||||
|
||||
nav.get_by_role('button',name='全部需求',exact=True).click()
|
||||
expect(page.get_by_role('heading',name='全部需求',exact=True)).to_be_visible()
|
||||
expect(page.locator('tbody tr')).to_have_count(3)
|
||||
expect(page.get_by_role('button',name='其他同事的正式需求',exact=True)).to_be_visible()
|
||||
expect(page.get_by_text('业务成员的私有草稿',exact=True)).not_to_be_attached()
|
||||
expect(page.get_by_text('管理员自己的草稿',exact=True)).not_to_be_attached()
|
||||
page.get_by_label('搜索需求',exact=True).fill('其他同事')
|
||||
expect(page.locator('tbody tr')).to_have_count(1)
|
||||
page.get_by_label('搜索需求',exact=True).fill('')
|
||||
page.screenshot(path=str(output/'all-demands-desktop.png'),animations='disabled')
|
||||
page.get_by_role('button',name='其他同事的正式需求',exact=True).click()
|
||||
expect(page.get_by_text('管理员查看模式:可查看需求、评审记录和附件,修改及确认由对应责任人操作。',exact=True)).to_be_visible()
|
||||
for name in ['补充信息','取消需求','指定开发责任人','提交方案供业务确认','确认方案','退回修改']:
|
||||
expect(page.get_by_role('button',name=name,exact=True)).not_to_be_attached()
|
||||
with page.expect_download() as download_event:
|
||||
page.get_by_role('link',name='业务说明.txt',exact=True).click()
|
||||
download=download_event.value
|
||||
assert download.suggested_filename=='业务说明.txt'
|
||||
assert Path(download.path()).read_bytes()=='管理员可核对的正式附件'.encode()
|
||||
page.screenshot(path=str(output/'readonly-detail-desktop.png'),animations='disabled')
|
||||
page.get_by_role('button',name='关闭需求详情',exact=True).click()
|
||||
checks.append('all formal demands can be searched and viewed with exact attachment downloads and no write controls')
|
||||
|
||||
nav.get_by_role('button',name='我的需求',exact=True).click()
|
||||
expect(page.locator('tbody tr')).to_have_count(2)
|
||||
expect(page.get_by_role('button',name='其他同事的正式需求',exact=True)).not_to_be_attached()
|
||||
nav.get_by_role('button',name='待我处理',exact=True).click()
|
||||
expect(page.locator('tbody tr')).to_have_count(2)
|
||||
nav.get_by_role('button',name='草稿箱',exact=True).click()
|
||||
expect(page.locator('tbody tr')).to_have_count(1)
|
||||
expect(page.get_by_role('button',name='管理员自己的草稿',exact=True)).to_be_visible()
|
||||
checks.append('my demands retain owner/developer participation while the draft box stays private')
|
||||
|
||||
for width in [390,320]:
|
||||
page.set_viewport_size({'width':width,'height':844})
|
||||
nav.get_by_role('button',name='全部需求',exact=True).click()
|
||||
expect(page.get_by_role('button',name='其他同事的正式需求',exact=True)).to_be_visible()
|
||||
assert page.evaluate('document.documentElement.scrollWidth<=window.innerWidth+1'),f'page overflow at {width}px'
|
||||
page.screenshot(path=str(output/f'all-demands-mobile-{width}.png'),animations='disabled')
|
||||
page.set_viewport_size({'width':390,'height':844})
|
||||
page.get_by_role('button',name='其他同事的正式需求',exact=True).click()
|
||||
expect(page.get_by_text('管理员查看模式:可查看需求、评审记录和附件,修改及确认由对应责任人操作。',exact=True)).to_be_visible()
|
||||
page.screenshot(path=str(output/'readonly-detail-mobile.png'),animations='disabled')
|
||||
page.get_by_role('button',name='关闭需求详情',exact=True).click()
|
||||
checks.append('administrator navigation and readonly details work at mobile widths')
|
||||
|
||||
member_page=business.new_page();member_page.on('pageerror',lambda error:errors.append(str(error)))
|
||||
member_page.goto(origin);member_page.wait_for_load_state('networkidle')
|
||||
expect(member_page.get_by_role('navigation',name='主导航').get_by_role('button',name='全部需求',exact=True)).not_to_be_attached()
|
||||
expect(member_page.get_by_role('button',name='管理员自己的正式需求',exact=True)).not_to_be_attached()
|
||||
member_page.get_by_role('button',name='其他同事的正式需求',exact=True).click()
|
||||
expect(member_page.get_by_role('button',name='指定开发责任人',exact=True)).not_to_be_attached()
|
||||
expect(member_page.get_by_role('button',name='补充信息',exact=True)).to_be_visible()
|
||||
expect(member_page.get_by_role('button',name='取消需求',exact=True)).to_be_visible()
|
||||
checks.append('business users keep their original access and editing controls without an administrator entry')
|
||||
assert not errors,errors
|
||||
print(json.dumps({'result':'passed','checks':checks,'screenshots':str(output)},ensure_ascii=False),flush=True)
|
||||
browser.close()
|
||||
@@ -0,0 +1,183 @@
|
||||
"""Browser regressions against a disposable local production instance.
|
||||
|
||||
Requires Python Playwright and APP_URL, INITIAL_ADMIN_PASSWORD, QA_PASSWORD.
|
||||
Only accepts the temporary DATA_DIR created by the isolated test runner.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
from playwright.sync_api import sync_playwright, expect
|
||||
|
||||
origin = os.environ['APP_URL']
|
||||
assert urlparse(origin).hostname == '127.0.0.1'
|
||||
assert Path(os.environ['DATA_DIR']).name.startswith('demand-scope-browser-db-')
|
||||
output = Path(os.environ.get('ATTACHMENT_QA_OUTPUT', '/private/tmp/attachment-fixes-qa'))
|
||||
output.mkdir(exist_ok=True)
|
||||
checks = []
|
||||
|
||||
|
||||
def post(context, path, data):
|
||||
response = context.request.post(origin + path, data=data, headers={'Origin': origin})
|
||||
assert response.ok, (response.status, response.text())
|
||||
return response.json()
|
||||
|
||||
|
||||
def new_form(page, title):
|
||||
page.get_by_role('button', name=re.compile('登记新需求$')).first.click()
|
||||
page.get_by_label(re.compile('^需求标题')).fill(title)
|
||||
page.get_by_role('button', name=re.compile('数据与参考材料')).click()
|
||||
|
||||
|
||||
def close_form(page):
|
||||
page.get_by_role('button', name='关闭登记窗口', exact=True).click()
|
||||
page.get_by_role('button', name='放弃修改并关闭', exact=True).click()
|
||||
expect(page.get_by_role('dialog')).not_to_be_attached()
|
||||
|
||||
|
||||
def upload(context, name):
|
||||
response = context.request.post(origin + '/api/attachments', headers={'Origin': origin}, multipart={
|
||||
'file': {'name': name, 'mimeType': 'text/plain', 'buffer': b'attachment test'},
|
||||
})
|
||||
assert response.status == 201, response.text()
|
||||
return response.json()['attachment']
|
||||
|
||||
|
||||
def cleanup(context, files):
|
||||
for file in files:
|
||||
response = context.request.delete(origin + '/api/attachments/' + file['id'], headers={'Origin': origin})
|
||||
assert response.ok, response.text()
|
||||
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True, channel='chrome')
|
||||
context = browser.new_context(viewport={'width': 1440, 'height': 1000})
|
||||
post(context, '/api/auth/login', {'username': 'scope_qa', 'password': os.environ['INITIAL_ADMIN_PASSWORD']})
|
||||
post(context, '/api/auth/password', {'currentPassword': os.environ['INITIAL_ADMIN_PASSWORD'], 'newPassword': os.environ['QA_PASSWORD']})
|
||||
first = context.new_page()
|
||||
second = context.new_page()
|
||||
errors = []
|
||||
first.on('pageerror', lambda error: errors.append(str(error)))
|
||||
second.on('pageerror', lambda error: errors.append(str(error)))
|
||||
for page in [first, second]:
|
||||
page.goto(origin)
|
||||
page.wait_for_load_state('networkidle')
|
||||
|
||||
new_form(first, '窗口 A:保留正在使用的附件')
|
||||
first.get_by_label('选择文件附件', exact=True).set_input_files({
|
||||
'name': 'A-still-editing.txt', 'mimeType': 'text/plain', 'buffer': b'demand A content',
|
||||
})
|
||||
expect(first.get_by_role('button', name='上传附件', exact=True)).to_be_enabled()
|
||||
own_file = context.request.get(origin + '/api/attachments').json()['attachments'][0]
|
||||
new_form(second, '窗口 B:取消不影响窗口 A')
|
||||
second.get_by_text('找回未保存的附件(1)', exact=True).click()
|
||||
second.get_by_role('button', name='选用 A-still-editing.txt', exact=True).click()
|
||||
deletes = []
|
||||
second.on('request', lambda request: deletes.append(request.url) if request.method == 'DELETE' else None)
|
||||
close_form(second)
|
||||
assert not deletes, deletes
|
||||
assert context.request.get(origin + '/api/attachments/' + own_file['id']).body() == b'demand A content'
|
||||
checks.append('cancelling a second window does not delete a recovered attachment')
|
||||
|
||||
new_form(second, '窗口 B:移除找回附件仅取消选用')
|
||||
second.get_by_text('找回未保存的附件(1)', exact=True).click()
|
||||
second.get_by_role('button', name='选用 A-still-editing.txt', exact=True).click()
|
||||
second.get_by_role('button', name='移除 A-still-editing.txt', exact=True).click()
|
||||
close_form(second)
|
||||
assert not deletes, deletes
|
||||
first.get_by_role('button', name='保存草稿', exact=True).click()
|
||||
expect(first.get_by_role('heading', name='窗口 A:保留正在使用的附件', exact=True)).to_be_attached()
|
||||
record = context.request.get(origin + '/api/demands').json()['demands'][0]
|
||||
assert record['attachments'][0]['id'] == own_file['id']
|
||||
checks.append('removing a recovered selection preserves the original and the first window can save')
|
||||
|
||||
new_form(second, '本窗口新上传仍可清理')
|
||||
second.get_by_label('选择文件附件', exact=True).set_input_files({
|
||||
'name': 'new-in-B.txt', 'mimeType': 'text/plain', 'buffer': b'new upload',
|
||||
})
|
||||
expect(second.get_by_role('button', name='上传附件', exact=True)).to_be_enabled()
|
||||
own_new = context.request.get(origin + '/api/attachments').json()['attachments'][0]
|
||||
with second.expect_response(lambda response: own_new['id'] in response.url and response.request.method == 'DELETE') as removed:
|
||||
close_form(second)
|
||||
assert removed.value.status == 200
|
||||
assert context.request.get(origin + '/api/attachments/' + own_new['id']).status == 404
|
||||
checks.append('cancelling still cleans up files newly uploaded by that window')
|
||||
|
||||
staged = [upload(context, f'previous-{i}.txt') for i in range(10)]
|
||||
failure_mode = {'enabled': True}
|
||||
listing_calls = []
|
||||
|
||||
def fail_listing(route):
|
||||
if route.request.method == 'GET':
|
||||
listing_calls.append(route.request.url)
|
||||
if failure_mode['enabled']:
|
||||
route.fulfill(status=503, content_type='application/json', body='{"error":"模拟暂时无法加载"}')
|
||||
return
|
||||
route.continue_()
|
||||
|
||||
second.route('**/api/attachments', fail_listing)
|
||||
new_form(second, '加载失败后保留表单并重试')
|
||||
expect(second.get_by_text('未保存附件列表加载失败:模拟暂时无法加载', exact=True)).to_be_attached()
|
||||
expect(second.get_by_role('button', name='重新加载未保存附件', exact=True)).to_be_enabled()
|
||||
second.set_viewport_size({'width': 390, 'height': 844})
|
||||
second.get_by_role('button', name='重新加载未保存附件', exact=True).scroll_into_view_if_needed()
|
||||
assert second.get_by_role('dialog').evaluate('(el)=>el.scrollWidth<=el.clientWidth+1')
|
||||
second.screenshot(path=str(output / 'recovery-error-mobile.png'), animations='disabled')
|
||||
failure_mode['enabled'] = False
|
||||
second.get_by_role('button', name='重新加载未保存附件', exact=True).click()
|
||||
expect(second.get_by_text('找回未保存的附件(10)', exact=True)).to_be_attached()
|
||||
expect(second.get_by_role('button', name='重新加载未保存附件', exact=True)).not_to_be_attached()
|
||||
second.get_by_text('找回未保存的附件(10)', exact=True).click()
|
||||
second.get_by_role('button', name='选用 previous-0.txt', exact=True).click()
|
||||
second.get_by_role('button', name='保存草稿', exact=True).click()
|
||||
expect(second.get_by_role('heading', name='加载失败后保留表单并重试', exact=True)).to_be_attached()
|
||||
saved = context.request.get(origin + '/api/demands').json()['demands'][0]
|
||||
assert saved['fields']['title'] == '加载失败后保留表单并重试'
|
||||
assert saved['attachments'][0]['id'] == staged[0]['id']
|
||||
checks.append('manual retry loads recovered files and preserves all current form input')
|
||||
cleanup(context, staged[1:])
|
||||
second.get_by_role('button', name='关闭需求详情', exact=True).click()
|
||||
|
||||
second.set_viewport_size({'width': 1440, 'height': 1000})
|
||||
new_form(second, '达到暂存上限后自动刷新')
|
||||
expect(second.get_by_role('button', name='刷新未保存附件', exact=True)).to_be_enabled()
|
||||
assert second.get_by_text(re.compile('找回未保存的附件')).count() == 0
|
||||
# Another window uploads after this form loaded its initially empty list.
|
||||
staged = [upload(context, f'concurrent-{i}.txt') for i in range(10)]
|
||||
calls_before = len(listing_calls)
|
||||
second.get_by_label('选择文件附件', exact=True).set_input_files([
|
||||
{'name': 'quota-1.txt', 'mimeType': 'text/plain', 'buffer': b'one'},
|
||||
{'name': 'quota-2.txt', 'mimeType': 'text/plain', 'buffer': b'two'},
|
||||
])
|
||||
expect(second.get_by_role('button', name='上传附件', exact=True)).to_be_enabled()
|
||||
expect(second.get_by_text(re.compile('未保存附件已达 10 个'))).to_be_attached()
|
||||
expect(second.get_by_role('button', name='选用 concurrent-0.txt', exact=True)).to_be_visible()
|
||||
assert len(listing_calls) == calls_before + 1
|
||||
expect(second.get_by_text('本批剩余文件尚未上传,请先选用或清理未保存附件,再重新选择文件。', exact=True)).to_be_attached()
|
||||
second.get_by_text('找回未保存的附件(10)', exact=True).scroll_into_view_if_needed()
|
||||
second.locator('.toast').wait_for(state='hidden')
|
||||
second.screenshot(path=str(output / 'quota-recovery-desktop.png'), animations='disabled')
|
||||
checks.append('staging quota rejection refreshes and opens recovery without retrying the full batch')
|
||||
close_form(second)
|
||||
cleanup(context, staged)
|
||||
|
||||
failure_mode['enabled'] = True
|
||||
new_form(second, '自动刷新失败仍可手动重试')
|
||||
expect(second.get_by_role('button', name='重新加载未保存附件', exact=True)).to_be_enabled()
|
||||
staged = [upload(context, f'retry-{i}.txt') for i in range(10)]
|
||||
calls_before = len(listing_calls)
|
||||
second.get_by_label('选择文件附件', exact=True).set_input_files({'name': 'quota-again.txt', 'mimeType': 'text/plain', 'buffer': b'file'})
|
||||
expect(second.get_by_role('button', name='上传附件', exact=True)).to_be_enabled()
|
||||
expect(second.get_by_role('button', name='重新加载未保存附件', exact=True)).to_be_enabled()
|
||||
assert len(listing_calls) == calls_before + 1
|
||||
failure_mode['enabled'] = False
|
||||
second.get_by_role('button', name='重新加载未保存附件', exact=True).click()
|
||||
expect(second.get_by_role('button', name='选用 retry-0.txt', exact=True)).to_be_visible()
|
||||
close_form(second)
|
||||
cleanup(context, staged)
|
||||
checks.append('a failed automatic recovery refresh remains manually retryable')
|
||||
|
||||
assert not errors, errors
|
||||
print(json.dumps({'result': 'passed', 'checks': checks, 'screenshots': str(output)}, ensure_ascii=False), flush=True)
|
||||
browser.close()
|
||||
@@ -0,0 +1,104 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { after, before, test } from 'node:test';
|
||||
import { mkdtempSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import { closeDatabases, getDatabase } from '../lib/server/database.ts';
|
||||
import { attachmentIds, storeUpload, syncDemandAttachments, commitDemandAttachments, downloadAttachment, deleteStagedAttachment, listStagedAttachments } from '../lib/server/attachments.ts';
|
||||
import { MAX_ATTACHMENT_BYTES } from '../lib/attachments.ts';
|
||||
import { emptyFields, type Demand } from '../lib/demand.ts';
|
||||
|
||||
const directory = mkdtempSync(join(tmpdir(), 'demand-attachments-test-'));
|
||||
const previousEnvironment = { ...process.env };
|
||||
let ownerId: string;
|
||||
before(() => {
|
||||
process.env.DATA_DIR = directory;
|
||||
process.env.APP_URL = 'https://attachments.example.test';
|
||||
process.env.INITIAL_ADMIN_USERNAME = 'attachment_owner';
|
||||
process.env.INITIAL_ADMIN_PASSWORD = 'Temporary test password 48362';
|
||||
ownerId = getDatabase().prepare('SELECT id FROM accounts').first<{ id: string }>()!.id;
|
||||
});
|
||||
after(() => { closeDatabases(); process.env = previousEnvironment; rmSync(directory, { recursive: true, force: true }); });
|
||||
const now = () => new Date().toISOString();
|
||||
function record(): Demand { return { id: randomUUID(), revision: 1, fields: { ...emptyFields }, status: '草稿', reviewReady: false, createdAt: now(), updatedAt: now(), history: [], changes: [] }; }
|
||||
function insert(d: Demand) { getDatabase().prepare('INSERT INTO demands (id, owner_id, payload, updated_at) VALUES (?, ?, ?, ?)').bind(d.id, ownerId, JSON.stringify(d), now()).run(); }
|
||||
function save(d: Demand, ids: string[]) {
|
||||
getDatabase().transaction(() => {
|
||||
syncDemandAttachments(d, ownerId, ids, now());
|
||||
getDatabase().prepare('UPDATE demands SET payload = ? WHERE id = ?').bind(JSON.stringify(d), d.id).run();
|
||||
commitDemandAttachments(d, ownerId);
|
||||
});
|
||||
}
|
||||
|
||||
test('version 1 databases gain attachment storage without changing existing accounts or demands', () => {
|
||||
const d = record(); insert(d); closeDatabases();
|
||||
const native = new DatabaseSync(join(directory, 'demand-center.sqlite'));
|
||||
native.exec('DROP TABLE attachments; DROP TABLE feishu_notifications; DROP TABLE feishu_oauth_states; DROP TABLE feishu_identities; PRAGMA user_version = 1;'); native.close();
|
||||
const database = getDatabase();
|
||||
assert.equal(database.prepare('PRAGMA user_version').first<{ user_version: number }>()!.user_version, 3);
|
||||
assert.equal(database.prepare('SELECT id FROM accounts').first<{ id: string }>()!.id, ownerId);
|
||||
assert.equal(database.prepare('SELECT id FROM demands WHERE id = ?').bind(d.id).first<{ id: string }>()!.id, d.id);
|
||||
assert.equal(listStagedAttachments(ownerId).length, 0);
|
||||
});
|
||||
|
||||
test('uploads enforce size, filename and attachment count; staged data stays private and recoverable', () => {
|
||||
assert.throws(() => storeUpload(ownerId, 'empty.txt', new Uint8Array()), /空文件/);
|
||||
assert.throws(() => storeUpload(ownerId, 'large.bin', new Uint8Array(MAX_ATTACHMENT_BYTES + 1)), /20 MB/);
|
||||
assert.throws(() => attachmentIds(Array.from({ length: 11 }, () => randomUUID())), /最多 10/);
|
||||
const ids = Array.from({ length: 10 }, (_, i) => storeUpload(ownerId, `文件${i}.txt`, new Uint8Array([i])));
|
||||
assert.equal(listStagedAttachments(ownerId).length, 10);
|
||||
assert.throws(() => storeUpload(ownerId, 'extra.txt', new Uint8Array([1])), /未保存附件/);
|
||||
assert.throws(() => downloadAttachment(ids[0].id, { userId: 'unrelated-account', role: 'user' }), /没有访问权限/);
|
||||
assert.throws(() => attachmentIds([ids[0].id, ids[0].id]), /附件列表无效/);
|
||||
ids.forEach(file => deleteStagedAttachment(file.id, ownerId));
|
||||
});
|
||||
|
||||
test('failed demand saves do not claim uploads, and bound files cannot be stolen by another demand', () => {
|
||||
const d = record(); insert(d);
|
||||
const file = storeUpload(ownerId, '../需求说明\n.txt', new Uint8Array([1, 2, 3]));
|
||||
assert.equal(file.name, '.._需求说明_.txt');
|
||||
assert.throws(() => getDatabase().transaction(() => {
|
||||
syncDemandAttachments(d, ownerId, [file.id], now());
|
||||
commitDemandAttachments(d, ownerId);
|
||||
throw new Error('Simulated failed save');
|
||||
}), /Simulated/);
|
||||
assert.equal(listStagedAttachments(ownerId).some(item => item.id === file.id), true);
|
||||
save(d, [file.id]);
|
||||
assert.throws(() => deleteStagedAttachment(file.id, ownerId), /已保存/);
|
||||
const other = record(); insert(other);
|
||||
assert.throws(() => save(other, [file.id]), /附件已失效或无法访问/);
|
||||
save(d, []);
|
||||
assert.throws(() => downloadAttachment(file.id, { userId: ownerId, role: 'user' }), /找不到/);
|
||||
});
|
||||
|
||||
test('expired uploads are rejected and removed during the next upload', () => {
|
||||
const file = storeUpload(ownerId, 'expired.txt', new Uint8Array([1]));
|
||||
getDatabase().prepare('UPDATE attachments SET created_at = ? WHERE id = ?').bind('2000-01-01T00:00:00Z', file.id).run();
|
||||
const d = record(); insert(d);
|
||||
assert.throws(() => save(d, [file.id]), /附件已失效/);
|
||||
assert.throws(() => downloadAttachment(file.id, { userId: ownerId, role: 'user' }), /找不到/);
|
||||
const next = storeUpload(ownerId, 'next.txt', new Uint8Array([2]));
|
||||
assert.equal(getDatabase().prepare('SELECT id FROM attachments WHERE id = ?').bind(file.id).first(), null);
|
||||
deleteStagedAttachment(next.id, ownerId);
|
||||
});
|
||||
|
||||
test('administrator downloads follow formal-demand visibility and never expose private drafts', () => {
|
||||
const admin = { userId: 'observing-admin', role: 'admin' as const };
|
||||
const other = { userId: 'unrelated-user', role: 'user' as const };
|
||||
const file = storeUpload(ownerId, '管理员查看范围.txt', new Uint8Array([10, 20, 30]));
|
||||
assert.throws(() => downloadAttachment(file.id, admin), /没有访问权限/);
|
||||
const d = record();
|
||||
// Even a stale developer assignment must not make a private draft visible.
|
||||
d.review = { developer: { userId: admin.userId, username: 'admin', displayName: '管理员' }, proposals: [] };
|
||||
insert(d); save(d, [file.id]);
|
||||
assert.throws(() => downloadAttachment(file.id, admin), /没有访问权限/);
|
||||
assert.deepEqual([...downloadAttachment(file.id, { userId: ownerId, role: 'admin' }).bytes], [10, 20, 30]);
|
||||
d.status = '待评审'; delete d.review; save(d, [file.id]);
|
||||
assert.deepEqual([...downloadAttachment(file.id, admin).bytes], [10, 20, 30]);
|
||||
assert.throws(() => downloadAttachment(file.id, other), /没有访问权限/);
|
||||
d.status = '草稿'; save(d, [file.id]);
|
||||
assert.throws(() => downloadAttachment(file.id, admin), /没有访问权限/);
|
||||
save(d, []);
|
||||
});
|
||||
@@ -0,0 +1,203 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { after, before, test } from 'node:test';
|
||||
import { mkdtempSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { closeDatabases, getDatabase, type AccountRow } from '../lib/server/database.ts';
|
||||
import { hashPassword, verifyPassword } from '../lib/server/password.ts';
|
||||
import {
|
||||
AuthError, authenticateSession, changeAccountPassword, createAccount, isSameOrigin,
|
||||
listAccounts, loginWithPassword, revokeSession, sessionCookie, updateAccount,
|
||||
} from '../lib/server/auth.ts';
|
||||
|
||||
const directory = mkdtempSync(join(tmpdir(), 'demand-auth-tests-'));
|
||||
const originalEnvironment = { ...process.env };
|
||||
const initialPassword = 'Initial test password 9274';
|
||||
let adminId: string;
|
||||
let adminToken: string;
|
||||
|
||||
before(() => {
|
||||
process.env.DATA_DIR = directory;
|
||||
process.env.APP_URL = 'https://demands.example.test';
|
||||
process.env.INITIAL_ADMIN_USERNAME = 'test.admin';
|
||||
process.env.INITIAL_ADMIN_PASSWORD = initialPassword;
|
||||
process.env.INITIAL_ADMIN_DISPLAY_NAME = '测试管理员';
|
||||
delete process.env.LOGIN_CLIENT_IP_HEADER;
|
||||
});
|
||||
after(() => {
|
||||
closeDatabases();
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
process.env = originalEnvironment;
|
||||
});
|
||||
|
||||
test('scrypt hashes are salted and reject altered or malformed values', async () => {
|
||||
const first = await hashPassword(initialPassword);
|
||||
const second = await hashPassword(initialPassword);
|
||||
assert.notEqual(first, second);
|
||||
assert.equal(await verifyPassword(initialPassword, first), true);
|
||||
assert.equal(await verifyPassword('different long password', first), false);
|
||||
assert.equal(await verifyPassword(initialPassword, 'scrypt$999999999$8$1$abc$def'), false);
|
||||
await assert.rejects(() => hashPassword('short'));
|
||||
});
|
||||
|
||||
test('bootstrap is once-only, stores no plaintext and rotates sessions on first password change', async () => {
|
||||
const login = await loginWithPassword('TEST.ADMIN', initialPassword);
|
||||
assert.equal(login.user.mustChangePassword, true);
|
||||
assert.equal(login.user.role, 'admin');
|
||||
adminId = login.user.userId;
|
||||
const stored = getDatabase().prepare('SELECT * FROM accounts WHERE id = ?').bind(adminId).first<AccountRow>()!;
|
||||
assert.notEqual(stored.password_hash, initialPassword);
|
||||
const session = getDatabase().prepare('SELECT token_hash FROM sessions WHERE account_id = ?').bind(adminId).first<{ token_hash: string }>()!;
|
||||
assert.notEqual(session.token_hash, login.token);
|
||||
assert.equal(authenticateSession(login.token)?.userId, adminId);
|
||||
const changed = await changeAccountPassword(adminId, initialPassword, 'Changed administrator password 9274');
|
||||
adminToken = changed.token;
|
||||
assert.equal(changed.user.mustChangePassword, false);
|
||||
assert.equal(authenticateSession(login.token), null);
|
||||
assert.equal(authenticateSession(changed.token)?.userId, adminId);
|
||||
closeDatabases();
|
||||
process.env.INITIAL_ADMIN_PASSWORD = 'Different environment secret 1234';
|
||||
assert.equal(authenticateSession(changed.token)?.userId, adminId, 'session survives DB connection restart');
|
||||
assert.equal(getDatabase().prepare('SELECT COUNT(*) AS count FROM accounts').first<{ count: number }>()!.count, 1);
|
||||
assert.equal(await verifyPassword('Changed administrator password 9274', getDatabase().prepare('SELECT password_hash FROM accounts WHERE id = ?').bind(adminId).first<{ password_hash: string }>()!.password_hash), true);
|
||||
});
|
||||
|
||||
test('specified-user provisioning, disable/enable, reset and access guards work', async () => {
|
||||
const created = await createAccount(adminId, { username: 'business.user', displayName: '业务同事', password: 'First business password 9812', role: 'user' });
|
||||
assert.equal(created.mustChangePassword, true);
|
||||
let login = await loginWithPassword('business.user', 'First business password 9812');
|
||||
assert.equal(authenticateSession(login.token)?.userId, created.userId);
|
||||
await assert.rejects(() => createAccount(created.userId, { username: 'unauthorized', displayName: '不可创建', password: 'Unauthorized password 123', role: 'admin' }), error => error instanceof AuthError && error.status === 403);
|
||||
await updateAccount(adminId, { id: created.userId, action: 'disable' });
|
||||
assert.equal(authenticateSession(login.token), null);
|
||||
await assert.rejects(() => loginWithPassword('business.user', 'First business password 9812'), error => error instanceof AuthError && error.status === 401);
|
||||
await updateAccount(adminId, { id: created.userId, action: 'enable' });
|
||||
login = await loginWithPassword('business.user', 'First business password 9812');
|
||||
await updateAccount(adminId, { id: created.userId, action: 'reset-password', password: 'Reset business password 5234' });
|
||||
assert.equal(authenticateSession(login.token), null);
|
||||
await assert.rejects(() => loginWithPassword('business.user', 'First business password 9812'), error => error instanceof AuthError && error.status === 401);
|
||||
const resetLogin = await loginWithPassword('business.user', 'Reset business password 5234');
|
||||
assert.equal(resetLogin.user.mustChangePassword, true);
|
||||
const listed = listAccounts(adminId);
|
||||
assert.equal(listed.length, 2);
|
||||
assert.equal(JSON.stringify(listed).includes('password_hash'), false);
|
||||
assert.equal(JSON.stringify(listed).includes('token_hash'), false);
|
||||
await assert.rejects(() => updateAccount(adminId, { id: adminId, action: 'disable' }));
|
||||
await assert.rejects(() => updateAccount(adminId, { id: adminId, action: 'reset-password', password: 'Unsafe admin reset 99999' }));
|
||||
await assert.rejects(() => createAccount(adminId, { username: 'BUSINESS.USER', displayName: '重复', password: 'Repeated account password 123', role: 'user' }), error => error instanceof AuthError && error.status === 409);
|
||||
});
|
||||
|
||||
test('persistent login limit stops repeated password guesses', async () => {
|
||||
for (let attempt = 0; attempt < 5; attempt++) {
|
||||
await assert.rejects(() => loginWithPassword('nonexistent.user', 'An invalid password 5922'), error => error instanceof AuthError && error.status === 401);
|
||||
}
|
||||
closeDatabases();
|
||||
await assert.rejects(() => loginWithPassword('nonexistent.user', 'An invalid password 5922'), error => error instanceof AuthError && error.status === 429);
|
||||
});
|
||||
|
||||
test('default configuration ignores forwarded headers and has no global login quota', async () => {
|
||||
const request = new Request('https://demands.example.test/api/auth/login', {
|
||||
headers: { 'x-forwarded-for': '203.0.113.5', 'x-real-ip': '203.0.113.5' },
|
||||
});
|
||||
// A leftover global bucket from an earlier application version must have no effect.
|
||||
getDatabase().prepare('INSERT INTO login_limits (key, window_start, attempts) VALUES (?, ?, ?)').bind('global', Date.now(), 1000).run();
|
||||
for (let attempt = 0; attempt < 61; attempt++) {
|
||||
await assert.rejects(() => loginWithPassword(`default.unknown.${attempt}`, 'An invalid password 5922', request), error => error instanceof AuthError && error.status === 401);
|
||||
}
|
||||
const login = await loginWithPassword('test.admin', 'Changed administrator password 9274', request);
|
||||
assert.equal(login.user.userId, adminId);
|
||||
revokeSession(login.token);
|
||||
assert.equal(getDatabase().prepare("SELECT COUNT(*) AS count FROM login_limits WHERE key LIKE 'source:%'").first<{ count: number }>()!.count, 0);
|
||||
});
|
||||
|
||||
test('trusted source limit isolates sources and cannot be bypassed through other headers', async () => {
|
||||
process.env.LOGIN_CLIENT_IP_HEADER = 'X-Trusted-Client-IP';
|
||||
const request = (address: string, extra: Record<string, string> = {}) => new Request('https://demands.example.test/api/auth/login', {
|
||||
headers: { 'x-trusted-client-ip': address, ...extra },
|
||||
});
|
||||
try {
|
||||
for (let attempt = 0; attempt < 60; attempt++) {
|
||||
await assert.rejects(() => loginWithPassword(`source.unknown.${attempt}`, 'An invalid password 5922', request('192.0.2.10')), error => error instanceof AuthError && error.status === 401);
|
||||
}
|
||||
closeDatabases();
|
||||
await assert.rejects(() => loginWithPassword('test.admin', 'Changed administrator password 9274', request('192.0.2.10')), error => error instanceof AuthError && error.status === 429);
|
||||
await assert.rejects(() => loginWithPassword('test.admin', 'Changed administrator password 9274', request('192.0.2.10', { 'x-forwarded-for': '198.51.100.9', 'x-real-ip': '198.51.100.9' })), error => error instanceof AuthError && error.status === 429);
|
||||
await assert.rejects(() => loginWithPassword('test.admin', 'Changed administrator password 9274', request('::ffff:192.0.2.10')), error => error instanceof AuthError && error.status === 429);
|
||||
const otherSource = await loginWithPassword('test.admin', 'Changed administrator password 9274', request('192.0.2.11'));
|
||||
assert.equal(otherSource.user.userId, adminId);
|
||||
revokeSession(otherSource.token);
|
||||
const buckets = getDatabase().prepare("SELECT key, attempts FROM login_limits WHERE key LIKE 'source:%'").all<{ key: string; attempts: number }>().results;
|
||||
assert.equal(buckets.length, 2);
|
||||
assert.deepEqual(buckets.map(bucket => bucket.attempts).sort((a, b) => a - b), [1, 60]);
|
||||
assert.ok(buckets.every(bucket => /^source:[a-f0-9]{64}$/.test(bucket.key)), 'source IPs are hashed before persistence');
|
||||
} finally { delete process.env.LOGIN_CLIENT_IP_HEADER; }
|
||||
});
|
||||
|
||||
test('enabled source limit rejects missing, malformed and list-valued trusted headers', async () => {
|
||||
process.env.LOGIN_CLIENT_IP_HEADER = 'X-Trusted-Client-IP';
|
||||
try {
|
||||
for (const address of [undefined, '', 'unknown', '127.1', '192.0.2.1, 192.0.2.2', '192.0.2.1:8080', '[2001:db8::1]', 'fe80::1%eth0']) {
|
||||
const request = new Request('https://demands.example.test/api/auth/login', {
|
||||
headers: { 'x-forwarded-for': '192.0.2.99', ...(address === undefined ? {} : { 'x-trusted-client-ip': address }) },
|
||||
});
|
||||
await assert.rejects(() => loginWithPassword('test.admin', 'Changed administrator password 9274', request), error => error instanceof AuthError && error.status === 403);
|
||||
}
|
||||
await assert.rejects(() => loginWithPassword('test.admin', 'Changed administrator password 9274'), error => error instanceof AuthError && error.status === 403);
|
||||
process.env.LOGIN_CLIENT_IP_HEADER = 'invalid header name';
|
||||
await assert.rejects(() => loginWithPassword('test.admin', 'Changed administrator password 9274'), error => error instanceof AuthError && error.status === 503);
|
||||
} finally { delete process.env.LOGIN_CLIENT_IP_HEADER; }
|
||||
});
|
||||
|
||||
test('equivalent IPv6 source representations use the same quota', async () => {
|
||||
process.env.LOGIN_CLIENT_IP_HEADER = 'X-Trusted-Client-IP';
|
||||
try {
|
||||
const addresses = ['2001:db8::1', '2001:0DB8:0000:0000:0000:0000:0000:0001'];
|
||||
const countBefore = getDatabase().prepare("SELECT COUNT(*) AS count FROM login_limits WHERE key LIKE 'source:%'").first<{ count: number }>()!.count;
|
||||
for (let index = 0; index < addresses.length; index++) {
|
||||
const request = new Request('https://demands.example.test/api/auth/login', { headers: { 'x-trusted-client-ip': addresses[index] } });
|
||||
await assert.rejects(() => loginWithPassword(`ipv6.unknown.${index}`, 'An invalid password 5922', request), error => error instanceof AuthError && error.status === 401);
|
||||
}
|
||||
assert.equal(getDatabase().prepare("SELECT COUNT(*) AS count FROM login_limits WHERE key LIKE 'source:%'").first<{ count: number }>()!.count, countBefore + 1);
|
||||
} finally { delete process.env.LOGIN_CLIENT_IP_HEADER; }
|
||||
});
|
||||
|
||||
test('administrator reset immediately clears account lockout while retaining source attempts', async () => {
|
||||
const created = await createAccount(adminId, { username: 'locked.user', displayName: '密码恢复测试', password: 'Locked user initial password 1234', role: 'user' });
|
||||
process.env.LOGIN_CLIENT_IP_HEADER = 'X-Trusted-Client-IP';
|
||||
const request = new Request('https://demands.example.test/api/auth/login', { headers: { 'x-trusted-client-ip': '198.51.100.44' } });
|
||||
try {
|
||||
for (let attempt = 0; attempt < 5; attempt++) {
|
||||
await assert.rejects(() => loginWithPassword('locked.user', 'An invalid password 5922', request), error => error instanceof AuthError && error.status === 401);
|
||||
}
|
||||
await assert.rejects(() => loginWithPassword('locked.user', 'Locked user initial password 1234', request), error => error instanceof AuthError && error.status === 429);
|
||||
const sourcesBefore = getDatabase().prepare("SELECT key, window_start, attempts FROM login_limits WHERE key LIKE 'source:%' ORDER BY key").all().results;
|
||||
await updateAccount(adminId, { id: created.userId, action: 'reset-password', password: 'Locked user reset password 5678' });
|
||||
const sourcesAfter = getDatabase().prepare("SELECT key, window_start, attempts FROM login_limits WHERE key LIKE 'source:%' ORDER BY key").all().results;
|
||||
assert.deepEqual(sourcesAfter, sourcesBefore, 'reset only clears the account quota, never the source quota');
|
||||
const recovered = await loginWithPassword('locked.user', 'Locked user reset password 5678', request);
|
||||
assert.equal(recovered.user.userId, created.userId);
|
||||
assert.equal(recovered.user.mustChangePassword, true);
|
||||
} finally { delete process.env.LOGIN_CLIENT_IP_HEADER; }
|
||||
});
|
||||
|
||||
test('sessions expire and logout invalidates the server-side session', () => {
|
||||
getDatabase().prepare('UPDATE sessions SET expires_at = 0 WHERE account_id = ?').bind(adminId).run();
|
||||
assert.equal(authenticateSession(adminToken), null);
|
||||
assert.equal(authenticateSession('not-a-token'), null);
|
||||
revokeSession(adminToken);
|
||||
assert.equal(getDatabase().prepare('SELECT COUNT(*) AS count FROM sessions WHERE account_id = ?').bind(adminId).first<{ count: number }>()!.count, 0);
|
||||
});
|
||||
|
||||
test('CSRF checks require configured origin; sessions use secure HttpOnly cookies', () => {
|
||||
const request = (headers: Record<string, string>) => new Request('http://internal-container:3000/api/auth/login', { method: 'POST', headers });
|
||||
assert.equal(isSameOrigin(request({ origin: 'https://demands.example.test' })), true);
|
||||
assert.equal(isSameOrigin(request({ origin: 'https://attacker.example', 'x-forwarded-host': 'demands.example.test' })), false);
|
||||
assert.equal(isSameOrigin(request({ 'x-openai-user-id': adminId })), false);
|
||||
assert.equal(isSameOrigin(request({ origin: 'https://demands.example.test', 'sec-fetch-site': 'cross-site' })), false);
|
||||
assert.equal(isSameOrigin(request({})), false);
|
||||
const cookie = sessionCookie('some-token');
|
||||
assert.match(cookie, /HttpOnly/);
|
||||
assert.match(cookie, /SameSite=Lax/);
|
||||
assert.match(cookie, /Secure/);
|
||||
assert.match(sessionCookie(''), /Max-Age=0/);
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { after, before, test } from 'node:test';
|
||||
import { mkdtempSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { emptyFields, type Demand } from '../lib/demand.ts';
|
||||
import { closeDatabases, getDatabase, type AccountRow } from '../lib/server/database.ts';
|
||||
import { withDefaultDeveloper } from '../lib/server/default-developer.ts';
|
||||
import { applyReviewAction } from '../lib/server/demand-review.ts';
|
||||
import type { AuthUser } from '../lib/server/auth.ts';
|
||||
|
||||
const directory = mkdtempSync(join(tmpdir(), 'demand-default-developer-'));
|
||||
const environment = { ...process.env };
|
||||
let admin: AuthUser;
|
||||
before(() => {
|
||||
Object.assign(process.env, { DATA_DIR: directory, APP_URL: 'https://test.example', INITIAL_ADMIN_USERNAME: 'default_admin', INITIAL_ADMIN_PASSWORD: 'Local test password 9274', INITIAL_ADMIN_DISPLAY_NAME: '系统管理员' });
|
||||
const row = getDatabase().prepare('SELECT * FROM accounts').first<AccountRow>()!;
|
||||
admin = { userId: row.id, username: row.username, displayName: row.display_name, role: 'admin', mustChangePassword: false };
|
||||
});
|
||||
after(() => { closeDatabases(); rmSync(directory, { recursive: true, force: true }); process.env = environment; });
|
||||
const demand = (status = '待评审'): Demand => ({ id: 'default', fields: { ...emptyFields }, revision: 7, status, reviewReady: true, createdAt: '', updatedAt: '', history: [], changes: [] });
|
||||
|
||||
test('unassigned formal demands resolve to an enabled system administrator without changing revision or history', () => {
|
||||
const original = demand();
|
||||
const assigned = withDefaultDeveloper(original);
|
||||
assert.equal(assigned.review?.developer.userId, admin.userId);
|
||||
assert.equal(assigned.review?.developer.displayName, '系统管理员');
|
||||
assert.equal(assigned.revision, 7);
|
||||
assert.deepEqual(assigned.history, []);
|
||||
assert.equal(original.review, undefined);
|
||||
assert.deepEqual(withDefaultDeveloper(original), assigned);
|
||||
});
|
||||
|
||||
test('existing assignments, private drafts and closed historical demands remain unchanged', () => {
|
||||
const assigned = { ...demand(), review: { developer: { userId: 'legacy', username: 'legacy', displayName: '原开发' }, proposals: [] } };
|
||||
for (const record of [assigned, demand('草稿'), demand('已取消'), demand('已完成')]) assert.equal(withDefaultDeveloper(record), record);
|
||||
});
|
||||
|
||||
test('default administrator can submit and confirm a demand they registered', () => {
|
||||
const record = withDefaultDeveloper(demand());
|
||||
applyReviewAction(record, admin.userId, admin, { action: 'propose-solution', scope: 'F-01 查询订单', outOfScope: '无' }, '2026-09-23T00:00:00Z');
|
||||
assert.equal(record.review?.proposals[0].developer.userId, admin.userId);
|
||||
applyReviewAction(record, admin.userId, admin, { action: 'confirm-solution', proposalVersion: 1, confirm: true }, '2026-09-23T00:01:00Z');
|
||||
assert.equal(record.review?.proposals[0].decision?.result, 'confirmed');
|
||||
});
|
||||
|
||||
test('disabled administrators are skipped and ordinary accounts are never used as defaults', () => {
|
||||
const database = getDatabase();
|
||||
database.prepare('UPDATE accounts SET disabled = 1 WHERE id = ?').bind(admin.userId).run();
|
||||
assert.throws(() => withDefaultDeveloper(demand()), /暂无启用的系统管理员/);
|
||||
database.prepare('UPDATE accounts SET disabled = 0, role = ? WHERE id = ?').bind('user', admin.userId).run();
|
||||
assert.throws(() => withDefaultDeveloper(demand()), /暂无启用的系统管理员/);
|
||||
database.prepare('UPDATE accounts SET role = ? WHERE id = ?').bind('admin', admin.userId).run();
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { test } from 'node:test';
|
||||
import { emptyFields, isMyDemand, needsAction, type Demand } from '../lib/demand.ts';
|
||||
import { currentProposal, invalidateProposal, reviewStage } from '../lib/demand-review.ts';
|
||||
|
||||
const developer = { userId: 'developer', username: 'dev', displayName: '开发' };
|
||||
const business = { userId: 'business', username: 'owner', displayName: '业务' };
|
||||
function demand(): Demand {
|
||||
return { id: 'review', revision: 1, fields: { ...emptyFields }, status: '待评审', reviewReady: true, createdAt: '', updatedAt: '', history: [], changes: [], access: { business: true, developer: false } };
|
||||
}
|
||||
function withProposal(): Demand {
|
||||
const d = demand();
|
||||
d.review = { developer, proposals: [{ version: 1, developer, submittedAt: '2026-09-17T00:00:00Z', scope: '方案', outOfScope: '无', businessFields: { ...emptyFields } }] };
|
||||
return d;
|
||||
}
|
||||
|
||||
test('review tasks are directed to the actor who can perform the next step', () => {
|
||||
const d = demand();
|
||||
assert.equal(reviewStage(d), '待开发提出方案');
|
||||
assert.equal(needsAction(d), false);
|
||||
d.review = { developer, proposals: [] };
|
||||
assert.equal(needsAction(d), false);
|
||||
d.access = { business: false, developer: true };
|
||||
assert.equal(needsAction(d), true);
|
||||
const proposed = withProposal();
|
||||
assert.equal(needsAction(proposed), true);
|
||||
proposed.access = { business: false, developer: true };
|
||||
assert.equal(needsAction(proposed), false);
|
||||
});
|
||||
|
||||
test('changes requested go back to development; confirmed solutions move to planning', () => {
|
||||
const d = withProposal();
|
||||
currentProposal(d)!.decision = { result: 'changes_requested', actor: business, time: '', comment: '补充细节' };
|
||||
assert.equal(needsAction(d), false);
|
||||
d.access = { business: false, developer: true };
|
||||
assert.equal(needsAction(d), true);
|
||||
currentProposal(d)!.decision!.result = 'confirmed';
|
||||
assert.equal(reviewStage(d), '方案已确认');
|
||||
assert.equal(needsAction(d), true);
|
||||
d.access = { business: true, developer: false };
|
||||
assert.equal(needsAction(d), false);
|
||||
});
|
||||
|
||||
test('invalidating a confirmed proposal preserves evidence and requires a new developer version', () => {
|
||||
const d = withProposal();
|
||||
currentProposal(d)!.decision = { result: 'confirmed', actor: business, time: 'original-time', comment: '同意' };
|
||||
invalidateProposal(d, 'updated-time', '业务变更');
|
||||
assert.equal(currentProposal(d)!.decision!.time, 'original-time');
|
||||
assert.equal(reviewStage(d), '待开发提出方案');
|
||||
d.access = { business: false, developer: true };
|
||||
assert.equal(needsAction(d), true);
|
||||
invalidateProposal(d, 'later-time', '后来变更');
|
||||
assert.equal(currentProposal(d)!.invalidated!.time, 'updated-time');
|
||||
});
|
||||
|
||||
test('incomplete business material and acceptance stay with the business account', () => {
|
||||
const d = withProposal();
|
||||
d.reviewReady = false;
|
||||
assert.equal(needsAction(d), true);
|
||||
d.access = { business: false, developer: true };
|
||||
assert.equal(needsAction(d), false);
|
||||
d.status = '待验收';
|
||||
assert.equal(needsAction(d), false);
|
||||
d.access = { business: true, developer: false };
|
||||
assert.equal(needsAction(d), true);
|
||||
d.status = '已取消';
|
||||
assert.equal(needsAction(d), false);
|
||||
});
|
||||
|
||||
test('administrator observation does not populate personal demands or actionable tasks', () => {
|
||||
const observed = withProposal();
|
||||
observed.access = { business: false, developer: false };
|
||||
for (const status of ['待评审', '待验收', '已完成']) {
|
||||
observed.status = status;
|
||||
assert.equal(isMyDemand(observed), false);
|
||||
assert.equal(needsAction(observed), false);
|
||||
}
|
||||
observed.status = '待评审'; observed.reviewReady = false;
|
||||
assert.equal(needsAction(observed), false);
|
||||
const own = demand();
|
||||
const assigned = demand(); assigned.access = { business: false, developer: true };
|
||||
assert.deepEqual([own, assigned, observed].filter(isMyDemand), [own, assigned]);
|
||||
});
|
||||
|
||||
test('administrator with both responsibilities receives developer review tasks', () => {
|
||||
const d = demand();
|
||||
d.review = { developer, proposals: [] };
|
||||
d.access = { business: true, developer: true };
|
||||
assert.equal(needsAction(d), true);
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { test } from 'node:test';
|
||||
import { emptyFields, type Demand } from '../lib/demand.ts';
|
||||
import { mergeDemandSnapshot } from '../lib/demand-snapshot.ts';
|
||||
|
||||
function record(id: string, revision = 1): Demand {
|
||||
return {
|
||||
id, revision, fields: { ...emptyFields, title: id }, status: '草稿', reviewReady: false,
|
||||
createdAt: '2026-09-16T00:00:00Z', updatedAt: `2026-09-16T00:0${revision}:00Z`,
|
||||
history: [], changes: [],
|
||||
};
|
||||
}
|
||||
|
||||
test('late initial GET retains both existing records and the draft saved while it was pending', () => {
|
||||
const existing = record('existing');
|
||||
const saved = record('saved-draft');
|
||||
const result = mergeDemandSnapshot([existing], [{ version: 1, demand: saved }], 0);
|
||||
assert.equal(result.length, 2);
|
||||
assert.ok(result.includes(existing));
|
||||
assert.ok(result.includes(saved));
|
||||
});
|
||||
|
||||
test('concurrent edits keep the latest acknowledged revision without downgrading a newer server record', () => {
|
||||
const old = record('edited', 1);
|
||||
const saved = record('edited', 2);
|
||||
assert.deepEqual(mergeDemandSnapshot([old], [{ version: 2, demand: saved }], 1), [saved]);
|
||||
const newer = record('edited', 3);
|
||||
assert.deepEqual(mergeDemandSnapshot([newer], [{ version: 2, demand: saved }], 1), [newer]);
|
||||
});
|
||||
|
||||
test('a later refresh treats writes made before its request as already included in the server snapshot', () => {
|
||||
const beforeRefresh = record('previous-write');
|
||||
const other = record('other-server-record');
|
||||
assert.deepEqual(mergeDemandSnapshot([other], [{ version: 1, demand: beforeRefresh }], 1), [other]);
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { after, before, beforeEach, test } from 'node:test';
|
||||
import { mkdtempSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { emptyFields, type Demand } from '../lib/demand.ts';
|
||||
import { canTakeOverDevelopment } from '../lib/server/default-developer.ts';
|
||||
import { applyReviewAction } from '../lib/server/demand-review.ts';
|
||||
import { applyWorkflowAction } from '../lib/server/workflow.ts';
|
||||
import { planConfirmed } from '../lib/workflow.ts';
|
||||
import { closeDatabases, getDatabase, type AccountRow } from '../lib/server/database.ts';
|
||||
import type { AuthUser } from '../lib/server/auth.ts';
|
||||
|
||||
const directory = mkdtempSync(join(tmpdir(), 'demand-takeover-test-'));
|
||||
const environment = { ...process.env };
|
||||
let original: AuthUser;
|
||||
const admin: AuthUser = { userId: 'replacement', username: 'replacement_admin', displayName: '接手管理员', role: 'admin', mustChangePassword: false };
|
||||
const business: AuthUser = { userId: 'business', username: 'business', displayName: '业务', role: 'user', mustChangePassword: false };
|
||||
const now = '2026-09-23T08:00:00Z';
|
||||
before(() => {
|
||||
Object.assign(process.env, { DATA_DIR: directory, APP_URL: 'https://test.example', INITIAL_ADMIN_USERNAME: 'original_admin', INITIAL_ADMIN_PASSWORD: 'Local test password 9274' });
|
||||
const row = getDatabase().prepare('SELECT * FROM accounts').first<AccountRow>()!;
|
||||
original = { userId: row.id, username: row.username, displayName: row.display_name, role: 'admin', mustChangePassword: false };
|
||||
getDatabase().prepare(`INSERT INTO accounts (id, username, display_name, password_hash, role, must_change_password, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, 'admin', 0, ?, ?)`).bind(admin.userId, admin.username, admin.displayName, row.password_hash, now, now).run();
|
||||
});
|
||||
beforeEach(() => {
|
||||
getDatabase().prepare('UPDATE accounts SET disabled = 0, must_change_password = 0').run();
|
||||
getDatabase().prepare('UPDATE accounts SET disabled = 1 WHERE id = ?').bind(original.userId).run();
|
||||
});
|
||||
after(() => { closeDatabases(); rmSync(directory, { recursive: true, force: true }); process.env = environment; });
|
||||
function fixture(status = '待验收'): Demand {
|
||||
const testing = { round: 1, testVersion: 'build-1', environment: 'https://test.example', deadline: '2026-10-01', items: [], instructions: '说明' };
|
||||
return { id: 'handoff', revision: 4, fields: { ...emptyFields }, status, reviewReady: true, createdAt: now, updatedAt: now, history: [], changes: [],
|
||||
review: { developer: original, proposals: [{ version: 1, scope: '原方案', outOfScope: '无', developer: original, submittedAt: now, businessFields: { ...emptyFields }, decision: { result: 'confirmed', actor: business, time: now, comment: '确认原方案' } }] },
|
||||
plan: { developer: original.displayName, testDate: '2026-10-01', releaseDate: '2026-10-03', version: 1, proposalVersion: 1, proposedBy: original, proposedAt: now, decision: { actor: business, time: now, approved: true, comment: '确认原计划' } },
|
||||
acceptance: structuredClone(testing), delivery: { testing: [testing] },
|
||||
};
|
||||
}
|
||||
const takeOver = (d: Demand, user = admin, confirm = true) => applyReviewAction(d, business.userId, user, { action: 'take-over-development', confirm }, now);
|
||||
|
||||
test('only initialized enabled administrators can recover an unavailable developer', () => {
|
||||
const d = fixture();
|
||||
assert.equal(canTakeOverDevelopment(d, admin), true);
|
||||
assert.equal(canTakeOverDevelopment(d, business), false);
|
||||
assert.equal(canTakeOverDevelopment(d, original), false);
|
||||
assert.throws(() => takeOver(d, business), /仅启用的管理员/);
|
||||
for (const status of ['草稿', '已取消']) assert.throws(() => takeOver(fixture(status)), /仅启用的管理员/);
|
||||
for (const field of ['disabled', 'must_change_password']) {
|
||||
getDatabase().prepare(`UPDATE accounts SET ${field} = 1 WHERE id = ?`).bind(admin.userId).run();
|
||||
assert.throws(() => takeOver(d), /仅启用的管理员/);
|
||||
getDatabase().prepare(`UPDATE accounts SET ${field} = 0 WHERE id = ?`).bind(admin.userId).run();
|
||||
}
|
||||
});
|
||||
test('handoff preserves evidence and invalidates old approvals and tests across formal states', () => {
|
||||
for (const status of ['待评审', '已排期', '开发中', '待验收', '待发布', '已上线', '已完成']) {
|
||||
const d = fixture(status);
|
||||
const oldPlan = structuredClone(d.plan), oldDecision = structuredClone(d.review!.proposals[0].decision);
|
||||
assert.equal(planConfirmed(d), true);
|
||||
const event = takeOver(d);
|
||||
assert.equal(d.status, '待评审');
|
||||
assert.equal(d.review!.developer.userId, admin.userId);
|
||||
assert.equal(d.review!.proposals[0].developer.userId, original.userId);
|
||||
assert.deepEqual(d.review!.proposals[0].decision, oldDecision);
|
||||
assert.equal(d.review!.proposals[0].invalidated?.time, now);
|
||||
assert.deepEqual(d.plan, oldPlan);
|
||||
assert.equal(planConfirmed(d), false);
|
||||
assert.equal(d.acceptance?.withdrawnAt, now);
|
||||
assert.equal(d.delivery?.testing?.[0].withdrawnAt, now);
|
||||
assert.equal(event.label, '接手开发职责');
|
||||
assert(event.detail.includes(original.username) && event.detail.includes(admin.username));
|
||||
assert.throws(() => applyWorkflowAction(d, business.userId, original, { action: 'add-note', notes: '旧开发无权限' }, now), /对应责任人/);
|
||||
}
|
||||
});
|
||||
test('stale availability, missing confirmation and pending changes cannot mutate the record', () => {
|
||||
const d = fixture();
|
||||
let before = JSON.stringify(d);
|
||||
assert.throws(() => takeOver(d, admin, false), /请确认/);
|
||||
assert.equal(JSON.stringify(d), before);
|
||||
d.changes.push({ id: 'pending', time: now, content: '新范围', reason: '业务调整', actor: '业务', status: '待开发评估', originalVersion: 'v1.0' });
|
||||
before = JSON.stringify(d);
|
||||
assert.throws(() => takeOver(d), /处理或撤回/);
|
||||
assert.equal(JSON.stringify(d), before);
|
||||
d.changes[0].status = '已撤回';
|
||||
getDatabase().prepare('UPDATE accounts SET disabled = 0 WHERE id = ?').bind(original.userId).run();
|
||||
before = JSON.stringify(d);
|
||||
assert.throws(() => takeOver(d), /仅启用的管理员/);
|
||||
assert.equal(JSON.stringify(d), before);
|
||||
});
|
||||
test('incomplete material can be handed over but still requires business completion', () => {
|
||||
const d = fixture('待评审'); d.reviewReady = false;
|
||||
takeOver(d);
|
||||
assert.equal(d.reviewReady, false);
|
||||
assert.throws(() => applyReviewAction(d, business.userId, admin, { action: 'propose-solution', scope: '新方案', outOfScope: '无' }, now), /补齐业务材料/);
|
||||
});
|
||||
test('replacement submits a new version and business must confirm it again', () => {
|
||||
const d = fixture(); takeOver(d);
|
||||
applyReviewAction(d, business.userId, admin, { action: 'propose-solution', scope: '接手后的方案', outOfScope: '无' }, now);
|
||||
assert.equal(d.review!.proposals.at(-1)?.version, 2);
|
||||
assert.throws(() => applyReviewAction(d, business.userId, admin, { action: 'confirm-solution', proposalVersion: 2, confirm: true }, now), /登记账号/);
|
||||
applyReviewAction(d, business.userId, business, { action: 'confirm-solution', proposalVersion: 2, confirm: true }, now);
|
||||
assert.equal(d.review!.proposals.at(-1)?.decision?.actor.userId, business.userId);
|
||||
assert.equal(planConfirmed(d), false);
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { test } from 'node:test';
|
||||
import { documents, findDocument, linkedDocument, templateDownloadUrl, FEISHU_TEMPLATE_DIRECTORY } from '../lib/documents.ts';
|
||||
|
||||
test('document registry retains legacy names and points visible downloads to Word', () => {
|
||||
for (const document of documents) {
|
||||
assert.equal(findDocument(document.filename)?.id, document.id);
|
||||
assert.equal(findDocument(document.id)?.filename, document.filename);
|
||||
const url = new URL(templateDownloadUrl(document.id), 'https://example.test');
|
||||
assert.equal(url.searchParams.get('format'), 'docx');
|
||||
assert.equal(decodeURIComponent(url.pathname.split('/').at(-1)!), document.filename);
|
||||
}
|
||||
assert.equal(findDocument('../../.env'), undefined);
|
||||
assert.equal(findDocument('not-a-document'), undefined);
|
||||
});
|
||||
|
||||
test('links between built-in documents resolve to the correct preview and preserve the provided Feishu directory', () => {
|
||||
assert.equal(linkedDocument('开发SOP附件/附件03_数据来源填写模板.md')?.id, 'data-source');
|
||||
assert.equal(linkedDocument(encodeURIComponent('附件02_需求文档模板.md'))?.id, 'requirement');
|
||||
assert.equal(linkedDocument('%invalid'), undefined);
|
||||
assert.equal(linkedDocument('javascript:alert(1)'), undefined);
|
||||
assert.equal(FEISHU_TEMPLATE_DIRECTORY, 'https://ecnldnvsv8es.feishu.cn/wiki/Bvnbw852biK7qRkhwJkcOIvun4f?from=from_copylink');
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { test } from 'node:test';
|
||||
import { feishuJson } from '../lib/server/feishu-config.ts';
|
||||
|
||||
test('Feishu diagnostics retain provider stage and numeric error codes without credentials or user fields', async () => {
|
||||
const fetchBefore = globalThis.fetch;
|
||||
const logBefore = console.error;
|
||||
const logs: unknown[][] = [];
|
||||
console.error = (...args: unknown[]) => { logs.push(args); };
|
||||
try {
|
||||
globalThis.fetch = async () => Response.json({ code: 20010, error: 'invalid_request', error_description: 'secret-must-never-appear', access_token: 'private-token' }, { status: 400 });
|
||||
await assert.rejects(() => feishuJson('https://accounts.feishu.cn/oauth/v3/token', { method: 'POST', body: 'private-code-and-secret' }), /HTTP 400/);
|
||||
assert.deepEqual(logs.at(-1), ['Feishu API failure', { stage: 'oauth-token', httpStatus: 400, providerCode: 20010 }]);
|
||||
globalThis.fetch = async () => Response.json({ code: 20021, msg: 'private-user-information' });
|
||||
await feishuJson('https://open.feishu.cn/open-apis/authen/v1/user_info', {});
|
||||
assert.deepEqual(logs.at(-1), ['Feishu API failure', { stage: 'user-info', httpStatus: 200, providerCode: 20021 }]);
|
||||
globalThis.fetch = async () => { throw new Error('https://open.feishu.cn/open-apis/bot/v2/hook/private-webhook'); };
|
||||
await assert.rejects(() => feishuJson('https://open.feishu.cn/open-apis/bot/v2/hook/private-webhook', {}), /连接失败/);
|
||||
const text = JSON.stringify(logs);
|
||||
for (const secret of ['secret-must-never-appear', 'private-token', 'private-code', 'private-user', 'private-webhook']) assert.ok(!text.includes(secret));
|
||||
} finally { globalThis.fetch = fetchBefore; console.error = logBefore; }
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
// Only loaded by the isolated test process via --import. Never imported by application code.
|
||||
import { appendFileSync, existsSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
if (!process.env.DATA_DIR?.includes('demand-feishu-http-')) throw new Error('Feishu fixture requires an isolated test directory.');
|
||||
const original = globalThis.fetch;
|
||||
globalThis.fetch = async (input, init = {}) => {
|
||||
const url = String(input);
|
||||
if (url === 'https://open.feishu.cn/open-apis/authen/v2/oauth/token') {
|
||||
const data = JSON.parse(init.body);
|
||||
const [identity, challenge] = data.code.split('.');
|
||||
if (init.headers['Content-Type'] !== 'application/json' || data.client_id !== 'cli_http_test' || data.client_secret !== 'http-test-secret' || !data.code_verifier || !data.redirect_uri.endsWith('/api/auth/feishu/callback')) throw new Error('Invalid OAuth token exchange.');
|
||||
if (createHash('sha256').update(data.code_verifier).digest('base64url') !== challenge) return Response.json({ code: 20049 }, { status: 400 });
|
||||
return Response.json({ code: 0, access_token: 'mock-' + identity });
|
||||
}
|
||||
if (url === 'https://open.feishu.cn/open-apis/authen/v1/user_info') {
|
||||
const identity = init.headers.Authorization.replace('Bearer mock-', '');
|
||||
return Response.json({ code: 0, data: { open_id: identity === 'bound' ? 'ou_http_test' : 'ou_' + identity, tenant_key: 'tenant_http_test', name: identity === 'browser-new' ? '飞书新成员' : '飞书联调用户' } });
|
||||
}
|
||||
if (url === 'https://open.feishu.cn/open-apis/bot/v2/hook/http-test-hook') {
|
||||
const data = JSON.parse(init.body);
|
||||
appendFileSync(join(process.env.DATA_DIR, 'messages.jsonl'), JSON.stringify(data) + '\n');
|
||||
return Response.json(existsSync(join(process.env.DATA_DIR, 'fail-bot')) ? { code: 19021 } : { code: 0 });
|
||||
}
|
||||
if (url.includes('feishu.cn')) throw new Error('Unexpected Feishu request blocked by test fixture.');
|
||||
return original(input, init);
|
||||
};
|
||||
@@ -0,0 +1,123 @@
|
||||
"""Run through feishu.integration.mjs with FEISHU_BROWSER_PYTHON; uses its disposable instance."""
|
||||
import os
|
||||
from urllib.parse import urlsplit, parse_qs, urlencode
|
||||
from pathlib import Path
|
||||
from playwright.sync_api import sync_playwright, expect
|
||||
|
||||
origin = os.environ['TEST_ORIGIN']
|
||||
artifacts = Path('/tmp/demand-feishu-browser-qa')
|
||||
artifacts.mkdir(exist_ok=True)
|
||||
errors = []
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True, **({'executable_path': os.environ['PLAYWRIGHT_CHROMIUM_EXECUTABLE']} if os.environ.get('PLAYWRIGHT_CHROMIUM_EXECUTABLE') else {}))
|
||||
page = browser.new_page(viewport={'width': 1440, 'height': 1000}, device_scale_factor=1)
|
||||
page.set_extra_http_headers({'x-test-client-ip': '198.51.100.30'})
|
||||
page.on('pageerror', lambda e: errors.append(str(e)))
|
||||
authorize_urls = []
|
||||
def intercept_start(route):
|
||||
response = route.fetch(max_redirects=0)
|
||||
authorize_urls.append(response.headers['location'])
|
||||
route.fulfill(status=200, content_type='text/html; charset=utf-8', body='<h1>模拟飞书授权页</h1>')
|
||||
page.route('**/api/auth/feishu/start', intercept_start)
|
||||
page.goto(origin + '/login', wait_until='networkidle')
|
||||
expect(page.get_by_role('button', name='飞书登录', exact=True)).to_be_visible()
|
||||
page.screenshot(path=str(artifacts / 'login-desktop.png'), full_page=True)
|
||||
page.get_by_role('button', name='飞书登录', exact=True).click()
|
||||
expect(page.get_by_role('heading', name='模拟飞书授权页')).to_be_visible()
|
||||
assert authorize_urls[0].startswith('https://accounts.feishu.cn/')
|
||||
assert 'code_challenge_method=S256' in authorize_urls[0]
|
||||
page.goto(origin + '/?demand=' + os.environ['TEST_DEMAND_ID'], wait_until='networkidle')
|
||||
assert '/login?next=' in page.url
|
||||
page.get_by_label('账号', exact=True).fill(os.environ['TEST_USERNAME'])
|
||||
page.get_by_label('密码', exact=True).fill(os.environ['TEST_PASSWORD'])
|
||||
page.get_by_role('button', name='登录工作台', exact=True).click()
|
||||
page.wait_for_url(lambda url: '?demand=' in url and '/login' not in url)
|
||||
page.wait_for_load_state('networkidle')
|
||||
expect(page.get_by_role('dialog')).to_be_visible()
|
||||
expect(page.get_by_role('dialog')).to_contain_text('飞书通知联调需求')
|
||||
page.screenshot(path=str(artifacts / 'notification-deep-link.png'), full_page=True)
|
||||
page.goto(origin + '/account/feishu', wait_until='networkidle')
|
||||
expect(page.get_by_role('heading', name='飞书绑定', exact=True)).to_be_visible()
|
||||
expect(page.get_by_text('飞书联调用户', exact=True)).to_be_visible()
|
||||
page.screenshot(path=str(artifacts / 'binding-desktop.png'), full_page=True)
|
||||
page.goto(origin + '/admin/feishu', wait_until='networkidle')
|
||||
expect(page.get_by_role('heading', name='飞书集成', exact=True)).to_be_visible()
|
||||
page.get_by_role('button', name='刷新状态', exact=True).click()
|
||||
expect(page.get_by_role('status')).to_contain_text('状态已刷新')
|
||||
expect(page.get_by_role('cell', name='已发送', exact=True).first).to_be_visible()
|
||||
page.screenshot(path=str(artifacts / 'admin-desktop.png'), full_page=False)
|
||||
page.get_by_label('通知筛选', exact=True).select_option('failed')
|
||||
expect(page.get_by_role('cell', name='发送失败', exact=True)).to_have_count(50)
|
||||
page.get_by_role('button', name='下一页', exact=True).click()
|
||||
expect(page.get_by_role('cell', name='发送失败', exact=True)).to_have_count(1)
|
||||
expect(page.get_by_text('第 2 页', exact=False)).to_be_visible()
|
||||
page.get_by_role('button', name='重试发送', exact=True).click()
|
||||
expect(page.get_by_role('status')).to_contain_text('已加入发送队列')
|
||||
expect(page.get_by_text('当前页暂无失败通知。', exact=False)).to_be_visible()
|
||||
page.get_by_role('button', name='上一页', exact=True).click()
|
||||
expect(page.get_by_role('cell', name='发送失败', exact=True)).to_have_count(50)
|
||||
page.get_by_role('button', name='刷新状态', exact=True).click()
|
||||
expect(page.get_by_label('通知筛选', exact=True)).to_have_value('failed')
|
||||
page.screenshot(path=str(artifacts / 'admin-failed-filter.png'), full_page=False)
|
||||
for path, name in [('/admin/feishu', 'admin-mobile'), ('/account/feishu', 'binding-mobile')]:
|
||||
page.set_viewport_size({'width': 375, 'height': 812})
|
||||
page.goto(origin + path, wait_until='networkidle')
|
||||
assert page.evaluate('document.documentElement.scrollWidth <= innerWidth'), name + ' overflow'
|
||||
page.screenshot(path=str(artifacts / (name + '.png')), full_page=False)
|
||||
if name == 'admin-mobile':
|
||||
page.get_by_role('button', name='下一页', exact=True).scroll_into_view_if_needed()
|
||||
page.screenshot(path=str(artifacts / 'admin-mobile-pagination.png'), full_page=False)
|
||||
anonymous = browser.new_context(viewport={'width': 375, 'height': 812})
|
||||
mobile = anonymous.new_page()
|
||||
mobile.goto(origin + '/login?feishuError=expired', wait_until='networkidle')
|
||||
expect(mobile.get_by_role('alert').filter(has_text='授权已过期')).to_be_visible()
|
||||
assert mobile.evaluate('document.documentElement.scrollWidth <= innerWidth')
|
||||
mobile.screenshot(path=str(artifacts / 'login-error-mobile.png'), full_page=True)
|
||||
newcomer = browser.new_context(viewport={'width': 390, 'height': 844}, extra_http_headers={'x-test-client-ip': '198.51.100.40'})
|
||||
registration = newcomer.new_page()
|
||||
registration.on('pageerror', lambda e: errors.append(str(e)))
|
||||
def finish_mock_authorization(route):
|
||||
response = route.fetch(max_redirects=0)
|
||||
params = parse_qs(urlsplit(response.headers['location']).query)
|
||||
callback = origin + '/api/auth/feishu/callback?' + urlencode({'state': params['state'][0], 'code': 'browser-new.' + params['code_challenge'][0]})
|
||||
route.fulfill(status=303, headers={'location': callback, 'set-cookie': response.headers['set-cookie'], 'cache-control': 'no-store'}, body='')
|
||||
registration.route('**/api/auth/feishu/start', finish_mock_authorization)
|
||||
registration.goto(origin + '/login', wait_until='networkidle')
|
||||
expect(registration.get_by_text('首次飞书登录将自动注册普通成员账号。', exact=False)).to_be_visible()
|
||||
registration.get_by_role('button', name='飞书登录', exact=True).click()
|
||||
registration.wait_for_url(lambda url: url.rstrip('/') == origin)
|
||||
registration.wait_for_load_state('networkidle')
|
||||
auto_user = newcomer.request.get(origin + '/api/auth/me').json()['user']
|
||||
assert auto_user['role'] == 'user' and not auto_user['mustChangePassword']
|
||||
assert newcomer.request.get(origin + '/api/admin/users').status == 403
|
||||
registration.get_by_role('button', name='账号菜单', exact=True).click()
|
||||
expect(registration.get_by_role('menuitem', name='设置密码', exact=True)).to_be_visible()
|
||||
expect(registration.get_by_role('menuitem', name='账号管理', exact=True)).to_have_count(0)
|
||||
registration.goto(origin + '/account/feishu', wait_until='networkidle')
|
||||
expect(registration.get_by_role('button', name='验证密码并解除绑定', exact=True)).to_have_count(0)
|
||||
registration.get_by_role('link', name='设置系统密码', exact=True).click()
|
||||
expect(registration.get_by_role('heading', name='设置系统密码', exact=True)).to_be_visible()
|
||||
expect(registration.get_by_label('当前密码', exact=True)).to_have_count(0)
|
||||
assert registration.evaluate('document.documentElement.scrollWidth <= innerWidth')
|
||||
registration.screenshot(path=str(artifacts / 'first-password-mobile.png'), full_page=True)
|
||||
registration.get_by_label('新密码', exact=True).fill(os.environ['TEST_PASSWORD'])
|
||||
registration.get_by_label('确认新密码', exact=True).fill(os.environ['TEST_PASSWORD'])
|
||||
registration.get_by_role('button', name='保存密码并进入工作台', exact=True).click()
|
||||
registration.wait_for_url(lambda url: url.rstrip('/') == origin)
|
||||
registration.goto(origin + '/account/feishu', wait_until='networkidle')
|
||||
registration.get_by_label('当前系统密码', exact=True).fill(os.environ['TEST_PASSWORD'])
|
||||
registration.get_by_role('button', name='验证密码并解除绑定', exact=True).click()
|
||||
expect(registration.get_by_text('已解除飞书绑定', exact=False)).to_be_visible()
|
||||
expect(registration.get_by_role('button', name='绑定我的飞书账号', exact=True)).to_be_visible()
|
||||
registration.goto(origin + '/', wait_until='networkidle')
|
||||
registration.get_by_role('button', name='账号菜单', exact=True).click()
|
||||
registration.get_by_role('menuitem', name='退出登录', exact=True).click()
|
||||
registration.wait_for_url('**/login')
|
||||
registration.get_by_label('账号', exact=True).fill(auto_user['username'])
|
||||
registration.get_by_label('密码', exact=True).fill(os.environ['TEST_PASSWORD'])
|
||||
registration.get_by_role('button', name='登录工作台', exact=True).click()
|
||||
registration.wait_for_url(lambda url: url.rstrip('/') == origin)
|
||||
assert newcomer.request.get(origin + '/api/auth/me').json()['user']['userId'] == auto_user['userId']
|
||||
assert not errors, errors
|
||||
browser.close()
|
||||
print('Feishu browser QA passed: desktop/mobile, first-login registration, first password setup, unlink/password fallback, permissions, notification history, no page errors.')
|
||||
@@ -0,0 +1,168 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { mkdtemp, readFile, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { createServer } from 'node:net';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
|
||||
const directory = await mkdtemp(join(tmpdir(), 'demand-feishu-http-'));
|
||||
const port = await new Promise(resolve => { const server = createServer(); server.listen(0, '127.0.0.1', () => { const port = server.address().port; server.close(() => resolve(port)); }); });
|
||||
const origin = `http://127.0.0.1:${port}`;
|
||||
const basePath = process.env.NEXT_PUBLIC_BASE_PATH || '';
|
||||
const initial = randomBytes(24).toString('hex'), password = randomBytes(24).toString('hex');
|
||||
let server, logs = '', checks = 0;
|
||||
const verify = (condition, message) => { assert(condition, message); checks++; };
|
||||
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
||||
async function call(path, { body, cookie, method, headers = {}, form } = {}) {
|
||||
const response = await fetch(origin + basePath + path, { method: method || (body || form ? 'POST' : 'GET'), redirect: 'manual',
|
||||
headers: { 'x-test-client-ip': '198.51.100.20', ...(body || form ? { Origin: origin, 'Content-Type': form ? 'application/x-www-form-urlencoded' : 'application/json' } : {}), ...(cookie ? { Cookie: cookie } : {}), ...headers },
|
||||
body: form ? new URLSearchParams(form).toString() : body ? JSON.stringify(body) : undefined });
|
||||
const text = await response.text(); let data; try { data = JSON.parse(text); } catch { data = text; }
|
||||
return { status: response.status, data, headers: response.headers, cookies: response.headers.getSetCookie().map(c => c.split(';')[0]) };
|
||||
}
|
||||
async function oauth(intent, cookie = '', code = 'bound') {
|
||||
const start = await call('/api/auth/feishu/start', { cookie, form: { intent, next: '/?demand=REQ-NOT-ACCESSIBLE' } });
|
||||
verify(start.status === 303, 'OAuth start redirects');
|
||||
const url = new URL(start.headers.get('location'));
|
||||
verify(url.origin === 'https://accounts.feishu.cn', 'authorization origin is fixed');
|
||||
verify(url.searchParams.get('redirect_uri') === origin + basePath + '/api/auth/feishu/callback', 'callback respects base path');
|
||||
const state = url.searchParams.get('state');
|
||||
const flowCookie = [cookie, ...start.cookies].filter(Boolean).join('; ');
|
||||
return { cookie: flowCookie, path: '/api/auth/feishu/callback?state=' + state + '&code=' + code + '.' + url.searchParams.get('code_challenge') };
|
||||
}
|
||||
try {
|
||||
server = spawn(process.execPath, ['--import', './tests/feishu-fetch.fixture.mjs', 'scripts/start.mjs'], {
|
||||
env: { ...process.env, NODE_ENV: 'production', HOSTNAME: '127.0.0.1', PORT: String(port), APP_URL: origin, DATA_DIR: directory,
|
||||
INITIAL_ADMIN_USERNAME: 'feishu_http_admin', INITIAL_ADMIN_PASSWORD: initial, LOGIN_CLIENT_IP_HEADER: 'x-test-client-ip',
|
||||
FEISHU_APP_ID: 'cli_http_test', FEISHU_APP_SECRET: 'http-test-secret', FEISHU_TENANT_KEY: 'tenant_http_test',
|
||||
FEISHU_BOT_WEBHOOK: 'https://open.feishu.cn/open-apis/bot/v2/hook/http-test-hook', FEISHU_BOT_SECRET: 'http-test-signature' },
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
server.stdout.on('data', c => { logs += c; }); server.stderr.on('data', c => { logs += c; });
|
||||
let ready = false;
|
||||
for (let i = 0; i < 100; i++) { if (server.exitCode !== null) throw new Error(logs); try { if ((await call('/api/health')).status === 200) { ready = true; break; } } catch {} await sleep(150); }
|
||||
assert(ready, logs);
|
||||
verify((await call('/api/admin/feishu')).status === 401, 'anonymous cannot read notifications');
|
||||
verify((await call('/api/admin/feishu', { body: { action: 'test' } })).status === 401, 'anonymous cannot send test');
|
||||
verify((await call('/login')).data.includes('飞书登录'), 'configured login appears');
|
||||
const forged = await call('/api/auth/feishu/start', { form: { intent: 'bind' }, headers: { Origin: 'https://evil.example' } });
|
||||
verify(!forged.headers.get('location').includes('accounts.feishu.cn'), 'cross-origin bind rejected');
|
||||
for (const ip of ['', 'invalid', '198.51.100.20, 198.51.100.21']) {
|
||||
const denied = await call('/api/auth/feishu/start', { form: { intent: 'login' }, headers: { 'x-test-client-ip': ip, 'x-forwarded-for': '198.51.100.20' } });
|
||||
verify(denied.headers.get('location').includes('feishuError=source') && !denied.cookies.length, 'OAuth rejects missing or invalid trusted source');
|
||||
}
|
||||
for (let attempt = 0; attempt < 60; attempt++) {
|
||||
const start = await call('/api/auth/feishu/start', { form: { intent: 'login' }, headers: { 'x-test-client-ip': '198.51.100.90' } });
|
||||
assert(start.headers.get('location').startsWith('https://accounts.feishu.cn/'));
|
||||
}
|
||||
const limited = await call('/api/auth/feishu/start', { form: { intent: 'login' }, headers: { 'x-test-client-ip': '198.51.100.90' } });
|
||||
verify(limited.headers.get('location').includes('feishuError=rate_limited') && !limited.cookies.length, 'OAuth shows a rate-limit error instead of creating state');
|
||||
const limitDb = new DatabaseSync(join(directory, 'demand-center.sqlite'));
|
||||
verify(limitDb.prepare('SELECT COUNT(*) AS n FROM feishu_oauth_states').get().n === 60, 'denied OAuth attempts do not insert rows');
|
||||
limitDb.close();
|
||||
let login = await call('/api/auth/login', { body: { username: 'feishu_http_admin', password: initial } });
|
||||
let admin = login.cookies[0];
|
||||
verify((await call('/api/admin/feishu', { cookie: admin })).status === 403, 'initial password guard applies to integration settings');
|
||||
login = await call('/api/auth/password', { cookie: admin, body: { currentPassword: initial, newPassword: password } });
|
||||
admin = login.cookies[0];
|
||||
const settings = await call('/api/admin/feishu', { cookie: admin });
|
||||
verify(settings.status === 200 && settings.data.botConfigured, 'admin can read redacted configuration');
|
||||
verify(!JSON.stringify(settings.data).includes('http-test-secret') && !JSON.stringify(settings.data).includes('http-test-hook'), 'secrets never returned');
|
||||
const flow = await oauth('bind', admin);
|
||||
const bound = await call(flow.path, { cookie: flow.cookie });
|
||||
verify(bound.status === 303 && bound.headers.get('location').endsWith('/account/feishu?bound=1'), 'binding callback succeeds');
|
||||
verify(bound.cookies.some(c => c === 'demand_feishu_state='), 'state cookie cleared');
|
||||
verify((await call(flow.path, { cookie: flow.cookie })).headers.get('location').includes('expired'), 'replay fails');
|
||||
await call('/api/auth/logout', { cookie: admin, method: 'POST', headers: { Origin: origin } });
|
||||
const loginFlow = await oauth('login');
|
||||
const loggedIn = await call(loginFlow.path, { cookie: loginFlow.cookie });
|
||||
admin = loggedIn.cookies.find(c => c.startsWith('demand_session='));
|
||||
verify(Boolean(admin), 'bound identity creates local session');
|
||||
verify(loggedIn.headers.get('location') === origin + basePath + '/?demand=REQ-NOT-ACCESSIBLE', 'deep link survives OAuth login');
|
||||
verify((await call('/api/auth/me', { cookie: admin })).status === 200, 'OAuth session authenticates');
|
||||
const unbound = await oauth('login', '', 'unbound');
|
||||
const registered = await call(unbound.path, { cookie: unbound.cookie });
|
||||
let autoCookie = registered.cookies.find(cookie => cookie.startsWith('demand_session='));
|
||||
verify(registered.status === 303 && Boolean(autoCookie) && !registered.headers.get('location').includes('/account/password'), 'first Feishu login registers and logs in without password setup');
|
||||
const autoUser = (await call('/api/auth/me', { cookie: autoCookie })).data.user;
|
||||
verify(autoUser.role === 'user' && !autoUser.mustChangePassword && /^feishu_/.test(autoUser.username), 'auto-registration is a regular member with a generated account');
|
||||
verify((await call('/api/demands', { cookie: autoCookie })).status === 200, 'registered member can immediately use workspace');
|
||||
verify((await call('/api/admin/users', { cookie: autoCookie })).status === 403, 'registered member has no admin rights');
|
||||
verify((await call('/api/auth/login', { body: { username: autoUser.username, password: 'dummy timing password that never authenticates' } })).status === 401, 'passwordless account cannot authenticate with timing dummy password');
|
||||
verify((await call('/api/account/feishu', { cookie: autoCookie, method: 'DELETE', body: { password } })).status === 409, 'cannot remove the only available login method');
|
||||
const repeat = await oauth('login', '', 'unbound');
|
||||
const repeatLogin = await call(repeat.path, { cookie: repeat.cookie });
|
||||
autoCookie = repeatLogin.cookies.find(cookie => cookie.startsWith('demand_session='));
|
||||
verify((await call('/api/auth/me', { cookie: autoCookie })).data.user.userId === autoUser.userId, 'repeat login reuses auto-created account');
|
||||
verify((await call('/api/auth/password', { body: { newPassword: password } })).status === 401, 'first password setup requires a session');
|
||||
const firstPassword = await call('/api/auth/password', { cookie: autoCookie, body: { newPassword: password } });
|
||||
verify(firstPassword.status === 200 && firstPassword.cookies.length === 1, 'Feishu member can optionally set first system password');
|
||||
verify((await call('/api/auth/me', { cookie: autoCookie })).status === 401, 'first password setup revokes old sessions');
|
||||
autoCookie = firstPassword.cookies[0];
|
||||
verify((await call('/api/auth/password', { cookie: autoCookie, body: { newPassword: initial } })).status === 400, 'later password changes still require current password');
|
||||
verify((await call('/api/auth/login', { body: { username: autoUser.username, password } })).status === 200, 'optional password enables normal account login');
|
||||
await call('/api/admin/users', { cookie: admin, method: 'PATCH', body: { id: autoUser.userId, action: 'disable' } });
|
||||
const disabledFlow = await oauth('login', '', 'unbound');
|
||||
const disabledLogin = await call(disabledFlow.path, { cookie: disabledFlow.cookie });
|
||||
verify(!disabledLogin.cookies.some(cookie => cookie.startsWith('demand_session=')) && disabledLogin.headers.get('location').includes('feishuError='), 'disabled Feishu account cannot bypass disable by re-registering');
|
||||
await call('/api/admin/users', { cookie: admin, method: 'PATCH', body: { id: autoUser.userId, action: 'enable' } });
|
||||
autoCookie = (await call('/api/auth/login', { body: { username: autoUser.username, password } })).cookies[0];
|
||||
const autoUnlink = await call('/api/account/feishu', { cookie: autoCookie, method: 'DELETE', body: { password } });
|
||||
verify(autoUnlink.status === 200, 'registered member can unlink after setting password');
|
||||
autoCookie = autoUnlink.cookies[0];
|
||||
const member = await call('/api/admin/users', { cookie: admin, body: { username: 'feishu_http_member', displayName: '联调成员', password: initial, role: 'user' } });
|
||||
verify(member.status === 201, 'create member');
|
||||
const ml = await call('/api/auth/login', { body: { username: 'feishu_http_member', password: initial } });
|
||||
const mc = await call('/api/auth/password', { cookie: ml.cookies[0], body: { currentPassword: initial, newPassword: password } });
|
||||
verify((await call('/api/admin/feishu', { cookie: mc.cookies[0] })).status === 403, 'regular member cannot read global notifications');
|
||||
verify((await call('/api/admin/feishu', { cookie: admin, body: { action: 'test' }, headers: { Origin: 'https://evil.example' } })).status === 403, 'bot management requires same origin');
|
||||
verify((await call('/api/admin/feishu', { cookie: admin, body: { action: 'test' } })).status === 200, 'signed test message accepted by mock');
|
||||
verify((await call('/api/admin/feishu', { cookie: admin, body: { action: 'test' } })).status === 429, 'test message rate limited');
|
||||
const fields = { title: '飞书通知联调需求', project: '测试项目', module: '测试模块', type: '新增功能', proposer: '联调管理员', department: '测试部门', source: '本地', owner: '管理员', background: '私密正文不推送', impact: '业务', goal: '验证通知', expectedDate: '', noFixedDate: true, dateReason: '', scope: '', outOfScope: '', criteria: '', priority: 'P2', priorityReason: '', dataSource: '', dataContact: '', noData: true, risk: '', pending: '', references: '', version: 'v1.0' };
|
||||
const draft = await call('/api/demands', { cookie: admin, body: { action: 'create', mode: 'draft', fields } });
|
||||
verify(draft.status === 200, 'draft save succeeds');
|
||||
verify((await call('/api/admin/feishu', { cookie: admin })).data.deliveries.length === 0, 'draft has no notification');
|
||||
const created = await call('/api/demands', { cookie: admin, body: { action: 'update', id: draft.data.demand.id, revision: 1, mode: 'register', fields } });
|
||||
verify(created.status === 200, 'draft becomes formal demand');
|
||||
verify(!(await call('/api/demands', { cookie: autoCookie })).data.demands.some(demand => demand.id === created.data.demand.id), 'new member cannot read another account demand');
|
||||
const conflict = await call('/api/demands', { cookie: admin, body: { action: 'update', id: draft.data.demand.id, revision: 1, mode: 'register', fields } });
|
||||
verify(conflict.status === 409, 'conflicting write rejected');
|
||||
let deliveries;
|
||||
for (let i = 0; i < 60; i++) { deliveries = (await call('/api/admin/feishu', { cookie: admin })).data.deliveries; if (deliveries[0]?.status === 'sent') break; await sleep(150); }
|
||||
verify(deliveries.length === 1 && deliveries[0].status === 'sent', 'instrumentation worker drains committed outbox');
|
||||
const messages = (await readFile(join(directory, 'messages.jsonl'), 'utf8')).trim().split('\n').map(JSON.parse);
|
||||
const nodes = messages[1].content.post.zh_cn.content.flat();
|
||||
const deliveredText = nodes.map(node => node.text).join('\n');
|
||||
verify(messages.length === 2 && deliveredText.includes(created.data.demand.id) && !deliveredText.includes(fields.background), 'only minimal notification and test delivered');
|
||||
verify(nodes.some(node => node.tag === 'a' && node.href === origin + basePath + '/?demand=' + created.data.demand.id), 'notification links respect deployment prefix');
|
||||
const historyDb = new DatabaseSync(join(directory, 'demand-center.sqlite'));
|
||||
const target = historyDb.prepare('SELECT target_key FROM feishu_notifications LIMIT 1').get().target_key;
|
||||
const insert = historyDb.prepare('INSERT INTO feishu_notifications (id,demand_id,revision,target_key,content,status,attempts,next_attempt_at,created_at) VALUES (?,?,?,?,?,?,?,?,?)');
|
||||
for (let index = 1; index <= 52; index++) insert.run('old-failed-' + String(index).padStart(3, '0'), created.data.demand.id, 100 + index, target, '需有序 · 历史失败通知', 'failed', 5, 0, '2026-01-01T00:00:00.000Z');
|
||||
for (let index = 1; index <= 50; index++) insert.run('new-sent-' + String(index).padStart(3, '0'), created.data.demand.id, 200 + index, target, '需有序 · 较新通知', 'sent', 1, 0, '2026-02-01T00:00:00.000Z');
|
||||
historyDb.close();
|
||||
const recent = await call('/api/admin/feishu', { cookie: admin });
|
||||
verify(recent.data.failedCount === 52 && recent.data.deliveries.every(item => item.status === 'sent') && recent.data.nextCursor, 'failure count stays visible outside the current page');
|
||||
const failures = await call('/api/admin/feishu?filter=failed', { cookie: admin });
|
||||
verify(failures.data.deliveries.length === 50 && failures.data.nextCursor, 'failed-only list exposes old failures with pagination');
|
||||
const oldPageUrl = '/api/admin/feishu?filter=failed&cursor=' + failures.data.nextCursor;
|
||||
const oldPage = await call(oldPageUrl, { cookie: admin });
|
||||
verify(oldPage.data.deliveries.length === 2 && oldPage.data.nextCursor === null, 'second failed-only page is reachable');
|
||||
const retried = await call(oldPageUrl, { cookie: admin, body: { action: 'retry', id: oldPage.data.deliveries[0].id } });
|
||||
verify(retried.status === 200 && retried.data.deliveryFilter === 'failed' && retried.data.failedCount === 51 && retried.data.deliveries.length === 1, 'old failure can be retried without resetting the selected page');
|
||||
verify((await call('/api/admin/feishu?filter=unexpected', { cookie: admin })).status === 400, 'invalid filter rejected');
|
||||
verify((await call('/api/admin/feishu?cursor=invalid!', { cookie: admin, body: { action: 'test' } })).status === 400, 'invalid paging rejected before sending test message');
|
||||
if (process.env.FEISHU_BROWSER_PYTHON) {
|
||||
const browser = spawn(process.env.FEISHU_BROWSER_PYTHON, ['tests/feishu.browser.py'], { env: { ...process.env, TEST_ORIGIN: origin + basePath, TEST_USERNAME: 'feishu_http_admin', TEST_PASSWORD: password, TEST_DEMAND_ID: created.data.demand.id }, stdio: 'inherit' });
|
||||
assert.equal(await new Promise(resolve => browser.on('exit', resolve)), 0, 'browser verification failed');
|
||||
}
|
||||
const unlinked = await call('/api/account/feishu', { cookie: admin, method: 'DELETE', body: { password } });
|
||||
verify(unlinked.status === 200 && unlinked.cookies.some(c => c.startsWith('demand_session=')), 'unlink rotates current session');
|
||||
verify((await call('/api/auth/me', { cookie: admin })).status === 401, 'old session invalid after unlink');
|
||||
const db = new DatabaseSync(join(directory, 'demand-center.sqlite'));
|
||||
verify(db.prepare('SELECT COUNT(*) AS n FROM feishu_identities').get().n === 0, 'binding removed'); db.close();
|
||||
console.log(`Feishu HTTP integration passed: ${checks} checks (all external calls mocked).`);
|
||||
} catch (error) { console.error(logs); throw error; }
|
||||
finally { if (server?.exitCode === null) { server.kill('SIGTERM'); await new Promise(resolve => server.once('exit', resolve)); } await rm(directory, { recursive: true, force: true }); }
|
||||
@@ -0,0 +1,350 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { after, before, test } from 'node:test';
|
||||
import { mkdtempSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { createHash, createHmac } from 'node:crypto';
|
||||
import { closeDatabases, getDatabase } from '../lib/server/database.ts';
|
||||
import { AuthError, authenticateSession, changeAccountPassword, createAccount, hasAccountPassword, loginWithPassword, updateAccount } from '../lib/server/auth.ts';
|
||||
import { beginFeishuAuth, completeFeishuAuth, consumeFeishuState, FeishuAuthError, getFeishuBinding, unbindFeishu } from '../lib/server/feishu-auth.ts';
|
||||
import { feishuBotConfig, feishuCallbackUrl } from '../lib/server/feishu-config.ts';
|
||||
import { deliverNextFeishuNotification, feishuStatus, parseFeishuDeliveryQuery, queueDemandNotification, retryFeishuNotification, signFeishuMessage } from '../lib/server/feishu-notifications.ts';
|
||||
import { safeReturnTo } from '../lib/auth-return.ts';
|
||||
import { feishuErrorMessage } from '../lib/feishu.ts';
|
||||
import { emptyFields, type Demand } from '../lib/demand.ts';
|
||||
import { PASSWORD_LOGIN_DISABLED, verifyPassword } from '../lib/server/password.ts';
|
||||
|
||||
const directory = mkdtempSync(join(tmpdir(), 'demand-feishu-tests-'));
|
||||
const env = { ...process.env };
|
||||
const realFetch = globalThis.fetch;
|
||||
const password = 'Feishu local password 12345';
|
||||
let adminId: string, adminToken: string, otherId: string, otherToken: string;
|
||||
let openId = 'ou_test_admin', tenant = 'tenant_test';
|
||||
let sent: Array<{ url: string; init: RequestInit }> = [];
|
||||
let failBot = false;
|
||||
const request = (url: string, cookie = '') => new Request(url, { headers: { cookie } });
|
||||
const isError = (code: string) => (error: unknown) => error instanceof FeishuAuthError && error.code === code;
|
||||
|
||||
before(async () => {
|
||||
Object.assign(process.env, { DATA_DIR: directory, APP_URL: 'https://demand.example.test', INITIAL_ADMIN_USERNAME: 'feishu.admin',
|
||||
INITIAL_ADMIN_PASSWORD: password, FEISHU_APP_ID: 'cli_test', FEISHU_APP_SECRET: 'test-app-secret', FEISHU_TENANT_KEY: 'tenant_test',
|
||||
FEISHU_BOT_WEBHOOK: 'https://open.feishu.cn/open-apis/bot/v2/hook/test-hook', FEISHU_BOT_SECRET: 'test-signing-secret' });
|
||||
delete process.env.LOGIN_CLIENT_IP_HEADER;
|
||||
const login = await loginWithPassword('feishu.admin', password);
|
||||
adminId = login.user.userId;
|
||||
adminToken = (await changeAccountPassword(adminId, password, password + ' changed')).token;
|
||||
const other = await createAccount(adminId, { username: 'feishu.member', displayName: '其他用户', password, role: 'user' });
|
||||
otherId = other.userId;
|
||||
otherToken = (await changeAccountPassword(otherId, password, password + ' changed')).token;
|
||||
globalThis.fetch = async (input, init = {}) => {
|
||||
const url = String(input);
|
||||
sent.push({ url, init });
|
||||
if (url.endsWith('/authen/v2/oauth/token')) return Response.json({ code: 0, access_token: 'ephemeral-user-token' });
|
||||
if (url.endsWith('/authen/v1/user_info')) return Response.json({ code: 0, data: { open_id: openId, tenant_key: tenant, name: '飞书测试用户' } });
|
||||
if (url.includes('/bot/v2/hook/')) return Response.json(failBot ? { code: 19021, msg: 'secret echoed, must not be stored' } : { code: 0 });
|
||||
throw new Error('Unexpected network call: ' + url);
|
||||
};
|
||||
});
|
||||
after(() => { globalThis.fetch = realFetch; closeDatabases(); rmSync(directory, { recursive: true, force: true }); process.env = env; });
|
||||
|
||||
function start(intent = 'login', token = '', returnTo = '/?demand=REQ-TEST') {
|
||||
const sessionCookie = token ? `demand_session=${token}` : '';
|
||||
const started = beginFeishuAuth(request('https://demand.example.test/api/auth/feishu/start', sessionCookie), intent, returnTo);
|
||||
const authorize = new URL(started.url);
|
||||
const callback = request(feishuCallbackUrl() + '?state=' + authorize.searchParams.get('state') + '&code=test-code',
|
||||
[sessionCookie, started.cookie.split(';')[0]].filter(Boolean).join('; '));
|
||||
return { ...started, authorize, callback };
|
||||
}
|
||||
async function finish(flow: ReturnType<typeof start>) { return completeFeishuAuth(flow.callback, consumeFeishuState(flow.callback)); }
|
||||
|
||||
test('configuration never exposes secrets and return URLs cannot leave the app', () => {
|
||||
assert.equal(feishuErrorMessage('__proto__'), '');
|
||||
assert.equal(feishuErrorMessage(['unbound']), '');
|
||||
for (const value of ['//evil.example', '/\\evil.example', 'https://evil.example', '/a/..//evil.example', '/api/auth/logout', '/login', '/\nevil']) assert.equal(safeReturnTo(value), '/');
|
||||
assert.equal(safeReturnTo('/?demand=REQ-TEST'), '/?demand=REQ-TEST');
|
||||
const status = JSON.stringify(feishuStatus());
|
||||
for (const secret of ['test-hook', 'test-signing-secret', 'test-app-secret']) assert.ok(!status.includes(secret));
|
||||
const webhook = process.env.FEISHU_BOT_WEBHOOK;
|
||||
for (const value of ['http://localhost/hook/x', 'https://open.feishu.cn.evil.com/open-apis/bot/v2/hook/x', 'https://open.feishu.cn/open-apis/bot/v2/hook/x?secret=y']) {
|
||||
process.env.FEISHU_BOT_WEBHOOK = value;
|
||||
assert.throws(feishuBotConfig);
|
||||
}
|
||||
process.env.FEISHU_BOT_WEBHOOK = webhook;
|
||||
});
|
||||
|
||||
test('OAuth uses PKCE, browser-bound state, single consumption and expiration', () => {
|
||||
const flow = start();
|
||||
assert.equal(flow.authorize.origin, 'https://accounts.feishu.cn');
|
||||
assert.equal(flow.authorize.searchParams.get('code_challenge_method'), 'S256');
|
||||
assert.ok(flow.cookie.includes('HttpOnly; SameSite=Lax; Max-Age=600; Secure'));
|
||||
assert.throws(() => consumeFeishuState(request(flow.callback.url, 'demand_feishu_state=' + 'a'.repeat(43))), isError('expired'));
|
||||
const state = consumeFeishuState(flow.callback);
|
||||
assert.equal(flow.authorize.searchParams.get('code_challenge'), createHash('sha256').update(state.verifier).digest('base64url'));
|
||||
assert.throws(() => consumeFeishuState(flow.callback), isError('expired'));
|
||||
const expired = start();
|
||||
getDatabase().prepare('UPDATE feishu_oauth_states SET expires_at = 0').run();
|
||||
assert.throws(() => consumeFeishuState(expired.callback), isError('expired'));
|
||||
});
|
||||
|
||||
test('OAuth checks trusted IP and shares the persistent password-login source quota before creating state', async () => {
|
||||
process.env.LOGIN_CLIENT_IP_HEADER = 'x-real-ip';
|
||||
const db = getDatabase();
|
||||
db.prepare('DELETE FROM feishu_oauth_states').run();
|
||||
const req = (ip: string, extra: Record<string, string> = {}) => new Request('https://demand.example.test/api/auth/feishu/start', { headers: { 'x-real-ip': ip, ...extra } });
|
||||
try {
|
||||
for (const ip of ['', 'invalid', '192.0.2.10, 192.0.2.11']) {
|
||||
assert.throws(() => beginFeishuAuth(req(ip, { 'x-forwarded-for': '192.0.2.10' }), 'login', '/'), error => error instanceof AuthError && error.status === 403);
|
||||
}
|
||||
assert.equal(db.prepare('SELECT COUNT(*) AS n FROM feishu_oauth_states').first<{ n: number }>()!.n, 0);
|
||||
for (let i = 0; i < 59; i++) beginFeishuAuth(req('192.0.2.10'), 'login', '/');
|
||||
await assert.rejects(() => loginWithPassword('missing.account', password, req('192.0.2.10')), error => error instanceof AuthError && error.status === 401);
|
||||
closeDatabases();
|
||||
assert.throws(() => beginFeishuAuth(req('192.0.2.10', { 'x-forwarded-for': '192.0.2.11' }), 'login', '/'), error => error instanceof AuthError && error.status === 429);
|
||||
assert.equal(getDatabase().prepare('SELECT COUNT(*) AS n FROM feishu_oauth_states').first<{ n: number }>()!.n, 59);
|
||||
beginFeishuAuth(req('192.0.2.11'), 'login', '/');
|
||||
getDatabase().prepare('UPDATE login_limits SET window_start = ?').bind(Date.now() - 61_000).run();
|
||||
beginFeishuAuth(req('192.0.2.10'), 'login', '/');
|
||||
} finally { delete process.env.LOGIN_CLIENT_IP_HEADER; }
|
||||
});
|
||||
|
||||
test('first Feishu login registers a regular member without requiring a password or merging names', async () => {
|
||||
openId = 'ou_new_member';
|
||||
const first = await finish(start());
|
||||
assert.equal(first.user.role, 'user');
|
||||
assert.equal(first.user.mustChangePassword, false);
|
||||
assert.equal(first.user.displayName, '飞书测试用户');
|
||||
assert.match(first.user.username, /^feishu_[a-f0-9]{32}$/);
|
||||
assert.ok(![adminId, otherId].includes(first.user.userId));
|
||||
assert.equal(first.returnTo, '/?demand=REQ-TEST');
|
||||
assert.equal(authenticateSession(first.token!)?.userId, first.user.userId);
|
||||
assert.equal(hasAccountPassword(first.user.userId), false);
|
||||
const storedHash = getDatabase().prepare('SELECT password_hash FROM accounts WHERE id = ?').bind(first.user.userId).first<{ password_hash: string }>()!.password_hash;
|
||||
assert.equal(storedHash, PASSWORD_LOGIN_DISABLED);
|
||||
assert.equal(await verifyPassword('dummy timing password that never authenticates', storedHash), false, 'older password verifiers also reject the disabled marker');
|
||||
assert.equal(getFeishuBinding(first.user.userId)?.name, '飞书测试用户');
|
||||
const again = await finish(start());
|
||||
assert.equal(again.user.userId, first.user.userId);
|
||||
assert.equal(getDatabase().prepare('SELECT COUNT(*) AS n FROM accounts').first<{ n: number }>()!.n, 3);
|
||||
await assert.rejects(() => loginWithPassword(first.user.username, 'dummy timing password that never authenticates'), error => error instanceof AuthError && error.status === 401);
|
||||
const req = request('https://demand.example.test/api/account/feishu', 'demand_session=' + again.token);
|
||||
await assert.rejects(() => unbindFeishu(again.user, 'anything', req), /先设置系统密码/);
|
||||
const withPassword = await changeAccountPassword(first.user.userId, undefined, password);
|
||||
assert.equal(hasAccountPassword(first.user.userId), true);
|
||||
assert.equal(authenticateSession(again.token!), null);
|
||||
assert.ok(authenticateSession(withPassword.token));
|
||||
assert.equal((await loginWithPassword(first.user.username, password)).user.userId, first.user.userId);
|
||||
await assert.rejects(() => changeAccountPassword(first.user.userId, undefined, password + ' changed'), /当前密码/);
|
||||
await updateAccount(adminId, { id: first.user.userId, action: 'disable' });
|
||||
await assert.rejects(() => finish(start()), /账号已停用/);
|
||||
assert.equal(getDatabase().prepare('SELECT COUNT(*) AS n FROM accounts').first<{ n: number }>()!.n, 3);
|
||||
openId = 'ou_test_admin';
|
||||
assert.throws(() => start('bind'), isError('session'));
|
||||
});
|
||||
|
||||
test('concurrent first logins create one account; binding insertion failure rolls back account and session creation', async () => {
|
||||
openId = 'ou_concurrent';
|
||||
const count = () => getDatabase().prepare('SELECT COUNT(*) AS n FROM accounts').first<{ n: number }>()!.n;
|
||||
const before = count();
|
||||
const [first, second] = await Promise.all([finish(start()), finish(start())]);
|
||||
assert.equal(first.user.userId, second.user.userId);
|
||||
assert.equal(count(), before + 1);
|
||||
const db = getDatabase();
|
||||
db.prepare("CREATE TRIGGER reject_registration BEFORE INSERT ON feishu_identities WHEN NEW.open_id = 'ou_rollback' BEGIN SELECT RAISE(ABORT, 'registration failure'); END").run();
|
||||
openId = 'ou_rollback';
|
||||
const sessionsBefore = db.prepare('SELECT COUNT(*) AS n FROM sessions').first<{ n: number }>()!.n;
|
||||
try {
|
||||
await assert.rejects(() => finish(start()), /registration failure/);
|
||||
assert.equal(count(), before + 1);
|
||||
assert.equal(db.prepare('SELECT COUNT(*) AS n FROM sessions').first<{ n: number }>()!.n, sessionsBefore);
|
||||
} finally { db.prepare('DROP TRIGGER reject_registration').run(); openId = 'ou_test_admin'; }
|
||||
});
|
||||
|
||||
test('binding preserves existing role and ownership and stores no OAuth tokens', async () => {
|
||||
sent = [];
|
||||
const flow = start('bind', adminToken);
|
||||
const result = await finish(flow);
|
||||
assert.equal(result.bound, true);
|
||||
assert.equal(result.user.userId, adminId);
|
||||
assert.equal(result.user.role, 'admin');
|
||||
assert.equal(getFeishuBinding(adminId)?.name, '飞书测试用户');
|
||||
assert.equal(Object.getPrototypeOf(getFeishuBinding(adminId)), Object.prototype, 'binding is serializable by React server components');
|
||||
assert.equal(sent[0].url, 'https://open.feishu.cn/open-apis/authen/v2/oauth/token');
|
||||
assert.equal((sent[0].init.headers as Record<string, string>)['Content-Type'], 'application/json');
|
||||
const tokenBody = JSON.parse(sent[0].init.body as string);
|
||||
assert.equal(tokenBody.redirect_uri, feishuCallbackUrl());
|
||||
assert.equal(tokenBody.code_verifier.length, 43);
|
||||
assert.equal(createHash('sha256').update(tokenBody.code_verifier).digest('base64url'), flow.authorize.searchParams.get('code_challenge'));
|
||||
assert.equal((sent[1].init.headers as Record<string, string>).Authorization, 'Bearer ephemeral-user-token');
|
||||
assert.equal(JSON.stringify(getDatabase().prepare('SELECT * FROM feishu_identities').all()).includes('ephemeral-user-token'), false);
|
||||
const login = await finish(start());
|
||||
assert.equal(login.user.userId, adminId);
|
||||
assert.equal(login.returnTo, '/?demand=REQ-TEST');
|
||||
assert.equal(authenticateSession(login.token!)?.role, 'admin');
|
||||
});
|
||||
|
||||
test('tenant boundaries, identity conflicts, session switching and disabled users fail closed', async () => {
|
||||
const before = getDatabase().prepare('SELECT COUNT(*) AS n FROM accounts').first<{ n: number }>()!.n;
|
||||
tenant = 'wrong-enterprise';
|
||||
await assert.rejects(() => finish(start()), isError('tenant'));
|
||||
assert.equal(getDatabase().prepare('SELECT COUNT(*) AS n FROM accounts').first<{ n: number }>()!.n, before);
|
||||
tenant = 'tenant_test';
|
||||
await assert.rejects(() => finish(start('bind', otherToken)), isError('conflict'));
|
||||
const switched = start('bind', adminToken);
|
||||
const changedRequest = request(switched.callback.url, switched.callback.headers.get('cookie')!.replace(adminToken, otherToken));
|
||||
await assert.rejects(() => completeFeishuAuth(changedRequest, consumeFeishuState(changedRequest)), isError('session'));
|
||||
openId = 'ou_other';
|
||||
await finish(start('bind', otherToken));
|
||||
await updateAccount(adminId, { id: otherId, action: 'disable' });
|
||||
await assert.rejects(() => finish(start()), /账号已停用/);
|
||||
await updateAccount(adminId, { id: otherId, action: 'enable' });
|
||||
await updateAccount(adminId, { id: otherId, action: 'reset-password', password });
|
||||
const resetLogin = await finish(start());
|
||||
assert.equal(resetLogin.user.mustChangePassword, true);
|
||||
assert.equal(resetLogin.returnTo, '/account/password');
|
||||
openId = 'ou_test_admin';
|
||||
});
|
||||
|
||||
test('cancellation and app rotation do not issue sessions', async () => {
|
||||
const flow = start();
|
||||
const cancelled = request(flow.callback.url + '&error=access_denied', flow.callback.headers.get('cookie')!);
|
||||
await assert.rejects(() => completeFeishuAuth(cancelled, consumeFeishuState(cancelled)), isError('denied'));
|
||||
const rotated = start();
|
||||
process.env.FEISHU_APP_ID = 'cli_replaced';
|
||||
await assert.rejects(() => finish(rotated), isError('expired'));
|
||||
process.env.FEISHU_APP_ID = 'cli_test';
|
||||
});
|
||||
|
||||
test('unlink requires password and revokes existing sessions and pending binding flows', async () => {
|
||||
const user = authenticateSession(adminToken)!;
|
||||
const req = request('https://demand.example.test/api/account/feishu', 'demand_session=' + adminToken);
|
||||
await assert.rejects(() => unbindFeishu(user, 'wrong password', req));
|
||||
assert.ok(getFeishuBinding(adminId));
|
||||
const pending = start('bind', adminToken);
|
||||
const unbound = await unbindFeishu(user, password + ' changed', req);
|
||||
assert.equal(getFeishuBinding(adminId), null);
|
||||
assert.equal(authenticateSession(adminToken), null);
|
||||
assert.ok(authenticateSession(unbound.token));
|
||||
assert.throws(() => consumeFeishuState(pending.callback), isError('expired'));
|
||||
const newAccount = await finish(start());
|
||||
assert.notEqual(newAccount.user.userId, adminId);
|
||||
assert.equal(newAccount.user.role, 'user');
|
||||
assert.equal(authenticateSession(unbound.token)?.userId, adminId, 'unlink keeps the original password account and data ownership');
|
||||
adminToken = unbound.token;
|
||||
});
|
||||
|
||||
function fixture(revision = 1): Demand {
|
||||
return { id: 'REQ-FEISHU', revision, fields: { ...emptyFields, title: '通知需求', background: 'private body excluded' }, status: '待评审',
|
||||
reviewReady: true, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), changes: [],
|
||||
history: [{ time: new Date().toISOString(), actor: '测试成员', action: '提交评审', detail: 'private detail excluded' }] };
|
||||
}
|
||||
function queue(revision: number) { const d = fixture(revision); getDatabase().transaction(() => queueDemandNotification(d)); }
|
||||
function due() { getDatabase().prepare("UPDATE feishu_notifications SET next_attempt_at = 0 WHERE status != 'sent'").run(); }
|
||||
|
||||
test('transactional outbox suppresses drafts, rolled-back saves and duplicate revisions', () => {
|
||||
const d = fixture();
|
||||
getDatabase().prepare('INSERT INTO demands (id, owner_id, payload, revision, updated_at) VALUES (?, ?, ?, 1, ?)')
|
||||
.bind(d.id, adminId, JSON.stringify(d), d.updatedAt).run();
|
||||
queueDemandNotification({ ...d, status: '草稿' });
|
||||
assert.equal(feishuStatus().deliveries.length, 0);
|
||||
assert.throws(() => getDatabase().transaction(() => { queueDemandNotification(d); throw new Error('rollback'); }));
|
||||
assert.equal(feishuStatus().deliveries.length, 0);
|
||||
queue(1); queue(1);
|
||||
assert.equal(feishuStatus().deliveries.length, 1);
|
||||
assert.equal(Object.getPrototypeOf(feishuStatus().deliveries[0]), Object.prototype, 'delivery is serializable by React server components');
|
||||
const content = getDatabase().prepare('SELECT content FROM feishu_notifications').first<{ content: string }>()!.content;
|
||||
assert.ok(content.includes('/?demand=REQ-FEISHU'));
|
||||
assert.ok(!content.includes('private'));
|
||||
});
|
||||
|
||||
test('signed delivery is sent once on success, with one lease across concurrent workers', async () => {
|
||||
sent = [];
|
||||
const results = await Promise.all([deliverNextFeishuNotification(), deliverNextFeishuNotification()]);
|
||||
assert.equal(results.filter(Boolean).length, 1);
|
||||
assert.equal(sent.length, 1);
|
||||
const body = JSON.parse(sent[0].init.body as string);
|
||||
assert.equal(body.sign, createHmac('sha256', body.timestamp + '\ntest-signing-secret').digest('base64'));
|
||||
assert.equal(signFeishuMessage('100', 'secret'), createHmac('sha256', '100\nsecret').digest('base64'));
|
||||
assert.equal(feishuStatus().deliveries[0].status, 'sent');
|
||||
assert.equal(await deliverNextFeishuNotification(), false);
|
||||
});
|
||||
|
||||
test('queued mention markup stays literal text and only the real detail link becomes a link node', async () => {
|
||||
const d = fixture(10);
|
||||
d.fields.title = '<at user_id="all">所有人</at> <at user_id="all">';
|
||||
d.history[0].actor = '<at user_id="ou_member">成员</at>';
|
||||
getDatabase().transaction(() => queueDemandNotification(d));
|
||||
assert.ok(getDatabase().prepare('SELECT content FROM feishu_notifications WHERE revision = 10').first<{ content: string }>()!.content.includes('<at'));
|
||||
sent = [];
|
||||
await deliverNextFeishuNotification();
|
||||
const body = JSON.parse(sent[0].init.body as string);
|
||||
assert.equal(body.msg_type, 'post');
|
||||
const nodes = body.content.post.zh_cn.content.flat();
|
||||
assert.ok(nodes.every((node: { tag: string }) => node.tag === 'text' || node.tag === 'a'));
|
||||
assert.ok(nodes.some((node: { text: string }) => node.text === d.fields.title));
|
||||
assert.ok(nodes.filter((node: { tag: string }) => node.tag === 'text').every((node: { un_escape: boolean }) => node.un_escape === false));
|
||||
assert.equal(nodes.filter((node: { tag: string }) => node.tag === 'a').length, 1);
|
||||
assert.equal(nodes.at(-1).href, 'https://demand.example.test/?demand=REQ-FEISHU');
|
||||
});
|
||||
|
||||
test('failed messages retry with backoff, survive restart and can be manually retried', async () => {
|
||||
queue(2); failBot = true;
|
||||
for (let i = 0; i < 5; i++) {
|
||||
due(); await deliverNextFeishuNotification();
|
||||
closeDatabases();
|
||||
const delivery = feishuStatus().deliveries.find(d => d.revision === 2)!;
|
||||
assert.equal(delivery.attempts, i + 1);
|
||||
assert.equal(delivery.status, i === 4 ? 'failed' : 'pending');
|
||||
assert.ok(!delivery.lastError?.includes('secret echoed'));
|
||||
assert.equal(await deliverNextFeishuNotification(), false);
|
||||
}
|
||||
const failed = feishuStatus().deliveries.find(d => d.revision === 2)!;
|
||||
retryFeishuNotification(failed.id); failBot = false;
|
||||
await deliverNextFeishuNotification();
|
||||
assert.equal(feishuStatus().deliveries.find(d => d.revision === 2)?.status, 'sent');
|
||||
assert.throws(() => retryFeishuNotification(failed.id));
|
||||
});
|
||||
|
||||
test('changing destination cannot leak queued messages into another group', async () => {
|
||||
queue(3); sent = [];
|
||||
process.env.FEISHU_BOT_WEBHOOK = 'https://open.feishu.cn/open-apis/bot/v2/hook/new-target';
|
||||
assert.equal(await deliverNextFeishuNotification(), false);
|
||||
assert.equal(sent.length, 0);
|
||||
const old = feishuStatus().deliveries.find(d => d.revision === 3)!;
|
||||
assert.equal(old.status, 'failed');
|
||||
assert.throws(() => retryFeishuNotification(old.id));
|
||||
delete process.env.FEISHU_BOT_WEBHOOK;
|
||||
queue(4);
|
||||
assert.ok(!feishuStatus().deliveries.some(d => d.revision === 4));
|
||||
});
|
||||
|
||||
test('old failed notifications remain discoverable and retryable across filtered cursor pages', () => {
|
||||
process.env.FEISHU_BOT_WEBHOOK = 'https://open.feishu.cn/open-apis/bot/v2/hook/test-hook';
|
||||
const db = getDatabase();
|
||||
db.prepare('DELETE FROM feishu_notifications').run();
|
||||
for (let revision = 1; revision <= 102; revision++) queue(revision);
|
||||
// Equal timestamps force stable pagination on the ID tie-breaker.
|
||||
db.prepare("UPDATE feishu_notifications SET status = 'failed', created_at = '2026-01-01T00:00:00.000Z' WHERE revision <= 52").run();
|
||||
db.prepare("UPDATE feishu_notifications SET status = 'sent', created_at = '2026-02-01T00:00:00.000Z' WHERE revision > 52").run();
|
||||
const first = feishuStatus();
|
||||
assert.equal(first.failedCount, 52);
|
||||
assert.equal(first.deliveries.filter(row => row.status === 'failed').length, 0);
|
||||
assert.ok(first.nextCursor);
|
||||
const query = (filter: string, cursor?: string | null) => parseFeishuDeliveryQuery(new URLSearchParams({ filter, ...(cursor ? { cursor } : {}) }));
|
||||
const failedFirst = feishuStatus(query('failed'));
|
||||
assert.equal(failedFirst.deliveries.length, 50);
|
||||
assert.ok(failedFirst.deliveries.every(row => row.status === 'failed'));
|
||||
const failedNext = feishuStatus(query('failed', failedFirst.nextCursor));
|
||||
assert.equal(failedNext.deliveries.length, 2);
|
||||
assert.equal(failedNext.nextCursor, null);
|
||||
assert.equal(new Set([...failedFirst.deliveries, ...failedNext.deliveries].map(row => row.id)).size, 52);
|
||||
const allSecond = feishuStatus(query('all', first.nextCursor));
|
||||
assert.equal(allSecond.deliveries.length, 50);
|
||||
// A new item must not shift the cursor and duplicate/skip records on later pages.
|
||||
queue(103);
|
||||
assert.deepEqual(feishuStatus(query('all', first.nextCursor)).deliveries.map(row => row.id), allSecond.deliveries.map(row => row.id));
|
||||
retryFeishuNotification(failedNext.deliveries[0].id);
|
||||
assert.equal(feishuStatus(query('failed')).failedCount, 51);
|
||||
assert.equal(feishuStatus(query('failed', failedFirst.nextCursor)).deliveries.length, 1);
|
||||
assert.throws(() => query('unexpected'), /筛选条件/);
|
||||
for (const cursor of ['invalid!', 'a', 'a'.repeat(513), Buffer.from('{"createdAt":"bad","id":"x"}').toString('base64url')]) assert.throws(() => query('all', cursor), /分页参数/);
|
||||
});
|
||||
@@ -0,0 +1,295 @@
|
||||
/** Runs against a disposable production instance; never writes to ./data or the hosted site. */
|
||||
import assert from 'node:assert/strict';
|
||||
import { spawn, execFile } from 'node:child_process';
|
||||
import { promisify } from 'node:util';
|
||||
import { mkdtemp, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { createServer } from 'node:net';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
|
||||
const directory=await mkdtemp(join(tmpdir(),'demand-selfhost-test-'));
|
||||
const port=await new Promise(resolve=>{const s=createServer();s.listen(0,'127.0.0.1',()=>{const p=s.address().port;s.close(()=>resolve(p));});});
|
||||
const origin=`http://127.0.0.1:${port}`;
|
||||
const basePath=process.env.NEXT_PUBLIC_BASE_PATH||'';
|
||||
const secret=()=>randomBytes(24).toString('base64url');
|
||||
const initial=secret(),adminPassword=secret(),memberInitial=secret(),memberPassword=secret();
|
||||
let processHandle,logs='',checks=0;
|
||||
const verify=(condition,message)=>{assert(condition,message);checks++;};
|
||||
async function start(){
|
||||
processHandle=spawn(process.execPath,['scripts/start.mjs'],{cwd:process.cwd(),env:{...process.env,NODE_ENV:'production',HOSTNAME:'127.0.0.1',PORT:String(port),APP_URL:origin,DATA_DIR:directory,INITIAL_ADMIN_USERNAME:'test_admin',INITIAL_ADMIN_PASSWORD:initial,INITIAL_ADMIN_DISPLAY_NAME:'测试管理员',LOGIN_CLIENT_IP_HEADER:'x-test-client-ip'},stdio:['ignore','pipe','pipe']});
|
||||
processHandle.stdout.on('data',chunk=>{logs+=chunk.toString()});processHandle.stderr.on('data',chunk=>{logs+=chunk.toString()});
|
||||
for(let i=0;i<160;i++){if(processHandle.exitCode!==null)throw new Error('Test server exited: '+logs);try{const r=await fetch(origin+basePath+'/api/health');if(r.ok)return;}catch{}await new Promise(resolve=>setTimeout(resolve,150));}
|
||||
throw new Error('Test server did not become ready: '+logs);
|
||||
}
|
||||
async function stop(){if(processHandle&&processHandle.exitCode===null){processHandle.kill('SIGTERM');await new Promise(resolve=>processHandle.once('exit',resolve));}}
|
||||
async function call(path,{body,cookie,method,headers}={}){
|
||||
const r=await fetch(origin+basePath+path,{method:method??(body?'POST':'GET'),redirect:'manual',headers:{'x-test-client-ip':'198.51.100.10',...(body?{'Content-Type':'application/json',Origin:origin}:{}),...(cookie?{Cookie:cookie}:{}),...headers},body:body?JSON.stringify(body):undefined});
|
||||
const text=await r.text();let data;try{data=JSON.parse(text)}catch{data=text}
|
||||
return {status:r.status,data,headers:r.headers,cookie:r.headers.get('set-cookie')?.split(';')[0]};
|
||||
}
|
||||
try{
|
||||
await start();
|
||||
verify((await call('/api/demands')).status===401,'anonymous demands denied');
|
||||
verify((await call('/api/admin/users')).status===401,'anonymous account administration denied');
|
||||
verify((await call('/api/documents/'+encodeURIComponent('开发SOP_公示版.md'))).status===401,'SOP requires authentication');
|
||||
verify((await call('/api/demands',{headers:{'oai-authenticated-user-id':'spoof','oai-authenticated-user-email':'spoof@example.com'}})).status===401,'hosted identity header cannot authenticate');
|
||||
verify((await call('/api/auth/login',{body:{username:'test_admin',password:initial},headers:{'x-test-client-ip':'','x-forwarded-for':'198.51.100.11'}})).status===403,'missing trusted client address cannot fall back to a spoofed forwarding header');
|
||||
verify((await call('/api/auth/login',{body:{username:'test_admin',password:initial},headers:{'x-test-client-ip':'198.51.100.11, 198.51.100.12'}})).status===403,'trusted client address must be one valid IP');
|
||||
let login=await call('/api/auth/login',{body:{username:'test_admin',password:initial}});
|
||||
verify(login.status===200&&!!login.cookie,'bootstrap admin can log in');
|
||||
verify(login.headers.get('set-cookie').includes(`Path=${basePath||'/'};`),'session cookie scoped to configured base path');
|
||||
let admin=login.cookie;
|
||||
verify(login.data.user.mustChangePassword,'bootstrap password change required');
|
||||
verify((await call('/api/admin/users',{cookie:admin})).status===403,'unchanged initial password cannot administer');
|
||||
verify((await call('/api/auth/password',{cookie:admin,body:{currentPassword:initial,newPassword:adminPassword},headers:{Origin:'https://untrusted.example'}})).status===403,'cross-origin password change blocked');
|
||||
const changed=await call('/api/auth/password',{cookie:admin,body:{currentPassword:initial,newPassword:adminPassword}});
|
||||
verify(changed.status===200,'bootstrap password changed');
|
||||
login=await call('/api/auth/login',{body:{username:'test_admin',password:adminPassword}});admin=login.cookie;
|
||||
verify(login.status===200&&!login.data.user.mustChangePassword,'password change retained');
|
||||
verify((await call('/api/admin/users',{cookie:admin})).status===200,'admin list available');
|
||||
const created=await call('/api/admin/users',{cookie:admin,body:{username:'business_one',displayName:'业务测试用户',password:memberInitial,role:'user'}});
|
||||
verify(created.status===200||created.status===201,'admin creates an allowed account: '+JSON.stringify(created.data));
|
||||
const accountList=await call('/api/admin/users',{cookie:admin});
|
||||
const member=accountList.data.users.find(u=>u.username==='business_one');
|
||||
verify(!!member,'created account listed');
|
||||
const memberId=member.userId??member.id;
|
||||
verify(!JSON.stringify(accountList.data).includes('password_hash'),'password hashes not returned');
|
||||
let memberLogin=await call('/api/auth/login',{body:{username:'business_one',password:memberInitial}});
|
||||
verify(memberLogin.status===200&&memberLogin.data.user.mustChangePassword,'new account forced to change password');
|
||||
verify((await call('/api/demands',{cookie:memberLogin.cookie})).status===403,'initial password cannot use business API');
|
||||
verify((await call('/api/auth/password',{cookie:memberLogin.cookie,body:{currentPassword:memberInitial,newPassword:memberPassword}})).status===200,'member sets own password');
|
||||
memberLogin=await call('/api/auth/login',{body:{username:'business_one',password:memberPassword}});let memberCookie=memberLogin.cookie;
|
||||
verify((await call('/api/admin/users',{cookie:memberCookie})).status===403,'regular user cannot administer accounts');
|
||||
verify((await call('/api/documents/'+encodeURIComponent('附件01_需求登记模板.md'),{cookie:memberCookie})).status===200,'authorized user can download template');
|
||||
verify((await call('/api/documents/'+encodeURIComponent('附件02_需求文档模板.md')+'?format=json')).status===401,'document preview requires authentication');
|
||||
verify((await call('/api/documents/'+encodeURIComponent('附件02_需求文档模板.md')+'?format=docx')).status===401,'Word download requires authentication');
|
||||
const preview=await call('/api/documents/'+encodeURIComponent('附件02_需求文档模板.md')+'?format=json',{cookie:memberCookie});
|
||||
verify(preview.status===200&&preview.data.content.includes('背景与目标')&&preview.data.content.includes('开发责任人'),'authenticated preview provides the canonical template content');
|
||||
for(const name of ['开发SOP_公示版.md','附件01_需求登记模板.md','附件02_需求文档模板.md','附件03_数据来源填写模板.md','附件04_验收记录模板.md','附件05_需求变更记录模板.md','附件06_缺陷记录模板.md','附件07_发布记录模板.md']){
|
||||
const response=await fetch(origin+basePath+'/api/documents/'+encodeURIComponent(name)+'?format=docx',{headers:{Cookie:memberCookie}});
|
||||
const bytes=new Uint8Array(await response.arrayBuffer());
|
||||
verify(response.status===200&&response.headers.get('content-type').includes('wordprocessingml')&&response.headers.get('content-disposition').includes(encodeURIComponent(name.replace('.md','.docx')))&&bytes[0]===0x50&&bytes[1]===0x4b,'Word download is a genuine DOCX archive: '+name);
|
||||
}
|
||||
verify((await call('/api/documents/'+encodeURIComponent('附件02_需求文档模板.md')+'?format=invalid',{cookie:memberCookie})).status===400,'unsupported document format is rejected');
|
||||
verify((await call('/api/documents/not-a-template?format=docx',{cookie:memberCookie})).status===404,'unknown document cannot read arbitrary files');
|
||||
const fields={title:'仅本地自动测试的需求',project:'测试项目',module:'业务模块',type:'新增功能',proposer:'测试用户',department:'业务部门',source:'本地测试',owner:'测试用户',background:'业务背景',impact:'业务岗位',goal:'期望结果',expectedDate:'',noFixedDate:true,dateReason:'',scope:'',outOfScope:'',criteria:'',priority:'P2',priorityReason:'',dataSource:'',dataContact:'',noData:true,risk:'',pending:'',references:'',version:'v1.0'};
|
||||
const demand=await call('/api/demands',{cookie:memberCookie,body:{action:'create',mode:'register',fields}});
|
||||
verify(demand.status===200,'member registers a demand');
|
||||
verify((await call('/api/demands',{cookie:admin})).data.demands.some(d=>d.id===demand.data.demand.id&&!d.access.business&&d.access.developer),'new formal demand defaults to administrator development');
|
||||
verify((await call('/api/demands',{cookie:admin,body:{action:'cancel',id:demand.data.demand.id,revision:1,reason:'不应成功'}})).status===403,'default developer cannot cancel business demand');
|
||||
const reviewFields={...fields,title:'本地测试:评审时确定方案',criteria:'业务人员按订单状态查询后,结果均符合所选状态。',priorityReason:'减少业务查询耗时',risk:'无',pending:'无'};
|
||||
const reviewDemand=await call('/api/demands',{cookie:memberCookie,body:{action:'create',mode:'review',fields:reviewFields}});
|
||||
verify(reviewDemand.status===200&&reviewDemand.data.demand.reviewReady,'business can submit for review before the developer proposes scope');
|
||||
verify(reviewDemand.data.demand.fields.scope===''&&reviewDemand.data.demand.fields.outOfScope==='','review submission does not invent a solution or exclusions');
|
||||
const reviewedUpdate=await call('/api/demands',{cookie:memberCookie,body:{action:'update',id:demand.data.demand.id,revision:1,mode:'review',fields:{...reviewFields,title:fields.title}}});
|
||||
verify(reviewedUpdate.status===200&&reviewedUpdate.data.demand.reviewReady,'registered demand can be completed and submitted without a solution');
|
||||
const missingCriteria=await call('/api/demands',{cookie:memberCookie,body:{action:'create',mode:'review',fields:{...reviewFields,title:'本地测试:缺少业务验收标准',criteria:''}}});
|
||||
verify(missingCriteria.status===400&&missingCriteria.data.error.includes('验收标准'),'review still requires business acceptance criteria');
|
||||
const legacyFields={...reviewFields,scope:'原有功能说明',outOfScope:'原有范围外事项'};
|
||||
// Simulate a record created before review ownership was introduced, using only this disposable database.
|
||||
const legacyDatabase=new DatabaseSync(join(directory,'demand-center.sqlite'));
|
||||
legacyDatabase.prepare('UPDATE demands SET payload = ? WHERE id = ?').run(JSON.stringify({...reviewDemand.data.demand,review:undefined,fields:legacyFields}),reviewDemand.data.demand.id);
|
||||
legacyDatabase.close();
|
||||
const legacyVisible=(await call('/api/demands',{cookie:admin})).data.demands.find(d=>d.id===reviewDemand.data.demand.id);
|
||||
verify(legacyVisible.access.developer&&legacyVisible.review.developer.username==='test_admin'&&legacyVisible.revision===1,'unassigned legacy demand automatically resolves administrator without changing revision');
|
||||
const legacyDemand=await call('/api/demands',{cookie:memberCookie,body:{action:'update',id:reviewDemand.data.demand.id,revision:1,mode:'review',fields:legacyFields}});
|
||||
verify(legacyDemand.status===200,'existing solution fields remain compatible');
|
||||
const preserved=await call('/api/demands',{cookie:memberCookie,body:{action:'update',id:legacyDemand.data.demand.id,revision:2,mode:'review',fields:{...legacyDemand.data.demand.fields,background:'更新业务背景'}}});
|
||||
verify(preserved.status===200&&preserved.data.demand.fields.scope===legacyFields.scope&&preserved.data.demand.fields.outOfScope===legacyFields.outOfScope,'business edits preserve existing solution content');
|
||||
async function createDeveloper(username){
|
||||
const password=secret(),nextPassword=secret();
|
||||
const response=await call('/api/admin/users',{cookie:admin,body:{username,displayName:username,password,role:'user'}});
|
||||
verify(response.status===201||response.status===200,'provision developer account');
|
||||
let session=await call('/api/auth/login',{body:{username,password}});
|
||||
verify((await call('/api/auth/password',{cookie:session.cookie,body:{currentPassword:password,newPassword:nextPassword}})).status===200,'developer changes initial password');
|
||||
session=await call('/api/auth/login',{body:{username,password:nextPassword}});
|
||||
return session;
|
||||
}
|
||||
const developer=await createDeveloper('developer_one');
|
||||
const replacement=await createDeveloper('developer_two');
|
||||
let reviewRecord=preserved.data.demand;
|
||||
async function reviewCall(cookie,action,extra={}){
|
||||
const response=await call('/api/demands',{cookie,body:{action,id:reviewRecord.id,revision:reviewRecord.revision,...extra}});
|
||||
if(response.status===200)reviewRecord=response.data.demand;
|
||||
return response;
|
||||
}
|
||||
verify((await call('/api/demands',{cookie:developer.cookie})).data.demands.length===0,'unassigned developer sees no other users demands');
|
||||
verify((await reviewCall(memberCookie,'assign-developer',{username:'business_one'})).status===400,'business owner cannot assign self as developer');
|
||||
verify((await reviewCall(memberCookie,'assign-developer',{username:'missing-developer'})).status===400,'unknown developer account rejected');
|
||||
verify((await reviewCall(memberCookie,'confirm-solution',{proposalVersion:1,confirm:true})).status===409,'legacy content cannot be confirmed before developer submits a proposal');
|
||||
verify((await reviewCall(memberCookie,'assign-developer',{username:'developer_one'})).status===200,'business owner assigns developer');
|
||||
const visible=await call('/api/demands',{cookie:developer.cookie});
|
||||
verify(visible.data.demands.length===1&&visible.data.demands[0].id===reviewRecord.id&&visible.data.demands[0].access.developer&&!visible.data.demands[0].access.business,'assigned developer sees exactly the shared demand with developer permissions');
|
||||
verify((await call('/api/demands',{cookie:admin})).data.demands.some(d=>d.id===reviewRecord.id&&!d.access.business&&!d.access.developer),'administrator can observe an assigned demand without business or developer permissions');
|
||||
const beforeAdminWrites=JSON.stringify(reviewRecord);
|
||||
for(const action of ['update','cancel','change','accept','assign-developer','propose-solution','confirm-solution','return-solution']){
|
||||
const denied=await reviewCall(admin,action,{mode:'review',fields:reviewRecord.fields,reason:'不应修改',content:'不应变更',username:'developer_two',scope:'不应代提',outOfScope:'无',proposalVersion:1,confirm:true,comment:'不应代确认',results:['通过'],notes:'无'});
|
||||
verify(denied.status===404,'administrator read access does not permit '+action);
|
||||
}
|
||||
const afterAdminWrites=(await call('/api/demands',{cookie:memberCookie})).data.demands.find(d=>d.id===reviewRecord.id);
|
||||
verify(JSON.stringify(afterAdminWrites)===beforeAdminWrites,'administrator write attempts leave the persisted demand unchanged');
|
||||
verify((await reviewCall(developer.cookie,'cancel',{reason:'must fail'})).status===403,'developer cannot cancel business demand');
|
||||
verify((await reviewCall(developer.cookie,'update',{mode:'review',fields:reviewRecord.fields})).status===403,'developer cannot edit business fields');
|
||||
verify((await reviewCall(developer.cookie,'assign-developer',{username:'developer_two'})).status===403,'developer cannot delegate access');
|
||||
verify((await reviewCall(memberCookie,'propose-solution',{scope:'业务方不能代填',outOfScope:'无'})).status===403,'business owner cannot impersonate developer proposal');
|
||||
verify((await reviewCall(memberCookie,'update',{mode:'review',fields:{...reviewRecord.fields,scope:'绕过界面修改方案'}})).status===403,'business update cannot mutate developer solution fields');
|
||||
verify((await reviewCall(developer.cookie,'propose-solution',{scope:' ',outOfScope:'无'})).status===400,'blank proposal rejected');
|
||||
const revisionBeforeProposal=reviewRecord.revision;
|
||||
verify((await reviewCall(developer.cookie,'propose-solution',{scope:'F-01:按状态筛选订单',outOfScope:'不修改历史订单',developer:{userId:memberId}})).status===200,'developer submits proposal');
|
||||
verify(reviewRecord.review.proposals[0].version===1&&reviewRecord.review.proposals[0].developer.userId===developer.data.user.userId&&reviewRecord.fields.scope==='F-01:按状态筛选订单','proposal version and actor are assigned by server');
|
||||
verify((await reviewCall(developer.cookie,'confirm-solution',{proposalVersion:1,confirm:true})).status===403,'developer cannot confirm own proposal for business');
|
||||
verify((await reviewCall(developer.cookie,'propose-solution',{scope:'静默覆盖',outOfScope:'无'})).status===409,'pending proposal cannot be silently overwritten');
|
||||
verify((await reviewCall(memberCookie,'confirm-solution',{proposalVersion:0,confirm:true})).status===409,'wrong proposal version rejected');
|
||||
verify((await reviewCall(memberCookie,'confirm-solution',{proposalVersion:1,confirm:true,revision:revisionBeforeProposal})).status===409,'stale record revision rejected');
|
||||
verify((await reviewCall(memberCookie,'confirm-solution',{proposalVersion:1,confirm:false})).status===400,'explicit business confirmation required');
|
||||
verify((await reviewCall(memberCookie,'return-solution',{proposalVersion:1,comment:''})).status===400,'return requires actionable feedback');
|
||||
verify((await reviewCall(memberCookie,'return-solution',{proposalVersion:1,comment:'补充异常场景'})).status===200,'business requests revision');
|
||||
verify((await reviewCall(developer.cookie,'propose-solution',{scope:'F-01:按状态筛选订单;空数据展示暂无订单',outOfScope:'不修改历史订单'})).status===200,'developer submits revised proposal');
|
||||
verify(reviewRecord.review.proposals.length===2&&reviewRecord.review.proposals[0].decision.result==='changes_requested','previous proposal and feedback are retained');
|
||||
verify((await reviewCall(memberCookie,'confirm-solution',{proposalVersion:2,confirm:true,comment:'业务已核对'})).status===200,'business confirms revised solution');
|
||||
const confirmed=structuredClone(reviewRecord.review.proposals[1]);
|
||||
verify(confirmed.decision.actor.userId===memberId&&!!confirmed.decision.time&&confirmed.decision.result==='confirmed','confirmation stores actual business actor and time');
|
||||
verify((await reviewCall(memberCookie,'confirm-solution',{proposalVersion:2,confirm:true})).status===409,'same version cannot be confirmed twice');
|
||||
verify((await reviewCall(memberCookie,'update',{mode:'review',fields:{...reviewRecord.fields,goal:'新增业务目标'}})).status===200,'business can amend requirements');
|
||||
verify(!!reviewRecord.review.proposals[1].invalidated&&reviewRecord.review.proposals[1].decision.time===confirmed.decision.time&&reviewRecord.fields.scope===confirmed.scope,'business edit invalidates approval while preserving the proposal and its confirmation');
|
||||
verify((await reviewCall(memberCookie,'confirm-solution',{proposalVersion:2,confirm:true})).status===409,'invalidated solution cannot be reconfirmed without developer review');
|
||||
verify((await reviewCall(developer.cookie,'propose-solution',{scope:'F-01:根据新目标调整筛选结果',outOfScope:'不修改历史订单'})).status===200,'developer proposes against amended business requirements');
|
||||
verify(reviewRecord.review.proposals[2].businessFields.goal==='新增业务目标','proposal retains business requirement snapshot');
|
||||
verify((await reviewCall(memberCookie,'confirm-solution',{proposalVersion:3,confirm:true})).status===200,'new business version confirmed');
|
||||
verify((await reviewCall(memberCookie,'return-solution',{proposalVersion:3,comment:'再补充筛选条件'})).status===200,'business may request changes to an approved version');
|
||||
verify(!!reviewRecord.review.proposals[2].invalidated&&reviewRecord.review.proposals[2].decision.result==='confirmed','reopened approval keeps original confirmation record');
|
||||
verify((await reviewCall(memberCookie,'assign-developer',{username:'developer_two'})).status===200,'business reassigns development');
|
||||
verify((await call('/api/demands',{cookie:developer.cookie})).data.demands.length===0,'reassignment revokes previous developer visibility');
|
||||
verify((await reviewCall(developer.cookie,'propose-solution',{scope:'旧责任人写入',outOfScope:'无'})).status===404,'previous developer can no longer write');
|
||||
verify((await reviewCall(replacement.cookie,'propose-solution',{scope:'F-01:新责任人提出完整方案',outOfScope:'无'})).status===200,'replacement developer can submit next version');
|
||||
verify(reviewRecord.review.proposals.at(-1).version===4&&reviewRecord.review.proposals.at(-1).developer.userId===replacement.data.user.userId,'versions remain monotonic across reassignment');
|
||||
verify((await reviewCall(memberCookie,'confirm-solution',{proposalVersion:4,confirm:true})).status===200,'business confirms replacement proposal');
|
||||
await stop();await start();
|
||||
const afterRestart=(await call('/api/demands',{cookie:replacement.cookie})).data.demands.find(d=>d.id===reviewRecord.id);
|
||||
verify(afterRestart.review.proposals.length===4&&afterRestart.review.proposals.at(-1).decision.result==='confirmed','assignment, proposal history and confirmations survive restart');
|
||||
verify((await call('/api/demands',{cookie:memberCookie})).data.demands.some(d=>d.id===demand.data.demand.id),'records and sessions survive server restart');
|
||||
async function upload(cookie,name,content,overrideOrigin=origin){
|
||||
const form=new FormData();form.append('file',new Blob([content]),name);
|
||||
const response=await fetch(origin+basePath+'/api/attachments',{method:'POST',headers:{Origin:overrideOrigin,...(cookie?{Cookie:cookie}:{})},body:form});
|
||||
return {status:response.status,data:await response.json()};
|
||||
}
|
||||
const attachmentContent='需求说明:<script>测试附件仅作下载,不执行</script>\nUnicode 文档';
|
||||
verify((await upload(undefined,'需求说明.html',attachmentContent)).status===401,'anonymous upload rejected');
|
||||
verify((await upload(memberCookie,'需求说明.html',attachmentContent,'https://untrusted.example')).status===403,'cross-origin upload rejected');
|
||||
verify((await upload(memberCookie,'空文件.txt','')).status===400,'empty upload rejected');
|
||||
verify((await upload(memberCookie,'超限.bin',new Uint8Array(20*1024*1024+1))).status===413,'oversized upload rejected by server');
|
||||
const uploaded=await upload(memberCookie,'需求说明.html',attachmentContent);
|
||||
verify(uploaded.status===201&&uploaded.data.attachment.name==='需求说明.html','authenticated upload returns filename and metadata');
|
||||
const file=uploaded.data.attachment;
|
||||
const downloadPath='/api/attachments/'+file.id;
|
||||
verify((await call('/api/attachments',{cookie:memberCookie})).data.attachments.some(a=>a.id===file.id),'unsaved attachments can be recovered after reload');
|
||||
verify((await call(downloadPath)).status===401,'anonymous download rejected');
|
||||
verify((await call(downloadPath,{cookie:admin})).status===404,'administrator cannot download another users staged file');
|
||||
verify((await call('/api/attachments',{cookie:admin})).data.attachments.every(a=>a.id!==file.id),'administrator cannot list another users staged files');
|
||||
verify((await call(downloadPath,{cookie:admin,method:'DELETE',headers:{Origin:origin}})).status===409,'administrator cannot delete another users staged file');
|
||||
verify((await call(downloadPath,{cookie:replacement.cookie})).status===404,'developer cannot access file before it is attached to shared demand');
|
||||
const ownDownload=await call(downloadPath,{cookie:memberCookie});
|
||||
verify(ownDownload.status===200&&ownDownload.data===attachmentContent,'uploaded bytes round-trip unchanged');
|
||||
verify(ownDownload.headers.get('content-disposition').startsWith('attachment;')&&ownDownload.headers.get('content-disposition').includes(encodeURIComponent(file.name))&&ownDownload.headers.get('content-type')==='application/octet-stream'&&ownDownload.headers.get('content-security-policy').includes('sandbox'),'active content is downloaded with a safe Unicode filename and sandbox headers');
|
||||
verify((await reviewCall(memberCookie,'update',{mode:'review',fields:reviewRecord.fields,attachmentIds:[file.id]})).status===200,'attachment binds atomically when saving demand');
|
||||
verify(reviewRecord.attachments[0].id===file.id&&reviewRecord.review.proposals.at(-1).invalidated.reason.includes('附件'),'new reference material invalidates previous review approval');
|
||||
verify((await call('/api/attachments',{cookie:memberCookie})).data.attachments.every(a=>a.id!==file.id),'saved attachment is no longer listed as staged');
|
||||
verify((await call(downloadPath,{cookie:replacement.cookie})).status===200,'assigned developer can download demand attachment');
|
||||
const adminDownload=await call(downloadPath,{cookie:admin});
|
||||
verify(adminDownload.status===200&&adminDownload.data===attachmentContent,'administrator can download exact bytes of formal demand attachments');
|
||||
verify((await call(downloadPath,{cookie:admin,method:'DELETE',headers:{Origin:origin}})).status===409,'administrator read access does not permit deleting bound attachments');
|
||||
verify((await call(downloadPath,{cookie:developer.cookie})).status===404,'former developer cannot download shared attachment');
|
||||
verify((await call(downloadPath,{cookie:memberCookie,method:'DELETE',headers:{Origin:origin}})).status===409,'bound files cannot be deleted via staging cleanup');
|
||||
const foreign=await upload(replacement.cookie,'other.txt','other account file');
|
||||
verify((await reviewCall(memberCookie,'update',{mode:'review',fields:reviewRecord.fields,attachmentIds:[foreign.data.attachment.id]})).status===400,'cannot claim another users uploaded file');
|
||||
const unchanged=(await call('/api/demands',{cookie:memberCookie})).data.demands.find(d=>d.id===reviewRecord.id);
|
||||
verify(unchanged.revision===reviewRecord.revision&&unchanged.attachments[0].id===file.id,'failed attachment save leaves demand and existing files unchanged');
|
||||
verify((await reviewCall(replacement.cookie,'propose-solution',{scope:'方案包含新参考文件',outOfScope:'无'})).status===200,'developer reviews new attachment');
|
||||
const attachmentVersion=reviewRecord.review.proposals.at(-1).version;
|
||||
verify(reviewRecord.review.proposals.at(-1).businessAttachments[0].id===file.id,'review snapshot includes the exact attachments considered');
|
||||
verify((await reviewCall(memberCookie,'confirm-solution',{proposalVersion:attachmentVersion,confirm:true})).status===200,'business confirms solution with reference attachment');
|
||||
verify((await reviewCall(memberCookie,'update',{mode:'review',fields:reviewRecord.fields,attachmentIds:[]})).status===200,'business removes current attachment');
|
||||
verify(reviewRecord.attachments.length===0&&reviewRecord.review.proposals.at(-1).businessAttachments[0].id===file.id,'removed attachment is retained in historical review');
|
||||
verify((await call(downloadPath,{cookie:replacement.cookie})).data===attachmentContent,'historical review attachment remains downloadable by current participants');
|
||||
verify((await call(downloadPath,{cookie:admin})).data===attachmentContent,'administrator can download retained historical review attachments');
|
||||
const temporary=await upload(memberCookie,'临时附件.txt','temporary file');
|
||||
verify((await call('/api/attachments/'+temporary.data.attachment.id,{cookie:memberCookie,method:'DELETE',headers:{Origin:origin}})).status===200,'discarding staged attachment cleans up stored bytes');
|
||||
verify((await call('/api/attachments/'+temporary.data.attachment.id,{cookie:memberCookie})).status===404,'discarded staged attachment is unavailable');
|
||||
const draftUpload=await upload(memberCookie,'草稿附件.txt','draft persistence');
|
||||
const draftWithFile=await call('/api/demands',{cookie:memberCookie,body:{action:'create',mode:'draft',fields:{...fields,title:'含附件草稿'},attachmentIds:[draftUpload.data.attachment.id]}});
|
||||
verify(draftWithFile.status===200&&draftWithFile.data.demand.attachments.length===1,'new draft saves attached file');
|
||||
const draftRecord=draftWithFile.data.demand;
|
||||
verify((await call('/api/demands',{cookie:admin})).data.demands.every(d=>d.id!==draftRecord.id),'administrator cannot read another users draft');
|
||||
verify((await call('/api/attachments/'+draftUpload.data.attachment.id,{cookie:admin})).status===404,'administrator cannot download another users draft attachment');
|
||||
const legacyClient=await call('/api/demands',{cookie:memberCookie,body:{action:'update',mode:'draft',id:draftRecord.id,revision:draftRecord.revision,fields:{...draftRecord.fields,title:'旧客户端保留附件'}}});
|
||||
verify(legacyClient.status===200&&legacyClient.data.demand.attachments[0].id===draftUpload.data.attachment.id,'old clients omitting attachmentIds do not drop attachments');
|
||||
const removedFile=await call('/api/demands',{cookie:memberCookie,body:{action:'update',mode:'draft',id:draftRecord.id,revision:legacyClient.data.demand.revision,fields:legacyClient.data.demand.fields,attachmentIds:[]}});
|
||||
verify(removedFile.status===200&&(await call('/api/attachments/'+draftUpload.data.attachment.id,{cookie:memberCookie})).status===404,'unreferenced removed files are deleted');
|
||||
|
||||
const privateUpload=await upload(memberCookie,'发布后可见.txt','draft becomes formal');
|
||||
const privateDraft=await call('/api/demands',{cookie:memberCookie,body:{action:'create',mode:'draft',fields:{...reviewFields,title:'管理员查看范围回归'},attachmentIds:[privateUpload.data.attachment.id]}});
|
||||
verify(privateDraft.status===200,'create a private draft for visibility transition');
|
||||
const adminDraft=await call('/api/demands',{cookie:admin,body:{action:'create',mode:'draft',fields:{...fields,title:'管理员自己的草稿'}}});
|
||||
verify(adminDraft.status===200&&adminDraft.data.demand.access.business,'administrator keeps business permissions on own drafts');
|
||||
const adminList=(await call('/api/demands',{cookie:admin})).data.demands;
|
||||
verify(adminList.some(d=>d.id===adminDraft.data.demand.id)&&adminList.every(d=>d.id!==privateDraft.data.demand.id),'administrator sees own draft but not another users draft');
|
||||
const published=await call('/api/demands',{cookie:memberCookie,body:{action:'update',mode:'review',id:privateDraft.data.demand.id,revision:privateDraft.data.demand.revision,fields:privateDraft.data.demand.fields}});
|
||||
verify(published.status===200&&(await call('/api/demands',{cookie:admin})).data.demands.some(d=>d.id===published.data.demand.id),'publishing a draft makes it visible to administrators');
|
||||
verify((await call('/api/attachments/'+privateUpload.data.attachment.id,{cookie:admin})).data==='draft becomes formal','publishing also enables administrator attachment download');
|
||||
verify((await call('/api/demands?role=admin',{cookie:developer.cookie})).data.demands.every(d=>d.id!==published.data.demand.id),'regular users cannot request administrator visibility');
|
||||
verify(published.data.demand.review.developer.username==='test_admin','publishing a draft automatically assigns the administrator');
|
||||
const adminParticipant=(await call('/api/demands',{cookie:admin})).data.demands.find(d=>d.id===published.data.demand.id);
|
||||
verify(adminParticipant.access.developer&&!adminParticipant.access.business,'default assignment grants only developer participation');
|
||||
const adminProposal=await call('/api/demands',{cookie:admin,body:{action:'propose-solution',id:adminParticipant.id,revision:adminParticipant.revision,scope:'F-01:明确指派后提交',outOfScope:'无'}});
|
||||
verify(adminProposal.status===200,'default administrator may submit developer proposal');
|
||||
verify((await call('/api/demands',{cookie:admin,body:{action:'confirm-solution',id:adminParticipant.id,revision:adminProposal.data.demand.revision,proposalVersion:1,confirm:true}})).status===403,'assigned administrator still cannot replace business confirmation');
|
||||
const adminReassigned=await call('/api/demands',{cookie:memberCookie,body:{action:'assign-developer',id:adminParticipant.id,revision:adminProposal.data.demand.revision,username:'developer_two'}});
|
||||
verify(adminReassigned.status===200,'business owner can reassign an administrator developer');
|
||||
const observerAgain=(await call('/api/demands',{cookie:admin})).data.demands.find(d=>d.id===adminParticipant.id);
|
||||
verify(observerAgain&&!observerAgain.access.developer&&!observerAgain.access.business,'former developer retains only administrator reading access');
|
||||
verify((await call('/api/demands',{cookie:admin,body:{action:'propose-solution',id:adminParticipant.id,revision:observerAgain.revision,scope:'不应成功',outOfScope:'无'}})).status===404,'reassigned administrator loses proposal permission');
|
||||
const cancelObserved=await call('/api/demands',{cookie:memberCookie,body:{action:'cancel',id:adminParticipant.id,revision:observerAgain.revision,reason:'结束测试需求'}});
|
||||
verify(cancelObserved.status===200&&(await call('/api/demands',{cookie:admin})).data.demands.some(d=>d.id===adminParticipant.id&&d.status==='已取消'),'cancelled formal demands stay visible to administrators');
|
||||
const roleDatabase=new DatabaseSync(join(directory,'demand-center.sqlite'));
|
||||
roleDatabase.prepare('UPDATE accounts SET role = ? WHERE id = ?').run('user',login.data.user.userId);
|
||||
try{
|
||||
verify((await call('/api/demands',{cookie:admin})).data.demands.every(d=>d.id!==reviewRecord.id),'administrator visibility is revoked on the next request after role removal');
|
||||
verify((await call(downloadPath,{cookie:admin})).status===404,'attachment downloads also recheck the current account role');
|
||||
}finally{roleDatabase.prepare('UPDATE accounts SET role = ? WHERE id = ?').run('admin',login.data.user.userId);roleDatabase.close();}
|
||||
const backupPath=join(directory,'attachment-backup.sqlite');
|
||||
await promisify(execFile)(process.execPath,['scripts/backup.mjs',backupPath],{env:{...process.env,DATA_DIR:directory}});
|
||||
const backupDatabase=new DatabaseSync(backupPath,{readOnly:true});
|
||||
const backedUp=backupDatabase.prepare('SELECT content FROM attachments WHERE id = ?').get(file.id);
|
||||
verify(Buffer.from(backedUp.content).toString()===attachmentContent,'online database backup includes exact file contents');
|
||||
backupDatabase.close();
|
||||
await stop();await start();
|
||||
verify((await call(downloadPath,{cookie:replacement.cookie})).data===attachmentContent,'attachment download survives production server restart');
|
||||
const disabled=await call('/api/admin/users',{method:'PATCH',cookie:admin,body:{id:memberId,action:'disable'}});
|
||||
verify(disabled.status===200,'admin disables user');
|
||||
verify((await call('/api/demands',{cookie:memberCookie})).status===401,'disabled account session immediately invalid');
|
||||
verify((await call('/api/auth/login',{body:{username:'business_one',password:memberPassword}})).status===401,'disabled account cannot log in');
|
||||
verify((await call('/api/admin/users',{method:'PATCH',cookie:admin,body:{id:memberId,action:'enable'}})).status===200,'admin re-enables user');
|
||||
memberLogin=await call('/api/auth/login',{body:{username:'business_one',password:memberPassword}});memberCookie=memberLogin.cookie;
|
||||
for(let attempt=0;attempt<5;attempt++){
|
||||
verify((await call('/api/auth/login',{body:{username:'business_one',password:'Incorrect password for regression'}})).status===401,'incorrect password consumes account attempt');
|
||||
}
|
||||
verify((await call('/api/auth/login',{body:{username:'business_one',password:memberPassword}})).status===429,'account is locked before administrator recovery');
|
||||
const resetPassword=secret();
|
||||
verify((await call('/api/admin/users',{method:'PATCH',cookie:admin,body:{id:memberId,action:'reset-password',password:resetPassword}})).status===200,'administrator resets password');
|
||||
verify((await call('/api/demands',{cookie:memberCookie})).status===401,'password reset revokes old session');
|
||||
const recovered=await call('/api/auth/login',{body:{username:'business_one',password:resetPassword}});
|
||||
verify(recovered.status===200&&recovered.data.user.mustChangePassword,'reset password clears old account lock immediately and forces change');
|
||||
const adminId=login.data.user.userId;
|
||||
verify((await call('/api/admin/users',{method:'PATCH',cookie:admin,body:{id:adminId,action:'disable'}})).status>=400,'administrator cannot disable self');
|
||||
verify((await call('/api/auth/logout',{method:'POST',cookie:admin,headers:{Origin:origin}})).status===200,'logout succeeds');
|
||||
verify((await call('/api/admin/users',{cookie:admin})).status===401,'logout revokes session');
|
||||
const retry=await call('/api/auth/login',{body:{username:'test_admin',password:initial}});verify(retry.status===401,'initial bootstrap password cannot overwrite changed password on restart');
|
||||
for(let attempt=0;attempt<60;attempt++){
|
||||
assert.equal((await call('/api/auth/login',{body:{username:`unknown-source-test-${attempt}`,password:'Incorrect source test password'},headers:{'x-test-client-ip':'198.51.100.77'}})).status,401);
|
||||
}
|
||||
verify((await call('/api/auth/login',{body:{username:'unknown-source-test-over-limit',password:'Incorrect source test password'},headers:{'x-test-client-ip':'198.51.100.77','x-forwarded-for':'198.51.100.78'}})).status===429,'source limit applies across usernames and ignores unrelated spoofed headers');
|
||||
verify((await call('/api/auth/login',{body:{username:'test_admin',password:adminPassword}})).status===200,'one exhausted source does not prevent another source from logging in');
|
||||
console.log(`${checks} self-hosted authentication, authorization and persistence checks passed.`);
|
||||
}catch(error){console.error(error);process.exitCode=1;}finally{await stop();await rm(directory,{recursive:true,force:true});}
|
||||
@@ -0,0 +1,148 @@
|
||||
"""Chunk failure recovery and Escape regressions on an isolated local instance."""
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
from playwright.async_api import async_playwright, expect
|
||||
|
||||
origin = os.environ['APP_URL']
|
||||
assert urlparse(origin).hostname == '127.0.0.1'
|
||||
assert Path(os.environ['DATA_DIR']).name.startswith('demand-scope-browser-db-')
|
||||
output = Path('/private/tmp/demand-template-resilience-qa')
|
||||
output.mkdir(exist_ok=True)
|
||||
|
||||
|
||||
async def main():
|
||||
checks = []
|
||||
async with async_playwright() as p:
|
||||
browser = await p.chromium.launch(headless=True, channel='chrome')
|
||||
context = await browser.new_context(viewport={'width': 1440, 'height': 1000})
|
||||
async def post(path, data):
|
||||
response = await context.request.post(origin + path, data=data, headers={'Origin': origin})
|
||||
assert response.ok, (response.status, await response.text())
|
||||
return await response.json()
|
||||
await post('/api/auth/login', {'username': 'scope_qa', 'password': os.environ['INITIAL_ADMIN_PASSWORD']})
|
||||
await post('/api/auth/password', {'currentPassword': os.environ['INITIAL_ADMIN_PASSWORD'], 'newPassword': os.environ['QA_PASSWORD']})
|
||||
errors = []
|
||||
async def start_form():
|
||||
page = await context.new_page()
|
||||
page.on('pageerror', lambda error: errors.append(str(error)))
|
||||
await page.goto(origin)
|
||||
await page.wait_for_load_state('networkidle')
|
||||
await page.get_by_role('button', name=re.compile('登记新需求$')).first.click()
|
||||
await page.get_by_label('需求标题', exact=False).fill('模板容错回归')
|
||||
await page.get_by_role('button', name=re.compile('业务背景与目标')).click()
|
||||
await page.get_by_label('业务背景与现有处理方式', exact=False).fill('保留未保存的业务说明')
|
||||
return page
|
||||
async def expect_form(page):
|
||||
await expect(page.get_by_role('dialog')).to_have_count(1)
|
||||
await expect(page.get_by_role('alertdialog')).not_to_be_attached()
|
||||
await expect(page.get_by_label('业务背景与现有处理方式', exact=False)).to_have_value('保留未保存的业务说明')
|
||||
await expect(page.get_by_role('button', name='查看需求说明模板', exact=True)).to_be_focused()
|
||||
|
||||
page = await start_form()
|
||||
reference = 'https://example.feishu.cn/docx/template-error-recovery'
|
||||
await page.get_by_label('需求说明文档链接(选填)', exact=True).fill(reference)
|
||||
await page.get_by_label('选择文件附件', exact=True).set_input_files({'name': '保留的说明.txt', 'mimeType': 'text/plain', 'buffer': '附件内容不丢失'.encode()})
|
||||
await expect(page.get_by_role('link', name='保留的说明.txt', exact=True)).to_be_visible()
|
||||
await expect(page.get_by_role('button', name='上传文件', exact=True)).to_be_enabled()
|
||||
chunks = {'fail': True, 'blocked': 0}
|
||||
async def fail_chunks(route):
|
||||
if chunks['fail']:
|
||||
chunks['blocked'] += 1
|
||||
await route.abort('failed')
|
||||
else:
|
||||
await route.continue_()
|
||||
await page.route('**/_next/static/chunks/*.js', fail_chunks)
|
||||
await page.get_by_role('button', name='查看需求说明模板', exact=True).click()
|
||||
await expect(page.get_by_role('alert')).to_contain_text('模板预览未能加载,请重试。已填内容仍然保留。')
|
||||
assert chunks['blocked'] > 0
|
||||
await expect(page.get_by_role('dialog', include_hidden=True)).to_have_count(2)
|
||||
await page.screenshot(path=str(output / 'chunk-error-desktop.png'), animations='disabled')
|
||||
blocked = chunks['blocked']
|
||||
await page.get_by_role('button', name='重新加载', exact=True).click()
|
||||
await expect(page.get_by_role('alert')).to_contain_text('模板预览未能加载')
|
||||
assert chunks['blocked'] > blocked, 'retry must request failed chunks again'
|
||||
await page.set_viewport_size({'width': 390, 'height': 844})
|
||||
await page.screenshot(path=str(output / 'chunk-error-mobile.png'), animations='disabled')
|
||||
assert await page.locator('.template-modal').evaluate('(el)=>el.scrollWidth<=el.clientWidth+1')
|
||||
await page.keyboard.press('Escape')
|
||||
await expect_form(page)
|
||||
await expect(page.get_by_label('需求说明文档链接(选填)', exact=True)).to_have_value(reference)
|
||||
await expect(page.get_by_role('link', name='保留的说明.txt', exact=True)).to_be_attached()
|
||||
await page.get_by_role('button', name='查看需求说明模板', exact=True).click()
|
||||
await expect(page.get_by_role('alert')).to_contain_text('模板预览未能加载')
|
||||
chunks['fail'] = False
|
||||
await page.get_by_role('button', name='重新加载', exact=True).click()
|
||||
await expect(page.get_by_role('article')).to_contain_text('二、背景与目标')
|
||||
await page.get_by_role('button', name='返回填写', exact=True).click()
|
||||
await expect_form(page)
|
||||
await page.get_by_role('button', name='保存草稿', exact=True).click()
|
||||
await expect(page.get_by_role('heading', name='模板容错回归', exact=True)).to_be_attached()
|
||||
records = await (await context.request.get(origin + '/api/demands')).json()
|
||||
record = records['demands'][0]
|
||||
assert record['fields']['background'] == '保留未保存的业务说明'
|
||||
assert record['fields']['references'] == reference
|
||||
assert record['attachments'][0]['name'] == '保留的说明.txt'
|
||||
download = await context.request.get(origin + '/api/attachments/' + record['attachments'][0]['id'])
|
||||
assert download.ok and await download.body() == '附件内容不丢失'.encode()
|
||||
checks.append('failed chunks stay inside the preview; repeated retry, close, reopen and successful retry preserve text, links and attachment bytes')
|
||||
await page.unroute_all(behavior='wait')
|
||||
await page.close()
|
||||
|
||||
page = await start_form()
|
||||
entered, release, finished = asyncio.Event(), asyncio.Event(), asyncio.Event()
|
||||
async def hold_response(route):
|
||||
entered.set()
|
||||
await release.wait()
|
||||
try:
|
||||
await route.continue_()
|
||||
finally:
|
||||
finished.set()
|
||||
await page.route('**/api/documents/**?format=json', hold_response)
|
||||
await page.get_by_role('button', name='查看需求说明模板', exact=True).click()
|
||||
await asyncio.wait_for(entered.wait(), timeout=5)
|
||||
await expect(page.get_by_text('正在加载模板…', exact=True)).to_be_visible()
|
||||
await page.keyboard.press('Escape')
|
||||
await expect_form(page)
|
||||
release.set()
|
||||
await asyncio.wait_for(finished.wait(), timeout=5)
|
||||
await page.unroute_all(behavior='wait')
|
||||
await page.wait_for_load_state('networkidle')
|
||||
await expect_form(page)
|
||||
checks.append('Escape before the first body response closes only the preview and late responses do not reopen it')
|
||||
|
||||
await page.get_by_role('button', name='查看需求说明模板', exact=True).click()
|
||||
await expect(page.get_by_role('article')).to_contain_text('二、背景与目标')
|
||||
await page.get_by_role('button', name='返回填写', exact=True).click()
|
||||
await expect_form(page)
|
||||
for _ in range(4):
|
||||
await page.get_by_role('button', name='查看需求说明模板', exact=True).click()
|
||||
await expect(page.get_by_role('heading', name='需求说明模板', exact=True)).to_be_visible()
|
||||
# Do not wait for article/API completion: this caught the regression.
|
||||
await page.keyboard.press('Escape')
|
||||
await expect_form(page)
|
||||
await page.keyboard.press('Escape')
|
||||
await expect(page.get_by_role('alertdialog')).to_contain_text('放弃未保存的修改?')
|
||||
await page.get_by_role('button', name='继续填写', exact=True).click()
|
||||
await expect(page.get_by_label('业务背景与现有处理方式', exact=False)).to_have_value('保留未保存的业务说明')
|
||||
checks.append('rapid Escape after reopening never triggers form exit; Escape on the form still asks before discarding input')
|
||||
await page.close()
|
||||
|
||||
page = await context.new_page()
|
||||
await page.goto(origin)
|
||||
await page.wait_for_load_state('networkidle')
|
||||
await page.get_by_role('button', name='流程与规范', exact=True).click()
|
||||
await page.get_by_role('button', name='查看数据来源模板', exact=True).click()
|
||||
await expect(page.get_by_role('article')).to_contain_text('数据从哪里来')
|
||||
await page.get_by_role('button', name='关闭模板预览', exact=True).click()
|
||||
await expect(page.get_by_role('button', name='查看数据来源模板', exact=True)).to_be_focused()
|
||||
checks.append('closing previews from the template directory restores focus to the originating button')
|
||||
assert not errors, errors
|
||||
print(json.dumps({'result': 'passed', 'checks': checks, 'screenshots': str(output)}, ensure_ascii=False), flush=True)
|
||||
await browser.close()
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,150 @@
|
||||
"""Template preview, contextual uploads and download regressions on an isolated local instance."""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
from zipfile import ZipFile
|
||||
from urllib.parse import urlparse
|
||||
from playwright.sync_api import sync_playwright, expect
|
||||
|
||||
origin = os.environ['APP_URL']
|
||||
assert urlparse(origin).hostname == '127.0.0.1'
|
||||
assert Path(os.environ['DATA_DIR']).name.startswith('demand-scope-browser-db-')
|
||||
output = Path('/private/tmp/demand-template-ui-qa')
|
||||
output.mkdir(exist_ok=True)
|
||||
hub = 'https://ecnldnvsv8es.feishu.cn/wiki/Bvnbw852biK7qRkhwJkcOIvun4f?from=from_copylink'
|
||||
checks = []
|
||||
|
||||
|
||||
def post(context, path, data):
|
||||
response = context.request.post(origin + path, data=data, headers={'Origin': origin})
|
||||
assert response.ok, (response.status, response.text())
|
||||
return response.json()
|
||||
|
||||
|
||||
def screenshot(page, name):
|
||||
page.locator('.toast').wait_for(state='hidden')
|
||||
page.screenshot(path=str(output / name), animations='disabled')
|
||||
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True, channel='chrome')
|
||||
context = browser.new_context(viewport={'width': 1440, 'height': 1000}, accept_downloads=True)
|
||||
post(context, '/api/auth/login', {'username': 'scope_qa', 'password': os.environ['INITIAL_ADMIN_PASSWORD']})
|
||||
post(context, '/api/auth/password', {'currentPassword': os.environ['INITIAL_ADMIN_PASSWORD'], 'newPassword': os.environ['QA_PASSWORD']})
|
||||
page = context.new_page()
|
||||
errors = []
|
||||
page.on('pageerror', lambda error: errors.append(str(error)))
|
||||
page.goto(origin)
|
||||
page.wait_for_load_state('networkidle')
|
||||
page.get_by_role('button', name=re.compile('登记新需求$')).first.click()
|
||||
for label, value in {'需求标题': '模板与材料完整流程验证', '所属项目': '测试项目', '业务模块': '订单查询', '所属部门': '业务部', '需求来源': '本地测试'}.items():
|
||||
page.get_by_label(re.compile('^' + label)).fill(value)
|
||||
page.get_by_role('button', name=re.compile('业务背景与目标')).click()
|
||||
page.get_by_label('业务背景与现有处理方式', exact=False).fill('简短说明:需要按状态查找订单。')
|
||||
expect(page.get_by_role('button', name='上传文件', exact=True)).to_be_visible()
|
||||
expect(page.get_by_role('link', name='下载需求说明模板 Word 版', exact=True)).to_be_visible()
|
||||
assert page.get_by_role('link', name='飞书总目录', exact=True).get_attribute('href') == hub
|
||||
page.get_by_role('button', name='查看需求说明模板', exact=True).click()
|
||||
expect(page.get_by_role('dialog', include_hidden=True)).to_have_count(2)
|
||||
preview = page.get_by_role('dialog').filter(has=page.get_by_role('heading', name='需求说明模板', exact=True))
|
||||
expect(preview.locator('article')).to_contain_text('二、背景与目标')
|
||||
assert preview.get_by_role('link', name='飞书模板总目录', exact=True).get_attribute('href') == hub
|
||||
screenshot(page, 'requirement-preview-desktop.png')
|
||||
preview.get_by_role('button', name=re.compile('附件03')).click()
|
||||
expect(page.get_by_role('heading', name='数据来源模板', exact=True)).to_be_visible()
|
||||
preview = page.get_by_role('dialog').filter(has=page.get_by_role('heading', name='数据来源模板', exact=True))
|
||||
with page.expect_download() as download_event:
|
||||
preview.get_by_role('link', name='下载 Word 版本', exact=True).click()
|
||||
download = download_event.value
|
||||
assert download.suggested_filename == '附件03_数据来源填写模板.docx'
|
||||
with ZipFile(download.path()) as archive:
|
||||
assert '数据从哪里来' in archive.read('word/document.xml').decode()
|
||||
preview.get_by_role('button', name='返回上一份模板', exact=True).click()
|
||||
expect(page.get_by_role('heading', name='需求说明模板', exact=True)).to_be_visible()
|
||||
page.get_by_role('button', name='关闭模板预览', exact=True).click()
|
||||
expect(page.get_by_role('dialog')).to_have_count(1)
|
||||
expect(page.get_by_label('业务背景与现有处理方式', exact=False)).to_have_value('简短说明:需要按状态查找订单。')
|
||||
checks.append('contextual previews, related-template navigation and genuine Word downloads preserve the form')
|
||||
|
||||
page.get_by_role('button', name='查看需求说明模板', exact=True).click()
|
||||
expect(page.get_by_role('heading', name='需求说明模板', exact=True)).to_be_visible()
|
||||
expect(page.get_by_role('article')).to_contain_text('二、背景与目标')
|
||||
page.keyboard.press('Escape')
|
||||
expect(page.get_by_role('dialog')).to_have_count(1)
|
||||
expect(page.get_by_role('alertdialog')).not_to_be_attached()
|
||||
checks.append('Escape closes only the template preview')
|
||||
page.get_by_label('选择文件附件', exact=True).set_input_files({'name': '业务需求说明.txt', 'mimeType': 'text/plain', 'buffer': '详细业务材料'.encode()})
|
||||
expect(page.get_by_role('button', name='上传文件', exact=True)).to_be_enabled()
|
||||
expect(page.get_by_role('link', name='业务需求说明.txt', exact=True)).to_be_visible()
|
||||
reference = 'https://example.feishu.cn/docx/filled-test-document'
|
||||
page.get_by_label('需求说明文档链接(选填)', exact=True).fill(reference)
|
||||
page.get_by_label('业务背景与现有处理方式', exact=False).scroll_into_view_if_needed()
|
||||
screenshot(page, 'background-actions-desktop.png')
|
||||
page.get_by_label('影响对象与业务依据', exact=False).fill('业务查询人员')
|
||||
page.get_by_label('预期目标', exact=False).fill('快速定位符合条件的订单')
|
||||
page.get_by_label('没有固定的上线日期').check()
|
||||
page.get_by_role('button', name=re.compile('验收与优先级')).click()
|
||||
page.get_by_label('验收标准', exact=False).fill('按待发货状态查询时,仅展示待发货订单。')
|
||||
page.get_by_label('优先级依据', exact=False).fill('减少操作时间')
|
||||
page.get_by_role('button', name=re.compile('数据与参考材料')).click()
|
||||
expect(page.get_by_role('link', name='业务需求说明.txt', exact=True)).to_be_visible()
|
||||
expect(page.get_by_label('参考材料与链接', exact=True)).to_have_value(reference)
|
||||
page.get_by_role('button', name='查看数据来源模板', exact=True).click()
|
||||
expect(page.get_by_role('heading', name='数据来源模板', exact=True)).to_be_visible()
|
||||
page.get_by_role('button', name='返回填写', exact=True).click()
|
||||
page.get_by_label('本需求不涉及数据来源').check()
|
||||
page.get_by_label('依赖与风险', exact=False).fill('无')
|
||||
page.get_by_label('待确认事项', exact=False).fill('无')
|
||||
page.get_by_role('button', name='提交评审', exact=True).click()
|
||||
expect(page.get_by_role('heading', name='模板与材料完整流程验证', exact=True)).to_be_attached()
|
||||
record = context.request.get(origin + '/api/demands').json()['demands'][0]
|
||||
assert record['fields']['background'] == '简短说明:需要按状态查找订单。'
|
||||
assert record['fields']['references'] == reference
|
||||
assert record['attachments'][0]['name'] == '业务需求说明.txt'
|
||||
assert record['reviewReady']
|
||||
checks.append('brief business description, uploaded files and document links share state and submit together')
|
||||
|
||||
page.get_by_role('button', name='关闭需求详情', exact=True).click()
|
||||
page.get_by_role('button', name='流程与规范', exact=True).click()
|
||||
expect(page.locator('.template-library-item')).to_have_count(8)
|
||||
assert page.get_by_role('link', name='打开飞书模板总目录', exact=True).get_attribute('href') == hub
|
||||
for link in page.locator('.template-library a[download]').all():
|
||||
assert 'format=docx' in link.get_attribute('href')
|
||||
checks.append('the template library uses inline reading, Word downloads and the supplied Feishu directory')
|
||||
|
||||
page.set_viewport_size({'width': 390, 'height': 844})
|
||||
page.get_by_role('button', name='查看验收记录模板', exact=True).click()
|
||||
preview = page.get_by_role('dialog')
|
||||
expect(preview.get_by_role('table')).to_be_visible()
|
||||
expect(preview.get_by_role('cell', name='AC-01', exact=True)).to_be_visible()
|
||||
assert preview.evaluate('(el)=>el.scrollWidth<=el.clientWidth+1')
|
||||
assert preview.locator('.template-table-wrap').evaluate('(el)=>el.scrollWidth>el.clientWidth')
|
||||
screenshot(page, 'acceptance-preview-mobile.png')
|
||||
preview.get_by_role('button', name='关闭模板预览', exact=True).click()
|
||||
page.get_by_role('button', name='登记新需求', exact=True).click()
|
||||
page.get_by_role('button', name=re.compile('业务背景与目标')).click()
|
||||
page.get_by_label('业务背景与现有处理方式', exact=False).fill('手机端保留简短说明')
|
||||
expect(page.get_by_text('正在读取未保存附件…', exact=True)).not_to_be_visible()
|
||||
screenshot(page, 'background-actions-mobile.png')
|
||||
assert page.get_by_role('dialog').evaluate('(el)=>el.scrollWidth<=el.clientWidth+1')
|
||||
checks.append('mobile contextual actions and wide preview tables remain usable without modal overflow')
|
||||
|
||||
failures = {'remaining': 1}
|
||||
def document_failure(route):
|
||||
if failures['remaining']:
|
||||
failures['remaining'] -= 1
|
||||
route.fulfill(status=503, content_type='application/json', body='{"error":"模板暂时无法加载,请重试。"}')
|
||||
else:
|
||||
route.continue_()
|
||||
page.route('**/api/documents/**?format=json', document_failure)
|
||||
page.get_by_role('button', name='查看需求说明模板', exact=True).click()
|
||||
expect(page.get_by_text('模板暂时无法加载,请重试。', exact=True)).to_be_visible()
|
||||
page.get_by_role('button', name='重新加载', exact=True).click()
|
||||
expect(page.get_by_role('article')).to_contain_text('二、背景与目标')
|
||||
page.get_by_role('button', name='返回填写', exact=True).click()
|
||||
expect(page.get_by_label('业务背景与现有处理方式', exact=False)).to_have_value('手机端保留简短说明')
|
||||
checks.append('failed previews are retryable without losing user input')
|
||||
assert not errors, errors
|
||||
print(json.dumps({'result': 'passed', 'checks': checks, 'screenshots': str(output)}, ensure_ascii=False), flush=True)
|
||||
browser.close()
|
||||
@@ -0,0 +1,96 @@
|
||||
"""Full workflow through business and developer UI on disposable local data."""
|
||||
import json, os, secrets, sqlite3
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
from playwright.sync_api import sync_playwright, expect
|
||||
origin=os.environ['APP_URL'];data_dir=Path(os.environ['DATA_DIR'])
|
||||
assert urlparse(origin).hostname=='127.0.0.1' and data_dir.name.startswith('demand-scope-browser-db-')
|
||||
out=Path('/private/tmp/demand-workflow-fixes-ui-qa');out.mkdir(exist_ok=True)
|
||||
title='交付审查修复页面回归'
|
||||
fields={'title':title,'project':'订单平台','module':'订单查询','type':'新增功能','proposer':'业务人员','department':'业务部','source':'本地验证','owner':'业务人员','background':'需要按状态查询订单','impact':'日常业务人员','goal':'准确筛选订单','expectedDate':'','noFixedDate':True,'dateReason':'','scope':'','outOfScope':'','criteria':'筛选结果符合状态且受权限约束','priority':'P2','priorityReason':'减少查询时间','dataSource':'','dataContact':'','noData':True,'risk':'无','pending':'无','references':'','version':'v1.0'}
|
||||
checks=[]
|
||||
with sync_playwright() as p:
|
||||
browser=p.chromium.launch(headless=True,channel='chrome')
|
||||
admin=browser.new_context(viewport={'width':1440,'height':1000})
|
||||
def post(ctx,path,body):
|
||||
r=ctx.request.post(origin+path,data=body,headers={'Origin':origin});assert r.ok,(r.status,r.text());return r.json()
|
||||
post(admin,'/api/auth/login',{'username':'scope_qa','password':os.environ['INITIAL_ADMIN_PASSWORD']})
|
||||
post(admin,'/api/auth/password',{'currentPassword':os.environ['INITIAL_ADMIN_PASSWORD'],'newPassword':os.environ['QA_PASSWORD']})
|
||||
def member(username):
|
||||
initial=secrets.token_urlsafe(20);current=secrets.token_urlsafe(20)
|
||||
post(admin,'/api/admin/users',{'username':username,'displayName':username,'password':initial,'role':'user'})
|
||||
ctx=browser.new_context(viewport={'width':1440,'height':1000})
|
||||
post(ctx,'/api/auth/login',{'username':username,'password':initial});post(ctx,'/api/auth/password',{'currentPassword':initial,'newPassword':current})
|
||||
return ctx
|
||||
business=member('workflow_business');developer=member('workflow_developer')
|
||||
record=post(business,'/api/demands',{'action':'create','mode':'review','fields':fields})['demand']
|
||||
def api(ctx,action,values):
|
||||
global record
|
||||
record=post(ctx,'/api/demands',{'action':action,'id':record['id'],'revision':record['revision'],**values})['demand'];return record
|
||||
api(business,'assign-developer',{'username':'workflow_developer'});api(developer,'propose-solution',{'scope':'F-01 按状态筛选订单','outOfScope':'不修改历史订单'});api(business,'confirm-solution',{'proposalVersion':1,'confirm':True,'comment':'同意实施'})
|
||||
errors=[]
|
||||
owner=business.new_page();dev=developer.new_page()
|
||||
for page in [owner,dev]:page.on('pageerror',lambda e:errors.append(str(e)))
|
||||
def open_record(page,tab='交付流程'):
|
||||
page.goto(origin);page.wait_for_load_state('networkidle');page.get_by_role('button',name=title,exact=True).click();page.get_by_role('tab',name=tab,exact=False).click()
|
||||
def begin(page,action):page.get_by_role('button',name=action,exact=True).click();expect(page.locator('.workflow-form')).to_be_visible()
|
||||
def fill(page,values):
|
||||
form=page.locator('.workflow-form')
|
||||
for label,value in values.items():form.get_by_label(label,exact=False).and_(form.locator('input:not([type=checkbox]), textarea')).fill(str(value))
|
||||
def confirm(page):page.locator('.workflow-form').get_by_label('我已核对内容并确认提交',exact=True).check()
|
||||
def submit(page,label):page.locator('.workflow-form').get_by_role('button',name=label,exact=True).click();expect(page.locator('.workflow-form')).not_to_be_attached()
|
||||
def screenshot(page,name):
|
||||
page.locator('.toast').wait_for(state='hidden');page.screenshot(path=str(out/name),animations='disabled')
|
||||
|
||||
def refresh_record():
|
||||
global record
|
||||
record=next(d for d in business.request.get(origin+'/api/demands').json()['demands'] if d['id']==record['id'])
|
||||
api(developer,'propose-plan',{'hours':8,'testDate':'2026-10-01','feedbackDate':'2026-10-02','releaseDate':'2026-10-03','priority':'P2','designRequired':True,'notes':'交付计划'})
|
||||
api(business,'decide-plan',{'planVersion':record['plan']['version'],'approved':True,'comment':'确认','confirm':True})
|
||||
api(developer,'submit-design',{'reference':'design-v1','notes':'初稿'})
|
||||
api(business,'decide-design',{'approved':True,'comment':'确认','confirm':True})
|
||||
api(developer,'start-development',{'technicalPlan':'技术方案','dependencies':'已确认','confirm':True})
|
||||
open_record(dev);begin(dev,'提交设计确认');fill(dev,{'设计稿或交互说明链接':'https://design.example.test/v2','设计版本':'开发中修改设计,v2'});submit(dev,'提交设计确认')
|
||||
owner.goto(origin);owner.wait_for_load_state('networkidle');owner.get_by_role('navigation',name='主导航').get_by_role('button',name='待我处理',exact=True).click()
|
||||
expect(owner.get_by_text('确认设计',exact=True)).to_be_visible();owner.get_by_role('button',name=title,exact=True).click();owner.get_by_role('tab',name='交付流程',exact=True).click();begin(owner,'确认设计');fill(owner,{'确认意见':'新版设计符合业务流程'});confirm(owner);submit(owner,'确认设计')
|
||||
checks.append('a design resubmitted during development generates a business task and can be confirmed from it')
|
||||
|
||||
open_record(dev);begin(dev,'提交业务验收');fill(dev,{'测试版本或提交号':'fixes-build-1','测试环境地址':'https://test.example.test/orders','操作步骤及测试数据获取方式':'授权测试数据','自测结果与记录':'ST-1 通过','代码审查结论与记录':'CR-1 通过','集成验证结果与已知问题':'集成通过'})
|
||||
for _ in range(2):dev.get_by_role('button',name='添加验收项',exact=True).click()
|
||||
dev.get_by_role('button',name='移除此验收项',exact=True).nth(1).click();dev.get_by_role('button',name='添加验收项',exact=True).click()
|
||||
ids=[dev.get_by_label(f'验收项 {i} 编号',exact=True).input_value() for i in range(1,4)];assert len(set(ids))==3,ids
|
||||
for i in range(1,4):
|
||||
dev.get_by_label(f'验收项 {i} 关联功能',exact=True).fill(f'F-{i}')
|
||||
dev.get_by_label(f'验收项 {i} 场景与操作',exact=True).fill('执行订单查询')
|
||||
dev.get_by_label(f'验收项 {i} 预期结果',exact=True).fill('结果准确')
|
||||
confirm(dev);submit(dev,'提交业务验收');refresh_record();assert len(record['acceptance']['items'])==3
|
||||
api(business,'accept',{'testVersion':'fixes-build-1','version':'v1.0','round':record['acceptance']['round'],'results':['通过']*3,'notes':'无','confirm':True})
|
||||
release={'version':'fixes-build-1','previousVersion':'stable-0','rollbackPlan':'恢复旧版本','backup':'备份已验证,数据兼容','deployment':'实际发布完成','verificationPlan':'核对核心流程及监控','observationMinutes':15,'testsPassed':True,'configurationReady':True,'recoveryReady':True,'noticeComplete':True,'confirm':True}
|
||||
api(developer,'publish',release)
|
||||
checks.append('removing a middle checklist item and adding another produces unique IDs and successfully submits all items')
|
||||
|
||||
open_record(dev);begin(dev,'登记线上故障并启动修复');fill(dev,{'线上故障及影响范围':'核心查询边界故障','既有范围内需要修复的内容':'仅修复空指针,不变更业务规则'});confirm(dev);submit(dev,'登记线上故障并启动修复');refresh_record()
|
||||
api(developer,'request-recovery',{'targetVersion':'stable-0','dataImpact':'需先确认增量保留','plan':'快照恢复前核对新增数据'})
|
||||
open_record(dev);begin(dev,'撤回数据恢复申请');fill(dev,{'撤回原因':'采用代码修复,不恢复数据'});submit(dev,'撤回数据恢复申请');refresh_record();assert record['delivery']['releases'][-1]['recoveryRequest']['withdrawn']
|
||||
checks.append('the developer can explicitly withdraw a pending recovery request without performing data recovery')
|
||||
|
||||
dev.set_viewport_size({'width':390,'height':844});begin(dev,'登记紧急生产发布')
|
||||
fill(dev,{'无法等待完整业务验收的原因':'核心查询不可用,需先恢复','修复内容及影响评估':'修复空指针,业务规则与范围不变','自测与关键流程验证记录':'ST-H1 通过','代码审查及确认记录':'CR-H1 独立审查通过','构建、集成及关联回归记录':'构建与关键查询回归通过','已知问题及风险处理':'无','修复同步、记录补充及后续业务验证安排':'同步主分支,下一工作日补充记录,业务核对订单查询','业务验证完成日期':'2099-10-05','发布版本':'fixes-hotfix-1','上一稳定版本':'fixes-build-1','回滚与恢复方案':'恢复上一镜像','备份、数据脚本和兼容性检查':'备份完整,与旧数据兼容','实际发布操作及结果':'部署记录 H-1,完成','生产验证与监控方式':'验证订单核心查询与监控','观察时长':'15'})
|
||||
for box in dev.locator('.workflow-form input[type=checkbox]').all():box.check()
|
||||
dev.locator('.workflow-form h2').scroll_into_view_if_needed();screenshot(dev,'emergency-form-mobile.png')
|
||||
assert dev.get_by_role('dialog').evaluate('(e)=>e.scrollWidth<=e.clientWidth+1')
|
||||
submit(dev,'登记紧急生产发布');refresh_record();assert record['delivery']['releases'][-1]['emergency'] and record['acceptance']['withdrawnAt'];expect(dev.locator('.detail-progress .done').filter(has_text='业务补验')).to_have_count(0)
|
||||
dev.set_viewport_size({'width':1440,'height':1000});begin(dev,'记录生产验证');fill(dev,{'核心功能、数据与监控验证结果':'核心查询、数据与监控正常'});confirm(dev);submit(dev,'记录生产验证')
|
||||
# Only this disposable fixture has its observation clock advanced.
|
||||
connection=sqlite3.connect(data_dir/'demand-center.sqlite');row=connection.execute('SELECT payload FROM demands WHERE id=?',(record['id'],)).fetchone();payload=json.loads(row[0]);payload['delivery']['releases'][-1]['observeUntil']='2000-01-01T00:00:00.000Z';connection.execute('UPDATE demands SET payload=? WHERE id=?',(json.dumps(payload,ensure_ascii=False),record['id']));connection.commit();connection.close()
|
||||
begin(dev,'交付完成并归档');fill(dev,{'观察结论与交付总结':'核心查询已恢复','交接资料及业务通知记录':'已同步主分支、补齐记录并通知业务','监控、故障联系人和告警渠道':'监控 M-H1,联系人开发责任人'});confirm(dev);dev.locator('.workflow-form').get_by_role('button',name='交付完成并归档',exact=True).click();expect(dev.get_by_role('alert')).to_contain_text('业务验证')
|
||||
expect(dev.get_by_label('观察结论与交付总结',exact=False)).to_have_value('核心查询已恢复')
|
||||
owner.goto(origin);owner.wait_for_load_state('networkidle');owner.get_by_role('navigation',name='主导航').get_by_role('button',name='待我处理',exact=True).click();expect(owner.get_by_text('补充紧急发布业务验证',exact=True)).to_be_visible();owner.get_by_role('button',name=title,exact=True).click();owner.get_by_role('tab',name='交付流程',exact=True).click()
|
||||
screenshot(owner,'emergency-followup-desktop.png');begin(owner,'补充紧急发布业务验证');fill(owner,{'验证结果、证据与问题说明':'订单查询复验通过,证据 E-H1'});confirm(owner);submit(owner,'补充紧急发布业务验证')
|
||||
open_record(dev);begin(dev,'交付完成并归档');fill(dev,{'观察结论与交付总结':'业务复验与观察通过','交接资料及业务通知记录':'已同步主分支并完成交接','监控、故障联系人和告警渠道':'监控 M-H1,开发值守'});confirm(dev);submit(dev,'交付完成并归档')
|
||||
expect(dev.get_by_text('已完成',exact=True).first).to_be_visible();expect(dev.locator('.detail-progress .done').filter(has_text='业务补验')).to_have_count(1)
|
||||
checks.append('mobile emergency publication keeps technical checks, creates a version-bound business task, and cannot archive until follow-up verification passes')
|
||||
observer=admin.new_page();observer.goto(origin);observer.wait_for_load_state('networkidle');observer.get_by_role('navigation',name='主导航').get_by_role('button',name='全部需求',exact=True).click();observer.get_by_role('button',name=title,exact=True).click();observer.get_by_role('tab',name='交付流程',exact=True).click();expect(observer.locator('.workflow-buttons button')).to_have_count(0)
|
||||
assert not errors,errors
|
||||
print(json.dumps({'result':'passed','checks':checks,'screenshots':str(out)},ensure_ascii=False),flush=True)
|
||||
browser.close()
|
||||
@@ -0,0 +1,101 @@
|
||||
"""Full workflow through business and developer UI on disposable local data."""
|
||||
import json, os, secrets, sqlite3
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
from playwright.sync_api import sync_playwright, expect
|
||||
origin=os.environ['APP_URL'];data_dir=Path(os.environ['DATA_DIR'])
|
||||
assert urlparse(origin).hostname=='127.0.0.1' and data_dir.name.startswith('demand-scope-browser-db-')
|
||||
out=Path('/private/tmp/demand-workflow-ui-qa');out.mkdir(exist_ok=True)
|
||||
title='完整交付流程页面回归'
|
||||
fields={'title':title,'project':'订单平台','module':'订单查询','type':'新增功能','proposer':'业务人员','department':'业务部','source':'本地验证','owner':'业务人员','background':'需要按状态查询订单','impact':'日常业务人员','goal':'准确筛选订单','expectedDate':'','noFixedDate':True,'dateReason':'','scope':'','outOfScope':'','criteria':'筛选结果符合状态且受权限约束','priority':'P2','priorityReason':'减少查询时间','dataSource':'','dataContact':'','noData':True,'risk':'无','pending':'无','references':'','version':'v1.0'}
|
||||
checks=[]
|
||||
with sync_playwright() as p:
|
||||
browser=p.chromium.launch(headless=True,channel='chrome')
|
||||
admin=browser.new_context(viewport={'width':1440,'height':1000})
|
||||
def post(ctx,path,body):
|
||||
r=ctx.request.post(origin+path,data=body,headers={'Origin':origin});assert r.ok,(r.status,r.text());return r.json()
|
||||
post(admin,'/api/auth/login',{'username':'scope_qa','password':os.environ['INITIAL_ADMIN_PASSWORD']})
|
||||
post(admin,'/api/auth/password',{'currentPassword':os.environ['INITIAL_ADMIN_PASSWORD'],'newPassword':os.environ['QA_PASSWORD']})
|
||||
def member(username):
|
||||
initial=secrets.token_urlsafe(20);current=secrets.token_urlsafe(20)
|
||||
post(admin,'/api/admin/users',{'username':username,'displayName':username,'password':initial,'role':'user'})
|
||||
ctx=browser.new_context(viewport={'width':1440,'height':1000})
|
||||
post(ctx,'/api/auth/login',{'username':username,'password':initial});post(ctx,'/api/auth/password',{'currentPassword':initial,'newPassword':current})
|
||||
return ctx
|
||||
business=member('workflow_business');developer=member('workflow_developer')
|
||||
record=post(business,'/api/demands',{'action':'create','mode':'review','fields':fields})['demand']
|
||||
def api(ctx,action,values):
|
||||
global record
|
||||
record=post(ctx,'/api/demands',{'action':action,'id':record['id'],'revision':record['revision'],**values})['demand'];return record
|
||||
api(business,'assign-developer',{'username':'workflow_developer'});api(developer,'propose-solution',{'scope':'F-01 按状态筛选订单','outOfScope':'不修改历史订单'});api(business,'confirm-solution',{'proposalVersion':1,'confirm':True,'comment':'同意实施'})
|
||||
errors=[]
|
||||
owner=business.new_page();dev=developer.new_page()
|
||||
for page in [owner,dev]:page.on('pageerror',lambda e:errors.append(str(e)))
|
||||
def open_record(page,tab='交付流程'):
|
||||
page.goto(origin);page.wait_for_load_state('networkidle');page.get_by_role('button',name=title,exact=True).click();page.get_by_role('tab',name=tab,exact=False).click()
|
||||
def begin(page,action):page.get_by_role('button',name=action,exact=True).click();expect(page.locator('.workflow-form')).to_be_visible()
|
||||
def fill(page,values):
|
||||
form=page.locator('.workflow-form')
|
||||
for label,value in values.items():form.get_by_label(label,exact=False).and_(form.locator('input:not([type=checkbox]), textarea')).fill(str(value))
|
||||
def confirm(page):page.locator('.workflow-form').get_by_label('我已核对内容并确认提交',exact=True).check()
|
||||
def submit(page,label):page.locator('.workflow-form').get_by_role('button',name=label,exact=True).click();expect(page.locator('.workflow-form')).not_to_be_attached()
|
||||
def screenshot(page,name):
|
||||
page.locator('.toast').wait_for(state='hidden');page.screenshot(path=str(out/name),animations='disabled')
|
||||
open_record(dev);begin(dev,'提出交付计划');fill(dev,{'预计工作量':'16','计划提测日期':'2026-10-01','验收反馈截止日期':'2026-10-02','计划上线日期':'2026-10-03','排期依据':'按业务节点安排'})
|
||||
dev.locator('.workflow-form').get_by_label('需要业务方确认设计稿或交互说明',exact=True).check()
|
||||
dev.get_by_role('button',name='关闭需求详情',exact=True).click();expect(dev.get_by_role('alertdialog')).to_be_visible();dev.get_by_role('button',name='继续填写',exact=True).click()
|
||||
expect(dev.locator('.workflow-form').get_by_label('预计工作量',exact=False)).to_have_value('16')
|
||||
screenshot(dev,'plan-form-desktop.png');submit(dev,'提出交付计划')
|
||||
open_record(owner);begin(owner,'确认交付计划');fill(owner,{'确认意见':'同意此工作量和日期'});confirm(owner);submit(owner,'确认交付计划')
|
||||
open_record(dev);begin(dev,'提交设计确认');fill(dev,{'设计稿或交互说明链接':'https://design.example.test/v1','设计版本':'设计负责人 A,版本 v1'});submit(dev,'提交设计确认')
|
||||
open_record(owner);begin(owner,'确认设计');fill(owner,{'确认意见':'设计与业务流程一致'});confirm(owner);submit(owner,'确认设计')
|
||||
open_record(dev);begin(dev,'开始开发');fill(dev,{'技术方案与代码分支':'技术方案 T-1,分支 feature/order-status','依赖、接口与开发准入检查':'依赖已落实,接口约定完成'});confirm(dev);submit(dev,'开始开发')
|
||||
begin(dev,'更新开发进度');fill(dev,{'完成进度':'80','已完成内容':'筛选逻辑完成,正在自测','下一步':'完成回归并提交验收'});submit(dev,'更新开发进度')
|
||||
checks.append('developer plan, business approval, design confirmation and development progress work through the UI without losing unsaved input')
|
||||
|
||||
dev.set_viewport_size({'width':390,'height':844});begin(dev,'提交业务验收')
|
||||
fill(dev,{'测试版本或提交号':'ui-build-1','测试环境地址':'https://test.example.test/orders','操作步骤及测试数据获取方式':'使用授权测试账号和订单样例','自测结果与记录':'ST-1 自测通过','代码审查结论与记录':'CR-1 审查通过','集成验证结果与已知问题':'集成通过,无已知问题'})
|
||||
dev.get_by_label('验收项 1 场景与操作',exact=True).fill('在订单列表筛选待发货状态')
|
||||
confirm(dev);dev.locator('.workflow-form h2').scroll_into_view_if_needed();screenshot(dev,'testing-form-mobile.png')
|
||||
dev.locator('.testing-items').scroll_into_view_if_needed();screenshot(dev,'testing-checklist-mobile.png')
|
||||
assert dev.get_by_role('dialog').evaluate('(e)=>e.scrollWidth<=e.clientWidth+1')
|
||||
submit(dev,'提交业务验收')
|
||||
open_record(owner,'业务验收');owner.get_by_label('AC-01 验收结果',exact=True).select_option('通过')
|
||||
owner.get_by_label('遗留问题、证据/缺陷及处理计划',exact=False).fill('无,验收证据 AC-1')
|
||||
owner.get_by_label('我已逐项核对以上版本并确认验收结果;全部通过后,同意按约定发布计划上线。',exact=True).check()
|
||||
owner.get_by_role('button',name='提交验收结论',exact=True).click();expect(owner.locator('.acceptance-confirm')).not_to_be_attached()
|
||||
checks.append('mobile developer testing checklist reaches business acceptance and confirmed results advance to release')
|
||||
|
||||
dev.set_viewport_size({'width':1440,'height':1000});open_record(dev);begin(dev,'登记生产发布')
|
||||
fill(dev,{'上一稳定版本':'stable-0','回滚与恢复方案':'恢复上一镜像,按备份方案核对数据','备份、数据脚本和兼容性检查':'B-1 备份完整,与旧版兼容','实际发布操作及结果':'发布记录 D-1,部署完成','生产验证与监控方式':'核对订单查询及错误日志','观察时长':'15'})
|
||||
for box in dev.locator('.workflow-form input[type=checkbox]').all():box.check()
|
||||
submit(dev,'登记生产发布');begin(dev,'记录生产验证');fill(dev,{'核心功能、数据与监控验证结果':'核心查询和统计正常,无错误告警'});confirm(dev);submit(dev,'记录生产验证')
|
||||
begin(dev,'交付完成并归档');fill(dev,{'观察结论与交付总结':'业务验证与监控正常','交接资料及业务通知记录':'交接 H-1,已通知业务负责人','监控、故障联系人和告警渠道':'监控 M-1,联系人 workflow_developer'});confirm(dev)
|
||||
dev.locator('.workflow-form').get_by_role('button',name='交付完成并归档',exact=True).click()
|
||||
expect(dev.get_by_role('alert')).to_contain_text('尚未达到约定观察结束时间')
|
||||
expect(dev.locator('.workflow-form').get_by_label('观察结论与交付总结',exact=False)).to_have_value('业务验证与监控正常')
|
||||
# This is a guarded disposable fixture, never the preview or production database.
|
||||
connection=sqlite3.connect(data_dir/'demand-center.sqlite');row=connection.execute('SELECT payload FROM demands WHERE id=?',(record['id'],)).fetchone();payload=json.loads(row[0]);payload['delivery']['releases'][-1]['observeUntil']='2000-01-01T00:00:00.000Z';connection.execute('UPDATE demands SET payload=? WHERE id=?',(json.dumps(payload,ensure_ascii=False),record['id']));connection.commit();connection.close()
|
||||
submit(dev,'交付完成并归档');expect(dev.get_by_text('已完成',exact=True).first).to_be_visible();screenshot(dev,'completed-delivery-desktop.png')
|
||||
checks.append('release checks, production verification and observation-gated completion preserve input on rejection and archive the full record')
|
||||
|
||||
open_record(dev);begin(dev,'登记线上故障并启动修复');fill(dev,{'线上故障及影响范围':'查询边界故障','既有范围内需要修复的内容':'修复订单查询边界'});confirm(dev);submit(dev,'登记线上故障并启动修复')
|
||||
open_record(owner,'需求变更');begin(owner,'提出需求变更');fill(owner,{'变更内容':'增加退款订单筛选规则','变更原因':'业务确认新口径'});submit(owner,'提出需求变更')
|
||||
open_record(dev,'需求变更');begin(dev,'评估需求变更');fill(dev,{'工作量、设计、数据及交付风险影响':'增加 4 小时,影响查询和验收','调整后实施范围与功能说明':'F-01 查询退款订单','调整后范围外事项':'无','调整后验收标准':'退款状态筛选结果准确','新的需求文档版本':'v2.0'})
|
||||
dev.locator('.workflow-form').get_by_label('需要业务方确认设计稿或交互说明',exact=True).uncheck();submit(dev,'评估需求变更')
|
||||
open_record(owner,'需求变更');begin(owner,'确认需求变更');fill(owner,{'确认意见':'同意新的范围、口径与交付计划'});confirm(owner);submit(owner,'确认需求变更')
|
||||
expect(owner.get_by_text('已确认',exact=True).first).to_be_visible();screenshot(owner,'approved-change-desktop.png')
|
||||
open_record(owner,'缺陷');begin(owner,'登记缺陷');fill(owner,{'缺陷标题':'提示文案错误','发现版本':'ui-build-1','复现步骤':'打开查询页面','预期结果':'显示准确提示','实际结果':'提示文字错误','证据、截图或日志链接':'https://evidence.example.test/defect-1'})
|
||||
owner.locator('.workflow-form').get_by_label('影响核心流程、数据或权限,阻断交付',exact=True).uncheck();submit(owner,'登记缺陷')
|
||||
open_record(dev,'缺陷');dev.get_by_role('button',name='提交复验',exact=True).click();fill(dev,{'修复版本或提交号':'ui-fix-1','处理说明':'已修复提示文字'});submit(dev,'提交缺陷复验')
|
||||
open_record(owner,'缺陷');owner.get_by_role('button',name='复验缺陷',exact=True).click();fill(owner,{'处理说明':'复验通过'});confirm(owner);submit(owner,'复验缺陷');expect(owner.get_by_text('已关闭',exact=True)).to_be_visible()
|
||||
owner.set_viewport_size({'width':390,'height':844});screenshot(owner,'closed-defect-mobile.png')
|
||||
checks.append('business change request, developer impact assessment, explicit approval and independent defect verification are operable')
|
||||
|
||||
observer=admin.new_page();observer.goto(origin);observer.wait_for_load_state('networkidle');observer.get_by_role('navigation',name='主导航').get_by_role('button',name='全部需求',exact=True).click();observer.get_by_role('button',name=title,exact=True).click();observer.get_by_role('tab',name='交付流程',exact=True).click()
|
||||
expect(observer.locator('.workflow-buttons button')).to_have_count(0)
|
||||
observer.get_by_role('tab',name='缺陷',exact=True).click();expect(observer.get_by_role('button',name='登记缺陷',exact=True)).not_to_be_attached()
|
||||
checks.append('administrator global visibility remains read-only for all new workflow controls')
|
||||
assert not errors,errors
|
||||
print(json.dumps({'result':'passed','checks':checks,'screenshots':str(out)},ensure_ascii=False),flush=True)
|
||||
browser.close()
|
||||
@@ -0,0 +1,151 @@
|
||||
/** Disposable real HTTP workflow test. No production data or credentials are used. */
|
||||
import assert from 'node:assert/strict';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { mkdtemp, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { createServer } from 'node:net';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
const directory=await mkdtemp(join(tmpdir(),'demand-workflow-test-'));
|
||||
const port=await new Promise(resolve=>{const s=createServer();s.listen(0,'127.0.0.1',()=>{const p=s.address().port;s.close(()=>resolve(p));});});
|
||||
const origin=`http://127.0.0.1:${port}`,secret=()=>randomBytes(24).toString('base64url'),initial=secret();
|
||||
let child,logs='',checks=0,record;
|
||||
const verify=(test,message)=>{assert(test,message);checks++;};
|
||||
async function start(){child=spawn(process.execPath,['scripts/start.mjs'],{env:{...process.env,APP_URL:origin,PORT:String(port),HOSTNAME:'127.0.0.1',DATA_DIR:directory,INITIAL_ADMIN_USERNAME:'workflow_admin',INITIAL_ADMIN_PASSWORD:initial},stdio:['ignore','pipe','pipe']});child.stdout.on('data',x=>logs+=x);child.stderr.on('data',x=>logs+=x);for(let i=0;i<150;i++){if(child.exitCode!==null)throw new Error(logs);try{if((await fetch(origin+'/api/health')).ok)return;}catch{}await new Promise(resolve=>setTimeout(resolve,100));}throw new Error(logs);}
|
||||
async function stop(){if(child&&child.exitCode===null){child.kill('SIGTERM');await new Promise(resolve=>child.once('exit',resolve));}}
|
||||
async function call(path,cookie,body,method){const response=await fetch(origin+path,{method:method??(body?'POST':'GET'),headers:{...(cookie?{Cookie:cookie}:{}),...(body?{Origin:origin,'Content-Type':'application/json'}:{})},body:body?JSON.stringify(body):undefined});const data=await response.json();return {status:response.status,data,cookie:response.headers.get('set-cookie')?.split(';')[0]};}
|
||||
async function step(cookie,action,values={},expected=200){const response=await call('/api/demands',cookie,{action,id:record.id,revision:record.revision,...values});verify(response.status===expected,`${action}: expected ${expected}, received ${response.status} ${JSON.stringify(response.data)}`);if(response.status===200)record=response.data.demand;return response;}
|
||||
const fields={title:'完整交付 HTTP 回归',project:'业务系统',module:'订单',type:'新增功能',proposer:'业务',department:'业务部',source:'测试',owner:'业务',background:'需要查询订单',impact:'业务人员',goal:'正确筛选订单',expectedDate:'',noFixedDate:true,dateReason:'',scope:'',outOfScope:'',criteria:'筛选结果正确',priority:'P2',priorityReason:'业务查询',dataSource:'',dataContact:'',noData:true,risk:'无',pending:'无',references:'',version:'v1.0'};
|
||||
const plan={hours:8,testDate:'2026-10-01',feedbackDate:'2026-10-02',releaseDate:'2026-10-03',priority:'P1',designRequired:true,notes:'交付计划'};
|
||||
const testing={testVersion:'http-build-1',environment:'https://test.example.test',deadline:'2026-10-02',instructions:'按测试数据操作',selfTest:'自测通过,证据 ST-1',codeReview:'审查通过 CR-1',integration:'集成验证通过,无已知问题',items:[{id:'AC-01',feature:'F-01',scenario:'筛选状态',expected:'仅展示匹配订单'}],confirm:true};
|
||||
const release={version:'http-build-2',previousVersion:'stable-0',rollbackPlan:'恢复上一版本',backup:'快照 B-1,数据库兼容',deployment:'部署完成,记录 D-1',verificationPlan:'核对核心流程及监控',observationMinutes:15,testsPassed:true,configurationReady:true,recoveryReady:true,noticeComplete:true,confirm:true};
|
||||
try{
|
||||
await start();let login=await call('/api/auth/login',null,{username:'workflow_admin',password:initial});verify(login.status===200,'admin login');const adminPass=secret();const changed=await call('/api/auth/password',login.cookie,{currentPassword:initial,newPassword:adminPass});verify(changed.status===200,'admin initial password change');const admin=changed.cookie;
|
||||
async function account(username,role='user'){const password=secret(),next=secret();verify((await call('/api/admin/users',admin,{username,displayName:username,password,role})).status===201,'account created');const login=await call('/api/auth/login',null,{username,password});const result=await call('/api/auth/password',login.cookie,{currentPassword:password,newPassword:next});verify(result.status===200,'account initialized');return result.cookie;}
|
||||
const owner=await account('workflow_business'),dev=await account('workflow_developer'),other=await account('workflow_other');
|
||||
const created=await call('/api/demands',owner,{action:'create',mode:'review',fields});verify(created.status===200,'review demand created');record=created.data.demand;
|
||||
await step(owner,'assign-developer',{username:'workflow_developer'});await step(dev,'propose-solution',{scope:'F-01 按状态筛选订单',outOfScope:'不改写历史数据'});await step(owner,'confirm-solution',{proposalVersion:1,confirm:true,comment:'同意方案'});
|
||||
for(const action of ['propose-plan','decide-plan','start-development','submit-testing','report-defect','publish','complete','rollback'])await step(admin,action,{},404);
|
||||
await step(other,'add-note',{notes:'无权查看'},404);
|
||||
await step(owner,'propose-plan',plan,403);
|
||||
await step(dev,'start-development',{technicalPlan:'分支',dependencies:'无',confirm:true},409);
|
||||
await step(dev,'propose-plan',{...plan,feedbackDate:'2026-09-01'},400);
|
||||
await step(dev,'propose-plan',plan);await step(owner,'decide-plan',{planVersion:0,approved:true,comment:'错误版本',confirm:true},409);
|
||||
await step(owner,'decide-plan',{planVersion:record.plan.version,approved:false,comment:'调整计划',confirm:true});
|
||||
await step(dev,'propose-plan',plan);await step(owner,'decide-plan',{planVersion:record.plan.version,approved:true,comment:'确认计划',confirm:true});verify(record.status==='已排期','plan moves demand to scheduled');
|
||||
await step(dev,'start-development',{technicalPlan:'技术方案 T-1',dependencies:'依赖检查通过',confirm:true},409);
|
||||
await step(dev,'submit-design',{reference:'https://design.example.test/v1',notes:'设计师 A 的交互设计'});await step(owner,'decide-design',{approved:false,comment:'补充空态',confirm:true});
|
||||
await step(dev,'submit-design',{reference:'https://design.example.test/v2',notes:'补充空态'});await step(owner,'decide-design',{approved:true,comment:'确认设计',confirm:true});await step(dev,'start-development',{technicalPlan:'技术方案 T-1 / feature/REQ',dependencies:'依赖和接口已验证',confirm:true});
|
||||
const revision=record.revision;
|
||||
const writes=await Promise.all([call('/api/demands',dev,{action:'update-progress',id:record.id,revision,percent:40,notes:'完成接口',next:'自测'}),call('/api/demands',dev,{action:'update-progress',id:record.id,revision,percent:50,notes:'完成查询',next:'联调'})]);
|
||||
verify(writes.filter(x=>x.status===200).length===1&&writes.filter(x=>x.status===409).length===1,'concurrent updates preserve one acknowledged revision');record=writes.find(x=>x.status===200).data.demand;
|
||||
await step(owner,'set-blocker',{reason:'待提供样例',owner:'业务方',dueDate:'2026-10-01'});await step(dev,'submit-testing',testing,409);await step(owner,'resolve-blocker',{notes:'样例已提供'});
|
||||
await step(dev,'submit-testing',{...testing,items:[testing.items[0],testing.items[0]]},400);await step(dev,'submit-testing',testing);verify(record.status==='待验收','testing entry is reachable');
|
||||
await step(dev,'accept',{results:['通过'],notes:'越权',confirm:true,testVersion:testing.testVersion,version:record.fields.version,round:1},403);
|
||||
await step(owner,'accept',{results:['不通过'],notes:'空数据错误',confirm:true,testVersion:testing.testVersion,version:record.fields.version,round:1});verify(record.status==='开发中','failed acceptance returns to development');
|
||||
await step(dev,'submit-testing',testing,409);await step(dev,'submit-testing',{...testing,testVersion:'http-build-2'});
|
||||
const defect={title:'空数据异常',steps:'空数据查询',expected:'空态',actual:'报错',evidence:'日志 E-1',version:'http-build-2',blocking:true};
|
||||
await step(owner,'report-defect',defect);const defectId=record.delivery.defects[0].id;
|
||||
await step(owner,'accept',{results:['通过'],notes:'无',confirm:true,testVersion:'http-build-2',version:record.fields.version,round:2},409);
|
||||
await step(dev,'resolve-defect',{defectId,fixVersion:'http-build-3',notes:'修复空态'});await step(owner,'verify-defect',{defectId,approved:true,notes:'复验通过',confirm:true});
|
||||
// A new fixed binary must be submitted and accepted rather than publishing the older test version.
|
||||
verify(record.status==='开发中'&&record.acceptance.withdrawnAt,'recording a defect fix invalidates the older test version');await step(dev,'submit-testing',{...testing,testVersion:'http-build-3'});
|
||||
await step(owner,'accept',{results:['通过'],notes:'无遗留',confirm:true,testVersion:'http-build-3',version:record.fields.version,round:3});
|
||||
await step(dev,'publish',release,409);
|
||||
await step(dev,'publish',{...release,version:'http-build-3'});verify(record.status==='已上线','production release is reachable');
|
||||
await step(dev,'verify-production',{approved:true,results:'核心功能、数据及错误监控正常',confirm:true});
|
||||
const complete={summary:'观察与验证通过',handover:'交接文档 H-1,已通知业务方',monitoring:'监控 M-1,联系人 D',confirm:true};
|
||||
await step(dev,'complete',complete,409);
|
||||
// Advance only the disposable fixture's observation deadline; production has no clock override.
|
||||
const database=new DatabaseSync(join(directory,'demand-center.sqlite'));
|
||||
const stored=JSON.parse(database.prepare('SELECT payload FROM demands WHERE id = ?').get(record.id).payload);stored.delivery.releases.at(-1).observeUntil='2000-01-01T00:00:00.000Z';database.prepare('UPDATE demands SET payload = ? WHERE id = ?').run(JSON.stringify(stored),record.id);database.close();
|
||||
await step(dev,'complete',complete);verify(record.status==='已完成'&&record.delivery.releases[0].completion,'completion and archival evidence persisted');
|
||||
const before=structuredClone(record);await stop();await start();const persisted=(await call('/api/demands',owner)).data.demands.find(x=>x.id===record.id);verify(persisted.delivery.testing.length===3&&persisted.delivery.releases[0].completion.summary===before.delivery.releases[0].completion.summary,'workflow history survives server restart');
|
||||
record=persisted;await step(dev,'reopen-incident',{impact:'线上边界故障',reason:'在既有范围内修复',confirm:true});
|
||||
await step(owner,'change',{content:'补充筛选规则',reason:'业务明确规则'});const changeId=record.changes.at(-1).id;
|
||||
await step(dev,'submit-testing',{...testing,testVersion:'http-build-4'},409);
|
||||
await step(dev,'assess-change',{...plan,designRequired:false,changeId,impact:'新增 4 小时,影响查询与验收',scope:'F-01 新筛选',outOfScope:'无',criteria:'按新规则验证',version:'v2.0'});
|
||||
await step(owner,'decide-change',{changeId,approved:true,comment:'确认新范围、版本和计划',confirm:true});verify(record.status==='已排期'&&record.fields.version==='v2.0'&&record.review.proposals.length===2,'approved change updates scope and plan and requires fresh development');
|
||||
await step(dev,'start-development',{technicalPlan:'新技术说明 T-2',dependencies:'接口已核对',confirm:true});await step(dev,'submit-testing',{...testing,testVersion:'http-build-4'});await step(owner,'accept',{results:['通过'],notes:'无',confirm:true,testVersion:'http-build-4',version:'v2.0',round:4});await step(dev,'request-recovery',{targetVersion:'stable-0',dataImpact:'先核对新增数据',plan:'恢复前保留增量'});const recoveryReleaseId=record.delivery.releases.at(-1).id;
|
||||
await step(dev,'publish',{...release,version:'http-build-4'},409);
|
||||
await step(owner,'withdraw-recovery',{releaseId:recoveryReleaseId,reason:'不能代开发撤回'},403);
|
||||
await step(dev,'withdraw-recovery',{releaseId:recoveryReleaseId,reason:'采用新版本修复,无需恢复数据'});
|
||||
await step(owner,'decide-recovery',{releaseId:recoveryReleaseId,approved:true,comment:'不能确认已撤回申请',confirm:true},409);
|
||||
await step(dev,'publish',{...release,version:'http-build-4'});
|
||||
const rollback={runningVersion:'stable-0',reason:'数据校验异常',verification:'恢复后数据正确',dataRestored:true,confirm:true};
|
||||
await step(dev,'rollback',rollback,409);await step(dev,'request-recovery',{targetVersion:'stable-0',dataImpact:'恢复快照并保留增量',plan:'先冻结写入,导出新增数据再恢复与合并'});await step(owner,'decide-recovery',{approved:true,comment:'确认数据影响与保留方式',confirm:true});await step(dev,'rollback',rollback);verify(record.status==='开发中'&&record.delivery.releases.at(-1).rollback.dataRestored,'approved data recovery is recorded and returns to development');
|
||||
await step(dev,'retrospective',{cause:'遗漏边界数据',actions:'增加数据校验及回归案例',owner:'开发责任人',dueDate:'2026-10-05'});
|
||||
const hotfix={...release,version:'http-hotfix-1',businessRulesUnchanged:true,scopeUnchanged:true,noIrreversibleData:true,emergencyReason:'核心查询故障,不能等待完整验收',fixSummary:'修复查询边界,不改变业务规则',selfTest:'自测通过 ST-H1',codeReview:'独立审查通过 CR-H1',integration:'构建和回归通过',knownIssues:'无',followUpPlan:'同步主分支,下一工作日补充记录并由业务核对查询',followUpDate:'2099-10-05'};
|
||||
await step(owner,'publish-emergency',hotfix,403);await step(admin,'publish-emergency',hotfix,404);
|
||||
await step(dev,'publish-emergency',{...hotfix,scopeUnchanged:false},409);await step(dev,'publish-emergency',{...hotfix,codeReview:''},400);
|
||||
await step(dev,'publish-emergency',hotfix);verify(record.status==='已上线'&&record.delivery.releases.at(-1).emergency&&record.acceptance.withdrawnAt,'emergency release records technical evidence without faking a passed acceptance');
|
||||
const hotfixReleaseId=record.delivery.releases.at(-1).id;
|
||||
await step(dev,'complete',complete,409);await step(dev,'verify-emergency',{releaseId:hotfixReleaseId,approved:true,comment:'不能代业务验证',confirm:true},403);
|
||||
await step(owner,'verify-emergency',{releaseId:'stale',approved:true,comment:'错版本',confirm:true},409);
|
||||
await step(owner,'verify-emergency',{releaseId:hotfixReleaseId,approved:true,comment:'业务核心查询正常',confirm:true});await step(dev,'verify-production',{approved:true,results:'生产指标正常',confirm:true});await step(dev,'complete',complete,409);
|
||||
const hotfixDb=new DatabaseSync(join(directory,'demand-center.sqlite'));const hotfixStored=JSON.parse(hotfixDb.prepare('SELECT payload FROM demands WHERE id = ?').get(record.id).payload);hotfixStored.delivery.releases.at(-1).observeUntil='2000-01-01T00:00:00.000Z';hotfixDb.prepare('UPDATE demands SET payload = ? WHERE id = ?').run(JSON.stringify(hotfixStored),record.id);hotfixDb.close();
|
||||
await step(dev,'complete',complete);verify(record.status==='已完成','emergency completion requires business verification, production verification and observation');
|
||||
await stop();await start();record=(await call('/api/demands',owner)).data.demands.find(x=>x.id===record.id);verify(record.delivery.releases.at(-1).emergency.followUp.approved,'emergency confirmation survives server restart');
|
||||
await step(dev,'reopen-incident',{impact:'再次跟进边界问题',reason:'进入交接前修复',confirm:true});
|
||||
const beforeUnauthorized=JSON.stringify(record.delivery);await step(admin,'complete',complete,404);verify(JSON.stringify((await call('/api/demands',owner)).data.demands.find(x=>x.id===record.id).delivery)===beforeUnauthorized,'read-only administrator never mutates lifecycle data');
|
||||
await step(owner,'change',{content:'交接前待定变更',reason:'确认交接范围'});
|
||||
await step(owner,'assign-developer',{username:'workflow_other'},409);
|
||||
await step(owner,'withdraw-change',{changeId:record.changes.at(-1).id,comment:'先交接原范围'});
|
||||
const previousPlan=record.plan.version,previousRound=record.acceptance.round;
|
||||
await step(owner,'assign-developer',{username:'workflow_other'});
|
||||
verify(record.status==='待评审'&&record.review.proposals.at(-1).invalidated&&record.acceptance.withdrawnAt&&record.delivery.testing.find(x=>x.round===previousRound).withdrawnAt,'late developer handoff invalidates the solution and current test version while retaining history');
|
||||
await step(dev,'update-progress',{percent:80,notes:'原开发无权修改',next:'交接'},404);
|
||||
verify(!(await call('/api/demands',dev)).data.demands.some(x=>x.id===record.id),'previous developer loses demand access after handoff');
|
||||
await step(other,'submit-testing',{...testing,testVersion:'http-build-5'},409);
|
||||
await step(other,'propose-solution',{scope:record.fields.scope,outOfScope:record.fields.outOfScope});await step(owner,'confirm-solution',{proposalVersion:record.review.proposals.at(-1).version,confirm:true,comment:'新开发接手方案'});
|
||||
await step(owner,'decide-plan',{planVersion:previousPlan,approved:true,comment:'旧排期不能再次批准',confirm:true},409);
|
||||
await step(other,'propose-plan',{...plan,designRequired:false});await step(owner,'decide-plan',{planVersion:record.plan.version,approved:true,comment:'确认新开发排期',confirm:true});
|
||||
await step(owner,'change',{content:'取消前待确认变更',reason:'业务方向调整'});await step(owner,'set-blocker',{reason:'暂停业务',owner:'业务方',dueDate:'2026-10-01'});
|
||||
await step(owner,'cancel',{reason:'该业务目标停止投入'});verify(record.status==='已取消'&&record.changes.at(-1).status==='随需求取消'&&!record.blocked&&!record.delivery.blocker,'cancellation closes pending changes and blockers while retaining their history');
|
||||
await step(other,'propose-plan',plan,409);await step(owner,'report-defect',defect,409);
|
||||
const draft=await call('/api/demands',owner,{action:'create',mode:'draft',fields:{...fields,title:'交付草稿边界'}});verify(draft.status===200,'draft fixture created');record=draft.data.demand;await step(owner,'add-note',{notes:'草稿不能执行交付'},409);
|
||||
// Recover a disabled default administrator without granting general write access to observers.
|
||||
const recoveryCreated=await call('/api/demands',owner,{action:'create',mode:'review',fields:{...fields,title:'停用管理员交接回归'}});verify(recoveryCreated.status===200,'handoff fixture created');record=recoveryCreated.data.demand;
|
||||
const originalAdminId=record.review.developer.userId;
|
||||
const backup=await account('workflow_backup','admin');
|
||||
await step(backup,'take-over-development',{confirm:true},404);
|
||||
await step(admin,'propose-solution',{scope:'F-01 原开发方案',outOfScope:'无'});await step(owner,'confirm-solution',{proposalVersion:1,confirm:true});
|
||||
await step(admin,'propose-plan',{...plan,designRequired:false});await step(owner,'decide-plan',{planVersion:1,approved:true,comment:'原计划确认',confirm:true});
|
||||
await step(admin,'start-development',{technicalPlan:'原技术方案',dependencies:'无',confirm:true});await step(admin,'submit-testing',testing);
|
||||
await step(owner,'change',{content:'交接前待处理变更',reason:'确认范围'});
|
||||
const oldProposal=structuredClone(record.review.proposals[0]),oldPlan=structuredClone(record.plan),oldRound=record.acceptance.round;
|
||||
verify((await call('/api/admin/users',backup,{action:'disable',id:originalAdminId},'PATCH')).status===200,'backup administrator disables original administrator');
|
||||
verify((await call('/api/demands',admin)).status===401,'disabled administrator session is revoked');
|
||||
const takeoverView=(await call('/api/demands',backup)).data.demands.find(d=>d.id===record.id);
|
||||
verify(takeoverView.access.canTakeOverDevelopment&&!takeoverView.access.developer&&!takeoverView.access.business,'observer receives only the explicit recovery capability');
|
||||
verify(!(await call('/api/demands',owner)).data.demands.find(d=>d.id===record.id).access.canTakeOverDevelopment,'business account cannot recover development ownership');
|
||||
await step(backup,'propose-solution',{scope:'不能在接手前写入',outOfScope:'无'},404);
|
||||
await step(owner,'take-over-development',{confirm:true},403);
|
||||
await step(backup,'take-over-development',{confirm:true},409);
|
||||
const staleRevision=record.revision;
|
||||
await step(owner,'withdraw-change',{changeId:record.changes.at(-1).id,comment:'先交接原范围'});
|
||||
verify((await call('/api/demands',backup,{action:'take-over-development',id:record.id,revision:staleRevision,confirm:true})).status===409,'handoff rejects stale demand revisions');
|
||||
await step(backup,'take-over-development',{confirm:false},400);
|
||||
verify((await call('/api/admin/users',backup,{action:'enable',id:originalAdminId},'PATCH')).status===200,'original account can be re-enabled before handoff');
|
||||
await step(backup,'take-over-development',{confirm:true},404);
|
||||
verify((await call('/api/admin/users',backup,{action:'disable',id:originalAdminId},'PATCH')).status===200,'original account disabled for confirmed handoff');
|
||||
await step(backup,'take-over-development',{confirm:true,username:'workflow_other',developer:{userId:'spoof'}});
|
||||
verify(record.review.developer.username==='workflow_backup'&&record.access.developer&&!record.access.business&&!record.access.canTakeOverDevelopment,'handoff target comes from authenticated administrator, never request fields');
|
||||
verify(record.status==='待评审'&&record.acceptance.withdrawnAt&&record.delivery.testing.find(x=>x.round===oldRound).withdrawnAt,'handoff requires renewed review and acceptance');
|
||||
verify(record.review.proposals[0].invalidated&&JSON.stringify(record.review.proposals[0].decision)===JSON.stringify(oldProposal.decision)&&JSON.stringify(record.plan)===JSON.stringify(oldPlan),'handoff retains original proposal decision and delivery plan evidence');
|
||||
verify(record.history.at(-1).action==='接手开发职责'&&record.history.at(-1).detail.includes('workflow_admin')&&record.history.at(-1).detail.includes('workflow_backup'),'handoff is audited with original and replacement accounts');
|
||||
await step(backup,'confirm-solution',{proposalVersion:1,confirm:true},403);
|
||||
await step(backup,'propose-solution',{scope:'F-01 接手后重新提出方案',outOfScope:'无'});
|
||||
await step(owner,'confirm-solution',{proposalVersion:2,confirm:true});
|
||||
await step(backup,'start-development',{technicalPlan:'新技术方案',dependencies:'无',confirm:true},409);
|
||||
await step(backup,'propose-plan',{...plan,designRequired:false});await step(owner,'decide-plan',{planVersion:record.plan.version,approved:true,comment:'确认接手后计划',confirm:true});
|
||||
await step(backup,'start-development',{technicalPlan:'新技术方案',dependencies:'无',confirm:true});
|
||||
verify((await call('/api/admin/users',backup,{action:'enable',id:originalAdminId},'PATCH')).status===200,'former administrator restored without ownership');
|
||||
const restored=(await call('/api/auth/login',null,{username:'workflow_admin',password:adminPass})).cookie;
|
||||
await step(restored,'update-progress',{percent:80,notes:'不能恢复原权限',next:'无'},404);
|
||||
const handoffId=record.id;await stop();await start();
|
||||
record=(await call('/api/demands',backup)).data.demands.find(d=>d.id===handoffId);
|
||||
verify(record.review.developer.username==='workflow_backup'&&record.review.proposals.length===2&&record.access.developer,'handoff ownership and historical evidence survive restart');
|
||||
console.log(`${checks} complete-workflow HTTP checks passed.`);
|
||||
}catch(error){console.error(error);process.exitCode=1;}finally{await stop();await rm(directory,{recursive:true,force:true});}
|
||||
@@ -0,0 +1,219 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { test } from 'node:test';
|
||||
import { emptyFields, needsAction, type Demand } from '../lib/demand.ts';
|
||||
import { applyWorkflowAction } from '../lib/server/workflow.ts';
|
||||
import { planConfirmed, unresolvedDefects, latestRelease, workflowTask, nextAcceptanceId, pendingRecovery, pendingEmergencyVerification, designConfirmed } from '../lib/workflow.ts';
|
||||
import type { AuthUser } from '../lib/server/auth.ts';
|
||||
const owner:AuthUser={userId:'business',username:'business',displayName:'业务',role:'user',mustChangePassword:false};
|
||||
const dev:AuthUser={userId:'developer',username:'developer',displayName:'开发',role:'user',mustChangePassword:false};
|
||||
const admin:AuthUser={userId:'observer',username:'admin',displayName:'管理员',role:'admin',mustChangePassword:false};
|
||||
const now='2026-09-17T08:00:00.000Z';
|
||||
const plan={hours:8,testDate:'2026-09-18',feedbackDate:'2026-09-19',releaseDate:'2026-09-20',priority:'P1',designRequired:false,notes:'双方约定的交付计划'};
|
||||
const testing={testVersion:'build-1',environment:'https://test.example.test',deadline:'2026-09-19',instructions:'使用测试数据按步骤操作',selfTest:'自测通过',codeReview:'代码审查记录 CR-1',integration:'集成验证通过,无已知问题',items:[{id:'AC-01',feature:'F-01',scenario:'按订单状态查询',expected:'结果符合筛选条件'}],confirm:true};
|
||||
const publish={version:'build-1',previousVersion:'build-0',rollbackPlan:'恢复上一版本',backup:'备份 B-1,数据库兼容',deployment:'已实际发布',verificationPlan:'查询核心数据,检查日志',observationMinutes:30,testsPassed:true,configurationReady:true,recoveryReady:true,noticeComplete:true,confirm:true};
|
||||
function fixture(design=false){
|
||||
let d:Demand={id:'REQ-test',revision:1,fields:{...emptyFields,title:'完整流程',version:'v1.0'},status:'待评审',createdAt:now,updatedAt:now,reviewReady:true,history:[],changes:[],review:{developer:dev,proposals:[{version:1,scope:'F-01',outOfScope:'无',developer:dev,submittedAt:now,businessFields:{...emptyFields},decision:{result:'confirmed',actor:owner,time:now,comment:'同意'}}]}};
|
||||
const act=(user:AuthUser,action:string,body:Record<string,unknown>={},time=now)=>{const next=structuredClone(d);const result=applyWorkflowAction(next,owner.userId,user,{...body,action},time);next.revision++;next.history.push({time,actor:user.displayName,action:result.label,detail:result.detail});d=next;return d;};
|
||||
const schedule=()=>{act(dev,'propose-plan',{...plan,designRequired:design});act(owner,'decide-plan',{planVersion:d.plan!.version,approved:true,comment:'确认排期',confirm:true});};
|
||||
const start=()=>act(dev,'start-development',{technicalPlan:'技术方案与分支 feature/test',dependencies:'接口和依赖已落实',confirm:true});
|
||||
const accept=()=>act(owner,'accept',{testVersion:d.acceptance!.testVersion,version:d.fields.version,round:d.acceptance!.round,results:['通过'],notes:'无',confirm:true});
|
||||
const release=()=>{schedule();start();act(dev,'submit-testing',testing);accept();act(dev,'publish',publish);};
|
||||
return {get d(){return d;},act,schedule,start,accept,release};
|
||||
}
|
||||
|
||||
test('plan approval, design confirmation and development entry enforce distinct responsibility and prerequisites',()=>{
|
||||
const f=fixture(true);
|
||||
assert.throws(()=>f.start(),/交付计划|当前处于/);
|
||||
assert.throws(()=>f.act(owner,'propose-plan',plan),/对应责任人/);
|
||||
assert.throws(()=>f.act(admin,'propose-plan',plan),/对应责任人/);
|
||||
assert.throws(()=>f.act(dev,'propose-plan',{...plan,feedbackDate:'2026-09-10'}),/计划/);
|
||||
f.act(dev,'propose-plan',{...plan,designRequired:true});
|
||||
assert.throws(()=>f.act(dev,'decide-plan',{planVersion:1,approved:true,comment:'越权',confirm:true}),/对应责任人/);
|
||||
assert.throws(()=>f.act(owner,'decide-plan',{planVersion:0,approved:true,comment:'旧版',confirm:true}),/版本/);
|
||||
f.act(owner,'decide-plan',{planVersion:1,approved:false,comment:'调整时间',confirm:true});
|
||||
assert.equal(f.d.status,'待评审');
|
||||
f.act(dev,'propose-plan',{...plan,designRequired:true});f.act(owner,'decide-plan',{planVersion:2,approved:true,comment:'同意',confirm:true});
|
||||
assert.equal(f.d.status,'已排期');assert.equal(f.d.delivery!.plans!.length,1);assert.equal(planConfirmed(f.d),true);
|
||||
assert.throws(()=>f.start(),/设计/);
|
||||
f.act(dev,'submit-design',{reference:'https://design.example.test/v1',notes:'设计负责人 A,版本 v1'});
|
||||
f.act(owner,'decide-design',{approved:true,comment:'确认此设计',confirm:true});f.start();assert.equal(f.d.status,'开发中');
|
||||
f.act(dev,'submit-design',{reference:'https://design.example.test/v2',notes:'新交互'});
|
||||
assert.throws(()=>f.act(dev,'submit-testing',testing),/设计/);
|
||||
assert.equal(f.d.delivery!.designHistory!.length,1);
|
||||
});
|
||||
|
||||
test('testing, rejected acceptance, resubmission, publishing and timed completion retain all evidence',()=>{
|
||||
const f=fixture();f.schedule();f.start();f.act(dev,'update-progress',{percent:75,notes:'主要功能完成',next:'执行自测'});
|
||||
f.act(owner,'set-blocker',{reason:'缺少测试数据',owner:'业务方',dueDate:'2026-09-18'});
|
||||
assert.throws(()=>f.act(dev,'submit-testing',testing),/阻塞/);f.act(owner,'resolve-blocker',{notes:'测试数据已提供'});
|
||||
assert.throws(()=>f.act(dev,'submit-testing',{...testing,items:[testing.items[0],testing.items[0]]}),/唯一/);
|
||||
f.act(dev,'submit-testing',testing);
|
||||
assert.throws(()=>f.act(owner,'accept',{testVersion:'stale',version:'v1.0',round:1,results:['通过'],notes:'无',confirm:true}),/版本/);
|
||||
f.act(owner,'accept',{testVersion:'build-1',version:'v1.0',round:1,results:['不通过'],notes:'筛选结果不符',confirm:true});assert.equal(f.d.status,'开发中');
|
||||
assert.throws(()=>f.act(dev,'submit-testing',testing),/已提测/);
|
||||
f.act(dev,'submit-testing',{...testing,testVersion:'build-2'});f.accept();assert.equal(f.d.status,'待发布');
|
||||
assert.throws(()=>f.act(dev,'publish',publish),/发布版本/);
|
||||
assert.throws(()=>f.act(dev,'publish',{...publish,version:'build-2',recoveryReady:false}),/逐项/);
|
||||
f.act(dev,'publish',{...publish,version:'build-2'});assert.equal(f.d.status,'已上线');
|
||||
const complete={summary:'观察正常',handover:'交接文档与通知记录',monitoring:'监控链接和故障联系人',confirm:true};
|
||||
assert.throws(()=>f.act(dev,'complete',complete),/生产验证/);
|
||||
f.act(dev,'verify-production',{approved:false,results:'查询异常',confirm:true});assert.throws(()=>f.act(dev,'complete',complete),/生产验证/);
|
||||
f.act(dev,'verify-production',{approved:true,results:'核心功能和数据已核对',confirm:true});assert.throws(()=>f.act(dev,'complete',complete),/观察结束/);
|
||||
f.act(dev,'complete',complete,'2026-09-17T08:31:00.000Z');assert.equal(f.d.status,'已完成');assert.equal(f.d.delivery!.testing!.length,2);assert.equal(f.d.acceptanceRecords!.length,2);assert.ok(latestRelease(f.d)!.completion);
|
||||
assert.throws(()=>f.act(owner,'reopen-incident',{impact:'异常',reason:'修复',confirm:true}),/对应责任人/);
|
||||
f.act(dev,'reopen-incident',{impact:'线上查询失败',reason:'既有查询范围修复',confirm:true});assert.equal(f.d.status,'开发中');assert.ok(f.d.acceptance!.withdrawnAt);
|
||||
f.act(dev,'retrospective',{cause:'遗漏边界',actions:'补充边界测试',owner:'开发责任人',dueDate:'2026-09-21'});assert.equal(f.d.delivery!.retrospectives!.length,1);
|
||||
});
|
||||
|
||||
test('change assessment is explicit, blocks forward progress, and updates scope and plan only after business approval',()=>{
|
||||
const f=fixture();f.schedule();f.start();const old=structuredClone(f.d.fields);
|
||||
f.act(owner,'change',{content:'增加筛选条件',reason:'业务需要'});const id=f.d.changes[0].id;
|
||||
assert.throws(()=>f.act(dev,'submit-testing',testing),/待处理需求变更/);
|
||||
assert.throws(()=>f.act(owner,'change',{content:'并行变更',reason:'测试'}),/已有变更/);
|
||||
f.act(dev,'assess-change',{...plan,changeId:id,impact:'增加 4 小时工作量',scope:'F-01 新条件',outOfScope:'无',criteria:'新筛选结果正确',version:'v2.0',hours:12});
|
||||
assert.deepEqual(f.d.fields,old);
|
||||
f.act(owner,'decide-change',{changeId:id,approved:false,comment:'暂缓',confirm:true});assert.deepEqual(f.d.fields,old);assert.equal(f.d.status,'开发中');
|
||||
f.act(owner,'change',{content:'再次提出条件调整',reason:'确认业务价值'});const next=f.d.changes[1].id;
|
||||
f.act(dev,'assess-change',{...plan,changeId:next,impact:'影响查询与验收',scope:'F-01 新条件',outOfScope:'无',criteria:'新结果正确',version:'v2.0'});
|
||||
f.act(owner,'decide-change',{changeId:next,approved:true,comment:'同意新范围及排期',confirm:true});
|
||||
assert.equal(f.d.fields.version,'v2.0');assert.equal(f.d.status,'已排期');assert.equal(f.d.review!.proposals.length,2);assert.equal(planConfirmed(f.d),true);assert.deepEqual(f.d.changes[1].originalFields,old);assert.equal(f.d.delivery!.kickoff,undefined);
|
||||
});
|
||||
|
||||
test('blocking defects require repair and independent verification; ordinary deferrals require business approval',()=>{
|
||||
const f=fixture();f.schedule();f.start();
|
||||
const base={title:'查询异常',steps:'执行查询',expected:'正确数据',actual:'无结果',evidence:'日志记录',version:'build-1',blocking:true};
|
||||
f.act(owner,'report-defect',base);const id=f.d.delivery!.defects![0].id;
|
||||
assert.throws(()=>f.act(dev,'defer-defect',{defectId:id,notes:'延后',dueDate:'2026-09-20'}),/阻断/);
|
||||
assert.throws(()=>f.act(dev,'submit-testing',testing),/未修复/);
|
||||
f.act(dev,'resolve-defect',{defectId:id,fixVersion:'fix-1',notes:'修复查询'});f.act(dev,'submit-testing',testing);
|
||||
assert.throws(()=>f.accept(),/阻断缺陷/);
|
||||
f.act(owner,'verify-defect',{defectId:id,approved:true,notes:'复验通过',confirm:true});f.accept();
|
||||
f.act(owner,'report-defect',{...base,title:'提示文案',blocking:false});const minor=f.d.delivery!.defects![1].id;
|
||||
assert.throws(()=>f.act(dev,'publish',publish),/缺陷/);
|
||||
f.act(dev,'defer-defect',{defectId:minor,notes:'下次优化,不影响验收',dueDate:'2026-09-21'});
|
||||
assert.throws(()=>f.act(dev,'publish',publish),/缺陷/);
|
||||
f.act(owner,'decide-deferral',{defectId:minor,approved:true,notes:'认可计划',confirm:true});assert.equal(unresolvedDefects(f.d).length,0);
|
||||
f.act(dev,'publish',publish);f.act(dev,'start-defect',{defectId:minor,notes:'开始处理遗留'});f.act(dev,'resolve-defect',{defectId:minor,notes:'修复文案',fixVersion:'fix-2'});f.act(owner,'verify-defect',{defectId:minor,approved:false,notes:'仍不完整',confirm:true});
|
||||
assert.equal(f.d.delivery!.defects![1].status,'修复中');assert.equal(f.d.delivery!.defects![1].events.length,5);
|
||||
});
|
||||
|
||||
test('data recovery requires exact business approval and rollback always invalidates the old acceptance',()=>{
|
||||
const f=fixture();f.release();const rollback={reason:'生产数据异常',runningVersion:'build-0',verification:'核心查询已恢复',dataRestored:true,confirm:true};
|
||||
assert.throws(()=>f.act(dev,'rollback',rollback),/业务方确认/);
|
||||
f.act(dev,'request-recovery',{targetVersion:'build-0',plan:'快照恢复并保留新增数据',dataImpact:'短暂只读,增量单独合并'});
|
||||
assert.throws(()=>f.act(dev,'decide-recovery',{approved:true,comment:'不能代批',confirm:true}),/对应责任人/);
|
||||
f.act(owner,'decide-recovery',{approved:true,comment:'确认数据影响与保留措施',confirm:true});
|
||||
assert.throws(()=>f.act(dev,'rollback',{...rollback,runningVersion:'wrong-version'}),/目标版本/);
|
||||
f.act(dev,'rollback',rollback);assert.equal(f.d.status,'开发中');assert.ok(f.d.acceptance!.withdrawnAt);assert.ok(latestRelease(f.d)!.rollback);
|
||||
assert.throws(()=>f.act(dev,'rollback',rollback),/已经回滚/);
|
||||
});
|
||||
|
||||
test('workflow tasks reflect plan and development responsibility without assigning work to read-only administrators',()=>{
|
||||
const f=fixture();f.d.access={business:false,developer:true};assert.equal(needsAction(f.d),true);
|
||||
f.act(dev,'propose-plan',plan);f.d.access={business:true,developer:false};assert.equal(needsAction(f.d),true);
|
||||
f.d.access={business:false,developer:false};assert.equal(needsAction(f.d),false);
|
||||
});
|
||||
|
||||
test('invalidated plans stop generating approval tasks and cannot authorize development',()=>{
|
||||
const f=fixture();f.act(dev,'propose-plan',plan);f.d.access={business:true,developer:false};
|
||||
assert.equal(workflowTask(f.d),'确认交付计划');
|
||||
f.d.review!.proposals[0].invalidated={time:now,reason:'责任人更换'};
|
||||
assert.equal(workflowTask(f.d),undefined);assert.equal(planConfirmed(f.d),false);
|
||||
assert.throws(()=>f.act(owner,'decide-plan',{planVersion:1,approved:true,comment:'旧计划',confirm:true}),/方案评审/);
|
||||
});
|
||||
|
||||
test('production recovery remains reachable while a change is being developed and preserves blockers',()=>{
|
||||
const f=fixture();f.release();f.act(dev,'reopen-incident',{impact:'生产异常',reason:'修复查询',confirm:true});
|
||||
f.act(owner,'set-blocker',{reason:'待业务核对数据',owner:'业务方',dueDate:'2026-09-20'});
|
||||
f.act(dev,'request-recovery',{targetVersion:'build-0',plan:'核对后恢复',dataImpact:'涉及当天数据'});
|
||||
f.act(dev,'rollback',{runningVersion:'build-0',reason:'先回滚代码',verification:'基本查询恢复',dataRestored:false,confirm:true});
|
||||
assert.equal(f.d.status,'开发中');assert.equal(f.d.blocked,'待业务核对数据');
|
||||
assert.equal(latestRelease(f.d)!.recoveryRequest!.decision!.approved,false);
|
||||
assert.throws(()=>f.act(owner,'decide-recovery',{approved:true,comment:'过期恢复',confirm:true}),/没有待确认/);
|
||||
});
|
||||
|
||||
|
||||
test('design tasks cover in-development resubmissions and invalidate confirmations after scope changes',()=>{
|
||||
const f=fixture(true);f.schedule();f.act(dev,'submit-design',{reference:'design-v1',notes:'初稿'});f.act(owner,'decide-design',{approved:true,comment:'同意',confirm:true});f.start();
|
||||
f.act(dev,'submit-design',{reference:'design-v2',notes:'开发中调整'});f.d.access={business:true,developer:false};
|
||||
assert.equal(workflowTask(f.d),'确认设计');assert.equal(needsAction(f.d),true);assert.throws(()=>f.act(dev,'submit-testing',testing),/设计/);
|
||||
f.act(owner,'decide-design',{approved:false,comment:'补充空态',confirm:true});f.d.access={business:false,developer:true};assert.equal(workflowTask(f.d),'提交设计');
|
||||
f.act(dev,'submit-design',{reference:'design-v3',notes:'补齐空态'});f.act(owner,'decide-design',{approved:true,comment:'同意',confirm:true});
|
||||
f.act(owner,'change',{content:'新增字段',reason:'业务调整'});f.act(dev,'assess-change',{...plan,designRequired:true,changeId:f.d.changes[0].id,scope:'F-02',outOfScope:'无',criteria:'新字段正确',version:'v2.0',impact:'调整页面'});f.act(owner,'decide-change',{changeId:f.d.changes[0].id,approved:true,comment:'同意',confirm:true});
|
||||
assert.equal(designConfirmed(f.d),false);assert.equal(workflowTask(f.d),'提交设计');assert.throws(()=>f.start(),/设计/);
|
||||
f.d.access={business:false,developer:false};assert.equal(needsAction(f.d),false);
|
||||
});
|
||||
|
||||
test('new checklist IDs avoid existing, removed-middle and manually edited identifiers',()=>{
|
||||
const items=[{id:'AC-01'},{id:'AC-03'},{id:' AC-02 '},{id:'custom'}];
|
||||
assert.equal(nextAcceptanceId(items),'AC-04');assert.equal(nextAcceptanceId([{id:'AC-01'},{id:'AC-03'}]),'AC-02');
|
||||
const full=Array.from({length:99},(_,i)=>({id:`AC-${String(i+1).padStart(2,'0')}`}));assert.equal(nextAcceptanceId(full),'AC-100');
|
||||
});
|
||||
|
||||
test('pending recovery blocks publication, can be withdrawn, and superseded requests remain closeable',()=>{
|
||||
const f=fixture();f.release();f.act(dev,'reopen-incident',{impact:'故障',reason:'修复',confirm:true});f.act(dev,'request-recovery',{targetVersion:'build-0',dataImpact:'核对增量',plan:'保留数据后恢复'});
|
||||
const oldId=latestRelease(f.d)!.id;f.act(dev,'submit-testing',{...testing,testVersion:'build-2'});f.accept();
|
||||
assert.throws(()=>f.act(dev,'publish',{...publish,version:'build-2'}),/数据恢复申请/);
|
||||
assert.throws(()=>f.act(owner,'withdraw-recovery',{releaseId:oldId,reason:'不能代撤回'}),/对应责任人/);
|
||||
f.act(dev,'withdraw-recovery',{releaseId:oldId,reason:'采用修复发布,不恢复数据'});assert.equal(pendingRecovery(f.d),undefined);
|
||||
assert.throws(()=>f.act(owner,'decide-recovery',{releaseId:oldId,approved:true,comment:'旧申请',confirm:true}),/没有待确认/);
|
||||
f.act(dev,'publish',{...publish,version:'build-2'});
|
||||
// A record created by an older version can still contain an orphaned pending request.
|
||||
delete f.d.delivery!.releases![0].recoveryRequest!.withdrawn;
|
||||
f.d.access={business:true,developer:false};assert.equal(workflowTask(f.d),'确认数据恢复方案');
|
||||
assert.throws(()=>f.act(owner,'decide-recovery',{releaseId:oldId,approved:true,comment:'过期恢复',confirm:true}),/替代/);
|
||||
f.act(owner,'decide-recovery',{releaseId:oldId,approved:false,comment:'旧发布已替代,关闭申请',confirm:true});assert.equal(pendingRecovery(f.d),undefined);
|
||||
});
|
||||
|
||||
const emergency={...publish,version:'hotfix-1',businessRulesUnchanged:true,scopeUnchanged:true,noIrreversibleData:true,emergencyReason:'核心查询故障,需及时恢复',fixSummary:'修复空指针,不改业务规则',selfTest:'关键流程通过',codeReview:'非提交人审查通过 CR-2',integration:'构建和关联回归通过',knownIssues:'无',followUpPlan:'同步主分支,下一工作日补充记录,业务核对查询',followUpDate:'2026-09-18'};
|
||||
const completion={summary:'观察正常',handover:'通知与交接完成',monitoring:'监控正常',confirm:true};
|
||||
function incident(f:ReturnType<typeof fixture>){f.act(dev,'reopen-incident',{impact:'核心查询不可用',reason:'既有范围内修复',confirm:true});}
|
||||
|
||||
test('emergency release requires a real incident, stable scope, technical proof and the assigned developer',()=>{
|
||||
const f=fixture();f.schedule();f.start();assert.throws(()=>f.act(dev,'publish-emergency',emergency),/已有线上版本/);
|
||||
const g=fixture();g.release();incident(g);
|
||||
for(const user of [owner,admin])assert.throws(()=>g.act(user,'publish-emergency',emergency),/对应责任人/);
|
||||
for(const key of ['businessRulesUnchanged','scopeUnchanged','noIrreversibleData'])assert.throws(()=>g.act(dev,'publish-emergency',{...emergency,[key]:false}),/常规验收/);
|
||||
for(const key of ['selfTest','codeReview','integration','followUpPlan'])assert.throws(()=>g.act(dev,'publish-emergency',{...emergency,[key]:''}),/请填写/);
|
||||
assert.throws(()=>g.act(dev,'publish-emergency',{...emergency,followUpDate:'2026-09-16'}),/早于今天/);
|
||||
assert.throws(()=>g.act(dev,'publish-emergency',{...emergency,testsPassed:false}),/逐项/);
|
||||
g.act(owner,'change',{content:'新业务规则',reason:'新口径'});assert.throws(()=>g.act(dev,'publish-emergency',emergency),/待处理需求变更/);
|
||||
g.act(dev,'assess-change',{...plan,changeId:g.d.changes[0].id,scope:'新规则',outOfScope:'无',criteria:'新口径准确',version:'v2.0',impact:'改变业务结果'});g.act(owner,'decide-change',{changeId:g.d.changes[0].id,approved:true,comment:'同意规则调整',confirm:true});g.start();
|
||||
assert.throws(()=>g.act(dev,'publish-emergency',emergency),/范围或方案已变化/);
|
||||
});
|
||||
|
||||
test('emergency publication preserves normal acceptance and requires business follow-up, production checks and observation',()=>{
|
||||
const f=fixture();f.release();incident(f);const count=f.d.acceptanceRecords!.length;
|
||||
f.act(dev,'publish-emergency',emergency);const release=latestRelease(f.d)!;
|
||||
assert.equal(f.d.status,'已上线');assert.equal(f.d.acceptanceRecords!.length,count);assert.ok(f.d.acceptance!.withdrawnAt);assert.equal(release.acceptanceRound,0);
|
||||
f.d.access={business:true,developer:false};assert.equal(workflowTask(f.d),'补充紧急发布业务验证');assert.equal(needsAction(f.d),true);
|
||||
assert.throws(()=>f.act(dev,'complete',completion),/业务验证/);
|
||||
assert.throws(()=>f.act(dev,'verify-emergency',{releaseId:release.id,approved:true,comment:'不能代验',confirm:true}),/对应责任人/);
|
||||
assert.throws(()=>f.act(owner,'verify-emergency',{releaseId:'stale',approved:true,comment:'旧版',confirm:true}),/待补充/);
|
||||
f.act(owner,'verify-emergency',{releaseId:release.id,approved:true,comment:'业务查询验证通过',confirm:true});
|
||||
assert.throws(()=>f.act(owner,'verify-emergency',{releaseId:release.id,approved:true,comment:'重复',confirm:true}),/待补充/);
|
||||
assert.throws(()=>f.act(dev,'complete',completion),/生产验证/);
|
||||
f.act(dev,'verify-production',{approved:true,results:'生产功能和监控通过',confirm:true});assert.throws(()=>f.act(dev,'complete',completion),/观察结束/);
|
||||
f.act(dev,'complete',completion,'2026-09-17T08:31:00.000Z');assert.equal(f.d.status,'已完成');assert.equal(pendingEmergencyVerification(f.d),undefined);
|
||||
});
|
||||
|
||||
test('emergency business rejection reopens current release, and later releases do not orphan prior verification',()=>{
|
||||
const f=fixture();f.release();incident(f);f.act(dev,'publish-emergency',emergency);const first=latestRelease(f.d)!.id;
|
||||
f.act(owner,'verify-emergency',{releaseId:first,approved:false,comment:'业务查询仍异常',confirm:true});assert.equal(f.d.status,'开发中');
|
||||
f.act(dev,'publish-emergency',{...emergency,version:'hotfix-2'});const second=latestRelease(f.d)!.id;
|
||||
incident(f);f.act(dev,'publish-emergency',{...emergency,version:'hotfix-3'});const third=latestRelease(f.d)!.id;
|
||||
assert.equal(pendingEmergencyVerification(f.d)!.id,second);
|
||||
f.act(owner,'verify-emergency',{releaseId:second,approved:false,comment:'历史版本问题已知',confirm:true});assert.equal(f.d.status,'已上线');assert.equal(pendingEmergencyVerification(f.d)!.id,third);
|
||||
f.act(owner,'verify-emergency',{releaseId:third,approved:true,comment:'最新版本正常',confirm:true});
|
||||
});
|
||||
|
||||
test('blocker tasks match either role for a dual-role administrator without leaking to observers', () => {
|
||||
for(const responsibility of ['业务方','开发责任人']){
|
||||
const f=fixture();f.act(owner,'set-blocker',{reason:'待处理',owner:responsibility,dueDate:'2026-10-01'});
|
||||
for(const access of [{business:true,developer:true},{business:true,developer:false},{business:false,developer:true},{business:false,developer:false}]){
|
||||
const d={...f.d,access};const expected=responsibility==='业务方'?access.business:access.developer;
|
||||
assert.equal(workflowTask(d),expected?'处理阻塞事项':undefined);
|
||||
assert.equal(needsAction(d),expected);
|
||||
}
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user