dsh-github-console 0.5.0 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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/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.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": [
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,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')
@@ -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
+ })