dsh-remote-peers 0.3.63 → 0.3.138
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 +4 -1
- package/README.zh-CN.md +7 -1
- package/index.mjs +145 -94
- package/lib/client.js +3833 -2429
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -35,6 +35,7 @@ Both machines run this plugin. On the machine you want to reach, the panel shows
|
|
|
35
35
|
|
|
36
36
|
- **Sessions**: every session of the peer, grouped by the peer's workspaces, archived ones pushed to the bottom
|
|
37
37
|
- **Chat**: read history in pages, send a prompt, watch the reply stream in; thinking rows, code blocks, markdown and file cards follow the host app's look
|
|
38
|
+
- **Attachments**: paste files with Ctrl+V or pick them from `+ → 文件`; images arrive as 64×64 thumbnails, every other file as a 240×64 file card. Each draft uploads to the peer as soon as it is picked and is sent with the prompt as a `{ type: 'file', receiptId }` part
|
|
38
39
|
- **Approvals and questions**: approve or answer here; the decision is relayed to the peer
|
|
39
40
|
- **Files**: preview PDF / Word / Excel / PPT / images / text in the right pane; downloads land in one shared local copy, and *Open*, *Download* and *Show in folder* all reuse it
|
|
40
41
|
- **Run state**: a remote session that is still working keeps showing its running state, including after you reopen the panel
|
|
@@ -63,6 +64,7 @@ Exposed through the gateway (token required):
|
|
|
63
64
|
Local-only routes (the browser talks to its own Host; peer tokens stay there):
|
|
64
65
|
|
|
65
66
|
- `/remote-peers` RPC: `status`, `token/reset`, `peers/list|upsert|remove|ping`, `proxy`, `file/size(s)`, `open-local`, `local/copy`, `download/status|save|cancel`, `diag`
|
|
67
|
+
- `POST /api/remote-peers/upload?id=<peer>&sessionId=<id>[&name=<name>][&mediaType=<type>]` → the raw request body is streamed to the peer's own `/api/session/uploadFileBinary`; returns that route's `{ ok, value: { receiptId, image | file } }`
|
|
66
68
|
- `GET|HEAD /api/remote-peers/file?id=<peer>&path=<absolute path>[&v=<version>][&download=1]`
|
|
67
69
|
- `GET /api/remote-peers/export|markdown|stream|call|diag|vendor|office|present-open|changes`
|
|
68
70
|
|
|
@@ -70,6 +72,7 @@ Local-only routes (the browser talks to its own Host; peer tokens stay there):
|
|
|
70
72
|
|
|
71
73
|
- **LAN only.** No NAT traversal or relay yet; both machines must reach each other directly (same subnet, or a VPN that keeps layer-3 reachability).
|
|
72
74
|
- **The sidebar cannot nest.** DSH's `sidebar.panellist` is a flat list, and `sidebar.workspaces` is a single slot already owned by the host. So the plugin registers one entry per peer and renders the workspace tree inside the session list page.
|
|
75
|
+
- **Attachments stream as bytes.** A picked file leaves the browser as the request body of the local `/api/remote-peers/upload` route and is piped to the peer without base64 expansion, the same path the desktop app takes. Footprint is one in-flight request per file; very large archives still belong to the file *download* path.
|
|
73
76
|
- **Preview only, no editing.** Formats mirror the host's renderers (PDF via pdf.js, Office via the peer's `officeKit`).
|
|
74
77
|
- **No `Trajectory` tab.** It needs event-level call trees, which this plugin does not reconstruct.
|
|
75
78
|
- **`Show in folder` takes about 2 seconds.** Explorer itself takes that long to raise a window, so the button shows a fixed 2-second "Opening…" state instead of polling for the window.
|
|
@@ -83,7 +86,7 @@ npm run probe # headless render smoke for the panel
|
|
|
83
86
|
npm run audit # dead declarations / duplicated blocks in src/client.js
|
|
84
87
|
```
|
|
85
88
|
|
|
86
|
-
Layout: `index.mjs` is the Host face (gateway, routes, local copies); `src/client.js` is the Client face (panel UI); `scripts/build.mjs` bundles the client; `probes/` holds smoke scripts; `vendor/pdfjs` carries the assets the preview serves. Deep implementation notes live in [`docs/internals.zh-CN.md`](docs/internals.zh-CN.md) (Chinese).
|
|
89
|
+
Layout: `index.mjs` is the Host face (gateway, routes, local copies); `src/client.js` is the Client face (panel UI: state, RPC, layout), with `src/theme.js` (style tokens), `src/icons.js` (inline SVG glyphs), `src/preview.js` (PDF/image/Excel preview) and `src/conversation.js` (model, usage and process-label helpers) split out; `scripts/build.mjs` bundles the client; `probes/` holds smoke scripts; `vendor/pdfjs` carries the assets the preview serves. Deep implementation notes live in [`docs/internals.zh-CN.md`](docs/internals.zh-CN.md) (Chinese).
|
|
87
90
|
|
|
88
91
|
## License
|
|
89
92
|
|
package/README.zh-CN.md
CHANGED
|
@@ -38,6 +38,8 @@ dsh plugin --profile desktop remove dsh-remote-peers
|
|
|
38
38
|
|
|
39
39
|
- **会话**:对端的全部会话,按对端工作区分组,已归档的置底
|
|
40
40
|
- **对话**:分页读历史、发消息、流式接收回复;思考行、代码块、Markdown、文件卡片都对齐宿主外观
|
|
41
|
+
- **附件**:`Ctrl+V` 直接粘贴,或从 `+ → 文件` 选;图片成 64×64 缩略图,其余文件成 240×64 文件卡。
|
|
42
|
+
选中即开始上传到对端,发送时随正文带一张 `{ type: 'file', receiptId }` 收据
|
|
41
43
|
- **审批 / 提问**:在本侧批准或作答,决定回传给对端
|
|
42
44
|
- **文件**:右侧预览 PDF / Word / Excel / PPT / 图片 / 文本;下载落进同一份本机副本,
|
|
43
45
|
**打开**、**下载**、**显示文件位置** 共用这份副本
|
|
@@ -71,6 +73,8 @@ dsh plugin --profile desktop remove dsh-remote-peers
|
|
|
71
73
|
|
|
72
74
|
- `/remote-peers` RPC:`status`、`token/reset`、`peers/list|upsert|remove|ping`、`proxy`、`file/size(s)`、
|
|
73
75
|
`open-local`、`local/copy`、`download/status|save|cancel`、`diag`
|
|
76
|
+
- `POST /api/remote-peers/upload?id=<peer>&sessionId=<id>[&name=<名字>][&mediaType=<类型>]` →
|
|
77
|
+
请求体原样流给节点自己的 `/api/session/uploadFileBinary`,回那条路由的 `{ ok, value: { receiptId, image | file } }`
|
|
74
78
|
- `GET|HEAD /api/remote-peers/file?id=<peer>&path=<绝对路径>[&v=<版本>][&download=1]`
|
|
75
79
|
- `GET /api/remote-peers/export|markdown|stream|call|diag|vendor|office|present-open|changes`
|
|
76
80
|
|
|
@@ -80,6 +84,8 @@ dsh plugin --profile desktop remove dsh-remote-peers
|
|
|
80
84
|
- **侧栏做不成文件夹。** 宿主的 `sidebar.panellist` 是平铺列表,`sidebar.workspaces` 是单槽且已被宿主占用,
|
|
81
85
|
所以本插件给每个他端注册一条入口,把工作区树放在会话列表页里。
|
|
82
86
|
- **只做预览,不做编辑。** 各格式对齐宿主渲染链(PDF 走 pdf.js,Office 走对端 `officeKit`)。
|
|
87
|
+
- **附件按字节流过去。** 选中的文件直接作为本机 `/api/remote-peers/upload` 的请求体发出,网关原样转给节点,
|
|
88
|
+
不再做 base64 展开,与桌面端同一条路径;占用是每份文件一条在途请求,几百 MB 的大包仍建议走文件**下载**那条路。
|
|
83
89
|
- **没有「轨迹」tab。** 它需要事件级调用树,本插件不重建。
|
|
84
90
|
- **「显示文件位置」固定约 2 秒。** 资源管理器起窗本身就要这么久,按钮固定显示 2 秒「正在打开…」,不再轮询窗口。
|
|
85
91
|
|
|
@@ -92,7 +98,7 @@ npm run probe # 面板的无头渲染冒烟
|
|
|
92
98
|
npm run audit # src/client.js 的死声明 / 重复块检查
|
|
93
99
|
```
|
|
94
100
|
|
|
95
|
-
结构:`index.mjs` 是 Host 面(网关、路由、本机副本);`src/client.js` 是 Client
|
|
101
|
+
结构:`index.mjs` 是 Host 面(网关、路由、本机副本);`src/client.js` 是 Client 面入口(面板 UI 的状态、RPC 与布局),样式令牌、图标字形、预览与语义助手分别拆在 `src/theme.js`、`src/icons.js`、`src/preview.js`、`src/conversation.js`;
|
|
96
102
|
`scripts/build.mjs` 打客户端产物;`probes/` 是冒烟脚本;`vendor/pdfjs` 是预览要用的资源。
|
|
97
103
|
实现细节见 [`docs/internals.zh-CN.md`](docs/internals.zh-CN.md)。
|
|
98
104
|
|
package/index.mjs
CHANGED
|
@@ -185,12 +185,13 @@ export function apply(ctx, config = {}) {
|
|
|
185
185
|
case 'file/size': {
|
|
186
186
|
const id = typeof payload?.id === 'string' ? payload.id : ''
|
|
187
187
|
const peerEntry = peerById(id)
|
|
188
|
-
if (peerEntry === undefined) return fail('remote-peers/unknown-peer',
|
|
188
|
+
if (peerEntry === undefined) return fail('remote-peers/unknown-peer', `未知节点 ${JSON.stringify(id)}`)
|
|
189
189
|
const source = typeof payload?.path === 'string' ? payload.path : ''
|
|
190
190
|
if (!isAbsoluteFsPath(source)) return fail('remote-peers/bad-path', '需要绝对文件路径')
|
|
191
191
|
const sessionId = typeof payload?.sessionId === 'string' ? payload.sessionId : ''
|
|
192
|
-
|
|
193
|
-
|
|
192
|
+
const probe = await remoteProbeOf(peerEntry, source, sessionId, signal)
|
|
193
|
+
if (probe.missing === true) missing[source] = true
|
|
194
|
+
sizes[source] = typeof probe.size === 'number' && probe.size > 0 ? probe.size : null
|
|
194
195
|
hostDiag(`size host ${source} session=${sessionId === '' ? '-' : sessionId} -> ${String(size ?? 'unknown')}`)
|
|
195
196
|
if (size === undefined) return fail('remote-peers/size-unknown', '对端没有给出文件大小')
|
|
196
197
|
return ok({ size })
|
|
@@ -200,15 +201,16 @@ export function apply(ctx, config = {}) {
|
|
|
200
201
|
// 不让一个坏路径拖垮整批(前端把 null 记成 error 占位,不再重问)。
|
|
201
202
|
const id = typeof payload?.id === 'string' ? payload.id : ''
|
|
202
203
|
const peerEntry = peerById(id)
|
|
203
|
-
if (peerEntry === undefined) return fail('remote-peers/unknown-peer',
|
|
204
|
+
if (peerEntry === undefined) return fail('remote-peers/unknown-peer', `未知节点 ${JSON.stringify(id)}`)
|
|
204
205
|
const sessionId = typeof payload?.sessionId === 'string' ? payload.sessionId : ''
|
|
205
206
|
const wanted = Array.isArray(payload?.paths) ? payload.paths : []
|
|
206
207
|
const paths = wanted
|
|
207
208
|
.filter((item) => typeof item === 'string' && item !== '' && !item.includes('\0') && isAbsoluteFsPath(item))
|
|
208
209
|
.slice(0, 200)
|
|
209
|
-
if (paths.length === 0) return ok({ sizes: {}, locals: {} })
|
|
210
|
+
if (paths.length === 0) return ok({ sizes: {}, locals: {}, missing: {} })
|
|
210
211
|
const sizes = {}
|
|
211
212
|
const locals = {}
|
|
213
|
+
const missing = {}
|
|
212
214
|
await runPool(paths, 4, async (source) => {
|
|
213
215
|
// 「本机是否已有副本」是纯本地 stat,顺路带回给前端,卡片据此显示「已下载」。
|
|
214
216
|
locals[source] = hasLocalCopy(localCopyPathOf(peerEntry.id, source))
|
|
@@ -221,7 +223,7 @@ export function apply(ctx, config = {}) {
|
|
|
221
223
|
}
|
|
222
224
|
})
|
|
223
225
|
hostDiag(`size batch ${paths.length} -> ${paths.filter((item) => typeof sizes[item] === 'number').length} hit, ${paths.filter((item) => locals[item] === true).length} local`)
|
|
224
|
-
return ok({ sizes, locals })
|
|
226
|
+
return ok({ sizes, locals, missing })
|
|
225
227
|
}
|
|
226
228
|
case 'open-local':
|
|
227
229
|
return ok(await openLocal(payload, signal))
|
|
@@ -229,7 +231,7 @@ export function apply(ctx, config = {}) {
|
|
|
229
231
|
// 「显示文件位置」用的探针:只回答本机有没有这份副本,绝不顺手去下载。
|
|
230
232
|
const id = typeof payload?.id === 'string' ? payload.id : ''
|
|
231
233
|
const peerEntry = peerById(id)
|
|
232
|
-
if (peerEntry === undefined) return fail('remote-peers/unknown-peer',
|
|
234
|
+
if (peerEntry === undefined) return fail('remote-peers/unknown-peer', `未知节点 ${JSON.stringify(id)}`)
|
|
233
235
|
const source = typeof payload?.path === 'string' ? payload.path : ''
|
|
234
236
|
if (source === '' || source.includes('\0') || !isAbsoluteFsPath(source)) {
|
|
235
237
|
return fail('remote-peers/bad-path', '需要绝对文件路径')
|
|
@@ -258,12 +260,17 @@ export function apply(ctx, config = {}) {
|
|
|
258
260
|
// 不再弹「另存为」:直接落到本机副本目录。已有副本就当场返回 `reused`,一次字节都不取。
|
|
259
261
|
const id = typeof payload?.id === 'string' ? payload.id : ''
|
|
260
262
|
const peerEntry = peerById(id)
|
|
261
|
-
if (peerEntry === undefined) return fail('remote-peers/unknown-peer',
|
|
263
|
+
if (peerEntry === undefined) return fail('remote-peers/unknown-peer', `未知节点 ${JSON.stringify(id)}`)
|
|
262
264
|
const source = typeof payload?.path === 'string' ? payload.path : ''
|
|
263
265
|
if (source === '' || source.includes('\0') || !isAbsoluteFsPath(source)) {
|
|
264
266
|
return fail('remote-peers/bad-path', '需要绝对文件路径')
|
|
265
267
|
}
|
|
266
268
|
const sessionId = typeof payload?.sessionId === 'string' ? payload.sessionId : ''
|
|
269
|
+
// 点下载先确认这份文件还在:对端已清理掉就直接回「不存在」,不建任务、不进 loading。
|
|
270
|
+
const localPath = localCopyPathOf(peerEntry.id, source)
|
|
271
|
+
if (!hasLocalCopy(localPath) && (await remoteProbeOf(peerEntry, source, sessionId, signal)).missing === true) {
|
|
272
|
+
return fail('remote-peers/file-missing', '对端上没有这份文件(可能已被清理或移动)')
|
|
273
|
+
}
|
|
267
274
|
const started = startCopy(peerEntry, source, sessionId, '下载')
|
|
268
275
|
return ok({
|
|
269
276
|
key: started.key,
|
|
@@ -273,14 +280,22 @@ export function apply(ctx, config = {}) {
|
|
|
273
280
|
reused: started.reused,
|
|
274
281
|
})
|
|
275
282
|
}
|
|
276
|
-
case 'download/cancel': {
|
|
277
|
-
|
|
278
|
-
const
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
283
|
+
case 'download/cancel': {
|
|
284
|
+
// 取消允许两种寻址:精确 key,或 id + path(分隔符/大小写对不上时按路径找)。
|
|
285
|
+
const key = typeof payload?.key === 'string' ? payload.key : ''
|
|
286
|
+
const byId = typeof payload?.id === 'string' ? payload.id : ''
|
|
287
|
+
const byPath = typeof payload?.path === 'string' ? payload.path : ''
|
|
288
|
+
const samePath = (value) => String(value).replace(/[/\\]+/gu, '\\').toLowerCase()
|
|
289
|
+
const target = liveTransfers.get(key)
|
|
290
|
+
?? (byPath === ''
|
|
291
|
+
? undefined
|
|
292
|
+
: [...liveTransfers.values()].find((entry) => (byId === '' || entry.peerId === byId) && samePath(entry.path) === samePath(byPath)))
|
|
293
|
+
// 已经没有这条任务也算取消成功:前端只需要一个「停掉它」的回答,不该再弹失败。
|
|
294
|
+
if (target === undefined) return ok({ cancelled: key, missing: true })
|
|
295
|
+
target.abort?.()
|
|
296
|
+
liveTransfers.delete(target.key)
|
|
297
|
+
return ok({ cancelled: target.key })
|
|
298
|
+
}
|
|
284
299
|
case 'diag': {
|
|
285
300
|
// TEMP-DIAG:把渲染器一侧探测到的结果落到 stateDir/diag.log(渲染器 console 无处可看)。
|
|
286
301
|
const line = `${new Date().toISOString()} ${JSON.stringify(payload)}\n`
|
|
@@ -480,6 +495,16 @@ export function apply(ctx, config = {}) {
|
|
|
480
495
|
* 有 `v` 取版本串第三段(`<inode>:<…>:<size>:…`),否则用 `content-length`。
|
|
481
496
|
*/
|
|
482
497
|
async function remoteSizeOf(peerEntry, source, sessionId, signal) {
|
|
498
|
+
const probe = await remoteProbeOf(peerEntry, source, sessionId, signal)
|
|
499
|
+
return probe.size
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/**
|
|
503
|
+
* 对端这份文件的「大小 / 是否已经不在了」。只有 `workspaceFiles/stat` 或 `/api/file`
|
|
504
|
+
* 明确回 not-found / 404 才判 missing,超时、旧版本端点缺失一律不下结论(免得误伤可下载的文件)。
|
|
505
|
+
* @returns `{ size?: number, missing?: true }`
|
|
506
|
+
*/
|
|
507
|
+
async function remoteProbeOf(peerEntry, source, sessionId, signal) {
|
|
483
508
|
if (typeof sessionId === 'string' && sessionId !== '') {
|
|
484
509
|
const statUrl = upstreamUrl(peerEntry, '/api/workspaceFiles/stat')
|
|
485
510
|
const stat = await fetch(statUrl, {
|
|
@@ -495,22 +520,26 @@ export function apply(ctx, config = {}) {
|
|
|
495
520
|
})
|
|
496
521
|
if (stat.ok) {
|
|
497
522
|
const body = await stat.json().catch(() => undefined)
|
|
498
|
-
const
|
|
499
|
-
if (
|
|
523
|
+
const result = body?.result
|
|
524
|
+
if (String(result?.error?.code ?? '').includes('not-found')) return { missing: true }
|
|
525
|
+
const value = result?.value
|
|
526
|
+
if (result?.ok === true && typeof value?.bytes === 'number' && value.bytes > 0) return { size: value.bytes }
|
|
527
|
+
// stat 成功但没有字节数(0 字节/目录):交给 /api/file 兜底,别在这里猜。
|
|
500
528
|
}
|
|
501
529
|
}
|
|
502
530
|
const upstream = upstreamUrl(peerEntry, '/api/file')
|
|
503
531
|
upstream.searchParams.set('path', source)
|
|
504
532
|
const response = await fetch(upstream, { headers: peerHeaders(peerEntry), redirect: 'manual', signal })
|
|
505
533
|
await response.body?.cancel().catch(() => {})
|
|
534
|
+
if (response.status === 404) return { missing: true }
|
|
506
535
|
const token = /[?&]v=([^&]+)/u.exec(response.headers.get('location') ?? '')
|
|
507
536
|
if (token !== null) {
|
|
508
537
|
const fields = decodeURIComponent(token[1]).split(':')
|
|
509
538
|
const size = Number(fields[2] ?? Number.NaN)
|
|
510
|
-
if (Number.isFinite(size) && size > 0) return size
|
|
539
|
+
if (Number.isFinite(size) && size > 0) return { size }
|
|
511
540
|
}
|
|
512
541
|
const length = Number(response.headers.get('content-length') ?? Number.NaN)
|
|
513
|
-
return Number.isFinite(length) && length > 0 ? length :
|
|
542
|
+
return Number.isFinite(length) && length > 0 ? { size: length } : {}
|
|
514
543
|
}
|
|
515
544
|
|
|
516
545
|
/** 原名做目录里的文件名:去掉 Windows 不允许的字符,保留中文。 */
|
|
@@ -589,7 +618,7 @@ export function apply(ctx, config = {}) {
|
|
|
589
618
|
async function openLocal(payload, signal) {
|
|
590
619
|
const startedAt = Date.now()
|
|
591
620
|
const peerEntry = peerById(typeof payload?.id === 'string' ? payload.id : undefined)
|
|
592
|
-
if (peerEntry === undefined) throw new Error('
|
|
621
|
+
if (peerEntry === undefined) throw new Error('未找到该节点,请先在列表里登记')
|
|
593
622
|
const source = typeof payload?.path === 'string' ? payload.path : ''
|
|
594
623
|
if (source === '' || source.includes('\0') || !isAbsoluteFsPath(source)) throw new Error('需要绝对文件路径')
|
|
595
624
|
const action = payload?.action === 'reveal' ? 'reveal' : 'open'
|
|
@@ -695,32 +724,14 @@ export function apply(ctx, config = {}) {
|
|
|
695
724
|
})
|
|
696
725
|
},
|
|
697
726
|
}
|
|
698
|
-
const streamRoute =
|
|
699
|
-
|
|
700
|
-
methods: ['GET'],
|
|
701
|
-
requestBody: 'buffered',
|
|
702
|
-
fetch: async (request) => {
|
|
703
|
-
const url = new URL(request.url)
|
|
704
|
-
const id = url.searchParams.get('id')
|
|
705
|
-
const peerEntry = peerById(id)
|
|
706
|
-
if (peerEntry === undefined) return new Response('unknown peer', { status: 404 })
|
|
727
|
+
const streamRoute = peerPassRoute('/api/remote-peers/stream', '/remote-peers/stream',
|
|
728
|
+
(url) => {
|
|
707
729
|
const endpoint = url.searchParams.get('endpoint')
|
|
708
730
|
const payload = url.searchParams.get('payload')
|
|
709
|
-
if (endpoint === null || payload === null) return
|
|
710
|
-
|
|
711
|
-
upstream.searchParams.set('endpoint', endpoint)
|
|
712
|
-
upstream.searchParams.set('payload', payload)
|
|
713
|
-
const response = await fetch(upstream, {
|
|
714
|
-
headers: peerHeaders(peerEntry),
|
|
715
|
-
signal: request.signal,
|
|
716
|
-
})
|
|
717
|
-
if (!response.ok) return new Response(`upstream ${response.status}`, { status: 502 })
|
|
718
|
-
return new Response(response.body, {
|
|
719
|
-
status: 200,
|
|
720
|
-
headers: { 'content-type': 'text/event-stream; charset=utf-8', 'cache-control': 'no-cache, no-transform' },
|
|
721
|
-
})
|
|
731
|
+
if (endpoint === null || payload === null) return 'missing endpoint or payload'
|
|
732
|
+
return { endpoint, payload }
|
|
722
733
|
},
|
|
723
|
-
|
|
734
|
+
() => ({ 'content-type': 'text/event-stream; charset=utf-8', 'cache-control': 'no-cache, no-transform' }))
|
|
724
735
|
// 会话导出:把对端的 `GET /api/session.export` 原样转成本机的一条下载路由,
|
|
725
736
|
// 浏览器只与本机通信,对端令牌不出 Host。
|
|
726
737
|
|
|
@@ -757,67 +768,61 @@ function peerHeaders(peerEntry) {
|
|
|
757
768
|
return { [TOKEN_HEADER]: peerEntry.token }
|
|
758
769
|
}
|
|
759
770
|
|
|
760
|
-
|
|
761
|
-
|
|
771
|
+
/**
|
|
772
|
+
* 对端 `GET <upstreamPath>?…` 的直通路由:查 peer → 组查询串 → 带令牌转发 → 回写指定响应头。
|
|
773
|
+
* `paramsOf(url)` 返回要转发的查询参数,或返回一段文案表示参数不合法(回 400)。
|
|
774
|
+
* 404/400/502 的口径与原各条路由一致。
|
|
775
|
+
* @param path - 本机暴露的路由路径
|
|
776
|
+
* @param upstreamPath - 对端路径(`/api/…`)
|
|
777
|
+
* @param paramsOf - `(url) => Record<string,string> | string`
|
|
778
|
+
* @param headersOf - `(response, params) => Record<string,string>`,写回浏览器的响应头
|
|
779
|
+
* @returns 路由定义
|
|
780
|
+
*/
|
|
781
|
+
function peerPassRoute(path, upstreamPath, paramsOf, headersOf) {
|
|
782
|
+
return {
|
|
783
|
+
path,
|
|
762
784
|
methods: ['GET'],
|
|
763
785
|
requestBody: 'buffered',
|
|
764
786
|
fetch: async (request) => {
|
|
765
787
|
const url = new URL(request.url)
|
|
766
|
-
const
|
|
767
|
-
const peerEntry = peerById(id)
|
|
788
|
+
const peerEntry = peerById(url.searchParams.get('id'))
|
|
768
789
|
if (peerEntry === undefined) return new Response('unknown peer', { status: 404 })
|
|
769
|
-
const
|
|
770
|
-
if (
|
|
771
|
-
const upstream = upstreamUrl(peerEntry,
|
|
772
|
-
upstream.searchParams.set(
|
|
773
|
-
upstream
|
|
774
|
-
const response = await fetch(upstream, {
|
|
775
|
-
headers: peerHeaders(peerEntry),
|
|
776
|
-
signal: request.signal,
|
|
777
|
-
})
|
|
790
|
+
const params = paramsOf(url)
|
|
791
|
+
if (typeof params === 'string') return new Response(params, { status: 400 })
|
|
792
|
+
const upstream = upstreamUrl(peerEntry, upstreamPath)
|
|
793
|
+
for (const [name, value] of Object.entries(params)) upstream.searchParams.set(name, value)
|
|
794
|
+
const response = await fetch(upstream, { headers: peerHeaders(peerEntry), signal: request.signal })
|
|
778
795
|
if (!response.ok) return new Response(`upstream ${response.status}`, { status: 502 })
|
|
779
|
-
|
|
780
|
-
?? `attachment; filename="dsh-session-${sessionId}.zip"`
|
|
781
|
-
return new Response(response.body, {
|
|
782
|
-
status: 200,
|
|
783
|
-
headers: {
|
|
784
|
-
'content-type': response.headers.get('content-type') ?? 'application/zip',
|
|
785
|
-
'content-disposition': disposition,
|
|
786
|
-
'cache-control': 'no-store',
|
|
787
|
-
},
|
|
788
|
-
})
|
|
796
|
+
return new Response(response.body, { status: 200, headers: headersOf(response, params) })
|
|
789
797
|
},
|
|
790
798
|
}
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
const exportRoute = peerPassRoute('/api/remote-peers/export', '/api/session.export',
|
|
802
|
+
(url) => {
|
|
803
|
+
const sessionId = url.searchParams.get('sessionId')
|
|
804
|
+
if (sessionId === null || sessionId === '') return 'missing sessionId'
|
|
805
|
+
return { sessionId, includeDescendants: url.searchParams.get('includeDescendants') ?? 'true' }
|
|
806
|
+
},
|
|
807
|
+
(response, params) => ({
|
|
808
|
+
'content-type': response.headers.get('content-type') ?? 'application/zip',
|
|
809
|
+
'content-disposition': response.headers.get('content-disposition')
|
|
810
|
+
?? `attachment; filename="dsh-session-${params.sessionId}.zip"`,
|
|
811
|
+
'cache-control': 'no-store',
|
|
812
|
+
}))
|
|
791
813
|
|
|
792
814
|
// 复制会话为 Markdown:把对端的 `GET /api/session.markdown` 转成本机一条路由,
|
|
793
815
|
// 对端 Host 自己按会话日志生成 Markdown(原生同一实现),令牌不出 Host。
|
|
794
|
-
const markdownRoute =
|
|
795
|
-
|
|
796
|
-
methods: ['GET'],
|
|
797
|
-
requestBody: 'buffered',
|
|
798
|
-
fetch: async (request) => {
|
|
799
|
-
const url = new URL(request.url)
|
|
800
|
-
const id = url.searchParams.get('id')
|
|
801
|
-
const peerEntry = peerById(id)
|
|
802
|
-
if (peerEntry === undefined) return new Response('unknown peer', { status: 404 })
|
|
816
|
+
const markdownRoute = peerPassRoute('/api/remote-peers/markdown', '/api/session.markdown',
|
|
817
|
+
(url) => {
|
|
803
818
|
const sessionId = url.searchParams.get('sessionId')
|
|
804
|
-
if (sessionId === null || sessionId === '') return
|
|
805
|
-
|
|
806
|
-
upstream.searchParams.set('sessionId', sessionId)
|
|
807
|
-
const response = await fetch(upstream, {
|
|
808
|
-
headers: peerHeaders(peerEntry),
|
|
809
|
-
signal: request.signal,
|
|
810
|
-
})
|
|
811
|
-
if (!response.ok) return new Response(`upstream ${response.status}`, { status: 502 })
|
|
812
|
-
return new Response(response.body, {
|
|
813
|
-
status: 200,
|
|
814
|
-
headers: {
|
|
815
|
-
'content-type': response.headers.get('content-type') ?? 'text/markdown; charset=utf-8',
|
|
816
|
-
'cache-control': 'no-store',
|
|
817
|
-
},
|
|
818
|
-
})
|
|
819
|
+
if (sessionId === null || sessionId === '') return 'missing sessionId'
|
|
820
|
+
return { sessionId }
|
|
819
821
|
},
|
|
820
|
-
|
|
822
|
+
(response) => ({
|
|
823
|
+
'content-type': response.headers.get('content-type') ?? 'text/markdown; charset=utf-8',
|
|
824
|
+
'cache-control': 'no-store',
|
|
825
|
+
}))
|
|
821
826
|
|
|
822
827
|
// 预览 / 下载:把对端的 `GET|HEAD /api/file?path=` 转成本机一条路由。
|
|
823
828
|
// 对端在缺 `v` 时 302 到带版本号的 URL;这里把重定向改写成指回本路由(保留 id),
|
|
@@ -911,6 +916,7 @@ function peerHeaders(peerEntry) {
|
|
|
911
916
|
upstream.searchParams.set('path', source)
|
|
912
917
|
upstream.searchParams.set('download', '1')
|
|
913
918
|
const response = await fetch(upstream, { headers: peerHeaders(peerEntry), signal })
|
|
919
|
+
if (response.status === 404) throw new Error('对端上没有这份文件(可能已被清理或移动)')
|
|
914
920
|
if (!response.ok) throw new Error(`对端返回 HTTP ${response.status}`)
|
|
915
921
|
let written = 0
|
|
916
922
|
await pipeline(Readable.fromWeb(response.body), async function* (chunks) {
|
|
@@ -1101,7 +1107,14 @@ function peerHeaders(peerEntry) {
|
|
|
1101
1107
|
})
|
|
1102
1108
|
if (!response.ok) throw new Error(`upstream ${response.status}`)
|
|
1103
1109
|
const boundary = /boundary=([^;]+)/u.exec(response.headers.get('content-type') ?? '')
|
|
1104
|
-
if (boundary === null)
|
|
1110
|
+
if (boundary === null) {
|
|
1111
|
+
// 对端没给分区数据就是信封错误:`not-found` 说明文件已被清理,换成能读懂的文案。
|
|
1112
|
+
const body = await response.json().catch(() => undefined)
|
|
1113
|
+
const error = body?.result?.error
|
|
1114
|
+
if (String(error?.code ?? '').includes('not-found')) throw new Error('对端上没有这份文件(可能已被清理或移动)')
|
|
1115
|
+
if (typeof error?.message === 'string' && error.message !== '') throw new Error(error.message)
|
|
1116
|
+
return undefined
|
|
1117
|
+
}
|
|
1105
1118
|
const buffer = Buffer.from(await response.arrayBuffer())
|
|
1106
1119
|
return extractMultipartPart(buffer, boundary[1].trim().replace(/^"|"$/gu, ''))
|
|
1107
1120
|
}
|
|
@@ -1238,6 +1251,44 @@ function peerHeaders(peerEntry) {
|
|
|
1238
1251
|
},
|
|
1239
1252
|
}
|
|
1240
1253
|
|
|
1254
|
+
// 附件上行:浏览器把 `File` 的字节直接投给本机网关,网关原样流给节点自己的
|
|
1255
|
+
// `/api/session/uploadFileBinary`(原生 Client 同一条路由),不经过 JSON-RPC 的 base64 展开。
|
|
1256
|
+
const uploadRoute = {
|
|
1257
|
+
path: '/api/remote-peers/upload',
|
|
1258
|
+
methods: ['POST'],
|
|
1259
|
+
requestBody: 'streaming',
|
|
1260
|
+
fetch: async (request) => {
|
|
1261
|
+
const url = new URL(request.url)
|
|
1262
|
+
const peerEntry = peerById(url.searchParams.get('id'))
|
|
1263
|
+
if (peerEntry === undefined) return new Response('unknown peer', { status: 404 })
|
|
1264
|
+
const sessionId = url.searchParams.get('sessionId')
|
|
1265
|
+
if (sessionId === null || sessionId === '') return new Response('missing sessionId', { status: 400 })
|
|
1266
|
+
const query = new URLSearchParams({ sessionId })
|
|
1267
|
+
// 带 `mediaType` 的按提示词图片存放;名字用于节点侧保留原始文件名。
|
|
1268
|
+
const name = url.searchParams.get('name')
|
|
1269
|
+
if (name !== null && name !== '') query.set('name', name)
|
|
1270
|
+
const mediaType = url.searchParams.get('mediaType')
|
|
1271
|
+
if (mediaType !== null && mediaType !== '') query.set('mediaType', mediaType)
|
|
1272
|
+
const response = await fetch(
|
|
1273
|
+
`http://${peerEntry.host}:${peerEntry.port}/api/session/uploadFileBinary?${query.toString()}`,
|
|
1274
|
+
{
|
|
1275
|
+
method: 'POST',
|
|
1276
|
+
headers: { 'content-type': 'application/octet-stream', [TOKEN_HEADER]: peerEntry.token },
|
|
1277
|
+
body: request.body,
|
|
1278
|
+
duplex: 'half',
|
|
1279
|
+
signal: request.signal,
|
|
1280
|
+
},
|
|
1281
|
+
)
|
|
1282
|
+
return new Response(response.body, {
|
|
1283
|
+
status: response.status,
|
|
1284
|
+
headers: {
|
|
1285
|
+
'content-type': response.headers.get('content-type') ?? 'application/json; charset=utf-8',
|
|
1286
|
+
'cache-control': 'no-store',
|
|
1287
|
+
},
|
|
1288
|
+
})
|
|
1289
|
+
},
|
|
1290
|
+
}
|
|
1291
|
+
|
|
1241
1292
|
// 本轮改动摘要/对比:把对端的 `GET /api/changes.summary|changes.diff` 转成本机一条路由。
|
|
1242
1293
|
const changesRoute = {
|
|
1243
1294
|
path: '/api/remote-peers/changes',
|
|
@@ -1279,7 +1330,7 @@ function peerHeaders(peerEntry) {
|
|
|
1279
1330
|
}
|
|
1280
1331
|
|
|
1281
1332
|
// 与通道注册同理:重载瞬间旧实例可能还没释放这条精确路由。
|
|
1282
|
-
const fetchRoutes = [streamRoute, exportRoute, markdownRoute, fileRoute, downloadRoute, vendorRoute, diagRoute, officeRoute, presentOpenRoute, changesRoute, callRoute]
|
|
1333
|
+
const fetchRoutes = [streamRoute, exportRoute, markdownRoute, fileRoute, downloadRoute, vendorRoute, diagRoute, officeRoute, presentOpenRoute, changesRoute, uploadRoute, callRoute]
|
|
1283
1334
|
const registerFetchRoute = (attempt = 0) => {
|
|
1284
1335
|
try {
|
|
1285
1336
|
for (const route of fetchRoutes) connection.fetch.register(route)
|