dsh-vigil 0.0.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.
Files changed (56) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +188 -0
  3. package/client.js +4652 -0
  4. package/cordis.patch.yml +7 -0
  5. package/docs/DETAIL.md +66 -0
  6. package/icon.png +0 -0
  7. package/illustrations/notice.png +0 -0
  8. package/illustrations/warning.png +0 -0
  9. package/locale/en.json +7 -0
  10. package/locale/zh.json +7 -0
  11. package/package.json +75 -0
  12. package/rules/audit.yaml +130 -0
  13. package/rules/manifest.json +7 -0
  14. package/rules/sentinel.yaml +289 -0
  15. package/src/alert-route.js +194 -0
  16. package/src/approval.js +398 -0
  17. package/src/artwork-route.js +87 -0
  18. package/src/audit/ast.js +213 -0
  19. package/src/audit/install-scan.js +127 -0
  20. package/src/audit/lexer.js +307 -0
  21. package/src/audit/narrative.js +320 -0
  22. package/src/audit/rules.js +1440 -0
  23. package/src/audit/scan.js +880 -0
  24. package/src/audit-clear-route.js +89 -0
  25. package/src/audit-feed.js +265 -0
  26. package/src/audit-log.js +887 -0
  27. package/src/config-schema.js +194 -0
  28. package/src/config.js +580 -0
  29. package/src/delete/command-kinds.js +46 -0
  30. package/src/delete/lex.js +46 -0
  31. package/src/delete/parser-posix.js +1427 -0
  32. package/src/delete/parser-pwsh.js +1729 -0
  33. package/src/delete/parser.js +2082 -0
  34. package/src/delete/policy.js +680 -0
  35. package/src/delete/quarantine.js +417 -0
  36. package/src/index.js +1134 -0
  37. package/src/install-scan-route.js +58 -0
  38. package/src/install-watch.js +389 -0
  39. package/src/integrity.js +509 -0
  40. package/src/live-config.js +88 -0
  41. package/src/quarantine-route.js +74 -0
  42. package/src/quarantine-view.js +44 -0
  43. package/src/rules/pack.js +423 -0
  44. package/src/rules/update.js +341 -0
  45. package/src/rules/yaml.js +186 -0
  46. package/src/sage-action-route.js +63 -0
  47. package/src/sage-provision.js +716 -0
  48. package/src/sentinel/guard.js +392 -0
  49. package/src/sentinel/hook.js +546 -0
  50. package/src/sentinel/rules.js +488 -0
  51. package/src/sentinel/sage-load.js +79 -0
  52. package/src/sentinel/sage.js +550 -0
  53. package/src/tools.js +727 -0
  54. package/src/update-check.js +339 -0
  55. package/src/util.js +400 -0
  56. package/threats/README.md +25 -0
