mirror of
https://git.zhongyuan.online/ytke/tap.git
synced 2026-11-24 22:15:18 -08:00
支持自部署需求管理、交付流程与飞书集成
This commit is contained in:
1 parent
4556a5b483
commit
e22b66d9dd
148 files changed
+8300
-6393
No files matched your search
@@ -0,0 +1,9 @@
|
||||
export const MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024;
|
||||
export const MAX_ATTACHMENTS = 10;
|
||||
export const STAGED_ATTACHMENT_TTL_MS = 24 * 60 * 60 * 1000;
|
||||
export type Attachment = { id: string; name: string; size: number; createdAt: string };
|
||||
export function formatFileSize(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
/** Only app-relative navigation is accepted, including after an OAuth round trip. */
|
||||
export function safeReturnTo(value: unknown): string {
|
||||
if (typeof value !== 'string' || value.length > 2048 || !value.startsWith('/') || value.startsWith('//') || /[\\\u0000-\u0020\u007f]/.test(value)) return '/';
|
||||
const url = new URL(value, 'https://local.invalid');
|
||||
if (url.origin !== 'https://local.invalid' || url.pathname.startsWith('//') || url.pathname.startsWith('/api/') || url.pathname === '/login') return '/';
|
||||
return url.pathname + url.search + url.hash;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
/** Build-time public prefix. Keep in sync with Next.js `basePath`. */
|
||||
export const basePath = process.env.NEXT_PUBLIC_BASE_PATH || '';
|
||||
|
||||
/** Prefix browser-native app URLs; Next.js Link/router/redirect already do this. */
|
||||
export function appPath(path: string): string {
|
||||
if (!basePath || !path.startsWith('/') || path.startsWith('//') || path.startsWith('/\\')) return path;
|
||||
if (path === basePath || path.startsWith(`${basePath}/`) || path.startsWith(`${basePath}?`) || path.startsWith(`${basePath}#`)) return path;
|
||||
return `${basePath}${path}`;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { Attachment } from './attachments.ts';
|
||||
import type { Demand, Fields } from './demand.ts';
|
||||
|
||||
export type ReviewPerson = { userId: string; username: string; displayName: string };
|
||||
export type ReviewProposal = {
|
||||
version: number;
|
||||
scope: string;
|
||||
outOfScope: string;
|
||||
developer: ReviewPerson;
|
||||
submittedAt: string;
|
||||
businessFields: Fields;
|
||||
businessAttachments?: Attachment[];
|
||||
invalidated?: { time: string; reason: string };
|
||||
decision?: { result: 'confirmed' | 'changes_requested'; actor: ReviewPerson; time: string; comment: string };
|
||||
};
|
||||
export type DemandReview = { developer: ReviewPerson; proposals: ReviewProposal[] };
|
||||
export type DemandAccess = { business: boolean; developer: boolean; canTakeOverDevelopment?: boolean };
|
||||
|
||||
export function currentProposal(d: Demand): ReviewProposal | undefined {
|
||||
return d.review?.proposals.at(-1);
|
||||
}
|
||||
|
||||
export function reviewStage(d: Demand): string {
|
||||
if (!d.reviewReady) return '资料待补充';
|
||||
if (!d.review) return '待开发提出方案';
|
||||
const proposal = currentProposal(d);
|
||||
if (!proposal || proposal.invalidated) return '待开发提出方案';
|
||||
if (proposal.decision?.result === 'confirmed') return '方案已确认';
|
||||
if (proposal.decision?.result === 'changes_requested') return '待开发修改方案';
|
||||
return '待业务确认方案';
|
||||
}
|
||||
|
||||
export function invalidateProposal(d: Demand, time: string, reason: string): void {
|
||||
const proposal = currentProposal(d);
|
||||
if (proposal && !proposal.invalidated) proposal.invalidated = { time, reason };
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { Demand } from './demand';
|
||||
|
||||
export type SavedDemandWrite = { version: number; demand: Demand };
|
||||
|
||||
/** Retain writes acknowledged after a GET began without dropping its other records. */
|
||||
export function mergeDemandSnapshot(
|
||||
snapshot: Demand[],
|
||||
writes: Iterable<SavedDemandWrite>,
|
||||
startedAtVersion: number,
|
||||
): Demand[] {
|
||||
const records = new Map(snapshot.map(demand => [demand.id, demand]));
|
||||
for (const { version, demand } of writes) {
|
||||
if (version <= startedAtVersion) continue;
|
||||
const serverRecord = records.get(demand.id);
|
||||
if (!serverRecord || serverRecord.revision <= demand.revision) records.set(demand.id, demand);
|
||||
}
|
||||
return [...records.values()].sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
|
||||
}
|
||||
+15
-3
@@ -1,4 +1,7 @@
|
||||
import { z } from 'zod';
|
||||
import type { Attachment } from './attachments.ts';
|
||||
import { workflowTask, pendingChange, type ChangeRecord, type Delivery, type DeliveryPlan, type TestingRound } from './workflow.ts';
|
||||
import { reviewStage, type DemandAccess, type DemandReview } from './demand-review.ts';
|
||||
export const statuses = ['待评审','已排期','开发中','待验收','待发布','已上线','已完成'] as const;
|
||||
export const fieldSchema = z.object({
|
||||
title:z.string().trim().max(100),project:z.string().trim().max(100),module:z.string().trim().max(100),type:z.enum(['新增功能','功能优化','缺陷修复','配置/数据变更']),proposer:z.string().trim().max(100),department:z.string().trim().max(100),source:z.string().trim().max(200),owner:z.string().trim().max(100),
|
||||
@@ -8,14 +11,23 @@ export const fieldSchema = z.object({
|
||||
export type Fields=z.infer<typeof fieldSchema>;
|
||||
export type History={time:string;actor:string;action:string;detail:string};
|
||||
export type AcceptanceItem={id:string;feature:string;scenario:string;expected:string};
|
||||
export type Demand={id:string;revision:number;fields:Fields;status:string;createdAt:string;updatedAt:string;reviewReady:boolean;blocked?:string;history:History[];changes:{time:string;content:string;reason:string;actor:string;status:string;originalVersion:string;originalFields?:Fields}[];acceptance?:{testVersion:string;environment:string;deadline:string;items:AcceptanceItem[];instructions:string};acceptanceRecords?:{time:string;actor:string;version:string;testVersion:string;results:string[];notes:string;passed:boolean;items?: (AcceptanceItem & {result:string})[];environment?:string}[];plan?:{developer:string;testDate:string;releaseDate:string};demo?:boolean};
|
||||
export type Demand={attachments?:Attachment[];review?:DemandReview;access?:DemandAccess;id:string;revision:number;fields:Fields;status:string;createdAt:string;updatedAt:string;reviewReady:boolean;blocked?:string;history:History[];changes:ChangeRecord[];acceptance?:TestingRound;acceptanceRecords?:{time:string;actor:string;version:string;testVersion:string;round?:number;results:string[];notes:string;passed:boolean;items?: (AcceptanceItem & {result:string})[];environment?:string}[];plan?:DeliveryPlan;delivery?:Delivery};
|
||||
export const emptyFields:Fields={title:'',project:'',module:'',type:'新增功能',proposer:'',department:'',source:'',owner:'',background:'',impact:'',goal:'',expectedDate:'',noFixedDate:false,dateReason:'',scope:'',outOfScope:'',criteria:'',priority:'P2',priorityReason:'',dataSource:'',dataContact:'',noData:false,risk:'',pending:'',references:'',version:'v1.0'};
|
||||
export function missingFields(f:Fields,review=false):string[]{
|
||||
const required: [keyof Fields,string][]=[['title','需求标题'],['project','所属项目'],['module','业务模块'],['proposer','提出人'],['department','所属部门'],['source','需求来源'],['owner','需求负责人'],['background','业务背景'],['impact','影响对象与依据'],['goal','预期目标']];
|
||||
const missing=required.filter(([k])=>!f[k]).map(([,label])=>label);
|
||||
if(!f.noFixedDate){if(!/^\d{4}-\d{2}-\d{2}$/.test(f.expectedDate)||Number.isNaN(Date.parse(f.expectedDate))||new Date(f.expectedDate).toISOString().slice(0,10)!==f.expectedDate)missing.push('有效的期望上线日期');if(!f.dateReason)missing.push('期望日期依据');}
|
||||
if(review){const rs:[keyof Fields,string][]=[['scope','实施范围与功能说明'],['outOfScope','范围外事项'],['criteria','验收标准'],['priorityReason','优先级依据'],['risk','依赖与风险'],['pending','待确认事项'],['version','文档版本']];missing.push(...rs.filter(([k])=>!f[k]).map(([,l])=>l));if(!f.noData){if(!f.dataSource)missing.push('数据来源');if(!f.dataContact)missing.push('数据提供人');}}
|
||||
if(review){const rs:[keyof Fields,string][]=[['criteria','验收标准'],['priorityReason','优先级依据'],['risk','依赖与风险'],['pending','待确认事项'],['version','文档版本']];missing.push(...rs.filter(([k])=>!f[k]).map(([,l])=>l));if(!f.noData){if(!f.dataSource)missing.push('数据来源');if(!f.dataContact)missing.push('数据提供人');}}
|
||||
return missing;
|
||||
}
|
||||
export function needsAction(d:Demand){return d.status==='待验收'||(d.status==='待评审'&&!d.reviewReady);}
|
||||
export function needsAction(d:Demand){
|
||||
if(pendingChange(d)||d.blocked)return Boolean(workflowTask(d));
|
||||
if(workflowTask(d))return true;
|
||||
const business=d.access?.business??true;
|
||||
if(d.status==='待验收')return business;
|
||||
if(d.status!=='待评审')return false;
|
||||
const stage=reviewStage(d);
|
||||
return Boolean(business&&['资料待补充','待业务确认方案'].includes(stage)||d.access?.developer&&['待开发提出方案','待开发修改方案'].includes(stage));
|
||||
}
|
||||
export function isActive(d:Demand){return !['草稿','已完成','已取消'].includes(d.status);}
|
||||
export function isMyDemand(d:Demand){return d.access===undefined||d.access.business||d.access.developer;}
|
||||
-11
@@ -1,11 +0,0 @@
|
||||
import { emptyFields, type Demand } from './demand';
|
||||
const entries=[
|
||||
['销售订单批量导出','待验收','P1','2026-09-20','销售部'],['客户信息统一管理','开发中','P1','2026-09-25','客户服务部'],['经营数据看板','待评审','P2','2026-09-30','运营部'],['采购审批流程优化','待评审','P2','2026-10-08','采购部'],['库存预警自动通知','已完成','P2','2026-09-12','仓储部'],['合同到期自动提醒','已排期','P2','2026-10-12','销售部'],['门店经营周报','开发中','P1','2026-09-28','运营部'],['供应商资料归档','已排期','P2','2026-10-15','采购部'],['员工报销查询','草稿','P2','','财务部'],['客户回访记录','草稿','P2','','客户服务部'],
|
||||
];
|
||||
export const demoDemands:Demand[]=entries.map(([title,status,priority,date,department],i)=>({
|
||||
id:`REQ-202609${String(14-i).padStart(2,'0')}-${String(8-i>0?8-i:12-i).padStart(3,'0')}`,revision:1,demo:true,status,reviewReady:status!=='待评审',createdAt:`2026-09-${String(14-i).padStart(2,'0')}T02:00:00.000Z`,updatedAt:'2026-09-16T02:00:00.000Z',
|
||||
fields:{...emptyFields,title,project:'企业业务平台',module:title.slice(0,4),type:'功能优化',proposer:'业务用户',department,source:'业务日常反馈',owner:'业务用户',background:i===0?'销售同事每周手动整理订单数据,需要逐页复制订单信息,耗时较长且容易遗漏。':'当前相关业务信息分散,需要多次查询和人工处理,影响日常工作效率。',impact:department+'业务同事;以日常操作记录和部门反馈为依据。',goal:i===0?'支持一次导出筛选后的订单,确保导出内容与列表结果一致,减少重复整理。':'统一业务信息和操作入口,减少重复工作,保证关键业务结果准确。',expectedDate:date,noFixedDate:!date,dateReason:'配合部门月度业务计划',scope:'F-01:支持按业务条件筛选记录。\nF-02:支持导出当前筛选结果。',outOfScope:'本次不包含历史数据清洗。',criteria:'AC-01:使用有效条件筛选时,仅展示符合条件的记录。\nAC-02:导出文件应包含筛选结果,字段与列表一致。\nAC-03:无记录时提示暂无数据,不生成空文件。',priority:priority as 'P1'|'P2',priorityReason:'支持近期业务目标,按部门计划推进。',dataSource:i===2?'':'企业业务平台中的业务管理列表',dataContact:i===2?'':'各部门业务负责人',risk:'无',pending:i===2?'待确认:指标数据来源;责任人:业务用户;计划确认时间:2026-09-18。':'无'},
|
||||
history:[{time:'2026-09-10T02:00:00Z',actor:'业务用户',action:'登记需求',detail:'已登记业务背景、目标与影响范围。'},...(status==='待验收'?[{time:'2026-09-15T08:30:00Z',actor:'开发负责人(示例)',action:'提交业务验收',detail:'审查、自测及集成验证通过;已提供测试版本与验收清单。'}]:[])],changes:[],
|
||||
...(['已排期','开发中','待验收'].includes(status)?{plan:{developer:'开发负责人(示例)',testDate:'2026-09-18',releaseDate:date}}:{}),
|
||||
...(status==='待验收'?{acceptance:{testVersion:'v1.2.0-rc.1(示例)',environment:'示例环境,仅用于体验验收流程',deadline:'2026-09-19',instructions:'使用测试账号筛选订单后导出,核对导出内容与筛选结果。账号及数据通过约定受限渠道获取。',items:[{id:'AC-01',feature:'F-01 条件筛选',scenario:'选择订单状态为已完成',expected:'仅展示已完成的订单。'},{id:'AC-02',feature:'F-02 批量导出',scenario:'导出当前筛选结果',expected:'文件中的订单、金额和数量与列表一致。'},{id:'AC-03',feature:'F-02 空数据处理',scenario:'筛选没有匹配记录的条件并导出',expected:'提示暂无数据,不生成空文件。'}]}}:{}),
|
||||
}));
|
||||
@@ -0,0 +1,20 @@
|
||||
import { appPath } from './base-path.ts';
|
||||
|
||||
export const FEISHU_TEMPLATE_DIRECTORY = 'https://ecnldnvsv8es.feishu.cn/wiki/Bvnbw852biK7qRkhwJkcOIvun4f?from=from_copylink';
|
||||
export const documents = [
|
||||
{ id: 'sop', title: '软件开发流程管理规范', filename: '开发SOP_公示版.md', description: '职责、需求评审、验收与发布的完整约定。' },
|
||||
{ id: 'registration', title: '需求登记模板', filename: '附件01_需求登记模板.md', description: '用于登记业务问题、目标、负责人及期望时间。' },
|
||||
{ id: 'requirement', title: '需求说明模板', filename: '附件02_需求文档模板.md', description: '用于补充业务背景、目标、场景及验收标准;方案部分由开发责任人在评审时填写。' },
|
||||
{ id: 'data-source', title: '数据来源模板', filename: '附件03_数据来源填写模板.md', description: '用于说明数据从哪里来、由谁提供、更新频率及参考样例。' },
|
||||
{ id: 'acceptance', title: '验收记录模板', filename: '附件04_验收记录模板.md', description: '业务验收时记录逐项结果、证据及确认结论。' },
|
||||
{ id: 'change', title: '需求变更记录模板', filename: '附件05_需求变更记录模板.md', description: '记录变更原因、影响、调整后的计划和确认人。' },
|
||||
{ id: 'defect', title: '缺陷记录模板', filename: '附件06_缺陷记录模板.md', description: '记录复现步骤、预期与实际结果、修复和复验情况。' },
|
||||
{ id: 'release', title: '发布记录模板', filename: '附件07_发布记录模板.md', description: '记录上线版本、检查结果、恢复方式和生产验证。' },
|
||||
] as const;
|
||||
export type DocumentId = typeof documents[number]['id'];
|
||||
export type DocumentInfo = typeof documents[number];
|
||||
export function findDocument(value: string): DocumentInfo | undefined { return documents.find(item => item.id === value || item.filename === value); }
|
||||
export function templateDownloadUrl(id: DocumentId): string { return appPath('/api/documents/' + encodeURIComponent(findDocument(id)!.filename) + '?format=docx'); }
|
||||
export function linkedDocument(href: string): DocumentInfo | undefined {
|
||||
try { return findDocument(decodeURIComponent(href.split('#')[0].split('?')[0].split('/').at(-1) || '')); } catch { return undefined; }
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
export const feishuErrors: Record<string, string> = {
|
||||
unavailable: '飞书登录暂未配置完成,请使用账号密码登录或联系管理员。',
|
||||
expired: '飞书授权已过期或浏览器状态不匹配,请重新发起授权。',
|
||||
denied: '已取消飞书授权,你可以重试或使用账号密码登录。',
|
||||
unbound: '此飞书身份尚未关联账号,请重新使用飞书登录,系统会自动注册普通成员账号。',
|
||||
conflict: '此飞书身份或系统账号已有绑定,请先解除原有绑定。',
|
||||
tenant: '此飞书账号不属于允许登录的企业,请联系管理员。',
|
||||
session: '系统登录状态已变化,请重新登录后绑定飞书。',
|
||||
rate_limited: '登录尝试过于频繁,请稍后再试。',
|
||||
source: '登录请求来源无效,请从系统访问地址重新打开;如持续出现,请联系管理员检查代理配置。',
|
||||
failed: '飞书授权暂未完成,请重试;如持续失败,请联系管理员检查应用配置。',
|
||||
};
|
||||
export function feishuErrorMessage(code: unknown): string {
|
||||
return typeof code === 'string' && Object.hasOwn(feishuErrors, code) ? feishuErrors[code] : '';
|
||||
}
|
||||
export type FeishuBinding = { name: string; boundAt: string } | null;
|
||||
export type FeishuDelivery = {
|
||||
id: string; demandId: string; revision: number; status: 'pending' | 'sending' | 'sent' | 'failed';
|
||||
attempts: number; lastError: string | null; createdAt: string; sentAt: string | null;
|
||||
};
|
||||
export type FeishuDeliveryFilter = 'all' | 'failed';
|
||||
export type FeishuStatus = {
|
||||
loginConfigured: boolean; callbackUrl: string; tenantRestricted: boolean;
|
||||
botConfigured: boolean; botSigned: boolean; configurationError: string | null;
|
||||
deliveries: FeishuDelivery[];
|
||||
deliveryFilter: FeishuDeliveryFilter; nextCursor: string | null; failedCount: number;
|
||||
};
|
||||
@@ -0,0 +1,99 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { z } from 'zod';
|
||||
import { MAX_ATTACHMENT_BYTES, MAX_ATTACHMENTS, STAGED_ATTACHMENT_TTL_MS, type Attachment } from '../attachments.ts';
|
||||
import type { Demand } from '../demand.ts';
|
||||
import { invalidateProposal } from '../demand-review.ts';
|
||||
import { AuthError, jsonResponse } from './auth.ts';
|
||||
import { getDatabase } from './database.ts';
|
||||
import { readableDemandWhere, readableDemandBindings, type DemandViewer } from './demand-access.ts';
|
||||
|
||||
type AttachmentRow = { id: string; owner_id: string; demand_id: string | null; name: string; size: number; created_at: string };
|
||||
const metadata = (row: AttachmentRow): Attachment => ({ id: row.id, name: row.name, size: row.size, createdAt: row.created_at });
|
||||
const idSchema = z.string().uuid();
|
||||
|
||||
export function attachmentIds(value: unknown): string[] | undefined {
|
||||
if (value === undefined) return undefined;
|
||||
const parsed = z.array(idSchema).max(MAX_ATTACHMENTS).safeParse(value);
|
||||
if (!parsed.success || new Set(parsed.data).size !== parsed.data.length) throw new AuthError(`附件列表无效,每条需求最多 ${MAX_ATTACHMENTS} 个附件。`);
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
export function storeUpload(userId: string, inputName: string, bytes: Uint8Array): Attachment {
|
||||
const name = inputName.replace(/[\\/\u0000-\u001f\u007f]/g, '_').trim();
|
||||
if (!name || name.length > 200) throw new AuthError('文件名须为 1–200 个字符。');
|
||||
if (!bytes.byteLength) throw new AuthError('不能上传空文件。');
|
||||
if (bytes.byteLength > MAX_ATTACHMENT_BYTES) throw new AuthError('单个文件不能超过 20 MB。', 413);
|
||||
const database = getDatabase();
|
||||
return database.transaction(() => {
|
||||
const now = new Date().toISOString();
|
||||
database.prepare('DELETE FROM attachments WHERE demand_id IS NULL AND created_at < ?').bind(new Date(Date.now() - STAGED_ATTACHMENT_TTL_MS).toISOString()).run();
|
||||
const pending = database.prepare('SELECT COUNT(*) AS count FROM attachments WHERE owner_id = ? AND demand_id IS NULL').bind(userId).first<{ count: number }>()!;
|
||||
if (pending.count >= MAX_ATTACHMENTS) throw new AuthError('未保存附件已达 10 个,请先保存需求或移除未使用的附件。', 409);
|
||||
const id = randomUUID();
|
||||
database.prepare('INSERT INTO attachments (id, owner_id, name, size, content, created_at) VALUES (?, ?, ?, ?, ?, ?)').bind(id, userId, name, bytes.byteLength, bytes, now).run();
|
||||
return { id, name, size: bytes.byteLength, createdAt: now };
|
||||
});
|
||||
}
|
||||
|
||||
/** Called inside the same transaction that writes the demand. No claims or removals escape a failed save. */
|
||||
export function syncDemandAttachments(record: Demand, ownerId: string, ids: string[] | undefined, now: string): boolean {
|
||||
if (ids === undefined) return false;
|
||||
const database = getDatabase();
|
||||
const cutoff = new Date(Date.now() - STAGED_ATTACHMENT_TTL_MS).toISOString();
|
||||
const selected = ids.map(id => {
|
||||
const row = database.prepare('SELECT id, owner_id, demand_id, name, size, created_at FROM attachments WHERE id = ?').bind(id).first<AttachmentRow>();
|
||||
if (!row || row.owner_id !== ownerId || (row.demand_id !== null && row.demand_id !== record.id) || (!row.demand_id && row.created_at < cutoff)) throw new AuthError('附件已失效或无法访问,请移除后重新上传。');
|
||||
return metadata(row);
|
||||
});
|
||||
const before = (record.attachments ?? []).map(file => file.id).sort().join(',');
|
||||
const changed = before !== [...ids].sort().join(',');
|
||||
if (changed) invalidateProposal(record, now, '参考附件已修改,需开发责任人重新提交方案并由业务方确认。');
|
||||
record.attachments = selected;
|
||||
return changed;
|
||||
}
|
||||
|
||||
/** The demand row must exist first so foreign keys remain valid. Historical review files are retained. */
|
||||
export function commitDemandAttachments(record: Demand, ownerId: string): void {
|
||||
const database = getDatabase();
|
||||
for (const file of record.attachments ?? []) database.prepare('UPDATE attachments SET demand_id = ? WHERE id = ? AND owner_id = ? AND demand_id IS NULL').bind(record.id, file.id, ownerId).run();
|
||||
const retained = new Set([
|
||||
...(record.attachments ?? []).map(file => file.id),
|
||||
...(record.review?.proposals ?? []).flatMap(proposal => (proposal.businessAttachments ?? []).map(file => file.id)),
|
||||
]);
|
||||
for (const row of database.prepare('SELECT id FROM attachments WHERE demand_id = ?').bind(record.id).all<{ id: string }>().results) {
|
||||
if (!retained.has(row.id)) database.prepare('DELETE FROM attachments WHERE id = ? AND demand_id = ?').bind(row.id, record.id).run();
|
||||
}
|
||||
}
|
||||
|
||||
export function downloadAttachment(id: string, user: DemandViewer): { file: Attachment; bytes: Uint8Array } {
|
||||
if (!idSchema.safeParse(id).success) throw new AuthError('找不到该附件或你没有访问权限。', 404);
|
||||
const database = getDatabase();
|
||||
const row = database.prepare('SELECT id, owner_id, demand_id, name, size, created_at FROM attachments WHERE id = ?').bind(id).first<AttachmentRow>();
|
||||
if (!row) throw new AuthError('找不到该附件或你没有访问权限。', 404);
|
||||
if (row.demand_id) {
|
||||
const demand = database.prepare(`SELECT id FROM demands WHERE id = ? AND ${readableDemandWhere}`)
|
||||
.bind(row.demand_id, ...readableDemandBindings(user)).first();
|
||||
if (!demand) throw new AuthError('找不到该附件或你没有访问权限。', 404);
|
||||
} else if (row.owner_id !== user.userId || row.created_at < new Date(Date.now() - STAGED_ATTACHMENT_TTL_MS).toISOString()) {
|
||||
throw new AuthError('找不到该附件或你没有访问权限。', 404);
|
||||
}
|
||||
const content = database.prepare('SELECT content FROM attachments WHERE id = ?').bind(id).first<{ content: Uint8Array }>()!;
|
||||
return { file: metadata(row), bytes: content.content };
|
||||
}
|
||||
|
||||
export function deleteStagedAttachment(id: string, userId: string): void {
|
||||
const database = getDatabase();
|
||||
const result = database.prepare('DELETE FROM attachments WHERE id = ? AND owner_id = ? AND demand_id IS NULL').bind(id, userId).run();
|
||||
if (!result.meta.changes) throw new AuthError('该附件已保存或无法访问,请在需求表单中移除并保存。', 409);
|
||||
}
|
||||
|
||||
export function listStagedAttachments(userId: string): Attachment[] {
|
||||
return getDatabase().prepare('SELECT id, owner_id, demand_id, name, size, created_at FROM attachments WHERE owner_id = ? AND demand_id IS NULL AND created_at >= ? ORDER BY created_at')
|
||||
.bind(userId, new Date(Date.now() - STAGED_ATTACHMENT_TTL_MS).toISOString()).all<AttachmentRow>().results.map(metadata);
|
||||
}
|
||||
|
||||
export function attachmentFailure(error: unknown): Response {
|
||||
if (error instanceof AuthError) return jsonResponse({ error: error.message }, error.status);
|
||||
console.error('Attachment operation failed', error);
|
||||
return jsonResponse({ error: '附件服务暂时不可用,请稍后重试。' }, 503);
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
import { createHash, randomBytes } from 'node:crypto';
|
||||
import { isIP } from 'node:net';
|
||||
import { basePath } from '../base-path.ts';
|
||||
import { applicationOrigin, getDatabase, normalizeDisplayName, normalizeUsername, type AccountRow } from './database.ts';
|
||||
import { hashPassword, hashPasswordSync, hasStoredPassword, validatePassword, verifyPassword } from './password.ts';
|
||||
|
||||
export type AuthUser = {
|
||||
userId: string; username: string; displayName: string;
|
||||
role: 'admin' | 'user'; mustChangePassword: boolean;
|
||||
};
|
||||
export type AdminUser = AuthUser & { disabled: boolean; createdAt: string; lastLoginAt: string | null };
|
||||
export class AuthError extends Error {
|
||||
status: number;
|
||||
constructor(message: string, status = 400) { super(message); this.name = 'AuthError'; this.status = status; }
|
||||
}
|
||||
|
||||
const SESSION_SECONDS = 7 * 24 * 60 * 60;
|
||||
const COOKIE_NAME = 'demand_session';
|
||||
let dummyPasswordHash: string | undefined;
|
||||
|
||||
function publicUser(account: AccountRow): AuthUser {
|
||||
return { userId: account.id, username: account.username, displayName: account.display_name, role: account.role, mustChangePassword: Boolean(account.must_change_password) };
|
||||
}
|
||||
function accountById(id: string): AccountRow | null {
|
||||
return getDatabase().prepare('SELECT * FROM accounts WHERE id = ?').bind(id).first<AccountRow>();
|
||||
}
|
||||
export function hasAccountPassword(userId: string): boolean {
|
||||
return hasStoredPassword(accountById(userId)?.password_hash);
|
||||
}
|
||||
function tokenHash(token: string): string { return createHash('sha256').update(token).digest('hex'); }
|
||||
|
||||
export function isSameOrigin(request: Request): boolean {
|
||||
const origin = request.headers.get('origin');
|
||||
if (!origin || origin === 'null') return false;
|
||||
const fetchSite = request.headers.get('sec-fetch-site');
|
||||
if (fetchSite && !['same-origin', 'none'].includes(fetchSite)) return false;
|
||||
return origin === applicationOrigin(request);
|
||||
}
|
||||
export function assertSameOrigin(request: Request): void {
|
||||
if (!isSameOrigin(request)) throw new AuthError('请求来源无效,请从系统访问地址重新打开页面。', 403);
|
||||
}
|
||||
|
||||
export function sessionCookie(token: string, request?: Request): string {
|
||||
const secure = applicationOrigin(request).startsWith('https://') ? '; Secure' : '';
|
||||
return `${COOKIE_NAME}=${token}; Path=${basePath || '/'}; HttpOnly; SameSite=Lax; Max-Age=${token ? SESSION_SECONDS : 0}${secure}`;
|
||||
}
|
||||
|
||||
function issueSession(account: AccountRow): { user: AuthUser; token: string } {
|
||||
const database = getDatabase();
|
||||
const token = randomBytes(32).toString('base64url');
|
||||
const now = Date.now();
|
||||
database.prepare('DELETE FROM sessions WHERE expires_at <= ?').bind(now).run();
|
||||
database.prepare('INSERT INTO sessions (token_hash, account_id, expires_at, created_at) VALUES (?, ?, ?, ?)')
|
||||
.bind(tokenHash(token), account.id, now + SESSION_SECONDS * 1000, now).run();
|
||||
return { user: publicUser(account), token };
|
||||
}
|
||||
|
||||
/** Called only after a server-side identity provider has authenticated a bound account. */
|
||||
export function issueIdentitySession(accountId: string): { user: AuthUser; token: string } {
|
||||
const account = accountById(accountId);
|
||||
if (!account || account.disabled) throw new AuthError('账号已停用,请联系管理员。', 403);
|
||||
getDatabase().prepare('UPDATE accounts SET last_login_at = ? WHERE id = ?')
|
||||
.bind(new Date().toISOString(), account.id).run();
|
||||
return issueSession(account);
|
||||
}
|
||||
|
||||
export function authenticateSession(token: string | undefined): AuthUser | null {
|
||||
if (!token || !/^[A-Za-z0-9_-]{43}$/.test(token)) return null;
|
||||
const account = getDatabase().prepare(`SELECT accounts.* FROM sessions JOIN accounts ON accounts.id = sessions.account_id
|
||||
WHERE sessions.token_hash = ? AND sessions.expires_at > ? AND accounts.disabled = 0`)
|
||||
.bind(tokenHash(token), Date.now()).first<AccountRow>();
|
||||
return account ? publicUser(account) : null;
|
||||
}
|
||||
|
||||
export async function getCurrentUser(): Promise<AuthUser | null> {
|
||||
const { cookies } = await import('next/headers');
|
||||
return authenticateSession((await cookies()).get(COOKIE_NAME)?.value);
|
||||
}
|
||||
|
||||
export async function requireUser(returnTo = '/'): Promise<AuthUser> {
|
||||
const { redirect } = await import('next/navigation');
|
||||
const user = await getCurrentUser();
|
||||
const safeReturn = returnTo.startsWith('/') && !returnTo.startsWith('//') ? returnTo : '/';
|
||||
if (!user) return redirect(`/login?next=${encodeURIComponent(safeReturn)}`);
|
||||
if (user.mustChangePassword && safeReturn.split('?')[0] !== '/account/password') redirect('/account/password');
|
||||
return user;
|
||||
}
|
||||
|
||||
export async function requireApiUser(options: { admin?: boolean; allowPasswordChange?: boolean } = {}): Promise<AuthUser> {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) throw new AuthError('请先登录。', 401);
|
||||
if (!options.allowPasswordChange && user.mustChangePassword) throw new AuthError('请先修改初始密码后继续。', 403);
|
||||
if (options.admin && user.role !== 'admin') throw new AuthError('仅管理员可以管理账号。', 403);
|
||||
return user;
|
||||
}
|
||||
|
||||
function loginSourceKey(request?: Request): string | undefined {
|
||||
const configuredHeader = process.env.LOGIN_CLIENT_IP_HEADER?.trim().toLowerCase();
|
||||
if (!configuredHeader) return undefined;
|
||||
if (!/^[a-z][a-z0-9-]{0,63}$/.test(configuredHeader)) throw new AuthError('登录来源配置无效,请联系管理员。', 503);
|
||||
|
||||
// Opt-in trust boundary: the reverse proxy must overwrite this single-IP header,
|
||||
// and the application port must not be directly reachable by untrusted clients.
|
||||
// Other forwarded headers are ignored; missing or invalid configured values fail closed.
|
||||
const address = request?.headers.get(configuredHeader)?.trim();
|
||||
const family = address && !address.includes('%') ? isIP(address) : 0;
|
||||
if (!address || !family) throw new AuthError('登录来源信息无效,请联系管理员。', 403);
|
||||
|
||||
let normalized = address;
|
||||
if (family === 6) {
|
||||
normalized = new URL(`http://[${address}]/`).hostname.slice(1, -1);
|
||||
// Equivalent IPv6 spellings and IPv4-mapped addresses share the same bucket.
|
||||
const mapped = /^::ffff:([a-f0-9]{1,4}):([a-f0-9]{1,4})$/.exec(normalized);
|
||||
if (mapped) {
|
||||
const high = Number.parseInt(mapped[1], 16); const low = Number.parseInt(mapped[2], 16);
|
||||
normalized = `${high >>> 8}.${high & 255}.${low >>> 8}.${low & 255}`;
|
||||
}
|
||||
}
|
||||
return `source:${tokenHash(normalized)}`;
|
||||
}
|
||||
|
||||
function consumeLoginAttempt(username: string | undefined, sourceKey?: string): void {
|
||||
const database = getDatabase();
|
||||
const now = Date.now();
|
||||
// Database-backed limits survive restarts and work across local application processes.
|
||||
// There is no shared global bucket: one source cannot spend another source's quota.
|
||||
const buckets = [
|
||||
...(sourceKey ? [{ key: sourceKey, span: 60_000, limit: 60 }] : []),
|
||||
...(username !== undefined ? [{ key: `username:${tokenHash(username)}`, span: 15 * 60_000, limit: 5 }] : []),
|
||||
];
|
||||
if (!buckets.length) return;
|
||||
database.transaction(() => {
|
||||
database.prepare('DELETE FROM login_limits WHERE window_start < ?').bind(now - 15 * 60_000).run();
|
||||
for (const bucket of buckets) {
|
||||
const row = database.prepare('SELECT window_start, attempts FROM login_limits WHERE key = ?').bind(bucket.key).first<{ window_start: number; attempts: number }>();
|
||||
if (row && now - row.window_start < bucket.span && row.attempts >= bucket.limit) {
|
||||
throw new AuthError('登录尝试过于频繁,请稍后再试。', 429);
|
||||
}
|
||||
}
|
||||
for (const bucket of buckets) {
|
||||
database.prepare(`INSERT INTO login_limits (key, window_start, attempts) VALUES (?, ?, 1)
|
||||
ON CONFLICT(key) DO UPDATE SET
|
||||
attempts = CASE WHEN login_limits.window_start <= ? THEN 1 ELSE login_limits.attempts + 1 END,
|
||||
window_start = CASE WHEN login_limits.window_start <= ? THEN excluded.window_start ELSE login_limits.window_start END`)
|
||||
.bind(bucket.key, now, now - bucket.span, now - bucket.span).run();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** OAuth and password login share the same trusted-source quota (when configured). */
|
||||
export function consumeLoginSourceAttempt(request: Request): void {
|
||||
consumeLoginAttempt(undefined, loginSourceKey(request));
|
||||
}
|
||||
|
||||
export async function loginWithPassword(usernameInput: unknown, passwordInput: unknown, request?: Request): Promise<{ user: AuthUser; token: string }> {
|
||||
if (typeof usernameInput !== 'string' || typeof passwordInput !== 'string' || !usernameInput.trim() || usernameInput.length > 128 || !passwordInput || passwordInput.length > 128) {
|
||||
throw new AuthError('账号或密码错误。', 401);
|
||||
}
|
||||
const username = usernameInput.trim().toLowerCase();
|
||||
consumeLoginAttempt(username, loginSourceKey(request));
|
||||
const database = getDatabase();
|
||||
const account = database.prepare('SELECT * FROM accounts WHERE username = ?').bind(username).first<AccountRow>();
|
||||
dummyPasswordHash ??= hashPasswordSync('dummy timing password that never authenticates');
|
||||
const valid = await verifyPassword(passwordInput, hasStoredPassword(account?.password_hash) ? account!.password_hash : dummyPasswordHash);
|
||||
// Feishu-only accounts cannot authenticate using the timing dummy password.
|
||||
if (!account || !hasStoredPassword(account.password_hash) || !valid || account.disabled) throw new AuthError('账号或密码错误。', 401);
|
||||
return database.transaction(() => {
|
||||
const current = accountById(account.id);
|
||||
if (!current || current.disabled || current.password_hash !== account.password_hash) throw new AuthError('账号或密码错误。', 401);
|
||||
database.prepare('DELETE FROM login_limits WHERE key = ?').bind(`username:${tokenHash(username)}`).run();
|
||||
database.prepare('UPDATE accounts SET last_login_at = ? WHERE id = ?').bind(new Date().toISOString(), account.id).run();
|
||||
return issueSession(current);
|
||||
});
|
||||
}
|
||||
|
||||
export function revokeSession(token: string | undefined): void {
|
||||
if (token && /^[A-Za-z0-9_-]{43}$/.test(token)) getDatabase().prepare('DELETE FROM sessions WHERE token_hash = ?').bind(tokenHash(token)).run();
|
||||
}
|
||||
|
||||
export async function logoutCurrentSession(): Promise<void> {
|
||||
const { cookies } = await import('next/headers');
|
||||
revokeSession((await cookies()).get(COOKIE_NAME)?.value);
|
||||
}
|
||||
|
||||
export async function changeAccountPassword(userId: string, currentPassword: unknown, newPassword: unknown): Promise<{ user: AuthUser; token: string }> {
|
||||
try { validatePassword(newPassword); } catch (error) { throw new AuthError((error as Error).message); }
|
||||
const current = accountById(userId);
|
||||
if (!current || current.disabled) throw new AuthError('账号已停用,请联系管理员。', 401);
|
||||
if (hasStoredPassword(current.password_hash)) {
|
||||
if (typeof currentPassword !== 'string' || currentPassword.length > 128 || !await verifyPassword(currentPassword, current.password_hash)) throw new AuthError('当前密码不正确。');
|
||||
if (currentPassword === newPassword) throw new AuthError('新密码不能与当前密码相同。');
|
||||
} else if (!getDatabase().prepare('SELECT account_id FROM feishu_identities WHERE account_id = ?').bind(userId).first()) {
|
||||
throw new AuthError('账号缺少可用的登录方式,请联系管理员。', 403);
|
||||
}
|
||||
const passwordHash = await hashPassword(newPassword);
|
||||
return getDatabase().transaction(() => {
|
||||
const fresh = accountById(userId);
|
||||
if (!fresh || fresh.disabled || fresh.password_hash !== current.password_hash) throw new AuthError('账号状态已变化,请重新登录。', 409);
|
||||
getDatabase().prepare('UPDATE accounts SET password_hash = ?, must_change_password = 0, updated_at = ? WHERE id = ?')
|
||||
.bind(passwordHash, new Date().toISOString(), userId).run();
|
||||
getDatabase().prepare('DELETE FROM sessions WHERE account_id = ?').bind(userId).run();
|
||||
return issueSession({ ...fresh, password_hash: passwordHash, must_change_password: 0 });
|
||||
});
|
||||
}
|
||||
|
||||
function activeAdmin(actorId: string): AccountRow {
|
||||
const actor = accountById(actorId);
|
||||
if (!actor || actor.disabled || actor.role !== 'admin' || actor.must_change_password) throw new AuthError('当前账号无权管理用户,请重新登录。', 403);
|
||||
return actor;
|
||||
}
|
||||
|
||||
export function listAccounts(actorId: string): AdminUser[] {
|
||||
activeAdmin(actorId);
|
||||
return getDatabase().prepare('SELECT * FROM accounts ORDER BY created_at ASC, username ASC').all<AccountRow>().results.map(account => ({
|
||||
...publicUser(account), disabled: Boolean(account.disabled), createdAt: account.created_at, lastLoginAt: account.last_login_at,
|
||||
}));
|
||||
}
|
||||
|
||||
export async function createAccount(actorId: string, input: Record<string, unknown>): Promise<AuthUser> {
|
||||
activeAdmin(actorId);
|
||||
let username: string; let displayName: string;
|
||||
try { username = normalizeUsername(input.username); displayName = normalizeDisplayName(input.displayName); validatePassword(input.password); }
|
||||
catch (error) { throw new AuthError((error as Error).message); }
|
||||
if (!['admin', 'user'].includes(String(input.role))) throw new AuthError('账号角色无效。');
|
||||
const passwordHash = await hashPassword(input.password as string);
|
||||
return getDatabase().transaction(() => {
|
||||
activeAdmin(actorId);
|
||||
if (getDatabase().prepare('SELECT id FROM accounts WHERE username = ?').bind(username).first()) throw new AuthError('该账号已存在。', 409);
|
||||
const now = new Date().toISOString();
|
||||
const userId = randomBytes(16).toString('hex');
|
||||
getDatabase().prepare(`INSERT INTO accounts (id, username, display_name, password_hash, role, must_change_password, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, 1, ?, ?)`).bind(userId, username, displayName, passwordHash, input.role as string, now, now).run();
|
||||
return publicUser(accountById(userId)!);
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateAccount(actorId: string, input: Record<string, unknown>): Promise<AuthUser> {
|
||||
activeAdmin(actorId);
|
||||
if (typeof input.id !== 'string' || input.id.length > 128 || !['disable', 'enable', 'reset-password'].includes(String(input.action))) throw new AuthError('账号操作无效。');
|
||||
if (input.id === actorId && ['disable', 'reset-password'].includes(String(input.action))) throw new AuthError('不能停用或重置自己的账号;请使用“修改密码”。');
|
||||
let passwordHash: string | undefined;
|
||||
if (input.action === 'reset-password') {
|
||||
try { validatePassword(input.password); } catch (error) { throw new AuthError((error as Error).message); }
|
||||
passwordHash = await hashPassword(input.password as string);
|
||||
}
|
||||
return getDatabase().transaction(() => {
|
||||
activeAdmin(actorId);
|
||||
const target = accountById(input.id as string);
|
||||
if (!target) throw new AuthError('找不到该账号。', 404);
|
||||
const database = getDatabase();
|
||||
const now = new Date().toISOString();
|
||||
if (input.action === 'disable') {
|
||||
const admins = database.prepare("SELECT COUNT(*) AS count FROM accounts WHERE role = 'admin' AND disabled = 0").first<{ count: number }>()!;
|
||||
if (target.role === 'admin' && !target.disabled && admins.count <= 1) throw new AuthError('必须至少保留一位启用的管理员。', 409);
|
||||
database.prepare('UPDATE accounts SET disabled = 1, updated_at = ? WHERE id = ?').bind(now, target.id).run();
|
||||
} else if (input.action === 'enable') {
|
||||
database.prepare('UPDATE accounts SET disabled = 0, updated_at = ? WHERE id = ?').bind(now, target.id).run();
|
||||
} else {
|
||||
database.prepare('UPDATE accounts SET password_hash = ?, must_change_password = 1, updated_at = ? WHERE id = ?').bind(passwordHash!, now, target.id).run();
|
||||
database.prepare('DELETE FROM login_limits WHERE key = ?').bind(`username:${tokenHash(target.username)}`).run();
|
||||
}
|
||||
if (input.action !== 'enable') database.prepare('DELETE FROM sessions WHERE account_id = ?').bind(target.id).run();
|
||||
return publicUser(accountById(target.id)!);
|
||||
});
|
||||
}
|
||||
|
||||
export function jsonResponse(value: unknown, status = 200, cookie?: string): Response {
|
||||
const headers = new Headers({ 'Cache-Control': 'no-store' });
|
||||
if (cookie) headers.set('Set-Cookie', cookie);
|
||||
return Response.json(value, { status, headers });
|
||||
}
|
||||
export function authFailure(error: unknown): Response {
|
||||
if (error instanceof AuthError) return jsonResponse({ error: error.message }, error.status);
|
||||
console.error('Account operation failed:', error instanceof Error ? error.message : 'Unknown failure');
|
||||
return jsonResponse({ error: '账号服务暂时不可用,请联系管理员或稍后重试。' }, 503);
|
||||
}
|
||||
|
||||
export async function readJsonObject(request: Request): Promise<Record<string, unknown>> {
|
||||
if (!request.headers.get('content-type')?.toLowerCase().startsWith('application/json')) throw new AuthError('请使用 JSON 格式提交。', 415);
|
||||
const reader = request.body?.getReader();
|
||||
if (!reader) throw new AuthError('提交内容不能为空。');
|
||||
const chunks: Uint8Array[] = []; let length = 0;
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
length += value.length;
|
||||
if (length > 8192) { await reader.cancel(); throw new AuthError('提交内容过长。', 413); }
|
||||
chunks.push(value);
|
||||
}
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('Invalid JSON object');
|
||||
return parsed as Record<string, unknown>;
|
||||
} catch { throw new AuthError('提交内容格式无效。'); }
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
import { mkdirSync, chmodSync } from 'node:fs';
|
||||
import { resolve, join } from 'node:path';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { DatabaseSync, type SQLInputValue } from 'node:sqlite';
|
||||
import { hashPasswordSync } from './password.ts';
|
||||
|
||||
export type AccountRole = 'admin' | 'user';
|
||||
export type AccountRow = {
|
||||
id: string; username: string; display_name: string; password_hash: string;
|
||||
role: AccountRole; disabled: number; must_change_password: number;
|
||||
created_at: string; updated_at: string; last_login_at: string | null;
|
||||
};
|
||||
|
||||
export function normalizeUsername(value: unknown): string {
|
||||
if (typeof value !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9._@-]{2,63}$/.test(value.trim())) {
|
||||
throw new Error('账号须为 3–64 位字母、数字或 . _ @ -,并以字母或数字开头。');
|
||||
}
|
||||
return value.trim().toLowerCase();
|
||||
}
|
||||
|
||||
export function normalizeDisplayName(value: unknown): string {
|
||||
if (typeof value !== 'string' || !value.trim() || value.trim().length > 80 || /[\u0000-\u001f\u007f]/.test(value)) {
|
||||
throw new Error('姓名须为 1–80 个字符。');
|
||||
}
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
export function applicationOrigin(request?: Request): string {
|
||||
const configured = process.env.APP_URL;
|
||||
if (!configured) {
|
||||
if (process.env.NODE_ENV === 'production') throw new Error('生产环境必须设置 APP_URL,例如 https://demand.example.com。');
|
||||
return request ? new URL(request.url).origin : 'http://localhost:3000';
|
||||
}
|
||||
const url = new URL(configured);
|
||||
if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password || (url.pathname !== '/' && url.pathname !== '') || url.search || url.hash) {
|
||||
throw new Error('APP_URL 必须为系统的完整访问域名,例如 https://demand.example.com,不含路径。');
|
||||
}
|
||||
return url.origin;
|
||||
}
|
||||
|
||||
class PreparedQuery {
|
||||
private database: DatabaseSync;
|
||||
private sql: string;
|
||||
private values: SQLInputValue[];
|
||||
constructor(database: DatabaseSync, sql: string, values: SQLInputValue[] = []) {
|
||||
this.database = database; this.sql = sql; this.values = values;
|
||||
}
|
||||
bind(...values: SQLInputValue[]): PreparedQuery { return new PreparedQuery(this.database, this.sql, values); }
|
||||
all<T = Record<string, unknown>>(): { results: T[] } {
|
||||
return { results: this.database.prepare(this.sql).all(...this.values) as T[] };
|
||||
}
|
||||
first<T = Record<string, unknown>>(): T | null {
|
||||
return (this.database.prepare(this.sql).get(...this.values) as T | undefined) ?? null;
|
||||
}
|
||||
run(): { meta: { changes: number; last_row_id: number | bigint } } {
|
||||
const result = this.database.prepare(this.sql).run(...this.values);
|
||||
return { meta: { changes: Number(result.changes), last_row_id: result.lastInsertRowid } };
|
||||
}
|
||||
}
|
||||
|
||||
export class AppDatabase {
|
||||
private database: DatabaseSync;
|
||||
constructor(database: DatabaseSync) { this.database = database; }
|
||||
prepare(sql: string): PreparedQuery { return new PreparedQuery(this.database, sql); }
|
||||
transaction<T>(action: () => T): T {
|
||||
this.database.exec('BEGIN IMMEDIATE');
|
||||
try { const result = action(); this.database.exec('COMMIT'); return result; }
|
||||
catch (error) { this.database.exec('ROLLBACK'); throw error; }
|
||||
}
|
||||
close(): void { this.database.close(); }
|
||||
}
|
||||
|
||||
const databases = new Map<string, AppDatabase>();
|
||||
|
||||
function migrate(database: DatabaseSync): void {
|
||||
database.exec('BEGIN IMMEDIATE');
|
||||
try {
|
||||
const version = Number((database.prepare('PRAGMA user_version').get() as { user_version: number }).user_version);
|
||||
if (version > 3) throw new Error('数据库版本比当前应用更新,请使用匹配的应用版本。');
|
||||
if (version < 1) {
|
||||
database.exec(`
|
||||
CREATE TABLE IF NOT EXISTS demands (
|
||||
id TEXT PRIMARY KEY, owner_id TEXT NOT NULL, payload TEXT NOT NULL,
|
||||
revision INTEGER NOT NULL DEFAULT 1, updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS demands_owner_updated ON demands(owner_id, updated_at DESC);
|
||||
CREATE TABLE IF NOT EXISTS accounts (
|
||||
id TEXT PRIMARY KEY, username TEXT NOT NULL COLLATE NOCASE UNIQUE,
|
||||
display_name TEXT NOT NULL, password_hash TEXT NOT NULL,
|
||||
role TEXT NOT NULL CHECK(role IN ('admin', 'user')),
|
||||
disabled INTEGER NOT NULL DEFAULT 0 CHECK(disabled IN (0, 1)),
|
||||
must_change_password INTEGER NOT NULL DEFAULT 1 CHECK(must_change_password IN (0, 1)),
|
||||
created_at TEXT NOT NULL, updated_at TEXT NOT NULL, last_login_at TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
token_hash TEXT PRIMARY KEY, account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
|
||||
expires_at INTEGER NOT NULL, created_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS sessions_account ON sessions(account_id);
|
||||
CREATE INDEX IF NOT EXISTS sessions_expiry ON sessions(expires_at);
|
||||
CREATE TABLE IF NOT EXISTS login_limits (
|
||||
key TEXT PRIMARY KEY, window_start INTEGER NOT NULL, attempts INTEGER NOT NULL
|
||||
);
|
||||
PRAGMA user_version = 1;
|
||||
`);
|
||||
}
|
||||
if (version < 2) {
|
||||
database.exec(`
|
||||
CREATE TABLE IF NOT EXISTS attachments (
|
||||
id TEXT PRIMARY KEY,
|
||||
owner_id TEXT NOT NULL REFERENCES accounts(id),
|
||||
demand_id TEXT REFERENCES demands(id),
|
||||
name TEXT NOT NULL,
|
||||
size INTEGER NOT NULL CHECK(size > 0 AND size <= 20971520),
|
||||
content BLOB NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS attachments_demand ON attachments(demand_id);
|
||||
CREATE INDEX IF NOT EXISTS attachments_owner_staged ON attachments(owner_id, demand_id, created_at);
|
||||
PRAGMA user_version = 2;
|
||||
`);
|
||||
}
|
||||
if (version < 3) {
|
||||
database.exec(`
|
||||
CREATE TABLE feishu_identities (
|
||||
account_id TEXT PRIMARY KEY REFERENCES accounts(id) ON DELETE CASCADE,
|
||||
app_id TEXT NOT NULL, tenant_key TEXT NOT NULL, open_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL, bound_at TEXT NOT NULL,
|
||||
UNIQUE(app_id, tenant_key, open_id)
|
||||
);
|
||||
CREATE TABLE feishu_oauth_states (
|
||||
state_hash TEXT PRIMARY KEY, browser_hash TEXT NOT NULL,
|
||||
account_id TEXT REFERENCES accounts(id) ON DELETE CASCADE,
|
||||
session_hash TEXT, app_id TEXT NOT NULL, verifier TEXT NOT NULL,
|
||||
return_to TEXT NOT NULL, expires_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX feishu_oauth_expiry ON feishu_oauth_states(expires_at);
|
||||
CREATE TABLE feishu_notifications (
|
||||
id TEXT PRIMARY KEY, demand_id TEXT NOT NULL REFERENCES demands(id),
|
||||
revision INTEGER NOT NULL, target_key TEXT NOT NULL, content TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending','sending','sent','failed')),
|
||||
attempts INTEGER NOT NULL DEFAULT 0, next_attempt_at INTEGER NOT NULL,
|
||||
lease_token TEXT, last_error TEXT, created_at TEXT NOT NULL, sent_at TEXT,
|
||||
UNIQUE(demand_id, revision, target_key)
|
||||
);
|
||||
CREATE INDEX feishu_notifications_due ON feishu_notifications(status, next_attempt_at);
|
||||
PRAGMA user_version = 3;
|
||||
`);
|
||||
}
|
||||
const count = Number((database.prepare('SELECT COUNT(*) AS count FROM accounts').get() as { count: number }).count);
|
||||
if (count === 0) {
|
||||
const username = process.env.INITIAL_ADMIN_USERNAME;
|
||||
const password = process.env.INITIAL_ADMIN_PASSWORD;
|
||||
if (!username || !password) throw new Error('首次启动请设置 INITIAL_ADMIN_USERNAME 和 INITIAL_ADMIN_PASSWORD(至少 12 位)。');
|
||||
const now = new Date().toISOString();
|
||||
database.prepare(`INSERT INTO accounts (id, username, display_name, password_hash, role, must_change_password, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, 'admin', 1, ?, ?)`).run(randomUUID(), normalizeUsername(username), normalizeDisplayName(process.env.INITIAL_ADMIN_DISPLAY_NAME || '系统管理员'), hashPasswordSync(password), now, now);
|
||||
}
|
||||
database.exec('COMMIT');
|
||||
} catch (error) { database.exec('ROLLBACK'); throw error; }
|
||||
}
|
||||
|
||||
// Lazy initialization is intentional: Next.js builds never open or bootstrap a database.
|
||||
export function getDatabase(): AppDatabase {
|
||||
applicationOrigin();
|
||||
const directory = resolve(process.env.DATA_DIR || './data');
|
||||
const filename = join(directory, 'demand-center.sqlite');
|
||||
const existing = databases.get(filename);
|
||||
if (existing) return existing;
|
||||
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
||||
const native = new DatabaseSync(filename);
|
||||
try {
|
||||
chmodSync(filename, 0o600);
|
||||
native.exec('PRAGMA busy_timeout = 5000; PRAGMA foreign_keys = ON; PRAGMA journal_mode = WAL; PRAGMA synchronous = FULL;');
|
||||
migrate(native);
|
||||
const adapter = new AppDatabase(native);
|
||||
databases.set(filename, adapter);
|
||||
return adapter;
|
||||
} catch (error) { native.close(); throw error; }
|
||||
}
|
||||
|
||||
/** Close connections for isolated test processes and graceful maintenance tooling. */
|
||||
export function closeDatabases(): void {
|
||||
for (const database of databases.values()) database.close();
|
||||
databases.clear();
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { Demand } from '../demand.ts';
|
||||
import { getDatabase } from './database.ts';
|
||||
import { AuthError, type AuthUser } from './auth.ts';
|
||||
|
||||
/** Resolve missing assignments without rewriting existing responsibilities or history. */
|
||||
export function withDefaultDeveloper(demand: Demand): Demand {
|
||||
if (demand.review || ['草稿', '已取消', '已完成'].includes(demand.status)) return demand;
|
||||
const admin = getDatabase().prepare(`SELECT id, username, display_name FROM accounts
|
||||
WHERE role = 'admin' AND disabled = 0 ORDER BY created_at, id LIMIT 1`)
|
||||
.first<{ id: string; username: string; display_name: string }>();
|
||||
if (!admin) throw new AuthError('暂无启用的系统管理员,请联系管理员恢复账号后重试。', 503);
|
||||
return { ...demand, review: { developer: { userId: admin.id, username: admin.username, displayName: admin.display_name }, proposals: [] } };
|
||||
}
|
||||
|
||||
/** A read-only administrator can only recover an unavailable developer's assignment. */
|
||||
export function canTakeOverDevelopment(demand: Demand, user: AuthUser): boolean {
|
||||
if (user.role !== 'admin' || !demand.review || ['草稿', '已取消'].includes(demand.status) || demand.review.developer.userId === user.userId) return false;
|
||||
return Boolean(getDatabase().prepare(`SELECT 1 FROM accounts
|
||||
WHERE id = ? AND role = 'admin' AND disabled = 0 AND must_change_password = 0
|
||||
AND NOT EXISTS (SELECT 1 FROM accounts WHERE id = ? AND disabled = 0)`)
|
||||
.bind(user.userId, demand.review.developer.userId).first());
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import type { AuthUser } from './auth.ts';
|
||||
|
||||
export type DemandViewer = Pick<AuthUser, 'userId' | 'role'>;
|
||||
|
||||
// Read access only: admin visibility must never grant business/developer writes.
|
||||
// The owner can read drafts; everyone else's access requires a formal demand.
|
||||
export const readableDemandWhere = "(owner_id = ? OR (json_extract(payload, '$.status') != '草稿' AND (? = 1 OR json_extract(payload, '$.review.developer.userId') = ?)))";
|
||||
|
||||
export function readableDemandBindings(user: DemandViewer): [string, number, string] {
|
||||
return [user.userId, user.role === 'admin' ? 1 : 0, user.userId];
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { z } from 'zod';
|
||||
import { currentProposal, invalidateProposal, type ReviewPerson } from '../demand-review.ts';
|
||||
import type { Demand } from '../demand.ts';
|
||||
import { AuthError, type AuthUser } from './auth.ts';
|
||||
import { getDatabase } from './database.ts';
|
||||
import { pendingChange } from '../workflow.ts';
|
||||
import { canTakeOverDevelopment } from './default-developer.ts';
|
||||
|
||||
const proposalSchema = z.object({
|
||||
scope: z.string().trim().min(1).max(6000),
|
||||
outOfScope: z.string().trim().min(1).max(3000),
|
||||
});
|
||||
const person = (user: AuthUser): ReviewPerson => ({ userId: user.userId, username: user.username, displayName: user.displayName });
|
||||
|
||||
function changeDeveloper(d: Demand, developer: ReviewPerson, now: string): void {
|
||||
invalidateProposal(d, now, '开发责任人已变更,需重新提出方案并确认。');
|
||||
d.status = '待评审';
|
||||
if (d.acceptance) {
|
||||
d.acceptance.withdrawnAt = now;
|
||||
const round = d.delivery?.testing?.find(item => item.round === d.acceptance?.round);
|
||||
if (round) round.withdrawnAt = now;
|
||||
}
|
||||
d.review = { developer, proposals: d.review?.proposals ?? [] };
|
||||
}
|
||||
|
||||
export function applyReviewAction(d: Demand, ownerId: string, user: AuthUser, body: Record<string, unknown>, now: string): { label: string; detail: string } {
|
||||
if (body.action === 'take-over-development') {
|
||||
if (!canTakeOverDevelopment(d, user)) throw new AuthError('仅启用的管理员可接手已停用或不可用的开发账号所负责的需求。', 403);
|
||||
if (pendingChange(d)) throw new AuthError('请先由业务方处理或撤回待确认变更,再接手开发职责。', 409);
|
||||
if (body.confirm !== true) throw new AuthError('请确认接手开发职责,并重新评审和排期。');
|
||||
const previous = d.review!.developer;
|
||||
changeDeveloper(d, person(user), now);
|
||||
return { label: '接手开发职责', detail: `${previous.displayName}(${previous.username}) → ${user.displayName}(${user.username});原开发账号已停用或不可用。历史方案、计划和验收记录保留,需重新评审、确认计划并提测验收。` };
|
||||
}
|
||||
if ((d.status !== '待评审' && (body.action !== 'assign-developer' || ['草稿','已取消'].includes(d.status))) || !d.reviewReady) throw new AuthError('请先补齐业务材料并提交评审。', 409);
|
||||
const business = ownerId === user.userId;
|
||||
if (body.action === 'assign-developer') {
|
||||
if (!business) throw new AuthError('只有需求登记账号可以指定开发责任人。', 403);
|
||||
if(pendingChange(d))throw new AuthError('请先处理或撤回待确认变更,再更换开发责任人。',409);
|
||||
if (typeof body.username !== 'string' || !body.username.trim() || body.username.length > 64) throw new AuthError('请填写开发责任人的系统账号。');
|
||||
const account = getDatabase().prepare('SELECT id, username, display_name FROM accounts WHERE username = ? AND disabled = 0')
|
||||
.bind(body.username.trim().toLowerCase()).first<{ id: string; username: string; display_name: string }>();
|
||||
if (!account) throw new AuthError('未找到启用的账号,请核对开发责任人的系统账号。');
|
||||
if (account.id === ownerId) throw new AuthError('开发责任人与业务确认人须使用不同账号。');
|
||||
if (account.id === d.review?.developer.userId) throw new AuthError('该账号已是本需求的开发责任人。');
|
||||
const previous = d.review?.developer;
|
||||
changeDeveloper(d, { userId: account.id, username: account.username, displayName: account.display_name }, now);
|
||||
return { label: previous ? '更换开发责任人' : '指定开发责任人', detail: `${previous ? previous.displayName + ' → ' : ''}${account.display_name}(${account.username})。该账号负责后续方案与交付;更换后需重新评审并确认计划。` };
|
||||
}
|
||||
if (body.action === 'propose-solution') {
|
||||
if (d.review?.developer.userId !== user.userId) throw new AuthError('只有当前开发责任人可以提交方案。', 403);
|
||||
const parsed = proposalSchema.safeParse(body);
|
||||
if (!parsed.success) throw new AuthError('请填写实施范围与功能说明(6000 字以内)和范围外事项(3000 字以内,无则填“无”)。');
|
||||
const previous = currentProposal(d);
|
||||
if (previous && !previous.invalidated && previous.decision?.result !== 'changes_requested') throw new AuthError('当前方案已提交,请等待业务方确认或退回修改。', 409);
|
||||
const version = (previous?.version ?? 0) + 1;
|
||||
d.review.proposals.push({ ...parsed.data, version, developer: person(user), submittedAt: now, businessFields: structuredClone(d.fields), businessAttachments: structuredClone(d.attachments ?? []) });
|
||||
d.fields.scope = parsed.data.scope;
|
||||
d.fields.outOfScope = parsed.data.outOfScope;
|
||||
return { label: '提交评审方案', detail: `方案 v${version} 已由 ${user.displayName} 提交,等待业务方确认。` };
|
||||
}
|
||||
if (body.action === 'confirm-solution' || body.action === 'return-solution') {
|
||||
if (!business) throw new AuthError('只有需求登记账号可以代表业务方确认或退回方案。', 403);
|
||||
const proposal = currentProposal(d);
|
||||
if (!proposal || proposal.invalidated || proposal.developer.userId !== d.review?.developer.userId || body.proposalVersion !== proposal.version) throw new AuthError('方案已变化,请刷新后核对当前版本。', 409);
|
||||
const confirming = body.action === 'confirm-solution';
|
||||
if (proposal.decision && (confirming || proposal.decision.result !== 'confirmed')) throw new AuthError('该版本已处理,请刷新查看最新结果。', 409);
|
||||
if (confirming && body.confirm !== true) throw new AuthError('请明确勾选同意按当前方案实施。');
|
||||
const comment = typeof body.comment === 'string' ? body.comment.trim() : '';
|
||||
if ((!confirming && !comment) || comment.length > 3000) throw new AuthError('请填写修改意见(3000 字以内)。');
|
||||
// A request to revise an already confirmed version invalidates it without overwriting its original confirmation.
|
||||
if (proposal.decision?.result === 'confirmed') {
|
||||
invalidateProposal(d, now, `业务方要求调整:${comment}`);
|
||||
} else {
|
||||
proposal.decision = { result: confirming ? 'confirmed' : 'changes_requested', actor: person(user), time: now, comment };
|
||||
}
|
||||
return { label: confirming ? '业务方确认方案' : '退回修改方案', detail: `方案 v${proposal.version};${user.displayName} ${confirming ? '同意按此版本实施。' : '要求修改:'}${comment}` };
|
||||
}
|
||||
throw new AuthError('不支持的评审操作。');
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
||||
import { basePath } from '../base-path.ts';
|
||||
import { safeReturnTo } from '../auth-return.ts';
|
||||
import type { FeishuBinding } from '../feishu.ts';
|
||||
import { applicationOrigin, getDatabase } from './database.ts';
|
||||
import { AuthError, authenticateSession, consumeLoginSourceAttempt, hasAccountPassword, issueIdentitySession, loginWithPassword, revokeSession, type AuthUser } from './auth.ts';
|
||||
import { feishuJson, feishuLoginConfig } from './feishu-config.ts';
|
||||
import { PASSWORD_LOGIN_DISABLED } from './password.ts';
|
||||
|
||||
const STATE_SECONDS = 600;
|
||||
const STATE_COOKIE = 'demand_feishu_state';
|
||||
const hash = (value: string) => createHash('sha256').update(value).digest('hex');
|
||||
type StateRow = { browser_hash: string; account_id: string | null; session_hash: string | null; app_id: string; verifier: string; return_to: string; expires_at: number };
|
||||
type Identity = { openId: string; tenantKey: string; name: string };
|
||||
export class FeishuAuthError extends Error {
|
||||
code: string;
|
||||
constructor(code: string) { super(code); this.code = code; }
|
||||
}
|
||||
export function requestCookie(request: Request, name: string): string {
|
||||
return request.headers.get('cookie')?.split(';').map(part => part.trim()).find(part => part.startsWith(name + '='))?.slice(name.length + 1) || '';
|
||||
}
|
||||
export function feishuStateCookie(token: string): string {
|
||||
return `${STATE_COOKIE}=${token}; Path=${basePath || '/'}; HttpOnly; SameSite=Lax; Max-Age=${token ? STATE_SECONDS : 0}${applicationOrigin().startsWith('https://') ? '; Secure' : ''}`;
|
||||
}
|
||||
export function beginFeishuAuth(request: Request, intent: string, returnTo: unknown) {
|
||||
let config;
|
||||
try { config = feishuLoginConfig(); } catch { throw new FeishuAuthError('unavailable'); }
|
||||
if (!['login', 'bind'].includes(intent)) throw new FeishuAuthError('failed');
|
||||
const session = requestCookie(request, 'demand_session');
|
||||
const user = authenticateSession(session);
|
||||
if (intent === 'bind' && (!user || user.mustChangePassword)) throw new FeishuAuthError('session');
|
||||
consumeLoginSourceAttempt(request);
|
||||
const state = randomBytes(32).toString('base64url');
|
||||
const browser = randomBytes(32).toString('base64url');
|
||||
const verifier = randomBytes(32).toString('base64url');
|
||||
const db = getDatabase();
|
||||
db.transaction(() => {
|
||||
db.prepare('DELETE FROM feishu_oauth_states WHERE expires_at <= ?').bind(Date.now()).run();
|
||||
// A new attempt replaces the previous attempt in this browser.
|
||||
const previous = requestCookie(request, STATE_COOKIE);
|
||||
if (previous) db.prepare('DELETE FROM feishu_oauth_states WHERE browser_hash = ?').bind(hash(previous)).run();
|
||||
db.prepare(`INSERT INTO feishu_oauth_states (state_hash, browser_hash, account_id, session_hash, app_id, verifier, return_to, expires_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).bind(hash(state), hash(browser), intent === 'bind' ? user!.userId : null,
|
||||
intent === 'bind' ? hash(session) : null, config.appId, verifier, safeReturnTo(returnTo), Date.now() + STATE_SECONDS * 1000).run();
|
||||
});
|
||||
const url = new URL('https://accounts.feishu.cn/open-apis/authen/v1/authorize');
|
||||
url.search = new URLSearchParams({ client_id: config.appId, response_type: 'code', redirect_uri: config.callbackUrl,
|
||||
state, code_challenge: createHash('sha256').update(verifier).digest('base64url'), code_challenge_method: 'S256' }).toString();
|
||||
if (intent === 'bind') url.searchParams.set('prompt', 'consent');
|
||||
return { url: url.href, cookie: feishuStateCookie(browser) };
|
||||
}
|
||||
|
||||
export function consumeFeishuState(request: Request): StateRow {
|
||||
const state = new URL(request.url).searchParams.get('state') || '';
|
||||
const browser = requestCookie(request, STATE_COOKIE);
|
||||
if (![state, browser].every(value => /^[A-Za-z0-9_-]{43}$/.test(value))) throw new FeishuAuthError('expired');
|
||||
return getDatabase().transaction(() => {
|
||||
const row = getDatabase().prepare('SELECT * FROM feishu_oauth_states WHERE state_hash = ?').bind(hash(state)).first<StateRow>();
|
||||
if (!row || row.expires_at <= Date.now() || !timingSafeEqual(Buffer.from(row.browser_hash), Buffer.from(hash(browser)))) throw new FeishuAuthError('expired');
|
||||
getDatabase().prepare('DELETE FROM feishu_oauth_states WHERE state_hash = ?').bind(hash(state)).run();
|
||||
return row;
|
||||
});
|
||||
}
|
||||
|
||||
async function exchangeIdentity(code: string, verifier: string): Promise<Identity> {
|
||||
const config = feishuLoginConfig();
|
||||
// The authorize endpoint's PKCE documentation currently pairs it with v2.
|
||||
// v3 rejected the live app's valid S256 flow with 20049; keep PKCE and use the documented pair.
|
||||
const token = await feishuJson('https://open.feishu.cn/open-apis/authen/v2/oauth/token', {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ grant_type: 'authorization_code', client_id: config.appId, client_secret: config.secret,
|
||||
code, redirect_uri: config.callbackUrl, code_verifier: verifier }),
|
||||
});
|
||||
if (token.code !== undefined && token.code !== 0) throw new FeishuAuthError('failed');
|
||||
if (typeof token.access_token !== 'string' || !token.access_token) {
|
||||
console.error('Feishu identity failure', { stage: 'oauth-token', reason: 'missing-access-token' });
|
||||
throw new FeishuAuthError('failed');
|
||||
}
|
||||
const info = await feishuJson('https://open.feishu.cn/open-apis/authen/v1/user_info', { headers: { Authorization: `Bearer ${token.access_token}` } });
|
||||
const data = info.data as Record<string, unknown> | undefined;
|
||||
if (info.code !== 0) throw new FeishuAuthError('failed');
|
||||
const invalidFields = ['open_id', 'tenant_key', 'name'].filter(field => typeof data?.[field] !== 'string' || (data[field] as string).length > 256 || (field !== 'name' && !data[field]));
|
||||
if (!data || invalidFields.length) {
|
||||
console.error('Feishu identity failure', { stage: 'user-info', invalidFields });
|
||||
throw new FeishuAuthError('failed');
|
||||
}
|
||||
if (config.tenantKey && data.tenant_key !== config.tenantKey) throw new FeishuAuthError('tenant');
|
||||
return { openId: data.open_id as string, tenantKey: data.tenant_key as string, name: data.name as string };
|
||||
}
|
||||
|
||||
function bindingUser(request: Request, state: StateRow): AuthUser {
|
||||
const session = requestCookie(request, 'demand_session');
|
||||
const current = authenticateSession(session);
|
||||
if (!current || current.mustChangePassword || current.userId !== state.account_id || hash(session) !== state.session_hash) throw new FeishuAuthError('session');
|
||||
return current;
|
||||
}
|
||||
|
||||
/** Called inside the identity lookup transaction; roles and usernames never come from browser input. */
|
||||
function registerFeishuAccount(appId: string, identity: Identity): string {
|
||||
const db = getDatabase();
|
||||
const id = randomBytes(16).toString('hex');
|
||||
const now = new Date().toISOString();
|
||||
const displayName = identity.name.replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, 80) || '飞书成员';
|
||||
db.prepare(`INSERT INTO accounts (id, username, display_name, password_hash, role, must_change_password, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, 'user', 0, ?, ?)`).bind(id, `feishu_${id}`, displayName, PASSWORD_LOGIN_DISABLED, now, now).run();
|
||||
db.prepare('INSERT INTO feishu_identities (account_id, app_id, tenant_key, open_id, name, bound_at) VALUES (?, ?, ?, ?, ?, ?)')
|
||||
.bind(id, appId, identity.tenantKey, identity.openId, identity.name, now).run();
|
||||
return id;
|
||||
}
|
||||
|
||||
export async function completeFeishuAuth(request: Request, state: StateRow) {
|
||||
if (state.app_id !== feishuLoginConfig().appId) throw new FeishuAuthError('expired');
|
||||
if (state.account_id) bindingUser(request, state);
|
||||
const params = new URL(request.url).searchParams;
|
||||
if (params.has('error')) throw new FeishuAuthError('denied');
|
||||
const code = params.get('code');
|
||||
if (!code || code.length > 2048) throw new FeishuAuthError('failed');
|
||||
const identity = await exchangeIdentity(code, state.verifier);
|
||||
return getDatabase().transaction(() => {
|
||||
const db = getDatabase();
|
||||
const bound = db.prepare('SELECT account_id FROM feishu_identities WHERE app_id = ? AND tenant_key = ? AND open_id = ?')
|
||||
.bind(state.app_id, identity.tenantKey, identity.openId).first<{ account_id: string }>();
|
||||
if (state.account_id) {
|
||||
const user = bindingUser(request, state); // Recheck after the network call, including reset/disable/logout.
|
||||
const existing = db.prepare('SELECT account_id FROM feishu_identities WHERE account_id = ?').bind(user.userId).first();
|
||||
if ((bound && bound.account_id !== user.userId) || (existing && !bound)) throw new FeishuAuthError('conflict');
|
||||
if (!bound) db.prepare('INSERT INTO feishu_identities (account_id, app_id, tenant_key, open_id, name, bound_at) VALUES (?, ?, ?, ?, ?, ?)')
|
||||
.bind(user.userId, state.app_id, identity.tenantKey, identity.openId, identity.name, new Date().toISOString()).run();
|
||||
return { bound: true as const, returnTo: '/account/feishu', token: null, user };
|
||||
}
|
||||
const accountId = bound?.account_id ?? registerFeishuAccount(state.app_id, identity);
|
||||
const result = issueIdentitySession(accountId);
|
||||
revokeSession(requestCookie(request, 'demand_session'));
|
||||
return { bound: false as const, returnTo: result.user.mustChangePassword ? '/account/password' : state.return_to, ...result };
|
||||
});
|
||||
}
|
||||
|
||||
export function getFeishuBinding(accountId: string): FeishuBinding {
|
||||
const row = getDatabase().prepare('SELECT name, bound_at AS boundAt FROM feishu_identities WHERE account_id = ?').bind(accountId).first<NonNullable<FeishuBinding>>();
|
||||
return row ? { ...row } : null;
|
||||
}
|
||||
|
||||
export async function unbindFeishu(user: AuthUser, password: unknown, request: Request) {
|
||||
if (!hasAccountPassword(user.userId)) throw new AuthError('请先设置系统密码,再解除飞书绑定。', 409);
|
||||
const verified = await loginWithPassword(user.username, password, request);
|
||||
revokeSession(verified.token);
|
||||
return getDatabase().transaction(() => {
|
||||
if (authenticateSession(requestCookie(request, 'demand_session'))?.userId !== user.userId || verified.user.userId !== user.userId) {
|
||||
throw new AuthError('登录状态已变化,请重新登录。', 401);
|
||||
}
|
||||
getDatabase().prepare('DELETE FROM feishu_identities WHERE account_id = ?').bind(user.userId).run();
|
||||
getDatabase().prepare('DELETE FROM feishu_oauth_states WHERE account_id = ?').bind(user.userId).run();
|
||||
getDatabase().prepare('DELETE FROM sessions WHERE account_id = ?').bind(user.userId).run();
|
||||
return issueIdentitySession(user.userId);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { appPath } from '../base-path.ts';
|
||||
import { applicationOrigin } from './database.ts';
|
||||
|
||||
export function feishuLoginConfigured(): boolean {
|
||||
return Boolean(process.env.FEISHU_APP_ID?.trim() && process.env.FEISHU_APP_SECRET?.trim());
|
||||
}
|
||||
export function feishuCallbackUrl(): string {
|
||||
return applicationOrigin() + appPath('/api/auth/feishu/callback');
|
||||
}
|
||||
export function feishuLoginConfig() {
|
||||
if (!feishuLoginConfigured()) throw new Error('飞书登录尚未配置 App ID 和 App Secret。');
|
||||
return {
|
||||
appId: process.env.FEISHU_APP_ID!.trim(), secret: process.env.FEISHU_APP_SECRET!.trim(),
|
||||
callbackUrl: feishuCallbackUrl(), tenantKey: process.env.FEISHU_TENANT_KEY?.trim() || '',
|
||||
};
|
||||
}
|
||||
export function feishuBotConfig() {
|
||||
const webhook = process.env.FEISHU_BOT_WEBHOOK?.trim();
|
||||
if (!webhook) return null;
|
||||
let url: URL;
|
||||
try { url = new URL(webhook); } catch { throw new Error('飞书群机器人 Webhook 地址无效。'); }
|
||||
if (url.protocol !== 'https:' || url.hostname !== 'open.feishu.cn' || url.port || url.username || url.password || url.search || url.hash || !/^\/open-apis\/bot\/v2\/hook\/[a-zA-Z0-9_-]+$/.test(url.pathname)) {
|
||||
throw new Error('飞书群机器人地址必须是 https://open.feishu.cn/open-apis/bot/v2/hook/ 开头的完整 Webhook。');
|
||||
}
|
||||
return { webhook: url.href, secret: process.env.FEISHU_BOT_SECRET?.trim() || '', targetKey: createHash('sha256').update(url.href).digest('hex') };
|
||||
}
|
||||
|
||||
/** Never expose upstream error text: providers may echo credentials or user information. */
|
||||
export async function feishuJson(url: string, init: RequestInit): Promise<Record<string, unknown>> {
|
||||
const stage = ['https://accounts.feishu.cn/oauth/v3/token', 'https://open.feishu.cn/open-apis/authen/v2/oauth/token'].includes(url) ? 'oauth-token'
|
||||
: url === 'https://open.feishu.cn/open-apis/authen/v1/user_info' ? 'user-info' : 'bot';
|
||||
let response: Response;
|
||||
try { response = await fetch(url, { ...init, redirect: 'error', cache: 'no-store', signal: AbortSignal.timeout(8000) }); }
|
||||
catch (error) {
|
||||
console.error('Feishu API failure', { stage, reason: error instanceof Error && error.name === 'TimeoutError' ? 'timeout' : 'network' });
|
||||
throw new Error('飞书服务连接失败或超时。');
|
||||
}
|
||||
let data: unknown;
|
||||
try { data = await response.json(); }
|
||||
catch {
|
||||
console.error('Feishu API failure', { stage, httpStatus: response.status, reason: 'invalid-json' });
|
||||
throw new Error('飞书服务返回格式无效。');
|
||||
}
|
||||
if (!data || typeof data !== 'object' || Array.isArray(data)) {
|
||||
console.error('Feishu API failure', { stage, httpStatus: response.status, reason: 'invalid-object' });
|
||||
throw new Error('飞书服务返回格式无效。');
|
||||
}
|
||||
const record = data as Record<string, unknown>;
|
||||
const code = record.code ?? record.StatusCode;
|
||||
if (!response.ok || (typeof code === 'number' && code !== 0)) {
|
||||
console.error('Feishu API failure', { stage, httpStatus: response.status, providerCode: typeof code === 'number' ? code : null });
|
||||
}
|
||||
if (!response.ok) throw new Error(`飞书服务返回 HTTP ${response.status}。`);
|
||||
return data as Record<string, unknown>;
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
import { createHmac, randomUUID } from 'node:crypto';
|
||||
import type { Demand } from '../demand.ts';
|
||||
import type { FeishuDelivery, FeishuDeliveryFilter, FeishuStatus } from '../feishu.ts';
|
||||
import { appPath } from '../base-path.ts';
|
||||
import { AuthError } from './auth.ts';
|
||||
import { applicationOrigin, getDatabase } from './database.ts';
|
||||
import { feishuBotConfig, feishuCallbackUrl, feishuJson, feishuLoginConfigured } from './feishu-config.ts';
|
||||
|
||||
const MAX_ATTEMPTS = 5;
|
||||
type NotificationRow = { id: string; target_key: string; content: string; attempts: number; lease_token: string };
|
||||
|
||||
export function signFeishuMessage(timestamp: string, secret: string): string {
|
||||
return createHmac('sha256', `${timestamp}\n${secret}`).update('').digest('base64');
|
||||
}
|
||||
|
||||
/** Must run inside the demand write transaction so failed writes never generate messages. */
|
||||
export function queueDemandNotification(demand: Demand): void {
|
||||
if (demand.status === '草稿') return;
|
||||
// A malformed notification configuration must not prevent saving a business record.
|
||||
let config;
|
||||
try { config = feishuBotConfig(); } catch { return; }
|
||||
if (!config) return;
|
||||
const event = demand.history.at(-1);
|
||||
if (!event) return;
|
||||
const link = applicationOrigin() + appPath('/?demand=' + encodeURIComponent(demand.id));
|
||||
const content = [
|
||||
`需有序 · ${event.action}`, demand.fields.title, `需求:${demand.id} · 第 ${demand.revision} 次保存`,
|
||||
`当前状态:${demand.status}`, `操作人:${event.actor}`,
|
||||
`开发责任人:${demand.review?.developer.displayName || '待分配'}`, `时间:${event.time}`, `查看需求:${link}`,
|
||||
].join('\n');
|
||||
getDatabase().prepare(`INSERT OR IGNORE INTO feishu_notifications (id, demand_id, revision, target_key, content, next_attempt_at, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)`).bind(randomUUID(), demand.id, demand.revision, config.targetKey, content, Date.now(), new Date().toISOString()).run();
|
||||
}
|
||||
|
||||
async function sendText(content: string): Promise<void> {
|
||||
const config = feishuBotConfig();
|
||||
if (!config) throw new Error('尚未配置飞书群机器人。');
|
||||
const timestamp = String(Math.floor(Date.now() / 1000));
|
||||
const result = await feishuJson(config.webhook, {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ msg_type: 'post', content: plainTextPost(content),
|
||||
...(config.secret ? { timestamp, sign: signFeishuMessage(timestamp, config.secret) } : {}) }),
|
||||
});
|
||||
const code = result.code ?? result.StatusCode;
|
||||
if (code !== 0) throw new Error(`飞书机器人拒绝消息(错误码 ${typeof code === 'number' ? code : '未知'}),请检查签名、关键词及 IP 限制。`);
|
||||
}
|
||||
|
||||
/** Typed text nodes cannot execute Feishu's text-message <at> markup, including queued legacy messages. */
|
||||
function plainTextPost(content: string) {
|
||||
const lines = content.split('\n');
|
||||
return { post: { zh_cn: { content: lines.map((line, index) => {
|
||||
const prefix = '查看需求:';
|
||||
if (index === lines.length - 1 && line.startsWith(prefix)) {
|
||||
const href = line.slice(prefix.length);
|
||||
// Only the server-generated final detail link becomes a link node.
|
||||
if (href.startsWith(applicationOrigin() + appPath('/?demand='))) return [{ tag: 'a', text: '查看需求', href }];
|
||||
}
|
||||
return [{ tag: 'text', text: line, un_escape: false }];
|
||||
}) } } };
|
||||
}
|
||||
|
||||
export async function deliverNextFeishuNotification(): Promise<boolean> {
|
||||
let config;
|
||||
try { config = feishuBotConfig(); } catch { return false; }
|
||||
if (!config) return false;
|
||||
const db = getDatabase();
|
||||
const now = Date.now();
|
||||
const row = db.transaction(() => {
|
||||
db.prepare(`UPDATE feishu_notifications SET status = 'failed', lease_token = NULL, last_error = '机器人地址已变更,旧通知已停止发送。'
|
||||
WHERE status IN ('pending','sending') AND target_key != ?`).bind(config.targetKey).run();
|
||||
db.prepare(`UPDATE feishu_notifications SET status = 'failed', lease_token = NULL, last_error = '发送中断且已达到重试上限,请检查后手动重试。'
|
||||
WHERE status = 'sending' AND next_attempt_at <= ? AND attempts >= ?`).bind(now, MAX_ATTEMPTS).run();
|
||||
const candidate = db.prepare(`SELECT id FROM feishu_notifications WHERE status IN ('pending','sending') AND next_attempt_at <= ?
|
||||
AND target_key = ? ORDER BY created_at ASC LIMIT 1`).bind(now, config.targetKey).first<{ id: string }>();
|
||||
if (!candidate) return null;
|
||||
const lease = randomUUID();
|
||||
db.prepare(`UPDATE feishu_notifications SET status = 'sending', attempts = attempts + 1, lease_token = ?, next_attempt_at = ? WHERE id = ?`)
|
||||
.bind(lease, now + 60_000, candidate.id).run();
|
||||
return db.prepare('SELECT * FROM feishu_notifications WHERE id = ?').bind(candidate.id).first<NotificationRow>();
|
||||
});
|
||||
if (!row) return false;
|
||||
try {
|
||||
await sendText(row.content);
|
||||
db.prepare(`UPDATE feishu_notifications SET status = 'sent', sent_at = ?, last_error = NULL, lease_token = NULL WHERE id = ? AND lease_token = ?`)
|
||||
.bind(new Date().toISOString(), row.id, row.lease_token).run();
|
||||
} catch (error) {
|
||||
// Fetch/network errors can contain a secret URL; retain only our known, sanitized messages.
|
||||
const message = error instanceof Error && /^飞书(服务返回 HTTP \d+。|机器人拒绝消息(错误码 (\d+|未知)))/.test(error.message)
|
||||
? error.message : '飞书消息发送失败或超时,请检查网络和机器人配置。';
|
||||
db.prepare(`UPDATE feishu_notifications SET status = ?, last_error = ?, lease_token = NULL, next_attempt_at = ? WHERE id = ? AND lease_token = ?`)
|
||||
.bind(row.attempts >= MAX_ATTEMPTS ? 'failed' : 'pending', message, Date.now() + Math.min(30_000 * 2 ** (row.attempts - 1), 15 * 60_000), row.id, row.lease_token).run();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
type DeliveryCursor = { createdAt: string; id: string };
|
||||
export type FeishuDeliveryQuery = { filter: FeishuDeliveryFilter; cursor: DeliveryCursor | null };
|
||||
export function parseFeishuDeliveryQuery(params: URLSearchParams): FeishuDeliveryQuery {
|
||||
const filter = params.get('filter') || 'all';
|
||||
if (filter !== 'all' && filter !== 'failed') throw new AuthError('通知筛选条件无效。');
|
||||
const encoded = params.get('cursor');
|
||||
let cursor: DeliveryCursor | null = null;
|
||||
if (encoded) {
|
||||
try {
|
||||
if (encoded.length > 512 || !/^[A-Za-z0-9_-]+$/.test(encoded)) throw new Error();
|
||||
const value: unknown = JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8'));
|
||||
if (!value || typeof value !== 'object' || !('createdAt' in value) || !('id' in value) ||
|
||||
typeof value.createdAt !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value.createdAt) ||
|
||||
!Number.isFinite(Date.parse(value.createdAt)) || typeof value.id !== 'string' || !/^[A-Za-z0-9-]{1,128}$/.test(value.id)) throw new Error();
|
||||
cursor = { createdAt: value.createdAt, id: value.id };
|
||||
} catch { throw new AuthError('通知分页参数无效,请返回第一页后重试。'); }
|
||||
}
|
||||
return { filter, cursor };
|
||||
}
|
||||
|
||||
export function feishuStatus(query: FeishuDeliveryQuery = { filter: 'all', cursor: null }): FeishuStatus {
|
||||
let config = null;
|
||||
let configurationError = null;
|
||||
try { config = feishuBotConfig(); } catch (error) { configurationError = (error as Error).message; }
|
||||
if (Boolean(process.env.FEISHU_APP_ID?.trim()) !== Boolean(process.env.FEISHU_APP_SECRET?.trim())) configurationError = '飞书登录需要同时配置 App ID 和 App Secret。';
|
||||
const conditions: string[] = [];
|
||||
const bindings: string[] = [];
|
||||
if (query.filter === 'failed') conditions.push("status = 'failed'");
|
||||
if (query.cursor) {
|
||||
conditions.push('(created_at < ? OR (created_at = ? AND id < ?))');
|
||||
bindings.push(query.cursor.createdAt, query.cursor.createdAt, query.cursor.id);
|
||||
}
|
||||
const rows = getDatabase().prepare(`SELECT id, demand_id AS demandId, revision, status, attempts, last_error AS lastError, created_at AS createdAt, sent_at AS sentAt
|
||||
FROM feishu_notifications ${conditions.length ? 'WHERE ' + conditions.join(' AND ') : ''}
|
||||
ORDER BY created_at DESC, id DESC LIMIT 51`).bind(...bindings).all<FeishuDelivery>().results;
|
||||
const deliveries = rows.slice(0, 50).map(row => ({ ...row }));
|
||||
const last = deliveries.at(-1);
|
||||
return {
|
||||
loginConfigured: feishuLoginConfigured(), callbackUrl: feishuCallbackUrl(), tenantRestricted: Boolean(process.env.FEISHU_TENANT_KEY?.trim()),
|
||||
botConfigured: Boolean(config), botSigned: Boolean(config?.secret), configurationError,
|
||||
deliveries, deliveryFilter: query.filter,
|
||||
nextCursor: rows.length > 50 && last ? Buffer.from(JSON.stringify({ createdAt: last.createdAt, id: last.id })).toString('base64url') : null,
|
||||
failedCount: getDatabase().prepare("SELECT COUNT(*) AS count FROM feishu_notifications WHERE status = 'failed'").first<{ count: number }>()!.count,
|
||||
};
|
||||
}
|
||||
|
||||
export function retryFeishuNotification(id: unknown): void {
|
||||
if (typeof id !== 'string' || id.length > 128) throw new AuthError('通知编号无效。');
|
||||
const config = feishuBotConfig();
|
||||
if (!config) throw new AuthError('请先配置群机器人。');
|
||||
const result = getDatabase().prepare(`UPDATE feishu_notifications SET status = 'pending', attempts = 0, next_attempt_at = ?, last_error = NULL
|
||||
WHERE id = ? AND status = 'failed' AND target_key = ?`).bind(Date.now(), id, config.targetKey).run();
|
||||
if (!result.meta.changes) throw new AuthError('只能重试当前机器人发送失败的通知。', 409);
|
||||
}
|
||||
|
||||
export async function testFeishuBot(): Promise<void> {
|
||||
if (!feishuBotConfig()) throw new AuthError('请先配置群机器人。');
|
||||
const db = getDatabase();
|
||||
db.transaction(() => {
|
||||
const last = db.prepare("SELECT window_start FROM login_limits WHERE key = 'feishu-bot-test'").first<{ window_start: number }>();
|
||||
if (last && Date.now() - last.window_start < 30_000) throw new AuthError('测试消息每 30 秒可发送一次。', 429);
|
||||
db.prepare("INSERT OR REPLACE INTO login_limits (key, window_start, attempts) VALUES ('feishu-bot-test', ?, 1)").bind(Date.now()).run();
|
||||
});
|
||||
try { await sendText('需有序 · 飞书群机器人连接测试\n收到此消息表示通知通道已连通。'); }
|
||||
catch { throw new AuthError('测试消息未确认发送成功,请检查 Webhook、签名、关键词、IP 限制及服务器网络。', 502); }
|
||||
}
|
||||
|
||||
let workerStarted = false;
|
||||
export function startFeishuNotificationWorker(): void {
|
||||
if (workerStarted || !process.env.FEISHU_BOT_WEBHOOK?.trim()) return;
|
||||
workerStarted = true;
|
||||
let busy = false;
|
||||
const tick = async () => {
|
||||
if (busy) return;
|
||||
busy = true;
|
||||
try { await deliverNextFeishuNotification(); }
|
||||
catch { console.error('Feishu notification worker could not access the notification queue.'); }
|
||||
finally { busy = false; }
|
||||
};
|
||||
const timer = setInterval(() => { void tick(); }, 3000);
|
||||
timer.unref();
|
||||
void tick();
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { randomBytes, scrypt as nativeScrypt, scryptSync, timingSafeEqual } from 'node:crypto';
|
||||
|
||||
const COST = 32768;
|
||||
const OPTIONS = { N: COST, r: 8, p: 1, maxmem: 64 * 1024 * 1024 };
|
||||
const KEY_LENGTH = 64;
|
||||
|
||||
// A nonempty, invalid hash also rejects password login on older compatible releases.
|
||||
export const PASSWORD_LOGIN_DISABLED = '!feishu-only';
|
||||
export function hasStoredPassword(hash: string | undefined): boolean {
|
||||
return Boolean(hash) && hash !== PASSWORD_LOGIN_DISABLED;
|
||||
}
|
||||
|
||||
export function validatePassword(password: unknown): asserts password is string {
|
||||
if (typeof password !== 'string' || password.length < 12 || password.length > 128) {
|
||||
throw new Error('密码须为 12–128 个字符。');
|
||||
}
|
||||
}
|
||||
|
||||
function derive(password: string, salt: Buffer): Promise<Buffer> {
|
||||
return new Promise((resolve, reject) => {
|
||||
nativeScrypt(password, salt, KEY_LENGTH, OPTIONS, (error, key) => error ? reject(error) : resolve(key));
|
||||
});
|
||||
}
|
||||
|
||||
function encode(salt: Buffer, key: Buffer): string {
|
||||
return `scrypt$${COST}$8$1$${salt.toString('hex')}$${key.toString('hex')}`;
|
||||
}
|
||||
|
||||
export async function hashPassword(password: string): Promise<string> {
|
||||
validatePassword(password);
|
||||
const salt = randomBytes(16);
|
||||
return encode(salt, await derive(password, salt));
|
||||
}
|
||||
|
||||
// Only used once while bootstrapping an empty database, within the startup transaction.
|
||||
export function hashPasswordSync(password: string): string {
|
||||
validatePassword(password);
|
||||
const salt = randomBytes(16);
|
||||
return encode(salt, scryptSync(password, salt, KEY_LENGTH, OPTIONS));
|
||||
}
|
||||
|
||||
export async function verifyPassword(password: string, encoded: string): Promise<boolean> {
|
||||
if (typeof password !== 'string' || password.length > 128) return false;
|
||||
const parts = encoded.split('$');
|
||||
if (parts.length !== 6 || parts[0] !== 'scrypt' || parts[1] !== String(COST) || parts[2] !== '8' || parts[3] !== '1') return false;
|
||||
if (!/^[a-f0-9]{32}$/.test(parts[4]) || !/^[a-f0-9]{128}$/.test(parts[5])) return false;
|
||||
const key = await derive(password, Buffer.from(parts[4], 'hex'));
|
||||
return timingSafeEqual(key, Buffer.from(parts[5], 'hex'));
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { z } from 'zod';
|
||||
import type { Demand } from '../demand.ts';
|
||||
import { currentProposal, type ReviewPerson } from '../demand-review.ts';
|
||||
import { changeKey, latestRelease, pendingChange, pendingRecovery, pendingEmergencyVerification, activeIncident, designConfirmed, planConfirmed, unresolvedDefects, type DeliveryPlan, type Release } from '../workflow.ts';
|
||||
import { AuthError, type AuthUser } from './auth.ts';
|
||||
|
||||
export const workflowActions = new Set(['propose-plan','decide-plan','submit-design','decide-design','start-development','update-progress','set-blocker','resolve-blocker','add-note','submit-testing','withdraw-testing','accept','change','assess-change','decide-change','withdraw-change','report-defect','start-defect','resolve-defect','verify-defect','defer-defect','decide-deferral','publish','publish-emergency','verify-emergency','withdraw-recovery','verify-production','request-recovery','decide-recovery','rollback','complete','reopen-incident','retrospective']);
|
||||
const ownerActions = new Set(['decide-plan','decide-design','accept','change','decide-change','withdraw-change','verify-defect','decide-deferral','decide-recovery','verify-emergency']);
|
||||
const sharedActions = new Set(['set-blocker','resolve-blocker','add-note','report-defect']);
|
||||
const dateSchema = z.string().regex(/^\d{4}-\d{2}-\d{2}$/).refine(s => !Number.isNaN(Date.parse(s)) && new Date(s).toISOString().slice(0,10) === s);
|
||||
const planSchema = z.object({ hours:z.number().positive().max(10000), testDate:dateSchema, feedbackDate:dateSchema, releaseDate:dateSchema, priority:z.enum(['P0','P1','P2']), designRequired:z.boolean(), notes:z.string().trim().min(1).max(3000) }).refine(p=>p.testDate<=p.feedbackDate&&p.feedbackDate<=p.releaseDate);
|
||||
const checklistSchema = z.array(z.object({id:z.string().trim().min(1).max(30),feature:z.string().trim().min(1).max(200),scenario:z.string().trim().min(1).max(2000),expected:z.string().trim().min(1).max(2000)})).min(1).max(100).refine(rows=>new Set(rows.map(x=>x.id)).size===rows.length);
|
||||
const person = (user:AuthUser):ReviewPerson => ({userId:user.userId,username:user.username,displayName:user.displayName});
|
||||
function text(body:Record<string,unknown>,key:string,label:string,max=5000):string {const value=body[key];if(typeof value!=='string'||!value.trim()||value.length>max)throw new AuthError(`请填写${label}(${max}字以内)。`);return value.trim();}
|
||||
function bool(body:Record<string,unknown>,key:string):boolean {if(typeof body[key]!=='boolean')throw new AuthError('请明确选择处理结果。');return body[key] as boolean;}
|
||||
function confirm(body:Record<string,unknown>){if(body.confirm!==true)throw new AuthError('请勾选确认后提交。');}
|
||||
function date(body:Record<string,unknown>,key:string,label:string){const result=dateSchema.safeParse(body[key]);if(!result.success)throw new AuthError(`请填写有效的${label}。`);return result.data;}
|
||||
function state(d:Demand,allowed:string[]){if(!allowed.includes(d.status))throw new AuthError(`当前处于“${d.status}”,不能执行该操作。`,409);}
|
||||
function solution(d:Demand){const p=currentProposal(d);if(!d.reviewReady||!p||p.invalidated||p.decision?.result!=='confirmed')throw new AuthError('请先完成当前版本的方案评审与业务确认。',409);return p;}
|
||||
function forward(d:Demand){if(pendingChange(d))throw new AuthError('存在待处理需求变更,请先完成评估与确认。',409);if(d.blocked)throw new AuthError('需求处于阻塞状态,请先记录处理结果并解除阻塞。',409);}
|
||||
function planned(d:Demand){solution(d);if(!planConfirmed(d))throw new AuthError('请先由业务方确认当前方案的交付计划。',409);}
|
||||
function readPlan(d:Demand,body:Record<string,unknown>,user:AuthUser,now:string):DeliveryPlan {const result=planSchema.safeParse(body);if(!result.success)throw new AuthError('请完整填写交付计划;工作量须大于 0,提测日期 ≤ 验收反馈截止日期 ≤ 上线日期。');return {...result.data,developer:d.review!.developer.displayName,version:(d.plan?.version??0)+1,proposalVersion:currentProposal(d)!.version,proposedBy:person(user),proposedAt:now};}
|
||||
function archivePlan(d:Demand){if(d.plan){d.delivery??={};d.delivery.plans??=[];d.delivery.plans.push(structuredClone(d.plan));}}
|
||||
function withdrawAcceptance(d:Demand,now:string){if(!d.acceptance)return;d.acceptance.withdrawnAt=now;const round=d.delivery?.testing?.find(x=>x.round===d.acceptance?.round);if(round)round.withdrawnAt=now;}
|
||||
function exactAcceptance(d:Demand){const a=d.acceptance;const r=d.acceptanceRecords?.at(-1);if(!a||a.withdrawnAt||!r?.passed||r.version!==d.fields.version||r.testVersion!==a.testVersion||(r.round??0)!==(a.round??0))throw new AuthError('当前交付版本尚未通过业务验收,请重新提测并确认。',409);return a;}
|
||||
|
||||
export function applyWorkflowAction(d:Demand,ownerId:string,user:AuthUser,body:Record<string,unknown>,now:string):{label:string;detail:string} {
|
||||
const action=String(body.action);if(!workflowActions.has(action))throw new AuthError('不支持的流程操作。');
|
||||
const business=user.userId===ownerId,developer=user.userId===d.review?.developer.userId;
|
||||
if(ownerActions.has(action)?!business:sharedActions.has(action)?!business&&!developer:!developer)throw new AuthError('仅当前需求的对应责任人可以执行此操作。',403);
|
||||
if(['草稿','已取消'].includes(d.status))throw new AuthError('草稿或已取消需求不能执行交付操作。',409);
|
||||
if(d.status==='已完成'&&!['report-defect','start-defect','resolve-defect','verify-defect','defer-defect','decide-deferral','request-recovery','decide-recovery','withdraw-recovery','verify-emergency','rollback','reopen-incident','retrospective','add-note'].includes(action))throw new AuthError('需求已归档;线上故障请登记紧急修复,独立新目标请另行登记。',409);
|
||||
d.delivery??={};const flow=d.delivery,actor=person(user);
|
||||
const result=(label:string,detail:string)=>({label,detail});
|
||||
if(action==='propose-plan'){
|
||||
state(d,['待评审','已排期','开发中']);solution(d);if(pendingChange(d))throw new AuthError('请先处理当前需求变更。',409);
|
||||
const plan=readPlan(d,body,user,now);archivePlan(d);d.plan=plan;
|
||||
return result('提出交付计划',`计划 v${plan.version};${plan.hours} 小时,提测 ${plan.testDate},验收反馈 ${plan.feedbackDate},上线 ${plan.releaseDate};等待业务方确认。`);
|
||||
}
|
||||
if(action==='decide-plan'){
|
||||
state(d,['待评审','已排期','开发中']);solution(d);if(pendingChange(d))throw new AuthError('请先处理当前需求变更。',409);
|
||||
if(!d.plan?.proposedAt||d.plan.decision||body.planVersion!==d.plan.version||d.plan.proposalVersion!==currentProposal(d)!.version)throw new AuthError('计划版本已变化或已处理,请刷新核对。',409);
|
||||
const approved=bool(body,'approved');confirm(body);const comment=text(body,'comment','排期确认意见',3000);
|
||||
d.plan.decision={actor,time:now,approved,comment};
|
||||
if(approved){d.fields.priority=d.plan.priority!;if(d.status==='待评审')d.status='已排期';}
|
||||
return result(approved?'确认交付计划':'退回交付计划',`计划 v${d.plan.version};${comment}`);
|
||||
}
|
||||
if(action==='submit-design'){
|
||||
state(d,['已排期','开发中']);planned(d);forward(d);
|
||||
if(!d.plan?.designRequired)throw new AuthError('当前计划不要求设计确认。',409);
|
||||
if(flow.design){flow.designHistory??=[];flow.designHistory.push(structuredClone(flow.design));}
|
||||
flow.design={reference:text(body,'reference','设计稿或交互说明链接'),notes:text(body,'notes','设计版本与说明'),actor,time:now,proposalVersion:currentProposal(d)!.version};
|
||||
return result('提交设计确认',flow.design.reference+';'+flow.design.notes);
|
||||
}
|
||||
if(action==='decide-design'){
|
||||
state(d,['已排期','开发中']);planned(d);forward(d);if(!flow.design||flow.design.decision||flow.design.proposalVersion!==currentProposal(d)!.version)throw new AuthError('当前没有待确认设计。',409);
|
||||
confirm(body);const approved=bool(body,'approved');flow.design.decision={actor,time:now,approved,comment:text(body,'comment','设计确认意见')};
|
||||
return result(approved?'确认设计':'退回设计',flow.design.decision.comment);
|
||||
}
|
||||
if(action==='start-development'){
|
||||
state(d,['已排期']);planned(d);forward(d);
|
||||
if(d.plan!.designRequired&&!designConfirmed(d))throw new AuthError('请先由业务方确认当前方案的设计版本。',409);
|
||||
confirm(body);flow.kickoff={actor,time:now,technicalPlan:text(body,'technicalPlan','技术方案与代码分支'),dependencies:text(body,'dependencies','依赖、接口与开发准入检查'),design:flow.design?.reference||'计划已确认无需单独设计'};
|
||||
d.status='开发中';flow.progress={percent:0,notes:'已开始开发',next:'完成开发、自测及代码审查',time:now,actor};
|
||||
return result('开始开发',flow.kickoff.technicalPlan+';'+flow.kickoff.dependencies);
|
||||
}
|
||||
if(action==='update-progress'){
|
||||
state(d,['开发中']);if(typeof body.percent!=='number'||!Number.isInteger(body.percent)||body.percent<0||body.percent>100)throw new AuthError('进度须为 0–100 的整数。');
|
||||
flow.progress={percent:body.percent,notes:text(body,'notes','进度说明'),next:text(body,'next','下一步及预计完成时间'),time:now,actor};
|
||||
return result('更新开发进度',`${body.percent}%:${flow.progress.notes};下一步:${flow.progress.next}`);
|
||||
}
|
||||
if(action==='set-blocker'){
|
||||
if(!['业务方','开发责任人'].includes(String(body.owner))||(body.owner==='开发责任人'&&!d.review))throw new AuthError('请选择阻塞处理责任人。');
|
||||
flow.blocker={reason:text(body,'reason','阻塞原因'),owner:String(body.owner),dueDate:date(body,'dueDate','跟进日期'),time:now,actor};d.blocked=flow.blocker.reason;
|
||||
return result('标记阻塞',`${flow.blocker.reason};${flow.blocker.owner},跟进日期 ${flow.blocker.dueDate}`);
|
||||
}
|
||||
if(action==='resolve-blocker'){
|
||||
if(!d.blocked)throw new AuthError('当前没有阻塞事项。',409);const notes=text(body,'notes','阻塞处理结果');delete flow.blocker;delete d.blocked;return result('解除阻塞',notes);
|
||||
}
|
||||
if(action==='add-note')return result('补充协作记录',text(body,'notes','进展、沟通结论或资料链接'));
|
||||
if(action==='submit-testing'){
|
||||
state(d,['开发中']);planned(d);forward(d);
|
||||
if(d.plan?.designRequired&&!designConfirmed(d))throw new AuthError('请先确认当前设计版本。',409);
|
||||
if(unresolvedDefects(d).some(x=>x.blocking&&['待处理','修复中','待确认遗留'].includes(x.status)))throw new AuthError('仍有未修复的阻断缺陷,请先修复后提测。',409);
|
||||
const parsed=checklistSchema.safeParse(body.items);if(!parsed.success)throw new AuthError('请填写 1–100 条完整且编号唯一的验收项。');
|
||||
const testVersion=text(body,'testVersion','测试版本或提交号',100);if(flow.testing?.some(x=>x.testVersion===testVersion))throw new AuthError('该测试版本已提测,请使用可追溯的新版本或提交号。',409);
|
||||
const environment=text(body,'environment','测试环境地址',2000);try{const u=new URL(environment);if(!['http:','https:'].includes(u.protocol)||u.username||u.password)throw new Error();}catch{throw new AuthError('测试环境须为不含账号密码的 HTTP 或 HTTPS 地址。');}
|
||||
confirm(body);const a={testVersion,environment,deadline:date(body,'deadline','验收截止日期'),items:parsed.data,instructions:text(body,'instructions','操作及测试数据说明'),selfTest:text(body,'selfTest','自测结果'),codeReview:text(body,'codeReview','代码审查结论与记录'),integration:text(body,'integration','集成验证与已知问题'),round:(flow.testing?.length??0)+1,documentVersion:d.fields.version,actor,time:now};
|
||||
d.acceptance=a;flow.testing??=[];flow.testing.push(structuredClone(a));d.status='待验收';
|
||||
return result('提交业务验收',`第 ${a.round} 轮,测试版本 ${a.testVersion};文档 ${d.fields.version};${a.items.length} 项,截止 ${a.deadline}。`);
|
||||
}
|
||||
if(action==='withdraw-testing'){
|
||||
state(d,['待验收','待发布']);const reason=text(body,'reason','撤回提测原因');withdrawAcceptance(d,now);d.status='开发中';return result('撤回交付版本',reason+';原验收记录保留,重新提测后需重新验收。');
|
||||
}
|
||||
if(action==='accept'){
|
||||
state(d,['待验收']);forward(d);const a=d.acceptance;if(!a||a.withdrawnAt)throw new AuthError('当前没有有效验收清单。',409);
|
||||
if(body.testVersion!==a.testVersion||body.version!==d.fields.version||(a.documentVersion&&a.documentVersion!==d.fields.version)||(a.round&&body.round!==a.round))throw new AuthError('验收版本已变化,请刷新核对。',409);
|
||||
const values=body.results;if(!Array.isArray(values)||values.length!==a.items.length||!values.length||values.some(x=>!['通过','不通过'].includes(x)))throw new AuthError('请逐项填写验收结果。');
|
||||
confirm(body);const notes=text(body,'notes','遗留问题、证据及处理计划');const passed=values.every(x=>x==='通过');
|
||||
if(passed&&unresolvedDefects(d).some(x=>x.blocking))throw new AuthError('阻断缺陷尚未复验关闭,不能确认验收通过。',409);
|
||||
d.acceptanceRecords??=[];d.acceptanceRecords.push({time:now,actor:user.displayName,version:d.fields.version,testVersion:a.testVersion,round:a.round,results:values,notes,passed,items:a.items.map((item,i)=>({...item,result:values[i]})),environment:a.environment});d.status=passed?'待发布':'开发中';
|
||||
return result(passed?'业务验收通过':'业务验收未通过',`测试 ${a.testVersion} / 文档 ${d.fields.version};${notes}`);
|
||||
}
|
||||
if(action==='change'){
|
||||
state(d,['已排期','开发中','待验收','待发布','已上线']);if(pendingChange(d))throw new AuthError('请先处理已有变更,避免并行改写范围。',409);
|
||||
const content=text(body,'content','变更内容'),reason=text(body,'reason','变更原因',3000);
|
||||
d.changes.push({id:randomUUID(),time:now,content,reason,actor:user.displayName,status:'待开发评估',originalVersion:d.fields.version,originalFields:structuredClone(d.fields),originalStatus:d.status});
|
||||
return result('提出需求变更',content+';'+reason+'。后续流转暂停,等待开发评估与业务确认。');
|
||||
}
|
||||
if(['assess-change','decide-change','withdraw-change'].includes(action)){
|
||||
const c=pendingChange(d);if(!c||changeKey(d,c)!==body.changeId)throw new AuthError('待处理变更已变化,请刷新。',409);
|
||||
if(action==='withdraw-change'){c.status='已撤回';c.decision={actor,time:now,approved:false,comment:text(body,'comment','撤回原因')};return result('撤回需求变更',c.decision.comment);}
|
||||
if(action==='assess-change'){
|
||||
if(c.status==='待业务确认')throw new AuthError('评估已提交,等待业务方确认。',409);solution(d);
|
||||
const version=text(body,'version','变更后文档版本',100);if(version===d.fields.version)throw new AuthError('变更后须使用新的文档版本。');
|
||||
c.assessment={time:now,actor,impact:text(body,'impact','工作量、风险及依赖影响'),fields:{...d.fields,scope:text(body,'scope','调整后实施范围',6000),outOfScope:text(body,'outOfScope','调整后范围外事项',3000),criteria:text(body,'criteria','调整后验收标准',6000),version},plan:readPlan(d,body,user,now)};c.status='待业务确认';
|
||||
return result('提交变更评估',c.assessment.impact+';调整后版本 '+version+',等待业务方确认。');
|
||||
}
|
||||
if(!c.assessment||c.status!=='待业务确认')throw new AuthError('请先由开发责任人提交变更评估。',409);
|
||||
confirm(body);const approved=bool(body,'approved');c.decision={actor,time:now,approved,comment:text(body,'comment','变更确认意见')};c.status=approved?'已确认':'已拒绝';
|
||||
if(approved){
|
||||
solution(d);archivePlan(d);d.fields=structuredClone(c.assessment.fields);d.fields.priority=c.assessment.plan.priority!;const version=(currentProposal(d)?.version??0)+1;
|
||||
d.review!.proposals.push({version,scope:d.fields.scope,outOfScope:d.fields.outOfScope,developer:c.assessment.actor,submittedAt:c.assessment.time,businessFields:structuredClone(d.fields),businessAttachments:structuredClone(d.attachments??[]),decision:{result:'confirmed',actor,time:now,comment:'业务确认变更:'+c.decision.comment}});
|
||||
d.plan={...c.assessment.plan,proposalVersion:version,decision:c.decision};d.fields.priority=d.plan.priority!;d.status='已排期';withdrawAcceptance(d,now);delete d.acceptance;delete flow.kickoff;delete flow.progress;
|
||||
}
|
||||
return result(approved?'确认需求变更':'拒绝需求变更',c.decision.comment+(approved?';范围及计划已同步,重新开发并提测验收。':';原范围及计划继续有效。'));
|
||||
}
|
||||
if(action==='report-defect'){
|
||||
const defect={id:'DEF-'+randomUUID().slice(0,8).toUpperCase(),title:text(body,'title','缺陷标题',200),steps:text(body,'steps','复现步骤'),expected:text(body,'expected','预期结果'),actual:text(body,'actual','实际结果'),evidence:text(body,'evidence','证据或日志链接'),version:text(body,'version','发现版本',100),blocking:bool(body,'blocking'),reporter:actor,time:now,status:'待处理' as const,events:[]};flow.defects??=[];flow.defects.push(defect);
|
||||
return result('登记缺陷',`${defect.id} ${defect.title};${defect.blocking?'阻断交付':'一般问题'}。`);
|
||||
}
|
||||
if(['start-defect','resolve-defect','verify-defect','defer-defect','decide-deferral'].includes(action)){
|
||||
const defect=flow.defects?.find(x=>x.id===body.defectId);if(!defect)throw new AuthError('找不到该缺陷。',404);
|
||||
const notes=text(body,'notes','处理说明');let label='';
|
||||
if(action==='start-defect'){if(!['待处理','已确认遗留'].includes(defect.status))throw new AuthError('该缺陷不在待处理状态。',409);defect.status='修复中';label='开始修复缺陷';}
|
||||
if(action==='resolve-defect'){if(!['待处理','修复中','已确认遗留'].includes(defect.status))throw new AuthError('该缺陷不能重复提交修复。',409);defect.resolution=notes;defect.fixVersion=text(body,'fixVersion','修复版本',100);defect.status='待复验';label='提交缺陷复验';if(['待验收','待发布','已上线','已完成'].includes(d.status)){if(['已上线','已完成'].includes(d.status)){flow.incidents??=[];flow.incidents.push({id:randomUUID(),time:now,actor,impact:defect.title,reason:notes,releaseId:latestRelease(d)?.id});}d.status='开发中';withdrawAcceptance(d,now);}}
|
||||
if(action==='verify-defect'){if(defect.status!=='待复验')throw new AuthError('请先由开发提交缺陷修复。',409);confirm(body);const passed=bool(body,'approved');defect.status=passed?'已关闭':'修复中';label=passed?'复验关闭缺陷':'缺陷复验未通过';}
|
||||
if(action==='defer-defect'){if(defect.blocking||!['待处理','修复中'].includes(defect.status))throw new AuthError('仅未处理的一般缺陷可以申请遗留,阻断缺陷必须修复。',409);defect.resolution=notes;defect.dueDate=date(body,'dueDate','遗留问题计划完成日期');defect.status='待确认遗留';label='申请保留一般缺陷';}
|
||||
if(action==='decide-deferral'){if(defect.status!=='待确认遗留'||defect.blocking)throw new AuthError('当前没有可确认的遗留申请。',409);confirm(body);const approved=bool(body,'approved');defect.status=approved?'已确认遗留':'修复中';label=approved?'确认遗留问题计划':'拒绝遗留申请';}
|
||||
defect.events.push({time:now,actor,action:label,notes});return result(label,`${defect.id};${notes}${action==='resolve-defect'?';修复后请使用新的测试版本重新提测。':''}`);
|
||||
}
|
||||
if(action==='publish'||action==='publish-emergency'){
|
||||
const urgent=action==='publish-emergency';
|
||||
state(d,urgent?['开发中','待验收','待发布']:['待发布']);forward(d);
|
||||
if(pendingRecovery(d))throw new AuthError('存在待处理的数据恢复申请,请先确认或撤回,再登记新发布。',409);
|
||||
let version:string,acceptanceRound=0,emergency:Release['emergency'];
|
||||
if(urgent){
|
||||
const base=latestRelease(d),incident=activeIncident(d),proposal=solution(d);
|
||||
if(!base||!incident)throw new AuthError('请先针对已有线上版本登记故障并启动修复。',409);
|
||||
if(base.documentVersion!==d.fields.version||base.proposalVersion!==proposal.version)throw new AuthError('当前范围或方案已变化,请完成常规业务验收后发布。',409);
|
||||
for(const key of ['businessRulesUnchanged','scopeUnchanged','noIrreversibleData'])if(body[key]!==true)throw new AuthError('紧急入口仅适用于业务规则及范围不变、且不涉及不可逆数据处理的修复;其他情况须先完成业务确认与常规验收。',409);
|
||||
if(unresolvedDefects(d).some(x=>x.blocking&&x.status!=='待复验'))throw new AuthError('阻断缺陷仍未修复,不能紧急发布。',409);
|
||||
version=text(body,'version','紧急发布版本',100);
|
||||
if(flow.releases?.some(r=>r.version===version)||d.acceptanceRecords?.some(r=>r.testVersion===version&&!r.passed))throw new AuthError('请使用新的、未被业务验收判定不通过的修复版本。',409);
|
||||
const followUpDate=date(body,'followUpDate','后续业务验证日期');
|
||||
if(followUpDate<new Date(now).toLocaleDateString('sv-SE',{timeZone:'Asia/Shanghai'}))throw new AuthError('后续业务验证日期不能早于今天。');
|
||||
emergency={incidentId:incident.id,reason:text(body,'emergencyReason','紧急发布原因'),fixSummary:text(body,'fixSummary','修复内容及影响评估'),selfTest:text(body,'selfTest','自测与关键流程验证'),codeReview:text(body,'codeReview','代码审查及确认记录'),integration:text(body,'integration','构建、集成及关联回归记录'),knownIssues:text(body,'knownIssues','已知问题及风险处理'),followUpPlan:text(body,'followUpPlan','修复同步、记录补充及后续业务验证安排'),followUpDate};
|
||||
}else{
|
||||
planned(d);const a=exactAcceptance(d);
|
||||
if(unresolvedDefects(d).length)throw new AuthError('存在未关闭或未经业务确认的遗留缺陷,不能发布。',409);
|
||||
if(body.version!==a.testVersion)throw new AuthError('发布版本必须与已验收的测试版本一致。',409);
|
||||
version=a.testVersion;acceptanceRound=a.round??0;
|
||||
}
|
||||
for(const key of ['testsPassed','configurationReady','recoveryReady','noticeComplete'])if(body[key]!==true)throw new AuthError('请逐项完成发布前检查。');confirm(body);
|
||||
const observationMinutes=body.observationMinutes;if(typeof observationMinutes!=='number'||!Number.isInteger(observationMinutes)||observationMinutes<15||observationMinutes>10080)throw new AuthError('观察时长须为 15–10080 分钟。');
|
||||
const release:Release={id:randomUUID(),version,previousVersion:text(body,'previousVersion','上一稳定版本',100),time:now,actor,acceptanceRound,documentVersion:d.fields.version,proposalVersion:currentProposal(d)!.version,rollbackPlan:text(body,'rollbackPlan','回滚与恢复方案'),backup:text(body,'backup','备份与数据库兼容性检查'),deployment:text(body,'deployment','实际发布操作及结果'),verificationPlan:text(body,'verificationPlan','生产验证与监控方式'),observationMinutes,observeUntil:new Date(Date.parse(now)+observationMinutes*60000).toISOString(),...(emergency?{emergency}:{})};
|
||||
if(urgent)withdrawAcceptance(d,now);
|
||||
flow.releases??=[];flow.releases.push(release);d.status='已上线';return result(urgent?'登记紧急生产发布':'登记生产发布',`版本 ${release.version};观察至 ${release.observeUntil};${release.deployment}${emergency?';待业务方于 '+emergency.followUpDate+' 前补充验证。':''}`);
|
||||
}
|
||||
if(action==='verify-emergency'){
|
||||
const release=flow.releases?.find(r=>r.id===body.releaseId);
|
||||
if(!release?.emergency||release.rollback||release.emergency.followUp)throw new AuthError('该紧急发布没有待补充的业务验证,请刷新核对。',409);
|
||||
confirm(body);const approved=bool(body,'approved'),comment=text(body,'comment','业务验证结果与证据');
|
||||
release.emergency.followUp={actor,time:now,approved,comment};
|
||||
if(!approved&&release.id===latestRelease(d)?.id&&d.status==='已上线'){
|
||||
d.status='开发中';withdrawAcceptance(d,now);flow.incidents??=[];
|
||||
flow.incidents.push({id:randomUUID(),releaseId:release.id,time:now,actor,impact:'紧急发布业务验证未通过',reason:comment});
|
||||
}
|
||||
return result(approved?'紧急发布业务验证通过':'紧急发布业务验证未通过',`版本 ${release.version};${comment}`);
|
||||
}
|
||||
if(action==='verify-production'){
|
||||
state(d,['已上线']);const release=latestRelease(d);if(!release||release.rollback)throw new AuthError('没有可验证的当前发布版本。',409);
|
||||
confirm(body);release.verification={actor,time:now,passed:bool(body,'approved'),results:text(body,'results','核心功能、数据与监控验证结果')};
|
||||
return result(release.verification.passed?'生产验证通过':'生产验证未通过',`${release.version};${release.verification.results}`);
|
||||
}
|
||||
if(action==='request-recovery'){
|
||||
const release=latestRelease(d);if(!release||release.rollback)throw new AuthError('当前没有可恢复的发布记录。',409);
|
||||
if(pendingRecovery(d))throw new AuthError('已有数据恢复申请,请等待业务确认。',409);
|
||||
release.recoveryRequest={actor,time:now,targetVersion:text(body,'targetVersion','恢复目标版本',100),plan:text(body,'plan','数据恢复及增量保留方案'),dataImpact:text(body,'dataImpact','对现有业务数据的影响')};
|
||||
return result('申请数据恢复确认',`发布 ${release.version} → 恢复目标 ${release.recoveryRequest.targetVersion};${release.recoveryRequest.dataImpact};${release.recoveryRequest.plan}`);
|
||||
}
|
||||
if(action==='decide-recovery'||action==='withdraw-recovery'){
|
||||
const release=body.releaseId?flow.releases?.find(r=>r.id===body.releaseId):pendingRecovery(d),request=release?.recoveryRequest;
|
||||
if(!request||request.decision||request.withdrawn||release?.rollback)throw new AuthError('没有待确认的数据恢复申请。',409);
|
||||
if(action==='withdraw-recovery'){
|
||||
request.withdrawn={actor,time:now,reason:text(body,'reason','撤回恢复申请的原因')};
|
||||
return result('撤回数据恢复申请',`发布 ${release!.version},恢复目标 ${request.targetVersion};${request.withdrawn.reason}`);
|
||||
}
|
||||
confirm(body);const approved=bool(body,'approved');
|
||||
if(approved&&release!.id!==latestRelease(d)?.id)throw new AuthError('原发布已被新版本替代,请退回旧申请后针对当前版本重新申请。',409);
|
||||
request.decision={actor,time:now,approved,comment:text(body,'comment','数据恢复确认意见')};return result(approved?'确认数据恢复方案':'拒绝数据恢复方案',`发布 ${release!.version},恢复目标 ${request.targetVersion};${request.decision.comment}`);
|
||||
}
|
||||
if(action==='rollback'){
|
||||
const release=latestRelease(d);if(!release||release.rollback)throw new AuthError('当前版本已经回滚或没有发布记录。',409);
|
||||
const dataRestored=bool(body,'dataRestored'),runningVersion=text(body,'runningVersion','恢复后的实际运行版本',100);
|
||||
if(dataRestored&&(!release.recoveryRequest?.decision?.approved||release.recoveryRequest.withdrawn||release.recoveryRequest.targetVersion!==runningVersion))throw new AuthError('涉及数据恢复时,须先由业务方确认对应目标版本和增量保留方案。',409);
|
||||
confirm(body);release.rollback={actor,time:now,reason:text(body,'reason','回滚原因与影响'),runningVersion,verification:text(body,'verification','恢复后的验证结果'),dataRestored};if(release.recoveryRequest&&!release.recoveryRequest.decision&&!release.recoveryRequest.withdrawn)release.recoveryRequest.decision={actor,time:now,approved:false,comment:'此次仅回滚代码,未执行数据恢复,原申请已结束。'};if(d.status!=='待评审'&&d.status!=='已排期')d.status='开发中';withdrawAcceptance(d,now);
|
||||
if(!activeIncident(d)){flow.incidents??=[];flow.incidents.push({id:randomUUID(),releaseId:release.id,time:now,actor,impact:release.rollback.reason,reason:'回滚后启动修复'});}
|
||||
return result('登记回滚与恢复',`${release.version} → ${runningVersion};${release.rollback.reason};${release.rollback.verification}。修复后须重新提测验收。`);
|
||||
}
|
||||
if(action==='complete'){
|
||||
state(d,['已上线']);forward(d);const release=latestRelease(d);
|
||||
if(release?.emergency){solution(d);if(!release.emergency.followUp?.approved)throw new AuthError('请先由业务方完成紧急发布后的业务验证。',409);}else{planned(d);exactAcceptance(d);}
|
||||
if(pendingEmergencyVerification(d))throw new AuthError('仍有紧急发布待补充业务验证,请先完成。',409);
|
||||
if(!release||release.rollback||!release.verification?.passed||release.documentVersion!==d.fields.version||(release.proposalVersion!==undefined&&release.proposalVersion!==currentProposal(d)?.version)||(!release.emergency&&release.version!==d.acceptance!.testVersion))throw new AuthError('请先完成当前发布版本的生产验证。',409);
|
||||
if(Date.parse(now)<Date.parse(release.observeUntil))throw new AuthError('尚未达到约定观察结束时间,不能归档完成。',409);
|
||||
if(unresolvedDefects(d).length)throw new AuthError('请先关闭缺陷或完成遗留事项确认。',409);
|
||||
if(pendingRecovery(d))throw new AuthError('请先处理待确认的数据恢复申请。',409);
|
||||
confirm(body);release.completion={actor,time:now,handover:text(body,'handover','交接资料及业务通知记录'),monitoring:text(body,'monitoring','监控、故障联系人和告警渠道'),summary:text(body,'summary','观察结论与交付总结')};d.status='已完成';return result('交付完成并归档',release.completion.summary+';交接:'+release.completion.handover+';监控:'+release.completion.monitoring);
|
||||
}
|
||||
if(action==='reopen-incident'){
|
||||
state(d,['已上线','已完成']);confirm(body);const incident={id:randomUUID(),releaseId:latestRelease(d)?.id,time:now,actor,impact:text(body,'impact','线上故障影响'),reason:text(body,'reason','既有范围内的修复内容')};flow.incidents??=[];flow.incidents.push(incident);d.status='开发中';withdrawAcceptance(d,now);return result('登记线上故障并启动修复',incident.impact+';'+incident.reason+'。原范围不变,修复后重新提测、验收和发布。');
|
||||
}
|
||||
if(action==='retrospective'){
|
||||
const item={time:now,actor,cause:text(body,'cause','原因分析'),actions:text(body,'actions','改进措施'),owner:text(body,'owner','改进责任人',100),dueDate:date(body,'dueDate','改进完成日期')};flow.retrospectives??=[];flow.retrospectives.push(item);return result('记录复盘与改进',`${item.cause};${item.actions};${item.owner},${item.dueDate}`);
|
||||
}
|
||||
throw new AuthError('不支持的流程操作。');
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
import type { Demand, Fields, AcceptanceItem } from './demand.ts';
|
||||
import type { ReviewPerson } from './demand-review.ts';
|
||||
|
||||
export type Decision = { actor: ReviewPerson; time: string; approved: boolean; comment: string };
|
||||
export type DeliveryPlan = {
|
||||
developer: string; testDate: string; releaseDate: string; version?: number;
|
||||
hours?: number; feedbackDate?: string; priority?: Fields['priority']; designRequired?: boolean;
|
||||
notes?: string; proposalVersion?: number; proposedBy?: ReviewPerson; proposedAt?: string; decision?: Decision;
|
||||
};
|
||||
export type ChangeRecord = {
|
||||
id?: string; time: string; content: string; reason: string; actor: string; status: string;
|
||||
originalVersion: string; originalFields?: Fields; originalStatus?: string;
|
||||
assessment?: { time: string; actor: ReviewPerson; impact: string; fields: Fields; plan: DeliveryPlan };
|
||||
decision?: Decision;
|
||||
};
|
||||
export type TestingRound = {
|
||||
testVersion: string; environment: string; deadline: string; items: AcceptanceItem[]; instructions: string;
|
||||
round?: number; documentVersion?: string; selfTest?: string; codeReview?: string; integration?: string;
|
||||
actor?: ReviewPerson; time?: string; withdrawnAt?: string;
|
||||
};
|
||||
export type Defect = {
|
||||
id: string; title: string; steps: string; expected: string; actual: string; evidence: string; version: string;
|
||||
blocking: boolean; reporter: ReviewPerson; time: string;
|
||||
status: '待处理' | '修复中' | '待复验' | '已关闭' | '待确认遗留' | '已确认遗留';
|
||||
resolution?: string; fixVersion?: string; dueDate?: string;
|
||||
events: { time: string; actor: ReviewPerson; action: string; notes: string }[];
|
||||
};
|
||||
export type Release = {
|
||||
id: string; version: string; previousVersion: string; time: string; actor: ReviewPerson;
|
||||
acceptanceRound: number; documentVersion: string; rollbackPlan: string; backup: string; deployment: string;
|
||||
verificationPlan: string; observationMinutes: number; observeUntil: string;
|
||||
proposalVersion?: number;
|
||||
emergency?: { incidentId: string; reason: string; fixSummary: string; selfTest: string; codeReview: string; integration: string; knownIssues: string; followUpPlan: string; followUpDate: string; followUp?: Decision };
|
||||
verification?: { actor: ReviewPerson; time: string; passed: boolean; results: string };
|
||||
recoveryRequest?: { targetVersion: string; plan: string; dataImpact: string; actor: ReviewPerson; time: string; decision?: Decision; withdrawn?: { actor: ReviewPerson; time: string; reason: string } };
|
||||
rollback?: { actor: ReviewPerson; time: string; reason: string; runningVersion: string; verification: string; dataRestored: boolean };
|
||||
completion?: { actor: ReviewPerson; time: string; handover: string; monitoring: string; summary: string };
|
||||
};
|
||||
export type Delivery = {
|
||||
plans?: DeliveryPlan[];
|
||||
design?: { reference: string; notes: string; time: string; actor: ReviewPerson; proposalVersion: number; decision?: Decision };
|
||||
designHistory?: NonNullable<Delivery['design']>[];
|
||||
kickoff?: { actor: ReviewPerson; time: string; technicalPlan: string; dependencies: string; design: string };
|
||||
progress?: { percent: number; notes: string; next: string; time: string; actor: ReviewPerson };
|
||||
blocker?: { reason: string; owner: string; dueDate: string; time: string; actor: ReviewPerson };
|
||||
testing?: TestingRound[];
|
||||
defects?: Defect[];
|
||||
releases?: Release[];
|
||||
incidents?: { id: string; time: string; actor: ReviewPerson; impact: string; reason: string; releaseId?: string }[];
|
||||
retrospectives?: { time: string; actor: ReviewPerson; cause: string; actions: string; owner: string; dueDate: string }[];
|
||||
};
|
||||
export const pendingChange = (d: Demand) => d.changes.find(c => ['待开发评估与双方确认', '待开发评估', '待业务确认'].includes(c.status));
|
||||
export const changeKey = (d: Demand, change: ChangeRecord) => change.id || `legacy-${d.changes.indexOf(change)}`;
|
||||
export const latestRelease = (d: Demand) => d.delivery?.releases?.at(-1);
|
||||
export const pendingRecovery = (d: Demand) => d.delivery?.releases?.find(r => !r.rollback && r.recoveryRequest && !r.recoveryRequest.decision && !r.recoveryRequest.withdrawn);
|
||||
export const pendingEmergencyVerification = (d: Demand) => d.delivery?.releases?.find(r => !r.rollback && r.emergency && !r.emergency.followUp);
|
||||
export const activeIncident = (d: Demand) => d.delivery?.incidents?.findLast(i => i.releaseId === latestRelease(d)?.id);
|
||||
export const designCurrent = (d: Demand) => Boolean(planConfirmed(d) && d.delivery?.design && d.delivery.design.proposalVersion === d.review?.proposals.at(-1)?.version);
|
||||
export const designConfirmed = (d: Demand) => designCurrent(d) && Boolean(d.delivery?.design?.decision?.approved);
|
||||
export function nextAcceptanceId(items: Pick<AcceptanceItem, 'id'>[]): string {
|
||||
const used = new Set(items.map(item => item.id.trim()));
|
||||
let index = 1;
|
||||
while (used.has(`AC-${String(index).padStart(2, '0')}`)) index++;
|
||||
return `AC-${String(index).padStart(2, '0')}`;
|
||||
}
|
||||
export const unresolvedDefects = (d: Demand) => (d.delivery?.defects ?? []).filter(x => !['已关闭', '已确认遗留'].includes(x.status));
|
||||
export const planCurrent = (d: Demand) => Boolean(d.plan && d.plan.proposalVersion === d.review?.proposals.at(-1)?.version && d.review?.proposals.at(-1)?.decision?.result === 'confirmed' && !d.review?.proposals.at(-1)?.invalidated);
|
||||
export const planConfirmed = (d: Demand) => planCurrent(d) && Boolean(d.plan?.decision?.approved);
|
||||
export function workflowTask(d: Demand): string | undefined {
|
||||
const business = d.access?.business ?? true;
|
||||
const developer = Boolean(d.access?.developer);
|
||||
if (!business && !developer || ['草稿', '已取消'].includes(d.status)) return;
|
||||
if (business && pendingRecovery(d)) return '确认数据恢复方案';
|
||||
if (business && pendingEmergencyVerification(d)) return '补充紧急发布业务验证';
|
||||
const change = pendingChange(d);
|
||||
if (change) return change.status === '待业务确认' ? business ? '确认需求变更' : undefined : developer ? '评估需求变更' : undefined;
|
||||
if (d.delivery?.blocker) return (business && d.delivery.blocker.owner === '业务方') || (developer && d.delivery.blocker.owner === '开发责任人') ? '处理阻塞事项' : undefined;
|
||||
const defects = d.delivery?.defects ?? [];
|
||||
if (business && defects.some(x => ['待复验', '待确认遗留'].includes(x.status))) return '复验缺陷或确认遗留';
|
||||
if (developer && defects.some(x => ['待处理', '修复中'].includes(x.status))) return '处理缺陷';
|
||||
if(developer&&defects.some(x=>x.status==='已确认遗留'&&x.dueDate&&x.dueDate<=new Date().toLocaleDateString('sv-SE',{timeZone:'Asia/Shanghai'})))return '处理到期遗留事项';
|
||||
if(d.status==='已完成')return;
|
||||
if(planCurrent(d)&&d.plan?.decision?.approved===false)return developer?'调整交付计划':undefined;
|
||||
if (planCurrent(d)&&d.plan?.proposedAt && !d.plan.decision) return business ? '确认交付计划' : undefined;
|
||||
const stage = d.review?.proposals.at(-1);
|
||||
if (d.status === '待评审' && stage?.decision?.result === 'confirmed' && !stage.invalidated) return developer ? '提出交付计划' : undefined;
|
||||
if (['已排期', '开发中'].includes(d.status) && planConfirmed(d) && d.plan?.designRequired && !designConfirmed(d)) return designCurrent(d) && !d.delivery?.design?.decision ? business ? '确认设计' : undefined : developer ? '提交设计' : undefined;
|
||||
if (d.status === '已排期') return developer ? '开始开发' : undefined;
|
||||
if (d.status === '开发中') return developer ? '推进开发并提测' : undefined;
|
||||
if (d.status === '待验收') return business ? '提交业务验收结论' : undefined;
|
||||
if (d.status === '待发布') return developer ? '完成发布检查并登记发布' : undefined;
|
||||
if (d.status === '已上线') {
|
||||
return developer ? '生产验证与观察归档' : undefined;
|
||||
}
|
||||
}
|
||||
export function dueDate(d: Demand): string | undefined {
|
||||
if (d.access?.business && pendingEmergencyVerification(d)) return pendingEmergencyVerification(d)?.emergency?.followUpDate;
|
||||
if (d.delivery?.blocker) return d.delivery.blocker.dueDate;
|
||||
if (d.status === '待验收') return d.acceptance?.deadline;
|
||||
if (['已排期', '开发中'].includes(d.status)) return d.plan?.testDate;
|
||||
if (d.status === '待发布') return d.plan?.releaseDate;
|
||||
return d.delivery?.defects?.filter(x=>x.status==='已确认遗留'&&x.dueDate).map(x=>x.dueDate!).sort()[0];
|
||||
}
|
||||
Reference in new issue
Block a user