dsh-total-quality 2.0.55 → 2.0.57

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 (197) hide show
  1. package/CONTRIBUTING.md +51 -47
  2. package/LICENSE.md +37 -37
  3. package/README.en.md +32 -30
  4. package/README.md +90 -88
  5. package/agent-host.cjs +277 -277
  6. package/client.js +199 -92
  7. package/cordis.patch.yml +5 -5
  8. package/docs/enterprise-onboarding.md +10 -10
  9. package/docs/technical-reference.md +223 -223
  10. package/host.cjs +91 -124
  11. package/llm-bridge.cjs +234 -234
  12. package/locale/en.json +5 -5
  13. package/locale/zh.json +5 -5
  14. package/package.json +3 -2
  15. package/public/app.css +3 -0
  16. package/public/app.js +6 -2
  17. package/public/index.html +8 -9
  18. package/public/js/api.js +152 -152
  19. package/public/js/assistant-history.js +62 -62
  20. package/public/js/material-library.js +100 -100
  21. package/public/js/mobile-preview.js +119 -0
  22. package/public/js/pages-company-knowledge.js +9 -32
  23. package/public/js/pages-core.js +232 -232
  24. package/public/js/pages-growth.js +148 -148
  25. package/public/js/pages-qms.js +1 -1
  26. package/public/js/pages-qtools.js +410 -410
  27. package/public/js/pages-thanks.js +71 -71
  28. package/public/js/plugin-updates.js +53 -0
  29. package/public/js/quality-workflow.js +205 -205
  30. package/public/js/survey-dates.js +41 -41
  31. package/public/js/survey-knowledge.js +301 -301
  32. package/public/js/tool-wizards.js +621 -621
  33. package/public/js/ui.js +467 -467
  34. package/public/js/voice-capture-worklet.js +30 -30
  35. package/public/js/xiaozhi-voice.js +264 -264
  36. package/public/js/xiaozhi.js +468 -468
  37. package/public/platform-help.html +426 -426
  38. package/public/platform-site/assets/0468a68574112812.css +10703 -10703
  39. package/public/platform-site/assets/159e086d35adfa1c.css +2094 -2094
  40. package/public/platform-site/assets/169e3159cade0d9f.css +98 -98
  41. package/public/platform-site/assets/22b917c4a3d4ae3d.svg +14 -14
  42. package/public/platform-site/assets/476f9254ccf723e7.css +8265 -8265
  43. package/public/platform-site/assets/85a0a4fb4416ded9.css +120 -120
  44. package/public/platform-site/assets/a3b272383226f6d9.svg +135 -135
  45. package/public/platform-site/assets/fd16dc5f3cc9d97e.svg +104 -104
  46. package/public/platform-site/assets/qip-favicon.svg +5 -5
  47. package/public/platform-site/index.html +279 -279
  48. package/public/platform-site/offline.js +261 -261
  49. package/public/platform-site/qip-brand.css +566 -566
  50. package/public/platform-site/qip-module-guides.js +237 -237
  51. package/public/responsive.css +103 -101
  52. package/public/vendor/markdown-it-15.0.3.LICENSE +22 -22
  53. package/public/vendor/markdown-it-15.0.3.umd.min.js +13 -13
  54. package/public/workbench.css +7 -7
  55. package/public/xiaozhi.css +292 -292
  56. package/resources/qms-templates/019ffb58f24ed48d.docx +0 -0
  57. package/resources/qms-templates/04a69165fc15143a.docx +0 -0
  58. package/resources/qms-templates/09af69358c989a63.docx +0 -0
  59. package/resources/qms-templates/0e7ac77844e45311.docx +0 -0
  60. package/resources/qms-templates/12446a1b5e173c71.docx +0 -0
  61. package/resources/qms-templates/15ae40f67f9a3efc.docx +0 -0
  62. package/resources/qms-templates/18a69bbebf2ece7f.docx +0 -0
  63. package/resources/qms-templates/1978faa989134f02.docx +0 -0
  64. package/resources/qms-templates/1a30e121de752f7b.docx +0 -0
  65. package/resources/qms-templates/1b88907969ea7d4c.docx +0 -0
  66. package/resources/qms-templates/1e92b808722bf90a.docx +0 -0
  67. package/resources/qms-templates/2091cad340dc0e7f.docx +0 -0
  68. package/resources/qms-templates/271ae1002c896ed7.docx +0 -0
  69. package/resources/qms-templates/280ce53e5d3b5fcf.docx +0 -0
  70. package/resources/qms-templates/28ca8e4ede0adf6d.docx +0 -0
  71. package/resources/qms-templates/2ac6675f3cb1f993.docx +0 -0
  72. package/resources/qms-templates/2c3b799389909d8b.docx +0 -0
  73. package/resources/qms-templates/2c51038ba2cc3264.docx +0 -0
  74. package/resources/qms-templates/30c888851d16d764.docx +0 -0
  75. package/resources/qms-templates/3459fc4daaa2743d.docx +0 -0
  76. package/resources/qms-templates/3751dafc335e0e80.docx +0 -0
  77. package/resources/qms-templates/38798cd4298cd2db.docx +0 -0
  78. package/resources/qms-templates/38f551f9d738ab0a.docx +0 -0
  79. package/resources/qms-templates/3c85a23ea17018b4.docx +0 -0
  80. package/resources/qms-templates/3cdb7d14caf1b852.docx +0 -0
  81. package/resources/qms-templates/3f23239bb6b3e1db.docx +0 -0
  82. package/resources/qms-templates/42a5b9efeeaa8007.docx +0 -0
  83. package/resources/qms-templates/47352aafe9b8dac1.docx +0 -0
  84. package/resources/qms-templates/495359b1e3cbb8fe.docx +0 -0
  85. package/resources/qms-templates/4ca6920464785166.docx +0 -0
  86. package/resources/qms-templates/4ce862582a7791be.docx +0 -0
  87. package/resources/qms-templates/54c9a02a10991b9e.docx +0 -0
  88. package/resources/qms-templates/5aeb8fddf5f3693f.docx +0 -0
  89. package/resources/qms-templates/5d7e5576b0e73be7.docx +0 -0
  90. package/resources/qms-templates/5db3a40edac37791.docx +0 -0
  91. package/resources/qms-templates/5ffa21eb78eb6f77.docx +0 -0
  92. package/resources/qms-templates/60d0fbcb709b7161.docx +0 -0
  93. package/resources/qms-templates/63e1d3a166756095.docx +0 -0
  94. package/resources/qms-templates/65c724c080d32f10.docx +0 -0
  95. package/resources/qms-templates/674bd7826c6cbac2.docx +0 -0
  96. package/resources/qms-templates/677e851acca1b879.docx +0 -0
  97. package/resources/qms-templates/6bf15feb1a0d2a8d.docx +0 -0
  98. package/resources/qms-templates/6c3889c7d0918db9.docx +0 -0
  99. package/resources/qms-templates/6c4c349eeb0a96a8.docx +0 -0
  100. package/resources/qms-templates/6c5befbd33f759c1.docx +0 -0
  101. package/resources/qms-templates/6df8367901347508.docx +0 -0
  102. package/resources/qms-templates/71db51997037692b.docx +0 -0
  103. package/resources/qms-templates/78a8ef8c76510c99.docx +0 -0
  104. package/resources/qms-templates/8397bfd1c0a1b013.docx +0 -0
  105. package/resources/qms-templates/84d750cf858b60a1.docx +0 -0
  106. package/resources/qms-templates/880de58a4b334533.docx +0 -0
  107. package/resources/qms-templates/88c37d1b87d9b78c.docx +0 -0
  108. package/resources/qms-templates/88e9cd42f1849462.docx +0 -0
  109. package/resources/qms-templates/8956597403be35b6.docx +0 -0
  110. package/resources/qms-templates/94675c810a233e1f.docx +0 -0
  111. package/resources/qms-templates/94dff59dd7ebec6e.docx +0 -0
  112. package/resources/qms-templates/9670b9cd02141594.docx +0 -0
  113. package/resources/qms-templates/98c373ebd7b5163d.docx +0 -0
  114. package/resources/qms-templates/a4078cf2378a9388.docx +0 -0
  115. package/resources/qms-templates/a5b110c7ef917139.docx +0 -0
  116. package/resources/qms-templates/aec75820e45774be.docx +0 -0
  117. package/resources/qms-templates/b31c085e281d230c.docx +0 -0
  118. package/resources/qms-templates/b7c1c3c72f8ffeef.docx +0 -0
  119. package/resources/qms-templates/b81b82eaa5c8f422.docx +0 -0
  120. package/resources/qms-templates/b92a2fa31f75f137.docx +0 -0
  121. package/resources/qms-templates/b96c54ae9cfffc54.docx +0 -0
  122. package/resources/qms-templates/bc47cfd626c010e7.docx +0 -0
  123. package/resources/qms-templates/be60792734afca69.docx +0 -0
  124. package/resources/qms-templates/c0018d8ae9ad19e1.docx +0 -0
  125. package/resources/qms-templates/c171027c964c8be3.docx +0 -0
  126. package/resources/qms-templates/c4b93d71f5d98b4b.docx +0 -0
  127. package/resources/qms-templates/c531da29fcb3090f.docx +0 -0
  128. package/resources/qms-templates/c88eddd43358d015.docx +0 -0
  129. package/resources/qms-templates/cb978da542f0d892.docx +0 -0
  130. package/resources/qms-templates/ccde4a94532a8d36.docx +0 -0
  131. package/resources/qms-templates/cf3fb1e20ae6f24d.docx +0 -0
  132. package/resources/qms-templates/d231b4982fc8113e.docx +0 -0
  133. package/resources/qms-templates/d3c55aa5ed14055c.docx +0 -0
  134. package/resources/qms-templates/db45c44a00a13349.docx +0 -0
  135. package/resources/qms-templates/db849a41210f54e0.docx +0 -0
  136. package/resources/qms-templates/dba9ce363d83ddc8.docx +0 -0
  137. package/resources/qms-templates/dca3ea4c95eb2225.docx +0 -0
  138. package/resources/qms-templates/dfa4220d2b6b8131.docx +0 -0
  139. package/resources/qms-templates/dfa51222c777734f.docx +0 -0
  140. package/resources/qms-templates/e07ea511507e14f5.docx +0 -0
  141. package/resources/qms-templates/e0a2e00c03458dfa.docx +0 -0
  142. package/resources/qms-templates/e0e802f46b6764d1.docx +0 -0
  143. package/resources/qms-templates/e53fc85717f2852b.docx +0 -0
  144. package/resources/qms-templates/e9dd82d5e54520e5.docx +0 -0
  145. package/resources/qms-templates/ea7bfc22c06d82a9.docx +0 -0
  146. package/resources/qms-templates/ecf0db9f37294536.docx +0 -0
  147. package/resources/qms-templates/f05fcfc87e82ff39.docx +0 -0
  148. package/resources/qms-templates/fb9e56a17c4a4f97.docx +0 -0
  149. package/resources/qms-templates/manifest.json +932 -0
  150. package/src/data/seed-sme.js +317 -317
  151. package/src/data/seed.js +879 -879
  152. package/src/lib/backup-identity.js +57 -57
  153. package/src/lib/chat-answer.js +225 -225
  154. package/src/lib/chat-context.js +99 -99
  155. package/src/lib/company-library.js +28 -19
  156. package/src/lib/data-import.js +217 -217
  157. package/src/lib/data-sources.js +118 -118
  158. package/src/lib/demo-data.js +27 -1
  159. package/src/lib/employee-intake.js +84 -84
  160. package/src/lib/growth.js +53 -53
  161. package/src/lib/intake-packets.js +119 -119
  162. package/src/lib/issue-intake.js +88 -88
  163. package/src/lib/kb-revision.js +214 -214
  164. package/src/lib/llm.js +279 -279
  165. package/src/lib/model-error.js +14 -14
  166. package/src/lib/privacy.js +26 -26
  167. package/src/lib/qms-drafting.js +194 -194
  168. package/src/lib/qms-jobs.js +11 -7
  169. package/src/lib/qms-manual-review.js +185 -185
  170. package/src/lib/qms-procedure-review.js +109 -109
  171. package/src/lib/qms-templates.js +358 -326
  172. package/src/lib/qms.js +369 -369
  173. package/src/lib/quality-priority.js +100 -100
  174. package/src/lib/quality-state.js +92 -92
  175. package/src/lib/quality-workflow.js +65 -65
  176. package/src/lib/retrieval.js +159 -159
  177. package/src/lib/spc.js +127 -127
  178. package/src/lib/voice-hotwords.txt +22 -22
  179. package/src/lib/voice-text.js +13 -13
  180. package/src/lib/voice-worker.js +72 -72
  181. package/src/lib/voice.js +330 -330
  182. package/src/lib/workbench-notices.js +49 -49
  183. package/src/lib/workbench.js +103 -106
  184. package/src/package.json +3 -3
  185. package/src/tools/analysis.js +306 -306
  186. package/src/tools/data.js +596 -596
  187. package/src/tools/docs.js +430 -430
  188. package/src/tools/registry.js +57 -57
  189. package/tools-dsh.cjs +153 -153
  190. package//345/256/211/350/243/205/350/257/264/346/230/216.md +33 -25
  191. package//346/234/254/346/234/272/347/213/254/347/253/213/345/256/211/350/243/205/350/257/264/346/230/216.md +17 -17
  192. package//350/207/252/346/243/200.cjs +88 -88
  193. package/public/js/remote-knowledge.js +0 -165
  194. package/public/js/workbench-notices.js +0 -67
  195. package/public/remote-knowledge-help.html +0 -35
  196. package/public/remote-knowledge.css +0 -40
  197. package/src/lib/remote-knowledge.js +0 -284
