dsh-github-console 0.6.1 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -15,3 +15,5 @@ jobs:
15
15
  node-version: '22'
16
16
  - name: Bundle consistency
17
17
  run: node scripts/check.mjs
18
+ - name: Unit tests
19
+ run: node --test test/
package/README.md CHANGED
@@ -108,15 +108,20 @@ manifest 的三步必须在 **1 小时**内完成,`state` 一次性、5 分钟
108
108
 
109
109
  发布步骤(全部通过 GitHub REST 完成,不需要本机 git,也不执行任何 `npm install` / `prepare` / `postinstall`):
110
110
 
111
- 1. **体检** —— `package.json`、`dsh.bundle.patch`、入口文件、README/LICENSE/.gitignore、疑似密钥正则、本机绝对路径、npm 同名同版本
111
+ 1. **体检** —— `package.json`(容忍 BOM)、`dsh.bundle.patch`、入口文件、README/LICENSE/.gitignore、疑似密钥正则、本机绝对路径、npm 同名同版本、**敏感文件名拦截**(`.env*`、`.npmrc`、`*.pem/key/p12` 等直接 block)、**分支保护探测**
112
112
  2. **仓库** —— 确认仓库可访问(不存在时给出 `github.com/new?name=…` 链接)
113
- 3. **推送** —— 收集目录内文件(跳过 `node_modules`、`.git`),经 blobs → tree → commit → ref 提交到目标分支
114
- 4. **topic** —— 读出原有 topics,与配置里的 `topic`(默认 `dsh-plugin`)并集后整体写回(该接口是全量替换,不会清掉你已有的 topic,也不会额外加别的 topic)
113
+ 3. **推送** —— 收集目录内文件(跳过 `node_modules`、`.git`),经 blobs → tree → commit → ref 提交到目标分支:
114
+ - **删除同步**:远端有、本地没有的文件会被删除,但 `.github/workflows/*` 与 `.github/dependabot.yml` 属受保护路径,永不删除
115
+ - **执行位**:本地可执行文件按 `100755` 提交,其余 `100644`;提交后回读 tree 校验,结果写进推送步骤详情
116
+ - **文件数上限 300**:达到上限即 block(不再静默截断),超大文件会计入「跳过」并在详情里显示
117
+ 4. **topic** —— 读出原有 topics,与配置里的 `topic`(默认 `dsh-plugin`)并集后整体写回;需要 `Administration: write`,没有权限时跳过而不是让发布失败
115
118
  5. **Release** —— `v<version>`;已存在则跳过并提示
116
119
  6. **市场探测** —— npm、仓库 topic、Release tag、`config.marketIndexUrls` 里的每个索引
117
120
 
118
121
  探测失败记作 `unknown`,不会写成「未收录」——收录通常滞后 1–2 天。
119
122
 
123
+ npm 与市场索引的探测走的是插件自己的传输层(同一个代理 / 公共 DNS / CA 设置),不会绕过你的网络配置。
124
+
120
125
  ## 配置(`cordis.patch.yml` 的 config)
121
126
 
122
127
  | 字段 | 默认 | 说明 |
@@ -149,12 +154,26 @@ manifest 的三步必须在 **1 小时**内完成,`state` 一次性、5 分钟
149
154
  - 只处理单个 installation;多账号需在面板里切换。
150
155
  - 合并 PR / 重跑 CI 需要显式 `confirm: true`;它们不会走宿主的审批弹窗。
151
156
  - 体检只做静态读取:命中的密钥会阻断发布并给出行号。
157
+ - 写请求(`POST/PATCH/DELETE`)**不自动重试**:超时后可能已经在服务端生效,重发会重复建 Issue/评论;读请求与 `PUT`(contents API 用 `sha` 做乐观锁)才重试。
158
+ - 推送后的执行位校验只能读回 GitHub 侧结果;本机是 Windows 时本地 `chmod` 语义受限,执行位规则的单元测试因此只在 Linux CI 上真跑。
159
+
160
+ ## 测试与一致性
161
+
162
+ ```bash
163
+ node scripts/check.mjs # 工具数/版本/README/locale 一致性 + 安全标记存在性
164
+ node --test test/ # 纯函数与目录收集规则(CI 上跑,Linux 才检查执行位)
165
+ ```
166
+
167
+ `test/pure.test.mjs` 覆盖:敏感文件名拦截、受保护路径、写操作能力映射、市场索引文档(单/多条目、时间戳稳定)、ZIP 解析(含 GitHub 日志那种「数据描述符导致本地头长度为 0」的回归用例);`test/collect.test.mjs` 覆盖:拒绝敏感文件、300 上限标记 `truncated`、超大文件计入 `skipped`、执行位映射。
152
168
 
153
169
  ## 安全
154
170
 
155
171
  - 私钥、安装令牌、桥令牌只在 Host 侧;面板用同源 `/github-console/api/*` + `Authorization: Bearer`,无令牌返回 401。
156
172
  - 回调与 setup 路由只在本机 webServer 上注册,不额外开端口。
157
173
  - 所有对外错误信息不含凭据原文。
174
+ - **单一写闸门**:`readOnly` 与能力校验都在 `gh.call()` 里,工具与面板路由共用,无法绕过;每个写请求(成功或被拒)都写审计。
175
+ - **审计轮转**:`audit.ndjson` 超过 2 MB 时改名为 `audit.ndjson.1`(只保留上一份),长期运行不会撑爆磁盘。
176
+ - **限流可见**:面板状态页显示 core / search / graphql 的剩余额度与重置时间(每分钟最多读一次)。
158
177
 
159
178
  ## License
160
179
 
package/index.js CHANGED
@@ -22,8 +22,10 @@ import https from 'node:https'
22
22
  import zlib from 'node:zlib'
23
23
  import { fileURLToPath } from 'node:url'
24
24
  import { promises as dnsPromises, Resolver } from 'node:dns'
