dsh-github-console 0.5.0 → 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.
@@ -0,0 +1,17 @@
1
+ name: check
2
+ on:
3
+ push:
4
+ pull_request:
5
+ workflow_dispatch:
6
+ permissions:
7
+ contents: read
8
+ jobs:
9
+ check:
10
+ runs-on: ubuntu-latest
11
+ steps:
12
+ - uses: actions/checkout@v4
13
+ - uses: actions/setup-node@v4
14
+ with:
15
+ node-version: '22'
16
+ - name: Bundle consistency
17
+ run: node scripts/check.mjs
@@ -0,0 +1,31 @@
1
+ name: publish
2
+ on:
3
+ workflow_dispatch:
4
+ inputs:
5
+ dry_run:
6
+ description: 'Run npm publish --dry-run'
7
+ type: boolean
8
+ default: false
9
+ permissions:
10
+ contents: read
11
+ id-token: write
12
+ concurrency:
13
+ group: npm-publish
14
+ cancel-in-progress: false
15
+ jobs:
16
+ publish:
17
+ runs-on: ubuntu-latest
18
+ steps:
19
+ - uses: actions/checkout@v4
20
+ - uses: actions/setup-node@v4
21
+ with:
22
+ node-version: '22'
23
+ registry-url: 'https://registry.npmjs.org'
24
+ - name: Ensure npm supports trusted publishing (needs >= 11.5.1)
25
+ run: npm install -g npm@11 && npm --version
26
+ - name: Show target
27
+ run: node -e "const p=require('./package.json');console.log(p.name+'@'+p.version)"
28
+ - name: Publish
29
+ run: npm publish --provenance --access public ${{ inputs.dry_run && '--dry-run' || '' }}
30
+ env:
31
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
package/README.md CHANGED
@@ -7,7 +7,8 @@ DSH 的 GitHub 插件:在你自己的账号下注册一个私有 GitHub App,
7
7
  - 左侧栏「**GitHub 控制台**」页签 → 主面板(状态 / 仓库 / 收件箱 / 发布 / 市场)
8
8
  - 设置页同名分区 → 同一个面板
9
9
  - 仓库页可以打开文件、点「编辑」直接提交到默认分支(带 sha 冲突保护,不自动开 PR)
10
- - Agent 工具(21 个):`plugin_discover`、`gh_status`、`gh_auth`、`gh_repos`、`gh_tree`、`gh_file_read`、`gh_file_write`、`gh_issues`、`gh_issue_create`、`gh_issue_comment`、`gh_pulls`、`gh_pull_create`、`gh_pull_merge`、`gh_actions`、`gh_actions_rerun`、`plugin_preflight`、`plugin_publish`、`plugin_publish_status`、`plugin_npm_publish`、`plugin_market_index`、`plugin_market_probe`
10
+ - Agent 工具(**38 个**,由代码生成核对):gh_status, gh_auth, gh_audit, gh_repos, gh_tree, gh_file_read, gh_file_write, gh_issues, gh_issue_create, gh_issue_comment, gh_pulls, gh_pull_create, gh_pull_merge, gh_pull_detail, gh_pull_comment, gh_pull_review, gh_issue_update, gh_actions, gh_actions_rerun, gh_actions_log, gh_workflows, gh_workflow_dispatch, gh_notifications, gh_notifications_read, gh_code_search, gh_releases, gh_commits, gh_compare, plugin_discover, plugin_preflight, plugin_publish, plugin_publish_status, plugin_release_asset, plugin_npm_publish, plugin_market_index, plugin_market_attach, plugin_market_probe, plugin_market_readiness
11
+ - 连接方式 5 种:GitHub App 安装、App 用户授权(OAuth 回调)、**设备码授权(Device Flow)**、个人访问令牌、环境变量
11
12
 
12
13
  ## 第一次打开:不需要先登录
13
14
 
@@ -85,18 +86,21 @@ manifest 的三步必须在 **1 小时**内完成,`state` 一次性、5 分钟
85
86
  - 仓库/包里没有任何硬编码密钥;每个用户注册的是自己的 App。
86
87
  - 撤销:面板「清除本地 App 凭据」删本机记录;App 本身到 GitHub → Settings → Applications 删除。
87
88
 
88
- ## 连接方式(三选一,面板里切换)
89
+ ## 连接方式(五选一,面板里切换)
89
90
 
90
91
  | 方式 | 怎么连 | 能做什么 | 代价 |
91
92
  |---|---|---|---|
