@fish-under-sea/dsh-ssh-fish 0.0.0-stage → 0.5.0
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/LICENSE +202 -0
- package/README.i18n.yaml +6 -0
- package/README.md +98 -2
- package/README.zh.md +99 -0
- package/cordis.patch.yml +12 -0
- package/icon.svg +3 -0
- package/lib/client.js +16487 -0
- package/lib/client.js.map +1 -0
- package/lib/index.js +3511 -0
- package/lib/types/client/api.d.ts +141 -0
- package/lib/types/client/index.d.ts +37 -0
- package/lib/types/client/locales.d.ts +164 -0
- package/lib/types/client/native-panel.d.ts +70 -0
- package/lib/types/client/panel/ClusterTab.d.ts +7 -0
- package/lib/types/client/panel/HostFormDialog.d.ts +12 -0
- package/lib/types/client/panel/HostsTab.d.ts +25 -0
- package/lib/types/client/panel/SshPanel.d.ts +14 -0
- package/lib/types/client/panel/TerminalTab.d.ts +22 -0
- package/lib/types/client/panel/TransferTab.d.ts +7 -0
- package/lib/types/client/panel/TunnelsTab.d.ts +19 -0
- package/lib/types/client/panel/controller.d.ts +89 -0
- package/lib/types/client/panel/helpers.d.ts +45 -0
- package/lib/types/client/panel/xterm.css.d.ts +2 -0
- package/lib/types/client/settings-binding.d.ts +61 -0
- package/lib/types/dsh-home.d.ts +16 -0
- package/lib/types/engine/cluster.d.ts +19 -0
- package/lib/types/engine/connection-pool.d.ts +112 -0
- package/lib/types/engine/proxy-command.d.ts +36 -0
- package/lib/types/engine/pty.d.ts +32 -0
- package/lib/types/engine/sftp.d.ts +20 -0
- package/lib/types/engine/terminal-sessions.d.ts +67 -0
- package/lib/types/engine/tunnel.d.ts +36 -0
- package/lib/types/engine.d.ts +89 -0
- package/lib/types/http.d.ts +59 -0
- package/lib/types/index.d.ts +83 -0
- package/lib/types/loopback.d.ts +24 -0
- package/lib/types/mount-once.d.ts +55 -0
- package/lib/types/protocol.d.ts +239 -0
- package/lib/types/routes.d.ts +33 -0
- package/lib/types/ssh-config.d.ts +34 -0
- package/lib/types/store.d.ts +71 -0
- package/lib/types/tool-surface.d.ts +71 -0
- package/lib/types/tools.d.ts +42 -0
- package/package.json +106 -4
- package/src/client/api.ts +562 -0
- package/src/client/css-modules.d.ts +5 -0
- package/src/client/index.ts +137 -0
- package/src/client/locales.ts +338 -0
- package/src/client/native-panel.tsx +141 -0
- package/src/client/panel/ClusterTab.tsx +123 -0
- package/src/client/panel/HostFormDialog.tsx +258 -0
- package/src/client/panel/HostsTab.tsx +325 -0
- package/src/client/panel/SshPanel.tsx +90 -0
- package/src/client/panel/TerminalTab.tsx +330 -0
- package/src/client/panel/TransferTab.tsx +232 -0
- package/src/client/panel/TunnelsTab.tsx +244 -0
- package/src/client/panel/controller.ts +167 -0
- package/src/client/panel/helpers.ts +84 -0
- package/src/client/panel/panel.module.css +876 -0
- package/src/client/panel/xterm.css.ts +2 -0
- package/src/client/settings-binding.ts +165 -0
- package/src/dsh-home.ts +42 -0
- package/src/engine/cluster.ts +60 -0
- package/src/engine/connection-pool.ts +543 -0
- package/src/engine/proxy-command.ts +248 -0
- package/src/engine/pty.ts +78 -0
- package/src/engine/sftp.ts +226 -0
- package/src/engine/terminal-sessions.ts +280 -0
- package/src/engine/tunnel.ts +194 -0
- package/src/engine.ts +176 -0
- package/src/http.ts +127 -0
- package/src/index.ts +234 -0
- package/src/loopback.ts +63 -0
- package/src/mount-once.ts +142 -0
- package/src/protocol.ts +230 -0
- package/src/routes.ts +494 -0
- package/src/ssh-config.ts +153 -0
- package/src/store.ts +419 -0
- package/src/tool-surface.ts +95 -0
- package/src/tools.ts +404 -0
package/src/http.ts
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
// Generated by scripts/sync-shared.mjs from shared/host/http.ts. Do not edit this copy; edit the shared source and run "node scripts/sync-shared.mjs".
|
|
2
|
+
/**
|
|
3
|
+
* Shared JSON body/response helpers for the host route families: one strict
|
|
4
|
+
* bounded body reader, one lenient bounded body reader, one JSON object
|
|
5
|
+
* narrow, one JSON writer, and the outbound request-init helper that keeps a
|
|
6
|
+
* host fetch body decodable (withIdentityEncoding). Previously the readers
|
|
7
|
+
* were copy-pasted across the
|
|
8
|
+
* package route files (routes.ts, update-routes.ts, mobile-api.ts, and each
|
|
9
|
+
* family's route module) with drifting contracts: body caps ranging 4 KiB to
|
|
10
|
+
* 1 MiB and four distinct overflow behaviors (reject, undefined, null, throw).
|
|
11
|
+
*
|
|
12
|
+
* Packages receive this file as a generated copy via scripts/sync-shared.mjs;
|
|
13
|
+
* edit this shared source and re-run the sync instead of editing a copy.
|
|
14
|
+
* Consumer code is migrated onto it in follow-up waves; no call site changes
|
|
15
|
+
* belong in the same change as its introduction.
|
|
16
|
+
* @module dsh-web-shared/host/http
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import type { IncomingMessage, OutgoingHttpHeaders, ServerResponse } from 'node:http'
|
|
20
|
+
|
|
21
|
+
/** Default body cap for readJsonBody: 64 KiB. */
|
|
22
|
+
const DEFAULT_JSON_BODY_MAX_BYTES = 64 * 1024
|
|
23
|
+
|
|
24
|
+
/** Family-default JSON response headers; callers may append or override. */
|
|
25
|
+
const JSON_HEADERS = {
|
|
26
|
+
'content-type': 'application/json; charset=utf-8',
|
|
27
|
+
'referrer-policy': 'no-referrer',
|
|
28
|
+
} satisfies OutgoingHttpHeaders
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Strict bounded body reader: parse a request body of at most maxBytes as
|
|
32
|
+
* JSON.
|
|
33
|
+
* @throws 'body too large' past the cap, or the JSON.parse error for an
|
|
34
|
+
* invalid or empty payload.
|
|
35
|
+
*/
|
|
36
|
+
export async function readBoundedJson(req: IncomingMessage, maxBytes: number): Promise<unknown> {
|
|
37
|
+
const chunks: Buffer[] = []
|
|
38
|
+
let size = 0
|
|
39
|
+
for await (const chunk of req) {
|
|
40
|
+
const buffer = chunk as Buffer
|
|
41
|
+
size += buffer.length
|
|
42
|
+
if (size > maxBytes) throw new Error('body too large')
|
|
43
|
+
chunks.push(buffer)
|
|
44
|
+
}
|
|
45
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'))
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Lenient bounded body reader: parse a request body as JSON, or null on an
|
|
50
|
+
* empty body, invalid JSON, or a body past maxBytes (default 64 KiB).
|
|
51
|
+
* Overflow destroys the request instead of draining the remainder (no drain
|
|
52
|
+
* call, matching the current repo-wide behavior); callers must not keep
|
|
53
|
+
* reading the request afterwards. With objectOnly, non-JSON-object payloads
|
|
54
|
+
* also yield null.
|
|
55
|
+
*/
|
|
56
|
+
export async function readJsonBody(
|
|
57
|
+
req: IncomingMessage,
|
|
58
|
+
opts: { maxBytes?: number; objectOnly?: boolean } = {},
|
|
59
|
+
): Promise<unknown | null> {
|
|
60
|
+
const maxBytes = opts.maxBytes ?? DEFAULT_JSON_BODY_MAX_BYTES
|
|
61
|
+
const chunks: Buffer[] = []
|
|
62
|
+
let size = 0
|
|
63
|
+
for await (const chunk of req) {
|
|
64
|
+
const buffer = chunk as Buffer
|
|
65
|
+
size += buffer.length
|
|
66
|
+
if (size > maxBytes) {
|
|
67
|
+
req.destroy()
|
|
68
|
+
return null
|
|
69
|
+
}
|
|
70
|
+
chunks.push(buffer)
|
|
71
|
+
}
|
|
72
|
+
const text = Buffer.concat(chunks).toString('utf8')
|
|
73
|
+
if (text === '') return null
|
|
74
|
+
try {
|
|
75
|
+
const parsed: unknown = JSON.parse(text)
|
|
76
|
+
if (opts.objectOnly && !isJsonObject(parsed)) return null
|
|
77
|
+
return parsed
|
|
78
|
+
} catch {
|
|
79
|
+
return null
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Whether a value is a JSON object: typeof object, not null, not an array. */
|
|
84
|
+
function isJsonObject(value: unknown): value is Record<string, unknown> {
|
|
85
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Narrow a value to a JSON object, or undefined when it is not one. */
|
|
89
|
+
export function asJsonObject(value: unknown): Record<string, unknown> | undefined {
|
|
90
|
+
return isJsonObject(value) ? value : undefined
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Request init that asks a remote origin for an uncompressed body.
|
|
95
|
+
*
|
|
96
|
+
* The DSH host boots `@deepseek-ai/dsh-http-proxy`, whose top-level import of
|
|
97
|
+
* the npm `undici` copy replaces the legacy `undici.globalDispatcher.1` slot
|
|
98
|
+
* Node's built-in `fetch()` reads. That cross-major wrapper drops the
|
|
99
|
+
* `content-encoding` header and automatic decompression, so a plain fetch
|
|
100
|
+
* resolves to raw gzip/brotli/zstd bytes — compressed noise no JSON or text
|
|
101
|
+
* consumer can read. Every host fetch that parses a remote body must request
|
|
102
|
+
* identity encoding. Caller headers survive; `accept-encoding` is forced to
|
|
103
|
+
* `identity` because a caller value has no decoder behind it in this host.
|
|
104
|
+
* @param init - the caller's request init (signal, headers, method, ...).
|
|
105
|
+
* @returns a copy with `accept-encoding: identity` merged in.
|
|
106
|
+
*/
|
|
107
|
+
export function withIdentityEncoding(init: RequestInit = {}): RequestInit {
|
|
108
|
+
const headers = new Headers(init.headers)
|
|
109
|
+
headers.set('accept-encoding', 'identity')
|
|
110
|
+
return { ...init, headers }
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Write one JSON response. Default headers are the family defaults
|
|
115
|
+
* (content-type and referrer-policy); caller headers are appended or
|
|
116
|
+
* override them.
|
|
117
|
+
*/
|
|
118
|
+
export function writeJson(
|
|
119
|
+
res: ServerResponse,
|
|
120
|
+
status: number,
|
|
121
|
+
body: unknown,
|
|
122
|
+
headers: OutgoingHttpHeaders = {},
|
|
123
|
+
): void {
|
|
124
|
+
const payload = JSON.stringify(body)
|
|
125
|
+
res.writeHead(status, { ...JSON_HEADERS, ...headers })
|
|
126
|
+
res.end(payload)
|
|
127
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-ssh — host half. Mounts the SSH engine (persistent ssh2 connection
|
|
3
|
+
* pool, exec / PTY shell / SFTP / tunnels / cluster), the /api/dsh-ssh route
|
|
4
|
+
* family plus the terminal WebSocket upgrade, the agent tools (ssh_list,
|
|
5
|
+
* ssh_exec, ssh_upload, ssh_download, ssh_tunnel, ssh_cluster), and a
|
|
6
|
+
* system-prompt announcement. The browser half (./client) renders the host
|
|
7
|
+
* manager and web terminal. Everything rides official NPM SDK packages —
|
|
8
|
+
* no dsh source changes.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { Context, Fiber } from '@deepseek-ai/cordis'
|
|
12
|
+
import z from '@deepseek-ai/schemastery'
|
|
13
|
+
import type {} from '@deepseek-ai/dsh-host-webserver'
|
|
14
|
+
import type {} from '@deepseek-ai/dsh-system-prompt'
|
|
15
|
+
import type {} from '@deepseek-ai/dsh-tools'
|
|
16
|
+
import { SshEngine } from './engine.ts'
|
|
17
|
+
import { makeRoutes } from './routes.ts'
|
|
18
|
+
import { HostStore } from './store.ts'
|
|
19
|
+
import { sshClusterTool, sshDownloadTool, sshExecTool, sshListTool, sshTunnelTool, sshUploadTool } from './tools.ts'
|
|
20
|
+
import { mountOnce } from './mount-once.ts'
|
|
21
|
+
import { PLUGIN_TOOL_SECTION_ORDERS, visibleToolText } from './tool-surface.ts'
|
|
22
|
+
|
|
23
|
+
/** Stable cordis plugin name. */
|
|
24
|
+
export const name = 'ssh'
|
|
25
|
+
|
|
26
|
+
/** Services required before the SSH surfaces can mount. */
|
|
27
|
+
export const inject = ['webServer', 'tools', 'systemPrompt']
|
|
28
|
+
|
|
29
|
+
declare module '@deepseek-ai/cordis' {
|
|
30
|
+
interface Events {
|
|
31
|
+
/**
|
|
32
|
+
* Volatile config values were committed into the running instance without a
|
|
33
|
+
* remount (cordis-plugin-loader); dispatched to the owning fiber only.
|
|
34
|
+
* @param paths - the changed config paths, as key arrays.
|
|
35
|
+
* @mode emit
|
|
36
|
+
*/
|
|
37
|
+
'loader/volatile-update'(paths: readonly (readonly string[])[]): void
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Plugin config as a profile patch declares it, before schema resolution. */
|
|
42
|
+
export interface Config {
|
|
43
|
+
/**
|
|
44
|
+
* When true, a system-prompt section announces the SSH plugin to every agent
|
|
45
|
+
* (tools + host store). Off by default to keep prompts clean.
|
|
46
|
+
*/
|
|
47
|
+
announceToAgent?: boolean
|
|
48
|
+
/** Master switch for the plugin (routes, tools, prompt section). */
|
|
49
|
+
enabled?: boolean
|
|
50
|
+
/**
|
|
51
|
+
* xterm `fontFamily` for the web terminal (issue #577). Empty (default)
|
|
52
|
+
* defers to the CSS chain: `--dsh-ssh-terminal-font`, then the official
|
|
53
|
+
* `--ds-font-family-code` token, then the built-in monospace stack. Set a
|
|
54
|
+
* Nerd Font stack here to render powerline/Nerd glyphs.
|
|
55
|
+
*/
|
|
56
|
+
terminalFontFamily?: string
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The stable reference a `volatile()` config field resolves to; its owner updates it in place. */
|
|
60
|
+
interface ConfigRef<T> {
|
|
61
|
+
/** @returns the field's current value. */
|
|
62
|
+
get(): T
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** One resolved config field: a live reference, or a plain value from a hand-built context. */
|
|
66
|
+
type ConfigField<T> = ConfigRef<T> | T
|
|
67
|
+
|
|
68
|
+
/** The config the Host hands to {@link apply} — the runtime face of {@link Config}. */
|
|
69
|
+
export interface ResolvedConfig {
|
|
70
|
+
announceToAgent?: ConfigField<boolean>
|
|
71
|
+
enabled?: ConfigField<boolean>
|
|
72
|
+
terminalFontFamily?: ConfigField<string>
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Plugin config schema. Under the 0.1.7 settings model this schema IS the
|
|
77
|
+
* entry's settings page: the Host derives one form per profile entry from it
|
|
78
|
+
* and serves it through the shared configuration forms. Every field is
|
|
79
|
+
* `volatile()`, which is what puts it on that page and what lets an edit reach
|
|
80
|
+
* a running instance without a remount: the loader commits the new value into
|
|
81
|
+
* the field's reference and announces `loader/volatile-update` on this fiber.
|
|
82
|
+
*/
|
|
83
|
+
export const Config = z.object({
|
|
84
|
+
announceToAgent: z.boolean().default(false).volatile(),
|
|
85
|
+
enabled: z.boolean().default(true).volatile(),
|
|
86
|
+
terminalFontFamily: z.string().default('').volatile(),
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
/** Schema defaults, re-read for hand-built test contexts (the loader applies them normally). */
|
|
90
|
+
const DEFAULT_ANNOUNCE = false
|
|
91
|
+
const DEFAULT_ENABLED = true
|
|
92
|
+
|
|
93
|
+
/** Read one resolved config field, following the live reference the schema produces. */
|
|
94
|
+
function readConfigField<T>(field: ConfigField<T> | undefined, fallback: T): T {
|
|
95
|
+
if (field === undefined) return fallback
|
|
96
|
+
if (typeof field === 'object' && field !== null && typeof (field as ConfigRef<T>).get === 'function') {
|
|
97
|
+
const value = (field as ConfigRef<T>).get()
|
|
98
|
+
return value === undefined ? fallback : value
|
|
99
|
+
}
|
|
100
|
+
return field as T
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* The loader's own record of the profile entry this instance was activated
|
|
105
|
+
* from, which carries the row's raw config — the user's own declaration, as
|
|
106
|
+
* opposed to the schema defaults and the inherited bundle layers. Absent on a
|
|
107
|
+
* host without the loader, which reads as "the profile declares nothing".
|
|
108
|
+
*/
|
|
109
|
+
interface LoaderEntry {
|
|
110
|
+
options?: { config?: unknown }
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Raw config the profile declares for this entry, when the loader exposes it. */
|
|
114
|
+
function profileConfig(ctx: Context): Record<string, unknown> | undefined {
|
|
115
|
+
const entry = (ctx.fiber as Fiber & { entry?: LoaderEntry }).entry
|
|
116
|
+
const config = entry?.options?.config
|
|
117
|
+
if (typeof config !== 'object' || config === null || Array.isArray(config)) return undefined
|
|
118
|
+
return config as Record<string, unknown>
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Order of the announcement section within the shared tool-guidance band. */
|
|
122
|
+
const SECTION_ORDER = PLUGIN_TOOL_SECTION_ORDERS.ssh
|
|
123
|
+
|
|
124
|
+
/** The six agent-tool names this plugin's announcement describes. */
|
|
125
|
+
const SSH_TOOL_NAMES = ['ssh_list', 'ssh_exec', 'ssh_upload', 'ssh_download', 'ssh_tunnel', 'ssh_cluster'] as const
|
|
126
|
+
|
|
127
|
+
/** Model-facing announcement: plugin presence, capabilities, and limits. */
|
|
128
|
+
export const SSH_GUIDANCE = '本机已安装 dsh-ssh 插件(DSH 远程 SSH 运维):侧边栏「SSH」入口;在 dsh-web 插件全家桶仓库(packages/dsh-ssh)统一维护。能力:主机配置存 $DSH_HOME/dsh-ssh.json(默认 ~/.dsh)(可从 ~/.ssh/config 导入);持久连接池复用长连接(空闲 30 分钟自动断开);ssh_list 列出主机、ssh_exec 执行远程命令、ssh_upload/ssh_download 传输文件、ssh_tunnel 本地端口转发(访问远程数据库/内网服务)、ssh_cluster 按 aliases/environment/tags 至少一种非空 selector 筛选后集群并发执行;支持密钥/密码/ssh-agent 认证、passphrase 密钥、ProxyJump 跳板机(别名或 [user@]host[:port] 地址)与 OpenSSH 语义的 ProxyCommand(跳过堡垒机客户端场景,只能由用户在 GUI 配置,agent 不可写);Web 终端走 WebSocket。限制:主机操作由用户在 GUI 中配置后 agent 方可使用;密码以明文存在用户主目录私有文件(权限 0600);命令输出原样返回、可能含敏感信息;断线重连可能重放非幂等命令;传输/执行消耗真实远程资源,先确认再操作。路径区分:本机(dsh host)上的文件与命令一律用本地工具(read / write / edit / bash),ssh_* 工具只针对远程主机上的路径。用户提到「SSH / 远程服务器 / 服务器操作 / 跳板机 / 隧道 / 部署 / 上传下载」时即指本插件,请据此协作。'
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Mount the SSH engine, routes, tools, and announcement.
|
|
132
|
+
* @param ctx - host plugin context carrying webServer/tools/systemPrompt.
|
|
133
|
+
* @param config - resolved plugin config (schema defaults applied by the loader).
|
|
134
|
+
*/
|
|
135
|
+
export const apply = mountOnce('@fish-under-sea/dsh-ssh-fish', applyImpl)
|
|
136
|
+
|
|
137
|
+
function applyImpl(ctx: Context, config?: ResolvedConfig): void {
|
|
138
|
+
const store = new HostStore()
|
|
139
|
+
const engine = new SshEngine(store)
|
|
140
|
+
ctx.effect(() => () => { engine.dispose() }, 'dsh-ssh: engine')
|
|
141
|
+
|
|
142
|
+
const resolve = (): { announceToAgent: boolean; enabled: boolean } => {
|
|
143
|
+
let enabled = readConfigField(config?.enabled, DEFAULT_ENABLED)
|
|
144
|
+
// When dsh-ssh was seeded with enabled: false (e.g. from an aggregate profile
|
|
145
|
+
// line), but the profile's own entry config never set the switch AND the user
|
|
146
|
+
// already has active host records in dsh-ssh.json, keep the plugin enabled so
|
|
147
|
+
// existing users are not broken upon upgrade (#1250).
|
|
148
|
+
if (enabled === false && profileConfig(ctx)?.enabled === undefined && store.list().length > 0) {
|
|
149
|
+
enabled = true
|
|
150
|
+
}
|
|
151
|
+
return {
|
|
152
|
+
announceToAgent: readConfigField(config?.announceToAgent, DEFAULT_ANNOUNCE),
|
|
153
|
+
enabled,
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// The /api/dsh-ssh route family + terminal upgrade.
|
|
158
|
+
const { routes, upgrade, terminalSessions } = makeRoutes({ store, engine })
|
|
159
|
+
let disposeRoutes: (() => void) | undefined
|
|
160
|
+
|
|
161
|
+
// Agent tools + their prompt sections.
|
|
162
|
+
const tools = [
|
|
163
|
+
sshListTool(engine),
|
|
164
|
+
sshExecTool(engine),
|
|
165
|
+
sshUploadTool(engine),
|
|
166
|
+
sshDownloadTool(engine),
|
|
167
|
+
sshTunnelTool(engine),
|
|
168
|
+
sshClusterTool(engine),
|
|
169
|
+
]
|
|
170
|
+
let disposeTools: (() => void) | undefined
|
|
171
|
+
|
|
172
|
+
// System-prompt announcement.
|
|
173
|
+
let disposeSection: (() => void) | undefined
|
|
174
|
+
|
|
175
|
+
// Register (or drop) every surface to match the resolved config. Each group
|
|
176
|
+
// is kept under one disposer: re-registering first tears the old one down
|
|
177
|
+
// so duplicate-name registrations never throw.
|
|
178
|
+
const sync = (): void => {
|
|
179
|
+
const value = resolve()
|
|
180
|
+
if (disposeSection !== undefined) {
|
|
181
|
+
disposeSection()
|
|
182
|
+
disposeSection = undefined
|
|
183
|
+
}
|
|
184
|
+
if (disposeRoutes !== undefined) {
|
|
185
|
+
disposeRoutes()
|
|
186
|
+
disposeRoutes = undefined
|
|
187
|
+
}
|
|
188
|
+
if (disposeTools !== undefined) {
|
|
189
|
+
disposeTools()
|
|
190
|
+
disposeTools = undefined
|
|
191
|
+
}
|
|
192
|
+
if (!value.enabled) return
|
|
193
|
+
if (value.announceToAgent) {
|
|
194
|
+
disposeSection = ctx.systemPrompt.section({
|
|
195
|
+
name: 'plugin:dsh-ssh',
|
|
196
|
+
order: SECTION_ORDER,
|
|
197
|
+
// The announcement names the ssh_* tools, so it renders only while at
|
|
198
|
+
// least one of them is reachable: a restriction that removes the tool
|
|
199
|
+
// surface must take the guidance with it, instead of telling the model
|
|
200
|
+
// to call tools this session cannot see.
|
|
201
|
+
text: visibleToolText(ctx.tools, SSH_TOOL_NAMES, SSH_GUIDANCE),
|
|
202
|
+
})
|
|
203
|
+
}
|
|
204
|
+
disposeRoutes = ctx.effect(
|
|
205
|
+
() => {
|
|
206
|
+
const disposers = routes.map(route => ctx.webServer.register(route))
|
|
207
|
+
const upgradeDisposer = ctx.webServer.registerUpgrade(upgrade)
|
|
208
|
+
return () => {
|
|
209
|
+
for (const dispose of disposers) dispose()
|
|
210
|
+
upgradeDisposer()
|
|
211
|
+
// Dropping the routes also ends the terminal sessions they served:
|
|
212
|
+
// a live shell must not outlive the surface that can reach it.
|
|
213
|
+
terminalSessions.dispose()
|
|
214
|
+
}
|
|
215
|
+
},
|
|
216
|
+
'dsh-ssh: routes',
|
|
217
|
+
)
|
|
218
|
+
disposeTools = ctx.effect(
|
|
219
|
+
() => {
|
|
220
|
+
const disposers = tools.map(tool => ctx.tools.register(tool))
|
|
221
|
+
return () => { for (const dispose of disposers) dispose() }
|
|
222
|
+
},
|
|
223
|
+
'dsh-ssh: tools',
|
|
224
|
+
)
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// A settings edit is committed into this instance's config references and
|
|
228
|
+
// announced on the owning fiber (the entry is not remounted), so the
|
|
229
|
+
// surfaces are re-derived from the new values here.
|
|
230
|
+
ctx.on('loader/volatile-update', () => { sync() })
|
|
231
|
+
|
|
232
|
+
// Initial registration from the config the Host activated this row with.
|
|
233
|
+
sync()
|
|
234
|
+
}
|
package/src/loopback.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// Generated by scripts/sync-shared.mjs from shared/host/loopback.ts. Do not edit this copy; edit the shared source and run "node scripts/sync-shared.mjs".
|
|
2
|
+
/**
|
|
3
|
+
* Loopback trust fence shared by the host route families: socket address,
|
|
4
|
+
* Host header, and browser same-origin markers. Packages receive this file as
|
|
5
|
+
* a generated copy via scripts/sync-shared.mjs; edit the shared source and
|
|
6
|
+
* re-run the sync instead of editing a copy.
|
|
7
|
+
*
|
|
8
|
+
* Semantics: RFC 5735 IPv4 127/8, ::1, IPv4-mapped ::ffff:127/8 (matching the
|
|
9
|
+
* remote-web-ui gate), localhost hostnames, plus the browser same-origin
|
|
10
|
+
* markers (sec-fetch-site and Origin) for the request-level fence.
|
|
11
|
+
* @module dsh-web-shared/host/loopback
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import type { IncomingMessage } from 'node:http'
|
|
15
|
+
|
|
16
|
+
/** IPv4 127/8 predicate (four decimal octets, first == 127). */
|
|
17
|
+
export function isIPv4Loopback(v4: string): boolean {
|
|
18
|
+
const parts = v4.split('.')
|
|
19
|
+
return parts.length === 4
|
|
20
|
+
&& parts[0] === '127'
|
|
21
|
+
&& parts.every(part => /^\d{1,3}$/.test(part) && Number(part) <= 255)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Whether a socket remote address names the loopback range (127/8, ::1, IPv4-mapped). */
|
|
25
|
+
export function isLoopbackAddress(address: string | undefined): boolean {
|
|
26
|
+
if (address === undefined) return false
|
|
27
|
+
const normalized = address.toLowerCase()
|
|
28
|
+
if (normalized === '::1') return true
|
|
29
|
+
if (normalized.startsWith('::ffff:')) return isIPv4Loopback(normalized.slice('::ffff:'.length))
|
|
30
|
+
return isIPv4Loopback(normalized)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Whether a normalized URL hostname names the loopback authority (localhost, [::1], 127/8). */
|
|
34
|
+
export function isLoopbackHostname(hostname: string): boolean {
|
|
35
|
+
if (hostname === 'localhost' || hostname === '[::1]') return true
|
|
36
|
+
return isIPv4Loopback(hostname)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Request-level trust fence: a loopback socket address AND a loopback Host
|
|
41
|
+
* header, plus browser same-origin markers. The socket address is
|
|
42
|
+
* authoritative; X-Forwarded-For is never trusted.
|
|
43
|
+
*/
|
|
44
|
+
export function isLoopbackRequest(request: IncomingMessage): boolean {
|
|
45
|
+
if (!isLoopbackAddress(request.socket.remoteAddress)) return false
|
|
46
|
+
const host = request.headers.host
|
|
47
|
+
if (typeof host !== 'string') return false
|
|
48
|
+
let hostUrl: URL
|
|
49
|
+
try {
|
|
50
|
+
hostUrl = new URL('http://' + host)
|
|
51
|
+
} catch {
|
|
52
|
+
return false
|
|
53
|
+
}
|
|
54
|
+
if (!isLoopbackHostname(hostUrl.hostname)) return false
|
|
55
|
+
if (request.headers['sec-fetch-site'] === 'cross-site') return false
|
|
56
|
+
const origin = request.headers.origin
|
|
57
|
+
if (origin === undefined) return true
|
|
58
|
+
try {
|
|
59
|
+
return new URL(origin).host === hostUrl.host
|
|
60
|
+
} catch {
|
|
61
|
+
return false
|
|
62
|
+
}
|
|
63
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
// Generated by scripts/sync-shared.mjs from shared/host/mount-once.ts. Do not edit this copy; edit the shared source and run "node scripts/sync-shared.mjs".
|
|
2
|
+
/**
|
|
3
|
+
* Host single-instance guard shared by the plugin family. The family bundle
|
|
4
|
+
* (dsh-web-all / dsh-skins) namespaces every child row id (web-ui-*), so
|
|
5
|
+
* the loader accepts a standalone install of the same package side by side;
|
|
6
|
+
* without this guard the second instance would still re-register the same
|
|
7
|
+
* webserver routes, tools, settings namespaces, and system-prompt sections
|
|
8
|
+
* and fail the boot. mountOnce makes a mount of an already-mounted package a
|
|
9
|
+
* no-op for as long as the first instance lives (the browser half is already
|
|
10
|
+
* deduped by package name in the client module host).
|
|
11
|
+
*
|
|
12
|
+
* A no-op is only safe while the holder is ALIVE. The holder can be disposed
|
|
13
|
+
* long after the refused mount ran its course: the Host reloads a profile by
|
|
14
|
+
* creating the new loader entries before the old ones are torn down (a
|
|
15
|
+
* plugin-manager enable/disable/install write, a settings-driven row reload,
|
|
16
|
+
* HMR), so the new aggregate shell entry mounts its family plugin while the
|
|
17
|
+
* previous entry still owns the name. Dropping that refused mount lost the
|
|
18
|
+
* plugin for good - the previous entry then disposed its own mount, releasing
|
|
19
|
+
* the name with nobody left to take it, and the family row stayed listed as
|
|
20
|
+
* active while its host routes 404ed (the task-board panel showed
|
|
21
|
+
* "board.hostError.notMounted", no degraded record appeared, and only a Host
|
|
22
|
+
* restart recovered it).
|
|
23
|
+
*
|
|
24
|
+
* The refused mount is therefore QUEUED, not dropped, and replayed the moment
|
|
25
|
+
* the holder releases the name - if the waiting fiber is still alive then. The
|
|
26
|
+
* single-instance guarantee is unchanged: exactly one mount is live per
|
|
27
|
+
* package name, and the replay re-enters the guard so a later mount still
|
|
28
|
+
* dedupes against it.
|
|
29
|
+
*
|
|
30
|
+
* The registry rides a global symbol so two module instances of the same
|
|
31
|
+
* package (npm copy vs repository link) still share one verdict. That symbol
|
|
32
|
+
* is a CROSS-REPOSITORY contract, not this file's private state: the four
|
|
33
|
+
* satellite packages (dsh-skins / dsh-pet / dsh-presets /
|
|
34
|
+
* dsh-community-plugins) are separate repositories carrying their own copy of
|
|
35
|
+
* this guard, rebuilt on their own schedule, so the value under `MOUNTED`
|
|
36
|
+
* must keep the shape every published copy reads (a `Set` of package names
|
|
37
|
+
* with `has`/`add`/`delete`). The wait queues this guard added therefore live
|
|
38
|
+
* under their own additive key, and the registry reads back a `Set` even when
|
|
39
|
+
* some other build left a different value there. Changing `MOUNTED`'s shape
|
|
40
|
+
* in place broke that contract once: a satellite's legacy copy created a
|
|
41
|
+
* `Set`, the family's new copy read it as a `Map`, and every family row
|
|
42
|
+
* mounted after it failed with "claims.get is not a function".
|
|
43
|
+
*
|
|
44
|
+
* cordis `ctx.effect` runs its callback immediately and treats the callback's
|
|
45
|
+
* return value as the fiber disposer, so the unmarker is returned, not run.
|
|
46
|
+
*/
|
|
47
|
+
|
|
48
|
+
/** Published cross-repository contract: package names currently mounted. */
|
|
49
|
+
const MOUNTED = Symbol.for('dsh-web.mounted-plugins')
|
|
50
|
+
|
|
51
|
+
/** Additive key this guard owns: refused mounts waiting for the name. */
|
|
52
|
+
const WAITERS = Symbol.for('dsh-web.mounted-plugins.waiters')
|
|
53
|
+
|
|
54
|
+
/** The slice of a cordis context this guard touches. */
|
|
55
|
+
interface MountContext {
|
|
56
|
+
effect?: (effect: () => unknown) => unknown
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** One mount that was refused while another fiber owned the package name. */
|
|
60
|
+
interface PendingMount {
|
|
61
|
+
/** Replay the refused mount; a no-op once its own fiber has been disposed. */
|
|
62
|
+
run(): void
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
interface MountRegistry {
|
|
66
|
+
[MOUNTED]?: unknown
|
|
67
|
+
[WAITERS]?: Map<string, PendingMount[]>
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The shared name registry, always a `Set` whatever another build stored here:
|
|
72
|
+
* a foreign value (an interim shape, a hand-written global) must not take every
|
|
73
|
+
* family plugin down with it.
|
|
74
|
+
* @returns the process-wide set of mounted package names.
|
|
75
|
+
*/
|
|
76
|
+
function mountedSet(): Set<string> {
|
|
77
|
+
const registry = globalThis as MountRegistry
|
|
78
|
+
const existing = registry[MOUNTED]
|
|
79
|
+
if (existing instanceof Set) return existing as Set<string>
|
|
80
|
+
const created = new Set<string>()
|
|
81
|
+
registry[MOUNTED] = created
|
|
82
|
+
return created
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Queue per package name for mounts refused while a holder was alive. */
|
|
86
|
+
function mountWaiters(): Map<string, PendingMount[]> {
|
|
87
|
+
const registry = globalThis as MountRegistry
|
|
88
|
+
return (registry[WAITERS] ??= new Map())
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Wrap a cordis plugin apply so the package runs at most once per process.
|
|
93
|
+
* The first mount registers normally and releases the name when its fiber
|
|
94
|
+
* disposes; a mount refused while that name is held waits for the release and
|
|
95
|
+
* then runs, unless its own fiber disposes first.
|
|
96
|
+
* @param packageName - npm package identity shared by every install source.
|
|
97
|
+
* @param fn - the original plugin apply.
|
|
98
|
+
* @returns an apply of the same shape.
|
|
99
|
+
*/
|
|
100
|
+
export function mountOnce<T extends (...args: any[]) => unknown>(packageName: string, fn: T): T {
|
|
101
|
+
const mount = (...args: unknown[]): unknown => {
|
|
102
|
+
const mounted = mountedSet()
|
|
103
|
+
const ctx = args[0] as MountContext | undefined
|
|
104
|
+
if (mounted.has(packageName)) {
|
|
105
|
+
// Another fiber (the aggregate row, a standalone install, or a copy built
|
|
106
|
+
// from an older revision of this guard) owns the name. Queue instead of
|
|
107
|
+
// dropping: dropping lost the plugin for the rest of the process when the
|
|
108
|
+
// holder was disposed by a reload.
|
|
109
|
+
const waiters = mountWaiters()
|
|
110
|
+
const queue = waiters.get(packageName) ?? []
|
|
111
|
+
let alive = true
|
|
112
|
+
const pending: PendingMount = {
|
|
113
|
+
run: () => {
|
|
114
|
+
if (alive) mount(...args)
|
|
115
|
+
},
|
|
116
|
+
}
|
|
117
|
+
// A fiber that dies while it waits must not be replayed afterwards: its
|
|
118
|
+
// context is disposed and registering effects on it would throw.
|
|
119
|
+
ctx?.effect?.(() => () => {
|
|
120
|
+
alive = false
|
|
121
|
+
const index = queue.indexOf(pending)
|
|
122
|
+
if (index >= 0) queue.splice(index, 1)
|
|
123
|
+
})
|
|
124
|
+
queue.push(pending)
|
|
125
|
+
waiters.set(packageName, queue)
|
|
126
|
+
return
|
|
127
|
+
}
|
|
128
|
+
mounted.add(packageName)
|
|
129
|
+
ctx?.effect?.(() => () => {
|
|
130
|
+
mounted.delete(packageName)
|
|
131
|
+
const waiters = mountWaiters()
|
|
132
|
+
const queue = waiters.get(packageName)
|
|
133
|
+
if (queue === undefined) return
|
|
134
|
+
waiters.delete(packageName)
|
|
135
|
+
// Defer the handover one microtask so the disposing mount's own effects
|
|
136
|
+
// (routes, ledger, timers) are torn down before the next one registers.
|
|
137
|
+
for (const waiter of queue.splice(0)) queueMicrotask(() => { waiter.run() })
|
|
138
|
+
})
|
|
139
|
+
return fn(...args)
|
|
140
|
+
}
|
|
141
|
+
return mount as T
|
|
142
|
+
}
|