dsh-github-console 0.0.0-stage → 0.4.1
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 +21 -0
- package/README.md +155 -2
- package/assets/icon-180.png +0 -0
- package/assets/icon-512.png +0 -0
- package/assets/icon-96.png +0 -0
- package/client.js +1546 -0
- package/cordis.patch.yml +20 -0
- package/icon.svg +7 -0
- package/index.js +4400 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +47 -4
package/index.js
ADDED
|
@@ -0,0 +1,4400 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DSH GitHub Console — Host half.
|
|
3
|
+
*
|
|
4
|
+
* GitHub App authentication (manifest flow) + installation tokens, a same-origin
|
|
5
|
+
* panel API, and agent tools for repositories, files, issues, pull requests,
|
|
6
|
+
* workflow runs, and plugin publishing.
|
|
7
|
+
*
|
|
8
|
+
* Secrets live only in the DSH credential service:
|
|
9
|
+
* github-console/app { appId, pem, slug, name, htmlUrl, owner, clientId, clientSecret }
|
|
10
|
+
* github-console/install { id, account, permissions } (which installation to use)
|
|
11
|
+
* github-console/bridge { token } (panel API bearer token)
|
|
12
|
+
* Installation access tokens are memory-only with a one hour life.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import crypto from 'node:crypto'
|
|
16
|
+
import fs from 'node:fs/promises'
|
|
17
|
+
import path from 'node:path'
|
|
18
|
+
import os from 'node:os'
|
|
19
|
+
import net from 'node:net'
|
|
20
|
+
import tls from 'node:tls'
|
|
21
|
+
import https from 'node:https'
|
|
22
|
+
import zlib from 'node:zlib'
|
|
23
|
+
import { fileURLToPath } from 'node:url'
|
|
24
|
+
import { promises as dnsPromises, Resolver } from 'node:dns'
|
|
25
|
+
|
|
26
|
+
const PLUGIN_VERSION = '0.4.1'
|
|
27
|
+
const APP_CRED = 'github-console/app'
|
|
28
|
+
const INSTALL_CRED = 'github-console/install'
|
|
29
|
+
const BRIDGE_CRED = 'github-console/bridge'
|
|
30
|
+
const INDEX_CRED = 'github-console/index'
|
|
31
|
+
// Connection choices: GitHub App installation (default), a user PAT, or a token
|
|
32
|
+
// taken from an environment variable. The active one is remembered separately so
|
|
33
|
+
// switching does not throw away another connection's credentials.
|
|
34
|
+
const PAT_CRED = 'github-console/pat'
|
|
35
|
+
const AUTH_CRED = 'github-console/active'
|
|
36
|
+
// App user authorization (user-to-server): short-lived token plus a refresh token.
|
|
37
|
+
const OAUTH_CRED = 'github-console/oauth'
|
|
38
|
+
const DEFAULT_API = 'https://api.github.com'
|
|
39
|
+
const PREFIX = '/github-console'
|
|
40
|
+
const PLUGIN_DIR = path.dirname(fileURLToPath(import.meta.url))
|
|
41
|
+
const MANIFEST_TTL_MS = 60 * 60 * 1000
|
|
42
|
+
const INSTALL_TOKEN_MARGIN_MS = 5 * 60 * 1000
|
|
43
|
+
|
|
44
|
+
// A credential key outside "<scope>/<id>" poisons the whole credentials document
|
|
45
|
+
// and aborts the next startup, so refuse to run with a malformed key.
|
|
46
|
+
for (const key of [APP_CRED, INSTALL_CRED, BRIDGE_CRED, INDEX_CRED, PAT_CRED, AUTH_CRED, OAUTH_CRED]) {
|
|
47
|
+
if (!/^[a-z][a-z0-9-]*\/[a-z][a-z0-9-]*$/.test(key)) {
|
|
48
|
+
throw new Error(`Invalid credential key "${key}": expected "<scope>/<id>"`)
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Only machine-local or VCS internals are skipped: a bundle's runtime entry can
|
|
53
|
+
// legitimately live in lib/ or dist/, so those must be published.
|
|
54
|
+
const SKIP_DIRS = new Set(['node_modules', '.git', '.pnpm-store', '.cache', '.turbo'])
|
|
55
|
+
const SECRET_PATTERNS = [
|
|
56
|
+
['GitHub token', /\b(gh[pousr]_[A-Za-z0-9]{16,}|github_pat_[A-Za-z0-9_]{20,})\b/],
|
|
57
|
+
['private key', /-----BEGIN [A-Z ]*PRIVATE KEY-----/],
|
|
58
|
+
['OpenAI-style key', /\bsk-[A-Za-z0-9]{20,}\b/],
|
|
59
|
+
['npm token', /\bnpm_[A-Za-z0-9]{20,}\b/],
|
|
60
|
+
['AWS key', /\bAKIA[0-9A-Z]{16}\b/],
|
|
61
|
+
]
|
|
62
|
+
|
|
63
|
+
// Directories that never contain a DSH plugin checkout worth listing, and that
|
|
64
|
+
// would make discovery slow in a large workspace.
|
|
65
|
+
const DISCOVER_SKIP = new Set([
|
|
66
|
+
'node_modules', '.git', '.pnpm-store', '.cache', 'dist', 'build', '.next',
|
|
67
|
+
'sessions', 'storages', 'profiles', 'attachments', 'cache', 'dsh-runtimes',
|
|
68
|
+
'media-desk', 'memory', 'llm-deepseek', 'skills',
|
|
69
|
+
])
|
|
70
|
+
|
|
71
|
+
async function looksLikePlugin(dir) {
|
|
72
|
+
const pkgPath = path.join(dir, 'package.json')
|
|
73
|
+
const stat = await fs.stat(pkgPath).catch(() => null)
|
|
74
|
+
if (!stat || !stat.isFile() || stat.size > 512 * 1024) return null
|
|
75
|
+
const raw = await fs.readFile(pkgPath, 'utf8').catch(() => '')
|
|
76
|
+
let pkg
|
|
77
|
+
try {
|
|
78
|
+
pkg = JSON.parse(raw)
|
|
79
|
+
} catch {
|
|
80
|
+
return null
|
|
81
|
+
}
|
|
82
|
+
const bundle = pkg.dsh && pkg.dsh.bundle && pkg.dsh.bundle.patch ? String(pkg.dsh.bundle.patch) : ''
|
|
83
|
+
const client = pkg.dsh && pkg.dsh.client ? true : false
|
|
84
|
+
if (!bundle && !client) return null
|
|
85
|
+
const dirStat = await fs.stat(dir).catch(() => null)
|
|
86
|
+
const name = typeof pkg.name === 'string' ? pkg.name : ''
|
|
87
|
+
return {
|
|
88
|
+
dir,
|
|
89
|
+
name,
|
|
90
|
+
version: typeof pkg.version === 'string' ? pkg.version : '',
|
|
91
|
+
description: typeof pkg.description === 'string' ? pkg.description : '',
|
|
92
|
+
patch: bundle,
|
|
93
|
+
hasClient: client,
|
|
94
|
+
// A repository name GitHub accepts: drop the npm scope and any odd characters.
|
|
95
|
+
suggestedRepo: name.replace(/^@[^/]+\//, '').replace(/[^A-Za-z0-9._-]/g, '-').slice(0, 90),
|
|
96
|
+
mtime: dirStat ? dirStat.mtime.toISOString() : null,
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Find publishable plugin checkouts without touching the network or GitHub, so
|
|
102
|
+
* the panel has something useful to show before anyone signs in.
|
|
103
|
+
*/
|
|
104
|
+
async function discoverPlugins(roots, limit = 40) {
|
|
105
|
+
const candidates = []
|
|
106
|
+
const seen = new Set()
|
|
107
|
+
const scanned = []
|
|
108
|
+
let examined = 0
|
|
109
|
+
const budget = 600
|
|
110
|
+
|
|
111
|
+
for (const root of roots) {
|
|
112
|
+
const stat = await fs.stat(root).catch(() => null)
|
|
113
|
+
if (!stat || !stat.isDirectory()) {
|
|
114
|
+
scanned.push({ root, exists: false, found: 0 })
|
|
115
|
+
continue
|
|
116
|
+
}
|
|
117
|
+
let found = 0
|
|
118
|
+
const selfHit = await looksLikePlugin(root)
|
|
119
|
+
if (selfHit && !seen.has(selfHit.dir)) {
|
|
120
|
+
seen.add(selfHit.dir)
|
|
121
|
+
candidates.push(selfHit)
|
|
122
|
+
found += 1
|
|
123
|
+
}
|
|
124
|
+
let level1 = []
|
|
125
|
+
try {
|
|
126
|
+
level1 = await fs.readdir(root, { withFileTypes: true })
|
|
127
|
+
} catch {
|
|
128
|
+
level1 = []
|
|
129
|
+
}
|
|
130
|
+
for (const entry of level1) {
|
|
131
|
+
if (candidates.length >= limit || examined >= budget) break
|
|
132
|
+
if (!entry.isDirectory() || entry.name.startsWith('.') || DISCOVER_SKIP.has(entry.name)) continue
|
|
133
|
+
examined += 1
|
|
134
|
+
const dir = path.join(root, entry.name)
|
|
135
|
+
const hit = await looksLikePlugin(dir)
|
|
136
|
+
if (hit && !seen.has(hit.dir)) {
|
|
137
|
+
seen.add(hit.dir)
|
|
138
|
+
candidates.push(hit)
|
|
139
|
+
found += 1
|
|
140
|
+
continue
|
|
141
|
+
}
|
|
142
|
+
let level2 = []
|
|
143
|
+
try {
|
|
144
|
+
level2 = await fs.readdir(dir, { withFileTypes: true })
|
|
145
|
+
} catch {
|
|
146
|
+
level2 = []
|
|
147
|
+
}
|
|
148
|
+
for (const child of level2) {
|
|
149
|
+
if (candidates.length >= limit || examined >= budget) break
|
|
150
|
+
if (!child.isDirectory() || child.name.startsWith('.') || DISCOVER_SKIP.has(child.name)) continue
|
|
151
|
+
examined += 1
|
|
152
|
+
const hit2 = await looksLikePlugin(path.join(dir, child.name))
|
|
153
|
+
if (hit2 && !seen.has(hit2.dir)) {
|
|
154
|
+
seen.add(hit2.dir)
|
|
155
|
+
candidates.push(hit2)
|
|
156
|
+
found += 1
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
scanned.push({ root, exists: true, found })
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
candidates.sort((a, b) => String(b.mtime || '').localeCompare(String(a.mtime || '')))
|
|
164
|
+
return { roots: scanned, count: candidates.length, items: candidates, limited: candidates.length >= limit }
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function normalizeConfig(raw) {
|
|
168
|
+
const config = raw && typeof raw === 'object' ? raw : {}
|
|
169
|
+
return {
|
|
170
|
+
baseUrl:
|
|
171
|
+
typeof config.baseUrl === 'string' && config.baseUrl
|
|
172
|
+
? config.baseUrl.replace(/\/+$/, '')
|
|
173
|
+
: DEFAULT_API,
|
|
174
|
+
appName: typeof config.appName === 'string' ? config.appName.trim() : '',
|
|
175
|
+
publishBranch:
|
|
176
|
+
typeof config.publishBranch === 'string' && config.publishBranch ? config.publishBranch : 'main',
|
|
177
|
+
topic: typeof config.topic === 'string' && config.topic ? config.topic : 'dsh-plugin',
|
|
178
|
+
marketIndexUrls: Array.isArray(config.marketIndexUrls)
|
|
179
|
+
? config.marketIndexUrls.filter((item) => typeof item === 'string' && /^https?:\/\//.test(item))
|
|
180
|
+
: [],
|
|
181
|
+
maxPushBytes:
|
|
182
|
+
Number.isFinite(config.maxPushBytes) && config.maxPushBytes > 0 ? config.maxPushBytes : 8 * 1024 * 1024,
|
|
183
|
+
// Network: a polluted hosts file (GitHub accelerators) or an intermittent
|
|
184
|
+
// local proxy must not decide whether the plugin works.
|
|
185
|
+
proxy: typeof config.proxy === 'string' ? config.proxy.trim() : '',
|
|
186
|
+
proxyPorts: Array.isArray(config.proxyPorts)
|
|
187
|
+
? config.proxyPorts.filter((port) => Number.isInteger(port) && port > 0 && port < 65536)
|
|
188
|
+
: [7897, 7890, 1080, 10808, 10809, 2080, 8888],
|
|
189
|
+
dnsServers: Array.isArray(config.dnsServers)
|
|
190
|
+
? config.dnsServers.filter((server) => typeof server === 'string' && server)
|
|
191
|
+
: ['223.5.5.5', '119.29.29.29', '114.114.114.114'],
|
|
192
|
+
bypassHosts: config.bypassHosts !== false,
|
|
193
|
+
caFile: typeof config.caFile === 'string' ? config.caFile.trim() : '',
|
|
194
|
+
requestTimeoutMs:
|
|
195
|
+
Number.isFinite(config.requestTimeoutMs) && config.requestTimeoutMs > 0 ? config.requestTimeoutMs : 20000,
|
|
196
|
+
// Publishing extras: the npm workflow lives in the repository, and the
|
|
197
|
+
// optional self-hosted market index is one JSON file next to the code.
|
|
198
|
+
npmWorkflow: typeof config.npmWorkflow === 'string' && config.npmWorkflow ? config.npmWorkflow : 'publish.yml',
|
|
199
|
+
npmPollSeconds:
|
|
200
|
+
Number.isFinite(config.npmPollSeconds) && config.npmPollSeconds > 0 ? config.npmPollSeconds : 90,
|
|
201
|
+
marketIndexPath:
|
|
202
|
+
typeof config.marketIndexPath === 'string' && config.marketIndexPath
|
|
203
|
+
? config.marketIndexPath
|
|
204
|
+
: 'market/index.json',
|
|
205
|
+
npmUser: typeof config.npmUser === 'string' ? config.npmUser.trim() : '',
|
|
206
|
+
// Connection selection: 'auto' prefers App, then PAT, then the environment.
|
|
207
|
+
authMode: ['auto', 'app', 'pat', 'env'].includes(config.authMode) ? config.authMode : 'auto',
|
|
208
|
+
patEnvName: typeof config.patEnvName === 'string' && config.patEnvName ? config.patEnvName : 'GITHUB_TOKEN',
|
|
209
|
+
readOnly: config.readOnly === true,
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Append-only record of write actions taken through this plugin. */
|
|
214
|
+
function auditPath() {
|
|
215
|
+
const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
|
|
216
|
+
return path.join(home, 'storages', 'dsh-github-console', 'audit.ndjson')
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
async function appendAudit(entry) {
|
|
220
|
+
try {
|
|
221
|
+
const target = auditPath()
|
|
222
|
+
await fs.mkdir(path.dirname(target), { recursive: true })
|
|
223
|
+
await fs.appendFile(target, `${JSON.stringify({ at: new Date().toISOString(), ...entry })}\n`, 'utf8')
|
|
224
|
+
} catch {
|
|
225
|
+
/* auditing never breaks an action */
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async function readAudit(limit = 50) {
|
|
230
|
+
try {
|
|
231
|
+
const text = await fs.readFile(auditPath(), 'utf8')
|
|
232
|
+
const lines = text.trim().split('\n').filter(Boolean)
|
|
233
|
+
return lines.slice(-Math.max(1, Math.min(500, limit))).map((line) => {
|
|
234
|
+
try {
|
|
235
|
+
return JSON.parse(line)
|
|
236
|
+
} catch {
|
|
237
|
+
return { raw: line }
|
|
238
|
+
}
|
|
239
|
+
})
|
|
240
|
+
} catch {
|
|
241
|
+
return []
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/* ------------------------------------------------------------------ */
|
|
246
|
+
/* Transport: direct, hosts-bypassing DNS, or a local proxy */
|
|
247
|
+
/* ------------------------------------------------------------------ */
|
|
248
|
+
|
|
249
|
+
function readUntil(socket, separator, timeoutMs) {
|
|
250
|
+
return new Promise((resolve, reject) => {
|
|
251
|
+
let buffer = ''
|
|
252
|
+
const timer = setTimeout(() => {
|
|
253
|
+
cleanup()
|
|
254
|
+
reject(new Error('READ_TIMEOUT'))
|
|
255
|
+
}, timeoutMs)
|
|
256
|
+
const onData = (chunk) => {
|
|
257
|
+
buffer += chunk.toString('latin1')
|
|
258
|
+
if (buffer.includes(separator)) {
|
|
259
|
+
cleanup()
|
|
260
|
+
resolve(buffer)
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
const onError = (error) => {
|
|
264
|
+
cleanup()
|
|
265
|
+
reject(error)
|
|
266
|
+
}
|
|
267
|
+
const cleanup = () => {
|
|
268
|
+
clearTimeout(timer)
|
|
269
|
+
socket.off('data', onData)
|
|
270
|
+
socket.off('error', onError)
|
|
271
|
+
}
|
|
272
|
+
socket.on('data', onData)
|
|
273
|
+
socket.on('error', onError)
|
|
274
|
+
})
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Builds a lookup() that asks public resolvers over UDP, which ignores the
|
|
279
|
+
* system hosts file. GitHub accelerators rewrite hosts to 127.0.0.1 and answer
|
|
280
|
+
* with their own CA, which Node does not trust; skipping hosts sidesteps both.
|
|
281
|
+
*/
|
|
282
|
+
function makeBypassLookup(servers) {
|
|
283
|
+
const resolver = new Resolver({ timeout: 4000, tries: 3 })
|
|
284
|
+
try {
|
|
285
|
+
resolver.setServers(servers)
|
|
286
|
+
} catch {
|
|
287
|
+
/* keep default servers */
|
|
288
|
+
}
|
|
289
|
+
// One publish writes ~10 blobs; resolving the host for every request both
|
|
290
|
+
// wastes time and multiplies the chance of a transient DNS timeout.
|
|
291
|
+
const cache = new Map()
|
|
292
|
+
const ttlMs = 5 * 60 * 1000
|
|
293
|
+
return (hostname, options, callback) => {
|
|
294
|
+
const wantAll = Boolean(options && options.all)
|
|
295
|
+
const settle = (list) => {
|
|
296
|
+
cache.set(hostname, { list, at: Date.now() })
|
|
297
|
+
if (wantAll) callback(null, list.map((address) => ({ address, family: net.isIP(address) })))
|
|
298
|
+
else callback(null, list[0], net.isIP(list[0]))
|
|
299
|
+
}
|
|
300
|
+
const cached = cache.get(hostname)
|
|
301
|
+
if (cached && cached.list.length && Date.now() - cached.at < ttlMs) {
|
|
302
|
+
if (wantAll) callback(null, cached.list.map((address) => ({ address, family: net.isIP(address) })))
|
|
303
|
+
else callback(null, cached.list[0], net.isIP(cached.list[0]))
|
|
304
|
+
return
|
|
305
|
+
}
|
|
306
|
+
resolver.resolve4(hostname, (error4, list4) => {
|
|
307
|
+
if (!error4 && list4 && list4.length) return settle(list4)
|
|
308
|
+
resolver.resolve6(hostname, (error6, list6) => {
|
|
309
|
+
if (!error6 && list6 && list6.length) return settle(list6)
|
|
310
|
+
callback(error4 || error6 || new Error('DNS_LOOKUP_FAILED'))
|
|
311
|
+
})
|
|
312
|
+
})
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function createTransport(cfg) {
|
|
317
|
+
const state = {
|
|
318
|
+
preferred: '',
|
|
319
|
+
lastRoute: '',
|
|
320
|
+
lastError: '',
|
|
321
|
+
proxy: '',
|
|
322
|
+
attempts: [],
|
|
323
|
+
checkedAt: 0,
|
|
324
|
+
}
|
|
325
|
+
let caPem
|
|
326
|
+
let caLoaded = false
|
|
327
|
+
const bypassLookup = makeBypassLookup(cfg.dnsServers)
|
|
328
|
+
|
|
329
|
+
async function loadCa() {
|
|
330
|
+
if (caLoaded) return caPem
|
|
331
|
+
caLoaded = true
|
|
332
|
+
if (!cfg.caFile) return undefined
|
|
333
|
+
caPem = await fs.readFile(cfg.caFile, 'utf8').catch(() => undefined)
|
|
334
|
+
return caPem
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function probePort(port, timeoutMs = 400) {
|
|
338
|
+
return new Promise((resolve) => {
|
|
339
|
+
const socket = net.connect({ host: '127.0.0.1', port })
|
|
340
|
+
const done = (value) => {
|
|
341
|
+
socket.destroy()
|
|
342
|
+
resolve(value)
|
|
343
|
+
}
|
|
344
|
+
socket.setTimeout(timeoutMs, () => done(false))
|
|
345
|
+
socket.once('connect', () => done(true))
|
|
346
|
+
socket.once('error', () => done(false))
|
|
347
|
+
})
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// A local proxy may be up, down, or started later; re-probe at most every 30s.
|
|
351
|
+
async function detectProxy(force) {
|
|
352
|
+
if (cfg.proxy) {
|
|
353
|
+
state.proxy = cfg.proxy
|
|
354
|
+
return cfg.proxy
|
|
355
|
+
}
|
|
356
|
+
if (!force && Date.now() - state.checkedAt < 30000) return state.proxy
|
|
357
|
+
state.checkedAt = Date.now()
|
|
358
|
+
const envProxy =
|
|
359
|
+
process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy || ''
|
|
360
|
+
if (envProxy) {
|
|
361
|
+
state.proxy = envProxy
|
|
362
|
+
return envProxy
|
|
363
|
+
}
|
|
364
|
+
for (const port of cfg.proxyPorts) {
|
|
365
|
+
if (await probePort(port)) {
|
|
366
|
+
state.proxy = `http://127.0.0.1:${port}`
|
|
367
|
+
return state.proxy
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
state.proxy = ''
|
|
371
|
+
return ''
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
function routesFor(proxy) {
|
|
375
|
+
const routes = []
|
|
376
|
+
if (proxy) routes.push({ id: `proxy:${proxy}`, kind: 'proxy', proxy })
|
|
377
|
+
if (cfg.bypassHosts) routes.push({ id: 'direct:public-dns', kind: 'direct', lookup: bypassLookup })
|
|
378
|
+
routes.push({ id: 'direct:system-dns', kind: 'direct' })
|
|
379
|
+
if (state.preferred) {
|
|
380
|
+
const index = routes.findIndex((route) => route.id === state.preferred)
|
|
381
|
+
if (index > 0) routes.unshift(routes.splice(index, 1)[0])
|
|
382
|
+
}
|
|
383
|
+
return routes
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
function rawRequest(options, body, timeoutMs, binary = false) {
|
|
387
|
+
return new Promise((resolve, reject) => {
|
|
388
|
+
const request = https.request(options, (response) => {
|
|
389
|
+
const chunks = []
|
|
390
|
+
response.on('data', (chunk) => chunks.push(chunk))
|
|
391
|
+
response.on('end', () => {
|
|
392
|
+
const joined = Buffer.concat(chunks)
|
|
393
|
+
resolve({
|
|
394
|
+
status: response.statusCode || 0,
|
|
395
|
+
headers: response.headers,
|
|
396
|
+
text: binary ? '' : joined.toString('utf8'),
|
|
397
|
+
buffer: binary ? joined : null,
|
|
398
|
+
})
|
|
399
|
+
})
|
|
400
|
+
response.on('error', reject)
|
|
401
|
+
})
|
|
402
|
+
request.setTimeout(timeoutMs, () => request.destroy(new Error('ETIMEDOUT')))
|
|
403
|
+
request.on('error', reject)
|
|
404
|
+
if (body) request.write(body)
|
|
405
|
+
request.end()
|
|
406
|
+
})
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
async function openTunnel(proxyUrl, host, port) {
|
|
410
|
+
const url = new URL(proxyUrl)
|
|
411
|
+
const secure = url.protocol === 'https:'
|
|
412
|
+
const proxyPort = Number(url.port || (secure ? 443 : 80))
|
|
413
|
+
const socket = await new Promise((resolve, reject) => {
|
|
414
|
+
const created = secure
|
|
415
|
+
? tls.connect({ host: url.hostname, port: proxyPort, servername: url.hostname }, () => resolve(created))
|
|
416
|
+
: net.connect({ host: url.hostname, port: proxyPort }, () => resolve(created))
|
|
417
|
+
created.setTimeout(8000, () => created.destroy(new Error('PROXY_TIMEOUT')))
|
|
418
|
+
created.once('error', reject)
|
|
419
|
+
})
|
|
420
|
+
const auth =
|
|
421
|
+
url.username || url.password
|
|
422
|
+
? `Proxy-Authorization: Basic ${Buffer.from(`${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`).toString('base64')}\r\n`
|
|
423
|
+
: ''
|
|
424
|
+
socket.write(`CONNECT ${host}:${port} HTTP/1.1\r\nHost: ${host}:${port}\r\n${auth}\r\n`)
|
|
425
|
+
const head = await readUntil(socket, '\r\n\r\n', 8000)
|
|
426
|
+
if (!/^HTTP\/1\.[01] 200/.test(head)) {
|
|
427
|
+
socket.destroy()
|
|
428
|
+
throw new Error(`PROXY_CONNECT_FAILED ${head.split('\r\n')[0]}`)
|
|
429
|
+
}
|
|
430
|
+
const ca = await loadCa()
|
|
431
|
+
return new Promise((resolve, reject) => {
|
|
432
|
+
const secured = tls.connect({ socket, servername: host, ca }, () => resolve(secured))
|
|
433
|
+
secured.once('error', reject)
|
|
434
|
+
})
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
async function requestViaRoute(route, url, options) {
|
|
438
|
+
const target = new URL(url)
|
|
439
|
+
const host = target.hostname
|
|
440
|
+
const port = Number(target.port || 443)
|
|
441
|
+
const path = `${target.pathname}${target.search}`
|
|
442
|
+
const headers = {
|
|
443
|
+
Host: host,
|
|
444
|
+
Connection: 'close',
|
|
445
|
+
// GitHub rejects requests without a User-Agent (HTTP 403 "Request
|
|
446
|
+
// forbidden by administrative rules"), and fetch used to add one for us.
|
|
447
|
+
'User-Agent': `dsh-github-console/${PLUGIN_VERSION}`,
|
|
448
|
+
...options.headers,
|
|
449
|
+
}
|
|
450
|
+
if (options.body) headers['Content-Length'] = Buffer.byteLength(options.body)
|
|
451
|
+
|
|
452
|
+
if (route.kind === 'proxy') {
|
|
453
|
+
const tunnel = await openTunnel(route.proxy, host, port)
|
|
454
|
+
// https.Agent.createConnection is expected to hand back a secured socket.
|
|
455
|
+
const agent = new https.Agent({
|
|
456
|
+
keepAlive: false,
|
|
457
|
+
maxSockets: 1,
|
|
458
|
+
createConnection: () => tunnel,
|
|
459
|
+
})
|
|
460
|
+
try {
|
|
461
|
+
return await rawRequest(
|
|
462
|
+
{ method: options.method, host, port, path, headers, agent, servername: host },
|
|
463
|
+
options.body,
|
|
464
|
+
cfg.requestTimeoutMs,
|
|
465
|
+
options.binary === true,
|
|
466
|
+
)
|
|
467
|
+
} finally {
|
|
468
|
+
tunnel.destroy()
|
|
469
|
+
agent.destroy()
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
const ca = await loadCa()
|
|
474
|
+
return rawRequest(
|
|
475
|
+
{
|
|
476
|
+
method: options.method,
|
|
477
|
+
host,
|
|
478
|
+
port,
|
|
479
|
+
path,
|
|
480
|
+
headers,
|
|
481
|
+
servername: host,
|
|
482
|
+
ca,
|
|
483
|
+
lookup: route.lookup,
|
|
484
|
+
},
|
|
485
|
+
options.body,
|
|
486
|
+
cfg.requestTimeoutMs,
|
|
487
|
+
options.binary === true,
|
|
488
|
+
)
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
async function request(url, options = {}) {
|
|
492
|
+
const failures = []
|
|
493
|
+
// One transient timeout must not fail a publish: retry the whole route set
|
|
494
|
+
// a couple of times, re-probing the proxy so one that just came up is seen.
|
|
495
|
+
const backoff = [0, 800, 2500]
|
|
496
|
+
for (let round = 0; round < backoff.length; round++) {
|
|
497
|
+
if (backoff[round]) await new Promise((resolve) => setTimeout(resolve, backoff[round]))
|
|
498
|
+
const proxy = await detectProxy(round > 0)
|
|
499
|
+
const routes = routesFor(proxy)
|
|
500
|
+
for (const route of routes) {
|
|
501
|
+
try {
|
|
502
|
+
const response = await requestViaRoute(route, url, options)
|
|
503
|
+
state.preferred = route.id
|
|
504
|
+
state.lastRoute = route.id
|
|
505
|
+
state.lastError = ''
|
|
506
|
+
state.attempts = [{ route: route.id, ok: true, round }]
|
|
507
|
+
return response
|
|
508
|
+
} catch (failure) {
|
|
509
|
+
const described = describeFetchFailure(failure)
|
|
510
|
+
const detail = described.codes.join('/') || errorMessage(failure)
|
|
511
|
+
if (!failures.some((item) => item.route === route.id)) failures.push({ route: route.id, error: detail })
|
|
512
|
+
state.lastError = `${route.id}: ${detail}`
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
// Forget the remembered route so the retry re-evaluates the order.
|
|
516
|
+
state.preferred = ''
|
|
517
|
+
}
|
|
518
|
+
state.attempts = failures.map((item) => ({ route: item.route, ok: false, error: item.error }))
|
|
519
|
+
const hint = await proxyHint(failures)
|
|
520
|
+
throw new GhError(
|
|
521
|
+
0,
|
|
522
|
+
'NETWORK',
|
|
523
|
+
`所有线路都失败(${failures.map((item) => `${item.route}=${item.error}`).join(';')})${hint}`,
|
|
524
|
+
{ failures },
|
|
525
|
+
)
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
async function proxyHint(failures) {
|
|
529
|
+
if (failures.some((item) => String(item.error).includes('UNABLE_TO_VERIFY_LEAF_SIGNATURE'))) {
|
|
530
|
+
return ':证书不被 Node 信任(常见于 GitHub 加速工具的本地中间人)。可在配置里写 caFile 指向其根证书,或让 hosts 不要劫持 api.github.com。'
|
|
531
|
+
}
|
|
532
|
+
if (failures.every((item) => String(item.error).includes('ENOTFOUND') || String(item.error).includes('EAI_AGAIN'))) {
|
|
533
|
+
return ':域名解析失败,检查 DNS 或代理。'
|
|
534
|
+
}
|
|
535
|
+
if (failures.every((item) => String(item.error).includes('ECONNREFUSED'))) {
|
|
536
|
+
return ':连接被拒,可能是 hosts 指向 127.0.0.1 而代理没开。'
|
|
537
|
+
}
|
|
538
|
+
return ''
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
return {
|
|
542
|
+
request,
|
|
543
|
+
state,
|
|
544
|
+
detectProxy,
|
|
545
|
+
refresh: () => {
|
|
546
|
+
state.checkedAt = 0
|
|
547
|
+
state.preferred = ''
|
|
548
|
+
},
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
class GhError extends Error {
|
|
553
|
+
constructor(status, code, message, detail) {
|
|
554
|
+
super(message)
|
|
555
|
+
this.name = 'GhError'
|
|
556
|
+
this.status = status
|
|
557
|
+
this.code = code
|
|
558
|
+
this.detail = detail
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
function jsonSafe(value) {
|
|
563
|
+
if (value === null) return null
|
|
564
|
+
if (typeof value === 'string' || typeof value === 'boolean') return value
|
|
565
|
+
if (typeof value === 'number') return Number.isFinite(value) ? value : null
|
|
566
|
+
if (typeof value === 'bigint') return value.toString()
|
|
567
|
+
if (Array.isArray(value)) return value.map((item) => jsonSafe(item) ?? null)
|
|
568
|
+
if (typeof value === 'object') {
|
|
569
|
+
const result = {}
|
|
570
|
+
for (const [key, item] of Object.entries(value)) {
|
|
571
|
+
if (item === undefined) continue
|
|
572
|
+
const safe = jsonSafe(item)
|
|
573
|
+
if (safe !== undefined) result[key] = safe
|
|
574
|
+
}
|
|
575
|
+
return result
|
|
576
|
+
}
|
|
577
|
+
return undefined
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
function errorMessage(error) {
|
|
581
|
+
if (error instanceof GhError) return error.message
|
|
582
|
+
return error instanceof Error ? error.message : String(error)
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/**
|
|
586
|
+
* A bare "fetch failed" hides everything worth knowing, so surface the cause
|
|
587
|
+
* code and, for the common local-proxy/hosts cases, what to do about it.
|
|
588
|
+
*/
|
|
589
|
+
function describeFetchFailure(error) {
|
|
590
|
+
const codes = []
|
|
591
|
+
let cause = error && error.cause
|
|
592
|
+
let depth = 0
|
|
593
|
+
while (cause && depth < 5) {
|
|
594
|
+
if (cause.code) codes.push(String(cause.code))
|
|
595
|
+
else if (cause.message) codes.push(String(cause.message))
|
|
596
|
+
cause = cause.cause
|
|
597
|
+
depth += 1
|
|
598
|
+
}
|
|
599
|
+
const text = codes.join(' / ')
|
|
600
|
+
const hint =
|
|
601
|
+
text.includes('UNABLE_TO_VERIFY_LEAF_SIGNATURE') ||
|
|
602
|
+
text.includes('SELF_SIGNED_CERT_IN_CHAIN') ||
|
|
603
|
+
text.includes('DEPTH_ZERO_SELF_SIGNED_CERT')
|
|
604
|
+
? 'GitHub 域名的证书不被 Node 信任:通常是 GitHub 加速工具写入 hosts 后,由本地中间人证书应答。关掉加速工具并清理 hosts 中的 GitHub 条目,或改用系统代理。'
|
|
605
|
+
: text.includes('ENOTFOUND') || text.includes('EAI_AGAIN')
|
|
606
|
+
? '域名解析失败:检查 DNS / hosts / 代理是否在运行。'
|
|
607
|
+
: text.includes('ECONNREFUSED')
|
|
608
|
+
? '连接被拒绝:本机 hosts 可能把域名指向了 127.0.0.1,而该端口的代理没有运行。'
|
|
609
|
+
: text.includes('ETIMEDOUT') || text.includes('UND_ERR_CONNECT_TIMEOUT')
|
|
610
|
+
? '连接超时:网络或代理不通。'
|
|
611
|
+
: ''
|
|
612
|
+
return { message: `网络请求失败(${text || 'unknown'})`, codes, hint }
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
/**
|
|
616
|
+
* DNS is resolved by the same process that makes the request, so a hosts entry
|
|
617
|
+
* that points GitHub at localhost is visible here without any network call.
|
|
618
|
+
*/
|
|
619
|
+
async function describeDns(host) {
|
|
620
|
+
try {
|
|
621
|
+
const addresses = await dnsPromises.lookup(host, { all: true })
|
|
622
|
+
const list = addresses.map((item) => `${item.address}/${item.family}`)
|
|
623
|
+
const local = addresses.some(
|
|
624
|
+
(item) =>
|
|
625
|
+
item.address === '127.0.0.1' ||
|
|
626
|
+
item.address === '::1' ||
|
|
627
|
+
item.address.startsWith('127.') ||
|
|
628
|
+
item.address === '0.0.0.0',
|
|
629
|
+
)
|
|
630
|
+
return {
|
|
631
|
+
host,
|
|
632
|
+
addresses: list,
|
|
633
|
+
localRedirect: local,
|
|
634
|
+
hint: local
|
|
635
|
+
? `${host} 被解析到本机地址(${list.join(', ')}):通常是 GitHub 加速工具写入的 hosts 重定向,或本地代理未运行。浏览器可能仍能打开 GitHub,但本插件的网络请求会失败。`
|
|
636
|
+
: '',
|
|
637
|
+
}
|
|
638
|
+
} catch (error) {
|
|
639
|
+
return { host, addresses: [], localRedirect: false, hint: `解析 ${host} 失败:${errorMessage(error)}` }
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
function escapeHtml(text) {
|
|
644
|
+
return String(text).replace(/[&<>"']/g, (ch) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[ch])
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
function sendHtml(response, status, title, detail, extraHtml = '') {
|
|
648
|
+
response.writeHead(status, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' })
|
|
649
|
+
response.end(
|
|
650
|
+
`<!doctype html><meta charset="utf-8"><title>${escapeHtml(title)}</title>` +
|
|
651
|
+
`<body style="font-family:system-ui,-apple-system,'Segoe UI',sans-serif;background:#f6f7f9;margin:0;padding:48px 16px;color:#1f2328">` +
|
|
652
|
+
`<div style="max-width:600px;margin:0 auto;background:#fff;border:1px solid #e3e6ea;border-radius:12px;padding:26px 30px">` +
|
|
653
|
+
`<h2 style="margin:0 0 10px;font-size:19px;font-weight:600">${escapeHtml(title)}</h2>` +
|
|
654
|
+
`<p style="color:#57606a;line-height:1.75;font-size:13px;margin:0 0 6px">${escapeHtml(detail)}</p>${extraHtml}</div></body>`,
|
|
655
|
+
)
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
function sendJson(response, status, value) {
|
|
659
|
+
const body = JSON.stringify(value)
|
|
660
|
+
response.writeHead(status, {
|
|
661
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
662
|
+
'Cache-Control': 'no-store',
|
|
663
|
+
})
|
|
664
|
+
response.end(body)
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
function readBody(request, limit = 512 * 1024) {
|
|
668
|
+
return new Promise((resolve, reject) => {
|
|
669
|
+
let data = ''
|
|
670
|
+
request.setEncoding('utf8')
|
|
671
|
+
request.on('data', (chunk) => {
|
|
672
|
+
data += chunk
|
|
673
|
+
if (data.length > limit) {
|
|
674
|
+
reject(new Error('请求体过大'))
|
|
675
|
+
request.destroy()
|
|
676
|
+
}
|
|
677
|
+
})
|
|
678
|
+
request.on('end', () => resolve(data))
|
|
679
|
+
request.on('error', reject)
|
|
680
|
+
})
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
function requestOrigin(request) {
|
|
684
|
+
const host = request.headers.host
|
|
685
|
+
if (host && /^[A-Za-z0-9.:\-[\]]+$/.test(host)) {
|
|
686
|
+
const proto = String(request.headers['x-forwarded-proto'] || 'http').split(',')[0].trim()
|
|
687
|
+
return `${proto === 'https' ? 'https' : 'http'}://${host}`
|
|
688
|
+
}
|
|
689
|
+
return 'http://127.0.0.1'
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
function bearerToken(request) {
|
|
693
|
+
const header = String(request.headers.authorization || '')
|
|
694
|
+
const match = /^Bearer\s+(.+)$/i.exec(header)
|
|
695
|
+
return match ? match[1].trim() : ''
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
function base64url(input) {
|
|
699
|
+
return Buffer.from(input).toString('base64url')
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
function semverCore(text) {
|
|
703
|
+
const match = /^(\d+)\.(\d+)\.(\d+)/.exec(String(text || '').trim())
|
|
704
|
+
return match ? `${match[1]}.${match[2]}.${match[3]}` : ''
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
function fmtBytes(bytes) {
|
|
708
|
+
const n = Number(bytes) || 0
|
|
709
|
+
if (n >= 1024 ** 2) return `${(n / 1024 ** 2).toFixed(1)} MB`
|
|
710
|
+
if (n >= 1024) return `${(n / 1024).toFixed(1)} KB`
|
|
711
|
+
return `${n} B`
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
function textOf(value) {
|
|
715
|
+
return [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }]
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/* ------------------------------------------------------------------ */
|
|
719
|
+
/* GitHub App authentication */
|
|
720
|
+
/* ------------------------------------------------------------------ */
|
|
721
|
+
|
|
722
|
+
function createGithub(ctx, cfg, transport) {
|
|
723
|
+
let installationTokenCache = null // { token, expiresAt }
|
|
724
|
+
const pendingManifests = new Map() // state -> startedAt
|
|
725
|
+
|
|
726
|
+
function store() {
|
|
727
|
+
return ctx.get('credentials')
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
async function readRecord(key) {
|
|
731
|
+
const credentials = store()
|
|
732
|
+
if (!credentials) return undefined
|
|
733
|
+
const record = await credentials.readRecord(key).catch(() => undefined)
|
|
734
|
+
return record && record.payload && typeof record.payload === 'object' ? record.payload : undefined
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
async function writeRecord(key, payload) {
|
|
738
|
+
const credentials = store()
|
|
739
|
+
if (!credentials) throw new Error('凭据服务不可用,无法保存 GitHub 凭据')
|
|
740
|
+
await credentials.modifyRecord(key, async () => ({ kind: 'grant', payload: jsonSafe(payload) }))
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
async function deleteRecord(key) {
|
|
744
|
+
const credentials = store()
|
|
745
|
+
if (credentials) await credentials.deleteRecord(key).catch(() => {})
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
async function readApp() {
|
|
749
|
+
const app = await readRecord(APP_CRED)
|
|
750
|
+
if (!app || !app.appId || !app.pem) return undefined
|
|
751
|
+
return app
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
async function waitForCredentials() {
|
|
755
|
+
let credentials = store()
|
|
756
|
+
// The credentials service can activate after this plugin; without a short
|
|
757
|
+
// bounded wait, the bridge token would be regenerated on every reload.
|
|
758
|
+
for (let attempt = 0; attempt < 30 && !credentials; attempt++) {
|
|
759
|
+
await new Promise((resolve) => setTimeout(resolve, 100))
|
|
760
|
+
credentials = store()
|
|
761
|
+
}
|
|
762
|
+
return credentials
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
function appJwt(app) {
|
|
766
|
+
const now = Math.floor(Date.now() / 1000)
|
|
767
|
+
const header = base64url(JSON.stringify({ alg: 'RS256', typ: 'JWT' }))
|
|
768
|
+
const payload = base64url(JSON.stringify({ iat: now - 60, exp: now + 540, iss: String(app.appId) }))
|
|
769
|
+
const signingInput = `${header}.${payload}`
|
|
770
|
+
const signature = crypto.createSign('RSA-SHA256').update(signingInput).sign(app.pem).toString('base64url')
|
|
771
|
+
return `${signingInput}.${signature}`
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
async function call(pathname, options = {}) {
|
|
775
|
+
const { method = 'GET', body, auth = 'auto', headers = {}, rawBody = false } = options
|
|
776
|
+
const init = { method, headers: { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28', ...headers } }
|
|
777
|
+
if (auth === 'app') {
|
|
778
|
+
const app = await readApp()
|
|
779
|
+
if (!app) throw new GhError(401, 'AUTH_MISSING', '尚未注册 GitHub App:在侧栏「GitHub 控制台」点「注册 GitHub App」')
|
|
780
|
+
init.headers.Authorization = `Bearer ${appJwt(app)}`
|
|
781
|
+
} else if (auth === 'installation') {
|
|
782
|
+
init.headers.Authorization = `Bearer ${await installationToken()}`
|
|
783
|
+
} else if (auth !== 'auto') {
|
|
784
|
+
init.headers.Authorization = `Bearer ${auth}`
|
|
785
|
+
} else {
|
|
786
|
+
const current = await resolveAuth()
|
|
787
|
+
if (current.kind === 'app') {
|
|
788
|
+
init.headers.Authorization = `Bearer ${await installationToken()}`
|
|
789
|
+
} else if (current.kind === 'pat' || current.kind === 'env' || current.kind === 'oauth') {
|
|
790
|
+
init.headers.Authorization = `Bearer ${current.token}`
|
|
791
|
+
} else {
|
|
792
|
+
throw new GhError(
|
|
793
|
+
401,
|
|
794
|
+
'AUTH_MISSING',
|
|
795
|
+
'还没有可用的 GitHub 连接:在面板「状态」里选一种(GitHub App / 个人访问令牌 / 环境变量)',
|
|
796
|
+
)
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
if (body !== undefined) {
|
|
800
|
+
if (rawBody) {
|
|
801
|
+
// Binary uploads (release assets) pass the bytes through unchanged.
|
|
802
|
+
init.body = body
|
|
803
|
+
} else {
|
|
804
|
+
init.headers['Content-Type'] = 'application/json'
|
|
805
|
+
init.body = JSON.stringify(body)
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
// Absolute URLs reach another host (uploads.github.com for release assets).
|
|
809
|
+
const target = /^https?:\/\//i.test(pathname) ? pathname : `${cfg.baseUrl}${pathname}`
|
|
810
|
+
let response
|
|
811
|
+
try {
|
|
812
|
+
response = await transport.request(target, { method, headers: init.headers, body: init.body })
|
|
813
|
+
} catch (failure) {
|
|
814
|
+
if (failure instanceof GhError) throw failure
|
|
815
|
+
const described = describeFetchFailure(failure)
|
|
816
|
+
throw new GhError(0, 'NETWORK', described.hint ? `${described.message}:${described.hint}` : described.message, {
|
|
817
|
+
codes: described.codes,
|
|
818
|
+
})
|
|
819
|
+
}
|
|
820
|
+
const raw = response.text
|
|
821
|
+
let data = null
|
|
822
|
+
if (raw) {
|
|
823
|
+
try {
|
|
824
|
+
data = JSON.parse(raw)
|
|
825
|
+
} catch {
|
|
826
|
+
data = { raw: raw.slice(0, 400) }
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
if (response.status < 200 || response.status >= 300) {
|
|
830
|
+
// GitHub sometimes answers with an empty or non-JSON body, which used to
|
|
831
|
+
// surface as a bare "HTTP 403"; keep a short body peek in the message.
|
|
832
|
+
const bodyPeek =
|
|
833
|
+
data && data.message
|
|
834
|
+
? ''
|
|
835
|
+
: data && data.raw
|
|
836
|
+
? `:${String(data.raw).slice(0, 200)}`
|
|
837
|
+
: raw
|
|
838
|
+
? `:${String(raw).slice(0, 200)}`
|
|
839
|
+
: '(空响应体)'
|
|
840
|
+
const message = data && data.message ? String(data.message) : `HTTP ${response.status}${bodyPeek}`
|
|
841
|
+
const remaining = response.headers['x-ratelimit-remaining']
|
|
842
|
+
const reset = response.headers['x-ratelimit-reset']
|
|
843
|
+
let code = `HTTP_${response.status}`
|
|
844
|
+
const limited =
|
|
845
|
+
response.status === 403 &&
|
|
846
|
+
(remaining === '0' || /rate limit/i.test(String(message || '')))
|
|
847
|
+
if (response.status === 401) code = 'AUTH_EXPIRED'
|
|
848
|
+
if (limited) code = 'RATE_LIMITED'
|
|
849
|
+
if (response.status === 403 && !limited) code = 'SCOPE_DENIED'
|
|
850
|
+
if (response.status === 404) code = 'NOT_FOUND'
|
|
851
|
+
if (response.status === 409) code = 'REF_CONFLICT'
|
|
852
|
+
if (response.status === 422) code = 'INVALID'
|
|
853
|
+
const suffix =
|
|
854
|
+
code === 'RATE_LIMITED' && reset
|
|
855
|
+
? `(限流重置于 ${new Date(Number(reset) * 1000).toLocaleString()})`
|
|
856
|
+
: ''
|
|
857
|
+
throw new GhError(response.status, code, `${message}${suffix}`, data)
|
|
858
|
+
}
|
|
859
|
+
return data
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
async function installations() {
|
|
863
|
+
const list = await call('/app/installations?per_page=100', { auth: 'app' })
|
|
864
|
+
return (Array.isArray(list) ? list : []).map((item) => ({
|
|
865
|
+
id: item.id,
|
|
866
|
+
account: item.account ? item.account.login : '',
|
|
867
|
+
accountType: item.account ? item.account.type : '',
|
|
868
|
+
avatarUrl: item.account ? item.account.avatar_url : '',
|
|
869
|
+
target: item.target_type || '',
|
|
870
|
+
permissions: item.permissions || {},
|
|
871
|
+
repositorySelection: item.repository_selection || '',
|
|
872
|
+
}))
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
async function selectedInstallation() {
|
|
876
|
+
const saved = await readRecord(INSTALL_CRED)
|
|
877
|
+
if (saved && saved.id) return saved
|
|
878
|
+
const list = await installations()
|
|
879
|
+
if (list.length === 1) {
|
|
880
|
+
const only = list[0]
|
|
881
|
+
await writeRecord(INSTALL_CRED, only)
|
|
882
|
+
return only
|
|
883
|
+
}
|
|
884
|
+
return undefined
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
async function installationToken(force = false) {
|
|
888
|
+
if (!force && installationTokenCache && Date.now() < installationTokenCache.expiresAt - INSTALL_TOKEN_MARGIN_MS) {
|
|
889
|
+
return installationTokenCache.token
|
|
890
|
+
}
|
|
891
|
+
const installation = await selectedInstallation()
|
|
892
|
+
if (!installation) {
|
|
893
|
+
throw new GhError(
|
|
894
|
+
401,
|
|
895
|
+
'AUTH_MISSING',
|
|
896
|
+
'GitHub App 还没有安装到任何账号:在 App 设置页点 Install,或在侧栏里选择 installation',
|
|
897
|
+
)
|
|
898
|
+
}
|
|
899
|
+
const created = await call(`/app/installations/${installation.id}/access_tokens`, {
|
|
900
|
+
method: 'POST',
|
|
901
|
+
auth: 'app',
|
|
902
|
+
})
|
|
903
|
+
const expiresAt = created.expires_at ? Date.parse(created.expires_at) : Date.now() + 3600 * 1000
|
|
904
|
+
installationTokenCache = { token: created.token, expiresAt }
|
|
905
|
+
return created.token
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
/* ---------------- manifest flow ---------------- */
|
|
909
|
+
|
|
910
|
+
function beginManifest() {
|
|
911
|
+
const state = crypto.randomBytes(16).toString('hex')
|
|
912
|
+
pendingManifests.set(state, Date.now())
|
|
913
|
+
for (const [key, startedAt] of pendingManifests) {
|
|
914
|
+
if (Date.now() - startedAt > MANIFEST_TTL_MS) pendingManifests.delete(key)
|
|
915
|
+
}
|
|
916
|
+
return state
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
function claimManifest(state) {
|
|
920
|
+
if (!state) return false
|
|
921
|
+
const startedAt = pendingManifests.get(state)
|
|
922
|
+
if (!startedAt) return false
|
|
923
|
+
return Date.now() - startedAt <= MANIFEST_TTL_MS
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
async function completeManifest(code, state) {
|
|
927
|
+
if (!claimManifest(state)) {
|
|
928
|
+
throw new Error('manifest state 不匹配或已过期(超过 1 小时),请重新注册')
|
|
929
|
+
}
|
|
930
|
+
const response = await transport
|
|
931
|
+
.request(`${cfg.baseUrl}/app-manifests/${encodeURIComponent(code)}/conversions`, {
|
|
932
|
+
method: 'POST',
|
|
933
|
+
headers: { Accept: 'application/vnd.github+json' },
|
|
934
|
+
})
|
|
935
|
+
.catch((failure) => {
|
|
936
|
+
const described = describeFetchFailure(failure)
|
|
937
|
+
throw new Error(errorMessage(failure).startsWith('所有线路')
|
|
938
|
+
? errorMessage(failure)
|
|
939
|
+
: described.hint
|
|
940
|
+
? `${described.message}:${described.hint}`
|
|
941
|
+
: described.message)
|
|
942
|
+
})
|
|
943
|
+
const data = (() => {
|
|
944
|
+
try {
|
|
945
|
+
return JSON.parse(response.text || '{}')
|
|
946
|
+
} catch {
|
|
947
|
+
return {}
|
|
948
|
+
}
|
|
949
|
+
})()
|
|
950
|
+
if (response.status < 200 || response.status >= 300 || !data.id || !data.pem) {
|
|
951
|
+
throw new Error(`换取 App 凭据失败(HTTP ${response.status}):${data.message || '未返回 id/pem'}`)
|
|
952
|
+
}
|
|
953
|
+
// Retire the state only after the exchange succeeded: a retried callback or
|
|
954
|
+
// a flaky network must not force the user to register a second App.
|
|
955
|
+
pendingManifests.delete(state)
|
|
956
|
+
// webhook_secret is not needed by this plugin: no inbound events.
|
|
957
|
+
await writeRecord(APP_CRED, {
|
|
958
|
+
appId: String(data.id),
|
|
959
|
+
pem: data.pem,
|
|
960
|
+
slug: data.slug || '',
|
|
961
|
+
name: data.name || '',
|
|
962
|
+
htmlUrl: data.html_url || '',
|
|
963
|
+
clientId: data.client_id || '',
|
|
964
|
+
clientSecret: data.client_secret || '',
|
|
965
|
+
owner: data.owner ? data.owner.login : '',
|
|
966
|
+
registeredAt: new Date().toISOString(),
|
|
967
|
+
})
|
|
968
|
+
await deleteRecord(INSTALL_CRED)
|
|
969
|
+
installationTokenCache = null
|
|
970
|
+
return { appId: String(data.id), slug: data.slug || '', htmlUrl: data.html_url || '' }
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
async function resetApp() {
|
|
974
|
+
await deleteRecord(APP_CRED)
|
|
975
|
+
await deleteRecord(INSTALL_CRED)
|
|
976
|
+
installationTokenCache = null
|
|
977
|
+
return { ok: true }
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
async function readPat() {
|
|
981
|
+
const record = await readRecord(PAT_CRED)
|
|
982
|
+
return record && typeof record.token === 'string' ? record.token : ''
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
function fingerprint(token) {
|
|
986
|
+
const text = String(token || '')
|
|
987
|
+
return text.length <= 4 ? '****' : `****${text.slice(-4)}`
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
/** Ask GitHub who a token belongs to; used before storing a PAT. */
|
|
991
|
+
async function whoAmI(token) {
|
|
992
|
+
const response = await transport.request(`${cfg.baseUrl}/user`, {
|
|
993
|
+
headers: {
|
|
994
|
+
Accept: 'application/vnd.github+json',
|
|
995
|
+
'X-GitHub-Api-Version': '2022-11-28',
|
|
996
|
+
Authorization: `Bearer ${token}`,
|
|
997
|
+
},
|
|
998
|
+
})
|
|
999
|
+
if (response.status !== 200) {
|
|
1000
|
+
throw new GhError(response.status, response.status === 401 ? 'AUTH_EXPIRED' : 'HTTP_' + response.status, `令牌无效(HTTP ${response.status})`)
|
|
1001
|
+
}
|
|
1002
|
+
const data = JSON.parse(response.text || '{}')
|
|
1003
|
+
const scopes = String(response.headers['x-oauth-scopes'] || '')
|
|
1004
|
+
return { login: data.login || '', id: data.id, name: data.name || '', scopes: scopes ? scopes.split(',').map((item) => item.trim()) : [] }
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
let authCache = null
|
|
1008
|
+
|
|
1009
|
+
/** The App's own OAuth callback must be registered before the authorize step. */
|
|
1010
|
+
async function ensureOAuthCallback(origin) {
|
|
1011
|
+
const app = await readApp()
|
|
1012
|
+
if (!app) throw new Error('还没有注册 GitHub App')
|
|
1013
|
+
if (!app.clientId) throw new Error('这个 App 没有 client_id:请重新注册一次 GitHub App')
|
|
1014
|
+
const callbackUrl = `${origin}${PREFIX}/oauth/callback`
|
|
1015
|
+
let current = null
|
|
1016
|
+
try {
|
|
1017
|
+
current = await call('/app', { auth: 'app' })
|
|
1018
|
+
} catch {
|
|
1019
|
+
current = null
|
|
1020
|
+
}
|
|
1021
|
+
const existing = current && Array.isArray(current.callback_urls) ? current.callback_urls : []
|
|
1022
|
+
let registered = existing.includes(callbackUrl)
|
|
1023
|
+
if (!registered) {
|
|
1024
|
+
// `PATCH /app` is not available for every app type; when it fails the user
|
|
1025
|
+
// registers the callback once in the App settings instead.
|
|
1026
|
+
try {
|
|
1027
|
+
await call('/app', { method: 'PATCH', auth: 'app', body: { callback_urls: [...existing, callbackUrl] } })
|
|
1028
|
+
registered = true
|
|
1029
|
+
} catch {
|
|
1030
|
+
registered = false
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
return { callbackUrl, clientId: app.clientId, clientSecret: app.clientSecret, registered }
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
function beginOAuth(origin) {
|
|
1037
|
+
return ensureOAuthCallback(origin).then(({ callbackUrl, clientId, registered }) => {
|
|
1038
|
+
const state = crypto.randomBytes(16).toString('hex')
|
|
1039
|
+
pendingManifests.set(`oauth:${state}`, Date.now())
|
|
1040
|
+
const url = new URL('https://github.com/login/oauth/authorize')
|
|
1041
|
+
url.searchParams.set('client_id', clientId)
|
|
1042
|
+
url.searchParams.set('redirect_uri', callbackUrl)
|
|
1043
|
+
url.searchParams.set('state', state)
|
|
1044
|
+
return {
|
|
1045
|
+
url: url.toString(),
|
|
1046
|
+
state,
|
|
1047
|
+
callbackUrl,
|
|
1048
|
+
callbackRegistered: registered,
|
|
1049
|
+
note: registered
|
|
1050
|
+
? '打开 url 授权即可'
|
|
1051
|
+
: `先把 ${callbackUrl} 加到 App 设置页(User authorization callback URL)再打开 url,否则 GitHub 会报 redirect_uri 不匹配`,
|
|
1052
|
+
}
|
|
1053
|
+
})
|
|
1054
|
+
}
|
|
1055
|
+
|
|
1056
|
+
async function completeOAuth(code, state, origin) {
|
|
1057
|
+
const key = `oauth:${state}`
|
|
1058
|
+
const startedAt = pendingManifests.get(key)
|
|
1059
|
+
if (!startedAt) throw new Error('OAuth state 不匹配或已过期,请重新发起授权')
|
|
1060
|
+
if (Date.now() - startedAt > 30 * 60 * 1000) {
|
|
1061
|
+
pendingManifests.delete(key)
|
|
1062
|
+
throw new Error('OAuth 授权超时(30 分钟),请重新发起')
|
|
1063
|
+
}
|
|
1064
|
+
const app = await readApp()
|
|
1065
|
+
if (!app || !app.clientId || !app.clientSecret) throw new Error('缺少 App 的 client_id / client_secret')
|
|
1066
|
+
const callbackUrl = `${origin}${PREFIX}/oauth/callback`
|
|
1067
|
+
const response = await transport.request('https://github.com/login/oauth/access_token', {
|
|
1068
|
+
method: 'POST',
|
|
1069
|
+
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
|
|
1070
|
+
body: JSON.stringify({
|
|
1071
|
+
client_id: app.clientId,
|
|
1072
|
+
client_secret: app.clientSecret,
|
|
1073
|
+
code,
|
|
1074
|
+
redirect_uri: callbackUrl,
|
|
1075
|
+
}),
|
|
1076
|
+
})
|
|
1077
|
+
const data = (() => {
|
|
1078
|
+
try {
|
|
1079
|
+
return JSON.parse(response.text || '{}')
|
|
1080
|
+
} catch {
|
|
1081
|
+
return {}
|
|
1082
|
+
}
|
|
1083
|
+
})()
|
|
1084
|
+
if (!data.access_token) {
|
|
1085
|
+
throw new Error(`换取用户令牌失败:${data.error_description || data.error || `HTTP ${response.status}`}`)
|
|
1086
|
+
}
|
|
1087
|
+
pendingManifests.delete(key)
|
|
1088
|
+
const now = Date.now()
|
|
1089
|
+
await writeRecord(OAUTH_CRED, {
|
|
1090
|
+
accessToken: data.access_token,
|
|
1091
|
+
refreshToken: data.refresh_token || '',
|
|
1092
|
+
expiresAt: now + Number(data.expires_in || 28800) * 1000,
|
|
1093
|
+
refreshExpiresAt: data.refresh_token_expires_in ? now + Number(data.refresh_token_expires_in) * 1000 : null,
|
|
1094
|
+
scope: data.scope || '',
|
|
1095
|
+
addedAt: new Date().toISOString(),
|
|
1096
|
+
})
|
|
1097
|
+
authCache = null
|
|
1098
|
+
return { ok: true }
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
async function refreshOAuth() {
|
|
1102
|
+
const record = await readRecord(OAUTH_CRED)
|
|
1103
|
+
if (!record || !record.refreshToken) throw new Error('用户授权已失效且没有 refresh token,请重新授权')
|
|
1104
|
+
const app = await readApp()
|
|
1105
|
+
const response = await transport.request('https://github.com/login/oauth/access_token', {
|
|
1106
|
+
method: 'POST',
|
|
1107
|
+
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
|
|
1108
|
+
body: JSON.stringify({
|
|
1109
|
+
client_id: app.clientId,
|
|
1110
|
+
client_secret: app.clientSecret,
|
|
1111
|
+
grant_type: 'refresh_token',
|
|
1112
|
+
refresh_token: record.refreshToken,
|
|
1113
|
+
}),
|
|
1114
|
+
})
|
|
1115
|
+
const data = (() => {
|
|
1116
|
+
try {
|
|
1117
|
+
return JSON.parse(response.text || '{}')
|
|
1118
|
+
} catch {
|
|
1119
|
+
return {}
|
|
1120
|
+
}
|
|
1121
|
+
})()
|
|
1122
|
+
if (!data.access_token) throw new Error(`刷新用户令牌失败:${data.error_description || data.error || response.status}`)
|
|
1123
|
+
const now = Date.now()
|
|
1124
|
+
await writeRecord(OAUTH_CRED, {
|
|
1125
|
+
...record,
|
|
1126
|
+
accessToken: data.access_token,
|
|
1127
|
+
refreshToken: data.refresh_token || record.refreshToken,
|
|
1128
|
+
expiresAt: now + Number(data.expires_in || 28800) * 1000,
|
|
1129
|
+
refreshExpiresAt: data.refresh_token_expires_in ? now + Number(data.refresh_token_expires_in) * 1000 : record.refreshExpiresAt,
|
|
1130
|
+
})
|
|
1131
|
+
return readRecord(OAUTH_CRED)
|
|
1132
|
+
}
|
|
1133
|
+
|
|
1134
|
+
async function oauthToken() {
|
|
1135
|
+
const record = await readRecord(OAUTH_CRED)
|
|
1136
|
+
if (!record || !record.accessToken) return ''
|
|
1137
|
+
if (record.expiresAt && Date.now() > record.expiresAt - 120000) {
|
|
1138
|
+
const fresh = await refreshOAuth().catch(() => null)
|
|
1139
|
+
if (fresh && fresh.accessToken) return fresh.accessToken
|
|
1140
|
+
}
|
|
1141
|
+
return record.accessToken
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
const pendingDevices = new Map()
|
|
1145
|
+
|
|
1146
|
+
/**
|
|
1147
|
+
* Device flow: no redirect URI, so no port to pin and nothing to register in
|
|
1148
|
+
* the App settings beyond enabling "Device Flow" once.
|
|
1149
|
+
*/
|
|
1150
|
+
async function deviceStart() {
|
|
1151
|
+
const app = await readApp()
|
|
1152
|
+
if (!app || !app.clientId) throw new Error('需要先注册 GitHub App(缺少 client_id)')
|
|
1153
|
+
const response = await transport.request('https://github.com/login/device/code', {
|
|
1154
|
+
method: 'POST',
|
|
1155
|
+
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
|
|
1156
|
+
body: JSON.stringify({ client_id: app.clientId }),
|
|
1157
|
+
})
|
|
1158
|
+
const data = (() => {
|
|
1159
|
+
try {
|
|
1160
|
+
return JSON.parse(response.text || '{}')
|
|
1161
|
+
} catch {
|
|
1162
|
+
return {}
|
|
1163
|
+
}
|
|
1164
|
+
})()
|
|
1165
|
+
if (!data.device_code) {
|
|
1166
|
+
const reason = /device flow/i.test(`${data.error || ''} ${data.error_description || ''}`)
|
|
1167
|
+
? 'App 没有启用 Device Flow:到 App 设置页勾选「Enable Device Flow」保存后再试'
|
|
1168
|
+
: `申请设备码失败:${data.error_description || data.error || `HTTP ${response.status}`}`
|
|
1169
|
+
throw new Error(reason)
|
|
1170
|
+
}
|
|
1171
|
+
pendingDevices.set(data.device_code, {
|
|
1172
|
+
interval: Number(data.interval) || 5,
|
|
1173
|
+
startedAt: Date.now(),
|
|
1174
|
+
expiresIn: Number(data.expires_in) || 900,
|
|
1175
|
+
})
|
|
1176
|
+
return {
|
|
1177
|
+
deviceCode: data.device_code,
|
|
1178
|
+
userCode: data.user_code,
|
|
1179
|
+
verificationUri: data.verification_uri,
|
|
1180
|
+
expiresIn: Number(data.expires_in) || 900,
|
|
1181
|
+
interval: Number(data.interval) || 5,
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
async function devicePoll(deviceCode) {
|
|
1186
|
+
const app = await readApp()
|
|
1187
|
+
const entry = pendingDevices.get(deviceCode)
|
|
1188
|
+
if (!entry) throw new Error('这个设备码不在本进程里(插件可能重载过),请重新发起设备码授权')
|
|
1189
|
+
const response = await transport.request('https://github.com/login/oauth/access_token', {
|
|
1190
|
+
method: 'POST',
|
|
1191
|
+
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
|
|
1192
|
+
body: JSON.stringify({
|
|
1193
|
+
client_id: app.clientId,
|
|
1194
|
+
device_code: deviceCode,
|
|
1195
|
+
grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
|
|
1196
|
+
}),
|
|
1197
|
+
})
|
|
1198
|
+
const data = (() => {
|
|
1199
|
+
try {
|
|
1200
|
+
return JSON.parse(response.text || '{}')
|
|
1201
|
+
} catch {
|
|
1202
|
+
return {}
|
|
1203
|
+
}
|
|
1204
|
+
})()
|
|
1205
|
+
if (data.access_token) {
|
|
1206
|
+
const now = Date.now()
|
|
1207
|
+
await writeRecord(OAUTH_CRED, {
|
|
1208
|
+
accessToken: data.access_token,
|
|
1209
|
+
refreshToken: data.refresh_token || '',
|
|
1210
|
+
expiresAt: now + Number(data.expires_in || 28800) * 1000,
|
|
1211
|
+
refreshExpiresAt: data.refresh_token_expires_in ? now + Number(data.refresh_token_expires_in) * 1000 : null,
|
|
1212
|
+
scope: data.scope || '',
|
|
1213
|
+
via: 'device',
|
|
1214
|
+
addedAt: new Date().toISOString(),
|
|
1215
|
+
})
|
|
1216
|
+
pendingDevices.delete(deviceCode)
|
|
1217
|
+
await writeRecord(AUTH_CRED, { kind: 'oauth' })
|
|
1218
|
+
authCache = null
|
|
1219
|
+
return { status: 'ok' }
|
|
1220
|
+
}
|
|
1221
|
+
const state = data.error || 'unknown'
|
|
1222
|
+
if (state === 'authorization_pending') return { status: 'pending' }
|
|
1223
|
+
if (state === 'slow_down') {
|
|
1224
|
+
pendingDevices.set(deviceCode, { ...entry, interval: entry.interval + 2 })
|
|
1225
|
+
return { status: 'pending', slowDown: true }
|
|
1226
|
+
}
|
|
1227
|
+
if (state === 'expired_token') {
|
|
1228
|
+
pendingDevices.delete(deviceCode)
|
|
1229
|
+
return { status: 'expired' }
|
|
1230
|
+
}
|
|
1231
|
+
if (state === 'access_denied') {
|
|
1232
|
+
pendingDevices.delete(deviceCode)
|
|
1233
|
+
return { status: 'denied' }
|
|
1234
|
+
}
|
|
1235
|
+
throw new Error(`设备码轮询失败:${data.error_description || state}`)
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
/**
|
|
1239
|
+
* Pick the connection to use. Order is App → PAT → environment unless the
|
|
1240
|
+
* profile pins one; the active choice is remembered in credentials.
|
|
1241
|
+
*/
|
|
1242
|
+
async function resolveAuth() {
|
|
1243
|
+
if (authCache && Date.now() - authCache.at < 30000) return authCache.value
|
|
1244
|
+
const stored = await readRecord(AUTH_CRED).catch(() => undefined)
|
|
1245
|
+
const storedKind = stored && typeof stored.kind === 'string' ? stored.kind : ''
|
|
1246
|
+
const preferred = cfg.authMode !== 'auto' ? cfg.authMode : storedKind || 'auto'
|
|
1247
|
+
const order =
|
|
1248
|
+
preferred === 'app'
|
|
1249
|
+
? ['app']
|
|
1250
|
+
: preferred === 'oauth'
|
|
1251
|
+
? ['oauth']
|
|
1252
|
+
: preferred === 'pat'
|
|
1253
|
+
? ['pat']
|
|
1254
|
+
: preferred === 'env'
|
|
1255
|
+
? ['env']
|
|
1256
|
+
: ['app', 'oauth', 'pat', 'env']
|
|
1257
|
+
let value = { kind: 'none' }
|
|
1258
|
+
for (const kind of order) {
|
|
1259
|
+
if (kind === 'app') {
|
|
1260
|
+
const app = await readApp()
|
|
1261
|
+
if (!app) continue
|
|
1262
|
+
const installation = await selectedInstallation().catch(() => undefined)
|
|
1263
|
+
if (!installation) continue
|
|
1264
|
+
value = {
|
|
1265
|
+
kind: 'app',
|
|
1266
|
+
account: installation.account,
|
|
1267
|
+
installationId: installation.id,
|
|
1268
|
+
permissions: installation.permissions || {},
|
|
1269
|
+
}
|
|
1270
|
+
break
|
|
1271
|
+
}
|
|
1272
|
+
if (kind === 'oauth') {
|
|
1273
|
+
const token = await oauthToken().catch(() => '')
|
|
1274
|
+
if (!token) continue
|
|
1275
|
+
value = { kind: 'oauth', token, fingerprint: fingerprint(token) }
|
|
1276
|
+
break
|
|
1277
|
+
}
|
|
1278
|
+
if (kind === 'pat') {
|
|
1279
|
+
const token = await readPat()
|
|
1280
|
+
if (!token) continue
|
|
1281
|
+
value = { kind: 'pat', token, fingerprint: fingerprint(token) }
|
|
1282
|
+
break
|
|
1283
|
+
}
|
|
1284
|
+
if (kind === 'env') {
|
|
1285
|
+
const token = process.env[cfg.patEnvName] || ''
|
|
1286
|
+
if (!token) continue
|
|
1287
|
+
value = { kind: 'env', token, fingerprint: fingerprint(token), envName: cfg.patEnvName }
|
|
1288
|
+
break
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
authCache = { at: Date.now(), value }
|
|
1292
|
+
return value
|
|
1293
|
+
}
|
|
1294
|
+
|
|
1295
|
+
/**
|
|
1296
|
+
* What the active connection can do. An installation token is scoped by the
|
|
1297
|
+
* App's permissions and cannot read notifications or search code; a user token
|
|
1298
|
+
* can do both.
|
|
1299
|
+
*/
|
|
1300
|
+
function capabilitiesOf(auth) {
|
|
1301
|
+
const none = {
|
|
1302
|
+
repoRead: false,
|
|
1303
|
+
repoWrite: false,
|
|
1304
|
+
pullWrite: false,
|
|
1305
|
+
issueWrite: false,
|
|
1306
|
+
actionsWrite: false,
|
|
1307
|
+
workflowsWrite: false,
|
|
1308
|
+
adminWrite: false,
|
|
1309
|
+
notifications: false,
|
|
1310
|
+
codeSearch: false,
|
|
1311
|
+
userLevel: false,
|
|
1312
|
+
}
|
|
1313
|
+
if (auth.kind === 'app') {
|
|
1314
|
+
const p = auth.permissions || {}
|
|
1315
|
+
return {
|
|
1316
|
+
...none,
|
|
1317
|
+
repoRead: true,
|
|
1318
|
+
repoWrite: p.contents === 'write',
|
|
1319
|
+
pullWrite: p.pull_requests === 'write',
|
|
1320
|
+
issueWrite: p.issues === 'write',
|
|
1321
|
+
actionsWrite: p.actions === 'write',
|
|
1322
|
+
workflowsWrite: p.workflows === 'write',
|
|
1323
|
+
adminWrite: p.administration === 'write',
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
if (auth.kind === 'pat' || auth.kind === 'env' || auth.kind === 'oauth') {
|
|
1327
|
+
return {
|
|
1328
|
+
repoRead: true,
|
|
1329
|
+
repoWrite: true,
|
|
1330
|
+
pullWrite: true,
|
|
1331
|
+
issueWrite: true,
|
|
1332
|
+
actionsWrite: true,
|
|
1333
|
+
workflowsWrite: true,
|
|
1334
|
+
adminWrite: true,
|
|
1335
|
+
notifications: true,
|
|
1336
|
+
codeSearch: true,
|
|
1337
|
+
userLevel: true,
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
return none
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
async function status() {
|
|
1344
|
+
const app = await readApp()
|
|
1345
|
+
const installError = []
|
|
1346
|
+
let networkFailure = null
|
|
1347
|
+
const installationsList = app
|
|
1348
|
+
? await installations().catch((error) => {
|
|
1349
|
+
installError.push(errorMessage(error))
|
|
1350
|
+
if (error && error.code === 'NETWORK') networkFailure = error
|
|
1351
|
+
return []
|
|
1352
|
+
})
|
|
1353
|
+
: []
|
|
1354
|
+
const installation = app
|
|
1355
|
+
? await selectedInstallation().catch((error) => {
|
|
1356
|
+
installError.push(errorMessage(error))
|
|
1357
|
+
if (error && error.code === 'NETWORK') networkFailure = error
|
|
1358
|
+
return undefined
|
|
1359
|
+
})
|
|
1360
|
+
: undefined
|
|
1361
|
+
// One transport failure produced two identical lines before; report each
|
|
1362
|
+
// distinct message once.
|
|
1363
|
+
const errors = Array.from(new Set(installError))
|
|
1364
|
+
const host = (() => {
|
|
1365
|
+
try {
|
|
1366
|
+
return new URL(cfg.baseUrl).hostname
|
|
1367
|
+
} catch {
|
|
1368
|
+
return 'api.github.com'
|
|
1369
|
+
}
|
|
1370
|
+
})()
|
|
1371
|
+
const network = app || networkFailure ? await describeDns(host) : { host, addresses: [], localRedirect: false, hint: '' }
|
|
1372
|
+
network.route = transport.state.lastRoute || ''
|
|
1373
|
+
network.preferred = transport.state.preferred || ''
|
|
1374
|
+
network.proxy = transport.state.proxy || ''
|
|
1375
|
+
network.attempts = transport.state.attempts || []
|
|
1376
|
+
// The hosts hijack only matters when we could NOT route around it.
|
|
1377
|
+
if (network.localRedirect) {
|
|
1378
|
+
network.hint =
|
|
1379
|
+
network.route === 'direct:public-dns'
|
|
1380
|
+
? `${host} 在 hosts 里被指向本机地址,已自动改用公共 DNS 直连(当前线路 ${network.route})。若想彻底干净,可以关掉加速工具或清理 hosts 中的 GitHub 条目。`
|
|
1381
|
+
: network.hint
|
|
1382
|
+
} else {
|
|
1383
|
+
network.hint = ''
|
|
1384
|
+
}
|
|
1385
|
+
const tokenReady = Boolean(installationTokenCache)
|
|
1386
|
+
// The active connection decides which capabilities the UI may offer.
|
|
1387
|
+
const authState = await resolveAuth().catch(() => ({ kind: 'none' }))
|
|
1388
|
+
const capabilities = capabilitiesOf(authState)
|
|
1389
|
+
let login = authState.account || ''
|
|
1390
|
+
let tokenScopes = []
|
|
1391
|
+
if ((authState.kind === 'pat' || authState.kind === 'env') && authState.token) {
|
|
1392
|
+
try {
|
|
1393
|
+
const me = await whoAmI(authState.token)
|
|
1394
|
+
login = me.login
|
|
1395
|
+
tokenScopes = me.scopes || []
|
|
1396
|
+
} catch (error) {
|
|
1397
|
+
installError.push(`当前令牌无效:${errorMessage(error)}`)
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
const patToken = await readPat().catch(() => '')
|
|
1401
|
+
const oauthState = await readRecord(OAUTH_CRED).catch(() => undefined)
|
|
1402
|
+
const envToken = process.env[cfg.patEnvName] || ''
|
|
1403
|
+
const base = {
|
|
1404
|
+
version: PLUGIN_VERSION,
|
|
1405
|
+
apiBase: cfg.baseUrl,
|
|
1406
|
+
configured: Boolean(app),
|
|
1407
|
+
app: app
|
|
1408
|
+
? {
|
|
1409
|
+
appId: app.appId,
|
|
1410
|
+
name: app.name || '',
|
|
1411
|
+
slug: app.slug || '',
|
|
1412
|
+
htmlUrl: app.htmlUrl || '',
|
|
1413
|
+
owner: app.owner || '',
|
|
1414
|
+
registeredAt: app.registeredAt || null,
|
|
1415
|
+
hasPrivateKey: Boolean(app.pem),
|
|
1416
|
+
}
|
|
1417
|
+
: null,
|
|
1418
|
+
installations: installationsList.map((item) => ({
|
|
1419
|
+
id: item.id,
|
|
1420
|
+
account: item.account,
|
|
1421
|
+
accountType: item.accountType,
|
|
1422
|
+
repositorySelection: item.repositorySelection,
|
|
1423
|
+
})),
|
|
1424
|
+
installationCount: installationsList.length,
|
|
1425
|
+
installation: installation
|
|
1426
|
+
? { id: installation.id, account: installation.account, permissions: installation.permissions || {} }
|
|
1427
|
+
: null,
|
|
1428
|
+
installationToken: tokenReady && installationTokenCache
|
|
1429
|
+
? { expiresAt: new Date(installationTokenCache.expiresAt).toISOString() }
|
|
1430
|
+
: null,
|
|
1431
|
+
publish: { branch: cfg.publishBranch, topic: cfg.topic, marketIndexUrls: cfg.marketIndexUrls },
|
|
1432
|
+
authMode: cfg.authMode,
|
|
1433
|
+
auth: {
|
|
1434
|
+
kind: authState.kind,
|
|
1435
|
+
account: login,
|
|
1436
|
+
scopes: tokenScopes,
|
|
1437
|
+
capabilities,
|
|
1438
|
+
readOnly: cfg.readOnly || !capabilities.repoWrite,
|
|
1439
|
+
readOnlyReason: cfg.readOnly
|
|
1440
|
+
? '配置里把 readOnly 设成了 true'
|
|
1441
|
+
: !capabilities.repoWrite
|
|
1442
|
+
? '当前连接没有写权限(App 只读安装,或令牌是只读的)'
|
|
1443
|
+
: '',
|
|
1444
|
+
},
|
|
1445
|
+
connections: {
|
|
1446
|
+
app: Boolean(app),
|
|
1447
|
+
oauth: {
|
|
1448
|
+
configured: Boolean(oauthState && oauthState.accessToken),
|
|
1449
|
+
expiresAt: oauthState && oauthState.expiresAt ? new Date(oauthState.expiresAt).toISOString() : null,
|
|
1450
|
+
},
|
|
1451
|
+
pat: { configured: Boolean(patToken), fingerprint: patToken ? fingerprint(patToken) : '' },
|
|
1452
|
+
env: { name: cfg.patEnvName, present: Boolean(envToken), fingerprint: envToken ? fingerprint(envToken) : '' },
|
|
1453
|
+
},
|
|
1454
|
+
errors,
|
|
1455
|
+
network,
|
|
1456
|
+
}
|
|
1457
|
+
if (authState.kind !== 'app') return base
|
|
1458
|
+
if (!app || !installation) return base
|
|
1459
|
+
try {
|
|
1460
|
+
const viewer = await call('/installation/repositories?per_page=1')
|
|
1461
|
+
return {
|
|
1462
|
+
...base,
|
|
1463
|
+
// The call above is what mints the installation token, so read the cache
|
|
1464
|
+
// again instead of reporting the pre-call state.
|
|
1465
|
+
installationToken: installationTokenCache
|
|
1466
|
+
? { expiresAt: new Date(installationTokenCache.expiresAt).toISOString() }
|
|
1467
|
+
: null,
|
|
1468
|
+
repositoryCount: typeof viewer.total_count === 'number' ? viewer.total_count : null,
|
|
1469
|
+
}
|
|
1470
|
+
} catch (error) {
|
|
1471
|
+
return { ...base, error: errorMessage(error) }
|
|
1472
|
+
}
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
async function listRepositories(query) {
|
|
1476
|
+
const json = await call('/installation/repositories?per_page=100')
|
|
1477
|
+
const items = (json.repositories || []).map((repo) => ({
|
|
1478
|
+
id: repo.id,
|
|
1479
|
+
fullName: repo.full_name,
|
|
1480
|
+
owner: repo.owner ? repo.owner.login : '',
|
|
1481
|
+
name: repo.name,
|
|
1482
|
+
private: Boolean(repo.private),
|
|
1483
|
+
description: repo.description || '',
|
|
1484
|
+
defaultBranch: repo.default_branch || 'main',
|
|
1485
|
+
updatedAt: repo.updated_at || null,
|
|
1486
|
+
topics: Array.isArray(repo.topics) ? repo.topics : [],
|
|
1487
|
+
}))
|
|
1488
|
+
const needle = String(query || '').toLowerCase()
|
|
1489
|
+
const filtered = needle ? items.filter((repo) => repo.fullName.toLowerCase().includes(needle)) : items
|
|
1490
|
+
return { total: json.total_count || items.length, returned: filtered.length, items: filtered }
|
|
1491
|
+
}
|
|
1492
|
+
|
|
1493
|
+
function repoPath(owner, name) {
|
|
1494
|
+
if (!owner || !name) throw new Error('需要 owner 与 name')
|
|
1495
|
+
return `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`
|
|
1496
|
+
}
|
|
1497
|
+
|
|
1498
|
+
async function readTree(owner, name, ref) {
|
|
1499
|
+
const repo = repoPath(owner, name)
|
|
1500
|
+
const meta = await call(repo)
|
|
1501
|
+
const branch = ref || meta.default_branch || 'main'
|
|
1502
|
+
const tree = await call(`${repo}/git/trees/${encodeURIComponent(branch)}`)
|
|
1503
|
+
const entries = (tree.tree || [])
|
|
1504
|
+
.slice(0, 1000)
|
|
1505
|
+
.map((entry) => ({ path: entry.path, type: entry.type, size: entry.size ?? null, sha: entry.sha }))
|
|
1506
|
+
return { owner, name, ref: branch, truncated: Boolean(tree.truncated), returned: entries.length, entries }
|
|
1507
|
+
}
|
|
1508
|
+
|
|
1509
|
+
async function readFile(owner, name, filePath, ref) {
|
|
1510
|
+
const repo = repoPath(owner, name)
|
|
1511
|
+
const query = ref ? `?ref=${encodeURIComponent(ref)}` : ''
|
|
1512
|
+
const json = await call(`${repo}/contents/${filePath.split('/').map(encodeURIComponent).join('/')}${query}`)
|
|
1513
|
+
if (Array.isArray(json)) throw new Error(`${filePath} 是目录,请用 gh_tree`)
|
|
1514
|
+
const text =
|
|
1515
|
+
json.encoding === 'base64' && json.content ? Buffer.from(json.content, 'base64').toString('utf8') : ''
|
|
1516
|
+
return { path: json.path, sha: json.sha, size: json.size, truncated: false, text }
|
|
1517
|
+
}
|
|
1518
|
+
|
|
1519
|
+
async function writeFile(owner, name, filePath, text, message, sha, branch) {
|
|
1520
|
+
const repo = repoPath(owner, name)
|
|
1521
|
+
const body = {
|
|
1522
|
+
message: message || `chore: update ${filePath}`,
|
|
1523
|
+
content: Buffer.from(text, 'utf8').toString('base64'),
|
|
1524
|
+
}
|
|
1525
|
+
if (sha) body.sha = sha
|
|
1526
|
+
if (branch) body.branch = branch
|
|
1527
|
+
const json = await call(`${repo}/contents/${filePath.split('/').map(encodeURIComponent).join('/')}`, {
|
|
1528
|
+
method: 'PUT',
|
|
1529
|
+
body,
|
|
1530
|
+
})
|
|
1531
|
+
return {
|
|
1532
|
+
path: json.content ? json.content.path : filePath,
|
|
1533
|
+
sha: json.content ? json.content.sha : null,
|
|
1534
|
+
commit: json.commit ? json.commit.sha : null,
|
|
1535
|
+
}
|
|
1536
|
+
}
|
|
1537
|
+
|
|
1538
|
+
async function listIssues(owner, name, state) {
|
|
1539
|
+
const repo = repoPath(owner, name)
|
|
1540
|
+
const json = await call(`${repo}/issues?state=${state || 'open'}&per_page=30`)
|
|
1541
|
+
const items = (Array.isArray(json) ? json : []).map((item) => ({
|
|
1542
|
+
number: item.number,
|
|
1543
|
+
title: item.title,
|
|
1544
|
+
state: item.state,
|
|
1545
|
+
user: item.user ? item.user.login : '',
|
|
1546
|
+
labels: (item.labels || []).map((label) => (typeof label === 'string' ? label : label.name)),
|
|
1547
|
+
isPullRequest: Boolean(item.pull_request),
|
|
1548
|
+
comments: item.comments,
|
|
1549
|
+
updatedAt: item.updated_at,
|
|
1550
|
+
htmlUrl: item.html_url,
|
|
1551
|
+
}))
|
|
1552
|
+
return { returned: items.length, items }
|
|
1553
|
+
}
|
|
1554
|
+
|
|
1555
|
+
async function createIssue(owner, name, title, body) {
|
|
1556
|
+
const repo = repoPath(owner, name)
|
|
1557
|
+
const json = await call(`${repo}/issues`, { method: 'POST', body: { title, body: body || '' } })
|
|
1558
|
+
return { number: json.number, title: json.title, htmlUrl: json.html_url }
|
|
1559
|
+
}
|
|
1560
|
+
|
|
1561
|
+
async function commentIssue(owner, name, number, body) {
|
|
1562
|
+
const repo = repoPath(owner, name)
|
|
1563
|
+
const json = await call(`${repo}/issues/${number}/comments`, { method: 'POST', body: { body } })
|
|
1564
|
+
return { id: json.id, htmlUrl: json.html_url }
|
|
1565
|
+
}
|
|
1566
|
+
|
|
1567
|
+
async function listPulls(owner, name, state) {
|
|
1568
|
+
const repo = repoPath(owner, name)
|
|
1569
|
+
const json = await call(`${repo}/pulls?state=${state || 'open'}&per_page=30`)
|
|
1570
|
+
const items = (Array.isArray(json) ? json : []).map((item) => ({
|
|
1571
|
+
number: item.number,
|
|
1572
|
+
title: item.title,
|
|
1573
|
+
state: item.state,
|
|
1574
|
+
draft: Boolean(item.draft),
|
|
1575
|
+
user: item.user ? item.user.login : '',
|
|
1576
|
+
head: item.head ? item.head.ref : '',
|
|
1577
|
+
base: item.base ? item.base.ref : '',
|
|
1578
|
+
mergeableState: item.mergeable_state || '',
|
|
1579
|
+
updatedAt: item.updated_at,
|
|
1580
|
+
htmlUrl: item.html_url,
|
|
1581
|
+
}))
|
|
1582
|
+
return { returned: items.length, items }
|
|
1583
|
+
}
|
|
1584
|
+
|
|
1585
|
+
async function createPull(owner, name, head, base, title, body) {
|
|
1586
|
+
const repo = repoPath(owner, name)
|
|
1587
|
+
const json = await call(`${repo}/pulls`, { method: 'POST', body: { head, base, title, body: body || '' } })
|
|
1588
|
+
return { number: json.number, htmlUrl: json.html_url, state: json.state }
|
|
1589
|
+
}
|
|
1590
|
+
|
|
1591
|
+
async function mergePull(owner, name, number, method) {
|
|
1592
|
+
const repo = repoPath(owner, name)
|
|
1593
|
+
const json = await call(`${repo}/pulls/${number}/merge`, {
|
|
1594
|
+
method: 'PUT',
|
|
1595
|
+
body: { merge_method: method || 'squash' },
|
|
1596
|
+
})
|
|
1597
|
+
return { merged: Boolean(json.merged), message: json.message || '', sha: json.sha || null }
|
|
1598
|
+
}
|
|
1599
|
+
|
|
1600
|
+
async function listRuns(owner, name) {
|
|
1601
|
+
const repo = repoPath(owner, name)
|
|
1602
|
+
const json = await call(`${repo}/actions/runs?per_page=15`)
|
|
1603
|
+
const runs = json.workflow_runs || []
|
|
1604
|
+
return {
|
|
1605
|
+
total: json.total_count || runs.length,
|
|
1606
|
+
items: runs.map((run) => ({
|
|
1607
|
+
id: run.id,
|
|
1608
|
+
name: run.name,
|
|
1609
|
+
status: run.status,
|
|
1610
|
+
conclusion: run.conclusion,
|
|
1611
|
+
branch: run.head_branch,
|
|
1612
|
+
event: run.event,
|
|
1613
|
+
createdAt: run.created_at,
|
|
1614
|
+
htmlUrl: run.html_url,
|
|
1615
|
+
})),
|
|
1616
|
+
}
|
|
1617
|
+
}
|
|
1618
|
+
|
|
1619
|
+
async function rerunWorkflow(owner, name, runId) {
|
|
1620
|
+
const repo = repoPath(owner, name)
|
|
1621
|
+
await call(`${repo}/actions/runs/${runId}/rerun`, { method: 'POST' })
|
|
1622
|
+
return { ok: true, runId }
|
|
1623
|
+
}
|
|
1624
|
+
|
|
1625
|
+
async function pullDetail(owner, name, number) {
|
|
1626
|
+
const repo = repoPath(owner, name)
|
|
1627
|
+
const [pull, files] = await Promise.all([
|
|
1628
|
+
call(`${repo}/pulls/${number}`),
|
|
1629
|
+
call(`${repo}/pulls/${number}/files?per_page=100`),
|
|
1630
|
+
])
|
|
1631
|
+
return {
|
|
1632
|
+
number: pull.number,
|
|
1633
|
+
title: pull.title,
|
|
1634
|
+
state: pull.state,
|
|
1635
|
+
draft: Boolean(pull.draft),
|
|
1636
|
+
user: pull.user ? pull.user.login : '',
|
|
1637
|
+
head: pull.head ? pull.head.ref : '',
|
|
1638
|
+
base: pull.base ? pull.base.ref : '',
|
|
1639
|
+
mergeable: pull.mergeable,
|
|
1640
|
+
mergeableState: pull.mergeable_state || '',
|
|
1641
|
+
additions: pull.additions,
|
|
1642
|
+
deletions: pull.deletions,
|
|
1643
|
+
changedFiles: pull.changed_files,
|
|
1644
|
+
body: pull.body || '',
|
|
1645
|
+
htmlUrl: pull.html_url,
|
|
1646
|
+
updatedAt: pull.updated_at,
|
|
1647
|
+
files: (Array.isArray(files) ? files : []).map((file) => ({
|
|
1648
|
+
path: file.filename,
|
|
1649
|
+
status: file.status,
|
|
1650
|
+
additions: file.additions,
|
|
1651
|
+
deletions: file.deletions,
|
|
1652
|
+
patch: file.patch ? String(file.patch).slice(0, 6000) : '',
|
|
1653
|
+
})),
|
|
1654
|
+
}
|
|
1655
|
+
}
|
|
1656
|
+
|
|
1657
|
+
async function addPullComment(owner, name, number, body, line) {
|
|
1658
|
+
const repo = repoPath(owner, name)
|
|
1659
|
+
if (!body || !String(body).trim()) throw new Error('评论内容不能为空')
|
|
1660
|
+
if (line && line.path) {
|
|
1661
|
+
const json = await call(`${repo}/pulls/${number}/comments`, {
|
|
1662
|
+
method: 'POST',
|
|
1663
|
+
body: { body, path: line.path, line: Number(line.number), side: line.side || 'RIGHT' },
|
|
1664
|
+
})
|
|
1665
|
+
return { id: json.id, inline: true, htmlUrl: json.html_url }
|
|
1666
|
+
}
|
|
1667
|
+
const json = await call(`${repo}/issues/${number}/comments`, { method: 'POST', body: { body } })
|
|
1668
|
+
return { id: json.id, inline: false, htmlUrl: json.html_url }
|
|
1669
|
+
}
|
|
1670
|
+
|
|
1671
|
+
async function submitReview(owner, name, number, event, body) {
|
|
1672
|
+
const allowed = ['APPROVE', 'REQUEST_CHANGES', 'COMMENT']
|
|
1673
|
+
if (!allowed.includes(event)) throw new Error(`event 必须是 ${allowed.join(' / ')}`)
|
|
1674
|
+
if (event === 'REQUEST_CHANGES' && !String(body || '').trim()) {
|
|
1675
|
+
throw new Error('请求修改必须写理由')
|
|
1676
|
+
}
|
|
1677
|
+
const repo = repoPath(owner, name)
|
|
1678
|
+
const json = await call(`${repo}/pulls/${number}/reviews`, { method: 'POST', body: { event, body: body || '' } })
|
|
1679
|
+
return { id: json.id, state: json.state, htmlUrl: json.html_url }
|
|
1680
|
+
}
|
|
1681
|
+
|
|
1682
|
+
async function updateIssue(owner, name, number, patch) {
|
|
1683
|
+
const repo = repoPath(owner, name)
|
|
1684
|
+
const body = {}
|
|
1685
|
+
for (const key of ['title', 'body', 'state', 'state_reason', 'milestone']) {
|
|
1686
|
+
if (patch[key] !== undefined) body[key] = patch[key]
|
|
1687
|
+
}
|
|
1688
|
+
if (Array.isArray(patch.labels)) body.labels = patch.labels
|
|
1689
|
+
if (Array.isArray(patch.assignees)) body.assignees = patch.assignees
|
|
1690
|
+
if (Object.keys(body).length === 0) throw new Error('没有要修改的字段')
|
|
1691
|
+
const json = await call(`${repo}/issues/${number}`, { method: 'PATCH', body })
|
|
1692
|
+
return {
|
|
1693
|
+
number: json.number,
|
|
1694
|
+
title: json.title,
|
|
1695
|
+
state: json.state,
|
|
1696
|
+
labels: (json.labels || []).map((label) => (typeof label === 'string' ? label : label.name)),
|
|
1697
|
+
assignees: (json.assignees || []).map((item) => item.login),
|
|
1698
|
+
htmlUrl: json.html_url,
|
|
1699
|
+
}
|
|
1700
|
+
}
|
|
1701
|
+
|
|
1702
|
+
async function listWorkflows(owner, name) {
|
|
1703
|
+
const repo = repoPath(owner, name)
|
|
1704
|
+
const json = await call(`${repo}/actions/workflows?per_page=50`)
|
|
1705
|
+
return {
|
|
1706
|
+
items: (json.workflows || []).map((item) => ({
|
|
1707
|
+
id: item.id,
|
|
1708
|
+
name: item.name,
|
|
1709
|
+
path: item.path,
|
|
1710
|
+
state: item.state,
|
|
1711
|
+
htmlUrl: item.html_url,
|
|
1712
|
+
})),
|
|
1713
|
+
}
|
|
1714
|
+
}
|
|
1715
|
+
|
|
1716
|
+
async function dispatchNamedWorkflow(owner, name, workflow, ref, inputs) {
|
|
1717
|
+
const repo = repoPath(owner, name)
|
|
1718
|
+
if (!workflow) throw new Error('需要 workflow(文件名或 id)')
|
|
1719
|
+
await call(`${repo}/actions/workflows/${encodeURIComponent(workflow)}/dispatches`, {
|
|
1720
|
+
method: 'POST',
|
|
1721
|
+
body: { ref: ref || 'main', ...(inputs && Object.keys(inputs).length ? { inputs } : {}) },
|
|
1722
|
+
})
|
|
1723
|
+
return { dispatched: true, workflow, ref: ref || 'main', inputs: inputs || {} }
|
|
1724
|
+
}
|
|
1725
|
+
|
|
1726
|
+
async function runLog(owner, name, runId, tailLines = 120) {
|
|
1727
|
+
const repo = repoPath(owner, name)
|
|
1728
|
+
const token = await installationToken()
|
|
1729
|
+
// The archive answers 302 to a signed objects.githubusercontent.com URL, and
|
|
1730
|
+
// both hosts are hijacked on some machines, so follow the redirect through
|
|
1731
|
+
// the same resilient transport instead of global fetch.
|
|
1732
|
+
let url = `${cfg.baseUrl}${repo}/actions/runs/${runId}/logs`
|
|
1733
|
+
let withAuth = true
|
|
1734
|
+
let response = null
|
|
1735
|
+
for (let hop = 0; hop < 5; hop++) {
|
|
1736
|
+
response = await transport.request(url, {
|
|
1737
|
+
headers: withAuth ? { Authorization: `Bearer ${token}`, Accept: 'application/vnd.github+json' } : { Accept: '*/*' },
|
|
1738
|
+
binary: true,
|
|
1739
|
+
})
|
|
1740
|
+
const location = response.headers && response.headers.location
|
|
1741
|
+
if (response.status >= 300 && response.status < 400 && location) {
|
|
1742
|
+
url = new URL(location, url).href
|
|
1743
|
+
withAuth = new URL(url).hostname === new URL(cfg.baseUrl).hostname
|
|
1744
|
+
continue
|
|
1745
|
+
}
|
|
1746
|
+
break
|
|
1747
|
+
}
|
|
1748
|
+
if (!response || response.status !== 200 || !response.buffer) {
|
|
1749
|
+
throw new GhError(response ? response.status : 0, 'LOG_UNAVAILABLE', `取日志失败(HTTP ${response ? response.status : '?'})`)
|
|
1750
|
+
}
|
|
1751
|
+
const entries = unzipEntries(response.buffer)
|
|
1752
|
+
const pick =
|
|
1753
|
+
entries.find((entry) => /Publish\.txt$/i.test(entry.name)) ||
|
|
1754
|
+
entries.find((entry) => /\.txt$/i.test(entry.name)) ||
|
|
1755
|
+
entries[entries.length - 1]
|
|
1756
|
+
const lines = pick ? pick.text.split('\n') : []
|
|
1757
|
+
return {
|
|
1758
|
+
runId,
|
|
1759
|
+
files: entries.map((entry) => entry.name),
|
|
1760
|
+
name: pick ? pick.name : '',
|
|
1761
|
+
tail: lines.slice(-Math.max(10, Math.min(2000, tailLines))).join('\n'),
|
|
1762
|
+
}
|
|
1763
|
+
}
|
|
1764
|
+
|
|
1765
|
+
return {
|
|
1766
|
+
call,
|
|
1767
|
+
installToken: installationToken,
|
|
1768
|
+
status,
|
|
1769
|
+
installations,
|
|
1770
|
+
selectedInstallation,
|
|
1771
|
+
resolveAuth,
|
|
1772
|
+
capabilitiesOf,
|
|
1773
|
+
whoAmI,
|
|
1774
|
+
fingerprint,
|
|
1775
|
+
useConnection: async (kind) => {
|
|
1776
|
+
if (!['app', 'oauth', 'pat', 'env'].includes(kind)) throw new Error(`未知连接类型:${kind}`)
|
|
1777
|
+
if (kind === 'app') {
|
|
1778
|
+
const app = await readApp()
|
|
1779
|
+
if (!app) throw new Error('还没有注册 GitHub App')
|
|
1780
|
+
const installation = await selectedInstallation()
|
|
1781
|
+
if (!installation) throw new Error('App 还没有安装到任何账号')
|
|
1782
|
+
}
|
|
1783
|
+
if (kind === 'oauth' && !(await oauthToken().catch(() => ''))) throw new Error('还没有完成 App 用户授权')
|
|
1784
|
+
if (kind === 'pat' && !(await readPat())) throw new Error('还没有保存个人访问令牌')
|
|
1785
|
+
if (kind === 'env' && !process.env[cfg.patEnvName]) throw new Error(`环境变量 ${cfg.patEnvName} 没有设置`)
|
|
1786
|
+
await writeRecord(AUTH_CRED, { kind })
|
|
1787
|
+
authCache = null
|
|
1788
|
+
return resolveAuth()
|
|
1789
|
+
},
|
|
1790
|
+
setPat: async (token) => {
|
|
1791
|
+
const value = String(token || '').trim()
|
|
1792
|
+
if (!value) throw new Error('令牌不能为空')
|
|
1793
|
+
const me = await whoAmI(value)
|
|
1794
|
+
await writeRecord(PAT_CRED, { token: value, login: me.login, scopes: me.scopes, addedAt: new Date().toISOString() })
|
|
1795
|
+
await writeRecord(AUTH_CRED, { kind: 'pat' })
|
|
1796
|
+
authCache = null
|
|
1797
|
+
return { login: me.login, fingerprint: fingerprint(value), scopes: me.scopes }
|
|
1798
|
+
},
|
|
1799
|
+
clearPat: async () => {
|
|
1800
|
+
await deleteRecord(PAT_CRED)
|
|
1801
|
+
const stored = await readRecord(AUTH_CRED).catch(() => undefined)
|
|
1802
|
+
if (stored && stored.kind === 'pat') await writeRecord(AUTH_CRED, { kind: 'app' })
|
|
1803
|
+
authCache = null
|
|
1804
|
+
return { ok: true }
|
|
1805
|
+
},
|
|
1806
|
+
selectInstallation: async (id) => {
|
|
1807
|
+
const list = await installations()
|
|
1808
|
+
const match = list.find((item) => String(item.id) === String(id))
|
|
1809
|
+
if (!match) throw new Error(`找不到 installation ${id}`)
|
|
1810
|
+
await writeRecord(INSTALL_CRED, match)
|
|
1811
|
+
installationTokenCache = null
|
|
1812
|
+
return match
|
|
1813
|
+
},
|
|
1814
|
+
beginManifest,
|
|
1815
|
+
completeManifest,
|
|
1816
|
+
deviceStart,
|
|
1817
|
+
devicePoll,
|
|
1818
|
+
beginOAuth,
|
|
1819
|
+
completeOAuth,
|
|
1820
|
+
clearOAuth: async () => {
|
|
1821
|
+
await deleteRecord(OAUTH_CRED)
|
|
1822
|
+
const stored = await readRecord(AUTH_CRED).catch(() => undefined)
|
|
1823
|
+
if (stored && stored.kind === 'oauth') await writeRecord(AUTH_CRED, { kind: 'app' })
|
|
1824
|
+
authCache = null
|
|
1825
|
+
return { ok: true }
|
|
1826
|
+
},
|
|
1827
|
+
resetApp,
|
|
1828
|
+
appConfigured: async () => Boolean(await readApp()),
|
|
1829
|
+
waitForCredentials,
|
|
1830
|
+
readRecord,
|
|
1831
|
+
writeRecord,
|
|
1832
|
+
listRepositories,
|
|
1833
|
+
readTree,
|
|
1834
|
+
readFile,
|
|
1835
|
+
writeFile,
|
|
1836
|
+
listIssues,
|
|
1837
|
+
createIssue,
|
|
1838
|
+
commentIssue,
|
|
1839
|
+
listPulls,
|
|
1840
|
+
createPull,
|
|
1841
|
+
mergePull,
|
|
1842
|
+
listRuns,
|
|
1843
|
+
rerunWorkflow,
|
|
1844
|
+
pullDetail,
|
|
1845
|
+
addPullComment,
|
|
1846
|
+
submitReview,
|
|
1847
|
+
updateIssue,
|
|
1848
|
+
listWorkflows,
|
|
1849
|
+
dispatchNamedWorkflow,
|
|
1850
|
+
runLog,
|
|
1851
|
+
}
|
|
1852
|
+
}
|
|
1853
|
+
|
|
1854
|
+
/* ------------------------------------------------------------------ */
|
|
1855
|
+
/* Plugin preflight and publishing */
|
|
1856
|
+
/* ------------------------------------------------------------------ */
|
|
1857
|
+
|
|
1858
|
+
async function exists(target) {
|
|
1859
|
+
try {
|
|
1860
|
+
await fs.access(target)
|
|
1861
|
+
return true
|
|
1862
|
+
} catch {
|
|
1863
|
+
return false
|
|
1864
|
+
}
|
|
1865
|
+
}
|
|
1866
|
+
|
|
1867
|
+
async function collectFiles(root, budget) {
|
|
1868
|
+
const files = []
|
|
1869
|
+
let total = 0
|
|
1870
|
+
let skipped = 0
|
|
1871
|
+
async function walk(dir) {
|
|
1872
|
+
let entries = []
|
|
1873
|
+
try {
|
|
1874
|
+
entries = await fs.readdir(dir, { withFileTypes: true })
|
|
1875
|
+
} catch {
|
|
1876
|
+
return
|
|
1877
|
+
}
|
|
1878
|
+
for (const entry of entries) {
|
|
1879
|
+
if (files.length >= 300) return
|
|
1880
|
+
const full = path.join(dir, entry.name)
|
|
1881
|
+
if (entry.isDirectory()) {
|
|
1882
|
+
if (SKIP_DIRS.has(entry.name)) continue
|
|
1883
|
+
await walk(full)
|
|
1884
|
+
continue
|
|
1885
|
+
}
|
|
1886
|
+
if (!entry.isFile()) continue
|
|
1887
|
+
const stat = await fs.stat(full).catch(() => null)
|
|
1888
|
+
if (!stat) continue
|
|
1889
|
+
if (stat.size > 1024 * 1024) {
|
|
1890
|
+
skipped += 1
|
|
1891
|
+
continue
|
|
1892
|
+
}
|
|
1893
|
+
if (total + stat.size > budget) {
|
|
1894
|
+
skipped += 1
|
|
1895
|
+
continue
|
|
1896
|
+
}
|
|
1897
|
+
const content = await fs.readFile(full)
|
|
1898
|
+
total += content.length
|
|
1899
|
+
files.push({ path: path.relative(root, full).split(path.sep).join('/'), content })
|
|
1900
|
+
}
|
|
1901
|
+
}
|
|
1902
|
+
await walk(root)
|
|
1903
|
+
return { files, total, skipped }
|
|
1904
|
+
}
|
|
1905
|
+
|
|
1906
|
+
function findSecrets(files) {
|
|
1907
|
+
const hits = []
|
|
1908
|
+
for (const file of files) {
|
|
1909
|
+
if (!/\.(js|mjs|cjs|ts|tsx|jsx|json|ya?ml|md|txt|env|sh|ps1|ini|toml)$/i.test(file.path) && !file.path.includes('.env')) {
|
|
1910
|
+
continue
|
|
1911
|
+
}
|
|
1912
|
+
const text = file.content.toString('utf8')
|
|
1913
|
+
for (const [name, pattern] of SECRET_PATTERNS) {
|
|
1914
|
+
const match = pattern.exec(text)
|
|
1915
|
+
if (!match) continue
|
|
1916
|
+
const line = text.slice(0, match.index).split('\n').length
|
|
1917
|
+
hits.push({ file: file.path, line, kind: name })
|
|
1918
|
+
}
|
|
1919
|
+
}
|
|
1920
|
+
return hits
|
|
1921
|
+
}
|
|
1922
|
+
|
|
1923
|
+
async function preflight(dir, gh, cfg) {
|
|
1924
|
+
const checks = []
|
|
1925
|
+
const add = (id, level, title, detail) => checks.push({ id, level, title, detail: detail || '' })
|
|
1926
|
+
const root = path.resolve(dir)
|
|
1927
|
+
const packagePath = path.join(root, 'package.json')
|
|
1928
|
+
|
|
1929
|
+
if (!(await exists(root))) {
|
|
1930
|
+
add('dir', 'block', '插件目录不存在', root)
|
|
1931
|
+
return { dir: root, checks, ready: false }
|
|
1932
|
+
}
|
|
1933
|
+
if (!(await exists(packagePath))) {
|
|
1934
|
+
add('package.json', 'block', '根目录缺 package.json', '')
|
|
1935
|
+
return { dir: root, checks, ready: false }
|
|
1936
|
+
}
|
|
1937
|
+
|
|
1938
|
+
let pkg = null
|
|
1939
|
+
try {
|
|
1940
|
+
pkg = JSON.parse(await fs.readFile(packagePath, 'utf8'))
|
|
1941
|
+
add('package.json', 'pass', 'package.json 可解析', `${pkg.name || '未命名'}@${pkg.version || '?'}`)
|
|
1942
|
+
} catch (error) {
|
|
1943
|
+
add('package.json', 'block', 'package.json 不是合法 JSON', errorMessage(error))
|
|
1944
|
+
return { dir: root, checks, ready: false }
|
|
1945
|
+
}
|
|
1946
|
+
|
|
1947
|
+
if (!pkg.name) add('name', 'block', '缺少 name 字段', '')
|
|
1948
|
+
else add('name', 'pass', '包名', String(pkg.name))
|
|
1949
|
+
if (!semverCore(pkg.version)) add('version', 'block', 'version 不是 semver', String(pkg.version || ''))
|
|
1950
|
+
else add('version', 'pass', '版本号', String(pkg.version))
|
|
1951
|
+
|
|
1952
|
+
const patchPath = pkg.dsh && pkg.dsh.bundle && pkg.dsh.bundle.patch ? pkg.dsh.bundle.patch : ''
|
|
1953
|
+
if (!patchPath) add('bundle.patch', 'block', '未声明 dsh.bundle.patch', '这不是一个 DSH bundle')
|
|
1954
|
+
else if (!(await exists(path.join(root, patchPath)))) add('bundle.patch', 'block', 'patch 文件不存在', patchPath)
|
|
1955
|
+
else add('bundle.patch', 'pass', 'bundle patch', patchPath)
|
|
1956
|
+
|
|
1957
|
+
// Bundles may declare the Host entry through exports instead of main.
|
|
1958
|
+
const dotExport = pkg.exports && typeof pkg.exports === 'object' ? pkg.exports['.'] : pkg.exports
|
|
1959
|
+
const mainEntry =
|
|
1960
|
+
typeof pkg.main === 'string' && pkg.main
|
|
1961
|
+
? pkg.main
|
|
1962
|
+
: typeof dotExport === 'string'
|
|
1963
|
+
? dotExport
|
|
1964
|
+
: dotExport && typeof dotExport === 'object' && typeof dotExport.default === 'string'
|
|
1965
|
+
? dotExport.default
|
|
1966
|
+
: ''
|
|
1967
|
+
if (mainEntry) {
|
|
1968
|
+
if (await exists(path.join(root, mainEntry))) add('entry', 'pass', '入口文件存在', mainEntry)
|
|
1969
|
+
else add('entry', 'block', '入口文件不存在', mainEntry)
|
|
1970
|
+
} else {
|
|
1971
|
+
add('entry', 'warn', '未声明 main 或 exports["."] 入口', '发布前确认 exports 指向真实文件')
|
|
1972
|
+
}
|
|
1973
|
+
|
|
1974
|
+
if (pkg.dsh && pkg.dsh.client) {
|
|
1975
|
+
const clientFile = typeof pkg.exports === 'object' && pkg.exports['./client'] ? pkg.exports['./client'] : './client.js'
|
|
1976
|
+
const resolved = typeof clientFile === 'string' ? clientFile : clientFile.default || ''
|
|
1977
|
+
if (resolved && (await exists(path.join(root, resolved)))) add('client', 'pass', '客户端入口存在', resolved)
|
|
1978
|
+
else add('client', 'block', 'dsh.client 声明的客户端入口不存在', resolved || '')
|
|
1979
|
+
}
|
|
1980
|
+
|
|
1981
|
+
for (const [file, level, title] of [
|
|
1982
|
+
['README.md', 'warn', '缺 README.md'],
|
|
1983
|
+
['LICENSE', 'warn', '缺 LICENSE'],
|
|
1984
|
+
['.gitignore', 'warn', '缺 .gitignore'],
|
|
1985
|
+
]) {
|
|
1986
|
+
if (!(await exists(path.join(root, file)))) add(file, level, title, '')
|
|
1987
|
+
}
|
|
1988
|
+
|
|
1989
|
+
const collected = await collectFiles(root, cfg.maxPushBytes)
|
|
1990
|
+
const secrets = findSecrets(collected.files)
|
|
1991
|
+
if (secrets.length) {
|
|
1992
|
+
add(
|
|
1993
|
+
'secrets',
|
|
1994
|
+
'block',
|
|
1995
|
+
`检出 ${secrets.length} 处疑似密钥`,
|
|
1996
|
+
secrets.slice(0, 5).map((hit) => `${hit.file}:${hit.line} ${hit.kind}`).join('; '),
|
|
1997
|
+
)
|
|
1998
|
+
} else {
|
|
1999
|
+
add('secrets', 'pass', '未检出疑似密钥', `扫描 ${collected.files.length} 个文件`)
|
|
2000
|
+
}
|
|
2001
|
+
|
|
2002
|
+
const hardPaths = []
|
|
2003
|
+
for (const file of collected.files) {
|
|
2004
|
+
if (!/\.(js|mjs|ts|json|md)$/.test(file.path)) continue
|
|
2005
|
+
const text = file.content.toString('utf8')
|
|
2006
|
+
const match = /[A-Za-z]:\\\\Users\\\\|[A-Za-z]:\\Users\\|\/Users\/[A-Za-z0-9._-]+\//.exec(text)
|
|
2007
|
+
if (match) hardPaths.push(file.path)
|
|
2008
|
+
}
|
|
2009
|
+
if (hardPaths.length) add('local-paths', 'warn', '代码里出现本机绝对路径', hardPaths.slice(0, 5).join(', '))
|
|
2010
|
+
|
|
2011
|
+
add('files', 'info', `待推送 ${collected.files.length} 个文件`, fmtBytes(collected.total) + (collected.skipped ? `(跳过 ${collected.skipped} 个大文件)` : ''))
|
|
2012
|
+
|
|
2013
|
+
if (gh) {
|
|
2014
|
+
try {
|
|
2015
|
+
const response = await fetch(`https://registry.npmjs.org/${encodeURIComponent(pkg.name)}`)
|
|
2016
|
+
if (response.status === 200) {
|
|
2017
|
+
const data = await response.json()
|
|
2018
|
+
const latest = data['dist-tags'] ? data['dist-tags'].latest : ''
|
|
2019
|
+
if (latest === pkg.version) {
|
|
2020
|
+
add('npm', 'block', 'npm 上已存在同名同版本', `${pkg.name}@${latest}`)
|
|
2021
|
+
} else {
|
|
2022
|
+
add('npm', 'info', 'npm 上已存在该包', `latest ${latest}`)
|
|
2023
|
+
}
|
|
2024
|
+
} else if (response.status === 404) {
|
|
2025
|
+
add('npm', 'pass', 'npm 上没有同名包', pkg.name)
|
|
2026
|
+
} else {
|
|
2027
|
+
add('npm', 'info', 'npm 查询未确认', `HTTP ${response.status}`)
|
|
2028
|
+
}
|
|
2029
|
+
} catch (error) {
|
|
2030
|
+
add('npm', 'info', 'npm 查询失败', errorMessage(error))
|
|
2031
|
+
}
|
|
2032
|
+
}
|
|
2033
|
+
|
|
2034
|
+
const ready = !checks.some((check) => check.level === 'block')
|
|
2035
|
+
return { dir: root, package: { name: pkg.name, version: pkg.version }, files: collected.files.length, checks, ready }
|
|
2036
|
+
}
|
|
2037
|
+
|
|
2038
|
+
async function ensureRepo(gh, owner, name) {
|
|
2039
|
+
try {
|
|
2040
|
+
const repo = await gh.call(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`)
|
|
2041
|
+
return repo
|
|
2042
|
+
} catch (error) {
|
|
2043
|
+
if (error.status === 404) {
|
|
2044
|
+
throw new GhError(
|
|
2045
|
+
404,
|
|
2046
|
+
'REPO_MISSING',
|
|
2047
|
+
`仓库 ${owner}/${name} 不存在或未授权给当前安装:先到 GitHub 建仓并把该仓库加入 App 的授权范围(https://github.com/new?name=${encodeURIComponent(name)})`,
|
|
2048
|
+
)
|
|
2049
|
+
}
|
|
2050
|
+
throw error
|
|
2051
|
+
}
|
|
2052
|
+
}
|
|
2053
|
+
|
|
2054
|
+
async function pushFiles(gh, owner, name, branch, files, message) {
|
|
2055
|
+
const repoPath = `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`
|
|
2056
|
+
const repo = repoPath
|
|
2057
|
+
const encodePath = (filePath) => String(filePath).split('/').map(encodeURIComponent).join('/')
|
|
2058
|
+
let baseCommitSha = null
|
|
2059
|
+
let baseTreeSha = null
|
|
2060
|
+
let bootstrapped = false
|
|
2061
|
+
let stage = 'read-ref'
|
|
2062
|
+
try {
|
|
2063
|
+
stage = 'read-ref'
|
|
2064
|
+
let ref = null
|
|
2065
|
+
try {
|
|
2066
|
+
ref = await gh.call(`${repo}/git/ref/heads/${encodeURIComponent(branch)}`)
|
|
2067
|
+
} catch (error) {
|
|
2068
|
+
// A missing branch answers 404; a repository with no commit at all answers
|
|
2069
|
+
// 409 "Git Repository is empty.". Both mean "no base to build on".
|
|
2070
|
+
const empty = error.status === 409 || /repository is empty/i.test(String(error.message || ''))
|
|
2071
|
+
if (error.status !== 404 && !empty) throw error
|
|
2072
|
+
if (empty) bootstrapped = true
|
|
2073
|
+
ref = null
|
|
2074
|
+
}
|
|
2075
|
+
baseCommitSha = ref && ref.object ? ref.object.sha : null
|
|
2076
|
+
|
|
2077
|
+
// The Git Data API refuses to create blobs in a repository without commits,
|
|
2078
|
+
// so seed one file through the contents API first and then build on it.
|
|
2079
|
+
if (!baseCommitSha && bootstrapped) {
|
|
2080
|
+
stage = 'bootstrap-empty-repo'
|
|
2081
|
+
const seed =
|
|
2082
|
+
files.find((file) => /^readme\.md$/i.test(file.path)) ||
|
|
2083
|
+
files.find((file) => /^\.gitignore$/i.test(file.path)) ||
|
|
2084
|
+
files[0] || { path: '.gitkeep', content: Buffer.from('') }
|
|
2085
|
+
await gh.call(`${repo}/contents/${encodePath(seed.path)}`, {
|
|
2086
|
+
method: 'PUT',
|
|
2087
|
+
body: { message: message || 'chore: initial commit', content: seed.content.toString('base64') },
|
|
2088
|
+
})
|
|
2089
|
+
stage = 'resync-after-bootstrap'
|
|
2090
|
+
const meta = await gh.call(repo)
|
|
2091
|
+
const defaultBranch = meta.default_branch || branch
|
|
2092
|
+
const seedRef = await gh.call(`${repo}/git/ref/heads/${encodeURIComponent(defaultBranch)}`)
|
|
2093
|
+
const seedSha = seedRef.object ? seedRef.object.sha : null
|
|
2094
|
+
if (!seedSha) throw new Error(`初始化后仍读不到 ${defaultBranch} 分支`)
|
|
2095
|
+
if (defaultBranch !== branch) {
|
|
2096
|
+
await gh.call(`${repo}/git/refs`, { method: 'POST', body: { ref: `refs/heads/${branch}`, sha: seedSha } })
|
|
2097
|
+
}
|
|
2098
|
+
baseCommitSha = seedSha
|
|
2099
|
+
const seedCommit = await gh.call(`${repo}/git/commits/${seedSha}`)
|
|
2100
|
+
baseTreeSha = seedCommit.tree ? seedCommit.tree.sha : null
|
|
2101
|
+
}
|
|
2102
|
+
|
|
2103
|
+
if (baseCommitSha && !baseTreeSha) {
|
|
2104
|
+
stage = 'read-base-commit'
|
|
2105
|
+
const base = await gh.call(`${repo}/git/commits/${baseCommitSha}`)
|
|
2106
|
+
baseTreeSha = base.tree ? base.tree.sha : null
|
|
2107
|
+
}
|
|
2108
|
+
|
|
2109
|
+
stage = 'create-blobs'
|
|
2110
|
+
const blobs = []
|
|
2111
|
+
for (const file of files) {
|
|
2112
|
+
const blob = await gh.call(`${repo}/git/blobs`, {
|
|
2113
|
+
method: 'POST',
|
|
2114
|
+
body: { content: file.content.toString('base64'), encoding: 'base64' },
|
|
2115
|
+
})
|
|
2116
|
+
blobs.push(blob.sha)
|
|
2117
|
+
}
|
|
2118
|
+
|
|
2119
|
+
stage = 'create-tree'
|
|
2120
|
+
const treeBody = {
|
|
2121
|
+
tree: files.map((file, index) => ({ path: file.path, mode: '100644', type: 'blob', sha: blobs[index] })),
|
|
2122
|
+
}
|
|
2123
|
+
if (baseTreeSha) treeBody.base_tree = baseTreeSha
|
|
2124
|
+
const tree = await gh.call(`${repo}/git/trees`, { method: 'POST', body: treeBody })
|
|
2125
|
+
|
|
2126
|
+
stage = 'create-commit'
|
|
2127
|
+
const commitBody = { message, tree: tree.sha }
|
|
2128
|
+
if (baseCommitSha) commitBody.parents = [baseCommitSha]
|
|
2129
|
+
const commit = await gh.call(`${repo}/git/commits`, { method: 'POST', body: commitBody })
|
|
2130
|
+
|
|
2131
|
+
stage = 'update-ref'
|
|
2132
|
+
if (baseCommitSha) {
|
|
2133
|
+
await gh.call(`${repo}/git/refs/heads/${encodeURIComponent(branch)}`, {
|
|
2134
|
+
method: 'PATCH',
|
|
2135
|
+
body: { sha: commit.sha, force: false },
|
|
2136
|
+
})
|
|
2137
|
+
} else {
|
|
2138
|
+
await gh.call(`${repo}/git/refs`, {
|
|
2139
|
+
method: 'POST',
|
|
2140
|
+
body: { ref: `refs/heads/${branch}`, sha: commit.sha },
|
|
2141
|
+
})
|
|
2142
|
+
}
|
|
2143
|
+
return { commit: commit.sha, files: files.length, branch, firstCommit: bootstrapped }
|
|
2144
|
+
} catch (error) {
|
|
2145
|
+
// Naming the failed stage turns "Git Repository is empty." into something
|
|
2146
|
+
// actionable instead of a single opaque message.
|
|
2147
|
+
throw new Error(`推送在「${stage}」阶段失败:${errorMessage(error)}`)
|
|
2148
|
+
}
|
|
2149
|
+
}
|
|
2150
|
+
|
|
2151
|
+
async function mergeTopics(gh, owner, name, topics) {
|
|
2152
|
+
const repo = `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`
|
|
2153
|
+
const current = await gh.call(`${repo}/topics`, { headers: { Accept: 'application/vnd.github+json' } })
|
|
2154
|
+
const existing = Array.isArray(current.names) ? current.names : []
|
|
2155
|
+
const merged = Array.from(new Set([...existing, ...topics].map((item) => String(item).toLowerCase())))
|
|
2156
|
+
// The topics endpoint replaces the whole set, so always send the union.
|
|
2157
|
+
const updated = await gh.call(`${repo}/topics`, {
|
|
2158
|
+
method: 'PUT',
|
|
2159
|
+
headers: { Accept: 'application/vnd.github+json' },
|
|
2160
|
+
body: { names: merged },
|
|
2161
|
+
})
|
|
2162
|
+
return { before: existing, after: Array.isArray(updated.names) ? updated.names : merged }
|
|
2163
|
+
}
|
|
2164
|
+
|
|
2165
|
+
async function createRelease(gh, owner, name, version, branch, notes) {
|
|
2166
|
+
const repo = `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`
|
|
2167
|
+
const tag = `v${version}`
|
|
2168
|
+
try {
|
|
2169
|
+
const release = await gh.call(`${repo}/releases/tags/${encodeURIComponent(tag)}`)
|
|
2170
|
+
return { skipped: true, tag, htmlUrl: release.html_url, reason: '该 tag 的 Release 已存在' }
|
|
2171
|
+
} catch (error) {
|
|
2172
|
+
if (error.status !== 404) throw error
|
|
2173
|
+
}
|
|
2174
|
+
const release = await gh.call(`${repo}/releases`, {
|
|
2175
|
+
method: 'POST',
|
|
2176
|
+
body: {
|
|
2177
|
+
tag_name: tag,
|
|
2178
|
+
target_commitish: branch,
|
|
2179
|
+
name: tag,
|
|
2180
|
+
body: notes || `Release ${tag}`,
|
|
2181
|
+
draft: false,
|
|
2182
|
+
prerelease: false,
|
|
2183
|
+
},
|
|
2184
|
+
})
|
|
2185
|
+
return { skipped: false, tag, htmlUrl: release.html_url }
|
|
2186
|
+
}
|
|
2187
|
+
|
|
2188
|
+
function publishWorkflowYaml() {
|
|
2189
|
+
// npm cannot attach a trusted publisher to a package that does not exist yet,
|
|
2190
|
+
// so this workflow also accepts an optional NPM_TOKEN secret for the very
|
|
2191
|
+
// first publish; after that, OIDC needs no secret at all.
|
|
2192
|
+
return `name: publish
|
|
2193
|
+
on:
|
|
2194
|
+
workflow_dispatch:
|
|
2195
|
+
inputs:
|
|
2196
|
+
dry_run:
|
|
2197
|
+
description: 'Run npm publish --dry-run'
|
|
2198
|
+
type: boolean
|
|
2199
|
+
default: false
|
|
2200
|
+
permissions:
|
|
2201
|
+
contents: read
|
|
2202
|
+
id-token: write
|
|
2203
|
+
concurrency:
|
|
2204
|
+
group: npm-publish
|
|
2205
|
+
cancel-in-progress: false
|
|
2206
|
+
jobs:
|
|
2207
|
+
publish:
|
|
2208
|
+
runs-on: ubuntu-latest
|
|
2209
|
+
steps:
|
|
2210
|
+
- uses: actions/checkout@v4
|
|
2211
|
+
- uses: actions/setup-node@v4
|
|
2212
|
+
with:
|
|
2213
|
+
node-version: '22'
|
|
2214
|
+
registry-url: 'https://registry.npmjs.org'
|
|
2215
|
+
- name: Ensure npm supports trusted publishing (needs >= 11.5.1)
|
|
2216
|
+
run: npm install -g npm@11 && npm --version
|
|
2217
|
+
- name: Show target
|
|
2218
|
+
run: node -e "const p=require('./package.json');console.log(p.name+'@'+p.version)"
|
|
2219
|
+
- name: Publish
|
|
2220
|
+
run: npm publish --provenance --access public \${{ inputs.dry_run && '--dry-run' || '' }}
|
|
2221
|
+
env:
|
|
2222
|
+
NODE_AUTH_TOKEN: \${{ secrets.NPM_TOKEN }}
|
|
2223
|
+
`
|
|
2224
|
+
}
|
|
2225
|
+
|
|
2226
|
+
const WORKFLOW_DIR = '.github/workflows'
|
|
2227
|
+
|
|
2228
|
+
/**
|
|
2229
|
+
* Minimal ustar writer plus gzip, so a release asset can be produced without
|
|
2230
|
+
* depending on a system tar or an npm install.
|
|
2231
|
+
*/
|
|
2232
|
+
function buildTarball(files, prefix = 'package') {
|
|
2233
|
+
const blocks = []
|
|
2234
|
+
const header = (name, size, mtime) => {
|
|
2235
|
+
const buffer = Buffer.alloc(512)
|
|
2236
|
+
const write = (value, offset, length) => buffer.write(value.slice(0, length), offset, length, 'utf8')
|
|
2237
|
+
write(name, 0, 100)
|
|
2238
|
+
write(`${(0o644).toString(8)}\0`, 100, 8)
|
|
2239
|
+
write(`${(0).toString(8)}\0`, 108, 8)
|
|
2240
|
+
write(`${(0).toString(8)}\0`, 116, 8)
|
|
2241
|
+
write(`${size.toString(8)}\0`, 124, 12)
|
|
2242
|
+
write(`${Math.floor(mtime / 1000).toString(8)}\0`, 136, 12)
|
|
2243
|
+
write(' ', 148, 8)
|
|
2244
|
+
write('0', 156, 1)
|
|
2245
|
+
write('ustar\0', 257, 6)
|
|
2246
|
+
write('00', 263, 2)
|
|
2247
|
+
let sum = 0
|
|
2248
|
+
for (const byte of buffer) sum += byte
|
|
2249
|
+
write(`${sum.toString(8).padStart(6, '0')}\0 `, 148, 8)
|
|
2250
|
+
return buffer
|
|
2251
|
+
}
|
|
2252
|
+
const now = Date.now()
|
|
2253
|
+
for (const file of files) {
|
|
2254
|
+
// ustar splits long paths into prefix/name at a slash before byte 100.
|
|
2255
|
+
let name = `${prefix}/${file.path}`
|
|
2256
|
+
let tail = name
|
|
2257
|
+
if (Buffer.byteLength(name) > 100) {
|
|
2258
|
+
const slash = name.lastIndexOf('/', 155)
|
|
2259
|
+
if (slash > 0 && Buffer.byteLength(name.slice(slash + 1)) <= 100) {
|
|
2260
|
+
tail = name.slice(slash + 1)
|
|
2261
|
+
const dir = name.slice(0, slash)
|
|
2262
|
+
const buffer = Buffer.alloc(512)
|
|
2263
|
+
buffer.write(tail, 0, 100, 'utf8')
|
|
2264
|
+
buffer.write(`${(0o644).toString(8)}\0`, 100, 8)
|
|
2265
|
+
buffer.write('0000000\0', 108, 8)
|
|
2266
|
+
buffer.write('0000000\0', 116, 8)
|
|
2267
|
+
buffer.write(`${file.content.length.toString(8)}\0`, 124, 12)
|
|
2268
|
+
buffer.write(`${Math.floor(now / 1000).toString(8)}\0`, 136, 12)
|
|
2269
|
+
buffer.write(' ', 148, 8)
|
|
2270
|
+
buffer.write('0', 156, 1)
|
|
2271
|
+
buffer.write('ustar\0', 257, 6)
|
|
2272
|
+
buffer.write('00', 263, 2)
|
|
2273
|
+
buffer.write(dir, 345, Math.min(155, Buffer.byteLength(dir)))
|
|
2274
|
+
let sum = 0
|
|
2275
|
+
for (const byte of buffer) sum += byte
|
|
2276
|
+
buffer.write(`${sum.toString(8).padStart(6, '0')}\0 `, 148, 8)
|
|
2277
|
+
blocks.push(buffer)
|
|
2278
|
+
blocks.push(file.content)
|
|
2279
|
+
const pad = (512 - (file.content.length % 512)) % 512
|
|
2280
|
+
if (pad) blocks.push(Buffer.alloc(pad))
|
|
2281
|
+
continue
|
|
2282
|
+
}
|
|
2283
|
+
}
|
|
2284
|
+
blocks.push(header(name, file.content.length, now))
|
|
2285
|
+
blocks.push(file.content)
|
|
2286
|
+
const pad = (512 - (file.content.length % 512)) % 512
|
|
2287
|
+
if (pad) blocks.push(Buffer.alloc(pad))
|
|
2288
|
+
}
|
|
2289
|
+
blocks.push(Buffer.alloc(1024))
|
|
2290
|
+
return zlib.gzipSync(Buffer.concat(blocks), { level: 9 })
|
|
2291
|
+
}
|
|
2292
|
+
|
|
2293
|
+
async function attachReleaseAsset(gh, owner, repo, version, fileName, buffer) {
|
|
2294
|
+
const repoPath = `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`
|
|
2295
|
+
const tag = `v${version}`
|
|
2296
|
+
let release = await gh.call(`${repoPath}/releases/tags/${encodeURIComponent(tag)}`).catch(() => null)
|
|
2297
|
+
if (!release) return { uploaded: false, reason: `Release ${tag} 还不存在:先发布一次` }
|
|
2298
|
+
const upload = async (name) => {
|
|
2299
|
+
const assets = Array.isArray(release.assets) ? release.assets : []
|
|
2300
|
+
const existing = assets.find((asset) => asset.name === name)
|
|
2301
|
+
if (existing) {
|
|
2302
|
+
await gh.call(`${repoPath}/releases/assets/${existing.id}`, { method: 'DELETE' }).catch(() => {})
|
|
2303
|
+
}
|
|
2304
|
+
return gh.call(
|
|
2305
|
+
`https://uploads.github.com/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/releases/${release.id}/assets?name=${encodeURIComponent(name)}`,
|
|
2306
|
+
{
|
|
2307
|
+
method: 'POST',
|
|
2308
|
+
rawBody: true,
|
|
2309
|
+
headers: { 'Content-Type': 'application/gzip', Accept: 'application/vnd.github+json' },
|
|
2310
|
+
body: buffer,
|
|
2311
|
+
},
|
|
2312
|
+
)
|
|
2313
|
+
}
|
|
2314
|
+
const uploaded = await upload(fileName)
|
|
2315
|
+
// A version-free duplicate keeps releases/latest/download/<name> alive: the
|
|
2316
|
+
// storefront list warns that a versioned name rots on the next release.
|
|
2317
|
+
let versionFree = null
|
|
2318
|
+
const versionFreeName = fileName.replace(new RegExp(`-${version.replace(/\./g, '\\.')}(?=\\.tgz$)`), '')
|
|
2319
|
+
if (versionFreeName !== fileName) {
|
|
2320
|
+
versionFree = await upload(versionFreeName).catch(() => null)
|
|
2321
|
+
}
|
|
2322
|
+
return {
|
|
2323
|
+
uploaded: true,
|
|
2324
|
+
id: uploaded.id,
|
|
2325
|
+
name: uploaded.name,
|
|
2326
|
+
size: uploaded.size,
|
|
2327
|
+
url: uploaded.browser_download_url,
|
|
2328
|
+
tag,
|
|
2329
|
+
versionFreeName: versionFree ? versionFree.name : '',
|
|
2330
|
+
versionFreeUrl: versionFree ? versionFree.browser_download_url : '',
|
|
2331
|
+
}
|
|
2332
|
+
}
|
|
2333
|
+
|
|
2334
|
+
/** Preconditions the awesome-dsh-plugin list checks before a PR can merge. */
|
|
2335
|
+
async function marketReadiness(gh, cfg, { owner, repo, dir }) {
|
|
2336
|
+
const checks = []
|
|
2337
|
+
const add = (id, level, title, detail) => checks.push({ id, level, title, detail: detail || '' })
|
|
2338
|
+
const repoPath = `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`
|
|
2339
|
+
const meta = await gh.call(repoPath).catch(() => null)
|
|
2340
|
+
|
|
2341
|
+
if (!meta) {
|
|
2342
|
+
add('repo', 'block', '读不到仓库信息', `${owner}/${repo}`)
|
|
2343
|
+
return { ready: false, checks }
|
|
2344
|
+
}
|
|
2345
|
+
const created = meta.created_at ? Date.parse(meta.created_at) : 0
|
|
2346
|
+
const ageHours = created ? (Date.now() - created) / 3600000 : 0
|
|
2347
|
+
add('repo-age', ageHours >= 24 ? 'pass' : 'block', '仓库年龄 ≥ 1 天', `${ageHours.toFixed(1)} 小时`)
|
|
2348
|
+
|
|
2349
|
+
let pkg = null
|
|
2350
|
+
try {
|
|
2351
|
+
pkg = await readLocalPackage(dir)
|
|
2352
|
+
} catch (error) {
|
|
2353
|
+
add('package', 'block', '本地 package.json 读不到', errorMessage(error))
|
|
2354
|
+
}
|
|
2355
|
+
if (pkg) {
|
|
2356
|
+
const hasBundle = Boolean(pkg.dsh && pkg.dsh.bundle && pkg.dsh.bundle.patch)
|
|
2357
|
+
add('dsh.bundle', hasBundle ? 'pass' : 'block', 'package.json 声明 dsh.bundle', hasBundle ? pkg.dsh.bundle.patch : '只声明 dsh.client 会在这条失败')
|
|
2358
|
+
const officialDeps = Object.keys(pkg.dependencies || {}).filter((name) => name.startsWith('@deepseek-ai/'))
|
|
2359
|
+
add(
|
|
2360
|
+
'peer-deps',
|
|
2361
|
+
officialDeps.length === 0 ? 'pass' : 'block',
|
|
2362
|
+
'@deepseek-ai/* 用 peerDependencies 而不是 dependencies',
|
|
2363
|
+
officialDeps.join(', '),
|
|
2364
|
+
)
|
|
2365
|
+
}
|
|
2366
|
+
|
|
2367
|
+
const iconCandidates = ['assets/icon-512.png', 'assets/icon-180.png', 'icon.png', 'assets/icon.png']
|
|
2368
|
+
let iconPath = ''
|
|
2369
|
+
for (const candidate of iconCandidates) {
|
|
2370
|
+
const file = await repoFile(gh, owner, repo, candidate, cfg.publishBranch).catch(() => null)
|
|
2371
|
+
if (file) {
|
|
2372
|
+
iconPath = candidate
|
|
2373
|
+
break
|
|
2374
|
+
}
|
|
2375
|
+
}
|
|
2376
|
+
add('icon', iconPath ? 'pass' : 'block', '仓库里有 GitHub 托管的 PNG 图标', iconPath || '列表拒收 SVG 与第三方图床')
|
|
2377
|
+
|
|
2378
|
+
const latest = await gh.call(`${repoPath}/releases/latest`).catch(() => null)
|
|
2379
|
+
const assets = latest && Array.isArray(latest.assets) ? latest.assets : []
|
|
2380
|
+
const versionFree = assets.find((asset) => /\.tgz$/i.test(asset.name) && !/\d+\.\d+\.\d+/.test(asset.name))
|
|
2381
|
+
add(
|
|
2382
|
+
'tarball',
|
|
2383
|
+
versionFree ? 'pass' : 'block',
|
|
2384
|
+
'最新 Release 有不带版本号的 .tgz',
|
|
2385
|
+
versionFree ? versionFree.name : 'releases/latest/download/<固定名>.tgz 才能在每次发版后继续可用',
|
|
2386
|
+
)
|
|
2387
|
+
|
|
2388
|
+
let readme = ''
|
|
2389
|
+
try {
|
|
2390
|
+
readme = await fs.readFile(path.join(dir, 'README.md'), 'utf8')
|
|
2391
|
+
} catch {
|
|
2392
|
+
readme = ''
|
|
2393
|
+
}
|
|
2394
|
+
const bilingual = /[\u4e00-\u9fff]/.test(readme) && /[A-Za-z]{4,}/.test(readme)
|
|
2395
|
+
add('readme', bilingual ? 'pass' : 'warn', 'README 中英双语(列表条目也是双语)', bilingual ? '' : 'README 里至少要有中英两种文字')
|
|
2396
|
+
|
|
2397
|
+
add('screenshots', 'info', '截图可选', '想控制展示顺序就在仓库放 screenshots.json(1-8 张,路径不能跳出插件目录)')
|
|
2398
|
+
add('category', 'info', '分类建议', 'Git & Code Review(条目里写 category: git)')
|
|
2399
|
+
|
|
2400
|
+
const ready = !checks.some((check) => check.level === 'block')
|
|
2401
|
+
return {
|
|
2402
|
+
ready,
|
|
2403
|
+
checks,
|
|
2404
|
+
entry: {
|
|
2405
|
+
url: `https://github.com/${owner}/${repo}`,
|
|
2406
|
+
name: `${owner}/${repo}`,
|
|
2407
|
+
category: 'git',
|
|
2408
|
+
icon: iconPath ? `https://raw.githubusercontent.com/${owner}/${repo}/${cfg.publishBranch}/${iconPath}` : '',
|
|
2409
|
+
tarball: versionFree ? `https://github.com/${owner}/${repo}/releases/latest/download/${versionFree.name}` : '',
|
|
2410
|
+
},
|
|
2411
|
+
}
|
|
2412
|
+
}
|
|
2413
|
+
|
|
2414
|
+
async function repoFile(gh, owner, repo, filePath, ref) {
|
|
2415
|
+
try {
|
|
2416
|
+
return await gh.readFile(owner, repo, filePath, ref)
|
|
2417
|
+
} catch (error) {
|
|
2418
|
+
if (error.status === 404) return null
|
|
2419
|
+
throw error
|
|
2420
|
+
}
|
|
2421
|
+
}
|
|
2422
|
+
|
|
2423
|
+
async function ensurePublishWorkflow(gh, owner, repo, branch, workflowFile) {
|
|
2424
|
+
const filePath = `${WORKFLOW_DIR}/${workflowFile}`
|
|
2425
|
+
const desired = publishWorkflowYaml()
|
|
2426
|
+
const existing = await repoFile(gh, owner, repo, filePath, branch)
|
|
2427
|
+
if (existing && String(existing.text).trim() === desired.trim()) {
|
|
2428
|
+
return { path: filePath, changed: false }
|
|
2429
|
+
}
|
|
2430
|
+
await gh.writeFile(
|
|
2431
|
+
owner,
|
|
2432
|
+
repo,
|
|
2433
|
+
filePath,
|
|
2434
|
+
desired,
|
|
2435
|
+
existing ? 'ci: update npm publish workflow' : 'ci: add npm publish workflow',
|
|
2436
|
+
existing ? existing.sha : undefined,
|
|
2437
|
+
branch,
|
|
2438
|
+
)
|
|
2439
|
+
return { path: filePath, changed: true }
|
|
2440
|
+
}
|
|
2441
|
+
|
|
2442
|
+
async function dispatchWorkflow(gh, owner, repo, workflowFile, ref, inputs) {
|
|
2443
|
+
const body = inputs && Object.keys(inputs).length ? { ref, inputs } : { ref }
|
|
2444
|
+
await gh.call(
|
|
2445
|
+
`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/actions/workflows/${encodeURIComponent(workflowFile)}/dispatches`,
|
|
2446
|
+
{ method: 'POST', body },
|
|
2447
|
+
)
|
|
2448
|
+
}
|
|
2449
|
+
|
|
2450
|
+
async function waitForWorkflowRun(gh, owner, repo, workflowFile, sinceMs, timeoutMs) {
|
|
2451
|
+
const repoPath = `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`
|
|
2452
|
+
const deadline = Date.now() + timeoutMs
|
|
2453
|
+
let last = null
|
|
2454
|
+
while (Date.now() < deadline) {
|
|
2455
|
+
const data = await gh
|
|
2456
|
+
.call(`${repoPath}/actions/workflows/${encodeURIComponent(workflowFile)}/runs?event=workflow_dispatch&per_page=5`)
|
|
2457
|
+
.catch(() => null)
|
|
2458
|
+
const run = data && Array.isArray(data.workflow_runs) ? data.workflow_runs[0] : null
|
|
2459
|
+
if (run && Date.parse(run.created_at) >= sinceMs - 15000) {
|
|
2460
|
+
last = {
|
|
2461
|
+
id: run.id,
|
|
2462
|
+
status: run.status,
|
|
2463
|
+
conclusion: run.conclusion || null,
|
|
2464
|
+
url: run.html_url,
|
|
2465
|
+
createdAt: run.created_at,
|
|
2466
|
+
}
|
|
2467
|
+
if (run.status === 'completed') return last
|
|
2468
|
+
}
|
|
2469
|
+
await new Promise((resolve) => setTimeout(resolve, 3000))
|
|
2470
|
+
}
|
|
2471
|
+
return last ? { ...last, status: 'timeout' } : { status: 'unknown', url: null }
|
|
2472
|
+
}
|
|
2473
|
+
|
|
2474
|
+
function marketIndexDocument({ pkg, owner, repo, commit, entryTitle, entryDescription }) {
|
|
2475
|
+
const repositoryUrl = `https://github.com/${owner}/${repo}`
|
|
2476
|
+
const engines =
|
|
2477
|
+
pkg.engines && typeof pkg.engines.dsh === 'string' && pkg.engines.dsh.trim() && !pkg.engines.dsh.startsWith('workspace:')
|
|
2478
|
+
? { dsh: pkg.engines.dsh.trim() }
|
|
2479
|
+
: {}
|
|
2480
|
+
const plugin = {
|
|
2481
|
+
name: pkg.name,
|
|
2482
|
+
title: entryTitle || pkg.name,
|
|
2483
|
+
description: entryDescription || pkg.description || pkg.name,
|
|
2484
|
+
// Resolved against the index URL, so the icon ships with the repository.
|
|
2485
|
+
icon: '../icon.svg',
|
|
2486
|
+
author: owner,
|
|
2487
|
+
repository: { url: repositoryUrl },
|
|
2488
|
+
metadata: {
|
|
2489
|
+
keywords: Array.isArray(pkg.keywords) ? pkg.keywords.filter((item) => typeof item === 'string').slice(0, 20) : [],
|
|
2490
|
+
},
|
|
2491
|
+
versions: [
|
|
2492
|
+
{
|
|
2493
|
+
version: pkg.version,
|
|
2494
|
+
publishTimestamp: Math.floor(Date.now() / 1000),
|
|
2495
|
+
source: { type: 'git', url: repositoryUrl, commit },
|
|
2496
|
+
engines,
|
|
2497
|
+
},
|
|
2498
|
+
],
|
|
2499
|
+
}
|
|
2500
|
+
if (pkg.homepage && /^https?:\/\//.test(pkg.homepage)) plugin.homepage = pkg.homepage
|
|
2501
|
+
return {
|
|
2502
|
+
format: 1,
|
|
2503
|
+
title: `${owner} DSH plugin index`,
|
|
2504
|
+
description: 'Self-hosted DSH plugin index generated by the GitHub console.',
|
|
2505
|
+
metadata: {},
|
|
2506
|
+
plugins: [plugin],
|
|
2507
|
+
}
|
|
2508
|
+
}
|
|
2509
|
+
|
|
2510
|
+
async function readLocalPackage(dir) {
|
|
2511
|
+
const raw = await fs.readFile(path.join(dir, 'package.json'), 'utf8')
|
|
2512
|
+
const pkg = JSON.parse(raw)
|
|
2513
|
+
if (!pkg.name || !pkg.version) throw new Error('package.json 缺少 name 或 version')
|
|
2514
|
+
return pkg
|
|
2515
|
+
}
|
|
2516
|
+
|
|
2517
|
+
async function npmPublishState(gh, cfg, { owner, repo, dir }) {
|
|
2518
|
+
// The registry answers whether a first publish is still needed; the workflow
|
|
2519
|
+
// file tells whether the automation is already in the repository.
|
|
2520
|
+
let pkg = null
|
|
2521
|
+
try {
|
|
2522
|
+
pkg = await readLocalPackage(dir)
|
|
2523
|
+
} catch {
|
|
2524
|
+
pkg = null
|
|
2525
|
+
}
|
|
2526
|
+
const name = pkg ? pkg.name : ''
|
|
2527
|
+
let exists = null
|
|
2528
|
+
if (name) {
|
|
2529
|
+
try {
|
|
2530
|
+
const response = await fetch(`https://registry.npmjs.org/${encodeURIComponent(name)}`, {
|
|
2531
|
+
headers: { 'User-Agent': `dsh-github-console/${PLUGIN_VERSION}` },
|
|
2532
|
+
})
|
|
2533
|
+
exists = response.status === 200
|
|
2534
|
+
} catch {
|
|
2535
|
+
exists = null
|
|
2536
|
+
}
|
|
2537
|
+
}
|
|
2538
|
+
const workflowPath = `${WORKFLOW_DIR}/${cfg.npmWorkflow}`
|
|
2539
|
+
const workflow = owner && repo ? await repoFile(gh, owner, repo, workflowPath, cfg.publishBranch).catch(() => null) : null
|
|
2540
|
+
const workflowPresent = Boolean(workflow)
|
|
2541
|
+
const phase = !name ? 'unknown' : exists === true ? (workflowPresent ? 'ready' : 'needs-workflow') : 'needs-first-publish'
|
|
2542
|
+
return {
|
|
2543
|
+
name,
|
|
2544
|
+
version: pkg ? pkg.version : '',
|
|
2545
|
+
registryHasPackage: exists,
|
|
2546
|
+
workflowPath,
|
|
2547
|
+
workflowPresent,
|
|
2548
|
+
phase,
|
|
2549
|
+
urls: {
|
|
2550
|
+
package: name ? `https://www.npmjs.com/package/${name}` : '',
|
|
2551
|
+
trustedPublisher: name ? `https://www.npmjs.com/package/${name}/access` : '',
|
|
2552
|
+
secrets: owner && repo ? `https://github.com/${owner}/${repo}/settings/secrets/actions/new` : '',
|
|
2553
|
+
// /settings/~tokens is a 404; the token list lives under the npm user name.
|
|
2554
|
+
tokens: cfg.npmUser ? `https://www.npmjs.com/settings/${cfg.npmUser}/tokens` : 'https://www.npmjs.com/settings/',
|
|
2555
|
+
workflow: owner && repo ? `https://github.com/${owner}/${repo}/blob/${cfg.publishBranch}/${workflowPath}` : '',
|
|
2556
|
+
},
|
|
2557
|
+
trustedPublisherValues: {
|
|
2558
|
+
provider: 'GitHub Actions',
|
|
2559
|
+
userOrOrg: owner || '',
|
|
2560
|
+
repository: repo || '',
|
|
2561
|
+
workflowFile: cfg.npmWorkflow,
|
|
2562
|
+
allowedAction: 'npm publish',
|
|
2563
|
+
},
|
|
2564
|
+
steps:
|
|
2565
|
+
phase === 'needs-first-publish'
|
|
2566
|
+
? [
|
|
2567
|
+
'打开下面的 npm 链接,Token name 填 dsh-github-console-ci(唯一的必填项)。',
|
|
2568
|
+
'勾上 Bypass two-factor authentication (2FA)——这是第二处需要你点的。',
|
|
2569
|
+
'其余保持默认(下表),点 Generate token 后立刻复制。',
|
|
2570
|
+
'打开 GitHub 的 Secrets 页面,Name 用 NPM_TOKEN,值粘贴 token,Add secret。',
|
|
2571
|
+
'回到这里点「生成 workflow 并触发发布」。',
|
|
2572
|
+
]
|
|
2573
|
+
: phase === 'ready'
|
|
2574
|
+
? [
|
|
2575
|
+
'包已经在 npm 上:打开该包的 Settings → Trusted Publisher,按下面五个值填一次(Provider 选 GitHub Actions)。',
|
|
2576
|
+
'注意 48 小时窗口:配好信任后要在 48 小时内跑一次发布,否则要重新配置。',
|
|
2577
|
+
'回到这里点「生成 workflow 并触发发布」。运行里会先把 npm 升到 11(可信发布要求 ≥ 11.5.1),再以 OIDC 身份发布,不再需要任何 token。',
|
|
2578
|
+
]
|
|
2579
|
+
: ['先在 npm 上发一次这个包(本机没有 npm),或添加 NPM_TOKEN 后再触发。'],
|
|
2580
|
+
// Mirrors the real form field by field, so the user compares instead of guessing.
|
|
2581
|
+
fields: [
|
|
2582
|
+
{ label: 'Token name', value: 'dsh-github-console-ci', note: '必填,只有这里需要你输入' },
|
|
2583
|
+
{ label: 'Description', value: '(可留空)', note: '' },
|
|
2584
|
+
{ label: 'Bypass two-factor authentication (2FA)', value: '勾上', note: '第二处需要你点的:CI 里没人能输 OTP' },
|
|
2585
|
+
{ label: 'Allowed IP ranges', value: '留空', note: 'Actions 出口 IP 不固定' },
|
|
2586
|
+
{ label: 'Permissions', value: 'Read and write (publish and stage)', note: '不要选 stage only' },
|
|
2587
|
+
{ label: 'Select packages', value: 'All packages', note: '新包还不存在,只有它能覆盖未来创建的包' },
|
|
2588
|
+
{ label: 'Organizations → Permissions', value: 'No access', note: '' },
|
|
2589
|
+
{ label: 'Expiration Date', value: '7 days(默认)', note: '最长 90 天;发完就撤销' },
|
|
2590
|
+
],
|
|
2591
|
+
}
|
|
2592
|
+
}
|
|
2593
|
+
|
|
2594
|
+
function unzipEntries(buffer) {
|
|
2595
|
+
// GitHub log archives use data descriptors, so sizes come from the central
|
|
2596
|
+
// directory rather than the local header. Minimal deflate-only reader.
|
|
2597
|
+
const entries = []
|
|
2598
|
+
let eocd = -1
|
|
2599
|
+
for (let i = buffer.length - 22; i >= Math.max(0, buffer.length - 70000); i--) {
|
|
2600
|
+
if (buffer.readUInt32LE(i) === 0x06054b50) {
|
|
2601
|
+
eocd = i
|
|
2602
|
+
break
|
|
2603
|
+
}
|
|
2604
|
+
}
|
|
2605
|
+
const read = (offset, nameLength, extraLength) => {
|
|
2606
|
+
const method = buffer.readUInt16LE(offset + 10)
|
|
2607
|
+
const compressed = buffer.readUInt32LE(offset + 20)
|
|
2608
|
+
const name = buffer.subarray(offset + 46, offset + 46 + nameLength).toString('utf8')
|
|
2609
|
+
const localOffset = buffer.readUInt32LE(offset + 42)
|
|
2610
|
+
const localNameLength = buffer.readUInt16LE(localOffset + 26)
|
|
2611
|
+
const localExtraLength = buffer.readUInt16LE(localOffset + 28)
|
|
2612
|
+
const dataStart = localOffset + 30 + localNameLength + localExtraLength
|
|
2613
|
+
const data = buffer.subarray(dataStart, dataStart + compressed)
|
|
2614
|
+
let text = ''
|
|
2615
|
+
try {
|
|
2616
|
+
text = method === 0 ? data.toString('utf8') : zlib.inflateRawSync(data).toString('utf8')
|
|
2617
|
+
} catch {
|
|
2618
|
+
text = ''
|
|
2619
|
+
}
|
|
2620
|
+
entries.push({ name, text })
|
|
2621
|
+
void extraLength
|
|
2622
|
+
}
|
|
2623
|
+
if (eocd >= 0) {
|
|
2624
|
+
const count = buffer.readUInt16LE(eocd + 10)
|
|
2625
|
+
let offset = buffer.readUInt32LE(eocd + 16)
|
|
2626
|
+
for (let index = 0; index < count; index++) {
|
|
2627
|
+
if (buffer.readUInt32LE(offset) !== 0x02014b50) break
|
|
2628
|
+
const nameLength = buffer.readUInt16LE(offset + 28)
|
|
2629
|
+
const extraLength = buffer.readUInt16LE(offset + 30)
|
|
2630
|
+
const commentLength = buffer.readUInt16LE(offset + 32)
|
|
2631
|
+
read(offset, nameLength, extraLength)
|
|
2632
|
+
offset += 46 + nameLength + extraLength + commentLength
|
|
2633
|
+
}
|
|
2634
|
+
if (entries.length) return entries
|
|
2635
|
+
}
|
|
2636
|
+
// Fallback: walk local headers (works when sizes are present).
|
|
2637
|
+
let offset = 0
|
|
2638
|
+
while (offset + 30 <= buffer.length) {
|
|
2639
|
+
if (buffer.readUInt32LE(offset) !== 0x04034b50) break
|
|
2640
|
+
const method = buffer.readUInt16LE(offset + 8)
|
|
2641
|
+
const compressed = buffer.readUInt32LE(offset + 18)
|
|
2642
|
+
const nameLength = buffer.readUInt16LE(offset + 26)
|
|
2643
|
+
const extraLength = buffer.readUInt16LE(offset + 28)
|
|
2644
|
+
const name = buffer.subarray(offset + 30, offset + 30 + nameLength).toString('utf8')
|
|
2645
|
+
const dataStart = offset + 30 + nameLength + extraLength
|
|
2646
|
+
const data = buffer.subarray(dataStart, dataStart + compressed)
|
|
2647
|
+
let text = ''
|
|
2648
|
+
try {
|
|
2649
|
+
text = method === 0 ? data.toString('utf8') : zlib.inflateRawSync(data).toString('utf8')
|
|
2650
|
+
} catch {
|
|
2651
|
+
text = ''
|
|
2652
|
+
}
|
|
2653
|
+
entries.push({ name, text })
|
|
2654
|
+
offset = dataStart + compressed
|
|
2655
|
+
}
|
|
2656
|
+
return entries
|
|
2657
|
+
}
|
|
2658
|
+
|
|
2659
|
+
async function probeMarket(input, gh, cfg) {
|
|
2660
|
+
const checkedAt = new Date().toISOString()
|
|
2661
|
+
const results = []
|
|
2662
|
+
const push = (id, state, detail, extra = {}) => results.push({ id, state, detail, checkedAt, ...extra })
|
|
2663
|
+
|
|
2664
|
+
// 1. npm package presence
|
|
2665
|
+
try {
|
|
2666
|
+
const response = await fetch(`https://registry.npmjs.org/${encodeURIComponent(input.name)}/latest`)
|
|
2667
|
+
if (response.status === 200) {
|
|
2668
|
+
const data = await response.json()
|
|
2669
|
+
push('npm', 'listed', `${input.name}@${data.version}`, { version: data.version })
|
|
2670
|
+
} else if (response.status === 404) {
|
|
2671
|
+
push('npm', 'absent', 'npm 上没有这个包名')
|
|
2672
|
+
} else {
|
|
2673
|
+
push('npm', 'unknown', `npm 返回 HTTP ${response.status}`)
|
|
2674
|
+
}
|
|
2675
|
+
} catch (error) {
|
|
2676
|
+
push('npm', 'unknown', `npm 探测失败:${errorMessage(error)}`)
|
|
2677
|
+
}
|
|
2678
|
+
|
|
2679
|
+
// 2. GitHub side: release tag and the topic crawlers look for
|
|
2680
|
+
if (gh && input.owner && input.repo) {
|
|
2681
|
+
try {
|
|
2682
|
+
const repo = `/repos/${encodeURIComponent(input.owner)}/${encodeURIComponent(input.repo)}`
|
|
2683
|
+
const meta = await gh.call(`${repo}`)
|
|
2684
|
+
const topics = Array.isArray(meta.topics) ? meta.topics : []
|
|
2685
|
+
push(
|
|
2686
|
+
'github-topic',
|
|
2687
|
+
topics.includes(cfg.topic) ? 'listed' : 'absent',
|
|
2688
|
+
topics.includes(cfg.topic) ? `已带 ${cfg.topic} topic` : `缺少 ${cfg.topic} topic`,
|
|
2689
|
+
{ topics },
|
|
2690
|
+
)
|
|
2691
|
+
} catch (error) {
|
|
2692
|
+
push('github-topic', 'unknown', `仓库信息读取失败:${errorMessage(error)}`)
|
|
2693
|
+
}
|
|
2694
|
+
if (input.version) {
|
|
2695
|
+
try {
|
|
2696
|
+
const repo = `/repos/${encodeURIComponent(input.owner)}/${encodeURIComponent(input.repo)}`
|
|
2697
|
+
const release = await gh.call(`${repo}/releases/tags/${encodeURIComponent(`v${input.version}`)}`)
|
|
2698
|
+
push('github-release', 'listed', `v${input.version}`, { htmlUrl: release.html_url })
|
|
2699
|
+
} catch (error) {
|
|
2700
|
+
push(
|
|
2701
|
+
'github-release',
|
|
2702
|
+
error.status === 404 ? 'absent' : 'unknown',
|
|
2703
|
+
error.status === 404 ? `没有 v${input.version} 的 Release` : errorMessage(error),
|
|
2704
|
+
)
|
|
2705
|
+
}
|
|
2706
|
+
} else {
|
|
2707
|
+
push('github-release', 'unknown', '未提供版本号,已跳过 Release 探测')
|
|
2708
|
+
}
|
|
2709
|
+
} else {
|
|
2710
|
+
push('github-topic', 'unknown', '未提供 owner/repo,已跳过 GitHub 侧探测')
|
|
2711
|
+
push('github-release', 'unknown', '未提供 owner/repo,已跳过 GitHub 侧探测')
|
|
2712
|
+
}
|
|
2713
|
+
|
|
2714
|
+
// 3. Configured market indexes (format 1 JSON with an items/plugins array)
|
|
2715
|
+
for (const url of cfg.marketIndexUrls) {
|
|
2716
|
+
try {
|
|
2717
|
+
const response = await fetch(url)
|
|
2718
|
+
if (!response.ok) {
|
|
2719
|
+
push(`index:${url}`, 'unknown', `HTTP ${response.status}`)
|
|
2720
|
+
continue
|
|
2721
|
+
}
|
|
2722
|
+
const text = await response.text()
|
|
2723
|
+
const found = text.includes(`"${input.name}"`) || text.includes(`"${input.name}@`)
|
|
2724
|
+
push(`index:${url}`, found ? 'listed' : 'absent', found ? '索引里出现该包名' : '索引里没有该包名')
|
|
2725
|
+
} catch (error) {
|
|
2726
|
+
push(`index:${url}`, 'unknown', `索引探测失败:${errorMessage(error)}`)
|
|
2727
|
+
}
|
|
2728
|
+
}
|
|
2729
|
+
|
|
2730
|
+
return {
|
|
2731
|
+
input,
|
|
2732
|
+
results,
|
|
2733
|
+
// A failed probe is never reported as "absent": crawlers lag 1-2 days.
|
|
2734
|
+
summary: results.some((item) => item.state === 'listed')
|
|
2735
|
+
? 'listed'
|
|
2736
|
+
: results.some((item) => item.state === 'unknown')
|
|
2737
|
+
? 'unknown'
|
|
2738
|
+
: 'absent',
|
|
2739
|
+
}
|
|
2740
|
+
}
|
|
2741
|
+
|
|
2742
|
+
/* ------------------------------------------------------------------ */
|
|
2743
|
+
/* Jobs (publish state machine with resumable steps) */
|
|
2744
|
+
/* ------------------------------------------------------------------ */
|
|
2745
|
+
|
|
2746
|
+
function createJobStore() {
|
|
2747
|
+
const jobs = new Map()
|
|
2748
|
+
const order = []
|
|
2749
|
+
function create(meta) {
|
|
2750
|
+
const id = crypto.randomBytes(6).toString('hex')
|
|
2751
|
+
const job = {
|
|
2752
|
+
id,
|
|
2753
|
+
createdAt: new Date().toISOString(),
|
|
2754
|
+
finishedAt: null,
|
|
2755
|
+
ok: null,
|
|
2756
|
+
target: meta,
|
|
2757
|
+
steps: [
|
|
2758
|
+
{ id: 'preflight', title: '体检', state: 'pending', detail: '' },
|
|
2759
|
+
{ id: 'repo', title: '确认仓库', state: 'pending', detail: '' },
|
|
2760
|
+
{ id: 'push', title: '推送文件', state: 'pending', detail: '' },
|
|
2761
|
+
{ id: 'topics', title: '设置 topic', state: 'pending', detail: '' },
|
|
2762
|
+
{ id: 'release', title: '创建 Release', state: 'pending', detail: '' },
|
|
2763
|
+
{ id: 'market', title: '市场探测', state: 'pending', detail: '' },
|
|
2764
|
+
],
|
|
2765
|
+
}
|
|
2766
|
+
jobs.set(id, job)
|
|
2767
|
+
order.push(id)
|
|
2768
|
+
while (order.length > 20) {
|
|
2769
|
+
const oldest = order.shift()
|
|
2770
|
+
if (oldest && jobs.get(oldest) && jobs.get(oldest).finishedAt) jobs.delete(oldest)
|
|
2771
|
+
}
|
|
2772
|
+
return job
|
|
2773
|
+
}
|
|
2774
|
+
return {
|
|
2775
|
+
create,
|
|
2776
|
+
get: (id) => jobs.get(id),
|
|
2777
|
+
list: () => order.filter((id) => jobs.has(id)).map((id) => jobs.get(id)),
|
|
2778
|
+
}
|
|
2779
|
+
}
|
|
2780
|
+
|
|
2781
|
+
function step(job, id) {
|
|
2782
|
+
return job.steps.find((item) => item.id === id)
|
|
2783
|
+
}
|
|
2784
|
+
|
|
2785
|
+
async function runPublish({ job, gh, cfg, dir, owner, repo, version, notes, opts }) {
|
|
2786
|
+
const finish = (ok) => {
|
|
2787
|
+
job.ok = ok
|
|
2788
|
+
job.finishedAt = new Date().toISOString()
|
|
2789
|
+
return job
|
|
2790
|
+
}
|
|
2791
|
+
|
|
2792
|
+
const report = await preflight(dir, gh, cfg)
|
|
2793
|
+
step(job, 'preflight').state = report.ready ? 'done' : 'failed'
|
|
2794
|
+
step(job, 'preflight').detail = report.ready
|
|
2795
|
+
? `${report.files} 个文件通过`
|
|
2796
|
+
: report.checks.filter((check) => check.level === 'block').map((check) => check.title).join(';')
|
|
2797
|
+
job.preflight = report
|
|
2798
|
+
if (!report.ready) return finish(false)
|
|
2799
|
+
|
|
2800
|
+
const pkgName = report.package ? report.package.name : ''
|
|
2801
|
+
const semver = version || (report.package ? report.package.version : '')
|
|
2802
|
+
if (!owner || !repo) {
|
|
2803
|
+
step(job, 'repo').state = 'failed'
|
|
2804
|
+
step(job, 'repo').detail = '缺少 owner/repo'
|
|
2805
|
+
return finish(false)
|
|
2806
|
+
}
|
|
2807
|
+
|
|
2808
|
+
try {
|
|
2809
|
+
const meta = await ensureRepo(gh, owner, repo)
|
|
2810
|
+
step(job, 'repo').state = 'done'
|
|
2811
|
+
step(job, 'repo').detail = `${owner}/${repo}(默认分支 ${meta.default_branch || 'main'})`
|
|
2812
|
+
} catch (error) {
|
|
2813
|
+
step(job, 'repo').state = 'failed'
|
|
2814
|
+
step(job, 'repo').detail = errorMessage(error)
|
|
2815
|
+
return finish(false)
|
|
2816
|
+
}
|
|
2817
|
+
|
|
2818
|
+
const branch = opts.branch || cfg.publishBranch
|
|
2819
|
+
try {
|
|
2820
|
+
const collected = await collectFiles(path.resolve(dir), cfg.maxPushBytes)
|
|
2821
|
+
const pushed = await pushFiles(gh, owner, repo, branch, collected.files, opts.message || `chore(release): v${semver}`)
|
|
2822
|
+
step(job, 'push').state = 'done'
|
|
2823
|
+
step(job, 'push').detail = `${pushed.files} 个文件 → ${branch} @ ${pushed.commit.slice(0, 7)}${pushed.firstCommit ? '(仓库原本为空,这是首个提交)' : ''}`
|
|
2824
|
+
job.commit = pushed.commit
|
|
2825
|
+
} catch (error) {
|
|
2826
|
+
step(job, 'push').state = 'failed'
|
|
2827
|
+
step(job, 'push').detail = errorMessage(error)
|
|
2828
|
+
return finish(false)
|
|
2829
|
+
}
|
|
2830
|
+
|
|
2831
|
+
try {
|
|
2832
|
+
const topics = await mergeTopics(gh, owner, repo, [cfg.topic])
|
|
2833
|
+
step(job, 'topics').state = 'done'
|
|
2834
|
+
step(job, 'topics').detail = topics.after.join(', ')
|
|
2835
|
+
} catch (error) {
|
|
2836
|
+
step(job, 'topics').state = 'failed'
|
|
2837
|
+
step(job, 'topics').detail = `${errorMessage(error)}(需 Administration: write)`
|
|
2838
|
+
}
|
|
2839
|
+
|
|
2840
|
+
try {
|
|
2841
|
+
const release = await createRelease(gh, owner, repo, semver, branch, notes)
|
|
2842
|
+
step(job, 'release').state = 'done'
|
|
2843
|
+
step(job, 'release').detail = release.skipped ? `${release.tag} 已存在,跳过` : `${release.tag} 已创建`
|
|
2844
|
+
job.releaseUrl = release.htmlUrl || null
|
|
2845
|
+
} catch (error) {
|
|
2846
|
+
step(job, 'release').state = 'failed'
|
|
2847
|
+
step(job, 'release').detail = errorMessage(error)
|
|
2848
|
+
}
|
|
2849
|
+
|
|
2850
|
+
try {
|
|
2851
|
+
const probe = await probeMarket({ name: pkgName, owner, repo, version: semver }, gh, cfg)
|
|
2852
|
+
step(job, 'market').state = 'done'
|
|
2853
|
+
step(job, 'market').detail = probe.results.map((item) => `${item.id}:${item.state}`).join(' · ')
|
|
2854
|
+
job.market = probe
|
|
2855
|
+
} catch (error) {
|
|
2856
|
+
step(job, 'market').state = 'failed'
|
|
2857
|
+
step(job, 'market').detail = errorMessage(error)
|
|
2858
|
+
}
|
|
2859
|
+
|
|
2860
|
+
const failed = job.steps.some((item) => item.state === 'failed')
|
|
2861
|
+
return finish(!failed)
|
|
2862
|
+
}
|
|
2863
|
+
|
|
2864
|
+
/* ------------------------------------------------------------------ */
|
|
2865
|
+
/* Plugin */
|
|
2866
|
+
/* ------------------------------------------------------------------ */
|
|
2867
|
+
|
|
2868
|
+
export const inject = ['tools']
|
|
2869
|
+
|
|
2870
|
+
export function apply(ctx, rawConfig) {
|
|
2871
|
+
const cfg = normalizeConfig(rawConfig)
|
|
2872
|
+
const transport = createTransport(cfg)
|
|
2873
|
+
const gh = createGithub(ctx, cfg, transport)
|
|
2874
|
+
const jobs = createJobStore()
|
|
2875
|
+
let bridgeToken = ''
|
|
2876
|
+
let webAttached = false
|
|
2877
|
+
|
|
2878
|
+
// Relative plugin directories resolve against the calling session's working
|
|
2879
|
+
// directory, then the deployment default; the profile directory is not a
|
|
2880
|
+
// useful base for a user's plugin checkout.
|
|
2881
|
+
const sessionBase = (exec) => {
|
|
2882
|
+
const workingDirectory = ctx.get('workingDirectory')
|
|
2883
|
+
if (workingDirectory) {
|
|
2884
|
+
const session = exec && exec.agent ? exec.agent.session : undefined
|
|
2885
|
+
if (session) {
|
|
2886
|
+
try {
|
|
2887
|
+
const directory = workingDirectory.get(session)
|
|
2888
|
+
if (typeof directory === 'string' && directory) return directory
|
|
2889
|
+
} catch {
|
|
2890
|
+
/* fall through */
|
|
2891
|
+
}
|
|
2892
|
+
}
|
|
2893
|
+
if (typeof workingDirectory.defaultDirectory === 'string' && workingDirectory.defaultDirectory) {
|
|
2894
|
+
return workingDirectory.defaultDirectory
|
|
2895
|
+
}
|
|
2896
|
+
}
|
|
2897
|
+
return process.cwd()
|
|
2898
|
+
}
|
|
2899
|
+
|
|
2900
|
+
const resolveDir = (dir, exec) => {
|
|
2901
|
+
if (!dir) throw new Error('需要插件目录 dir')
|
|
2902
|
+
return path.isAbsolute(dir) ? path.normalize(dir) : path.resolve(sessionBase(exec), dir)
|
|
2903
|
+
}
|
|
2904
|
+
|
|
2905
|
+
// Discovery must run before any sign-in: the panel shows local candidates and
|
|
2906
|
+
// an offline report first, and asks for GitHub only when the user publishes.
|
|
2907
|
+
// Project directories the user actually works in are the useful roots here;
|
|
2908
|
+
// the profile directory only holds installed links.
|
|
2909
|
+
const discoveryRoots = (extra) => {
|
|
2910
|
+
const roots = []
|
|
2911
|
+
const add = (value) => {
|
|
2912
|
+
if (typeof value !== 'string' || !value) return
|
|
2913
|
+
const normalized = path.normalize(value)
|
|
2914
|
+
if (!roots.includes(normalized)) roots.push(normalized)
|
|
2915
|
+
}
|
|
2916
|
+
add(extra)
|
|
2917
|
+
const registry = ctx.get('workspaceRegistry')
|
|
2918
|
+
if (registry && typeof registry.list === 'function') {
|
|
2919
|
+
try {
|
|
2920
|
+
for (const workspace of registry.list()) {
|
|
2921
|
+
if (!workspace) continue
|
|
2922
|
+
const directory =
|
|
2923
|
+
typeof workspace.directory === 'string'
|
|
2924
|
+
? workspace.directory
|
|
2925
|
+
: typeof workspace.getDirectory === 'function'
|
|
2926
|
+
? workspace.getDirectory()
|
|
2927
|
+
: typeof workspace.path === 'string'
|
|
2928
|
+
? workspace.path
|
|
2929
|
+
: ''
|
|
2930
|
+
add(directory)
|
|
2931
|
+
}
|
|
2932
|
+
} catch {
|
|
2933
|
+
/* a registry that cannot list is not fatal for discovery */
|
|
2934
|
+
}
|
|
2935
|
+
}
|
|
2936
|
+
const workingDirectory = ctx.get('workingDirectory')
|
|
2937
|
+
if (workingDirectory && typeof workingDirectory.defaultDirectory === 'string') {
|
|
2938
|
+
add(workingDirectory.defaultDirectory)
|
|
2939
|
+
}
|
|
2940
|
+
add(process.cwd())
|
|
2941
|
+
return roots
|
|
2942
|
+
}
|
|
2943
|
+
|
|
2944
|
+
const discover = (extra) => discoverPlugins(discoveryRoots(extra))
|
|
2945
|
+
|
|
2946
|
+
// Every mutating path records who did what, so a console leaves a trail.
|
|
2947
|
+
const audited = async (action, target, run) => {
|
|
2948
|
+
const started = Date.now()
|
|
2949
|
+
try {
|
|
2950
|
+
const result = await run()
|
|
2951
|
+
await appendAudit({ action, target, ok: true, ms: Date.now() - started })
|
|
2952
|
+
return result
|
|
2953
|
+
} catch (error) {
|
|
2954
|
+
await appendAudit({ action, target, ok: false, detail: errorMessage(error).slice(0, 300), ms: Date.now() - started })
|
|
2955
|
+
throw error
|
|
2956
|
+
}
|
|
2957
|
+
}
|
|
2958
|
+
|
|
2959
|
+
// Write actions are refused up front when the active connection cannot write.
|
|
2960
|
+
const requireWrite = async (capability = 'repoWrite') => {
|
|
2961
|
+
if (cfg.readOnly) throw new Error('只读模式已开启(配置 readOnly: true),写操作已禁用')
|
|
2962
|
+
const auth = await gh.resolveAuth()
|
|
2963
|
+
const capabilities = gh.capabilitiesOf(auth)
|
|
2964
|
+
if (!capabilities[capability]) {
|
|
2965
|
+
throw new Error(
|
|
2966
|
+
`当前连接(${auth.kind})没有 ${capability} 权限:到「状态 → 连接方式」换一个带写权限的连接,或给 App 补权限`,
|
|
2967
|
+
)
|
|
2968
|
+
}
|
|
2969
|
+
return auth
|
|
2970
|
+
}
|
|
2971
|
+
|
|
2972
|
+
async function withToken() {
|
|
2973
|
+
if (!bridgeToken) {
|
|
2974
|
+
const credentials = await gh.waitForCredentials()
|
|
2975
|
+
if (!credentials) return crypto.randomBytes(32).toString('hex')
|
|
2976
|
+
const record = await credentials.readRecord(BRIDGE_CRED).catch(() => undefined)
|
|
2977
|
+
const saved = record && record.payload && typeof record.payload.token === 'string' ? record.payload.token : ''
|
|
2978
|
+
if (saved.length >= 32) return saved
|
|
2979
|
+
const token = crypto.randomBytes(32).toString('hex')
|
|
2980
|
+
await credentials.modifyRecord(BRIDGE_CRED, async () => ({ kind: 'grant', payload: { token } }))
|
|
2981
|
+
return token
|
|
2982
|
+
}
|
|
2983
|
+
return bridgeToken
|
|
2984
|
+
}
|
|
2985
|
+
|
|
2986
|
+
const tokenPromise = withToken()
|
|
2987
|
+
.then((token) => {
|
|
2988
|
+
bridgeToken = token
|
|
2989
|
+
return token
|
|
2990
|
+
})
|
|
2991
|
+
.catch(() => '')
|
|
2992
|
+
|
|
2993
|
+
const bridgeInfo = () => ({ base: '', token: bridgeToken, setup: `${PREFIX}/setup` })
|
|
2994
|
+
const bridgeStatus = () => ({
|
|
2995
|
+
webAttached,
|
|
2996
|
+
tokenPersisted: bridgeToken.length >= 32,
|
|
2997
|
+
routes: [`${PREFIX}/setup`, `${PREFIX}/callback`, `${PREFIX}/api/*`],
|
|
2998
|
+
})
|
|
2999
|
+
|
|
3000
|
+
/* ---------------- HTTP surface ---------------- */
|
|
3001
|
+
|
|
3002
|
+
async function handleSetup(request, response) {
|
|
3003
|
+
const state = gh.beginManifest()
|
|
3004
|
+
const origin = requestOrigin(request)
|
|
3005
|
+
const manifest = buildManifestFor(origin)
|
|
3006
|
+
const action = `https://github.com/settings/apps/new?state=${encodeURIComponent(state)}`
|
|
3007
|
+
const html = `<!doctype html><meta charset="utf-8"><title>注册 GitHub App</title>
|
|
3008
|
+
<body style="font-family:system-ui,-apple-system,'Segoe UI',sans-serif;background:#f6f7f9;margin:0;padding:48px 16px">
|
|
3009
|
+
<div style="max-width:560px;margin:0 auto;background:#fff;border:1px solid #e3e6ea;border-radius:12px;padding:26px 30px">
|
|
3010
|
+
<h2 style="margin:0 0 10px;font-size:19px">正在跳转到 GitHub 创建 App</h2>
|
|
3011
|
+
<p style="color:#57606a;font-size:13px;line-height:1.7">GitHub 页面上只需点一次 <b>Create GitHub App</b>,回调地址已预填为 <code>${escapeHtml(origin + PREFIX + '/callback')}</code>。若页面没有自动跳转,点下面的按钮。</p>
|
|
3012
|
+
<form id="dgh-form" method="post" action="${escapeHtml(action)}">
|
|
3013
|
+
<input type="hidden" name="manifest" value="${escapeHtml(JSON.stringify(manifest))}">
|
|
3014
|
+
<button type="submit" style="margin-top:16px;padding:9px 18px;border:0;border-radius:8px;background:#3E6FD8;color:#fff;font-size:14px;cursor:pointer">打开 GitHub 创建页</button>
|
|
3015
|
+
</form>
|
|
3016
|
+
<script>document.getElementById('dgh-form').submit()</script>
|
|
3017
|
+
</div></body>`
|
|
3018
|
+
response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' })
|
|
3019
|
+
response.end(html)
|
|
3020
|
+
}
|
|
3021
|
+
|
|
3022
|
+
function buildManifestFor(origin) {
|
|
3023
|
+
const suffix = crypto.randomBytes(3).toString('hex')
|
|
3024
|
+
return {
|
|
3025
|
+
name: cfg.appName || `DSH GitHub Console ${suffix}`,
|
|
3026
|
+
url: 'https://github.com/deepseek-ai/deepseek-harness',
|
|
3027
|
+
description: 'DeepSeek Harness GitHub console: repository tools and plugin publishing.',
|
|
3028
|
+
redirect_url: `${origin}${PREFIX}/callback`,
|
|
3029
|
+
public: false,
|
|
3030
|
+
request_oauth_on_install: false,
|
|
3031
|
+
default_permissions: {
|
|
3032
|
+
metadata: 'read',
|
|
3033
|
+
contents: 'write',
|
|
3034
|
+
administration: 'write',
|
|
3035
|
+
pull_requests: 'write',
|
|
3036
|
+
issues: 'write',
|
|
3037
|
+
actions: 'write',
|
|
3038
|
+
workflows: 'write',
|
|
3039
|
+
},
|
|
3040
|
+
default_events: [],
|
|
3041
|
+
}
|
|
3042
|
+
}
|
|
3043
|
+
|
|
3044
|
+
async function handleCallback(request, response, url) {
|
|
3045
|
+
const code = url.searchParams.get('code')
|
|
3046
|
+
const state = url.searchParams.get('state')
|
|
3047
|
+
const error = url.searchParams.get('error')
|
|
3048
|
+
if (error || !code) {
|
|
3049
|
+
sendHtml(response, 400, '注册中断', error || '没有收到 code,请回到侧栏重新发起注册。')
|
|
3050
|
+
return
|
|
3051
|
+
}
|
|
3052
|
+
try {
|
|
3053
|
+
const result = await gh.completeManifest(code, state)
|
|
3054
|
+
const installUrl = result.slug ? `https://github.com/apps/${result.slug}/installations/new` : 'https://github.com/apps'
|
|
3055
|
+
sendHtml(
|
|
3056
|
+
response,
|
|
3057
|
+
200,
|
|
3058
|
+
'GitHub App 已创建',
|
|
3059
|
+
'私钥已写入 DSH 凭据服务。下一步把 App 安装到你的账号或组织,安装完成后回到 DSH 侧栏。',
|
|
3060
|
+
`<p style="margin:14px 0 0"><a href="${escapeHtml(installUrl)}" style="display:inline-block;padding:8px 16px;border-radius:8px;background:#3E6FD8;color:#fff;text-decoration:none;font-size:13px">安装 App</a></p>` +
|
|
3061
|
+
`<p style="color:#8c959f;font-size:12px;margin-top:12px">App ID ${escapeHtml(result.appId)}</p>`,
|
|
3062
|
+
)
|
|
3063
|
+
} catch (failure) {
|
|
3064
|
+
sendHtml(response, 400, '换取 App 凭据失败', errorMessage(failure))
|
|
3065
|
+
}
|
|
3066
|
+
}
|
|
3067
|
+
|
|
3068
|
+
// One click instead of "Settings → Plugins → market sources → paste": the
|
|
3069
|
+
// plugin-market service owns that list, and it is reachable from the Host.
|
|
3070
|
+
function webOrigin() {
|
|
3071
|
+
const webServer = ctx.get('webServer')
|
|
3072
|
+
if (webServer && typeof webServer.getOrigin === 'function') {
|
|
3073
|
+
try {
|
|
3074
|
+
return String(webServer.getOrigin()).replace(/\/+$/, '')
|
|
3075
|
+
} catch {
|
|
3076
|
+
/* not bound yet */
|
|
3077
|
+
}
|
|
3078
|
+
}
|
|
3079
|
+
return String(process.env.DSH_WEB_URL || '').replace(/\/+$/, '')
|
|
3080
|
+
}
|
|
3081
|
+
|
|
3082
|
+
async function attachIndexToMarket(input = {}) {
|
|
3083
|
+
const record = await gh.readRecord(INDEX_CRED).catch(() => undefined)
|
|
3084
|
+
if (!record || typeof record.body !== 'string') {
|
|
3085
|
+
return { attached: false, reason: '还没有生成市场索引:先在「市场」页点「生成 / 更新市场索引」' }
|
|
3086
|
+
}
|
|
3087
|
+
const origin = webOrigin()
|
|
3088
|
+
const url = input.url || (origin ? `${origin}${PREFIX}/market/index.json` : '')
|
|
3089
|
+
if (!url) {
|
|
3090
|
+
return { attached: false, reason: '拿不到本机 web 地址:请在参数里明确传 url' }
|
|
3091
|
+
}
|
|
3092
|
+
const service = ctx.get('pluginMarket')
|
|
3093
|
+
if (!service || typeof service.setIndexes !== 'function') {
|
|
3094
|
+
return {
|
|
3095
|
+
attached: false,
|
|
3096
|
+
url,
|
|
3097
|
+
reason: '当前 profile 没有挂载 plugin-market 服务(官方市场 bundle 未启用),无法自动写入市场源',
|
|
3098
|
+
manual: '设置 → 插件 → 发现 / 市场源 → 粘贴上面这个地址',
|
|
3099
|
+
}
|
|
3100
|
+
}
|
|
3101
|
+
try {
|
|
3102
|
+
const before = typeof service.listIndexes === 'function' ? await service.listIndexes() : []
|
|
3103
|
+
const urls = before
|
|
3104
|
+
.map((item) => (typeof item === 'string' ? item : item && item.url))
|
|
3105
|
+
.filter((item) => typeof item === 'string' && item)
|
|
3106
|
+
if (!urls.includes(url)) urls.push(url)
|
|
3107
|
+
await service.setIndexes(urls)
|
|
3108
|
+
const after = typeof service.listIndexes === 'function' ? await service.listIndexes() : urls
|
|
3109
|
+
// Read it back through the market service itself: this is what Discover
|
|
3110
|
+
// does, so a successful search proves the index is readable end to end.
|
|
3111
|
+
let verification = null
|
|
3112
|
+
if (typeof service.search === 'function') {
|
|
3113
|
+
try {
|
|
3114
|
+
const page = await service.search(url, { sort: { kind: 'index' }, offset: 0, limit: 5 })
|
|
3115
|
+
const entries = page && Array.isArray(page.entries) ? page.entries : []
|
|
3116
|
+
verification = {
|
|
3117
|
+
ok: true,
|
|
3118
|
+
total: page && typeof page.total === 'number' ? page.total : entries.length,
|
|
3119
|
+
indexTitle: page ? page.title : null,
|
|
3120
|
+
entries: entries.map((item) => ({
|
|
3121
|
+
name: item.name,
|
|
3122
|
+
defaultVersion: item.defaultVersion || null,
|
|
3123
|
+
status: item.installation ? item.installation.status : null,
|
|
3124
|
+
})),
|
|
3125
|
+
}
|
|
3126
|
+
} catch (failure) {
|
|
3127
|
+
verification = { ok: false, reason: errorMessage(failure) }
|
|
3128
|
+
}
|
|
3129
|
+
}
|
|
3130
|
+
return { attached: true, url, added: !before.some((item) => (item && item.url) === url), indexes: after, verification }
|
|
3131
|
+
} catch (failure) {
|
|
3132
|
+
return { attached: false, url, reason: errorMessage(failure), manual: '设置 → 插件 → 发现 / 市场源 → 粘贴上面这个地址' }
|
|
3133
|
+
}
|
|
3134
|
+
}
|
|
3135
|
+
|
|
3136
|
+
async function dispatchApi(request, response, url, body) {
|
|
3137
|
+
const route = `${request.method} ${url.pathname}`
|
|
3138
|
+
const args = body && typeof body === 'object' ? body : {}
|
|
3139
|
+
|
|
3140
|
+
if (route === 'POST /github-console/api/auth/device/start') {
|
|
3141
|
+
return sendJson(response, 200, await gh.deviceStart())
|
|
3142
|
+
}
|
|
3143
|
+
if (route === 'POST /github-console/api/auth/device/poll') {
|
|
3144
|
+
return sendJson(response, 200, await gh.devicePoll(args.deviceCode))
|
|
3145
|
+
}
|
|
3146
|
+
if (route === 'POST /github-console/api/auth/oauth/start') {
|
|
3147
|
+
return sendJson(response, 200, await gh.beginOAuth(requestOrigin(request)))
|
|
3148
|
+
}
|
|
3149
|
+
if (route === 'POST /github-console/api/auth/oauth/clear') {
|
|
3150
|
+
await gh.clearOAuth()
|
|
3151
|
+
await appendAudit({ action: 'auth.oauth-clear', account: '', ok: true })
|
|
3152
|
+
return sendJson(response, 200, { ok: true })
|
|
3153
|
+
}
|
|
3154
|
+
if (route === 'POST /github-console/api/auth/use') {
|
|
3155
|
+
const auth = await gh.useConnection(args.kind)
|
|
3156
|
+
await appendAudit({ action: 'auth.use', account: auth.account || auth.fingerprint || '', detail: args.kind })
|
|
3157
|
+
return sendJson(response, 200, { active: auth.kind, ok: true })
|
|
3158
|
+
}
|
|
3159
|
+
if (route === 'POST /github-console/api/auth/pat') {
|
|
3160
|
+
const result = await gh.setPat(args.token)
|
|
3161
|
+
await appendAudit({ action: 'auth.pat-set', account: result.login, detail: result.fingerprint })
|
|
3162
|
+
return sendJson(response, 200, { ok: true, login: result.login, fingerprint: result.fingerprint, scopes: result.scopes })
|
|
3163
|
+
}
|
|
3164
|
+
if (route === 'POST /github-console/api/auth/pat/clear') {
|
|
3165
|
+
await gh.clearPat()
|
|
3166
|
+
await appendAudit({ action: 'auth.pat-clear', account: '', detail: '' })
|
|
3167
|
+
return sendJson(response, 200, { ok: true })
|
|
3168
|
+
}
|
|
3169
|
+
if (route === 'POST /github-console/api/audit') {
|
|
3170
|
+
return sendJson(response, 200, { path: auditPath(), items: await readAudit(args.limit || 50) })
|
|
3171
|
+
}
|
|
3172
|
+
if (route === 'POST /github-console/api/status') {
|
|
3173
|
+
return sendJson(response, 200, { ...(await gh.status()), bridge: bridgeStatus() })
|
|
3174
|
+
}
|
|
3175
|
+
if (route === 'POST /github-console/api/auth/register') {
|
|
3176
|
+
// Re-registering throws away the current App (and its private key) and
|
|
3177
|
+
// drops the chosen installation, so require an explicit reset flag. The
|
|
3178
|
+
// panel otherwise offers the install page instead of a second App.
|
|
3179
|
+
const existing = await gh.appConfigured()
|
|
3180
|
+
if (existing && args.reset !== true) {
|
|
3181
|
+
return sendJson(response, 409, {
|
|
3182
|
+
error: '已经注册过 GitHub App:要沿用就打开安装页,确实要重来请用状态页的「重新注册」',
|
|
3183
|
+
code: 'APP_EXISTS',
|
|
3184
|
+
})
|
|
3185
|
+
}
|
|
3186
|
+
const origin = requestOrigin(request)
|
|
3187
|
+
const state = gh.beginManifest()
|
|
3188
|
+
return sendJson(response, 200, {
|
|
3189
|
+
setupUrl: `${origin}${PREFIX}/setup`,
|
|
3190
|
+
state,
|
|
3191
|
+
note: '打开 setupUrl 完成 GitHub 侧注册;回调成功后回到这里刷新',
|
|
3192
|
+
})
|
|
3193
|
+
}
|
|
3194
|
+
if (route === 'POST /github-console/api/auth/reset') {
|
|
3195
|
+
return sendJson(response, 200, await gh.resetApp())
|
|
3196
|
+
}
|
|
3197
|
+
if (route === 'POST /github-console/api/installations') {
|
|
3198
|
+
return sendJson(response, 200, { items: await gh.installations() })
|
|
3199
|
+
}
|
|
3200
|
+
if (route === 'POST /github-console/api/installations/select') {
|
|
3201
|
+
return sendJson(response, 200, await gh.selectInstallation(args.id))
|
|
3202
|
+
}
|
|
3203
|
+
if (route === 'POST /github-console/api/repos') {
|
|
3204
|
+
return sendJson(response, 200, await gh.listRepositories(args.q))
|
|
3205
|
+
}
|
|
3206
|
+
if (route === 'POST /github-console/api/tree') {
|
|
3207
|
+
return sendJson(response, 200, await gh.readTree(args.owner, args.name, args.ref))
|
|
3208
|
+
}
|
|
3209
|
+
if (route === 'POST /github-console/api/file/read') {
|
|
3210
|
+
return sendJson(response, 200, await gh.readFile(args.owner, args.name, args.path, args.ref))
|
|
3211
|
+
}
|
|
3212
|
+
if (route === 'POST /github-console/api/file/write') {
|
|
3213
|
+
await requireWrite('repoWrite')
|
|
3214
|
+
return sendJson(
|
|
3215
|
+
response,
|
|
3216
|
+
200,
|
|
3217
|
+
await audited('file.write', `${args.owner}/${args.name}:${args.path}`, () =>
|
|
3218
|
+
gh.writeFile(args.owner, args.name, args.path, args.text, args.message, args.sha, args.ref),
|
|
3219
|
+
),
|
|
3220
|
+
)
|
|
3221
|
+
}
|
|
3222
|
+
if (route === 'POST /github-console/api/pull/detail') {
|
|
3223
|
+
return sendJson(response, 200, await gh.pullDetail(args.owner, args.name, args.number))
|
|
3224
|
+
}
|
|
3225
|
+
if (route === 'POST /github-console/api/pull/comment') {
|
|
3226
|
+
await requireWrite('pullWrite')
|
|
3227
|
+
return sendJson(
|
|
3228
|
+
response,
|
|
3229
|
+
200,
|
|
3230
|
+
await audited('pull.comment', `${args.owner}/${args.name}#${args.number}`, () =>
|
|
3231
|
+
gh.addPullComment(args.owner, args.name, args.number, args.body, args.path ? { path: args.path, number: args.line } : null),
|
|
3232
|
+
),
|
|
3233
|
+
)
|
|
3234
|
+
}
|
|
3235
|
+
if (route === 'POST /github-console/api/pull/review') {
|
|
3236
|
+
await requireWrite('pullWrite')
|
|
3237
|
+
return sendJson(
|
|
3238
|
+
response,
|
|
3239
|
+
200,
|
|
3240
|
+
await audited('pull.review', `${args.owner}/${args.name}#${args.number} ${args.event}`, () =>
|
|
3241
|
+
gh.submitReview(args.owner, args.name, args.number, args.event, args.body),
|
|
3242
|
+
),
|
|
3243
|
+
)
|
|
3244
|
+
}
|
|
3245
|
+
if (route === 'POST /github-console/api/pull/merge') {
|
|
3246
|
+
await requireWrite('pullWrite')
|
|
3247
|
+
if (args.confirm !== true) return sendJson(response, 400, { error: '合并需要 confirm: true', code: 'INVALID' })
|
|
3248
|
+
return sendJson(
|
|
3249
|
+
response,
|
|
3250
|
+
200,
|
|
3251
|
+
await audited('pull.merge', `${args.owner}/${args.name}#${args.number} ${args.method || 'squash'}`, () =>
|
|
3252
|
+
gh.mergePull(args.owner, args.name, args.number, args.method),
|
|
3253
|
+
),
|
|
3254
|
+
)
|
|
3255
|
+
}
|
|
3256
|
+
if (route === 'POST /github-console/api/issue/update') {
|
|
3257
|
+
await requireWrite('issueWrite')
|
|
3258
|
+
const patch = {}
|
|
3259
|
+
for (const key of ['title', 'body', 'state', 'labels', 'assignees', 'milestone']) {
|
|
3260
|
+
if (args[key] !== undefined) patch[key] = args[key]
|
|
3261
|
+
}
|
|
3262
|
+
return sendJson(
|
|
3263
|
+
response,
|
|
3264
|
+
200,
|
|
3265
|
+
await audited('issue.update', `${args.owner}/${args.name}#${args.number}`, () =>
|
|
3266
|
+
gh.updateIssue(args.owner, args.name, args.number, patch),
|
|
3267
|
+
),
|
|
3268
|
+
)
|
|
3269
|
+
}
|
|
3270
|
+
if (route === 'POST /github-console/api/actions/log') {
|
|
3271
|
+
return sendJson(response, 200, await gh.runLog(args.owner, args.name, args.runId, args.tailLines || 120))
|
|
3272
|
+
}
|
|
3273
|
+
if (route === 'POST /github-console/api/workflows') {
|
|
3274
|
+
return sendJson(response, 200, await gh.listWorkflows(args.owner, args.name))
|
|
3275
|
+
}
|
|
3276
|
+
if (route === 'POST /github-console/api/workflows/dispatch') {
|
|
3277
|
+
await requireWrite('workflowsWrite')
|
|
3278
|
+
return sendJson(
|
|
3279
|
+
response,
|
|
3280
|
+
200,
|
|
3281
|
+
await audited('workflow.dispatch', `${args.owner}/${args.name}:${args.workflow}`, () =>
|
|
3282
|
+
gh.dispatchNamedWorkflow(args.owner, args.name, args.workflow, args.ref, args.inputs),
|
|
3283
|
+
),
|
|
3284
|
+
)
|
|
3285
|
+
}
|
|
3286
|
+
if (route === 'POST /github-console/api/issues') {
|
|
3287
|
+
return sendJson(response, 200, await gh.listIssues(args.owner, args.name, args.state))
|
|
3288
|
+
}
|
|
3289
|
+
if (route === 'POST /github-console/api/pulls') {
|
|
3290
|
+
return sendJson(response, 200, await gh.listPulls(args.owner, args.name, args.state))
|
|
3291
|
+
}
|
|
3292
|
+
if (route === 'POST /github-console/api/actions') {
|
|
3293
|
+
return sendJson(response, 200, await gh.listRuns(args.owner, args.name))
|
|
3294
|
+
}
|
|
3295
|
+
if (route === 'POST /github-console/api/release/asset') {
|
|
3296
|
+
const dir = resolveDir(args.dir)
|
|
3297
|
+
const pkg = await readLocalPackage(dir)
|
|
3298
|
+
const collected = await collectFiles(dir, cfg.maxPushBytes)
|
|
3299
|
+
const fileName =
|
|
3300
|
+
args.fileName || `${pkg.name.replace(/^@[^/]+\//, '')}-${pkg.version}.tgz`
|
|
3301
|
+
const asset = await attachReleaseAsset(
|
|
3302
|
+
gh,
|
|
3303
|
+
args.owner,
|
|
3304
|
+
args.repo,
|
|
3305
|
+
args.version || pkg.version,
|
|
3306
|
+
fileName,
|
|
3307
|
+
buildTarball(collected.files),
|
|
3308
|
+
)
|
|
3309
|
+
const ref = await gh
|
|
3310
|
+
.call(`/repos/${encodeURIComponent(args.owner)}/${encodeURIComponent(args.repo)}/git/ref/heads/${encodeURIComponent(cfg.publishBranch)}`)
|
|
3311
|
+
.catch(() => null)
|
|
3312
|
+
return sendJson(response, 200, {
|
|
3313
|
+
package: `${pkg.name}@${pkg.version}`,
|
|
3314
|
+
files: collected.files.length,
|
|
3315
|
+
asset,
|
|
3316
|
+
gitInstall: ref && ref.object ? `git+https://github.com/${args.owner}/${args.repo}.git#${ref.object.sha}` : '',
|
|
3317
|
+
})
|
|
3318
|
+
}
|
|
3319
|
+
if (route === 'POST /github-console/api/npm/status') {
|
|
3320
|
+
return sendJson(
|
|
3321
|
+
response,
|
|
3322
|
+
200,
|
|
3323
|
+
await npmPublishState(gh, cfg, {
|
|
3324
|
+
owner: args.owner,
|
|
3325
|
+
repo: args.repo,
|
|
3326
|
+
dir: resolveDir(args.dir),
|
|
3327
|
+
}),
|
|
3328
|
+
)
|
|
3329
|
+
}
|
|
3330
|
+
if (route === 'POST /github-console/api/market/readiness') {
|
|
3331
|
+
return sendJson(response, 200, await marketReadiness(gh, cfg, { owner: args.owner, repo: args.repo, dir: resolveDir(args.dir) }))
|
|
3332
|
+
}
|
|
3333
|
+
if (route === 'POST /github-console/api/market/attach') {
|
|
3334
|
+
return sendJson(
|
|
3335
|
+
response,
|
|
3336
|
+
200,
|
|
3337
|
+
await attachIndexToMarket({ url: args.url || `${requestOrigin(request)}${PREFIX}/market/index.json` }),
|
|
3338
|
+
)
|
|
3339
|
+
}
|
|
3340
|
+
if (route === 'POST /github-console/api/npm/prepare') {
|
|
3341
|
+
const pkg = await readLocalPackage(resolveDir(args.dir))
|
|
3342
|
+
const branch = args.branch || cfg.publishBranch
|
|
3343
|
+
const prepared = await ensurePublishWorkflow(gh, args.owner, args.repo, branch, cfg.npmWorkflow)
|
|
3344
|
+
return sendJson(response, 200, {
|
|
3345
|
+
...prepared,
|
|
3346
|
+
branch,
|
|
3347
|
+
package: `${pkg.name}@${pkg.version}`,
|
|
3348
|
+
hint:
|
|
3349
|
+
'首次发布前:到 npmjs.com 手动发一次该版本(或给仓库加 NPM_TOKEN secret);随后在包设置里把 Trusted Publisher 指向本仓库与本 workflow。',
|
|
3350
|
+
})
|
|
3351
|
+
}
|
|
3352
|
+
if (route === 'POST /github-console/api/npm/dispatch') {
|
|
3353
|
+
const since = Date.now()
|
|
3354
|
+
await dispatchWorkflow(gh, args.owner, args.repo, cfg.npmWorkflow, args.branch || cfg.publishBranch, args.dryRun ? { dry_run: 'true' } : undefined)
|
|
3355
|
+
const run = await waitForWorkflowRun(gh, args.owner, args.repo, cfg.npmWorkflow, since, cfg.npmPollSeconds * 1000)
|
|
3356
|
+
return sendJson(response, 200, { run })
|
|
3357
|
+
}
|
|
3358
|
+
if (route === 'POST /github-console/api/market/index') {
|
|
3359
|
+
const dir = resolveDir(args.dir)
|
|
3360
|
+
const pkg = await readLocalPackage(dir)
|
|
3361
|
+
const branch = args.branch || cfg.publishBranch
|
|
3362
|
+
const repoPath = `/repos/${encodeURIComponent(args.owner)}/${encodeURIComponent(args.repo)}`
|
|
3363
|
+
const ref = await gh.call(`${repoPath}/git/ref/heads/${encodeURIComponent(branch)}`)
|
|
3364
|
+
const commit = ref.object ? ref.object.sha : ''
|
|
3365
|
+
if (!commit) return sendJson(response, 400, { error: `读不到 ${branch} 的最新提交,请先发布一次` })
|
|
3366
|
+
const doc = marketIndexDocument({
|
|
3367
|
+
pkg,
|
|
3368
|
+
owner: args.owner,
|
|
3369
|
+
repo: args.repo,
|
|
3370
|
+
commit,
|
|
3371
|
+
entryTitle: args.title,
|
|
3372
|
+
entryDescription: args.description,
|
|
3373
|
+
})
|
|
3374
|
+
const existing = await repoFile(gh, args.owner, args.repo, cfg.marketIndexPath, branch)
|
|
3375
|
+
await gh.writeFile(
|
|
3376
|
+
args.owner,
|
|
3377
|
+
args.repo,
|
|
3378
|
+
cfg.marketIndexPath,
|
|
3379
|
+
JSON.stringify(doc, null, 2) + '\n',
|
|
3380
|
+
`chore: update market index for v${pkg.version}`,
|
|
3381
|
+
existing ? existing.sha : undefined,
|
|
3382
|
+
branch,
|
|
3383
|
+
)
|
|
3384
|
+
// Keep a copy locally so this machine can serve the index even when its
|
|
3385
|
+
// network cannot reach raw.githubusercontent.com.
|
|
3386
|
+
await gh
|
|
3387
|
+
.writeRecord(INDEX_CRED, { owner: args.owner, repo: args.repo, path: cfg.marketIndexPath, body: JSON.stringify(doc, null, 2) })
|
|
3388
|
+
.catch(() => {})
|
|
3389
|
+
return sendJson(response, 200, {
|
|
3390
|
+
url: `https://raw.githubusercontent.com/${args.owner}/${args.repo}/${branch}/${cfg.marketIndexPath}`,
|
|
3391
|
+
localUrl: `${PREFIX}/market/index.json`,
|
|
3392
|
+
commit,
|
|
3393
|
+
installSpec: `git+https://github.com/${args.owner}/${args.repo}.git#${commit}`,
|
|
3394
|
+
index: doc,
|
|
3395
|
+
})
|
|
3396
|
+
}
|
|
3397
|
+
if (route === 'POST /github-console/api/publish/preflight') {
|
|
3398
|
+
return sendJson(response, 200, await preflight(resolveDir(args.dir), gh, cfg))
|
|
3399
|
+
}
|
|
3400
|
+
if (route === 'POST /github-console/api/discover') {
|
|
3401
|
+
return sendJson(response, 200, await discover(args.root))
|
|
3402
|
+
}
|
|
3403
|
+
if (route === 'POST /github-console/api/publish/run') {
|
|
3404
|
+
await requireWrite('repoWrite')
|
|
3405
|
+
const dir = resolveDir(args.dir)
|
|
3406
|
+
const job = jobs.create({ dir, owner: args.owner, repo: args.repo })
|
|
3407
|
+
await appendAudit({ action: 'publish.run', target: `${args.owner}/${args.repo}`, ok: true })
|
|
3408
|
+
void runPublish({ job, gh, cfg, dir, owner: args.owner, repo: args.repo, version: args.version, notes: args.notes, opts: args })
|
|
3409
|
+
return sendJson(response, 200, { jobId: job.id })
|
|
3410
|
+
}
|
|
3411
|
+
if (route === 'POST /github-console/api/publish/job') {
|
|
3412
|
+
const job = jobs.get(args.jobId)
|
|
3413
|
+
if (!job) return sendJson(response, 404, { error: '没有这个任务' })
|
|
3414
|
+
return sendJson(response, 200, job)
|
|
3415
|
+
}
|
|
3416
|
+
if (route === 'POST /github-console/api/publish/jobs') {
|
|
3417
|
+
return sendJson(response, 200, { items: jobs.list() })
|
|
3418
|
+
}
|
|
3419
|
+
if (route === 'POST /github-console/api/market/probe') {
|
|
3420
|
+
return sendJson(
|
|
3421
|
+
response,
|
|
3422
|
+
200,
|
|
3423
|
+
await probeMarket(
|
|
3424
|
+
{ name: args.name, owner: args.owner, repo: args.repo, version: args.version },
|
|
3425
|
+
gh,
|
|
3426
|
+
cfg,
|
|
3427
|
+
),
|
|
3428
|
+
)
|
|
3429
|
+
}
|
|
3430
|
+
return sendJson(response, 404, { error: `no route for ${route}` })
|
|
3431
|
+
}
|
|
3432
|
+
|
|
3433
|
+
async function handlePanelHttp(request, response, url) {
|
|
3434
|
+
try {
|
|
3435
|
+
if (url.pathname === `${PREFIX}/setup`) {
|
|
3436
|
+
await handleSetup(request, response)
|
|
3437
|
+
return
|
|
3438
|
+
}
|
|
3439
|
+
if (url.pathname === `${PREFIX}/callback`) {
|
|
3440
|
+
await handleCallback(request, response, url)
|
|
3441
|
+
return
|
|
3442
|
+
}
|
|
3443
|
+
if (url.pathname === `${PREFIX}/oauth/callback`) {
|
|
3444
|
+
const code = url.searchParams.get('code')
|
|
3445
|
+
const state = url.searchParams.get('state')
|
|
3446
|
+
if (!code) {
|
|
3447
|
+
sendHtml(response, 400, '授权失败', url.searchParams.get('error_description') || '没有收到 code')
|
|
3448
|
+
return
|
|
3449
|
+
}
|
|
3450
|
+
try {
|
|
3451
|
+
await gh.completeOAuth(code, state, requestOrigin(request))
|
|
3452
|
+
await appendAudit({ action: 'auth.oauth', account: '', ok: true })
|
|
3453
|
+
sendHtml(response, 200, '已授权', 'App 的用户授权已保存,可以关闭此页面回到 DSH:现在可以读取通知与做代码搜索了。')
|
|
3454
|
+
} catch (failure) {
|
|
3455
|
+
sendHtml(response, 400, '授权未完成', errorMessage(failure))
|
|
3456
|
+
}
|
|
3457
|
+
return
|
|
3458
|
+
}
|
|
3459
|
+
if (url.pathname === `${PREFIX}/icon.svg`) {
|
|
3460
|
+
// The index references ../icon.svg relative to /github-console/market/index.json.
|
|
3461
|
+
const svg = await fs.readFile(path.join(PLUGIN_DIR, 'icon.svg')).catch(() => null)
|
|
3462
|
+
if (!svg) {
|
|
3463
|
+
sendJson(response, 404, { error: 'icon.svg 不存在' })
|
|
3464
|
+
return
|
|
3465
|
+
}
|
|
3466
|
+
response.writeHead(200, { 'Content-Type': 'image/svg+xml', 'Cache-Control': 'no-store' })
|
|
3467
|
+
response.end(svg)
|
|
3468
|
+
return
|
|
3469
|
+
}
|
|
3470
|
+
if (url.pathname === `${PREFIX}/market/index.json`) {
|
|
3471
|
+
// Anonymous by design: a market reader fetches its index without
|
|
3472
|
+
// credentials. Only the generated index document is served here.
|
|
3473
|
+
const record = await gh.readRecord(INDEX_CRED).catch(() => undefined)
|
|
3474
|
+
if (!record || typeof record.body !== 'string') {
|
|
3475
|
+
sendJson(response, 404, { error: '还没有生成市场索引:在面板「市场」页点「生成 / 更新市场索引」' })
|
|
3476
|
+
return
|
|
3477
|
+
}
|
|
3478
|
+
response.writeHead(200, {
|
|
3479
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
3480
|
+
'Cache-Control': 'no-store',
|
|
3481
|
+
})
|
|
3482
|
+
response.end(record.body)
|
|
3483
|
+
return
|
|
3484
|
+
}
|
|
3485
|
+
if (url.pathname.startsWith(`${PREFIX}/api/`)) {
|
|
3486
|
+
const expected = await tokenPromise
|
|
3487
|
+
if (!expected || bearerToken(request) !== expected) {
|
|
3488
|
+
sendJson(response, 401, { error: 'unauthorized' })
|
|
3489
|
+
return
|
|
3490
|
+
}
|
|
3491
|
+
const raw = request.method === 'POST' ? await readBody(request) : ''
|
|
3492
|
+
let body = {}
|
|
3493
|
+
if (raw) {
|
|
3494
|
+
try {
|
|
3495
|
+
body = JSON.parse(raw)
|
|
3496
|
+
} catch {
|
|
3497
|
+
sendJson(response, 400, { error: '请求体不是合法 JSON' })
|
|
3498
|
+
return
|
|
3499
|
+
}
|
|
3500
|
+
}
|
|
3501
|
+
await dispatchApi(request, response, url, body)
|
|
3502
|
+
return
|
|
3503
|
+
}
|
|
3504
|
+
sendJson(response, 404, { error: 'not found' })
|
|
3505
|
+
} catch (error) {
|
|
3506
|
+
// Keep the structured code: the panel maps it to a recovery action, and a
|
|
3507
|
+
// bare 500 would make 401/403/429/409 indistinguishable.
|
|
3508
|
+
const status = Number(error.status) >= 400 && Number(error.status) <= 599 ? Number(error.status) : 500
|
|
3509
|
+
sendJson(response, status, { error: errorMessage(error), code: error.code || 'INTERNAL' })
|
|
3510
|
+
}
|
|
3511
|
+
}
|
|
3512
|
+
|
|
3513
|
+
const attachWeb = (webServer) => {
|
|
3514
|
+
if (!webServer || webAttached) return
|
|
3515
|
+
webAttached = true
|
|
3516
|
+
if (typeof webServer.register === 'function') {
|
|
3517
|
+
ctx.effect(() =>
|
|
3518
|
+
webServer.register({
|
|
3519
|
+
kind: 'prefix',
|
|
3520
|
+
path: PREFIX,
|
|
3521
|
+
handler: (request, response) => handlePanelHttp(request, response, new URL(request.url || '/', 'http://127.0.0.1')),
|
|
3522
|
+
}),
|
|
3523
|
+
)
|
|
3524
|
+
}
|
|
3525
|
+
if (typeof webServer.tapIndex === 'function') {
|
|
3526
|
+
ctx.effect(() =>
|
|
3527
|
+
webServer.tapIndex((html) => {
|
|
3528
|
+
const payload = JSON.stringify(bridgeInfo()).replace(/</g, '\\u003c')
|
|
3529
|
+
const script = `<script>window.__DGH_BRIDGE__=${payload}</script>`
|
|
3530
|
+
return html.includes('</head>') ? html.replace('</head>', `${script}</head>`) : `${html}${script}`
|
|
3531
|
+
}),
|
|
3532
|
+
)
|
|
3533
|
+
}
|
|
3534
|
+
}
|
|
3535
|
+
|
|
3536
|
+
const existingWeb = ctx.get('webServer')
|
|
3537
|
+
if (existingWeb) attachWeb(existingWeb)
|
|
3538
|
+
else if (typeof ctx.inject === 'function') {
|
|
3539
|
+
ctx.effect(() =>
|
|
3540
|
+
ctx.inject(['webServer'], (scoped) => {
|
|
3541
|
+
attachWeb(scoped.webServer)
|
|
3542
|
+
}),
|
|
3543
|
+
)
|
|
3544
|
+
}
|
|
3545
|
+
|
|
3546
|
+
// The index-inject event is the documented way to publish a window global for
|
|
3547
|
+
// the client half; keep it as well because tapIndex is not always available.
|
|
3548
|
+
ctx.effect(() =>
|
|
3549
|
+
ctx.on('webserver/index-inject', (table) => {
|
|
3550
|
+
const info = bridgeInfo()
|
|
3551
|
+
if (info.token) table.push({ kind: 'global', name: '__DGH_BRIDGE__', value: info })
|
|
3552
|
+
}),
|
|
3553
|
+
)
|
|
3554
|
+
|
|
3555
|
+
/* ---------------- tools ---------------- */
|
|
3556
|
+
|
|
3557
|
+
const register = (definition) => ctx.effect(() => ctx.tools.register(definition))
|
|
3558
|
+
|
|
3559
|
+
register({
|
|
3560
|
+
name: 'gh_status',
|
|
3561
|
+
description:
|
|
3562
|
+
'Show GitHub console state: whether a GitHub App is registered, the selected installation, token expiry, repository count, and publish defaults. Read-only, never returns secrets.',
|
|
3563
|
+
parameters: { type: 'object', properties: {}, additionalProperties: false },
|
|
3564
|
+
output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
|
|
3565
|
+
async execute() {
|
|
3566
|
+
return { ...(await gh.status()), bridge: bridgeStatus() }
|
|
3567
|
+
},
|
|
3568
|
+
})
|
|
3569
|
+
|
|
3570
|
+
register({
|
|
3571
|
+
name: 'gh_auth',
|
|
3572
|
+
description:
|
|
3573
|
+
'GitHub connection management. action=start registers a GitHub App; installations/select manage App installations; use switches the active connection (app | pat | env); pat-set stores a user access token in the credential service and makes it active; pat-clear removes it; capabilities reports what the active connection may do (notifications and code search need a user token, not an installation token).',
|
|
3574
|
+
parameters: {
|
|
3575
|
+
type: 'object',
|
|
3576
|
+
properties: {
|
|
3577
|
+
action: {
|
|
3578
|
+
type: 'string',
|
|
3579
|
+
enum: ['start', 'installations', 'select', 'use', 'pat-set', 'pat-clear', 'oauth-start', 'oauth-clear', 'device-start', 'device-poll', 'capabilities'],
|
|
3580
|
+
},
|
|
3581
|
+
installationId: { type: 'string', description: 'Installation id, for action=select' },
|
|
3582
|
+
mode: { type: 'string', enum: ['app', 'oauth', 'pat', 'env'], description: 'Connection kind, for action=use' },
|
|
3583
|
+
token: { type: 'string', description: 'User access token (PAT), for action=pat-set. Stored in the credential service only.' },
|
|
3584
|
+
deviceCode: { type: 'string', description: 'device_code from action=device-start, for action=device-poll' },
|
|
3585
|
+
},
|
|
3586
|
+
required: ['action'],
|
|
3587
|
+
additionalProperties: false,
|
|
3588
|
+
},
|
|
3589
|
+
output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
|
|
3590
|
+
async execute(args) {
|
|
3591
|
+
if (args.action === 'start') {
|
|
3592
|
+
const base = String(process.env.DSH_WEB_URL || '').replace(/\/+$/, '')
|
|
3593
|
+
const state = gh.beginManifest()
|
|
3594
|
+
void state
|
|
3595
|
+
return {
|
|
3596
|
+
setupUrl: base ? `${base}${PREFIX}/setup` : `${PREFIX}/setup`,
|
|
3597
|
+
next: base
|
|
3598
|
+
? '在浏览器打开 setupUrl,GitHub 页面点一次 Create GitHub App,再点 Install;完成后回到 gh_status'
|
|
3599
|
+
: '侧栏「GitHub 控制台 → 状态 → 注册 GitHub App」是可靠入口(本进程没有 DSH_WEB_URL)',
|
|
3600
|
+
}
|
|
3601
|
+
}
|
|
3602
|
+
if (args.action === 'installations') return { items: await gh.installations() }
|
|
3603
|
+
if (args.action === 'select') return gh.selectInstallation(args.installationId)
|
|
3604
|
+
if (args.action === 'use') {
|
|
3605
|
+
const auth = await gh.useConnection(args.mode)
|
|
3606
|
+
await appendAudit({ action: 'auth.use', account: auth.account || auth.fingerprint || '', detail: args.mode })
|
|
3607
|
+
return { active: auth.kind, capabilities: gh.capabilitiesOf(auth) }
|
|
3608
|
+
}
|
|
3609
|
+
if (args.action === 'pat-set') {
|
|
3610
|
+
if (!args.token) throw new Error('action=pat-set 需要 token')
|
|
3611
|
+
const result = await gh.setPat(args.token)
|
|
3612
|
+
await appendAudit({ action: 'auth.pat-set', account: result.login, detail: result.fingerprint })
|
|
3613
|
+
return { ...result, next: 'PAT 已保存并设为当前连接;不需要时用 action=pat-clear 删除' }
|
|
3614
|
+
}
|
|
3615
|
+
if (args.action === 'pat-clear') {
|
|
3616
|
+
await gh.clearPat()
|
|
3617
|
+
await appendAudit({ action: 'auth.pat-clear', account: '', detail: '' })
|
|
3618
|
+
return { ok: true }
|
|
3619
|
+
}
|
|
3620
|
+
if (args.action === 'oauth-start') {
|
|
3621
|
+
// Registers the App's OAuth callback, then returns the authorize URL.
|
|
3622
|
+
const origin = webOrigin()
|
|
3623
|
+
if (!origin) throw new Error('拿不到本机 web 地址:请在面板「状态 → 连接方式」里点授权')
|
|
3624
|
+
const result = await gh.beginOAuth(origin)
|
|
3625
|
+
return { ...result, next: '打开 url 授权;回调页会保存用户令牌,然后 action=use mode=oauth' }
|
|
3626
|
+
}
|
|
3627
|
+
if (args.action === 'oauth-clear') {
|
|
3628
|
+
await gh.clearOAuth()
|
|
3629
|
+
await appendAudit({ action: 'auth.oauth-clear', account: '', ok: true })
|
|
3630
|
+
return { ok: true }
|
|
3631
|
+
}
|
|
3632
|
+
if (args.action === 'device-start') {
|
|
3633
|
+
const result = await gh.deviceStart()
|
|
3634
|
+
return {
|
|
3635
|
+
...result,
|
|
3636
|
+
next: `在浏览器打开 ${result.verificationUri},输入 ${result.userCode};然后反复调用 action=device-poll(同一个 deviceCode),直到 status=ok`,
|
|
3637
|
+
}
|
|
3638
|
+
}
|
|
3639
|
+
if (args.action === 'device-poll') {
|
|
3640
|
+
if (!args.deviceCode) throw new Error('action=device-poll 需要 deviceCode')
|
|
3641
|
+
const result = await gh.devicePoll(args.deviceCode)
|
|
3642
|
+
if (result.status === 'ok') {
|
|
3643
|
+
await appendAudit({ action: 'auth.device', account: '', ok: true })
|
|
3644
|
+
}
|
|
3645
|
+
return result
|
|
3646
|
+
}
|
|
3647
|
+
if (args.action === 'capabilities') {
|
|
3648
|
+
const state = await gh.status()
|
|
3649
|
+
return { auth: state.auth, connections: state.connections, authMode: state.authMode }
|
|
3650
|
+
}
|
|
3651
|
+
throw new Error(`未知 action:${args.action}`)
|
|
3652
|
+
},
|
|
3653
|
+
})
|
|
3654
|
+
|
|
3655
|
+
register({
|
|
3656
|
+
name: 'gh_audit',
|
|
3657
|
+
description:
|
|
3658
|
+
'Read the local audit trail of write actions this plugin performed: time, action, account, target and result. Newest last. Files stay on this machine.',
|
|
3659
|
+
parameters: {
|
|
3660
|
+
type: 'object',
|
|
3661
|
+
properties: { limit: { type: 'integer', minimum: 1, maximum: 500, description: 'How many recent entries, default 50' } },
|
|
3662
|
+
additionalProperties: false,
|
|
3663
|
+
},
|
|
3664
|
+
output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
|
|
3665
|
+
async execute(args) {
|
|
3666
|
+
return { path: auditPath(), items: await readAudit(args.limit || 50) }
|
|
3667
|
+
},
|
|
3668
|
+
})
|
|
3669
|
+
|
|
3670
|
+
register({
|
|
3671
|
+
name: 'gh_repos',
|
|
3672
|
+
description:
|
|
3673
|
+
'List repositories the GitHub App installation can access. Optional q filters by full name. Requires a registered App and a selected installation.',
|
|
3674
|
+
parameters: {
|
|
3675
|
+
type: 'object',
|
|
3676
|
+
properties: { q: { type: 'string', description: 'Case-insensitive substring filter on owner/name' } },
|
|
3677
|
+
additionalProperties: false,
|
|
3678
|
+
},
|
|
3679
|
+
output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
|
|
3680
|
+
async execute(args) {
|
|
3681
|
+
return gh.listRepositories(args.q)
|
|
3682
|
+
},
|
|
3683
|
+
})
|
|
3684
|
+
|
|
3685
|
+
register({
|
|
3686
|
+
name: 'gh_tree',
|
|
3687
|
+
description: 'List the file tree of a repository branch (flat paths). Use owner/name from gh_repos.',
|
|
3688
|
+
parameters: {
|
|
3689
|
+
type: 'object',
|
|
3690
|
+
properties: {
|
|
3691
|
+
owner: { type: 'string' },
|
|
3692
|
+
name: { type: 'string' },
|
|
3693
|
+
ref: { type: 'string', description: 'Branch or ref, default the repository default branch' },
|
|
3694
|
+
},
|
|
3695
|
+
required: ['owner', 'name'],
|
|
3696
|
+
additionalProperties: false,
|
|
3697
|
+
},
|
|
3698
|
+
output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
|
|
3699
|
+
async execute(args) {
|
|
3700
|
+
return gh.readTree(args.owner, args.name, args.ref)
|
|
3701
|
+
},
|
|
3702
|
+
})
|
|
3703
|
+
|
|
3704
|
+
register({
|
|
3705
|
+
name: 'gh_file_read',
|
|
3706
|
+
description: 'Read one text file from a repository. Returns the file sha, which a later write must carry.',
|
|
3707
|
+
parameters: {
|
|
3708
|
+
type: 'object',
|
|
3709
|
+
properties: {
|
|
3710
|
+
owner: { type: 'string' },
|
|
3711
|
+
name: { type: 'string' },
|
|
3712
|
+
path: { type: 'string', description: 'Path inside the repository, for example src/index.js' },
|
|
3713
|
+
ref: { type: 'string' },
|
|
3714
|
+
},
|
|
3715
|
+
required: ['owner', 'name', 'path'],
|
|
3716
|
+
additionalProperties: false,
|
|
3717
|
+
},
|
|
3718
|
+
output: {
|
|
3719
|
+
schema: { type: 'object' },
|
|
3720
|
+
render: (args, value) => [
|
|
3721
|
+
{
|
|
3722
|
+
type: 'text',
|
|
3723
|
+
text: `${value.path} · sha ${value.sha} · ${value.size} B\n\n${String(value.text || '')}`,
|
|
3724
|
+
},
|
|
3725
|
+
],
|
|
3726
|
+
},
|
|
3727
|
+
async execute(args) {
|
|
3728
|
+
return gh.readFile(args.owner, args.name, args.path, args.ref)
|
|
3729
|
+
},
|
|
3730
|
+
})
|
|
3731
|
+
|
|
3732
|
+
register({
|
|
3733
|
+
name: 'gh_file_write',
|
|
3734
|
+
description:
|
|
3735
|
+
'Create or update one file in a repository through the contents API. Pass the sha from gh_file_read to update; a stale sha fails with REF_CONFLICT instead of overwriting.',
|
|
3736
|
+
parameters: {
|
|
3737
|
+
type: 'object',
|
|
3738
|
+
properties: {
|
|
3739
|
+
owner: { type: 'string' },
|
|
3740
|
+
name: { type: 'string' },
|
|
3741
|
+
path: { type: 'string' },
|
|
3742
|
+
text: { type: 'string', description: 'Full new file content' },
|
|
3743
|
+
message: { type: 'string', description: 'Commit message' },
|
|
3744
|
+
sha: { type: 'string', description: 'Current blob sha for an update' },
|
|
3745
|
+
ref: { type: 'string', description: 'Branch, default the repository default branch' },
|
|
3746
|
+
},
|
|
3747
|
+
required: ['owner', 'name', 'path', 'text'],
|
|
3748
|
+
additionalProperties: false,
|
|
3749
|
+
},
|
|
3750
|
+
output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
|
|
3751
|
+
async execute(args) {
|
|
3752
|
+
return gh.writeFile(args.owner, args.name, args.path, args.text, args.message, args.sha, args.ref)
|
|
3753
|
+
},
|
|
3754
|
+
})
|
|
3755
|
+
|
|
3756
|
+
register({
|
|
3757
|
+
name: 'gh_issues',
|
|
3758
|
+
description: 'List repository issues (pull requests are flagged, not filtered out).',
|
|
3759
|
+
parameters: {
|
|
3760
|
+
type: 'object',
|
|
3761
|
+
properties: {
|
|
3762
|
+
owner: { type: 'string' },
|
|
3763
|
+
name: { type: 'string' },
|
|
3764
|
+
state: { type: 'string', enum: ['open', 'closed', 'all'] },
|
|
3765
|
+
},
|
|
3766
|
+
required: ['owner', 'name'],
|
|
3767
|
+
additionalProperties: false,
|
|
3768
|
+
},
|
|
3769
|
+
output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
|
|
3770
|
+
async execute(args) {
|
|
3771
|
+
return gh.listIssues(args.owner, args.name, args.state)
|
|
3772
|
+
},
|
|
3773
|
+
})
|
|
3774
|
+
|
|
3775
|
+
register({
|
|
3776
|
+
name: 'gh_issue_create',
|
|
3777
|
+
description: 'Create an issue in a repository.',
|
|
3778
|
+
parameters: {
|
|
3779
|
+
type: 'object',
|
|
3780
|
+
properties: {
|
|
3781
|
+
owner: { type: 'string' },
|
|
3782
|
+
name: { type: 'string' },
|
|
3783
|
+
title: { type: 'string' },
|
|
3784
|
+
body: { type: 'string' },
|
|
3785
|
+
},
|
|
3786
|
+
required: ['owner', 'name', 'title'],
|
|
3787
|
+
additionalProperties: false,
|
|
3788
|
+
},
|
|
3789
|
+
output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
|
|
3790
|
+
async execute(args) {
|
|
3791
|
+
return gh.createIssue(args.owner, args.name, args.title, args.body)
|
|
3792
|
+
},
|
|
3793
|
+
})
|
|
3794
|
+
|
|
3795
|
+
register({
|
|
3796
|
+
name: 'gh_issue_comment',
|
|
3797
|
+
description: 'Comment on an issue or pull request.',
|
|
3798
|
+
parameters: {
|
|
3799
|
+
type: 'object',
|
|
3800
|
+
properties: {
|
|
3801
|
+
owner: { type: 'string' },
|
|
3802
|
+
name: { type: 'string' },
|
|
3803
|
+
number: { type: 'integer', minimum: 1 },
|
|
3804
|
+
body: { type: 'string' },
|
|
3805
|
+
},
|
|
3806
|
+
required: ['owner', 'name', 'number', 'body'],
|
|
3807
|
+
additionalProperties: false,
|
|
3808
|
+
},
|
|
3809
|
+
output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
|
|
3810
|
+
async execute(args) {
|
|
3811
|
+
return gh.commentIssue(args.owner, args.name, args.number, args.body)
|
|
3812
|
+
},
|
|
3813
|
+
})
|
|
3814
|
+
|
|
3815
|
+
register({
|
|
3816
|
+
name: 'gh_pulls',
|
|
3817
|
+
description: 'List pull requests of a repository with head/base branches and mergeable state.',
|
|
3818
|
+
parameters: {
|
|
3819
|
+
type: 'object',
|
|
3820
|
+
properties: {
|
|
3821
|
+
owner: { type: 'string' },
|
|
3822
|
+
name: { type: 'string' },
|
|
3823
|
+
state: { type: 'string', enum: ['open', 'closed', 'all'] },
|
|
3824
|
+
},
|
|
3825
|
+
required: ['owner', 'name'],
|
|
3826
|
+
additionalProperties: false,
|
|
3827
|
+
},
|
|
3828
|
+
output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
|
|
3829
|
+
async execute(args) {
|
|
3830
|
+
return gh.listPulls(args.owner, args.name, args.state)
|
|
3831
|
+
},
|
|
3832
|
+
})
|
|
3833
|
+
|
|
3834
|
+
register({
|
|
3835
|
+
name: 'gh_pull_create',
|
|
3836
|
+
description: 'Open a pull request from an existing head branch into a base branch.',
|
|
3837
|
+
parameters: {
|
|
3838
|
+
type: 'object',
|
|
3839
|
+
properties: {
|
|
3840
|
+
owner: { type: 'string' },
|
|
3841
|
+
name: { type: 'string' },
|
|
3842
|
+
head: { type: 'string', description: 'Source branch, for example feature/x' },
|
|
3843
|
+
base: { type: 'string', description: 'Target branch, for example main' },
|
|
3844
|
+
title: { type: 'string' },
|
|
3845
|
+
body: { type: 'string' },
|
|
3846
|
+
},
|
|
3847
|
+
required: ['owner', 'name', 'head', 'base', 'title'],
|
|
3848
|
+
additionalProperties: false,
|
|
3849
|
+
},
|
|
3850
|
+
output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
|
|
3851
|
+
async execute(args) {
|
|
3852
|
+
return gh.createPull(args.owner, args.name, args.head, args.base, args.title, args.body)
|
|
3853
|
+
},
|
|
3854
|
+
})
|
|
3855
|
+
|
|
3856
|
+
register({
|
|
3857
|
+
name: 'gh_pull_merge',
|
|
3858
|
+
description:
|
|
3859
|
+
'Merge a pull request. Irreversible on the remote: confirm with the user first and pass confirm: true. Method defaults to squash.',
|
|
3860
|
+
parameters: {
|
|
3861
|
+
type: 'object',
|
|
3862
|
+
properties: {
|
|
3863
|
+
owner: { type: 'string' },
|
|
3864
|
+
name: { type: 'string' },
|
|
3865
|
+
number: { type: 'integer', minimum: 1 },
|
|
3866
|
+
method: { type: 'string', enum: ['merge', 'squash', 'rebase'] },
|
|
3867
|
+
confirm: { type: 'boolean', description: 'Must be true' },
|
|
3868
|
+
},
|
|
3869
|
+
required: ['owner', 'name', 'number', 'confirm'],
|
|
3870
|
+
additionalProperties: false,
|
|
3871
|
+
},
|
|
3872
|
+
output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
|
|
3873
|
+
async execute(args) {
|
|
3874
|
+
if (args.confirm !== true) throw new Error('合并 PR 必须显式确认:传 confirm: true')
|
|
3875
|
+
return gh.mergePull(args.owner, args.name, args.number, args.method)
|
|
3876
|
+
},
|
|
3877
|
+
})
|
|
3878
|
+
|
|
3879
|
+
register({
|
|
3880
|
+
name: 'gh_actions',
|
|
3881
|
+
description: 'List recent GitHub Actions workflow runs of a repository.',
|
|
3882
|
+
parameters: {
|
|
3883
|
+
type: 'object',
|
|
3884
|
+
properties: { owner: { type: 'string' }, name: { type: 'string' } },
|
|
3885
|
+
required: ['owner', 'name'],
|
|
3886
|
+
additionalProperties: false,
|
|
3887
|
+
},
|
|
3888
|
+
output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
|
|
3889
|
+
async execute(args) {
|
|
3890
|
+
return gh.listRuns(args.owner, args.name)
|
|
3891
|
+
},
|
|
3892
|
+
})
|
|
3893
|
+
|
|
3894
|
+
register({
|
|
3895
|
+
name: 'gh_actions_rerun',
|
|
3896
|
+
description: 'Re-run a workflow run by id. Confirm with the user first; pass confirm: true.',
|
|
3897
|
+
parameters: {
|
|
3898
|
+
type: 'object',
|
|
3899
|
+
properties: {
|
|
3900
|
+
owner: { type: 'string' },
|
|
3901
|
+
name: { type: 'string' },
|
|
3902
|
+
runId: { type: 'integer', minimum: 1 },
|
|
3903
|
+
confirm: { type: 'boolean' },
|
|
3904
|
+
},
|
|
3905
|
+
required: ['owner', 'name', 'runId', 'confirm'],
|
|
3906
|
+
additionalProperties: false,
|
|
3907
|
+
},
|
|
3908
|
+
output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
|
|
3909
|
+
async execute(args) {
|
|
3910
|
+
if (args.confirm !== true) throw new Error('重跑 CI 必须显式确认:传 confirm: true')
|
|
3911
|
+
return gh.rerunWorkflow(args.owner, args.name, args.runId)
|
|
3912
|
+
},
|
|
3913
|
+
})
|
|
3914
|
+
|
|
3915
|
+
register({
|
|
3916
|
+
name: 'plugin_discover',
|
|
3917
|
+
description:
|
|
3918
|
+
'Find publishable DSH plugin directories on this machine without any GitHub sign-in: scans the session workspace and the current process directory for package.json files declaring dsh.bundle.patch or dsh.client. Returns each directory with name, version, and a suggested repository name. Use it before plugin_preflight or plugin_publish when the user has not named the directory.',
|
|
3919
|
+
parameters: {
|
|
3920
|
+
type: 'object',
|
|
3921
|
+
properties: {
|
|
3922
|
+
root: { type: 'string', description: 'Optional extra absolute directory to scan first' },
|
|
3923
|
+
},
|
|
3924
|
+
additionalProperties: false,
|
|
3925
|
+
},
|
|
3926
|
+
output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
|
|
3927
|
+
async execute(args) {
|
|
3928
|
+
return discover(args.root)
|
|
3929
|
+
},
|
|
3930
|
+
})
|
|
3931
|
+
|
|
3932
|
+
register({
|
|
3933
|
+
name: 'plugin_preflight',
|
|
3934
|
+
description:
|
|
3935
|
+
'Static checks on a local DSH plugin directory before publishing: manifest and bundle patch, entry files, README/LICENSE/.gitignore, hardcoded secrets, local absolute paths, and npm name collisions. Never executes package scripts.',
|
|
3936
|
+
parameters: {
|
|
3937
|
+
type: 'object',
|
|
3938
|
+
properties: { dir: { type: 'string', description: 'Plugin directory; relative paths resolve against the workspace' } },
|
|
3939
|
+
required: ['dir'],
|
|
3940
|
+
additionalProperties: false,
|
|
3941
|
+
},
|
|
3942
|
+
output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
|
|
3943
|
+
async execute(args, exec) {
|
|
3944
|
+
return preflight(resolveDir(args.dir, exec), gh, cfg)
|
|
3945
|
+
},
|
|
3946
|
+
})
|
|
3947
|
+
|
|
3948
|
+
register({
|
|
3949
|
+
name: 'plugin_publish',
|
|
3950
|
+
description:
|
|
3951
|
+
'Publish a local DSH plugin to an existing GitHub repository: preflight, commit every bundled file through the Git Data API, merge the dsh-plugin topic, create the v<version> Release, then probe npm and market indexes. The repository must already exist and be authorized for the App. Returns a job id; poll with plugin_publish_status.',
|
|
3952
|
+
parameters: {
|
|
3953
|
+
type: 'object',
|
|
3954
|
+
properties: {
|
|
3955
|
+
dir: { type: 'string', description: 'Local plugin directory' },
|
|
3956
|
+
owner: { type: 'string', description: 'Repository owner (user or org)' },
|
|
3957
|
+
repo: { type: 'string', description: 'Repository name; create it on GitHub first if missing' },
|
|
3958
|
+
version: { type: 'string', description: 'Version for the tag; defaults to package.json version' },
|
|
3959
|
+
branch: { type: 'string', description: 'Target branch, default from plugin config (main)' },
|
|
3960
|
+
message: { type: 'string', description: 'Commit message' },
|
|
3961
|
+
notes: { type: 'string', description: 'Release notes body' },
|
|
3962
|
+
},
|
|
3963
|
+
required: ['dir', 'owner', 'repo'],
|
|
3964
|
+
additionalProperties: false,
|
|
3965
|
+
},
|
|
3966
|
+
output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
|
|
3967
|
+
async execute(args, exec) {
|
|
3968
|
+
const dir = resolveDir(args.dir, exec)
|
|
3969
|
+
const job = jobs.create({ dir, owner: args.owner, repo: args.repo })
|
|
3970
|
+
await runPublish({
|
|
3971
|
+
job,
|
|
3972
|
+
gh,
|
|
3973
|
+
cfg,
|
|
3974
|
+
dir,
|
|
3975
|
+
owner: args.owner,
|
|
3976
|
+
repo: args.repo,
|
|
3977
|
+
version: args.version,
|
|
3978
|
+
notes: args.notes,
|
|
3979
|
+
opts: args,
|
|
3980
|
+
})
|
|
3981
|
+
return {
|
|
3982
|
+
jobId: job.id,
|
|
3983
|
+
ok: job.ok,
|
|
3984
|
+
steps: job.steps.map((item) => ({ id: item.id, title: item.title, state: item.state, detail: item.detail })),
|
|
3985
|
+
releaseUrl: job.releaseUrl || null,
|
|
3986
|
+
market: job.market ? job.market.summary : null,
|
|
3987
|
+
}
|
|
3988
|
+
},
|
|
3989
|
+
})
|
|
3990
|
+
|
|
3991
|
+
register({
|
|
3992
|
+
name: 'plugin_npm_publish',
|
|
3993
|
+
description:
|
|
3994
|
+
'Publish the plugin to npm through GitHub Actions. Writes (or updates) .github/workflows/publish.yml, dispatches it on the publish branch, and waits for the run to finish. Needs confirm: true. npm cannot attach a trusted publisher to a package that does not exist yet, so the very first version must be published once by hand (or with an NPM_TOKEN repository secret); every version after that runs tokenless over OIDC.',
|
|
3995
|
+
parameters: {
|
|
3996
|
+
type: 'object',
|
|
3997
|
+
properties: {
|
|
3998
|
+
dir: { type: 'string', description: 'Local plugin directory' },
|
|
3999
|
+
owner: { type: 'string' },
|
|
4000
|
+
repo: { type: 'string' },
|
|
4001
|
+
branch: { type: 'string', description: 'Branch that dispatches the workflow; default the publish branch' },
|
|
4002
|
+
dryRun: { type: 'boolean', description: 'Ask the workflow to run npm publish --dry-run' },
|
|
4003
|
+
confirm: { type: 'boolean', description: 'Must be true' },
|
|
4004
|
+
},
|
|
4005
|
+
required: ['dir', 'owner', 'repo', 'confirm'],
|
|
4006
|
+
additionalProperties: false,
|
|
4007
|
+
},
|
|
4008
|
+
output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
|
|
4009
|
+
async execute(args, exec) {
|
|
4010
|
+
if (args.confirm !== true) throw new Error('触发 npm 发布需要确认:传 confirm: true')
|
|
4011
|
+
const dir = resolveDir(args.dir, exec)
|
|
4012
|
+
const pkg = await readLocalPackage(dir)
|
|
4013
|
+
const branch = args.branch || cfg.publishBranch
|
|
4014
|
+
const prepared = await ensurePublishWorkflow(gh, args.owner, args.repo, branch, cfg.npmWorkflow)
|
|
4015
|
+
const since = Date.now()
|
|
4016
|
+
await dispatchWorkflow(
|
|
4017
|
+
gh,
|
|
4018
|
+
args.owner,
|
|
4019
|
+
args.repo,
|
|
4020
|
+
cfg.npmWorkflow,
|
|
4021
|
+
branch,
|
|
4022
|
+
args.dryRun ? { dry_run: 'true' } : undefined,
|
|
4023
|
+
)
|
|
4024
|
+
const run = await waitForWorkflowRun(gh, args.owner, args.repo, cfg.npmWorkflow, since, cfg.npmPollSeconds * 1000)
|
|
4025
|
+
const state = await npmPublishState(gh, cfg, { owner: args.owner, repo: args.repo, dir }).catch(() => null)
|
|
4026
|
+
return {
|
|
4027
|
+
package: `${pkg.name}@${pkg.version}`,
|
|
4028
|
+
workflow: prepared.path,
|
|
4029
|
+
workflowChanged: prepared.changed,
|
|
4030
|
+
branch,
|
|
4031
|
+
dryRun: args.dryRun === true,
|
|
4032
|
+
run,
|
|
4033
|
+
npmState: state,
|
|
4034
|
+
next:
|
|
4035
|
+
args.dryRun === true
|
|
4036
|
+
? run.conclusion === 'success'
|
|
4037
|
+
? 'dry-run 通过:真实发布前仍需跨过「首次发布」这一步(面板里按 npmState.steps 做)。'
|
|
4038
|
+
: 'dry-run 未通过,看 run 日志。'
|
|
4039
|
+
: run.conclusion === 'success'
|
|
4040
|
+
? 'npm 已发布,可到 npmjs.com 查看 provenance。'
|
|
4041
|
+
: run.status === 'timeout'
|
|
4042
|
+
? `运行仍在进行,打开 run 页面查看:${run.url || ''}`
|
|
4043
|
+
: '运行失败时看 run 日志:首次发布需要先手动发一次该版本,或在仓库 Secrets 里加 NPM_TOKEN。',
|
|
4044
|
+
}
|
|
4045
|
+
},
|
|
4046
|
+
})
|
|
4047
|
+
|
|
4048
|
+
register({
|
|
4049
|
+
name: 'plugin_market_index',
|
|
4050
|
+
description:
|
|
4051
|
+
'Generate or refresh a self-hosted format-1 plugin market index for this repository and commit it (default market/index.json). Returns the raw URL to add to DSH plugin market sources, plus the commit-pinned install spec. The index pins the current branch head commit, so publish first and then refresh the index.',
|
|
4052
|
+
parameters: {
|
|
4053
|
+
type: 'object',
|
|
4054
|
+
properties: {
|
|
4055
|
+
dir: { type: 'string', description: 'Local plugin directory' },
|
|
4056
|
+
owner: { type: 'string' },
|
|
4057
|
+
repo: { type: 'string' },
|
|
4058
|
+
branch: { type: 'string', description: 'Branch to pin; default the publish branch' },
|
|
4059
|
+
title: { type: 'string', description: 'Display title for the entry; defaults to the package name' },
|
|
4060
|
+
description: { type: 'string', description: 'Display description; defaults to package.json description' },
|
|
4061
|
+
},
|
|
4062
|
+
required: ['dir', 'owner', 'repo'],
|
|
4063
|
+
additionalProperties: false,
|
|
4064
|
+
},
|
|
4065
|
+
output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
|
|
4066
|
+
async execute(args, exec) {
|
|
4067
|
+
const dir = resolveDir(args.dir, exec)
|
|
4068
|
+
const pkg = await readLocalPackage(dir)
|
|
4069
|
+
const branch = args.branch || cfg.publishBranch
|
|
4070
|
+
const repoPath = `/repos/${encodeURIComponent(args.owner)}/${encodeURIComponent(args.repo)}`
|
|
4071
|
+
const ref = await gh.call(`${repoPath}/git/ref/heads/${encodeURIComponent(branch)}`)
|
|
4072
|
+
const commit = ref.object ? ref.object.sha : ''
|
|
4073
|
+
if (!commit) throw new Error(`读不到 ${branch} 的最新提交:请先发布一次`)
|
|
4074
|
+
const doc = marketIndexDocument({
|
|
4075
|
+
pkg,
|
|
4076
|
+
owner: args.owner,
|
|
4077
|
+
repo: args.repo,
|
|
4078
|
+
commit,
|
|
4079
|
+
entryTitle: args.title,
|
|
4080
|
+
entryDescription: args.description,
|
|
4081
|
+
})
|
|
4082
|
+
const existing = await repoFile(gh, args.owner, args.repo, cfg.marketIndexPath, branch)
|
|
4083
|
+
await gh.writeFile(
|
|
4084
|
+
args.owner,
|
|
4085
|
+
args.repo,
|
|
4086
|
+
cfg.marketIndexPath,
|
|
4087
|
+
JSON.stringify(doc, null, 2) + '\n',
|
|
4088
|
+
`chore: update market index for v${pkg.version}`,
|
|
4089
|
+
existing ? existing.sha : undefined,
|
|
4090
|
+
branch,
|
|
4091
|
+
)
|
|
4092
|
+
await gh
|
|
4093
|
+
.writeRecord(INDEX_CRED, { owner: args.owner, repo: args.repo, path: cfg.marketIndexPath, body: JSON.stringify(doc, null, 2) })
|
|
4094
|
+
.catch(() => {})
|
|
4095
|
+
return {
|
|
4096
|
+
url: `https://raw.githubusercontent.com/${args.owner}/${args.repo}/${branch}/${cfg.marketIndexPath}`,
|
|
4097
|
+
localUrl: `${PREFIX}/market/index.json`,
|
|
4098
|
+
localUrlNote: '本机直接可读的地址(前面要加 DSH 的 web 地址);适用于 raw.githubusercontent.com 或 CDN 在本机不可达的情况',
|
|
4099
|
+
path: cfg.marketIndexPath,
|
|
4100
|
+
commit,
|
|
4101
|
+
version: pkg.version,
|
|
4102
|
+
installSpec: `git+https://github.com/${args.owner}/${args.repo}.git#${commit}`,
|
|
4103
|
+
next: '把 url 加进 DSH 的插件市场源(设置 → 插件 → 发现/市场源),即可在 Discover 里看到它',
|
|
4104
|
+
index: doc,
|
|
4105
|
+
}
|
|
4106
|
+
},
|
|
4107
|
+
})
|
|
4108
|
+
|
|
4109
|
+
register({
|
|
4110
|
+
name: 'plugin_market_attach',
|
|
4111
|
+
description:
|
|
4112
|
+
'Add this plugin\'s own market index to the DSH plugin market sources with one call, by writing the plugin-market index list. Falls back to instructions when the profile has no plugin-market service mounted. Generate the index first with plugin_market_index.',
|
|
4113
|
+
parameters: {
|
|
4114
|
+
type: 'object',
|
|
4115
|
+
properties: {
|
|
4116
|
+
url: {
|
|
4117
|
+
type: 'string',
|
|
4118
|
+
description: 'Index URL to attach; defaults to the local route of this DSH instance',
|
|
4119
|
+
},
|
|
4120
|
+
},
|
|
4121
|
+
additionalProperties: false,
|
|
4122
|
+
},
|
|
4123
|
+
output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
|
|
4124
|
+
async execute(args) {
|
|
4125
|
+
return attachIndexToMarket({ url: args.url })
|
|
4126
|
+
},
|
|
4127
|
+
})
|
|
4128
|
+
|
|
4129
|
+
register({
|
|
4130
|
+
name: 'plugin_release_asset',
|
|
4131
|
+
description:
|
|
4132
|
+
'Package the plugin directory into a .tgz and attach it to the GitHub Release for that version, so the plugin can be distributed without npm. Returns the download URL and the commit-pinned git install spec. Use this instead of npm when the user has no npm passkey or token.',
|
|
4133
|
+
parameters: {
|
|
4134
|
+
type: 'object',
|
|
4135
|
+
properties: {
|
|
4136
|
+
dir: { type: 'string', description: 'Local plugin directory' },
|
|
4137
|
+
owner: { type: 'string' },
|
|
4138
|
+
repo: { type: 'string' },
|
|
4139
|
+
version: { type: 'string', description: 'Release version to attach to; defaults to package.json version' },
|
|
4140
|
+
fileName: { type: 'string', description: 'Asset file name; defaults to <name>-<version>.tgz' },
|
|
4141
|
+
},
|
|
4142
|
+
required: ['dir', 'owner', 'repo'],
|
|
4143
|
+
additionalProperties: false,
|
|
4144
|
+
},
|
|
4145
|
+
output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
|
|
4146
|
+
async execute(args, exec) {
|
|
4147
|
+
const dir = resolveDir(args.dir, exec)
|
|
4148
|
+
const pkg = await readLocalPackage(dir)
|
|
4149
|
+
const collected = await collectFiles(dir, cfg.maxPushBytes)
|
|
4150
|
+
const version = args.version || pkg.version
|
|
4151
|
+
const fileName = args.fileName || `${pkg.name.replace(/^@[^/]+\//, '')}-${version}.tgz`
|
|
4152
|
+
const asset = await attachReleaseAsset(gh, args.owner, args.repo, version, fileName, buildTarball(collected.files))
|
|
4153
|
+
let commit = ''
|
|
4154
|
+
try {
|
|
4155
|
+
const ref = await gh.call(
|
|
4156
|
+
`/repos/${encodeURIComponent(args.owner)}/${encodeURIComponent(args.repo)}/git/ref/heads/${encodeURIComponent(cfg.publishBranch)}`,
|
|
4157
|
+
)
|
|
4158
|
+
commit = ref && ref.object ? ref.object.sha : ''
|
|
4159
|
+
} catch {
|
|
4160
|
+
commit = ''
|
|
4161
|
+
}
|
|
4162
|
+
return {
|
|
4163
|
+
package: `${pkg.name}@${version}`,
|
|
4164
|
+
files: collected.files.length,
|
|
4165
|
+
asset,
|
|
4166
|
+
gitInstall: commit ? `git+https://github.com/${args.owner}/${args.repo}.git#${commit}` : '',
|
|
4167
|
+
howToUse: [
|
|
4168
|
+
'下载 .tgz 解压后,用 Plugins → Add plugin 指向解压出来的目录;',
|
|
4169
|
+
'或直接把 gitInstall 那串交给 dsh plugin add;',
|
|
4170
|
+
'市场索引里已经用同一套 git 源,Discover 安装同样不需要 npm。',
|
|
4171
|
+
],
|
|
4172
|
+
}
|
|
4173
|
+
},
|
|
4174
|
+
})
|
|
4175
|
+
|
|
4176
|
+
register({
|
|
4177
|
+
name: 'plugin_market_readiness',
|
|
4178
|
+
description:
|
|
4179
|
+
'Check whether this plugin meets the awesome-dsh-plugin (dshmarket catalog) listing rules: repository older than one day, dsh.bundle declared, @deepseek-ai packages only in peerDependencies, a GitHub-hosted PNG icon, and a version-free .tgz on the latest release. Also returns a ready-to-paste entry (url/name/category/icon/tarball).',
|
|
4180
|
+
parameters: {
|
|
4181
|
+
type: 'object',
|
|
4182
|
+
properties: {
|
|
4183
|
+
dir: { type: 'string', description: 'Local plugin directory' },
|
|
4184
|
+
owner: { type: 'string' },
|
|
4185
|
+
repo: { type: 'string' },
|
|
4186
|
+
},
|
|
4187
|
+
required: ['dir', 'owner', 'repo'],
|
|
4188
|
+
additionalProperties: false,
|
|
4189
|
+
},
|
|
4190
|
+
output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
|
|
4191
|
+
async execute(args, exec) {
|
|
4192
|
+
return marketReadiness(gh, cfg, { owner: args.owner, repo: args.repo, dir: resolveDir(args.dir, exec) })
|
|
4193
|
+
},
|
|
4194
|
+
})
|
|
4195
|
+
|
|
4196
|
+
register({
|
|
4197
|
+
name: 'gh_pull_detail',
|
|
4198
|
+
description:
|
|
4199
|
+
'Read one pull request with its per-file diff patches, review state and mergeability. Use it before reviewing or merging; the patches are plain unified diff text.',
|
|
4200
|
+
parameters: {
|
|
4201
|
+
type: 'object',
|
|
4202
|
+
properties: {
|
|
4203
|
+
owner: { type: 'string' },
|
|
4204
|
+
name: { type: 'string' },
|
|
4205
|
+
number: { type: 'integer', minimum: 1 },
|
|
4206
|
+
},
|
|
4207
|
+
required: ['owner', 'name', 'number'],
|
|
4208
|
+
additionalProperties: false,
|
|
4209
|
+
},
|
|
4210
|
+
output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
|
|
4211
|
+
async execute(args) {
|
|
4212
|
+
return gh.pullDetail(args.owner, args.name, args.number)
|
|
4213
|
+
},
|
|
4214
|
+
})
|
|
4215
|
+
|
|
4216
|
+
register({
|
|
4217
|
+
name: 'gh_pull_comment',
|
|
4218
|
+
description:
|
|
4219
|
+
'Comment on a pull request. Pass path plus line for an inline review comment on the right side of the diff; omit them for a conversation comment.',
|
|
4220
|
+
parameters: {
|
|
4221
|
+
type: 'object',
|
|
4222
|
+
properties: {
|
|
4223
|
+
owner: { type: 'string' },
|
|
4224
|
+
name: { type: 'string' },
|
|
4225
|
+
number: { type: 'integer', minimum: 1 },
|
|
4226
|
+
body: { type: 'string' },
|
|
4227
|
+
path: { type: 'string', description: 'File path for an inline comment' },
|
|
4228
|
+
line: { type: 'integer', minimum: 1, description: 'Line number in the new file, for an inline comment' },
|
|
4229
|
+
},
|
|
4230
|
+
required: ['owner', 'name', 'number', 'body'],
|
|
4231
|
+
additionalProperties: false,
|
|
4232
|
+
},
|
|
4233
|
+
output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
|
|
4234
|
+
async execute(args) {
|
|
4235
|
+
await requireWrite('pullWrite')
|
|
4236
|
+
return audited('pull.comment', `${args.owner}/${args.name}#${args.number}`, () =>
|
|
4237
|
+
gh.addPullComment(args.owner, args.name, args.number, args.body, args.path ? { path: args.path, number: args.line } : null),
|
|
4238
|
+
)
|
|
4239
|
+
},
|
|
4240
|
+
})
|
|
4241
|
+
|
|
4242
|
+
register({
|
|
4243
|
+
name: 'gh_pull_review',
|
|
4244
|
+
description:
|
|
4245
|
+
'Submit a pull request review: APPROVE, REQUEST_CHANGES (needs a reason) or COMMENT. Confirm with the user before approving or requesting changes when it is not their own request.',
|
|
4246
|
+
parameters: {
|
|
4247
|
+
type: 'object',
|
|
4248
|
+
properties: {
|
|
4249
|
+
owner: { type: 'string' },
|
|
4250
|
+
name: { type: 'string' },
|
|
4251
|
+
number: { type: 'integer', minimum: 1 },
|
|
4252
|
+
event: { type: 'string', enum: ['APPROVE', 'REQUEST_CHANGES', 'COMMENT'] },
|
|
4253
|
+
body: { type: 'string' },
|
|
4254
|
+
},
|
|
4255
|
+
required: ['owner', 'name', 'number', 'event'],
|
|
4256
|
+
additionalProperties: false,
|
|
4257
|
+
},
|
|
4258
|
+
output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
|
|
4259
|
+
async execute(args) {
|
|
4260
|
+
await requireWrite('pullWrite')
|
|
4261
|
+
return audited('pull.review', `${args.owner}/${args.name}#${args.number} ${args.event}`, () =>
|
|
4262
|
+
gh.submitReview(args.owner, args.name, args.number, args.event, args.body),
|
|
4263
|
+
)
|
|
4264
|
+
},
|
|
4265
|
+
})
|
|
4266
|
+
|
|
4267
|
+
register({
|
|
4268
|
+
name: 'gh_issue_update',
|
|
4269
|
+
description:
|
|
4270
|
+
'Update an issue or pull request: title, body, state (open/closed), labels, assignees, milestone. Only the fields you pass are changed.',
|
|
4271
|
+
parameters: {
|
|
4272
|
+
type: 'object',
|
|
4273
|
+
properties: {
|
|
4274
|
+
owner: { type: 'string' },
|
|
4275
|
+
name: { type: 'string' },
|
|
4276
|
+
number: { type: 'integer', minimum: 1 },
|
|
4277
|
+
title: { type: 'string' },
|
|
4278
|
+
body: { type: 'string' },
|
|
4279
|
+
state: { type: 'string', enum: ['open', 'closed'] },
|
|
4280
|
+
labels: { type: 'array', items: { type: 'string' } },
|
|
4281
|
+
assignees: { type: 'array', items: { type: 'string' } },
|
|
4282
|
+
milestone: { type: 'integer', description: 'Milestone number, or null to clear' },
|
|
4283
|
+
},
|
|
4284
|
+
required: ['owner', 'name', 'number'],
|
|
4285
|
+
additionalProperties: false,
|
|
4286
|
+
},
|
|
4287
|
+
output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
|
|
4288
|
+
async execute(args) {
|
|
4289
|
+
await requireWrite('issueWrite')
|
|
4290
|
+
const patch = { ...args }
|
|
4291
|
+
delete patch.owner
|
|
4292
|
+
delete patch.name
|
|
4293
|
+
delete patch.number
|
|
4294
|
+
return audited('issue.update', `${args.owner}/${args.name}#${args.number}`, () =>
|
|
4295
|
+
gh.updateIssue(args.owner, args.name, args.number, patch),
|
|
4296
|
+
)
|
|
4297
|
+
},
|
|
4298
|
+
})
|
|
4299
|
+
|
|
4300
|
+
register({
|
|
4301
|
+
name: 'gh_workflows',
|
|
4302
|
+
description: 'List the repository workflows and their state, so a workflow can be dispatched by file name.',
|
|
4303
|
+
parameters: {
|
|
4304
|
+
type: 'object',
|
|
4305
|
+
properties: { owner: { type: 'string' }, name: { type: 'string' } },
|
|
4306
|
+
required: ['owner', 'name'],
|
|
4307
|
+
additionalProperties: false,
|
|
4308
|
+
},
|
|
4309
|
+
output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
|
|
4310
|
+
async execute(args) {
|
|
4311
|
+
return gh.listWorkflows(args.owner, args.name)
|
|
4312
|
+
},
|
|
4313
|
+
})
|
|
4314
|
+
|
|
4315
|
+
register({
|
|
4316
|
+
name: 'gh_workflow_dispatch',
|
|
4317
|
+
description:
|
|
4318
|
+
'Manually trigger a workflow (workflow_dispatch) with optional inputs. Needs workflows: write and the workflow must declare workflow_dispatch. Confirm with the user first.',
|
|
4319
|
+
parameters: {
|
|
4320
|
+
type: 'object',
|
|
4321
|
+
properties: {
|
|
4322
|
+
owner: { type: 'string' },
|
|
4323
|
+
name: { type: 'string' },
|
|
4324
|
+
workflow: { type: 'string', description: 'Workflow file name (publish.yml) or id' },
|
|
4325
|
+
ref: { type: 'string', description: 'Branch or tag, default main' },
|
|
4326
|
+
inputs: { type: 'object', description: 'Inputs the workflow declares' },
|
|
4327
|
+
confirm: { type: 'boolean', description: 'Must be true' },
|
|
4328
|
+
},
|
|
4329
|
+
required: ['owner', 'name', 'workflow', 'confirm'],
|
|
4330
|
+
additionalProperties: false,
|
|
4331
|
+
},
|
|
4332
|
+
output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
|
|
4333
|
+
async execute(args) {
|
|
4334
|
+
if (args.confirm !== true) throw new Error('触发 workflow 需要确认:传 confirm: true')
|
|
4335
|
+
await requireWrite('workflowsWrite')
|
|
4336
|
+
return audited('workflow.dispatch', `${args.owner}/${args.name}:${args.workflow}`, () =>
|
|
4337
|
+
gh.dispatchNamedWorkflow(args.owner, args.name, args.workflow, args.ref, args.inputs),
|
|
4338
|
+
)
|
|
4339
|
+
},
|
|
4340
|
+
})
|
|
4341
|
+
|
|
4342
|
+
register({
|
|
4343
|
+
name: 'gh_actions_log',
|
|
4344
|
+
description:
|
|
4345
|
+
'Read the end of a workflow run log (the archive is unzipped and the step log tail is returned). Useful to explain why a run failed.',
|
|
4346
|
+
parameters: {
|
|
4347
|
+
type: 'object',
|
|
4348
|
+
properties: {
|
|
4349
|
+
owner: { type: 'string' },
|
|
4350
|
+
name: { type: 'string' },
|
|
4351
|
+
runId: { type: 'integer', minimum: 1 },
|
|
4352
|
+
tailLines: { type: 'integer', minimum: 10, maximum: 2000, description: 'How many trailing lines, default 120' },
|
|
4353
|
+
},
|
|
4354
|
+
required: ['owner', 'name', 'runId'],
|
|
4355
|
+
additionalProperties: false,
|
|
4356
|
+
},
|
|
4357
|
+
output: { schema: { type: 'object' }, render: (args, value) => [{ type: 'text', text: String(value.tail || value.name || '') }] },
|
|
4358
|
+
async execute(args) {
|
|
4359
|
+
return gh.runLog(args.owner, args.name, args.runId, args.tailLines || 120)
|
|
4360
|
+
},
|
|
4361
|
+
})
|
|
4362
|
+
|
|
4363
|
+
register({
|
|
4364
|
+
name: 'plugin_publish_status',
|
|
4365
|
+
description: 'Read a publish job by id, including each step state and detail.',
|
|
4366
|
+
parameters: {
|
|
4367
|
+
type: 'object',
|
|
4368
|
+
properties: { jobId: { type: 'string' } },
|
|
4369
|
+
required: ['jobId'],
|
|
4370
|
+
additionalProperties: false,
|
|
4371
|
+
},
|
|
4372
|
+
output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
|
|
4373
|
+
async execute(args) {
|
|
4374
|
+
const job = jobs.get(args.jobId)
|
|
4375
|
+
if (!job) throw new Error(`没有任务 ${args.jobId}`)
|
|
4376
|
+
return job
|
|
4377
|
+
},
|
|
4378
|
+
})
|
|
4379
|
+
|
|
4380
|
+
register({
|
|
4381
|
+
name: 'plugin_market_probe',
|
|
4382
|
+
description:
|
|
4383
|
+
'Check whether a plugin is published and indexed: npm package, the GitHub dsh-plugin topic, the release tag, and any configured market index URLs. A failed probe reports unknown, never absent.',
|
|
4384
|
+
parameters: {
|
|
4385
|
+
type: 'object',
|
|
4386
|
+
properties: {
|
|
4387
|
+
name: { type: 'string', description: 'npm package name' },
|
|
4388
|
+
owner: { type: 'string' },
|
|
4389
|
+
repo: { type: 'string' },
|
|
4390
|
+
version: { type: 'string' },
|
|
4391
|
+
},
|
|
4392
|
+
required: ['name'],
|
|
4393
|
+
additionalProperties: false,
|
|
4394
|
+
},
|
|
4395
|
+
output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
|
|
4396
|
+
async execute(args) {
|
|
4397
|
+
return probeMarket(args, gh, cfg)
|
|
4398
|
+
},
|
|
4399
|
+
})
|
|
4400
|
+
}
|