bdip-office-assistant-cli 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +37 -2
  2. package/dist/accounts.js +30 -0
  3. package/dist/args.js +36 -0
  4. package/dist/auth-token.js +783 -0
  5. package/dist/auth.js +331 -0
  6. package/dist/blog.js +562 -0
  7. package/dist/browser-links.js +224 -0
  8. package/dist/captcha-display.js +30 -0
  9. package/dist/cli.js +5533 -0
  10. package/dist/client.js +254 -0
  11. package/dist/config.js +170 -0
  12. package/dist/createcontext.js +41 -0
  13. package/dist/crypto.js +139 -0
  14. package/dist/cube.js +1771 -0
  15. package/dist/documents.js +98 -0
  16. package/dist/email.js +841 -0
  17. package/dist/field-preparation.js +237 -0
  18. package/dist/fileutil.js +20 -0
  19. package/dist/formula-runtime.js +55 -0
  20. package/dist/hrm.js +478 -0
  21. package/dist/keepalive.js +99 -0
  22. package/dist/kq.js +280 -0
  23. package/dist/linkage-calculations.js +68 -0
  24. package/dist/links.js +34 -0
  25. package/dist/meetings.js +172 -0
  26. package/dist/nodemap.js +242 -0
  27. package/dist/odoc.js +199 -0
  28. package/dist/office-tools.js +155 -0
  29. package/dist/pageopen.js +29 -0
  30. package/dist/parse.js +177 -0
  31. package/dist/password-input.js +84 -0
  32. package/dist/password-login.js +208 -0
  33. package/dist/person-selection.js +81 -0
  34. package/dist/querystate.js +38 -0
  35. package/dist/render.js +21 -0
  36. package/dist/report.js +50 -0
  37. package/dist/session-worker.js +54 -0
  38. package/dist/session.js +280 -0
  39. package/dist/submissionplan.js +45 -0
  40. package/dist/submissionstate.js +81 -0
  41. package/dist/subordinate.js +458 -0
  42. package/dist/supervise.js +152 -0
  43. package/dist/todoaskidea.js +54 -0
  44. package/dist/todobatch.js +172 -0
  45. package/dist/todocc.js +128 -0
  46. package/dist/todoforward.js +66 -0
  47. package/dist/todoreject.js +215 -0
  48. package/dist/todosubmit.js +325 -0
  49. package/dist/todotransfer.js +54 -0
  50. package/dist/util.js +25 -0
  51. package/dist/wfagent.js +538 -0
  52. package/dist/wfcreate.js +102 -0
  53. package/dist/wfform.js +169 -0
  54. package/dist/wfops.js +40 -0
  55. package/dist/wfreceiver.js +43 -0
  56. package/dist/wfstart.js +558 -0
  57. package/dist/wfsummary.js +89 -0
  58. package/dist/wfupload.js +83 -0
  59. package/dist/wfuser.js +96 -0
  60. package/dist/workflow-runtime.js +177 -0
  61. package/dist/workflow.js +570 -0
  62. package/dist/workplan.js +431 -0
  63. package/package.json +29 -6
