feat: 上架视频剪辑固定材料与作者契约

This commit is contained in:
yige committed 2026-11-02 21:52:36 +08:00
1 parent 9577e9a411
commit eef65008eb
18 files changed
+5658 -198

No files matched your search

+146
View File
@@ -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, 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'))
})
+32 -1
View File
@@ -1,7 +1,32 @@
import { isApplicationEntry, isAuthoredRegistryEntry } from './entry-schema.mjs'
/** 发布者关系声明的跨字段检查;不推导安装、权限或运行时健康。 */
export function validateApplicationContract(manifest) {
if (!['docker-app', 'native-app', 'artifact'].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')
}
const ids = new Set()
for (const entrypoint of Array.isArray(manifest.entrypoints) ? manifest.entrypoints : []) {
if (!entrypoint || typeof entrypoint !== 'object') continue
@@ -18,3 +43,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 !== '..')
}
+10
View File
@@ -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)
}
+7
View File
@@ -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)) {
+22 -10
View File
@@ -4,6 +4,7 @@ import { basename, join, relative, resolve, sep } from 'node:path'
import { validateJsonSchema } from './json-schema.mjs'
import { findStaticMetrics } from './static-metadata.mjs'
import { validateApplicationContract } from './application-contract.mjs'
import { AUTHORED_ENTRY_SCHEMA_FILENAME, isApplicationEntry, isAuthoredRegistryEntry } from './entry-schema.mjs'
export const CATALOG_SIDECAR_FILENAME = 'catalog-metadata.v1.json'
@@ -33,6 +34,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' &&
@@ -77,7 +87,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'].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}`)
@@ -140,7 +150,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'].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 的治理事实必须一致')
}
@@ -205,15 +215,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 不能为空'))
@@ -240,8 +251,9 @@ 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'].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))
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 重复'))
@@ -259,7 +271,7 @@ 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))
}
+15 -6
View File
@@ -4,6 +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 { AUTHORED_ENTRY_SCHEMA_FILENAME, isAuthoredRegistryEntry } from './catalog/entry-schema.mjs'
const scriptDirectory = dirname(fileURLToPath(import.meta.url))
const rootArgumentIndex = process.argv.indexOf('--root')
@@ -281,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')
@@ -290,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()
@@ -344,8 +352,9 @@ 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}`)
if (manifest.type === 'external-integration') {