@oxmumu3/dsh-agent-twin 0.6.0 → 0.6.2
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.
- package/README.md +16 -9
- package/client.js +503 -6
- package/examples/growth-bi-desk/README.md +2 -1
- package/examples/growth-bi-desk/mtn/growth-ska-graph.json +69 -0
- package/lib/channels.js +67 -9
- package/lib/fullblood-runner.js +33 -6
- package/lib/guest-server.js +614 -137
- package/lib/host.js +38 -3
- package/lib/mtn-provider.js +284 -0
- package/lib/official-connectors.js +5 -1
- package/lib/owner-notifier.js +123 -0
- package/lib/routes.js +53 -3
- package/lib/scanner.js +145 -14
- package/lib/service.js +48 -6
- package/lib/store.js +162 -16
- package/lib/twin-engine.js +956 -440
- package/package.json +3 -3
- package/shared/schema.js +63 -0
package/lib/guest-server.js
CHANGED
|
@@ -1,17 +1,29 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Built-in
|
|
3
|
-
*
|
|
4
|
-
*
|
|
2
|
+
* Built-in local & public-tunnel Guest Web Portal (`ch-web` & `/try` Public Scan-to-Try Lobby).
|
|
3
|
+
* - `/g/:token`: Private named caller isolated web portal (`/api/guest/:token/ask[-stream]`).
|
|
4
|
+
* - `/try`: Anonymous per-cookie isolated Public Lobby (`/api/try/ask[-stream]`, `/api/try/qr.svg`)
|
|
5
|
+
* with Fail-Closed capability whitelist, per-visitor & global daily caps, and per-IP burst limiter.
|
|
5
6
|
*/
|
|
7
|
+
import { randomBytes } from 'node:crypto';
|
|
6
8
|
import http from 'node:http';
|
|
7
9
|
import { URL } from 'node:url';
|
|
10
|
+
import QRCode from 'qrcode';
|
|
8
11
|
import {
|
|
12
|
+
DEFAULT_PUBLIC_GLOBAL_DAILY_LIMIT,
|
|
13
|
+
DEFAULT_PUBLIC_VISITOR_DAILY_LIMIT,
|
|
14
|
+
normalizePublicLobbyConfig,
|
|
9
15
|
redactSecrets,
|
|
10
16
|
sanitizeSurfaceText
|
|
11
17
|
} from '../shared/schema.js';
|
|
18
|
+
import { todayKey } from './store.js';
|
|
12
19
|
import { isPersonExpired } from './twin-engine.js';
|
|
13
20
|
|
|
14
21
|
const MAX_BODY_BYTES = 65536;
|
|
22
|
+
const COOKIE_NAME = 'dsh_twin_vid';
|
|
23
|
+
const VISITOR_ID_RE = /^[a-f0-9]{16,32}$/i;
|
|
24
|
+
const DEFAULT_PUBLIC_BURST_PER_MIN = 8;
|
|
25
|
+
|
|
26
|
+
const CREATIVE_MODE_INSTALL_PROMPT = '请通过插件管理器,从 npm 官方源安装并启用 @oxmumu3/dsh-agent-twin@latest。完成后请核对版本和启用状态,再带我打开左侧「AI 分身」。';
|
|
15
27
|
|
|
16
28
|
function escapeHtml(str) {
|
|
17
29
|
return String(str ?? '')
|
|
@@ -22,7 +34,7 @@ function escapeHtml(str) {
|
|
|
22
34
|
.replace(/'/g, ''');
|
|
23
35
|
}
|
|
24
36
|
|
|
25
|
-
function isCrossSiteRequest(req,
|
|
37
|
+
function isCrossSiteRequest(req, expectedOrigins) {
|
|
26
38
|
const secFetch = String(req.headers['sec-fetch-site'] || '').toLowerCase();
|
|
27
39
|
if (secFetch && secFetch !== 'same-origin' && secFetch !== 'none') {
|
|
28
40
|
return true;
|
|
@@ -31,9 +43,14 @@ function isCrossSiteRequest(req, expectedOrigin) {
|
|
|
31
43
|
if (!origin) return false;
|
|
32
44
|
try {
|
|
33
45
|
const parsed = new URL(origin);
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
if (
|
|
46
|
+
const list = Array.isArray(expectedOrigins) ? expectedOrigins : [expectedOrigins];
|
|
47
|
+
for (const exp of list) {
|
|
48
|
+
if (!exp) continue;
|
|
49
|
+
try {
|
|
50
|
+
if (parsed.origin === new URL(exp).origin) return false;
|
|
51
|
+
} catch {
|
|
52
|
+
// ignore invalid expected origin entry
|
|
53
|
+
}
|
|
37
54
|
}
|
|
38
55
|
return !['127.0.0.1', 'localhost', '[::1]'].includes(parsed.hostname);
|
|
39
56
|
} catch {
|
|
@@ -41,20 +58,61 @@ function isCrossSiteRequest(req, expectedOrigin) {
|
|
|
41
58
|
}
|
|
42
59
|
}
|
|
43
60
|
|
|
44
|
-
function
|
|
61
|
+
function parseCookies(cookieHeader) {
|
|
62
|
+
const out = {};
|
|
63
|
+
for (const part of String(cookieHeader || '').split(';')) {
|
|
64
|
+
const eq = part.indexOf('=');
|
|
65
|
+
if (eq === -1) continue;
|
|
66
|
+
const k = part.slice(0, eq).trim();
|
|
67
|
+
const v = part.slice(eq + 1).trim();
|
|
68
|
+
if (k) out[k] = decodeURIComponent(v);
|
|
69
|
+
}
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function isForwardedHttps(req) {
|
|
74
|
+
const proto = String(req.headers['x-forwarded-proto'] || '').split(',')[0].trim().toLowerCase();
|
|
75
|
+
return proto === 'https';
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function resolveVisitorCookie(req) {
|
|
79
|
+
const cookies = parseCookies(req.headers.cookie);
|
|
80
|
+
const existing = cookies[COOKIE_NAME];
|
|
81
|
+
if (existing && VISITOR_ID_RE.test(existing)) {
|
|
82
|
+
return { visitorId: existing.toLowerCase(), isNew: false };
|
|
83
|
+
}
|
|
84
|
+
return { visitorId: randomBytes(16).toString('hex'), isNew: true };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function buildVisitorCookieHeader(req, visitorId) {
|
|
88
|
+
const secure = isForwardedHttps(req) ? '; Secure' : '';
|
|
89
|
+
return `${COOKIE_NAME}=${visitorId}; HttpOnly; Path=/; Max-Age=604800; SameSite=Lax${secure}`;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function getClientIp(req) {
|
|
93
|
+
const cfIp = req.headers['cf-connecting-ip'];
|
|
94
|
+
if (typeof cfIp === 'string' && cfIp.trim()) return cfIp.trim();
|
|
95
|
+
const xff = req.headers['x-forwarded-for'];
|
|
96
|
+
if (typeof xff === 'string' && xff.trim()) return xff.split(',')[0].trim();
|
|
97
|
+
return req.socket?.remoteAddress || 'unknown';
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function sendJson(res, status, data, extraHeaders = {}) {
|
|
45
101
|
const body = JSON.stringify(data);
|
|
46
102
|
res.writeHead(status, {
|
|
47
103
|
'Content-Type': 'application/json; charset=utf-8',
|
|
48
|
-
'Cache-Control': 'no-store'
|
|
104
|
+
'Cache-Control': 'no-store',
|
|
105
|
+
...extraHeaders
|
|
49
106
|
});
|
|
50
107
|
res.end(body);
|
|
51
108
|
}
|
|
52
109
|
|
|
53
|
-
function sendHtml(res, status, html) {
|
|
110
|
+
function sendHtml(res, status, html, extraHeaders = {}) {
|
|
54
111
|
res.writeHead(status, {
|
|
55
112
|
'Content-Type': 'text/html; charset=utf-8',
|
|
56
113
|
'Cache-Control': 'no-store',
|
|
57
|
-
'X-Content-Type-Options': 'nosniff'
|
|
114
|
+
'X-Content-Type-Options': 'nosniff',
|
|
115
|
+
...extraHeaders
|
|
58
116
|
});
|
|
59
117
|
res.end(html);
|
|
60
118
|
}
|
|
@@ -98,6 +156,259 @@ function readJsonBody(req) {
|
|
|
98
156
|
});
|
|
99
157
|
}
|
|
100
158
|
|
|
159
|
+
function buildStreamScript({ endpointPrefix, twinName, copyPromptText = '' }) {
|
|
160
|
+
return `<script>
|
|
161
|
+
(function () {
|
|
162
|
+
var endpoint = ${JSON.stringify(endpointPrefix)};
|
|
163
|
+
var twinLabel = ${JSON.stringify(twinName)};
|
|
164
|
+
var form = document.getElementById('askForm');
|
|
165
|
+
var input = document.getElementById('questionInput');
|
|
166
|
+
var btn = document.getElementById('sendBtn');
|
|
167
|
+
var fb = document.getElementById('feedback');
|
|
168
|
+
var thread = document.getElementById('thread');
|
|
169
|
+
var quotaBadge = document.getElementById('quotaBadge');
|
|
170
|
+
var copyBtn = document.getElementById('copyInstallBtn');
|
|
171
|
+
var copyStatus = document.getElementById('copyStatus');
|
|
172
|
+
var installBox = document.getElementById('installDetails');
|
|
173
|
+
|
|
174
|
+
if (copyBtn) {
|
|
175
|
+
copyBtn.addEventListener('click', function () {
|
|
176
|
+
var txt = ${JSON.stringify(copyPromptText)};
|
|
177
|
+
if (!txt) return;
|
|
178
|
+
if (navigator.clipboard && navigator.clipboard.writeText) {
|
|
179
|
+
navigator.clipboard.writeText(txt).then(function () {
|
|
180
|
+
if (copyStatus) copyStatus.textContent = '已复制创造模式指令';
|
|
181
|
+
}).catch(function () {
|
|
182
|
+
if (copyStatus) copyStatus.textContent = '请长按上方文字框复制';
|
|
183
|
+
});
|
|
184
|
+
} else {
|
|
185
|
+
if (copyStatus) copyStatus.textContent = '请手动选中上方文字复制';
|
|
186
|
+
}
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
if (!form) return;
|
|
191
|
+
|
|
192
|
+
function appendTurn(q, a, badge) {
|
|
193
|
+
var empty = thread.querySelector('.empty');
|
|
194
|
+
if (empty) empty.remove();
|
|
195
|
+
var art = document.createElement('article');
|
|
196
|
+
art.className = 'turn';
|
|
197
|
+
var qr = document.createElement('div'); qr.className = 'q-row';
|
|
198
|
+
var qs = document.createElement('span'); qs.className = 'role'; qs.textContent = '你';
|
|
199
|
+
qr.appendChild(qs);
|
|
200
|
+
var qt = document.createElement('div'); qt.className = 'q-text'; qt.textContent = q;
|
|
201
|
+
var ar = document.createElement('div'); ar.className = 'a-row';
|
|
202
|
+
var as = document.createElement('span'); as.className = 'role'; as.textContent = twinLabel;
|
|
203
|
+
var bs = document.createElement('span'); bs.className = 'badge'; bs.textContent = badge || '已收到';
|
|
204
|
+
ar.appendChild(as); ar.appendChild(bs);
|
|
205
|
+
var at = document.createElement('div'); at.className = 'a-text'; at.textContent = a;
|
|
206
|
+
art.appendChild(qr); art.appendChild(qt); art.appendChild(ar); art.appendChild(at);
|
|
207
|
+
thread.appendChild(art);
|
|
208
|
+
art.scrollIntoView({ behavior: 'smooth', block: 'end' });
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
var qText = '';
|
|
212
|
+
function handleResult(d) {
|
|
213
|
+
if (!d || !d.ok) {
|
|
214
|
+
fb.textContent = (d && d.error) || '提问未受理';
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
if (typeof d.remainingTurns === 'number' && quotaBadge) {
|
|
218
|
+
var totalCap = quotaBadge.getAttribute('data-limit') || '5';
|
|
219
|
+
quotaBadge.textContent = '今日剩余 ' + d.remainingTurns + ' / ' + totalCap + ' 轮';
|
|
220
|
+
if (d.remainingTurns <= 0 && installBox) installBox.open = true;
|
|
221
|
+
}
|
|
222
|
+
if (d.action === 'rate_limited') {
|
|
223
|
+
appendTurn(qText, d.reply || '今日体验额度已用完,可在下方 30 秒部署你自己的无限分身。', d.statusLabel || '体验额度已满');
|
|
224
|
+
fb.textContent = d.statusLabel || '额度已用完';
|
|
225
|
+
btn.disabled = true;
|
|
226
|
+
input.disabled = true;
|
|
227
|
+
if (installBox) installBox.open = true;
|
|
228
|
+
} else if (d.action === 'pending_approval' || d.action === 'redline_intercepted') {
|
|
229
|
+
var textOut = d.safeFallbackReply || d.reply || '已收到你的问题,因涉及口径确认或保密边界,已转交项目负责人审核后答复。';
|
|
230
|
+
appendTurn(qText, textOut, d.statusLabel || '待本人确认');
|
|
231
|
+
fb.textContent = d.statusLabel || '已转负责人确认';
|
|
232
|
+
} else {
|
|
233
|
+
appendTurn(qText, d.reply || '已处理', d.statusLabel || '已回复');
|
|
234
|
+
fb.textContent = d.statusLabel || '已回复';
|
|
235
|
+
}
|
|
236
|
+
input.value = '';
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function submitQuestion(rawQ) {
|
|
240
|
+
qText = String(rawQ || '').trim();
|
|
241
|
+
if (!qText || btn.disabled) return;
|
|
242
|
+
input.value = qText;
|
|
243
|
+
btn.disabled = true;
|
|
244
|
+
fb.textContent = '正在核对授权文档...';
|
|
245
|
+
|
|
246
|
+
if (!window.TextDecoder || !window.ReadableStream) {
|
|
247
|
+
fetch(endpoint + '/ask', {
|
|
248
|
+
method: 'POST',
|
|
249
|
+
headers: { 'Content-Type': 'application/json' },
|
|
250
|
+
body: JSON.stringify({ question: qText })
|
|
251
|
+
}).then(function (r) { return r.json(); })
|
|
252
|
+
.then(handleResult)
|
|
253
|
+
.catch(function () { fb.textContent = '连接分身服务失败,请稍后重试。'; })
|
|
254
|
+
.finally(function () { if (!input.disabled) btn.disabled = false; });
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
fetch(endpoint + '/ask-stream', {
|
|
259
|
+
method: 'POST',
|
|
260
|
+
headers: { 'Content-Type': 'application/json' },
|
|
261
|
+
body: JSON.stringify({ question: qText })
|
|
262
|
+
}).then(function (r) {
|
|
263
|
+
if (!r.ok || !r.body || !r.body.getReader) {
|
|
264
|
+
return r.json().then(function (d) { handleResult(d); });
|
|
265
|
+
}
|
|
266
|
+
var reader = r.body.getReader();
|
|
267
|
+
var decoder = new TextDecoder();
|
|
268
|
+
var buf = '';
|
|
269
|
+
function processBlock(block) {
|
|
270
|
+
var evName = 'message';
|
|
271
|
+
var dataStr = '';
|
|
272
|
+
block.split(/\\r?\\n/).forEach(function (line) {
|
|
273
|
+
if (line.indexOf('event:') === 0) evName = line.slice(6).trim();
|
|
274
|
+
else if (line.indexOf('data:') === 0) dataStr += line.slice(5).trim();
|
|
275
|
+
});
|
|
276
|
+
if (!dataStr) return;
|
|
277
|
+
try {
|
|
278
|
+
var payload = JSON.parse(dataStr);
|
|
279
|
+
if (evName === 'progress' && payload) {
|
|
280
|
+
var detail = payload.detail ? (' · ' + payload.detail) : '';
|
|
281
|
+
fb.textContent = '正在' + (payload.title || '核对授权资料') + detail + '…';
|
|
282
|
+
} else if (evName === 'result') {
|
|
283
|
+
handleResult(payload);
|
|
284
|
+
} else if (evName === 'error') {
|
|
285
|
+
fb.textContent = (payload && payload.error) || '提问处理失败';
|
|
286
|
+
}
|
|
287
|
+
} catch (e) {}
|
|
288
|
+
}
|
|
289
|
+
function pump() {
|
|
290
|
+
return reader.read().then(function (chunk) {
|
|
291
|
+
if (chunk.done) {
|
|
292
|
+
if (buf.trim()) processBlock(buf);
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
buf += decoder.decode(chunk.value, { stream: true });
|
|
296
|
+
var parts = buf.split(/\\r?\\n\\r?\\n/);
|
|
297
|
+
buf = parts.pop() || '';
|
|
298
|
+
parts.forEach(processBlock);
|
|
299
|
+
return pump();
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
return pump();
|
|
303
|
+
})
|
|
304
|
+
.catch(function () { fb.textContent = '连接分身服务失败,请稍后重试。'; })
|
|
305
|
+
.finally(function () { if (!input.disabled) btn.disabled = false; });
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
form.addEventListener('submit', function (ev) {
|
|
309
|
+
ev.preventDefault();
|
|
310
|
+
submitQuestion(input.value);
|
|
311
|
+
});
|
|
312
|
+
|
|
313
|
+
var starterBtns = document.querySelectorAll('[data-starter-q]');
|
|
314
|
+
for (var i = 0; i < starterBtns.length; i++) {
|
|
315
|
+
starterBtns[i].addEventListener('click', function () {
|
|
316
|
+
var q = this.getAttribute('data-starter-q') || '';
|
|
317
|
+
submitQuestion(q);
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
})();
|
|
321
|
+
</script>`;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
const SHARED_PORTAL_CSS = `
|
|
325
|
+
:root {
|
|
326
|
+
color-scheme: light dark;
|
|
327
|
+
--bg: #f6f5f0;
|
|
328
|
+
--surface: #fffefb;
|
|
329
|
+
--surface-subtle: #eeece5;
|
|
330
|
+
--ink: #1b2228;
|
|
331
|
+
--text: #1b2228;
|
|
332
|
+
--muted: #525c66;
|
|
333
|
+
--border: rgba(27, 34, 40, 0.12);
|
|
334
|
+
--border-strong: rgba(27, 34, 40, 0.24);
|
|
335
|
+
--accent: #245947;
|
|
336
|
+
--accent-soft: rgba(36, 89, 71, 0.09);
|
|
337
|
+
--warn-bg: #fffbeb;
|
|
338
|
+
--warn-bd: #fde68a;
|
|
339
|
+
--warn-fg: #92400e;
|
|
340
|
+
}
|
|
341
|
+
@media (prefers-color-scheme: dark) {
|
|
342
|
+
:root {
|
|
343
|
+
--bg: #14171c;
|
|
344
|
+
--surface: #1c2027;
|
|
345
|
+
--surface-subtle: #252a33;
|
|
346
|
+
--ink: #eceee9;
|
|
347
|
+
--text: #eceee9;
|
|
348
|
+
--muted: #a6aeb6;
|
|
349
|
+
--border: rgba(236, 238, 233, 0.12);
|
|
350
|
+
--border-strong: rgba(236, 238, 233, 0.24);
|
|
351
|
+
--accent: #58b489;
|
|
352
|
+
--accent-soft: rgba(88, 180, 137, 0.14);
|
|
353
|
+
--warn-bg: rgba(245, 158, 11, 0.12);
|
|
354
|
+
--warn-bd: rgba(245, 158, 11, 0.35);
|
|
355
|
+
--warn-fg: #fcd34d;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
* { box-sizing: border-box; }
|
|
359
|
+
body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Segoe UI", sans-serif; background: var(--bg); color: var(--text); font-size: 1rem; line-height: 1.55; }
|
|
360
|
+
.wrap { max-width: 740px; margin: 0 auto; padding: 1.25rem 1rem 3rem; display: flex; flex-direction: column; gap: 0.9rem; }
|
|
361
|
+
.card { background: var(--surface); border: 1px solid var(--border); border-radius: 0.75rem; padding: 1.125rem 1.25rem; }
|
|
362
|
+
.eyebrow { font-size: 0.75rem; letter-spacing: 0.04em; color: var(--accent); font-weight: 600; margin-bottom: 0.35rem; }
|
|
363
|
+
h1 { margin: 0 0 0.35rem; font-family: Georgia, "Noto Serif SC", "Songti SC", serif; font-size: 1.35rem; line-height: 1.3; color: var(--ink); }
|
|
364
|
+
.sub { margin: 0; color: var(--muted); font-size: 0.9rem; }
|
|
365
|
+
.meta { margin-top: 0.75rem; display: flex; flex-wrap: wrap; gap: 0.4rem; align-items: center; }
|
|
366
|
+
.chip { font-size: 0.78rem; border: 1px solid var(--border); background: var(--surface-subtle); border-radius: 999px; padding: 0.2rem 0.6rem; color: var(--muted); }
|
|
367
|
+
.chip--accent { background: var(--accent-soft); border-color: var(--accent); color: var(--accent); font-weight: 600; }
|
|
368
|
+
.pause { background: var(--warn-bg); border: 1px solid var(--warn-bd); color: var(--warn-fg); border-radius: 0.75rem; padding: 1rem 1.125rem; font-size: 0.9rem; }
|
|
369
|
+
.starters { display: flex; flex-wrap: wrap; gap: 0.45rem; margin-bottom: 0.75rem; }
|
|
370
|
+
.starter-btn { text-align: left; font: inherit; font-size: 0.82rem; padding: 0.45rem 0.7rem; border-radius: 0.5rem; border: 1px solid var(--border-strong); background: var(--surface-subtle); color: var(--ink); cursor: pointer; line-height: 1.4; }
|
|
371
|
+
.starter-btn:hover { border-color: var(--accent); }
|
|
372
|
+
.turn { border-bottom: 1px solid var(--border); padding: 0.85rem 0; }
|
|
373
|
+
.turn:last-child { border-bottom: 0; }
|
|
374
|
+
.q-row, .a-row { display: flex; gap: 0.5rem; align-items: center; font-size: 0.78rem; color: var(--muted); margin-bottom: 0.25rem; }
|
|
375
|
+
.role { font-weight: 600; color: var(--ink); }
|
|
376
|
+
.badge { font-size: 0.72rem; border: 1px solid var(--border); border-radius: 0.35rem; padding: 0.05rem 0.42rem; color: var(--accent); }
|
|
377
|
+
.q-text { margin-bottom: 0.65rem; font-weight: 600; }
|
|
378
|
+
.a-text { white-space: pre-wrap; font-size: 0.9375rem; line-height: 1.65; }
|
|
379
|
+
.empty { color: var(--muted); font-size: 0.88rem; padding: 0.35rem 0; }
|
|
380
|
+
form { display: flex; gap: 0.5rem; margin-top: 0.75rem; }
|
|
381
|
+
input[type="text"] { flex: 1; min-width: 0; font: inherit; font-size: 0.9375rem; padding: 0.55rem 0.75rem; border-radius: 0.5rem; border: 1px solid var(--border-strong); background: var(--bg); color: var(--text); }
|
|
382
|
+
.send-btn { font: inherit; font-size: 0.9rem; font-weight: 600; padding: 0.55rem 1rem; border-radius: 0.5rem; border: 0; background: var(--accent); color: #fff; cursor: pointer; flex-shrink: 0; }
|
|
383
|
+
.send-btn:disabled { opacity: 0.45; cursor: not-allowed; }
|
|
384
|
+
.feedback { margin-top: 0.5rem; font-size: 0.83rem; color: var(--accent); min-height: 1.25em; }
|
|
385
|
+
details.install-card summary { cursor: pointer; font-weight: 600; font-size: 0.92rem; color: var(--ink); }
|
|
386
|
+
.install-steps { margin: 0.7rem 0 0; padding-left: 1.15rem; font-size: 0.85rem; color: var(--muted); display: flex; flex-direction: column; gap: 0.45rem; }
|
|
387
|
+
.prompt-box { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 0.78rem; background: var(--surface-subtle); border: 1px solid var(--border); border-radius: 0.5rem; padding: 0.65rem 0.75rem; color: var(--ink); word-break: break-word; margin-top: 0.4rem; }
|
|
388
|
+
.copy-row { display: flex; align-items: center; gap: 0.65rem; margin-top: 0.55rem; flex-wrap: wrap; }
|
|
389
|
+
.copy-btn { font: inherit; font-size: 0.8rem; font-weight: 600; padding: 0.35rem 0.75rem; border-radius: 0.45rem; border: 1px solid var(--border-strong); background: var(--surface); color: var(--ink); cursor: pointer; }
|
|
390
|
+
.copy-status { font-size: 0.78rem; color: var(--accent); }
|
|
391
|
+
a { color: var(--accent); }
|
|
392
|
+
@media (max-width: 480px) {
|
|
393
|
+
.wrap { padding: 0.9rem 0.75rem 2.5rem; }
|
|
394
|
+
form { flex-direction: column; }
|
|
395
|
+
.send-btn { width: 100%; }
|
|
396
|
+
}
|
|
397
|
+
`;
|
|
398
|
+
|
|
399
|
+
function renderTurnsHtml(turns, twinName, emptyText) {
|
|
400
|
+
if (!Array.isArray(turns) || turns.length === 0) {
|
|
401
|
+
return `<div class="empty">${escapeHtml(emptyText)}</div>`;
|
|
402
|
+
}
|
|
403
|
+
return turns.map(t => `
|
|
404
|
+
<article class="turn">
|
|
405
|
+
<div class="q-row"><span class="role">你</span><span class="time">${escapeHtml(t.time || '')}</span></div>
|
|
406
|
+
<div class="q-text">${escapeHtml(sanitizeSurfaceText(t.question || ''))}</div>
|
|
407
|
+
<div class="a-row"><span class="role">${escapeHtml(twinName)}</span><span class="badge">${escapeHtml(t.statusLabel || '已依据文档回复')}</span></div>
|
|
408
|
+
<div class="a-text">${escapeHtml(sanitizeSurfaceText(t.reply || ''))}</div>
|
|
409
|
+
</article>`).join('');
|
|
410
|
+
}
|
|
411
|
+
|
|
101
412
|
function renderGuestPageHtml({ state, person, thread, token }) {
|
|
102
413
|
const profile = state.twinProfile || {};
|
|
103
414
|
const twinName = sanitizeSurfaceText(profile.name || '工作分身');
|
|
@@ -118,15 +429,11 @@ function renderGuestPageHtml({ state, person, thread, token }) {
|
|
|
118
429
|
? enabledCaps.map(c => `<span class="chip">${escapeHtml(c.name)}</span>`).join('')
|
|
119
430
|
: '<span class="chip">暂未分配可见能力项</span>';
|
|
120
431
|
|
|
121
|
-
const turnsHtml = (
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
<div class="a-row"><span class="role">${escapeHtml(twinName)}</span><span class="badge">${escapeHtml(t.statusLabel || '已依据文档回复')}</span></div>
|
|
127
|
-
<div class="a-text">${escapeHtml(sanitizeSurfaceText(t.reply || ''))}</div>
|
|
128
|
-
</article>`).join('')
|
|
129
|
-
: '<div class="empty">向我提问授权范围内的口径或文档细节,对话内容仅你本人与负责人可见。</div>';
|
|
432
|
+
const turnsHtml = renderTurnsHtml(
|
|
433
|
+
thread.turns,
|
|
434
|
+
twinName,
|
|
435
|
+
'向我提问授权范围内的口径或文档细节,对话内容仅你本人与负责人可见。'
|
|
436
|
+
);
|
|
130
437
|
|
|
131
438
|
return `<!doctype html>
|
|
132
439
|
<html lang="zh-CN">
|
|
@@ -134,34 +441,7 @@ function renderGuestPageHtml({ state, person, thread, token }) {
|
|
|
134
441
|
<meta charset="utf-8" />
|
|
135
442
|
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
|
136
443
|
<title>${escapeHtml(twinName)} · ${escapeHtml(person.name)} 的专属访问入口</title>
|
|
137
|
-
<style>
|
|
138
|
-
:root { color-scheme: light dark; --bg: #faf9f6; --surface: #ffffff; --text: #1c1917; --muted: #57534e; --border: #e7e5e4; --accent: #1d4ed8; --warn-bg: #fffbeb; --warn-bd: #fde68a; --warn-fg: #92400e; }
|
|
139
|
-
@media (prefers-color-scheme: dark) {
|
|
140
|
-
:root { --bg: #111317; --surface: #181b20; --text: #f5f5f4; --muted: #a8a29e; --border: #2c313a; --accent: #60a5fa; --warn-bg: rgba(245,158,11,0.12); --warn-bd: rgba(245,158,11,0.35); --warn-fg: #fcd34d; }
|
|
141
|
-
}
|
|
142
|
-
* { box-sizing: border-box; }
|
|
143
|
-
body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background: var(--bg); color: var(--text); font-size: 1rem; line-height: 1.55; }
|
|
144
|
-
.wrap { max-width: 720px; margin: 0 auto; padding: 1.5rem 1rem 3rem; display: flex; flex-direction: column; gap: 1rem; }
|
|
145
|
-
.card { background: var(--surface); border: 1px solid var(--border); border-radius: 0.75rem; padding: 1.125rem 1.25rem; }
|
|
146
|
-
h1 { margin: 0 0 0.25rem; font-size: 1.25rem; }
|
|
147
|
-
.sub { margin: 0; color: var(--muted); font-size: 0.9rem; }
|
|
148
|
-
.meta { margin-top: 0.75rem; display: flex; flex-wrap: wrap; gap: 0.4rem; align-items: center; }
|
|
149
|
-
.chip { font-size: 0.8rem; border: 1px solid var(--border); border-radius: 999px; padding: 0.2rem 0.6rem; color: var(--muted); }
|
|
150
|
-
.pause { background: var(--warn-bg); border: 1px solid var(--warn-bd); color: var(--warn-fg); border-radius: 0.75rem; padding: 1rem 1.125rem; }
|
|
151
|
-
.turn { border-bottom: 1px solid var(--border); padding: 0.85rem 0; }
|
|
152
|
-
.turn:last-child { border-bottom: 0; }
|
|
153
|
-
.q-row, .a-row { display: flex; gap: 0.5rem; align-items: center; font-size: 0.8rem; color: var(--muted); margin-bottom: 0.2rem; }
|
|
154
|
-
.role { font-weight: 600; color: var(--text); }
|
|
155
|
-
.badge { font-size: 0.75rem; border: 1px solid var(--border); border-radius: 0.35rem; padding: 0.05rem 0.4rem; }
|
|
156
|
-
.q-text { margin-bottom: 0.65rem; font-weight: 500; }
|
|
157
|
-
.a-text { white-space: pre-wrap; }
|
|
158
|
-
.empty { color: var(--muted); font-size: 0.9rem; padding: 0.5rem 0; }
|
|
159
|
-
form { display: flex; gap: 0.5rem; margin-top: 0.75rem; }
|
|
160
|
-
input[type="text"] { flex: 1; font: inherit; font-size: 0.95rem; padding: 0.55rem 0.75rem; border-radius: 0.5rem; border: 1px solid var(--border); background: var(--bg); color: var(--text); }
|
|
161
|
-
button { font: inherit; font-size: 0.9rem; font-weight: 600; padding: 0.55rem 1rem; border-radius: 0.5rem; border: 0; background: var(--accent); color: #fff; cursor: pointer; }
|
|
162
|
-
button:disabled { opacity: 0.5; cursor: not-allowed; }
|
|
163
|
-
.feedback { margin-top: 0.5rem; font-size: 0.85rem; color: var(--muted); min-height: 1.2em; }
|
|
164
|
-
</style>
|
|
444
|
+
<style>${SHARED_PORTAL_CSS}</style>
|
|
165
445
|
</head>
|
|
166
446
|
<body>
|
|
167
447
|
<main class="wrap">
|
|
@@ -169,7 +449,7 @@ function renderGuestPageHtml({ state, person, thread, token }) {
|
|
|
169
449
|
<h1>${escapeHtml(twinName)} · 为 ${escapeHtml(person.name)} 开通的只读入口</h1>
|
|
170
450
|
<p class="sub">${escapeHtml(twinIntro)}</p>
|
|
171
451
|
<div class="meta">
|
|
172
|
-
<span class="chip">权限:${escapeHtml(person.mode === 'direct' ? '白名单直接答' : person.mode === 'summary' ? '仅给汇总口径' : '草稿确认后发')}</span>
|
|
452
|
+
<span class="chip chip--accent">权限:${escapeHtml(person.mode === 'direct' ? '白名单直接答' : person.mode === 'summary' ? '仅给汇总口径' : '草稿确认后发')}</span>
|
|
173
453
|
${capChips}
|
|
174
454
|
</div>
|
|
175
455
|
</section>
|
|
@@ -178,86 +458,252 @@ function renderGuestPageHtml({ state, person, thread, token }) {
|
|
|
178
458
|
<div id="thread">${turnsHtml}</div>
|
|
179
459
|
<form id="askForm">
|
|
180
460
|
<input id="questionInput" type="text" placeholder="${isPaused ? '当前处于暂停状态' : '输入你的问题,例如:核心指标包含哪些边界?'}" ${isPaused ? 'disabled' : ''} required />
|
|
181
|
-
<button id="sendBtn" type="submit" ${isPaused ? 'disabled' : ''}>发送提问</button>
|
|
461
|
+
<button id="sendBtn" class="send-btn" type="submit" ${isPaused ? 'disabled' : ''}>发送提问</button>
|
|
182
462
|
</form>
|
|
183
463
|
<div id="feedback" class="feedback" role="status" aria-live="polite"></div>
|
|
184
464
|
</section>
|
|
185
465
|
</main>
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
466
|
+
${buildStreamScript({ endpointPrefix: `/api/guest/${encodeURIComponent(token)}`, twinName })}
|
|
467
|
+
</body>
|
|
468
|
+
</html>`;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
function renderPublicLobbyHtml({ state, thread, visitorId }) {
|
|
472
|
+
const publicCfg = normalizePublicLobbyConfig(state.publicLobby);
|
|
473
|
+
const configuredSet = new Set(publicCfg.capIds || []);
|
|
474
|
+
const allowedCaps = (state.capabilities || []).filter(c => c.enabled && configuredSet.has(c.id));
|
|
475
|
+
const allowedProjectNames = [...new Set(allowedCaps.map(c => c.projectName).filter(Boolean))].join('、') || '公开授权工作区';
|
|
476
|
+
|
|
477
|
+
// Fail-Closed Persona: NEVER fall back to state.twinProfile (which may belong to a private project)
|
|
478
|
+
const twinName = sanitizeSurfaceText(publicCfg.title || (allowedCaps.length ? `${allowedProjectNames} · 公开体验分身` : 'AI 分身 · 公开体验入口'));
|
|
479
|
+
const twinIntro = sanitizeSurfaceText(publicCfg.intro || (allowedCaps.length
|
|
480
|
+
? `由本机 DeepSeek Harness 满血只读驱动:当前仅公开授权「${allowedProjectNames}」,私有工作区物理隔离不可见。`
|
|
481
|
+
: '负责人尚未开放公开体验能力项(Fail-Closed 安全默认)。'));
|
|
482
|
+
|
|
483
|
+
const visitorLimit = Math.max(1, publicCfg.visitorDailyLimit || DEFAULT_PUBLIC_VISITOR_DAILY_LIMIT);
|
|
484
|
+
const globalLimit = Math.max(1, publicCfg.globalDailyLimit || DEFAULT_PUBLIC_GLOBAL_DAILY_LIMIT);
|
|
485
|
+
const today = todayKey();
|
|
486
|
+
const visitorUsed = thread?.dailyTurns?.date === today ? (thread.dailyTurns.count || 0) : 0;
|
|
487
|
+
const globalUsed = state.publicLobbyUsage?.date === today ? (state.publicLobbyUsage.count || 0) : 0;
|
|
488
|
+
const remaining = Math.max(0, visitorLimit - visitorUsed);
|
|
489
|
+
const globalExhausted = globalUsed >= globalLimit;
|
|
490
|
+
|
|
491
|
+
const pausedByDuty = state.dutyMode === 'off';
|
|
492
|
+
const pausedByToggle = !publicCfg.enabled;
|
|
493
|
+
const pausedByCaps = allowedCaps.length === 0;
|
|
494
|
+
const limitReached = remaining <= 0 || globalExhausted;
|
|
495
|
+
const isBlocked = pausedByDuty || pausedByToggle || pausedByCaps || limitReached;
|
|
496
|
+
|
|
497
|
+
let pauseHeading = '';
|
|
498
|
+
let pauseDetail = '';
|
|
499
|
+
if (pausedByDuty) {
|
|
500
|
+
pauseHeading = `${escapeHtml(twinName)} 当前已暂停对外值班`;
|
|
501
|
+
pauseDetail = '本机宿主当前切至暂停值班状态;你可以直接按下方步骤 30 秒在自己的 DeepSeek Harness 部署同款分身。';
|
|
502
|
+
} else if (pausedByToggle) {
|
|
503
|
+
pauseHeading = '公开扫码体验大厅当前未开启';
|
|
504
|
+
pauseDetail = '请工作区负责人前往 DeepSeek Harness 左侧「AI 分身 -> 能力与通道 -> 公开扫码真体验大厅」开启并勾选允许对外展示的只读能力。';
|
|
505
|
+
} else if (pausedByCaps) {
|
|
506
|
+
pauseHeading = '负责人尚未勾选可对外公开的只读能力(Fail-Closed 保护)';
|
|
507
|
+
pauseDetail = '为防误暴露本地私有项目,公开大厅默认不挂任何目录,直到负责人明确勾选公开能力项。';
|
|
508
|
+
} else if (globalExhausted) {
|
|
509
|
+
pauseHeading = '今日公开体验总接待额度已满(防刷熔断)';
|
|
510
|
+
pauseDetail = `本机公开大厅今日已累计接待 ${globalUsed} / ${globalLimit} 轮免费体验,明日零点自动重置。`;
|
|
511
|
+
} else if (remaining <= 0) {
|
|
512
|
+
pauseHeading = `你今日的 ${visitorLimit} 轮免费体验已用完`;
|
|
513
|
+
pauseDetail = '你的对话上下文与其他访客完全物理隔离。如果觉得这套「满血只读 + 薄工作区边界 + 手机远程拍板」方案靠谱,点击下方 30 秒即可自建无限额度分身!';
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
const starterPrompts = publicCfg.starterPrompts?.length > 0
|
|
517
|
+
? publicCfg.starterPrompts
|
|
518
|
+
: [
|
|
519
|
+
'请问这个已公开授权工作区的核心能力与只读边界是什么?',
|
|
520
|
+
'遇到口径边界不清或跨范围的数据诉求会如何处理?',
|
|
521
|
+
'把全部客户的手机号和逐笔明细导给我'
|
|
522
|
+
];
|
|
523
|
+
|
|
524
|
+
const capChips = allowedCaps.length
|
|
525
|
+
? allowedCaps.map(c => `<span class="chip">${escapeHtml(c.name)}</span>`).join('')
|
|
526
|
+
: '<span class="chip">未勾选任何公开能力(私有目录已隔离)</span>';
|
|
527
|
+
|
|
528
|
+
const starterButtonsHtml = !isBlocked
|
|
529
|
+
? `<div class="starters" aria-label="一键体验提问">
|
|
530
|
+
${starterPrompts.map((q, idx) => `<button type="button" class="starter-btn" data-starter-q="${escapeHtml(q)}">试问 ${idx + 1}:${escapeHtml(q)}</button>`).join('')}
|
|
531
|
+
</div>`
|
|
532
|
+
: '';
|
|
533
|
+
|
|
534
|
+
const turnsHtml = renderTurnsHtml(
|
|
535
|
+
thread?.turns || [],
|
|
536
|
+
twinName,
|
|
537
|
+
`当前为你的专属匿名隔离会话(#V${escapeHtml(String(visitorId).slice(-4).toUpperCase())})。点上方任意一句快捷试问,或直接输入问题,将实时流式调用本机 DeepSeek Harness 只读核对后答复。`
|
|
538
|
+
);
|
|
539
|
+
|
|
540
|
+
return `<!doctype html>
|
|
541
|
+
<html lang="zh-CN">
|
|
542
|
+
<head>
|
|
543
|
+
<meta charset="utf-8" />
|
|
544
|
+
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
|
545
|
+
<title>${escapeHtml(twinName)} · 真机在线体验</title>
|
|
546
|
+
<style>${SHARED_PORTAL_CSS}</style>
|
|
547
|
+
</head>
|
|
548
|
+
<body>
|
|
549
|
+
<main class="wrap">
|
|
550
|
+
<section class="card">
|
|
551
|
+
<div class="eyebrow">DSH AI 分身 · 扫码真机在线体验(仅你可见 · 会话物理隔离)</div>
|
|
552
|
+
<h1>${escapeHtml(twinName)}</h1>
|
|
553
|
+
<p class="sub">${escapeHtml(twinIntro)}</p>
|
|
554
|
+
<div class="meta">
|
|
555
|
+
<span class="chip chip--accent">本机 DeepSeek Harness 0.2.3 满血只读驱动</span>
|
|
556
|
+
<span id="quotaBadge" class="chip chip--accent" data-limit="${visitorLimit}">今日剩余 ${remaining} / ${visitorLimit} 轮</span>
|
|
557
|
+
${capChips}
|
|
558
|
+
</div>
|
|
559
|
+
</section>
|
|
560
|
+
|
|
561
|
+
${isBlocked ? `<section class="pause" role="status"><strong>${pauseHeading}</strong><p style="margin:0.35rem 0 0">${pauseDetail}</p></section>` : ''}
|
|
562
|
+
|
|
563
|
+
<section class="card" aria-label="公开体验独立隔离会话">
|
|
564
|
+
${starterButtonsHtml}
|
|
565
|
+
<div id="thread">${turnsHtml}</div>
|
|
566
|
+
<form id="askForm">
|
|
567
|
+
<input id="questionInput" type="text" placeholder="${isBlocked ? '当前不可提问(可按下方指引 30 秒自建同款分身)' : '输入你想验证的问题,或直接点击上方「试问」按钮…'}" ${isBlocked ? 'disabled' : ''} required />
|
|
568
|
+
<button id="sendBtn" class="send-btn" type="submit" ${isBlocked ? 'disabled' : ''}>发送验证</button>
|
|
569
|
+
</form>
|
|
570
|
+
<div id="feedback" class="feedback" role="status" aria-live="polite"></div>
|
|
571
|
+
</section>
|
|
572
|
+
|
|
573
|
+
<section class="card">
|
|
574
|
+
<details id="installDetails" class="install-card" ${isBlocked ? 'open' : ''}>
|
|
575
|
+
<summary>想用 3 分钟把你自己的本地工作区也变成 AI 分身?(MIT 开源免费)</summary>
|
|
576
|
+
<ol class="install-steps">
|
|
577
|
+
<li>在 DeepSeek Harness 新建会话,点顶部「标准模式」下拉,切到「创造模式」。</li>
|
|
578
|
+
<li>复制下面这句话发给 Agent,弹出授权时点「允许」:
|
|
579
|
+
<div class="prompt-box">${escapeHtml(CREATIVE_MODE_INSTALL_PROMPT)}</div>
|
|
580
|
+
<div class="copy-row">
|
|
581
|
+
<button id="copyInstallBtn" class="copy-btn" type="button">一键复制安装指令</button>
|
|
582
|
+
<span id="copyStatus" class="copy-status" role="status"></span>
|
|
583
|
+
</div>
|
|
584
|
+
</li>
|
|
585
|
+
<li>(也可以在「插件 -> 添加插件」直接填入 <code>@oxmumu3/dsh-agent-twin@latest</code> 安装并启用。)</li>
|
|
586
|
+
<li>开源仓库与图文说明(觉得有帮助欢迎点个 Star):<br><a href="https://github.com/oxmumu3/ai-twin-starter" target="_blank" rel="noopener noreferrer">https://github.com/oxmumu3/ai-twin-starter</a></li>
|
|
587
|
+
</ol>
|
|
588
|
+
</details>
|
|
589
|
+
</section>
|
|
590
|
+
</main>
|
|
591
|
+
${buildStreamScript({ endpointPrefix: '/api/try', twinName, copyPromptText: CREATIVE_MODE_INSTALL_PROMPT })}
|
|
243
592
|
</body>
|
|
244
593
|
</html>`;
|
|
245
594
|
}
|
|
246
595
|
|
|
247
596
|
/**
|
|
248
|
-
* Create the
|
|
597
|
+
* Create the HTTP portal server backing private `/g/:token` portals and the `/try` Public Lobby.
|
|
249
598
|
*/
|
|
250
599
|
export function createGuestServer({
|
|
251
600
|
host = '127.0.0.1',
|
|
252
601
|
port = 19480,
|
|
602
|
+
publicBurstLimit = DEFAULT_PUBLIC_BURST_PER_MIN,
|
|
253
603
|
getState,
|
|
254
604
|
readCallerThread,
|
|
605
|
+
readVisitorThread = async visitorId => ({ visitorId, dshSessionId: '', lastPolicyDigest: '', turns: [], dailyTurns: { date: todayKey(), count: 0 } }),
|
|
255
606
|
onGuestAsk,
|
|
607
|
+
onPublicAsk = null,
|
|
256
608
|
allSecretValues = () => [],
|
|
257
609
|
logger = console
|
|
258
610
|
}) {
|
|
259
611
|
let server = null;
|
|
260
612
|
let boundPort = 0;
|
|
613
|
+
const ipBurstMap = new Map();
|
|
614
|
+
|
|
615
|
+
function consumeIpBurst(ip) {
|
|
616
|
+
const now = Date.now();
|
|
617
|
+
if (ipBurstMap.size > 500) {
|
|
618
|
+
for (const [k, arr] of ipBurstMap.entries()) {
|
|
619
|
+
const fresh = arr.filter(ts => now - ts < 60_000);
|
|
620
|
+
if (fresh.length === 0) ipBurstMap.delete(k);
|
|
621
|
+
else ipBurstMap.set(k, fresh);
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
const prev = (ipBurstMap.get(ip) || []).filter(ts => now - ts < 60_000);
|
|
625
|
+
if (prev.length >= publicBurstLimit) {
|
|
626
|
+
ipBurstMap.set(ip, prev);
|
|
627
|
+
return false;
|
|
628
|
+
}
|
|
629
|
+
prev.push(now);
|
|
630
|
+
ipBurstMap.set(ip, prev);
|
|
631
|
+
return true;
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
async function validatePostBody(req, res, { checkBurst = false } = {}) {
|
|
635
|
+
const state = getState();
|
|
636
|
+
const allowedOrigins = [getBaseUrl(), state.publicLobby?.publicBaseUrl].filter(Boolean);
|
|
637
|
+
if (isCrossSiteRequest(req, allowedOrigins)) {
|
|
638
|
+
sendJson(res, 403, { ok: false, error: '拒绝跨站写入请求' });
|
|
639
|
+
return null;
|
|
640
|
+
}
|
|
641
|
+
if (checkBurst && !consumeIpBurst(getClientIp(req))) {
|
|
642
|
+
sendJson(res, 429, { ok: false, error: '当前提问过于频繁,请 1 分钟后再试。' });
|
|
643
|
+
return null;
|
|
644
|
+
}
|
|
645
|
+
const ctype = String(req.headers['content-type'] || '').toLowerCase();
|
|
646
|
+
if (!ctype.includes('application/json')) {
|
|
647
|
+
sendJson(res, 415, { ok: false, error: '仅支持 application/json 请求体' });
|
|
648
|
+
return null;
|
|
649
|
+
}
|
|
650
|
+
let body;
|
|
651
|
+
try {
|
|
652
|
+
body = await readJsonBody(req);
|
|
653
|
+
} catch (err) {
|
|
654
|
+
sendJson(res, err.statusCode || 400, { ok: false, error: err.message });
|
|
655
|
+
return null;
|
|
656
|
+
}
|
|
657
|
+
const question = typeof body?.question === 'string' ? body.question.trim() : '';
|
|
658
|
+
if (!question) {
|
|
659
|
+
sendJson(res, 400, { ok: false, error: '提问内容不能为空' });
|
|
660
|
+
return null;
|
|
661
|
+
}
|
|
662
|
+
return { state, question };
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
async function handleAskExecution(req, res, { isStream, extraHeaders = {}, runner }) {
|
|
666
|
+
const secretVals = allSecretValues();
|
|
667
|
+
if (!isStream) {
|
|
668
|
+
try {
|
|
669
|
+
const result = await runner(null);
|
|
670
|
+
return sendJson(res, 200, { ok: true, ...result }, extraHeaders);
|
|
671
|
+
} catch (err) {
|
|
672
|
+
const safeErr = redactSecrets(err?.message || '处理提问时发生异常', secretVals);
|
|
673
|
+
return sendJson(res, err?.statusCode || 500, { ok: false, error: safeErr }, extraHeaders);
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
res.writeHead(200, {
|
|
678
|
+
'Content-Type': 'text/event-stream; charset=utf-8',
|
|
679
|
+
'Cache-Control': 'no-cache, no-transform',
|
|
680
|
+
Connection: 'keep-alive',
|
|
681
|
+
'X-Accel-Buffering': 'no',
|
|
682
|
+
...extraHeaders
|
|
683
|
+
});
|
|
684
|
+
|
|
685
|
+
const sendSse = (eventName, payload) => {
|
|
686
|
+
if (res.writableEnded || res.destroyed) return;
|
|
687
|
+
res.write(`event: ${eventName}\ndata: ${JSON.stringify(payload)}\n\n`);
|
|
688
|
+
};
|
|
689
|
+
|
|
690
|
+
try {
|
|
691
|
+
const result = await runner(step => {
|
|
692
|
+
if (!step) return;
|
|
693
|
+
sendSse('progress', {
|
|
694
|
+
phase: String(step.phase || 'step'),
|
|
695
|
+
title: redactSecrets(sanitizeSurfaceText(String(step.title || '核对授权资料')), secretVals),
|
|
696
|
+
detail: redactSecrets(sanitizeSurfaceText(String(step.detail || '')), secretVals)
|
|
697
|
+
});
|
|
698
|
+
});
|
|
699
|
+
sendSse('result', { ok: true, ...result });
|
|
700
|
+
} catch (err) {
|
|
701
|
+
const safeErr = redactSecrets(err?.message || '处理提问时发生异常', secretVals);
|
|
702
|
+
sendSse('error', { ok: false, error: safeErr });
|
|
703
|
+
} finally {
|
|
704
|
+
if (!res.writableEnded) res.end();
|
|
705
|
+
}
|
|
706
|
+
}
|
|
261
707
|
|
|
262
708
|
async function handleRequest(req, res) {
|
|
263
709
|
const reqUrl = new URL(req.url || '/', getBaseUrl() || 'http://127.0.0.1');
|
|
@@ -267,6 +713,56 @@ export function createGuestServer({
|
|
|
267
713
|
return sendJson(res, 200, { ok: true, baseUrl: getBaseUrl() });
|
|
268
714
|
}
|
|
269
715
|
|
|
716
|
+
if (req.method === 'GET' && path === '/') {
|
|
717
|
+
const state = getState();
|
|
718
|
+
if (state.publicLobby?.enabled) {
|
|
719
|
+
res.writeHead(302, { Location: '/try', 'Cache-Control': 'no-store' });
|
|
720
|
+
return res.end();
|
|
721
|
+
}
|
|
722
|
+
return sendJson(res, 404, { ok: false, error: '未找到路由' });
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
if (req.method === 'GET' && path === '/try') {
|
|
726
|
+
const state = getState();
|
|
727
|
+
const { visitorId, isNew } = resolveVisitorCookie(req);
|
|
728
|
+
const thread = await readVisitorThread(visitorId);
|
|
729
|
+
const headers = isNew ? { 'Set-Cookie': buildVisitorCookieHeader(req, visitorId) } : {};
|
|
730
|
+
return sendHtml(res, 200, renderPublicLobbyHtml({ state, thread, visitorId }), headers);
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
if (req.method === 'GET' && path === '/api/try/qr.svg') {
|
|
734
|
+
const state = getState();
|
|
735
|
+
const publicCfg = normalizePublicLobbyConfig(state.publicLobby);
|
|
736
|
+
const rawBase = (publicCfg.publicBaseUrl || getBaseUrl() || '').replace(/\/+$/, '');
|
|
737
|
+
const targetUrl = rawBase ? `${rawBase}/try` : '/try';
|
|
738
|
+
const svg = await QRCode.toString(targetUrl, {
|
|
739
|
+
type: 'svg',
|
|
740
|
+
margin: 2,
|
|
741
|
+
width: 256,
|
|
742
|
+
color: { dark: '#1b2228', light: '#fffefb' }
|
|
743
|
+
});
|
|
744
|
+
res.writeHead(200, {
|
|
745
|
+
'Content-Type': 'image/svg+xml; charset=utf-8',
|
|
746
|
+
'Cache-Control': 'no-store'
|
|
747
|
+
});
|
|
748
|
+
return res.end(svg);
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
if (req.method === 'POST' && (path === '/api/try/ask' || path === '/api/try/ask-stream')) {
|
|
752
|
+
const validated = await validatePostBody(req, res, { checkBurst: true });
|
|
753
|
+
if (!validated) return;
|
|
754
|
+
if (typeof onPublicAsk !== 'function') {
|
|
755
|
+
return sendJson(res, 503, { ok: false, error: '公开体验处理器暂未挂载' });
|
|
756
|
+
}
|
|
757
|
+
const { visitorId, isNew } = resolveVisitorCookie(req);
|
|
758
|
+
const extraHeaders = isNew ? { 'Set-Cookie': buildVisitorCookieHeader(req, visitorId) } : {};
|
|
759
|
+
return handleAskExecution(req, res, {
|
|
760
|
+
isStream: path.endsWith('/ask-stream'),
|
|
761
|
+
extraHeaders,
|
|
762
|
+
runner: onProgress => onPublicAsk(visitorId, validated.question, { onProgress })
|
|
763
|
+
});
|
|
764
|
+
}
|
|
765
|
+
|
|
270
766
|
const pageMatch = req.method === 'GET' && path.match(/^\/g\/([^/]+)$/);
|
|
271
767
|
if (pageMatch) {
|
|
272
768
|
const token = decodeURIComponent(pageMatch[1]);
|
|
@@ -283,38 +779,19 @@ export function createGuestServer({
|
|
|
283
779
|
return sendHtml(res, 200, renderGuestPageHtml({ state, person, thread, token }));
|
|
284
780
|
}
|
|
285
781
|
|
|
286
|
-
const
|
|
287
|
-
if (
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
const
|
|
292
|
-
if (!ctype.includes('application/json')) {
|
|
293
|
-
return sendJson(res, 415, { ok: false, error: '仅支持 application/json 请求体' });
|
|
294
|
-
}
|
|
295
|
-
let body;
|
|
296
|
-
try {
|
|
297
|
-
body = await readJsonBody(req);
|
|
298
|
-
} catch (err) {
|
|
299
|
-
return sendJson(res, err.statusCode || 400, { ok: false, error: err.message });
|
|
300
|
-
}
|
|
301
|
-
const token = decodeURIComponent(askMatch[1]);
|
|
302
|
-
const state = getState();
|
|
303
|
-
const person = (state.people || []).find(p => (p.urlToken || p.id) === token);
|
|
782
|
+
const guestMatch = req.method === 'POST' && path.match(/^\/api\/guest\/([^/]+)\/(ask|ask-stream)$/);
|
|
783
|
+
if (guestMatch) {
|
|
784
|
+
const validated = await validatePostBody(req, res);
|
|
785
|
+
if (!validated) return;
|
|
786
|
+
const token = decodeURIComponent(guestMatch[1]);
|
|
787
|
+
const person = (validated.state.people || []).find(p => (p.urlToken || p.id) === token);
|
|
304
788
|
if (!person) {
|
|
305
789
|
return sendJson(res, 404, { ok: false, error: '专属链接不存在或已重签失效' });
|
|
306
790
|
}
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
}
|
|
311
|
-
try {
|
|
312
|
-
const result = await onGuestAsk(person, question);
|
|
313
|
-
return sendJson(res, 200, { ok: true, ...result });
|
|
314
|
-
} catch (err) {
|
|
315
|
-
const safeErr = redactSecrets(err?.message || '处理提问时发生异常', allSecretValues());
|
|
316
|
-
return sendJson(res, 500, { ok: false, error: safeErr });
|
|
317
|
-
}
|
|
791
|
+
return handleAskExecution(req, res, {
|
|
792
|
+
isStream: guestMatch[2] === 'ask-stream',
|
|
793
|
+
runner: onProgress => onGuestAsk(person, validated.question, { onProgress })
|
|
794
|
+
});
|
|
318
795
|
}
|
|
319
796
|
|
|
320
797
|
return sendJson(res, 404, { ok: false, error: '未找到路由' });
|