@capyclaw/publisher 0.1.0 → 0.1.4

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.
@@ -0,0 +1,339 @@
1
+ /**
2
+ * 拖拽发布的同源 HTTP 面(挂在 DSH 自带 webServer 上,和插件页同源)。
3
+ *
4
+ * GET /publisher-drop/health 探活 + npm 身份 + 最近发布
5
+ * POST /publisher-drop/prepare 上传压缩包 → 解包 → 版本规划 + 预检结果
6
+ * POST /publisher-drop/publish 对 prepare 得到的 token 真发布(不可撤销)
7
+ * POST /publisher-drop/discard 放弃一次预检(回收 staging)
8
+ *
9
+ * 路由只做「读写 HTTP + 管句柄」,发布逻辑全在 drop.mjs;token 是唯一句柄,
10
+ * 浏览器永远拿不到本机路径,也就无法让宿主对任意目录执行 npm publish。
11
+ */
12
+ import crypto from 'node:crypto'
13
+
14
+ import {
15
+ MAX_ARCHIVE_BYTES, cleanupStage, npmRun, prepareUpload, previewStage, publishStage, sweepOrphans,
16
+ } from './drop.mjs'
17
+
18
+ const ROUTE_PREFIX = '/publisher-drop'
19
+ const MAX_JSON_BYTES = 64 * 1024
20
+ const STAGE_TTL_MS = 2 * 60 * 60 * 1000
21
+ const MAX_STAGES = 16
22
+ const RECENT_LIMIT = 8
23
+ const WHOAMI_TTL_MS = 60 * 1000
24
+ const WHOAMI_HINT = 'npm whoami 失败——在宿主机 npm login,或设置 NODE_AUTH_TOKEN'
25
+
26
+ /**
27
+ * 建一套路由处理器;每次插件挂载一份独立状态(staging 句柄 / 最近发布 / 发布锁)。
28
+ * npm 调用全部异步:npm 一慢,卡住的只能这一个请求,不会把宿主事件循环钉住。
29
+ * `npm` / `whoami` 可注入,测试里用假实现代替真实 registry。
30
+ */
31
+ export function createRoutes({ webServer, log, packageVersion = '', npm = npmRun, whoami = null, publishedTtlMs }) {
32
+ /** previewStage 的版本缓存时长;测试传 0 关掉缓存,生产用默认 15s。 */
33
+ const cacheOpts = publishedTtlMs === undefined ? {} : { cacheTtlMs: publishedTtlMs };
34
+ const stages = new Map()
35
+ const recent = []
36
+ let publishing = false
37
+
38
+ /* whoami 带 60s 缓存:插件页每次切回都会探活,不能每次都真跑一遍 npm。 */
39
+ let whoamiCache = null
40
+ let whoamiAt = 0
41
+ let whoamiPending = null
42
+ const probeWhoami = () => {
43
+ if (whoamiCache && Date.now() - whoamiAt < WHOAMI_TTL_MS) return whoamiCache
44
+ if (whoamiPending) return whoamiPending
45
+ const run = whoami || (async () => {
46
+ const result = await npm(['whoami'], { timeout: 15000 })
47
+ if (result.status !== 0) return { ok: false, hint: WHOAMI_HINT }
48
+ const user = String(result.stdout || '').trim()
49
+ return user ? { ok: true, user } : { ok: false, hint: WHOAMI_HINT }
50
+ })
51
+ whoamiPending = Promise.resolve(run())
52
+ .then((value) => {
53
+ whoamiCache = value
54
+ whoamiAt = Date.now()
55
+ return value
56
+ })
57
+ .catch(() => ({ ok: false, hint: WHOAMI_HINT }))
58
+ .finally(() => { whoamiPending = null })
59
+ return whoamiPending
60
+ }
61
+
62
+ const remember = (entry) => {
63
+ recent.unshift(entry)
64
+ if (recent.length > RECENT_LIMIT) recent.length = RECENT_LIMIT
65
+ }
66
+
67
+ const sweep = () => {
68
+ const cutoff = Date.now() - STAGE_TTL_MS
69
+ for (const [token, entry] of stages) {
70
+ if (entry.createdAt < cutoff) {
71
+ stages.delete(token)
72
+ cleanupStage(entry.stage)
73
+ }
74
+ }
75
+ }
76
+
77
+ /* 内存里没记录、磁盘上却留下的 staging(崩溃/重启后的残骸)由这里兜底清掉。 */
78
+ const sweepDisk = () => {
79
+ const keep = new Set()
80
+ for (const entry of stages.values()) {
81
+ const base = entry.stage?.base
82
+ if (base) keep.add(base)
83
+ }
84
+ return sweepOrphans(keep, STAGE_TTL_MS)
85
+ }
86
+
87
+ /* 拖拽多次却一直不发布时,最多留 MAX_STAGES 份解包结果,超出的丢最旧的。 */
88
+ const trimStages = () => {
89
+ if (stages.size < MAX_STAGES) return
90
+ const ordered = [...stages.values()].sort((a, b) => a.createdAt - b.createdAt)
91
+ for (const entry of ordered.slice(0, stages.size - MAX_STAGES + 1)) {
92
+ stages.delete(entry.token)
93
+ cleanupStage(entry.stage)
94
+ }
95
+ }
96
+
97
+ /* 任何一个处理器抛错都不该变成「请求挂着不回」或未处理拒绝:统一回 500 JSON。 */
98
+ const guard = (handler) => async (req, res) => {
99
+ try {
100
+ await handler(req, res)
101
+ } catch (error) {
102
+ log?.warn?.(`[publisher] 路由异常:${messageOf(error)}`)
103
+ if (!res.headersSent) sendJson(res, 500, { ok: false, error: 'internal', message: messageOf(error) })
104
+ else res.end()
105
+ }
106
+ }
107
+
108
+ return {
109
+ handlers: {
110
+ health: guard(async (req, res) => {
111
+ if (!allow(webServer, req, res, 'GET')) return
112
+ sweep()
113
+ const who = await probeWhoami()
114
+ const orphans = await sweepDisk().catch(() => 0)
115
+ sendJson(res, 200, {
116
+ ok: true,
117
+ contractVersion: '1.0.0',
118
+ packageVersion,
119
+ /* 客户端据此判断宿主是否支持预演:页面可能比宿主新(刷新过浏览器但没重启 DSH)。 */
120
+ features: ['dry-run', 'orphan-sweep'],
121
+ npm: who.ok ? { ok: true, user: who.user } : { ok: false, hint: who.hint },
122
+ pending: stages.size,
123
+ orphans,
124
+ recent,
125
+ })
126
+ }),
127
+
128
+ prepare: guard(async (req, res) => {
129
+ if (!allow(webServer, req, res, 'POST')) return
130
+ /* 每次上传顺带回收过期 staging:用户可能拖进来就关掉页面,从不 discard。 */
131
+ sweep()
132
+ await sweepDisk().catch(() => 0)
133
+ if (publishing) {
134
+ sendJson(res, 200, { ok: false, error: 'busy', message: '上一次发布还没结束,请稍等。' })
135
+ return
136
+ }
137
+ try {
138
+ const buffer = await readBody(req, MAX_ARCHIVE_BYTES)
139
+ if (buffer.length === 0) {
140
+ sendJson(res, 200, { ok: false, error: 'empty', message: '上传的压缩包是空的。' })
141
+ return
142
+ }
143
+ const token = crypto.randomUUID()
144
+ const { stage, preview } = await prepareUpload({ token, buffer, filename: decodeFilename(req) }, { npm, ...cacheOpts })
145
+ stage.token = token
146
+ trimStages()
147
+ stages.set(token, { token, stage, createdAt: Date.now() })
148
+ if (!preview.ok) {
149
+ stages.delete(token)
150
+ cleanupStage(stage)
151
+ sendJson(res, 200, preview)
152
+ return
153
+ }
154
+ sendJson(res, 200, { ...preview, token })
155
+ } catch (error) {
156
+ if (error && error.code === 'too-large') {
157
+ /* readBody 已经把请求排空,这里只负责把原因回给客户端。 */
158
+ sendJson(res, 200, { ok: false, error: 'too-large', message: messageOf(error) })
159
+ return
160
+ }
161
+ sendJson(res, 200, { ok: false, error: 'unpack-failed', message: messageOf(error) })
162
+ }
163
+ }),
164
+
165
+ publish: guard(async (req, res) => {
166
+ if (!allow(webServer, req, res, 'POST')) return
167
+ let body
168
+ try {
169
+ body = await readJson(req)
170
+ } catch (error) {
171
+ sendJson(res, 200, { ok: false, error: 'bad-request', message: messageOf(error) })
172
+ return
173
+ }
174
+ if (publishing) {
175
+ sendJson(res, 200, { ok: false, error: 'busy', message: '上一次发布还没结束,请稍等。' })
176
+ return
177
+ }
178
+ const entry = stages.get(String(body.token || ''))
179
+ if (!entry) {
180
+ sendJson(res, 200, { ok: false, error: 'stage-missing', message: '这次预检已经过期,请重新把包拖进来。' })
181
+ return
182
+ }
183
+
184
+ publishing = true
185
+ try {
186
+ const preview = await previewStage(entry.stage, { npm, ...cacheOpts })
187
+ if (!preview.ok) {
188
+ sendJson(res, 200, preview)
189
+ return
190
+ }
191
+ if (preview.blocking.length > 0) {
192
+ sendJson(res, 200, { ok: false, error: 'gate-failed', message: preview.blocking[0], blocking: preview.blocking })
193
+ return
194
+ }
195
+ const version = typeof body.version === 'string' && body.version.trim() ? body.version.trim() : preview.plan.version
196
+ const tag = typeof body.tag === 'string' && body.tag.trim() ? body.tag.trim() : 'latest'
197
+ const dryRun = body.dryRun === true
198
+ const result = await publishStage(entry.stage, { version, tag, dryRun, npm })
199
+ const record = {
200
+ name: preview.name,
201
+ version,
202
+ tag,
203
+ ok: result.ok,
204
+ dryRun,
205
+ message: result.message || '',
206
+ at: new Date().toISOString(),
207
+ url: result.url || '',
208
+ fresh: preview.plan.mode,
209
+ from: preview.version,
210
+ }
211
+ remember(record)
212
+ if (result.ok && !dryRun) {
213
+ stages.delete(entry.token)
214
+ cleanupStage(entry.stage)
215
+ } else if (result.error === 'publish-failed') {
216
+ /* npm 明确拒绝(版本已存在/权限/2FA):staging 留着,改完再试。 */
217
+ log?.warn?.(`[publisher] 拖拽发布失败 ${preview.name}@${version}:${result.message}`)
218
+ }
219
+ sendJson(res, 200, { ...result, name: preview.name, fromVersion: preview.version, mode: preview.plan.mode, latest: preview.latest, dryRun })
220
+ } catch (error) {
221
+ sendJson(res, 200, { ok: false, error: 'publish-failed', message: messageOf(error) })
222
+ } finally {
223
+ publishing = false
224
+ }
225
+ }),
226
+
227
+ discard: guard(async (req, res) => {
228
+ if (!allow(webServer, req, res, 'POST')) return
229
+ let body
230
+ try {
231
+ body = await readJson(req)
232
+ } catch {
233
+ body = {}
234
+ }
235
+ const token = String(body.token || '')
236
+ const entry = stages.get(token)
237
+ if (entry) {
238
+ stages.delete(token)
239
+ cleanupStage(entry.stage)
240
+ }
241
+ sendJson(res, 200, { ok: true, discarded: Boolean(entry) })
242
+ }),
243
+ },
244
+
245
+ /* 插件卸载时把没发出去的 staging 一并回收,别在 %LOCALAPPDATA% 里越堆越多。 */
246
+ dispose: () => {
247
+ for (const [token, entry] of stages) {
248
+ stages.delete(token)
249
+ cleanupStage(entry.stage)
250
+ }
251
+ },
252
+ }
253
+ }
254
+
255
+ export { ROUTE_PREFIX }
256
+
257
+ /** 只允许本机页面调用:无 Origin(同源 GET / 服务端)或 loopback / 本 webServer 的 origin。 */
258
+ function allow(webServer, req, res, method) {
259
+ if ((req.method || 'GET').toUpperCase() !== method) {
260
+ sendJson(res, 405, { ok: false, error: 'method-not-allowed', message: `Use ${method}.` })
261
+ return false
262
+ }
263
+ if (!isLocalCaller(webServer, req)) {
264
+ sendJson(res, 403, { ok: false, error: 'forbidden', message: 'Only a local page may publish packages.' })
265
+ return false
266
+ }
267
+ return true
268
+ }
269
+
270
+ function isLocalCaller(webServer, req) {
271
+ const origin = req.headers.origin
272
+ if (!origin) return true
273
+ let url
274
+ try {
275
+ url = new URL(origin)
276
+ } catch {
277
+ return false
278
+ }
279
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return false
280
+ const host = url.hostname.toLowerCase()
281
+ if (host === 'localhost' || host === '127.0.0.1' || host === '::1' || host === '[::1]') return true
282
+ try {
283
+ return origin === webServer.getOrigin()
284
+ } catch {
285
+ return false
286
+ }
287
+ }
288
+
289
+ function decodeFilename(req) {
290
+ const raw = req.headers['x-dsh-filename']
291
+ const value = Array.isArray(raw) ? raw[0] : raw
292
+ if (!value) return 'package.zip'
293
+ try {
294
+ return decodeURIComponent(value)
295
+ } catch {
296
+ return value
297
+ }
298
+ }
299
+
300
+ async function readBody(req, limit) {
301
+ const chunks = []
302
+ let total = 0
303
+ let overflow = false
304
+ /* 超限时继续把请求排空再报错:直接抛会被当成连接中断,客户端拿不到可读的原因。 */
305
+ for await (const chunk of req) {
306
+ total += chunk.length
307
+ if (total > limit) {
308
+ overflow = true
309
+ continue
310
+ }
311
+ chunks.push(chunk)
312
+ }
313
+ if (overflow) {
314
+ const error = new Error(`内容超过 ${Math.round(limit / 1024 / 1024)} MB 上限。`)
315
+ error.code = 'too-large'
316
+ throw error
317
+ }
318
+ return Buffer.concat(chunks)
319
+ }
320
+
321
+ async function readJson(req) {
322
+ const buffer = await readBody(req, MAX_JSON_BYTES)
323
+ if (buffer.length === 0) return {}
324
+ return JSON.parse(buffer.toString('utf8'))
325
+ }
326
+
327
+ function sendJson(res, status, payload) {
328
+ const body = Buffer.from(JSON.stringify(payload), 'utf8')
329
+ res.writeHead(status, {
330
+ 'content-type': 'application/json; charset=utf-8',
331
+ 'content-length': body.length,
332
+ 'cache-control': 'no-store',
333
+ })
334
+ res.end(body)
335
+ }
336
+
337
+ function messageOf(error) {
338
+ return error instanceof Error ? error.message : String(error)
339
+ }
package/server/tools.mjs CHANGED
@@ -31,7 +31,7 @@ const whoamiTool = defineTool({
31
31
  description: 'npm 凭据预检:宿主环境是否已登录(npm whoami / NODE_AUTH_TOKEN)。发布前先调用。',
32
32
  inputSchema: { type: 'object', additionalProperties: false, properties: {} },
33
33
  kind: 'read',
34
- handler: () => text(npmWhoami()),
34
+ handler: () => npmWhoami().then(text),
35
35
  })