25
+ import { capabilityFor, isDeniedFile, isProtectedRemotePath, marketIndexDocument, unzipEntries } from './lib/pure.mjs'
26
+ import { collectFiles } from './lib/collect.mjs'
25
27
 
26
- const PLUGIN_VERSION = '0.6.1'
28
+ const PLUGIN_VERSION = '0.6.2'
27
29
  const APP_CRED = 'github-console/app'
28
30
  const INSTALL_CRED = 'github-console/install'
29
31
  const BRIDGE_CRED = 'github-console/bridge'
@@ -51,34 +53,6 @@ for (const key of [APP_CRED, INSTALL_CRED, BRIDGE_CRED, INDEX_CRED, PAT_CRED, AU
51
53
 
52
54
  // Only machine-local or VCS internals are skipped: a bundle's runtime entry can
53
55
  // legitimately live in lib/ or dist/, so those must be published.
54
- const SKIP_DIRS = new Set(['node_modules', '.git', '.pnpm-store', '.cache', '.turbo'])
55
- // 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
- }
82
56
  const SECRET_PATTERNS = [
83
57
  ['GitHub token', /\b(gh[pousr]_[A-Za-z0-9]{16,}|github_pat_[A-Za-z0-9_]{20,})\b/],
84
58
  ['private key', /-----BEGIN [A-Z ]*PRIVATE KEY-----/],
@@ -243,10 +217,23 @@ function auditPath() {
243
217
  return path.join(home, 'storages', 'dsh-github-console', 'audit.ndjson')
244
218
  }
245
219
 
220
+ const AUDIT_ROTATE_BYTES = 2 * 1024 * 1024
221
+
222
+ async function rotateAuditIfNeeded(target) {
223
+ const stat = await fs.stat(target).catch(() => null)
224
+ if (!stat || stat.size < AUDIT_ROTATE_BYTES) return
225
+ // Keep exactly one previous file: the trail runs for years, the disk does not.
226
+ await fs.rename(target, `${target}.1`).catch(async () => {
227
+ await fs.rm(`${target}.1`, { force: true }).catch(() => {})
228
+ await fs.rename(target, `${target}.1`).catch(() => {})
229
+ })
230
+ }
231
+
246
232
  async function appendAudit(entry) {
247
233
  try {
248
234
  const target = auditPath()
249
235
  await fs.mkdir(path.dirname(target), { recursive: true })
236
+ await rotateAuditIfNeeded(target)
250
237
  await fs.appendFile(target, `${JSON.stringify({ at: new Date().toISOString(), ...entry })}\n`, 'utf8')
251
238
  } catch {
252
239
  /* auditing never breaks an action */
@@ -828,16 +815,6 @@ function createGithub(ctx, cfg, transport) {
828
815
  return `${signingInput}.${signature}`
829
816
  }
830
817
 
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
818
 
842
819
  async function call(pathname, options = {}) {
843
820
  const { method = 'GET', body, auth = 'auto', headers = {}, rawBody = false } = options
@@ -1115,6 +1092,7 @@ function createGithub(ctx, cfg, transport) {
1115
1092
  }
1116
1093
 
1117
1094
  let authCache = null
1095
+ let rateLimitCache = null
1118
1096
 
1119
1097
  /** The App's own OAuth callback must be registered before the authorize step. */
1120
1098
  async function ensureOAuthCallback(origin) {
@@ -1526,8 +1504,33 @@ function createGithub(ctx, cfg, transport) {
1526
1504
  const patToken = await readPat().catch(() => '')
1527
1505
  const oauthState = await readRecord(OAUTH_CRED).catch(() => undefined)
1528
1506
  const envToken = process.env[cfg.patEnvName] || ''
1507
+ // Real rate-limit headroom, so a panel user can see the wall before hitting it.
1508
+ let limits = null
1509
+ try {
1510
+ const now = Date.now()
1511
+ if (!rateLimitCache || now - rateLimitCache.at > 60000) {
1512
+ const json = await call('/rate_limit')
1513
+ rateLimitCache = { at: now, value: json }
1514
+ }
1515
+ const resources = (rateLimitCache.value && rateLimitCache.value.resources) || {}
1516
+ limits = Object.fromEntries(
1517
+ ['core', 'search', 'graphql']
1518
+ .filter((key) => resources[key])
1519
+ .map((key) => [
1520
+ key,
1521
+ {
1522
+ limit: resources[key].limit,
1523
+ remaining: resources[key].remaining,
1524
+ resetAt: resources[key].reset ? new Date(resources[key].reset * 1000).toISOString() : null,
1525
+ },
1526
+ ]),
1527
+ )
1528
+ } catch {
1529
+ limits = null
1530
+ }
1529
1531
  const base = {
1530
1532
  version: PLUGIN_VERSION,
1533
+ limits,
1531
1534
  apiBase: cfg.baseUrl,
1532
1535
  configured: Boolean(app),
1533
1536
  app: app
@@ -2097,62 +2100,6 @@ async function exists(target) {
2097
2100
  }
2098
2101
  }
2099
2102
 
2100
- async function collectFiles(root, budget) {
2101
- const files = []
2102
- const denied = []
2103
- let total = 0
2104
- let skipped = 0
2105
- let truncated = false
2106
- async function walk(dir) {
2107
- let entries = []
2108
- try {
2109
- entries = await fs.readdir(dir, { withFileTypes: true })
2110
- } catch {
2111
- return
2112
- }
2113
- entries.sort((a, b) => a.name.localeCompare(b.name))
2114
- for (const entry of entries) {
2115
- if (files.length >= 300) {
2116
- // Stop scanning and say so, instead of silently dropping the rest.
2117
- truncated = true
2118
- return
2119
- }
2120
- const full = path.join(dir, entry.name)
2121
- if (entry.isDirectory()) {
2122
- if (SKIP_DIRS.has(entry.name)) continue
2123
- await walk(full)
2124
- continue
2125
- }
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
- }
2133
- const stat = await fs.stat(full).catch(() => null)
2134
- if (!stat) continue
2135
- if (stat.size > 1024 * 1024) {
2136
- skipped += 1
2137
- continue
2138
- }
2139
- if (total + stat.size > budget) {
2140
- skipped += 1
2141
- continue
2142
- }
2143
- const content = await fs.readFile(full)
2144
- total += content.length
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
- })
2151
- }
2152
- }
2153
- await walk(root)
2154
- return { files, total, skipped, denied, truncated }
2155
- }
2156
2103
 
2157
2104
  function findSecrets(files) {
2158
2105
  const hits = []
@@ -2434,7 +2381,26 @@ async function pushFiles(gh, owner, name, branch, files, message) {
2434
2381
  body: { ref: `refs/heads/${branch}`, sha: commit.sha },
2435
2382
  })
2436
2383
  }
2437
- return { commit: commit.sha, files: files.length, branch, firstCommit: bootstrapped, deleted }
2384
+ // Read the committed tree back: GitHub is the source of truth for modes, and
2385
+ // this catches an executable file that silently landed as 100644.
2386
+ let modeChecked = 0
2387
+ let modeMismatch = 0
2388
+ const executables = new Set(files.filter((file) => file.mode === '100755').map((file) => file.path))
2389
+ if (executables.size) {
2390
+ const committed = await gh.call(`${repo}/git/trees/${commit.sha}?recursive=1`).catch(() => null)
2391
+ const remoteModes = new Map(
2392
+ committed && Array.isArray(committed.tree)
2393
+ ? committed.tree.filter((item) => item.type === 'blob').map((item) => [item.path, item.mode])
2394
+ : [],
2395
+ )
2396
+ for (const filePath of executables) {
2397
+ const mode = remoteModes.get(filePath)
2398
+ if (!mode) continue
2399
+ modeChecked += 1
2400
+ if (mode !== '100755') modeMismatch += 1
2401
+ }
2402
+ }
2403
+ return { commit: commit.sha, files: files.length, branch, firstCommit: bootstrapped, deleted, modeChecked, modeMismatch }
2438
2404
  } catch (error) {
2439
2405
  // Naming the failed stage turns "Git Repository is empty." into something
2440
2406
  // actionable instead of a single opaque message.
@@ -2658,6 +2624,25 @@ async function marketReadiness(gh, cfg, { owner, repo, dir }) {
2658
2624
  )
2659
2625
  }
2660
2626
 
2627
+ // Direct pushes fail on a protected branch, so say it before the user tries.
2628
+ const protection = await gh
2629
+ .call(`${repoPath}/branches/${encodeURIComponent(cfg.publishBranch)}/protection`)
2630
+ .then((body) => ({ protected: true, body }))
2631
+ .catch((error) => (error && error.status === 404 ? { protected: false } : { protected: null, error: errorMessage(error) }))
2632
+ if (protection.protected === true) {
2633
+ const reviews = protection.body && protection.body.required_pull_request_reviews
2634
+ add(
2635
+ 'branch-protection',
2636
+ 'warn',
2637
+ `${cfg.publishBranch} 启用了分支保护`,
2638
+ `需要 PR 或评审${reviews ? '(至少 ' + (reviews.required_approving_review_count || 1) + ' 个批准)' : ''};直接推送会被拒,请先放开或改用 PR 流程`,
2639
+ )
2640
+ } else if (protection.protected === false) {
2641
+ add('branch-protection', 'pass', `${cfg.publishBranch} 未启用分支保护`, '可以直接推送')
2642
+ } else {
2643
+ add('branch-protection', 'info', '读不到分支保护状态', protection.error || '')
2644
+ }
2645
+
2661
2646
  const iconCandidates = ['assets/icon-512.png', 'assets/icon-180.png', 'icon.png', 'assets/icon.png']
2662
2647
  let iconPath = ''
2663
2648
  for (const candidate of iconCandidates) {
@@ -2781,80 +2766,6 @@ async function waitForWorkflowRun(gh, owner, repo, workflowFile, sinceMs, timeou
2781
2766
  return last ? { ...last, status: 'timeout' } : { status: 'unknown', url: null }
2782
2767
  }
2783
2768
 
2784
- function marketIndexDocument({ pkg, owner, repo, commit, entryTitle, entryDescription, iconPath, previous, entries }) {
2785
- const repositoryUrl = `https://github.com/${owner}/${repo}`
2786
- const relativeIcon = iconPath ? `../${String(iconPath).replace(/^\.\//, '')}` : '../icon.svg'
2787
- const engines =
2788
- pkg.engines && typeof pkg.engines.dsh === 'string' && pkg.engines.dsh.trim() && !pkg.engines.dsh.startsWith('workspace:')
2789
- ? { dsh: pkg.engines.dsh.trim() }
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
2801
- const plugin = {
2802
- name: pkg.name,
2803
- title: entryTitle || pkg.name,
2804
- description: entryDescription || pkg.description || pkg.name,
2805
- icon: relativeIcon,
2806
- author: owner,
2807
- repository: { url: repositoryUrl },
2808
- metadata: {
2809
- keywords: Array.isArray(pkg.keywords) ? pkg.keywords.filter((item) => typeof item === 'string').slice(0, 20) : [],
2810
- },
2811
- versions: [
2812
- {
2813
- version: pkg.version,
2814
- publishTimestamp: Number.isInteger(previousTimestamp) ? previousTimestamp : Math.floor(Date.now() / 1000),
2815
- source: { type: 'git', url: repositoryUrl, commit },
2816
- engines,
2817
- },
2818
- ],
2819
- }
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
- : []
2850
- return {
2851
- format: 1,
2852
- title: `${owner} DSH plugin index`,
2853
- description: 'Self-hosted DSH plugin index generated by the GitHub console.',
2854
- metadata: {},
2855
- plugins: [plugin, ...extra],
2856
- }
2857
- }
2858
2769
 
2859
2770
  async function readLocalPackage(dir) {
2860
2771
  // Strip a UTF-8 BOM: several Windows editors write one and JSON.parse rejects it.
@@ -2939,70 +2850,6 @@ async function npmPublishState(gh, cfg, { owner, repo, dir }) {
2939
2850
  }
2940
2851
  }
2941
2852
 
2942
- function unzipEntries(buffer) {
2943
- // GitHub log archives use data descriptors, so sizes come from the central
2944
- // directory rather than the local header. Minimal deflate-only reader.
2945
- const entries = []
2946
- let eocd = -1
2947
- for (let i = buffer.length - 22; i >= Math.max(0, buffer.length - 70000); i--) {
2948
- if (buffer.readUInt32LE(i) === 0x06054b50) {
2949
- eocd = i
2950
- break
2951
- }
2952
- }
2953
- const read = (offset, nameLength, extraLength) => {
2954
- const method = buffer.readUInt16LE(offset + 10)
2955
- const compressed = buffer.readUInt32LE(offset + 20)
2956
- const name = buffer.subarray(offset + 46, offset + 46 + nameLength).toString('utf8')
2957
- const localOffset = buffer.readUInt32LE(offset + 42)
2958
- const localNameLength = buffer.readUInt16LE(localOffset + 26)
2959
- const localExtraLength = buffer.readUInt16LE(localOffset + 28)
2960
- const dataStart = localOffset + 30 + localNameLength + localExtraLength
2961
- const data = buffer.subarray(dataStart, dataStart + compressed)
2962
- let text = ''
2963
- try {
2964
- text = method === 0 ? data.toString('utf8') : zlib.inflateRawSync(data).toString('utf8')
2965
- } catch {
2966
- text = ''
2967
- }
2968
- entries.push({ name, text })
2969
- void extraLength
2970
- }
2971
- if (eocd >= 0) {
2972
- const count = buffer.readUInt16LE(eocd + 10)
2973
- let offset = buffer.readUInt32LE(eocd + 16)
2974
- for (let index = 0; index < count; index++) {
2975
- if (buffer.readUInt32LE(offset) !== 0x02014b50) break
2976
- const nameLength = buffer.readUInt16LE(offset + 28)
2977
- const extraLength = buffer.readUInt16LE(offset + 30)
2978
- const commentLength = buffer.readUInt16LE(offset + 32)
2979
- read(offset, nameLength, extraLength)
2980
- offset += 46 + nameLength + extraLength + commentLength
2981
- }
2982
- if (entries.length) return entries
2983
- }
2984
- // Fallback: walk local headers (works when sizes are present).
2985
- let offset = 0
2986
- while (offset + 30 <= buffer.length) {
2987
- if (buffer.readUInt32LE(offset) !== 0x04034b50) break
2988
- const method = buffer.readUInt16LE(offset + 8)
2989
- const compressed = buffer.readUInt32LE(offset + 18)
2990
- const nameLength = buffer.readUInt16LE(offset + 26)
2991
- const extraLength = buffer.readUInt16LE(offset + 28)
2992
- const name = buffer.subarray(offset + 30, offset + 30 + nameLength).toString('utf8')
2993
- const dataStart = offset + 30 + nameLength + extraLength
2994
- const data = buffer.subarray(dataStart, dataStart + compressed)
2995
- let text = ''
2996
- try {
2997
- text = method === 0 ? data.toString('utf8') : zlib.inflateRawSync(data).toString('utf8')
2998
- } catch {
2999
- text = ''
3000
- }
3001
- entries.push({ name, text })
3002
- offset = dataStart + compressed
3003
- }
3004
- return entries
3005
- }
3006
2853
 
3007
2854
  /** Set once by apply(): every outbound JSON request shares the same routing. */
3008
2855
  let sharedTransport = null
@@ -3213,6 +3060,9 @@ async function runPublish({ job, gh, cfg, dir, owner, repo, version, notes, opts
3213
3060
  step(job, 'push').detail =
3214
3061
  `${pushed.files} 个文件 → ${branch} @ ${pushed.commit.slice(0, 7)}` +
3215
3062
  (pushed.deleted ? `,删除远端 ${pushed.deleted} 个过期文件` : '') +
3063
+ (pushed.modeChecked
3064
+ ? `,执行位已校验 ${pushed.modeChecked} 个${pushed.modeMismatch ? `(其中 ${pushed.modeMismatch} 个仍是 100644)` : ''}`
3065
+ : '') +
3216
3066
  (pushed.firstCommit ? '(仓库原本为空,这是首个提交)' : '')
3217
3067
  job.commit = pushed.commit
3218
3068
  } catch (error) {
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Directory walk for publishing. Kept separate from the host half so the rules
3
+ * (what is skipped, denied, truncated, and which mode a file gets) can be tested
4
+ * with plain `node --test` instead of only through a live publish.
5
+ */
6
+ import fs from 'node:fs/promises'
7
+ import path from 'node:path'
8
+ import { isDeniedFile } from './pure.mjs'
9
+
10
+ // Only machine-local or VCS internals are skipped: a bundle's runtime entry can
11
+ // legitimately live in lib/ or dist/, so those must be published.
12
+ export const SKIP_DIRS = new Set(['node_modules', '.git', '.pnpm-store', '.cache', '.turbo'])
13
+ export const MAX_FILES = 300
14
+ export const MAX_FILE_BYTES = 1024 * 1024
15
+
16
+ export async function collectFiles(root, budget, options = {}) {
17
+ const maxFiles = options.maxFiles || MAX_FILES
18
+ const maxFileBytes = options.maxFileBytes || MAX_FILE_BYTES
19
+ const files = []
20
+ const denied = []
21
+ let total = 0
22
+ let skipped = 0
23
+ let truncated = false
24
+ async function walk(dir) {
25
+ let entries = []
26
+ try {
27
+ entries = await fs.readdir(dir, { withFileTypes: true })
28
+ } catch {
29
+ return
30
+ }
31
+ entries.sort((a, b) => a.name.localeCompare(b.name))
32
+ for (const entry of entries) {
33
+ if (files.length >= maxFiles) {
34
+ // Stop scanning and say so, instead of silently dropping the rest.
35
+ truncated = true
36
+ return
37
+ }
38
+ const full = path.join(dir, entry.name)
39
+ if (entry.isDirectory()) {
40
+ if (SKIP_DIRS.has(entry.name)) continue
41
+ await walk(full)
42
+ continue
43
+ }
44
+ if (!entry.isFile()) continue
45
+ const relative = path.relative(root, full).split(path.sep).join('/')
46
+ // Credential-bearing files are refused by name before any content scan.
47
+ if (isDeniedFile(relative)) {
48
+ denied.push(relative)
49
+ continue
50
+ }
51
+ const stat = await fs.stat(full).catch(() => null)
52
+ if (!stat) continue
53
+ if (stat.size > maxFileBytes) {
54
+ skipped += 1
55
+ continue
56
+ }
57
+ if (total + stat.size > budget) {
58
+ skipped += 1
59
+ continue
60
+ }
61
+ const content = await fs.readFile(full)
62
+ total += content.length
63
+ files.push({
64
+ path: relative,
65
+ content,
66
+ // Preserve the executable bit so bin/*.sh survive the round trip.
67
+ mode: stat.mode & 0o111 ? '100755' : '100644',
68
+ })
69
+ }
70
+ }
71
+ await walk(root)
72
+ return { files, total, skipped, denied, truncated }
73
+ }
package/lib/pure.mjs ADDED
@@ -0,0 +1,196 @@
1
+ /**
2
+ * Pure helpers shared by the host half and the tests.
3
+ *
4
+ * Nothing here touches cordis, credentials or the network, so `node --test` can
5
+ * exercise it directly: the audit flagged that every rule lived inside one
6
+ * 4700-line file where no test could reach it.
7
+ */
8
+ import zlib from 'node:zlib'
9
+
10
+ // Files that must never be published by default, matched by name so the check
11
+ // does not depend on the file's content format.
12
+ export const DENY_FILE_PATTERNS = [
13
+ /^\.env(\..+)?$/i,
14
+ /^\.npmrc$/i,
15
+ /^\.netrc$/i,
16
+ /^\.aws$/i,
17
+ /\.(pem|key|p12|pfx|jks|keystore|ppk)$/i,
18
+ /^id_(rsa|dsa|ecdsa|ed25519)(\.pub)?$/i,
19
+ /^credentials(\.json)?$/i,
20
+ /^\.?secrets?(\..+)?$/i,
21
+ ]
22
+
23
+ export function isDeniedFile(filePath) {
24
+ const name = String(filePath).split('/').pop()
25
+ return DENY_FILE_PATTERNS.some((pattern) => pattern.test(name) || pattern.test(filePath))
26
+ }
27
+
28
+ /**
29
+ * Files this plugin writes straight to the repository (the npm workflow, the
30
+ * market index) are never in the local directory, so a delete-sync pass must
31
+ * leave them alone — and a user's own workflows are not ours to remove either.
32
+ */
33
+ export function isProtectedRemotePath(filePath) {
34
+ const text = String(filePath)
35
+ return text.startsWith('.github/workflows/') || text === '.github/dependabot.yml'
36
+ }
37
+
38
+ /** Which capability a write to this path needs; coarse but conservative. */
39
+ export function capabilityFor(pathname, method) {
40
+ if (method === 'GET' || method === 'HEAD') return ''
41
+ if (/\/actions\/workflows\/[^/]+\/dispatches|\/actions\/runs\/[^/]+\/rerun/.test(pathname)) return 'workflowsWrite'
42
+ if (/\/actions\//.test(pathname)) return 'actionsWrite'
43
+ if (/\/issues(\/|$)/.test(pathname)) return 'issueWrite'
44
+ if (/\/pulls(\/|$)/.test(pathname)) return 'pullWrite'
45
+ if (/\/topics/.test(pathname)) return 'adminWrite'
46
+ return 'repoWrite'
47
+ }
48
+
49
+ export function marketIndexDocument({
50
+ pkg,
51
+ owner,
52
+ repo,
53
+ commit,
54
+ entryTitle,
55
+ entryDescription,
56
+ iconPath,
57
+ previous,
58
+ entries,
59
+ now = Date.now(),
60
+ }) {
61
+ const repositoryUrl = `https://github.com/${owner}/${repo}`
62
+ const relativeIcon = iconPath ? `../${String(iconPath).replace(/^\.\//, '')}` : '../icon.svg'
63
+ const engines =
64
+ pkg.engines && typeof pkg.engines.dsh === 'string' && pkg.engines.dsh.trim() && !pkg.engines.dsh.startsWith('workspace:')
65
+ ? { dsh: pkg.engines.dsh.trim() }
66
+ : {}
67
+ // Keep the timestamp stable for a version that is already indexed, so a
68
+ // re-generated index does not look like a new release.
69
+ const previousVersion =
70
+ previous && Array.isArray(previous.plugins) ? previous.plugins.find((item) => item && item.name === pkg.name) : undefined
71
+ const previousTimestamp =
72
+ previousVersion && Array.isArray(previousVersion.versions)
73
+ ? (previousVersion.versions.find((item) => item && item.version === pkg.version) || {}).publishTimestamp
74
+ : undefined
75
+ const plugin = {
76
+ name: pkg.name,
77
+ title: entryTitle || pkg.name,
78
+ description: entryDescription || pkg.description || pkg.name,
79
+ icon: relativeIcon,
80
+ author: owner,
81
+ repository: { url: repositoryUrl },
82
+ metadata: {
83
+ keywords: Array.isArray(pkg.keywords) ? pkg.keywords.filter((item) => typeof item === 'string').slice(0, 20) : [],
84
+ },
85
+ versions: [
86
+ {
87
+ version: pkg.version,
88
+ publishTimestamp: Number.isInteger(previousTimestamp) ? previousTimestamp : Math.floor(now / 1000),
89
+ source: { type: 'git', url: repositoryUrl, commit },
90
+ engines,
91
+ },
92
+ ],
93
+ }
94
+ if (pkg.homepage && /^https?:\/\//.test(pkg.homepage)) plugin.homepage = pkg.homepage
95
+ // Optional extra entries let one repository index several installable plugins.
96
+ const extra = Array.isArray(entries)
97
+ ? entries
98
+ .filter((item) => item && typeof item.name === 'string' && item.name)
99
+ .map((item) => ({
100
+ name: item.name,
101
+ title: item.title || item.name,
102
+ description: item.description || item.name,
103
+ icon: item.icon ? `../${String(item.icon).replace(/^\.\//, '')}` : relativeIcon,
104
+ author: owner,
105
+ repository: { url: repositoryUrl },
106
+ metadata: { keywords: [] },
107
+ versions: [
108
+ {
109
+ version: item.version || pkg.version,
110
+ publishTimestamp: Number.isInteger(item.publishTimestamp) ? item.publishTimestamp : Math.floor(now / 1000),
111
+ source: {
112
+ type: 'git',
113
+ url: repositoryUrl,
114
+ commit: item.commit || commit,
115
+ ...(item.path ? { path: item.path } : {}),
116
+ },
117
+ engines,
118
+ },
119
+ ],
120
+ }))
121
+ : []
122
+ return {
123
+ format: 1,
124
+ title: `${owner} DSH plugin index`,
125
+ description: 'Self-hosted DSH plugin index generated by the GitHub console.',
126
+ metadata: {},
127
+ plugins: [plugin, ...extra],
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Minimal deflate-only ZIP reader for GitHub's log archives. Sizes come from the
133
+ * central directory because the entries use data descriptors.
134
+ */
135
+ export function unzipEntries(buffer) {
136
+ const entries = []
137
+ let eocd = -1
138
+ for (let i = buffer.length - 22; i >= Math.max(0, buffer.length - 70000); i--) {
139
+ if (buffer.readUInt32LE(i) === 0x06054b50) {
140
+ eocd = i
141
+ break
142
+ }
143
+ }
144
+ const read = (offset) => {
145
+ const method = buffer.readUInt16LE(offset + 10)
146
+ const compressed = buffer.readUInt32LE(offset + 20)
147
+ const nameLength = buffer.readUInt16LE(offset + 28)
148
+ const name = buffer.subarray(offset + 46, offset + 46 + nameLength).toString('utf8')
149
+ const localOffset = buffer.readUInt32LE(offset + 42)
150
+ const localNameLength = buffer.readUInt16LE(localOffset + 26)
151
+ const localExtraLength = buffer.readUInt16LE(localOffset + 28)
152
+ const dataStart = localOffset + 30 + localNameLength + localExtraLength
153
+ const data = buffer.subarray(dataStart, dataStart + compressed)
154
+ let text = ''
155
+ try {
156
+ text = method === 0 ? data.toString('utf8') : zlib.inflateRawSync(data).toString('utf8')
157
+ } catch {
158
+ text = ''
159
+ }
160
+ entries.push({ name, text })
161
+ }
162
+ if (eocd >= 0) {
163
+ const count = buffer.readUInt16LE(eocd + 10)
164
+ let offset = buffer.readUInt32LE(eocd + 16)
165
+ for (let index = 0; index < count; index++) {
166
+ if (buffer.readUInt32LE(offset) !== 0x02014b50) break
167
+ const nameLength = buffer.readUInt16LE(offset + 28)
168
+ const extraLength = buffer.readUInt16LE(offset + 30)
169
+ const commentLength = buffer.readUInt16LE(offset + 32)
170
+ read(offset)
171
+ offset += 46 + nameLength + extraLength + commentLength
172
+ }
173
+ if (entries.length) return entries
174
+ }
175
+ // Fallback: walk local headers (works when sizes are present).
176
+ let offset = 0
177
+ while (offset + 30 <= buffer.length) {
178
+ if (buffer.readUInt32LE(offset) !== 0x04034b50) break
179
+ const method = buffer.readUInt16LE(offset + 8)
180
+ const compressed = buffer.readUInt32LE(offset + 18)
181
+ const nameLength = buffer.readUInt16LE(offset + 26)
182
+ const extraLength = buffer.readUInt16LE(offset + 28)
183
+ const name = buffer.subarray(offset + 30, offset + 30 + nameLength).toString('utf8')
184
+ const dataStart = offset + 30 + nameLength + extraLength
185
+ const data = buffer.subarray(dataStart, dataStart + compressed)
186
+ let text = ''
187
+ try {
188
+ text = method === 0 ? data.toString('utf8') : zlib.inflateRawSync(data).toString('utf8')
189
+ } catch {
190
+ text = ''
191
+ }
192
+ entries.push({ name, text })
193
+ offset = dataStart + compressed
194
+ }
195
+ return entries
196
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-github-console",
3
- "version": "0.6.1",
3
+ "version": "0.6.2",
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,8 @@
24
24
  "./locale/*.json": "./locale/*.json",
25
25
  "./icon": "./icon.svg"
26
26
  },
27
- "files": ["scripts", ".github",
27
+ "scripts": { "test": "node --test test/" },
28
+ "files": ["lib", "test", "scripts", ".github",
28
29
  "index.js",
29
30
  "client.js",
30
31
  "cordis.patch.yml",
@@ -0,0 +1,61 @@
1
+ import assert from 'node:assert/strict'
2
+ import fs from 'node:fs/promises'
3
+ import os from 'node:os'
4
+ import path from 'node:path'
5
+ import test from 'node:test'
6
+ import { collectFiles } from '../lib/collect.mjs'
7
+
8
+ async function fixture(files) {
9
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'dgc-fixture-'))
10
+ for (const [relative, content] of Object.entries(files)) {
11
+ const full = path.join(dir, relative)
12
+ await fs.mkdir(path.dirname(full), { recursive: true })
13
+ await fs.writeFile(full, content)
14
+ }
15
+ return dir
16
+ }
17
+
18
+ test('collectFiles refuses credential files and keeps the rest', async () => {
19
+ const dir = await fixture({
20
+ 'package.json': '{"name":"x"}',
21
+ 'index.js': 'export {}',
22
+ '.env': 'TOKEN=1',
23
+ '.npmrc': '//registry',
24
+ 'nested/server.pem': 'PEM',
25
+ 'node_modules/dep/index.js': 'ignored',
26
+ })
27
+ const collected = await collectFiles(dir, 4 * 1024 * 1024)
28
+ const paths = collected.files.map((file) => file.path).sort()
29
+ assert.deepEqual(paths, ['index.js', 'package.json'])
30
+ assert.deepEqual(collected.denied.sort(), ['.env', '.npmrc', 'nested/server.pem'])
31
+ await fs.rm(dir, { recursive: true, force: true })
32
+ })
33
+
34
+ test('collectFiles marks truncation instead of dropping files silently', async () => {
35
+ const files = {}
36
+ for (let i = 0; i < 8; i++) files[`f${i}.js`] = 'x'
37
+ const dir = await fixture(files)
38
+ const collected = await collectFiles(dir, 4 * 1024 * 1024, { maxFiles: 3 })
39
+ assert.equal(collected.files.length, 3)
40
+ assert.equal(collected.truncated, true)
41
+ await fs.rm(dir, { recursive: true, force: true })
42
+ })
43
+
44
+ test('collectFiles counts oversized files as skipped', async () => {
45
+ const dir = await fixture({ 'big.bin': 'x'.repeat(2048), 'small.js': 'ok' })
46
+ const collected = await collectFiles(dir, 4 * 1024 * 1024, { maxFileBytes: 1024 })
47
+ assert.deepEqual(collected.files.map((file) => file.path), ['small.js'])
48
+ assert.equal(collected.skipped, 1)
49
+ await fs.rm(dir, { recursive: true, force: true })
50
+ })
51
+
52
+ test('collectFiles keeps the executable bit', { skip: process.platform === 'win32' ? 'chmod is a no-op on Windows' : false }, async () => {
53
+ const dir = await fixture({ 'bin/run.sh': '#!/bin/sh\necho hi\n', 'index.js': 'export {}' })
54
+ await fs.chmod(path.join(dir, 'bin/run.sh'), 0o755)
55
+ const collected = await collectFiles(dir, 4 * 1024 * 1024)
56
+ const script = collected.files.find((file) => file.path === 'bin/run.sh')
57
+ const entry = collected.files.find((file) => file.path === 'index.js')
58
+ assert.equal(script.mode, '100755')
59
+ assert.equal(entry.mode, '100644')
60
+ await fs.rm(dir, { recursive: true, force: true })
61
+ })
@@ -0,0 +1,137 @@
1
+ import assert from 'node:assert/strict'
2
+ import test from 'node:test'
3
+ import zlib from 'node:zlib'
4
+ import { capabilityFor, isDeniedFile, isProtectedRemotePath, marketIndexDocument, unzipEntries } from '../lib/pure.mjs'
5
+
6
+ test('isDeniedFile refuses credential-bearing names', () => {
7
+ for (const name of ['.env', '.env.local', 'server/.env', '.npmrc', '.netrc', 'deploy.key', 'a.pem', 'credentials.json', 'id_rsa', 'secrets.yaml']) {
8
+ assert.equal(isDeniedFile(name), true, `${name} should be denied`)
9
+ }
10
+ for (const name of ['index.js', 'README.md', 'package.json', 'assets/icon-512.png', 'env.sample']) {
11
+ assert.equal(isDeniedFile(name), false, `${name} should be allowed`)
12
+ }
13
+ })
14
+
15
+ test('isProtectedRemotePath keeps workflows out of the delete sync', () => {
16
+ assert.equal(isProtectedRemotePath('.github/workflows/publish.yml'), true)
17
+ assert.equal(isProtectedRemotePath('.github/workflows/ci.yml'), true)
18
+ assert.equal(isProtectedRemotePath('.github/dependabot.yml'), true)
19
+ assert.equal(isProtectedRemotePath('src/index.js'), false)
20
+ assert.equal(isProtectedRemotePath('.github/ISSUE_TEMPLATE.md'), false)
21
+ })
22
+
23
+ test('capabilityFor maps writes to the narrowest permission', () => {
24
+ assert.equal(capabilityFor('/repos/o/r/issues', 'POST'), 'issueWrite')
25
+ assert.equal(capabilityFor('/repos/o/r/issues/3/comments', 'POST'), 'issueWrite')
26
+ assert.equal(capabilityFor('/repos/o/r/pulls/3/reviews', 'POST'), 'pullWrite')
27
+ assert.equal(capabilityFor('/repos/o/r/actions/workflows/publish.yml/dispatches', 'POST'), 'workflowsWrite')
28
+ assert.equal(capabilityFor('/repos/o/r/actions/runs/1/rerun', 'POST'), 'workflowsWrite')
29
+ assert.equal(capabilityFor('/repos/o/r/actions/runs/1/logs', 'GET'), '')
30
+ assert.equal(capabilityFor('/repos/o/r/topics', 'PUT'), 'adminWrite')
31
+ assert.equal(capabilityFor('/repos/o/r/contents/a.js', 'PUT'), 'repoWrite')
32
+ })
33
+
34
+ test('marketIndexDocument keeps one entry and honours entries[]', () => {
35
+ const pkg = { name: 'x', version: '1.2.3', description: 'demo', keywords: ['a', 2, 'b'], engines: { dsh: '>=0.2.1' } }
36
+ const single = marketIndexDocument({ pkg, owner: 'me', repo: 'r', commit: 'abc', iconPath: 'assets/icon-512.png', now: 1_700_000_000_000 })
37
+ assert.equal(single.format, 1)
38
+ assert.equal(single.plugins.length, 1)
39
+ assert.equal(single.plugins[0].icon, '../assets/icon-512.png')
40
+ assert.deepEqual(single.plugins[0].metadata.keywords, ['a', 'b'])
41
+ assert.equal(single.plugins[0].versions[0].publishTimestamp, 1_700_000_000)
42
+ assert.deepEqual(single.plugins[0].versions[0].engines, { dsh: '>=0.2.1' })
43
+
44
+ const multi = marketIndexDocument({
45
+ pkg,
46
+ owner: 'me',
47
+ repo: 'r',
48
+ commit: 'abc',
49
+ iconPath: '',
50
+ entries: [{ name: 'y', title: 'Y', version: '0.1.0', path: 'plugins/y' }],
51
+ })
52
+ assert.equal(multi.plugins.length, 2)
53
+ assert.equal(multi.plugins[1].name, 'y')
54
+ assert.equal(multi.plugins[1].versions[0].source.path, 'plugins/y')
55
+ assert.equal(multi.plugins[0].icon, '../icon.svg')
56
+ })
57
+
58
+ test('marketIndexDocument reuses the timestamp of an already indexed version', () => {
59
+ const pkg = { name: 'x', version: '1.2.3' }
60
+ const previous = { plugins: [{ name: 'x', versions: [{ version: '1.2.3', publishTimestamp: 1234 }] }] }
61
+ const doc = marketIndexDocument({ pkg, owner: 'me', repo: 'r', commit: 'abc', previous, now: 1_700_000_000_000 })
62
+ assert.equal(doc.plugins[0].versions[0].publishTimestamp, 1234)
63
+ })
64
+
65
+ /** Build a minimal ZIP: optional data descriptors (sizes 0 in the local header). */
66
+ function buildZip(entries, { dataDescriptor = false } = {}) {
67
+ const chunks = []
68
+ const central = []
69
+ let offset = 0
70
+ for (const entry of entries) {
71
+ const name = Buffer.from(entry.name, 'utf8')
72
+ const raw = Buffer.from(entry.text, 'utf8')
73
+ const method = entry.method === 0 ? 0 : 8
74
+ const data = method === 0 ? raw : zlib.deflateRawSync(raw)
75
+ const local = Buffer.alloc(30)
76
+ local.writeUInt32LE(0x04034b50, 0)
77
+ local.writeUInt16LE(20, 4)
78
+ local.writeUInt16LE(dataDescriptor ? 0x08 : 0, 6)
79
+ local.writeUInt16LE(method, 8)
80
+ // Sizes stay zero when a data descriptor follows, exactly like GitHub's logs.
81
+ local.writeUInt32LE(dataDescriptor ? 0 : data.length, 18)
82
+ local.writeUInt32LE(dataDescriptor ? 0 : raw.length, 22)
83
+ local.writeUInt16LE(name.length, 26)
84
+ local.writeUInt16LE(0, 28)
85
+ const parts = [local, name, data]
86
+ if (dataDescriptor) {
87
+ const descriptor = Buffer.alloc(16)
88
+ descriptor.writeUInt32LE(0x08074b50, 0)
89
+ descriptor.writeUInt32LE(data.length, 8)
90
+ descriptor.writeUInt32LE(raw.length, 12)
91
+ parts.push(descriptor)
92
+ }
93
+ const size = parts.reduce((sum, part) => sum + part.length, 0)
94
+ const header = Buffer.alloc(46)
95
+ header.writeUInt32LE(0x02014b50, 0)
96
+ header.writeUInt16LE(20, 4)
97
+ header.writeUInt16LE(20, 6)
98
+ header.writeUInt16LE(dataDescriptor ? 0x08 : 0, 8)
99
+ header.writeUInt16LE(method, 10)
100
+ header.writeUInt32LE(data.length, 20)
101
+ header.writeUInt32LE(raw.length, 24)
102
+ header.writeUInt16LE(name.length, 28)
103
+ header.writeUInt32LE(offset, 42)
104
+ central.push(Buffer.concat([header, name]))
105
+ chunks.push(...parts)
106
+ offset += size
107
+ }
108
+ const centralBuffer = Buffer.concat(central)
109
+ const body = Buffer.concat(chunks)
110
+ const eocd = Buffer.alloc(22)
111
+ eocd.writeUInt32LE(0x06054b50, 0)
112
+ eocd.writeUInt16LE(entries.length, 8)
113
+ eocd.writeUInt16LE(entries.length, 10)
114
+ eocd.writeUInt32LE(centralBuffer.length, 12)
115
+ eocd.writeUInt32LE(body.length, 16)
116
+ return Buffer.concat([body, centralBuffer, eocd])
117
+ }
118
+
119
+ test('unzipEntries reads stored and deflated entries', () => {
120
+ const zip = buildZip([
121
+ { name: '0_publish.txt', text: 'hello log', method: 0 },
122
+ { name: '1_test.txt', text: 'deflated body '.repeat(50), method: 8 },
123
+ ])
124
+ const entries = unzipEntries(zip)
125
+ assert.equal(entries.length, 2)
126
+ assert.equal(entries[0].text, 'hello log')
127
+ assert.equal(entries[1].text, 'deflated body '.repeat(50))
128
+ })
129
+
130
+ test('unzipEntries survives data descriptors with zero lengths in the local header', () => {
131
+ // Regression: GitHub's log archives do this, and reading sizes from the local
132
+ // header returned empty text for every entry.
133
+ const zip = buildZip([{ name: '0_publish.txt', text: 'npm error 409 conflict', method: 8 }], { dataDescriptor: true })
134
+ const entries = unzipEntries(zip)
135
+ assert.equal(entries.length, 1)
136
+ assert.equal(entries[0].text, 'npm error 409 conflict')
137
+ })