Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion .github/workflows/track-releases.yml
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,14 @@ jobs:
if: steps.track.outputs.added != '0'
run: node scripts/validate-index.mjs lithe-plugin-index.json --verify-archives --base "$RUNNER_TEMP/base-index.json"

- name: Verify and record published deltas
if: steps.track.outputs.added != '0'
run: |
if ! command -v zstd && ! sudo apt-get install -y zstd; then
echo "::warning::Optional plugin patches cannot be decoded on this runner."
fi
node scripts/plugin-deltas.mjs refresh "$RUNNER_TEMP/base-index.json"

- name: Open or update the pull request
id: pr
if: steps.track.outputs.added != '0'
Expand All @@ -121,7 +129,7 @@ jobs:
# main is protected, so Sync README could only follow up with a second
# pull request. Render the overview here so one merge covers both.
node scripts/render-readme.mjs
git add lithe-plugin-index.json README.md
git add lithe-plugin-index.json lithe-plugin-deltas.json README.md
git commit -m "chore(index): track $SCOPE plugin releases" -m "$SUMMARY"
git push --force origin "$BRANCH"

Expand Down
11 changes: 10 additions & 1 deletion .github/workflows/validate.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,11 @@ jobs:
with:
node-version: 22

- name: Install the delta verifier
run: sudo apt-get install -y zstd

- name: Unit tests
run: node --test scripts/store.test.mjs
run: node --test scripts/store.test.mjs scripts/plugin-deltas.test.mjs

- name: Validate index
run: node scripts/validate-index.mjs lithe-plugin-index.json
Expand All @@ -48,6 +51,9 @@ jobs:
push) ref="${{ github.event.before }}" ;;
*) ref="" ;;
esac
if [ -n "$ref" ] && git show "$ref:lithe-plugin-deltas.json" > "$RUNNER_TEMP/base-deltas.json" 2>/dev/null; then
echo "deltas=$RUNNER_TEMP/base-deltas.json" >> "$GITHUB_OUTPUT"
fi
if [ -n "$ref" ] && git show "$ref:lithe-plugin-index.json" > "$RUNNER_TEMP/base-index.json" 2>/dev/null; then
echo "args=--base $RUNNER_TEMP/base-index.json" >> "$GITHUB_OUTPUT"
else
Expand All @@ -57,6 +63,9 @@ jobs:
- name: Verify archives (checksum and plugin.json)
run: node scripts/validate-index.mjs lithe-plugin-index.json --verify-archives ${{ steps.base.outputs.args }}

- name: Verify plugin deltas
run: node scripts/plugin-deltas.mjs validate ${{ steps.base.outputs.deltas }}

- name: Check the index contract has not changed
# validate-index.mjs follows the index rules of the Lithe plugin
# contract (v0), published in the Rust Core repository under
Expand Down
9 changes: 5 additions & 4 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

## 索引如何工作

这个仓库只存放一份索引文件 [`lithe-plugin-index.json`](lithe-plugin-index.json),列出插件、
这个仓库以主索引记录完整包,旁边的增量索引记录可选补丁。主索引文件 [`lithe-plugin-index.json`](lithe-plugin-index.json) 列出插件、
它们的版本和每个平台的下载包;插件代码和安装包都留在各自作者的 GitHub 仓库里,通过 GitHub Releases 分发。

Lithe 会把仓库地址 `https://github.com/Lithe-IDEA/Lithe-store` 解析为
Expand Down Expand Up @@ -66,7 +66,8 @@ Lithe 主仓库仍内置少量迁移前的 `dev.lithe.*` 插件,它们正在
## 仓库结构

