dsh-github-console 0.4.1 → 0.6.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/index.js CHANGED
@@ -23,7 +23,7 @@ import zlib from 'node:zlib'
23
23
  import { fileURLToPath } from 'node:url'
24
24
  import { promises as dnsPromises, Resolver } from 'node:dns'
25
25
 
26
- const PLUGIN_VERSION = '0.4.1'
26
+ const PLUGIN_VERSION = '0.6.1'
27
27
  const APP_CRED = 'github-console/app'
28
28
  const INSTALL_CRED = 'github-console/install'
29
29
  const BRIDGE_CRED = 'github-console/bridge'
@@ -52,6 +52,33 @@ for (const key of [APP_CRED, INSTALL_CRED, BRIDGE_CRED, INDEX_CRED, PAT_CRED, AU
52
52
  // Only machine-local or VCS internals are skipped: a bundle's runtime entry can
53
53
  // legitimately live in lib/ or dist/, so those must be published.
54
54
  const SKIP_DIRS = new Set(['node_modules', '.git', '.pnpm-store', '.cache', '.turbo'])
55
+ // Files that must never be published by default, matched by name so the check
56
+ // does not depend on the file's content format.
57
+ const DENY_FILE_PATTERNS = [
58
+ /^\.env(\..+)?$/i,
59
+ /^\.npmrc$/i,
60
+ /^\.netrc$/i,
61
+ /^\.aws$/i,
62
+ /\.(pem|key|p12|pfx|jks|keystore|ppk)$/i,
63
+ /^id_(rsa|dsa|ecdsa|ed25519)(\.pub)?$/i,
64
+ /^credentials(\.json)?$/i,
65
+ /^\.?secrets?(\..+)?$/i,
66
+ ]
67
+
68
+ function isDeniedFile(filePath) {
69
+ const name = String(filePath).split('/').pop()
70
+ return DENY_FILE_PATTERNS.some((pattern) => pattern.test(name) || pattern.test(filePath))
71
+ }
72
+
73
+ /**
74
+ * Files this plugin writes straight to the repository (the npm workflow, the
75
+ * market index) are never in the local directory, so a delete-sync pass must
76
+ * leave them alone — and a user's own workflows are not ours to remove either.
77
+ */
78
+ function isProtectedRemotePath(filePath) {
79
+ const text = String(filePath)
80
+ return text.startsWith('.github/workflows/') || text === '.github/dependabot.yml'
81
+ }
55
82
  const SECRET_PATTERNS = [
56
83
  ['GitHub token', /\b(gh[pousr]_[A-Za-z0-9]{16,}|github_pat_[A-Za-z0-9_]{20,})\b/],
57
84
  ['private key', /-----BEGIN [A-Z ]*PRIVATE KEY-----/],
@@ -279,37 +306,51 @@ function readUntil(socket, separator, timeoutMs) {
279
306
  * system hosts file. GitHub accelerators rewrite hosts to 127.0.0.1 and answer
280
307
  * with their own CA, which Node does not trust; skipping hosts sidesteps both.
281
308
  */
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.
309
+ function makeBypassLookup(servers, goodIps) {
310
+ // Answers differ per public resolver (one may hand back an unroutable IP), so
311
+ // merge them all and prefer whatever address actually worked last.
291
312
  const cache = new Map()
292
313
  const ttlMs = 5 * 60 * 1000
314
+
315
+ const resolveAll = (hostname) =>
316
+ Promise.all(
317
+ servers.map(
318
+ (server) =>
319
+ new Promise((resolve) => {
320
+ const resolver = new Resolver({ timeout: 2500, tries: 1 })
321
+ try {
322
+ resolver.setServers([server])
323
+ } catch {
324
+ resolve([])
325
+ return
326
+ }
327
+ resolver.resolve4(hostname, (error, list) => resolve(error || !list ? [] : list))
328
+ }),
329
+ ),
330
+ ).then((lists) => {
331
+ const preferred = goodIps ? goodIps.get(hostname) : ''
332
+ const merged = [...new Set(lists.flat())]
333
+ if (preferred && merged.includes(preferred)) {
334
+ return [preferred, ...merged.filter((ip) => ip !== preferred)]
335
+ }
336
+ return merged
337
+ })
338
+
293
339
  return (hostname, options, callback) => {
294
340
  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]))
341
+ const settle = (ips) => {
342
+ cache.set(hostname, { ips, at: Date.now() })
343
+ if (wantAll) callback(null, ips.map((address) => ({ address, family: net.isIP(address) })))
344
+ else callback(null, ips[0], net.isIP(ips[0]))
299
345
  }
300
346
  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]))
347
+ if (cached && cached.ips.length && Date.now() - cached.at < ttlMs) {
348
+ settle(cached.ips)
304
349
  return
305
350
  }
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
- })
351
+ resolveAll(hostname)
352
+ .then((ips) => (ips.length ? settle(ips) : callback(new Error('DNS_LOOKUP_FAILED'))))
353
+ .catch((error) => callback(error))
313
354
  }
314
355
  }
315
356
 
@@ -324,7 +365,10 @@ function createTransport(cfg) {
324
365
  }
325
366
  let caPem
326
367
  let caLoaded = false
327
- const bypassLookup = makeBypassLookup(cfg.dnsServers)
368
+ // Remember which resolved address actually answered, so later requests to that
369
+ // host go straight to a working IP even when one resolver answers badly.
370
+ const goodIps = new Map()
371
+ const bypassLookup = makeBypassLookup(cfg.dnsServers, goodIps)
328
372
 
