dsh-plugin-slim 0.0.0-stage → 0.1.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/lib/http.js ADDED
@@ -0,0 +1,231 @@
1
+ /**
2
+ * HTTP wire adapter for the four exact /api/plugin-slim/* routes.
3
+ *
4
+ * Every request crosses the local-access fence first: the harness
5
+ * `connection.requestRejection` service when present (an explicit rejection is
6
+ * final - a cross-site browser request also comes from 127.0.0.1), otherwise a
7
+ * loopback-only fallback. Write routes additionally require a same-origin
8
+ * request and an application/json body, and every request body is capped at
9
+ * 64 KB. Handlers return { status, json }; this adapter only serializes, so a
10
+ * route can be unit-tested with fake req/res objects and no host.
11
+ *
12
+ * @module dsh-plugin-slim/http
13
+ */
14
+ import { describeError, tryGet } from './host.js'
15
+
16
+ /** Largest request body accepted by a panel route. */
17
+ export const BODY_LIMIT = 64 * 1024
18
+
19
+ /** JSON response headers: never cached, never referrer-leaking. */
20
+ export const JSON_HEADERS = Object.freeze({
21
+ 'content-type': 'application/json; charset=utf-8',
22
+ 'cache-control': 'no-store',
23
+ 'referrer-policy': 'no-referrer',
24
+ })
25
+
26
+ /** Methods whose routes need the same-origin + JSON-content-type checks. */
27
+ const WRITE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])
28
+
29
+ /** @param {unknown} value @returns {value is Record<string, unknown>} */
30
+ function isObject(value) {
31
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
32
+ }
33
+
34
+ /** One JSON error body. @param {string} code @param {string} message */
35
+ function errorBody(code, message) {
36
+ return { ok: false, code, error: message }
37
+ }
38
+
39
+ /**
40
+ * Fallback access fence for builds with no connection service: the panel is
41
+ * served from the same origin, so loopback is the normal case.
42
+ * @param {import('node:http').IncomingMessage} request
43
+ */
44
+ export function isLoopbackRequest(request) {
45
+ const address = request?.socket?.remoteAddress
46
+ return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1'
47
+ }
48
+
49
+ /** Resolve the optional host connection fence without requiring injection. */
50
+ function resolveConnection(ctx) {
51
+ const candidate = tryGet(ctx, 'connection')
52
+ return isObject(candidate) && typeof candidate.requestRejection === 'function' ? candidate : undefined
53
+ }
54
+
55
+ /** Read one request header as a trimmed string ('' when absent/non-string). */
56
+ function headerValue(request, name) {
57
+ const headers = request?.headers
58
+ if (!isObject(headers)) return ''
59
+ const value = headers[name]
60
+ if (typeof value === 'string') return value.trim()
61
+ if (Array.isArray(value) && value.length > 0) return String(value[0]).trim()
62
+ return ''
63
+ }
64
+
65
+ /**
66
+ * Whether a write request may come from a page on the panel's own origin.
67
+ * A cross-site browser request carries an Origin that does not match Host (and
68
+ * usually Sec-Fetch-Site: cross-site); scripts send neither and stay
69
+ * loopback-fenced. This blocks CSRF-style cross-site writes only.
70
+ * @param {import('node:http').IncomingMessage} request
71
+ */
72
+ export function isSameOriginRequest(request) {
73
+ const site = headerValue(request, 'sec-fetch-site').toLowerCase()
74
+ if (site !== '' && site !== 'same-origin' && site !== 'none') return false
75
+ const origin = headerValue(request, 'origin')
76
+ if (origin === '') return true
77
+ const host = headerValue(request, 'host')
78
+ if (host === '') return false
79
+ try {
80
+ const parsed = new URL(origin)
81
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false
82
+ return parsed.host === host
83
+ } catch {
84
+ return false
85
+ }
86
+ }
87
+
88
+ /** Whether a write request declares an application/json body. */
89
+ export function isJsonContentType(request) {
90
+ return headerValue(request, 'content-type').toLowerCase().startsWith('application/json')
91
+ }
92
+
93
+ /**
94
+ * Whether a request may enter a panel route: the harness connection fence when
95
+ * available, otherwise the loopback check (never open the route to the network).
96
+ * A throwing fence must not turn into an open door, so it falls through to the
97
+ * loopback boundary.
98
+ * @param {*} ctx @param {import('node:http').IncomingMessage} request
99
+ */
100
+ export function isRequestAllowed(ctx, request) {
101
+ const connection = resolveConnection(ctx)
102
+ if (connection !== undefined) {
103
+ try {
104
+ const rejection = connection.requestRejection(request)
105
+ if (rejection === undefined) return true
106
+ return false
107
+ } catch {
108
+ // Fall through to the loopback fallback.
109
+ }
110
+ }
111
+ return isLoopbackRequest(request)
112
+ }
113
+
114
+ /** @param {import('node:http').IncomingMessage} request */
115
+ function requestUrl(request) {
116
+ return new URL(request.url ?? '/', 'http://localhost')
117
+ }
118
+
119
+ /** Write one JSON response (no-op once the response already ended). */
120
+ export function writeJson(response, status, body) {
121
+ if (response?.writableEnded === true) return
122
+ response.writeHead(status, JSON_HEADERS)
123
+ response.end(JSON.stringify(body))
124
+ }
125
+
126
+ /**
127
+ * Read a request body with a hard 64 KB cap; writes 413 itself and resolves
128
+ * undefined when it already answered.
129
+ * @param {import('node:http').IncomingMessage} request
130
+ * @param {import('node:http').ServerResponse} response
131
+ * @returns {Promise<string | undefined>}
132
+ */
133
+ export function readBody(request, response) {
134
+ return new Promise((resolve) => {
135
+ const chunks = []
136
+ let size = 0
137
+ let settled = false
138
+ const settle = (value) => {
139
+ if (settled) return
140
+ settled = true
141
+ resolve(value)
142
+ }
143
+ request.on('data', (chunk) => {
144
+ if (settled) return
145
+ size += chunk.length
146
+ if (size > BODY_LIMIT) {
147
+ writeJson(response, 413, errorBody('PAYLOAD_TOO_LARGE', '请求体超过 ' + BODY_LIMIT + ' 字节上限'))
148
+ // Keep draining so the client can read the 413 before the socket resets.
149
+ settle(undefined)
150
+ return
151
+ }
152
+ chunks.push(chunk)
153
+ })
154
+ request.on('end', () => settle(Buffer.concat(chunks).toString('utf8')))
155
+ request.on('error', () => {
156
+ writeJson(response, 400, errorBody('BODY_READ_FAILED', '请求体读取失败'))
157
+ settle(undefined)
158
+ })
159
+ })
160
+ }
161
+
162
+ /**
163
+ * Parse one JSON object body; undefined means a response was already written.
164
+ * @param {import('node:http').IncomingMessage} request
165
+ * @param {import('node:http').ServerResponse} response
166
+ * @returns {Promise<Record<string, unknown> | undefined>}
167
+ */
168
+ export async function readJsonObject(request, response) {
169
+ const raw = await readBody(request, response)
170
+ if (raw === undefined) return undefined
171
+ if (raw.trim() === '') return {}
172
+ let parsed
173
+ try {
174
+ parsed = JSON.parse(raw)
175
+ } catch {
176
+ writeJson(response, 400, errorBody('INVALID_JSON', '请求体不是合法 JSON'))
177
+ return undefined
178
+ }
179
+ if (!isObject(parsed)) {
180
+ writeJson(response, 400, errorBody('INVALID_INPUT', '请求体必须是 JSON 对象'))
181
+ return undefined
182
+ }
183
+ return parsed
184
+ }
185
+
186
+ /**
187
+ * Adapt one payload handler to a node http handler: fence, method check,
188
+ * same-origin + content-type for writes, body cap + JSON parse, then serialize
189
+ * { status, json }. All exceptions are caught and never escape the route.
190
+ * @param {*} ctx @param {{ method: string, path: string, handler: Function }} route
191
+ * @returns {(request: import('node:http').IncomingMessage, response: import('node:http').ServerResponse) => Promise<void>}
192
+ */
193
+ export function createHttpHandler(ctx, route) {
194
+ return async (request, response) => {
195
+ try {
196
+ if (!isRequestAllowed(ctx, request)) {
197
+ writeJson(response, 403, errorBody('FORBIDDEN', 'forbidden: loopback-only'))
198
+ return
199
+ }
200
+ if (request.method !== route.method) {
201
+ writeJson(response, 405, errorBody('METHOD_NOT_ALLOWED', 'method not allowed: ' + String(request.method ?? '')))
202
+ return
203
+ }
204
+ let payload
205
+ if (WRITE_METHODS.has(route.method)) {
206
+ if (!isSameOriginRequest(request)) {
207
+ writeJson(response, 403, errorBody('CROSS_ORIGIN_BLOCKED', 'forbidden: cross-origin write'))
208
+ return
209
+ }
210
+ if (!isJsonContentType(request)) {
211
+ writeJson(response, 415, errorBody('UNSUPPORTED_CONTENT_TYPE', 'content-type 必须是 application/json'))
212
+ return
213
+ }
214
+ payload = await readJsonObject(request, response)
215
+ if (payload === undefined) return
216
+ } else {
217
+ payload = Object.fromEntries(requestUrl(request).searchParams.entries())
218
+ }
219
+ const result = await route.handler(payload, { request, response })
220
+ if (isObject(result) && typeof result.status === 'number') {
221
+ writeJson(response, result.status, result.json ?? {})
222
+ return
223
+ }
224
+ writeJson(response, 200, result ?? {})
225
+ } catch (error) {
226
+ const status = isObject(error) && typeof error.status === 'number' ? error.status : 500
227
+ const code = isObject(error) && typeof error.code === 'string' ? error.code : 'INTERNAL_ERROR'
228
+ writeJson(response, status, errorBody(code, describeError(error)))
229
+ }
230
+ }
231
+ }
package/lib/index.js ADDED
@@ -0,0 +1,153 @@
1
+ /**
2
+ * 轻装 (Plugin Slim) · host half.
3
+ *
4
+ * The plugin row inserted by cordis.patch.yml loads this module. It exports
5
+ * `inject = []`: no hard service dependency, so a host without webServer (a CLI
6
+ * session) or on any DSH 0.1.5+ / 0.2.x / 0.3.x still loads the plugin with a
7
+ * warning instead of failing the profile boot.
8
+ *
9
+ * What it mounts: the four exact /api/plugin-slim/* routes through
10
+ * webServer.register inside a scope.effect, with the node http adapter
11
+ * (loopback / connection fence, CSRF checks, JSON body cap) in lib/http.js.
12
+ *
13
+ * What it never does: register an Agent tool. This plugin adds zero always-
14
+ * loaded tools and imports no third-party Agent-tool SDK. That
15
+ * "0 Agent tools" promise is asserted by test/packaging.test.js.
16
+ *
17
+ * Data root: dshHomePath('plugin-slim') -> profileContext.home -> $DSH_HOME ->
18
+ * ~/.dsh, resolved by lib/host.js resolveDataRoot. Snapshots are written under
19
+ * <dataRoot>/snapshots by lib/patch.js.
20
+ *
21
+ * Degradation policy: a missing service, a failed route registration or an
22
+ * unbuildable state layer is announced with a warning and skipped - never
23
+ * silently and never by throwing into the profile boot.
24
+ *
25
+ * @module dsh-plugin-slim
26
+ */
27
+ import { createHostAdapter, describeError, resolveDataRoot, tryGet } from './host.js'
28
+ import { createHttpHandler } from './http.js'
29
+ import { createPatchStore } from './patch.js'
30
+ import { createRoutes } from './routes.js'
31
+
32
+ /** Cordis plugin name (the package specifier lives in cordis.patch.yml). */
33
+ export const name = 'dsh-plugin-slim'
34
+
35
+ /**
36
+ * No mandatory dependency: webServer is mounted through the optional
37
+ * ctx.inject([...], cb) form. inject stays empty so the cordis row needs no
38
+ * inject list and the client panel (dsh.client) is loaded by the host itself.
39
+ */
40
+ export const inject = []
41
+
42
+ /** @param {unknown} value @returns {value is Record<string, unknown>} */
43
+ function isObject(value) {
44
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
45
+ }
46
+
47
+ /**
48
+ * Warn through the host logger, falling back to console: a degraded capability
49
+ * is always announced, never silently dropped.
50
+ * @param {*} ctx @param {string} message
51
+ */
52
+ function warn(ctx, message) {
53
+ const text = '[plugin-slim] ' + message
54
+ try {
55
+ if (ctx && typeof ctx.logger?.warn === 'function') ctx.logger.warn(text)
56
+ else if (typeof console !== 'undefined' && typeof console.warn === 'function') console.warn(text)
57
+ } catch {
58
+ // Logging must never break plugin load.
59
+ }
60
+ }
61
+
62
+ /**
63
+ * Register the four panel routes on the host web server. A partial mount
64
+ * releases everything this attempt already registered before it warns.
65
+ * @param {*} ctx @param {{ method: string, path: string, handler: Function }[]} routes
66
+ */
67
+ function mountRoutes(ctx, routes) {
68
+ if (typeof ctx?.inject !== 'function') {
69
+ warn(ctx, 'ctx.inject 不可用:面板 HTTP 路由未注册(宿主不提供 webServer 注入)')
70
+ return
71
+ }
72
+ // Probe first so a host that never provides webServer still leaves a warning
73
+ // instead of silently mounting nothing (inject callbacks wait for services).
74
+ if (tryGet(ctx, 'webServer') === undefined) {
75
+ warn(ctx, 'webServer 服务暂未提供:等待宿主注入面板路由(缺失时仅影响面板,不阻断启动)')
76
+ }
77
+ try {
78
+ ctx.inject(['webServer'], (scope) => {
79
+ try {
80
+ if (!isObject(scope?.webServer) || typeof scope.webServer.register !== 'function') {
81
+ warn(ctx, 'webServer 服务不可用:面板 HTTP 路由未注册')
82
+ return
83
+ }
84
+ const mount = () => {
85
+ const releases = []
86
+ try {
87
+ for (const route of routes) {
88
+ releases.push(scope.webServer.register({ kind: 'exact', path: route.path, handler: createHttpHandler(ctx, route) }))
89
+ }
90
+ } catch (error) {
91
+ for (const release of releases.splice(0)) {
92
+ try {
93
+ release()
94
+ } catch (inner) {
95
+ warn(ctx, '回滚部分面板路由失败:' + describeError(inner))
96
+ }
97
+ }
98
+ throw error
99
+ }
100
+ return () => {
101
+ for (const release of releases.splice(0)) {
102
+ try {
103
+ release()
104
+ } catch (error) {
105
+ warn(ctx, '注销面板路由失败:' + describeError(error))
106
+ }
107
+ }
108
+ }
109
+ }
110
+ if (typeof scope.effect === 'function') {
111
+ scope.effect(mount, 'plugin-slim: panel routes')
112
+ } else {
113
+ warn(ctx, 'scope.effect 不可用:面板路由无法随插件卸载回收')
114
+ mount()
115
+ }
116
+ } catch (error) {
117
+ warn(ctx, '注册面板路由失败:' + describeError(error))
118
+ }
119
+ })
120
+ } catch (error) {
121
+ warn(ctx, 'webServer 注入失败:' + describeError(error))
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Mount the 轻装 host half on one plugin load.
127
+ * @param {*} ctx cordis plugin context
128
+ * @param {{ profilePath?: string, patchPath?: string, home?: string }} [config] optional patch-row overrides
129
+ * @returns {void}
130
+ */
131
+ export function apply(ctx, config = {}) {
132
+ const options = isObject(config) ? config : {}
133
+ let host
134
+ let patchStore
135
+ let routes
136
+ try {
137
+ host = createHostAdapter(ctx, {
138
+ ...(typeof options.profilePath === 'string' && options.profilePath !== '' ? { profilePath: options.profilePath } : {}),
139
+ ...(typeof options.patchPath === 'string' && options.patchPath !== '' ? { patchPath: options.patchPath } : {}),
140
+ ...(typeof options.home === 'string' && options.home !== '' ? { home: options.home } : {}),
141
+ })
142
+ const dataRoot = resolveDataRoot(ctx, {
143
+ ...(typeof options.home === 'string' && options.home !== '' ? { home: options.home } : {}),
144
+ })
145
+ patchStore = createPatchStore({ backupDir: dataRoot })
146
+ routes = createRoutes({ host, patchStore, now: () => new Date() })
147
+ } catch (error) {
148
+ warn(ctx, '轻装初始化失败,面板路由降级为不注册:' + describeError(error))
149
+ return
150
+ }
151
+ // 0 Agent tools: this plugin registers nothing in the host tools service.
152
+ mountRoutes(ctx, routes)
153
+ }