mirror of
https://git.openapi.site/https://github.com/desirecore/registry.git
synced 2026-12-06 03:59:03 +08:00
merge: 同步 main 并改用已合入的作者契约
main 已在 #16 合入受主仓固定的 4.3 作者 Schema(95afcff…)和校验逻辑,因此保留其字节,不再引入本分支的候选 Schema(29ece0b…)。 - 删除 application-release-contract.mjs:它要求所有条目声明 definitionPath,会拒绝已上架的 definitionSource: manifest 条目;其余检查 main 已覆盖,仅把 definitionPath 规范路径检查移入 application-contract.mjs。 - 保留 webBundles 统计,并在 authored-release 测试样本中声明,与客户端 checkout 校验一致。 - 测试不再写死条目数,并增加 CLI 校验入口与作者 Schema 摘要断言。 - README 合并到现有作者契约章节,移除已过时的候选说明。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
80e0ff0355
38 files changed
+2240
-82
No files matched your search
@@ -1,12 +1,14 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync, cpSync, mkdtempSync, writeFileSync, rmSync } from 'node:fs'
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { createHash } from 'node:crypto'
|
||||
import { readFileSync, readdirSync, existsSync, cpSync, mkdtempSync, writeFileSync, rmSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { test, afterEach } from 'node:test'
|
||||
import Ajv from 'ajv'
|
||||
import { validateRegistry } from './catalog/validator.mjs'
|
||||
import { validateApplicationReleaseContract } from './catalog/application-release-contract.mjs'
|
||||
import { validateApplicationContract } from './catalog/application-contract.mjs'
|
||||
|
||||
const source = join(dirname(fileURLToPath(import.meta.url)),'..')
|
||||
const temporary = []
|
||||
@@ -15,12 +17,13 @@ const schema = JSON.parse(readFileSync(join(source,'schemas/registry-entry.v4.3.
|
||||
const validate = new Ajv({allErrors:true,strict:true,strictTypes:false,strictRequired:false,validateFormats:false}).compile(schema)
|
||||
const load = id => JSON.parse(readFileSync(join(source,'fixtures/authoring/entries',id,'manifest.json'),'utf8'))
|
||||
|
||||
test('4.3只新增候选文件和合成fixtures,正式4.2目录不提前激活新格式',() => {
|
||||
test('根格式仍为4.2,作者Schema保持主仓固定字节,合成fixtures不进入正式目录',() => {
|
||||
const root = JSON.parse(readFileSync(join(source,'manifest.json'),'utf8'))
|
||||
assert.equal(root.version,'4.2.0')
|
||||
assert.equal(readFileSync(join(source,'SCHEMA_VERSION'),'utf8').trim(),'4.2.0')
|
||||
assert.equal(root.stats.totalEntries,24)
|
||||
assert.equal(root.stats.webBundles,undefined)
|
||||
assert.equal(createHash('sha256').update(readFileSync(join(source,'schemas/registry-entry.v4.3.schema.json'))).digest('hex'),'95afcffce0c985215685554ec8b3f5e3012036bf2c4ecc4214c23e4eff895b10')
|
||||
for (const id of readdirSync(join(source,'fixtures/authoring/entries'))) assert.equal(existsSync(join(source,'entries',id)),false,id)
|
||||
})
|
||||
test('静态与带服务合成目录三文件保持App语义,两个validator同样通过',() => {
|
||||
const root = mkdtempSync(join(tmpdir(),'registry-authoring-'));temporary.push(root)
|
||||
@@ -34,9 +37,11 @@ test('静态与带服务合成目录三文件保持App语义,两个validator
|
||||
const report = validateRegistry(root)
|
||||
assert.equal(report.ok,true,JSON.stringify(report.errors))
|
||||
assert.equal(report.counts.webBundles,1)
|
||||
const cli = spawnSync(process.execPath,[join(source,'scripts/validate-registry.mjs'),'--root',root],{encoding:'utf8'})
|
||||
assert.equal(cli.status,0,cli.stdout+cli.stderr)
|
||||
for (const id of ['static-workbench-example','service-workbench-example','docker-workbench-example']) {
|
||||
const item=load(id);assert.equal(validate(item),true,JSON.stringify(validate.errors))
|
||||
assert.deepEqual(validateApplicationReleaseContract(item),[])
|
||||
assert.deepEqual(validateApplicationContract(item),[])
|
||||
assert.equal(item.sourceId,undefined)
|
||||
assert.notEqual(item.appRelease.releaseDigest,item.source.sha256)
|
||||
assert.equal(item.availability,'listing-only')
|
||||
@@ -51,9 +56,19 @@ test('不能把完整HTML伪装成artifact、native-node或内部MCP服务',() =
|
||||
test('未知能力、可变ref和私有凭据不成为正式分发事实',() => {
|
||||
const item=load('static-workbench-example')
|
||||
for (const change of [copy=>{copy.source.ref='latest'},copy=>{copy.source.url='https://credential@git.example.test/private.zip'},copy=>{copy.appRelease.requiredCapabilities=['app-authoring-v1']}]) {
|
||||
const copy=structuredClone(item);change(copy);assert.ok(validateApplicationReleaseContract(copy).length>0)
|
||||
const copy=structuredClone(item);change(copy);assert.ok(validateApplicationContract(copy).length>0)
|
||||
}
|
||||
})
|
||||
test('definitionPath声明时必须是规范相对路径,内联定义不要求该字段',() => {
|
||||
const item=load('service-workbench-example')
|
||||
for (const path of ['C:/application.json','runtime//application.json','../application.json']) {
|
||||
const copy=structuredClone(item);copy.appRelease.definitionPath=path
|
||||
assert.ok(validateApplicationContract(copy).length>0,path)
|
||||
}
|
||||
const inline=structuredClone(item);delete inline.appRelease.definitionPath;inline.appRelease.definitionSource='manifest'
|
||||
assert.equal(validate(inline),true,JSON.stringify(validate.errors))
|
||||
assert.deepEqual(validateApplicationContract(inline),[])
|
||||
})
|
||||
test('保留既有native-node条目,新native release字段不污染旧分支',() => {
|
||||
const old=JSON.parse(readFileSync(join(source,'entries/desirecore-control/manifest.json'),'utf8'))
|
||||
assert.equal(validate(old),true,JSON.stringify(validate.errors))
|
||||
@@ -66,6 +81,6 @@ test('Docker发布固定真实镜像内容引用,不把浮动tag或错误端
|
||||
assert.equal(item.install.method,'release');assert.equal(item.install.requirements.docker,true)
|
||||
for (const image of ['node:latest','registry.example.test/example/app:1.0.0','localhost:70000/app@sha256:'+'d'.repeat(64)]) {
|
||||
const copy=structuredClone(item);copy.appRelease.imageRefs=[image]
|
||||
assert.ok(!validate(copy) || validateApplicationReleaseContract(copy).length>0)
|
||||
assert.ok(!validate(copy) || validateApplicationContract(copy).length>0)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,146 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { afterEach, test } from 'node:test'
|
||||
import { cpSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { createHash } from 'node:crypto'
|
||||
import { dirname, join, resolve } from 'node:path'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { validateRegistry } from './catalog/validator.mjs'
|
||||
import { validateJsonSchema } from './catalog/json-schema.mjs'
|
||||
|
||||
const source = resolve(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const temporary = []
|
||||
const entryFile = 'entries/desirecore-control/manifest.json'
|
||||
const sidecarFile = 'entries/desirecore-control/catalog-metadata.v1.json'
|
||||
afterEach(() => { for (const root of temporary.splice(0)) rmSync(root, { recursive: true, force: true }) })
|
||||
|
||||
function mutate(root, file, change) {
|
||||
const path = join(root, file)
|
||||
const data = JSON.parse(readFileSync(path, 'utf8'))
|
||||
change(data)
|
||||
writeFileSync(path, JSON.stringify(data))
|
||||
}
|
||||
|
||||
function fixture(type = 'native-app') {
|
||||
const root = mkdtempSync(join(tmpdir(), 'registry-authored-'))
|
||||
temporary.push(root)
|
||||
cpSync(join(source, 'schemas'), join(root, 'schemas'), { recursive: true })
|
||||
cpSync(join(source, 'entries/desirecore-control'), join(root, 'entries/desirecore-control'), { recursive: true })
|
||||
const manifest = JSON.parse(readFileSync(join(source, 'manifest.json'), 'utf8'))
|
||||
manifest.stats = { totalEntries: 1, dockerApps: 0, nativeApps: type === 'native-app' ? 1 : 0, ...(type === 'web-bundle' ? { webBundles: 1 } : {}), mcpServices: 0, httpApis: 0, externalIntegrations: 0 }
|
||||
writeFileSync(join(root, 'manifest.json'), JSON.stringify(manifest))
|
||||
writeFileSync(join(root, 'SCHEMA_VERSION'), manifest.version + '\n')
|
||||
// 测试 release 引用仅用于校验分支;不代表线上 Control 已发布此 release。
|
||||
mutate(root, entryFile, entry => {
|
||||
entry.type = type
|
||||
entry.install.method = type === 'web-bundle' ? 'web-bundle' : 'release'
|
||||
if (type === 'web-bundle') entry.install.requirements = { docker: false, ports: [] }
|
||||
entry.entrypoints = [{ id: 'editor', name: 'Editor', kind: 'embedded-web', serviceRef: 'demo:editor' }]
|
||||
entry.appRelease = {
|
||||
schemaVersion: 1,
|
||||
releaseDigest: 'a'.repeat(64),
|
||||
manifestPath: 'app-release.json',
|
||||
definitionSource: 'manifest',
|
||||
requiredCapabilities: ['app-authoring-v1', 'release', ...(type === 'web-bundle' ? ['web-bundle'] : [])],
|
||||
}
|
||||
})
|
||||
mutate(root, sidecarFile, sidecar => { sidecar.spec.entrypointKinds = ['embedded-web'] })
|
||||
return root
|
||||
}
|
||||
|
||||
function result(root) {
|
||||
const cli = spawnSync(process.execPath, [join(source, 'scripts/validate-registry.mjs'), '--root', root], { encoding: 'utf8' })
|
||||
return { cli, offline: validateRegistry(root) }
|
||||
}
|
||||
function expectValid(root) {
|
||||
const report = result(root)
|
||||
assert.equal(report.cli.status, 0, report.cli.stderr)
|
||||
assert.equal(report.offline.ok, true, JSON.stringify(report.offline.errors))
|
||||
}
|
||||
function expectInvalid(root) {
|
||||
const report = result(root)
|
||||
assert.equal(report.cli.status, 1, report.cli.stdout + report.cli.stderr)
|
||||
assert.equal(report.offline.ok, false, JSON.stringify(report.offline))
|
||||
}
|
||||
|
||||
test('官方根仍为4.2且global Schema保留已发布原字节', () => {
|
||||
assert.equal(readFileSync(join(source, 'SCHEMA_VERSION'), 'utf8'), '4.2.0\n')
|
||||
assert.equal(createHash('sha256').update(readFileSync(join(source, 'schemas/registry-entry.schema.json'))).digest('hex'), 'ea63d6305ae17994e595aea009a131c41300d2b7fdb07ec83cc2c19c37b32038')
|
||||
})
|
||||
for (const type of ['native-app', 'web-bundle']) test('两个入口接受固定内联定义 ' + type, () => { expectValid(fixture(type)) })
|
||||
test('旧独立definitionPath分支继续通过', () => {
|
||||
const root = fixture()
|
||||
mutate(root, entryFile, entry => { delete entry.appRelease.definitionSource; entry.appRelease.definitionPath = 'definition.json' })
|
||||
expectValid(root)
|
||||
})
|
||||
test('普通条目与external-integration不被作者Schema重定义', () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'registry-global-'))
|
||||
temporary.push(root)
|
||||
for (const path of ['entries', 'schemas']) cpSync(join(source, path), join(root, path), { recursive: true })
|
||||
for (const path of ['SCHEMA_VERSION', 'manifest.json']) cpSync(join(source, path), join(root, path))
|
||||
for (const id of readdirSync(join(root, 'entries'))) {
|
||||
const entry = JSON.parse(readFileSync(join(root, 'entries', id, 'manifest.json'), 'utf8'))
|
||||
if (entry.type === 'web-bundle' || Object.hasOwn(entry, 'appRelease')) {
|
||||
rmSync(join(root, 'entries', id), { recursive: true })
|
||||
mutate(root, 'manifest.json', manifest => {
|
||||
manifest.stats.totalEntries -= 1
|
||||
const stat = { 'native-app': 'nativeApps', 'docker-app': 'dockerApps' }[entry.type]
|
||||
if (stat) manifest.stats[stat] -= 1
|
||||
})
|
||||
}
|
||||
}
|
||||
writeFileSync(join(root, 'schemas/registry-entry.v4.3.schema.json'), 'false\n')
|
||||
expectValid(root)
|
||||
writeFileSync(join(root, 'schemas/registry-entry.schema.json'), 'false\n')
|
||||
expectInvalid(root)
|
||||
})
|
||||
test('作者Schema拒绝时不回退global', () => {
|
||||
const root = fixture()
|
||||
writeFileSync(join(root, 'schemas/registry-entry.v4.3.schema.json'), 'false\n')
|
||||
expectInvalid(root)
|
||||
})
|
||||
for (const invalid of ['null', '[]', '42']) test('两个入口拒绝非法作者Schema根 ' + invalid, () => {
|
||||
const root = fixture()
|
||||
writeFileSync(join(root, 'schemas/registry-entry.v4.3.schema.json'), invalid + '\n')
|
||||
expectInvalid(root)
|
||||
})
|
||||
test('离线contains匹配实际元素并拒绝空数组与缺失能力', () => {
|
||||
const schema = { type: 'array', contains: { const: 'app-authoring-v1' } }
|
||||
assert.deepEqual(validateJsonSchema(['release', 'app-authoring-v1'], schema), [])
|
||||
assert.ok(validateJsonSchema(['release'], schema).length > 0)
|
||||
assert.ok(validateJsonSchema([], schema).length > 0)
|
||||
})
|
||||
for (const [name, change] of [
|
||||
['同时声明两种定义来源', entry => { entry.appRelease.definitionPath = 'definition.json' }],
|
||||
['缺少定义来源', entry => { delete entry.appRelease.definitionSource }],
|
||||
['伪造inline来源', entry => { entry.appRelease.definitionSource = 'payload' }],
|
||||
['缺app-authoring-v1能力', entry => { entry.appRelease.requiredCapabilities = ['release'] }],
|
||||
['缺release能力', entry => { entry.appRelease.requiredCapabilities = ['app-authoring-v1'] }],
|
||||
['浮动源码ref', entry => { entry.source.ref = 'main' }],
|
||||
['缺归档摘要', entry => { delete entry.source.sha256 }],
|
||||
['HTTPS URL携带凭据', entry => { entry.source.url = 'https://user@example.com/release.zip' }],
|
||||
['HTTPS URL携带query', entry => { entry.source.url += '?download=1' }],
|
||||
['HTTP归档', entry => { entry.source.url = 'http://example.com/release.zip' }],
|
||||
['git缺归档内路径', entry => { entry.source.kind = 'git'; delete entry.source.path }],
|
||||
['git归档内路径穿越', entry => { entry.source.kind = 'git'; entry.source.path = '../release' }],
|
||||
['非Docker镜像依赖', entry => { entry.appRelease.imageRefs = ['registry.example.com/app@sha256:' + 'a'.repeat(64)] }],
|
||||
['重复入口ID', entry => { entry.entrypoints.push({ ...entry.entrypoints[0] }) }],
|
||||
['保留端口引用', entry => { entry.entrypoints[0].serviceRef = 'native-port:9333' }],
|
||||
]) test('两个入口拒绝 ' + name, () => {
|
||||
const root = fixture()
|
||||
mutate(root, entryFile, change)
|
||||
expectInvalid(root)
|
||||
})
|
||||
test('web-bundle缺web-bundle能力仍拒绝', () => {
|
||||
const root = fixture('web-bundle')
|
||||
mutate(root, entryFile, entry => { entry.appRelease.requiredCapabilities = ['app-authoring-v1', 'release'] })
|
||||
expectInvalid(root)
|
||||
})
|
||||
test('web-bundle仍核对sidecar治理与内容来源', () => {
|
||||
const root = fixture('web-bundle')
|
||||
mutate(root, sidecarFile, sidecar => { sidecar.provenance.content.sha256 = 'b'.repeat(64) })
|
||||
const report = validateRegistry(root)
|
||||
assert.equal(report.ok, false)
|
||||
assert.ok(report.errors.some(item => item.code === 'native-source-mismatch'))
|
||||
})
|
||||
@@ -1,7 +1,35 @@
|
||||
import { isApplicationEntry, isAuthoredRegistryEntry } from './entry-schema.mjs'
|
||||
|
||||
/** 发布者关系声明的跨字段检查;不推导安装、权限或运行时健康。 */
|
||||
export function validateApplicationContract(manifest) {
|
||||
if (!['docker-app', 'native-app', 'artifact', 'web-bundle'].includes(manifest.type)) return []
|
||||
if (!isApplicationEntry(manifest) && !isAuthoredRegistryEntry(manifest)) return []
|
||||
const errors = []
|
||||
if (isAuthoredRegistryEntry(manifest)) {
|
||||
if (!['web-bundle', 'native-app', 'docker-app'].includes(manifest.type)) errors.push('appRelease: unsupported delivery type')
|
||||
const required = manifest.appRelease?.requiredCapabilities
|
||||
if (!Array.isArray(required) || !required.includes('release') || (manifest.type === 'web-bundle' && !required.includes('web-bundle'))) {
|
||||
errors.push('appRelease: delivery capability handshake required')
|
||||
}
|
||||
const images = manifest.appRelease?.imageRefs
|
||||
// 镜像语法由严格 Schema 校验;端口范围属于同一跨字段合同。
|
||||
if (manifest.type === 'docker-app' && (!Array.isArray(images) || images.length === 0 || images.some(image =>
|
||||
typeof image !== 'string' || Number(image.split('/')[0].split(':')[1] ?? 0) > 65535))) errors.push('appRelease: Docker images must be pinned by digest')
|
||||
if (manifest.type !== 'docker-app' && images !== undefined) errors.push('appRelease: imageRefs belongs only to Docker release')
|
||||
const source = manifest.source
|
||||
if (!source || !['git', 'release'].includes(source.kind) ||
|
||||
typeof source.ref !== 'string' || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(source.ref) ||
|
||||
typeof source.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(source.sha256)) {
|
||||
errors.push('source: authored release requires immutable commit and archive sha256')
|
||||
}
|
||||
try {
|
||||
const url = new URL(String(source?.url))
|
||||
if (url.protocol !== 'https:' || url.username || url.password || url.hash || url.search) errors.push('source: credential-free fixed HTTPS URL required')
|
||||
} catch { errors.push('source: invalid URL') }
|
||||
if (source?.kind === 'git' && (typeof source.path !== 'string' || !isPortablePath(source.path))) errors.push('source: git archive path must be canonical and relative')
|
||||
// 内联定义不声明 definitionPath;声明时才要求规范相对路径。
|
||||
const definitionPath = manifest.appRelease?.definitionPath
|
||||
if (definitionPath !== undefined && (typeof definitionPath !== 'string' || !isPortablePath(definitionPath))) errors.push('appRelease: definitionPath must be canonical and relative')
|
||||
}
|
||||
const ids = new Set()
|
||||
for (const entrypoint of Array.isArray(manifest.entrypoints) ? manifest.entrypoints : []) {
|
||||
if (!entrypoint || typeof entrypoint !== 'object') continue
|
||||
@@ -18,3 +46,9 @@ export function validateApplicationContract(manifest) {
|
||||
}
|
||||
return errors
|
||||
}
|
||||
|
||||
function isPortablePath(value) {
|
||||
return value.length > 0 && value.length <= 512 &&
|
||||
!/[\\\x00-\x1f?#:]/.test(value) && !value.startsWith('/') &&
|
||||
value.split('/').every(part => part.length > 0 && part !== '.' && part !== '..')
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
/** 作者材料的跨字段检查;身份与运行事实由客户端owner核验,不执行安装说明。 */
|
||||
export function validateApplicationReleaseContract(manifest) {
|
||||
if (manifest.type !== 'web-bundle' && manifest.appRelease === undefined) return []
|
||||
const errors = []
|
||||
if (!['web-bundle', 'native-app', 'docker-app'].includes(manifest.type)) errors.push('appRelease: unsupported delivery type')
|
||||
if (!manifest.appRelease?.requiredCapabilities?.includes('app-authoring-v1')) errors.push('appRelease: app-authoring-v1 capability handshake required')
|
||||
if (!manifest.appRelease?.requiredCapabilities?.includes('release') ||
|
||||
(manifest.type === 'web-bundle' && !manifest.appRelease.requiredCapabilities.includes('web-bundle'))) errors.push('appRelease: delivery capability handshake required')
|
||||
const images = manifest.appRelease?.imageRefs
|
||||
if (manifest.type === 'docker-app' && (!Array.isArray(images) || !images.length || images.some(image =>
|
||||
typeof image !== 'string' || !/^[a-z0-9][a-z0-9._:/-]*@sha256:[a-f0-9]{64}$/.test(image) ||
|
||||
Number(image.split('/')[0].split(':')[1] ?? 0) > 65535))) errors.push('appRelease: Docker images must be pinned by digest')
|
||||
if (manifest.type !== 'docker-app' && images !== undefined) errors.push('appRelease: imageRefs belongs only to Docker release')
|
||||
const source = manifest.source
|
||||
if (!source || !['git', 'release'].includes(source.kind) ||
|
||||
!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(source.ref ?? '') || !/^[a-f0-9]{64}$/.test(source.sha256 ?? '')) {
|
||||
errors.push('source: authored release requires immutable commit and archive sha256')
|
||||
}
|
||||
try {
|
||||
const url = new URL(source?.url)
|
||||
if (url.protocol !== 'https:' || url.username || url.password || url.hash || url.search) errors.push('source: credential-free fixed HTTPS URL required')
|
||||
} catch { errors.push('source: invalid URL') }
|
||||
if (source?.kind === 'git' && !isPortablePath(source.path)) errors.push('source: git archive path must be canonical and relative')
|
||||
if (!isPortablePath(manifest.appRelease?.definitionPath)) errors.push('appRelease: definitionPath must be canonical and relative')
|
||||
return errors
|
||||
}
|
||||
|
||||
function isPortablePath(value) {
|
||||
return typeof value === 'string' && value.length > 0 && value.length <= 512 &&
|
||||
!/[\\\x00-\x1f?#:]/.test(value) && !value.startsWith('/') &&
|
||||
value.split('/').every(part => part.length > 0 && part !== '.' && part !== '..')
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/** MCP 机器审核记录的绑定契约;仅机械核验,不授予运行权限。 */
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { validateJsonSchema } from './json-schema.mjs'
|
||||
const schema = JSON.parse(readFileSync(new URL('../../schemas/mcp-package-review.v1.schema.json', import.meta.url), 'utf8'))
|
||||
export const MCP_PACKAGE_REVIEWER = schema.properties.reviewer.const
|
||||
const checks = schema.properties.checks.required
|
||||
|
||||
export function validateMcpPackageReview(manifest, catalog, record) {
|
||||
const content = catalog.provenance?.content
|
||||
const compliance = catalog.governance?.compliance
|
||||
const errors = validateJsonSchema(record, schema).map(error => `${error.path}: ${error.message}`)
|
||||
if (errors.length) return errors
|
||||
if (manifest.type !== 'mcp' || content?.kind !== 'package' || record.schemaVersion !== 1
|
||||
|| record.reviewer !== MCP_PACKAGE_REVIEWER || record.entryId !== manifest.id
|
||||
|| record.version !== manifest.version || record.version !== content.ref
|
||||
|| record.sourceUrl !== content.url || record.contentSha256 !== content.sha256
|
||||
|| !/^[a-f0-9]{64}$/.test(record.contentSha256 ?? '')
|
||||
|| record.packageName !== manifest.install?.packageName
|
||||
|| !['npm', 'pypi'].includes(record.ecosystem)
|
||||
|| typeof record.previousVersion !== 'string' || record.previousVersion === record.version) errors.push('机器审核必须绑定当前 MCP 包身份、版本和摘要')
|
||||
const expectedMethod = record.ecosystem === 'npm' ? ['npx'] : ['uvx', 'pip']
|
||||
const expectedUrl = record.ecosystem === 'npm' ? 'https://www.npmjs.com/package/' + record.packageName : 'https://pypi.org/project/' + record.packageName
|
||||
if (!expectedMethod.includes(manifest.install?.method) || content?.url?.replace(/\/$/, '') !== expectedUrl) errors.push('包生态与目录来源不一致')
|
||||
const separator = record.ecosystem === 'npm' ? '@' : '=='
|
||||
const selector = record.packageName + separator + record.version
|
||||
for (const config of [manifest.install, manifest.connection]) {
|
||||
if (!Array.isArray(config?.args) || !config.args.includes(selector)
|
||||
|| config.args.filter(arg => typeof arg === 'string' && (arg === record.packageName || arg.startsWith(record.packageName + separator))).length !== 1) errors.push('启动配置未唯一固定到审核版本')
|
||||
}
|
||||
if (checks.some(key => record.checks?.[key] !== true)) errors.push('机器审核检查不完整')
|
||||
if (typeof record.reviewedAt !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(record.reviewedAt)
|
||||
|| !Number.isFinite(Date.parse(record.reviewedAt)) || new Date(record.reviewedAt).toISOString().replace('.000Z', 'Z') !== record.reviewedAt || record.reviewedAt.slice(0, 10) !== compliance?.reviewedAt
|
||||
|| compliance?.reviewedBy !== MCP_PACKAGE_REVIEWER) errors.push('机器审核身份和日期不一致')
|
||||
const evidence = record.licenseEvidenceSha256
|
||||
if (!evidence || typeof evidence !== 'object' || Array.isArray(evidence) || !Object.keys(evidence).length
|
||||
|| Object.values(evidence).some(value => typeof value !== 'string' || !/^[a-f0-9]{64}$/.test(value))) errors.push('缺少许可及 Notice 摘要')
|
||||
for (const path of [compliance?.licenseEvidencePath, compliance?.noticePath].filter(Boolean)) {
|
||||
if (!evidence?.[path]) errors.push('未绑定声明的许可证据路径')
|
||||
}
|
||||
if (!Array.isArray(record.limitations) || !record.limitations.length) errors.push('缺少核验范围披露')
|
||||
try {
|
||||
const url = new URL(record.artifactUrl)
|
||||
const host = record.ecosystem === 'npm' ? 'registry.npmjs.org' : 'files.pythonhosted.org'
|
||||
if (url.protocol !== 'https:' || url.hostname !== host || url.username || url.password) throw new Error()
|
||||
} catch { errors.push('固定制品来源无效') }
|
||||
return errors
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync, cpSync, mkdtempSync, writeFileSync, rmSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { validateMcpPackageReview, MCP_PACKAGE_REVIEWER } from './automated-mcp-review.mjs'
|
||||
import { validateRegistry } from './validator.mjs'
|
||||
|
||||
function fixture() {
|
||||
const manifest = JSON.parse(readFileSync(new URL('../../entries/rea-mcp/manifest.json', import.meta.url)))
|
||||
const catalog = JSON.parse(readFileSync(new URL('../../entries/rea-mcp/catalog-metadata.v1.json', import.meta.url)))
|
||||
manifest.version = '6.5.0'
|
||||
for (const config of [manifest.install, manifest.connection]) config.args = config.args.map(arg => arg.replace('rea-agents@6.4.0', 'rea-agents@6.5.0'))
|
||||
catalog.release.version = manifest.version
|
||||
catalog.provenance.content.ref = manifest.version
|
||||
catalog.provenance.content.sha256 = 'a'.repeat(64)
|
||||
catalog.governance.compliance.reviewedRef = manifest.version
|
||||
catalog.governance.compliance.reviewedBy = MCP_PACKAGE_REVIEWER
|
||||
catalog.governance.compliance.reviewedAt = '2026-10-31'
|
||||
catalog.timestamps.reviewedAt = { state: 'known', value: '2026-10-31', precision: 'day' }
|
||||
const checks = ['publishedIntegrity', 'previousCatalogDigest', 'boundedOrdinaryFiles', 'licenseAndNoticeUnchanged', 'structuredPrerequisitesUnchanged', 'pinnedLaunchSelectors']
|
||||
const receipt = { schemaVersion: 1, reviewer: MCP_PACKAGE_REVIEWER, reviewedAt: '2026-10-31T08:00:00Z', entryId: 'rea-mcp', previousVersion: '6.4.0', version: '6.5.0', packageName: 'rea-agents', ecosystem: 'npm', sourceUrl: catalog.provenance.content.url, artifactUrl: 'https://registry.npmjs.org/rea-agents/-/rea-agents-6.5.0.tgz', contentSha256: 'a'.repeat(64), licenseEvidenceSha256: { LICENSE: 'b'.repeat(64) }, checks: Object.fromEntries(checks.map(key => [key, true])), limitations: ['Source verification only; no runtime/security acceptance'] }
|
||||
return { manifest, catalog, receipt }
|
||||
}
|
||||
|
||||
test('machine receipt binds package version, archive digest, review time and required checks', () => {
|
||||
const { manifest, catalog, receipt } = fixture()
|
||||
assert.deepEqual(validateMcpPackageReview(manifest, catalog, receipt), [])
|
||||
for (const patch of [{ entryId: 'other' }, { contentSha256: 'c'.repeat(64) }, { reviewedAt: '2026-10-30T08:00:00Z' }, { reviewedAt: '2026-02-31T08:00:00Z' }, { checks: {} }, { licenseEvidenceSha256: {} }, { artifactUrl: 'https://attacker.invalid/file' }, { previousVersion: null }]) {
|
||||
assert.ok(validateMcpPackageReview(manifest, catalog, { ...receipt, ...patch }).length)
|
||||
}
|
||||
assert.ok(validateMcpPackageReview(manifest, catalog, null).length)
|
||||
})
|
||||
|
||||
test('real catalog validator accepts bound evidence and rejects missing or tampered evidence', () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'mcp-review-'))
|
||||
try {
|
||||
for (const name of ['entries', 'schemas', 'manifest.json', 'SCHEMA_VERSION']) cpSync(new URL('../../' + name, import.meta.url), join(root, name), { recursive: true })
|
||||
const { manifest, catalog, receipt } = fixture()
|
||||
const folder = join(root, 'entries/rea-mcp')
|
||||
const write = (name, value) => writeFileSync(join(folder, name), JSON.stringify(value))
|
||||
write('manifest.json', manifest); write('catalog-metadata.v1.json', catalog); write('upstream-audit.v1.json', receipt)
|
||||
assert.equal(validateRegistry(root, { requireSidecars: true }).ok, true)
|
||||
write('upstream-audit.v1.json', { ...receipt, contentSha256: '0'.repeat(64) })
|
||||
assert.ok(validateRegistry(root).errors.some(issue => issue.code === 'automated-mcp-review'))
|
||||
rmSync(join(folder, 'upstream-audit.v1.json'))
|
||||
assert.ok(validateRegistry(root).errors.some(issue => issue.code === 'automated-mcp-review'))
|
||||
} finally { rmSync(root, { recursive: true, force: true }) }
|
||||
})
|
||||
@@ -0,0 +1,10 @@
|
||||
/** 作者 release 使用受审的新契约;普通条目仍由已发布 global Schema 校验。 */
|
||||
export const AUTHORED_ENTRY_SCHEMA_FILENAME = 'registry-entry.v4.3.schema.json'
|
||||
|
||||
export function isAuthoredRegistryEntry(entry) {
|
||||
return entry?.type === 'web-bundle' || (entry !== null && typeof entry === 'object' && Object.hasOwn(entry, 'appRelease'))
|
||||
}
|
||||
|
||||
export function isApplicationEntry(entry) {
|
||||
return ['docker-app', 'native-app', 'artifact', 'web-bundle'].includes(entry?.type)
|
||||
}
|
||||
@@ -141,6 +141,13 @@ function validateNode(value, schema, rootSchema, path, errors) {
|
||||
if (schema.items) {
|
||||
value.forEach((item, index) => validateNode(item, schema.items, rootSchema, joinPath(path, index), errors))
|
||||
}
|
||||
if (schema.contains !== undefined && !value.some((item, index) => {
|
||||
const candidateErrors = []
|
||||
validateNode(item, schema.contains, rootSchema, joinPath(path, index), candidateErrors)
|
||||
return candidateErrors.length === 0
|
||||
})) {
|
||||
errors.push({ path, message: '数组必须包含符合 contains 的元素' })
|
||||
}
|
||||
}
|
||||
|
||||
if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
|
||||
|
||||
@@ -3,8 +3,9 @@ import { isDeepStrictEqual } from 'node:util'
|
||||
import { basename, join, relative, resolve, sep } from 'node:path'
|
||||
import { validateJsonSchema } from './json-schema.mjs'
|
||||
import { findStaticMetrics } from './static-metadata.mjs'
|
||||
import { MCP_PACKAGE_REVIEWER, validateMcpPackageReview } from './automated-mcp-review.mjs'
|
||||
import { validateApplicationContract } from './application-contract.mjs'
|
||||
import { validateApplicationReleaseContract } from './application-release-contract.mjs'
|
||||
import { AUTHORED_ENTRY_SCHEMA_FILENAME, isApplicationEntry, isAuthoredRegistryEntry } from './entry-schema.mjs'
|
||||
|
||||
export const CATALOG_SIDECAR_FILENAME = 'catalog-metadata.v1.json'
|
||||
|
||||
@@ -34,6 +35,15 @@ function schemaDiagnostics(value, schema, file) {
|
||||
)
|
||||
}
|
||||
|
||||
function readSchema(file, diagnostics) {
|
||||
const schema = readJson(file, diagnostics)
|
||||
if (schema === null || Array.isArray(schema) || !['object', 'boolean'].includes(typeof schema)) {
|
||||
diagnostics.push(diagnostic('error', 'invalid-schema', file, '$', 'Schema 根必须是对象或 boolean'))
|
||||
return null
|
||||
}
|
||||
return schema
|
||||
}
|
||||
|
||||
function safeRelativePath(value) {
|
||||
return (
|
||||
typeof value === 'string' &&
|
||||
@@ -78,7 +88,7 @@ function timestampShapeIsConsistent(timestamp) {
|
||||
function validateSidecarSemantics(manifest, sidecar, file) {
|
||||
const errors = []
|
||||
const add = (code, path, message) => errors.push(diagnostic('error', code, file, path, message))
|
||||
const expectedKind = ['docker-app', 'native-app', 'artifact', 'web-bundle'].includes(manifest.type) ? 'app' : 'service'
|
||||
const expectedKind = isApplicationEntry(manifest) ? 'app' : 'service'
|
||||
|
||||
if (sidecar.identity?.id !== manifest.id) add('identity-mismatch', '$.identity.id', 'sidecar identity.id 必须与 legacy manifest.id 一致')
|
||||
if (sidecar.identity?.kind !== expectedKind) add('kind-mismatch', '$.identity.kind', `legacy ${manifest.type} 必须映射为 ${expectedKind}`)
|
||||
@@ -141,7 +151,7 @@ function validateSidecarSemantics(manifest, sidecar, file) {
|
||||
if (manifest.toolCount !== undefined && sidecar.spec?.toolCount !== manifest.toolCount) add('spec-mismatch', '$.spec.toolCount', 'toolCount 必须与 legacy 一致')
|
||||
}
|
||||
|
||||
if (['native-app', 'artifact', 'web-bundle'].includes(manifest.type)) {
|
||||
if (['native-app', 'artifact', 'web-bundle'].includes(manifest.type) || isAuthoredRegistryEntry(manifest)) {
|
||||
for (const field of ['stewardship', 'availability', 'redistribution', 'listingMaintainer', 'upstreamMaintainer', 'branding', 'compliance']) {
|
||||
if (!isDeepStrictEqual(manifest[field], sidecar.governance?.[field])) add('native-governance-mismatch', '$.governance.' + field, '原生应用 manifest 与 sidecar 的治理事实必须一致')
|
||||
}
|
||||
@@ -206,15 +216,16 @@ export function validateRegistry(repoRoot, options = {}) {
|
||||
const diagnostics = []
|
||||
const manifestFile = join(root, 'manifest.json')
|
||||
const schemaVersionFile = join(root, 'SCHEMA_VERSION')
|
||||
const rootSchema = readJson(join(root, 'schemas', 'registry-manifest.v3.schema.json'), diagnostics)
|
||||
const legacyEntrySchema = readJson(join(root, 'schemas', 'registry-entry.v3.schema.json'), diagnostics)
|
||||
const externalEntrySchema = readJson(join(root, 'schemas', 'registry-entry.schema.json'), diagnostics)
|
||||
const sidecarSchema = readJson(join(root, 'schemas', 'catalog-metadata.v1.schema.json'), diagnostics)
|
||||
const rootSchema = readSchema(join(root, 'schemas', 'registry-manifest.v3.schema.json'), diagnostics)
|
||||
const legacyEntrySchema = readSchema(join(root, 'schemas', 'registry-entry.v3.schema.json'), diagnostics)
|
||||
const externalEntrySchema = readSchema(join(root, 'schemas', 'registry-entry.schema.json'), diagnostics)
|
||||
const authoredEntrySchema = readSchema(join(root, 'schemas', AUTHORED_ENTRY_SCHEMA_FILENAME), diagnostics)
|
||||
const sidecarSchema = readSchema(join(root, 'schemas', 'catalog-metadata.v1.schema.json'), diagnostics)
|
||||
const rootManifest = readJson(manifestFile, diagnostics)
|
||||
const entryDirs = findEntryDirs(join(root, 'entries'))
|
||||
const counts = { totalEntries: 0, dockerApps: 0, mcpServices: 0, httpApis: 0, externalIntegrations: 0, sidecars: 0, legacyOnly: 0 }
|
||||
|
||||
if (rootManifest && rootSchema) diagnostics.push(...schemaDiagnostics(rootManifest, rootSchema, relativeFile(root, manifestFile)))
|
||||
if (rootManifest && rootSchema !== null) diagnostics.push(...schemaDiagnostics(rootManifest, rootSchema, relativeFile(root, manifestFile)))
|
||||
const schemaVersion = existsSync(schemaVersionFile) ? readFileSync(schemaVersionFile, 'utf8').trim() : ''
|
||||
const currentEntrySchema = /^4\./.test(schemaVersion) ? externalEntrySchema : legacyEntrySchema
|
||||
if (!schemaVersion) diagnostics.push(diagnostic('error', 'missing-schema-version', 'SCHEMA_VERSION', '$', 'SCHEMA_VERSION 不能为空'))
|
||||
@@ -242,10 +253,10 @@ export function validateRegistry(repoRoot, options = {}) {
|
||||
if (entry.type === 'mcp') counts.mcpServices += 1
|
||||
if (entry.type === 'http-api') counts.httpApis += 1
|
||||
if (entry.type === 'external-integration') counts.externalIntegrations += 1
|
||||
const effectiveEntrySchema = ['external-integration', 'native-app', 'artifact', 'web-bundle'].includes(entry.type) ? externalEntrySchema : currentEntrySchema
|
||||
if (effectiveEntrySchema) diagnostics.push(...schemaDiagnostics(entry, effectiveEntrySchema, manifestRelative))
|
||||
const effectiveEntrySchema = isAuthoredRegistryEntry(entry) ? authoredEntrySchema
|
||||
: ['external-integration', 'native-app', 'artifact'].includes(entry.type) ? externalEntrySchema : currentEntrySchema
|
||||
if (effectiveEntrySchema !== null && effectiveEntrySchema !== undefined) diagnostics.push(...schemaDiagnostics(entry, effectiveEntrySchema, manifestRelative))
|
||||
for (const message of validateApplicationContract(entry)) diagnostics.push(diagnostic('error', 'application-contract', manifestRelative, '$', message))
|
||||
for (const message of validateApplicationReleaseContract(entry)) diagnostics.push(diagnostic('error', 'application-release-contract', manifestRelative, '$', message))
|
||||
if (entry.id !== basename(entryDir)) diagnostics.push(diagnostic('error', 'directory-id-mismatch', manifestRelative, '$.id', 'manifest.id 必须与 entries/<id> 目录名一致'))
|
||||
if (seenIds.has(entry.id)) diagnostics.push(diagnostic('error', 'duplicate-id', manifestRelative, '$.id', 'Registry 条目 ID 重复'))
|
||||
seenIds.add(entry.id)
|
||||
@@ -262,8 +273,15 @@ export function validateRegistry(repoRoot, options = {}) {
|
||||
const sidecar = readJson(sidecarPath, diagnostics)
|
||||
if (!sidecar) continue
|
||||
const sidecarRelative = relativeFile(root, sidecarPath)
|
||||
if (sidecarSchema) diagnostics.push(...schemaDiagnostics(sidecar, sidecarSchema, sidecarRelative))
|
||||
if (sidecarSchema !== null) diagnostics.push(...schemaDiagnostics(sidecar, sidecarSchema, sidecarRelative))
|
||||
diagnostics.push(...validateSidecarSemantics(entry, sidecar, sidecarRelative))
|
||||
if (sidecar.governance?.compliance?.reviewedBy === MCP_PACKAGE_REVIEWER) {
|
||||
const receiptPath = join(entryDir, 'upstream-audit.v1.json')
|
||||
const receipt = readJson(receiptPath, diagnostics)
|
||||
for (const message of validateMcpPackageReview(entry, sidecar, receipt)) {
|
||||
diagnostics.push(diagnostic('error', 'automated-mcp-review', sidecarRelative, '$.governance.compliance', message))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (rootManifest?.stats) {
|
||||
|
||||
@@ -208,10 +208,10 @@ test('当前 v4.2 条目保持可读,原生应用与既有 App/Service 具备
|
||||
httpApis: report.counts.httpApis,
|
||||
externalIntegrations: report.counts.externalIntegrations,
|
||||
}, {
|
||||
totalEntries: 24,
|
||||
totalEntries: 27,
|
||||
dockerApps: 8,
|
||||
nativeApps: 1,
|
||||
mcpServices: 9,
|
||||
nativeApps: 3,
|
||||
mcpServices: 10,
|
||||
httpApis: 5,
|
||||
externalIntegrations: 1,
|
||||
})
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# MCP 上游更新
|
||||
|
||||
`propose_mcp_updates.py` 默认只检查所有 MCP 条目并输出 JSON/Markdown 状态。npm 使用已声明包的 latest,PyPI 使用项目版本元数据;没有本地安装声明的远程服务标记 remote-managed;有本地安装声明的 HTTP/SSE 服务仍检查发行包,不因传输类型就当作托管服务,关联应用标记 app-managed,未配置可靠规则的交付形态标记 requires-version-feed。网络失败不等于已是最新。
|
||||
|
||||
`--publish` 仅在官方 Registry 使用触发用户身份,每次最多提出五个去重 PR,不覆盖已有候选,不自动合并。旧版本已经具备准入证据,且固定包、许可/第三方声明、结构化依赖、引擎和启动入口不变时,核验实际发布摘要和旧目录 SHA-256,生成明确机器身份、绑定新版本和摘要的审核记录;通过 Registry 两套校验后提交普通 PR。
|
||||
|
||||
许可、依赖或入口变化、版本相关实测说明、工具数量等不能自动判定时,只生成带原因的候选说明草稿,不改变旧 manifest、sidecar 或准入状态。不能把旧版本的运行验收继承到新版。自动核验不执行安装脚本、MCP 握手或业务工具,不代表安全认证。npm 签名和供应链认证未在此实现。
|
||||
|
||||
核验预算为下载 32 MiB、展开 128 MiB、单文件 16 MiB、5000 个文件,仅用于 CI 自动核验。制品只读,不解压到用户目录。Python 自动核验限唯一通用 wheel;平台 wheel、Docker/Go/二进制需要另外的固定制品规则,明确报告阻碍。
|
||||
|
||||
运行相关单文件:`python3 scripts/upstream/test_mcp_updates.py`、`node --test scripts/catalog/automated-mcp-review.test.mjs`。定时流程须合入 main,且仓库允许 Actions 创建 PR 后才生效。默认 GITHUB_TOKEN 创建 PR 不保证触发其它工作流,因此候选提交前执行目录校验,合并前仍确认必需检查。
|
||||
@@ -0,0 +1,309 @@
|
||||
"""MCP 固定包来源的发现与机械核验。不安装包、不执行上游代码。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import copy
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
import tarfile
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import zipfile
|
||||
from datetime import datetime, timezone
|
||||
from email.parser import BytesParser
|
||||
from pathlib import Path, PurePosixPath
|
||||
|
||||
REVIEW_SCHEMA = json.loads((Path(__file__).resolve().parents[2] / 'schemas/mcp-package-review.v1.schema.json').read_text())
|
||||
REVIEWER = REVIEW_SCHEMA['properties']['reviewer']['const']
|
||||
MAX_DOWNLOAD = 32 * 1024 * 1024
|
||||
MAX_FILE = 16 * 1024 * 1024
|
||||
MAX_EXPANDED = 128 * 1024 * 1024
|
||||
MAX_FILES = 5000
|
||||
NPM_NAME = re.compile(r'(?:@[a-z0-9_.-]+/)?[a-z0-9][a-z0-9_.-]*')
|
||||
PYPI_NAME = re.compile(r'[A-Za-z0-9][A-Za-z0-9._-]*')
|
||||
VERSION = re.compile(r'\d+(?:\.\d+){1,3}')
|
||||
|
||||
|
||||
|
||||
class AuditBlocked(ValueError):
|
||||
"""证据不足时保持旧目录,不填写新审核通过记录。"""
|
||||
def __init__(self, message, findings=None):
|
||||
super().__init__(message)
|
||||
self.findings = findings or {}
|
||||
|
||||
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
def download(url: str, maximum=MAX_DOWNLOAD) -> bytes:
|
||||
parsed = urllib.parse.urlsplit(url)
|
||||
if (parsed.scheme != 'https' or parsed.hostname not in
|
||||
{'registry.npmjs.org', 'pypi.org', 'files.pythonhosted.org', 'api.github.com'}
|
||||
or parsed.username or parsed.password or parsed.port not in (None, 443)):
|
||||
raise AuditBlocked('仅获取固定官方包注册表 HTTPS 地址')
|
||||
request = urllib.request.Request(url, headers={'User-Agent': 'DesireCore-upstream-review/1.0'})
|
||||
chunks, total = [], 0
|
||||
with urllib.request.build_opener(NoRedirect).open(request, timeout=30) as response:
|
||||
while chunk := response.read(min(64 * 1024, maximum + 1 - total)):
|
||||
chunks.append(chunk); total += len(chunk)
|
||||
if total > maximum:
|
||||
raise AuditBlocked('制品超过自动核验下载预算')
|
||||
return b''.join(chunks)
|
||||
|
||||
|
||||
def fetch_json(url):
|
||||
return json.loads(download(url, 2 * 1024 * 1024))
|
||||
|
||||
|
||||
def identity(name, ecosystem):
|
||||
if not isinstance(name, str): raise AuditBlocked('上游包名称必须是字符串')
|
||||
return re.sub('[-_.]+', '-', name).lower() if ecosystem == 'pypi' else name
|
||||
|
||||
|
||||
def discover(manifest: dict, fetch=fetch_json, version_scheme=None) -> dict:
|
||||
row = {'id': manifest['id'], 'listedVersion': manifest.get('version')}
|
||||
connection, install = manifest.get('connection', {}), manifest.get('install', {})
|
||||
if manifest.get('sourceAppId'):
|
||||
return {**row, 'status': 'app-managed', 'reason': '随关联应用维护,不独立升级此 MCP 入口'}
|
||||
if connection.get('transport') in ('streamable-http', 'sse') and not install:
|
||||
return {**row, 'status': 'remote-managed', 'reason': '由服务端维护;目录版本不是实际服务端版本'}
|
||||
method, package = install.get('method'), install.get('packageName', '')
|
||||
ecosystem = 'npm' if method == 'npx' else 'pypi' if method in ('pip', 'uvx') else None
|
||||
if method == 'docker' and manifest['id'] == 'github-mcp' and package == 'ghcr.io/github/github-mcp-server':
|
||||
url = 'https://api.github.com/repos/github/github-mcp-server/releases/latest'
|
||||
published = fetch(url)
|
||||
if not isinstance(published, dict): raise AuditBlocked('发行元数据必须是对象')
|
||||
latest, listed = str(published.get('tag_name', '')).removeprefix('v'), manifest.get('version', '')
|
||||
if not VERSION.fullmatch(latest) or not VERSION.fullmatch(listed):
|
||||
return {**row, 'status':'manual-review-required', 'reason':'容器发行标签不能可靠比较'}
|
||||
status = 'current' if latest == listed else 'outdated' if tuple(map(int, latest.split('.'))) > tuple(map(int, listed.split('.'))) else 'upstream-version-behind'
|
||||
return {**row,'status':status,'latestVersion':latest,'ecosystem':'github-release','packageName':package,'metadataUrl':url,'metadata':published,
|
||||
'reason':'已登记 GitHub 官方发行源;镜像 digest 和准入仍需核验,不自动拉取容器'}
|
||||
if ecosystem is None:
|
||||
return {**row, 'status': 'requires-version-feed', 'reason': '该交付类型尚无已登记的可靠新版发现与固定制品规则'}
|
||||
pattern = NPM_NAME if ecosystem == 'npm' else PYPI_NAME
|
||||
if not isinstance(package, str) or not pattern.fullmatch(package):
|
||||
return {**row, 'status': 'invalid-package-identity', 'reason': '缺少明确包身份,不能把任意 URL 或命令当作包名'}
|
||||
url = (f'https://registry.npmjs.org/{urllib.parse.quote(package, safe="@/")}/latest'
|
||||
if ecosystem == 'npm' else f'https://pypi.org/pypi/{package}/json')
|
||||
published = fetch(url)
|
||||
if not isinstance(published, dict): raise AuditBlocked('包元数据必须是对象')
|
||||
details = published if ecosystem == 'npm' else published.get('info')
|
||||
if not isinstance(details, dict): raise AuditBlocked('包发行身份必须是对象')
|
||||
if identity(details.get('name', ''), ecosystem) != identity(package, ecosystem):
|
||||
raise AuditBlocked('上游返回了不同包身份')
|
||||
latest, listed = details.get('version', ''), manifest.get('version', '')
|
||||
row.update(ecosystem=ecosystem, packageName=package, latestVersion=latest, metadataUrl=url)
|
||||
if not all(isinstance(value, str) and VERSION.fullmatch(value) for value in (latest, listed)):
|
||||
return {**row, 'status': 'manual-review-required', 'reason': '预发布、标签或不透明版本需单独复核'}
|
||||
looks_calver = lambda value: bool(re.fullmatch(r'(?:19|20)\d{2}\.\d{1,2}\.\d{1,2}', value))
|
||||
if (version_scheme == 'calver' or (version_scheme is None and looks_calver(listed))) != looks_calver(latest):
|
||||
return {**row, 'status':'version-scheme-mismatch', 'reason':'目录与包注册表的版本体系不同,需核对映射;不自动降级或推进'}
|
||||
if version_scheme == 'opaque' and latest != listed:
|
||||
return {**row, 'status':'manual-review-required', 'reason':'目录版本是不透明标识,不能自动进行数值排序'}
|
||||
latest_key, listed_key = (tuple(map(int, value.split('.'))) for value in (latest, listed))
|
||||
status = 'outdated' if latest_key > listed_key else 'current' if latest_key == listed_key else 'upstream-version-behind'
|
||||
return {**row, 'status': status, 'reason': '只比较公开发行版本,不声称本机已升级', 'metadata': published}
|
||||
|
||||
|
||||
def inspect_archive(body: bytes, ecosystem='npm') -> dict[str, bytes]:
|
||||
files, expanded = {}, 0
|
||||
def accept(name, size, ordinary, reader):
|
||||
nonlocal expanded
|
||||
path = PurePosixPath(name)
|
||||
if path.is_absolute() or '..' in path.parts or '\\' in name or not ordinary:
|
||||
raise AuditBlocked('制品包含不安全路径、链接或特殊节点')
|
||||
if size > MAX_FILE or len(files) >= MAX_FILES or expanded + size > MAX_EXPANDED:
|
||||
raise AuditBlocked('制品超过自动核验展开预算')
|
||||
normalized = path.as_posix()
|
||||
if normalized in files: raise AuditBlocked('制品存在重复文件路径')
|
||||
content = reader()
|
||||
if len(content) != size: raise AuditBlocked('文件实际长度不匹配')
|
||||
files[normalized] = content; expanded += size
|
||||
if ecosystem == 'npm':
|
||||
with tarfile.open(fileobj=io.BytesIO(body), mode='r:gz') as archive:
|
||||
for number, member in enumerate(archive):
|
||||
if number >= MAX_FILES: raise AuditBlocked('制品节点数超过核验预算')
|
||||
path = PurePosixPath(member.name)
|
||||
if member.isdir():
|
||||
if path.is_absolute() or '..' in path.parts or '\\' in member.name: raise AuditBlocked('目录路径不安全')
|
||||
continue
|
||||
if not path.parts or path.parts[0] != 'package' or len(path.parts) < 2:
|
||||
raise AuditBlocked('npm 制品必须以 package/ 为内容根')
|
||||
accept(PurePosixPath(*path.parts[1:]).as_posix(), member.size, member.isfile(), lambda: archive.extractfile(member).read())
|
||||
else:
|
||||
with zipfile.ZipFile(io.BytesIO(body)) as archive:
|
||||
for member in archive.infolist():
|
||||
if member.is_dir(): continue
|
||||
mode = member.external_attr >> 16
|
||||
accept(member.filename, member.file_size, mode & 0o170000 in (0, 0o100000), lambda: archive.read(member))
|
||||
if not files: raise AuditBlocked('制品为空')
|
||||
return files
|
||||
|
||||
|
||||
def evidence(files):
|
||||
result = {}
|
||||
for path, body in files.items():
|
||||
parts = PurePosixPath(path).parts
|
||||
if parts[-1].upper().startswith(('LICENSE', 'NOTICE', 'COPYING')) or any(part.lower() == 'licenses' for part in parts[:-1]):
|
||||
result[path] = hashlib.sha256(body).hexdigest()
|
||||
return result
|
||||
|
||||
|
||||
def package_contract(files, ecosystem):
|
||||
if ecosystem == 'npm':
|
||||
value = json.loads(files['package.json'])
|
||||
if not isinstance(value, dict): raise AuditBlocked('package.json 必须是对象')
|
||||
keys = ('name', 'license', 'dependencies', 'optionalDependencies', 'peerDependencies',
|
||||
'peerDependenciesMeta', 'engines', 'os', 'cpu', 'bin', 'scripts', 'type', 'exports', 'main', 'repository')
|
||||
return {key: value.get(key) for key in keys}, value.get('version')
|
||||
paths = [path for path in files if path.endswith('.dist-info/METADATA')]
|
||||
if len(paths) != 1: raise AuditBlocked('需要唯一的 Python wheel METADATA')
|
||||
metadata = BytesParser().parsebytes(files[paths[0]])
|
||||
keys = ('Name', 'Requires-Python', 'Requires-Dist', 'Provides-Extra', 'License', 'License-Expression', 'Classifier')
|
||||
return {key: sorted(metadata.get_all(key, [])) for key in keys}, metadata.get('Version')
|
||||
|
||||
|
||||
def fixed_artifact(metadata, ecosystem, expected_sha=None):
|
||||
if ecosystem == 'npm':
|
||||
dist = metadata.get('dist', {})
|
||||
if not isinstance(dist, dict): raise AuditBlocked('npm dist 必须是对象')
|
||||
url, integrity = dist.get('tarball'), dist.get('integrity')
|
||||
if not isinstance(integrity, str) or not integrity.startswith('sha512-'):
|
||||
raise AuditBlocked('npm 缺少 SHA-512 integrity 证据')
|
||||
return url, integrity
|
||||
candidates = metadata.get('urls')
|
||||
if not isinstance(candidates, list) or any(not isinstance(item, dict) for item in candidates):
|
||||
raise AuditBlocked('PyPI 制品列表格式不正确')
|
||||
for item in candidates:
|
||||
if not isinstance(item.get('filename'), str) or not isinstance(item.get('digests'), dict):
|
||||
raise AuditBlocked('PyPI 制品名称或摘要格式不正确')
|
||||
if not re.fullmatch('[a-f0-9]{64}', str(item['digests'].get('sha256', ''))):
|
||||
raise AuditBlocked('PyPI 制品缺少有效 SHA-256')
|
||||
artifacts = [item for item in candidates if not item.get('yanked')
|
||||
and item.get('filename', '').endswith('-none-any.whl')
|
||||
and (expected_sha is None or item.get('digests', {}).get('sha256') == expected_sha)]
|
||||
if len(artifacts) != 1:
|
||||
raise AuditBlocked('需要唯一且匹配已审核摘要的通用 Python wheel;平台包需专项复核')
|
||||
return artifacts[0]['url'], 'sha256-' + base64.b64encode(bytes.fromhex(artifacts[0]['digests']['sha256'])).decode()
|
||||
|
||||
|
||||
def verified_artifact(metadata, ecosystem, fetch_bytes, expected_sha=None):
|
||||
url, integrity = fixed_artifact(metadata, ecosystem, expected_sha)
|
||||
# 测试替身也必须满足官方来源约束,不能借注入 fetch 绕过来源规则。
|
||||
parsed = urllib.parse.urlsplit(url or '')
|
||||
host = 'registry.npmjs.org' if ecosystem == 'npm' else 'files.pythonhosted.org'
|
||||
if parsed.scheme != 'https' or parsed.hostname != host or parsed.username or parsed.password or parsed.port not in (None, 443):
|
||||
raise AuditBlocked('固定制品不是对应官方包注册表 HTTPS 地址')
|
||||
body = fetch_bytes(url)
|
||||
if len(body) > MAX_DOWNLOAD: raise AuditBlocked('制品超过下载预算')
|
||||
algorithm, encoded = integrity.split('-', 1)
|
||||
if base64.b64encode(hashlib.new(algorithm, body).digest()).decode() != encoded:
|
||||
raise AuditBlocked('发布摘要与实际制品不一致')
|
||||
digest = hashlib.sha256(body).hexdigest()
|
||||
if expected_sha is not None and digest != expected_sha:
|
||||
raise AuditBlocked('旧包与目录已审核摘要不一致')
|
||||
try:
|
||||
files = inspect_archive(body, ecosystem)
|
||||
except (tarfile.TarError, zipfile.BadZipFile, EOFError) as error:
|
||||
raise AuditBlocked('固定制品格式损坏') from error
|
||||
return files, digest, url
|
||||
|
||||
|
||||
def advance_selector(config, package, old, new, ecosystem):
|
||||
args = config.get('args')
|
||||
separator = '@' if ecosystem == 'npm' else '=='
|
||||
old_values = {package, package + separator + old, package + ('@latest' if ecosystem == 'npm' else '')}
|
||||
if not isinstance(args, list) or sum(arg in old_values for arg in args) != 1:
|
||||
raise AuditBlocked('启动选择器不能唯一绑定当前包,需专项复核')
|
||||
config['args'] = [package + separator + new if arg in old_values else arg for arg in args]
|
||||
|
||||
|
||||
def prepare_update(manifest, sidecar, result, fetch=fetch_json, fetch_bytes=download, observed_at=None):
|
||||
if result.get('status') != 'outdated' or result['listedVersion'] != manifest['version']:
|
||||
raise AuditBlocked('新版检查快照已过期或不支持自动推进')
|
||||
old, new, ecosystem, package = manifest['version'], result['latestVersion'], result['ecosystem'], result['packageName']
|
||||
if ecosystem not in ('npm', 'pypi'):
|
||||
raise AuditBlocked('容器或二进制新版需要固定制品 digest 和许可准入证据;不自动拉取或运行')
|
||||
governance, content = sidecar.get('governance', {}), sidecar.get('provenance', {}).get('content', {})
|
||||
compliance = governance.get('compliance', {})
|
||||
if (governance.get('availability') != 'installable' or governance.get('license', {}).get('state') != 'known'
|
||||
or compliance.get('reviewedRef') != old or not compliance.get('reviewedBy') or not compliance.get('reviewedAt')
|
||||
or content.get('kind') != 'package' or content.get('ref') != old
|
||||
or not re.fullmatch('[0-9a-f]{64}', content.get('sha256', ''))):
|
||||
raise AuditBlocked('旧版本缺少完整准入与固定制品审核证据')
|
||||
expected_url = ('https://www.npmjs.com/package/' + package if ecosystem == 'npm' else 'https://pypi.org/project/' + package + '/')
|
||||
if content.get('url', '').rstrip('/') != expected_url.rstrip('/'):
|
||||
raise AuditBlocked('目录包来源与实际包身份不一致')
|
||||
old_url = (f'https://registry.npmjs.org/{urllib.parse.quote(package, safe="@/")}/{old}'
|
||||
if ecosystem == 'npm' else f'https://pypi.org/pypi/{package}/{old}/json')
|
||||
old_metadata, new_metadata = fetch(old_url), result['metadata']
|
||||
for metadata, version in ((old_metadata, old), (new_metadata, new)):
|
||||
if not isinstance(metadata, dict): raise AuditBlocked('固定版本元数据必须是对象')
|
||||
details = metadata if ecosystem == 'npm' else metadata.get('info')
|
||||
if not isinstance(details, dict): raise AuditBlocked('固定版本包身份必须是对象')
|
||||
if identity(details.get('name', ''), ecosystem) != identity(package, ecosystem) or details.get('version') != version:
|
||||
raise AuditBlocked('固定版本元数据身份不一致')
|
||||
old_files, _, _ = verified_artifact(old_metadata, ecosystem, fetch_bytes, content['sha256'])
|
||||
new_files, digest, artifact_url = verified_artifact(new_metadata, ecosystem, fetch_bytes)
|
||||
old_evidence, new_evidence = evidence(old_files), evidence(new_files)
|
||||
normalize_path = lambda path: re.sub(r'[^/]+\.dist-info/', 'PACKAGE.dist-info/', path, count=1)
|
||||
old_normalized = {normalize_path(path):value for path,value in old_evidence.items()}
|
||||
new_normalized = {normalize_path(path):value for path,value in new_evidence.items()}
|
||||
if not old_evidence or old_normalized != new_normalized:
|
||||
raise AuditBlocked('许可证或第三方 Notice 有变化,不能继承旧审核', {
|
||||
'licenseOrNoticePaths': sorted(path for path in old_normalized.keys() | new_normalized.keys()
|
||||
if old_normalized.get(path) != new_normalized.get(path))
|
||||
})
|
||||
for key in ('licenseEvidencePath', 'noticePath'):
|
||||
if compliance.get(key) and compliance[key] not in old_files:
|
||||
raise AuditBlocked('声明的许可证据文件不存在')
|
||||
evidence_paths = {}
|
||||
for path in {compliance.get('licenseEvidencePath'), compliance.get('noticePath'), governance.get('license', {}).get('evidencePath')} - {None}:
|
||||
matches = [candidate for candidate in new_evidence if normalize_path(candidate) == normalize_path(path)]
|
||||
if path not in old_evidence or len(matches) != 1:
|
||||
raise AuditBlocked('声明的许可证据无法绑定新包文件')
|
||||
evidence_paths[path] = matches[0]
|
||||
old_contract, old_version = package_contract(old_files, ecosystem)
|
||||
new_contract, new_version = package_contract(new_files, ecosystem)
|
||||
declared_name = new_contract.get('name') if ecosystem == 'npm' else (new_contract.get('Name') or [''])[0]
|
||||
if identity(declared_name or '', ecosystem) != identity(package, ecosystem):
|
||||
raise AuditBlocked('制品中的包名称与请求身份不同')
|
||||
if old_version != old or new_version != new or old_contract != new_contract:
|
||||
raise AuditBlocked('包身份、许可、依赖、启动入口或平台要求变化,需要复核')
|
||||
# 版本相关的运行验收说明不能随新包机械继承。
|
||||
presentation = json.dumps(sidecar.get('presentation', {}), ensure_ascii=False)
|
||||
if old in presentation or manifest.get('toolCount') is not None:
|
||||
raise AuditBlocked('版本相关说明或工具数量需要新版证据,不能冒充已完成运行验收')
|
||||
updated, catalog = copy.deepcopy(manifest), copy.deepcopy(sidecar)
|
||||
for config in (updated['install'], updated['connection']):
|
||||
advance_selector(config, package, old, new, ecosystem)
|
||||
updated['version'] = new
|
||||
catalog['release'] = {'state': 'known', 'version': new, 'versionScheme': sidecar['release']['versionScheme']}
|
||||
catalog['provenance']['content'].update(ref=new, sha256=digest)
|
||||
now = observed_at or datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
|
||||
datetime.strptime(now, '%Y-%m-%dT%H:%M:%SZ')
|
||||
catalog['governance']['compliance'].update(reviewedRef=new, reviewedBy=REVIEWER, reviewedAt=now[:10])
|
||||
for key in ('licenseEvidencePath', 'noticePath'):
|
||||
if compliance.get(key): catalog['governance']['compliance'][key] = evidence_paths[compliance[key]]
|
||||
if governance.get('license', {}).get('evidencePath'):
|
||||
catalog['governance']['license']['evidencePath'] = evidence_paths[governance['license']['evidencePath']]
|
||||
catalog.setdefault('timestamps', {}).update({
|
||||
'catalogUpdatedAt': {'state':'known','value':now,'precision':'second'},
|
||||
'upstreamObservedAt': {'state':'known','value':now,'precision':'second'},
|
||||
'reviewedAt': {'state':'known','value':now[:10],'precision':'day'},
|
||||
'releasePublishedAt': {'state':'unknown'},
|
||||
})
|
||||
report = {'schemaVersion':1,'reviewer':REVIEWER,'reviewedAt':now,'entryId':manifest['id'],
|
||||
'previousVersion':old,'version':new,'packageName':package,'ecosystem':ecosystem,
|
||||
'sourceUrl':content['url'],'artifactUrl':artifact_url,'contentSha256':digest,
|
||||
'licenseEvidenceSha256':new_evidence,
|
||||
'checks':{'publishedIntegrity':True,'previousCatalogDigest':True,'boundedOrdinaryFiles':True,
|
||||
'licenseAndNoticeUnchanged':True,'structuredPrerequisitesUnchanged':True,'pinnedLaunchSelectors':True},
|
||||
'limitations':['仅来源、制品、许可和结构化前置条件核验;未执行上游代码、MCP 握手、业务工具或跨平台验收。',
|
||||
'包签名、供应链认证与非结构化行为变化不在本次机械核验范围;不自动合并。']}
|
||||
return updated, catalog, report
|
||||
@@ -0,0 +1,133 @@
|
||||
#!/usr/bin/env python3
|
||||
"""每日发现 MCP 新版;核验通过普通 PR,受阻只提交候选说明草稿。"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from mcp_updates import discover, prepare_update, AuditBlocked
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def run(*args, cwd=ROOT):
|
||||
return subprocess.run(args,cwd=cwd,check=True,capture_output=True,text=True).stdout.strip()
|
||||
|
||||
|
||||
def write_report(rows, destination):
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
public = [{key:value for key,value in row.items() if key != 'metadata'} for row in rows]
|
||||
destination.write_text(json.dumps(public,ensure_ascii=False,indent=2)+'\n')
|
||||
lines=['| MCP | 目录版本 | 上游版本 | 状态 | 说明 |','|---|---|---|---|---|']
|
||||
for row in public:
|
||||
cell=lambda value:str(value or '').replace('|','/').replace('\n',' ')
|
||||
lines.append('| '+' | '.join(cell(row.get(key)) for key in ['id','listedVersion','latestVersion','status','reason'])+' |')
|
||||
destination.with_suffix('.md').write_text('\n'.join(lines)+'\n')
|
||||
|
||||
|
||||
def publish(root, manifest, metadata, result, actor, repository):
|
||||
package = re.sub('[^a-zA-Z0-9_.-]','-',result['latestVersion'])
|
||||
branch = f"updates/mcp-{manifest['id']}-{package}"
|
||||
existing = json.loads(run('gh','pr','list','--repo',repository,'--state','all','--head',branch,'--json','number'))
|
||||
open_prs = json.loads(run('gh','pr','list','--repo',repository,'--state','open','--limit','1000','--json','headRefName'))
|
||||
if existing or any(pr['headRefName'].startswith(f"updates/mcp-{manifest['id']}-") for pr in open_prs):
|
||||
result.update(status='already-proposed',reason='已有候选或同快照记录,保留审核者修改');return False
|
||||
# push 已成功但创建 PR 的网络请求失败时,下一轮恢复待审入口,不覆盖既有分支。
|
||||
try:
|
||||
orphan = run('gh','api',f'repos/{repository}/git/ref/heads/{branch}','--jq','.object.sha')
|
||||
except subprocess.CalledProcessError as error:
|
||||
if '404' not in (error.stderr or ''): raise
|
||||
orphan = ''
|
||||
if orphan:
|
||||
run('gh','pr','create','--repo',repository,'--base','main','--head',branch,'--draft',
|
||||
'--title',f"chore(registry): 恢复 {manifest['id']} 新版候选审核",
|
||||
'--body','发现已有候选分支但没有 PR。仅恢复草稿审核入口,未重新核验分支内容;合并前须复核来源、摘要及目录校验。\n\nRecovered an existing candidate branch as a draft; no new review or auto-merge.')
|
||||
result.update(status='review-blocked',reason='恢复已有候选分支的草稿;未重新核验其内容,不覆盖维护者修改')
|
||||
return True
|
||||
proposal, receipt, reason, findings = None, None, None, {}
|
||||
try:
|
||||
updated, sidecar, receipt = prepare_update(manifest,metadata,result)
|
||||
proposal = (updated,sidecar)
|
||||
except (AuditBlocked, OSError, ValueError, KeyError, RuntimeError) as error:
|
||||
reason=str(error)[:500]
|
||||
findings=getattr(error,'findings',{})
|
||||
with tempfile.TemporaryDirectory(prefix='mcp-update-') as temporary:
|
||||
checkout=Path(temporary)/'checkout'
|
||||
run('git','worktree','add','--detach',str(checkout),'HEAD')
|
||||
try:
|
||||
run('git','switch','-c',branch,cwd=checkout)
|
||||
folder=checkout/'entries'/manifest['id'];paths=[]
|
||||
def write(name,value):
|
||||
(folder/name).write_text(json.dumps(value,ensure_ascii=False,indent=2)+'\n')
|
||||
paths.append(str((folder/name).relative_to(checkout)))
|
||||
if proposal:
|
||||
write('manifest.json',proposal[0]);write('catalog-metadata.v1.json',proposal[1]);write('upstream-audit.v1.json',receipt)
|
||||
try:
|
||||
run('node','scripts/validate-registry.mjs',cwd=checkout)
|
||||
run('node','scripts/catalog/validate-registry.mjs','--require-sidecars',cwd=checkout)
|
||||
except subprocess.CalledProcessError:
|
||||
run('git','restore','--',*paths[:2],cwd=checkout)
|
||||
(folder/'upstream-audit.v1.json').unlink();paths=[];receipt=None
|
||||
reason='目录校验未通过;保留现有版本、审核及运行事实'
|
||||
if not receipt:
|
||||
write('upstream-update-candidate.json',{
|
||||
'schemaVersion':1,'entryId':manifest['id'],'listedVersion':manifest['version'],
|
||||
'observedVersion':result['latestVersion'],'metadataUrl':result['metadataUrl'],
|
||||
'reason':reason,'reviewPassed':False,
|
||||
'findings':findings,
|
||||
'note':'仅候选说明,不修改当前 manifest、sidecar、审核结论或安装状态。',
|
||||
})
|
||||
run('git','add','--',*paths,cwd=checkout)
|
||||
run('git','-c',f'user.name={actor}','-c',f'user.email={actor}@users.noreply.github.com','commit','-m',f"chore(registry): 更新 {manifest['id']} 候选 {result['latestVersion']}",cwd=checkout)
|
||||
run('git','push','origin',f'HEAD:refs/heads/{branch}',cwd=checkout)
|
||||
body=Path(temporary)/'body.md'
|
||||
body.write_text(f"{manifest['id']}: {manifest['version']} → {result['latestVersion']}\n\n"
|
||||
+( '来源、旧摘要、发布摘要、许可与结构化前置条件核验通过,附机器记录。\n' if receipt else '核验受阻:'+str(reason)+'。仅提交候选说明,旧目录与审核不变。\n')
|
||||
+'\n未运行上游安装脚本、MCP 握手或业务工具,不代表安全认证或新版运行验收。不自动合并。\n\n'
|
||||
+'Automated package-source verification only; no upstream execution, runtime/security acceptance or auto-merge.\n')
|
||||
args=['gh','pr','create','--repo',repository,'--base','main','--head',branch,'--title',f"chore(registry): 更新 {manifest['id']} 至 {result['latestVersion']}",'--body-file',str(body)]
|
||||
if not receipt:args.append('--draft')
|
||||
run(*args,cwd=checkout)
|
||||
result.update(status='proposed' if receipt else 'review-blocked',reason=reason or '机器核验通过,已提交普通 PR;未合并或升级用户服务')
|
||||
return True
|
||||
finally:
|
||||
run('git','worktree','remove','--force',str(checkout))
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--publish',action='store_true')
|
||||
parser.add_argument('--limit',type=int,default=5)
|
||||
parser.add_argument('--report',type=Path,default=Path('mcp-upstream-report.json'))
|
||||
args=parser.parse_args()
|
||||
if args.limit<1:parser.error('limit 必须大于零')
|
||||
repository=os.environ.get('GITHUB_REPOSITORY','desirecore/registry');actor=os.environ.get('GITHUB_ACTOR','')
|
||||
if args.publish and (repository!='desirecore/registry' or not re.fullmatch('[A-Za-z0-9-]+',actor)):
|
||||
parser.error('仅允许官方仓库使用触发用户身份发布')
|
||||
rows=[];failed=False;count=0
|
||||
try:
|
||||
for path in sorted((ROOT/'entries').glob('*/manifest.json')):
|
||||
manifest=json.loads(path.read_text())
|
||||
if manifest.get('type')!='mcp':continue
|
||||
try:
|
||||
sidecar_path=path.parent/'catalog-metadata.v1.json'
|
||||
metadata=json.loads(sidecar_path.read_text()) if sidecar_path.exists() else {}
|
||||
result=discover(manifest,version_scheme=metadata.get('release',{}).get('versionScheme'))
|
||||
except (OSError,ValueError,KeyError,RuntimeError) as error:
|
||||
result={'id':manifest['id'],'listedVersion':manifest['version'],'status':'check-failed','reason':str(error)[:300]};failed=True
|
||||
rows.append(result)
|
||||
if result['status']=='outdated' and args.publish and count<args.limit:
|
||||
try:
|
||||
created = publish(ROOT,manifest,metadata,result,actor,repository)
|
||||
if created: count+=1
|
||||
except (OSError,ValueError,KeyError,subprocess.SubprocessError) as error:
|
||||
count+=1
|
||||
result.update(status='publish-failed',reason=str(error)[:300]);failed=True
|
||||
finally:
|
||||
write_report(rows,args.report)
|
||||
if failed:raise SystemExit(1)
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,159 @@
|
||||
"""MCP 来源发现与固定制品审核的相关单文件测试;不执行上游代码。"""
|
||||
import base64
|
||||
import copy
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import tarfile
|
||||
import tempfile
|
||||
import subprocess
|
||||
import unittest
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from mcp_updates import discover, prepare_update, AuditBlocked, inspect_archive, fixed_artifact
|
||||
|
||||
|
||||
def archive(version='1.0.0', dependencies=None, license_text=b'MIT previously reviewed', link=False):
|
||||
manifest={'name':'example-mcp','version':version,'license':'MIT','engines':{'node':'>=22'},'dependencies':dependencies or {'example':'1.0.0'}}
|
||||
output=io.BytesIO()
|
||||
with tarfile.open(fileobj=output,mode='w:gz') as tar:
|
||||
for name,body in {'package/package.json':json.dumps(manifest).encode(),'package/LICENSE':license_text,'package/main.js':b'throw new Error("must not execute")'}.items():
|
||||
info=tarfile.TarInfo(name);info.size=len(body);tar.addfile(info,io.BytesIO(body))
|
||||
if link:
|
||||
info=tarfile.TarInfo('package/alias');info.type=tarfile.SYMTYPE;info.linkname='/etc/passwd';tar.addfile(info)
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
def published(version, body):
|
||||
return {'name':'example-mcp','version':version,'dist':{'tarball':f'https://registry.npmjs.org/example-mcp/-/example-mcp-{version}.tgz','integrity':'sha512-'+base64.b64encode(hashlib.sha512(body).digest()).decode()}}
|
||||
|
||||
|
||||
class McpUpdatesTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.old=archive();self.new=archive('1.1.0')
|
||||
self.manifest={'id':'demo-mcp','name':'Demo','type':'mcp','version':'1.0.0','description':'Example service','install':{'method':'npx','packageName':'example-mcp','command':'npx','args':['--yes','--ignore-scripts','example-mcp@1.0.0']},'connection':{'transport':'stdio','command':'npx','args':['--yes','--ignore-scripts','example-mcp@1.0.0']}}
|
||||
self.sidecar={'identity':{'kind':'service','id':'demo-mcp'},'presentation':{'i18n':{'zh-CN':{'summary':'示例服务'}}},'release':{'state':'known','version':'1.0.0','versionScheme':'semver'},'provenance':{'content':{'kind':'package','url':'https://www.npmjs.com/package/example-mcp','ref':'1.0.0','sha256':hashlib.sha256(self.old).hexdigest(),'path':'package'}},'governance':{'availability':'installable','license':{'state':'known','value':'MIT','evidencePath':'LICENSE'},'redistribution':'allowed','compliance':{'reviewedRef':'1.0.0','reviewedAt':'2026-10-01','reviewedBy':'previous-reviewer','licenseEvidencePath':'LICENSE','upstreamEndorsed':False}},'timestamps':{}}
|
||||
self.documents={'https://registry.npmjs.org/example-mcp/latest':published('1.1.0',self.new),'https://registry.npmjs.org/example-mcp/1.0.0':published('1.0.0',self.old)}
|
||||
self.artifacts={published('1.0.0',self.old)['dist']['tarball']:self.old,published('1.1.0',self.new)['dist']['tarball']:self.new}
|
||||
|
||||
def prepare(self):
|
||||
result=discover(self.manifest,self.documents.__getitem__)
|
||||
return prepare_update(self.manifest,self.sidecar,result,self.documents.__getitem__,self.artifacts.__getitem__,'2026-10-31T08:00:00Z')
|
||||
|
||||
def test_discovers_npm_and_never_executes_the_package(self):
|
||||
result=discover(self.manifest,self.documents.__getitem__)
|
||||
self.assertEqual(result['status'],'outdated');self.assertEqual(result['latestVersion'],'1.1.0')
|
||||
manifest,sidecar,audit=self.prepare()
|
||||
self.assertEqual(manifest['connection']['args'][-1],'example-mcp@1.1.0')
|
||||
self.assertEqual(sidecar['governance']['compliance']['reviewedRef'],'1.1.0')
|
||||
self.assertTrue(sidecar['governance']['compliance']['reviewedBy'].startswith('automated:'))
|
||||
self.assertFalse(sidecar['governance']['compliance']['upstreamEndorsed'])
|
||||
self.assertEqual(audit['contentSha256'],hashlib.sha256(self.new).hexdigest())
|
||||
self.assertNotIn('source',manifest)
|
||||
# Python 实际生成的回执交给 Node 真实共享契约,不用另造成功回执冒充组合验收。
|
||||
with tempfile.TemporaryDirectory() as temporary:
|
||||
payload=Path(temporary)/'receipt.json';payload.write_text(json.dumps({'manifest':manifest,'catalog':sidecar,'receipt':audit}))
|
||||
code="import fs from 'node:fs'; import {validateMcpPackageReview} from './scripts/catalog/automated-mcp-review.mjs'; const p=JSON.parse(fs.readFileSync(process.argv[1],'utf8')); const errors=validateMcpPackageReview(p.manifest,p.catalog,p.receipt); if(errors.length) throw new Error(errors.join(';'));"
|
||||
subprocess.run(['node','--input-type=module','-e',code,str(payload)],cwd=Path(__file__).resolve().parents[2],check=True,capture_output=True,text=True)
|
||||
|
||||
|
||||
def test_current_and_rollback_are_distinct(self):
|
||||
self.documents['https://registry.npmjs.org/example-mcp/latest']=published('1.0.0',self.old)
|
||||
self.assertEqual(discover(self.manifest,self.documents.__getitem__)['status'],'current')
|
||||
self.documents['https://registry.npmjs.org/example-mcp/latest']=published('0.9.0',self.old)
|
||||
self.assertEqual(discover(self.manifest,self.documents.__getitem__)['status'],'upstream-version-behind')
|
||||
|
||||
def test_remote_and_parent_app_are_not_local_updates(self):
|
||||
self.assertEqual(discover({'id':'hosted','type':'mcp','version':'1.0','connection':{'transport':'streamable-http','url':'https://example.com/mcp'}},lambda _:None)['status'],'remote-managed')
|
||||
self.assertEqual(discover({'id':'app','type':'mcp','version':'1.0','sourceAppId':'example','connection':{'transport':'stdio'}},lambda _:None)['status'],'app-managed')
|
||||
|
||||
def test_version_scheme_mismatch_is_not_reported_as_current_or_downgraded(self):
|
||||
manifest={**self.manifest,'version':'2026.1.26'}
|
||||
result=discover(manifest,lambda url:published('2.0.1',self.new),version_scheme='calver')
|
||||
self.assertEqual(result['status'],'version-scheme-mismatch')
|
||||
self.assertEqual(discover(self.manifest,lambda url:published('1.1.0',self.new),version_scheme='opaque')['status'],'manual-review-required')
|
||||
|
||||
def test_malformed_registry_payload_is_a_reportable_audit_block(self):
|
||||
with self.assertRaises(AuditBlocked):discover(self.manifest,lambda url:[])
|
||||
for payload in [{'urls':None},{'urls':[None]},{'urls':[{'filename':'x-none-any.whl','digests':None}]}]:
|
||||
with self.subTest(payload=payload),self.assertRaises(AuditBlocked):fixed_artifact(payload,'pypi')
|
||||
|
||||
def test_changed_license_paths_are_available_for_review_without_copying_sources(self):
|
||||
body=archive('1.1.0',license_text=b'changed terms')
|
||||
self.documents['https://registry.npmjs.org/example-mcp/latest']=published('1.1.0',body)
|
||||
self.artifacts[published('1.1.0',body)['dist']['tarball']]=body
|
||||
with self.assertRaises(AuditBlocked) as raised:self.prepare()
|
||||
self.assertEqual(raised.exception.findings,{'licenseOrNoticePaths':['LICENSE']})
|
||||
|
||||
def test_pypi_discovery_and_unsupported_feed_are_explicit(self):
|
||||
manifest={**self.manifest,'install':{'method':'uvx','packageName':'example-mcp'}}
|
||||
result=discover(manifest,lambda url:{'info':{'name':'example-mcp','version':'1.2.0'},'urls':[]})
|
||||
self.assertEqual(result['latestVersion'],'1.2.0');self.assertEqual(result['ecosystem'],'pypi')
|
||||
manifest['install']={'method':'docker','packageName':'ghcr.io/example/server'}
|
||||
self.assertEqual(discover(manifest,lambda _:None)['status'],'requires-version-feed')
|
||||
|
||||
def test_license_dependency_link_and_digest_changes_block_automatic_approval(self):
|
||||
for body in [archive('1.1.0',license_text=b'new terms'),archive('1.1.0',dependencies={'example':'2'}),archive('1.1.0',link=True)]:
|
||||
with self.subTest(sha=hashlib.sha256(body).hexdigest()):
|
||||
self.new=body;self.documents['https://registry.npmjs.org/example-mcp/latest']=published('1.1.0',body);self.artifacts[published('1.1.0',body)['dist']['tarball']]=body
|
||||
with self.assertRaises(AuditBlocked):self.prepare()
|
||||
self.new=archive('1.1.0');self.documents['https://registry.npmjs.org/example-mcp/latest']=published('1.1.0',self.new)
|
||||
self.artifacts[published('1.1.0',self.new)['dist']['tarball']]=b'corrupt'
|
||||
with self.assertRaises(AuditBlocked):self.prepare()
|
||||
|
||||
def test_listing_only_is_not_promoted(self):
|
||||
self.sidecar['governance']['availability']='listing-only'
|
||||
with self.assertRaisesRegex(AuditBlocked,'准入'):self.prepare()
|
||||
self.assertEqual(self.sidecar['governance']['availability'],'listing-only')
|
||||
|
||||
def test_runtime_claims_need_new_evidence(self):
|
||||
self.sidecar['presentation']['i18n']['zh-CN']['description']='版本 1.0.0 已进行真实运行验收'
|
||||
with self.assertRaisesRegex(AuditBlocked,'版本相关'):self.prepare()
|
||||
|
||||
def test_github_container_feed_is_discovered_without_pulling_images(self):
|
||||
manifest={**self.manifest,'id':'github-mcp','install':{'method':'docker','packageName':'ghcr.io/github/github-mcp-server'}}
|
||||
result=discover(manifest,lambda url:{'tag_name':'v1.2.0'})
|
||||
self.assertEqual(result['status'],'outdated')
|
||||
self.assertEqual(result['ecosystem'],'github-release')
|
||||
with self.assertRaisesRegex(AuditBlocked,'容器'):prepare_update(manifest,self.sidecar,result)
|
||||
|
||||
def test_pypi_wheel_is_verified_and_versioned_license_path_advances(self):
|
||||
def wheel(version,dependency='example==1'):
|
||||
output=io.BytesIO()
|
||||
with zipfile.ZipFile(output,'w') as bundle:
|
||||
bundle.writestr(f'example_mcp-{version}.dist-info/METADATA',f'Name: example-mcp\nVersion: {version}\nLicense: MIT\nRequires-Python: >=3.10\nRequires-Dist: {dependency}\n')
|
||||
bundle.writestr(f'example_mcp-{version}.dist-info/licenses/LICENSE','previously reviewed license')
|
||||
bundle.writestr('example_mcp/main.py','raise Exception("must not execute")')
|
||||
return output.getvalue()
|
||||
def metadata(version,body):
|
||||
return {'info':{'name':'example-mcp','version':version},'urls':[{'filename':f'example_mcp-{version}-py3-none-any.whl','url':f'https://files.pythonhosted.org/example_mcp-{version}-py3-none-any.whl','digests':{'sha256':hashlib.sha256(body).hexdigest()}}]}
|
||||
old,new=wheel('1.0.0'),wheel('1.1.0')
|
||||
manifest=copy.deepcopy(self.manifest)
|
||||
for config in [manifest['install'],manifest['connection']]:config.update(command='uvx',args=['example-mcp==1.0.0'])
|
||||
manifest['install']['method']='uvx'
|
||||
sidecar=copy.deepcopy(self.sidecar)
|
||||
sidecar['provenance']['content'].update(url='https://pypi.org/project/example-mcp/',sha256=hashlib.sha256(old).hexdigest())
|
||||
sidecar['provenance']['content'].pop('path',None)
|
||||
path='example_mcp-1.0.0.dist-info/licenses/LICENSE'
|
||||
sidecar['governance']['license']['evidencePath']=path
|
||||
sidecar['governance']['compliance']['licenseEvidencePath']=path
|
||||
result=discover(manifest,lambda url:metadata('1.1.0',new))
|
||||
result['metadata']=metadata('1.1.0',new)
|
||||
artifacts={metadata('1.0.0',old)['urls'][0]['url']:old,metadata('1.1.0',new)['urls'][0]['url']:new}
|
||||
updated,catalog,receipt=prepare_update(manifest,sidecar,result,lambda url:metadata('1.0.0',old),artifacts.__getitem__)
|
||||
self.assertEqual(updated['connection']['args'],['example-mcp==1.1.0'])
|
||||
self.assertIn('example_mcp-1.1.0.dist-info/licenses/LICENSE',receipt['licenseEvidenceSha256'])
|
||||
self.assertEqual(catalog['governance']['compliance']['licenseEvidencePath'],'example_mcp-1.1.0.dist-info/licenses/LICENSE')
|
||||
# 所需 Python 或依赖变化不能机械继承。
|
||||
changed=wheel('1.1.0',dependency='example==2')
|
||||
result['metadata']=metadata('1.1.0',changed);artifacts[result['metadata']['urls'][0]['url']]=changed
|
||||
with self.assertRaisesRegex(AuditBlocked,'依赖'):prepare_update(manifest,sidecar,result,lambda url:metadata('1.0.0',old),artifacts.__getitem__)
|
||||
|
||||
def test_package_identity_and_foreign_urls_cannot_be_rewritten(self):
|
||||
self.manifest['connection']['args']=['another-package@1.0.0']
|
||||
with self.assertRaises(AuditBlocked):self.prepare()
|
||||
self.manifest['install']['packageName']='https://attacker.invalid/file'
|
||||
self.assertEqual(discover(self.manifest,lambda _:None)['status'],'invalid-package-identity')
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,98 @@
|
||||
"""发布与失败报告的单文件回归;GitHub/Git 使用替身,不发送真实 PR。"""
|
||||
import copy
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
import propose_mcp_updates as publisher
|
||||
from mcp_updates import AuditBlocked
|
||||
|
||||
|
||||
class ProposalTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.manifest={'id':'demo-mcp','type':'mcp','version':'1.0.0'}
|
||||
self.metadata={'governance':{'compliance':{'reviewedRef':'1.0.0','reviewedBy':'previous-reviewer'}}}
|
||||
self.result={'id':'demo-mcp','listedVersion':'1.0.0','latestVersion':'1.1.0','status':'outdated','metadataUrl':'https://registry.npmjs.org/demo-mcp/latest'}
|
||||
|
||||
def publish(self, blocked=False, validation_failure=False):
|
||||
with tempfile.TemporaryDirectory() as temporary:
|
||||
root=Path(temporary);folder=root/'entries/demo-mcp';folder.mkdir(parents=True)
|
||||
(folder/'manifest.json').write_text(json.dumps(self.manifest));(folder/'catalog-metadata.v1.json').write_text(json.dumps(self.metadata))
|
||||
seen={}
|
||||
def run(*args,cwd=None):
|
||||
if args[:3]==('gh','pr','list'):return '[]'
|
||||
if args[:3]==('git','worktree','add'):shutil.copytree(root/'entries',Path(args[4])/'entries')
|
||||
if args[:2]==('git','restore'):
|
||||
shutil.copyfile(folder/'manifest.json',cwd/'entries/demo-mcp/manifest.json')
|
||||
shutil.copyfile(folder/'catalog-metadata.v1.json',cwd/'entries/demo-mcp/catalog-metadata.v1.json')
|
||||
if args[0]=='node' and validation_failure:raise subprocess.CalledProcessError(1,args)
|
||||
if args[:3]==('gh','pr','create'):
|
||||
seen['draft']='--draft' in args
|
||||
seen['manifest']=json.loads((cwd/'entries/demo-mcp/manifest.json').read_text())
|
||||
seen['metadata']=json.loads((cwd/'entries/demo-mcp/catalog-metadata.v1.json').read_text())
|
||||
seen['candidate']=(cwd/'entries/demo-mcp/upstream-update-candidate.json').exists()
|
||||
return ''
|
||||
updated={**self.manifest,'version':'1.1.0'}
|
||||
with patch.object(publisher,'ROOT',root),patch.object(publisher,'run',side_effect=run),patch.object(publisher,'prepare_update',return_value=(updated,self.metadata,{'reviewer':'automated:test'}),side_effect=AuditBlocked('license changed') if blocked else None):
|
||||
result=copy.deepcopy(self.result)
|
||||
self.assertTrue(publisher.publish(root,self.manifest,self.metadata,result,'fixture-user','desirecore/registry'))
|
||||
seen['result']=result
|
||||
return seen
|
||||
|
||||
def test_successful_audit_and_validators_open_a_normal_pr(self):
|
||||
result=self.publish();self.assertFalse(result['draft']);self.assertFalse(result['candidate']);self.assertEqual(result['manifest']['version'],'1.1.0')
|
||||
|
||||
def test_blocked_audit_only_opens_a_candidate_draft_without_changing_old_facts(self):
|
||||
result=self.publish(blocked=True);self.assertTrue(result['draft']);self.assertTrue(result['candidate'])
|
||||
self.assertEqual(result['manifest'],self.manifest);self.assertEqual(result['metadata'],self.metadata)
|
||||
self.assertEqual(result['result']['status'],'review-blocked')
|
||||
|
||||
def test_failed_catalog_validation_restores_old_metadata_before_draft(self):
|
||||
result=self.publish(validation_failure=True);self.assertTrue(result['draft']);self.assertEqual(result['manifest'],self.manifest)
|
||||
|
||||
def test_existing_branch_without_pr_is_recovered_as_a_draft_without_overwriting(self):
|
||||
calls=[]
|
||||
def run(*args,**kwargs):
|
||||
calls.append(args)
|
||||
if args[:3]==('gh','pr','list'):return '[]'
|
||||
if args[:2]==('gh','api'):return 'a'*40
|
||||
return ''
|
||||
with patch.object(publisher,'run',side_effect=run),patch.object(publisher,'prepare_update') as prepare:
|
||||
result=copy.deepcopy(self.result)
|
||||
self.assertTrue(publisher.publish(Path('/unused'),self.manifest,self.metadata,result,'fixture-user','desirecore/registry'))
|
||||
self.assertTrue(any(args[:3]==('gh','pr','create') and '--draft' in args for args in calls))
|
||||
self.assertFalse(any(args[0]=='git' for args in calls))
|
||||
prepare.assert_not_called()
|
||||
|
||||
def test_existing_candidates_do_not_consume_the_daily_new_candidate_budget(self):
|
||||
with tempfile.TemporaryDirectory() as temporary:
|
||||
root=Path(temporary)
|
||||
for name in ['a-mcp','b-mcp']:
|
||||
folder=root/'entries'/name;folder.mkdir(parents=True)
|
||||
(folder/'manifest.json').write_text(json.dumps({**self.manifest,'id':name}))
|
||||
(folder/'catalog-metadata.v1.json').write_text(json.dumps(self.metadata))
|
||||
calls=[]
|
||||
def publish(*args):
|
||||
calls.append(args[1]['id']);return len(calls)>1
|
||||
with patch.object(publisher,'ROOT',root),patch.object(publisher,'discover',side_effect=lambda item,**kwargs:{**self.result,'id':item['id']}),patch.object(publisher,'publish',side_effect=publish),patch.dict(os.environ,{'GITHUB_REPOSITORY':'desirecore/registry','GITHUB_ACTOR':'fixture-user'}),patch('sys.argv',['propose','--publish','--limit','1','--report',str(root/'report.json')]):
|
||||
publisher.main()
|
||||
self.assertEqual(calls,['a-mcp','b-mcp'])
|
||||
|
||||
def test_check_failure_is_reported_and_other_sources_still_run(self):
|
||||
with tempfile.TemporaryDirectory() as temporary:
|
||||
root=Path(temporary)
|
||||
for name in ['a-mcp','b-mcp']:
|
||||
folder=root/'entries'/name;folder.mkdir(parents=True)
|
||||
(folder/'manifest.json').write_text(json.dumps({**self.manifest,'id':name}))
|
||||
with patch.object(publisher,'ROOT',root),patch.object(publisher,'discover',side_effect=[OSError('offline'),{'id':'b-mcp','status':'remote-managed'}]),patch('sys.argv',['propose','--report',str(root/'report.json')]):
|
||||
with self.assertRaises(SystemExit):publisher.main()
|
||||
rows=json.loads((root/'report.json').read_text())
|
||||
self.assertEqual([row['status'] for row in rows],['check-failed','remote-managed'])
|
||||
self.assertTrue((root/'report.md').is_file())
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -4,7 +4,7 @@ import { fileURLToPath } from 'node:url'
|
||||
import Ajv from 'ajv'
|
||||
import { findStaticMetrics } from './catalog/static-metadata.mjs'
|
||||
import { validateApplicationContract } from './catalog/application-contract.mjs'
|
||||
import { validateApplicationReleaseContract } from './catalog/application-release-contract.mjs'
|
||||
import { AUTHORED_ENTRY_SCHEMA_FILENAME, isAuthoredRegistryEntry } from './catalog/entry-schema.mjs'
|
||||
|
||||
const scriptDirectory = dirname(fileURLToPath(import.meta.url))
|
||||
const rootArgumentIndex = process.argv.indexOf('--root')
|
||||
@@ -282,6 +282,7 @@ const validateExternalIntegration = async (entryDirectory, manifest) => {
|
||||
const schemaVersion = (await readText(join(repositoryRoot, 'SCHEMA_VERSION')))?.trim()
|
||||
const rootManifest = await readJson(join(repositoryRoot, 'manifest.json'))
|
||||
const entrySchema = await readJson(join(repositoryRoot, 'schemas', 'registry-entry.schema.json'))
|
||||
const authoredEntrySchema = await readJson(join(repositoryRoot, 'schemas', AUTHORED_ENTRY_SCHEMA_FILENAME))
|
||||
|
||||
if (!schemaVersion || !/^\d+\.\d+\.\d+$/.test(schemaVersion)) {
|
||||
addError('SCHEMA_VERSION: expected a semantic version')
|
||||
@@ -291,16 +292,22 @@ if (rootManifest) {
|
||||
if (rootManifest.dataVersion !== schemaVersion) addError('manifest.json#dataVersion must equal SCHEMA_VERSION')
|
||||
}
|
||||
|
||||
let validateEntry = null
|
||||
if (entrySchema) {
|
||||
const compileEntrySchema = (schema, filename) => {
|
||||
if (schema === null || Array.isArray(schema) || !['object', 'boolean'].includes(typeof schema)) {
|
||||
addError(`schemas/${filename}: Schema root must be an object or boolean`)
|
||||
return null
|
||||
}
|
||||
try {
|
||||
// Draft-07 条件块补充父 Schema 的约束;无需在每个 then/not 再写局部 type。
|
||||
const ajv = new Ajv({ allErrors: true, strict: true, strictTypes: false, strictRequired: false, validateFormats: false })
|
||||
validateEntry = ajv.compile(entrySchema)
|
||||
return ajv.compile(schema)
|
||||
} catch (error) {
|
||||
addError(`schemas/registry-entry.schema.json: unable to compile (${error.message})`)
|
||||
addError(`schemas/${filename}: unable to compile (${error.message})`)
|
||||
return null
|
||||
}
|
||||
}
|
||||
const validateEntry = compileEntrySchema(entrySchema, 'registry-entry.schema.json')
|
||||
const validateAuthoredEntry = compileEntrySchema(authoredEntrySchema, AUTHORED_ENTRY_SCHEMA_FILENAME)
|
||||
|
||||
const manifests = []
|
||||
const seenIds = new Set()
|
||||
@@ -345,11 +352,11 @@ for (const directoryEntry of await readdir(entriesRoot, { withFileTypes: true })
|
||||
}
|
||||
}
|
||||
|
||||
if (validateEntry && !validateEntry(manifest)) {
|
||||
addError(`entries/${directoryEntry.name}/manifest.json: ${formatAjvErrors(validateEntry.errors)}`)
|
||||
const validateManifest = isAuthoredRegistryEntry(manifest) ? validateAuthoredEntry : validateEntry
|
||||
if (validateManifest && !validateManifest(manifest)) {
|
||||
addError(`entries/${directoryEntry.name}/manifest.json: ${formatAjvErrors(validateManifest.errors)}`)
|
||||
}
|
||||
for (const message of validateApplicationContract(manifest)) addError(`entries/${directoryEntry.name}/manifest.json: ${message}`)
|
||||
for (const message of validateApplicationReleaseContract(manifest)) addError(`entries/${directoryEntry.name}/manifest.json: ${message}`)
|
||||
if (manifest.type === 'external-integration') {
|
||||
await validateExternalIntegration(entryDirectory, manifest)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user