dsh-github-console 0.5.0 → 0.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/workflows/ci.yml +19 -0
- package/.github/workflows/publish.yml +31 -0
- package/README.md +34 -10
- package/index.js +296 -180
- package/lib/collect.mjs +73 -0
- package/lib/pure.mjs +196 -0
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +3 -2
- package/scripts/check.mjs +79 -0
- package/test/collect.test.mjs +61 -0
- package/test/pure.test.mjs +137 -0
package/index.js
CHANGED
|
@@ -22,8 +22,10 @@ import https from 'node:https'
|
|
|
22
22
|
import zlib from 'node:zlib'
|
|
23
23
|
import { fileURLToPath } from 'node:url'
|
|
24
24
|
import { promises as dnsPromises, Resolver } from 'node:dns'
|
|
25
|
+
import { capabilityFor, isDeniedFile, isProtectedRemotePath, marketIndexDocument, unzipEntries } from './lib/pure.mjs'
|
|
26
|
+
import { collectFiles } from './lib/collect.mjs'
|
|
25
27
|
|
|
26
|
-
const PLUGIN_VERSION = '0.
|
|
28
|
+
const PLUGIN_VERSION = '0.6.2'
|
|
27
29
|
const APP_CRED = 'github-console/app'
|
|
28
30
|
const INSTALL_CRED = 'github-console/install'
|
|
29
31
|
const BRIDGE_CRED = 'github-console/bridge'
|
|
@@ -51,7 +53,6 @@ for (const key of [APP_CRED, INSTALL_CRED, BRIDGE_CRED, INDEX_CRED, PAT_CRED, AU
|
|
|
51
53
|
|
|
52
54
|
// Only machine-local or VCS internals are skipped: a bundle's runtime entry can
|
|
53
55
|
// 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
56
|
const SECRET_PATTERNS = [
|
|
56
57
|
['GitHub token', /\b(gh[pousr]_[A-Za-z0-9]{16,}|github_pat_[A-Za-z0-9_]{20,})\b/],
|
|
57
58
|
['private key', /-----BEGIN [A-Z ]*PRIVATE KEY-----/],
|
|
@@ -216,10 +217,23 @@ function auditPath() {
|
|
|
216
217
|
return path.join(home, 'storages', 'dsh-github-console', 'audit.ndjson')
|
|
217
218
|
}
|
|
218
219
|
|
|
220
|
+
const AUDIT_ROTATE_BYTES = 2 * 1024 * 1024
|
|
221
|
+
|
|
222
|
+
async function rotateAuditIfNeeded(target) {
|
|
223
|
+
const stat = await fs.stat(target).catch(() => null)
|
|
224
|
+
if (!stat || stat.size < AUDIT_ROTATE_BYTES) return
|
|
225
|
+
// Keep exactly one previous file: the trail runs for years, the disk does not.
|
|
226
|
+
await fs.rename(target, `${target}.1`).catch(async () => {
|
|
227
|
+
await fs.rm(`${target}.1`, { force: true }).catch(() => {})
|
|
228
|
+
await fs.rename(target, `${target}.1`).catch(() => {})
|
|
229
|
+
})
|
|
230
|
+
}
|
|
231
|
+
|
|
219
232
|
async function appendAudit(entry) {
|
|
220
233
|
try {
|
|
221
234
|
const target = auditPath()
|
|
222
235
|
await fs.mkdir(path.dirname(target), { recursive: true })
|
|
236
|
+
await rotateAuditIfNeeded(target)
|
|
223
237
|
await fs.appendFile(target, `${JSON.stringify({ at: new Date().toISOString(), ...entry })}\n`, 'utf8')
|
|
224
238
|
} catch {
|
|
225
239
|
/* auditing never breaks an action */
|
|
@@ -518,7 +532,11 @@ function createTransport(cfg) {
|
|
|
518
532
|
const failures = []
|
|
519
533
|
// One transient timeout must not fail a publish: retry the whole route set
|
|
520
534
|
// a couple of times, re-probing the proxy so one that just came up is seen.
|
|
521
|
-
|
|
535
|
+
// Only idempotent requests are retried: a POST that timed out may already
|
|
536
|
+
// have created the issue/comment, and a blind retry duplicates it.
|
|
537
|
+
const methodText = String(options.method || 'GET').toUpperCase()
|
|
538
|
+
const idempotent = methodText === 'GET' || methodText === 'HEAD' || methodText === 'PUT' || methodText === 'OPTIONS'
|
|
539
|
+
const backoff = idempotent ? [0, 800, 2500] : [0]
|
|
522
540
|
for (let round = 0; round < backoff.length; round++) {
|
|
523
541
|
if (backoff[round]) await new Promise((resolve) => setTimeout(resolve, backoff[round]))
|
|
524
542
|
const proxy = await detectProxy(round > 0)
|
|
@@ -797,8 +815,36 @@ function createGithub(ctx, cfg, transport) {
|
|
|
797
815
|
return `${signingInput}.${signature}`
|
|
798
816
|
}
|
|
799
817
|
|
|
818
|
+
|
|
800
819
|
async function call(pathname, options = {}) {
|
|
801
820
|
const { method = 'GET', body, auth = 'auto', headers = {}, rawBody = false } = options
|
|
821
|
+
// The single exit for every GitHub request: readOnly and capability checks
|
|
822
|
+
// live here so no caller (tool or route) can bypass them, and every write
|
|
823
|
+
// leaves one audit record.
|
|
824
|
+
const isWrite = method !== 'GET' && method !== 'HEAD'
|
|
825
|
+
let writeAuth = null
|
|
826
|
+
if (isWrite) {
|
|
827
|
+
if (cfg.readOnly) {
|
|
828
|
+
await appendAudit({ action: `${method} ${pathname}`, ok: false, detail: 'readOnly' })
|
|
829
|
+
throw new GhError(403, 'READ_ONLY', '只读模式已开启(readOnly: true),写操作已拒绝')
|
|
830
|
+
}
|
|
831
|
+
const needed = capabilityFor(pathname, method)
|
|
832
|
+
if (needed && auth === 'auto') {
|
|
833
|
+
const current = await resolveAuth()
|
|
834
|
+
if (current.kind !== 'none') {
|
|
835
|
+
writeAuth = current
|
|
836
|
+
const capabilities = capabilitiesOf(current)
|
|
837
|
+
if (!capabilities[needed]) {
|
|
838
|
+
await appendAudit({ action: `${method} ${pathname}`, ok: false, detail: `missing ${needed}` })
|
|
839
|
+
throw new GhError(
|
|
840
|
+
403,
|
|
841
|
+
'NO_CAPABILITY',
|
|
842
|
+
`当前连接(${current.kind})没有 ${needed} 权限:到「状态 → 连接方式」换一个带写权限的连接`,
|
|
843
|
+
)
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
}
|
|
802
848
|
const init = { method, headers: { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28', ...headers } }
|
|
803
849
|
if (auth === 'app') {
|
|
804
850
|
const app = await readApp()
|
|
@@ -880,8 +926,23 @@ function createGithub(ctx, cfg, transport) {
|
|
|
880
926
|
code === 'RATE_LIMITED' && reset
|
|
881
927
|
? `(限流重置于 ${new Date(Number(reset) * 1000).toLocaleString()})`
|
|
882
928
|
: ''
|
|
929
|
+
if (isWrite) {
|
|
930
|
+
await appendAudit({
|
|
931
|
+
action: `${method} ${pathname}`,
|
|
932
|
+
ok: false,
|
|
933
|
+
detail: `${response.status} ${code}`,
|
|
934
|
+
account: writeAuth ? writeAuth.kind : '',
|
|
935
|
+
})
|
|
936
|
+
}
|
|
883
937
|
throw new GhError(response.status, code, `${message}${suffix}`, data)
|
|
884
938
|
}
|
|
939
|
+
if (isWrite) {
|
|
940
|
+
await appendAudit({
|
|
941
|
+
action: `${method} ${pathname}`,
|
|
942
|
+
ok: true,
|
|
943
|
+
account: writeAuth ? writeAuth.kind : '',
|
|
944
|
+
})
|
|
945
|
+
}
|
|
885
946
|
return data
|
|
886
947
|
}
|
|
887
948
|
|
|
@@ -1031,6 +1092,7 @@ function createGithub(ctx, cfg, transport) {
|
|
|
1031
1092
|
}
|
|
1032
1093
|
|
|
1033
1094
|
let authCache = null
|
|
1095
|
+
let rateLimitCache = null
|
|
1034
1096
|
|
|
1035
1097
|
/** The App's own OAuth callback must be registered before the authorize step. */
|
|
1036
1098
|
async function ensureOAuthCallback(origin) {
|
|
@@ -1442,8 +1504,33 @@ function createGithub(ctx, cfg, transport) {
|
|
|
1442
1504
|
const patToken = await readPat().catch(() => '')
|
|
1443
1505
|
const oauthState = await readRecord(OAUTH_CRED).catch(() => undefined)
|
|
1444
1506
|
const envToken = process.env[cfg.patEnvName] || ''
|
|
1507
|
+
// Real rate-limit headroom, so a panel user can see the wall before hitting it.
|
|
1508
|
+
let limits = null
|
|
1509
|
+
try {
|
|
1510
|
+
const now = Date.now()
|
|
1511
|
+
if (!rateLimitCache || now - rateLimitCache.at > 60000) {
|
|
1512
|
+
const json = await call('/rate_limit')
|
|
1513
|
+
rateLimitCache = { at: now, value: json }
|
|
1514
|
+
}
|
|
1515
|
+
const resources = (rateLimitCache.value && rateLimitCache.value.resources) || {}
|
|
1516
|
+
limits = Object.fromEntries(
|
|
1517
|
+
['core', 'search', 'graphql']
|
|
1518
|
+
.filter((key) => resources[key])
|
|
1519
|
+
.map((key) => [
|
|
1520
|
+
key,
|
|
1521
|
+
{
|
|
1522
|
+
limit: resources[key].limit,
|
|
1523
|
+
remaining: resources[key].remaining,
|
|
1524
|
+
resetAt: resources[key].reset ? new Date(resources[key].reset * 1000).toISOString() : null,
|
|
1525
|
+
},
|
|
1526
|
+
]),
|
|
1527
|
+
)
|
|
1528
|
+
} catch {
|
|
1529
|
+
limits = null
|
|
1530
|
+
}
|
|
1445
1531
|
const base = {
|
|
1446
1532
|
version: PLUGIN_VERSION,
|
|
1533
|
+
limits,
|
|
1447
1534
|
apiBase: cfg.baseUrl,
|
|
1448
1535
|
configured: Boolean(app),
|
|
1449
1536
|
app: app
|
|
@@ -1864,7 +1951,11 @@ function createGithub(ctx, cfg, transport) {
|
|
|
1864
1951
|
|
|
1865
1952
|
async function runLog(owner, name, runId, tailLines = 120) {
|
|
1866
1953
|
const repo = repoPath(owner, name)
|
|
1867
|
-
|
|
1954
|
+
// A log download is a read of the run, so it must work with any connection,
|
|
1955
|
+
// not only an App installation token.
|
|
1956
|
+
const current = await resolveAuth()
|
|
1957
|
+
const token = current.kind === 'app' ? await installationToken() : current.token
|
|
1958
|
+
if (!token) throw new GhError(401, 'AUTH_MISSING', '还没有可用的 GitHub 连接')
|
|
1868
1959
|
// The archive answers 302 to a signed objects.githubusercontent.com URL, and
|
|
1869
1960
|
// both hosts are hijacked on some machines, so follow the redirect through
|
|
1870
1961
|
// the same resilient transport instead of global fetch.
|
|
@@ -2009,44 +2100,6 @@ async function exists(target) {
|
|
|
2009
2100
|
}
|
|
2010
2101
|
}
|
|
2011
2102
|
|
|
2012
|
-
async function collectFiles(root, budget) {
|
|
2013
|
-
const files = []
|
|
2014
|
-
let total = 0
|
|
2015
|
-
let skipped = 0
|
|
2016
|
-
async function walk(dir) {
|
|
2017
|
-
let entries = []
|
|
2018
|
-
try {
|
|
2019
|
-
entries = await fs.readdir(dir, { withFileTypes: true })
|
|
2020
|
-
} catch {
|
|
2021
|
-
return
|
|
2022
|
-
}
|
|
2023
|
-
for (const entry of entries) {
|
|
2024
|
-
if (files.length >= 300) return
|
|
2025
|
-
const full = path.join(dir, entry.name)
|
|
2026
|
-
if (entry.isDirectory()) {
|
|
2027
|
-
if (SKIP_DIRS.has(entry.name)) continue
|
|
2028
|
-
await walk(full)
|
|
2029
|
-
continue
|
|
2030
|
-
}
|
|
2031
|
-
if (!entry.isFile()) continue
|
|
2032
|
-
const stat = await fs.stat(full).catch(() => null)
|
|
2033
|
-
if (!stat) continue
|
|
2034
|
-
if (stat.size > 1024 * 1024) {
|
|
2035
|
-
skipped += 1
|
|
2036
|
-
continue
|
|
2037
|
-
}
|
|
2038
|
-
if (total + stat.size > budget) {
|
|
2039
|
-
skipped += 1
|
|
2040
|
-
continue
|
|
2041
|
-
}
|
|
2042
|
-
const content = await fs.readFile(full)
|
|
2043
|
-
total += content.length
|
|
2044
|
-
files.push({ path: path.relative(root, full).split(path.sep).join('/'), content })
|
|
2045
|
-
}
|
|
2046
|
-
}
|
|
2047
|
-
await walk(root)
|
|
2048
|
-
return { files, total, skipped }
|
|
2049
|
-
}
|
|
2050
2103
|
|
|
2051
2104
|
function findSecrets(files) {
|
|
2052
2105
|
const hits = []
|
|
@@ -2082,7 +2135,8 @@ async function preflight(dir, gh, cfg) {
|
|
|
2082
2135
|
|
|
2083
2136
|
let pkg = null
|
|
2084
2137
|
try {
|
|
2085
|
-
|
|
2138
|
+
// Strip a UTF-8 BOM: several Windows editors write one and JSON.parse rejects it.
|
|
2139
|
+
pkg = JSON.parse((await fs.readFile(packagePath, 'utf8')).replace(/^\uFEFF/, ''))
|
|
2086
2140
|
add('package.json', 'pass', 'package.json 可解析', `${pkg.name || '未命名'}@${pkg.version || '?'}`)
|
|
2087
2141
|
} catch (error) {
|
|
2088
2142
|
add('package.json', 'block', 'package.json 不是合法 JSON', errorMessage(error))
|
|
@@ -2132,6 +2186,19 @@ async function preflight(dir, gh, cfg) {
|
|
|
2132
2186
|
}
|
|
2133
2187
|
|
|
2134
2188
|
const collected = await collectFiles(root, cfg.maxPushBytes)
|
|
2189
|
+
if (collected.denied.length) {
|
|
2190
|
+
add(
|
|
2191
|
+
'denied-files',
|
|
2192
|
+
'block',
|
|
2193
|
+
`发现 ${collected.denied.length} 个不应发布的敏感文件`,
|
|
2194
|
+
`${collected.denied.slice(0, 6).join(', ')}(按文件名拦截,不依赖内容格式)`,
|
|
2195
|
+
)
|
|
2196
|
+
} else {
|
|
2197
|
+
add('denied-files', 'pass', '没有 .env / .npmrc / 私钥类文件', '')
|
|
2198
|
+
}
|
|
2199
|
+
if (collected.truncated) {
|
|
2200
|
+
add('files', 'block', '文件数超过 300,已中止', '请先排除 dist/ 等生成物,或分批发布')
|
|
2201
|
+
}
|
|
2135
2202
|
const secrets = findSecrets(collected.files)
|
|
2136
2203
|
if (secrets.length) {
|
|
2137
2204
|
add(
|
|
@@ -2153,23 +2220,30 @@ async function preflight(dir, gh, cfg) {
|
|
|
2153
2220
|
}
|
|
2154
2221
|
if (hardPaths.length) add('local-paths', 'warn', '代码里出现本机绝对路径', hardPaths.slice(0, 5).join(', '))
|
|
2155
2222
|
|
|
2156
|
-
add(
|
|
2223
|
+
add(
|
|
2224
|
+
'files',
|
|
2225
|
+
collected.truncated ? 'block' : 'info',
|
|
2226
|
+
`待推送 ${collected.files.length} 个文件`,
|
|
2227
|
+
fmtBytes(collected.total) +
|
|
2228
|
+
(collected.skipped ? `(跳过 ${collected.skipped} 个大文件)` : '') +
|
|
2229
|
+
(collected.truncated ? '(已达到 300 个上限)' : ''),
|
|
2230
|
+
)
|
|
2157
2231
|
|
|
2158
2232
|
if (gh) {
|
|
2159
2233
|
try {
|
|
2160
|
-
const
|
|
2161
|
-
if (
|
|
2162
|
-
const data =
|
|
2234
|
+
const probe = await httpGetJson(`https://registry.npmjs.org/${encodeURIComponent(pkg.name)}`)
|
|
2235
|
+
if (probe.status === 200) {
|
|
2236
|
+
const data = JSON.parse(probe.text || '{}')
|
|
2163
2237
|
const latest = data['dist-tags'] ? data['dist-tags'].latest : ''
|
|
2164
2238
|
if (latest === pkg.version) {
|
|
2165
2239
|
add('npm', 'block', 'npm 上已存在同名同版本', `${pkg.name}@${latest}`)
|
|
2166
2240
|
} else {
|
|
2167
2241
|
add('npm', 'info', 'npm 上已存在该包', `latest ${latest}`)
|
|
2168
2242
|
}
|
|
2169
|
-
} else if (
|
|
2243
|
+
} else if (probe.status === 404) {
|
|
2170
2244
|
add('npm', 'pass', 'npm 上没有同名包', pkg.name)
|
|
2171
2245
|
} else {
|
|
2172
|
-
add('npm', 'info', 'npm 查询未确认', `HTTP ${
|
|
2246
|
+
add('npm', 'info', 'npm 查询未确认', `HTTP ${probe.status}`)
|
|
2173
2247
|
}
|
|
2174
2248
|
} catch (error) {
|
|
2175
2249
|
add('npm', 'info', 'npm 查询失败', errorMessage(error))
|
|
@@ -2262,9 +2336,31 @@ async function pushFiles(gh, owner, name, branch, files, message) {
|
|
|
2262
2336
|
}
|
|
2263
2337
|
|
|
2264
2338
|
stage = 'create-tree'
|
|
2265
|
-
const
|
|
2266
|
-
|
|
2339
|
+
const entries = files.map((file, index) => ({
|
|
2340
|
+
path: file.path,
|
|
2341
|
+
// Keep executable files executable; everything else stays 100644.
|
|
2342
|
+
mode: file.mode || '100644',
|
|
2343
|
+
type: 'blob',
|
|
2344
|
+
sha: blobs[index],
|
|
2345
|
+
}))
|
|
2346
|
+
let deleted = 0
|
|
2347
|
+
if (baseTreeSha) {
|
|
2348
|
+
// A tree with base_tree is a patch: without explicit `sha: null` entries,
|
|
2349
|
+
// files deleted locally stay in the repository forever.
|
|
2350
|
+
stage = 'diff-remote-tree'
|
|
2351
|
+
const remote = await gh.call(`${repo}/git/trees/${baseTreeSha}?recursive=1`).catch(() => null)
|
|
2352
|
+
const remotePaths =
|
|
2353
|
+
remote && Array.isArray(remote.tree) ? remote.tree.filter((item) => item.type === 'blob').map((item) => item.path) : []
|
|
2354
|
+
const local = new Set(files.map((file) => file.path))
|
|
2355
|
+
const stale = remotePaths.filter(
|
|
2356
|
+
(filePath) => !local.has(filePath) && !isDeniedFile(filePath) && !isProtectedRemotePath(filePath),
|
|
2357
|
+
)
|
|
2358
|
+
deleted = stale.length
|
|
2359
|
+
for (const filePath of stale) {
|
|
2360
|
+
entries.push({ path: filePath, mode: '100644', type: 'blob', sha: null })
|
|
2361
|
+
}
|
|
2267
2362
|
}
|
|
2363
|
+
const treeBody = { tree: entries }
|
|
2268
2364
|
if (baseTreeSha) treeBody.base_tree = baseTreeSha
|
|
2269
2365
|
const tree = await gh.call(`${repo}/git/trees`, { method: 'POST', body: treeBody })
|
|
2270
2366
|
|
|
@@ -2285,7 +2381,26 @@ async function pushFiles(gh, owner, name, branch, files, message) {
|
|
|
2285
2381
|
body: { ref: `refs/heads/${branch}`, sha: commit.sha },
|
|
2286
2382
|
})
|
|
2287
2383
|
}
|
|
2288
|
-
|
|
2384
|
+
// Read the committed tree back: GitHub is the source of truth for modes, and
|
|
2385
|
+
// this catches an executable file that silently landed as 100644.
|
|
2386
|
+
let modeChecked = 0
|
|
2387
|
+
let modeMismatch = 0
|
|
2388
|
+
const executables = new Set(files.filter((file) => file.mode === '100755').map((file) => file.path))
|
|
2389
|
+
if (executables.size) {
|
|
2390
|
+
const committed = await gh.call(`${repo}/git/trees/${commit.sha}?recursive=1`).catch(() => null)
|
|
2391
|
+
const remoteModes = new Map(
|
|
2392
|
+
committed && Array.isArray(committed.tree)
|
|
2393
|
+
? committed.tree.filter((item) => item.type === 'blob').map((item) => [item.path, item.mode])
|
|
2394
|
+
: [],
|
|
2395
|
+
)
|
|
2396
|
+
for (const filePath of executables) {
|
|
2397
|
+
const mode = remoteModes.get(filePath)
|
|
2398
|
+
if (!mode) continue
|
|
2399
|
+
modeChecked += 1
|
|
2400
|
+
if (mode !== '100755') modeMismatch += 1
|
|
2401
|
+
}
|
|
2402
|
+
}
|
|
2403
|
+
return { commit: commit.sha, files: files.length, branch, firstCommit: bootstrapped, deleted, modeChecked, modeMismatch }
|
|
2289
2404
|
} catch (error) {
|
|
2290
2405
|
// Naming the failed stage turns "Git Repository is empty." into something
|
|
2291
2406
|
// actionable instead of a single opaque message.
|
|
@@ -2509,6 +2624,25 @@ async function marketReadiness(gh, cfg, { owner, repo, dir }) {
|
|
|
2509
2624
|
)
|
|
2510
2625
|
}
|
|
2511
2626
|
|
|
2627
|
+
// Direct pushes fail on a protected branch, so say it before the user tries.
|
|
2628
|
+
const protection = await gh
|
|
2629
|
+
.call(`${repoPath}/branches/${encodeURIComponent(cfg.publishBranch)}/protection`)
|
|
2630
|
+
.then((body) => ({ protected: true, body }))
|
|
2631
|
+
.catch((error) => (error && error.status === 404 ? { protected: false } : { protected: null, error: errorMessage(error) }))
|
|
2632
|
+
if (protection.protected === true) {
|
|
2633
|
+
const reviews = protection.body && protection.body.required_pull_request_reviews
|
|
2634
|
+
add(
|
|
2635
|
+
'branch-protection',
|
|
2636
|
+
'warn',
|
|
2637
|
+
`${cfg.publishBranch} 启用了分支保护`,
|
|
2638
|
+
`需要 PR 或评审${reviews ? '(至少 ' + (reviews.required_approving_review_count || 1) + ' 个批准)' : ''};直接推送会被拒,请先放开或改用 PR 流程`,
|
|
2639
|
+
)
|
|
2640
|
+
} else if (protection.protected === false) {
|
|
2641
|
+
add('branch-protection', 'pass', `${cfg.publishBranch} 未启用分支保护`, '可以直接推送')
|
|
2642
|
+
} else {
|
|
2643
|
+
add('branch-protection', 'info', '读不到分支保护状态', protection.error || '')
|
|
2644
|
+
}
|
|
2645
|
+
|
|
2512
2646
|
const iconCandidates = ['assets/icon-512.png', 'assets/icon-180.png', 'icon.png', 'assets/icon.png']
|
|
2513
2647
|
let iconPath = ''
|
|
2514
2648
|
for (const candidate of iconCandidates) {
|
|
@@ -2586,9 +2720,25 @@ async function ensurePublishWorkflow(gh, owner, repo, branch, workflowFile) {
|
|
|
2586
2720
|
|
|
2587
2721
|
async function dispatchWorkflow(gh, owner, repo, workflowFile, ref, inputs) {
|
|
2588
2722
|
const body = inputs && Object.keys(inputs).length ? { ref, inputs } : { ref }
|
|
2589
|
-
|
|
2590
|
-
|
|
2591
|
-
|
|
2723
|
+
const url = `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/actions/workflows/${encodeURIComponent(workflowFile)}/dispatches`
|
|
2724
|
+
// GitHub indexes a new or changed workflow file within seconds; until then the
|
|
2725
|
+
// dispatch answers 404 "No workflow found". Retry only that case.
|
|
2726
|
+
let lastError = null
|
|
2727
|
+
for (const wait of [0, 1000, 2000, 4000, 8000]) {
|
|
2728
|
+
if (wait) await new Promise((resolve) => setTimeout(resolve, wait))
|
|
2729
|
+
try {
|
|
2730
|
+
await gh.call(url, { method: 'POST', body })
|
|
2731
|
+
return { dispatched: true, attempts: wait ? wait : 1 }
|
|
2732
|
+
} catch (error) {
|
|
2733
|
+
if (error.status !== 404) throw error
|
|
2734
|
+
lastError = error
|
|
2735
|
+
}
|
|
2736
|
+
}
|
|
2737
|
+
throw new GhError(
|
|
2738
|
+
404,
|
|
2739
|
+
'WORKFLOW_NOT_FOUND',
|
|
2740
|
+
`${workflowFile} 已提交但 GitHub 尚未索引它;稍等几秒再点一次即可`,
|
|
2741
|
+
{ cause: lastError ? lastError.message : '' },
|
|
2592
2742
|
)
|
|
2593
2743
|
}
|
|
2594
2744
|
|
|
@@ -2616,44 +2766,10 @@ async function waitForWorkflowRun(gh, owner, repo, workflowFile, sinceMs, timeou
|
|
|
2616
2766
|
return last ? { ...last, status: 'timeout' } : { status: 'unknown', url: null }
|
|
2617
2767
|
}
|
|
2618
2768
|
|
|
2619
|
-
function marketIndexDocument({ pkg, owner, repo, commit, entryTitle, entryDescription }) {
|
|
2620
|
-
const repositoryUrl = `https://github.com/${owner}/${repo}`
|
|
2621
|
-
const engines =
|
|
2622
|
-
pkg.engines && typeof pkg.engines.dsh === 'string' && pkg.engines.dsh.trim() && !pkg.engines.dsh.startsWith('workspace:')
|
|
2623
|
-
? { dsh: pkg.engines.dsh.trim() }
|
|
2624
|
-
: {}
|
|
2625
|
-
const plugin = {
|
|
2626
|
-
name: pkg.name,
|
|
2627
|
-
title: entryTitle || pkg.name,
|
|
2628
|
-
description: entryDescription || pkg.description || pkg.name,
|
|
2629
|
-
// Resolved against the index URL, so the icon ships with the repository.
|
|
2630
|
-
icon: '../icon.svg',
|
|
2631
|
-
author: owner,
|
|
2632
|
-
repository: { url: repositoryUrl },
|
|
2633
|
-
metadata: {
|
|
2634
|
-
keywords: Array.isArray(pkg.keywords) ? pkg.keywords.filter((item) => typeof item === 'string').slice(0, 20) : [],
|
|
2635
|
-
},
|
|
2636
|
-
versions: [
|
|
2637
|
-
{
|
|
2638
|
-
version: pkg.version,
|
|
2639
|
-
publishTimestamp: Math.floor(Date.now() / 1000),
|
|
2640
|
-
source: { type: 'git', url: repositoryUrl, commit },
|
|
2641
|
-
engines,
|
|
2642
|
-
},
|
|
2643
|
-
],
|
|
2644
|
-
}
|
|
2645
|
-
if (pkg.homepage && /^https?:\/\//.test(pkg.homepage)) plugin.homepage = pkg.homepage
|
|
2646
|
-
return {
|
|
2647
|
-
format: 1,
|
|
2648
|
-
title: `${owner} DSH plugin index`,
|
|
2649
|
-
description: 'Self-hosted DSH plugin index generated by the GitHub console.',
|
|
2650
|
-
metadata: {},
|
|
2651
|
-
plugins: [plugin],
|
|
2652
|
-
}
|
|
2653
|
-
}
|
|
2654
2769
|
|
|
2655
2770
|
async function readLocalPackage(dir) {
|
|
2656
|
-
|
|
2771
|
+
// Strip a UTF-8 BOM: several Windows editors write one and JSON.parse rejects it.
|
|
2772
|
+
const raw = (await fs.readFile(path.join(dir, 'package.json'), 'utf8')).replace(/^\uFEFF/, '')
|
|
2657
2773
|
const pkg = JSON.parse(raw)
|
|
2658
2774
|
if (!pkg.name || !pkg.version) throw new Error('package.json 缺少 name 或 version')
|
|
2659
2775
|
return pkg
|
|
@@ -2672,10 +2788,8 @@ async function npmPublishState(gh, cfg, { owner, repo, dir }) {
|
|
|
2672
2788
|
let exists = null
|
|
2673
2789
|
if (name) {
|
|
2674
2790
|
try {
|
|
2675
|
-
const
|
|
2676
|
-
|
|
2677
|
-
})
|
|
2678
|
-
exists = response.status === 200
|
|
2791
|
+
const probe = await httpGetJson(`https://registry.npmjs.org/${encodeURIComponent(name)}`)
|
|
2792
|
+
exists = probe.status === 200
|
|
2679
2793
|
} catch {
|
|
2680
2794
|
exists = null
|
|
2681
2795
|
}
|
|
@@ -2736,69 +2850,47 @@ async function npmPublishState(gh, cfg, { owner, repo, dir }) {
|
|
|
2736
2850
|
}
|
|
2737
2851
|
}
|
|
2738
2852
|
|
|
2739
|
-
|
|
2740
|
-
|
|
2741
|
-
|
|
2742
|
-
|
|
2743
|
-
|
|
2744
|
-
|
|
2745
|
-
|
|
2746
|
-
|
|
2747
|
-
|
|
2748
|
-
|
|
2853
|
+
|
|
2854
|
+
/** Set once by apply(): every outbound JSON request shares the same routing. */
|
|
2855
|
+
let sharedTransport = null
|
|
2856
|
+
|
|
2857
|
+
/**
|
|
2858
|
+
* JSON over the plugin's transport, so npm and market probes obey the same
|
|
2859
|
+
* proxy / DNS / CA settings as GitHub requests instead of bypassing them.
|
|
2860
|
+
*/
|
|
2861
|
+
async function httpGetJson(url, options = {}) {
|
|
2862
|
+
const headers = {
|
|
2863
|
+
'User-Agent': `dsh-github-console/${PLUGIN_VERSION}`,
|
|
2864
|
+
Accept: 'application/json',
|
|
2865
|
+
...(options.headers || {}),
|
|
2866
|
+
}
|
|
2867
|
+
if (sharedTransport) {
|
|
2868
|
+
const response = await sharedTransport.request(url, {
|
|
2869
|
+
method: options.method || 'GET',
|
|
2870
|
+
headers,
|
|
2871
|
+
body: options.body,
|
|
2872
|
+
})
|
|
2873
|
+
return { status: response.status, text: response.text }
|
|
2749
2874
|
}
|
|
2750
|
-
const
|
|
2751
|
-
|
|
2752
|
-
|
|
2753
|
-
|
|
2754
|
-
|
|
2755
|
-
|
|
2756
|
-
|
|
2757
|
-
|
|
2758
|
-
|
|
2759
|
-
|
|
2760
|
-
|
|
2761
|
-
|
|
2762
|
-
|
|
2763
|
-
|
|
2764
|
-
|
|
2765
|
-
|
|
2766
|
-
|
|
2767
|
-
|
|
2768
|
-
if (eocd >= 0) {
|
|
2769
|
-
const count = buffer.readUInt16LE(eocd + 10)
|
|
2770
|
-
let offset = buffer.readUInt32LE(eocd + 16)
|
|
2771
|
-
for (let index = 0; index < count; index++) {
|
|
2772
|
-
if (buffer.readUInt32LE(offset) !== 0x02014b50) break
|
|
2773
|
-
const nameLength = buffer.readUInt16LE(offset + 28)
|
|
2774
|
-
const extraLength = buffer.readUInt16LE(offset + 30)
|
|
2775
|
-
const commentLength = buffer.readUInt16LE(offset + 32)
|
|
2776
|
-
read(offset, nameLength, extraLength)
|
|
2777
|
-
offset += 46 + nameLength + extraLength + commentLength
|
|
2778
|
-
}
|
|
2779
|
-
if (entries.length) return entries
|
|
2780
|
-
}
|
|
2781
|
-
// Fallback: walk local headers (works when sizes are present).
|
|
2782
|
-
let offset = 0
|
|
2783
|
-
while (offset + 30 <= buffer.length) {
|
|
2784
|
-
if (buffer.readUInt32LE(offset) !== 0x04034b50) break
|
|
2785
|
-
const method = buffer.readUInt16LE(offset + 8)
|
|
2786
|
-
const compressed = buffer.readUInt32LE(offset + 18)
|
|
2787
|
-
const nameLength = buffer.readUInt16LE(offset + 26)
|
|
2788
|
-
const extraLength = buffer.readUInt16LE(offset + 28)
|
|
2789
|
-
const name = buffer.subarray(offset + 30, offset + 30 + nameLength).toString('utf8')
|
|
2790
|
-
const dataStart = offset + 30 + nameLength + extraLength
|
|
2791
|
-
const data = buffer.subarray(dataStart, dataStart + compressed)
|
|
2792
|
-
let text = ''
|
|
2793
|
-
try {
|
|
2794
|
-
text = method === 0 ? data.toString('utf8') : zlib.inflateRawSync(data).toString('utf8')
|
|
2795
|
-
} catch {
|
|
2796
|
-
text = ''
|
|
2797
|
-
}
|
|
2798
|
-
entries.push({ name, text })
|
|
2799
|
-
offset = dataStart + compressed
|
|
2875
|
+
const response = await fetch(url, { method: options.method || 'GET', headers })
|
|
2876
|
+
return { status: response.status, text: await response.text() }
|
|
2877
|
+
}
|
|
2878
|
+
|
|
2879
|
+
/** Prefer a raster icon when the repository ships one. */
|
|
2880
|
+
async function detectLocalIcon(dir) {
|
|
2881
|
+
for (const candidate of ['assets/icon-512.png', 'assets/icon-180.png', 'icon.png', 'assets/icon.png']) {
|
|
2882
|
+
if (await exists(path.join(dir, candidate))) return candidate
|
|
2883
|
+
}
|
|
2884
|
+
return ''
|
|
2885
|
+
}
|
|
2886
|
+
|
|
2887
|
+
function parseIndexFile(file) {
|
|
2888
|
+
if (!file || typeof file.text !== 'string' || !file.text) return null
|
|
2889
|
+
try {
|
|
2890
|
+
return JSON.parse(file.text)
|
|
2891
|
+
} catch {
|
|
2892
|
+
return null
|
|
2800
2893
|
}
|
|
2801
|
-
return entries
|
|
2802
2894
|
}
|
|
2803
2895
|
|
|
2804
2896
|
async function probeMarket(input, gh, cfg) {
|
|
@@ -2808,9 +2900,9 @@ async function probeMarket(input, gh, cfg) {
|
|
|
2808
2900
|
|
|
2809
2901
|
// 1. npm package presence
|
|
2810
2902
|
try {
|
|
2811
|
-
const response = await
|
|
2903
|
+
const response = await httpGetJson(`https://registry.npmjs.org/${encodeURIComponent(input.name)}/latest`)
|
|
2812
2904
|
if (response.status === 200) {
|
|
2813
|
-
const data =
|
|
2905
|
+
const data = JSON.parse(response.text || '{}')
|
|
2814
2906
|
push('npm', 'listed', `${input.name}@${data.version}`, { version: data.version })
|
|
2815
2907
|
} else if (response.status === 404) {
|
|
2816
2908
|
push('npm', 'absent', 'npm 上没有这个包名')
|
|
@@ -2859,12 +2951,12 @@ async function probeMarket(input, gh, cfg) {
|
|
|
2859
2951
|
// 3. Configured market indexes (format 1 JSON with an items/plugins array)
|
|
2860
2952
|
for (const url of cfg.marketIndexUrls) {
|
|
2861
2953
|
try {
|
|
2862
|
-
const response = await
|
|
2863
|
-
if (
|
|
2954
|
+
const response = await httpGetJson(url)
|
|
2955
|
+
if (response.status < 200 || response.status >= 300) {
|
|
2864
2956
|
push(`index:${url}`, 'unknown', `HTTP ${response.status}`)
|
|
2865
2957
|
continue
|
|
2866
2958
|
}
|
|
2867
|
-
const text =
|
|
2959
|
+
const text = response.text
|
|
2868
2960
|
const found = text.includes(`"${input.name}"`) || text.includes(`"${input.name}@`)
|
|
2869
2961
|
push(`index:${url}`, found ? 'listed' : 'absent', found ? '索引里出现该包名' : '索引里没有该包名')
|
|
2870
2962
|
} catch (error) {
|
|
@@ -2965,7 +3057,13 @@ async function runPublish({ job, gh, cfg, dir, owner, repo, version, notes, opts
|
|
|
2965
3057
|
const collected = await collectFiles(path.resolve(dir), cfg.maxPushBytes)
|
|
2966
3058
|
const pushed = await pushFiles(gh, owner, repo, branch, collected.files, opts.message || `chore(release): v${semver}`)
|
|
2967
3059
|
step(job, 'push').state = 'done'
|
|
2968
|
-
step(job, 'push').detail =
|
|
3060
|
+
step(job, 'push').detail =
|
|
3061
|
+
`${pushed.files} 个文件 → ${branch} @ ${pushed.commit.slice(0, 7)}` +
|
|
3062
|
+
(pushed.deleted ? `,删除远端 ${pushed.deleted} 个过期文件` : '') +
|
|
3063
|
+
(pushed.modeChecked
|
|
3064
|
+
? `,执行位已校验 ${pushed.modeChecked} 个${pushed.modeMismatch ? `(其中 ${pushed.modeMismatch} 个仍是 100644)` : ''}`
|
|
3065
|
+
: '') +
|
|
3066
|
+
(pushed.firstCommit ? '(仓库原本为空,这是首个提交)' : '')
|
|
2969
3067
|
job.commit = pushed.commit
|
|
2970
3068
|
} catch (error) {
|
|
2971
3069
|
step(job, 'push').state = 'failed'
|
|
@@ -2978,8 +3076,10 @@ async function runPublish({ job, gh, cfg, dir, owner, repo, version, notes, opts
|
|
|
2978
3076
|
step(job, 'topics').state = 'done'
|
|
2979
3077
|
step(job, 'topics').detail = topics.after.join(', ')
|
|
2980
3078
|
} catch (error) {
|
|
2981
|
-
|
|
2982
|
-
|
|
3079
|
+
// Topics need Administration: write, which the manifest deliberately does
|
|
3080
|
+
// not request — the release itself is already done at this point.
|
|
3081
|
+
step(job, 'topics').state = 'done'
|
|
3082
|
+
step(job, 'topics').detail = `已跳过(可选权限 Administration: write):${errorMessage(error)}`
|
|
2983
3083
|
}
|
|
2984
3084
|
|
|
2985
3085
|
try {
|
|
@@ -3015,6 +3115,7 @@ export const inject = ['tools']
|
|
|
3015
3115
|
export function apply(ctx, rawConfig) {
|
|
3016
3116
|
const cfg = normalizeConfig(rawConfig)
|
|
3017
3117
|
const transport = createTransport(cfg)
|
|
3118
|
+
sharedTransport = transport
|
|
3018
3119
|
const gh = createGithub(ctx, cfg, transport)
|
|
3019
3120
|
const jobs = createJobStore()
|
|
3020
3121
|
let bridgeToken = ''
|
|
@@ -3088,17 +3189,23 @@ export function apply(ctx, rawConfig) {
|
|
|
3088
3189
|
|
|
3089
3190
|
const discover = (extra) => discoverPlugins(discoveryRoots(extra))
|
|
3090
3191
|
|
|
3091
|
-
|
|
3192
|
+
/**
|
|
3193
|
+
* Keep the local copy in step with the committed one. Without this the next
|
|
3194
|
+
* publish collects the stale file from disk and overwrites the fresh index.
|
|
3195
|
+
*/
|
|
3196
|
+
async function persistLocalIndex(dir, doc) {
|
|
3197
|
+
const target = path.join(dir, cfg.marketIndexPath)
|
|
3198
|
+
await fs.mkdir(path.dirname(target), { recursive: true })
|
|
3199
|
+
await fs.writeFile(target, `${JSON.stringify(doc, null, 2)}\n`, 'utf8')
|
|
3200
|
+
return target
|
|
3201
|
+
}
|
|
3202
|
+
|
|
3203
|
+
// Kept as a thin wrapper: audit records are written by gh.call(), the single
|
|
3204
|
+
// exit for GitHub requests, so entry points no longer decide whether to log.
|
|
3092
3205
|
const audited = async (action, target, run) => {
|
|
3093
|
-
|
|
3094
|
-
|
|
3095
|
-
|
|
3096
|
-
await appendAudit({ action, target, ok: true, ms: Date.now() - started })
|
|
3097
|
-
return result
|
|
3098
|
-
} catch (error) {
|
|
3099
|
-
await appendAudit({ action, target, ok: false, detail: errorMessage(error).slice(0, 300), ms: Date.now() - started })
|
|
3100
|
-
throw error
|
|
3101
|
-
}
|
|
3206
|
+
void action
|
|
3207
|
+
void target
|
|
3208
|
+
return run()
|
|
3102
3209
|
}
|
|
3103
3210
|
|
|
3104
3211
|
// Write actions are refused up front when the active connection cannot write.
|
|
@@ -3176,7 +3283,7 @@ export function apply(ctx, rawConfig) {
|
|
|
3176
3283
|
default_permissions: {
|
|
3177
3284
|
metadata: 'read',
|
|
3178
3285
|
contents: 'write',
|
|
3179
|
-
|
|
3286
|
+
|
|
3180
3287
|
pull_requests: 'write',
|
|
3181
3288
|
issues: 'write',
|
|
3182
3289
|
actions: 'write',
|
|
@@ -3530,6 +3637,7 @@ export function apply(ctx, rawConfig) {
|
|
|
3530
3637
|
const ref = await gh.call(`${repoPath}/git/ref/heads/${encodeURIComponent(branch)}`)
|
|
3531
3638
|
const commit = ref.object ? ref.object.sha : ''
|
|
3532
3639
|
if (!commit) return sendJson(response, 400, { error: `读不到 ${branch} 的最新提交,请先发布一次` })
|
|
3640
|
+
const existing = await repoFile(gh, args.owner, args.repo, cfg.marketIndexPath, branch)
|
|
3533
3641
|
const doc = marketIndexDocument({
|
|
3534
3642
|
pkg,
|
|
3535
3643
|
owner: args.owner,
|
|
@@ -3537,8 +3645,10 @@ export function apply(ctx, rawConfig) {
|
|
|
3537
3645
|
commit,
|
|
3538
3646
|
entryTitle: args.title,
|
|
3539
3647
|
entryDescription: args.description,
|
|
3648
|
+
iconPath: await detectLocalIcon(dir),
|
|
3649
|
+
previous: parseIndexFile(existing),
|
|
3650
|
+
entries: args.entries,
|
|
3540
3651
|
})
|
|
3541
|
-
const existing = await repoFile(gh, args.owner, args.repo, cfg.marketIndexPath, branch)
|
|
3542
3652
|
await gh.writeFile(
|
|
3543
3653
|
args.owner,
|
|
3544
3654
|
args.repo,
|
|
@@ -3549,7 +3659,9 @@ export function apply(ctx, rawConfig) {
|
|
|
3549
3659
|
branch,
|
|
3550
3660
|
)
|
|
3551
3661
|
// Keep a copy locally so this machine can serve the index even when its
|
|
3552
|
-
// network cannot reach raw.githubusercontent.com
|
|
3662
|
+
// network cannot reach raw.githubusercontent.com, and so the next publish
|
|
3663
|
+
// does not push the previous version back over it.
|
|
3664
|
+
await persistLocalIndex(dir, doc).catch(() => {})
|
|
3553
3665
|
await gh
|
|
3554
3666
|
.writeRecord(INDEX_CRED, { owner: args.owner, repo: args.repo, path: cfg.marketIndexPath, body: JSON.stringify(doc, null, 2) })
|
|
3555
3667
|
.catch(() => {})
|
|
@@ -3791,7 +3903,7 @@ export function apply(ctx, rawConfig) {
|
|
|
3791
3903
|
register({
|
|
3792
3904
|
name: 'gh_auth',
|
|
3793
3905
|
description:
|
|
3794
|
-
'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 (
|
|
3906
|
+
'GitHub connection management. action=start registers a GitHub App; installations/select manage App installations; use switches the active connection (app | oauth | pat | env); pat-set stores a user access token in the credential service and makes it active; pat-clear removes it; device-start/device-poll run the GitHub App device flow (no callback URL, works with any local port) and oauth-start/oauth-clear manage the callback-based user authorization; capabilities reports what the active connection may do (code search needs a user token; notifications need a PAT or environment token, GitHub does not expose them to App tokens).',
|
|
3795
3907
|
parameters: {
|
|
3796
3908
|
type: 'object',
|
|
3797
3909
|
properties: {
|
|
@@ -4292,6 +4404,7 @@ export function apply(ctx, rawConfig) {
|
|
|
4292
4404
|
const ref = await gh.call(`${repoPath}/git/ref/heads/${encodeURIComponent(branch)}`)
|
|
4293
4405
|
const commit = ref.object ? ref.object.sha : ''
|
|
4294
4406
|
if (!commit) throw new Error(`读不到 ${branch} 的最新提交:请先发布一次`)
|
|
4407
|
+
const existing = await repoFile(gh, args.owner, args.repo, cfg.marketIndexPath, branch)
|
|
4295
4408
|
const doc = marketIndexDocument({
|
|
4296
4409
|
pkg,
|
|
4297
4410
|
owner: args.owner,
|
|
@@ -4299,8 +4412,10 @@ export function apply(ctx, rawConfig) {
|
|
|
4299
4412
|
commit,
|
|
4300
4413
|
entryTitle: args.title,
|
|
4301
4414
|
entryDescription: args.description,
|
|
4415
|
+
iconPath: await detectLocalIcon(dir),
|
|
4416
|
+
previous: parseIndexFile(existing),
|
|
4417
|
+
entries: args.entries,
|
|
4302
4418
|
})
|
|
4303
|
-
const existing = await repoFile(gh, args.owner, args.repo, cfg.marketIndexPath, branch)
|
|
4304
4419
|
await gh.writeFile(
|
|
4305
4420
|
args.owner,
|
|
4306
4421
|
args.repo,
|
|
@@ -4310,6 +4425,7 @@ export function apply(ctx, rawConfig) {
|
|
|
4310
4425
|
existing ? existing.sha : undefined,
|
|
4311
4426
|
branch,
|
|
4312
4427
|
)
|
|
4428
|
+
await persistLocalIndex(dir, doc).catch(() => {})
|
|
4313
4429
|
await gh
|
|
4314
4430
|
.writeRecord(INDEX_CRED, { owner: args.owner, repo: args.repo, path: cfg.marketIndexPath, body: JSON.stringify(doc, null, 2) })
|
|
4315
4431
|
.catch(() => {})
|
|
@@ -4563,7 +4679,7 @@ export function apply(ctx, rawConfig) {
|
|
|
4563
4679
|
register({
|
|
4564
4680
|
name: 'gh_actions_log',
|
|
4565
4681
|
description:
|
|
4566
|
-
'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.',
|
|
4682
|
+
'Read the end of a workflow run log (the archive is unzipped and the step log tail is returned). Works with every connection kind, not only an App installation token. Useful to explain why a run failed.',
|
|
4567
4683
|
parameters: {
|
|
4568
4684
|
type: 'object',
|
|
4569
4685
|
properties: {
|