@@ -0,0 +1,339 @@
1
+ /**
2
+ * Self-update check and update request for the installed plugin.
3
+ *
4
+ * GET /api/dsh-vigil/update-check read-only check
5
+ * POST /api/dsh-vigil/update-check { action: 'update' }
6
+ *
7
+ * The check reports the running version, the repository the bundle came from,
8
+ * the newest stable `vX.Y.Z` tag and its commit, and whether DSH lists this
9
+ * bundle with `update: 'git'` — the only shape in which the plugin manager can
10
+ * replace it without changing the install kind.
11
+ *
12
+ * The update request stays inside DSH: it calls `ctx.pluginManager.updateBundle`
13
+ * with a spec pinned to the full commit, so the plugin manager performs the
14
+ * remove/install pair and its failure rollback. A profile-installed Git bundle
15
+ * is packed without `.git`, so its saved `source` is authoritative; the
16
+ * checkout's `origin` is only a fallback for development `link:` installs.
17
+ *
18
+ * @module dsh-vigil/update-check
19
+ */
20
+
21
+ import { execFile } from 'node:child_process'
22
+ import { promisify } from 'node:util'
23
+
24
+ const execFileAsync = promisify(execFile)
25
+
26
+ /** Authenticated browser fetch path for the update check. */
27
+ export const UPDATE_CHECK_PATH = '/api/dsh-vigil/update-check'
28
+
29
+ /** Git tag forms this check understands: `v1.2.3` and `1.2.3`, stable only. */
30
+ const SEMVER_TAG = /^v?(\d+)\.(\d+)\.(\d+)$/
31
+
32
+ /** Bound on one git command; `ls-remote` asks the network. */
33
+ const GIT_TIMEOUT_MS = 12000
34
+
35
+ /**
36
+ * Parse a stable `vX.Y.Z` tag.
37
+ * @param {string} tag
38
+ * @returns {{ version: string, major: number, minor: number, patch: number } | null}
39
+ */
40
+ export function parseSemverTag(tag) {
41
+ if (typeof tag !== 'string') return null
42
+ const match = SEMVER_TAG.exec(tag.trim())
43
+ if (!match) return null
44
+ return {
45
+ version: `${Number(match[1])}.${Number(match[2])}.${Number(match[3])}`,
46
+ major: Number(match[1]),
47
+ minor: Number(match[2]),
48
+ patch: Number(match[3]),
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Compare two stable `X.Y.Z` versions.
54
+ * @param {string} left
55
+ * @param {string} right
56
+ * @returns {number} positive when `left` is newer
57
+ */
58
+ export function compareVersions(left, right) {
59
+ const a = parseSemverTag(left)
60
+ const b = parseSemverTag(right)
61
+ if (!a || !b) return 0
62
+ if (a.major !== b.major) return a.major - b.major
63
+ if (a.minor !== b.minor) return a.minor - b.minor
64
+ return a.patch - b.patch
65
+ }
66
+
67
+ /**
68
+ * Turn a checkout's `origin` URL into the base of a pnpm Git spec. Credentials
69
+ * in an https userinfo section are dropped; scp-like SSH addresses become
70
+ * `git+ssh` URLs.
71
+ * @param {string} remote
72
+ * @returns {{ display: string, specBase: string } | null}
73
+ */
74
+ export function normalizeGitRemote(remote) {
75
+ if (typeof remote !== 'string') return null
76
+ const value = remote.trim()
77
+ if (value === '') return null
78
+ const sshScp = /^(?:[^@/\s]+@)([^:/\s]+):(.+)$/.exec(value)
79
+ if (sshScp) {
80
+ const host = sshScp[1]
81
+ const path = sshScp[2].replace(/^\/+/, '')
82
+ return { display: `${host}/${path}`, specBase: `git+ssh://git@${host}/${path}` }
83
+ }
84
+ let parsed
85
+ try {
86
+ parsed = new URL(value)
87
+ } catch {
88
+ return null
89
+ }
90
+ if (!parsed.host) return null
91
+ const path = parsed.pathname.replace(/^\/+/, '')
92
+ if (path === '') return null
93
+ const display = `${parsed.host}/${path}`
94
+ if (parsed.protocol === 'https:' || parsed.protocol === 'http:') {
95
+ return { display, specBase: `git+https://${parsed.host}/${path}` }
96
+ }
97
+ if (parsed.protocol === 'ssh:') {
98
+ const user = parsed.username === '' ? '' : `${parsed.username}@`
99
+ return { display, specBase: `git+ssh://${user}${parsed.host}/${path}` }
100
+ }
101
+ if (parsed.protocol === 'git:') {
102
+ return { display, specBase: `git+git://${parsed.host}/${path}` }
103
+ }
104
+ return null
105
+ }
106
+
107
+ /**
108
+ * Turn an installed bundle's `source` spec (what pnpm saved in the profile)
109
+ * into the same normalized remote. A pnpm Git checkout need not keep `.git`,
110
+ * so this is the primary source of the repository.
111
+ * @param {string} source
112
+ * @returns {{ display: string, specBase: string } | null}
113
+ */
114
+ export function parseBundleSource(source) {
115
+ if (typeof source !== 'string') return null
116
+ const value = source.trim().split('#')[0]
117
+ if (value === '' || /^(?:link|file|workspace|npm):/i.test(value)) return null
118
+ const hosted = /^(github|gitlab|bitbucket|gist):(.+)$/i.exec(value)
119
+ if (hosted) {
120
+ const host = { github: 'github.com', gitlab: 'gitlab.com', bitbucket: 'bitbucket.org', gist: 'gist.github.com' }[hosted[1].toLowerCase()]
121
+ const path = hosted[2].replace(/^\/+/, '').replace(/\.git$/i, '')
122
+ const repo = `${host}/${path}`
123
+ return { display: repo, specBase: `git+https://${repo}.git` }
124
+ }
125
+ const withoutPrefix = value.replace(/^git\+/i, '')
126
+ return normalizeGitRemote(withoutPrefix)
127
+ }
128
+
129
+ /**
130
+ * Parse `git ls-remote --tags` output into tag -> commit. An annotated tag
131
+ * prints both the tag object and a peeled `^{}` line; the peeled commit is the
132
+ * one an install must pin.
133
+ * @param {string} stdout
134
+ * @returns {Map<string, string>}
135
+ */
136
+ export function parseTagRefs(stdout) {
137
+ const tags = new Map()
138
+ if (typeof stdout !== 'string') return tags
139
+ for (const line of stdout.split('\n')) {
140
+ const match = /^([0-9a-f]{40})\trefs\/tags\/(.+)$/.exec(line.trim())
141
+ if (!match) continue
142
+ const sha = match[1]
143
+ const name = match[2]
144
+ if (name.endsWith('^{}')) {
145
+ tags.set(name.slice(0, -3), sha)
146
+ } else if (!tags.has(name)) {
147
+ tags.set(name, sha)
148
+ }
149
+ }
150
+ return tags
151
+ }
152
+
153
+ /**
154
+ * Pick the newest stable tag newer than the running version.
155
+ * @param {string} stdout `git ls-remote` output
156
+ * @param {string} currentVersion
157
+ * @returns {{ version: string, sha: string, tag: string } | null}
158
+ */
159
+ export function pickLatestTag(stdout, currentVersion) {
160
+ const tags = parseTagRefs(stdout)
161
+ let best = null
162
+ for (const [tag, sha] of tags) {
163
+ const parsed = parseSemverTag(tag)
164
+ if (!parsed) continue
165
+ if (compareVersions(parsed.version, currentVersion) <= 0) continue
166
+ if (!best || compareVersions(parsed.version, best.version) > 0) {
167
+ best = { version: parsed.version, sha, tag }
168
+ }
169
+ }
170
+ return best
171
+ }
172
+
173
+ /**
174
+ * One git invocation; resolves stdout or throws.
175
+ * @param {string[]} args
176
+ * @returns {Promise<string>}
177
+ */
178
+ async function git(args) {
179
+ const result = await execFileAsync('git', args, {
180
+ timeout: GIT_TIMEOUT_MS,
181
+ windowsHide: true,
182
+ maxBuffer: 1024 * 1024,
183
+ })
184
+ return String(result.stdout ?? '')
185
+ }
186
+
187
+ /**
188
+ * Read the update state without changing anything.
189
+ * @param {{
190
+ * pluginDir: string,
191
+ * currentVersion: string,
192
+ * getPluginManager?: () => any,
193
+ * logger?: { warn?: (message: string) => void },
194
+ * }} deps
195
+ * @returns {Promise<{
196
+ * ok: boolean, currentVersion: string, updateKind: string|null, canUpdate: boolean,
197
+ * reason: string|null, remote: string|null, latestVersion: string|null, spec: string|null, error?: string,
198
+ * }>}
199
+ */
200
+ export async function inspectUpdate(deps) {
201
+ /** @type {{ ok: boolean, currentVersion: string, updateKind: string|null, canUpdate: boolean, reason: string|null, remote: string|null, latestVersion: string|null, spec: string|null, error?: string }} */
202
+ const payload = {
203
+ ok: true,
204
+ currentVersion: deps.currentVersion,
205
+ updateKind: null,
206
+ canUpdate: false,
207
+ reason: null,
208
+ remote: null,
209
+ latestVersion: null,
210
+ spec: null,
211
+ }
212
+ try {
213
+ let updateKind = null
214
+ /** @type {{ display: string, specBase: string } | null} */
215
+ let sourceRemote = null
216
+ let sourceSpec = ''
217
+ try {
218
+ const manager = deps.getPluginManager?.()
219
+ if (manager && typeof manager.listBundles === 'function') {
220
+ const bundles = await manager.listBundles()
221
+ const self = Array.isArray(bundles) ? bundles.find(bundle => bundle?.name === 'dsh-vigil') : null
222
+ updateKind = typeof self?.update === 'string' ? self.update : null
223
+ sourceSpec = typeof self?.source === 'string' ? self.source : ''
224
+ sourceRemote = parseBundleSource(sourceSpec)
225
+ }
226
+ } catch (error) {
227
+ deps.logger?.warn?.(`[dsh-vigil] 更新检查读取插件信息失败:${String(error)}`)
228
+ }
229
+ payload.updateKind = updateKind
230
+
231
+ let remote = sourceRemote
232
+ if (!remote) {
233
+ let remoteRaw = ''
234
+ try {
235
+ remoteRaw = (await git(['-C', deps.pluginDir, 'remote', 'get-url', 'origin'])).trim()
236
+ } catch {
237
+ payload.reason = 'no-remote'
238
+ }
239
+ remote = remoteRaw === '' ? null : normalizeGitRemote(remoteRaw)
240
+ }
241
+ if (remote) payload.remote = remote.display
242
+ else if (payload.reason === null) payload.reason = 'unusable-remote'
243
+
244
+ if (remote) {
245
+ try {
246
+ const stdout = await git(['ls-remote', '--tags', remote.specBase.replace(/^git\+/, '')])
247
+ const latest = pickLatestTag(stdout, deps.currentVersion)
248
+ if (latest) {
249
+ payload.latestVersion = latest.version
250
+ payload.spec = `${remote.specBase}#${latest.sha}`
251
+ }
252
+ } catch (error) {
253
+ payload.reason = 'network'
254
+ deps.logger?.warn?.(`[dsh-vigil] 更新检查读取标签失败:${String(error)}`)
255
+ }
256
+ }
257
+
258
+ if (payload.reason === null) {
259
+ if (payload.latestVersion === null) payload.reason = 'no-newer-tag'
260
+ else if (updateKind === 'git') payload.canUpdate = true
261
+ else if (updateKind === 'registry') payload.reason = 'registry'
262
+ else if (sourceRemote) {
263
+ // A Git source without a full commit pin cannot be replaced by
264
+ // updateBundle; distinguish it from a local link install.
265
+ payload.reason = /#[0-9a-f]{40}$/i.test(sourceSpec) ? 'local-install' : 'git-unpinned'
266
+ } else payload.reason = 'local-install'
267
+ }
268
+ } catch (error) {
269
+ payload.ok = false
270
+ payload.reason = 'error'
271
+ payload.error = error instanceof Error ? error.message : String(error)
272
+ }
273
+ return payload
274
+ }
275
+
276
+ /**
277
+ * @param {{
278
+ * pluginDir: string,
279
+ * currentVersion: string,
280
+ * getPluginManager?: () => any,
281
+ * logger?: { warn?: (message: string) => void },
282
+ * }} deps
283
+ * @returns {{ path: string, methods: string[], requestBody: 'buffered', fetch: (request: Request) => Promise<Response> }}
284
+ */
285
+ export function createUpdateCheckRoute(deps) {
286
+ const json = (payload, status = 200) => new Response(`${JSON.stringify(payload)}\n`, {
287
+ status,
288
+ headers: {
289
+ 'content-type': 'application/json; charset=utf-8',
290
+ 'cache-control': 'no-store',
291
+ 'x-content-type-options': 'nosniff',
292
+ },
293
+ })
294
+
295
+ return {
296
+ path: UPDATE_CHECK_PATH,
297
+ methods: ['GET', 'POST'],
298
+ requestBody: 'buffered',
299
+ fetch: async request => {
300
+ const method = typeof request?.method === 'string' ? request.method.toUpperCase() : 'GET'
301
+ if (method !== 'POST') return json(await inspectUpdate(deps))
302
+
303
+ let body
304
+ try {
305
+ body = typeof request.json === 'function' ? await request.json().catch(() => null) : null
306
+ } catch {
307
+ body = null
308
+ }
309
+ if (body?.action !== 'update') return json({ ok: false, error: '未知操作' }, 400)
310
+
311
+ const state = await inspectUpdate(deps)
312
+ if (!state.ok) return json({ ok: false, error: state.error ?? '检查失败' }, 500)
313
+ if (!state.canUpdate) {
314
+ const error = state.reason === 'local-install'
315
+ ? '当前是本地 link 安装,DSH 无法自动更新;请从 GitHub 固定提交安装后再更新'
316
+ : state.reason === 'no-remote'
317
+ ? '尚未配置 GitHub 远程仓库'
318
+ : state.reason === 'no-newer-tag'
319
+ ? '当前已是最新版本'
320
+ : `当前安装不支持 DSH 更新(${state.reason ?? 'unknown'})`
321
+ return json({ ok: false, error, state }, 409)
322
+ }
323
+ const manager = deps.getPluginManager?.()
324
+ if (!manager || typeof manager.updateBundle !== 'function') {
325
+ return json({ ok: false, error: '插件管理器不可用', state }, 503)
326
+ }
327
+ try {
328
+ const result = await manager.updateBundle('dsh-vigil', state.latestVersion, { spec: state.spec })
329
+ return json({ ok: true, updatedTo: state.latestVersion, spec: state.spec, result })
330
+ } catch (error) {
331
+ return json({
332
+ ok: false,
333
+ error: error instanceof Error ? error.message : String(error),
334
+ state,
335
+ }, 500)
336
+ }
337
+ },
338
+ }
339
+ }