package/dist/parse.js ADDED
@@ -0,0 +1,177 @@
1
+ /**
2
+ * BDIP5 ec/dev/table/datas 响应解析。
3
+ *
4
+ * 实跑确认的结构:
5
+ * - splitPageKey 响应里 dataKey 在 `sessionkey` 字段(小写)。
6
+ * - datas 响应顶层含 `columns`(列定义,dataIndex/title/dbField)和 `datas`(行数组,50 行/页)。
7
+ * - 每行同时有原始字段(如 creater="1" 是 id)和 `<field>span` 渲染字段(含可读名称 / HTML)。
8
+ * 可读值优先取 span 字段并去 HTML 标签。
9
+ * - counts 响应 `{"count":N,"status":true}`。
10
+ */
11
+ /** 从一组候选路径里取第一个非空值,路径用点号分隔、支持下标。 */
12
+ export function pickByPaths(obj, paths) {
13
+ if (obj == null)
14
+ return undefined;
15
+ for (const p of paths) {
16
+ const v = getPath(obj, p);
17
+ if (v !== undefined && v !== null && v !== '')
18
+ return v;
19
+ }
20
+ return undefined;
21
+ }
22
+ function getPath(obj, path) {
23
+ const tokens = path.replace(/\[(\d+)\]/g, '.$1').split('.').filter((t) => t.length > 0);
24
+ let cur = obj;
25
+ for (const t of tokens) {
26
+ if (cur == null)
27
+ return undefined;
28
+ cur = cur[t];
29
+ }
30
+ return cur;
31
+ }
32
+ /** 从 getWfListParams / splitPageKey 响应里提取 dataKey(sessionkey)。 */
33
+ export function extractDataKey(resp) {
34
+ const v = pickByPaths(resp, [
35
+ 'sessionkey',
36
+ 'data.sessionkey',
37
+ 'sessionKey',
38
+ 'data.sessionKey',
39
+ 'dataKey',
40
+ 'data.dataKey',
41
+ 'data',
42
+ ]);
43
+ if (typeof v === 'string' && v.trim())
44
+ return v.trim();
45
+ return scanForDataKey(resp);
46
+ }
47
+ function scanForDataKey(obj) {
48
+ if (obj == null)
49
+ return null;
50
+ if (typeof obj === 'string') {
51
+ if (/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}_[A-F0-9]{32}$/.test(obj)) {
52
+ return obj;
53
+ }
54
+ return null;
55
+ }
56
+ if (Array.isArray(obj)) {
57
+ for (const it of obj) {
58
+ const r = scanForDataKey(it);
59
+ if (r)
60
+ return r;
61
+ }
62
+ return null;
63
+ }
64
+ if (typeof obj === 'object') {
65
+ for (const v of Object.values(obj)) {
66
+ const r = scanForDataKey(v);
67
+ if (r)
68
+ return r;
69
+ }
70
+ }
71
+ return null;
72
+ }
73
+ /** 提取列定义(可用于把行字段映射到中文标题)。 */
74
+ export function extractColumns(datasResp) {
75
+ const cols = pickByPaths(datasResp, ['columns', 'data.columns', 'result.columns']);
76
+ if (!Array.isArray(cols))
77
+ return [];
78
+ return cols.map((c) => ({ dataIndex: c?.dataIndex, title: c?.title, dbField: c?.dbField })).filter((c) => c.dataIndex);
79
+ }
80
+ /** 从 datas 响应里提取行数组。 */
81
+ export function extractRows(datasResp) {
82
+ const arr = pickByPaths(datasResp, ['datas', 'data.datas', 'rows', 'data.rows', 'data', 'list']);
83
+ if (Array.isArray(arr))
84
+ return arr;
85
+ if (arr && typeof arr === 'object' && !Array.isArray(arr)) {
86
+ const vals = Object.values(arr).filter((v) => v && typeof v === 'object');
87
+ if (vals.length)
88
+ return vals;
89
+ }
90
+ return [];
91
+ }
92
+ /** 从 counts 或 datas 响应里提取总数。 */
93
+ export function extractTotal(resp) {
94
+ const v = pickByPaths(resp, ['count', 'data.count', 'total', 'data.total', 'totalCount', 'data.totalCount', 'result.count']);
95
+ if (typeof v === 'number')
96
+ return v;
97
+ if (typeof v === 'string' && /^\d+$/.test(v))
98
+ return parseInt(v, 10);
99
+ return null;
100
+ }
101
+ /** 去掉 HTML 标签与常见实体,得到纯文本。 */
102
+ export function stripHtml(s) {
103
+ if (s == null)
104
+ return '';
105
+ let str = String(s);
106
+ str = str.replace(/<[^>]*>/g, '');
107
+ str = str
108
+ .replace(/&nbsp;/g, ' ')
109
+ .replace(/&amp;/g, '&')
110
+ .replace(/&lt;/g, '<')
111
+ .replace(/&gt;/g, '>')
112
+ .replace(/&quot;/g, '"')
113
+ .replace(/&#39;/g, "'");
114
+ return str.trim();
115
+ }
116
+ /**
117
+ * 从 requestnamespan 提取可见标题。
118
+ * OA 把标题放进第一个 `<a>`(模板前缀如「[退回]」也在 `<a>` 内),把「我的关注」等状态标签
119
+ * 以独立 `<div class='wf_attention_div_btn'>` 追加在 `<a>` 之后——整体去标签会把标签文字并进标题
120
+ * (实测「我的关注」页签的标题被渲染成「采购审批4-... 我的关注」)。
121
+ * 故优先只取第一个 `<a>` 的文本;无 `<a>` 时回退整体去标签。
122
+ */
123
+ function extractTitleFromNamespan(html) {
124
+ const s = String(html ?? '');
125
+ if (!s)
126
+ return '';
127
+ const m = s.match(/<a\b[^>]*>([\s\S]*?)<\/a>/i);
128
+ return stripHtml(m ? m[1] : s);
129
+ }
130
+ const LEVEL_LABEL = {
131
+ '0': '一般',
132
+ '1': '重要',
133
+ '2': '紧急',
134
+ '3': '紧急',
135
+ };
136
+ /**
137
+ * 把一行数据映射成标准待办项。
138
+ * 可读值优先取 `<field>span`(去 HTML),其次原始字段。
139
+ */
140
+ export function normalizeRow(row, columns) {
141
+ if (!row || typeof row !== 'object')
142
+ return {};
143
+ void columns; // 列定义目前仅用于 extractColumns;字段名已稳定,直接按已知 dataIndex 取
144
+ const get = (keys) => pickByPaths(row, keys);
145
+ const spanOr = (dataIndex, extraKeys = []) => stripHtml(get([`${dataIndex}span`, dataIndex, ...extraKeys]));
146
+ // requestnamespan 是 OA 已按管理员模板渲染的可见标题;原始 requestname 仅作回退。
147
+ const rawTitle = stringify(get(['requestname', 'requestName']));
148
+ const title = extractTitleFromNamespan(get(['requestnamespan'])) || rawTitle;
149
+ const levelRaw = stringify(get(['requestlevel', 'level'])) ?? '';
150
+ const level = levelRaw ? (LEVEL_LABEL[levelRaw] ?? levelRaw) : undefined;
151
+ const creatorIdRaw = get(['createrid', 'creatorid', 'creatorId', 'creater']);
152
+ const creatorId = /^\d+$/.test(String(creatorIdRaw ?? '').trim()) ? String(creatorIdRaw).trim() : undefined;
153
+ return {
154
+ requestId: stringify(get(['requestid', 'requestId', 'id', 'randomField2', 'randomFieldId'])),
155
+ title,
156
+ rawTitle,
157
+ creator: spanOr('creater', ['createrName', 'creator', 'createName']),
158
+ creatorId,
159
+ createdate: spanOr('createdate', ['createdatespan', 'createDate']),
160
+ receivedate: spanOr('receivedate', ['receivedate', 'recieveDate']),
161
+ // 注意:服务端流程列表**只有节点 id**(currentnodeidspan 实测也是 id 本身,整行无节点名),
162
+ // 节点名由 nodemap.annotateNodeNames 按流程节点表回填到 nodeName。
163
+ node: stripHtml(get(['currentnodeidspan', 'currentnodespan'])) || stringify(get(['currentnodeid', 'nodeName', 'nodename'])),
164
+ nodeName: undefined,
165
+ workflowId: stringify(get(['workflowid', 'workflowId'])),
166
+ status: stripHtml(get(['statusspan'])) || stringify(get(['status'])),
167
+ level,
168
+ requestmark: stringify(get(['requestmark'])),
169
+ currentOperator: spanOr('unoperators', ['unoperatorspan', 'currentoperator', 'operator']),
170
+ raw: row,
171
+ };
172
+ }
173
+ function stringify(v) {
174
+ if (v === undefined || v === null || v === '')
175
+ return undefined;
176
+ return String(v);
177
+ }
@@ -0,0 +1,84 @@
1
+ // Separate input boundary: never accept credentials in argv, files or configuration.
2
+ import { StringDecoder } from 'node:string_decoder';
3
+ export const PASSWORD_RISK_NOTICE = '临时兼容登录需要处理账号密码;通过聊天输入可能进入平台记录、模型上下文或日志。程序不保存密码,但不能消除平台侧风险。请单独征得用户明确同意,不要使用管理员账号。';
4
+ function failure(code, message) { const error = new Error(message); error.code = code; return error; }
5
+ export function assertNoCredentialArguments(args) {
6
+ const flags = args?.flags ?? {};
7
+ if (Object.keys(flags).some(key => /password|passwd|credentials|username|loginid|secret/i.test(key)
8
+ && !['allow-insecure-password-input', 'credentials-stdin'].includes(key))) {
9
+ throw failure('PASSWORD_ARGUMENT_FORBIDDEN', '不接受命令行、配置或文件传入的账号密码;请使用独立进程 stdin。');
10
+ }
11
+ if ((args?._?.length ?? 0) > 2) throw failure('PASSWORD_ARGUMENT_FORBIDDEN', '登录命令不接受附加位置参数。');
12
+ }
13
+ /** One JSON line from a distinct process stdin; no shell command interpolation. */
14
+ export async function readPasswordCredentials(input = process.stdin, options = {}) {
15
+ return readInputLine(input, options, false);
16
+ }
17
+ export async function readCaptchaAnswer(input = process.stdin, options = {}) {
18
+ return readInputLine(input, { timeoutMs: 300000, maxBytes: 1024, ...options }, true);
19
+ }
20
+ async function readInputLine(input, { timeoutMs = 60000, maxBytes = 8192, signal } = {}, captcha) {
21
+ if (signal?.aborted) throw failure('PASSWORD_CANCELLED', '输入已取消。');
22
+ if (!input || input.isTTY === true || input.destroyed || input.readableEnded || typeof input.on !== 'function') {
23
+ throw failure('PASSWORD_INPUT_UNAVAILABLE', '当前工具没有可用的独立 stdin 输入;请勿把密码拼入命令或临时文件。');
24
+ }
25
+ return new Promise((resolve, reject) => {
26
+ let text = '', bytes = 0, settled = false, timer;
27
+ const decoder = new StringDecoder('utf8');
28
+ const cleanup = () => {
29
+ clearTimeout(timer);
30
+ input.removeListener('data', data);
31
+ input.removeListener('end', end);
32
+ input.removeListener('error', failed);
33
+ signal?.removeEventListener('abort', cancelled);
34
+ input.pause?.();
35
+ // An open tool pipe must remain reusable for captcha, but not keep a
36
+ // completed CLI alive. The next read has its own referenced timeout.
37
+ input.unref?.();
38
+ text = '';
39
+ };
40
+ const finish = error => {
41
+ if (settled) return;
42
+ settled = true;
43
+ if (error) { cleanup(); reject(error); return; }
44
+ try {
45
+ const value = JSON.parse(text);
46
+ if (captcha) {
47
+ if (!value || typeof value !== 'object' || Array.isArray(value)
48
+ || Object.keys(value).length !== 1 || typeof value.captcha !== 'string'
49
+ || !/^[A-Za-z0-9]{1,16}$/.test(value.captcha)) throw new Error('invalid');
50
+ const answer = value.captcha;
51
+ cleanup(); resolve(answer); return;
52
+ }
53
+ if (!value || typeof value !== 'object' || Array.isArray(value)
54
+ || Object.keys(value).some(k => !['username', 'password'].includes(k))
55
+ || typeof value.username !== 'string' || !value.username.trim()
56
+ || typeof value.password !== 'string' || !value.password
57
+ || value.username.length > 256 || value.password.length > 1024
58
+ || /[\u0000-\u001f\u007f]/.test(value.username + value.password)) {
59
+ throw new Error('invalid');
60
+ }
61
+ const credentials = { username: value.username, password: value.password };
62
+ cleanup(); resolve(credentials);
63
+ } catch { cleanup(); reject(failure('PASSWORD_INPUT_INVALID', captcha ? '下一行必须是仅含 captcha 字符串的 JSON;未输出输入内容。' : 'stdin 必须是一行仅含 username 和 password 字符串的 JSON;未输出输入内容。')); }
64
+ };
65
+ const data = chunk => {
66
+ bytes += Buffer.isBuffer(chunk) ? chunk.length : Buffer.byteLength(String(chunk));
67
+ if (bytes > maxBytes) return finish(failure('PASSWORD_INPUT_INVALID', '凭据输入过长,已停止;未输出输入内容。'));
68
+ text += Buffer.isBuffer(chunk) ? decoder.write(chunk) : String(chunk);
69
+ if (text.includes('\n')) {
70
+ const [line, ...rest] = text.split('\n');
71
+ if (rest.join('\n').trim()) return finish(failure('PASSWORD_INPUT_INVALID', '只接受一行凭据 JSON。'));
72
+ text = line.replace(/\r$/, ''); finish();
73
+ }
74
+ };
75
+ const end = () => finish();
76
+ const failed = () => finish(failure('PASSWORD_INPUT_UNAVAILABLE', '凭据输入通道中断;未输出输入内容。'));
77
+ const cancelled = () => finish(failure('PASSWORD_CANCELLED', '输入已取消。'));
78
+ signal?.addEventListener('abort', cancelled, { once: true });
79
+ input.ref?.();
80
+ input.on('data', data); input.on('end', end); input.on('error', failed);
81
+ timer = setTimeout(() => finish(failure('PASSWORD_INPUT_UNAVAILABLE', '等待独立 stdin 输入超时;请勿改用聊天命令或临时文件拼接密码。')), timeoutMs);
82
+ input.resume?.();
83
+ });
84
+ }
@@ -0,0 +1,208 @@
1
+ import { constants, createPublicKey, publicEncrypt } from 'node:crypto';
2
+
3
+ // Intentionally independent of auth/config/token: no persistence, registration, or logging.
4
+ const messages = {
5
+ PASSWORD_INVALID_INPUT: '密码登录输入或平台地址无效', PASSWORD_NETWORK_ERROR: '密码登录网络请求失败',
6
+ PASSWORD_INVALID_URL: '密码登录平台地址无效', PASSWORD_TLS_REQUIRED: '密码登录仅支持HTTP或HTTPS地址',
7
+ PASSWORD_HTTP_CONSENT_REQUIRED: '当前HTTP站点尚未启用密码登录兼容设置',
8
+ PASSWORD_INVALID_USERNAME: '密码登录用户名无效', PASSWORD_INVALID_PASSWORD: '密码登录密码输入无效', PASSWORD_INVALID_OPTIONS: '密码登录选项无效',
9
+ PASSWORD_CAPTCHA_REQUIRED: '平台要求图片验证码,请提供人工验证码处理', PASSWORD_CAPTCHA_REJECTED: '原生图片验证码未通过,未自动重试',
10
+ PASSWORD_INPUT_UNAVAILABLE: '无法取得人工验证输入', PASSWORD_INPUT_INVALID: '人工验证输入格式无效', PASSWORD_CAPTCHA_INVALID: '人工验证码输入无效',
11
+ PASSWORD_TIMEOUT: '密码登录请求超时', PASSWORD_CANCELLED: '密码登录已取消',
12
+ PASSWORD_REDIRECT_REJECTED: '密码登录不允许重定向', PASSWORD_RESPONSE_TOO_LARGE: '密码登录响应超过安全上限',
13
+ PASSWORD_RESPONSE_INVALID: '密码登录响应格式无效', PASSWORD_HTTP_ERROR: '密码登录服务器请求失败',
14
+ PASSWORD_REQUIREMENTS_UNKNOWN: '无法确认账号登录要求,已停止', PASSWORD_CHALLENGE_UNSUPPORTED: '账号要求额外验证,请使用原生登录处理',
15
+ PASSWORD_RSA_INVALID: '无法确认原生加密参数,已停止', PASSWORD_RSA_CAPACITY: '登录输入超过原生加密容量,已停止',
16
+ PASSWORD_LOGIN_REJECTED: '原生密码认证未通过,未自动重试', PASSWORD_COOKIE_UNVERIFIED: '未取得可验证的新登录会话',
17
+ PASSWORD_CHANGE_REQUIRED: '平台要求修改密码,请先在原生界面处理', PASSWORD_POLICY_UNKNOWN: '无法确认平台密码策略,已停止',
18
+ PASSWORD_POLICY_UNSUPPORTED: '平台已启用弱密码限制,当前安全接口不支持验证,请使用原生登录',
19
+ PASSWORD_IDENTITY_MISMATCH: '无法核实唯一当前登录身份,已停止', FORCED_OFFLINE: '当前会话已被强制下线',
20
+ };
21
+ function fail(code) { const e = new Error(messages[code]); e.code = code; throw e; }
22
+ function object(v) { return v && typeof v === 'object' && !Array.isArray(v); }
23
+ function off(v) { return v === false || v === 0 || v === '0'; }
24
+ function on(v) { return v === true || v === 1 || v === '1'; }
25
+ function bit(v) { return off(v) || on(v); }
26
+ function pathMatches(path, scope) { return path === scope || path.startsWith(scope.endsWith('/') ? scope : scope + '/'); }
27
+ class CookieJar {
28
+ constructor() { this.items = new Map(); }
29
+ receive(headers, url) {
30
+ const lines = typeof headers.getSetCookie === 'function' ? headers.getSetCookie() : (headers.get('set-cookie') || '').split(/,(?=\s*[^;,\s]+=)/);
31
+ for (const line of lines) {
32
+ if (!line || /[\r\n]/.test(line)) continue;
33
+ const [pair, ...rest] = line.split(';').map(s=>s.trim()); const eq=pair.indexOf('='); if(eq<1) continue;
34
+ const name=pair.slice(0,eq), value=pair.slice(eq+1);
35
+ if (!/^[!#$%&'*+.^_`|~\w-]+$/.test(name) || /[^\x21-\x7e]|[;,]/.test(value)) continue;
36
+ const attrs=Object.fromEntries(rest.map(s=>{const i=s.indexOf('='); return i<0?[s.toLowerCase(),true]:[s.slice(0,i).toLowerCase(),s.slice(i+1)];}));
37
+ const domain = typeof attrs.domain==='string'?attrs.domain.replace(/^\./,'').toLowerCase():url.hostname;
38
+ // Exact host only is deliberately stricter than browser domain matching. No public-suffix scope.
39
+ if (domain!==url.hostname || (attrs.secure && url.protocol!=='https:')) continue;
40
+ const path=typeof attrs.path==='string' && attrs.path.startsWith('/')?attrs.path:url.pathname.slice(0,url.pathname.lastIndexOf('/')+1).replace(/\/$/,'')||'/';
41
+ let expiry=Infinity;
42
+ if (attrs['max-age']!==undefined) { if(!/^-?\d+$/.test(String(attrs['max-age']))) continue; expiry=Date.now()+Number(attrs['max-age'])*1000; }
43
+ else if(attrs.expires!==undefined) {expiry=Date.parse(attrs.expires);if(!Number.isFinite(expiry))continue;}
44
+ if(name.startsWith('__Secure-') && (!attrs.secure || url.protocol!=='https:'))continue;
45
+ if(name.startsWith('__Host-') && (!attrs.secure || attrs.domain || path!=='/'))continue;
46
+ const key=`${domain}\n${path}\n${name}`;
47
+ if(expiry<=Date.now())this.items.delete(key);else this.items.set(key,{name,value,domain,path,secure:!!attrs.secure,expiry});
48
+ }
49
+ }
50
+ applicable(url) { return [...this.items.values()].filter(c=>c.expiry>Date.now() && c.domain===url.hostname && (!c.secure||url.protocol==='https:') && pathMatches(url.pathname,c.path)).sort((a,b)=>b.path.length-a.path.length); }
51
+ header(url) { return this.applicable(url).map(c=>`${c.name}=${c.value}`).join('; '); }
52
+ exported(base) {
53
+ const api=new URL(base+'/api/hrm/login/getAccountList'), business=new URL(base+'/wui/index.html');
54
+ return this.applicable(business).filter(c=>pathMatches(api.pathname,c.path)).map(c=>`${c.name}=${c.value}`).join('; ');
55
+ }
56
+ }
57
+ function requirements(data) {
58
+ const s=data?.loginSetting;
59
+ if(!object(s)||!bit(s.openRSA)||!bit(s.hasValidateCode)||!bit(s.showDynamicPwd)||!['0','1','2','3','4','5','6'].includes(String(s.userUsbType)))fail('PASSWORD_REQUIREMENTS_UNKNOWN');
60
+ if(!off(s.showDynamicPwd)||String(s.userUsbType)!=='0')fail('PASSWORD_CHALLENGE_UNSUPPORTED');
61
+ // These keys are the complete native GetLoginFromCmd contract. Unknown policy keys fail closed.
62
+ const known=new Set(['userUsbType','hasMultiLang','hasValidateCode','validateCodeKey','numValidateWrong','validateType','showDynamicPwd','needforgotpassword','openRSA']);
63
+ if(Object.keys(s).some(k=>!known.has(k)))fail('PASSWORD_REQUIREMENTS_UNKNOWN');
64
+ const names=data.formItems?.map?.(i=>object(i)?i.name:null);
65
+ if(!Array.isArray(names)||names.length<2||names.length>3||!names.includes('loginid')||!names.includes('userpassword')||names.some(n=>!['loginid','userpassword','validatecode'].includes(n))||new Set(names).size!==names.length||(!on(s.hasValidateCode)&&names.includes('validatecode')))fail('PASSWORD_CHALLENGE_UNSUPPORTED');
66
+ if(Object.keys(data).some(k=>!['loginSetting','formItems','qrcode','message','status'].includes(k)))fail('PASSWORD_CHALLENGE_UNSUPPORTED');
67
+ if(data.status!==undefined && String(data.status)!=='1')fail('PASSWORD_REQUIREMENTS_UNKNOWN');
68
+ return on(s.openRSA);
69
+ }
70
+ function encrypt(value,rsa) {
71
+ try {
72
+ if(!object(rsa)||typeof rsa.rsa_pub!=='string'||typeof rsa.rsa_code!=='string'||!rsa.rsa_code||rsa.rsa_code.length>256||typeof rsa.rsa_flag!=='string'||!rsa.rsa_flag||rsa.rsa_flag.length>128)fail('PASSWORD_RSA_INVALID');
73
+ const key=createPublicKey(rsa.rsa_pub.includes('BEGIN')?rsa.rsa_pub:`-----BEGIN PUBLIC KEY-----\n${rsa.rsa_pub}\n-----END PUBLIC KEY-----`);
74
+ const bits=key.asymmetricKeyDetails?.modulusLength;
75
+ if(key.asymmetricKeyType!=='rsa'||!bits||bits<1024||bits>8192)fail('PASSWORD_RSA_INVALID');
76
+ // Native scripts split at 240 JS chars. Never reproduce their unsafe multi-block ambiguity.
77
+ const bytes=Buffer.from(value+rsa.rsa_code,'utf8');
78
+ if(value.length>240 || bytes.length>Math.ceil(bits/8)-11)fail('PASSWORD_RSA_CAPACITY');
79
+ return publicEncrypt({key,padding:constants.RSA_PKCS1_PADDING},bytes).toString('base64')+rsa.rsa_flag;
80
+ } catch(e) {if(messages[e?.code])throw e;fail('PASSWORD_RSA_INVALID');}
81
+ }
82
+
83
+ /** Validate before collecting credentials; an HTTP grant is exact to scheme/host/port. */
84
+ export function assertPasswordLoginTransport(cfg) {
85
+ try {
86
+ const u=new URL(cfg?.baseUrl);
87
+ if(!['http:','https:'].includes(u.protocol))fail('PASSWORD_TLS_REQUIRED');
88
+ if(u.username||u.password||u.search||u.hash||/%2f|%5c/i.test(u.pathname))fail('PASSWORD_INVALID_URL');
89
+ const loopback=u.hostname==='localhost'||u.hostname==='[::1]'||/^127(?:\.\d{1,3}){3}$/.test(u.hostname);
90
+ if(u.protocol==='http:'&&!loopback&&cfg?.httpPasswordLoginOrigin!==u.origin)fail('PASSWORD_HTTP_CONSENT_REQUIRED');
91
+ return u.href.replace(/\/+$/,'');
92
+ } catch(e) {if(messages[e?.code])throw e;fail('PASSWORD_INVALID_URL');}
93
+ }
94
+
95
+ /** Native HTTP authentication. No persistence, custom token registration, or logging.
96
+ * onCaptcha({image:Buffer,contentType,expiresAt?},{signal}) resolves to one human answer.
97
+ * The callback must honor signal to release input/file resources when cancelled.
98
+ * Only JPEG/PNG/GIF <=512KiB are delivered; no server expiry is invented.
99
+ * Callback wait is excluded from the network budget and bounded to 5 minutes.
100
+ * Network injection never changes origin consent, redirect or platform policy checks.
101
+ */
102
+ export async function passwordLogin(cfg, options = {}) {
103
+ try { if(!object(options))fail('PASSWORD_INVALID_OPTIONS');return await login(cfg,options); }
104
+ catch(e) { const code=Object.hasOwn(messages,e?.code)?e.code:'PASSWORD_NETWORK_ERROR';const safe=new Error(messages[code]);safe.code=code;throw safe; }
105
+ }
106
+ async function login(cfg,{username,password,fetchImpl=globalThis.fetch,timeoutMs=8000,totalTimeoutMs=45000,maxResponseBytes=1024*1024,signal,onCaptcha}={}) {
107
+ // Error objects are reconstructed below so no raw server/network/crypto text escapes.
108
+ const base=assertPasswordLoginTransport(cfg);
109
+ if(typeof username!=='string'||!username.trim()||username!==username.trim()||username.length>1024||/[\x00-\x1f\x7f]/.test(username))fail('PASSWORD_INVALID_USERNAME');
110
+ if(typeof password!=='string'||!password||password.length>16384||/[\x00\r\n]/.test(password))fail('PASSWORD_INVALID_PASSWORD');
111
+ if(typeof fetchImpl!=='function'||(onCaptcha!==undefined&&typeof onCaptcha!=='function')||(signal!==undefined&&!(signal instanceof AbortSignal))||![timeoutMs,totalTimeoutMs,maxResponseBytes].every(v=>Number.isSafeInteger(v)&&v>0)||timeoutMs>30000||totalTimeoutMs>120000||maxResponseBytes>4*1024*1024)fail('PASSWORD_INVALID_OPTIONS');
112
+ const jar=new CookieJar();let deadline=Date.now()+totalTimeoutMs;
113
+ async function request(path,method='GET',params,cookieOverride,{image=false,allow405=false}={}) {
114
+ if(signal?.aborted)fail('PASSWORD_CANCELLED');
115
+ const remaining=Math.min(timeoutMs,deadline-Date.now());if(remaining<=0)fail('PASSWORD_TIMEOUT');
116
+ const controller=new AbortController();let timeout;let abort;
117
+ const stop=new Promise((_,reject)=>{const rejectCode=code=>{controller.abort(); const e=new Error(messages[code]);e.code=code;reject(e);};timeout=setTimeout(()=>rejectCode('PASSWORD_TIMEOUT'),remaining);abort=()=>rejectCode('PASSWORD_CANCELLED');signal?.addEventListener('abort',abort,{once:true});});
118
+ try {
119
+ return await Promise.race([stop,(async()=>{
120
+ const url=new URL(base+path); const res=await fetchImpl(url,{method,redirect:'manual',credentials:'omit',signal:controller.signal,headers:{Accept:'*/*','User-Agent':'BDIP-Office-Assistant','X-Requested-With':'XMLHttpRequest',Cookie:cookieOverride ?? jar.header(url),...(method==='POST'?{'Content-Type':'application/x-www-form-urlencoded; charset=utf-8'}:{})},...(method==='POST'?{body:new URLSearchParams(params).toString()}:{})});
121
+ if(controller.signal.aborted)fail(signal?.aborted?'PASSWORD_CANCELLED':'PASSWORD_TIMEOUT');
122
+ if(res.redirected || (res.status>=300&&res.status<400)){void res.body?.cancel().catch(()=>{});fail('PASSWORD_REDIRECT_REJECTED');}
123
+ if(allow405&&res.status===405){void res.body?.cancel().catch(()=>{});return null;}
124
+ const cap=image?Math.min(maxResponseBytes,512*1024):maxResponseBytes;
125
+ const length=res.headers.get('content-length'); if(length && Number(length)>cap){void res.body?.cancel().catch(()=>{});fail('PASSWORD_RESPONSE_TOO_LARGE');}
126
+ if(!res.body?.getReader)fail('PASSWORD_RESPONSE_INVALID');
127
+ const reader=res.body.getReader();const chunks=[];let count=0;
128
+ try { while(true){const {done,value}=await reader.read();if(done)break;count+=value.byteLength;if(count>cap){void reader.cancel().catch(()=>{});fail('PASSWORD_RESPONSE_TOO_LARGE');}chunks.push(Buffer.from(value));} } finally {reader.releaseLock();}
129
+ if(controller.signal.aborted)fail(signal?.aborted?'PASSWORD_CANCELLED':'PASSWORD_TIMEOUT');
130
+ if(image){
131
+ if(res.status!==200)fail('PASSWORD_HTTP_ERROR');
132
+ const bytes=Buffer.concat(chunks),type=(res.headers.get('content-type')||'').split(';')[0].trim().toLowerCase();
133
+ const valid=(type==='image/jpeg'&&bytes.length>=4&&bytes[0]===255&&bytes[1]===216&&bytes[2]===255&&bytes.at(-2)===255&&bytes.at(-1)===217)||(type==='image/png'&&bytes.length>=24&&bytes.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])))||(type==='image/gif'&&bytes.length>=13&&['GIF87a','GIF89a'].includes(bytes.subarray(0,6).toString('ascii')));
134
+ if(!valid)fail('PASSWORD_RESPONSE_INVALID');jar.receive(res.headers,url);return {image:bytes,contentType:type};
135
+ }
136
+ let data;try{data=JSON.parse(Buffer.concat(chunks).toString('utf8'));}catch{fail('PASSWORD_RESPONSE_INVALID');}if(!object(data))fail('PASSWORD_RESPONSE_INVALID');
137
+ if(['003','004','FORCED_OFFLINE'].some(c=>[data.code,data.errorCode,data.msgcode].some(v=>String(v)===c)))fail('FORCED_OFFLINE');
138
+ if(res.status!==200)fail('PASSWORD_HTTP_ERROR');
139
+ jar.receive(res.headers,url);return data;
140
+ })()]);
141
+ } finally {clearTimeout(timeout);signal?.removeEventListener('abort',abort);}
142
+ }
143
+ const bootstrap=await request('/api/hrm/login/getLoginForm','POST',{loginid:'',langid:'7'});
144
+ const rsaEnabled=requirements(bootstrap);
145
+ const rsaInfo=()=>request('/rsa/weaver.rsa.GetRsaInfo?ts='+Date.now());
146
+ let loginid=username;
147
+ if(rsaEnabled)loginid=encrypt(username,await rsaInfo());
148
+ const account=await request('/api/hrm/login/getLoginForm','POST',{loginid,langid:'7'});
149
+ if(requirements(account)!==rsaEnabled)fail('PASSWORD_REQUIREMENTS_UNKNOWN');
150
+ let validatecode='',validateCodeKey='';
151
+ if(on(account.loginSetting.hasValidateCode)){
152
+ if(!onCaptcha)fail('PASSWORD_CAPTCHA_REQUIRED');
153
+ validateCodeKey=account.loginSetting.validateCodeKey;
154
+ if(typeof validateCodeKey!=='string'||!validateCodeKey||validateCodeKey.length>256||/[\x00-\x20\x7f]/.test(validateCodeKey))fail('PASSWORD_REQUIREMENTS_UNKNOWN');
155
+ if(account.loginSetting.validateType!==undefined&&!off(account.loginSetting.validateType))fail('PASSWORD_CHALLENGE_UNSUPPORTED');
156
+ // Observed native public image request: seriesnum_ + validateCodeKey, never key.
157
+ const challenge=await request('/weaver/weaver.file.MakeValidateCode?'+new URLSearchParams({seriesnum_:String(Date.now()),validateCodeKey}), 'GET',undefined,undefined,{image:true});
158
+ const start=Date.now(),captchaController=new AbortController();let timer,abort;
159
+ try{
160
+ const stop=new Promise((_,reject)=>{const rejectCode=code=>{const e=new Error(messages[code]);e.code=code;reject(e);captchaController.abort();};timer=setTimeout(()=>rejectCode('PASSWORD_TIMEOUT'),300000);abort=()=>rejectCode('PASSWORD_CANCELLED');signal?.addEventListener('abort',abort,{once:true});if(signal?.aborted)abort();});
161
+ validatecode=await Promise.race([stop,Promise.resolve().then(()=>onCaptcha(challenge,{signal:captchaController.signal}))]);
162
+ }catch(e){if(['PASSWORD_CANCELLED','PASSWORD_TIMEOUT','PASSWORD_INPUT_UNAVAILABLE','PASSWORD_INPUT_INVALID','PASSWORD_CAPTCHA_INVALID'].includes(e?.code))throw e;fail('PASSWORD_INPUT_UNAVAILABLE');}
163
+ finally{clearTimeout(timer);signal?.removeEventListener('abort',abort);captchaController.abort();deadline+=Date.now()-start;}
164
+ if(typeof validatecode!=='string'||!validatecode.trim()||validatecode!==validatecode.trim()||validatecode.length>128||/[\x00-\x20\x7f]/.test(validatecode))fail('PASSWORD_CAPTCHA_INVALID');
165
+ }
166
+ let userpassword=password;
167
+ if(rsaEnabled){const rsa=await rsaInfo();loginid=encrypt(username,rsa);userpassword=encrypt(password,rsa);}
168
+ const before=jar.exported(base);
169
+ const result=await request('/api/hrm/login/checkLogin','POST',{loginid,userpassword,islanguid:'7',logintype:'1',validatecode,validateCodeKey,dynamicPassword:'',tokenAuthKey:'',messages:'',isie:'false'});
170
+ if(String(result.msgcode)==='52')fail('PASSWORD_CAPTCHA_REJECTED');
171
+ const uid=String(result.userid??'');
172
+ if(String(result.loginstatus)!=='true'||String(result.msgcode)!=='0'||! /^[1-9]\d*$/.test(uid))fail('PASSWORD_LOGIN_REJECTED');
173
+ if((result.authUrl!==undefined&&result.authUrl!=='')||(result.qysflag!==undefined&&String(result.qysflag)!=='0')||(result.isRemoveSession!==undefined&&!off(result.isRemoveSession)))fail('PASSWORD_CHALLENGE_UNSUPPORTED');
174
+ const fresh=jar.exported(base);if(!fresh||fresh===before)fail('PASSWORD_COOKIE_UNVERIFIED');
175
+ const policy=await request('/api/hrm/login/remindLogin','POST',{logintype:'1'});
176
+ if(String(policy.status)!=='1'||(policy.isUpPswd!==undefined&&!['true','false'].includes(String(policy.isUpPswd))))fail('PASSWORD_POLICY_UNKNOWN');
177
+ if(String(policy.isUpPswd)==='true')fail('PASSWORD_CHANGE_REQUIRED');
178
+ if(policy.passwdReminder!==undefined&&!bit(policy.passwdReminder))fail('PASSWORD_POLICY_UNKNOWN');
179
+ if(on(policy.passwdReminder)){if(!bit(policy.canpass))fail('PASSWORD_POLICY_UNKNOWN');if(!on(policy.canpass))fail('PASSWORD_CHANGE_REQUIRED');}
180
+ // Native online script uses POST {password:C}; legacy backend may be GET only. Metadata
181
+ // GET fallback is metadata only: no secret or password-strength proof.
182
+ // Never put plaintext/ciphertext in a URL. On fallback only explicitly
183
+ // disabled prohibition can proceed; enabled/unknown policy requires native UI.
184
+ let weak=await request('/api/hrm/password/isWeakPassword','POST',{password:userpassword},undefined,{allow405:true});
185
+ const metadataOnly=weak===null;
186
+ if(metadataOnly)weak=await request('/api/hrm/password/isWeakPassword');
187
+ if((weak.status!==undefined&&String(weak.status)!=='1')||!bit(weak.weakPasswordDisable)||(!metadataOnly&&typeof weak.isWeakPassword!=='boolean'))fail('PASSWORD_POLICY_UNKNOWN');
188
+ if(on(weak.weakPasswordDisable)&&(metadataOnly||weak.isWeakPassword))fail('PASSWORD_POLICY_UNSUPPORTED');
189
+ const identity=await request('/api/hrm/login/getAccountList');
190
+ const rows=identity?.data?.accountlist;
191
+ const current=Array.isArray(rows)?rows.filter(r=>object(r)&&String(r.iscurrent)==='1'):[];
192
+ if(identity.status!==undefined&&String(identity.status)!=='1')fail('PASSWORD_IDENTITY_MISMATCH');
193
+ if(current.length!==1||String(current[0].userid)!==uid)fail('PASSWORD_IDENTITY_MISMATCH');
194
+ const cookie=jar.exported(base);if(!cookie)fail('PASSWORD_COOKIE_UNVERIFIED');
195
+ // Prove the exact portable candidate, not a richer API-path jar header that
196
+ // might contain the only authenticating cookie. One final read; never loop.
197
+ const finalIdentity=await request('/api/hrm/login/getAccountList','GET',undefined,cookie);
198
+ const finalRows=finalIdentity?.data?.accountlist;
199
+ const finalCurrent=Array.isArray(finalRows)?finalRows.filter(r=>object(r)&&String(r.iscurrent)==='1'):[];
200
+ if((finalIdentity.status!==undefined&&String(finalIdentity.status)!=='1')||finalCurrent.length!==1||String(finalCurrent[0].userid)!==uid)fail('PASSWORD_IDENTITY_MISMATCH');
201
+ // Even benign rotation changes the candidate and needs a new proof. Stop
202
+ // conservatively rather than return credentials that were not actually sent.
203
+ if(jar.exported(base)!==cookie)fail('PASSWORD_COOKIE_UNVERIFIED');
204
+ // Native GetAccountListCmd returns userid/username/iscurrent, not canonical loginid.
205
+ // UID is bound to the single fresh password-authenticated session above. Do not
206
+ // mislabel a display name or user-supplied alias as a verified canonical login ID.
207
+ return {cookie,userId:uid,loginId:null,mode:'password-http'};
208
+ }
@@ -0,0 +1,81 @@
1
+ import {buildHrmCardUrl} from './hrm.js';
2
+
3
+ const clean = v => String(v ?? '').replace(/<[^>]*>/g,'').trim();
4
+ export async function currentPersonAccount(api) {
5
+ const r=await api.get('/api/hrm/login/getAccountList',{__random__:Date.now()},{forceCookie:true});
6
+ const rows=r.json?.data?.accountlist;
7
+ const current=Array.isArray(rows)?rows.filter(a=>String(a.iscurrent)==='1'):[];
8
+ if(current.length!==1 || !/^\d+$/.test(String(current[0].userid??'')) || !/^\d+$/.test(String(current[0].subcompanyid??'')))throw Error('无法核实当前账号及所属分部,停止选人');
9
+ const a=current[0];
10
+ return {id:String(a.userid),divisionId:String(a.subcompanyid),division:a.subcompanyname,name:a.username};
11
+ }
12
+ const conditionKey=c=>Array.isArray(c?.domkey)?c.domkey[0]:c?.domkey;
13
+ export function personSearchQuery(query,conditions,account,context={}) {
14
+ const q={...query};
15
+ const names=conditions.filter(c=>c.isQuickSearch&&c.conditionType==='INPUT');
16
+ const name=names.length===1?names[0]:null;
17
+ const division=conditions.find(c=>conditionKey(c)==='subcompanyid');
18
+ if(!name||!division)throw Error('未识别人员姓名/分部查询条件,需核实当前协议');
19
+ for(const c of conditions) {
20
+ const key=conditionKey(c);
21
+ const value=c.value??c.options?.filter(o=>o.selected).map(o=>o.key).join(',');
22
+ if(key&&value!==undefined&&value!==''&&q[key]===undefined)q[key]=value;
23
+ }
24
+ if(context.subcompanyId && String(context.subcompanyId)!==account.divisionId && context.crossDivision!==true)throw Error('跨分部查询需要用户明确指定范围');
25
+ const target=String(context.subcompanyId??account.divisionId);
26
+ if(!/^\d+$/.test(target))throw Error('分部ID格式错误');
27
+ const key=conditionKey(division),fixed=[q[key],q.subcompanyid1];
28
+ // 固定过滤只能收窄,不能被默认分部或跨分部要求覆盖。
29
+ if(fixed.some(v=>v!=null&&String(v)!==''&&!String(v).split(',').includes(target)))return {query:q,target,empty:true};
30
+ q[key]=target;
31
+ const nk=conditionKey(name);
32
+ if(context.search) {
33
+ if(q[nk] && String(q[nk])!==String(context.search))throw Error('姓名搜索与字段固定条件冲突');
34
+ q[nk]=String(context.search);
35
+ }
36
+ if(q.cmd&&q.cmd!=='search')throw Error('字段指定了其他人员协议,需适配');
37
+ q.cmd='search';
38
+ return {query:q,target,empty:false};
39
+ }
40
+ export function validPersonCandidates(rows,target,search,baseUrl) {
41
+ const selected=new Map();
42
+ for(const r of rows) {
43
+ const id=clean(r.id),divisionId=clean(r.subcompanyid??r.subcompanyid1),name=clean(r.lastnamespan??r.lastname);
44
+ if(!id||!divisionId)throw Error('人员结果缺少账号ID或分部ID,无法核验候选');
45
+ if(divisionId!==target || (search&&!name.includes(String(search))))continue;
46
+ selected.set(id,{id,name,department:clean(r.departmentname??r.departmentidspan),division:clean(r.subcompanyname??r.subcompanyid1span),divisionId,url:buildHrmCardUrl(baseUrl,id)});
47
+ }
48
+ return [...selected.values()];
49
+ }
50
+ export async function queryPersonBrowser(api,form,field,query,context={}) {
51
+ const before=await currentPersonAccount(api);
52
+ if(String(form.params.currentUserid)!==before.id)throw Error('表单身份与当前账号不符,请重新读取');
53
+ const path='/api/public/browser/';
54
+ const c=await api.get(path+'condition/'+field.detailtype,query,{forceCookie:true});
55
+ const conditions=c.json?.conditions;
56
+ if(!Array.isArray(conditions))throw Error('人员浏览条件查询失败,未证明表单可选性');
57
+ const scoped=personSearchQuery(query,conditions,before,context);
58
+ const rows=[],seen=new Set();let total=null,complete=scoped.empty;
59
+ const size=50;
60
+ for(let page=1;!complete&&page<=100;page++) {
61
+ const q={...scoped.query,current:String(page),pageSize:String(size),min:String((page-1)*size+1),max:String(page*size)};
62
+ const url=path+'data/'+field.detailtype;
63
+ const method=(url+'?'+new URLSearchParams(q)).length>6000?'post':'get';
64
+ const r=await api[method](url,q,{forceCookie:true}),j=r.json;
65
+ if(!r.ok||!j||j.status===false||j.status==='false'||!Array.isArray(j.datas)||j.count==null||!Number.isInteger(Number(j.count))||Number(j.count)<0)throw Error('人员浏览查询失败或分页总数缺失,未证明表单可选性');
66
+ if(total!==null&&total!==Number(j.count))throw Error('人员查询范围发生变化,请重查');
67
+ total=Number(j.count);
68
+ for(const row of j.datas){const id=String(row.id??'');if(seen.has(id))throw Error('人员分页重复,无法确认完整范围');seen.add(id);rows.push(row);}
69
+ if(rows.length>total)throw Error('人员分页条数与总数不符');
70
+ complete=rows.length>=total;
71
+ if(!complete&&!j.datas.length)throw Error('人员分页不完整');
72
+ }
73
+ if(!complete)throw Error('人员查询超出分页上限,不能据此唯一选人');
74
+ const after=await currentPersonAccount(api);
75
+ if(after.id!==before.id||after.divisionId!==before.divisionId)throw Error('选人期间账号/分部变化,候选已失效,请重查');
76
+ const items=validPersonCandidates(rows,scoped.target,context.search,context.baseUrl??'');
77
+ return {account:before,scope:{divisionId:scoped.target,crossDivision:context.crossDivision===true},conditions,
78
+ verification:'field-browser-api',complete:true,count:items.length,items,
79
+ resolution:items.length===1?'unique':items.length?'choose':'none',
80
+ note:'已核验当前字段浏览接口范围;不代替保存/提交时后端权限校验。零匹配不扩大范围。'};
81
+ }
@@ -0,0 +1,38 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+
5
+ const stateDir = () => path.resolve(process.cwd(), 'state');
6
+ const queryDir = () => path.join(stateDir(), 'query_contexts');
7
+
8
+ export function saveCandidateQuery({ workflow, candidates, options }) {
9
+ fs.mkdirSync(queryDir(), { recursive: true });
10
+ const id = randomUUID();
11
+ fs.writeFileSync(path.join(queryDir(), `${id}.json`), JSON.stringify({ id, workflow, candidates, options, createdAt: new Date().toISOString() }, null, 2), 'utf8');
12
+ return id;
13
+ }
14
+ export function loadCandidateQuery(id) {
15
+ if (!/^[a-zA-Z0-9-]+$/.test(String(id)))
16
+ throw new Error('resume-query 格式无效。');
17
+ const file = path.join(queryDir(), `${id}.json`);
18
+ if (!fs.existsSync(file))
19
+ throw new Error('查询上下文不存在或已被清理,请重新搜索流程名称。');
20
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
21
+ }
22
+ export function persistSearchResult(result, title = '待办查询') {
23
+ const json = JSON.stringify(result, null, 2);
24
+ if (Buffer.byteLength(json, 'utf8') <= 8192)
25
+ return null;
26
+ fs.mkdirSync(stateDir(), { recursive: true });
27
+ const jsonPath = path.join(stateDir(), 'last_search.json');
28
+ const mdPath = path.join(stateDir(), 'last_search.md');
29
+ fs.writeFileSync(jsonPath, json, 'utf8');
30
+ const items = Array.isArray(result.items)
31
+ ? result.items
32
+ : (Array.isArray(result.groups) ? result.groups.flatMap((group) => group.items ?? []) : []);
33
+ const lines = [`# ${title}`, '', `共 ${result.total ?? items.length} 条,以下为前 10 条:`, ''];
34
+ for (const item of items.slice(0, 10))
35
+ lines.push(`- ${item.title ?? '(无标题)'}(${item.requestId ?? ''})`);
36
+ fs.writeFileSync(mdPath, lines.join('\n'), 'utf8');
37
+ return { jsonPath, mdPath };
38
+ }
package/dist/render.js ADDED
@@ -0,0 +1,21 @@
1
+ /**
2
+ * 人类可读输出渲染:框线表格、分隔线。
3
+ * 集中框线宽度,避免散落的字面量重复。
4
+ */
5
+ export const BOX_TOP = '═'.repeat(50); // 上下封口
6
+ export const DIVIDER = '─'.repeat(53); // 区内分隔
7
+ /**
8
+ * 打印一个标题框:顶线 + title + 可选正文行 + 底线。
9
+ * title/lines 已含前导空格等格式,由调用方决定对齐。
10
+ */
11
+ export function box(title, lines = []) {
12
+ console.log(BOX_TOP);
13
+ if (title)
14
+ console.log(title);
15
+ for (const l of lines)
16
+ console.log(l);
17
+ console.log(BOX_TOP);
18
+ }
19
+ export function divider() {
20
+ console.log(DIVIDER);
21
+ }