92
- | **GitHub App**(默认) | 注册 → 安装 → 选 installation | 仓库读写、PR、Issue、Actions、Workflows、管理;**拿不到通知与代码搜索** | 1 小时安装令牌,最安全 |
93
+ | **GitHub App**(默认) | 注册 → 安装 → 选 installation | 仓库读写、PR、Issue、Actions、Workflows;**拿不到通知与代码搜索** | 1 小时安装令牌,最安全 |
94
+ | **设备码授权**(推荐补全) | App 设置里勾 Enable Device Flow → 面板点「设备码授权」→ 输 8 位码 | 在 App 权限之上再加用户级身份:**代码搜索可用**;通知不可用(见下) | 8 小时用户令牌,到期自动续 |
95
+ | **App 用户授权(OAuth 回调)** | App 设置里登记回调 URL `http://127.0.0.1:<端口>/github-console/oauth/callback` → 面板授权 | 同设备码 | 端口变了要重新登记,不如设备码省事 |
93
96
  | **个人访问令牌(PAT)** | 面板粘贴,存进凭据服务,只显示末四位 | 用户级能力全开(含通知、代码搜索、个人仓建仓) | 长期令牌,建议 fine-grained + 有效期 |
94
97
  | **环境变量** | 配置 `patEnvName`(默认 `GITHUB_TOKEN`),值不落盘 | 同 PAT | 你自己管理变量 |
95
98
 
96
- - 选择存进 `github-console/active`,切换不会丢另一种连接的凭据;`authMode` 可固定成 `app|pat|env`。
99
+ - 选择存进 `github-console/active`,切换不会丢另一种连接的凭据;`authMode` 可固定成 `app|oauth|pat|env`。
100
+ - **通知只有 PAT / 环境变量能读**:GitHub 不对 GitHub App 令牌(含 App 用户令牌)开放 `/notifications`,实测返回 `Resource not accessible by integration`。
97
101
  - 面板「状态 → 连接方式」显示**能力矩阵**(代码读写 / PR / Issue / Actions / Workflow / 管理 / 通知 / 代码搜索),灰度即代表当前连接做不到。
98
- - **只读降级**:`readOnly: true`,或当前连接没有写权限时,所有写操作被拒绝并说明原因。
99
- - **审计留痕**:写操作追加到 `$DSH_HOME/storages/dsh-github-console/audit.ndjson`(时间、动作、账号、目标、结果),可用 `gh_audit` 或面板查看。
102
+ - **只读降级**:`readOnly: true` 时,**任何**写请求(面板路由或 Agent 工具)都在唯一出口 `gh.call()` 被拒绝并留痕,不依赖各工具自觉。
103
+ - **审计留痕**:每个写请求(方法 + 路径 + 连接类型 + 结果)追加到 `$DSH_HOME/storages/dsh-github-console/audit.ndjson`,被拒绝的写同样留痕,可用 `gh_audit` 或面板查看。
100
104
 
101
105
  ## 发布一个插件
102
106
 
@@ -139,7 +143,8 @@ manifest 的三步必须在 **1 小时**内完成,`state` 一次性、5 分钟
139
143
  ## 已知限制
140
144
 
141
145
  - **个人仓库创建不在 API 内**:GitHub App 安装令牌结构上无法调用 `POST /user/repos`。请先建仓,或建空仓后让插件推送。
142
- - 不做 npm publish、不提交市场 PR:市场收录靠爬虫刷新。
146
+ - **不在本机执行 npm**:npm 发布通过 GitHub Actions + Trusted Publisher(OIDC)完成;本机没有任何 npm 调用,也不保存 npm 令牌。
147
+ - 不自动提交第三方市场 PR:awesome-dsh-plugin 的条目录入仍需你提一次 PR(面板可生成条目字段)。
143
148
  - 不接收 webhook(本地无公网入口),收件箱是拉取式。
144
149
  - 只处理单个 installation;多账号需在面板里切换。