```text
lithe-plugin-index.json # 唯一的数据文件,Lithe 客户端读取它
lithe-plugin-index.json # 完整包的主索引
lithe-plugin-deltas.json # 可选增量包,保持旧版主索引兼容
scripts/validate-index.mjs # 与 Lithe Rust Core 同规则的校验 + 下载包校验
scripts/track-releases.mjs # 追踪已收录插件和 Lithe-IDEA 组织 lithe-plugin-* 仓库的新 Release,生成索引条目;--scope 区分组织插件与组织外插件
scripts/render-readme.mjs # 根据索引生成 README 的插件总览
Expand All @@ -77,10 +78,10 @@ assets/ # README 用到的图片(无图标插件的默

## 本地校验

需要 Node.js 22+ 与 `unzip`:
需要 Node.js 22+、`unzip` 和 `zstd`:

```bash
node --test scripts/store.test.mjs
node --test scripts/store.test.mjs scripts/plugin-deltas.test.mjs
node scripts/validate-index.mjs --verify-archives
node scripts/render-readme.mjs # 本地预览 README 插件总览
```
12 changes: 12 additions & 0 deletions docs/publishing.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,18 @@ pre-release 的仓库不会被收录。
不匹配或缺失/畸形的能力表、多个资产声明了不同的版本号、插件 API 版本或能力表、
版本号已被别的资产占用。单个发布存在分歧时拒绝整个版本,不只保留其中一个平台包。

### 可选的增量包

发布流水线可用上一版同平台的完整 ZIP 生成增量包。两个 ZIP 都必须是发布物的原始字节,大小最多 64 MiB。完整包继续随 Release 发布。

```bash
node scripts/plugin-deltas.mjs generate previous.zip my-plugin-darwin-arm64.zip 1.2.3
```

在 Store 检出中运行,传入实际路径和已收录的基线版本。命令使用 Zstandard 的 `--patch-from`,重建核对 SHA-256。成功时输出 `my-plugin-darwin-arm64.from-1.2.3.zip.zst` 的路径,上传到新版 ZIP 所在的同一 Release。补丁超过目标 ZIP 大小的 75% 时,命令跳过输出。

Store 跟踪新版本时,按平台在本轮追踪前已公开的三个最近旧版本中查找补丁,采用第一个通过基线和重建校验的补丁,并与主索引一同更新 `lithe-plugin-deltas.json`。首次安装和缺少匹配基线的更新走完整包。格式详见 [Core 市场契约](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/shared/plugins/contract/v1/README.md#delta-archives)。

## 5. 修改信息、转移或下架

- 修改名称、描述、标签、主页、图标:直接提 PR 修改条目。
Expand Down
4 changes: 4 additions & 0 deletions lithe-plugin-deltas.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"schemaVersion": 0,
"patches": []
}
200 changes: 200 additions & 0 deletions scripts/plugin-deltas.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
import { execFileSync } from "node:child_process";
import { createHash } from "node:crypto";
import { mkdtempSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { basename, join, resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { compareVersions } from "./track-releases.mjs";

const maxZIP = 64 * 2 ** 20;
const maxBaseVersions = 3;
const timeLimit = 60_000;
const hex = /^[a-f0-9]{64}$/;
const sha = (bytes) => createHash("sha256").update(bytes).digest("hex");
const names = ["pluginID", "platform", "fromVersion", "fromSHA256", "toVersion",
"toSHA256", "toSize", "format", "downloadURL", "sha256", "size"];
const indexFile = "lithe-plugin-index.json";
const deltasFile = "lithe-plugin-deltas.json";

function archiveFor(entry, version, platform) {
return entry.versions.find((item) => item.version === version)
?.downloads.find((archive) => archive.platforms.includes(platform));
}

function patchURL(target, fromVersion) {
return target.replace(/\.zip$/i, `.from-${fromVersion}.zip.zst`);
}

const key = p => JSON.stringify([p.pluginID, p.platform, p.fromVersion, p.toVersion]);

function referencedArchives(market, p) {
const entry = market.plugins.find((item) => item.id === p.pluginID);
const base = entry && archiveFor(entry, p.fromVersion, p.platform);
const target = entry && archiveFor(entry, p.toVersion, p.platform);
return { base, target };
}

export function validateDeltas(index, market) {
if (index?.schemaVersion !== 0 || Object.keys(index).length !== 2 ||
!Array.isArray(index.patches) || index.patches.length > 20_000) {
throw new Error("invalid marketplace delta index");
}
const known = new Set();
for (const p of index.patches) {
const { base, target } = referencedArchives(market, p ?? {});
if (!p || Object.keys(p).length !== names.length || !names.every((name) => Object.hasOwn(p, name)) ||
!base || base.sha256 !== p.fromSHA256 || !target || target.sha256 !== p.toSHA256 ||
compareVersions(p.fromVersion, p.toVersion) >= 0 ||
p.format !== "zstd-prefix" || p.downloadURL !== patchURL(target.downloadURL, p.fromVersion) ||
!Number.isInteger(p.toSize) || p.toSize < 1 || p.toSize > maxZIP ||
!Number.isInteger(p.size) || p.size < 1 || p.size > Math.floor(p.toSize * 3 / 4) ||
typeof p.sha256 !== "string" || !hex.test(p.sha256) || known.has(key(p))) {
throw new Error(`invalid marketplace delta ${p?.pluginID ?? "entry"}`);
}
known.add(key(p));
}
}

async function fetchBytes(url, limit, optional = false) {
const response = await fetch(url, { signal: AbortSignal.timeout(timeLimit) });
if (optional && response.status === 404) return null;
if (!response.ok || new URL(response.url).protocol !== "https:") {
throw new Error(`Cannot read ${url} (HTTP ${response.status})`);
}
const chunks = [];
let size = 0;
for await (const chunk of response.body) {
size += chunk.length;
if (size > limit) throw new Error(`Size limit exceeded for ${url}`);
chunks.push(chunk);
}
return Buffer.concat(chunks, size);
}

export function reconstruct(base, patch, targetSize) {
const scratch = mkdtempSync(join(tmpdir(), "lithe-store-delta-"));
try {
const basePath = join(scratch, "base.zip");
const patchPath = join(scratch, "plugin.zip.zst");
writeFileSync(basePath, base);
writeFileSync(patchPath, patch);
return execFileSync("zstd", ["-q", "-dc", "-M128MB", `--patch-from=${basePath}`, "--", patchPath],
{ timeout: timeLimit, maxBuffer: targetSize, stdio: ["ignore", "pipe", "pipe"] });
} finally {
rmSync(scratch, { recursive: true, force: true });
}
}

async function verify(base, patch, p, read) {
const bytes = await read(base.downloadURL, maxZIP);
if (sha(bytes) !== p.fromSHA256 || patch.length !== p.size || sha(patch) !== p.sha256) {
throw new Error(`Asset checksum mismatch for ${p.downloadURL}`);
}
const target = reconstruct(bytes, patch, p.toSize);
if (target.length !== p.toSize || sha(target) !== p.toSHA256) {
throw new Error(`Delta does not reconstruct the indexed ZIP for ${p.downloadURL}`);
}
}

async function discoverPatch(entry, known, target, archive, platform, read, report) {
let checked = 0;
for (const from of known) {
if (compareVersions(from.version, target.version) >= 0) continue;
const publishedBase = from.downloads.find((download) => download.platforms.includes(platform));
const base = archiveFor(entry, from.version, platform);
if (!base || base.sha256 !== publishedBase?.sha256) continue;
if (checked === maxBaseVersions) break;
checked++;
const downloadURL = patchURL(archive.downloadURL, from.version);
try {
const patch = await read(downloadURL, maxZIP * 3 / 4, true);
if (!patch) continue;
const zip = await read(archive.downloadURL, maxZIP);
if (sha(zip) !== archive.sha256) throw new Error(`Target checksum mismatch for ${archive.downloadURL}`);
const p = { pluginID: entry.id, platform, fromVersion: from.version, fromSHA256: base.sha256,
toVersion: target.version, toSHA256: archive.sha256, toSize: zip.length,
format: "zstd-prefix", downloadURL, sha256: sha(patch), size: patch.length };
if (p.size > Math.floor(p.toSize * 3 / 4)) continue;
await verify(base, patch, p, read);
return p;
} catch (error) {
// An optional bad asset must not prevent publishing the full package.
report(error);
}
}
return null;
}

export async function refreshDeltas(index, market, previous, read = fetchBytes, report = (error) => { throw error; }) {
// A withdrawn version disappears from both feeds in the same commit.
const patches = index.patches.filter((p) => {
const { base, target } = referencedArchives(market, p);
return base?.sha256 === p.fromSHA256 && target?.sha256 === p.toSHA256;
});
for (const entry of market.plugins) {
// The publisher generates the patch against the public index. This scan may
// include several new versions or follow a Store index update during release.
const known = previous.plugins.find((p) => p.id === entry.id)?.versions ?? [];
for (const target of entry.versions) {
if (known.some((item) => item.version === target.version)) continue;
for (const archive of target.downloads) {
for (const platform of archive.platforms) {
const patch = await discoverPatch(entry, known, target, archive, platform, read, report);
if (patch && !patches.some((other) => key(other) === key(patch))) patches.push(patch);
}
}
}
}
patches.sort((a, b) => key(a).localeCompare(key(b), "en"));
const updated = { schemaVersion: 0, patches };
validateDeltas(updated, market);
return updated;
}

export function generateDelta(base, target, fromVersion) {
if (!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(fromVersion) ||
!target.toLowerCase().endsWith(".zip") || statSync(base).size > maxZIP || statSync(target).size > maxZIP) {
throw new Error("expected a base version and ZIP archives up to 64 MiB");
}
const scratch = mkdtempSync(join(tmpdir(), "lithe-generate-delta-"));
try {
const candidate = join(scratch, "candidate.zip.zst");
execFileSync("zstd", ["-q", "-M128MB", `--patch-from=${resolve(base)}`, "-o", candidate, "--", resolve(target)],
{ timeout: timeLimit, stdio: ["ignore", "pipe", "pipe"] });
const toSize = statSync(target).size;
if (statSync(candidate).size > Math.floor(toSize * 3 / 4)) return null;
const output = resolve(patchURL(basename(target), fromVersion));
const bytes = reconstruct(readFileSync(base), readFileSync(candidate), toSize);
if (sha(bytes) !== sha(readFileSync(target))) throw new Error("generated delta does not reconstruct target ZIP");
writeFileSync(output, readFileSync(candidate), { flag: "wx" });
return output;
} finally {
rmSync(scratch, { recursive: true, force: true });
}
}

const json = path => JSON.parse(readFileSync(path));
if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) {
const [action, base, target, fromVersion] = process.argv.slice(2);
if (action === "generate" && base && target && fromVersion) {
const output = generateDelta(base, target, fromVersion);
if (output) console.log(output);
} else if (action === "refresh" && base) {
const updated = await refreshDeltas(json(deltasFile), json(indexFile), json(base), fetchBytes,
(error) => console.warn(`Plugin delta skipped: ${error.message}`));
const temporary = deltasFile + ".tmp";
writeFileSync(temporary, JSON.stringify(updated, null, 2) + "\n", { flag: "wx" });
renameSync(temporary, deltasFile);
} else if (action === "validate") {
const index = json(deltasFile);
const market = json(indexFile);
validateDeltas(index, market);
const previous = base ? json(base) : { patches: [] };
for (const p of index.patches) {
if (previous.patches.some((other) => JSON.stringify(other) === JSON.stringify(p))) continue;
await verify(referencedArchives(market, p).base, await fetchBytes(p.downloadURL, p.size), p, fetchBytes);
}
} else {
throw new Error("usage: plugin-deltas.mjs generate OLD.zip NEW.zip OLD_VERSION | refresh BASE_INDEX.json | validate [BASE_DELTAS.json]");
}
}
59 changes: 59 additions & 0 deletions scripts/plugin-deltas.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import { generateDelta, reconstruct, refreshDeltas, validateDeltas } from "./plugin-deltas.mjs";

const digest = (bytes) => createHash("sha256").update(bytes).digest("hex");

test("a release delta is generated, verified and bound to both archives", { timeout: 30_000 }, async () => {
const scratch = mkdtempSync(join(tmpdir(), "lithe-store-delta-test-"));
const previousDirectory = process.cwd();
try {
const base = Buffer.concat(Array.from({ length: 256 }, (_, i) => Buffer.from(digest(String(i)), "hex")));
const target = Buffer.from(base);
Buffer.from("changed plugin archive").copy(target, 1024);
writeFileSync(join(scratch, "old.zip"), base);
writeFileSync(join(scratch, "new.zip"), target);
process.chdir(scratch);
const path = generateDelta("old.zip", "new.zip", "1.0.0");
const patch = readFileSync(path);
assert.ok(patch.length < 256);
assert.deepEqual(reconstruct(base, patch, target.length), target);

const repo = "https://github.com/example/delta/releases/download";
const version = (version, asset, bytes) => ({
version,
downloads: [{ platforms: ["darwin-arm64"], downloadURL: `${repo}/v${version}/${asset}`, sha256: digest(bytes) }],
});
const old = version("1.0.0", "old.zip", base);
const next = version("1.1.0", "new.zip", target);
const market = { plugins: [{ id: "io.example.delta", versions: [next, old] }] };
const previous = { plugins: [{ id: "io.example.delta", versions: [old] }] };
const urls = new Map([
[old.downloads[0].downloadURL, base],
[next.downloads[0].downloadURL, target],
[`${repo}/v1.1.0/new.from-1.0.0.zip.zst`, patch],
]);
const empty = { schemaVersion: 0, patches: [] };
const refresh = async (url) => urls.get(url);
const index = await refreshDeltas(empty, market, previous, refresh);
assert.equal(index.patches.length, 1);
assert.equal(index.patches[0].sha256, digest(patch));
const intermediate = version("1.0.1", "intermediate.zip", base);
const batch = { plugins: [{ id: "io.example.delta", versions: [next, intermediate, old] }] };
assert.deepEqual(await refreshDeltas(empty, batch, previous, refresh), index);
const advanced = { plugins: [{ id: "io.example.delta", versions: [intermediate, old] }] };
assert.deepEqual(await refreshDeltas(empty, batch, advanced, refresh), index);
assert.doesNotThrow(() => validateDeltas(index, market));
assert.throws(() => validateDeltas(index, previous), /invalid marketplace delta/);
assert.deepEqual(await refreshDeltas(index, previous, market, refresh), empty);
urls.set(index.patches[0].downloadURL, Buffer.from("corrupt zstd patch"));
await assert.rejects(refreshDeltas(empty, market, previous, refresh));
} finally {
process.chdir(previousDirectory);
rmSync(scratch, { recursive: true, force: true });
}
});