36
36
 
37
37
  const previewTool = defineTool({
package/lib/host.mjs DELETED
@@ -1,27 +0,0 @@
1
- /**
2
- * @capyclaw/publisher 宿主插件(Cordis 入口)。
3
- *
4
- * 服务宿主、工具面全部来自公共插件;本文件只负责生命周期装配。
5
- * 发布动作发生在独立服务进程里(spawnSync npm),不阻塞 Cordis 事件循环。
6
- */
7
- import path from 'node:path'
8
- import { fileURLToPath } from 'node:url'
9
- import { startService } from '../server/relay.mjs'
10
-
11
- export const name = '@capyclaw/publisher'
12
-
13
- export async function apply(ctx, config = {}) {
14
- const packageDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
15
- const service = await startService({
16
- packageDir,
17
- port: Number(config.port) || 39700,
18
- hostDir: config.hostDir || process.env.DSH_PUBLISHER_HOME,
19
- strictPort: config.strictPort,
20
- lockFile: config.lockFile,
21
- })
22
- console.log(`[@capyclaw/publisher] ${service.reused ? '复用' : '启动'}服务: ${service.url}`)
23
- return async () => {
24
- await service.stop()
25
- console.log('[@capyclaw/publisher] 服务已停止')
26
- }
27
- }
package/server/relay.mjs DELETED
@@ -1,70 +0,0 @@
1
- /**
2
- * @capyclaw/publisher 服务组合根。
3
- *
4
- * 宿主(端口/锁/复用/健康/指标/关闭)由 @capyclaw/service-host 提供;
5
- * 工具面(能力 DSL/注册表/校验/契约/MCP)由 @capyclaw/tool-host 提供;
6
- * 本文件只保留业务装配。
7
- */
8
- import fs from 'node:fs'
9
- import path from 'node:path'
10
- import { fileURLToPath } from 'node:url'
11
- import { createServiceApp, send } from '@capyclaw/service-host/src'
12
- import {
13
- tools, contractVersion, capabilities, buildInstructions, createMcp,
14
- } from './tools.mjs'
15
-
16
- const HERE = path.dirname(fileURLToPath(import.meta.url))
17
- const DEFAULT_PORT = 39700
18
- const SERVICE_NAME = 'capyclaw-publisher'
19
- const PKG = JSON.parse(fs.readFileSync(path.join(HERE, '..', 'package.json'), 'utf8'))
20
-
21
- export async function startService(options = {}) {
22
- const packageDir = options.packageDir || path.resolve(HERE, '..')
23
-
24
- const app = createServiceApp({
25
- id: SERVICE_NAME,
26
- title: PKG.meta?.title || PKG.name,
27
- version: PKG.version,
28
- contractVersion,
29
- slug: 'publisher',
30
- health: () => ({
31
- tools: tools.length,
32
- }),
33
- })
34
-
35
- const instructions = buildInstructions({
36
- title: PKG.meta?.title || PKG.name,
37
- intro: '本服务提供 publisher_* 工具,在 dsh 内发布 capyclaw 插件工程的可发布集。',
38
- startup: [
39
- '先调用 `publisher_capabilities` 确认 contractVersion 为 1.x。',
40
- '先 `publisher_whoami` 确认 npm 凭据可用,再 `publisher_preview` 预演。',
41
- '`publisher_execute` 需要显式 confirm: true,发布不可撤销。',
42
- ],
43
- capabilities: capabilities().capabilities,
44
- rules: ['工具返回已含逐包回执;改完一句话回复,不要重复验证。'],
45
- })
46
- const mcp = createMcp({ name: SERVICE_NAME, version: PKG.version }, instructions)
47
- app.use((req, res, u) => {
48
- if (u.pathname !== '/mcp') return false
49
- return mcp(req, res).then(() => true)
50
- })
51
-
52
- app.get('/api/info', (req, res) => {
53
- send(req, res, 200, {
54
- ok: true,
55
- name: SERVICE_NAME,
56
- version: PKG.version,
57
- contractVersion,
58
- tools: tools.map((tool) => ({ name: tool.name, description: tool.description })),
59
- })
60
- })
61
-
62
- const info = await app.listen({
63
- port: Number(options.port ?? DEFAULT_PORT),
64
- hostDir: options.hostDir,
65
- strictPort: options.strictPort,
66
- lockFile: options.lockFile,
67
- allowReuse: options.allowReuse !== false,
68
- })
69
- return { ...info, stop: () => info.stop() }
70
- }