@@ -1,284 +0,0 @@
1
- 'use strict';
2
-
3
- const { createHash,randomBytes,randomUUID } = require('node:crypto');
4
-
5
- const protocol=1;
6
- const mount='/qip-real-workbench';
7
- const gateway='/api/kb-federation/v1';
8
- const keysSetting='remoteKnowledgeKeys';
9
- const accountsSetting='remoteKnowledgeConnections';
10
- const serverSetting='remoteKnowledgeServerId';
11
- const approvedSetting='remoteKnowledgeEndpoint';
12
- const maxJson=2*1024*1024;
13
- const tokenPattern=/^qkb_[a-f0-9]{64}$/;
14
- const documentPattern=/^[a-f0-9-]{36}$/i;
15
- const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
16
- const hash=(value)=>createHash('sha256').update(value).digest('hex');
17
- const localHost=(host)=>['localhost','127.0.0.1','[::1]'].includes(host);
18
-
19
- function endpoint(input) {
20
- const address=typeof input==='string'?input.trim():'';
21
- if (!address || address.length>500 || /[\s\\]/.test(address) || address.startsWith('//')) {
22
- fail('请填写 B 服务器的实际域名、IP 或接入链接');
23
- }
24
- let url;
25
- try { url=new URL(/^[a-z][a-z\d+.-]*:\/\//i.test(address)?address:'https://'+address); }
26
- catch { fail('服务器地址格式不正确,请核对域名、IP 和端口'); }
27
- if (/^(?:example|.+\.example)\.?$/i.test(url.hostname)) {
28
- fail('这是示例域名,请填写 B 服务器的实际地址');
29
- }
30
- if (!(url.protocol==='https:' || url.protocol==='http:' && localHost(url.hostname))) {
31
- fail('跨电脑连接需要 B 的 HTTPS 地址,本机环回测试可以使用 HTTP');
32
- }
33
- let pathname=url.pathname.replace(/\/+$/,'');
34
- for (const suffix of ['/health','']) {
35
- const interfacePath=mount+gateway+suffix;
36
- if (pathname.endsWith(interfacePath)) pathname=pathname.slice(0,-(gateway+suffix).length);
37
- }
38
- if (url.username || url.password || url.search || url.hash && !(url.hash==='#remoteKnowledge'&&pathname.endsWith(mount))) {
39
- fail('请使用 B 的服务地址或知识库接入链接');
40
- }
41
- url.hash='';
42
- url.pathname=pathname.endsWith(mount)?pathname:pathname+mount;
43
- return url.href;
44
- }
45
- function checkedTransport(req,identity) {
46
- const proxy=String(process.env.QIP_REMOTE_KB_TLS_PROXY||'').split(',').map(item=>item.trim()).filter(Boolean);
47
- const proxied=proxy.includes(req.socket.remoteAddress) && req.headers['x-forwarded-proto']==='https';
48
- if (!req.socket.encrypted && !identity.loopback(req) && !proxied) fail('远程知识库连接需要 HTTPS',403);
49
- }
50
- function keyRows(store) {
51
- return store.getSetting(keysSetting,[]);
52
- }
53
- function safeKey({id,accountId,memberId,name,role,label,createdAt,expiresAt}) {
54
- return {id,accountId,memberId,name,role,label,createdAt,expiresAt};
55
- }
56
- function grants(store) {
57
- return keyRows(store).filter(row=>Date.parse(row.expiresAt)>Date.now()).map(safeKey);
58
- }
59
- function issueKey(store,account,input) {
60
- const days=Number(input.days===undefined?30:input.days);
61
- const label=typeof input.label==='string'?input.label.trim().slice(0,100):'';
62
- if (!account || !label || !Number.isSafeInteger(days) || days<1 || days>365) fail('请选择员工,填写设备名称及 1–365 天有效期');
63
- const token='qkb_'+randomBytes(32).toString('hex');
64
- const row={id:randomUUID(),accountId:account.id,memberId:account.memberId,name:account.name,role:account.role,label,
65
- createdAt:new Date().toISOString(),expiresAt:new Date(Date.now()+days*86400000).toISOString(),hash:hash(token)};
66
- store.transaction(()=>{
67
- const active=keyRows(store).filter(item=>Date.parse(item.expiresAt)>Date.now());
68
- if (active.filter(item=>item.accountId===account.id).length>=10) fail('此员工已持有 10 个设备授权,请先撤销不用的授权',409);
69
- store.setSetting(keysSetting,[...active,row]);
70
- if (!store.getSetting(serverSetting)) store.setSetting(serverSetting,randomUUID());
71
- store.audit({user:input.issuer,plugin:'远程知识库',action:'发放访问授权',params:{id:row.id,memberId:row.memberId,device:label}});
72
- });
73
- return {token,grant:safeKey(row)};
74
- }
75
- function revokeKey(store,id,issuer) {
76
- const before=keyRows(store);
77
- if (!before.some(row=>row.id===id)) fail('授权已经失效或不存在',404);
78
- store.transaction(()=>{
79
- store.setSetting(keysSetting,before.filter(row=>row.id!==id));
80
- store.audit({user:issuer,plugin:'远程知识库',action:'撤销访问授权',params:{id}});
81
- });
82
- }
83
- function identify(req,store,identity) {
84
- checkedTransport(req,identity);
85
- const token=/^Bearer ([a-z0-9_]+)$/i.exec(req.headers.authorization||'')?.[1];
86
- if (!tokenPattern.test(token||'')) fail('请提供远程知识库访问授权',401);
87
- const fingerprint=hash(token);
88
- const grant=keyRows(store).find(row=>row.hash===fingerprint&&Date.parse(row.expiresAt)>Date.now());
89
- if (!grant) fail('远程知识库的访问授权已撤销或过期',401);
90
- const actor=identity.directoryView().accounts.find(row=>row.id===grant.accountId&&row.memberId===grant.memberId);
91
- if (!actor || actor.role!==grant.role || !store.col('members').get(actor.memberId)) fail('服务端员工身份已经失效',403);
92
- return {actor,expiresAt:grant.expiresAt,serverId:store.getSetting(serverSetting)};
93
- }
94
-
95
- function localKey(req) {
96
- return (req.signer?.id||'local')+':'+expectedRole(req);
97
- }
98
- function expectedRole(req) {
99
- return req.employeeWorkbench?'worker':'manager';
100
- }
101
- function connection(store,req) {
102
- return store.getSetting(accountsSetting,{})[localKey(req)]||null;
103
- }
104
- function writeConnection(store,req,entry) {
105
- const key=localKey(req);
106
- store.transaction(()=>{
107
- const { [key]:previous,...others }=store.getSetting(accountsSetting,{});
108
- store.setSetting(accountsSetting,entry?{...others,[key]:entry}:others);
109
- });
110
- }
111
- function safeConnection(row) {
112
- if (!row) return null;
113
- const {id,endpoint,brand,name,workshop,product,process,expiresAt,checkedAt}=row;
114
- return {id,endpoint,brand,name,workshop,product,process,expiresAt,checkedAt};
115
- }
116
- function approvedEndpoint(store) {
117
- return store.getSetting(approvedSetting,'');
118
- }
119
- function setApprovedEndpoint(store,value) {
120
- const address=endpoint(value);
121
- store.transaction(()=>{
122
- if (approvedEndpoint(store)!==address) {
123
- const entries=Object.entries(store.getSetting(accountsSetting,{})).filter(([,row])=>row.endpoint===address);
124
- store.setSetting(accountsSetting,Object.fromEntries(entries));
125
- store.setSetting(approvedSetting,address);
126
- }
127
- });
128
- return address;
129
- }
130
- function remoteQuery(query){
131
- const text=(value,max)=>typeof value==='string'?value.trim().slice(0,max):'';
132
- const integer=(value,fallback,max)=>/^\d+$/.test(String(value||''))?Math.min(max,Number(value)):fallback;
133
- return {q:text(query.q,200),product:text(query.product,100),process:text(query.process,100),
134
- limit:Math.max(1,integer(query.limit,30,100)),offset:integer(query.offset,0,100000)};
135
- }
136
-
137
- function remoteEndpoint(row,suffix,query={}) {
138
- const url=new URL(row.endpoint+gateway+suffix);
139
- for (const [key,value] of Object.entries(query)) if (value!==''&&value!==undefined) url.searchParams.set(key,String(value));
140
- return url;
141
- }
142
- function combinedSignal(signal,timeout) {
143
- const runtime=AbortSignal.timeout(timeout);
144
- return signal?AbortSignal.any([runtime,signal]):runtime;
145
- }
146
- async function request(row,suffix,query,signal,download=false) {
147
- let response;
148
- try {
149
- response=await fetch(remoteEndpoint(row,suffix,query),{
150
- headers:{...(row.token?{Authorization:'Bearer '+row.token}:{}),Accept:download?'application/octet-stream':'application/json'},
151
- redirect:'manual',signal:combinedSignal(signal,download?120000:10000),
152
- });
153
- } catch (error) {
154
- if (signal?.aborted && signal.reason?.name!=='TimeoutError') signal.throwIfAborted();
155
- const code=error.cause?.code||'';
156
- if (['ENOTFOUND','EAI_AGAIN'].includes(code)) fail('找不到 B 服务器的域名,请核对地址和内网 DNS',502);
157
- if (code==='ECONNREFUSED') fail('B 服务器的端口拒绝连接,请核对端口和服务状态',502);
158
- if (error.name==='TimeoutError' || /TIMEOUT|ETIMEDOUT/.test(code)) fail('连接 B 服务器超时,请检查内网、VPN 或防火墙',502);
159
- if (/SSL.*(?:WRONG_VERSION|UNKNOWN_PROTOCOL)/.test(code)) fail('B 的这个端口没有提供 HTTPS,请检查端口或反向代理配置',502);
160
- if (/CERT|TLS|SELF_SIGNED|VERIFY_LEAF/.test(code)) fail('B 服务器的 HTTPS 证书校验失败,请核对证书信任、域名和有效期',502);
161
- fail('无法到达 B 服务器,请确认本机可以访问该地址',502);
162
- }
163
- if (response.status>=300 && response.status<400) {
164
- await response.body?.cancel().catch(()=>{});
165
- fail('该地址返回了重定向,请填写 B 服务器实际提供服务的 HTTPS 地址',502);
166
- }
167
- return response;
168
- }
169
- async function get(row,suffix,query,signal,download=false) {
170
- const response=await request(row,suffix,query,signal,download);
171
- if (!response.ok) {
172
- await response.body?.cancel().catch(()=>{});
173
- if (response.status===401 || response.status===403) fail('B 服务器拒绝授权,请在服务端核对授权状态',403);
174
- if (response.status===404) fail('B 服务器未提供该文件或远程知识库接口',404);
175
- fail('B 服务器返回 HTTP '+response.status,502);
176
- }
177
- return response;
178
- }
179
- async function jsonResponse(response, requireProtocol=true) {
180
- const type=response.headers.get('content-type')||'';
181
- if (!type.includes('application/json') || !response.body) {
182
- await response.body?.cancel().catch(()=>{});
183
- fail('此地址没有提供兼容的远程知识库接口',502);
184
- }
185
- const reader=response.body.getReader(), chunks=[];
186
- let bytes=0;
187
- try {
188
- for (;;) {
189
- const {value,done}=await reader.read();
190
- if (done) break;
191
- bytes+=value.byteLength;
192
- if (bytes>maxJson) fail('B 服务器返回的数据超过单次读取上限',502);
193
- chunks.push(Buffer.from(value));
194
- }
195
- } catch(error) {
196
- if(error.status) throw error;
197
- fail('B 服务器读取中断,请重试',502);
198
- } finally { await reader.cancel().catch(()=>{}); reader.releaseLock(); }
199
- let data;
200
- try { data=JSON.parse(Buffer.concat(chunks).toString('utf8')); }
201
- catch { fail('B 服务器返回了无效的知识库数据',502); }
202
- if (requireProtocol && data?.protocol!==protocol) fail('B 服务器的知识库协议版本不兼容',502);
203
- return data;
204
- }
205
- async function probe(address,signal) {
206
- const row={endpoint:address};
207
- const time=combinedSignal(signal,12000);
208
- const health=await request(row,'/health',{},time);
209
- if (health.ok) {
210
- const data=await jsonResponse(health);
211
- if (data.service!=='qip-remote-knowledge' || typeof data.acceptingKeys!=='boolean') {
212
- fail('该地址未提供全质开源平台的远程知识库接口',502);
213
- }
214
- return {endpoint:address,healthUrl:remoteEndpoint(row,'/health').href,acceptingKeys:data.acceptingKeys};
215
- }
216
- await health.body?.cancel().catch(()=>{});
217
- if (health.status===404) {
218
- // The original protocol reported its presence through the unauthenticated metadata response.
219
- const meta=await request(row,'/meta',{},time);
220
- if (meta.status===401) {
221
- const data=await jsonResponse(meta,false);
222
- if (data?.error==='请提供远程知识库访问授权') {
223
- return {endpoint:address,healthUrl:remoteEndpoint(row,'/meta').href,acceptingKeys:null};
224
- }
225
- } else await meta.body?.cancel().catch(()=>{});
226
- fail('该地址可访问,但没有找到全质开源平台的远程知识库接口,请核对 B 的部署地址',502);
227
- }
228
- if ([401,403].includes(health.status)) {
229
- fail('该地址的服务器或网关拒绝了接口访问,请让 B 的管理员核对 HTTPS 和访问规则',502);
230
- }
231
- fail('B 服务器的接口返回 HTTP '+health.status,502);
232
- }
233
-
234
- const remoteString=(value,max=100)=>typeof value==='string'?value.slice(0,max):'';
235
- function remoteRow(row) {
236
- if (!documentPattern.test(row?.id||'')) return null;
237
- return {id:row.id,name:remoteString(row.name,250),documentNumber:remoteString(row.documentNumber),
238
- revision:remoteString(row.revision,50),effectiveFrom:remoteString(row.effectiveFrom,24),product:remoteString(row.product),
239
- process:remoteString(row.process),folderName:remoteString(row.folderName,160),size:Number.isSafeInteger(row.size)?row.size:0,
240
- chunkCount:Number.isSafeInteger(row.chunkCount)?row.chunkCount:0,
241
- ...(Number.isSafeInteger(row.part)&&row.part>0?{part:row.part,excerpt:remoteString(row.excerpt,1200)}:{})};
242
- }
243
- async function check(address,token,role,signal) {
244
- if (!tokenPattern.test(token||'')) fail('请粘贴 B 服务器发放的访问密钥,格式以 qkb_ 开头');
245
- const row={endpoint:address,token};
246
- const data=await jsonResponse(await get(row,'/meta',{},signal));
247
- if (data.actor?.role!==role) fail(role==='worker'?'员工端请使用 B 上的员工授权':'管理端请使用 B 上的主管授权',403);
248
- if (!documentPattern.test(data.serverId||'') || !documentPattern.test(data.actor.id||'')) fail('B 服务器缺少身份标识',502);
249
- const id=hash(JSON.stringify([address,data.serverId,data.actor.id,role])).slice(0,32);
250
- return {...row,id,brand:remoteString(data.brand,160),name:remoteString(data.actor.name),
251
- workshop:remoteString(data.actor.workshop),product:remoteString(data.actor.product),process:remoteString(data.actor.process),
252
- expiresAt:remoteString(data.expiresAt,35),checkedAt:new Date().toISOString()};
253
- }
254
- async function list(row,input,signal) {
255
- const options=remoteQuery(input);
256
- const data=await jsonResponse(await get(row,'/documents',options,signal));
257
- if (!Array.isArray(data.rows)||!Number.isSafeInteger(data.total)||data.total<0) fail('B 服务器返回了无效的文档目录',502);
258
- return {rows:data.rows.slice(0,options.limit).map(remoteRow).filter(Boolean),total:data.total,...options};
259
- }
260
- async function search(row,q,signal) {
261
- const options=remoteQuery({q});
262
- if (!options.q) return [];
263
- const data=await jsonResponse(await get(row,'/search',options,signal));
264
- if (!Array.isArray(data.rows)) fail('B 服务器返回了无效的检索结果',502);
265
- return data.rows.slice(0,8).map(remoteRow).filter(row=>row?.excerpt);
266
- }
267
- async function download(row,id,signal) {
268
- if (!documentPattern.test(id||'')) fail('文件编号无效',404);
269
- const res=await get(row,'/documents/'+encodeURIComponent(id),{},signal,true);
270
- const name=res.headers.get('x-qip-file')||'';
271
- let filename;
272
- try { filename=decodeURIComponent(name); }
273
- catch {}
274
- if (!filename || filename.length>250 || /[\/\\\x00-\x1f]/.test(filename) ||
275
- res.headers.get('content-type')!=='application/octet-stream' || !res.body) {
276
- await res.body?.cancel().catch(()=>{});
277
- fail('B 服务器没有返回可下载的原件',502);
278
- }
279
- const length=res.headers.get('content-length');
280
- return {filename,bytes:length!==null && /^\d+$/.test(length)?Number(length):null,body:res.body};
281
- }
282
-
283
- module.exports={protocol,endpoint,grants,issueKey,revokeKey,identify,checkedTransport,expectedRole,probe,
284
- connection,writeConnection,safeConnection,approvedEndpoint,setApprovedEndpoint,remoteQuery,check,list,search,download};