329
373
  async function loadCa() {
330
374
  if (caLoaded) return caPem
@@ -383,13 +427,21 @@ function createTransport(cfg) {
383
427
  return routes
384
428
  }
385
429
 
386
- function rawRequest(options, body, timeoutMs, binary = false) {
430
+ function rawRequest(options, body, timeoutMs, binary = false, onAddress) {
387
431
  return new Promise((resolve, reject) => {
388
432
  const request = https.request(options, (response) => {
389
433
  const chunks = []
390
434
  response.on('data', (chunk) => chunks.push(chunk))
391
435
  response.on('end', () => {
392
436
  const joined = Buffer.concat(chunks)
437
+ if (onAddress) {
438
+ try {
439
+ const address = response.socket ? response.socket.remoteAddress : ''
440
+ if (address) onAddress(String(address).replace(/^::ffff:/, ''))
441
+ } catch {
442
+ /* best effort */
443
+ }
444
+ }
393
445
  resolve({
394
446
  status: response.statusCode || 0,
395
447
  headers: response.headers,
@@ -485,6 +537,7 @@ function createTransport(cfg) {
485
537
  options.body,
486
538
  cfg.requestTimeoutMs,
487
539
  options.binary === true,
540
+ (address) => goodIps.set(host, address),
488
541
  )
489
542
  }
490
543
 
@@ -492,7 +545,11 @@ function createTransport(cfg) {
492
545
  const failures = []
493
546
  // One transient timeout must not fail a publish: retry the whole route set
494
547
  // a couple of times, re-probing the proxy so one that just came up is seen.
495
- const backoff = [0, 800, 2500]
548
+ // Only idempotent requests are retried: a POST that timed out may already
549
+ // have created the issue/comment, and a blind retry duplicates it.
550
+ const methodText = String(options.method || 'GET').toUpperCase()
551
+ const idempotent = methodText === 'GET' || methodText === 'HEAD' || methodText === 'PUT' || methodText === 'OPTIONS'
552
+ const backoff = idempotent ? [0, 800, 2500] : [0]
496
553
  for (let round = 0; round < backoff.length; round++) {
497
554
  if (backoff[round]) await new Promise((resolve) => setTimeout(resolve, backoff[round]))
498
555
  const proxy = await detectProxy(round > 0)
@@ -771,8 +828,46 @@ function createGithub(ctx, cfg, transport) {
771
828
  return `${signingInput}.${signature}`
772
829
  }
773
830
 
831
+ /** Which capability a write to this path needs; coarse but conservative. */
832
+ function capabilityFor(pathname, method) {
833
+ if (method === 'GET' || method === 'HEAD') return ''
834
+ if (/\/actions\/workflows\/[^/]+\/dispatches|\/actions\/runs\/[^/]+\/rerun/.test(pathname)) return 'workflowsWrite'
835
+ if (/\/actions\//.test(pathname)) return 'actionsWrite'
836
+ if (/\/issues(\/|$)/.test(pathname)) return 'issueWrite'
837
+ if (/\/pulls(\/|$)/.test(pathname)) return 'pullWrite'
838
+ if (/\/topics/.test(pathname)) return 'adminWrite'
839
+ return 'repoWrite'
840
+ }
841
+
774
842
  async function call(pathname, options = {}) {
775
843
  const { method = 'GET', body, auth = 'auto', headers = {}, rawBody = false } = options
844
+ // The single exit for every GitHub request: readOnly and capability checks
845
+ // live here so no caller (tool or route) can bypass them, and every write
846
+ // leaves one audit record.
847
+ const isWrite = method !== 'GET' && method !== 'HEAD'
848
+ let writeAuth = null
849
+ if (isWrite) {
850
+ if (cfg.readOnly) {
851
+ await appendAudit({ action: `${method} ${pathname}`, ok: false, detail: 'readOnly' })
852
+ throw new GhError(403, 'READ_ONLY', '只读模式已开启(readOnly: true),写操作已拒绝')
853
+ }
854
+ const needed = capabilityFor(pathname, method)
855
+ if (needed && auth === 'auto') {
856
+ const current = await resolveAuth()
857
+ if (current.kind !== 'none') {
858
+ writeAuth = current
859
+ const capabilities = capabilitiesOf(current)
860
+ if (!capabilities[needed]) {
861
+ await appendAudit({ action: `${method} ${pathname}`, ok: false, detail: `missing ${needed}` })
862
+ throw new GhError(
863
+ 403,
864
+ 'NO_CAPABILITY',
865
+ `当前连接(${current.kind})没有 ${needed} 权限:到「状态 → 连接方式」换一个带写权限的连接`,
866
+ )
867
+ }
868
+ }
869
+ }
870
+ }
776
871
  const init = { method, headers: { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28', ...headers } }
777
872
  if (auth === 'app') {
778
873
  const app = await readApp()
@@ -854,8 +949,23 @@ function createGithub(ctx, cfg, transport) {
854
949
  code === 'RATE_LIMITED' && reset
855
950
  ? `(限流重置于 ${new Date(Number(reset) * 1000).toLocaleString()})`
856
951
  : ''
952
+ if (isWrite) {
953
+ await appendAudit({
954
+ action: `${method} ${pathname}`,
955
+ ok: false,
956
+ detail: `${response.status} ${code}`,
957
+ account: writeAuth ? writeAuth.kind : '',
958
+ })
959
+ }
857
960
  throw new GhError(response.status, code, `${message}${suffix}`, data)
858
961
  }
962
+ if (isWrite) {
963
+ await appendAudit({
964
+ action: `${method} ${pathname}`,
965
+ ok: true,
966
+ account: writeAuth ? writeAuth.kind : '',
967
+ })
968
+ }
859
969
  return data
860
970
  }
861
971
 
@@ -1323,7 +1433,23 @@ function createGithub(ctx, cfg, transport) {
1323
1433
  adminWrite: p.administration === 'write',
1324
1434
  }
1325
1435
  }
1326
- if (auth.kind === 'pat' || auth.kind === 'env' || auth.kind === 'oauth') {
1436
+ if (auth.kind === 'oauth') {
1437
+ // A GitHub App user token is still an App token: it can search code, but
1438
+ // GitHub exposes notifications only to OAuth-app/PAT tokens.
1439
+ return {
1440
+ repoRead: true,
1441
+ repoWrite: true,
1442
+ pullWrite: true,
1443
+ issueWrite: true,
1444
+ actionsWrite: true,
1445
+ workflowsWrite: true,
1446
+ adminWrite: true,
1447
+ notifications: false,
1448
+ codeSearch: true,
1449
+ userLevel: true,
1450
+ }
1451
+ }
1452
+ if (auth.kind === 'pat' || auth.kind === 'env') {
1327
1453
  return {
1328
1454
  repoRead: true,
1329
1455
  repoWrite: true,
@@ -1622,6 +1748,103 @@ function createGithub(ctx, cfg, transport) {
1622
1748
  return { ok: true, runId }
1623
1749
  }
1624
1750
 
1751
+ async function listNotifications(options = {}) {
1752
+ const query = new URLSearchParams({ per_page: String(Math.min(100, options.limit || 30)) })
1753
+ if (options.all) query.set('all', 'true')
1754
+ if (options.participating) query.set('participating', 'true')
1755
+ const json = await call(`/notifications?${query.toString()}`)
1756
+ const items = (Array.isArray(json) ? json : []).map((item) => ({
1757
+ id: item.id,
1758
+ reason: item.reason,
1759
+ unread: item.unread,
1760
+ title: item.subject ? item.subject.title : '',
1761
+ type: item.subject ? item.subject.type : '',
1762
+ apiUrl: item.subject ? item.subject.url : '',
1763
+ htmlUrl: item.subject && item.subject.latest_comment_url ? item.subject.latest_comment_url.replace('/pulls/', '/pull/').replace(/\/comments\/.*$/, '') : '',
1764
+ repo: item.repository ? item.repository.full_name : '',
1765
+ updatedAt: item.updated_at,
1766
+ }))
1767
+ return { count: items.length, unread: items.filter((item) => item.unread).length, items }
1768
+ }
1769
+
1770
+ async function markNotificationsRead(options = {}) {
1771
+ if (options.all) {
1772
+ await call('/notifications', { method: 'PUT', body: { last_read_at: new Date().toISOString(), read: true } })
1773
+ return { ok: true, scope: 'all' }
1774
+ }
1775
+ const ids = Array.isArray(options.ids) ? options.ids : []
1776
+ if (!ids.length) throw new Error('需要 ids 或 all: true')
1777
+ for (const id of ids) {
1778
+ await call(`/notifications/threads/${encodeURIComponent(id)}`, { method: 'PATCH' })
1779
+ }
1780
+ return { ok: true, scope: 'ids', count: ids.length }
1781
+ }
1782
+
1783
+ async function searchCode(query, options = {}) {
1784
+ const text = String(query || '').trim()
1785
+ if (!text) throw new Error('搜索词不能为空')
1786
+ const scope = options.owner && options.name ? ` repo:${options.owner}/${options.name}` : ''
1787
+ const response = await call(`/search/code?q=${encodeURIComponent(text + scope)}&per_page=${Math.min(50, options.limit || 20)}`)
1788
+ const items = (response.items || []).map((item) => ({
1789
+ path: item.path,
1790
+ repo: item.repository ? item.repository.full_name : '',
1791
+ htmlUrl: item.html_url,
1792
+ sha: item.sha,
1793
+ }))
1794
+ return { total: response.total_count || items.length, returned: items.length, items }
1795
+ }
1796
+
1797
+ async function listReleases(owner, name) {
1798
+ const repo = repoPath(owner, name)
1799
+ const json = await call(`${repo}/releases?per_page=30`)
1800
+ return {
1801
+ items: (Array.isArray(json) ? json : []).map((item) => ({
1802
+ id: item.id,
1803
+ tag: item.tag_name,
1804
+ name: item.name || item.tag_name,
1805
+ draft: Boolean(item.draft),
1806
+ prerelease: Boolean(item.prerelease),
1807
+ publishedAt: item.published_at,
1808
+ htmlUrl: item.html_url,
1809
+ assets: (item.assets || []).map((asset) => ({ name: asset.name, size: asset.size, url: asset.browser_download_url })),
1810
+ })),
1811
+ }
1812
+ }
1813
+
1814
+ async function listCommits(owner, name, options = {}) {
1815
+ const repo = repoPath(owner, name)
1816
+ const query = new URLSearchParams({ per_page: String(Math.min(100, options.limit || 20)) })
1817
+ if (options.ref) query.set('sha', options.ref)
1818
+ const json = await call(`${repo}/commits?${query.toString()}`)
1819
+ return {
1820
+ items: (Array.isArray(json) ? json : []).map((item) => ({
1821
+ sha: item.sha,
1822
+ short: String(item.sha || '').slice(0, 7),
1823
+ message: item.commit ? String(item.commit.message || '').split('\n')[0] : '',
1824
+ author: item.commit && item.commit.author ? item.commit.author.name : '',
1825
+ date: item.commit && item.commit.author ? item.commit.author.date : '',
1826
+ htmlUrl: item.html_url,
1827
+ })),
1828
+ }
1829
+ }
1830
+
1831
+ async function compareRefs(owner, name, base, head) {
1832
+ const repo = repoPath(owner, name)
1833
+ if (!base || !head) throw new Error('需要 base 与 head')
1834
+ const json = await call(`${repo}/compare/${encodeURIComponent(base)}...${encodeURIComponent(head)}`)
1835
+ return {
1836
+ status: json.status,
1837
+ aheadBy: json.ahead_by,
1838
+ behindBy: json.behind_by,
1839
+ totalCommits: json.total_commits,
1840
+ commits: (json.commits || []).map((item) => ({
1841
+ short: String(item.sha || '').slice(0, 7),
1842
+ message: item.commit ? String(item.commit.message || '').split('\n')[0] : '',
1843
+ })),
1844
+ files: (json.files || []).map((file) => ({ path: file.filename, additions: file.additions, deletions: file.deletions })),
1845
+ }
1846
+ }
1847
+
1625
1848
  async function pullDetail(owner, name, number) {
1626
1849
  const repo = repoPath(owner, name)
1627
1850
  const [pull, files] = await Promise.all([
@@ -1725,7 +1948,11 @@ function createGithub(ctx, cfg, transport) {
1725
1948
 
1726
1949
  async function runLog(owner, name, runId, tailLines = 120) {
1727
1950
  const repo = repoPath(owner, name)
1728
- const token = await installationToken()
1951
+ // A log download is a read of the run, so it must work with any connection,
1952
+ // not only an App installation token.
1953
+ const current = await resolveAuth()
1954
+ const token = current.kind === 'app' ? await installationToken() : current.token
1955
+ if (!token) throw new GhError(401, 'AUTH_MISSING', '还没有可用的 GitHub 连接')
1729
1956
  // The archive answers 302 to a signed objects.githubusercontent.com URL, and
1730
1957
  // both hosts are hijacked on some machines, so follow the redirect through
1731
1958
  // the same resilient transport instead of global fetch.
@@ -1848,6 +2075,12 @@ function createGithub(ctx, cfg, transport) {
1848
2075
  listWorkflows,
1849
2076
  dispatchNamedWorkflow,
1850
2077
  runLog,
2078
+ listNotifications,
2079
+ markNotificationsRead,
2080
+ searchCode,
2081
+ listReleases,
2082
+ listCommits,
2083
+ compareRefs,
1851
2084
  }
1852
2085
  }
1853
2086
 
@@ -1866,8 +2099,10 @@ async function exists(target) {
1866
2099
 
1867
2100
  async function collectFiles(root, budget) {
1868
2101
  const files = []
2102
+ const denied = []
1869
2103
  let total = 0
1870
2104
  let skipped = 0
2105
+ let truncated = false
1871
2106
  async function walk(dir) {
1872
2107
  let entries = []
1873
2108
  try {
@@ -1875,8 +2110,13 @@ async function collectFiles(root, budget) {
1875
2110
  } catch {
1876
2111
  return
1877
2112
  }
2113
+ entries.sort((a, b) => a.name.localeCompare(b.name))
1878
2114
  for (const entry of entries) {
1879
- if (files.length >= 300) return
2115
+ if (files.length >= 300) {
2116
+ // Stop scanning and say so, instead of silently dropping the rest.
2117
+ truncated = true
2118
+ return
2119
+ }
1880
2120
  const full = path.join(dir, entry.name)
1881
2121
  if (entry.isDirectory()) {
1882
2122
  if (SKIP_DIRS.has(entry.name)) continue
@@ -1884,6 +2124,12 @@ async function collectFiles(root, budget) {
1884
2124
  continue
1885
2125
  }
1886
2126
  if (!entry.isFile()) continue
2127
+ const relative = path.relative(root, full).split(path.sep).join('/')
2128
+ // Credential-bearing files are refused by name before any content scan.
2129
+ if (isDeniedFile(relative)) {
2130
+ denied.push(relative)
2131
+ continue
2132
+ }
1887
2133
  const stat = await fs.stat(full).catch(() => null)
1888
2134
  if (!stat) continue
1889
2135
  if (stat.size > 1024 * 1024) {
@@ -1896,11 +2142,16 @@ async function collectFiles(root, budget) {
1896
2142
  }
1897
2143
  const content = await fs.readFile(full)
1898
2144
  total += content.length
1899
- files.push({ path: path.relative(root, full).split(path.sep).join('/'), content })
2145
+ files.push({
2146
+ path: relative,
2147
+ content,
2148
+ // Preserve the executable bit so bin/*.sh survive the round trip.
2149
+ mode: stat.mode & 0o111 ? '100755' : '100644',
2150
+ })
1900
2151
  }
1901
2152
  }
1902
2153
  await walk(root)
1903
- return { files, total, skipped }
2154
+ return { files, total, skipped, denied, truncated }
1904
2155
  }
1905
2156
 
1906
2157
  function findSecrets(files) {
@@ -1937,7 +2188,8 @@ async function preflight(dir, gh, cfg) {
1937
2188
 
1938
2189
  let pkg = null
1939
2190
  try {
1940
- pkg = JSON.parse(await fs.readFile(packagePath, 'utf8'))
2191
+ // Strip a UTF-8 BOM: several Windows editors write one and JSON.parse rejects it.
2192
+ pkg = JSON.parse((await fs.readFile(packagePath, 'utf8')).replace(/^\uFEFF/, ''))
1941
2193
  add('package.json', 'pass', 'package.json 可解析', `${pkg.name || '未命名'}@${pkg.version || '?'}`)
1942
2194
  } catch (error) {
1943
2195
  add('package.json', 'block', 'package.json 不是合法 JSON', errorMessage(error))
@@ -1987,6 +2239,19 @@ async function preflight(dir, gh, cfg) {
1987
2239
  }
1988
2240
 
1989
2241
  const collected = await collectFiles(root, cfg.maxPushBytes)
2242
+ if (collected.denied.length) {
2243
+ add(
2244
+ 'denied-files',
2245
+ 'block',
2246
+ `发现 ${collected.denied.length} 个不应发布的敏感文件`,
2247
+ `${collected.denied.slice(0, 6).join(', ')}(按文件名拦截,不依赖内容格式)`,
2248
+ )
2249
+ } else {
2250
+ add('denied-files', 'pass', '没有 .env / .npmrc / 私钥类文件', '')
2251
+ }
2252
+ if (collected.truncated) {
2253
+ add('files', 'block', '文件数超过 300,已中止', '请先排除 dist/ 等生成物,或分批发布')
2254
+ }
1990
2255
  const secrets = findSecrets(collected.files)
1991
2256
  if (secrets.length) {
1992
2257
  add(
@@ -2008,23 +2273,30 @@ async function preflight(dir, gh, cfg) {
2008
2273
  }
2009
2274
  if (hardPaths.length) add('local-paths', 'warn', '代码里出现本机绝对路径', hardPaths.slice(0, 5).join(', '))
2010
2275
 
2011
- add('files', 'info', `待推送 ${collected.files.length} 个文件`, fmtBytes(collected.total) + (collected.skipped ? `(跳过 ${collected.skipped} 个大文件)` : ''))
2276
+ add(
2277
+ 'files',
2278
+ collected.truncated ? 'block' : 'info',
2279
+ `待推送 ${collected.files.length} 个文件`,
2280
+ fmtBytes(collected.total) +
2281
+ (collected.skipped ? `(跳过 ${collected.skipped} 个大文件)` : '') +
2282
+ (collected.truncated ? '(已达到 300 个上限)' : ''),
2283
+ )
2012
2284
 
2013
2285
  if (gh) {
2014
2286
  try {
2015
- const response = await fetch(`https://registry.npmjs.org/${encodeURIComponent(pkg.name)}`)
2016
- if (response.status === 200) {
2017
- const data = await response.json()
2287
+ const probe = await httpGetJson(`https://registry.npmjs.org/${encodeURIComponent(pkg.name)}`)
2288
+ if (probe.status === 200) {
2289
+ const data = JSON.parse(probe.text || '{}')
2018
2290
  const latest = data['dist-tags'] ? data['dist-tags'].latest : ''
2019
2291
  if (latest === pkg.version) {
2020
2292
  add('npm', 'block', 'npm 上已存在同名同版本', `${pkg.name}@${latest}`)
2021
2293
  } else {
2022
2294
  add('npm', 'info', 'npm 上已存在该包', `latest ${latest}`)
2023
2295
  }
2024
- } else if (response.status === 404) {
2296
+ } else if (probe.status === 404) {
2025
2297
  add('npm', 'pass', 'npm 上没有同名包', pkg.name)
2026
2298
  } else {
2027
- add('npm', 'info', 'npm 查询未确认', `HTTP ${response.status}`)
2299
+ add('npm', 'info', 'npm 查询未确认', `HTTP ${probe.status}`)
2028
2300
  }
2029
2301
  } catch (error) {
2030
2302
  add('npm', 'info', 'npm 查询失败', errorMessage(error))
@@ -2117,9 +2389,31 @@ async function pushFiles(gh, owner, name, branch, files, message) {
2117
2389
  }
2118
2390
 
2119
2391
  stage = 'create-tree'
2120
- const treeBody = {
2121
- tree: files.map((file, index) => ({ path: file.path, mode: '100644', type: 'blob', sha: blobs[index] })),
2392
+ const entries = files.map((file, index) => ({
2393
+ path: file.path,
2394
+ // Keep executable files executable; everything else stays 100644.
2395
+ mode: file.mode || '100644',
2396
+ type: 'blob',
2397
+ sha: blobs[index],
2398
+ }))
2399
+ let deleted = 0
2400
+ if (baseTreeSha) {
2401
+ // A tree with base_tree is a patch: without explicit `sha: null` entries,
2402
+ // files deleted locally stay in the repository forever.
2403
+ stage = 'diff-remote-tree'
2404
+ const remote = await gh.call(`${repo}/git/trees/${baseTreeSha}?recursive=1`).catch(() => null)
2405
+ const remotePaths =
2406
+ remote && Array.isArray(remote.tree) ? remote.tree.filter((item) => item.type === 'blob').map((item) => item.path) : []
2407
+ const local = new Set(files.map((file) => file.path))
2408
+ const stale = remotePaths.filter(
2409
+ (filePath) => !local.has(filePath) && !isDeniedFile(filePath) && !isProtectedRemotePath(filePath),
2410
+ )
2411
+ deleted = stale.length
2412
+ for (const filePath of stale) {
2413
+ entries.push({ path: filePath, mode: '100644', type: 'blob', sha: null })
2414
+ }
2122
2415
  }
2416
+ const treeBody = { tree: entries }
2123
2417
  if (baseTreeSha) treeBody.base_tree = baseTreeSha
2124
2418
  const tree = await gh.call(`${repo}/git/trees`, { method: 'POST', body: treeBody })
2125
2419
 
@@ -2140,7 +2434,7 @@ async function pushFiles(gh, owner, name, branch, files, message) {
2140
2434
  body: { ref: `refs/heads/${branch}`, sha: commit.sha },
2141
2435
  })
2142
2436
  }
2143
- return { commit: commit.sha, files: files.length, branch, firstCommit: bootstrapped }
2437
+ return { commit: commit.sha, files: files.length, branch, firstCommit: bootstrapped, deleted }
2144
2438
  } catch (error) {
2145
2439
  // Naming the failed stage turns "Git Repository is empty." into something
2146
2440
  // actionable instead of a single opaque message.
@@ -2441,9 +2735,25 @@ async function ensurePublishWorkflow(gh, owner, repo, branch, workflowFile) {
2441
2735
 
2442
2736
  async function dispatchWorkflow(gh, owner, repo, workflowFile, ref, inputs) {
2443
2737
  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 },
2738
+ const url = `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/actions/workflows/${encodeURIComponent(workflowFile)}/dispatches`
2739
+ // GitHub indexes a new or changed workflow file within seconds; until then the
2740
+ // dispatch answers 404 "No workflow found". Retry only that case.
2741
+ let lastError = null
2742
+ for (const wait of [0, 1000, 2000, 4000, 8000]) {
2743
+ if (wait) await new Promise((resolve) => setTimeout(resolve, wait))
2744
+ try {
2745
+ await gh.call(url, { method: 'POST', body })
2746
+ return { dispatched: true, attempts: wait ? wait : 1 }
2747
+ } catch (error) {
2748
+ if (error.status !== 404) throw error
2749
+ lastError = error
2750
+ }
2751
+ }
2752
+ throw new GhError(
2753
+ 404,
2754
+ 'WORKFLOW_NOT_FOUND',
2755
+ `${workflowFile} 已提交但 GitHub 尚未索引它;稍等几秒再点一次即可`,
2756
+ { cause: lastError ? lastError.message : '' },
2447
2757
  )
2448
2758
  }
2449
2759
 
@@ -2471,18 +2781,28 @@ async function waitForWorkflowRun(gh, owner, repo, workflowFile, sinceMs, timeou
2471
2781
  return last ? { ...last, status: 'timeout' } : { status: 'unknown', url: null }
2472
2782
  }
2473
2783
 
2474
- function marketIndexDocument({ pkg, owner, repo, commit, entryTitle, entryDescription }) {
2784
+ function marketIndexDocument({ pkg, owner, repo, commit, entryTitle, entryDescription, iconPath, previous, entries }) {
2475
2785
  const repositoryUrl = `https://github.com/${owner}/${repo}`
2786
+ const relativeIcon = iconPath ? `../${String(iconPath).replace(/^\.\//, '')}` : '../icon.svg'
2476
2787
  const engines =
2477
2788
  pkg.engines && typeof pkg.engines.dsh === 'string' && pkg.engines.dsh.trim() && !pkg.engines.dsh.startsWith('workspace:')
2478
2789
  ? { dsh: pkg.engines.dsh.trim() }
2479
2790
  : {}
2791
+ // Keep the timestamp stable for a version that is already indexed, so a
2792
+ // re-generated index does not look like a new release.
2793
+ const previousVersion =
2794
+ previous && Array.isArray(previous.plugins)
2795
+ ? previous.plugins.find((item) => item && item.name === pkg.name)
2796
+ : undefined
2797
+ const previousTimestamp =
2798
+ previousVersion && Array.isArray(previousVersion.versions)
2799
+ ? (previousVersion.versions.find((item) => item && item.version === pkg.version) || {}).publishTimestamp
2800
+ : undefined
2480
2801
  const plugin = {
2481
2802
  name: pkg.name,
2482
2803
  title: entryTitle || pkg.name,
2483
2804
  description: entryDescription || pkg.description || pkg.name,
2484
- // Resolved against the index URL, so the icon ships with the repository.
2485
- icon: '../icon.svg',
2805
+ icon: relativeIcon,
2486
2806
  author: owner,
2487
2807
  repository: { url: repositoryUrl },
2488
2808
  metadata: {
@@ -2491,24 +2811,54 @@ function marketIndexDocument({ pkg, owner, repo, commit, entryTitle, entryDescri
2491
2811
  versions: [
2492
2812
  {
2493
2813
  version: pkg.version,
2494
- publishTimestamp: Math.floor(Date.now() / 1000),
2814
+ publishTimestamp: Number.isInteger(previousTimestamp) ? previousTimestamp : Math.floor(Date.now() / 1000),
2495
2815
  source: { type: 'git', url: repositoryUrl, commit },
2496
2816
  engines,
2497
2817
  },
2498
2818
  ],
2499
2819
  }
2500
2820
  if (pkg.homepage && /^https?:\/\//.test(pkg.homepage)) plugin.homepage = pkg.homepage
2821
+ // Optional extra entries let one repository index several installable plugins.
2822
+ const extra = Array.isArray(entries)
2823
+ ? entries
2824
+ .filter((item) => item && typeof item.name === 'string' && item.name)
2825
+ .map((item) => ({
2826
+ name: item.name,
2827
+ title: item.title || item.name,
2828
+ description: item.description || item.name,
2829
+ icon: item.icon ? `../${String(item.icon).replace(/^\.\//, '')}` : relativeIcon,
2830
+ author: owner,
2831
+ repository: { url: repositoryUrl },
2832
+ metadata: { keywords: [] },
2833
+ versions: [
2834
+ {
2835
+ version: item.version || pkg.version,
2836
+ publishTimestamp: Number.isInteger(item.publishTimestamp)
2837
+ ? item.publishTimestamp
2838
+ : Math.floor(Date.now() / 1000),
2839
+ source: {
2840
+ type: 'git',
2841
+ url: repositoryUrl,
2842
+ commit: item.commit || commit,
2843
+ ...(item.path ? { path: item.path } : {}),
2844
+ },
2845
+ engines,
2846
+ },
2847
+ ],
2848
+ }))
2849
+ : []
2501
2850
  return {
2502
2851
  format: 1,
2503
2852
  title: `${owner} DSH plugin index`,
2504
2853
  description: 'Self-hosted DSH plugin index generated by the GitHub console.',
2505
2854
  metadata: {},
2506
- plugins: [plugin],
2855
+ plugins: [plugin, ...extra],
2507
2856
  }
2508
2857
  }
2509
2858
 
2510
2859
  async function readLocalPackage(dir) {
2511
- const raw = await fs.readFile(path.join(dir, 'package.json'), 'utf8')
2860
+ // Strip a UTF-8 BOM: several Windows editors write one and JSON.parse rejects it.
2861
+ const raw = (await fs.readFile(path.join(dir, 'package.json'), 'utf8')).replace(/^\uFEFF/, '')
2512
2862
  const pkg = JSON.parse(raw)
2513
2863
  if (!pkg.name || !pkg.version) throw new Error('package.json 缺少 name 或 version')
2514
2864
  return pkg
@@ -2527,10 +2877,8 @@ async function npmPublishState(gh, cfg, { owner, repo, dir }) {
2527
2877
  let exists = null
2528
2878
  if (name) {
2529
2879
  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
2880
+ const probe = await httpGetJson(`https://registry.npmjs.org/${encodeURIComponent(name)}`)
2881
+ exists = probe.status === 200
2534
2882
  } catch {
2535
2883
  exists = null
2536
2884
  }
@@ -2656,6 +3004,48 @@ function unzipEntries(buffer) {
2656
3004
  return entries
2657
3005
  }
2658
3006
 
3007
+ /** Set once by apply(): every outbound JSON request shares the same routing. */
3008
+ let sharedTransport = null
3009
+
3010
+ /**
3011
+ * JSON over the plugin's transport, so npm and market probes obey the same
3012
+ * proxy / DNS / CA settings as GitHub requests instead of bypassing them.
3013
+ */
3014
+ async function httpGetJson(url, options = {}) {
3015
+ const headers = {
3016
+ 'User-Agent': `dsh-github-console/${PLUGIN_VERSION}`,
3017
+ Accept: 'application/json',
3018
+ ...(options.headers || {}),
3019
+ }
3020
+ if (sharedTransport) {
3021
+ const response = await sharedTransport.request(url, {
3022
+ method: options.method || 'GET',
3023
+ headers,
3024
+ body: options.body,
3025
+ })
3026
+ return { status: response.status, text: response.text }
3027
+ }
3028
+ const response = await fetch(url, { method: options.method || 'GET', headers })
3029
+ return { status: response.status, text: await response.text() }
3030
+ }
3031
+
3032
+ /** Prefer a raster icon when the repository ships one. */
3033
+ async function detectLocalIcon(dir) {
3034
+ for (const candidate of ['assets/icon-512.png', 'assets/icon-180.png', 'icon.png', 'assets/icon.png']) {
3035
+ if (await exists(path.join(dir, candidate))) return candidate
3036
+ }
3037
+ return ''
3038
+ }
3039
+
3040
+ function parseIndexFile(file) {
3041
+ if (!file || typeof file.text !== 'string' || !file.text) return null
3042
+ try {
3043
+ return JSON.parse(file.text)
3044
+ } catch {
3045
+ return null
3046
+ }
3047
+ }
3048
+
2659
3049
  async function probeMarket(input, gh, cfg) {
2660
3050
  const checkedAt = new Date().toISOString()
2661
3051
  const results = []
@@ -2663,9 +3053,9 @@ async function probeMarket(input, gh, cfg) {
2663
3053
 
2664
3054
  // 1. npm package presence
2665
3055
  try {
2666
- const response = await fetch(`https://registry.npmjs.org/${encodeURIComponent(input.name)}/latest`)
3056
+ const response = await httpGetJson(`https://registry.npmjs.org/${encodeURIComponent(input.name)}/latest`)
2667
3057
  if (response.status === 200) {
2668
- const data = await response.json()
3058
+ const data = JSON.parse(response.text || '{}')
2669
3059
  push('npm', 'listed', `${input.name}@${data.version}`, { version: data.version })
2670
3060
  } else if (response.status === 404) {
2671
3061
  push('npm', 'absent', 'npm 上没有这个包名')
@@ -2714,12 +3104,12 @@ async function probeMarket(input, gh, cfg) {
2714
3104
  // 3. Configured market indexes (format 1 JSON with an items/plugins array)
2715
3105
  for (const url of cfg.marketIndexUrls) {
2716
3106
  try {
2717
- const response = await fetch(url)
2718
- if (!response.ok) {
3107
+ const response = await httpGetJson(url)
3108
+ if (response.status < 200 || response.status >= 300) {
2719
3109
  push(`index:${url}`, 'unknown', `HTTP ${response.status}`)
2720
3110
  continue
2721
3111
  }
2722
- const text = await response.text()
3112
+ const text = response.text
2723
3113
  const found = text.includes(`"${input.name}"`) || text.includes(`"${input.name}@`)
2724
3114
  push(`index:${url}`, found ? 'listed' : 'absent', found ? '索引里出现该包名' : '索引里没有该包名')
2725
3115
  } catch (error) {
@@ -2820,7 +3210,10 @@ async function runPublish({ job, gh, cfg, dir, owner, repo, version, notes, opts
2820
3210
  const collected = await collectFiles(path.resolve(dir), cfg.maxPushBytes)
2821
3211
  const pushed = await pushFiles(gh, owner, repo, branch, collected.files, opts.message || `chore(release): v${semver}`)
2822
3212
  step(job, 'push').state = 'done'
2823
- step(job, 'push').detail = `${pushed.files} 个文件 → ${branch} @ ${pushed.commit.slice(0, 7)}${pushed.firstCommit ? '(仓库原本为空,这是首个提交)' : ''}`
3213
+ step(job, 'push').detail =
3214
+ `${pushed.files} 个文件 → ${branch} @ ${pushed.commit.slice(0, 7)}` +
3215
+ (pushed.deleted ? `,删除远端 ${pushed.deleted} 个过期文件` : '') +
3216
+ (pushed.firstCommit ? '(仓库原本为空,这是首个提交)' : '')
2824
3217
  job.commit = pushed.commit
2825
3218
  } catch (error) {
2826
3219
  step(job, 'push').state = 'failed'
@@ -2833,8 +3226,10 @@ async function runPublish({ job, gh, cfg, dir, owner, repo, version, notes, opts
2833
3226
  step(job, 'topics').state = 'done'
2834
3227
  step(job, 'topics').detail = topics.after.join(', ')
2835
3228
  } catch (error) {
2836
- step(job, 'topics').state = 'failed'
2837
- step(job, 'topics').detail = `${errorMessage(error)}(需 Administration: write)`
3229
+ // Topics need Administration: write, which the manifest deliberately does
3230
+ // not request — the release itself is already done at this point.
3231
+ step(job, 'topics').state = 'done'
3232
+ step(job, 'topics').detail = `已跳过(可选权限 Administration: write):${errorMessage(error)}`
2838
3233
  }
2839
3234
 
2840
3235
  try {
@@ -2870,6 +3265,7 @@ export const inject = ['tools']
2870
3265
  export function apply(ctx, rawConfig) {
2871
3266
  const cfg = normalizeConfig(rawConfig)
2872
3267
  const transport = createTransport(cfg)
3268
+ sharedTransport = transport
2873
3269
  const gh = createGithub(ctx, cfg, transport)
2874
3270
  const jobs = createJobStore()
2875
3271
  let bridgeToken = ''
@@ -2943,17 +3339,23 @@ export function apply(ctx, rawConfig) {
2943
3339
 
2944
3340
  const discover = (extra) => discoverPlugins(discoveryRoots(extra))
2945
3341
 
2946
- // Every mutating path records who did what, so a console leaves a trail.
3342
+ /**
3343
+ * Keep the local copy in step with the committed one. Without this the next
3344
+ * publish collects the stale file from disk and overwrites the fresh index.
3345
+ */
3346
+ async function persistLocalIndex(dir, doc) {
3347
+ const target = path.join(dir, cfg.marketIndexPath)
3348
+ await fs.mkdir(path.dirname(target), { recursive: true })
3349
+ await fs.writeFile(target, `${JSON.stringify(doc, null, 2)}\n`, 'utf8')
3350
+ return target
3351
+ }
3352
+
3353
+ // Kept as a thin wrapper: audit records are written by gh.call(), the single
3354
+ // exit for GitHub requests, so entry points no longer decide whether to log.
2947
3355
  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
- }
3356
+ void action
3357
+ void target
3358
+ return run()
2957
3359
  }
2958
3360
 
2959
3361
  // Write actions are refused up front when the active connection cannot write.
@@ -3031,7 +3433,7 @@ export function apply(ctx, rawConfig) {
3031
3433
  default_permissions: {
3032
3434
  metadata: 'read',
3033
3435
  contents: 'write',
3034
- administration: 'write',
3436
+
3035
3437
  pull_requests: 'write',
3036
3438
  issues: 'write',
3037
3439
  actions: 'write',
@@ -3219,6 +3621,28 @@ export function apply(ctx, rawConfig) {
3219
3621
  ),
3220
3622
  )
3221
3623
  }
3624
+ if (route === 'POST /github-console/api/notifications') {
3625
+ return sendJson(response, 200, await gh.listNotifications(args))
3626
+ }
3627
+ if (route === 'POST /github-console/api/notifications/read') {
3628
+ return sendJson(
3629
+ response,
3630
+ 200,
3631
+ await audited('notifications.read', args.all ? 'all' : (args.ids || []).join(','), () => gh.markNotificationsRead(args)),
3632
+ )
3633
+ }
3634
+ if (route === 'POST /github-console/api/search/code') {
3635
+ return sendJson(response, 200, await gh.searchCode(args.q, args))
3636
+ }
3637
+ if (route === 'POST /github-console/api/releases') {
3638
+ return sendJson(response, 200, await gh.listReleases(args.owner, args.name))
3639
+ }
3640
+ if (route === 'POST /github-console/api/commits') {
3641
+ return sendJson(response, 200, await gh.listCommits(args.owner, args.name, args))
3642
+ }
3643
+ if (route === 'POST /github-console/api/compare') {
3644
+ return sendJson(response, 200, await gh.compareRefs(args.owner, args.name, args.base, args.head))
3645
+ }
3222
3646
  if (route === 'POST /github-console/api/pull/detail') {
3223
3647
  return sendJson(response, 200, await gh.pullDetail(args.owner, args.name, args.number))
3224
3648
  }
@@ -3363,6 +3787,7 @@ export function apply(ctx, rawConfig) {
3363
3787
  const ref = await gh.call(`${repoPath}/git/ref/heads/${encodeURIComponent(branch)}`)
3364
3788
  const commit = ref.object ? ref.object.sha : ''
3365
3789
  if (!commit) return sendJson(response, 400, { error: `读不到 ${branch} 的最新提交,请先发布一次` })
3790
+ const existing = await repoFile(gh, args.owner, args.repo, cfg.marketIndexPath, branch)
3366
3791
  const doc = marketIndexDocument({
3367
3792
  pkg,
3368
3793
  owner: args.owner,
@@ -3370,8 +3795,10 @@ export function apply(ctx, rawConfig) {
3370
3795
  commit,
3371
3796
  entryTitle: args.title,
3372
3797
  entryDescription: args.description,
3798
+ iconPath: await detectLocalIcon(dir),
3799
+ previous: parseIndexFile(existing),
3800
+ entries: args.entries,
3373
3801
  })
3374
- const existing = await repoFile(gh, args.owner, args.repo, cfg.marketIndexPath, branch)
3375
3802
  await gh.writeFile(
3376
3803
  args.owner,
3377
3804
  args.repo,
@@ -3382,7 +3809,9 @@ export function apply(ctx, rawConfig) {
3382
3809
  branch,
3383
3810
  )
3384
3811
  // Keep a copy locally so this machine can serve the index even when its
3385
- // network cannot reach raw.githubusercontent.com.
3812
+ // network cannot reach raw.githubusercontent.com, and so the next publish
3813
+ // does not push the previous version back over it.
3814
+ await persistLocalIndex(dir, doc).catch(() => {})
3386
3815
  await gh
3387
3816
  .writeRecord(INDEX_CRED, { owner: args.owner, repo: args.repo, path: cfg.marketIndexPath, body: JSON.stringify(doc, null, 2) })
3388
3817
  .catch(() => {})
@@ -3456,6 +3885,60 @@ export function apply(ctx, rawConfig) {
3456
3885
  }
3457
3886
  return
3458
3887
  }
3888
+ if (url.pathname === `${PREFIX}/device`) {
3889
+ // A plain HTML page: the panel may be stale or a popup blocked, but this
3890
+ // URL always shows the code and the verification link.
3891
+ try {
3892
+ const started = await gh.deviceStart()
3893
+ const checkUrl = `${PREFIX}/device/check?code=${encodeURIComponent(started.deviceCode)}`
3894
+ sendHtml(
3895
+ response,
3896
+ 200,
3897
+ 'GitHub 设备码授权',
3898
+ `在 GitHub 打开下面的页面,输入这个码并确认(${Math.round(started.expiresIn / 60)} 分钟内有效):`,
3899
+ `<p style="font:600 30px/1.3 ui-monospace,Consolas,monospace;letter-spacing:3px;margin:14px 0 6px">` +
3900
+ `${escapeHtml(started.userCode)}</p>` +
3901
+ `<p style="margin:0 0 16px"><a href="${escapeHtml(started.verificationUri)}" target="_blank" rel="noreferrer" ` +
3902
+ `style="display:inline-block;padding:9px 18px;border-radius:8px;background:#3E6FD8;color:#fff;text-decoration:none;font-size:14px">` +
3903
+ `打开 ${escapeHtml(started.verificationUri)}</a></p>` +
3904
+ `<p style="font-size:13px;color:#57606a">输入码并点 Authorize 之后,回到这里点下面的按钮确认:</p>` +
3905
+ `<p><a href="${escapeHtml(checkUrl)}" style="display:inline-block;padding:8px 16px;border:1px solid #3E6FD8;` +
3906
+ `border-radius:8px;color:#3E6FD8;text-decoration:none;font-size:13px">我已授权,检查状态</a></p>`,
3907
+ )
3908
+ } catch (failure) {
3909
+ const appRecord = await gh.readRecord(APP_CRED).catch(() => undefined)
3910
+ const appSlug = appRecord && appRecord.slug ? appRecord.slug : ''
3911
+ sendHtml(
3912
+ response,
3913
+ 200,
3914
+ '拿不到设备码',
3915
+ errorMessage(failure),
3916
+ `<p style="font-size:13px;color:#57606a;line-height:1.8">· 若是「App 没有启用 Device Flow」:到 ` +
3917
+ `<a href="${escapeHtml(appSlug ? `https://github.com/settings/apps/${appSlug}` : 'https://github.com/settings/apps')}">` +
3918
+ `GitHub App 设置页</a> 勾选 Enable Device Flow → 底部 Save changes。<br>` +
3919
+ `· 若是网络错误:这台机器连 GitHub 不稳定,请在网络正常时重试。</p>`,
3920
+ )
3921
+ }
3922
+ return
3923
+ }
3924
+ if (url.pathname === `${PREFIX}/device/check`) {
3925
+ const code = url.searchParams.get('code') || ''
3926
+ try {
3927
+ const result = await gh.devicePoll(code)
3928
+ if (result.status === 'ok') {
3929
+ sendHtml(response, 200, '授权成功', '已保存用户令牌,并切换为「App 用户授权」连接。可以关闭此页面。')
3930
+ } else if (result.status === 'pending') {
3931
+ sendHtml(response, 200, '还在等待确认', 'GitHub 那边还没点 Authorize,稍等几秒再点一次检查。')
3932
+ } else if (result.status === 'expired') {
3933
+ sendHtml(response, 200, '设备码已过期', '重新打开 /github-console/device 生成新码。')
3934
+ } else {
3935
+ sendHtml(response, 200, '授权被拒绝', '你在 GitHub 上取消了授权。')
3936
+ }
3937
+ } catch (failure) {
3938
+ sendHtml(response, 200, '检查失败', errorMessage(failure))
3939
+ }
3940
+ return
3941
+ }
3459
3942
  if (url.pathname === `${PREFIX}/icon.svg`) {
3460
3943
  // The index references ../icon.svg relative to /github-console/market/index.json.
3461
3944
  const svg = await fs.readFile(path.join(PLUGIN_DIR, 'icon.svg')).catch(() => null)
@@ -3570,7 +4053,7 @@ export function apply(ctx, rawConfig) {
3570
4053
  register({
3571
4054
  name: 'gh_auth',
3572
4055
  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).',
4056
+ '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).',
3574
4057
  parameters: {
3575
4058
  type: 'object',
3576
4059
  properties: {
@@ -4071,6 +4554,7 @@ export function apply(ctx, rawConfig) {
4071
4554
  const ref = await gh.call(`${repoPath}/git/ref/heads/${encodeURIComponent(branch)}`)
4072
4555
  const commit = ref.object ? ref.object.sha : ''
4073
4556
  if (!commit) throw new Error(`读不到 ${branch} 的最新提交:请先发布一次`)
4557
+ const existing = await repoFile(gh, args.owner, args.repo, cfg.marketIndexPath, branch)
4074
4558
  const doc = marketIndexDocument({
4075
4559
  pkg,
4076
4560
  owner: args.owner,
@@ -4078,8 +4562,10 @@ export function apply(ctx, rawConfig) {
4078
4562
  commit,
4079
4563
  entryTitle: args.title,
4080
4564
  entryDescription: args.description,
4565
+ iconPath: await detectLocalIcon(dir),
4566
+ previous: parseIndexFile(existing),
4567
+ entries: args.entries,
4081
4568
  })
4082
- const existing = await repoFile(gh, args.owner, args.repo, cfg.marketIndexPath, branch)
4083
4569
  await gh.writeFile(
4084
4570
  args.owner,
4085
4571
  args.repo,
@@ -4089,6 +4575,7 @@ export function apply(ctx, rawConfig) {
4089
4575
  existing ? existing.sha : undefined,
4090
4576
  branch,
4091
4577
  )
4578
+ await persistLocalIndex(dir, doc).catch(() => {})
4092
4579
  await gh
4093
4580
  .writeRecord(INDEX_CRED, { owner: args.owner, repo: args.repo, path: cfg.marketIndexPath, body: JSON.stringify(doc, null, 2) })
4094
4581
  .catch(() => {})
@@ -4342,7 +4829,7 @@ export function apply(ctx, rawConfig) {
4342
4829
  register({
4343
4830
  name: 'gh_actions_log',
4344
4831
  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.',
4832
+ '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.',
4346
4833
  parameters: {
4347
4834
  type: 'object',
4348
4835
  properties: {
@@ -4360,6 +4847,118 @@ export function apply(ctx, rawConfig) {
4360
4847
  },
4361
4848
  })
4362
4849
 
4850
+ register({
4851
+ name: 'gh_notifications',
4852
+ description:
4853
+ 'List GitHub notifications (mentions, review requests, CI failures, assigned issues). Requires a user connection (App user authorization, PAT or environment token): an installation token cannot read notifications. Set all=true for read threads too.',
4854
+ parameters: {
4855
+ type: 'object',
4856
+ properties: {
4857
+ all: { type: 'boolean', description: 'Include already-read threads' },
4858
+ participating: { type: 'boolean', description: 'Only threads you participate in' },
4859
+ limit: { type: 'integer', minimum: 1, maximum: 100 },
4860
+ },
4861
+ additionalProperties: false,
4862
+ },
4863
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
4864
+ async execute(args) {
4865
+ return gh.listNotifications(args)
4866
+ },
4867
+ })
4868
+
4869
+ register({
4870
+ name: 'gh_notifications_read',
4871
+ description: 'Mark notifications read: pass ids for selected threads, or all=true to mark everything read. Writes are audited.',
4872
+ parameters: {
4873
+ type: 'object',
4874
+ properties: {
4875
+ ids: { type: 'array', items: { type: 'string' }, description: 'Notification thread ids' },
4876
+ all: { type: 'boolean', description: 'Mark every thread read' },
4877
+ },
4878
+ additionalProperties: false,
4879
+ },
4880
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
4881
+ async execute(args) {
4882
+ return audited('notifications.read', args.all ? 'all' : (args.ids || []).join(','), () => gh.markNotificationsRead(args))
4883
+ },
4884
+ })
4885
+
4886
+ register({
4887
+ name: 'gh_code_search',
4888
+ description:
4889
+ 'Search code across GitHub or inside one repository. Requires a user connection (an installation token cannot use the code search API). Rate limited to about 10 requests per minute.',
4890
+ parameters: {
4891
+ type: 'object',
4892
+ properties: {
4893
+ q: { type: 'string', description: 'Search terms, GitHub code search syntax' },
4894
+ owner: { type: 'string', description: 'Restrict to this owner' },
4895
+ name: { type: 'string', description: 'Restrict to this repository' },
4896
+ limit: { type: 'integer', minimum: 1, maximum: 50 },
4897
+ },
4898
+ required: ['q'],
4899
+ additionalProperties: false,
4900
+ },
4901
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
4902
+ async execute(args) {
4903
+ return gh.searchCode(args.q, args)
4904
+ },
4905
+ })
4906
+
4907
+ register({
4908
+ name: 'gh_releases',
4909
+ description: 'List repository releases with their assets and download URLs.',
4910
+ parameters: {
4911
+ type: 'object',
4912
+ properties: { owner: { type: 'string' }, name: { type: 'string' } },
4913
+ required: ['owner', 'name'],
4914
+ additionalProperties: false,
4915
+ },
4916
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
4917
+ async execute(args) {
4918
+ return gh.listReleases(args.owner, args.name)
4919
+ },
4920
+ })
4921
+
4922
+ register({
4923
+ name: 'gh_commits',
4924
+ description: 'List recent commits of a branch or ref with author, date and message subject.',
4925
+ parameters: {
4926
+ type: 'object',
4927
+ properties: {
4928
+ owner: { type: 'string' },
4929
+ name: { type: 'string' },
4930
+ ref: { type: 'string', description: 'Branch, tag or sha; default the repository default branch' },
4931
+ limit: { type: 'integer', minimum: 1, maximum: 100 },
4932
+ },
4933
+ required: ['owner', 'name'],
4934
+ additionalProperties: false,
4935
+ },
4936
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
4937
+ async execute(args) {
4938
+ return gh.listCommits(args.owner, args.name, args)
4939
+ },
4940
+ })
4941
+
4942
+ register({
4943
+ name: 'gh_compare',
4944
+ description: 'Compare two refs: ahead/behind counts, commits and changed files. Use it to review a branch before opening a pull request.',
4945
+ parameters: {
4946
+ type: 'object',
4947
+ properties: {
4948
+ owner: { type: 'string' },
4949
+ name: { type: 'string' },
4950
+ base: { type: 'string', description: 'Base ref, for example main' },
4951
+ head: { type: 'string', description: 'Head ref, for example feature/x' },
4952
+ },
4953
+ required: ['owner', 'name', 'base', 'head'],
4954
+ additionalProperties: false,
4955
+ },
4956
+ output: { schema: { type: 'object' }, render: (args, value) => textOf(value) },
4957
+ async execute(args) {
4958
+ return gh.compareRefs(args.owner, args.name, args.base, args.head)
4959
+ },
4960
+ })
4961
+
4363
4962
  register({
4364
4963
  name: 'plugin_publish_status',
4365
4964
  description: 'Read a publish job by id, including each step state and detail.',