@capyclaw/gateway 0.0.0-stage → 0.1.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.
Files changed (78) hide show
  1. package/README.md +89 -2
  2. package/cordis.patch.yml +4 -0
  3. package/lib/http.mjs +101 -0
  4. package/lib/index.mjs +714 -0
  5. package/lib/paths.mjs +171 -0
  6. package/lib/store.mjs +193 -0
  7. package/lib/upstream.mjs +111 -0
  8. package/node_modules/@capyclaw/foundation/README.md +51 -0
  9. package/node_modules/@capyclaw/foundation/abi/assets.mjs +26 -0
  10. package/node_modules/@capyclaw/foundation/abi/bridge.mjs +88 -0
  11. package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
  12. package/node_modules/@capyclaw/foundation/abi/index.mjs +50 -0
  13. package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
  14. package/node_modules/@capyclaw/foundation/abi/loader.mjs +352 -0
  15. package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
  16. package/node_modules/@capyclaw/foundation/abi/spec.mjs +258 -0
  17. package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
  18. package/node_modules/@capyclaw/foundation/abi/version.mjs +140 -0
  19. package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -0
  20. package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
  21. package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
  22. package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
  23. package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
  24. package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
  25. package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +72 -0
  26. package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
  27. package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +69 -0
  28. package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +120 -0
  29. package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
  30. package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
  31. package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
  32. package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
  33. package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
  34. package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +38 -0
  35. package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +88 -0
  36. package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +54 -0
  37. package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +187 -0
  38. package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
  39. package/node_modules/@capyclaw/foundation/lib/kernel.mjs +195 -0
  40. package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +115 -0
  41. package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
  42. package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
  43. package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +198 -0
  44. package/node_modules/@capyclaw/foundation/package.json +53 -0
  45. package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
  46. package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
  47. package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
  48. package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
  49. package/node_modules/@capyclaw/plugin-kit/package.json +71 -0
  50. package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
  51. package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
  52. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +132 -0
  53. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
  54. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +60 -0
  55. package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
  56. package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
  57. package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
  58. package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
  59. package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
  60. package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
  61. package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
  62. package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
  63. package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
  64. package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
  65. package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
  66. package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
  67. package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
  68. package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
  69. package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
  70. package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
  71. package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
  72. package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
  73. package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
  74. package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
  75. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +664 -0
  76. package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
  77. package/package.json +61 -4
  78. package/plugin.mjs +329 -0
