From 2b993ab958d2a866720d41bd39257844a8e62200 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kov=C3=A1cs=20B=C3=A1lint=20Hunor?= Date: Tue, 17 Nov 2026 00:27:16 +0200 Subject: [PATCH 1/5] feat(registry): community plugin registry, versioned releases and submission CI - community-plugins.json + JSON Schema, listing Code Snippets - release-plugin.yml: tag @ builds, smoke-tests and publishes -.amplugin + .sha256 as a GitHub release - generated community-index.json (latest version, download URL, SHA-256, ABI) built from the registry and releases by index.yml; format in docs/registry.md - registry.yml submission CI: schema, unique/unreserved ids, public repo, OSI/OFL license, README table in sync, release resolution, build and released-CLI render - rename Code Snippets to io.github.animathio.code-snippets (org.animathio.* is reserved and the host refuses it in the user plugin folder) Part of AniMathIO/AniMathIO#304 Co-Authored-By: Claude Sonnet 5.5 --- .github/actions/animathio-cli/action.yml | 38 ++ .github/workflows/index.yml | 48 ++ .github/workflows/registry.yml | 70 +++ .github/workflows/release-plugin.yml | 89 ++++ .gitignore | 1 + CONTRIBUTING.md | 114 ++++- README.md | 34 +- RELEASING.md | 55 +++ community-index.json | 6 + community-plugins.json | 17 + community/code-snippets/README.md | 4 +- community/code-snippets/plugin.toml | 2 +- community/code-snippets/smoke.py | 2 +- docs/registry.md | 189 ++++++++ schemas/community-index.schema.json | 72 +++ schemas/community-plugins.schema.json | 78 ++++ schemas/osi-approved-licenses.txt | 136 ++++++ scripts/check_submission.py | 88 ++++ scripts/dry-run-release.sh | 21 + scripts/registry.py | 554 +++++++++++++++++++++++ scripts/registry_smoke.py | 105 +++++ scripts/requirements.txt | 2 + scripts/test_registry.py | 194 ++++++++ 23 files changed, 1895 insertions(+), 24 deletions(-) create mode 100644 .github/actions/animathio-cli/action.yml create mode 100644 .github/workflows/index.yml create mode 100644 .github/workflows/registry.yml create mode 100644 .github/workflows/release-plugin.yml create mode 100644 RELEASING.md create mode 100644 community-index.json create mode 100644 community-plugins.json create mode 100644 docs/registry.md create mode 100644 schemas/community-index.schema.json create mode 100644 schemas/community-plugins.schema.json create mode 100644 schemas/osi-approved-licenses.txt create mode 100755 scripts/check_submission.py create mode 100755 scripts/dry-run-release.sh create mode 100755 scripts/registry.py create mode 100755 scripts/registry_smoke.py create mode 100644 scripts/requirements.txt create mode 100644 scripts/test_registry.py diff --git a/.github/actions/animathio-cli/action.yml b/.github/actions/animathio-cli/action.yml new file mode 100644 index 0000000..9b0ab6c --- /dev/null +++ b/.github/actions/animathio-cli/action.yml @@ -0,0 +1,38 @@ +name: Released AniMathIO CLI +description: Download a released AniMathIO AppImage, verify its SHA-256 and extract animathio-cli. +inputs: + github-token: + description: Token for `gh release download` (the release is public). + required: true + tag: + description: AniMathIO release tag. + default: v2.1.0 + asset: + description: AppImage asset name. + default: animathio_2.1.0_x86_64.AppImage + sha256: + description: Pinned SHA-256 of the asset. + default: cce18dd8215aa9c23ba7c5756e6c0785c1931dd027aadf31a7bbbf3b92fac6ec +outputs: + cli: + description: Absolute path of the extracted animathio-cli. + value: ${{ steps.extract.outputs.cli }} +runs: + using: composite + steps: + - id: extract + shell: bash + env: + GH_TOKEN: ${{ inputs.github-token }} + TAG: ${{ inputs.tag }} + ASSET: ${{ inputs.asset }} + SHA256: ${{ inputs.sha256 }} + run: | + set -euo pipefail + dir="$RUNNER_TEMP/animathio-cli" + mkdir -p "$dir" + gh release download "$TAG" --repo AniMathIO/AniMathIO --pattern "$ASSET" --dir "$dir" + echo "$SHA256 $dir/$ASSET" | sha256sum -c - + chmod +x "$dir/$ASSET" + (cd "$dir" && "./$ASSET" --appimage-extract > /dev/null) + echo "cli=$dir/squashfs-root/usr/bin/animathio-cli" >> "$GITHUB_OUTPUT" diff --git a/.github/workflows/index.yml b/.github/workflows/index.yml new file mode 100644 index 0000000..d174152 --- /dev/null +++ b/.github/workflows/index.yml @@ -0,0 +1,48 @@ +name: Community index +# Regenerates community-index.json (the single static file the editor reads) from +# community-plugins.json and the GitHub releases it points at. See docs/registry.md. +on: + workflow_call: + workflow_dispatch: + schedule: + # Plugins released from their own repositories are picked up within hours. + - cron: "17 */6 * * *" + push: + branches: [main] + paths: + - community-plugins.json + - schemas/community-index.schema.json + - scripts/registry.py +concurrency: + group: community-index + cancel-in-progress: false +permissions: + contents: read +jobs: + index: + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: write + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: main + - run: python3 -m pip install -r scripts/requirements.txt + - name: Regenerate community-index.json + env: + GH_TOKEN: ${{ github.token }} + # Not strict: a plugin whose release cannot be verified keeps its previous entry + # (or is left out) and a warning annotation is raised; the other plugins still update. + run: python3 scripts/registry.py index + - name: Commit the index + run: | + if git diff --quiet -- community-index.json; then + echo "community-index.json is up to date" + exit 0 + fi + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git add community-index.json + git commit -m "chore(registry): update community-index.json" + git push origin HEAD:main diff --git a/.github/workflows/registry.yml b/.github/workflows/registry.yml new file mode 100644 index 0000000..f357d28 --- /dev/null +++ b/.github/workflows/registry.yml @@ -0,0 +1,70 @@ +name: Registry +# Submission checks for community-plugins.json (see docs/registry.md and CONTRIBUTING.md). +on: + pull_request: + paths: + - community-plugins.json + - community/** + - schemas/** + - scripts/registry*.py + - scripts/check_submission.py + - scripts/test_registry.py + - scripts/requirements.txt + - README.md + - .github/workflows/registry.yml + - .github/actions/** + push: + branches: [main] + paths: + - community-plugins.json + - schemas/** + - scripts/** + - .github/workflows/registry.yml + workflow_dispatch: +permissions: + contents: read +jobs: + registry: + runs-on: ubuntu-latest + timeout-minutes: 45 + env: + CARGO_BUILD_JOBS: 3 + CARGO_PROFILE_DEV_DEBUG: 0 + CARGO_INCREMENTAL: 0 + ANIMATHIO_AUDIO: none + GH_TOKEN: ${{ github.token }} + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + persist-credentials: false + - name: Install tools + run: | + python3 -m pip install -r scripts/requirements.txt + rustup toolchain install stable --profile minimal --target wasm32-wasip2 + rustup default stable + - name: Registry script tests + run: python3 -m unittest discover -s scripts -v + - name: Validate community-plugins.json + # Schema, unique and unreserved ids, public repositories, OSI/OFL licenses, README table. + run: python3 scripts/registry.py validate + - name: Resolve releases into an index + # External plugins need a published release (asset + .sha256); plugins hosted here are + # released after merge, so they are built below instead. + run: python3 scripts/registry.py index --strict --allow-unreleased-hosted --previous /dev/null --output "$RUNNER_TEMP/index.json" + - name: Released AniMathIO CLI + id: cli + uses: ./.github/actions/animathio-cli + with: + github-token: ${{ github.token }} + - name: Build and smoke-test changed entries + env: + BASE_REF: ${{ github.base_ref }} + run: | + if [ "${{ github.event_name }}" = "pull_request" ]; then + git show "origin/$BASE_REF:community-plugins.json" > "$RUNNER_TEMP/base.json" 2>/dev/null || echo '{"plugins":[]}' > "$RUNNER_TEMP/base.json" + scope=(--base "$RUNNER_TEMP/base.json") + else + scope=(--all) + fi + python3 scripts/check_submission.py "${{ steps.cli.outputs.cli }}" "$RUNNER_TEMP/index.json" "$RUNNER_TEMP/work" "${scope[@]}" diff --git a/.github/workflows/release-plugin.yml b/.github/workflows/release-plugin.yml new file mode 100644 index 0000000..3599d36 --- /dev/null +++ b/.github/workflows/release-plugin.yml @@ -0,0 +1,89 @@ +name: Release plugin +# Tag @ (or run manually with the plugin directory) to build a plugin +# hosted in this repository and publish `-.amplugin` plus its `.sha256`. +# The tag must be on main, the plugin must be listed in community-plugins.json and its +# plugin.toml must carry exactly that id and version. Versions are immutable: a release +# that exists is never replaced. +on: + push: + tags: + - "*@*" + workflow_dispatch: + inputs: + path: + description: "Plugin directory to release, e.g. community/code-snippets (version from its plugin.toml)" + required: true +permissions: + contents: read +jobs: + release: + runs-on: ubuntu-latest + timeout-minutes: 45 + permissions: + contents: write + env: + CARGO_BUILD_JOBS: 3 + CARGO_PROFILE_DEV_DEBUG: 0 + CARGO_INCREMENTAL: 0 + ANIMATHIO_AUDIO: none + GH_TOKEN: ${{ github.token }} + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Only release what is on main + run: | + git fetch origin main + git merge-base --is-ancestor "$GITHUB_SHA" origin/main || { echo "::error::$GITHUB_SHA is not on main"; exit 1; } + - name: Install tools + run: | + python3 -m pip install -r scripts/requirements.txt + rustup toolchain install stable --profile minimal --target wasm32-wasip2 + rustup default stable + - name: Resolve the plugin from the registry + id: plugin + env: + INPUT_PATH: ${{ inputs.path }} + run: | + if [ "$GITHUB_EVENT_NAME" = "push" ]; then + python3 scripts/registry.py resolve --tag "$GITHUB_REF_NAME" | tee -a "$GITHUB_OUTPUT" + else + python3 scripts/registry.py resolve --path "$INPUT_PATH" | tee -a "$GITHUB_OUTPUT" + fi + - name: Refuse to replace an existing release + env: + TAG: ${{ steps.plugin.outputs.tag }} + run: | + if gh release view "$TAG" > /dev/null 2>&1; then + echo "::error::release $TAG already exists; bump the version in plugin.toml" + exit 1 + fi + - name: Build and package + env: + PLUGIN_PATH: ${{ steps.plugin.outputs.path }} + run: python3 scripts/registry.py package "$PLUGIN_PATH" --out dist + - name: Released AniMathIO CLI + id: cli + uses: ./.github/actions/animathio-cli + with: + github-token: ${{ github.token }} + - name: Load and render with the released CLI + env: + PLUGIN_ID: ${{ steps.plugin.outputs.id }} + run: python3 scripts/registry_smoke.py "${{ steps.cli.outputs.cli }}" dist --only "$PLUGIN_ID" + - name: Publish the release + env: + TAG: ${{ steps.plugin.outputs.tag }} + PLUGIN_ID: ${{ steps.plugin.outputs.id }} + VERSION: ${{ steps.plugin.outputs.version }} + run: | + sha=$(cut -d' ' -f1 "dist/$PLUGIN_ID-$VERSION.amplugin.sha256") + printf '%s %s\n\nSHA-256: `%s`\n\nInstall from the Plugins tab in AniMathIO 2.2+ (Browse), or download the .amplugin into your user plugin folder. See the README for details.\n' \ + "$PLUGIN_ID" "$VERSION" "$sha" > notes.md + gh release create "$TAG" dist/*.amplugin dist/*.amplugin.sha256 \ + --target "$GITHUB_SHA" --title "$PLUGIN_ID $VERSION" --notes-file notes.md --latest=false + index: + needs: release + permissions: + contents: write + uses: ./.github/workflows/index.yml diff --git a/.gitignore b/.gitignore index 395b52a..74157dc 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ .host/ .generated/ *.deb +__pycache__/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9683a6d..12d437b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,12 +1,106 @@ # Contributing -For a community listing, submit a PR adding a table row with a short description, -public source URL, explicit license, passing public CI URL and minimum ABI version. -The source must build for wasm32-wasip2 and package a matching plugin.toml and -plugin.wasm. Use unique reverse-domain IDs and document parameters and host requirements. -No network access or telemetry beyond what the documented sandbox permits; disclose -all host services and capabilities used. Do not imply that a listing is a security audit. - -Template/example changes must pass CI including generated-template builds and -released-host smoke renders. Keep the vendored ABI unchanged unless deliberately -upgrading the contract and documenting compatibility. Use Conventional Commits. +## Listing a community plugin + +Community plugins are listed in [`community-plugins.json`](community-plugins.json) and show up in +the editor's Plugins tab (AniMathIO 2.2+). To list yours, open a pull request that adds one entry +(the format and the generated index are described in [docs/registry.md](docs/registry.md)): + +```json +{ + "id": "com.example.spiral", + "name": "Spiral", + "author": "Ada Example", + "description": "A keyframeable spiral clip source", + "repo": "ada/animathio-spiral", + "license": "MIT", + "min_abi": "1.1.0" +} +``` + +then run `python3 scripts/registry.py table --write` to refresh the README table (CI checks it). +Add `"path": ""` if the plugin lives in a subdirectory of a repository with +several plugins. A plugin developed in this repository goes under `community/` and uses +`"repo": "AniMathIO/plugins"` with that `path`. + +### Rules + +* **Id**: a unique reverse-domain id you control (`com.example.spiral`, `io.github..`), + lowercase, never `org.animathio.*` (reserved for first-party plugins; the host will not load + such an id from the user plugin folder). It must equal `id` in `plugin.toml`. Ids are never reused. +* **Source and license**: public GitHub repository with a recognizable `LICENSE`. The `license` + field is an SPDX expression whose identifiers are all OSI-approved (or SIL OFL for bundled + fonts and assets) and include the license GitHub detects in your repository. Keep the notices + for anything you bundle inside the `.amplugin` (like `community/code-snippets`). +* **Build**: use the plugin template layout (`cargo generate gh:AniMathIO/plugins template`): a + `build.sh` that builds for `wasm32-wasip2` and packages `target/.amplugin` with + `plugin.toml` and `plugin.wasm`. +* **Release before you submit** (plugins outside this repository): publish a GitHub release + tagged `@`, or `v`/`` when the repository has a single plugin and + no `path`, carrying exactly two assets, `-.amplugin` and + `-.amplugin.sha256` (`sha256sum` format). `plugin.toml` must have the same `id` and + `version`, and `api_version` must equal `min_abi`. Recipe for your repository + (`.github/workflows/release.yml`, triggered by pushing a tag such as `v0.1.0`): + + ```yaml + on: + push: + tags: ["v*"] + permissions: + contents: write + jobs: + release: + runs-on: ubuntu-latest + env: + GH_TOKEN: ${{ github.token }} + steps: + - uses: actions/checkout@v4 + - run: rustup target add wasm32-wasip2 && bash build.sh + - run: | + id=$(python3 -c "import tomllib; print(tomllib.load(open('plugin.toml','rb'))['id'])") + version=$(python3 -c "import tomllib; print(tomllib.load(open('plugin.toml','rb'))['version'])") + cp target/*.amplugin "$id-$version.amplugin" + sha256sum "$id-$version.amplugin" > "$id-$version.amplugin.sha256" + gh release create "$GITHUB_REF_NAME" "$id-$version.amplugin" "$id-$version.amplugin.sha256" --generate-notes + ``` + + Pin actions by digest if you prefer; releases are immutable, so ship fixes as a new version. + New versions need no pull request: the index picks up the latest release within hours. +* **Behaviour**: document parameters and the host services you use. No network access or + telemetry beyond what the documented sandbox permits (plugins cannot open sockets or files). + A source plugin must draw something with its default parameters. +* **Honest listing**: do not imply that a listing is a security audit or endorsement. + +### What CI checks + +`.github/workflows/registry.yml` validates the JSON against the schema, that ids are unique, not +reserved and not delisted, that the repository exists and is public, the license, that the README +table is in sync, that the latest release resolves (assets, SHA-256 and manifest all agree), that +the source builds for `wasm32-wasip2` with its `build.sh` and produces the same id, version and +ABI, and that the released package loads and renders with the released AniMathIO CLI. Run the +same checks locally with `python3 scripts/registry.py validate` and +`python3 scripts/registry_smoke.py PATH/TO/animathio-cli DIR_WITH_AMPLUGIN`. + +CI builds the plugin from your repository, so review your own `build.rs` and dependencies as +you would for any CI. Fork pull requests run with a read-only token and no secrets. + +### Review + +A maintainer reviews every listing before merge: the description, the license, whether the plugin +does what it says and uses the sandbox as documented. Review is not a security audit and a +merged listing is not an endorsement. Updates (new versions) do not need review; changes to a +listing's metadata do. + +### Delisting + +A maintainer can delist a plugin (malicious or deceptive behaviour, an unresponsive broken +release, licence problems, or at the author's request) by moving its entry to `delisted` with +a reason in `community-plugins.json`. The next index run removes it from Browse; users who installed it +get a notice with the reason in the editor. The id stays reserved. Authors can ask for delisting +by opening an issue or a pull request. + +## Template, examples and the vendored ABI + +Template/example changes must pass CI including generated-template builds and released-host smoke +renders. Keep the vendored ABI unchanged unless deliberately upgrading the contract and +documenting compatibility. Use Conventional Commits. diff --git a/README.md b/README.md index 060b1dd..b477559 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # AniMathIO plugins -A cargo-generate template, working examples and community index for AniMathIO 2. +A cargo-generate template, working examples and the community plugin registry for AniMathIO 2. MIT licensed, like AniMathIO. Plugins are sandboxed WebAssembly components. ## Contents @@ -13,17 +13,29 @@ MIT licensed, like AniMathIO. Plugins are sandboxed WebAssembly components. ## Community plugins -| Name | Description | Source | License | CI | ABI | + +| Name | Author | Description | License | ABI | Source | | --- | --- | --- | --- | --- | --- | -| [Code Snippets](community/code-snippets) | Syntax-highlighted code with reveal and token morph animations | [Source](https://github.com/AniMathIO/plugins/tree/main/community/code-snippets) | MIT; font OFL-1.1 | [Plugins CI](https://github.com/AniMathIO/plugins/actions/workflows/ci.yml) | 1.1.0 | +| [Code Snippets](https://github.com/AniMathIO/plugins/tree/HEAD/community/code-snippets) | AniMathIO | Syntax-highlighted code with type-on reveal and token morph animations | MIT AND OFL-1.1 | 1.1.0 | [AniMathIO/plugins](https://github.com/AniMathIO/plugins/tree/HEAD/community/code-snippets) | + -Submit a PR adding a row under the rules in -[CONTRIBUTING.md](CONTRIBUTING.md). A listing is not an endorsement or security audit. +Install from the editor's Plugins tab in AniMathIO 2.2+, or manually as described +[below](#installing-a-plugin). Every +plugin is a versioned GitHub release with a SHA-256 checksum; the editor reads the generated +[`community-index.json`](community-index.json) and verifies each download against it. + +This table is generated from [`community-plugins.json`](community-plugins.json). To list your +plugin, open a PR adding an entry under the rules in [CONTRIBUTING.md](CONTRIBUTING.md); the +registry format, release convention and index are specified in [docs/registry.md](docs/registry.md). +A listing is not an endorsement or security audit. ## Installing a plugin -Plugins are `.amplugin` files. AniMathIO loads every bundle in your user plugin folder at -startup; restart the editor after adding or removing one: +In AniMathIO 2.2+ use the editor's Plugins tab (Browse, Install, then enable the plugin). +To install manually, download `-.amplugin` from the plugin's release +(for the plugins hosted here: the [releases page](https://github.com/AniMathIO/plugins/releases)) +and check it against the `.sha256` asset. AniMathIO loads every bundle in your user plugin +folder at startup; restart the editor after adding or removing one: | OS | User plugin folder | | --- | --- | @@ -31,11 +43,11 @@ startup; restart the editor after adding or removing one: | macOS | `~/Library/Application Support/animathio/plugins` | | Windows | `%APPDATA%\animathio\plugins` | -Community plugins are never bundled or enabled by AniMathIO itself: you install the ones -you want. They run in the same sandbox as first-party plugins (no network or file access, +Community plugins are never bundled or enabled by AniMathIO itself: you install (and enable) +the ones you want. They run in the same sandbox as first-party plugins (no network or file access, memory and time limits), and they cannot replace the bundled `org.animathio.*` plugins. -Build a plugin from its folder with `bash build.sh` (see each plugin's README) and copy -the resulting `.amplugin` into the folder above. +To build one from source instead, run `bash build.sh` in its folder (see each plugin's README) +and copy the resulting `.amplugin` into the folder above. ## Quick start diff --git a/RELEASING.md b/RELEASING.md new file mode 100644 index 0000000..6172fcd --- /dev/null +++ b/RELEASING.md @@ -0,0 +1,55 @@ +# Releasing plugins hosted in this repository + +Plugins under `community/` are released from this repository; the editor downloads the assets +of these releases (see [docs/registry.md](docs/registry.md)). The plugin must be listed in +[`community-plugins.json`](community-plugins.json) (added by pull request) first. + +1. Set `version` in the plugin's `plugin.toml` (and `Cargo.toml`) and merge it to `main`. +2. Tag that commit `@` and push the tag: + + ```sh + git checkout main && git pull --ff-only + git tag io.github.animathio.code-snippets@0.1.0 + git push origin io.github.animathio.code-snippets@0.1.0 + ``` + + or, without a local tag, run the workflow against `main`: + + ```sh + gh workflow run release-plugin.yml --repo AniMathIO/plugins --ref main -f path=community/code-snippets + ``` + +3. `release-plugin.yml` checks that the tag is on `main`, that `plugin.toml` has this id and + version, builds the plugin with its `build.sh`, loads and renders it with the released + AniMathIO CLI, and creates the release with `-.amplugin` and + `-.amplugin.sha256`. It then calls `index.yml`, which commits the refreshed + `community-index.json` to `main`. +4. Check that the run is green, that + lists the new + version, and that `sha256sum -c` passes on the downloaded assets. + +Versions are immutable: if a release is wrong, publish the next patch version. To withdraw a bad +release, `gh release delete --cleanup-tag --yes` and run the *Community index* workflow; the +previous release becomes the latest again (or the plugin leaves the index if there is none). + +## Dry run + +```sh +scripts/dry-run-release.sh community/code-snippets path/to/animathio-cli +``` + +builds the plugin, writes the assets, smoke-tests them and generates a `community-index.json` +from the local assets exactly as the index workflow does from the release (output in +`target/dry-run/`, which is git-ignored). + +## First release: Code Snippets 0.1.0 + +Plugin id `io.github.animathio.code-snippets` (it was `org.animathio.community.code-snippets` +before: ids under `org.animathio.*` are reserved and the host would not load them from the user +plugin folder). After the registry pull request is merged: + +```sh +git checkout main && git pull --ff-only +git tag io.github.animathio.code-snippets@0.1.0 +git push origin io.github.animathio.code-snippets@0.1.0 +``` diff --git a/community-index.json b/community-index.json new file mode 100644 index 0000000..d3068de --- /dev/null +++ b/community-index.json @@ -0,0 +1,6 @@ +{ + "$schema": "./schemas/community-index.schema.json", + "schema_version": 1, + "plugins": [], + "delisted": [] +} diff --git a/community-plugins.json b/community-plugins.json new file mode 100644 index 0000000..dd7d98f --- /dev/null +++ b/community-plugins.json @@ -0,0 +1,17 @@ +{ + "$schema": "./schemas/community-plugins.schema.json", + "schema_version": 1, + "plugins": [ + { + "id": "io.github.animathio.code-snippets", + "name": "Code Snippets", + "author": "AniMathIO", + "description": "Syntax-highlighted code with type-on reveal and token morph animations", + "repo": "AniMathIO/plugins", + "path": "community/code-snippets", + "license": "MIT AND OFL-1.1", + "min_abi": "1.1.0" + } + ], + "delisted": [] +} diff --git a/community/code-snippets/README.md b/community/code-snippets/README.md index 6b92043..5a45626 100644 --- a/community/code-snippets/README.md +++ b/community/code-snippets/README.md @@ -2,7 +2,9 @@ Animated, syntax-highlighted code for AniMathIO 2. ABI **1.1.0**, tested with the released **AniMathIO 2.1.0** Linux CLI. MIT; embedded JetBrains Mono is OFL 1.1. -Plugin ID: `org.animathio.community.code-snippets`. +Plugin ID: `io.github.animathio.code-snippets` (renamed before the first release from +`org.animathio.community.code-snippets`: `org.animathio.*` ids are reserved for first-party +plugins and the host does not load them from the user plugin folder). A behavioral port of [Shiki Magic Move](https://github.com/shikijs/shiki-magic-move/tree/v1.1.0) by Anthony Fu (**MIT**): retained tokens slide to their new positions while removed diff --git a/community/code-snippets/plugin.toml b/community/code-snippets/plugin.toml index 04c8d25..528e2c8 100644 --- a/community/code-snippets/plugin.toml +++ b/community/code-snippets/plugin.toml @@ -1,5 +1,5 @@ api_version = "1.1.0" -id = "org.animathio.community.code-snippets" +id = "io.github.animathio.code-snippets" name = "Code Snippets" version = "0.1.0" description = "Syntax-highlighted code with type-on reveal and token morph animations" diff --git a/community/code-snippets/smoke.py b/community/code-snippets/smoke.py index c5ddcf1..7effca2 100644 --- a/community/code-snippets/smoke.py +++ b/community/code-snippets/smoke.py @@ -54,7 +54,7 @@ def run(*args): }''' def render(name, frame=0, **params): - clip['kind'] = {'Plugin': {'plugin_id': 'org.animathio.community.code-snippets', + clip['kind'] = {'Plugin': {'plugin_id': 'io.github.animathio.code-snippets', 'params': dict(dict(code=CODE, code_to=TARGET, font_size=4.0), **params)}} file = WORK / (name + '.amio') with zipfile.ZipFile(file, 'w', zipfile.ZIP_DEFLATED) as z: diff --git a/docs/registry.md b/docs/registry.md new file mode 100644 index 0000000..110779c --- /dev/null +++ b/docs/registry.md @@ -0,0 +1,189 @@ +# Community plugin registry + +How AniMathIO 2.2+ finds, verifies and installs community plugins +([AniMathIO#304](https://github.com/AniMathIO/AniMathIO/issues/304)). This page is the +contract between this repository and the editor. + +``` +community-plugins.json hand-edited, reviewed by PR (id, name, author, repo, license, ...) + | nothing here changes per plugin version + v scripts/registry.py index (.github/workflows/index.yml) +community-index.json generated: latest release, download URL, SHA-256, ABI per plugin + ^ + | GitHub releases (assets `-.amplugin` + `.sha256`) + +- AniMathIO/plugins tag `@`, made by release-plugin.yml + +- / the author's own releases +``` + +The editor fetches **one static file**: + +``` +https://raw.githubusercontent.com/AniMathIO/plugins/main/community-index.json +``` + +and downloads plugins only from the `download_url` it contains. Both files have a JSON +Schema in [`schemas/`](../schemas) (`community-plugins.schema.json`, `community-index.schema.json`). + +## `community-plugins.json` (the registry) + +```json +{ + "$schema": "./schemas/community-plugins.schema.json", + "schema_version": 1, + "plugins": [ + { + "id": "io.github.animathio.code-snippets", + "name": "Code Snippets", + "author": "AniMathIO", + "description": "Syntax-highlighted code with type-on reveal and token morph animations", + "repo": "AniMathIO/plugins", + "path": "community/code-snippets", + "license": "MIT AND OFL-1.1", + "min_abi": "1.1.0" + } + ], + "delisted": [] +} +``` + +| Field | Rule | +| --- | --- | +| `id` | Reverse-domain, lowercase, at least three dot-separated labels, at most 100 characters. Unique. **Never `org.animathio.*`**: those ids are reserved for first-party plugins and the host refuses to load them from the user plugin folder. Must equal `id` in the plugin's `plugin.toml`. | +| `name`, `author`, `description` | Display text (60 / 80 / 10-200 characters). Names are unique (case-insensitive). | +| `repo` | Public GitHub repository `owner/name` that carries the release assets. | +| `path` | Optional subdirectory of `repo` that holds the plugin (`plugin.toml`, `build.sh`). Required for plugins hosted here (`community/`). A plugin with a `path` is a monorepo plugin: its release tags must be `@`. | +| `license` | SPDX expression, e.g. `MIT`, `Apache-2.0 OR MIT`, `MIT AND OFL-1.1`. Every identifier must be OSI-approved or an SIL OFL variant ([`schemas/osi-approved-licenses.txt`](../schemas/osi-approved-licenses.txt)). For plugins outside this repository, the licence GitHub detects in the repository must be one of the declared identifiers. | +| `min_abi` | The plugin ABI (`api_version` in `plugin.toml`) of the latest release. The index builder refuses a release whose manifest says otherwise, so raising the ABI is a one-line PR together with the release. | +| `delisted[]` | `{ "id", "reason", "date" }` for removed plugins. A delisted id can never be listed again. | + +No version, URL or checksum lives here: they are resolved from releases. + +## Releases + +A release is a GitHub release in `repo` with exactly two assets: + +| Asset | Content | +| --- | --- | +| `-.amplugin` | The plugin bundle (a zip with `plugin.toml` and `plugin.wasm` at its root). | +| `-.amplugin.sha256` | ` ` (`sha256sum` format). | + +* **Tag:** `@` for every plugin; additionally `v` or `` for a + plugin that has no `path` (one plugin per repository). `` is `MAJOR.MINOR.PATCH`. +* The bundle's `plugin.toml` must have the same `id`, the same `version` and `api_version == min_abi`. +* Draft and pre-release releases are ignored. The latest version is the highest + `MAJOR.MINOR.PATCH` (numeric, so `1.10.0 > 1.9.0`) among the remaining releases. +* Releases are immutable: never replace an asset, publish a new version instead. +* Plugins hosted here are released by [`release-plugin.yml`](../.github/workflows/release-plugin.yml) + when a `@` tag is pushed (see [RELEASING.md](../RELEASING.md)). Plugins in their + own repository are released by their author (see CONTRIBUTING.md for a ready-made workflow + recipe: `bash build.sh`, then upload the two assets). + +## `community-index.json` (what the editor reads) + +Generated by `scripts/registry.py index` from the registry and the releases: for each plugin it +downloads the latest release asset, recomputes its SHA-256, checks it against the `.sha256` +asset, opens the archive and checks `plugin.toml`. Never edit it by hand. + +```json +{ + "$schema": "./schemas/community-index.schema.json", + "schema_version": 1, + "plugins": [ + { + "id": "io.github.animathio.code-snippets", + "name": "Code Snippets", + "author": "AniMathIO", + "description": "Syntax-highlighted code with type-on reveal and token morph animations", + "license": "MIT AND OFL-1.1", + "repo": "AniMathIO/plugins", + "path": "community/code-snippets", + "source_url": "https://github.com/AniMathIO/plugins/tree/HEAD/community/code-snippets", + "kinds": ["clip-source"], + "min_abi": "1.1.0", + "version": "0.1.0", + "download_url": "https://github.com/AniMathIO/plugins/releases/download/io.github.animathio.code-snippets@0.1.0/io.github.animathio.code-snippets-0.1.0.amplugin", + "sha256": "bf7bb255cf4f5dc90f49749679197a1c8799193648082fd7946a2b540d33d725", + "size": 795124, + "released_at": "2026-11-17T01:00:00Z" + } + ], + "delisted": [ + { "id": "com.example.removed", "reason": "Unmaintained", "date": "2026-11-20" } + ] +} +``` + +(Example values; the real file is the source of truth.) + +| Field | Meaning | +| --- | --- | +| `schema_version` | `1`. A client that sees another value must ignore the file and say it needs a newer AniMathIO. Unknown extra fields must be ignored (they are only added in a compatible way within version 1). | +| `plugins[]` | One entry per listed plugin **that has a verified release**, sorted by `id`. Only the latest release is described. | +| `id`, `name`, `author`, `description`, `license`, `repo`, `path?` | Copied from the registry. | +| `source_url` | Human-facing link to the source (open in a browser; never downloaded). | +| `kinds` | Plugin kinds from the release's `plugin.toml` (`clip-source`, `effect`, `audio-effect`, `animation-preset`, `importer`). | +| `min_abi` | `api_version` from the release's `plugin.toml`: the minimum host plugin ABI. Show it in Browse and apply the same compatibility rule the host applies when loading a bundle (reuse that code), instead of reimplementing it. | +| `version` | Latest version (`plugin.toml` `version`). Compare numerically per component with the installed version to offer updates. | +| `download_url` | HTTPS URL of the `.amplugin` asset on `github.com` (redirects to GitHub's CDN). Download only this, never anything derived from `repo`. | +| `sha256` | Lowercase hex SHA-256 of the file. **Reject the download if it differs.** | +| `size` | Bytes. Reject a download larger than this. | +| `released_at` | RFC 3339 UTC publication time of the release. | +| `delisted[]` | `{ id, reason, date }` removed plugins. If one is installed, show a notice with the reason; do not remove it silently. | + +### Client rules + +1. Fetch the index with a short timeout and no personal data (the update check's client). + `ANIMATHIO_NO_UPDATE_CHECK=1` disables background fetches; an explicit Browse click is a + user action. Honour `ETag` / `If-None-Match` (raw.githubusercontent.com caches for about + five minutes). On failure, keep working with the plugins already installed. +2. Install = download `download_url`, check size and `sha256`, open the archive and confirm + that `plugin.toml` has the index `id` and `version` and that `kinds`/`api_version` match, + then write it atomically to the user plugin folder (suggested file name `.amplugin`, so an + update replaces it). The editor refuses `org.animathio.*` ids already. +3. Installed plugins start disabled; the user enables each one. +4. A project that references a plugin id that is not installed can offer "Install" when that + id is in the index. + +### Failure handling + +The index is regenerated whenever a plugin is released here, whenever `community-plugins.json` +changes and every six hours (for plugins released from other repositories). If one plugin's +latest release cannot be verified (missing asset, checksum or manifest mismatch, deleted +release), that plugin is **left out** and the run reports a warning, the other plugins still +update. If GitHub itself is unreachable or rate limiting, the previous entries are kept. +Pull requests that touch the registry run the same resolution strictly. + +## Submitting, releasing, delisting + +* Submission: [CONTRIBUTING.md](../CONTRIBUTING.md). CI is + [`registry.yml`](../.github/workflows/registry.yml): schema, unique and unreserved ids, public + repository, OSI/OFL licence, README table in sync, a strict resolution of the release, then + build (`wasm32-wasip2`) and load/render with the released AniMathIO CLI + ([`scripts/registry_smoke.py`](../scripts/registry_smoke.py)). A source plugin must draw + something with its default parameters; other kinds are checked for loading only. +* Releasing plugins hosted here: [RELEASING.md](../RELEASING.md). +* Delisting: a maintainer moves the entry to `delisted` with a reason. The next index run drops it + from `plugins` and lists it under `delisted`. + +## Scripts + +All are Python 3.11+ (`scripts/requirements.txt`: `jsonschema`, `Pillow`). + +| Command | Does | +| --- | --- | +| `python3 scripts/registry.py validate [--offline]` | Static checks (the submission CI). | +| `python3 scripts/registry.py table --write` | Regenerates the README table from the registry (`--check` in CI). | +| `python3 scripts/registry.py package PLUGIN_DIR --out DIR` | Runs `build.sh`, writes the two release assets. | +| `python3 scripts/registry.py resolve --tag TAG` or `--path DIR` | Maps a release tag or plugin directory to its registry entry. | +| `python3 scripts/registry.py index [--assets-dir DIR] [--strict]` | Generates `community-index.json`; `--assets-dir` is a dry run using local assets instead of GitHub. | +| `python3 scripts/registry_smoke.py CLI PLUGIN_DIR` | Loads and renders the plugins with a released CLI. | +| `scripts/dry-run-release.sh PLUGIN_DIR CLI` | The whole release + index flow locally, without tagging or uploading. | +| `python3 -m unittest discover -s scripts` | Tests of the registry tooling (offline). | + +## Not covered + +* Only the latest version of each plugin is indexed (no version history or rollback list). +* A listing is not a security audit. The sandbox (no network or file access, memory and time + limits) is the protection; see CONTRIBUTING.md. +* Release assets are not signed; integrity comes from the SHA-256 in the index plus HTTPS from + github.com. Build provenance attestations could be added to `release-plugin.yml` later. diff --git a/schemas/community-index.schema.json b/schemas/community-index.schema.json new file mode 100644 index 0000000..1596f3b --- /dev/null +++ b/schemas/community-index.schema.json @@ -0,0 +1,72 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://raw.githubusercontent.com/AniMathIO/plugins/main/schemas/community-index.schema.json", + "title": "AniMathIO community plugin index", + "description": "Generated by scripts/registry.py index from community-plugins.json and the GitHub releases it points at. The editor fetches this single static file. Never edit it by hand.", + "type": "object", + "additionalProperties": false, + "required": ["schema_version", "plugins", "delisted"], + "properties": { + "$schema": { "type": "string" }, + "schema_version": { "const": 1 }, + "plugins": { + "description": "One entry per listed plugin that has a verified release, sorted by id. Each entry describes the latest release only.", + "type": "array", + "items": { "$ref": "#/$defs/entry" } + }, + "delisted": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": ["id", "reason", "date"], + "properties": { + "id": { "type": "string" }, + "reason": { "type": "string" }, + "date": { "type": "string" } + } + } + } + }, + "$defs": { + "entry": { + "type": "object", + "additionalProperties": false, + "required": ["id", "name", "author", "description", "license", "repo", "source_url", "kinds", "min_abi", "version", "download_url", "sha256", "size", "released_at"], + "properties": { + "id": { "type": "string" }, + "name": { "type": "string" }, + "author": { "type": "string" }, + "description": { "type": "string" }, + "license": { "type": "string" }, + "repo": { "type": "string" }, + "path": { "type": "string" }, + "source_url": { "description": "Human-facing link to the source (browsable page, never downloaded by the editor).", "type": "string", "format": "uri" }, + "kinds": { + "description": "Plugin kinds from the release's plugin.toml.", + "type": "array", + "items": { "enum": ["clip-source", "effect", "audio-effect", "animation-preset", "importer"] }, + "minItems": 1 + }, + "min_abi": { + "description": "api_version from the release's plugin.toml: install only when the host ABI is at least this (same major, minor >=).", + "type": "string", + "pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+$" + }, + "version": { + "description": "Semantic version of the latest release (= plugin.toml version).", + "type": "string", + "pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+$" + }, + "download_url": { + "description": "HTTPS URL of the .amplugin release asset on github.com (follows redirects to the GitHub release CDN).", + "type": "string", + "pattern": "^https://github\\.com/[^/]+/[^/]+/releases/download/.+\\.amplugin$" + }, + "sha256": { "description": "Lowercase hex SHA-256 of the downloaded file. The editor must reject a download that does not match.", "type": "string", "pattern": "^[0-9a-f]{64}$" }, + "size": { "description": "Size of the .amplugin in bytes; the editor can reject larger downloads.", "type": "integer", "minimum": 1 }, + "released_at": { "description": "RFC 3339 UTC time the release was published.", "type": "string" } + } + } + } +} diff --git a/schemas/community-plugins.schema.json b/schemas/community-plugins.schema.json new file mode 100644 index 0000000..6c6fcbd --- /dev/null +++ b/schemas/community-plugins.schema.json @@ -0,0 +1,78 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://raw.githubusercontent.com/AniMathIO/plugins/main/schemas/community-plugins.schema.json", + "title": "AniMathIO community plugin registry", + "description": "Hand-edited list of community plugins (submitted by pull request). Nothing here changes per plugin version: versions, download URLs and checksums are resolved from GitHub releases into community-index.json.", + "type": "object", + "additionalProperties": false, + "required": ["schema_version", "plugins"], + "properties": { + "$schema": { "type": "string" }, + "schema_version": { "const": 1 }, + "plugins": { + "type": "array", + "items": { "$ref": "#/$defs/plugin" } + }, + "delisted": { + "description": "Plugins removed from the registry. Their ids stay reserved and the editor tells users who installed them.", + "type": "array", + "items": { "$ref": "#/$defs/delisted" } + } + }, + "$defs": { + "id": { + "description": "Reverse-domain plugin id: lowercase, at least three dot-separated labels, never org.animathio.* (reserved for first-party plugins).", + "type": "string", + "maxLength": 100, + "pattern": "^[a-z0-9]+(?:[-_][a-z0-9]+)*(?:\\.[a-z0-9]+(?:[-_][a-z0-9]+)*){2,}$" + }, + "abi": { + "type": "string", + "pattern": "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)$" + }, + "plugin": { + "type": "object", + "additionalProperties": false, + "required": ["id", "name", "author", "description", "repo", "license", "min_abi"], + "properties": { + "id": { "$ref": "#/$defs/id" }, + "name": { "type": "string", "minLength": 1, "maxLength": 60 }, + "author": { "type": "string", "minLength": 1, "maxLength": 80 }, + "description": { "type": "string", "minLength": 10, "maxLength": 200 }, + "repo": { + "description": "GitHub repository (owner/name) whose releases carry the .amplugin files.", + "type": "string", + "pattern": "^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?/[A-Za-z0-9._-]+$" + }, + "path": { + "description": "Subdirectory of repo that holds the plugin (plugin.toml, build.sh). Present for monorepos, including every plugin hosted in AniMathIO/plugins (community/); when present, release tags must be @.", + "type": "string", + "maxLength": 200, + "pattern": "^[A-Za-z0-9._-]+(?:/[A-Za-z0-9._-]+)*$", + "not": { "pattern": "(^|/)\\.\\.?(/|$)" } + }, + "license": { + "description": "SPDX license expression, e.g. MIT, Apache-2.0 OR MIT, or MIT AND OFL-1.1 when a bundled font is OFL. Every identifier must be OSI-approved or an SIL OFL variant (schemas/osi-approved-licenses.txt).", + "type": "string", + "minLength": 2, + "maxLength": 120, + "pattern": "^[A-Za-z0-9.+() -]+$" + }, + "min_abi": { + "description": "Plugin ABI (plugin.toml api_version) of the latest release: the minimum host ABI the plugin needs.", + "$ref": "#/$defs/abi" + } + } + }, + "delisted": { + "type": "object", + "additionalProperties": false, + "required": ["id", "reason", "date"], + "properties": { + "id": { "$ref": "#/$defs/id" }, + "reason": { "type": "string", "minLength": 5, "maxLength": 300 }, + "date": { "type": "string", "format": "date", "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$" } + } + } + } +} diff --git a/schemas/osi-approved-licenses.txt b/schemas/osi-approved-licenses.txt new file mode 100644 index 0000000..e691f37 --- /dev/null +++ b/schemas/osi-approved-licenses.txt @@ -0,0 +1,136 @@ +# SPDX identifiers accepted in community-plugins.json `license` (one per line). +# Source: spdx/license-list-data v3.27.0, licenses with isOsiApproved=true and not deprecated, +# plus the SIL Open Font License variants (fonts and other assets). +# Regenerate from the SPDX list: keep every license with "isOsiApproved": true and no "isDeprecatedLicenseId". +0BSD +AAL +AFL-1.1 +AFL-1.2 +AFL-2.0 +AFL-2.1 +AFL-3.0 +AGPL-3.0-only +AGPL-3.0-or-later +APL-1.0 +APSL-1.0 +APSL-1.1 +APSL-1.2 +APSL-2.0 +Apache-1.1 +Apache-2.0 +Artistic-1.0 +Artistic-1.0-Perl +Artistic-1.0-cl8 +Artistic-2.0 +BSD-1-Clause +BSD-2-Clause +BSD-2-Clause-Patent +BSD-3-Clause +BSD-3-Clause-LBNL +BSL-1.0 +BlueOak-1.0.0 +CAL-1.0 +CAL-1.0-Combined-Work-Exception +CATOSL-1.1 +CDDL-1.0 +CECILL-2.1 +CERN-OHL-P-2.0 +CERN-OHL-S-2.0 +CERN-OHL-W-2.0 +CNRI-Python +CPAL-1.0 +CPL-1.0 +CUA-OPL-1.0 +ECL-1.0 +ECL-2.0 +EFL-1.0 +EFL-2.0 +EPL-1.0 +EPL-2.0 +EUDatagrid +EUPL-1.1 +EUPL-1.2 +Entessa +Fair +Frameworx-1.0 +GPL-2.0-only +GPL-2.0-or-later +GPL-3.0-only +GPL-3.0-or-later +HPND +ICU +IPA +IPL-1.0 +ISC +Intel +Jam +LGPL-2.0-only +LGPL-2.0-or-later +LGPL-2.1-only +LGPL-2.1-or-later +LGPL-3.0-only +LGPL-3.0-or-later +LPL-1.0 +LPL-1.02 +LPPL-1.3c +LiLiQ-P-1.1 +LiLiQ-R-1.1 +LiLiQ-Rplus-1.1 +MIT +MIT-0 +MIT-Modern-Variant +MPL-1.0 +MPL-1.1 +MPL-2.0 +MPL-2.0-no-copyleft-exception +MS-PL +MS-RL +MirOS +Motosoto +MulanPSL-2.0 +Multics +NASA-1.3 +NCSA +NGPL +NPOSL-3.0 +NTP +Naumen +Nokia +OCLC-2.0 +OFL-1.1 +OFL-1.1-RFN +OFL-1.1-no-RFN +OGTSL +OLDAP-2.8 +OLFL-1.3 +OSET-PL-2.1 +OSL-1.0 +OSL-2.0 +OSL-2.1 +OSL-3.0 +PHP-3.0 +PHP-3.01 +PostgreSQL +Python-2.0 +QPL-1.0 +RPL-1.1 +RPL-1.5 +RPSL-1.0 +RSCPL +SISSL +SPL-1.0 +SimPL-2.0 +Sleepycat +UCL-1.0 +UPL-1.0 +Unicode-3.0 +Unicode-DFS-2016 +Unlicense +VSL-1.0 +W3C +W3C-20150513 +Watcom-1.0 +Xnet +ZPL-2.0 +ZPL-2.1 +Zlib diff --git a/scripts/check_submission.py b/scripts/check_submission.py new file mode 100755 index 0000000..886831a --- /dev/null +++ b/scripts/check_submission.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 +"""Build and smoke-test registry entries (submission CI). + +Usage: python3 scripts/check_submission.py CLI INDEX_JSON WORK_DIR [--base community-plugins.json | --all] + +Targets are the entries that differ from --base (a previous copy of community-plugins.json; +new entries and changed fields count) or every entry with --all. For each target: + * hosted in AniMathIO/plugins: build it with its build.sh and package it like a release; + * elsewhere: download the release asset the index points at (already SHA-256 checked by + `registry.py index`), clone the repository at that release tag and build it with its + build.sh; the built package must carry the same id, version and ABI as the release. +Then every collected .amplugin is loaded and rendered with the released CLI. +""" +import json +import re +import shutil +import subprocess +import sys +import urllib.request +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import registry # noqa: E402 + + +def targets(current: dict, base_file: str | None) -> list[dict]: + if base_file is None: + return current["plugins"] + old = {p["id"]: p for p in json.loads(Path(base_file).read_text())["plugins"]} if Path(base_file).is_file() else {} + return [p for p in current["plugins"] if old.get(p["id"]) != p] + + +def main() -> int: + argv = sys.argv[1:] + cli, index_file, work = argv[0], Path(argv[1]), Path(argv[2]).resolve() + base = argv[argv.index("--base") + 1] if "--base" in argv else None + if "--all" not in argv and base is None: + print("pass --base FILE or --all", file=sys.stderr) + return 2 + index = {p["id"]: p for p in json.loads(index_file.read_text())["plugins"]} + chosen = targets(registry.load_json(registry.REGISTRY), None if "--all" in argv else base) + shutil.rmtree(work, ignore_errors=True) + plugins = work / "plugins" + plugins.mkdir(parents=True) + failures = [] + for entry in chosen: + pid = entry["id"] + print(f"== {pid}") + try: + if entry["repo"] == registry.HOSTED_REPO: + package, _ = registry.package_plugin(registry.ROOT / entry["path"], plugins) + print(f"built {package.name}") + continue + released = index.get(pid) + if released is None: + raise registry.RegistryError("no release in the index (publish a release first)") + asset = {"name": Path(released["download_url"]).name, "browser_download_url": released["download_url"]} + data = registry.GitHub().fetch(asset, registry.MAX_PLUGIN_BYTES) + if registry.sha256_hex(data) != released["sha256"]: + raise registry.RegistryError("download does not match the index checksum") + (plugins / asset["name"]).write_bytes(data) + tag = re.search(r"/releases/download/([^/]+)/", released["download_url"]).group(1) + src = work / "src" / pid + subprocess.run(["git", "clone", "--quiet", "--depth", "1", "--branch", tag, + f"https://github.com/{entry['repo']}.git", str(src)], check=True, timeout=300) + plugin_dir = src / entry.get("path", "") + if not (plugin_dir / "build.sh").is_file(): + raise registry.RegistryError(f"{entry.get('path', '.')}/build.sh not found in {entry['repo']}@{tag} " + "(use the plugin template layout)") + built, _ = registry.package_plugin(plugin_dir, work / "built") + manifest = registry.inspect_package(built.read_bytes(), built.name) + for key, want in (("id", released["id"]), ("version", released["version"]), ("api_version", released["min_abi"])): + if manifest[key] != want: + raise registry.RegistryError(f"source at {tag} builds {key} {manifest[key]!r}, release has {want!r}") + print(f"source at {tag} builds for wasm32-wasip2 and matches the release") + except (registry.RegistryError, subprocess.SubprocessError, OSError) as e: + failures.append(pid) + registry.annotate("error", f"{pid}: {e}") + if failures: + return 1 + if not any(plugins.glob("*.amplugin")): + print("no registry entries changed; nothing to smoke-test") + return 0 + return subprocess.run([sys.executable, str(Path(__file__).with_name("registry_smoke.py")), cli, str(plugins)]).returncode + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/dry-run-release.sh b/scripts/dry-run-release.sh new file mode 100755 index 0000000..470c493 --- /dev/null +++ b/scripts/dry-run-release.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# Local dry run of .github/workflows/release-plugin.yml + index.yml: no tag, no upload. +# Usage: scripts/dry-run-release.sh PLUGIN_DIR PATH/TO/animathio-cli [OUT_DIR] +# scripts/dry-run-release.sh community/code-snippets .host/cli/squashfs-root/usr/bin/animathio-cli +# Builds the plugin, writes the release assets (-.amplugin + .sha256), loads and renders +# it with the CLI, then generates community-index.json from those assets exactly as the index +# workflow would from the GitHub release, and validates it against schemas/community-index.schema.json. +set -euo pipefail +cd "$(dirname "$0")/.." +plugin=${1:?plugin directory} +cli=${2:?path to animathio-cli} +out=${3:-target/dry-run} +rm -rf "$out"; mkdir -p "$out" +eval "$(python3 scripts/registry.py resolve --path "$plugin" | sed 's/^/export REG_/')" +echo "== would tag $REG_tag" +python3 scripts/registry.py package "$plugin" --out "$out/assets" +python3 scripts/registry_smoke.py "$cli" "$out/assets" --only "$REG_id" +python3 scripts/registry.py index --assets-dir "$out/assets" --previous /dev/null --strict --output "$out/community-index.json" +(cd "$out/assets" && sha256sum -c ./*.sha256) +echo "== $out/community-index.json" +cat "$out/community-index.json" diff --git a/scripts/registry.py b/scripts/registry.py new file mode 100755 index 0000000..4863685 --- /dev/null +++ b/scripts/registry.py @@ -0,0 +1,554 @@ +#!/usr/bin/env python3 +"""Community plugin registry tooling (stdlib only; `validate` and `index` use jsonschema). + + registry.py validate [--offline] check community-plugins.json (submission CI) + registry.py package PLUGIN_DIR --out DIR build a hosted plugin and write the release assets + registry.py resolve (--tag TAG | --path DIR) map a release tag / plugin dir to registry data + registry.py index [--output FILE] ... resolve every plugin's latest release into + community-index.json + registry.py table [--check | --write] keep the README table in sync + +Format and rules: docs/registry.md. +""" +from __future__ import annotations + +import argparse +import datetime +import hashlib +import io +import json +import os +import re +import subprocess +import sys +import tomllib +import urllib.error +import urllib.request +import zipfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +REGISTRY = ROOT / "community-plugins.json" +INDEX = ROOT / "community-index.json" +README = ROOT / "README.md" +HOSTED_REPO = "AniMathIO/plugins" +RESERVED_PREFIX = "org.animathio." +SEMVER = re.compile(r"(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)") +KINDS = {"clip-source", "effect", "audio-effect", "animation-preset", "importer"} +MAX_PLUGIN_BYTES = 64 * 1024 * 1024 +MAX_MANIFEST_BYTES = 64 * 1024 +TABLE_START = "" +TABLE_END = "" + + +class RegistryError(Exception): + pass + + +class TransientError(RegistryError): + """GitHub could not be reached or is rate limiting: says nothing about the plugin itself.""" + + +def load_json(path: Path): + with open(path, encoding="utf-8") as f: + return json.load(f) + + +def semver_key(version: str): + return tuple(int(part) for part in version.split(".")) + + +def abi_at_most(a: str, b: str) -> bool: + return semver_key(a) <= semver_key(b) + + +def annotate(level: str, message: str): + # GitHub Actions turns these into annotations; elsewhere they are plain lines. + print(f"::{level}::{message}", file=sys.stderr) + + +# --- licences --------------------------------------------------------------------------- + +def approved_licenses() -> set[str]: + lines = (ROOT / "schemas" / "osi-approved-licenses.txt").read_text().splitlines() + return {line.strip() for line in lines if line.strip() and not line.startswith("#")} + + +def license_ids(expression: str) -> list[str]: + """License identifiers of an SPDX expression (operators, parentheses and exceptions dropped).""" + ids, skip_next = [], False + for token in re.findall(r"[()]|[A-Za-z0-9.+-]+", expression): + if token in "()": + continue + if skip_next: # exception id after WITH + skip_next = False + continue + if token in ("AND", "OR"): + continue + if token == "WITH": + skip_next = True + continue + ids.append(token) + return ids + + +# --- manifests and packages ------------------------------------------------------------- + +def read_manifest_text(text: str, where: str) -> dict: + try: + manifest = tomllib.loads(text) + except tomllib.TOMLDecodeError as e: + raise RegistryError(f"{where}: plugin.toml is not valid TOML: {e}") + for key in ("api_version", "id", "name", "version", "kinds"): + if key not in manifest: + raise RegistryError(f"{where}: plugin.toml lacks `{key}`") + if not SEMVER.fullmatch(str(manifest["version"])): + raise RegistryError(f"{where}: version {manifest['version']!r} must be MAJOR.MINOR.PATCH") + if not SEMVER.fullmatch(str(manifest["api_version"])): + raise RegistryError(f"{where}: api_version {manifest['api_version']!r} must be MAJOR.MINOR.PATCH") + kinds = manifest["kinds"] + if not isinstance(kinds, list) or not kinds or not set(kinds) <= KINDS: + raise RegistryError(f"{where}: kinds {kinds!r} must be a non-empty subset of {sorted(KINDS)}") + return manifest + + +def inspect_package(data: bytes, where: str) -> dict: + """Manifest of an .amplugin held in memory; checks the archive has the required members.""" + try: + with zipfile.ZipFile(io.BytesIO(data)) as z: + names = set(z.namelist()) + for required in ("plugin.toml", "plugin.wasm"): + if required not in names: + raise RegistryError(f"{where}: archive lacks {required}") + info = z.getinfo("plugin.toml") + if info.file_size > MAX_MANIFEST_BYTES: + raise RegistryError(f"{where}: plugin.toml is larger than {MAX_MANIFEST_BYTES} bytes") + return read_manifest_text(z.read("plugin.toml").decode("utf-8"), where) + except zipfile.BadZipFile: + raise RegistryError(f"{where}: not a zip archive") + + +def sha256_hex(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def package_plugin(plugin_dir: Path, out: Path, build: bool = True) -> tuple[Path, Path]: + manifest = read_manifest_text((plugin_dir / "plugin.toml").read_text(), str(plugin_dir)) + if build: + subprocess.run(["bash", "build.sh"], cwd=plugin_dir, check=True) + built = sorted((plugin_dir / "target").glob("*.amplugin"), key=lambda p: p.stat().st_mtime) + if not built: + raise RegistryError(f"{plugin_dir}: build.sh produced no target/*.amplugin") + data = built[-1].read_bytes() + packaged = inspect_package(data, str(built[-1])) + for key in ("id", "version", "api_version"): + if packaged[key] != manifest[key]: + raise RegistryError(f"{built[-1]}: {key} {packaged[key]!r} differs from plugin.toml {manifest[key]!r}") + name = f"{manifest['id']}-{manifest['version']}.amplugin" + out.mkdir(parents=True, exist_ok=True) + package, checksum = out / name, out / (name + ".sha256") + package.write_bytes(data) + checksum.write_text(f"{sha256_hex(data)} {name}\n") + return package, checksum + + +# --- release sources -------------------------------------------------------------------- + +class GitHub: + """Releases and assets from the GitHub API (token optional; public repositories only).""" + + def __init__(self): + self.token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN") + + def _open(self, url: str, accept: str, auth: bool): + headers = {"User-Agent": "animathio-registry", "Accept": accept, + "X-GitHub-Api-Version": "2022-11-28"} + if auth and self.token: + headers["Authorization"] = f"Bearer {self.token}" + try: + return urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=60) + except urllib.error.HTTPError as e: + error = TransientError if e.code in (403, 429) or e.code >= 500 else RegistryError + raise error(f"GET {url}: HTTP {e.code}") + except (urllib.error.URLError, TimeoutError) as e: + raise TransientError(f"GET {url}: {getattr(e, 'reason', e)}") + + def api(self, path: str): + with self._open(f"https://api.github.com{path}", "application/vnd.github+json", True) as r: + return json.load(r) + + def releases(self, repo: str) -> list[dict]: + out = [] + for page in range(1, 6): + batch = self.api(f"/repos/{repo}/releases?per_page=100&page={page}") + out.extend(batch) + if len(batch) < 100: + break + return out + + def fetch(self, asset: dict, limit: int) -> bytes: + # Public assets: no token, so it is never forwarded to a redirect target. + with self._open(asset["browser_download_url"], "application/octet-stream", False) as r: + data = r.read(limit + 1) + if len(data) > limit: + raise RegistryError(f"{asset['name']}: larger than {limit} bytes") + return data + + +class LocalAssets: + """Dry run: assets in a directory stand in for releases of the hosted repository, with + the URLs GitHub would give them. `package` writes exactly this layout.""" + + def __init__(self, directory: Path): + self.directory = directory + + def api(self, path: str): + if path.startswith(f"/repos/{HOSTED_REPO}"): + return {"private": False, "archived": False, "disabled": False, + "license": {"spdx_id": "MIT"}} + raise RegistryError(f"dry run has no data for {path}") + + def releases(self, repo: str) -> list[dict]: + if repo != HOSTED_REPO: + return [] + releases = {} + for file in sorted(self.directory.glob("*.amplugin*")): + m = re.fullmatch(r"(.+)-(\d+\.\d+\.\d+)\.amplugin(\.sha256)?", file.name) + if not m: + continue + tag = f"{m.group(1)}@{m.group(2)}" + stamp = datetime.datetime.fromtimestamp(file.stat().st_mtime, datetime.timezone.utc) + release = releases.setdefault(tag, { + "tag_name": tag, "draft": False, "prerelease": False, "assets": [], + "published_at": stamp.strftime("%Y-%m-%dT%H:%M:%SZ")}) + release["assets"].append({ + "name": file.name, + "browser_download_url": f"https://github.com/{repo}/releases/download/{tag}/{file.name}"}) + return list(releases.values()) + + def fetch(self, asset: dict, limit: int) -> bytes: + data = (self.directory / asset["name"]).read_bytes() + if len(data) > limit: + raise RegistryError(f"{asset['name']}: larger than {limit} bytes") + return data + + +def tag_version(entry: dict, tag: str) -> str | None: + """Version a release tag stands for, or None when the tag is not for this plugin.""" + prefix = entry["id"] + "@" + if tag.startswith(prefix): + version = tag[len(prefix):] + return version if SEMVER.fullmatch(version) else None + if "path" not in entry: # one plugin per repository: v1.2.3 or 1.2.3 + m = re.fullmatch(r"v?(" + SEMVER.pattern + ")", tag) + return m.group(1) if m else None + return None + + +def source_url(entry: dict) -> str: + base = f"https://github.com/{entry['repo']}" + return f"{base}/tree/HEAD/{entry['path']}" if "path" in entry else base + + +def resolve_release(entry: dict, source) -> dict: + candidates = [] + for release in source.releases(entry["repo"]): + if release.get("draft") or release.get("prerelease"): + continue + version = tag_version(entry, release["tag_name"]) + if version: + candidates.append((semver_key(version), version, release)) + if not candidates: + raise RegistryError(f"{entry['id']}: no published release of {entry['repo']} is tagged " + f"{entry['id']}@" + ("" if "path" in entry else ", v or ")) + _, version, release = max(candidates, key=lambda c: c[0]) + stem = f"{entry['id']}-{version}.amplugin" + assets = {a["name"]: a for a in release.get("assets", [])} + for needed in (stem, stem + ".sha256"): + if needed not in assets: + raise RegistryError(f"{entry['id']}: release {release['tag_name']} lacks asset {needed}") + data = source.fetch(assets[stem], MAX_PLUGIN_BYTES) + digest = sha256_hex(data) + published = source.fetch(assets[stem + ".sha256"], 4096).decode("utf-8", "replace").split() + if not published or published[0].lower() != digest: + raise RegistryError(f"{entry['id']}: {stem}.sha256 does not match the downloaded {stem} ({digest})") + manifest = inspect_package(data, stem) + for key, want in (("id", entry["id"]), ("version", version)): + if manifest[key] != want: + raise RegistryError(f"{entry['id']}: {stem} contains plugin.toml {key} = {manifest[key]!r}, expected {want!r}") + if manifest["api_version"] != entry["min_abi"]: + raise RegistryError(f"{entry['id']}: {stem} needs ABI {manifest['api_version']} but " + f"community-plugins.json says min_abi {entry['min_abi']}; update it") + result = {key: entry[key] for key in ("id", "name", "author", "description", "license", "repo")} + if "path" in entry: + result["path"] = entry["path"] + result.update( + source_url=source_url(entry), kinds=manifest["kinds"], min_abi=manifest["api_version"], + version=version, download_url=assets[stem]["browser_download_url"], sha256=digest, + size=len(data), released_at=release.get("published_at") or "") + return result + + +# --- validation ------------------------------------------------------------------------- + +def schema_errors(instance, schema_file: str) -> list[str]: + import jsonschema + schema = load_json(ROOT / "schemas" / schema_file) + validator = jsonschema.Draft202012Validator(schema, format_checker=jsonschema.FormatChecker()) + return [f"{'/'.join(str(p) for p in e.absolute_path) or ''}: {e.message}" + for e in sorted(validator.iter_errors(instance), key=lambda e: list(e.absolute_path))] + + +def validate(offline: bool, source=None) -> list[str]: + errors = [] + registry = load_json(REGISTRY) + errors += [f"community-plugins.json {e}" for e in schema_errors(registry, "community-plugins.schema.json")] + if errors: + return errors + approved = approved_licenses() + plugins = registry["plugins"] + delisted = {d["id"] for d in registry.get("delisted", [])} + seen_ids, seen_names = {}, {} + source = source or GitHub() + for entry in plugins: + pid = entry["id"] + where = f"{pid}:" + if pid in seen_ids: + errors.append(f"{where} duplicate id") + seen_ids[pid] = entry + if pid.lower().startswith(RESERVED_PREFIX): + errors.append(f"{where} ids under {RESERVED_PREFIX}* are reserved for first-party plugins " + "(the host refuses to load them from the user plugin folder)") + if pid in delisted: + errors.append(f"{where} was delisted; delisted ids cannot be listed again") + lowered = entry["name"].casefold() + if lowered in seen_names: + errors.append(f"{where} name {entry['name']!r} is already used by {seen_names[lowered]}") + seen_names[lowered] = pid + ids = license_ids(entry["license"]) + if not ids: + errors.append(f"{where} license {entry['license']!r} has no SPDX identifier") + bad = [i for i in ids if i not in approved] + if bad: + errors.append(f"{where} license identifiers not OSI-approved (or OFL): {', '.join(bad)}") + hosted = entry["repo"] == HOSTED_REPO + if hosted and "path" not in entry: + errors.append(f"{where} plugins hosted in {HOSTED_REPO} need a path (community/)") + if hosted and "path" in entry: + plugin_dir = ROOT / entry["path"] + if not entry["path"].startswith("community/"): + errors.append(f"{where} hosted plugins live under community/") + if not (plugin_dir / "plugin.toml").is_file(): + errors.append(f"{where} {entry['path']}/plugin.toml does not exist") + else: + try: + manifest = read_manifest_text((plugin_dir / "plugin.toml").read_text(), entry["path"]) + if manifest["id"] != pid: + errors.append(f"{where} {entry['path']}/plugin.toml has id {manifest['id']!r}") + if manifest["api_version"] != entry["min_abi"]: + errors.append(f"{where} min_abi {entry['min_abi']} differs from " + f"{entry['path']}/plugin.toml api_version {manifest['api_version']}") + if not (plugin_dir / "build.sh").is_file(): + errors.append(f"{where} {entry['path']}/build.sh is missing") + except RegistryError as e: + errors.append(str(e)) + if not (ROOT / "LICENSE").is_file(): + errors.append(f"{where} no LICENSE file") + if offline: + continue + try: + repo = source.api(f"/repos/{entry['repo']}") + except RegistryError as e: + errors.append(f"{where} repository {entry['repo']} is not reachable ({e})") + continue + if repo.get("private"): + errors.append(f"{where} {entry['repo']} is not public") + if repo.get("archived") or repo.get("disabled"): + errors.append(f"{where} {entry['repo']} is archived or disabled") + if not hosted: + detected = (repo.get("license") or {}).get("spdx_id") + if detected in (None, "NOASSERTION"): + errors.append(f"{where} GitHub finds no recognizable LICENSE file in {entry['repo']}") + elif detected not in ids: + errors.append(f"{where} {entry['repo']} is licensed {detected} but the entry declares {entry['license']!r}") + return errors + + +# --- README table ----------------------------------------------------------------------- + +def cell(text: str) -> str: + return text.replace("|", "\\|").replace("\n", " ") + + +def render_table(registry: dict) -> str: + rows = ["| Name | Author | Description | License | ABI | Source |", "| --- | --- | --- | --- | --- | --- |"] + for entry in sorted(registry["plugins"], key=lambda e: e["name"].casefold()): + url = source_url(entry) + rows.append(f"| [{cell(entry['name'])}]({url}) | {cell(entry['author'])} | " + f"{cell(entry['description'])} | {cell(entry['license'])} | {entry['min_abi']} | " + f"[{entry['repo']}]({url}) |") + return "\n".join(rows) + + +def sync_readme(write: bool) -> bool: + text = README.read_text() + start, end = text.find(TABLE_START), text.find(TABLE_END) + if start < 0 or end < start: + raise RegistryError(f"README.md needs the {TABLE_START} / {TABLE_END} markers") + wanted = text[:start + len(TABLE_START)] + "\n" + render_table(load_json(REGISTRY)) + "\n" + text[end:] + if wanted == text: + return True + if write: + README.write_text(wanted) + return write + + +# --- index ------------------------------------------------------------------------------ + +def build_index(source, previous: dict, strict: bool, allow_unreleased_hosted: bool) -> tuple[dict, list[str]]: + registry = load_json(REGISTRY) + old = {p["id"]: p for p in previous.get("plugins", [])} + entries, problems = [], [] + for entry in registry["plugins"]: + try: + entries.append(resolve_release(entry, source)) + except RegistryError as e: + unreleased = "no published release" in str(e) + if allow_unreleased_hosted and unreleased and entry["repo"] == HOSTED_REPO: + annotate("notice", f"{entry['id']}: not released yet (hosted plugins are released after merge)") + continue + problems.append(str(e)) + if strict: + continue + if isinstance(e, TransientError) and entry["id"] in old: + # GitHub hiccup: keep serving the entry that was verified earlier. + annotate("warning", f"{e}; keeping the previous index entry") + entries.append(old[entry["id"]]) + else: + # Missing, deleted or unverifiable release: never keep serving it. + annotate("warning", f"{e}; plugin left out of the index") + index = {"$schema": "./schemas/community-index.schema.json", "schema_version": 1, + "plugins": sorted(entries, key=lambda p: p["id"]), + "delisted": sorted(registry.get("delisted", []), key=lambda d: d["id"])} + return index, problems + + +def dump(data) -> str: + return json.dumps(data, indent=2, ensure_ascii=False) + "\n" + + +# --- commands --------------------------------------------------------------------------- + +def cmd_validate(args) -> int: + errors = validate(args.offline) + if not errors and not sync_readme(write=False): + errors.append("README.md community table is out of date: run `python3 scripts/registry.py table --write`") + for error in errors: + annotate("error", error) + print(f"registry: {'FAILED' if errors else 'ok'} ({len(errors)} problem(s))") + return 1 if errors else 0 + + +def cmd_package(args) -> int: + package, checksum = package_plugin(Path(args.plugin_dir).resolve(), Path(args.out).resolve(), not args.no_build) + print(package) + print(checksum) + return 0 + + +def cmd_resolve(args) -> int: + registry = load_json(REGISTRY) + if args.tag: + pid, sep, version = args.tag.rpartition("@") + if not sep or not SEMVER.fullmatch(version): + raise RegistryError(f"tag {args.tag!r} must be @") + entry = next((p for p in registry["plugins"] if p["id"] == pid), None) + if entry is None: + raise RegistryError(f"{pid} is not in community-plugins.json; add it by pull request before releasing") + else: + path = args.path.strip("/") + entry = next((p for p in registry["plugins"] if p.get("path") == path and p["repo"] == HOSTED_REPO), None) + if entry is None: + raise RegistryError(f"no hosted registry entry has path {path!r}") + version = None + if entry["repo"] != HOSTED_REPO: + raise RegistryError(f"{entry['id']} is released from {entry['repo']}, not from {HOSTED_REPO}") + manifest = read_manifest_text((ROOT / entry["path"] / "plugin.toml").read_text(), entry["path"]) + if manifest["id"] != entry["id"]: + raise RegistryError(f"{entry['path']}/plugin.toml has id {manifest['id']!r}, registry says {entry['id']!r}") + if version is not None and manifest["version"] != version: + raise RegistryError(f"tag version {version} differs from {entry['path']}/plugin.toml version {manifest['version']}") + version = manifest["version"] + for key, value in (("id", entry["id"]), ("version", version), ("path", entry["path"]), + ("tag", f"{entry['id']}@{version}")): + print(f"{key}={value}") + return 0 + + +def cmd_index(args) -> int: + source = LocalAssets(Path(args.assets_dir)) if args.assets_dir else GitHub() + previous = {} + if args.previous and Path(args.previous).is_file(): + previous = load_json(Path(args.previous)) + index, problems = build_index(source, previous, args.strict, args.allow_unreleased_hosted) + errors = schema_errors(index, "community-index.schema.json") + for error in errors: + annotate("error", f"index {error}") + output = Path(args.output) + output.write_text(dump(index)) + print(f"wrote {output} with {len(index['plugins'])} plugin(s)") + for problem in problems: + annotate("error" if args.strict else "warning", problem) + summary = os.environ.get("GITHUB_STEP_SUMMARY") + if summary and problems: + with open(summary, "a", encoding="utf-8") as f: + f.write("### Registry problems\n\n" + "".join(f"- {p}\n" for p in problems)) + return 1 if errors or (args.strict and problems) else 0 + + +def cmd_table(args) -> int: + ok = sync_readme(write=args.write) + if not ok: + annotate("error", "README.md community table is out of date: run `python3 scripts/registry.py table --write`") + return 0 if ok else 1 + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + sub = parser.add_subparsers(dest="command", required=True) + p = sub.add_parser("validate") + p.add_argument("--offline", action="store_true", help="skip GitHub API checks") + p.set_defaults(run=cmd_validate) + p = sub.add_parser("package") + p.add_argument("plugin_dir") + p.add_argument("--out", required=True) + p.add_argument("--no-build", action="store_true", help="reuse an existing target/*.amplugin") + p.set_defaults(run=cmd_package) + p = sub.add_parser("resolve") + group = p.add_mutually_exclusive_group(required=True) + group.add_argument("--tag") + group.add_argument("--path") + p.set_defaults(run=cmd_resolve) + p = sub.add_parser("index") + p.add_argument("--output", default=str(INDEX)) + p.add_argument("--previous", default=str(INDEX), help="keep these entries when a release cannot be resolved (non-strict)") + p.add_argument("--assets-dir", help="dry run: use assets from this directory instead of GitHub releases") + p.add_argument("--strict", action="store_true", help="fail when any plugin cannot be resolved") + p.add_argument("--allow-unreleased-hosted", action="store_true", + help="submission CI: plugins hosted here are released after merge") + p.set_defaults(run=cmd_index) + p = sub.add_parser("table") + group = p.add_mutually_exclusive_group(required=True) + group.add_argument("--check", action="store_true") + group.add_argument("--write", action="store_true") + p.set_defaults(run=cmd_table) + args = parser.parse_args() + try: + return args.run(args) + except RegistryError as e: + annotate("error", str(e)) + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/registry_smoke.py b/scripts/registry_smoke.py new file mode 100755 index 0000000..3630e2a --- /dev/null +++ b/scripts/registry_smoke.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +"""Generic load/render check of .amplugin files with a released animathio-cli. + +Usage: python3 scripts/registry_smoke.py PATH/TO/animathio-cli PLUGIN_DIR [--only PLUGIN_ID] + +PLUGIN_DIR holds the .amplugin files to test (it is used as ANIMATHIO_PLUGIN_DIR, so nothing +else is loaded). Every plugin must load without a host diagnostic. A `clip-source` plugin is +also rendered with its default parameters and must draw something. Other kinds are checked +for loading only: the editor cannot enumerate their parameters headlessly, so a maintainer +reviews their behaviour (plugins can add their own smoke test like community/code-snippets). +No GUI and no audio device are used. +""" +import io +import json +import os +import subprocess +import sys +import tempfile +import tomllib +import zipfile +from pathlib import Path + +from PIL import Image + +BAD_WORDS = ("not loaded", "failed", "trap", "placeholder", "unresolved", "panick") + + +def main() -> int: + args = [a for a in sys.argv[1:] if not a.startswith("--")] + only = sys.argv[sys.argv.index("--only") + 1] if "--only" in sys.argv else None + if only: + args.remove(only) + cli, plugins = str(Path(args[0]).resolve()), Path(args[1]).resolve() + env = dict(os.environ, ANIMATHIO_PLUGIN_DIR=str(plugins), ANIMATHIO_AUDIO="none", + PIPEWIRE_REMOTE="animathio-silent-no-such-remote", + PULSE_SERVER="unix:/nonexistent/animathio-silent", SDL_AUDIODRIVER="dummy") + + def run(*cmd): + result = subprocess.run([cli, *map(str, cmd)], env=env, capture_output=True, text=True, timeout=300) + problem = result.returncode or any(w in result.stderr.lower() for w in BAD_WORDS) + if problem: + raise RuntimeError(f"animathio-cli {' '.join(map(str, cmd))}\n{result.stdout}{result.stderr}") + + manifests = [] + for package in sorted(plugins.glob("*.amplugin")): + try: + with zipfile.ZipFile(package) as bundle: + manifest = tomllib.loads(bundle.read("plugin.toml").decode()) + except (zipfile.BadZipFile, KeyError, tomllib.TOMLDecodeError) as e: + print(f"FAIL {package.name}: not a valid .amplugin ({e})", file=sys.stderr) + return 1 + if only is None or manifest["id"] == only: + manifests.append(manifest) + if not manifests: + print("no plugins to test", file=sys.stderr) + return 1 + + failures = 0 + with tempfile.TemporaryDirectory(dir=plugins.parent) as temporary: + work = Path(temporary) + run("new-sample", "-o", work / "sample.amio") + with zipfile.ZipFile(work / "sample.amio") as bundle: + project = json.loads(bundle.read("project.json")) + project["assets"] = {} + project["tracks"] = project["tracks"][:1] + clip = project["tracks"][0]["clips"]["1"] + clip["animations"] = [] + clip["effects"] = [] + original_clips = project["tracks"][0]["clips"] + + def render(name, kind=None): + project["tracks"][0]["clips"] = {} if kind is None else original_clips + if kind is not None: + clip["kind"] = kind + path = work / f"{name}.amio" + with zipfile.ZipFile(path, "w") as bundle: + bundle.writestr("project.json", json.dumps(project)) + output = work / f"{name}.png" + output.unlink(missing_ok=True) + run("render", path, "--frame", "0", "-o", output) + return Image.open(io.BytesIO(output.read_bytes())).convert("RGBA") + + try: + empty = render("empty") # background only: also proves every plugin in the folder loads + except RuntimeError as e: + print(f"FAIL loading plugins from {plugins}\n{e}", file=sys.stderr) + return 1 + for manifest in manifests: + pid = manifest["id"] + try: + if manifest["kinds"] == ["clip-source"]: + image = render("source", {"Plugin": {"plugin_id": pid, "params": {}}}) + if image.tobytes() == empty.tobytes(): + raise RuntimeError("default parameters draw nothing (the render equals the empty background)") + print(f"PASS {pid}: loads and renders with default parameters") + else: + print(f"PASS {pid}: loads ({', '.join(manifest['kinds'])}; behaviour left to review)") + except RuntimeError as e: + failures += 1 + print(f"FAIL {pid}: {e}", file=sys.stderr) + return 1 if failures else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/requirements.txt b/scripts/requirements.txt new file mode 100644 index 0000000..488f425 --- /dev/null +++ b/scripts/requirements.txt @@ -0,0 +1,2 @@ +jsonschema==4.26.0 +Pillow==11.3.0 diff --git a/scripts/test_registry.py b/scripts/test_registry.py new file mode 100644 index 0000000..a026f92 --- /dev/null +++ b/scripts/test_registry.py @@ -0,0 +1,194 @@ +#!/usr/bin/env python3 +"""Offline tests for scripts/registry.py: python3 -m unittest discover -s scripts (needs jsonschema).""" +import copy +import io +import json +import sys +import tempfile +import unittest +import zipfile +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import registry # noqa: E402 + +REAL = json.loads(registry.REGISTRY.read_text()) +EXTERNAL = {"id": "com.example.spiral", "name": "Spiral", "author": "Example", "repo": "example/spiral", + "description": "A spiral clip source for tests", "license": "Apache-2.0 OR MIT", "min_abi": "1.0.0"} + + +def amplugin(pid="com.example.spiral", version="1.2.0", abi="1.0.0", kinds=("clip-source",)): + manifest = (f'api_version = "{abi}"\nid = "{pid}"\nname = "Spiral"\nversion = "{version}"\n' + f'kinds = {json.dumps(list(kinds))}\n') + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w") as z: + z.writestr("plugin.toml", manifest) + z.writestr("plugin.wasm", b"\0asm") + return buffer.getvalue() + + +class FakeSource: + """Stands in for GitHub: releases = {tag: {asset_name: bytes}}.""" + + def __init__(self, releases, prerelease=()): + self.releases_data, self.prerelease = releases, set(prerelease) + + def releases(self, repo): + return [{"tag_name": tag, "draft": False, "prerelease": tag in self.prerelease, + "published_at": "2026-01-01T00:00:00Z", + "assets": [{"name": n, "browser_download_url": f"https://github.com/{repo}/releases/download/{tag}/{n}"} + for n in assets]} for tag, assets in self.releases_data.items()] + + def fetch(self, asset, limit): + tag = asset["browser_download_url"].split("/download/")[1].split("/")[0] + return self.releases_data[tag][asset["name"]] + + def api(self, path): + return {"private": False, "archived": False, "license": {"spdx_id": "MIT"}} + + +def release(version, data=None, digest=None, **kw): + data = data or amplugin(version=version, **kw) + name = f"com.example.spiral-{version}.amplugin" + digest = digest or registry.sha256_hex(data) + return {name: data, name + ".sha256": f"{digest} {name}\n".encode()} + + +class RegistryFile: + def __init__(self, test, registry_data): + self.directory = tempfile.TemporaryDirectory() + test.addCleanup(self.directory.cleanup) + self.path = Path(self.directory.name) / "community-plugins.json" + self.path.write_text(json.dumps(registry_data)) + patcher = mock.patch.object(registry, "REGISTRY", self.path) + patcher.start() + test.addCleanup(patcher.stop) + + +class ValidateTests(unittest.TestCase): + def check(self, mutate, expect=None): + data = copy.deepcopy(REAL) + mutate(data) + RegistryFile(self, data) + errors = registry.validate(offline=True) + if expect is None: + self.assertEqual(errors, []) + else: + self.assertTrue(any(expect in e for e in errors), errors) + + def test_committed_registry_is_valid(self): + self.check(lambda d: None) + + def test_readme_table_in_sync(self): + self.assertTrue(registry.sync_readme(write=False)) + + def test_external_entry_is_valid(self): + self.check(lambda d: d["plugins"].append(dict(EXTERNAL))) + + def test_reserved_id(self): + def mutate(d): + d["plugins"].append(dict(EXTERNAL, id="org.animathio.evil")) + self.check(mutate, "reserved") + + def test_duplicate_id(self): + self.check(lambda d: d["plugins"].append(dict(d["plugins"][0], name="Other")), "duplicate id") + + def test_duplicate_name(self): + self.check(lambda d: d["plugins"].append(dict(EXTERNAL, name="code snippets")), "already used") + + def test_id_must_be_reverse_domain(self): + self.check(lambda d: d["plugins"].append(dict(EXTERNAL, id="spiral")), "does not match") + + def test_license_must_be_osi_approved(self): + self.check(lambda d: d["plugins"].append(dict(EXTERNAL, license="Proprietary")), "not OSI-approved") + self.check(lambda d: d["plugins"].append(dict(EXTERNAL, license="CC-BY-NC-4.0")), "not OSI-approved") + + def test_unknown_field_rejected(self): + self.check(lambda d: d["plugins"].append(dict(EXTERNAL, version="1.0.0")), "Additional properties") + + def test_hosted_needs_path_and_matching_manifest(self): + self.check(lambda d: d["plugins"][0].pop("path"), "need a path") + self.check(lambda d: d["plugins"][0].update(min_abi="1.0.0"), "min_abi 1.0.0 differs") + self.check(lambda d: d["plugins"][0].update(id="io.github.animathio.other"), "has id") + + def test_delisted_ids_cannot_return(self): + def mutate(d): + d["delisted"].append({"id": d["plugins"][0]["id"], "reason": "removed for tests", "date": "2026-11-17"}) + self.check(mutate, "delisted") + + def test_path_traversal_rejected(self): + self.check(lambda d: d["plugins"].append(dict(EXTERNAL, path="../x")), "") + + def test_license_ids(self): + self.assertEqual(registry.license_ids("MIT AND OFL-1.1"), ["MIT", "OFL-1.1"]) + self.assertEqual(registry.license_ids("(Apache-2.0 OR MIT) AND GPL-3.0-or-later WITH Classpath-exception-2.0"), + ["Apache-2.0", "MIT", "GPL-3.0-or-later"]) + + +class IndexTests(unittest.TestCase): + def build(self, releases, strict=True, previous=None, prerelease=(), entry=None): + data = copy.deepcopy(REAL) + data["plugins"] = [dict(entry or EXTERNAL)] + RegistryFile(self, data) + return registry.build_index(FakeSource(releases, prerelease), previous or {}, strict, False) + + def test_picks_highest_published_release(self): + index, problems = self.build({"v1.2.0": release("1.2.0"), "v1.10.0": release("1.10.0"), + "v2.0.0": release("2.0.0"), "v1.9.0": release("1.9.0")}, + prerelease=["v2.0.0"]) + self.assertEqual(problems, []) + entry = index["plugins"][0] + self.assertEqual((entry["version"], entry["min_abi"], entry["kinds"]), ("1.10.0", "1.0.0", ["clip-source"])) + self.assertEqual(entry["sha256"], registry.sha256_hex(amplugin(version="1.10.0"))) + self.assertEqual(entry["download_url"], + "https://github.com/example/spiral/releases/download/v1.10.0/com.example.spiral-1.10.0.amplugin") + self.assertEqual(registry.schema_errors(index, "community-index.schema.json"), []) + + def test_monorepo_entries_only_accept_id_tags(self): + mono = dict(EXTERNAL, path="plugins/spiral") + _, problems = self.build({"v1.2.0": release("1.2.0")}, entry=mono) + self.assertTrue(problems and "no published release" in problems[0]) + index, problems = self.build({"com.example.spiral@1.2.0": release("1.2.0")}, entry=mono) + self.assertEqual((problems, index["plugins"][0]["path"]), ([], "plugins/spiral")) + + def test_checksum_mismatch(self): + _, problems = self.build({"v1.2.0": release("1.2.0", digest="0" * 64)}) + self.assertIn("does not match", problems[0]) + + def test_manifest_must_match_registry_and_tag(self): + _, problems = self.build({"v1.2.0": release("1.2.0", data=amplugin(pid="com.example.other"))}) + self.assertIn("expected 'com.example.spiral'", problems[0]) + _, problems = self.build({"v1.2.0": release("1.2.0", data=amplugin(version="1.1.0"))}) + self.assertIn("expected '1.2.0'", problems[0]) + _, problems = self.build({"v1.2.0": release("1.2.0", abi="1.1.0")}) + self.assertIn("min_abi", problems[0]) + + def test_missing_assets_and_bad_archive(self): + _, problems = self.build({"v1.2.0": {}}) + self.assertIn("lacks asset", problems[0]) + _, problems = self.build({"v1.2.0": release("1.2.0", data=b"not a zip")}) + self.assertIn("not a zip", problems[0]) + + def test_non_strict_keeps_previous_entry_only_for_transient_errors(self): + good, _ = self.build({"v1.2.0": release("1.2.0")}) + + class Flaky(FakeSource): + def releases(self, repo): + raise registry.TransientError("GitHub is down") + + data = copy.deepcopy(REAL) + data["plugins"] = [dict(EXTERNAL)] + RegistryFile(self, data) + index, problems = registry.build_index(Flaky({}), good, False, False) + self.assertTrue(problems) + self.assertEqual(index["plugins"][0]["version"], "1.2.0") + # A release that is gone or does not verify is never served from the old index. + for releases in ({}, {"v1.3.0": release("1.3.0", digest="0" * 64)}): + index, problems = self.build(releases, strict=False, previous=good) + self.assertTrue(problems) + self.assertEqual(index["plugins"], []) + + +if __name__ == "__main__": + unittest.main() From ff2e5ba902adc9da429e6cc633e0b974160f5bcc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kov=C3=A1cs=20B=C3=A1lint=20Hunor?= Date: Tue, 17 Nov 2026 00:29:49 +0200 Subject: [PATCH 2/5] fix(registry): pin repository ids and keep third-party builds off main and tokens - external entries need repo_id; validate and the index builder refuse a renamed, transferred or re-created repository until re-reviewed - build third-party sources only for pull requests that add or change the entry and run that step without GH_TOKEN; pushes and manual runs only render released assets - document the trust model in docs/registry.md Part of AniMathIO/AniMathIO#304 Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/registry.yml | 8 ++++++-- CONTRIBUTING.md | 10 ++++++++-- docs/registry.md | 21 +++++++++++++++++++++ schemas/community-plugins.schema.json | 5 +++++ scripts/check_submission.py | 11 +++++++++-- scripts/registry.py | 10 ++++++++++ scripts/test_registry.py | 26 ++++++++++++++++++++++++-- 7 files changed, 83 insertions(+), 8 deletions(-) diff --git a/.github/workflows/registry.yml b/.github/workflows/registry.yml index f357d28..0ff3d3f 100644 --- a/.github/workflows/registry.yml +++ b/.github/workflows/registry.yml @@ -32,7 +32,6 @@ jobs: CARGO_PROFILE_DEV_DEBUG: 0 CARGO_INCREMENTAL: 0 ANIMATHIO_AUDIO: none - GH_TOKEN: ${{ github.token }} steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 with: @@ -47,10 +46,14 @@ jobs: run: python3 -m unittest discover -s scripts -v - name: Validate community-plugins.json # Schema, unique and unreserved ids, public repositories, OSI/OFL licenses, README table. + env: + GH_TOKEN: ${{ github.token }} run: python3 scripts/registry.py validate - name: Resolve releases into an index # External plugins need a published release (asset + .sha256); plugins hosted here are # released after merge, so they are built below instead. + env: + GH_TOKEN: ${{ github.token }} run: python3 scripts/registry.py index --strict --allow-unreleased-hosted --previous /dev/null --output "$RUNNER_TEMP/index.json" - name: Released AniMathIO CLI id: cli @@ -63,8 +66,9 @@ jobs: run: | if [ "${{ github.event_name }}" = "pull_request" ]; then git show "origin/$BASE_REF:community-plugins.json" > "$RUNNER_TEMP/base.json" 2>/dev/null || echo '{"plugins":[]}' > "$RUNNER_TEMP/base.json" - scope=(--base "$RUNNER_TEMP/base.json") + scope=(--base "$RUNNER_TEMP/base.json" --build-external) else scope=(--all) fi + # Third-party build scripts may run above: no token is passed to this step. python3 scripts/check_submission.py "${{ steps.cli.outputs.cli }}" "$RUNNER_TEMP/index.json" "$RUNNER_TEMP/work" "${scope[@]}" diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 12d437b..5b1bd91 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -13,6 +13,7 @@ the editor's Plugins tab (AniMathIO 2.2+). To list yours, open a pull request th "author": "Ada Example", "description": "A keyframeable spiral clip source", "repo": "ada/animathio-spiral", + "repo_id": 123456789, "license": "MIT", "min_abi": "1.1.0" } @@ -28,6 +29,10 @@ several plugins. A plugin developed in this repository goes under `community/.`), lowercase, never `org.animathio.*` (reserved for first-party plugins; the host will not load such an id from the user plugin folder). It must equal `id` in `plugin.toml`. Ids are never reused. +* **Repository identity**: `repo_id` is the numeric GitHub id of your repository + (`gh api repos// --jq .id`). New releases are indexed automatically, so if the + repository is renamed, transferred or re-created the index stops serving it until a maintainer + re-reviews the entry (open a PR updating `repo`/`repo_id`). * **Source and license**: public GitHub repository with a recognizable `LICENSE`. The `license` field is an SPDX expression whose identifiers are all OSI-approved (or SIL OFL for bundled fonts and assets) and include the license GitHub detects in your repository. Keep the notices @@ -81,8 +86,9 @@ ABI, and that the released package loads and renders with the released AniMathIO same checks locally with `python3 scripts/registry.py validate` and `python3 scripts/registry_smoke.py PATH/TO/animathio-cli DIR_WITH_AMPLUGIN`. -CI builds the plugin from your repository, so review your own `build.rs` and dependencies as -you would for any CI. Fork pull requests run with a read-only token and no secrets. +For a pull request that adds or changes your entry, CI runs your repository's `build.sh` at the +release tag (so `build.rs` and dependencies execute on a GitHub runner). That step gets no token +or secrets and the workflow is read-only; pushes to `main` never build third-party source. ### Review diff --git a/docs/registry.md b/docs/registry.md index 110779c..7baae8d 100644 --- a/docs/registry.md +++ b/docs/registry.md @@ -46,11 +46,14 @@ Schema in [`schemas/`](../schemas) (`community-plugins.schema.json`, `community- } ``` +(An entry for a plugin in another repository also has `"repo_id": 123456789`.) + | Field | Rule | | --- | --- | | `id` | Reverse-domain, lowercase, at least three dot-separated labels, at most 100 characters. Unique. **Never `org.animathio.*`**: those ids are reserved for first-party plugins and the host refuses to load them from the user plugin folder. Must equal `id` in the plugin's `plugin.toml`. | | `name`, `author`, `description` | Display text (60 / 80 / 10-200 characters). Names are unique (case-insensitive). | | `repo` | Public GitHub repository `owner/name` that carries the release assets. | +| `repo_id` | Numeric GitHub id of `repo` (`gh api repos// --jq .id`). Required outside AniMathIO/plugins. A repository that is renamed, deleted and re-created, or transferred, gets a different id (or the old name points at someone else), and the index builder then refuses its releases until a maintainer re-reviews the entry. | | `path` | Optional subdirectory of `repo` that holds the plugin (`plugin.toml`, `build.sh`). Required for plugins hosted here (`community/`). A plugin with a `path` is a monorepo plugin: its release tags must be `@`. | | `license` | SPDX expression, e.g. `MIT`, `Apache-2.0 OR MIT`, `MIT AND OFL-1.1`. Every identifier must be OSI-approved or an SIL OFL variant ([`schemas/osi-approved-licenses.txt`](../schemas/osi-approved-licenses.txt)). For plugins outside this repository, the licence GitHub detects in the repository must be one of the declared identifiers. | | `min_abi` | The plugin ABI (`api_version` in `plugin.toml`) of the latest release. The index builder refuses a release whose manifest says otherwise, so raising the ABI is a one-line PR together with the release. | @@ -153,6 +156,24 @@ release), that plugin is **left out** and the run reports a warning, the other p update. If GitHub itself is unreachable or rate limiting, the previous entries are kept. Pull requests that touch the registry run the same resolution strictly. +## Trust model + +* A listing is reviewed once, by pull request; **new versions of a listed external plugin are + indexed automatically** (no PR per release), because the issue's design is that the user + installs and updates each plugin explicitly. Nothing is installed or updated without the + user's click, downloads are checked against the index SHA-256, and plugins run sandboxed. +* The registry pins the repository identity (`repo_id`) and the index builder verifies the + release asset against its `.sha256`, the archive manifest against the registry id and `min_abi`, + and refuses `org.animathio.*`. A maintainer can delist at any time; to stop one version only, + delete that release (the previous release becomes latest). +* Submission CI runs a plugin's own `build.sh` from its repository **only for pull requests that + add or change that entry**, in a step that gets no token or secrets (the workflow has + read-only permissions; GitHub withholds secrets from fork PRs). It checks that the source builds and + produces the same id, version and ABI as the release; it does not require byte-identical + output (zip timestamps and toolchains differ), so the release asset, not the source, is what + the editor installs and what the smoke test renders. Pushes to `main` and manual runs download and + render released assets but never build third-party source. + ## Submitting, releasing, delisting * Submission: [CONTRIBUTING.md](../CONTRIBUTING.md). CI is diff --git a/schemas/community-plugins.schema.json b/schemas/community-plugins.schema.json index 6c6fcbd..9654f68 100644 --- a/schemas/community-plugins.schema.json +++ b/schemas/community-plugins.schema.json @@ -44,6 +44,11 @@ "type": "string", "pattern": "^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?/[A-Za-z0-9._-]+$" }, + "repo_id": { + "description": "Numeric GitHub id of repo (`gh api repos// --jq .id`). Required outside AniMathIO/plugins: new releases are indexed automatically, so the index builder refuses a repository that was renamed, deleted and re-created or transferred until a maintainer re-reviews it.", + "type": "integer", + "minimum": 1 + }, "path": { "description": "Subdirectory of repo that holds the plugin (plugin.toml, build.sh). Present for monorepos, including every plugin hosted in AniMathIO/plugins (community/); when present, release tags must be @.", "type": "string", diff --git a/scripts/check_submission.py b/scripts/check_submission.py index 886831a..6029ff0 100755 --- a/scripts/check_submission.py +++ b/scripts/check_submission.py @@ -2,13 +2,16 @@ """Build and smoke-test registry entries (submission CI). Usage: python3 scripts/check_submission.py CLI INDEX_JSON WORK_DIR [--base community-plugins.json | --all] + [--build-external] Targets are the entries that differ from --base (a previous copy of community-plugins.json; new entries and changed fields count) or every entry with --all. For each target: * hosted in AniMathIO/plugins: build it with its build.sh and package it like a release; * elsewhere: download the release asset the index points at (already SHA-256 checked by - `registry.py index`), clone the repository at that release tag and build it with its - build.sh; the built package must carry the same id, version and ABI as the release. + `registry.py index`); with --build-external also clone the repository at that release tag + and build it with its build.sh (third-party code runs: only for pull requests that add or + change the entry, in a step without credentials). The built package must carry the same id, + version and ABI as the release. Then every collected .amplugin is loaded and rendered with the released CLI. """ import json @@ -37,6 +40,7 @@ def main() -> int: if "--all" not in argv and base is None: print("pass --base FILE or --all", file=sys.stderr) return 2 + build_external = "--build-external" in argv index = {p["id"]: p for p in json.loads(index_file.read_text())["plugins"]} chosen = targets(registry.load_json(registry.REGISTRY), None if "--all" in argv else base) shutil.rmtree(work, ignore_errors=True) @@ -59,6 +63,9 @@ def main() -> int: if registry.sha256_hex(data) != released["sha256"]: raise registry.RegistryError("download does not match the index checksum") (plugins / asset["name"]).write_bytes(data) + if not build_external: + print("source build skipped (it runs for pull requests that add or change an entry)") + continue tag = re.search(r"/releases/download/([^/]+)/", released["download_url"]).group(1) src = work / "src" / pid subprocess.run(["git", "clone", "--quiet", "--depth", "1", "--branch", tag, diff --git a/scripts/registry.py b/scripts/registry.py index 4863685..3a11080 100755 --- a/scripts/registry.py +++ b/scripts/registry.py @@ -261,6 +261,11 @@ def resolve_release(entry: dict, source) -> dict: if not candidates: raise RegistryError(f"{entry['id']}: no published release of {entry['repo']} is tagged " f"{entry['id']}@" + ("" if "path" in entry else ", v or ")) + if "repo_id" in entry: # the repository must still be the one that was reviewed + current = source.api(f"/repos/{entry['repo']}").get("id") + if current != entry["repo_id"]: + raise RegistryError(f"{entry['id']}: {entry['repo']} now has GitHub id {current}, the registry pins " + f"{entry['repo_id']} (renamed or transferred repository: a maintainer must re-review)") _, version, release = max(candidates, key=lambda c: c[0]) stem = f"{entry['id']}-{version}.amplugin" assets = {a["name"]: a for a in release.get("assets", [])} @@ -334,6 +339,9 @@ def validate(offline: bool, source=None) -> list[str]: hosted = entry["repo"] == HOSTED_REPO if hosted and "path" not in entry: errors.append(f"{where} plugins hosted in {HOSTED_REPO} need a path (community/)") + if not hosted and "repo_id" not in entry: + errors.append(f"{where} plugins outside {HOSTED_REPO} need repo_id " + f"(`gh api repos/{entry['repo']} --jq .id`)") if hosted and "path" in entry: plugin_dir = ROOT / entry["path"] if not entry["path"].startswith("community/"): @@ -365,6 +373,8 @@ def validate(offline: bool, source=None) -> list[str]: errors.append(f"{where} {entry['repo']} is not public") if repo.get("archived") or repo.get("disabled"): errors.append(f"{where} {entry['repo']} is archived or disabled") + if not hosted and "repo_id" in entry and repo.get("id") != entry["repo_id"]: + errors.append(f"{where} {entry['repo']} has GitHub id {repo.get('id')}, repo_id says {entry['repo_id']}") if not hosted: detected = (repo.get("license") or {}).get("spdx_id") if detected in (None, "NOASSERTION"): diff --git a/scripts/test_registry.py b/scripts/test_registry.py index a026f92..edfc925 100644 --- a/scripts/test_registry.py +++ b/scripts/test_registry.py @@ -15,7 +15,7 @@ REAL = json.loads(registry.REGISTRY.read_text()) EXTERNAL = {"id": "com.example.spiral", "name": "Spiral", "author": "Example", "repo": "example/spiral", - "description": "A spiral clip source for tests", "license": "Apache-2.0 OR MIT", "min_abi": "1.0.0"} + "description": "A spiral clip source for tests", "license": "Apache-2.0 OR MIT", "min_abi": "1.0.0", "repo_id": 4242} def amplugin(pid="com.example.spiral", version="1.2.0", abi="1.0.0", kinds=("clip-source",)): @@ -44,8 +44,10 @@ def fetch(self, asset, limit): tag = asset["browser_download_url"].split("/download/")[1].split("/")[0] return self.releases_data[tag][asset["name"]] + repo_id = 4242 + def api(self, path): - return {"private": False, "archived": False, "license": {"spdx_id": "MIT"}} + return {"id": self.repo_id, "private": False, "archived": False, "license": {"spdx_id": "MIT"}} def release(version, data=None, digest=None, **kw): @@ -100,6 +102,16 @@ def test_duplicate_name(self): def test_id_must_be_reverse_domain(self): self.check(lambda d: d["plugins"].append(dict(EXTERNAL, id="spiral")), "does not match") + def test_external_entry_needs_repo_id_and_it_must_match(self): + self.check(lambda d: d["plugins"].append({k: v for k, v in EXTERNAL.items() if k != "repo_id"}), "need repo_id") + data = copy.deepcopy(REAL) + data["plugins"].append(dict(EXTERNAL)) + RegistryFile(self, data) + self.assertEqual(registry.validate(offline=False, source=FakeSource({})), []) + other = FakeSource({}) + other.repo_id = 7 + self.assertTrue(any("repo_id says" in e for e in registry.validate(offline=False, source=other))) + def test_license_must_be_osi_approved(self): self.check(lambda d: d["plugins"].append(dict(EXTERNAL, license="Proprietary")), "not OSI-approved") self.check(lambda d: d["plugins"].append(dict(EXTERNAL, license="CC-BY-NC-4.0")), "not OSI-approved") @@ -152,6 +164,16 @@ def test_monorepo_entries_only_accept_id_tags(self): index, problems = self.build({"com.example.spiral@1.2.0": release("1.2.0")}, entry=mono) self.assertEqual((problems, index["plugins"][0]["path"]), ([], "plugins/spiral")) + def test_repository_identity_is_pinned(self): + source = FakeSource({"v1.2.0": release("1.2.0")}) + source.repo_id = 7 # renamed, transferred or re-created repository + data = copy.deepcopy(REAL) + data["plugins"] = [dict(EXTERNAL)] + RegistryFile(self, data) + index, problems = registry.build_index(source, {}, True, False) + self.assertIn("now has GitHub id 7", problems[0]) + self.assertEqual(index["plugins"], []) + def test_checksum_mismatch(self): _, problems = self.build({"v1.2.0": release("1.2.0", digest="0" * 64)}) self.assertIn("does not match", problems[0]) From 883ad208dc940d3d416a4339c181d9e79ef41155 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kov=C3=A1cs=20B=C3=A1lint=20Hunor?= Date: Tue, 17 Nov 2026 01:20:23 +0200 Subject: [PATCH 3/5] docs(registry): clarify repository identity pinning limits --- docs/registry.md | 2 +- schemas/community-plugins.schema.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/registry.md b/docs/registry.md index 7baae8d..7526ddc 100644 --- a/docs/registry.md +++ b/docs/registry.md @@ -53,7 +53,7 @@ Schema in [`schemas/`](../schemas) (`community-plugins.schema.json`, `community- | `id` | Reverse-domain, lowercase, at least three dot-separated labels, at most 100 characters. Unique. **Never `org.animathio.*`**: those ids are reserved for first-party plugins and the host refuses to load them from the user plugin folder. Must equal `id` in the plugin's `plugin.toml`. | | `name`, `author`, `description` | Display text (60 / 80 / 10-200 characters). Names are unique (case-insensitive). | | `repo` | Public GitHub repository `owner/name` that carries the release assets. | -| `repo_id` | Numeric GitHub id of `repo` (`gh api repos// --jq .id`). Required outside AniMathIO/plugins. A repository that is renamed, deleted and re-created, or transferred, gets a different id (or the old name points at someone else), and the index builder then refuses its releases until a maintainer re-reviews the entry. | +| `repo_id` | Numeric GitHub id of `repo` (`gh api repos// --jq .id`). Required outside AniMathIO/plugins. The index builder refuses releases if the configured name resolves to a different numeric id, including deletion and re-creation or reuse of an old name. Renames and transfers preserve the numeric id; this pin does not detect ownership changes or require their re-review. | | `path` | Optional subdirectory of `repo` that holds the plugin (`plugin.toml`, `build.sh`). Required for plugins hosted here (`community/`). A plugin with a `path` is a monorepo plugin: its release tags must be `@`. | | `license` | SPDX expression, e.g. `MIT`, `Apache-2.0 OR MIT`, `MIT AND OFL-1.1`. Every identifier must be OSI-approved or an SIL OFL variant ([`schemas/osi-approved-licenses.txt`](../schemas/osi-approved-licenses.txt)). For plugins outside this repository, the licence GitHub detects in the repository must be one of the declared identifiers. | | `min_abi` | The plugin ABI (`api_version` in `plugin.toml`) of the latest release. The index builder refuses a release whose manifest says otherwise, so raising the ABI is a one-line PR together with the release. | diff --git a/schemas/community-plugins.schema.json b/schemas/community-plugins.schema.json index 9654f68..5ae1ccf 100644 --- a/schemas/community-plugins.schema.json +++ b/schemas/community-plugins.schema.json @@ -45,7 +45,7 @@ "pattern": "^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?/[A-Za-z0-9._-]+$" }, "repo_id": { - "description": "Numeric GitHub id of repo (`gh api repos// --jq .id`). Required outside AniMathIO/plugins: new releases are indexed automatically, so the index builder refuses a repository that was renamed, deleted and re-created or transferred until a maintainer re-reviews it.", + "description": "Numeric GitHub id of repo (`gh api repos// --jq .id`). Required outside AniMathIO/plugins: new releases are indexed automatically, so the index builder refuses a different repository at the configured name until a maintainer re-reviews it. Renames and transfers preserve this id; ownership changes are not detected.", "type": "integer", "minimum": 1 }, From 06327eed1598c40af2b0d481ddc7e67df9b6ffe1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kov=C3=A1cs=20B=C3=A1lint=20Hunor?= Date: Tue, 17 Nov 2026 01:27:39 +0200 Subject: [PATCH 4/5] fix(registry): reject ids the community installer cannot accept --- docs/registry.md | 2 +- scripts/registry.py | 2 ++ scripts/test_registry.py | 9 ++++++++- 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/docs/registry.md b/docs/registry.md index 7526ddc..e9e341f 100644 --- a/docs/registry.md +++ b/docs/registry.md @@ -50,7 +50,7 @@ Schema in [`schemas/`](../schemas) (`community-plugins.schema.json`, `community- | Field | Rule | | --- | --- | -| `id` | Reverse-domain, lowercase, at least three dot-separated labels, at most 100 characters. Unique. **Never `org.animathio.*`**: those ids are reserved for first-party plugins and the host refuses to load them from the user plugin folder. Must equal `id` in the plugin's `plugin.toml`. | +| `id` | Reverse-domain, lowercase, at least three dot-separated labels, at most 100 characters. Unique. **Never `org.animathio.*`**: those ids are reserved for first-party plugins and the host refuses to load them from the user plugin folder. Windows device-name prefixes (`con`, `nul`, `com1`–`com9`, etc.) are refused, matching the host. Must equal `id` in the plugin's `plugin.toml`. | | `name`, `author`, `description` | Display text (60 / 80 / 10-200 characters). Names are unique (case-insensitive). | | `repo` | Public GitHub repository `owner/name` that carries the release assets. | | `repo_id` | Numeric GitHub id of `repo` (`gh api repos// --jq .id`). Required outside AniMathIO/plugins. The index builder refuses releases if the configured name resolves to a different numeric id, including deletion and re-creation or reuse of an old name. Renames and transfers preserve the numeric id; this pin does not detect ownership changes or require their re-review. | diff --git a/scripts/registry.py b/scripts/registry.py index 3a11080..3c1a333 100755 --- a/scripts/registry.py +++ b/scripts/registry.py @@ -324,6 +324,8 @@ def validate(offline: bool, source=None) -> list[str]: if pid.lower().startswith(RESERVED_PREFIX): errors.append(f"{where} ids under {RESERVED_PREFIX}* are reserved for first-party plugins " "(the host refuses to load them from the user plugin folder)") + if re.fullmatch(r"(?:con|prn|aux|nul|com[1-9]|lpt[1-9])", pid.split(".")[0]): + errors.append(f"{where} Windows device names cannot be installed by the host") if pid in delisted: errors.append(f"{where} was delisted; delisted ids cannot be listed again") lowered = entry["name"].casefold() diff --git a/scripts/test_registry.py b/scripts/test_registry.py index edfc925..a6a7f7f 100644 --- a/scripts/test_registry.py +++ b/scripts/test_registry.py @@ -93,6 +93,13 @@ def mutate(d): d["plugins"].append(dict(EXTERNAL, id="org.animathio.evil")) self.check(mutate, "reserved") + def test_windows_device_ids_are_rejected(self): + for stem in ("con", "prn", "aux", "nul", "com1", "com9", "lpt1", "lpt9"): + with self.subTest(stem=stem): + self.check(lambda d: d["plugins"].append(dict(EXTERNAL, id=f"{stem}.example.plugin")), + "Windows device names") + self.check(lambda d: d["plugins"].append(dict(EXTERNAL, id="com0.example.plugin"))) + def test_duplicate_id(self): self.check(lambda d: d["plugins"].append(dict(d["plugins"][0], name="Other")), "duplicate id") @@ -166,7 +173,7 @@ def test_monorepo_entries_only_accept_id_tags(self): def test_repository_identity_is_pinned(self): source = FakeSource({"v1.2.0": release("1.2.0")}) - source.repo_id = 7 # renamed, transferred or re-created repository + source.repo_id = 7 # a different repository now occupies the configured name data = copy.deepcopy(REAL) data["plugins"] = [dict(EXTERNAL)] RegistryFile(self, data) From 5e1b1c67c7a7e256a51e29a255c37ae215fe111f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kov=C3=A1cs=20B=C3=A1lint=20Hunor?= Date: Tue, 17 Nov 2026 01:42:32 +0200 Subject: [PATCH 5/5] fix(security): isolate plugin builds from publishing credentials --- .github/workflows/index.yml | 36 ++++++++++++-- .github/workflows/release-plugin.yml | 73 ++++++++++++++++++++++------ RELEASING.md | 8 ++- 3 files changed, 95 insertions(+), 22 deletions(-) diff --git a/.github/workflows/index.yml b/.github/workflows/index.yml index d174152..698039f 100644 --- a/.github/workflows/index.yml +++ b/.github/workflows/index.yml @@ -19,15 +19,16 @@ concurrency: permissions: contents: read jobs: - index: + generate: runs-on: ubuntu-latest timeout-minutes: 15 permissions: - contents: write + contents: read steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 with: ref: main + persist-credentials: false - run: python3 -m pip install -r scripts/requirements.txt - name: Regenerate community-index.json env: @@ -35,8 +36,34 @@ jobs: # Not strict: a plugin whose release cannot be verified keeps its previous entry # (or is left out) and a warning annotation is raised; the other plugins still update. run: python3 scripts/registry.py index + - name: Upload the index + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: community-index + path: community-index.json + if-no-files-found: error + commit: + needs: generate + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: write + # Only copy and commit data on this runner; no repository scripts or plugin code. + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: main + persist-credentials: false + - name: Download the index + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: community-index + path: ${{ runner.temp }}/generated-index - name: Commit the index + env: + GH_TOKEN: ${{ github.token }} run: | + cp "$RUNNER_TEMP/generated-index/community-index.json" community-index.json if git diff --quiet -- community-index.json; then echo "community-index.json is up to date" exit 0 @@ -44,5 +71,6 @@ jobs: git config user.name "github-actions[bot]" git config user.email "41898282+github-actions[bot]@users.noreply.github.com" git add community-index.json - git commit -m "chore(registry): update community-index.json" - git push origin HEAD:main + git -c core.hooksPath=/dev/null commit -m "chore(registry): update community-index.json" + auth=$(printf 'x-access-token:%s' "$GH_TOKEN" | base64 -w0) + git -c "http.https://github.com/.extraheader=AUTHORIZATION: basic $auth" push origin HEAD:main diff --git a/.github/workflows/release-plugin.yml b/.github/workflows/release-plugin.yml index 3599d36..ed72458 100644 --- a/.github/workflows/release-plugin.yml +++ b/.github/workflows/release-plugin.yml @@ -16,21 +16,25 @@ on: permissions: contents: read jobs: - release: + build: runs-on: ubuntu-latest timeout-minutes: 45 permissions: - contents: write + contents: read + outputs: + id: ${{ steps.plugin.outputs.id }} + version: ${{ steps.plugin.outputs.version }} + tag: ${{ steps.plugin.outputs.tag }} env: CARGO_BUILD_JOBS: 3 CARGO_PROFILE_DEV_DEBUG: 0 CARGO_INCREMENTAL: 0 ANIMATHIO_AUDIO: none - GH_TOKEN: ${{ github.token }} steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 with: fetch-depth: 0 + persist-credentials: false - name: Only release what is on main run: | git fetch origin main @@ -50,14 +54,6 @@ jobs: else python3 scripts/registry.py resolve --path "$INPUT_PATH" | tee -a "$GITHUB_OUTPUT" fi - - name: Refuse to replace an existing release - env: - TAG: ${{ steps.plugin.outputs.tag }} - run: | - if gh release view "$TAG" > /dev/null 2>&1; then - echo "::error::release $TAG already exists; bump the version in plugin.toml" - exit 1 - fi - name: Build and package env: PLUGIN_PATH: ${{ steps.plugin.outputs.path }} @@ -71,19 +67,64 @@ jobs: env: PLUGIN_ID: ${{ steps.plugin.outputs.id }} run: python3 scripts/registry_smoke.py "${{ steps.cli.outputs.cli }}" dist --only "$PLUGIN_ID" + - name: Upload release assets + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: plugin-release + path: | + dist/${{ steps.plugin.outputs.id }}-${{ steps.plugin.outputs.version }}.amplugin + dist/${{ steps.plugin.outputs.id }}-${{ steps.plugin.outputs.version }}.amplugin.sha256 + if-no-files-found: error + publish: + needs: build + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: write + # A fresh runner: never check out the repository or execute downloaded code here. + steps: + - name: Download release assets + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: plugin-release + path: dist + - name: Verify release assets + env: + PLUGIN_ID: ${{ needs.build.outputs.id }} + VERSION: ${{ needs.build.outputs.version }} + TAG: ${{ needs.build.outputs.tag }} + run: | + python3 - <<'PYTHON' + import hashlib, os, pathlib, re + pid, version, tag = (os.environ[k] for k in ('PLUGIN_ID', 'VERSION', 'TAG')) + assert re.fullmatch(r'[a-z0-9]+(?:[-_][a-z0-9]+)*(?:\.[a-z0-9]+(?:[-_][a-z0-9]+)*){2,}', pid), 'invalid plugin id' + assert re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+', version), 'invalid version' + assert tag == f'{pid}@{version}', 'tag mismatch' + name = f'{pid}-{version}.amplugin' + directory = pathlib.Path('dist') + assert {p.name for p in directory.iterdir()} == {name, name + '.sha256'}, 'unexpected assets' + digest = hashlib.sha256((directory / name).read_bytes()).hexdigest() + assert (directory / (name + '.sha256')).read_text() == f'{digest} {name}\n', 'SHA-256 mismatch' + PYTHON - name: Publish the release env: - TAG: ${{ steps.plugin.outputs.tag }} - PLUGIN_ID: ${{ steps.plugin.outputs.id }} - VERSION: ${{ steps.plugin.outputs.version }} + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + TAG: ${{ needs.build.outputs.tag }} + PLUGIN_ID: ${{ needs.build.outputs.id }} + VERSION: ${{ needs.build.outputs.version }} run: | + if gh release view "$TAG" > /dev/null 2>&1; then + echo "::error::release $TAG already exists; bump the version in plugin.toml" + exit 1 + fi sha=$(cut -d' ' -f1 "dist/$PLUGIN_ID-$VERSION.amplugin.sha256") printf '%s %s\n\nSHA-256: `%s`\n\nInstall from the Plugins tab in AniMathIO 2.2+ (Browse), or download the .amplugin into your user plugin folder. See the README for details.\n' \ "$PLUGIN_ID" "$VERSION" "$sha" > notes.md - gh release create "$TAG" dist/*.amplugin dist/*.amplugin.sha256 \ + gh release create "$TAG" "dist/$PLUGIN_ID-$VERSION.amplugin" "dist/$PLUGIN_ID-$VERSION.amplugin.sha256" \ --target "$GITHUB_SHA" --title "$PLUGIN_ID $VERSION" --notes-file notes.md --latest=false index: - needs: release + needs: publish permissions: contents: write uses: ./.github/workflows/index.yml diff --git a/RELEASING.md b/RELEASING.md index 6172fcd..242bc40 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -21,9 +21,13 @@ of these releases (see [docs/registry.md](docs/registry.md)). The plugin must be 3. `release-plugin.yml` checks that the tag is on `main`, that `plugin.toml` has this id and version, builds the plugin with its `build.sh`, loads and renders it with the released - AniMathIO CLI, and creates the release with `-.amplugin` and + AniMathIO CLI in a read-only job (without persisted checkout credentials), and uploads + the assets. A separate publish runner re-verifies the SHA-256 and creates the release with + `-.amplugin` and `-.amplugin.sha256`. It then calls `index.yml`, which commits the refreshed - `community-index.json` to `main`. + `community-index.json` to `main`. Index generation also runs read-only; a separate runner + only copies and commits the generated JSON. Neither write-enabled job executes plugin code + or repository build scripts. 4. Check that the run is green, that lists the new version, and that `sha256sum -c` passes on the downloaded assets.