diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a5995b6..7244c01 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,9 +1,10 @@ name: CI on: - pull_request: push: branches: [main] + pull_request: + workflow_dispatch: jobs: validate: @@ -19,3 +20,4 @@ jobs: - run: pnpm check - run: pnpm test - run: pnpm validate + - run: pnpm aggregate diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 9aad2b0..cbde982 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -1,65 +1,185 @@ name: Publish -# Aggregates plugins/ into dist/plugins.json and uploads it (plus assets/) -# to the motrix-registry R2 bucket served by dl.motrix.app/registry/*. -# Uploads use the S3-compatible API so the credentials can stay scoped to -# this one bucket (Object Read & Write) — wrangler's REST path would need -# an account-wide Admin token (cloudflare/workers-sdk#9235). -# Requires repo secrets: R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, -# CLOUDFLARE_ACCOUNT_ID. - on: push: branches: [main] workflow_dispatch: +permissions: + contents: read + concurrency: - group: publish + group: registry-production cancel-in-progress: false +defaults: + run: + shell: bash + jobs: - publish: + candidate: + name: Build and verify registry v2 runs-on: ubuntu-latest - environment: plugin-publishing + timeout-minutes: 20 + outputs: + sha256: ${{ steps.inspect.outputs.sha256 }} + bytes: ${{ steps.inspect.outputs.bytes }} + artifact_id: ${{ steps.upload.outputs.artifact-id }} + artifact_sha256: ${{ steps.upload.outputs.artifact-digest }} steps: - - uses: actions/checkout@v7 - - uses: pnpm/action-setup@v6 - - uses: actions/setup-node@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9 + - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 with: node-version: 24 cache: pnpm + - name: Require current main + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + test "$GITHUB_REF" = refs/heads/main + test "$(git rev-parse HEAD)" = "$GITHUB_SHA" + test "$(gh api "repos/$GITHUB_REPOSITORY/git/ref/heads/main" --jq .object.sha)" = "$GITHUB_SHA" - run: pnpm install --frozen-lockfile + - run: pnpm check + - run: pnpm test - run: pnpm validate - run: pnpm aggregate - - - name: Upload plugins.json to R2 + - name: Record exact candidate bytes + id: inspect + run: | + set -euo pipefail + pnpm exec tsx scripts/registry-artifact.ts dist/plugins.json > "$RUNNER_TEMP/registry-identity.json" + jq -r '"sha256=\(.sha256)", "bytes=\(.bytes)"' "$RUNNER_TEMP/registry-identity.json" >> "$GITHUB_OUTPUT" + { + echo "Registry source: $GITHUB_SHA" + echo 'Candidate identity:' + cat "$RUNNER_TEMP/registry-identity.json" + } >> "$GITHUB_STEP_SUMMARY" + - name: Upload the raw registry candidate + id: upload + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + path: dist/plugins.json + archive: false + if-no-files-found: error + retention-days: 90 + - name: Bind uploaded artifact to the validated bytes env: - AWS_ACCESS_KEY_ID: ${{ secrets.R2_ACCESS_KEY_ID }} - AWS_SECRET_ACCESS_KEY: ${{ secrets.R2_SECRET_ACCESS_KEY }} - AWS_REGION: auto - # R2 predates the aws CLI v2.23 default integrity checksums - AWS_REQUEST_CHECKSUM_CALCULATION: when_required - AWS_RESPONSE_CHECKSUM_VALIDATION: when_required - R2_ENDPOINT: https://${{ secrets.CLOUDFLARE_ACCOUNT_ID }}.r2.cloudflarestorage.com - run: > - aws s3api put-object - --endpoint-url "$R2_ENDPOINT" - --bucket motrix-registry - --key plugins.json - --body dist/plugins.json - --content-type "application/json; charset=utf-8" + EXPECTED_SHA: ${{ steps.inspect.outputs.sha256 }} + ARTIFACT_SHA: ${{ steps.upload.outputs.artifact-digest }} + run: test "$ARTIFACT_SHA" = "$EXPECTED_SHA" - - name: Upload assets to R2 + publish: + name: Approve and publish the verified registry + needs: candidate + runs-on: ubuntu-latest + timeout-minutes: 20 + environment: plugin-publishing + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9 + - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: 24 + cache: pnpm + - run: pnpm install --frozen-lockfile --ignore-scripts + - name: Download only the approved artifact id + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + artifact-ids: ${{ needs.candidate.outputs.artifact_id }} + path: ${{ runner.temp }}/registry-candidate + skip-decompress: true + digest-mismatch: error + - name: Recheck artifact identity and source after approval env: + GH_TOKEN: ${{ github.token }} + EXPECTED_SHA: ${{ needs.candidate.outputs.sha256 }} + EXPECTED_BYTES: ${{ needs.candidate.outputs.bytes }} + ARTIFACT_SHA: ${{ needs.candidate.outputs.artifact_sha256 }} + run: | + set -euo pipefail + test "$GITHUB_REF" = refs/heads/main + test "$(git rev-parse HEAD)" = "$GITHUB_SHA" + test "$ARTIFACT_SHA" = "$EXPECTED_SHA" + test "$(gh api "repos/$GITHUB_REPOSITORY/git/ref/heads/main" --jq .object.sha)" = "$GITHUB_SHA" + pnpm exec tsx scripts/registry-artifact.ts \ + "$RUNNER_TEMP/registry-candidate/plugins.json" "$EXPECTED_SHA" "$EXPECTED_BYTES" + - name: Back up, conditionally publish, and verify R2 + env: + GH_TOKEN: ${{ github.token }} AWS_ACCESS_KEY_ID: ${{ secrets.R2_ACCESS_KEY_ID }} AWS_SECRET_ACCESS_KEY: ${{ secrets.R2_SECRET_ACCESS_KEY }} AWS_REGION: auto AWS_REQUEST_CHECKSUM_CALCULATION: when_required AWS_RESPONSE_CHECKSUM_VALIDATION: when_required R2_ENDPOINT: https://${{ secrets.CLOUDFLARE_ACCOUNT_ID }}.r2.cloudflarestorage.com + EXPECTED_SHA: ${{ needs.candidate.outputs.sha256 }} + EXPECTED_BYTES: ${{ needs.candidate.outputs.bytes }} run: | + set -euo pipefail + candidate="$RUNNER_TEMP/registry-candidate/plugins.json" + previous="$RUNNER_TEMP/registry-previous.json" + # Fail before writes if this runner's AWS CLI lacks conditional PutObject. + aws s3api put-object --generate-cli-skeleton input > "$RUNNER_TEMP/put-object-input.json" + jq -e 'has("IfMatch") and has("IfNoneMatch")' "$RUNNER_TEMP/put-object-input.json" > /dev/null + aws s3api get-object --endpoint-url "$R2_ENDPOINT" \ + --bucket motrix-registry --key plugins.json "$previous" > "$RUNNER_TEMP/previous-object.json" + previous_etag="$(jq -er '.ETag' "$RUNNER_TEMP/previous-object.json")" + pnpm exec tsx scripts/registry-artifact.ts "$previous" > "$RUNNER_TEMP/previous-identity.json" + previous_sha="$(jq -er '.sha256' "$RUNNER_TEMP/previous-identity.json")" + backup_key="private/backups/plugins/${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}-${previous_sha}.json" + aws s3api put-object --endpoint-url "$R2_ENDPOINT" \ + --bucket motrix-registry --key "$backup_key" --body "$previous" \ + --if-none-match '*' --content-type 'application/json; charset=utf-8' > "$RUNNER_TEMP/backup-object.json" + aws s3api get-object --endpoint-url "$R2_ENDPOINT" \ + --bucket motrix-registry --key "$backup_key" "$RUNNER_TEMP/backup-readback.json" > /dev/null + cmp "$previous" "$RUNNER_TEMP/backup-readback.json" + # Recheck main and the exact candidate immediately before replacing the live key. + test "$(gh api "repos/$GITHUB_REPOSITORY/git/ref/heads/main" --jq .object.sha)" = "$GITHUB_SHA" + pnpm exec tsx scripts/registry-artifact.ts "$candidate" "$EXPECTED_SHA" "$EXPECTED_BYTES" if [ -d assets ]; then - aws s3 sync assets/ "s3://motrix-registry/assets/" --endpoint-url "$R2_ENDPOINT" - else - echo "no assets directory; skipping" + aws s3 sync assets/ s3://motrix-registry/assets/ \ + --endpoint-url "$R2_ENDPOINT" --no-follow-symlinks fi + test "$(gh api "repos/$GITHUB_REPOSITORY/git/ref/heads/main" --jq .object.sha)" = "$GITHUB_SHA" + aws s3api put-object --endpoint-url "$R2_ENDPOINT" \ + --bucket motrix-registry --key plugins.json --body "$candidate" \ + --if-match "$previous_etag" --content-type 'application/json; charset=utf-8' > "$RUNNER_TEMP/published-object.json" + published_etag="$(jq -er '.ETag' "$RUNNER_TEMP/published-object.json")" + aws s3api get-object --endpoint-url "$R2_ENDPOINT" \ + --bucket motrix-registry --key plugins.json --if-match "$published_etag" \ + "$RUNNER_TEMP/published-readback.json" > /dev/null + pnpm exec tsx scripts/registry-artifact.ts \ + "$RUNNER_TEMP/published-readback.json" "$EXPECTED_SHA" "$EXPECTED_BYTES" + { + echo "Published registry source: $GITHUB_SHA" + echo "SHA-256: $EXPECTED_SHA" + echo "Bytes: $EXPECTED_BYTES" + echo "Previous object backup: $backup_key" + echo "Published ETag: $published_etag" + echo 'The website remains a separate manual deployment.' + } >> "$GITHUB_STEP_SUMMARY" + - name: Verify the public registry + env: + EXPECTED_SHA: ${{ needs.candidate.outputs.sha256 }} + EXPECTED_BYTES: ${{ needs.candidate.outputs.bytes }} + run: | + set -euo pipefail + for attempt in $(seq 1 10); do + if curl --fail --silent --show-error --max-time 15 --max-filesize 4194304 \ + "https://dl.motrix.app/registry/plugins.json?sha256=$EXPECTED_SHA" \ + --output "$RUNNER_TEMP/public-registry.json" && + pnpm exec tsx scripts/registry-artifact.ts \ + "$RUNNER_TEMP/public-registry.json" "$EXPECTED_SHA" "$EXPECTED_BYTES"; then + exit 0 + fi + if [ "$attempt" -lt 10 ]; then sleep 5; fi + done + echo 'R2 was updated and verified, but the public endpoint has not converged. Inspect the release before retrying.' >&2 + exit 1 diff --git a/.github/workflows/registry-entry-update.yml b/.github/workflows/registry-entry-update.yml index 7244cbd..c23f492 100644 --- a/.github/workflows/registry-entry-update.yml +++ b/.github/workflows/registry-entry-update.yml @@ -67,7 +67,11 @@ jobs: PLUGIN_TAG: ${{ steps.in.outputs.tag }} run: pnpm entry:from-release "$PLUGIN_ID" "$PLUGIN_TAG" - name: Self-gate - run: pnpm validate && pnpm test + run: | + pnpm check + pnpm test + pnpm validate + pnpm aggregate # Prefer a GitHub App token for the PR so it TRIGGERS this repo's # on:pull_request CI (a GITHUB_TOKEN-created PR does not, by GitHub's # anti-recursion rule). Requires the App to also have Pull requests: diff --git a/CLAUDE.md b/CLAUDE.md index a1bcba5..7c9a562 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -14,15 +14,46 @@ in-app marketplace. ## Hard rules - **`schema/registry.ts` is the wire-contract source of truth.** Consumers - vendor byte-identical copies of the schema and of - `schema/registry.fixture.json`. Any wire-shape change must land in - lockstep with all consumers in the same PR cycle, and is additive-only — - never rename, retype, or remove a published field. + vendor wire-equivalent tolerant schemas/resolvers and byte-identical copies + of `schema/registry.fixture.json` and + `schema/registry.conformance.json`. Corpus channels are independent: + every consumer runs `wireExpected`, only this publisher runs + `authoringExpected`, and App/website run `resolverExpected`. +- Registry v2 is already published and evolves additively. Never rename, + retype, or remove a published field, endpoint, root version, or public + filename. +- Consumer parsing is tolerant: safe profile locale tags, future category + slugs, and unknown object fields survive parsing, except the known v1 + localized plugin-root fields `name`, `description`, and `features`, which are + rejected explicitly. Publisher source is strict at every controlled object + layer, pins canonical `Intl` locale spelling, and currently requires + `listing.defaultLocale === "en-US"`. Never use the strict authoring schema in + a consumer. +- Marketplace listing locales are open BCP 47 data and are independent of App + resource `SupportedLocale`. Do not add fixed language properties or bind + listing resolution to a runtime UI-locale enum. Adding `ja-JP` must remain + a data-only change. +- Before a formal App/website release, run the shared resolver corpus in the + exact shipping Electron and browser runtimes and record their ICU/CLDR + versions. `Intl.Locale.maximize()` divergence is release-blocking even when + the Node publisher suite passes. - Policy (what may merge HERE) lives in `scripts/lib.ts` `validateEntry`, not in the wire schema: `motrix.*` namespace is builtin-only, community entries need a `package` pointer from the URL allowlist, categories must be registered, assets live under `https://dl.motrix.app/registry/assets//`. +- Do not hand-edit or commit `dist/plugins.json`. Aggregation must keep the + stable `dist/plugins.json` filename, public URL, R2 `plugins.json` key, + root `version: 2`, sorted ids, final newline, and 4 MiB UTF-8 byte gate. +- The website is deployed manually from its local repository. Registry + publication must not require a website GitHub repository or website deploy + credentials. Keep the registry URL and v2 contract compatible with both + consumers. +- Build and validate the registry before the `plugin-publishing` environment + approval. Publish only those exact immutable artifact bytes, verify their + SHA-256 and schema after download, and reject a superseded `main` commit. + Back up the previous object and conditionally replace it using its observed + ETag; verify the uploaded bytes. Never rebuild or re-aggregate after approval. ## Commands @@ -33,3 +64,14 @@ pnpm test # vitest (fixture lockstep + policy tests) pnpm validate # CI gate over plugins/ pnpm aggregate # build dist/plugins.json ``` + +Run all four before handing off. `pnpm test` also exercises the immutable +registry artifact validation used by the publish workflow. + +## Documentation + +Keep maintainer runbooks and private rollout plans in the configured Obsidian +documentation workspace, using the project's `pnpm run docs -- ...` gateway. +Do not add them to this public repository unless the user explicitly requests +a public document. Public documentation describes the reviewed wire and +release contracts without private deployment records or local paths. diff --git a/README.md b/README.md index 4eb6796..b4993d1 100644 --- a/README.md +++ b/README.md @@ -10,9 +10,10 @@ https://dl.motrix.app/registry/plugins.json ``` Two peer consumers read that file: the [motrix.app/plugins](https://motrix.app/plugins) -directory and the in-app marketplace of Motrix itself. New plugins go live -for both the moment the publish workflow finishes — no website or app -release required. +directory and the in-app marketplace of Motrix itself. A merge builds a +validated registry candidate; publication waits for the `plugin-publishing` +environment approval. The website is built and deployed separately by its +maintainer. This workflow publishes only registry data and assets. ## Submitting a plugin @@ -25,8 +26,25 @@ release required. 3. Icons/screenshots are optional. Put files under `assets//` and reference them by their published URL: `https://dl.motrix.app/registry/assets//`. -4. Open a PR. CI runs `pnpm validate` (schema + policy: id namespace, - package allowlist, registered categories, asset prefixes). A maintainer +4. Put editorial text under `listing`. Publisher policy currently requires + `defaultLocale: "en-US"`; that default record must contain `name` and + `description`. Other canonical BCP 47 keys may be sparse: + + ```json + { + "listing": { + "defaultLocale": "en-US", + "localizations": { + "en-US": { "name": "Example", "description": "Example plugin" }, + "zh-CN": { "name": "示例" }, + "ja-JP": { "description": "サンプルプラグイン" } + } + } + } + ``` + +5. Open a PR. CI runs typecheck, tests, validation, aggregation, and the final + UTF-8 artifact-size gate. A maintainer review is the trust gate — the registry pins your package hash, so any new release needs a version-bump PR. @@ -34,8 +52,11 @@ Rules enforced by CI: - `id` is dot-namespaced lowercase (`author.plugin-name`); `motrix.*` is reserved for builtin plugins. -- `name`/`description` carry at least English; add `zh` if you can — - consumers fall back to `en` automatically. +- Locale keys are canonical BCP 47 tags without extensions/private use. + Adding a language such as `ja-JP` is data-only and requires no schema edit. + Consumers resolve each field independently through exact, structural parent, + inferred language-script, language, then default fallback; an explicit empty + list is an intentional override. - `categories` must be registered in `schema/registry.ts` (PR a new slug first if none fits). - Permission fields are a **preview** for the install consent screen; the @@ -44,25 +65,39 @@ Rules enforced by CI: ## How publishing works -Merges to `main` trigger `.github/workflows/publish.yml`: -validate → aggregate (`dist/plugins.json`, stamped with `generatedAt`) → -upload to the `motrix-registry` R2 bucket, together with `assets/`. -Consumers cache the file with ETags and keep a last-good copy, so a bad -deploy can never blank the directory. +Merges to `main` run `check → test → validate → aggregate` before approval. +The workflow uploads the exact `plugins.json` bytes as an immutable artifact +and records its SHA-256, size, artifact id, and source commit. After approval, +it downloads that artifact by id and verifies the bytes and v2 schema without +rebuilding. + +The publisher rejects a superseded `main` commit, backs up the previous R2 +object, uploads referenced assets from the reviewed commit, and replaces the +stable `plugins.json` key only if its observed ETag still matches. It checks +both the R2 readback and public endpoint against the approved SHA-256. The +website remains a separate manual deployment; no website repository or deploy +credentials are required by this workflow. ## Contract & lockstep -The wire schema in `schema/registry.ts` is the **source of truth**; -consumers vendor byte-identical copies of the schema and of -`schema/registry.fixture.json`. Changing the wire shape means updating -every consumer in the same PR cycle, and evolution is additive-only: -never rename, retype, or remove a published field. +The tolerant wire schema and resolver in `schema/registry.ts` are the +**source of truth**. Consumers vendor wire-equivalent implementations plus +byte-identical copies of `schema/registry.fixture.json` and +`schema/registry.conformance.json`. The strict publisher-authoring schema is +deliberately narrower and is not a consumer contract. Even tolerant v2 +consumers reject the known v1 plugin-root fields `name`, `description`, and +`features`, while unrelated future fields remain preserved. Registry v2 +evolution is additive-only: never rename, retype, or remove a published field. ## Development ```bash pnpm install -pnpm test # fixture lockstep + entry policy tests +pnpm check # TypeScript +pnpm test # schema, corpus, policy, aggregation, release artifact integrity pnpm validate # what CI runs against plugins/ pnpm aggregate # build dist/plugins.json locally ``` + +Do not hand-edit or commit `dist/plugins.json`. The public URL, root +`version: 2`, R2 key `plugins.json`, and output filename remain stable. diff --git a/README.zh-CN.md b/README.zh-CN.md index a7f56a4..d7d8098 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -10,8 +10,9 @@ https://dl.motrix.app/registry/plugins.json ``` 有两个对等的消费方读取该文件:[motrix.app/plugins](https://motrix.app/plugins) -插件目录和 Motrix 应用内的插件市场。publish workflow 完成的那一刻,新插件 -即在两端同时上线——无需等待官网或 App 发版。 +插件目录和 Motrix 应用内的插件市场。合并后会构建经过校验的注册表产物, +通过 `plugin-publishing` 环境审批后才发布。官网仍由维护者单独构建和手动部署; +本仓库的工作流只发布注册表数据与资源。 ## 提交插件 @@ -23,8 +24,25 @@ https://dl.motrix.app/registry/plugins.json Motrix 在解包前校验哈希,不匹配会直接拒绝。 3. 图标 / 截图可选。文件放在 `assets/<你的插件id>/` 下,并以发布后的 URL 引用:`https://dl.motrix.app/registry/assets/<你的插件id>/<文件名>`。 -4. 提交 PR。CI 会运行 `pnpm validate`(schema + 策略:id 命名空间、 - package 地址白名单、已注册的 categories、资产路径前缀)。maintainer +4. 编辑文案统一放在 `listing` 下。当前 publisher 策略要求 + `defaultLocale: "en-US"`;default record 必须包含 `name` 与 + `description`,其他 canonical BCP 47 locale 可以只提供部分字段: + + ```json + { + "listing": { + "defaultLocale": "en-US", + "localizations": { + "en-US": { "name": "Example", "description": "Example plugin" }, + "zh-CN": { "name": "示例" }, + "ja-JP": { "description": "サンプルプラグイン" } + } + } + } + ``` + +5. 提交 PR。CI 会运行 typecheck、test、validate、aggregate 与最终 UTF-8 + 产物大小闸门。maintainer review 是信任关卡——registry 会锁定你的包哈希,因此每次发布新版本 都需要一个 bump 版本号的 PR。 @@ -32,8 +50,10 @@ CI 强制执行的规则: - `id` 为点分隔的小写命名(`author.plugin-name`);`motrix.*` 命名空间 保留给 builtin 插件。 -- `name` / `description` 至少提供英文;有条件请补充 `zh`——消费方会 - 自动回退到 `en`。 +- Locale key 必须是无 extension/private-use 的 canonical BCP 47 tag。 + 新增 `ja-JP` 等语言只需改数据,不需改 schema。消费方逐字段按 exact、 + structural parent、inferred language-script、language、default 回退;显式 + 空 list 表示有意覆盖。 - `categories` 必须已在 `schema/registry.ts` 中注册(没有合适的先提 PR 新增 slug)。 - 权限字段只是安装确认页的**预览**;实际授权始终以包内 manifest 为准, @@ -41,24 +61,33 @@ CI 强制执行的规则: ## 发布流程 -merge 到 `main` 触发 `.github/workflows/publish.yml`: -validate → aggregate(生成 `dist/plugins.json`,并盖上 `generatedAt` -时间戳)→ 连同 `assets/` 一起上传到 `motrix-registry` R2 bucket。 -消费方使用 ETag 缓存该文件并保留最后一份可用副本,因此一次糟糕的发布 -永远不会把插件目录清空。 +合并到 `main` 后,先执行 `check → test → validate → aggregate`,再进入审批。 +工作流将生成的 `plugins.json` 原始字节上传为不可变产物,记录 SHA-256、大小、 +产物 ID 和源码提交。审批后按 ID 下载,校验字节与 v2 schema,不重新构建。 + +发布前确认 `main` 没有更新,备份 R2 中的旧对象,从已审查的提交上传引用的资源, +仅当旧对象的 ETag 仍匹配时才替换固定的 `plugins.json`。随后校验 R2 读回和 +公开地址的 SHA-256。官网继续独立手动部署,本流程不需要官网 GitHub 仓库或 +网站部署凭据。 ## 契约与 lockstep -`schema/registry.ts` 中的 wire schema 是 **source of truth**;各消费方 -vendor 与之逐字节一致的 schema 副本和 `schema/registry.fixture.json`。 -改变 wire 结构意味着在同一个 PR 周期内更新所有消费方,且演进只增不删: -永远不要重命名、更改类型或移除已发布的字段。 +`schema/registry.ts` 中的 tolerant wire schema 与 resolver 是 +**source of truth**。各消费方 vendor wire-equivalent 实现,以及逐字节一致的 +`schema/registry.fixture.json` 与 `schema/registry.conformance.json`。 +Strict publisher-authoring schema 有意更窄,不是 consumer contract。Registry v2 +的 tolerant consumer 也会显式拒绝 v1 plugin-root 字段 `name`、`description` 与 `features`,但仍保留其他未来字段。 +Registry v2 此后仅 additive-only:永远不要重命名、更改类型或移除已发布字段。 ## 开发 ```bash pnpm install -pnpm test # fixture lockstep + 条目策略测试 +pnpm check # TypeScript +pnpm test # schema、corpus、策略、aggregate、发布产物完整性 pnpm validate # CI 对 plugins/ 运行的检查 pnpm aggregate # 本地构建 dist/plugins.json ``` + +不要手工编辑或提交 `dist/plugins.json`。公开 URL、root `version: 2`、 +R2 key `plugins.json` 与输出文件名保持不变。 diff --git a/plugins/motrix.filename-template.json b/plugins/motrix.filename-template.json index ca3b994..ed2ec9d 100644 --- a/plugins/motrix.filename-template.json +++ b/plugins/motrix.filename-template.json @@ -1,12 +1,29 @@ { "id": "motrix.filename-template", - "name": { - "en": "Motrix Filename Template", - "zh": "Motrix 文件名模板" - }, - "description": { - "en": "Renames downloaded files using a template ({{title}}, {{ext}}, {{date}}, {{id}}) before they are finalized.", - "zh": "在完成下载前按模板({{title}}、{{ext}}、{{date}}、{{id}})重命名文件。" + "listing": { + "defaultLocale": "en-US", + "localizations": { + "en-US": { + "name": "Motrix Filename Template", + "description": "Renames downloaded files using a template ({{title}}, {{ext}}, {{date}}, {{id}}) before they are finalized.", + "features": [ + "Renames finished downloads from a configurable template", + "Placeholders: {{title}}, {{ext}}, {{date}}, {{id}}", + "Works with HTTP, FTP and BitTorrent downloads", + "Applies before the file is finalized on disk" + ] + }, + "zh-CN": { + "name": "Motrix 文件名模板", + "description": "在完成下载前按模板({{title}}、{{ext}}、{{date}}、{{id}})重命名文件。", + "features": [ + "按可配置模板重命名已完成的下载", + "支持占位符:{{title}}、{{ext}}、{{date}}、{{id}}", + "支持 HTTP、FTP 与 BitTorrent 下载", + "在文件最终落盘前执行" + ] + } + } }, "version": "1.1.1", "author": { @@ -27,20 +44,6 @@ "*://*/*" ], "repository": "https://github.com/motrixapp/builtin-plugins", - "features": { - "en": [ - "Renames finished downloads from a configurable template", - "Placeholders: {{title}}, {{ext}}, {{date}}, {{id}}", - "Works with HTTP, FTP and BitTorrent downloads", - "Applies before the file is finalized on disk" - ], - "zh": [ - "按可配置模板重命名已完成的下载", - "支持占位符:{{title}}、{{ext}}、{{date}}、{{id}}", - "支持 HTTP、FTP 与 BitTorrent 下载", - "在文件最终落盘前执行" - ] - }, "updatedAt": "2026-07-22", "package": { "url": "https://github.com/motrixapp/builtin-plugins/releases/download/motrix.filename-template%401.1.1/motrix.filename-template-1.1.1.moext", diff --git a/plugins/motrix.scraper-hook.json b/plugins/motrix.scraper-hook.json index 5dad2b1..10996a9 100644 --- a/plugins/motrix.scraper-hook.json +++ b/plugins/motrix.scraper-hook.json @@ -1,12 +1,29 @@ { "id": "motrix.scraper-hook", - "name": { - "en": "Motrix Page Scraper", - "zh": "Motrix 页面抓取" - }, - "description": { - "en": "Detects HTML download pages and rewrites the URL to the archive link they reference.", - "zh": "识别 HTML 下载页面并改写到页面里指向的压缩包链接。" + "listing": { + "defaultLocale": "en-US", + "localizations": { + "en-US": { + "name": "Motrix Page Scraper", + "description": "Detects HTML download pages and rewrites the URL to the archive link they reference.", + "features": [ + "Inspects a URL before the task is created", + "Detects when the target is an HTML landing page instead of a file", + "Rewrites the task to the first archive or installer link on the page (.zip, .tar.gz, .tgz, .rar, .7z, .exe, .dmg, .iso, .pkg)", + "Configurable page-scan size limit; direct file links are never touched" + ] + }, + "zh-CN": { + "name": "Motrix 页面抓取", + "description": "识别 HTML 下载页面并改写到页面里指向的压缩包链接。", + "features": [ + "在任务创建前检查 URL", + "识别目标是 HTML 落地页而非文件的情况", + "自动改写为页面中第一个压缩包或安装包直链(.zip、.tar.gz、.tgz、.rar、.7z、.exe、.dmg、.iso、.pkg)", + "可配置扫描页面体积上限;文件直链不受影响" + ] + } + } }, "version": "1.0.0", "author": { @@ -27,20 +44,6 @@ "*://*/*" ], "repository": "https://github.com/motrixapp/builtin-plugins", - "features": { - "en": [ - "Inspects a URL before the task is created", - "Detects when the target is an HTML landing page instead of a file", - "Rewrites the task to the first archive or installer link on the page (.zip, .tar.gz, .tgz, .rar, .7z, .exe, .dmg, .iso, .pkg)", - "Configurable page-scan size limit; direct file links are never touched" - ], - "zh": [ - "在任务创建前检查 URL", - "识别目标是 HTML 落地页而非文件的情况", - "自动改写为页面中第一个压缩包或安装包直链(.zip、.tar.gz、.tgz、.rar、.7z、.exe、.dmg、.iso、.pkg)", - "可配置扫描页面体积上限;文件直链不受影响" - ] - }, "updatedAt": "2026-07-22", "package": { "url": "https://github.com/motrixapp/builtin-plugins/releases/download/motrix.scraper-hook%401.0.0/motrix.scraper-hook-1.0.0.moext", diff --git a/plugins/motrix.url-resolver.json b/plugins/motrix.url-resolver.json index 879f48e..389b518 100644 --- a/plugins/motrix.url-resolver.json +++ b/plugins/motrix.url-resolver.json @@ -1,12 +1,29 @@ { "id": "motrix.url-resolver", - "name": { - "en": "Motrix URL Resolver", - "zh": "Motrix URL 解析器" - }, - "description": { - "en": "URL-resolver framework for Motrix. Ships no site-specific extractors; includes only a Wikimedia Commons demo resolver. Site resolution is provided by separately installed site-resolver plugins.", - "zh": "Motrix 的 URL 解析框架。不内置任何站点特定抽取器,仅含一个 Wikimedia Commons 演示解析器;站点解析由单独安装的 site-resolver 插件提供。" + "listing": { + "defaultLocale": "en-US", + "localizations": { + "en-US": { + "name": "Motrix URL Resolver", + "description": "URL-resolver framework for Motrix. Ships no site-specific extractors; includes only a Wikimedia Commons demo resolver. Site resolution is provided by separately installed site-resolver plugins.", + "features": [ + "Base framework for site-specific media resolver plugins", + "Includes a Wikimedia Commons demo resolver", + "Preferred quality setting (1080p, 720p or 480p) shared with installed site resolvers", + "Supports direct-URL and split video/audio (mux) resolver results" + ] + }, + "zh-CN": { + "name": "Motrix URL 解析器", + "description": "Motrix 的 URL 解析框架。不内置任何站点特定抽取器,仅含一个 Wikimedia Commons 演示解析器;站点解析由单独安装的 site-resolver 插件提供。", + "features": [ + "站点媒体解析插件的基础框架", + "内置 Wikimedia Commons 演示解析器", + "首选清晰度设置(1080p / 720p / 480p),供已安装的 site-resolver 插件使用", + "支持直链与音视频分离(mux)两种解析结果" + ] + } + } }, "version": "1.0.0", "author": { @@ -27,20 +44,6 @@ "*://commons.wikimedia.org/*" ], "repository": "https://github.com/motrixapp/builtin-plugins", - "features": { - "en": [ - "Base framework for site-specific media resolver plugins", - "Includes a Wikimedia Commons demo resolver", - "Preferred quality setting (1080p, 720p or 480p) shared with installed site resolvers", - "Supports direct-URL and split video/audio (mux) resolver results" - ], - "zh": [ - "站点媒体解析插件的基础框架", - "内置 Wikimedia Commons 演示解析器", - "首选清晰度设置(1080p / 720p / 480p),供已安装的 site-resolver 插件使用", - "支持直链与音视频分离(mux)两种解析结果" - ] - }, "updatedAt": "2026-07-22", "featured": true, "package": { diff --git a/schema/registry.conformance.json b/schema/registry.conformance.json new file mode 100644 index 0000000..6d1fd29 --- /dev/null +++ b/schema/registry.conformance.json @@ -0,0 +1,565 @@ +{ + "$comment": "Shared registry v2 three-channel conformance corpus. wireExpected runs in all tolerant wire parsers; authoringExpected runs only in plugin-registry strict source validation; resolverExpected runs in consumers.", + "version": 2, + "baseFile": { + "version": 2, + "generatedAt": "2026-08-02T00:00:00.000Z", + "plugins": [ + { + "id": "example.contract", + "listing": { + "defaultLocale": "en-US", + "localizations": { + "en-US": { + "name": "Default name", + "description": "Default description", + "features": ["Default feature"], + "keywords": ["default"] + } + } + }, + "version": "1.0.0", + "author": { "name": "Example" }, + "origin": "builtin", + "categories": ["integration"], + "engines": { "motrix": ">=2.0.0" }, + "updatedAt": "2026-08-02" + } + ] + }, + "cases": [ + { + "id": "valid-baseline", + "operations": [], + "wireExpected": { "accepted": true }, + "authoringExpected": { "accepted": true }, + "resolverExpected": { + "pluginId": "example.contract", + "requestedLocale": "en-US", + "resolved": { + "name": "Default name", + "description": "Default description", + "features": ["Default feature"], + "keywords": ["default"] + } + } + }, + { + "id": "v1-root-version-is-rejected", + "operations": [ + { "op": "set", "path": ["version"], "value": 1 } + ], + "wireExpected": { "accepted": false }, + "authoringExpected": { "accepted": false } + }, + { + "id": "legacy-only-localized-root-fields-are-rejected", + "operations": [ + { "op": "delete", "path": ["plugins", 0, "listing"] }, + { + "op": "set", + "path": ["plugins", 0, "name"], + "value": { "en": "Legacy name", "zh": "旧名称" } + }, + { + "op": "set", + "path": ["plugins", 0, "description"], + "value": { "en": "Legacy description" } + }, + { + "op": "set", + "path": ["plugins", 0, "features"], + "value": { "en": ["Legacy feature"], "zh": ["旧功能"] } + } + ], + "wireExpected": { "accepted": false }, + "authoringExpected": { "accepted": false } + }, + { + "id": "mixed-legacy-localized-root-fields-are-rejected", + "operations": [ + { + "op": "set", + "path": ["plugins", 0, "name"], + "value": { "en": "Legacy name", "zh": "旧名称" } + }, + { + "op": "set", + "path": ["plugins", 0, "description"], + "value": { "en": "Legacy description" } + }, + { + "op": "set", + "path": ["plugins", 0, "features"], + "value": { "en": ["Legacy feature"], "zh": ["旧功能"] } + } + ], + "wireExpected": { "accepted": false }, + "authoringExpected": { "accepted": false } + }, + { + "id": "future-plugin-root-field-is-preserved", + "operations": [ + { + "op": "set", + "path": ["plugins", 0, "futureMetadata"], + "value": { "tagline": "Future metadata" } + } + ], + "wireExpected": { + "accepted": true, + "preservedPaths": [["plugins", 0, "futureMetadata"]] + }, + "authoringExpected": { "accepted": false } + }, + { + "id": "thirty-three-locales-are-wire-open-authoring-limited", + "operations": [ + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "fr-FR"], + "value": { "name": "fr-FR" } + }, + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "de-DE"], + "value": { "name": "de-DE" } + }, + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "es-ES"], + "value": { "name": "es-ES" } + }, + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "it-IT"], + "value": { "name": "it-IT" } + }, + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "pt-BR"], + "value": { "name": "pt-BR" } + }, + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "nl-NL"], + "value": { "name": "nl-NL" } + }, + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "sv-SE"], + "value": { "name": "sv-SE" } + }, + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "da-DK"], + "value": { "name": "da-DK" } + }, + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "fi-FI"], + "value": { "name": "fi-FI" } + }, + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "no-NO"], + "value": { "name": "no-NO" } + }, + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "pl-PL"], + "value": { "name": "pl-PL" } + }, + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "cs-CZ"], + "value": { "name": "cs-CZ" } + }, + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "sk-SK"], + "value": { "name": "sk-SK" } + }, + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "hu-HU"], + "value": { "name": "hu-HU" } + }, + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "ro-RO"], + "value": { "name": "ro-RO" } + }, + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "bg-BG"], + "value": { "name": "bg-BG" } + }, + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "uk-UA"], + "value": { "name": "uk-UA" } + }, + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "ru-RU"], + "value": { "name": "ru-RU" } + }, + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "el-GR"], + "value": { "name": "el-GR" } + }, + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "tr-TR"], + "value": { "name": "tr-TR" } + }, + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "ar-SA"], + "value": { "name": "ar-SA" } + }, + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "he-IL"], + "value": { "name": "he-IL" } + }, + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "hi-IN"], + "value": { "name": "hi-IN" } + }, + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "bn-BD"], + "value": { "name": "bn-BD" } + }, + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "th-TH"], + "value": { "name": "th-TH" } + }, + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "vi-VN"], + "value": { "name": "vi-VN" } + }, + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "id-ID"], + "value": { "name": "id-ID" } + }, + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "ms-MY"], + "value": { "name": "ms-MY" } + }, + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "ja-JP"], + "value": { "name": "ja-JP" } + }, + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "ko-KR"], + "value": { "name": "ko-KR" } + }, + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "zh-CN"], + "value": { "name": "zh-CN" } + }, + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "zh-TW"], + "value": { "name": "zh-TW" } + } + ], + "wireExpected": { + "accepted": true, + "preservedPaths": [ + ["plugins", 0, "listing", "localizations", "zh-TW"] + ] + }, + "authoringExpected": { "accepted": false } + }, + { + "id": "future-only-localization-field", + "operations": [ + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "fr"], + "value": { "tagline": "Future field" } + } + ], + "wireExpected": { + "accepted": true, + "preservedPaths": [ + ["plugins", 0, "listing", "localizations", "fr", "tagline"] + ] + }, + "authoringExpected": { "accepted": false }, + "resolverExpected": { + "pluginId": "example.contract", + "requestedLocale": "fr-FR", + "resolved": { + "name": "Default name", + "description": "Default description", + "features": ["Default feature"], + "keywords": ["default"] + } + } + }, + { + "id": "known-field-plus-authoring-typo", + "operations": [ + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "zh-CN"], + "value": { "name": "中文名称", "descripton": "拼错字段" } + } + ], + "wireExpected": { + "accepted": true, + "preservedPaths": [ + ["plugins", 0, "listing", "localizations", "zh-CN", "descripton"] + ] + }, + "authoringExpected": { "accepted": false } + }, + { + "id": "unknown-category-is-wire-open", + "operations": [ + { + "op": "set", + "path": ["plugins", 0, "categories"], + "value": ["future-category"] + } + ], + "wireExpected": { + "accepted": true, + "preservedPaths": [["plugins", 0, "categories"]] + }, + "authoringExpected": { "accepted": false } + }, + { + "id": "noncanonical-alias-is-wire-safe", + "operations": [ + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "iw-IL"], + "value": { "name": "Alias name" } + } + ], + "wireExpected": { + "accepted": true, + "preservedPaths": [ + ["plugins", 0, "listing", "localizations", "iw-IL"] + ] + }, + "authoringExpected": { "accepted": false }, + "resolverExpected": { + "pluginId": "example.contract", + "requestedLocale": "iw-IL", + "resolved": { + "name": "Default name", + "description": "Default description", + "features": ["Default feature"], + "keywords": ["default"] + } + } + }, + { + "id": "icu-unknown-tag-is-preserved", + "operations": [ + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "abcd"], + "value": { "name": "Future language" } + } + ], + "wireExpected": { + "accepted": true, + "preservedPaths": [ + ["plugins", 0, "listing", "localizations", "abcd"] + ] + }, + "authoringExpected": { "accepted": false }, + "resolverExpected": { + "pluginId": "example.contract", + "requestedLocale": "abcd", + "resolved": { + "name": "Default name", + "description": "Default description", + "features": ["Default feature"], + "keywords": ["default"] + } + } + }, + { + "id": "und-record-is-preserved-but-not-matched", + "operations": [ + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "und"], + "value": { "name": "Undefined language" } + } + ], + "wireExpected": { + "accepted": true, + "preservedPaths": [ + ["plugins", 0, "listing", "localizations", "und"] + ] + }, + "authoringExpected": { "accepted": false }, + "resolverExpected": { + "pluginId": "example.contract", + "requestedLocale": "und-Cyrl", + "resolved": { + "name": "Default name", + "description": "Default description", + "features": ["Default feature"], + "keywords": ["default"] + } + } + }, + { + "id": "underscore-tag-is-malformed", + "operations": [ + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "zh_cn"], + "value": { "name": "Bad" } + } + ], + "wireExpected": { "accepted": false }, + "authoringExpected": { "accepted": false } + }, + { + "id": "extension-tag-is-malformed-for-wire", + "operations": [ + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "en-US-u-ca-gregory"], + "value": { "name": "Bad" } + } + ], + "wireExpected": { "accepted": false }, + "authoringExpected": { "accepted": false } + }, + { + "id": "empty-sparse-record", + "operations": [ + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "fr"], + "value": {} + } + ], + "wireExpected": { "accepted": false }, + "authoringExpected": { "accepted": false } + }, + { + "id": "missing-default-record", + "operations": [ + { + "op": "delete", + "path": ["plugins", 0, "listing", "localizations", "en-US"] + } + ], + "wireExpected": { "accepted": false }, + "authoringExpected": { "accepted": false } + }, + { + "id": "duplicate-plugin-id", + "operations": [ + { + "op": "appendCopy", + "path": ["plugins"], + "from": ["plugins", 0] + } + ], + "wireExpected": { "accepted": false }, + "authoringExpected": { "accepted": false } + }, + { + "id": "oversized-default-name", + "operations": [ + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "en-US", "name"], + "value": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + } + ], + "wireExpected": { "accepted": false }, + "authoringExpected": { "accepted": false } + }, + { + "id": "inferred-script-and-empty-array-override", + "operations": [ + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "zh-Hant"], + "value": { "description": "繁體說明", "features": [] } + } + ], + "wireExpected": { "accepted": true }, + "authoringExpected": { "accepted": true }, + "resolverExpected": { + "pluginId": "example.contract", + "requestedLocale": "zh-TW", + "resolved": { + "name": "Default name", + "description": "繁體說明", + "features": [], + "keywords": ["default"] + } + } + }, + { + "id": "no-arbitrary-sibling-region", + "operations": [ + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "zh-CN"], + "value": { "name": "简体名称", "description": "简体说明" } + } + ], + "wireExpected": { "accepted": true }, + "authoringExpected": { "accepted": true }, + "resolverExpected": { + "pluginId": "example.contract", + "requestedLocale": "zh-TW", + "resolved": { + "name": "Default name", + "description": "Default description", + "features": ["Default feature"], + "keywords": ["default"] + } + } + }, + { + "id": "multi-variant-right-to-left-parent", + "operations": [ + { + "op": "set", + "path": ["plugins", 0, "listing", "localizations", "sl-1994-biske"], + "value": { "name": "Biske name" } + } + ], + "wireExpected": { "accepted": true }, + "authoringExpected": { "accepted": true }, + "resolverExpected": { + "pluginId": "example.contract", + "requestedLocale": "sl-1994-biske-rozaj", + "resolved": { + "name": "Biske name", + "description": "Default description", + "features": ["Default feature"], + "keywords": ["default"] + } + } + } + ] +} diff --git a/schema/registry.fixture.json b/schema/registry.fixture.json index 521491b..85dccf3 100644 --- a/schema/registry.fixture.json +++ b/schema/registry.fixture.json @@ -1,17 +1,33 @@ { - "$comment": "Shared contract fixture for the registry wire shape (spec 2026-07-10-plugin-registry-api-design.md §8). Mirrored into motrix-turbo and the registry repo; all three consumers must parse this file unchanged. Entries are fictional.", - "version": 1, - "generatedAt": "2026-07-10T00:00:00.000Z", + "$comment": "Shared registry v2 wire fixture. Copy byte-for-byte into motrix-turbo and motrix-website.", + "version": 2, + "generatedAt": "2026-08-02T00:00:00.000Z", "plugins": [ { "id": "example.archive-unpacker", - "name": { - "en": "Example Archive Unpacker", - "zh": "示例压缩包解压器" - }, - "description": { - "en": "Unpacks finished archive downloads into a folder next to the file.", - "zh": "下载完成后将压缩包解压到同级目录。" + "listing": { + "defaultLocale": "en-US", + "localizations": { + "en-US": { + "name": "Example Archive Unpacker", + "description": "Unpacks finished archive downloads into a folder next to the file.", + "features": [ + "Unpacks zip, tar and 7z archives", + "Optional completion notification" + ], + "keywords": ["archive", "extract"] + }, + "zh-CN": { + "name": "示例压缩包解压器", + "description": "下载完成后将压缩包解压到同级目录。", + "features": ["支持 zip、tar、7z 压缩包", "可选的完成通知"], + "keywords": ["压缩包", "解压"] + }, + "ja-JP": { + "name": "サンプル・アーカイブ展開", + "features": [] + } + } }, "version": "2.1.0", "author": { @@ -35,32 +51,42 @@ "screenshots": [ "https://dl.motrix.app/registry/assets/example.archive-unpacker/shot-1.png" ], - "features": { - "en": [ - "Unpacks zip, tar and 7z archives", - "Optional completion notification" - ], - "zh": ["支持 zip、tar、7z 压缩包", "可选的完成通知"] - }, "updatedAt": "2026-07-08", "featured": true }, { "id": "example.minimal", - "name": { "en": "Example Minimal" }, - "description": { "en": "The smallest entry the contract accepts." }, + "listing": { + "defaultLocale": "en-US", + "localizations": { + "en-US": { + "name": "Example Minimal", + "description": "The smallest default-only listing in the fixture." + } + } + }, "version": "0.1.0", "author": { "name": "Example Dev" }, "origin": "community", "categories": ["integration"], "engines": { "motrix": ">=2.0.0" }, + "package": { + "url": "https://github.com/example/minimal/releases/download/v0.1.0/minimal.zip", + "sha256": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "size": 1024 + }, "updatedAt": "2026-07-01" }, { "id": "motrix.url-resolver", - "name": { "en": "URL Resolver" }, - "description": { - "en": "Resolves obfuscated download URLs before submission." + "listing": { + "defaultLocale": "en-US", + "localizations": { + "en-US": { + "name": "URL Resolver", + "description": "Resolves obfuscated download URLs before submission." + } + } }, "version": "1.0.0", "author": { "name": "Motrix" }, diff --git a/schema/registry.ts b/schema/registry.ts index 3348b3f..c36e82c 100644 --- a/schema/registry.ts +++ b/schema/registry.ts @@ -1,30 +1,16 @@ import { z } from 'zod' -// Wire schema for the Motrix plugin registry — contract v1. +// Registry v2 wire contract for the Motrix plugin registry. // -// THIS FILE IS THE SOURCE OF TRUTH. Copies are vendored into: -// - motrix-website src/data/plugins.ts -// - motrix-turbo src/shared/schemas/registry.ts -// together with the byte-identical schema/registry.fixture.json. -// Lockstep rule: any wire-shape change lands in all three repos in the -// same PR cycle, and evolution is additive-only — never rename, retype, -// or remove a published field. Design doc: motrix-website -// docs/superpowers/specs/2026-07-10-plugin-registry-api-design.md. +// THIS FILE IS THE SOURCE OF TRUTH. Consumers vendor the tolerant wire schema, +// resolver, registry.fixture.json, and registry.conformance.json. Publisher +// authoring is deliberately stricter and stays in this repository. export const REGISTRY_URL = 'https://dl.motrix.app/registry/plugins.json' - -/** Absolute base every icon/screenshot URL must live under (spec §3.3). */ export const ASSETS_BASE_URL = 'https://dl.motrix.app/registry/assets' - -/** Dot-namespaced lowercase plugin id; `motrix.*` is reserved for builtins. */ export const REGISTRY_PLUGIN_ID_RE = /^[a-z0-9-]+(\.[a-z0-9-]+)+$/ +export const MAX_LOCALIZATION_RECORDS = 32 -/** - * Registered category slugs. Adding a slug is an additive change; entries - * in this repo must use registered slugs (CI-enforced in - * scripts/validate.ts). Consumers may be more lenient — the app buckets - * unknown slugs under "other", the website filters them. - */ export const REGISTERED_CATEGORIES = [ 'site-resolver', 'post-action', @@ -32,57 +18,364 @@ export const REGISTERED_CATEGORIES = [ 'integration', ] as const -const LocalizedTextSchema = z.object({ - en: z.string().min(1), - zh: z.string().min(1).optional(), -}) +const LANGUAGE_RE = /^[a-z]{2,8}$/ +const SCRIPT_RE = /^[A-Z][a-z]{3}$/ +const REGION_RE = /^(?:[A-Z]{2}|[0-9]{3})$/ +const VARIANT_RE = /^(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3})$/ +const CONTROL_RE = /[\u0000-\u001f\u007f-\u009f]/u +const LEGACY_LOCALIZED_ROOT_KEYS = ['name', 'description', 'features'] as const + +/** + * ICU-independent consumer profile: canonical ASCII casing for language, + * optional script/region, then variants. Extensions/private use are excluded. + * Alias and registry knowledge are intentionally not required here. + */ +export function isMotrixLocaleTag(tag: string): boolean { + if (tag.length === 0 || tag.length > 255 || !/^[A-Za-z0-9-]+$/.test(tag)) { + return false + } + const parts = tag.split('-') + if (!LANGUAGE_RE.test(parts[0] ?? '')) return false + + let index = 1 + if (SCRIPT_RE.test(parts[index] ?? '')) index += 1 + if (REGION_RE.test(parts[index] ?? '')) index += 1 + + const variants = new Set() + for (; index < parts.length; index += 1) { + const part = parts[index] ?? '' + if (!VARIANT_RE.test(part) || variants.has(part)) return false + variants.add(part) + } + return true +} + +/** Strict source policy; consumers must not use this for wire parsing. */ +export function isCanonicalPublisherLocale(tag: string): boolean { + if (!isMotrixLocaleTag(tag) || tag.split('-')[0] === 'und') return false + try { + const canonical = Intl.getCanonicalLocales(tag) + if (canonical.length !== 1 || canonical[0] !== tag) return false + const locale = new Intl.Locale(tag) + return locale.baseName === tag + } catch { + return false + } +} + +export const MotrixLocaleTagSchema = z + .string() + .refine(isMotrixLocaleTag, 'must be a safe Motrix BCP 47 profile tag') -const LocalizedListSchema = z.object({ - en: z.array(z.string().min(1)), - zh: z.array(z.string().min(1)).optional(), -}) +export const PublisherLocaleTagSchema = z + .string() + .refine( + isCanonicalPublisherLocale, + 'must be canonical BCP 47 without extensions/private use or und' + ) -export const RegistryPluginSchema = z.object({ +function boundedPlainText(label: string, max: number) { + return z + .string() + .min(1, `${label} must not be empty`) + .max(max, `${label} must be at most ${max} UTF-16 code units`) + .superRefine((value, ctx) => { + if (value !== value.trim()) { + ctx.addIssue({ + code: 'custom', + message: `${label} must not have leading or trailing whitespace`, + }) + } + if (value !== value.normalize('NFC')) { + ctx.addIssue({ + code: 'custom', + message: `${label} must be Unicode NFC`, + }) + } + if (CONTROL_RE.test(value)) { + ctx.addIssue({ + code: 'custom', + message: `${label} must not contain C0/C1 control characters`, + }) + } + }) +} + +function uniqueTextList(label: string, itemMax: number) { + return z + .array(boundedPlainText(`${label} item`, itemMax)) + .max(20, `${label} must contain at most 20 items`) + .superRefine((items, ctx) => { + const seen = new Set() + for (const [index, item] of items.entries()) { + if (seen.has(item)) { + ctx.addIssue({ + code: 'custom', + path: [index], + message: `${label} items must be unique`, + }) + } + seen.add(item) + } + }) +} + +const localizationShape = { + name: boundedPlainText('name', 80).optional(), + description: boundedPlainText('description', 2_000).optional(), + features: uniqueTextList('features', 160).optional(), + keywords: uniqueTextList('keywords', 64).optional(), +} + +/** Tolerant extension point: future own fields survive old-consumer parsing. */ +export const RegistryLocalizationSchema = z + .object(localizationShape) + .passthrough() +export type RegistryLocalization = z.infer + +const RegistryLocalizationAuthoringSchema = z + .object(localizationShape) + .strict() + +function addListingIssues( + listing: { + defaultLocale: string + localizations: Record + }, + ctx: z.RefinementCtx +): void { + if (!Object.hasOwn(listing.localizations, listing.defaultLocale)) { + ctx.addIssue({ + code: 'custom', + path: ['defaultLocale'], + message: 'defaultLocale must be an own key of localizations', + }) + return + } + + const defaultRecord = listing.localizations[listing.defaultLocale] + if ( + !defaultRecord || + !Object.hasOwn(defaultRecord, 'name') || + !Object.hasOwn(defaultRecord, 'description') + ) { + ctx.addIssue({ + code: 'custom', + path: ['localizations', listing.defaultLocale], + message: 'default localization must contain name and description', + }) + } + + for (const [locale, localization] of Object.entries(listing.localizations)) { + if (locale !== listing.defaultLocale && Object.keys(localization).length === 0) { + ctx.addIssue({ + code: 'custom', + path: ['localizations', locale], + message: 'non-default localization must contain at least one own field', + }) + } + } +} + +function addAuthoringLocalizationLimit( + listing: { localizations: Record }, + ctx: z.RefinementCtx +): void { + if (Object.keys(listing.localizations).length > MAX_LOCALIZATION_RECORDS) { + ctx.addIssue({ + code: 'custom', + path: ['localizations'], + message: `listing must contain at most ${MAX_LOCALIZATION_RECORDS} localizations`, + }) + } +} + +export const RegistryListingSchema = z + .object({ + defaultLocale: MotrixLocaleTagSchema, + localizations: z.record(MotrixLocaleTagSchema, RegistryLocalizationSchema), + }) + .passthrough() + .superRefine(addListingIssues) +export type RegistryListing = z.infer + +const RegistryListingAuthoringSchema = z + .object({ + defaultLocale: PublisherLocaleTagSchema, + localizations: z.record( + PublisherLocaleTagSchema, + RegistryLocalizationAuthoringSchema + ), + }) + .strict() + .superRefine(addListingIssues) + .superRefine(addAuthoringLocalizationLimit) + +const authorShape = { + name: z.string().min(1), + url: z.url().optional(), +} +const enginesShape = { motrix: z.string().min(1) } +const packageShape = { + url: z.url(), + sha256: z.string().regex(/^[a-f0-9]{64}$/), + size: z.number().int().positive(), + signature: z.string().min(1).optional(), +} + +const commonPluginShape = { id: z.string().regex(REGISTRY_PLUGIN_ID_RE), - name: LocalizedTextSchema, - description: LocalizedTextSchema, version: z.string().min(1), - author: z.object({ name: z.string().min(1), url: z.url().optional() }), origin: z.enum(['builtin', 'community']), categories: z.array(z.string().min(1)).min(1), - engines: z.object({ motrix: z.string().min(1) }), - // Consent preview only — actual grants always come from the manifest - // inside the package (spec §6.3). permissions: z.array(z.string().min(1)).default([]), optionalPermissions: z.array(z.string().min(1)).default([]), hostPermissions: z.array(z.string().min(1)).default([]), - // Historically absent for builtins; builtin entries carry it (plus - // `signature`) for independent hot updates. - package: z - .object({ - url: z.url(), - sha256: z.string().regex(/^[a-f0-9]{64}$/), - size: z.number().int().positive(), - // Phase 2 of the builtin independent-update design: detached ed25519 - // signature (base64) over the .moext bytes. THE trust boundary for - // builtin hot updates; sha256 above is a pre-check only. - signature: z.string().min(1).optional(), - }) - .optional(), repository: z.url().optional(), homepage: z.url().optional(), icon: z.string().optional(), screenshots: z.array(z.string()).default([]), - features: LocalizedListSchema.optional(), updatedAt: z.iso.date(), featured: z.boolean().default(false), -}) +} + +export const RegistryPluginSchema = z + .object({ + ...commonPluginShape, + listing: RegistryListingSchema, + author: z.object(authorShape).passthrough(), + engines: z.object(enginesShape).passthrough(), + package: z.object(packageShape).passthrough().optional(), + }) + .passthrough() + .superRefine((plugin, ctx) => { + for (const key of LEGACY_LOCALIZED_ROOT_KEYS) { + if (Object.hasOwn(plugin, key)) { + ctx.addIssue({ + code: 'custom', + path: [key], + message: `legacy localized root field "${key}" is not valid in registry v2`, + }) + } + } + }) export type RegistryPlugin = z.infer -export const RegistryFileSchema = z.object({ - version: z.literal(1), - /** Stamped by the aggregation CI at publish time. */ - generatedAt: z.iso.datetime(), - plugins: z.array(RegistryPluginSchema), -}) +/** Strict schema for one JSON file under plugins/. */ +export const RegistryPluginAuthoringSchema = z + .object({ + ...commonPluginShape, + listing: RegistryListingAuthoringSchema, + author: z.object(authorShape).strict(), + engines: z.object(enginesShape).strict(), + package: z.object(packageShape).strict().optional(), + }) + .strict() + +function addDuplicateIdIssues( + file: { plugins: Array<{ id: string }> }, + ctx: z.RefinementCtx +): void { + const seen = new Set() + for (const [index, plugin] of file.plugins.entries()) { + if (seen.has(plugin.id)) { + ctx.addIssue({ + code: 'custom', + path: ['plugins', index, 'id'], + message: `duplicate plugin id "${plugin.id}"`, + }) + } + seen.add(plugin.id) + } +} + +export const RegistryFileSchema = z + .object({ + version: z.literal(2), + generatedAt: z.iso.datetime(), + plugins: z.array(RegistryPluginSchema), + }) + .passthrough() + .superRefine(addDuplicateIdIssues) export type RegistryFile = z.infer + +/** Conformance-only root contract for strict publisher-source expectations. */ +export const RegistryFileAuthoringSchema = z + .object({ + version: z.literal(2), + generatedAt: z.iso.datetime(), + plugins: z.array(RegistryPluginAuthoringSchema), + }) + .strict() + .superRefine(addDuplicateIdIssues) + +export interface ResolvedRegistryListing { + name: string + description: string + features: string[] + keywords: string[] +} + +function localeCandidates(listing: RegistryListing, requestedLocale: string): string[] { + const candidates: string[] = [] + const add = (candidate: string | undefined) => { + if (candidate && !candidates.includes(candidate)) candidates.push(candidate) + } + + let locale: Intl.Locale + try { + locale = new Intl.Locale(requestedLocale) + } catch { + return [listing.defaultLocale] + } + if (locale.language === 'und') return [listing.defaultLocale] + + const baseName = locale.baseName + add(baseName) + const parentParts = baseName.split('-') + while (parentParts.length > 1) { + parentParts.pop() + if (parentParts.length > 1) add(parentParts.join('-')) + } + + try { + const maximized = locale.maximize() + if (maximized.language !== 'und' && maximized.script) { + add(`${maximized.language}-${maximized.script}`) + } + } catch { + // The exact/base candidates remain useful even if likely-subtag data fails. + } + add(locale.language) + add(listing.defaultLocale) + return candidates +} + +/** Deterministic field-level resolver shared by App and website. */ +export function resolveRegistryListing( + listing: RegistryListing, + requestedLocale: string +): ResolvedRegistryListing { + const candidates = localeCandidates(listing, requestedLocale) + const defaultRecord = listing.localizations[listing.defaultLocale] + if (!defaultRecord) { + throw new Error('invalid listing: defaultLocale is not present') + } + + const resolve = (field: 'name' | 'description' | 'features' | 'keywords') => { + for (const candidate of candidates) { + const localization = listing.localizations[candidate] + if (localization && Object.hasOwn(localization, field)) { + return localization[field] + } + } + return defaultRecord[field] + } + + return { + name: resolve('name') as string, + description: resolve('description') as string, + features: (resolve('features') as string[] | undefined) ?? [], + keywords: (resolve('keywords') as string[] | undefined) ?? [], + } +} diff --git a/scripts/aggregate.ts b/scripts/aggregate.ts index 594d688..3cc967c 100644 --- a/scripts/aggregate.ts +++ b/scripts/aggregate.ts @@ -1,33 +1,56 @@ import { mkdir, writeFile } from 'node:fs/promises' +import { pathToFileURL } from 'node:url' import { type RegistryFile, RegistryFileSchema } from '../schema/registry.ts' import { loadEntries } from './lib.ts' -const { entries, problems } = await loadEntries() +export const MAX_REGISTRY_BYTES = 4 * 1024 * 1024 +export const REGISTRY_OUTPUT_FILENAME = 'plugins.json' -if (problems.length > 0) { - console.error('✗ refusing to aggregate with invalid entries; run validate') - for (const problem of problems) { - console.error(` ${problem.file}: ${problem.message}`) +export function assertRegistryArtifactSize(serialized: string): void { + const bytes = Buffer.byteLength(serialized, 'utf8') + if (bytes > MAX_REGISTRY_BYTES) { + throw new Error( + `registry artifact exceeds 4 MiB (${bytes} > ${MAX_REGISTRY_BYTES} UTF-8 bytes)` + ) } - process.exit(1) } -const file: RegistryFile = { - version: 1, - generatedAt: new Date().toISOString(), - plugins: entries, +export function serializeRegistry(file: RegistryFile): string { + const output = RegistryFileSchema.parse(file) + const serialized = `${JSON.stringify(output, null, 2)}\n` + assertRegistryArtifactSize(serialized) + return serialized } -// Round-trip through the schema so the published artifact is exactly what -// consumers will parse (defaults materialized, nothing extra). -const output = RegistryFileSchema.parse(file) -const outUrl = new URL('../dist/', import.meta.url) -await mkdir(outUrl, { recursive: true }) -await writeFile( - new URL('plugins.json', outUrl), - `${JSON.stringify(output, null, 2)}\n` -) +export async function aggregateRegistry(): Promise { + const { entries, problems } = await loadEntries() + if (problems.length > 0) { + console.error('✗ refusing to aggregate with invalid entries; run validate') + for (const problem of problems) { + console.error(` ${problem.file}: ${problem.message}`) + } + process.exitCode = 1 + return + } + + const file: RegistryFile = { + version: 2, + generatedAt: new Date().toISOString(), + plugins: entries, + } + const serialized = serializeRegistry(file) + const outUrl = new URL('../dist/', import.meta.url) + await mkdir(outUrl, { recursive: true }) + await writeFile(new URL(REGISTRY_OUTPUT_FILENAME, outUrl), serialized) -console.log( - `✓ dist/plugins.json — ${output.plugins.length} plugin(s), generatedAt ${output.generatedAt}` -) + console.log( + `✓ dist/${REGISTRY_OUTPUT_FILENAME} — ${entries.length} plugin(s), ${Buffer.byteLength(serialized)} UTF-8 bytes, generatedAt ${file.generatedAt}` + ) +} + +if ( + process.argv[1] && + import.meta.url === pathToFileURL(process.argv[1]).href +) { + await aggregateRegistry() +} diff --git a/scripts/lib.ts b/scripts/lib.ts index 874a4de..56a9be8 100644 --- a/scripts/lib.ts +++ b/scripts/lib.ts @@ -4,7 +4,7 @@ import { ASSETS_BASE_URL, REGISTERED_CATEGORIES, type RegistryPlugin, - RegistryPluginSchema, + RegistryPluginAuthoringSchema, } from '../schema/registry.ts' export const PLUGINS_DIR = new URL('../plugins/', import.meta.url).pathname @@ -20,6 +20,17 @@ export interface EntryProblem { message: string } +/** Locale-independent UTF-16 code-unit order for ASCII protocol identifiers. */ +export function compareCodeUnitStrings(a: string, b: string): number { + if (a === b) return 0 + const commonLength = Math.min(a.length, b.length) + for (let index = 0; index < commonLength; index += 1) { + const difference = a.charCodeAt(index) - b.charCodeAt(index) + if (difference !== 0) return difference + } + return a.length - b.length +} + /** * Repo-level policy checks layered on top of the wire schema. The wire * schema stays identical across the three vendored copies; these rules @@ -30,7 +41,7 @@ export function validateEntry( raw: unknown ): { entry?: RegistryPlugin; problems: EntryProblem[] } { const problems: EntryProblem[] = [] - const parsed = RegistryPluginSchema.safeParse(raw) + const parsed = RegistryPluginAuthoringSchema.safeParse(raw) if (!parsed.success) { return { problems: parsed.error.issues.map((issue) => ({ @@ -41,6 +52,13 @@ export function validateEntry( } const entry = parsed.data + if (entry.listing.defaultLocale !== 'en-US') { + problems.push({ + file, + message: 'publisher policy requires listing.defaultLocale to be "en-US"', + }) + } + if (path.basename(file) !== `${entry.id}.json`) { problems.push({ file, @@ -119,9 +137,15 @@ export async function loadEntries(dir = PLUGINS_DIR): Promise<{ for (const file of files) { let raw: unknown try { - raw = JSON.parse(await readFile(path.join(dir, file), 'utf8')) + const bytes = await readFile(path.join(dir, file)) + const source = new TextDecoder('utf-8', { fatal: true }).decode(bytes) + raw = JSON.parse(source) } catch (error) { - problems.push({ file, message: `invalid JSON: ${String(error)}` }) + const message = + error instanceof TypeError + ? `invalid UTF-8: ${error.message}` + : `invalid JSON: ${String(error)}` + problems.push({ file, message }) continue } const result = validateEntry(file, raw) @@ -140,6 +164,6 @@ export async function loadEntries(dir = PLUGINS_DIR): Promise<{ entries.push(result.entry) } - entries.sort((a, b) => a.id.localeCompare(b.id)) + entries.sort((a, b) => compareCodeUnitStrings(a.id, b.id)) return { entries, problems } } diff --git a/scripts/registry-artifact.ts b/scripts/registry-artifact.ts new file mode 100644 index 0000000..9622a3b --- /dev/null +++ b/scripts/registry-artifact.ts @@ -0,0 +1,66 @@ +import { createHash } from 'node:crypto' +import { lstat, readFile } from 'node:fs/promises' +import { pathToFileURL } from 'node:url' +import { RegistryFileSchema } from '../schema/registry.ts' +import { MAX_REGISTRY_BYTES } from './aggregate.ts' + +export interface RegistryArtifactIdentity { + sha256: string + bytes: number +} + +/** Validate the original bytes; never serialize or rebuild a release artifact. */ +export function inspectRegistryArtifact( + bytes: Buffer, + expected?: RegistryArtifactIdentity +): RegistryArtifactIdentity { + if (bytes.length === 0 || bytes.length > MAX_REGISTRY_BYTES) { + throw new Error('registry artifact must contain between 1 byte and 4 MiB') + } + if ( + expected && + (!/^[a-f0-9]{64}$/.test(expected.sha256) || + !Number.isSafeInteger(expected.bytes) || + expected.bytes < 1 || + expected.bytes > MAX_REGISTRY_BYTES) + ) { + throw new Error('invalid expected registry artifact identity') + } + const identity = { + sha256: createHash('sha256').update(bytes).digest('hex'), + bytes: bytes.length, + } + if ( + expected && + (identity.sha256 !== expected.sha256 || identity.bytes !== expected.bytes) + ) { + throw new Error('registry artifact does not match the approved SHA-256 and size') + } + const source = new TextDecoder('utf-8', { fatal: true }).decode(bytes) + RegistryFileSchema.parse(JSON.parse(source)) + return identity +} + +export async function inspectRegistryArtifactFile( + file: string, + expected?: RegistryArtifactIdentity +): Promise { + const stat = await lstat(file) + if (!stat.isFile() || stat.size === 0 || stat.size > MAX_REGISTRY_BYTES) { + throw new Error('registry artifact must be a regular file of at most 4 MiB') + } + return inspectRegistryArtifact(await readFile(file), expected) +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const [file, sha256, bytes, ...extra] = process.argv.slice(2) + if ( + !file || extra.length > 0 || + (sha256 === undefined) !== (bytes === undefined) || + (bytes !== undefined && !/^[1-9][0-9]*$/.test(bytes)) + ) { + throw new Error('usage: registry-artifact.ts [ ]') + } + const expected = sha256 === undefined ? undefined : { sha256, bytes: Number(bytes) } + console.log(JSON.stringify(await inspectRegistryArtifactFile(file, expected))) +} diff --git a/tests/entry-from-release.test.ts b/tests/entry-from-release.test.ts index 25a8382..cb95f1d 100644 --- a/tests/entry-from-release.test.ts +++ b/tests/entry-from-release.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os' import path from 'node:path' import { strToU8, zipSync } from 'fflate' import { afterEach, describe, expect, it } from 'vitest' -import { RegistryPluginSchema } from '../schema/registry.ts' +import { RegistryPluginAuthoringSchema } from '../schema/registry.ts' import { buildPackageBlock, patchEntry, @@ -234,8 +234,15 @@ describe('patchEntry', () => { dir = await mkdtemp(path.join(tmpdir(), 'plugin-registry-test-')) const entry = { id, - name: { en: 'Test Plugin' }, - description: { en: 'A test plugin.' }, + listing: { + defaultLocale: 'en-US', + localizations: { + 'en-US': { + name: 'Test Plugin', + description: 'A test plugin.', + }, + }, + }, version: '0.0.1', author: { name: 'Motrix Team' }, origin: 'builtin', @@ -258,7 +265,15 @@ describe('patchEntry', () => { const patched = JSON.parse(await readFile(path.join(d, 'motrix.url-resolver.json'), 'utf8')) expect(patched.version).toBe('1.0.0') expect(patched.package).toEqual(block().package) - expect(patched.name).toEqual({ en: 'Test Plugin' }) + expect(patched.listing).toEqual({ + defaultLocale: 'en-US', + localizations: { + 'en-US': { + name: 'Test Plugin', + description: 'A test plugin.', + }, + }, + }) expect(patched.id).toBe('motrix.url-resolver') }) @@ -286,8 +301,16 @@ describe('patchEntry syncs consent+compat fields from the signed manifest', () = dir = await mkdtemp(path.join(tmpdir(), 'plugin-registry-test-')) const entry = { id, - name: { en: 'Filename Template' }, - description: { en: 'Renames finished downloads.' }, + listing: { + defaultLocale: 'en-US', + localizations: { + 'en-US': { + name: 'Filename Template', + description: 'Renames finished downloads.', + }, + 'zh-CN': { name: '文件名模板' }, + }, + }, version: '1.0.0', author: { name: 'Motrix Team' }, origin: 'builtin', @@ -337,7 +360,7 @@ describe('patchEntry syncs consent+compat fields from the signed manifest', () = const patched = JSON.parse(await readFile(path.join(dir, `${id}.json`), 'utf8')) expect(patched.hostPermissions).toEqual([]) expect(patched.optionalPermissions).toEqual([]) - expect(RegistryPluginSchema.safeParse(patched).success).toBe(true) + expect(RegistryPluginAuthoringSchema.safeParse(patched).success).toBe(true) }) it('syncs the engines range from the manifest', async () => { @@ -356,7 +379,7 @@ describe('patchEntry syncs consent+compat fields from the signed manifest', () = expect(patched.engines).toEqual({ motrix: '>=2.0.0 <3.0.0' }) }) - it('leaves editorial fields (name, description, categories, updatedAt) untouched', async () => { + it('preserves the parsed listing by deep equality while manifest fields change', async () => { const id = 'motrix.filename-template' await writeStaleEntry(id, { hostPermissions: ['*://*/*'] }) const before = JSON.parse(await readFile(path.join(dir, `${id}.json`), 'utf8')) @@ -370,8 +393,7 @@ describe('patchEntry syncs consent+compat fields from the signed manifest', () = }) await patchEntry(id, buildPackageBlock(rel, tag, PUB), dir) const patched = JSON.parse(await readFile(path.join(dir, `${id}.json`), 'utf8')) - expect(patched.name).toEqual(before.name) - expect(patched.description).toEqual(before.description) + expect(patched.listing).toEqual(before.listing) expect(patched.categories).toEqual(before.categories) expect(patched.updatedAt).toEqual(before.updatedAt) }) diff --git a/tests/registry-artifact.test.ts b/tests/registry-artifact.test.ts new file mode 100644 index 0000000..ef8da87 --- /dev/null +++ b/tests/registry-artifact.test.ts @@ -0,0 +1,75 @@ +import { createHash } from 'node:crypto' +import { mkdtemp, rm, symlink, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import path from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import fixture from '../schema/registry.fixture.json' +import { + inspectRegistryArtifact, + inspectRegistryArtifactFile, +} from '../scripts/registry-artifact.ts' + +const bytes = Buffer.from(`${JSON.stringify(fixture, null, 2)}\n`) +const identity = { + sha256: createHash('sha256').update(bytes).digest('hex'), + bytes: bytes.length, +} + +describe('immutable registry release artifact', () => { + let directory: string | undefined + afterEach(async () => { + if (directory) await rm(directory, { recursive: true, force: true }) + directory = undefined + }) + + it('validates and hashes the exact bytes without materializing schema defaults', () => { + const original = Buffer.from(bytes) + expect(inspectRegistryArtifact(bytes, identity)).toEqual(identity) + expect(bytes).toEqual(original) + }) + + it('rejects different valid JSON bytes even when they describe the same registry', () => { + expect(() => inspectRegistryArtifact(Buffer.from(JSON.stringify(fixture)), identity)) + .toThrow('approved SHA-256 and size') + }) + + it('rejects a mismatched expected size', () => { + expect(() => inspectRegistryArtifact(bytes, { ...identity, bytes: bytes.length + 1 })) + .toThrow('approved SHA-256 and size') + }) + + it('rejects a v1 registry even with its correct hash', () => { + const legacy = Buffer.from(JSON.stringify({ ...fixture, version: 1 })) + expect(() => inspectRegistryArtifact(legacy)).toThrow() + }) + + it('rejects invalid UTF-8 instead of silently replacing bytes', () => { + const invalid = Buffer.concat([Buffer.from('{"ignored":"'), Buffer.from([0xff]), Buffer.from('"}')]) + expect(() => inspectRegistryArtifact(invalid)).toThrow() + }) + + it.each([Buffer.alloc(0), Buffer.alloc(4 * 1024 * 1024 + 1)])( + 'rejects an empty or oversized artifact', + (input) => expect(() => inspectRegistryArtifact(input)).toThrow('between 1 byte and 4 MiB') + ) + + it.each([ + { ...identity, sha256: 'invalid' }, + { ...identity, bytes: Number.NaN }, + { ...identity, bytes: -1 }, + { ...identity, bytes: 4 * 1024 * 1024 + 1 }, + ])('rejects malformed expected identity', (expected) => { + expect(() => inspectRegistryArtifact(bytes, expected)).toThrow('invalid expected') + }) + + it('accepts a regular file and rejects a symlink or directory', async () => { + directory = await mkdtemp(path.join(tmpdir(), 'registry-artifact-')) + const file = path.join(directory, 'plugins.json') + await writeFile(file, bytes) + await expect(inspectRegistryArtifactFile(file, identity)).resolves.toEqual(identity) + const link = path.join(directory, 'linked.json') + await symlink(file, link) + await expect(inspectRegistryArtifactFile(link, identity)).rejects.toThrow('regular file') + await expect(inspectRegistryArtifactFile(directory, identity)).rejects.toThrow('regular file') + }) +}) diff --git a/tests/registry.test.ts b/tests/registry.test.ts index 9547475..419e1a7 100644 --- a/tests/registry.test.ts +++ b/tests/registry.test.ts @@ -1,141 +1,489 @@ -import { describe, expect, it } from 'vitest' +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import path from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import conformance from '../schema/registry.conformance.json' import fixture from '../schema/registry.fixture.json' -import { RegistryFileSchema } from '../schema/registry.ts' -import { loadEntries, validateEntry } from '../scripts/lib.ts' +import { + isCanonicalPublisherLocale, + isMotrixLocaleTag, + RegistryFileAuthoringSchema, + RegistryFileSchema, + RegistryPluginAuthoringSchema, + resolveRegistryListing, +} from '../schema/registry.ts' +import { + assertRegistryArtifactSize, + MAX_REGISTRY_BYTES, + REGISTRY_OUTPUT_FILENAME, + serializeRegistry, +} from '../scripts/aggregate.ts' +import { + compareCodeUnitStrings, + loadEntries, + validateEntry, +} from '../scripts/lib.ts' + +const baseEntry = { + id: 'acme.unzip', + listing: { + defaultLocale: 'en-US', + localizations: { + 'en-US': { + name: 'Acme Unzip', + description: 'Unzips things.', + features: ['Extract archives'], + keywords: ['archive'], + }, + 'zh-CN': { name: 'Acme 解压' }, + }, + }, + version: '1.0.0', + author: { name: 'Acme' }, + origin: 'community' as const, + categories: ['post-action'], + engines: { motrix: '>=2.0.0' }, + package: { + url: 'https://github.com/acme/unzip/releases/download/v1.0.0/unzip.zip', + sha256: 'a'.repeat(64), + size: 1234, + }, + updatedAt: '2026-07-01', +} describe('contract fixture (lockstep)', () => { - // The same fixture is vendored byte-identical into motrix-website and - // motrix-turbo. A parse failure here means this repo drifted from its - // consumers — land the change in all three repos in one PR cycle. - it('parses unchanged', () => { + it('parses the registry v2 fixture without field loss', () => { const parsed = RegistryFileSchema.parse(fixture) expect(parsed.plugins).toHaveLength(3) - // Guards that the vendored schema actually carries the Phase-2 - // signature field (Zod would otherwise silently strip it). + expect(parsed.plugins[0]?.listing.localizations['ja-JP']).toEqual({ + name: 'サンプル・アーカイブ展開', + features: [], + }) const builtin = parsed.plugins.find((p) => p.id === 'motrix.url-resolver') expect(builtin?.package?.signature).toBe('c2lnbmF0dXJl') }) }) -describe('published entries', () => { - it('all plugins/ entries pass schema and policy checks', async () => { - const { entries, problems } = await loadEntries() - expect(problems).toEqual([]) - expect(entries.length).toBeGreaterThanOrEqual(3) - expect(entries.map((e) => e.id)).toEqual( - [...entries.map((e) => e.id)].sort() +describe('Motrix BCP 47 profile', () => { + it.each([ + 'en-US', + 'zh-Hant', + 'ja', + 'sl-1994-biske', + 'iw-IL', + 'und', + 'abcd', + ])('accepts safe wire tag %s', (tag) => { + expect(isMotrixLocaleTag(tag)).toBe(true) + }) + + it.each([ + 'zh_cn', + 'zh-cn', + 'en-US-u-ca-gregory', + 'de-DE-x-phonebk', + 'e', + `en-${'a'.repeat(256)}`, + ])('rejects malformed wire tag %s', (tag) => { + expect(isMotrixLocaleTag(tag)).toBe(false) + }) + + it.each(['en-US', 'zh-Hant', 'ja', 'sl-1994-biske'])( + 'accepts canonical publisher tag %s', + (tag) => { + expect(isCanonicalPublisherLocale(tag)).toBe(true) + } + ) + + it.each(['zh-cn', 'iw-IL', 'und', 'und-US', 'und-Latn', 'abcd', 'en-US-u-ca-gregory'])( + 'rejects noncanonical publisher tag %s', + (tag) => { + expect(isCanonicalPublisherLocale(tag)).toBe(false) + } + ) +}) + +describe('tolerant wire and strict authoring contracts', () => { + it('rejects legacy-only and mixed old/new entries in both contracts', () => { + const removedEditorialFields = { + name: Object.fromEntries([['en', 'Legacy name']]), + description: Object.fromEntries([['en', 'Legacy description']]), + features: Object.fromEntries([['en', ['Legacy feature']]]), + } + const legacyOnly = { + ...baseEntry, + ...removedEditorialFields, + } as Record + delete legacyOnly.listing + expect(RegistryPluginAuthoringSchema.safeParse(legacyOnly).success).toBe( + false ) + + const mixed = { ...baseEntry, ...removedEditorialFields } + expect(RegistryPluginAuthoringSchema.safeParse(mixed).success).toBe(false) + expect( + RegistryFileSchema.safeParse({ + version: 2, + generatedAt: '2026-08-02T00:00:00.000Z', + plugins: [mixed], + }).success + ).toBe(false) + }) + + it('preserves unrelated future plugin-root fields in the tolerant wire schema', () => { + const raw = { + ...baseEntry, + futureMetadata: { tagline: 'Future metadata' }, + } + expect( + RegistryFileSchema.parse({ + version: 2, + generatedAt: '2026-08-02T00:00:00.000Z', + plugins: [raw], + }).plugins[0]?.futureMetadata + ).toEqual({ tagline: 'Future metadata' }) + expect(RegistryPluginAuthoringSchema.safeParse(raw).success).toBe(false) + }) + + it('preserves a future-only localization while strict authoring rejects it', () => { + const raw = structuredClone(baseEntry) as Record + raw.listing.localizations.fr = { tagline: 'Future field' } + const wire = RegistryPluginAuthoringSchema.safeParse(raw) + expect(RegistryFileSchema.parse({ + version: 2, + generatedAt: '2026-08-02T00:00:00.000Z', + plugins: [raw], + }).plugins[0]?.listing.localizations.fr).toEqual({ tagline: 'Future field' }) + expect(wire.success).toBe(false) + }) + + it.each([ + ['plugin', { future: true }], + ['author', { author: { ...baseEntry.author, future: true } }], + ['engines', { engines: { ...baseEntry.engines, future: true } }], + ['package', { package: { ...baseEntry.package, future: true } }], + ['listing', { listing: { ...baseEntry.listing, future: true } }], + ])('rejects unknown authoring fields at the %s layer', (_layer, patch) => { + expect( + RegistryPluginAuthoringSchema.safeParse({ ...baseEntry, ...patch }).success + ).toBe(false) + }) + + it('rejects a localized typo even beside a valid field', () => { + const raw = structuredClone(baseEntry) as Record + raw.listing.localizations['zh-CN'] = { + name: '合法名称', + descripton: '拼错字段', + } + expect(RegistryPluginAuthoringSchema.safeParse(raw).success).toBe(false) + expect( + RegistryFileSchema.parse({ + version: 2, + generatedAt: '2026-08-02T00:00:00.000Z', + plugins: [raw], + }).plugins[0]?.listing.localizations['zh-CN']?.descripton + ).toBe('拼错字段') + }) + + it('requires a complete default and rejects empty sparse records', () => { + const incomplete = structuredClone(baseEntry) as Record + delete incomplete.listing.localizations['en-US'].description + expect(RegistryPluginAuthoringSchema.safeParse(incomplete).success).toBe(false) + + const empty = structuredClone(baseEntry) as Record + empty.listing.localizations.fr = {} + expect(RegistryPluginAuthoringSchema.safeParse(empty).success).toBe(false) + expect( + RegistryFileSchema.safeParse({ + version: 2, + generatedAt: '2026-08-02T00:00:00.000Z', + plugins: [empty], + }).success + ).toBe(false) + }) + + it('rejects non-trimmed, non-NFC, control-bearing, duplicate and oversized text', () => { + const values = [ + ' padded', + 'e\u0301', + 'bad\u0000text', + 'x'.repeat(81), + ] + for (const name of values) { + const raw = structuredClone(baseEntry) as Record + raw.listing.localizations['en-US'].name = name + expect(RegistryPluginAuthoringSchema.safeParse(raw).success).toBe(false) + expect( + RegistryFileSchema.safeParse({ + version: 2, + generatedAt: '2026-08-02T00:00:00.000Z', + plugins: [raw], + }).success + ).toBe(false) + } + + const duplicate = structuredClone(baseEntry) as Record + duplicate.listing.localizations['en-US'].features = ['same', 'same'] + expect(RegistryPluginAuthoringSchema.safeParse(duplicate).success).toBe(false) + }) + + it('keeps the 32-locale cap in authoring policy, not the wire schema', () => { + const raw = structuredClone(baseEntry) as Record + for (let i = 0; i < 31; i += 1) { + raw.listing.localizations[`en-v${String(i).padStart(4, '0')}`] = { + name: `N${i}`, + } + } + expect(RegistryPluginAuthoringSchema.safeParse(raw).success).toBe(false) + expect( + RegistryFileSchema.safeParse({ + version: 2, + generatedAt: '2026-08-02T00:00:00.000Z', + plugins: [raw], + }).success + ).toBe(true) + }) + + it('rejects duplicate plugin ids at the file level', () => { + const input = { + version: 2, + generatedAt: '2026-08-02T00:00:00.000Z', + plugins: [baseEntry, structuredClone(baseEntry)], + } + expect(RegistryFileSchema.safeParse(input).success).toBe(false) + expect(RegistryFileAuthoringSchema.safeParse(input).success).toBe(false) }) }) -describe('validateEntry policy', () => { - const base = { - id: 'acme.unzip', - name: { en: 'Acme Unzip' }, - description: { en: 'Unzips things.' }, - version: '1.0.0', - author: { name: 'Acme' }, - origin: 'community', - categories: ['post-action'], - engines: { motrix: '>=2.0.0' }, - package: { - url: 'https://github.com/acme/unzip/releases/download/v1.0.0/unzip.zip', - sha256: 'a'.repeat(64), - size: 1234, +describe('exact listing resolver', () => { + const listing = { + defaultLocale: 'en-US', + localizations: { + 'en-US': { + name: 'Default name', + description: 'Default description', + features: ['default feature'], + keywords: ['default keyword'], + }, + 'zh-CN': { name: '简体名称' }, + 'zh-Hant': { description: '繁體說明', features: [] }, + 'sl-1994-biske': { name: 'Biske name' }, + fr: { name: 'Nom français', keywords: [] }, }, - updatedAt: '2026-07-01', } - it('accepts a valid community entry', () => { - expect(validateEntry('acme.unzip.json', base).problems).toEqual([]) + it.each([ + ['fr-FR', 'Nom français', 'Default description'], + ['zh-TW', 'Default name', '繁體說明'], + ['zh-CN', '简体名称', 'Default description'], + ['zh-TW-u-ca-chinese', 'Default name', '繁體說明'], + ['sl-1994-biske-rozaj', 'Biske name', 'Default description'], + ])('resolves %s field-by-field', (requested, name, description) => { + expect(resolveRegistryListing(listing, requested)).toMatchObject({ + name, + description, + }) }) - it('rejects filename/id mismatch', () => { - const { problems } = validateEntry('other.json', base) - expect(problems[0]?.message).toMatch(/filename must be/) + it.each(['invalid_locale', 'und', 'und-Latn', 'und-Cyrl'])( + 'uses only default for %s', + (requested) => { + expect(resolveRegistryListing(listing, requested)).toEqual({ + name: 'Default name', + description: 'Default description', + features: ['default feature'], + keywords: ['default keyword'], + }) + } + ) + + it('does not choose an arbitrary sibling region', () => { + const onlySimplified = { + defaultLocale: 'en-US', + localizations: { + 'en-US': { name: 'English', description: 'English description' }, + 'zh-CN': { name: '简体中文', description: '简体说明' }, + }, + } + expect(resolveRegistryListing(onlySimplified, 'zh-TW').name).toBe('English') }) - it('reserves the motrix.* namespace for builtins', () => { - const { problems } = validateEntry('motrix.unzip.json', { - ...base, - id: 'motrix.unzip', - }) - expect(problems.some((p) => /reserved for builtin/.test(p.message))).toBe( - true - ) + it('treats explicit empty arrays as overrides', () => { + const resolved = resolveRegistryListing(listing, 'zh-Hant-TW') + expect(resolved.features).toEqual([]) + expect(resolveRegistryListing(listing, 'fr-FR').keywords).toEqual([]) }) - it('requires a package pointer on community entries', () => { - const { package: _omit, ...noPackage } = base - const { problems } = validateEntry('acme.unzip.json', noPackage) - expect(problems.some((p) => /package install pointer/.test(p.message))).toBe( - true + it('is independent of locale-map insertion order', () => { + const reversed = { + ...listing, + localizations: Object.fromEntries( + Object.entries(listing.localizations).reverse() + ), + } + expect(resolveRegistryListing(reversed, 'zh-TW')).toEqual( + resolveRegistryListing(listing, 'zh-TW') ) }) +}) + +type PathPart = string | number +type CorpusOperation = { + op: 'set' | 'delete' | 'appendCopy' + path: PathPart[] + from?: PathPart[] + value?: unknown +} + +function atPath(root: any, parts: PathPart[]): any { + return parts.reduce((value, part) => value[part], root) +} - it('rejects package URLs outside the allowlist', () => { - const { problems } = validateEntry('acme.unzip.json', { - ...base, - package: { ...base.package, url: 'https://evil.example.com/x.zip' }, +function materializeCase(operations: CorpusOperation[]): any { + const result = structuredClone(conformance.baseFile) + for (const operation of operations) { + if (operation.op === 'appendCopy') { + atPath(result, operation.path).push( + structuredClone(atPath(result, operation.from ?? [])) + ) + continue + } + const parent = atPath(result, operation.path.slice(0, -1)) + const key = operation.path.at(-1) as string | number + if (operation.op === 'delete') delete parent[key] + else parent[key] = structuredClone(operation.value) + } + return result +} + +function authoringAccepts(input: any): boolean { + if (!RegistryFileAuthoringSchema.safeParse(input).success) return false + return input.plugins.every( + (entry: Record) => + validateEntry(`${String(entry.id)}.json`, entry).problems.length === 0 + ) +} + +describe('shared three-channel conformance corpus', () => { + for (const corpusCase of conformance.cases) { + it(corpusCase.id, () => { + const input = materializeCase( + corpusCase.operations as CorpusOperation[] + ) + const wire = RegistryFileSchema.safeParse(input) + expect(wire.success).toBe(corpusCase.wireExpected.accepted) + if (wire.success) { + for (const preserved of corpusCase.wireExpected.preservedPaths ?? []) { + expect(atPath(wire.data, preserved as PathPart[])).toEqual( + atPath(input, preserved as PathPart[]) + ) + } + } + if (corpusCase.authoringExpected) { + expect(authoringAccepts(input)).toBe( + corpusCase.authoringExpected.accepted + ) + } + if (corpusCase.resolverExpected && wire.success) { + const plugin = wire.data.plugins.find( + (entry) => entry.id === corpusCase.resolverExpected?.pluginId + ) + expect(plugin).toBeDefined() + expect( + resolveRegistryListing( + plugin!.listing, + corpusCase.resolverExpected.requestedLocale + ) + ).toEqual(corpusCase.resolverExpected.resolved) + } }) - expect(problems.some((p) => /allowlist|GitHub release/.test(p.message))).toBe( + } +}) + +describe('published entries and policy', () => { + it('sorts protocol ids independently of the host locale', () => { + const ids = ['a.cz', 'a.ch'] + expect([...ids].sort(compareCodeUnitStrings)).toEqual(['a.ch', 'a.cz']) + expect([...ids].sort(new Intl.Collator('cs-CZ').compare)).toEqual([ + 'a.cz', + 'a.ch', + ]) + }) + + it('all plugins/ entries pass schema and policy checks in id order', async () => { + const { entries, problems } = await loadEntries() + expect(problems).toEqual([]) + expect(entries).toHaveLength(3) + expect(entries.map((entry) => entry.id)).toEqual( + [...entries.map((entry) => entry.id)].sort(compareCodeUnitStrings) + ) + expect(entries.every((entry) => entry.listing.defaultLocale === 'en-US')).toBe( true ) }) - it('rejects unregistered category slugs', () => { - const { problems } = validateEntry('acme.unzip.json', { - ...base, - categories: ['brand-new'], - }) - expect(problems.some((p) => /unregistered category/.test(p.message))).toBe( - true + it('rejects a filename mismatch, unregistered category and bad asset', () => { + expect(validateEntry('other.json', baseEntry).problems).toEqual( + expect.arrayContaining([expect.objectContaining({ message: expect.stringMatching(/filename/) })]) ) + expect( + validateEntry('acme.unzip.json', { + ...baseEntry, + categories: ['brand-new'], + icon: 'https://elsewhere.example/icon.png', + }).problems.map((problem) => problem.message).join('\n') + ).toMatch(/unregistered category[\s\S]*assets/) }) - it('pins assets to the per-plugin assets prefix', () => { - const { problems } = validateEntry('acme.unzip.json', { - ...base, - icon: 'https://elsewhere.example.com/icon.png', - }) - expect(problems.some((p) => /assets/.test(p.message))).toBe(true) + it('rejects malformed UTF-8 before JSON parsing', async () => { + const dir = await mkdtemp(path.join(tmpdir(), 'registry-invalid-utf8-')) + try { + await writeFile( + path.join(dir, 'bad.json'), + Buffer.from([0x7b, 0x22, 0x78, 0x22, 0x3a, 0x22, 0xc3, 0x28, 0x22, 0x7d]) + ) + const { problems } = await loadEntries(dir) + expect(problems[0]?.message).toMatch(/UTF-8/i) + } finally { + await rm(dir, { recursive: true, force: true }) + } + }) +}) - const ok = validateEntry('acme.unzip.json', { - ...base, - icon: 'https://dl.motrix.app/registry/assets/acme.unzip/icon.png', - }) - expect(ok.problems).toEqual([]) - }) - - it('requires a signature on a builtin package', () => { - const { problems } = validateEntry('motrix.demo.json', { - ...base, - id: 'motrix.demo', - origin: 'builtin', - package: { - url: 'https://github.com/motrixapp/builtin-plugins/releases/download/x/x.moext', - sha256: 'a'.repeat(64), - size: 10, - }, +describe('artifact byte gate', () => { + it('serializes the stable registry-v2 filename, root, order and shape', async () => { + const { entries, problems } = await loadEntries() + expect(problems).toEqual([]) + const serialized = serializeRegistry({ + version: 2, + generatedAt: '2026-08-02T00:00:00.000Z', + plugins: entries, }) - expect( - problems.some((p) => /builtin package.*signature|signature/.test(p.message)) - ).toBe(true) + const output = JSON.parse(serialized) as Record + + expect(REGISTRY_OUTPUT_FILENAME).toBe('plugins.json') + expect(output.version).toBe(2) + expect(serialized.endsWith('\n')).toBe(true) + expect(output.plugins.map((plugin: any) => plugin.id)).toEqual( + [...output.plugins.map((plugin: any) => plugin.id)].sort( + compareCodeUnitStrings + ) + ) + for (const plugin of output.plugins) { + expect(Object.hasOwn(plugin, 'name')).toBe(false) + expect(Object.hasOwn(plugin, 'description')).toBe(false) + expect(Object.hasOwn(plugin, 'features')).toBe(false) + expect(plugin.listing.defaultLocale).toBe('en-US') + } }) - it('accepts a builtin package that carries a signature', () => { - const { problems } = validateEntry('motrix.demo.json', { - ...base, - id: 'motrix.demo', - origin: 'builtin', - categories: ['integration'], - package: { - url: 'https://github.com/motrixapp/builtin-plugins/releases/download/x/x.moext', - sha256: 'a'.repeat(64), - size: 10, - signature: 'c2ln', - }, - }) - expect(problems).toEqual([]) + it('includes the final newline and accepts exactly 4 MiB', () => { + const exact = `${'a'.repeat(MAX_REGISTRY_BYTES - 1)}\n` + expect(() => assertRegistryArtifactSize(exact)).not.toThrow() + }) + + it('rejects one UTF-8 byte over 4 MiB', () => { + const over = `${'a'.repeat(MAX_REGISTRY_BYTES - 1)}é\n` + expect(() => assertRegistryArtifactSize(over)).toThrow(/4 MiB|4194304/) }) })