package/lib/index.mjs ADDED
@@ -0,0 +1,714 @@
1
+ /**
2
+ * 网关核心:把 `/s/<会话id>/` 这个命名空间翻译成「哪个文件」或「哪个服务」。
3
+ *
4
+ * 这里刻意不做的事(都是踩过的坑):
5
+ * - **不缓存目标**:每次请求现读注册表、现查 services.json,重启/换端口立刻生效;
6
+ * - **不接受 URL 里的目标地址**:`/s/<sid>/app/x?to=http://…` 这种一律不认,
7
+ * 否则一个前缀就成了开放代理 + SSRF;
8
+ * - **不做目录透传**:只发「显式发布过」的条目,URL 里的名字只是别名。
9
+ */
10
+ import fs from 'node:fs'
11
+ import http from 'node:http'
12
+ import https from 'node:https'
13
+ import path from 'node:path'
14
+
15
+ import { readJson, send, sendText, tokenMatches } from './http.mjs'
16
+ import { isHtmlMime, mimeFor, splitTarget, safeChild } from './paths.mjs'
17
+ import { publicItems, patchSession, readStore, sessionEntry, upsertItem, removeItem, pruneStore, writeStore } from './store.mjs'
18
+ import { resolveService } from './upstream.mjs'
19
+
20
+ export const BASE = '/s'
21
+ export const CONTROL = '/__gateway__'
22
+
23
+ const HOP_BY_HOP = new Set([
24
+ 'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te',
25
+ 'trailer', 'transfer-encoding', 'upgrade', 'host', 'content-length',
26
+ ])
27
+
28
+ /** 上游请求头白名单:只带语义必需的,`cookie` 单独处理。 */
29
+ const FORWARD_REQUEST = new Set([
30
+ 'accept', 'accept-language', 'accept-encoding', 'content-type', 'range',
31
+ 'if-none-match', 'if-modified-since', 'user-agent', 'cookie',
32
+ ])
33
+
34
+ /** 上游响应头白名单:`set-cookie`/`location` 要重写,不能盲拷。 */
35
+ const FORWARD_RESPONSE = new Set([
36
+ 'cache-control', 'content-type', 'content-language', 'content-encoding', 'etag',
37
+ 'last-modified', 'expires', 'vary', 'accept-ranges', 'content-range', 'content-length',
38
+ 'x-content-type-options',
39
+ ])
40
+
41
+ /* ───────────────────────── 条目解析 ───────────────────────── */
42
+
43
+ /**
44
+ * 在一段名字里找出「最长的、已发布的条目前缀」。
45
+ * `a/b/c.css` 会依次试 `f/a/b/c.css` → `f/a/b` → `f/a`,
46
+ * 命中目录型条目时把剩下的部分当子路径。
47
+ */
48
+ export function resolveItem(entry, kind, name) {
49
+ if (!entry) return null
50
+ const items = entry.items || {}
51
+ const prefix = `${kind}/`
52
+ const clean = String(name || '').replace(/^\/+/, '')
53
+ if (!clean) return null
54
+ const segments = clean.split('/')
55
+ for (let take = segments.length; take >= 1; take -= 1) {
56
+ const key = prefix + segments.slice(0, take).join('/')
57
+ const item = items[key]
58
+ if (!item) continue
59
+ const rest = segments.slice(take).join('/')
60
+ return { key, item, rest }
61
+ }
62
+ return null
63
+ }
64
+
65
+ /* ───────────────────────── 静态产物 ───────────────────────── */
66
+
67
+ function serveFile(req, res, file, { size, mime, immutable = false } = {}) {
68
+ const headers = {
69
+ 'content-type': mime || mimeFor(file),
70
+ 'cache-control': immutable ? 'private, max-age=86400' : 'no-cache',
71
+ 'x-content-type-options': 'nosniff',
72
+ 'referrer-policy': 'no-referrer',
73
+ 'content-length': size,
74
+ }
75
+ if (req.method === 'HEAD') {
76
+ res.writeHead(200, headers)
77
+ res.end()
78
+ return
79
+ }
80
+ res.writeHead(200, headers)
81
+ const stream = fs.createReadStream(file)
82
+ stream.on('error', () => { try { res.destroy() } catch { /* 已断开 */ } })
83
+ stream.pipe(res)
84
+ }
85
+
86
+ function redirect301(res, location) {
87
+ res.writeHead(301, { location, 'cache-control': 'no-store', 'content-length': 0 })
88
+ res.end()
89
+ }
90
+
91
+ function notFoundPage(res, message, { sid = '', kind = 'f', name = '' } = {}) {
92
+ const body = `<!doctype html><meta charset="utf-8">
93
+ <title>404 · 网关</title>
94
+ <style>body{font:15px/1.6 system-ui,"Segoe UI",sans-serif;max-width:44rem;margin:12vh auto;padding:0 1.5rem;color:#1f2328}
95
+ code{background:#f2f4f7;padding:.1em .35em;border-radius:4px}
96
+ h1{font-size:1.3rem;margin:0 0 .8rem}p{margin:.4rem 0;color:#4a5563}</style>
97
+ <h1>这个地址没有对应的产物</h1>
98
+ <p>${escapeHtml(message)}</p>
99
+ <p>会话 <code>${escapeHtml(sid || '(空)')}</code> · 类型 <code>${escapeHtml(kind)}</code> · 名字 <code>${escapeHtml(name || '(空)')}</code></p>
100
+ <p>产物是「显式发布」的:只有调用过 <code>gateway_publish</code>(或直接 PUT 控制面)之后,这个地址才会存在。</p>`
101
+ sendText(res, 404, body, 'text/html; charset=utf-8')
102
+ }
103
+
104
+ /* HTML 转义不在这里实现:全仓只有 @capyclaw/plugin-kit/util/http 一份。 */
105
+ import { escapeHtml } from '@capyclaw/plugin-kit/util/http'
106
+
107
+ export { escapeHtml }
108
+
109
+ /* ───────────────────────── 上游反代 ───────────────────────── */
110
+
111
+ function rewriteSetCookie(value, mountPath) {
112
+ /* `Path=/` 会被浏览器当成整个 10170 的 cookie,必须收窄到这条应用自己的前缀下。 */
113
+ return String(value).replace(/(;\s*path=)(\/[^;]*)?/i, (_all, head, _old) => `${head}${mountPath}/`)
114
+ }
115
+
116
+ function rewriteLocation(value, origin, mountPath) {
117
+ const text = String(value)
118
+ try {
119
+ const url = new URL(text, origin)
120
+ if (url.origin !== origin) return text
121
+ const rest = `${url.pathname}${url.search}`
122
+ return `${mountPath}${rest === '/' ? '/' : rest}`
123
+ } catch {
124
+ return text
125
+ }
126
+ }
127
+
128
+ function proxy(req, res, { origin, mountPath, upstreamPath }) {
129
+ let target
130
+ try {
131
+ target = new URL(upstreamPath || '/', origin)
132
+ } catch {
133
+ return send(res, 502, { ok: false, error: '上游地址拼接失败' })
134
+ }
135
+ const lib = target.protocol === 'https:' ? https : http
136
+ const headers = {}
137
+ for (const [key, value] of Object.entries(req.headers)) {
138
+ if (FORWARD_REQUEST.has(key)) headers[key] = value
139
+ }
140
+ /* 让上游知道自己在哪个公共前缀下——<img>/<a> 这类不带前缀的相对地址要靠它修正。 */
141
+ headers['x-forwarded-prefix'] = mountPath
142
+ headers['x-forwarded-host'] = req.headers.host || ''
143
+ const upstream = lib.request({
144
+ protocol: target.protocol,
145
+ hostname: target.hostname,
146
+ port: target.port || (target.protocol === 'https:' ? 443 : 80),
147
+ method: req.method,
148
+ path: `${target.pathname}${target.search}`,
149
+ headers,
150
+ timeout: 30_000,
151
+ }, (up) => {
152
+ const out = {}
153
+ for (const [key, value] of Object.entries(up.headers)) {
154
+ if (!FORWARD_RESPONSE.has(key)) continue
155
+ out[key] = value
156
+ }
157
+ if (up.headers['set-cookie']) {
158
+ out['set-cookie'] = up.headers['set-cookie'].map((one) => rewriteSetCookie(one, mountPath))
159
+ }
160
+ if (up.headers.location) {
161
+ out.location = rewriteLocation(up.headers.location, origin, mountPath)
162
+ }
163
+ res.writeHead(up.statusCode || 502, out)
164
+ up.pipe(res)
165
+ })
166
+ upstream.on('timeout', () => upstream.destroy(new Error('上游超时')))
167
+ upstream.on('error', (error) => {
168
+ if (res.headersSent) { try { res.destroy() } catch { /* ignore */ } return }
169
+ send(res, 502, {
170
+ ok: false,
171
+ error: `上游没在服务(${origin}):${String(error?.message || error)}`,
172
+ hint: '服务可能已重启或换端口;网关每次请求都会重新查发现表,刷新一次即可。',
173
+ })
174
+ })
175
+ req.on('aborted', () => upstream.destroy())
176
+ req.pipe(upstream)
177
+ }
178
+
179
+ /* ───────────────────────── 页面 ───────────────────────── */
180
+
181
+ function pageShell(title, inner) {
182
+ return `<!doctype html><meta charset="utf-8">
183
+ <meta name="viewport" content="width=device-width,initial-scale=1">
184
+ <title>${escapeHtml(title)}</title>
185
+ <style>
186
+ :root{color-scheme:light dark}
187
+ body{font:14px/1.65 system-ui,"Segoe UI","Microsoft YaHei",sans-serif;max-width:52rem;margin:6vh auto;padding:0 1.5rem;color:#1f2328}
188
+ h1{font-size:1.25rem;margin:0 0 1.2rem}
189
+ h2{font-size:.95rem;margin:2rem 0 .6rem;color:#57606a;font-weight:600}
190
+ ul{list-style:none;padding:0;margin:0}
191
+ li{padding:.5rem .7rem;border:1px solid #e3e6ea;border-radius:8px;margin-bottom:.45rem;display:flex;gap:.7rem;align-items:baseline}
192
+ li .k{font-family:ui-monospace,Consolas,monospace;font-size:.86rem;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
193
+ li .t{font-size:.76rem;color:#6b7280;border:1px solid #e3e6ea;border-radius:999px;padding:0 .45rem}
194
+ a{color:#0969da;text-decoration:none}a:hover{text-decoration:underline}
195
+ p.note{color:#6b7280;font-size:.86rem}
196
+ code{background:#f2f4f7;padding:.1em .35em;border-radius:4px;font-size:.86em}
197
+ </style>${inner}`
198
+ }
199
+
200
+ /* 状态值可能是对象,摊平成一行的形式给人看;太长就截断,页面上不该出现大块 JSON。 */
201
+ function stateValue(value) {
202
+ const text = typeof value === 'string' ? value : JSON.stringify(value)
203
+ return text.length > 240 ? `${text.slice(0, 237)}…` : text
204
+ }
205
+
206
+ function sessionPage(sid, entry, { origin = '' } = {}) {
207
+ const items = publicItems(entry)
208
+ const state = Object.entries(entry?.state || {}).filter(([, value]) => value !== undefined && value !== null)
209
+ const groups = new Map([['f', []], ['app', []]])
210
+ for (const item of items) {
211
+ const kind = item.key.startsWith('app/') ? 'app' : 'f'
212
+ groups.get(kind).push(item)
213
+ }
214
+ const row = (item) => {
215
+ const kind = item.key.slice(0, item.key.indexOf('/'))
216
+ const name = item.key.slice(item.key.indexOf('/') + 1)
217
+ const href = `${BASE}/${encodeURIComponent(sid)}/${kind}/${name.split('/').map(encodeURIComponent).join('/')}`
218
+ const label = item.label ? `${item.label} ` : ''
219
+ return `<li><a class="k" href="${href}">${escapeHtml(name)}</a><span class="t">${escapeHtml(label || kind)}</span></li>`
220
+ }
221
+ const files = groups.get('f')
222
+ const apps = groups.get('app')
223
+ const selfUrl = `${origin}${BASE}/${encodeURIComponent(sid)}/`
224
+ const stateRows = state
225
+ .map(([key, value]) => `<li><code>${escapeHtml(key)}</code><span class="k">${escapeHtml(stateValue(value))}</span></li>`)
226
+ .join('')
227
+ const body = `
228
+ <h1>会话 <code>${escapeHtml(sid)}</code></h1>
229
+ <p class="note">这个会话的地址:<code>${escapeHtml(selfUrl)}</code>(端口不出现在地址里,换机换端口都还是这个)</p>
230
+ ${entry?.label ? `<p class="note">${escapeHtml(entry.label)}</p>` : ''}
231
+ ${entry?.workspace ? `<p class="note">工作区:<code>${escapeHtml(entry.workspace)}</code></p>` : ''}
232
+ ${entry?.updatedAt ? `<p class="note">最近更新:<code>${escapeHtml(entry.updatedAt)}</code></p>` : ''}
233
+ ${state.length ? `<h2>会话状态(关掉再打开从这里接着走)</h2><ul>${stateRows}</ul>` : ''}
234
+ ${files.length ? `<h2>产物</h2><ul>${files.map(row).join('')}</ul>` : '<p class="note">还没有发布过静态产物。</p>'}
235
+ ${apps.length ? `<h2>应用</h2><ul>${apps.map(row).join('')}</ul>` : ''}
236
+ <p class="note">这个页面只是索引;真正要给别人看的地址是上面每一条的链接。</p>`
237
+ return pageShell(`会话 ${sid} · 网关`, body)
238
+ }
239
+
240
+ function rootPage(store) {
241
+ /* 最近改过的排前面:用户「关掉再打开」时先要看到的就是上一次那个会话。 */
242
+ const entries = Object.entries(store.entries || {})
243
+ .sort((a, b) => String(b[1]?.updatedAt || '').localeCompare(String(a[1]?.updatedAt || '')))
244
+ const rows = entries
245
+ .map(([sid, entry]) => {
246
+ const count = Object.keys(entry?.items || {}).length
247
+ const stated = Object.keys(entry?.state || {}).length
248
+ const bits = []
249
+ if (count) bits.push(`${count} 条产物`)
250
+ if (stated) bits.push(`${stated} 项状态`)
251
+ if (!bits.length) bits.push('空')
252
+ if (entry?.updatedAt) bits.push(String(entry.updatedAt).replace('T', ' ').slice(0, 16))
253
+ return `<li><a class="k" href="${BASE}/${encodeURIComponent(sid)}/">${escapeHtml(sid)}</a>`
254
+ + `<span class="t">${escapeHtml(bits.join(' · '))}</span></li>`
255
+ })
256
+ .join('')
257
+ const body = `
258
+ <h1>统一入口</h1>
259
+ <p class="note">每个会话一个地址:<code>${BASE}/&lt;会话id&gt;/</code>。端口不出现在任何链接里;关掉再打开,产物和会话状态都还在这一页。</p>
260
+ ${entries.length ? `<h2>所有会话(${entries.length})</h2><ul>${rows}</ul>` : '<p class="note">还没有任何会话记过状态、也没发布过产物。</p>'}`
261
+ return pageShell('统一入口 · 网关', body)
262
+ }
263
+
264
+ /* ───────────────────────── 主处理器 ───────────────────────── */
265
+
266
+ /**
267
+ * 处理 `/s/...` 的读请求。
268
+ * @param {import('node:http').IncomingMessage} req
269
+ * @param {import('node:http').ServerResponse} res
270
+ * @param {{store?:object}} [options]
271
+ */
272
+ export function handleRead(req, res, options = {}) {
273
+ const url = new URL(String(req.url || '/'), 'http://127.0.0.1')
274
+ const pathname = url.pathname.replace(/\/+$/, '') || '/'
275
+ const trailingSlash = /\/$/.test(url.pathname)
276
+
277
+ if (pathname === BASE || pathname === '/') {
278
+ if (!trailingSlash && pathname === BASE) return redirect301(res, `${BASE}/`)
279
+ const store = options.store || readStore()
280
+ return sendText(res, 200, rootPage(store), 'text/html; charset=utf-8')
281
+ }
282
+
283
+ const rest = pathname.slice(BASE.length)
284
+ const segments = rest.split('/').filter(Boolean)
285
+ if (!segments.length) return sendText(res, 200, rootPage(options.store || readStore()), 'text/html; charset=utf-8')
286
+
287
+ let sid
288
+ try {
289
+ sid = decodeURIComponent(segments[0])
290
+ } catch {
291
+ return notFoundPage(res, '会话 id 的百分号转义不合法')
292
+ }
293
+
294
+ const store = options.store || readStore()
295
+ const entry = sessionEntry(store, sid)
296
+
297
+ /* `/s/<sid>` 少尾斜杠:必须 301 补上。
298
+ * 不补的话浏览器会把 document.baseURI 算到上一级,页面里的 `./app.js`
299
+ * 全部解析到别处,表现为「白屏、控制台一堆 404」——这是台账里记过的真实事故。 */
300
+ if (segments.length === 1 && !trailingSlash) return redirect301(res, `${BASE}/${encodeURIComponent(sid)}/`)
301
+ if (segments.length === 1) {
302
+ if (!entry) return notFoundPage(res, '这个会话还没有发布过任何产物', { sid })
303
+ /* origin 只用来把「这个会话的地址」整条显示出来(复制给别人用);
304
+ * 用 Host 头是安全的:它只进页面文本,且已经过 escapeHtml。 */
305
+ const origin = `http://${String(req.headers.host || '127.0.0.1:10170')}`
306
+ return sendText(res, 200, sessionPage(sid, entry, { origin }), 'text/html; charset=utf-8')
307
+ }
308
+
309
+ const target = splitTarget(rest)
310
+ if (!target) return notFoundPage(res, '地址形状不认识(应为 /s/<会话id>/f/<名字>)', { sid })
311
+ if (!entry) return notFoundPage(res, '这个会话还没有发布过任何产物', { sid, kind: target.kind, name: target.name })
312
+ if (!target.name) return redirect301(res, `${BASE}/${encodeURIComponent(sid)}/`)
313
+
314
+ const hit = resolveItem(entry, target.kind, target.name)
315
+ if (!hit) return notFoundPage(res, '没有这个条目', { sid, kind: target.kind, name: target.name })
316
+
317
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
318
+ return send(res, 405, { ok: false, error: '产物只读;写入请走控制面' }, { allow: 'GET, HEAD' })
319
+ }
320
+
321
+ if (target.kind === 'app') {
322
+ const resolved = resolveService(hit.item.serviceId)
323
+ if (!resolved.ok) {
324
+ return send(res, resolved.status === 503 ? 503 : resolved.status, {
325
+ ok: false, error: resolved.error,
326
+ hint: '服务没起来时网关不会替你拉起它——用 broker 的控制面启动,或让套件自己启。',
327
+ })
328
+ }
329
+ const mountPath = `${BASE}/${encodeURIComponent(sid)}/app/${hit.key.slice(4)}`
330
+ const suffix = hit.rest ? `/${hit.rest}` : ''
331
+ return proxy(req, res, {
332
+ origin: resolved.origin,
333
+ mountPath,
334
+ upstreamPath: `${suffix || '/'}${url.search}`,
335
+ })
336
+ }
337
+
338
+ /* 静态产物:单文件条目直接发;目录条目拿子路径,缺省补 index.html。 */
339
+ if (hit.item.kind === 'dir') {
340
+ const sub = hit.rest || ''
341
+ const child = safeChild(hit.item.absPath, sub || 'index.html')
342
+ if (!child.ok) return notFoundPage(res, child.error, { sid, kind: 'f', name: target.name })
343
+ if (child.isDirectory) {
344
+ if (!trailingSlash) return redirect301(res, `${url.pathname}/`)
345
+ const index = safeChild(hit.item.absPath, `${sub ? `${sub}/` : ''}index.html`)
346
+ if (!index.ok) return notFoundPage(res, '目录里没有 index.html', { sid, kind: 'f', name: target.name })
347
+ return serveFile(req, res, index.real, { size: index.size, mime: 'text/html; charset=utf-8' })
348
+ }
349
+ return serveFile(req, res, child.real, { size: child.size, mime: mimeFor(child.real) })
350
+ }
351
+
352
+ const file = hit.item.absPath
353
+ if (!file) return notFoundPage(res, '条目没有绑定文件', { sid, kind: 'f', name: target.name })
354
+ let stat
355
+ try {
356
+ stat = fs.statSync(file)
357
+ } catch {
358
+ return notFoundPage(res, '产物文件已不存在(可能被清理或改名)', { sid, kind: 'f', name: target.name })
359
+ }
360
+ if (!stat.isFile()) return notFoundPage(res, '条目指向的不是文件', { sid, kind: 'f', name: target.name })
361
+ const mime = hit.item.mime || mimeFor(file)
362
+ if (isHtmlMime(mime) && !trailingSlash && target.name.endsWith('/')) {
363
+ return redirect301(res, `${url.pathname}/`)
364
+ }
365
+ return serveFile(req, res, file, { size: stat.size, mime })
366
+ }
367
+
368
+ /* ───────────────────────── 发布原语 ───────────────────────── */
369
+
370
+ /** 条目在 URL 里的形状(单文件不带尾斜杠,目录带尾斜杠)。 */
371
+ export function itemUrl(sid, key, { dir = false } = {}) {
372
+ const encoded = String(key).split('/').map(encodeURIComponent).join('/')
373
+ return `${BASE}/${encodeURIComponent(sid)}/${encoded}${dir ? '/' : ''}`
374
+ }
375
+
376
+ /**
377
+ * 发布一个静态产物(单文件或整个目录)。
378
+ *
379
+ * 控制面与工具面共用这一段:两边都只是「把已经校验过的绝对路径写进注册表」,
380
+ * 差别只在错误怎么回(JSON 还是工具结果)。
381
+ */
382
+ export function publishStaticItem({ sid, name, absPath, dirPath, mime, label = '', expiresAt = 0, workspace = '', sessionLabel = '' }) {
383
+ const isDir = Boolean(dirPath)
384
+ const target = isDir ? dirPath : absPath
385
+ const stat = fs.statSync(target)
386
+ if (isDir && !stat.isDirectory()) throw new Error(`不是目录:${target}`)
387
+ if (!isDir && !stat.isFile()) throw new Error(`不是文件:${target}`)
388
+ const store = readStore()
389
+ const key = `f/${name}`
390
+ const item = isDir
391
+ ? {
392
+ kind: 'dir',
393
+ absPath: fs.realpathSync(dirPath),
394
+ mime: 'text/html; charset=utf-8',
395
+ label: label || path.basename(dirPath),
396
+ expiresAt: Number(expiresAt || 0) || 0,
397
+ }
398
+ : {
399
+ kind: 'static',
400
+ absPath: fs.realpathSync(absPath),
401
+ mime: mime || mimeFor(absPath),
402
+ label: label || path.basename(absPath),
403
+ expiresAt: Number(expiresAt || 0) || 0,
404
+ }
405
+ const { created } = upsertItem(store, sid, key, item, { label: sessionLabel, workspace })
406
+ writeStore(store)
407
+ return { created, key, item, url: itemUrl(sid, key, { dir: isDir }) }
408
+ }
409
+
410
+ /**
411
+ * 发布一个上游应用。**只认服务 id**:地址由 services.json 现场给出,
412
+ * 这样 broker 重启换端口也不影响已经发出去的链接。
413
+ */
414
+ export function publishUpstreamItem({ sid, name, serviceId, label = '', ttl = 0, workspace = '', sessionLabel = '' }) {
415
+ const store = readStore()
416
+ const key = `app/${name}`
417
+ const item = {
418
+ kind: 'upstream',
419
+ serviceId,
420
+ label: label || serviceId,
421
+ expiresAt: Number(ttl || 0) ? Date.now() + Number(ttl) * 1000 : 0,
422
+ }
423
+ const { created } = upsertItem(store, sid, key, item, { label: sessionLabel, workspace })
424
+ writeStore(store)
425
+ return { created, key, item, url: itemUrl(sid, key) }
426
+ }
427
+
428
+ /**
429
+ * 会话本身的样子:状态 + 条目 + 地址。控制面与工具面共用同一个形状,
430
+ * 免得「HTTP 返回的字段」和「工具返回的字段」各写一套之后慢慢对不上。
431
+ */
432
+ export function describeSession(sid) {
433
+ const entry = sessionEntry(readStore(), sid)
434
+ if (!entry) return null
435
+ return {
436
+ sessionId: entry.sessionId,
437
+ label: entry.label,
438
+ workspace: entry.workspace,
439
+ updatedAt: entry.updatedAt,
440
+ state: entry.state,
441
+ url: `${BASE}/${encodeURIComponent(sid)}/`,
442
+ items: publicItems(entry).map((item) => ({
443
+ ...item,
444
+ url: itemUrl(sid, item.key, { dir: item.kind === 'dir' }),
445
+ })),
446
+ }
447
+ }
448
+
449
+ /**
450
+ * 记会话状态(浅合并;值为 null 表示擦掉该键)。
451
+ * 这是「关掉再打开接着走」的唯一写入点:状态落在 gateway.json 里,重启不丢。
452
+ */
453
+ export function recordSession(sid, patch = {}) {
454
+ const store = readStore()
455
+ patchSession(store, sid, patch)
456
+ writeStore(store)
457
+ return describeSession(sid)
458
+ }
459
+
460
+ /** 给工具面用的只读视图:某个会话(或全部会话)已发布的条目。 */
461
+ export function listEntries(workspace = '') {
462
+ const store = readStore()
463
+ const out = []
464
+ for (const [sid, entry] of Object.entries(store.entries || {})) {
465
+ if (workspace && entry?.workspace !== workspace) continue
466
+ for (const item of publicItems(entry)) {
467
+ out.push({
468
+ sid,
469
+ key: item.key,
470
+ kind: item.kind,
471
+ label: item.label,
472
+ serviceId: item.serviceId,
473
+ url: itemUrl(sid, item.key, { dir: item.kind === 'dir' }),
474
+ })
475
+ }
476
+ }
477
+ return out
478
+ }
479
+
480
+ /** 删一个条目(工具面与控制面共用)。返回是否真的删掉了。 */
481
+ export function deleteEntry(sid, key) {
482
+ const store = readStore()
483
+ if (!removeItem(store, sid, key)) return false
484
+ writeStore(store)
485
+ return true
486
+ }
487
+
488
+ /* ───────────────────────── 控制面 ───────────────────────── */
489
+
490
+ /**
491
+ * 控制面:发布/删除/列表/GC。全部要求 token(由调用方在 plugin 层校验)。
492
+ *
493
+ * 形状:
494
+ * PUT /__gateway__/s/<sid>/f/<name> { path | dirPath, mime?, label?, expiresAt? }
495
+ * PUT /__gateway__/s/<sid>/app/<name> { serviceId, label?, ttl? }
496
+ * DELETE /__gateway__/s/<sid>/<kind>/<name>
497
+ * GET /__gateway__/s/<sid> 会话本身:状态 + 条目 + 地址
498
+ * PUT /__gateway__/s/<sid>/state { label?, workspace?, state? } 浅合并
499
+ * DELETE /__gateway__/s/<sid> 整个会话
500
+ * GET /__gateway__/list[?workspace=]
501
+ * POST /__gateway__/gc
502
+ * GET /__gateway__/health
503
+ */
504
+ export async function handleControl(req, res, { token, onStore } = {}) {
505
+ const url = new URL(String(req.url || '/'), 'http://127.0.0.1')
506
+ const pathname = url.pathname.replace(/\/+$/, '') || CONTROL
507
+ const route = `${req.method} ${pathname}`
508
+
509
+ if (route === 'GET /__gateway__/health') {
510
+ return send(res, 200, { ok: true, service: 'gateway', control: CONTROL, base: BASE })
511
+ }
512
+
513
+ if (!tokenMatches(token, req.headers['x-gateway-token'])) {
514
+ return send(res, 401, { ok: false, error: '需要 x-gateway-token(文件默认在 $DSH_HOME/gateway-token)' })
515
+ }
516
+
517
+ if (route === 'GET /__gateway__/list') {
518
+ const store = readStore()
519
+ const workspace = url.searchParams.get('workspace') || ''
520
+ const entries = {}
521
+ for (const [sid, entry] of Object.entries(store.entries || {})) {
522
+ if (workspace && entry?.workspace !== workspace) continue
523
+ entries[sid] = {
524
+ sessionId: entry?.sessionId || sid,
525
+ label: entry?.label || '',
526
+ workspace: entry?.workspace || '',
527
+ updatedAt: entry?.updatedAt || '',
528
+ state: entry?.state && typeof entry.state === 'object' ? entry.state : {},
529
+ items: publicItems(entry).map((item) => ({
530
+ ...item,
531
+ url: `${BASE}/${encodeURIComponent(sid)}/${item.key}`,
532
+ })),
533
+ }
534
+ }
535
+ return send(res, 200, { ok: true, updatedAt: store.updatedAt, entries })
536
+ }
537
+
538
+ if (route === 'POST /__gateway__/gc') {
539
+ const store = readStore()
540
+ const removed = pruneStore(store)
541
+ if (removed) onStore ? onStore(store) : writeStore(store)
542
+ return send(res, 200, { ok: true, removed })
543
+ }
544
+
545
+ const tail = pathname.slice(CONTROL.length).replace(/^\/+/, '')
546
+ const segments = tail.split('/').filter(Boolean)
547
+ if (segments[0] !== 's' || segments.length < 2) {
548
+ return send(res, 404, { ok: false, error: `未知端点 ${route}` })
549
+ }
550
+ let sid
551
+ try {
552
+ sid = decodeURIComponent(segments[1])
553
+ } catch {
554
+ return send(res, 400, { ok: false, error: '会话 id 转义不合法' })
555
+ }
556
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(sid)) {
557
+ return send(res, 400, { ok: false, error: `会话 id 形状不合法:${sid}` })
558
+ }
559
+
560
+ const kind = segments[2]
561
+ if (req.method === 'DELETE' && !kind) {
562
+ const store = readStore()
563
+ if (!store.entries?.[sid]) return send(res, 404, { ok: false, error: '没有这个会话' })
564
+ delete store.entries[sid]
565
+ onStore ? onStore(store) : writeStore(store)
566
+ return send(res, 200, { ok: true, removed: sid })
567
+ }
568
+
569
+ /* 会话本身:GET 读状态,PUT/POST /s/<sid>/state 写状态。
570
+ * 状态是「关掉再打开还能接着走」的唯一来源,所以它和条目一样落在 gateway.json 里。 */
571
+ if (!kind) {
572
+ if (req.method !== 'GET') {
573
+ return send(res, 405, { ok: false, error: `${route} 不支持` }, { allow: 'GET, DELETE' })
574
+ }
575
+ const session = describeSession(sid)
576
+ if (!session) return send(res, 404, { ok: false, error: '没有这个会话' })
577
+ return send(res, 200, { ok: true, session })
578
+ }
579
+
580
+ if (kind === 'state') {
581
+ if (req.method !== 'PUT' && req.method !== 'POST') {
582
+ return send(res, 405, { ok: false, error: `${route} 不支持` }, { allow: 'PUT, POST' })
583
+ }
584
+ let body
585
+ try {
586
+ body = await readJson(req)
587
+ } catch (error) {
588
+ return send(res, error.status || 400, { ok: false, error: error.message })
589
+ }
590
+ const patch = {}
591
+ if (typeof body.label === 'string' && body.label) patch.label = body.label
592
+ if (typeof body.workspace === 'string' && body.workspace) patch.workspace = body.workspace
593
+ if (body.state !== undefined) {
594
+ if (!body.state || typeof body.state !== 'object' || Array.isArray(body.state)) {
595
+ return send(res, 400, { ok: false, error: 'state 必须是对象(键值对)' })
596
+ }
597
+ const keys = Object.keys(body.state)
598
+ if (keys.length > 32) return send(res, 400, { ok: false, error: 'state 最多 32 个键' })
599
+ const bad = keys.find((key) => !/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$/.test(key))
600
+ if (bad) return send(res, 400, { ok: false, error: `state 的键不合法:${bad}` })
601
+ if (JSON.stringify(body.state).length > 16 * 1024) {
602
+ return send(res, 400, { ok: false, error: 'state 序列化后不能超过 16KB' })
603
+ }
604
+ patch.state = body.state
605
+ }
606
+ if (!Object.keys(patch).length) return send(res, 400, { ok: false, error: '没有可写字段(label / workspace / state)' })
607
+ const store = readStore()
608
+ patchSession(store, sid, patch)
609
+ onStore ? onStore(store) : writeStore(store)
610
+ return send(res, 200, { ok: true, session: describeSession(sid) })
611
+ }
612
+
613
+ if (kind !== 'f' && kind !== 'app') {
614
+ return send(res, 400, { ok: false, error: '类型只能是 f(静态产物)或 app(上游应用)' })
615
+ }
616
+ let name
617
+ try {
618
+ name = segments.slice(3).map(decodeURIComponent).join('/')
619
+ } catch {
620
+ return send(res, 400, { ok: false, error: '名字转义不合法' })
621
+ }
622
+ if (!name) return send(res, 400, { ok: false, error: '缺少名字' })
623
+ if (name.split('/').some((segment) => !/^[A-Za-z0-9_-][A-Za-z0-9._-]*$/.test(segment))) {
624
+ return send(res, 400, { ok: false, error: `名字不合法:${name}(逐段只允许字母数字 . _ -,且不能以点开头)` })
625
+ }
626
+ const key = `${kind}/${name}`
627
+
628
+ if (req.method === 'DELETE') {
629
+ const store = readStore()
630
+ if (!removeItem(store, sid, key)) return send(res, 404, { ok: false, error: '没有这个条目' })
631
+ onStore ? onStore(store) : writeStore(store)
632
+ return send(res, 200, { ok: true, removed: key })
633
+ }
634
+
635
+ if (req.method !== 'PUT' && req.method !== 'POST') {
636
+ return send(res, 405, { ok: false, error: `${route} 不支持` }, { allow: 'PUT, POST, DELETE' })
637
+ }
638
+
639
+ let body
640
+ try {
641
+ body = await readJson(req)
642
+ } catch (error) {
643
+ return send(res, error.status || 400, { ok: false, error: error.message })
644
+ }
645
+
646
+ const store = readStore()
647
+ const meta = { label: body.label, workspace: body.workspace }
648
+
649
+ if (kind === 'f') {
650
+ const absPath = typeof body.path === 'string' ? body.path : ''
651
+ const dirPath = typeof body.dirPath === 'string' ? body.dirPath : ''
652
+ if (!absPath && !dirPath) return send(res, 400, { ok: false, error: '需要 path(单文件)或 dirPath(目录)' })
653
+ if (absPath && dirPath) return send(res, 400, { ok: false, error: 'path 与 dirPath 只能给一个' })
654
+ if (!path.isAbsolute(absPath || dirPath)) return send(res, 400, { ok: false, error: '必须给绝对路径' })
655
+ if (absPath) {
656
+ let stat
657
+ try {
658
+ stat = fs.statSync(absPath)
659
+ } catch {
660
+ return send(res, 400, { ok: false, error: `文件不存在:${absPath}` })
661
+ }
662
+ if (!stat.isFile()) return send(res, 400, { ok: false, error: `不是文件:${absPath}` })
663
+ const item = {
664
+ kind: 'static',
665
+ absPath: fs.realpathSync(absPath),
666
+ mime: body.mime || mimeFor(absPath),
667
+ label: body.label || path.basename(absPath),
668
+ expiresAt: Number(body.expiresAt || 0) || 0,
669
+ }
670
+ const { created } = upsertItem(store, sid, key, item, meta)
671
+ onStore ? onStore(store) : writeStore(store)
672
+ return send(res, created ? 201 : 200, {
673
+ ok: true, created, key, sessionId: sid,
674
+ url: `${BASE}/${encodeURIComponent(sid)}/${kind}/${name.split('/').map(encodeURIComponent).join('/')}`,
675
+ })
676
+ }
677
+ let stat
678
+ try {
679
+ stat = fs.statSync(dirPath)
680
+ } catch {
681
+ return send(res, 400, { ok: false, error: `目录不存在:${dirPath}` })
682
+ }
683
+ if (!stat.isDirectory()) return send(res, 400, { ok: false, error: `不是目录:${dirPath}` })
684
+ const item = {
685
+ kind: 'dir',
686
+ absPath: fs.realpathSync(dirPath),
687
+ mime: 'text/html; charset=utf-8',
688
+ label: body.label || path.basename(dirPath),
689
+ expiresAt: Number(body.expiresAt || 0) || 0,
690
+ }
691
+ const { created } = upsertItem(store, sid, key, item, meta)
692
+ onStore ? onStore(store) : writeStore(store)
693
+ return send(res, created ? 201 : 200, {
694
+ ok: true, created, key, sessionId: sid, kind: 'dir',
695
+ url: `${BASE}/${encodeURIComponent(sid)}/${kind}/${name.split('/').map(encodeURIComponent).join('/')}/`,
696
+ })
697
+ }
698
+
699
+ /* app:只认服务 id,不认地址——地址由 services.json 现场给出。 */
700
+ const serviceId = typeof body.serviceId === 'string' ? body.serviceId.trim() : ''
701
+ if (!serviceId) return send(res, 400, { ok: false, error: '需要 serviceId(服务 id,不是地址)' })
702
+ const item = {
703
+ kind: 'upstream',
704
+ serviceId,
705
+ label: body.label || serviceId,
706
+ expiresAt: Number(body.ttl || 0) ? Date.now() + Number(body.ttl) * 1000 : 0,
707
+ }
708
+ const { created } = upsertItem(store, sid, key, item, meta)
709
+ onStore ? onStore(store) : writeStore(store)
710
+ return send(res, created ? 201 : 200, {
711
+ ok: true, created, key, sessionId: sid, serviceId,
712
+ url: `${BASE}/${encodeURIComponent(sid)}/${kind}/${name.split('/').map(encodeURIComponent).join('/')}`,
713
+ })
714
+ }