145
150
  - 合并 PR / 重跑 CI 需要显式 `confirm: true`;它们不会走宿主的审批弹窗。
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.5.0'
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-----/],
@@ -518,7 +545,11 @@ function createTransport(cfg) {
518
545
  const failures = []
519
546
  // One transient timeout must not fail a publish: retry the whole route set
520
547
  // a couple of times, re-probing the proxy so one that just came up is seen.
521
- 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]
522
553
  for (let round = 0; round < backoff.length; round++) {
523
554
  if (backoff[round]) await new Promise((resolve) => setTimeout(resolve, backoff[round]))
524
555
  const proxy = await detectProxy(round > 0)
@@ -797,8 +828,46 @@ function createGithub(ctx, cfg, transport) {
797
828
  return `${signingInput}.${signature}`
798
829
  }
799
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
+
800
842
  async function call(pathname, options = {}) {
801
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
+ }
802
871
  const init = { method, headers: { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28', ...headers } }
803
872
  if (auth === 'app') {
804
873
  const app = await readApp()
@@ -880,8 +949,23 @@ function createGithub(ctx, cfg, transport) {
880
949
  code === 'RATE_LIMITED' && reset
881
950
  ? `(限流重置于 ${new Date(Number(reset) * 1000).toLocaleString()})`
882
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
+ }
883
960
  throw new GhError(response.status, code, `${message}${suffix}`, data)
884
961
  }
962
+ if (isWrite) {
963
+ await appendAudit({
964
+ action: `${method} ${pathname}`,
965
+ ok: true,
966
+ account: writeAuth ? writeAuth.kind : '',
967
+ })
968
+ }
885
969
  return data
886
970
  }
887
971
 
@@ -1864,7 +1948,11 @@ function createGithub(ctx, cfg, transport) {
1864
1948
 
1865
1949
  async function runLog(owner, name, runId, tailLines = 120) {
1866
1950
  const repo = repoPath(owner, name)
1867
- 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 连接')
1868
1956
  // The archive answers 302 to a signed objects.githubusercontent.com URL, and
1869
1957
  // both hosts are hijacked on some machines, so follow the redirect through
1870
1958
  // the same resilient transport instead of global fetch.
@@ -2011,8 +2099,10 @@ async function exists(target) {
2011
2099
 
2012
2100
  async function collectFiles(root, budget) {
2013
2101
  const files = []
2102
+ const denied = []
2014
2103
  let total = 0
2015
2104
  let skipped = 0
2105
+ let truncated = false
2016
2106
  async function walk(dir) {
2017
2107
  let entries = []
2018
2108
  try {
@@ -2020,8 +2110,13 @@ async function collectFiles(root, budget) {
2020
2110
  } catch {
2021
2111
  return
2022
2112
  }
2113
+ entries.sort((a, b) => a.name.localeCompare(b.name))
2023
2114
  for (const entry of entries) {
2024
- 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
+ }
2025
2120
  const full = path.join(dir, entry.name)
2026
2121
  if (entry.isDirectory()) {
2027
2122
  if (SKIP_DIRS.has(entry.name)) continue
@@ -2029,6 +2124,12 @@ async function collectFiles(root, budget) {
2029
2124
  continue
2030
2125
  }
2031
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
+ }
2032
2133
  const stat = await fs.stat(full).catch(() => null)
2033
2134
  if (!stat) continue
2034
2135
  if (stat.size > 1024 * 1024) {
@@ -2041,11 +2142,16 @@ async function collectFiles(root, budget) {
2041
2142
  }
2042
2143
  const content = await fs.readFile(full)
2043
2144
  total += content.length
2044
- 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
+ })
2045
2151
  }
2046
2152
  }
2047
2153
  await walk(root)
2048
- return { files, total, skipped }
2154
+ return { files, total, skipped, denied, truncated }
2049
2155
  }
2050
2156
 
2051
2157
  function findSecrets(files) {
@@ -2082,7 +2188,8 @@ async function preflight(dir, gh, cfg) {
2082
2188
 
2083
2189
  let pkg = null
2084
2190
  try {
2085
- 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/, ''))
2086
2193
  add('package.json', 'pass', 'package.json 可解析', `${pkg.name || '未命名'}@${pkg.version || '?'}`)
2087
2194
  } catch (error) {
2088
2195
  add('package.json', 'block', 'package.json 不是合法 JSON', errorMessage(error))
@@ -2132,6 +2239,19 @@ async function preflight(dir, gh, cfg) {
2132
2239
  }
2133
2240
 
2134
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
+ }
2135
2255
  const secrets = findSecrets(collected.files)
2136
2256
  if (secrets.length) {
2137
2257
  add(
@@ -2153,23 +2273,30 @@ async function preflight(dir, gh, cfg) {
2153
2273
  }
2154
2274
  if (hardPaths.length) add('local-paths', 'warn', '代码里出现本机绝对路径', hardPaths.slice(0, 5).join(', '))
2155
2275
 
2156
- 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
+ )
2157
2284
 
2158
2285
  if (gh) {
2159
2286
  try {
2160
- const response = await fetch(`https://registry.npmjs.org/${encodeURIComponent(pkg.name)}`)
2161
- if (response.status === 200) {
2162
- 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 || '{}')
2163
2290
  const latest = data['dist-tags'] ? data['dist-tags'].latest : ''
2164
2291
  if (latest === pkg.version) {
2165
2292
  add('npm', 'block', 'npm 上已存在同名同版本', `${pkg.name}@${latest}`)
2166
2293
  } else {
2167
2294
  add('npm', 'info', 'npm 上已存在该包', `latest ${latest}`)
2168
2295
  }
2169
- } else if (response.status === 404) {
2296
+ } else if (probe.status === 404) {
2170
2297
  add('npm', 'pass', 'npm 上没有同名包', pkg.name)
2171
2298
  } else {
2172
- add('npm', 'info', 'npm 查询未确认', `HTTP ${response.status}`)
2299
+ add('npm', 'info', 'npm 查询未确认', `HTTP ${probe.status}`)
2173
2300
  }
2174
2301
  } catch (error) {
2175
2302
  add('npm', 'info', 'npm 查询失败', errorMessage(error))
@@ -2262,9 +2389,31 @@ async function pushFiles(gh, owner, name, branch, files, message) {
2262
2389
  }
2263
2390
 
2264
2391
  stage = 'create-tree'
2265
- const treeBody = {
2266
- 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
+ }
2267
2415
  }
2416
+ const treeBody = { tree: entries }
2268
2417
  if (baseTreeSha) treeBody.base_tree = baseTreeSha
2269
2418
  const tree = await gh.call(`${repo}/git/trees`, { method: 'POST', body: treeBody })
2270
2419
 
@@ -2285,7 +2434,7 @@ async function pushFiles(gh, owner, name, branch, files, message) {
2285
2434
  body: { ref: `refs/heads/${branch}`, sha: commit.sha },
2286
2435
  })
2287
2436
  }
2288
- return { commit: commit.sha, files: files.length, branch, firstCommit: bootstrapped }
2437
+ return { commit: commit.sha, files: files.length, branch, firstCommit: bootstrapped, deleted }
2289
2438
  } catch (error) {
2290
2439
  // Naming the failed stage turns "Git Repository is empty." into something
2291
2440
  // actionable instead of a single opaque message.
@@ -2586,9 +2735,25 @@ async function ensurePublishWorkflow(gh, owner, repo, branch, workflowFile) {
2586
2735
 
2587
2736
  async function dispatchWorkflow(gh, owner, repo, workflowFile, ref, inputs) {
2588
2737
  const body = inputs && Object.keys(inputs).length ? { ref, inputs } : { ref }
2589
- await gh.call(
2590
- `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/actions/workflows/${encodeURIComponent(workflowFile)}/dispatches`,
2591
- { 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 : '' },
2592
2757
  )
2593
2758
  }
2594
2759
 
@@ -2616,18 +2781,28 @@ async function waitForWorkflowRun(gh, owner, repo, workflowFile, sinceMs, timeou
2616
2781
  return last ? { ...last, status: 'timeout' } : { status: 'unknown', url: null }
2617
2782
  }
2618
2783
 
2619
- function marketIndexDocument({ pkg, owner, repo, commit, entryTitle, entryDescription }) {
2784
+ function marketIndexDocument({ pkg, owner, repo, commit, entryTitle, entryDescription, iconPath, previous, entries }) {
2620
2785
  const repositoryUrl = `https://github.com/${owner}/${repo}`
2786
+ const relativeIcon = iconPath ? `../${String(iconPath).replace(/^\.\//, '')}` : '../icon.svg'
2621
2787
  const engines =
2622
2788
  pkg.engines && typeof pkg.engines.dsh === 'string' && pkg.engines.dsh.trim() && !pkg.engines.dsh.startsWith('workspace:')
2623
2789
  ? { dsh: pkg.engines.dsh.trim() }
2624
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
2625
2801
  const plugin = {
2626
2802
  name: pkg.name,
2627
2803
  title: entryTitle || pkg.name,
2628
2804
  description: entryDescription || pkg.description || pkg.name,
2629
- // Resolved against the index URL, so the icon ships with the repository.
2630
- icon: '../icon.svg',
2805
+ icon: relativeIcon,
2631
2806
  author: owner,
2632
2807
  repository: { url: repositoryUrl },
2633
2808
  metadata: {
@@ -2636,24 +2811,54 @@ function marketIndexDocument({ pkg, owner, repo, commit, entryTitle, entryDescri
2636
2811
  versions: [
2637
2812
  {
2638
2813
  version: pkg.version,
2639
- publishTimestamp: Math.floor(Date.now() / 1000),
2814
+ publishTimestamp: Number.isInteger(previousTimestamp) ? previousTimestamp : Math.floor(Date.now() / 1000),
2640
2815
  source: { type: 'git', url: repositoryUrl, commit },
2641
2816
  engines,
2642
2817
  },
2643
2818
  ],
2644
2819
  }
2645
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
+ : []
2646
2850
  return {
2647
2851
  format: 1,
2648
2852
  title: `${owner} DSH plugin index`,
2649
2853
  description: 'Self-hosted DSH plugin index generated by the GitHub console.',
2650
2854
  metadata: {},
2651
- plugins: [plugin],
2855
+ plugins: [plugin, ...extra],
2652
2856
  }
2653
2857
  }
2654
2858
 
2655
2859
  async function readLocalPackage(dir) {
2656
- 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/, '')
2657
2862
  const pkg = JSON.parse(raw)
2658
2863
  if (!pkg.name || !pkg.version) throw new Error('package.json 缺少 name 或 version')
2659
2864
  return pkg
@@ -2672,10 +2877,8 @@ async function npmPublishState(gh, cfg, { owner, repo, dir }) {
2672
2877
  let exists = null
2673
2878
  if (name) {
2674
2879
  try {
2675
- const response = await fetch(`https://registry.npmjs.org/${encodeURIComponent(name)}`, {
2676
- headers: { 'User-Agent': `dsh-github-console/${PLUGIN_VERSION}` },
2677
- })
2678
- exists = response.status === 200
2880
+ const probe = await httpGetJson(`https://registry.npmjs.org/${encodeURIComponent(name)}`)
2881
+ exists = probe.status === 200
2679
2882
  } catch {
2680
2883
  exists = null
2681
2884
  }
@@ -2801,6 +3004,48 @@ function unzipEntries(buffer) {
2801
3004
  return entries
2802
3005
  }
2803
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
+
2804
3049
  async function probeMarket(input, gh, cfg) {
2805
3050
  const checkedAt = new Date().toISOString()
2806
3051
  const results = []
@@ -2808,9 +3053,9 @@ async function probeMarket(input, gh, cfg) {
2808
3053
 
2809
3054
  // 1. npm package presence
2810
3055
  try {
2811
- 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`)
2812
3057
  if (response.status === 200) {
2813
- const data = await response.json()
3058
+ const data = JSON.parse(response.text || '{}')
2814
3059
  push('npm', 'listed', `${input.name}@${data.version}`, { version: data.version })
2815
3060
  } else if (response.status === 404) {
2816
3061
  push('npm', 'absent', 'npm 上没有这个包名')
@@ -2859,12 +3104,12 @@ async function probeMarket(input, gh, cfg) {
2859
3104
  // 3. Configured market indexes (format 1 JSON with an items/plugins array)
2860
3105
  for (const url of cfg.marketIndexUrls) {
2861
3106
  try {
2862
- const response = await fetch(url)
2863
- if (!response.ok) {
3107
+ const response = await httpGetJson(url)
3108
+ if (response.status < 200 || response.status >= 300) {
2864
3109
  push(`index:${url}`, 'unknown', `HTTP ${response.status}`)
2865
3110
  continue
2866
3111
  }
2867
- const text = await response.text()
3112
+ const text = response.text
2868
3113
  const found = text.includes(`"${input.name}"`) || text.includes(`"${input.name}@`)
2869
3114
  push(`index:${url}`, found ? 'listed' : 'absent', found ? '索引里出现该包名' : '索引里没有该包名')
2870
3115
  } catch (error) {
@@ -2965,7 +3210,10 @@ async function runPublish({ job, gh, cfg, dir, owner, repo, version, notes, opts
2965
3210
  const collected = await collectFiles(path.resolve(dir), cfg.maxPushBytes)
2966
3211
  const pushed = await pushFiles(gh, owner, repo, branch, collected.files, opts.message || `chore(release): v${semver}`)
2967
3212
  step(job, 'push').state = 'done'
2968
- 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 ? '(仓库原本为空,这是首个提交)' : '')
2969
3217
  job.commit = pushed.commit
2970
3218
  } catch (error) {
2971
3219
  step(job, 'push').state = 'failed'
@@ -2978,8 +3226,10 @@ async function runPublish({ job, gh, cfg, dir, owner, repo, version, notes, opts
2978
3226
  step(job, 'topics').state = 'done'
2979
3227
  step(job, 'topics').detail = topics.after.join(', ')
2980
3228
  } catch (error) {
2981
- step(job, 'topics').state = 'failed'
2982
- 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)}`
2983
3233
  }
2984
3234
 
2985
3235
  try {
@@ -3015,6 +3265,7 @@ export const inject = ['tools']
3015
3265
  export function apply(ctx, rawConfig) {
3016
3266
  const cfg = normalizeConfig(rawConfig)
3017
3267
  const transport = createTransport(cfg)
3268
+ sharedTransport = transport
3018
3269
  const gh = createGithub(ctx, cfg, transport)
3019
3270
  const jobs = createJobStore()
3020
3271
  let bridgeToken = ''
@@ -3088,17 +3339,23 @@ export function apply(ctx, rawConfig) {
3088
3339
 
3089
3340
  const discover = (extra) => discoverPlugins(discoveryRoots(extra))
3090
3341
 
3091
- // 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.
3092
3355
  const audited = async (action, target, run) => {
3093
- const started = Date.now()
3094
- try {
3095
- const result = await run()
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
- }
3356
+ void action
3357
+ void target
3358
+ return run()
3102
3359
  }
3103
3360
 
3104
3361
  // Write actions are refused up front when the active connection cannot write.
@@ -3176,7 +3433,7 @@ export function apply(ctx, rawConfig) {
3176
3433
  default_permissions: {
3177
3434
  metadata: 'read',
3178
3435
  contents: 'write',
3179
- administration: 'write',
3436
+
3180
3437
  pull_requests: 'write',
3181
3438
  issues: 'write',
3182
3439
  actions: 'write',
@@ -3530,6 +3787,7 @@ export function apply(ctx, rawConfig) {
3530
3787
  const ref = await gh.call(`${repoPath}/git/ref/heads/${encodeURIComponent(branch)}`)
3531
3788
  const commit = ref.object ? ref.object.sha : ''
3532
3789
  if (!commit) return sendJson(response, 400, { error: `读不到 ${branch} 的最新提交,请先发布一次` })
3790
+ const existing = await repoFile(gh, args.owner, args.repo, cfg.marketIndexPath, branch)
3533
3791
  const doc = marketIndexDocument({
3534
3792
  pkg,
3535
3793
  owner: args.owner,
@@ -3537,8 +3795,10 @@ export function apply(ctx, rawConfig) {
3537
3795
  commit,
3538
3796
  entryTitle: args.title,
3539
3797
  entryDescription: args.description,
3798
+ iconPath: await detectLocalIcon(dir),
3799
+ previous: parseIndexFile(existing),
3800
+ entries: args.entries,
3540
3801
  })
3541
- const existing = await repoFile(gh, args.owner, args.repo, cfg.marketIndexPath, branch)
3542
3802
  await gh.writeFile(
3543
3803
  args.owner,
3544
3804
  args.repo,
@@ -3549,7 +3809,9 @@ export function apply(ctx, rawConfig) {
3549
3809
  branch,
3550
3810
  )
3551
3811
  // Keep a copy locally so this machine can serve the index even when its
3552
- // 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(() => {})
3553
3815
  await gh
3554
3816
  .writeRecord(INDEX_CRED, { owner: args.owner, repo: args.repo, path: cfg.marketIndexPath, body: JSON.stringify(doc, null, 2) })
3555
3817
  .catch(() => {})
@@ -3791,7 +4053,7 @@ export function apply(ctx, rawConfig) {
3791
4053
  register({
3792
4054
  name: 'gh_auth',
3793
4055
  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 (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).',
3795
4057
  parameters: {
3796
4058
  type: 'object',
3797
4059
  properties: {
@@ -4292,6 +4554,7 @@ export function apply(ctx, rawConfig) {
4292
4554
  const ref = await gh.call(`${repoPath}/git/ref/heads/${encodeURIComponent(branch)}`)
4293
4555
  const commit = ref.object ? ref.object.sha : ''
4294
4556
  if (!commit) throw new Error(`读不到 ${branch} 的最新提交:请先发布一次`)
4557
+ const existing = await repoFile(gh, args.owner, args.repo, cfg.marketIndexPath, branch)
4295
4558
  const doc = marketIndexDocument({
4296
4559
  pkg,
4297
4560
  owner: args.owner,
@@ -4299,8 +4562,10 @@ export function apply(ctx, rawConfig) {
4299
4562
  commit,
4300
4563
  entryTitle: args.title,
4301
4564
  entryDescription: args.description,
4565
+ iconPath: await detectLocalIcon(dir),
4566
+ previous: parseIndexFile(existing),
4567
+ entries: args.entries,
4302
4568
  })
4303
- const existing = await repoFile(gh, args.owner, args.repo, cfg.marketIndexPath, branch)
4304
4569
  await gh.writeFile(
4305
4570
  args.owner,
4306
4571
  args.repo,
@@ -4310,6 +4575,7 @@ export function apply(ctx, rawConfig) {
4310
4575
  existing ? existing.sha : undefined,
4311
4576
  branch,
4312
4577
  )
4578
+ await persistLocalIndex(dir, doc).catch(() => {})
4313
4579
  await gh
4314
4580
  .writeRecord(INDEX_CRED, { owner: args.owner, repo: args.repo, path: cfg.marketIndexPath, body: JSON.stringify(doc, null, 2) })
4315
4581
  .catch(() => {})
@@ -4563,7 +4829,7 @@ export function apply(ctx, rawConfig) {
4563
4829
  register({
4564
4830
  name: 'gh_actions_log',
4565
4831
  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.',
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.',
4567
4833
  parameters: {
4568
4834
  type: 'object',
4569
4835
  properties: {
package/locale/en.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "GitHub console",
4
- "description": "Sign in with your own GitHub App, then browse repositories, read and commit files, follow issues, pull requests and workflow runs, and publish a local DSH plugin to GitHub from one sidebar panel; 19 gh_* and plugin_* tools let the agent do the same. Opening the panel first scans your workspaces for publishable plugins and runs an offline report, which needs no sign-in; publishing then asks only for the directory, the account and the repository name. Registration uses GitHub's manifest flow, so the private key is written only to the DSH credential service and installation tokens stay in memory for one hour. Publishing commits an existing plugin directory into an existing repository through the Git Data API (no git binary, no package scripts), merges the dsh-plugin topic, creates a v<version> Release, and probes npm, the repository topic, the release tag and any configured market index URLs; a failed probe reports unknown rather than absent. Limitations: the repository must already exist and be authorized for the App (the panel links to a prefilled creation page; an installation token cannot create a personal repository directly), npm publish and market submission stay manual, no webhooks are received, and a file commit goes straight to the default branch without opening a pull request."
4
+ "description": "Sign in with your own GitHub App, then browse repositories, read and commit files, follow issues, pull requests and workflow runs, and publish a local DSH plugin to GitHub from one sidebar panel; 38 gh_* and plugin_* tools let the agent do the same. Opening the panel first scans your workspaces for publishable plugins and runs an offline report, which needs no sign-in; publishing then asks only for the directory, the account and the repository name. Registration uses GitHub's manifest flow, so the private key is written only to the DSH credential service and installation tokens stay in memory for one hour. Publishing commits an existing plugin directory into an existing repository through the Git Data API (no git binary, no package scripts), merges the dsh-plugin topic, creates a v<version> Release, and probes npm, the repository topic, the release tag and any configured market index URLs; a failed probe reports unknown rather than absent. Limitations: the repository must already exist and be authorized for the App (the panel links to a prefilled creation page; an installation token cannot create a personal repository directly), npm publish and market submission stay manual, no webhooks are received, and a file commit goes straight to the default branch without opening a pull request."
5
5
  }
6
6
  }
package/locale/zh.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "GitHub 控制台",
4
- "description": "用你自己的 GitHub App 登录,然后在左侧栏一个面板里浏览仓库、读取与提交文件、查看 Issue / PR / Actions,并把本地 DSH 插件发布到 GitHub;同时提供 19 个 gh_* 与 plugin_* 工具让 Agent 做同样的事。打开面板会先扫描工作区列出可发布的插件并做离线体检,这一步不需要登录;发布时只问目录、账号、仓库名三件事。注册走 GitHub manifest flow,私钥只写入 DSH 凭据服务,安装令牌只在内存里、1 小时过期。发布把一个已存在的插件目录经 Git Data API 提交进一个已存在的仓库(不需要 git 命令,也不执行任何包脚本),合并 dsh-plugin topic,创建 v<版本> Release,并探测 npm、仓库 topic、Release tag 与配置里的市场索引 URL;探测失败记作「未知」,不会误判为未收录。限制:仓库必须先存在并授权给 App(面板给一键建仓链接;安装令牌无法直接新建个人仓库),npm publish 与市场提交仍需手动,不接收 webhook,面板提交文件直接写入默认分支、不自动开 PR。"
4
+ "description": "用你自己的 GitHub App 登录,然后在左侧栏一个面板里浏览仓库、读取与提交文件、查看 Issue / PR / Actions,并把本地 DSH 插件发布到 GitHub;同时提供 38 个 gh_* 与 plugin_* 工具让 Agent 做同样的事。打开面板会先扫描工作区列出可发布的插件并做离线体检,这一步不需要登录;发布时只问目录、账号、仓库名三件事。注册走 GitHub manifest flow,私钥只写入 DSH 凭据服务,安装令牌只在内存里、1 小时过期。发布把一个已存在的插件目录经 Git Data API 提交进一个已存在的仓库(不需要 git 命令,也不执行任何包脚本),合并 dsh-plugin topic,创建 v<版本> Release,并探测 npm、仓库 topic、Release tag 与配置里的市场索引 URL;探测失败记作「未知」,不会误判为未收录。限制:仓库必须先存在并授权给 App(面板给一键建仓链接;安装令牌无法直接新建个人仓库),npm publish 与市场提交仍需手动,不接收 webhook,面板提交文件直接写入默认分支、不自动开 PR。"
5
5
  }
6
6
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-github-console",
3
- "version": "0.5.0",
3
+ "version": "0.6.1",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "description": "GitHub console for DeepSeek Harness: GitHub App sign-in, repository browsing, issues/pulls/CI, plugin publishing with market checks, npm release via GitHub Actions, and a self-hosted market index",
@@ -24,7 +24,7 @@
24
24
  "./locale/*.json": "./locale/*.json",
25
25
  "./icon": "./icon.svg"
26
26
  },
27
- "files": [
27
+ "files": ["scripts", ".github",
28
28
  "index.js",
29
29
  "client.js",
30
30
  "cordis.patch.yml",
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Consistency check for the bundle. Fails when the tool count in README or the
3
+ * locale files drifts from the tools actually registered in index.js, and when
4
+ * either file no longer parses.
5
+ *
6
+ * node scripts/check.mjs
7
+ */
8
+ import fs from 'node:fs'
9
+ import path from 'node:path'
10
+ import vm from 'node:vm'
11
+ import { pathToFileURL } from 'node:url'
12
+
13
+ const root = path.resolve(import.meta.dirname, '..')
14
+ const problems = []
15
+ const notes = []
16
+
17
+ function read(relative) {
18
+ return fs.readFileSync(path.join(root, relative), 'utf8')
19
+ }
20
+
21
+ const host = read('index.js')
22
+ const client = read('client.js')
23
+
24
+ // index.js is an ES module (dynamic import parses and evaluates its top level,
25
+ // which only declares functions); client.js is a classic script.
26
+ try {
27
+ await import(pathToFileURL(path.join(root, 'index.js')).href)
28
+ notes.push('index.js: parses')
29
+ } catch (error) {
30
+ problems.push(`index.js: ${error.message}`)
31
+ }
32
+ try {
33
+ new vm.Script(client, { filename: 'client.js' })
34
+ notes.push('client.js: parses')
35
+ } catch (error) {
36
+ problems.push(`client.js: ${error.message}`)
37
+ }
38
+
39
+ const tools = [...host.matchAll(/^\s{4}name: '((?:gh|plugin)_[a-z_]+)'/gm)].map((match) => match[1])
40
+ const unique = [...new Set(tools)]
41
+ if (!unique.length) problems.push('index.js: no tool registrations found')
42
+ notes.push(`tools registered: ${unique.length}`)
43
+
44
+ const pkg = JSON.parse(read('package.json'))
45
+ if (pkg.version !== host.match(/PLUGIN_VERSION = '([^']+)'/)[1]) {
46
+ problems.push(`version mismatch: package.json ${pkg.version} vs index.js`)
47
+ }
48
+
49
+ const readme = read('README.md')
50
+ if (!readme.includes(`${unique.length} 个`)) {
51
+ problems.push(`README.md: does not mention the ${unique.length} tools`)
52
+ }
53
+
54
+ for (const locale of ['locale/zh.json', 'locale/en.json']) {
55
+ const text = read(locale)
56
+ const declared = /(\d+)\s*(?:个\s*)?gh_\*/.exec(text) || /(\d+)\s+gh_\*/.exec(text)
57
+ if (!declared) {
58
+ problems.push(`${locale}: no "<n> gh_*" count in meta.description`)
59
+ } else if (Number(declared[1]) !== unique.length) {
60
+ problems.push(`${locale}: says ${declared[1]} tools, code registers ${unique.length}`)
61
+ }
62
+ }
63
+
64
+ // Guard rails from the audit: every capability gate must exist, and the token
65
+ // refresh path must not assume an App installation.
66
+ for (const marker of ['READ_ONLY', 'NO_CAPABILITY', 'appendAudit', 'isDeniedFile', 'persistLocalIndex']) {
67
+ if (!host.includes(marker)) problems.push(`index.js: missing audit marker ${marker}`)
68
+ }
69
+ if (/const token = await installationToken\(\)\n\s*\/\/ The archive/.test(host)) {
70
+ problems.push('index.js: runLog still assumes an installation token')
71
+ }
72
+
73
+ console.log(notes.join('\n'))
74
+ if (problems.length) {
75
+ console.error('\nPROBLEMS:')
76
+ for (const problem of problems) console.error(`- ${problem}`)
77
+ process.exit(1)
78
+ }
79
+ console.log('\ncheck passed')