Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:art: Improve marketplace package metadata and resource handling https://github.com/siyuan-note/siyuan/issues/19056

Daniela33950718511
diff --git a/app/src/assets/scss/business/_config.scss b/app/src/assets/scss/business/_config.scss
index 0f4386272a..2e8e346063 100644
--- a/app/src/assets/scss/business/_config.scss
+++ b/app/src/assets/scss/business/_config.scss
@@ -771,6 +771,12 @@
margin: 24px auto 16px;
border-radius: var(--b3-border-radius);
flex-shrink: 0;
+
+ &--placeholder {
+ box-sizing: border-box;
+ color: var(--b3-theme-primary);
+ padding: 24px;
+ }
}
&__meta {
diff --git a/app/src/config/bazaar.ts b/app/src/config/bazaar.ts
index 53304d16da..0f9c5f54b3 100644
--- a/app/src/config/bazaar.ts
+++ b/app/src/config/bazaar.ts
@@ -419,18 +419,29 @@ export const bazaar = {
return `${space}<span data-type="copy-funding" data-funding="${escapeAttr(funding)}" class="block__icon block__icon--show ariaLabel" data-position="north" aria-label="${window.siyuan.languages.sponsor} ${escapeAttr(funding)}"><svg class="ft__pink"><use xlink:href="#iconHeart"></use></svg></span>`;
}
},
- _genReadmeFundingHTML(funding: string): string {
+ _genReadmeFundingHTML(funding: {url: string, label?: string}): string {
try {
- const url = new URL(funding);
+ const url = new URL(funding.url);
if (!["http:", "https:", "mailto:"].includes(url.protocol)) {
throw new Error("not an allowed URL protocol");
}
- const displayFunding = url.host || url.pathname || funding;
- return `<a target="_blank" href="${escapeAttr(funding)}" title="${escapeAttr(funding)}" class="item__meta-funding">${escapeHtml(displayFunding)}</a>`;
+ const displayFunding = funding.label?.trim() || url.host || url.pathname || funding.url;
+ return `<a target="_blank" href="${escapeAttr(funding.url)}" title="${escapeAttr(funding.url)}" class="item__meta-funding">${escapeHtml(displayFunding)}</a>`;
} catch (e) {
- return `<span data-type="copy-funding" data-funding="${escapeAttr(funding)}" title="${escapeAttr(funding)}" class="item__meta-funding ft__primary fn__pointer">${escapeHtml(funding)}</span>`;
+ const displayFunding = funding.label?.trim() || funding.url;
+ return `<span data-type="copy-funding" data-funding="${escapeAttr(funding.url)}" title="${escapeAttr(funding.url)}" class="item__meta-funding ft__primary fn__pointer">${escapeHtml(displayFunding)}</span>`;
}
},
+ _genPackageIconHTML(iconURL: string, detail = false): string {
+ if (iconURL) {
+ const className = detail ? " class=\"item__img\"" : "";
+ return `<img${className} src="${escapeAttr(iconURL)}" loading="lazy" onerror="this.src='/stage/images/icon.png'">`;
+ }
+ if (detail) {
+ return "<svg class=\"item__img item__img--placeholder\"><use xlink:href=\"#iconBazaar\"></use></svg>";
+ }
+ return "<span><svg class=\"b3-card__icon\"><use xlink:href=\"#iconBazaar\"></use></svg></span>";
+ },
_genIncompatibleChipHTML(item: IBazaarItem, source: "installed" | "bazaar", bazaarType: TBazaarType) {
const incompatible = bazaarType === "themes" ?
!isThemeFrontendSupported(item.frontends, getFrontend()) :
@@ -474,7 +485,7 @@ export const bazaar = {
_genInvalidDownloadedCardHTML(item: IBazaarItem, bazaarType: TBazaarType) {
const tip = bazaar._getInvalidPackageTip(item.invalidReason);
return `<div data-name="${escapeAttr(item.name)}" data-package-type="${bazaarType}" data-package-source="downloaded" class="b3-card">
- <div class="b3-card__img"><img src="/stage/images/icon.png" loading="lazy"/></div>
+ <div class="b3-card__img">${bazaar._genPackageIconHTML("")}</div>
<div class="fn__flex-1 fn__flex-column">
<div class="b3-card__info b3-card__info--left fn__flex-1">${escapeHtml(item.name)}</div>
</div>
@@ -761,7 +772,7 @@ ${primaryAction ? '<div class="fn__hr"></div>' : ""}
const showDisable = item.installed && item.current && ["icons", "themes"].includes(bazaarType);
return `<div data-name="${escapeAttr(item.name)}" data-package-type="${bazaarType}" data-package-source="bazaar" class="b3-card${item.current ? " b3-card--current" : ""}">
<div class="b3-card__img">
- <img src="${escapeAttr(item.iconURL)}" loading="lazy" onerror="this.src='/stage/images/icon.png'"/>
+ ${bazaar._genPackageIconHTML(item.iconURL)}
</div>
<div class="fn__flex-1 fn__flex-column">
<div class="b3-card__info fn__flex-1">
@@ -846,7 +857,7 @@ ${primaryAction ? '<div class="fn__hr"></div>' : ""}
const ratingKey = bazaar._getRatingKey(bazaarType, installed.name);
const ratingLoaded = isBazaarPackageRatingLoaded("updated", bazaar._data.downloadedRatingKeys.has(ratingKey));
return `<div class="b3-card" data-name="${escapeAttr(installed.name)}" data-package-type="${bazaarType}" data-package-source="updated">
- <div class="b3-card__img"><img src="${escapeAttr(installed.iconURL)}" loading="lazy" onerror="this.src='/stage/images/icon.png'"/></div>
+ <div class="b3-card__img">${bazaar._genPackageIconHTML(installed.iconURL)}</div>
<div class="fn__flex-1 fn__flex-column">
<div class="b3-card__info b3-card__info--left fn__flex-1">
${escapeHtml(installed.preferredName)}
@@ -1099,7 +1110,7 @@ ${primaryAction ? '<div class="fn__hr"></div>' : ""}
const available = bazaar._getUpdatedItem(bazaarType, bazaarItem.name)?.available;
const ratingKey = bazaar._getRatingKey(bazaarType, bazaarItem.name);
return `<div data-name="${escapeAttr(bazaarItem.name)}" data-package-type="${bazaarType}" data-package-source="downloaded" class="b3-card${bazaarItem.current ? " b3-card--current" : ""}">
- <div class="b3-card__img"><img src="${escapeAttr(bazaarItem.iconURL)}" loading="lazy" onerror="this.src='/stage/images/icon.png'"/></div>
+ <div class="b3-card__img">${bazaar._genPackageIconHTML(bazaarItem.iconURL)}</div>
<div class="fn__flex-1 fn__flex-column">
<div class="b3-card__info b3-card__info--left fn__flex-1">
${escapeHtml(bazaarItem.preferredName)}
@@ -1308,7 +1319,7 @@ type="checkbox">
</div>` : "";
const fundingItems = getBazaarFundingItems(resourceData.funding);
if (fundingItems.length === 0 && resourceData.preferredFunding) {
- fundingItems.push(resourceData.preferredFunding);
+ fundingItems.push({url: resourceData.preferredFunding});
}
const packageSection = `<section class="item__meta-section">
<div class="item__meta-title">${window.siyuan.languages.bazaarPackageInfo}</div>
@@ -1324,10 +1335,12 @@ type="checkbox">
${bazaar._genReadmeActionsHTML(bazaarType, installed, available)}
${bazaar._genReadmeUpdateButtonHTML(available, bazaarType, Boolean(installed))}
</div>`;
+ const previewHTML = displayData.previewURL ?
+ `<div class="item__preview" data-preview-url="${escapeAttr(displayData.previewURL)}"></div>` : "";
readmeElement.innerHTML = `${isMobile() ? backHeaderHTML : ""}<div class="item__body"><div class="item__side" data-from="${from}" data-name="${escapeAttr(displayData.name)}" data-package-type="${bazaarType}" data-repourl="${escapeAttr(resourceData.repoURL)}" data-progress-id="${escapeAttr(available?.repoURL || resourceData.repoURL)}">
${isMobile() ? "" : backHeaderHTML}
<div class="fn__flex-1">
- <img class="item__img" src="${escapeAttr(displayData.iconURL)}" loading="lazy" onerror="this.src='/stage/images/icon.png'">
+ ${bazaar._genPackageIconHTML(displayData.iconURL, true)}
<div>
<span class="item__title">${escapeHtml(displayData.preferredName)}</span>
</div>
@@ -1353,7 +1366,7 @@ type="checkbox">
${isMobile() ? "" : readmeActionsHTML}
</div>
<div class="item__main">
- <div class="item__preview" data-preview-url="${escapeAttr(displayData.previewURL)}" style="background-image: url(${escapeAttr(displayData.previewURL)})"></div>
+ ${previewHTML}
<div class="b3-typography${displayData.preferredDesc ? "" : " fn__none"}">
<blockquote>
<p>
@@ -1365,6 +1378,10 @@ type="checkbox">
<img data-type="img-loading" style="height: 64px;width: 100%;padding: 16px 0;" src="/stage/loading-pure.svg">
</div>
</div></div>${isMobile() ? readmeActionsHTML : ""}`;
+ const previewElement = readmeElement.querySelector<HTMLElement>(".item__preview");
+ if (previewElement) {
+ previewElement.style.backgroundImage = `url(${JSON.stringify(displayData.previewURL)})`;
+ }
const isInstalledReadme = from === "downloaded";
if (isInstalledReadme) {
const mdElement = readmeElement.querySelector(".item__readme");
@@ -2621,6 +2638,7 @@ type="checkbox">
repoURL: installItem.repoURL,
packageName: installItem.name,
repoHash: installItem.repoHash,
+ repoRef: installItem.repoRef || "",
...themeAppearanceMode,
frontend: getFrontend()
}, response => {
diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.ts
index 0851d6cf9c..708d72a0b2 100644
--- a/app/src/types/index.d.ts
+++ b/app/src/types/index.d.ts
@@ -1136,11 +1136,17 @@ interface IMenu {
warning?: boolean
}
+interface IBazaarFundingLink {
+ label: string;
+ url: string;
+}
+
interface IBazaarFunding {
openCollective?: string;
patreon?: string;
github?: string;
custom?: string[];
+ links?: IBazaarFundingLink[];
}
type TBazaarRatingDistribution = [number, number, number, number, number];
@@ -1180,6 +1186,7 @@ interface IBazaarItem {
name: string;
previewURL: string;
repoHash: string;
+ repoRef?: string;
repoURL: string;
url: string;
openIssues: number;
diff --git a/app/src/util/bazaarPackage.test.ts b/app/src/util/bazaarPackage.test.ts
index 23a17d0615..aa708d3fb0 100644
--- a/app/src/util/bazaarPackage.test.ts
+++ b/app/src/util/bazaarPackage.test.ts
@@ -220,19 +220,34 @@ describe("getBazaarFundingItems", () => {
github: "sponsor",
custom: ["custom text", "https://example.com/custom", "custom text"],
}), [
- "https://opencollective.com/collective",
- "https://example.com/patreon",
- "https://github.com/sponsors/sponsor",
- "custom text",
- "https://example.com/custom",
- "custom text",
+ {url: "https://opencollective.com/collective"},
+ {url: "https://example.com/patreon"},
+ {url: "https://github.com/sponsors/sponsor"},
+ {url: "custom text"},
+ {url: "https://example.com/custom"},
+ {url: "custom text"},
]);
});
it("removes empty values without discarding later custom items", () => {
- assert.deepEqual(getBazaarFundingItems({custom: ["", "https://example.com"]}), ["https://example.com"]);
+ assert.deepEqual(getBazaarFundingItems({custom: ["", "https://example.com"]}), [
+ {url: "https://example.com"},
+ ]);
assert.deepEqual(getBazaarFundingItems(undefined), []);
});
+
+ it("preserves labeled links after custom items", () => {
+ assert.deepEqual(getBazaarFundingItems({
+ custom: ["https://example.com/custom"],
+ links: [
+ {label: "Buy me a coffee", url: "https://example.com/coffee"},
+ {label: "Empty", url: ""},
+ ],
+ }), [
+ {url: "https://example.com/custom"},
+ {label: "Buy me a coffee", url: "https://example.com/coffee"},
+ ]);
+ });
});
describe("isValidBazaarPackageName", () => {
diff --git a/app/src/util/bazaarPackage.ts b/app/src/util/bazaarPackage.ts
index 393c922098..98868a0e22 100644
--- a/app/src/util/bazaarPackage.ts
+++ b/app/src/util/bazaarPackage.ts
@@ -129,11 +129,12 @@ export const getBazaarFundingItems = (funding: IBazaarFunding | null | undefined
return [];
}
return [
- normalizeBazaarFundingURL(funding.openCollective, "https://opencollective.com/"),
- normalizeBazaarFundingURL(funding.patreon, "https://www.patreon.com/"),
- normalizeBazaarFundingURL(funding.github, "https://github.com/sponsors/"),
- ...(funding.custom || []),
- ].filter(Boolean);
+ {url: normalizeBazaarFundingURL(funding.openCollective, "https://opencollective.com/")},
+ {url: normalizeBazaarFundingURL(funding.patreon, "https://www.patreon.com/")},
+ {url: normalizeBazaarFundingURL(funding.github, "https://github.com/sponsors/")},
+ ...(funding.custom || []).map((url) => ({url})),
+ ...(funding.links || []).map((link) => ({url: link.url, label: link.label})),
+ ].filter((item) => Boolean(item.url));
};
export const normalizeBazaarRating = (rating: Partial<IBazaarRating> | null | undefined): IBazaarRating | undefined => {
diff --git a/kernel/api/bazaar.go b/kernel/api/bazaar.go
index af7c7f0ced..2e67c1d395 100644
--- a/kernel/api/bazaar.go
+++ b/kernel/api/bazaar.go
@@ -535,17 +535,18 @@ func installBazaarPlugin(c *gin.Context) {
return
}
- var frontend, keyword, repoURL, repoHash, packageName string
+ var frontend, keyword, repoURL, repoHash, repoRef, packageName string
if !util.ParseJsonArgs(arg, ret,
util.BindJsonArg("frontend", &frontend, true, true),
util.BindJsonArg("keyword", &keyword, false, false),
util.BindJsonArg("repoURL", &repoURL, true, true),
util.BindJsonArg("repoHash", &repoHash, true, true),
+ util.BindJsonArg("repoRef", &repoRef, false, false),
util.BindJsonArg("packageName", &packageName, true, true),
) {
return
}
- err := model.InstallBazaarPackage("plugins", repoURL, repoHash, packageName, nil)
+ err := model.InstallBazaarPackage("plugins", repoURL, repoHash, repoRef, packageName, nil)
if err != nil {
ret.Code = 1
ret.Msg = err.Error()
@@ -642,16 +643,17 @@ func installBazaarWidget(c *gin.Context) {
return
}
- var keyword, repoURL, repoHash, packageName string
+ var keyword, repoURL, repoHash, repoRef, packageName string
if !util.ParseJsonArgs(arg, ret,
util.BindJsonArg("keyword", &keyword, false, false),
util.BindJsonArg("repoURL", &repoURL, true, true),
util.BindJsonArg("repoHash", &repoHash, true, true),
+ util.BindJsonArg("repoRef", &repoRef, false, false),
util.BindJsonArg("packageName", &packageName, true, true),
) {
return
}
- err := model.InstallBazaarPackage("widgets", repoURL, repoHash, packageName, nil)
+ err := model.InstallBazaarPackage("widgets", repoURL, repoHash, repoRef, packageName, nil)
if err != nil {
ret.Code = 1
ret.Msg = err.Error()
@@ -739,16 +741,17 @@ func installBazaarIcon(c *gin.Context) {
return
}
- var keyword, repoURL, repoHash, packageName string
+ var keyword, repoURL, repoHash, repoRef, packageName string
if !util.ParseJsonArgs(arg, ret,
util.BindJsonArg("keyword", &keyword, false, false),
util.BindJsonArg("repoURL", &repoURL, true, true),
util.BindJsonArg("repoHash", &repoHash, true, true),
+ util.BindJsonArg("repoRef", &repoRef, false, false),
util.BindJsonArg("packageName", &packageName, true, true),
) {
return
}
- err := model.InstallBazaarPackage("icons", repoURL, repoHash, packageName, nil)
+ err := model.InstallBazaarPackage("icons", repoURL, repoHash, repoRef, packageName, nil)
if err != nil {
ret.Code = 1
ret.Msg = err.Error()
@@ -838,16 +841,17 @@ func installBazaarTemplate(c *gin.Context) {
return
}
- var keyword, repoURL, repoHash, packageName string
+ var keyword, repoURL, repoHash, repoRef, packageName string
if !util.ParseJsonArgs(arg, ret,
util.BindJsonArg("keyword", &keyword, false, false),
util.BindJsonArg("repoURL", &repoURL, true, true),
util.BindJsonArg("repoHash", &repoHash, true, true),
+ util.BindJsonArg("repoRef", &repoRef, false, false),
util.BindJsonArg("packageName", &packageName, true, true),
) {
return
}
- err := model.InstallBazaarPackage("templates", repoURL, repoHash, packageName, nil)
+ err := model.InstallBazaarPackage("templates", repoURL, repoHash, repoRef, packageName, nil)
if err != nil {
ret.Code = 1
ret.Msg = err.Error()
@@ -942,12 +946,13 @@ func installBazaarTheme(c *gin.Context) {
return
}
- var frontend, keyword, repoURL, repoHash, packageName string
+ var frontend, keyword, repoURL, repoHash, repoRef, packageName string
if !util.ParseJsonArgs(arg, ret,
util.BindJsonArg("frontend", &frontend, false, false),
util.BindJsonArg("keyword", &keyword, false, false),
util.BindJsonArg("repoURL", &repoURL, true, true),
util.BindJsonArg("repoHash", &repoHash, true, true),
+ util.BindJsonArg("repoRef", &repoRef, false, false),
util.BindJsonArg("packageName", &packageName, true, true),
) {
return
@@ -979,7 +984,7 @@ func installBazaarTheme(c *gin.Context) {
themeOptions = &model.ThemeInstallOptions{Mode: int(mode), ModeOS: modeOS}
}
- err := model.InstallBazaarPackage("themes", repoURL, repoHash, packageName, themeOptions)
+ err := model.InstallBazaarPackage("themes", repoURL, repoHash, repoRef, packageName, themeOptions)
if err != nil {
ret.Code = 1
ret.Msg = err.Error()
diff --git a/kernel/bazaar/bazaar.go b/kernel/bazaar/bazaar.go
index a5fb6e2a5b..60040beae3 100644
--- a/kernel/bazaar/bazaar.go
+++ b/kernel/bazaar/bazaar.go
@@ -18,8 +18,11 @@ package bazaar
import (
"errors"
+ "net/url"
+ "path"
"strings"
"time"
+ "unicode"
"github.com/88250/go-humanize"
"github.com/araddon/dateparse"
@@ -90,6 +93,63 @@ func isValidStageRepoURL(url string) bool {
return true
}
+func packageImageName(configured *string, legacyName string) string {
+ if configured == nil {
+ return legacyName
+ }
+ return *configured
+}
+
+func isSupportedPackageImageName(name string) bool {
+ if name == "" || name != strings.TrimSpace(name) || path.Base(name) != name || strings.ContainsRune(name, '\\') {
+ return false
+ }
+ switch strings.ToLower(path.Ext(name)) {
+ case ".png", ".jpg", ".jpeg", ".webp", ".avif":
+ return true
+ }
+ return false
+}
+
+func onlinePackageImageURL(repoURL, imageName string) string {
+ if !isSupportedPackageImageName(imageName) {
+ return ""
+ }
+ return util.BazaarOSSServer + "/package/" + repoURL + "/" + url.PathEscape(imageName)
+}
+
+func onlinePackagePreviewURL(repoURL, imageName string) string {
+ previewURL := onlinePackageImageURL(repoURL, imageName)
+ if previewURL == "" {
+ return ""
+ }
+ switch strings.ToLower(path.Ext(imageName)) {
+ case ".png", ".jpg", ".jpeg":
+ return previewURL + "?imageslim"
+ }
+ return previewURL
+}
+
+func normalizeGitHubPackageSource(repoURL, repoRef string) (string, string) {
+ const githubPrefix = "https://github.com/"
+ repoURL = strings.TrimSuffix(repoURL, "/")
+ if !strings.HasPrefix(repoURL, githubPrefix) || !isValidBazaarRepo(strings.TrimPrefix(repoURL, githubPrefix)) {
+ return "", ""
+ }
+ if repoRef == "" {
+ return repoURL, ""
+ }
+ if len(repoRef) > 256 || repoRef != strings.TrimSpace(repoRef) {
+ return "", ""
+ }
+ for _, r := range repoRef {
+ if unicode.IsControl(r) {
+ return "", ""
+ }
+ }
+ return repoURL, repoRef
+}
+
// buildBazaarPackageWithMetadata 从 StageRepo 构建带有在线元数据的集市包。
func buildBazaarPackageWithMetadata(repo *StageRepo, bazaarStats map[string]*bazaarStats,
bazaarRatings map[string]*PackageRating, ratingsAvailable bool, pkgType string, frontend string) *Package {
@@ -106,10 +166,11 @@ func buildBazaarPackageWithMetadata(repo *StageRepo, bazaarStats map[string]*baz
}
pkg.RepoURL = "https://github.com/" + repoURLHash[0]
pkg.RepoHash = repoURLHash[1]
+ pkg.RepoRef = repo.RepoRef
// 展示信息
- pkg.IconURL = util.BazaarOSSServer + "/package/" + repo.URL + "/icon.png"
- pkg.PreviewURL = util.BazaarOSSServer + "/package/" + repo.URL + "/preview.png?imageslim"
+ pkg.IconURL = onlinePackageImageURL(repo.URL, packageImageName(pkg.Icon, "icon.png"))
+ pkg.PreviewURL = onlinePackagePreviewURL(repo.URL, packageImageName(pkg.Preview, "preview.png"))
pkg.PreferredName = GetPreferredLocaleString(pkg.DisplayName, pkg.Name)
pkg.PreferredDesc = GetPreferredLocaleString(pkg.Description, "")
pkg.PreferredFunding = getPreferredFunding(pkg.Funding)
diff --git a/kernel/bazaar/install.go b/kernel/bazaar/install.go
index 3c8461ec50..0531b7502c 100644
--- a/kernel/bazaar/install.go
+++ b/kernel/bazaar/install.go
@@ -96,7 +96,7 @@ var packageManifestNames = func() map[string]string {
}()
// InstallPackage 安装集市包
-func InstallPackage(repoURL, repoHash, installPath, systemID, pkgType, packageName string, update bool) error {
+func InstallPackage(repoURL, repoHash, repoRef, installPath, systemID, pkgType, packageName string, update bool) error {
var fallbackInstallTime time.Time
if update {
if info, statErr := os.Stat(installPath); statErr == nil {
@@ -116,7 +116,7 @@ func InstallPackage(repoURL, repoHash, installPath, systemID, pkgType, packageNa
// 记录首次安装时间或最近更新时间
now := time.Now()
- recordPackageOperationTime(pkgType, packageName, now, fallbackInstallTime, update)
+ recordPackageOperationTime(pkgType, packageName, now, fallbackInstallTime, update, repoURL, repoRef)
// 文件夹的修改时间设置为当前操作时间
if err = os.Chtimes(installPath, now, now); err != nil {
@@ -258,7 +258,7 @@ func InstallLocalPackage(sourcePath, installPath, pkgType, packageName string, u
RemoveInstalledPackageSizeCache(pkgType, packageName)
now := time.Now()
- recordPackageOperationTime(pkgType, packageName, now, fallbackInstallTime, update)
+ recordPackageOperationTime(pkgType, packageName, now, fallbackInstallTime, update, "", "")
if chtimesErr := os.Chtimes(installPath, now, now); chtimesErr != nil {
logging.LogWarnf("set package [%s] folder mtime failed: %s", packageName, chtimesErr)
}
diff --git a/kernel/bazaar/installed.go b/kernel/bazaar/installed.go
index 4cd67c5390..5768ad9b59 100644
--- a/kernel/bazaar/installed.go
+++ b/kernel/bazaar/installed.go
@@ -17,8 +17,10 @@
package bazaar
import (
+ "net/url"
"os"
"path/filepath"
+ "strconv"
"sync"
"time"
@@ -87,20 +89,24 @@ func PackageDirContainsFile(dirPath string) (bool, error) {
// SetInstalledPackageMetadata 设置本地集市包的通用元数据
func SetInstalledPackageMetadata(pkg *Package, installPath, baseURLPath, pkgType string) bool {
clearBazaarPackageRating(pkg)
+ pkg.InstallTime, pkg.UpdateTime = getPackageTimes(pkgType, pkg.Name, installPath)
+ pkg.RepoRef = getPackageRepoRef(pkgType, pkg.Name)
+ cacheVersion := installedPackageCacheVersion(pkg)
if pkg.InvalidReason != "" {
pkg.PreferredName = pkg.Name
pkg.Installed = true
- pkg.InstallTime, pkg.UpdateTime = getPackageTimes(pkgType, pkg.Name, installPath)
pkg.HInstallDate = time.UnixMilli(pkg.InstallTime).Format("2006-01-02")
return true
}
// 展示信息
- pkg.IconURL = baseURLPath + "icon.png"
- pkg.PreviewURL = baseURLPath + "preview.png"
+ pkg.IconURL = installedPackageImageURL(installPath, baseURLPath, packageImageName(pkg.Icon, "icon.png"), cacheVersion)
+ pkg.PreviewURL = installedPackageImageURL(installPath, baseURLPath, packageImageName(pkg.Preview, "preview.png"), cacheVersion)
pkg.PreferredName = GetPreferredLocaleString(pkg.DisplayName, pkg.Name)
pkg.PreferredDesc = GetPreferredLocaleString(pkg.Description, "")
- pkg.PreferredReadme = getInstalledPackageREADME(installPath, baseURLPath, pkg.Readme)
+ sourceRepoURL, sourceRepoRef := getPackageSource(pkgType, pkg.Name)
+ pkg.PreferredReadme = getInstalledPackageREADME(installPath, baseURLPath, sourceRepoURL, sourceRepoRef,
+ cacheVersion, pkg.Readme)
pkg.PreferredFunding = getPreferredFunding(pkg.Funding)
// 安装状态
@@ -113,13 +119,48 @@ func SetInstalledPackageMetadata(pkg *Package, installPath, baseURLPath, pkgType
pkg.RepoURL = ""
}
- // 安装信息
- pkg.InstallTime, pkg.UpdateTime = getPackageTimes(pkgType, pkg.Name, installPath)
pkg.HInstallDate = time.UnixMilli(pkg.InstallTime).Format("2006-01-02")
return true
}
+// RefreshInstalledPackageREADME 使用已确认的在线版本来源重新渲染本地 README。
+func RefreshInstalledPackageREADME(pkg *Package, installPath, baseURLPath, repoURL, repoRef string) {
+ if pkg == nil {
+ return
+ }
+ repoURL, repoRef = normalizeGitHubPackageSource(repoURL, repoRef)
+ if repoURL == "" || repoRef == "" {
+ return
+ }
+ pkg.PreferredReadme = getInstalledPackageREADME(installPath, baseURLPath, repoURL, repoRef,
+ installedPackageCacheVersion(pkg), pkg.Readme)
+ pkg.RepoRef = repoRef
+}
+
+func installedPackageCacheVersion(pkg *Package) int64 {
+ ret := pkg.InstallTime
+ if pkg.UpdateTime > ret {
+ ret = pkg.UpdateTime
+ }
+ return ret
+}
+
+func installedPackageImageURL(installPath, baseURLPath, imageName string, cacheVersion int64) string {
+ if !isSupportedPackageImageName(imageName) {
+ return ""
+ }
+ info, err := os.Stat(filepath.Join(installPath, imageName))
+ if err != nil || !info.Mode().IsRegular() {
+ return ""
+ }
+ ret := baseURLPath + url.PathEscape(imageName)
+ if cacheVersion > 0 {
+ ret += "?v=" + strconv.FormatInt(cacheVersion, 10)
+ }
+ return ret
+}
+
// GetInstalledPackageSize 获取本地集市包的安装大小,结果缓存一分钟
func GetInstalledPackageSize(pkgType, packageName, installPath string) (size int64, hSize string, err error) {
cacheKey := pkgType + ":" + packageName
@@ -193,8 +234,10 @@ type BazaarInfo struct {
// PackageInfo 集市包的持久化信息
type PackageInfo struct {
- InstallTime int64 `json:"installTime"` // 安装时间戳(毫秒)
- UpdateTime int64 `json:"updateTime"` // 更新时间戳(毫秒)
+ InstallTime int64 `json:"installTime"` // 安装时间戳(毫秒)
+ UpdateTime int64 `json:"updateTime"` // 更新时间戳(毫秒)
+ RepoURL string `json:"repoURL,omitempty"`
+ RepoRef string `json:"repoRef,omitempty"`
}
var (
@@ -286,8 +329,10 @@ func saveBazaarInfo() {
}
// recordPackageOperationTime 记录集市包的首次安装时间或最近更新时间
-func recordPackageOperationTime(pkgType, pkgName string, operationTime, fallbackInstallTime time.Time, update bool) {
+func recordPackageOperationTime(pkgType, pkgName string, operationTime, fallbackInstallTime time.Time, update bool,
+ repoURL, repoRef string) {
getBazaarInfo()
+ repoURL, repoRef = normalizeGitHubPackageSource(repoURL, repoRef)
bazaarInfoCacheLock.Lock()
defer bazaarInfoCacheLock.Unlock()
@@ -318,9 +363,29 @@ func recordPackageOperationTime(pkgType, pkgName string, operationTime, fallback
p.InstallTime = operationTime.UnixMilli()
p.UpdateTime = 0
}
+ p.RepoURL = repoURL
+ p.RepoRef = repoRef
saveBazaarInfo()
}
+func getPackageSource(pkgType, pkgName string) (repoURL, repoRef string) {
+ getBazaarInfo()
+ bazaarInfoCacheLock.RLock()
+ defer bazaarInfoCacheLock.RUnlock()
+ if bazaarInfoCache == nil || bazaarInfoCache.Packages[pkgType] == nil {
+ return
+ }
+ if info := bazaarInfoCache.Packages[pkgType][pkgName]; info != nil {
+ return normalizeGitHubPackageSource(info.RepoURL, info.RepoRef)
+ }
+ return
+}
+
+func getPackageRepoRef(pkgType, pkgName string) string {
+ _, repoRef := getPackageSource(pkgType, pkgName)
+ return repoRef
+}
+
// ensurePackageInstallTime 在没有首次安装时间时进行初始化
func ensurePackageInstallTime(pkgType, pkgName string, fallbackInstallTime time.Time) (installTime, updateTime int64) {
getBazaarInfo()
diff --git a/kernel/bazaar/installed_test.go b/kernel/bazaar/installed_test.go
index ec3150353c..0ae0ce43f9 100644
--- a/kernel/bazaar/installed_test.go
+++ b/kernel/bazaar/installed_test.go
@@ -19,13 +19,15 @@ package bazaar
import (
"os"
"path/filepath"
+ "strings"
"testing"
"time"
"github.com/siyuan-note/siyuan/kernel/util"
)
-func TestRecordPackageOperationTime(t *testing.T) {
+func useTestBazaarInfo(t *testing.T) {
+ t.Helper()
oldDataDir := util.DataDir
bazaarInfoCacheLock.Lock()
oldCache := bazaarInfoCache
@@ -41,11 +43,17 @@ func TestRecordPackageOperationTime(t *testing.T) {
bazaarInfoModTime = oldModTime
bazaarInfoCacheLock.Unlock()
})
+}
+
+func TestRecordPackageOperationTime(t *testing.T) {
+ useTestBazaarInfo(t)
installTime := time.UnixMilli(1000)
updateTime := time.UnixMilli(2000)
- recordPackageOperationTime("plugins", "test-package", installTime, time.Time{}, false)
- recordPackageOperationTime("plugins", "test-package", updateTime, time.Time{}, true)
+ recordPackageOperationTime("plugins", "test-package", installTime, time.Time{}, false,
+ "https://github.com/owner/repo", "v1.0.0")
+ recordPackageOperationTime("plugins", "test-package", updateTime, time.Time{}, true,
+ "https://github.com/owner/repo", "v2.0.0")
info := bazaarInfoCache.Packages["plugins"]["test-package"]
if info.InstallTime != installTime.UnixMilli() {
@@ -54,6 +62,9 @@ func TestRecordPackageOperationTime(t *testing.T) {
if info.UpdateTime != updateTime.UnixMilli() {
t.Fatalf("unexpected update time: %d", info.UpdateTime)
}
+ if info.RepoURL != "https://github.com/owner/repo" || info.RepoRef != "v2.0.0" {
+ t.Fatalf("unexpected package source: %#v", info)
+ }
gotInstallTime, gotUpdateTime := ensurePackageInstallTime("plugins", "test-package", time.UnixMilli(3000))
if gotInstallTime != installTime.UnixMilli() || gotUpdateTime != updateTime.UnixMilli() {
@@ -61,7 +72,7 @@ func TestRecordPackageOperationTime(t *testing.T) {
}
reinstallTime := time.UnixMilli(4000)
- recordPackageOperationTime("plugins", "test-package", reinstallTime, time.Time{}, false)
+ recordPackageOperationTime("plugins", "test-package", reinstallTime, time.Time{}, false, "", "")
info = bazaarInfoCache.Packages["plugins"]["test-package"]
if info.InstallTime != reinstallTime.UnixMilli() {
t.Fatalf("unexpected reinstall time: %d", info.InstallTime)
@@ -69,6 +80,57 @@ func TestRecordPackageOperationTime(t *testing.T) {
if info.UpdateTime != 0 {
t.Fatalf("update time was not cleared after reinstall: %d", info.UpdateTime)
}
+ if info.RepoURL != "" || info.RepoRef != "" {
+ t.Fatalf("local reinstall retained remote source: %#v", info)
+ }
+}
+
+func TestRecordPackageOperationTimeRejectsUntrustedSource(t *testing.T) {
+ useTestBazaarInfo(t)
+ recordPackageOperationTime("plugins", "test-package", time.UnixMilli(1000), time.Time{}, false,
+ "https://example.com/owner/repo", "v1.0.0")
+ info := bazaarInfoCache.Packages["plugins"]["test-package"]
+ if info.RepoURL != "" || info.RepoRef != "" {
+ t.Fatalf("untrusted package source was persisted: %#v", info)
+ }
+}
+
+func TestSetInstalledPackageMetadataImageURLs(t *testing.T) {
+ useTestBazaarInfo(t)
+ installPath := t.TempDir()
+ for name, content := range map[string]string{
+ "README.md": "README\n\n![icon](custom%20%23%25%28+%29.webp)",
+ "custom #%(+).webp": "icon",
+ "preview.png": "preview",
+ } {
+ if err := os.WriteFile(filepath.Join(installPath, name), []byte(content), 0644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ icon := "custom #%(+).webp"
+ noPreview := ""
+ recordPackageOperationTime("plugins", "A B#C%D(E)+F", time.UnixMilli(2000), time.Time{}, false, "", "")
+ recordPackageOperationTime("plugins", "A B#C%D(E)+F", time.UnixMilli(1000), time.Time{}, true, "", "")
+ pkg := &Package{
+ Name: "A B#C%D(E)+F",
+ Icon: &icon,
+ Preview: &noPreview,
+ Readme: LocaleStrings{"default": "README.md"},
+ }
+ baseURL := "/plugins/A%20B%23C%25D%28E%29+F/"
+ if !SetInstalledPackageMetadata(pkg, installPath, baseURL, "plugins") {
+ t.Fatal("expected installed metadata")
+ }
+ if pkg.IconURL != baseURL+"custom%20%23%25%28+%29.webp?v=2000" {
+ t.Fatalf("unexpected icon URL: %q", pkg.IconURL)
+ }
+ if pkg.PreviewURL != "" {
+ t.Fatalf("explicit missing preview should not use preview.png: %q", pkg.PreviewURL)
+ }
+ if !strings.Contains(pkg.PreferredReadme, baseURL+"custom%20%23%25%28+%29.webp?v=2000") ||
+ !strings.Contains(pkg.PreferredReadme, "README") {
+ t.Fatalf("unexpected installed README: %q", pkg.PreferredReadme)
+ }
}
func TestInstalledPackageSizeCacheAndInvalidation(t *testing.T) {
diff --git a/kernel/bazaar/package.go b/kernel/bazaar/package.go
index 45b9fc6428..62cb4d824b 100644
--- a/kernel/bazaar/package.go
+++ b/kernel/bazaar/package.go
@@ -33,10 +33,16 @@ import (
type LocaleStrings map[string]string
type Funding struct {
- OpenCollective string `json:"openCollective"`
- Patreon string `json:"patreon"`
- GitHub string `json:"github"`
- Custom []string `json:"custom"`
+ OpenCollective string `json:"openCollective"`
+ Patreon string `json:"patreon"`
+ GitHub string `json:"github"`
+ Custom []string `json:"custom"`
+ Links []FundingLink `json:"links,omitempty"`
+}
+
+type FundingLink struct {
+ Label string `json:"label"`
+ URL string `json:"url"`
}
// PackageRating 描述集市包的公开评分汇总。
@@ -67,6 +73,8 @@ type Package struct {
DisplayName LocaleStrings `json:"displayName"`
Description LocaleStrings `json:"description"`
Readme LocaleStrings `json:"readme"`
+ Icon *string `json:"icon,omitempty"`
+ Preview *string `json:"preview,omitempty"`
Funding *Funding `json:"funding"`
Keywords []string `json:"keywords"`
Deprecated bool `json:"deprecated,omitempty"`
@@ -82,6 +90,7 @@ type Package struct {
Name string `json:"name"` // 包名,不一定是仓库名
RepoURL string `json:"repoURL"` // 形式为 https://github.com/owner/repo
RepoHash string `json:"repoHash"`
+ RepoRef string `json:"repoRef,omitempty"`
PreviewURL string `json:"previewURL"`
IconURL string `json:"iconURL"`
@@ -151,6 +160,7 @@ func IsValidInstalledPackage(pkg *Package, dirName string) bool {
type StageRepo struct {
URL string `json:"url"` // owner/repo@hash 形式
+ RepoRef string `json:"repoRef,omitempty"`
Updated string `json:"updated"`
Stars int `json:"stars"`
OpenIssues int `json:"openIssues"`
@@ -224,6 +234,10 @@ func unescapePackageDisplayStrings(pkg *Package) {
for i, v := range pkg.Funding.Custom {
pkg.Funding.Custom[i] = html.UnescapeString(v)
}
+ for i, link := range pkg.Funding.Links {
+ pkg.Funding.Links[i].Label = html.UnescapeString(link.Label)
+ pkg.Funding.Links[i].URL = html.UnescapeString(link.URL)
+ }
}
for i, kw := range pkg.Keywords {
pkg.Keywords[i] = html.UnescapeString(kw)
@@ -296,6 +310,11 @@ func getPreferredFunding(funding *Funding) string {
return v
}
}
+ for _, link := range funding.Links {
+ if !unsafeFundingURI(link.URL) && "" != strings.TrimSpace(link.URL) {
+ return link.URL
+ }
+ }
return ""
}
diff --git a/kernel/bazaar/package_test.go b/kernel/bazaar/package_test.go
index 61eb299f4b..0d78ce5c10 100644
--- a/kernel/bazaar/package_test.go
+++ b/kernel/bazaar/package_test.go
@@ -17,6 +17,7 @@
package bazaar
import (
+ "encoding/json"
"os"
"path/filepath"
"strings"
@@ -67,6 +68,19 @@ func TestGetPreferredFunding(t *testing.T) {
funding: &Funding{Custom: []string{"Note: scan the QR code"}},
want: "Note: scan the QR code",
},
+ {
+ name: "legacy custom before labeled links",
+ funding: &Funding{
+ Custom: []string{"https://example.com/legacy"},
+ Links: []FundingLink{{Label: "Sponsor", URL: "https://example.com/labeled"}},
+ },
+ want: "https://example.com/legacy",
+ },
+ {
+ name: "labeled link fallback",
+ funding: &Funding{Links: []FundingLink{{Label: "Sponsor", URL: "https://example.com/labeled"}}},
+ want: "https://example.com/labeled",
+ },
}
for _, test := range tests {
@@ -78,6 +92,95 @@ func TestGetPreferredFunding(t *testing.T) {
}
}
+func TestPackageImageMetadataStates(t *testing.T) {
+ var legacy Package
+ if err := json.Unmarshal([]byte(`{"name":"legacy"}`), &legacy); err != nil {
+ t.Fatal(err)
+ }
+ if legacy.Icon != nil || legacy.Preview != nil {
+ t.Fatalf("missing image fields should remain nil: %#v", legacy)
+ }
+
+ var explicit Package
+ if err := json.Unmarshal([]byte(`{"name":"explicit","icon":"","preview":"preview.avif"}`), &explicit); err != nil {
+ t.Fatal(err)
+ }
+ if explicit.Icon == nil || *explicit.Icon != "" || explicit.Preview == nil || *explicit.Preview != "preview.avif" {
+ t.Fatalf("explicit image fields lost their state: %#v", explicit)
+ }
+}
+
+func TestBuildBazaarPackageImageURLs(t *testing.T) {
+ empty := ""
+ icon := "custom icon.webp"
+ preview := "preview.avif"
+ tests := []struct {
+ name string
+ icon *string
+ preview *string
+ wantIcon string
+ wantPreview string
+ }{
+ {name: "legacy defaults", wantIcon: "/icon.png", wantPreview: "/preview.png?imageslim"},
+ {name: "explicit missing", icon: &empty, preview: &empty},
+ {name: "declared formats", icon: &icon, preview: &preview, wantIcon: "/custom%20icon.webp", wantPreview: "/preview.avif"},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ pkg := buildBazaarPackageWithMetadata(&StageRepo{
+ URL: "owner/repo@hash",
+ RepoRef: "v1.0.0",
+ Package: &Package{Name: "sample", Icon: test.icon, Preview: test.preview},
+ }, nil, nil, false, "widgets", "")
+ if pkg == nil {
+ t.Fatal("expected package")
+ }
+ if test.wantIcon == "" && test.wantPreview == "" {
+ if pkg.IconURL != "" || pkg.PreviewURL != "" {
+ t.Fatalf("explicit missing images should produce empty URLs: icon=%q preview=%q", pkg.IconURL,
+ pkg.PreviewURL)
+ }
+ return
+ }
+ if !strings.HasSuffix(pkg.IconURL, test.wantIcon) || !strings.HasSuffix(pkg.PreviewURL, test.wantPreview) {
+ t.Fatalf("unexpected image URLs: icon=%q preview=%q", pkg.IconURL, pkg.PreviewURL)
+ }
+ if pkg.RepoRef != "v1.0.0" {
+ t.Fatalf("unexpected package source metadata: %#v", pkg)
+ }
+ })
+ }
+}
+
+func TestOnlinePackagePreviewURLCompression(t *testing.T) {
+ if got := onlinePackagePreviewURL("owner/repo@hash", "../preview.jpg"); got != "" {
+ t.Fatalf("unexpected invalid preview URL: %q", got)
+ }
+ for _, name := range []string{"preview.png", "preview.jpg", "preview.jpeg"} {
+ if got := onlinePackagePreviewURL("owner/repo@hash", name); !strings.HasSuffix(got, "?imageslim") {
+ t.Fatalf("expected compressed preview URL for %q: %q", name, got)
+ }
+ }
+ for _, name := range []string{"preview.webp", "preview.avif"} {
+ if got := onlinePackagePreviewURL("owner/repo@hash", name); strings.Contains(got, "imageslim") {
+ t.Fatalf("unexpected compressed preview URL for %q: %q", name, got)
+ }
+ }
+}
+
+func TestPackageImageNamesRejectUnsupportedFiles(t *testing.T) {
+ for _, name := range []string{"icon.svg", "../icon.png", "folder/icon.webp", `folder\\icon.webp`, "icon.png "} {
+ if isSupportedPackageImageName(name) {
+ t.Fatalf("unsupported package image name accepted: %q", name)
+ }
+ }
+ for _, name := range []string{"icon.png", "icon.jpg", "icon.jpeg", "icon.webp", "icon.avif"} {
+ if !isSupportedPackageImageName(name) {
+ t.Fatalf("supported package image name rejected: %q", name)
+ }
+ }
+}
+
func TestSetPreferredPackageDeprecationMetadata(t *testing.T) {
oldLang := util.Lang
util.Lang = "zh-CN"
diff --git a/kernel/bazaar/readme.go b/kernel/bazaar/readme.go
index 4261376071..59d08f6e1e 100644
--- a/kernel/bazaar/readme.go
+++ b/kernel/bazaar/readme.go
@@ -20,8 +20,11 @@ import (
"bytes"
"context"
"fmt"
+ "net/url"
"os"
+ "path"
"path/filepath"
+ "strconv"
"strings"
"github.com/88250/gulu"
@@ -30,6 +33,8 @@ import (
"github.com/88250/lute/parse"
"github.com/siyuan-note/logging"
"github.com/siyuan-note/siyuan/kernel/util"
+ nethtml "golang.org/x/net/html"
+ "golang.org/x/net/html/atom"
textUnicode "golang.org/x/text/encoding/unicode"
"golang.org/x/text/transform"
)
@@ -41,7 +46,65 @@ func getReadmeFileCandidates(readme LocaleStrings) []string {
if v := strings.TrimSpace(readme["default"]); v != "" {
defaultName = v
}
- return gulu.Str.RemoveDuplicatedElem([]string{preferred, defaultName, "README.md"})
+ candidates := gulu.Str.RemoveDuplicatedElem([]string{preferred, defaultName, "README.md"})
+ ret := make([]string, 0, len(candidates))
+ for _, candidate := range candidates {
+ if normalized, ok := normalizePackageRelativePath(candidate); ok {
+ ret = append(ret, normalized)
+ }
+ }
+ return gulu.Str.RemoveDuplicatedElem(ret)
+}
+
+func normalizePackageRelativePath(value string) (string, bool) {
+ if value == "" || strings.ContainsAny(value, `\:`) || strings.HasPrefix(value, "/") {
+ return "", false
+ }
+ value = path.Clean(value)
+ if value == "." || value == ".." || strings.HasPrefix(value, "../") {
+ return "", false
+ }
+ return value, true
+}
+
+func escapePackageRelativeURLPath(value string) string {
+ parts := strings.Split(value, "/")
+ for i, part := range parts {
+ parts[i] = url.PathEscape(part)
+ }
+ return strings.Join(parts, "/")
+}
+
+func packageRemoteRootURL(repoURL, repoRef string, allowUnversioned bool) string {
+ repoURL, normalizedRef := normalizeGitHubPackageSource(repoURL, repoRef)
+ if repoURL == "" || (repoRef != "" && normalizedRef == "") || (!allowUnversioned && normalizedRef == "") {
+ return ""
+ }
+ ownerRepo := strings.TrimPrefix(repoURL, "https://github.com/")
+ ret := "https://cdn.jsdelivr.net/gh/" + ownerRepo
+ if normalizedRef != "" {
+ ret += "@" + url.PathEscape(normalizedRef)
+ }
+ return ret + "/"
+}
+
+func packageURLAtPath(rootURL, relativePath, rawQuery, fragment string) string {
+ ret := rootURL + escapePackageRelativeURLPath(relativePath)
+ if rawQuery != "" {
+ ret += "?" + rawQuery
+ }
+ if fragment != "" {
+ ret += "#" + (&url.URL{Fragment: fragment}).EscapedFragment()
+ }
+ return ret
+}
+
+func readmeDirectoryURL(rootURL, readmePath string) string {
+ dir := path.Dir(readmePath)
+ if dir == "." {
+ return strings.TrimSuffix(rootURL, "/")
+ }
+ return strings.TrimSuffix(rootURL, "/") + "/" + escapePackageRelativeURLPath(dir)
}
// GetBazaarPackageREADME 获取集市包的在线 README。
@@ -57,9 +120,11 @@ func GetBazaarPackageREADME(ctx context.Context, repoURL, repoHash, pkgType stri
var data []byte
var loadErr error
var errMsgs []string
+ var readmePath string
for _, name := range candidates {
- data, loadErr = downloadBazaarFile(repoURLHash+"/"+name, false)
+ data, loadErr = downloadBazaarFile(repoURLHash+"/"+escapePackageRelativeURLPath(name), false)
if loadErr == nil {
+ readmePath = name
break
}
errMsgs = append(errMsgs, fmt.Sprintf("Load bazaar package's README(%s) failed: %s", name, loadErr.Error()))
@@ -83,19 +148,27 @@ func GetBazaarPackageREADME(ctx context.Context, repoURL, repoHash, pkgType stri
}
}
- linkBase := "https://cdn.jsdelivr.net/gh/" + strings.TrimPrefix(repoURL, "https://github.com/")
- ret = renderPackageREADME(linkBase, data)
+ remoteRoot := packageRemoteRootURL(repoURL, repo.RepoRef, true)
+ linkBase := readmeDirectoryURL(remoteRoot, readmePath)
+ ret = renderPackageREADMEWithImageResolver(linkBase, data, func(src string) string {
+ return resolvePackageREADMEImage(src, "", "", remoteRoot, readmePath, 0)
+ })
return
}
// getInstalledPackageREADME 获取集市包的本地 README。
-func getInstalledPackageREADME(installPath, linkBase string, readme LocaleStrings) (ret string) {
+func getInstalledPackageREADME(installPath, localRootURL, repoURL, repoRef string, cacheVersion int64,
+ readme LocaleStrings) (ret string) {
candidates := getReadmeFileCandidates(readme)
var errMsgs []string
for _, name := range candidates {
readmeData, readErr := os.ReadFile(filepath.Join(installPath, name))
if readErr == nil {
- ret = renderPackageREADME(linkBase, readmeData)
+ remoteRoot := packageRemoteRootURL(repoURL, repoRef, false)
+ linkBase := readmeDirectoryURL(localRootURL, name)
+ ret = renderPackageREADMEWithImageResolver(linkBase, readmeData, func(src string) string {
+ return resolvePackageREADMEImage(src, installPath, localRootURL, remoteRoot, name, cacheVersion)
+ })
return
}
logging.LogWarnf("read installed %s failed: %s", name, readErr)
@@ -107,6 +180,10 @@ func getInstalledPackageREADME(installPath, linkBase string, readme LocaleString
// renderPackageREADME 渲染 README Markdown 为 HTML。
func renderPackageREADME(linkBase string, mdData []byte) (ret string) {
+ return renderPackageREADMEWithImageResolver(linkBase, mdData, nil)
+}
+
+func renderPackageREADMEWithImageResolver(linkBase string, mdData []byte, resolveImage func(string) string) (ret string) {
mdData = bytes.Clone(bytes.TrimPrefix(mdData, []byte("\xef\xbb\xbf"))) // 移除文件开头的 BOM 并隔离解析缓冲区
luteEngine := lute.New()
luteEngine.SetSanitize(true)
@@ -116,12 +193,106 @@ func renderPackageREADME(linkBase string, mdData []byte) (ret string) {
tree := parse.Parse("", mdData, luteEngine.ParseOptions)
normalizeNodesIAL(tree)
+ rewritePackageREADMEImages(tree, resolveImage)
ret = luteEngine.Tree2HTML(tree, luteEngine.RenderOptions, luteEngine.ParseOptions)
ret = util.ConvertIframeToLink(ret)
ret = util.LinkTarget(ret, linkBase)
return
}
+func resolvePackageREADMEImage(src, installPath, localRootURL, remoteRootURL, readmePath string,
+ cacheVersion int64) string {
+ parsed, err := url.Parse(src)
+ if err != nil || src == "" || parsed.IsAbs() || parsed.Host != "" || strings.HasPrefix(src, "/") ||
+ strings.HasPrefix(src, "#") {
+ return src
+ }
+ resolvedPath, ok := normalizePackageRelativePath(path.Join(path.Dir(readmePath), parsed.Path))
+ if !ok {
+ return "/"
+ }
+
+ useLocal := remoteRootURL == ""
+ if installPath != "" {
+ info, statErr := os.Stat(filepath.Join(installPath, filepath.FromSlash(resolvedPath)))
+ useLocal = statErr == nil && info.Mode().IsRegular()
+ }
+ if !useLocal && remoteRootURL != "" {
+ return packageURLAtPath(remoteRootURL, resolvedPath, parsed.RawQuery, parsed.Fragment)
+ }
+
+ rawQuery := parsed.RawQuery
+ if cacheVersion > 0 {
+ if rawQuery != "" {
+ rawQuery += "&"
+ }
+ rawQuery += "v=" + strconv.FormatInt(cacheVersion, 10)
+ }
+ return packageURLAtPath(localRootURL, resolvedPath, rawQuery, parsed.Fragment)
+}
+
+func rewritePackageREADMEImages(tree *parse.Tree, resolveImage func(string) string) {
+ if tree == nil || tree.Root == nil || resolveImage == nil {
+ return
+ }
+ ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if !entering {
+ return ast.WalkContinue
+ }
+ switch n.Type {
+ case ast.NodeImage:
+ if dest := n.ChildByType(ast.NodeLinkDest); dest != nil {
+ dest.Tokens = []byte(resolveImage(string(dest.Tokens)))
+ }
+ case ast.NodeHTMLBlock, ast.NodeInlineHTML:
+ n.Tokens = rewriteHTMLImageSources(n.Tokens, resolveImage)
+ }
+ return ast.WalkContinue
+ })
+}
+
+func rewriteHTMLImageSources(tokens []byte, resolveImage func(string) string) []byte {
+ if !bytes.Contains(bytes.ToLower(tokens), []byte("<img")) {
+ return tokens
+ }
+ contextNode := &nethtml.Node{Type: nethtml.ElementNode, Data: "div", DataAtom: atom.Div}
+ nodes, err := nethtml.ParseFragment(bytes.NewReader(tokens), contextNode)
+ if err != nil {
+ return tokens
+ }
+ changed := false
+ var rewrite func(*nethtml.Node)
+ rewrite = func(node *nethtml.Node) {
+ if node.Type == nethtml.ElementNode && node.DataAtom == atom.Img {
+ for i, attr := range node.Attr {
+ if strings.EqualFold(attr.Key, "src") {
+ resolved := resolveImage(attr.Val)
+ if resolved != attr.Val {
+ node.Attr[i].Val = resolved
+ changed = true
+ }
+ }
+ }
+ }
+ for child := node.FirstChild; child != nil; child = child.NextSibling {
+ rewrite(child)
+ }
+ }
+ for _, node := range nodes {
+ rewrite(node)
+ }
+ if !changed {
+ return tokens
+ }
+ var buf bytes.Buffer
+ for _, node := range nodes {
+ if renderErr := nethtml.Render(&buf, node); renderErr != nil {
+ return tokens
+ }
+ }
+ return buf.Bytes()
+}
+
func normalizeNodesIAL(tree *parse.Tree) {
if tree == nil || tree.Root == nil {
return
diff --git a/kernel/bazaar/readme_test.go b/kernel/bazaar/readme_test.go
index e98e3b38be..32a1b78d1e 100644
--- a/kernel/bazaar/readme_test.go
+++ b/kernel/bazaar/readme_test.go
@@ -18,10 +18,112 @@ package bazaar
import (
"bytes"
+ "os"
+ "path/filepath"
+ "strings"
"sync"
"testing"
)
+func TestResolvePackageREADMEImage(t *testing.T) {
+ installPath := t.TempDir()
+ if err := os.MkdirAll(filepath.Join(installPath, "docs"), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(installPath, "docs", "local image.png"), []byte("image"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ localRoot := "/plugins/A%20B%23C%25D%28E%29+F/"
+ remoteRoot := "https://cdn.jsdelivr.net/gh/owner/[email protected]/"
+ tests := []struct {
+ name string
+ src string
+ want string
+ }{
+ {
+ name: "local image keeps query and fragment",
+ src: "local%20image.png?width=10#view",
+ want: localRoot + "docs/local%20image.png?width=10&v=42#view",
+ },
+ {
+ name: "missing image uses pinned source",
+ src: "../assets/missing.png?raw=1#preview",
+ want: remoteRoot + "assets/missing.png?raw=1#preview",
+ },
+ {name: "network image unchanged", src: "https://example.com/image.png", want: "https://example.com/image.png"},
+ {name: "data image unchanged", src: "data:image/png;base64,AAAA", want: "data:image/png;base64,AAAA"},
+ {name: "root image unchanged", src: "/assets/image.png", want: "/assets/image.png"},
+ {name: "path traversal rejected", src: "../../outside.png", want: "/"},
+ {name: "encoded path traversal rejected", src: "%2e%2e/%2e%2e/outside.png", want: "/"},
+ {name: "backslash traversal rejected", src: `..\..\outside.png`, want: "/"},
+ {name: "leading backslash rejected", src: `\..\outside.png`, want: "/"},
+ {name: "network path backslash rejected", src: `\\host\outside.png`, want: "/"},
+ {name: "encoded Windows volume rejected", src: `C%3A/outside.png`, want: "/"},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ got := resolvePackageREADMEImage(test.src, installPath, localRoot, remoteRoot, "docs/README.md", 42)
+ if got != test.want {
+ t.Fatalf("expected %q, got %q", test.want, got)
+ }
+ })
+ }
+
+ got := resolvePackageREADMEImage("missing.png", installPath, localRoot, "", "docs/README.md", 42)
+ if got != localRoot+"docs/missing.png?v=42" {
+ t.Fatalf("missing image without a remote source should retain its local URL, got %q", got)
+ }
+}
+
+func TestInstalledPackageREADMERewritesMarkdownAndHTMLImages(t *testing.T) {
+ installPath := t.TempDir()
+ readmeDir := "docs #%(+)"
+ if err := os.MkdirAll(filepath.Join(installPath, readmeDir), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(installPath, readmeDir, "local #%(+).png"), []byte("image"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ markdown := "![local](local%20%23%25%28+%29.png)\n\n![remote](missing%20%23%25%28+%29.webp?raw=1#view)" +
+ "\n\n<img src=\"missing-html.avif\">"
+ readmePath := readmeDir + "/README (v1)+#.md"
+ if err := os.WriteFile(filepath.Join(installPath, filepath.FromSlash(readmePath)), []byte(markdown), 0644); err != nil {
+ t.Fatal(err)
+ }
+ html := getInstalledPackageREADME(installPath, "/plugins/sample/", "https://github.com/owner/repo", "v1.2.3", 99,
+ LocaleStrings{"default": readmePath})
+ for _, expected := range []string{
+ `/plugins/sample/docs%20%23%25%28+%29/local%20%23%25%28+%29.png?v=99`,
+ `https://cdn.jsdelivr.net/gh/owner/[email protected]/docs%20%23%25%28+%29/missing%20%23%25%28+%29.webp?raw=1#view`,
+ `https://cdn.jsdelivr.net/gh/owner/[email protected]/docs%20%23%25%28+%29/missing-html.avif`,
+ } {
+ if !strings.Contains(html, expected) {
+ t.Fatalf("rendered README is missing %q:\n%s", expected, html)
+ }
+ }
+}
+
+func TestPackageRemoteRootURL(t *testing.T) {
+ if got := packageRemoteRootURL("https://github.com/owner/repo", "release/v1", false); got !=
+ "https://cdn.jsdelivr.net/gh/owner/repo@release%2Fv1/" {
+ t.Fatalf("unexpected versioned source: %q", got)
+ }
+ if got := packageRemoteRootURL("https://github.com/owner/repo", "", true); got !=
+ "https://cdn.jsdelivr.net/gh/owner/repo/" {
+ t.Fatalf("unexpected legacy source: %q", got)
+ }
+ if got := packageRemoteRootURL("https://example.com/owner/repo", "v1", true); got != "" {
+ t.Fatalf("untrusted source accepted: %q", got)
+ }
+}
+
+func TestReadmeCandidatesRejectTraversal(t *testing.T) {
+ candidates := getReadmeFileCandidates(LocaleStrings{"default": "docs/README.md", "en": "../../outside.md"})
+ if len(candidates) != 2 || candidates[0] != "docs/README.md" || candidates[1] != "README.md" {
+ t.Fatalf("unexpected README candidates: %#v", candidates)
+ }
+}
+
func TestRenderPackageREADMEDoesNotMutateInput(t *testing.T) {
source := []byte(`<div style="display: flex;">
<!-- 按钮:感谢您的支持 -->
diff --git a/kernel/model/bazaar.go b/kernel/model/bazaar.go
index 611c49754d..2eba2fb8b4 100644
--- a/kernel/model/bazaar.go
+++ b/kernel/model/bazaar.go
@@ -20,6 +20,7 @@ import (
"context"
"errors"
"fmt"
+ "net/url"
"os"
"path/filepath"
"strings"
@@ -117,7 +118,7 @@ func updatePackages(packages []*UpdatedPackage, pkgType string, successCount, fa
items := make([]batchInstallItem, 0, len(packages))
for _, updated := range packages {
pkg := updated.Available
- meta, err := installBazaarPackage(pkgType, pkg.RepoURL, pkg.RepoHash, pkg.Name)
+ meta, err := installBazaarPackage(pkgType, pkg.RepoURL, pkg.RepoHash, pkg.RepoRef, pkg.Name)
if err != nil {
logging.LogErrorf("update %s [%s] failed: %s", pkgType, pkg.Name, err)
util.PushErrMsg(fmt.Sprintf(Conf.language(238), pkg.Name), 5000)
@@ -349,6 +350,10 @@ func GetInstalledPackages(pkgType, frontend, keyword string) (installedPackages
return v.([]*bazaar.Package)
}
+func installedPackageBaseURLPath(prefix, packageName string) string {
+ return prefix + url.PathEscape(packageName) + "/"
+}
+
func getInstalledPackages0(pkgType, frontend, keyword string) (installedPackages []*bazaar.Package) {
installedPackages = []*bazaar.Package{}
@@ -364,7 +369,7 @@ func getInstalledPackages0(pkgType, frontend, keyword string) (installedPackages
for _, info := range installedInfos {
pkg := info.Pkg
installPath := filepath.Join(basePath, info.DirName)
- baseURLPath := baseURLPathPrefix + info.DirName + "/"
+ baseURLPath := installedPackageBaseURLPath(baseURLPathPrefix, info.DirName)
// 设置本地集市包的通用元数据
if !bazaar.SetInstalledPackageMetadata(pkg, installPath, baseURLPath, pkgType) {
continue
@@ -444,9 +449,29 @@ func GetBazaarPackageDetail(pkgType, packageName, frontend string) (installed, a
available.Installed = true
available.Outdated = 0 > semver.Compare("v"+installed.Version, "v"+available.Version)
available.Current = installed.Current
+ refreshInstalledPackageREADME(pkgType, installed, available)
return
}
+func refreshInstalledPackageREADME(pkgType string, installed, available *bazaar.Package) {
+ if installed == nil || available == nil || installed.Version != available.Version || available.RepoRef == "" {
+ return
+ }
+ installedInfos, basePath, baseURLPathPrefix, err := GetInstalledPackageInfos(pkgType)
+ if err != nil {
+ return
+ }
+ for _, info := range installedInfos {
+ if info.Pkg.InvalidReason != "" || info.Pkg.Name != installed.Name {
+ continue
+ }
+ installPath := filepath.Join(basePath, info.DirName)
+ baseURLPath := installedPackageBaseURLPath(baseURLPathPrefix, info.DirName)
+ bazaar.RefreshInstalledPackageREADME(installed, installPath, baseURLPath, available.RepoURL, available.RepoRef)
+ return
+ }
+}
+
// GetBazaarPackages 获取在线集市包列表
func GetBazaarPackages(pkgType, frontend, keyword string) (bazaarPackages []*bazaar.Package) {
bazaarPackages = bazaar.GetBazaarPackages(pkgType, frontend)
@@ -485,7 +510,7 @@ func GetBazaarPackageREADME(ctx context.Context, repoURL, repoHash, pkgType stri
}
// installBazaarPackage 下载并安装集市包
-func installBazaarPackage(pkgType, repoURL, repoHash, packageName string) (meta installMeta, err error) {
+func installBazaarPackage(pkgType, repoURL, repoHash, repoRef, packageName string) (meta installMeta, err error) {
installPath, jsonFileName, err := getPackageInstallPath(pkgType, packageName)
if err != nil {
return
@@ -494,7 +519,7 @@ func installBazaarPackage(pkgType, repoURL, repoHash, packageName string) (meta
installedPkg, parseErr := bazaar.ParsePackageJSON(filepath.Join(installPath, jsonFileName))
meta.update = parseErr == nil && installedPkg != nil && installedPkg.Name == packageName
- err = bazaar.InstallPackage(repoURL, repoHash, installPath, Conf.System.ID, pkgType, packageName, meta.update)
+ err = bazaar.InstallPackage(repoURL, repoHash, repoRef, installPath, Conf.System.ID, pkgType, packageName, meta.update)
if err != nil {
err = fmt.Errorf(Conf.Language(46), packageName, err)
}
@@ -579,8 +604,8 @@ func finishInstall(pkgType string, items []batchInstallItem, themeOptions *Theme
}
// InstallBazaarPackage 安装集市包,themeOptions 仅在 pkgType 为 "themes" 时生效
-func InstallBazaarPackage(pkgType, repoURL, repoHash, packageName string, themeOptions *ThemeInstallOptions) error {
- meta, err := installBazaarPackage(pkgType, repoURL, repoHash, packageName)
+func InstallBazaarPackage(pkgType, repoURL, repoHash, repoRef, packageName string, themeOptions *ThemeInstallOptions) error {
+ meta, err := installBazaarPackage(pkgType, repoURL, repoHash, repoRef, packageName)
if err != nil {
return err
}
@@ -649,7 +674,8 @@ func UpdateBazaarPackage(pkgType, packageName, frontend string) error {
if updated.Available.DisallowUpdate {
return errors.New("marketplace package update is not allowed")
}
- return InstallBazaarPackage(pkgType, updated.Available.RepoURL, updated.Available.RepoHash, packageName, nil)
+ return InstallBazaarPackage(pkgType, updated.Available.RepoURL, updated.Available.RepoHash,
+ updated.Available.RepoRef, packageName, nil)
}
return errors.New("marketplace package update not found")
}
diff --git a/kernel/model/bazaar_test.go b/kernel/model/bazaar_test.go
index ad23120d5f..889d2cd0fa 100644
--- a/kernel/model/bazaar_test.go
+++ b/kernel/model/bazaar_test.go
@@ -50,6 +50,13 @@ func TestIsBuiltInAppearancePackageIgnoresCase(t *testing.T) {
}
}
+func TestInstalledPackageBaseURLPathEscapesPackageNameOnce(t *testing.T) {
+ got := installedPackageBaseURLPath("/plugins/", "A B#C%D(E)+F")
+ if got != "/plugins/A%20B%23C%25D%28E%29+F/" {
+ t.Fatalf("unexpected installed package URL: %q", got)
+ }
+}
+
func TestBuildUpdatedPackagesKeepsInstalledAndAvailableMetadataSeparate(t *testing.T) {
installed := &bazaar.Package{
Name: "example",
@@ -119,6 +126,55 @@ func TestBuildUpdatedPackagesIgnoresMissingAndCurrentPackages(t *testing.T) {
}
}
+func TestRefreshInstalledPackageREADMEUsesOnlyMatchingVersion(t *testing.T) {
+ oldDataDir := util.DataDir
+ util.DataDir = t.TempDir()
+ t.Cleanup(func() { util.DataDir = oldDataDir })
+
+ packageName := "sample #%(test)+ package"
+ installPath := filepath.Join(util.DataDir, "plugins", packageName)
+ if err := os.MkdirAll(installPath, 0755); err != nil {
+ t.Fatal(err)
+ }
+ manifest := `{"name":"sample #%(test)+ package","version":"1.0.0","readme":{"default":"README.md"}}`
+ if err := os.WriteFile(filepath.Join(installPath, "plugin.json"), []byte(manifest), 0644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(installPath, "README.md"), []byte("![missing](missing.webp)"), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ installed := &bazaar.Package{
+ Name: packageName,
+ Version: "1.0.0",
+ Readme: bazaar.LocaleStrings{"default": "README.md"},
+ InstallTime: 42,
+ }
+ available := &bazaar.Package{
+ Name: packageName,
+ Version: "1.0.0",
+ RepoURL: "https://github.com/owner/repo",
+ RepoRef: "v1.0.0",
+ }
+ refreshInstalledPackageREADME("plugins", installed, available)
+ if !strings.Contains(installed.PreferredReadme,
+ "https://cdn.jsdelivr.net/gh/owner/[email protected]/missing.webp") {
+ t.Fatalf("matching version did not use the pinned README source: %q", installed.PreferredReadme)
+ }
+ if installed.RepoRef != "v1.0.0" {
+ t.Fatalf("matching version did not expose its repo ref: %q", installed.RepoRef)
+ }
+
+ installed.PreferredReadme = "unchanged"
+ installed.RepoRef = ""
+ available.Version = "2.0.0"
+ available.RepoRef = "v2.0.0"
+ refreshInstalledPackageREADME("plugins", installed, available)
+ if installed.PreferredReadme != "unchanged" || installed.RepoRef != "" {
+ t.Fatalf("outdated installed README used the latest source: %#v", installed)
+ }
+}
+
func TestGetInstalledPackageInfosIncludesInvalidPackages(t *testing.T) {
oldDataDir := util.DataDir
util.DataDir = t.TempDir()